示例#1
0
        private static async void PersistsToCache(IEnumerable <InvoiceProformaItemDTO> list)
        {
            System.Diagnostics.Debug.WriteLine("<WRITING_TO_CACHE>");
            var recsPerWrite = Properties.Settings.Default.RecordsPerWrite;
            var list1        = list.ToArray();
            var list2        = new List <InvoiceProformaItemDTO>();

            using (var dao = new BillingDbContext())
            {
                dao.Configuration.AutoDetectChangesEnabled = false;
                for (var i = 0; i < list1.Count(); i++)
                {
                    list2.Add(list1[i]);
                    if (i % recsPerWrite == 0 && i != 0)
                    {
                        dao.CachedBillings.AddRange(list2);
                        dao.SaveChanges();
                        list2 = new List <InvoiceProformaItemDTO>();
                    }
                }
                dao.CachedBillings.AddRange(list2);
                dao.SaveChanges();
                dao.Configuration.AutoDetectChangesEnabled = true;
            }
            System.Diagnostics.Debug.WriteLine("</WRITING_TO_CACHE>");
            await Task.Delay(2000);
        }
示例#2
0
        /// <summary>
        /// Проверка срока действия тарифа
        /// </summary>
        /// <param name="isTimer">Признак запуска таймера</param>
        public void CheckProfilesForTariffExpiring(object isTimer = null)
        {
            using (_dbContext)
            {
                var iQuery = _dbContext.Profiles
                             .Include(p => p.Tariff)
                             .Where(p => p.Tariff.AmounfOfDays != 0 &&
                                    !p.IsHolded && p.IsEnabled);

                var currDate = DateTime.Now;
                iQuery.ForEachAsync(async p =>
                {
                    try
                    {
                        await CheckTariffStatehAsync(p);
                        _dbContext.Update(p);
                    }
                    catch (Exception ex)
                    { }
                }).Wait();

                try
                {
                    _dbContext.SaveChanges();
                }
                catch (Exception ex)
                { }
            }

            if (isTimer != null)
            {
                Console.WriteLine($"Tariff regulator by timer is success run. ({DateTime.Now})");
            }
        }
示例#3
0
        public MonthlyProjectData UpdateMonthlyProjectData(int month, int year, int id, MonthlyProjectData monthlyProjectData)
        {
            _context.Entry(monthlyProjectData).State = EntityState.Modified;

            foreach (var sow in monthlyProjectData.SOWs)
            {
                _context.Entry(sow).State = EntityState.Modified;
                foreach (var workItem in sow.WorkItems)
                {
                    _context.Entry(workItem).State = EntityState.Modified;
                    foreach (var resource in workItem.Resources)
                    {
                        _context.Entry(resource).State = EntityState.Modified;
                    }
                    if (workItem.FixedCost != null)
                    {
                        _context.Entry(workItem.FixedCost).State = EntityState.Modified;
                    }
                }
            }

            _context.SaveChanges();

            return(monthlyProjectData);
        }
        public string Put(string reqType, int settlementId)
        {
            RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser");
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            responseData.Status = "OK";//by default status would be OK, hence assigning at the top
            try
            {
                if (reqType == "updateSettlementPrintCount")
                {
                    BillingDbContext bilDbContext = new BillingDbContext(connString);
                    int settlmntId    = settlementId;
                    var currSettlment = bilDbContext.BillSettlements.Where(s => s.SettlementId == settlmntId).FirstOrDefault();
                    if (currSettlment != null)
                    {
                        int?printCount = currSettlment.PrintCount.HasValue ? currSettlment.PrintCount : 0;
                        printCount += 1;
                        bilDbContext.BillSettlements.Attach(currSettlment);
                        currSettlment.PrintCount = printCount;
                        currSettlment.PrintedOn  = System.DateTime.Now; //Yubraj: 13th August'19
                        currSettlment.PrintedBy  = currentUser.EmployeeId;
                        bilDbContext.Entry(currSettlment).Property(b => b.PrintCount).IsModified = true;
                        bilDbContext.SaveChanges();

                        responseData.Results = new { SettlementId = settlementId, PrintCount = printCount };
                    }
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
示例#5
0
        //this function post IRD posting log details to Danphe IRD_Log table
        public static void PostIRDLog(IRDLogModel irdLogdata, BillingDbContext dbContext)
        {
            try
            {
                irdLogdata.CreatedOn = DateTime.Now;

                string url_IRDNepal = ConfigurationManager.AppSettings["url_IRDNepal"];
                switch (irdLogdata.BillType)
                {
                case "billing-sales":
                {
                    string api_SalesIRDNepal = ConfigurationManager.AppSettings["api_SalesIRDNepal"];
                    irdLogdata.UrlInfo = url_IRDNepal + "/" + api_SalesIRDNepal;
                    break;
                }

                case "billing-sales-return":
                {
                    string api_SalesReturnIRDNepal = ConfigurationManager.AppSettings["api_SalesReturnIRDNepal"];
                    irdLogdata.UrlInfo = url_IRDNepal + "/" + api_SalesReturnIRDNepal;
                    break;
                }
                }
                dbContext.IRDLog.Add(irdLogdata);
                dbContext.SaveChanges();
            }
            catch (Exception ex)
            {
            }
        }
        public string Put()
        {
            RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser");
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            responseData.Status = "OK";
            try
            {
                BillingDbContext billingDbContext = new BillingDbContext(connString);
                string           reqType          = this.ReadQueryStringData("reqType");
                int depositId = ToInt(this.ReadQueryStringData("depositId"));

                if (reqType == "updateDepositPrintCount")
                {
                    BillingDeposit deposit = billingDbContext.BillingDeposits
                                             .Where(a => a.DepositId == depositId)
                                             .FirstOrDefault <BillingDeposit>();
                    if (deposit != null)
                    {
                        deposit.PrintCount = deposit.PrintCount == null || deposit.PrintCount == 0 ? 1 : deposit.PrintCount + 1;
                        deposit.PrintedOn  = System.DateTime.Now; //Yubraj: 13th August'19
                        deposit.PrintedBy  = currentUser.EmployeeId;
                        billingDbContext.Entry(deposit).Property(a => a.PrintCount).IsModified = true;
                    }
                    billingDbContext.SaveChanges();
                    responseData.Status = "OK";
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
示例#7
0
        public static void UpdateInsuranceCurrentBalance(string connString,
                                                         int patientId,
                                                         int insuranceProviderId,
                                                         int currentUserId,
                                                         double amount,
                                                         bool isDeduct = false)
        {
            BillingDbContext dbContext = new BillingDbContext(connString);

            try
            {
                InsuranceModel insurance = dbContext.Insurances.Where(ins => ins.PatientId == patientId && ins.InsuranceProviderId == insuranceProviderId).FirstOrDefault();
                if (insurance != null)
                {
                    insurance.CurrentBalance         = isDeduct ? insurance.CurrentBalance - amount : amount;
                    insurance.ModifiedOn             = DateTime.Now;
                    insurance.ModifiedBy             = currentUserId;
                    dbContext.Entry(insurance).State = EntityState.Modified;
                    dbContext.SaveChanges();
                }
                else
                {
                    throw new Exception("Unable to update Insurance Balance. Detail: Insurance object is null.");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Unable to update Insurance Balance. Detail:" + ex.ToString());
            }
        }
        //updates billStatus in respective tables.
        public static void UpdateRequisitionItemsBillStatus(BillingDbContext billingDbContext,
                                                            string serviceDepartmentName,
                                                            string billStatus, //provisional,paid,unpaid,returned
                                                            int userId,
                                                            long?requisitionId,
                                                            DateTime?modifiedDate)
        {
            string integrationName = billingDbContext.ServiceDepartment
                                     .Where(a => a.ServiceDepartmentName == serviceDepartmentName)
                                     .Select(a => a.IntegrationName).FirstOrDefault();

            if (integrationName != null)
            {
                //update return status in lab
                if (integrationName.ToLower() == "lab")
                {
                    var labItem = billingDbContext.LabRequisitions.Where(req => req.RequisitionId == requisitionId).FirstOrDefault();
                    if (labItem != null)
                    {
                        labItem.BillingStatus = billStatus;
                        labItem.ModifiedOn    = modifiedDate;
                        labItem.ModifiedBy    = userId;
                        billingDbContext.Entry(labItem).Property(a => a.BillingStatus).IsModified = true;
                        billingDbContext.Entry(labItem).Property(a => a.ModifiedOn).IsModified    = true;
                        billingDbContext.Entry(labItem).Property(a => a.ModifiedBy).IsModified    = true;
                    }
                }
                //update return status for Radiology
                else if (integrationName.ToLower() == "radiology")
                {
                    var radioItem = billingDbContext.RadiologyImagingRequisitions.Where(req => req.ImagingRequisitionId == requisitionId).FirstOrDefault();
                    if (radioItem != null)
                    {
                        radioItem.BillingStatus = billStatus;
                        radioItem.ModifiedOn    = modifiedDate;
                        radioItem.ModifiedBy    = userId;
                        billingDbContext.Entry(radioItem).Property(a => a.BillingStatus).IsModified = true;
                        billingDbContext.Entry(radioItem).Property(a => a.ModifiedOn).IsModified    = true;
                        billingDbContext.Entry(radioItem).Property(a => a.ModifiedBy).IsModified    = true;
                    }
                }
                //update return status for Visit
                else if (integrationName.ToLower() == "opd" || integrationName.ToLower() == "er")
                {
                    var visitItem = billingDbContext.Visit.Where(vis => vis.PatientVisitId == requisitionId).FirstOrDefault();
                    if (visitItem != null)
                    {
                        visitItem.BillingStatus = billStatus;
                        visitItem.ModifiedOn    = modifiedDate;
                        visitItem.ModifiedBy    = userId;
                        billingDbContext.Entry(visitItem).Property(a => a.BillingStatus).IsModified = true;
                        billingDbContext.Entry(visitItem).Property(a => a.ModifiedOn).IsModified    = true;
                        billingDbContext.Entry(visitItem).Property(a => a.ModifiedBy).IsModified    = true;
                    }
                }
                billingDbContext.SaveChanges();
            }
        }
        public static Boolean ReAssignProviderTxn(VisitDbContext visitDb, VisitModel visit, BillingDbContext billingDb)
        {
            using (var dbContextTxn = visitDb.Database.BeginTransaction())
            {
                try
                {
                    //updating visit-table
                    visitDb.Visits.Attach(visit);
                    visitDb.Entry(visit).Property(x => x.ProviderId).IsModified   = true;
                    visitDb.Entry(visit).Property(x => x.ProviderName).IsModified = true;
                    visitDb.Entry(visit).Property(x => x.ModifiedBy).IsModified   = true;
                    visitDb.Entry(visit).Property(x => x.ModifiedOn).IsModified   = true;
                    visitDb.Entry(visit).Property(x => x.Remarks).IsModified      = true;
                    visitDb.SaveChanges();

                    //updating billingTxnItem table

                    //getting ServiceDepartmentId of OPD
                    int servDeptId = (from d in billingDb.ServiceDepartment
                                      where d.ServiceDepartmentName == "OPD"
                                      select d.ServiceDepartmentId).FirstOrDefault();
                    //for updating get data from table using PatientVisitId as RequisitionId
                    BillingTransactionItemModel billitm = (from b in billingDb.BillingTransactionItems
                                                           where b.RequisitionId == visit.PatientVisitId && b.ServiceDepartmentId == servDeptId
                                                           select b).FirstOrDefault();
                    //assiging updated values
                    billitm.ProviderId   = visit.ProviderId;
                    billitm.ProviderName = visit.ProviderName;

                    billingDb.BillingTransactionItems.Attach(billitm);
                    billingDb.Entry(billitm).Property(x => x.ProviderId).IsModified   = true;
                    billingDb.Entry(billitm).Property(x => x.ProviderName).IsModified = true;
                    billingDb.SaveChanges();


                    //Commit Transaction
                    dbContextTxn.Commit();
                    return(true);
                }
                catch (Exception ex)
                {
                    //Rollback all transaction if exception occured
                    dbContextTxn.Rollback();
                    throw ex;
                }
            }
        }
示例#10
0
 public static void AddPatientInsurancePackage(BillingDbContext dbContext, int packageId, int patientId, int currentUserId)
 {
     try
     {
         PatientInsurancePackageTransactionModel patInsPkgTxn = new PatientInsurancePackageTransactionModel();
         patInsPkgTxn.PatientId = patientId;
         patInsPkgTxn.PackageId = packageId;
         patInsPkgTxn.StartDate = DateTime.Now;
         patInsPkgTxn.CreatedOn = DateTime.Now;
         patInsPkgTxn.CreatedBy = currentUserId;
         patInsPkgTxn.IsActive  = true;
         dbContext.PatientInsurancePackageTransactions.Add(patInsPkgTxn);
         dbContext.SaveChanges();
     }
     catch (Exception ex)
     {
         throw new Exception("Unable to update Insurance Balance. Detail:" + ex.ToString());
     }
 }
        [HttpPost]// POST api/values
        public string Post()
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>(); //type 'object' since we have variable return types

            responseData.Status = "OK";                                                   //by default status would be OK, hence assigning at the top
            string ipDataString = this.ReadPostData();
            string reqType      = this.ReadQueryStringData("reqType");

            try
            {
                RbacUser         currentUser      = HttpContext.Session.Get <RbacUser>("currentuser");
                BillingDbContext billingDbContext = new BillingDbContext(connString);

                if (reqType == "Deposit")
                {
                    BillingDeposit deposit = DanpheJSONConvert.DeserializeObject <BillingDeposit>(ipDataString);
                    deposit.CreatedOn = System.DateTime.Now;
                    deposit.CreatedBy = currentUser.EmployeeId;
                    BillingFiscalYear fiscYear = BillingBL.GetFiscalYear(connString);
                    deposit.FiscalYearId = fiscYear.FiscalYearId;
                    if (deposit.DepositType != "depositdeduct")
                    {
                        deposit.ReceiptNo = BillingBL.GetDepositReceiptNo(connString);
                    }
                    deposit.FiscalYear = fiscYear.FiscalYearFormatted;
                    EmployeeModel currentEmp = billingDbContext.Employee.Where(emp => emp.EmployeeId == currentUser.EmployeeId).FirstOrDefault();
                    deposit.BillingUser = currentEmp.FirstName + " " + currentEmp.LastName;

                    deposit.IsActive = true; //yubraj: 18th Dec '18

                    billingDbContext.BillingDeposits.Add(deposit);
                    billingDbContext.SaveChanges();
                    responseData.Status  = "OK";
                    responseData.Results = deposit;//check if we need to send back the whole input object back to client.--sudarshan
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
示例#12
0
        [HttpPost]// POST api/values
        public string Post()
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>(); //type 'object' since we have variable return types

            responseData.Status = "OK";                                                   //by default status would be OK, hence assigning at the top
            try
            {
                string           ipDataString     = this.ReadPostData();
                string           reqType          = this.ReadQueryStringData("reqType");
                RbacUser         currentUser      = HttpContext.Session.Get <RbacUser>("currentuser");
                BillingDbContext billingDbContext = new BillingDbContext(connString);
                if (reqType == "postBillTransaction")//submit
                {
                    DateTime currentDate = DateTime.Now;
                    BillingTransactionModel billTransaction = DanpheJSONConvert.DeserializeObject <BillingTransactionModel>(ipDataString);

                    if (billTransaction != null)
                    {
                        //Transaction Begins
                        using (var dbContextTransaction = billingDbContext.Database.BeginTransaction())
                        {
                            try
                            {
                                //step:1 -- make copy of billingTxnItems into new list, so thate EF doesn't add txn items again.
                                //step:2-- if there's deposit deduction, then add to deposit table.
                                billTransaction = BillingTransactionBL.PostBillingTransaction(billingDbContext, connString, billTransaction, currentUser.EmployeeId, currentDate);

                                //step:3-- if there's deposit balance, then add a return transaction to deposit table.
                                if (billTransaction.PaymentMode != "credit" && billTransaction.DepositBalance != null && billTransaction.DepositBalance > 0)
                                {
                                    BillingDeposit dep = new BillingDeposit()
                                    {
                                        DepositType = "ReturnDeposit",
                                        Remarks     = "Deposit Refunded from InvoiceNo. " + billTransaction.InvoiceCode + billTransaction.InvoiceNo,
                                        //Remarks = "ReturnDeposit" + " for transactionid:" + billTransaction.BillingTransactionId,
                                        Amount               = billTransaction.DepositBalance,
                                        IsActive             = true,
                                        BillingTransactionId = billTransaction.BillingTransactionId,
                                        DepositBalance       = 0,
                                        FiscalYearId         = billTransaction.FiscalYearId,
                                        CounterId            = billTransaction.CounterId,
                                        CreatedBy            = billTransaction.CreatedBy,
                                        CreatedOn            = currentDate,
                                        PatientId            = billTransaction.PatientId,
                                        PatientVisitId       = billTransaction.PatientVisitId,
                                        PaymentMode          = billTransaction.PaymentMode,
                                        PaymentDetails       = billTransaction.PaymentDetails,
                                        ReceiptNo            = billTransaction.ReceiptNo
                                    };

                                    billingDbContext.BillingDeposits.Add(dep);
                                    billingDbContext.SaveChanges();
                                }

                                //For cancel BillingTransactionItems
                                List <BillingTransactionItemModel> item = (from itm in billingDbContext.BillingTransactionItems
                                                                           where itm.PatientId == billTransaction.PatientId && itm.PatientVisitId == billTransaction.PatientVisitId && itm.BillStatus == "provisional" && itm.Quantity == 0
                                                                           select itm).ToList();
                                if (item.Count() > 0)
                                {
                                    item.ForEach(itm =>
                                    {
                                        var txnItem = BillingTransactionBL.UpdateTxnItemBillStatus(billingDbContext, itm, "adtCancel", billTransaction.CreatedBy.Value, currentDate, billTransaction.CounterId, null);
                                    });
                                }


                                dbContextTransaction.Commit();
                                responseData.Results = billTransaction;
                            }
                            catch (Exception ex)
                            {
                                //rollback all changes if any error occurs
                                dbContextTransaction.Rollback();
                                throw ex;
                            }
                        }
                    }
                    else
                    {
                        responseData.Status       = "Failed";
                        responseData.ErrorMessage = "billTransaction is invalid";
                    }
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
 public ProjectLockedUnlockedHistory AddHistory(ProjectLockedUnlockedHistory projectLockedUnlockedHistory)
 {
     _context.ProjectLockedUnlockedHistorys.Add(projectLockedUnlockedHistory);
     _context.SaveChanges();
     return(projectLockedUnlockedHistory);
 }
        public string Put(string reqType, int settlementId)
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            responseData.Status = "OK";//by default status would be OK, hence assigning at the top
            try
            {
                int patientId             = ToInt(this.ReadQueryStringData("patientId"));
                int insuranceProviderId   = ToInt(this.ReadQueryStringData("insuranceProviderId"));
                int updatedInsBalance     = ToInt(this.ReadQueryStringData("updatedInsBalance"));
                int patientInsurancePkgId = ToInt(this.ReadQueryStringData("patientInsurancePkgId"));
                int couterId = ToInt(this.ReadQueryStringData("counterId"));
                BillingDbContext billingDbContext = new BillingDbContext(connString);
                RbacUser         currentUser      = HttpContext.Session.Get <RbacUser>("currentuser");

                if (reqType == "update-insurance-balance")
                {
                    BillingBL.UpdateInsuranceCurrentBalance(connString,
                                                            patientId,
                                                            insuranceProviderId,
                                                            currentUser.EmployeeId,
                                                            updatedInsBalance);
                    responseData.Status = "OK";
                }

                else if (reqType == "close-insurance-package")
                {
                    PatientInsurancePackageTransactionModel insPkg = billingDbContext.PatientInsurancePackageTransactions
                                                                     .Where(ins => ins.PatientInsurancePackageId == patientInsurancePkgId).FirstOrDefault();
                    if (insPkg != null)
                    {
                        insPkg.EndDate     = DateTime.Now;
                        insPkg.IsCompleted = true;
                        insPkg.ModifiedOn  = DateTime.Now;
                        insPkg.ModifiedBy  = currentUser.EmployeeId;
                        billingDbContext.Entry(insPkg).State = EntityState.Modified;
                        billingDbContext.SaveChanges();
                        responseData.Status = "OK";
                    }
                }

                else if (reqType == "update-insurance-claim")
                {
                    string       str = this.ReadPostData();
                    List <Int32> billingTransactionIdList         = JsonConvert.DeserializeObject <List <Int32> >(str);
                    List <BillingTransactionModel> claimInsurance = new List <BillingTransactionModel>();
                    DateTime settlementDate = DateTime.Now;
                    foreach (var invoice in billingTransactionIdList)
                    {
                        BillingTransactionModel billingTransaction = billingDbContext.BillingTransactions
                                                                     .Where(a => a.BillingTransactionId == invoice)
                                                                     .FirstOrDefault <BillingTransactionModel>();

                        if (billingTransaction != null)
                        {
                            billingDbContext.BillingTransactions.Attach(billingTransaction);
                            billingTransaction.BillStatus           = "paid";
                            billingTransaction.PaidAmount           = billingTransaction.TotalAmount;
                            billingTransaction.PaidDate             = settlementDate;
                            billingTransaction.PaymentReceivedBy    = currentUser.EmployeeId;
                            billingTransaction.PaidCounterId        = couterId;
                            billingTransaction.IsInsuranceClaimed   = true;
                            billingTransaction.InsuranceClaimedDate = DateTime.Now;
                            billingDbContext.Entry(billingTransaction).Property(b => b.IsInsuranceClaimed).IsModified   = true;
                            billingDbContext.Entry(billingTransaction).Property(b => b.InsuranceClaimedDate).IsModified = true;
                            billingDbContext.Entry(billingTransaction).Property(b => b.BillStatus).IsModified           = true;
                            billingDbContext.Entry(billingTransaction).Property(b => b.PaidAmount).IsModified           = true;
                            billingDbContext.Entry(billingTransaction).Property(b => b.PaidDate).IsModified             = true;
                            billingDbContext.Entry(billingTransaction).Property(b => b.PaymentReceivedBy).IsModified    = true;
                            billingDbContext.Entry(billingTransaction).Property(b => b.PaidCounterId).IsModified        = true;



                            List <BillingTransactionItemModel> txnItems = billingDbContext.BillingTransactionItems
                                                                          .Where(b => b.BillingTransactionId == billingTransaction.BillingTransactionId).ToList();

                            if (txnItems != null && txnItems.Count > 0)
                            {
                                foreach (var txnItm in txnItems)
                                {
                                    billingDbContext.BillingTransactionItems.Attach(txnItm);

                                    txnItm.BillStatus        = "paid";
                                    txnItm.PaidDate          = settlementDate;
                                    txnItm.PaidCounterId     = couterId;
                                    txnItm.PaymentReceivedBy = currentUser.EmployeeId;
                                    billingDbContext.Entry(txnItm).Property(b => b.BillStatus).IsModified        = true;
                                    billingDbContext.Entry(txnItm).Property(b => b.PaidDate).IsModified          = true;
                                    billingDbContext.Entry(txnItm).Property(b => b.PaymentReceivedBy).IsModified = true;
                                    billingDbContext.Entry(txnItm).Property(b => b.PaidCounterId).IsModified     = true;
                                }
                                billingDbContext.SaveChanges();
                            }
                            //claimInsurance.Add(billingTransaction);
                        }
                    }
                    billingDbContext.SaveChanges();
                    responseData.Status  = "OK";
                    responseData.Results = claimInsurance;
                }

                else
                {
                    responseData.Status       = "failed";
                    responseData.ErrorMessage = "Invalid request type.";
                }


                //responseData.Results = null;
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
 public Project UpdateProject(int id, Project project)
 {
     _context.Entry(project).State = EntityState.Modified;
     _context.SaveChanges();
     return(project);
 }
示例#16
0
        public override SAPResponse ExecuteCommand()
        {
            try
            {
                InvoiceProformaBillingRunsDTO ret = new InvoiceProformaBillingRunsDTO();
                System.Diagnostics.Debug.WriteLine("=========> MASUK SUBMIT TO SAP BY HEADER....");
                using (var dao = new BillingDbContext())
                {
                    var rawHeader = InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_PROFORMA_HEADER) as InvoiceProformaHeaderDto;
                    var header    = InMemoryCache.Instance.GetCached(Username + Suffix.REQUEST_HEADER) as RunInvoiceHeaderDTO;
                    var vrFromDb  = InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_VERSION_FROM_DB) is int?(int)InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_VERSION_FROM_DB) : 0;

                    InMemoryCache.Instance.ClearCached(Username + Suffix.QUERIED_VERSION_FROM_DB);

                    var          resp            = new InvoiceProformaBillingRunsDTO();
                    const string FUNCTIONAL_BAPI = "ZBAPI_SALESORDER_CHANGE";
                    var          sql2            = from o in dao.InvoiceProformaHeaders.Where(o =>
                                                                                              o.BillingNo == header.BillingNo &&
                                                                                              o.Version == vrFromDb && !o.Draft).OrderByDescending(o => o.Version).Include(o => o.Billings)
                                                   select o;
                    var count1 = sql2.ToList().Count();
                    var list2  = sql2.ToList();
                    resp.Items = list2.Select(h => new InvoiceProformaBillingRunDTO
                    {
                        Created     = h.Created,
                        Version     = h.Version,
                        No          = (int)h.No,
                        SoldToParty = h.SoldToParty,
                        Draft       = h.Draft
                    }).ToList();

                    ret = resp;
                    var reasonForRejection = new Dictionary <string, string>();
                    reasonForRejection["ASSIGNED BY THE SYSTEM (INTERNAL)"] = "00";
                    reasonForRejection["DELIVERY DATE TOO LATE"]            = "01";
                    reasonForRejection["POOR QUALITY"]                = "02";
                    reasonForRejection["TOO EXPENSIVE"]               = "03";
                    reasonForRejection["COMPETITOR BETTER"]           = "04";
                    reasonForRejection["GUARANTEE"]                   = "05";
                    reasonForRejection["UNREASONABLE REQUEST"]        = "10";
                    reasonForRejection["CUST.TO RECEIVE REPLACEMENT"] = "11";
                    reasonForRejection["BILLING BLOCKED"]             = "12";
                    reasonForRejection["DOUBLE INPUT"]                = "13";
                    reasonForRejection["AVAILABILITY"]                = "20";
                    reasonForRejection["COVERAGE"]                     = "21";
                    reasonForRejection["PRICE"]                        = "22";
                    reasonForRejection["RELATIONSHIP"]                 = "23";
                    reasonForRejection["STANDARDIZATON"]               = "24";
                    reasonForRejection["PRODUCT SPECIFICATION"]        = "25";
                    reasonForRejection["TERM OF PAYMENT"]              = "26";
                    reasonForRejection["OTHERS"]                       = "27";
                    reasonForRejection["DON'T PRINT"]                  = "28";
                    reasonForRejection["TRANSACTION IS BEING BLOCK"]   = "29";
                    reasonForRejection["DOCUMENT HELD"]                = "30";
                    reasonForRejection["LOST SALES"]                   = "31";
                    reasonForRejection["ZPROGRAM DO NOT USE"]          = "32";
                    reasonForRejection["TRANSACTION IS BEING CHECKED"] = "50";
                    reasonForRejection["EQUIPMENT REPLACEMENT"]        = "60";
                    reasonForRejection["EQUIPMENT REJECTION"]          = "61";
                    reasonForRejection["EXCESS HOURS"]                 = "63";
                    reasonForRejection["REVOKE USER APPLICATION"]      = "65";
                    reasonForRejection["RETURNED IT DEVICE"]           = "66";
                    reasonForRejection["REPLACEMENT IT DEVICE"]        = "67";
                    reasonForRejection["REPAIR AND MAINTENANCE"]       = "68";
                    reasonForRejection["UPGRADE IT DEVICE"]            = "69";
                    reasonForRejection["COMPLETION OF CONTRACT"]       = "70";
                    reasonForRejection["REJECT IN PROGRESS"]           = "91";
                    reasonForRejection["PTTU SERVICE REJECTION"]       = "99";
                    reasonForRejection["ADDITIONAL PARTS"]             = "C1";
                    reasonForRejection["REPLACEMENT PARTS"]            = "C2";
                    reasonForRejection["TRANSACTION TO BE DEAL"]       = "C3";
                    reasonForRejection["SSB SERVICE REJECTION"]        = "Z1";
                    reasonForRejection["TECHNICAL REASON"]             = "Z2";
                    reasonForRejection["BILLING BY DEBIT MEMO"]        = "Z3";

                    if (count1 > 0)
                    {
                        InvoiceProformaHeader oldHeaderVersion1 = sql2.ToArray()[0];
                        System.Diagnostics.Debug.WriteLine(">>>> " + Username);
                        var cred = ParseCredential(Username);
                        var dest = SAPConnectionFactory.Instance.GetRfcDestination(cred);

                        if (dest != null)
                        {
                            var repo      = dest.Repository;
                            var stopwatch = new Stopwatch();
                            stopwatch.Start();
                            var func = repo.CreateFunction(FUNCTIONAL_BAPI);

                            IRfcTable I_REJECT1 = func.GetTable("I_REJECT1");
                            foreach (var bi in oldHeaderVersion1.Billings)
                            {
                                I_REJECT1.Append();

                                I_REJECT1.SetValue("MANDT", "999");
                                I_REJECT1.SetValue("VBELN", bi.VBAK_VBELN);
                                I_REJECT1.SetValue("POSNR", bi.VBAK_POSNR);
                                try
                                {
                                    I_REJECT1.SetValue("ABGRU", reasonForRejection[bi.VBAK_ABGRU_T.ToUpper()]);
                                }
                                catch (Exception ex)
                                {
                                    I_REJECT1.SetValue("ABGRU", "");
                                }
                                // bi.LogMessage="test";
                            }

                            //dao.SaveChanges();

                            System.Diagnostics.Debug.WriteLine("<EXECUTING_BAPI NAME = '" + FUNCTIONAL_BAPI + "'>");
                            func.Invoke(dest);
                            var getDataMessage = func.GetTable("O_BLOCK_STAT");
                            var list           = new OstatusBlock();
                            var list3          = getDataMessage.Select(e => new OstatusBlock
                            {
                                VBELN   = e.GetString("VBELN"),
                                POSNR   = e.GetString("POSNR"),
                                FLAG    = e.GetString("FLAG"),
                                MESSAGE = e.GetString("MESSAGE"),
                            });

                            foreach (var item in list3)
                            {
                                if (item.MESSAGE == "")
                                {
                                    foreach (var xx in oldHeaderVersion1.Billings)
                                    {
                                        xx.LogMessage = "Success";
                                    }
                                }
                                else
                                {
                                    foreach (var xx in oldHeaderVersion1.Billings)
                                    {
                                        xx.LogMessage = item.MESSAGE;
                                    }
                                }
                            }
                            dao.SaveChanges();
                            System.Diagnostics.Debug.WriteLine("<EXECUTING_BAPI/>");
                            stopwatch.Stop();
                            System.Diagnostics.Debug.WriteLine(">>>> " + stopwatch.Elapsed);
                        }
                    }
                    else
                    {
                        throw new FaultException("Version Final not Found!");
                    }
                }
                return(ret);
            }
            catch (Exception ex) { throw ex; }
        }
        [HttpPost]// POST api/values
        public string Post(string reqType)
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();
            string ipDataString = this.ReadPostData();

            responseData.Status = "OK";//by default status would be OK, hence assigning at the top
            try
            {
                BillingDbContext billingDbContext = new BillingDbContext(connString);
                MasterDbContext  masterDbContext  = new MasterDbContext(connString);
                RbacUser         currentUser      = HttpContext.Session.Get <RbacUser>("currentuser");
                if (reqType == "returnInvoice")//submit
                {
                    //var currentDate = DateTime.Now;
                    BillInvoiceReturnModel billInvoiceRet = DanpheJSONConvert.DeserializeObject <BillInvoiceReturnModel>(ipDataString);
                    if (billInvoiceRet != null)
                    {
                        //Transaction Begins
                        using (var dbContextTransaction = billingDbContext.Database.BeginTransaction())
                        {
                            try
                            {
                                BillingFiscalYear currFiscYear = BillingBL.GetFiscalYear(billingDbContext);
                                //credit note number will continue from current fiscal year, regardless whether the bill was generated in earlier fiscal year.. (sud:30Aug'18)
                                int?maxCreditNoteNum = billingDbContext.BillReturns.Where(a => a.FiscalYearId == currFiscYear.FiscalYearId).Max(a => a.CreditNoteNumber);
                                billInvoiceRet.CreatedOn = DateTime.Now;
                                if (maxCreditNoteNum == null || !maxCreditNoteNum.HasValue)
                                {
                                    maxCreditNoteNum = 0;
                                }

                                billInvoiceRet.FiscalYear       = currFiscYear.FiscalYearFormatted;
                                billInvoiceRet.FiscalYearId     = currFiscYear.FiscalYearId;
                                billInvoiceRet.CreditNoteNumber = (int?)(maxCreditNoteNum + 1);
                                billInvoiceRet.CreatedBy        = currentUser.EmployeeId;
                                billingDbContext.BillReturns.Add(billInvoiceRet);
                                billingDbContext.SaveChanges();

                                //update transactiontable after bill is returned..
                                int invoiceNo = billInvoiceRet.RefInvoiceNum;
                                //BillingTransactionModel billTxn = billingDbContext.BillingTransactions
                                //  .Where(b => b.InvoiceNo == billInvoiceRet.RefInvoiceNum)
                                //  .FirstOrDefault();
                                //changed: sud: 18July, since Invoice No will repeat with fiscal year, so need to find by billingtransactionid.
                                BillingTransactionModel billTxn = billingDbContext.BillingTransactions
                                                                  .Where(b => b.BillingTransactionId == billInvoiceRet.BillingTransactionId)
                                                                  .FirstOrDefault();
                                billingDbContext.BillingTransactions.Attach(billTxn);
                                billTxn.ReturnStatus = true;
                                billingDbContext.Entry(billTxn).Property(a => a.ReturnStatus).IsModified = true;
                                billingDbContext.SaveChanges();

                                if (billTxn.IsInsuranceBilling == true)
                                {
                                    double deductableInsuranceAmount = (billTxn.TotalAmount ?? default(double)) * -1;
                                    BillingBL.UpdateInsuranceCurrentBalance(connString,
                                                                            billTxn.PatientId,
                                                                            billTxn.InsuranceProviderId ?? default(int),
                                                                            currentUser.EmployeeId, deductableInsuranceAmount, true);
                                }

                                var invoiceItems = billingDbContext.BillingTransactionItems.Where(b => b.BillingTransactionId == billInvoiceRet.BillingTransactionId).ToList();
                                //replaced calling centralized function in BillingBL
                                for (int i = 0; i < invoiceItems.Count; i++)
                                {
                                    invoiceItems[i] = BillingTransactionBL.UpdateTxnItemBillStatus(billingDbContext,
                                                                                                   invoiceItems[i],
                                                                                                   "returned",
                                                                                                   currentUser.EmployeeId);
                                }

                                //Yubraj: 18th Dec '18 :: Updating IsActive in deposit table while invoice return
                                List <BillingDeposit> deposit = (from dpt in billingDbContext.BillingDeposits
                                                                 where dpt.BillingTransactionId == billInvoiceRet.BillingTransactionId &&
                                                                 (dpt.DepositType == "depositdeduct" || dpt.DepositType == "ReturnDeposit")
                                                                 select dpt).ToList();
                                if (deposit != null)
                                {
                                    deposit.ForEach(a =>
                                    {
                                        a.IsActive        = true; //keeping false was affecting the patient deposit info
                                        a.ModifiedRemarks = "Updated after invoice return of BillTxnId: " + billInvoiceRet.BillingTransactionId.ToString();
                                        a.ModifiedOn      = DateTime.Now;
                                        a.ModifiedBy      = currentUser.EmployeeId;
                                    });
                                }
                                billInvoiceRet.ReturnedItems = invoiceItems.ToList();
                                billingDbContext.SaveChanges();

                                dbContextTransaction.Commit(); //end of transaction
                                responseData.Results = billInvoiceRet;
                            }
                            catch (Exception ex)
                            {
                                dbContextTransaction.Rollback();
                                throw ex;
                            }
                        }
                    }
                    else
                    {
                        responseData.Status       = "Failed";
                        responseData.ErrorMessage = "billTransactionitems is invalid";
                    }
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
        [HttpPost]// POST api/values
        public string Post()
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();
            int CreatedBy = ToInt(this.ReadQueryStringData("CreatedBy"));

            responseData.Status = "OK";//by default status would be OK, hence assigning at the top
            string ipDataString = this.ReadPostData();
            string reqType      = this.ReadQueryStringData("reqType");

            try
            {
                BillingDbContext billingDbContext = new BillingDbContext(connString);
                if (reqType == "postSettlementInvoice")//submit
                {
                    BillSettlementModel settlement = DanpheJSONConvert.DeserializeObject <BillSettlementModel>(ipDataString);
                    //List<BillingTransactionItemModel> billTxnItm = DanpheJSONConvert.DeserializeObject<List<BillingTransactionItemModel>>(ipDataString);
                    RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser");

                    using (var dbTransaction = billingDbContext.Database.BeginTransaction())
                    {
                        try
                        {
                            var txns = settlement.BillingTransactions;

                            //step:0, As EF automatically Inserts Child collection (billingtransactionmodel) while inserting settlement
                            // we have to first create a new list and set settlement.BillingTransactions as null.
                            List <BillingTransactionModel> newTxnList = new List <BillingTransactionModel>();
                            foreach (BillingTransactionModel txn in txns)
                            {
                                BillingTransactionModel newTxn = BillingTransactionModel.GetCloneWithItems(txn);
                                newTxnList.Add(newTxn);
                            }
                            settlement.BillingTransactions = null;

                            //Step1: assign server side values to the input model and Save the settlementModel
                            settlement.SettlementReceiptNo = GetSettlementReceiptNo(billingDbContext);
                            settlement.CreatedOn           = System.DateTime.Now;
                            settlement.SettlementDate      = System.DateTime.Now;
                            settlement.FiscalYearId        = BillingBL.GetFiscalYear(billingDbContext).FiscalYearId;
                            settlement.CreatedBy           = currentUser.EmployeeId;

                            billingDbContext.BillSettlements.Add(settlement);
                            billingDbContext.SaveChanges();
                            if (newTxnList != null && newTxnList.Count > 0)
                            {
                                //step2: Update necessary fields of BillingTransaction acc to above Settlement Object
                                foreach (var txn in newTxnList)
                                {
                                    billingDbContext.BillingTransactions.Attach(txn);
                                    txn.SettlementId      = settlement.SettlementId;
                                    txn.BillStatus        = "paid";
                                    txn.PaidAmount        = txn.TotalAmount;
                                    txn.PaidDate          = settlement.SettlementDate;
                                    txn.PaymentReceivedBy = currentUser.EmployeeId; //added: sud: 29may'18
                                    txn.PaidCounterId     = settlement.CounterId;   //added: sud: 29may'18

                                    billingDbContext.Entry(txn).Property(b => b.BillStatus).IsModified        = true;
                                    billingDbContext.Entry(txn).Property(b => b.SettlementId).IsModified      = true;
                                    billingDbContext.Entry(txn).Property(b => b.PaidAmount).IsModified        = true;
                                    billingDbContext.Entry(txn).Property(b => b.PaidDate).IsModified          = true;
                                    billingDbContext.Entry(txn).Property(b => b.PaymentReceivedBy).IsModified = true; //added: sud: 29may'18
                                    billingDbContext.Entry(txn).Property(b => b.PaidCounterId).IsModified     = true; //added: sud: 29may'18

                                    //setp3: Update BillStatus and PaidDate of each transaction items attached with above transactions

                                    List <BillingTransactionItemModel> txnItems = billingDbContext.BillingTransactionItems
                                                                                  .Where(b => b.BillingTransactionId == txn.BillingTransactionId).ToList();

                                    if (txnItems != null && txnItems.Count > 0)
                                    {
                                        for (int i = 0; i < txnItems.Count; i++)
                                        {
                                            txnItems[i] = BillingTransactionBL.UpdateTxnItemBillStatus(billingDbContext,
                                                                                                       txnItems[i],
                                                                                                       "paid",
                                                                                                       currentUser.EmployeeId,
                                                                                                       settlement.SettlementDate,
                                                                                                       settlement.CounterId);
                                        }
                                        billingDbContext.SaveChanges();
                                    }
                                }
                                billingDbContext.SaveChanges();
                            }

                            //step: 4 Add new row to deposit table if Deposit is deducted
                            if (settlement.DepositDeducted != null && settlement.DepositDeducted > 0)
                            {
                                VisitModel patientVisit = billingDbContext.Visit.Where(visit => visit.PatientId == settlement.PatientId)
                                                          .OrderByDescending(a => a.PatientVisitId)
                                                          .FirstOrDefault();
                                BillingDeposit depositModel = new BillingDeposit()
                                {
                                    Amount         = settlement.DepositDeducted,
                                    DepositType    = "depositdeduct",
                                    IsActive       = true,
                                    FiscalYearId   = BillingBL.GetFiscalYear(billingDbContext).FiscalYearId,
                                    Remarks        = "Deposit used in Settlement Receipt No. SR" + settlement.SettlementReceiptNo + " on " + settlement.SettlementDate,
                                    CreatedBy      = currentUser.EmployeeId,
                                    CreatedOn      = DateTime.Now,
                                    CounterId      = settlement.CounterId,
                                    PatientVisitId = patientVisit != null ? (int?)patientVisit.PatientVisitId : null,
                                    SettlementId   = settlement.SettlementId,
                                    PatientId      = settlement.PatientId,
                                    DepositBalance = 0,
                                    ReceiptNo      = BillingBL.GetDepositReceiptNo(connString),
                                    PaymentMode    = "cash",//yubraj 4th July '19
                                };

                                billingDbContext.BillingDeposits.Add(depositModel);
                                billingDbContext.SaveChanges();

                                ////update iscurrent and isactive in deposit table for settlement
                                //List<BillingDeposit> depositDetail= (from dep in billingDbContext.BillingDeposits
                                //                                   where dep.PatientId==settlement.PatientId  &&
                                //                                   dep.IsCurrent==true &&
                                //                                   dep.IsActive==true
                                //                                   select dep).ToList();

                                //if (depositDetail != null)
                                //{
                                //    depositDetail.ForEach(d =>
                                //    {
                                //        //d.IsActive = false;
                                //        d.IsCurrent = false;
                                //        billingDbContext.SaveChanges();
                                //    });
                                //}
                            }

                            dbTransaction.Commit();

                            responseData.Status  = "OK";
                            responseData.Results = settlement;
                        }
                        catch (Exception ex)
                        {
                            dbTransaction.Rollback();
                            responseData.Status       = "Failed";
                            responseData.ErrorMessage = ex.ToString();
                        }
                    }
                }
                //responseData.Results = null;
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
        public override SAPResponse ExecuteCommand()
        {
            var resp          = new NumberResult();
            var cachedVersion = (long)InMemoryCache.Instance.GetCached(Username + Suffix.CACHED_VERSION);
            var toUpdateList  = InMemoryCache.Instance.GetCached(Username + Suffix.BILLINGS_TO_UPDATE) as List <BillingToUpdate>;

            #region "CREATING NEW OR UPDATES HEADER"
            if (toUpdateList != null && toUpdateList.Count > 0)
            {
                System.Diagnostics.Debug.WriteLine("=========> CREATE OR UPDATES THE OLD OR NEW VERSION ON DATA LOADED FROM SAP OR DB....");

                var rawHeader = InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_PROFORMA_HEADER) as InvoiceProformaHeaderDto;
                var header    = InMemoryCache.Instance.GetCached(Username + Suffix.REQUEST_HEADER) as RunInvoiceHeaderDTO;
                if (rawHeader != null && header != null)
                {
                    #region "CREATE OR UPDATES DATA LOADED FROM DB"
                    var isFromDB = InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_FROM_DB) is bool && (bool)InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_FROM_DB);
                    if (isFromDB)
                    {
                        #region "UPDATING 0 VERSION"
                        var vrFromDb = InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_VERSION_FROM_DB) is int?(int)InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_VERSION_FROM_DB) : 0;
                        if (vrFromDb == 0)
                        {
                            System.Diagnostics.Debug.WriteLine("IS FROM DB = " + true + " - VER LOADED = " + vrFromDb);
                            using (var dao = new BillingDbContext())
                            {
                                System.Diagnostics.Debug.WriteLine("LOADED VER FROM DB = " + vrFromDb);
                                var loadedVersion = vrFromDb;
                                // Query the version which loaded
                                var sql1 = from o in dao.InvoiceProformaHeaders.Where(o => o.BillingNo == header.BillingNo &&
                                                                                      o.ReasonForRejection ==
                                                                                      header.ReasonForRejection &&
                                                                                      o.BillingBlock ==
                                                                                      header.BillingDocsCriteria &&
                                                                                      o.Version == loadedVersion)
                                           select o;
                                var loadedHeaderVersion = sql1.FirstOrDefault();

                                // Query the latest version from DB
                                var sql2 = from o in dao.InvoiceProformaHeaders.Where(o => o.BillingNo == header.BillingNo &&
                                                                                      o.ReasonForRejection ==
                                                                                      header.ReasonForRejection &&
                                                                                      o.BillingBlock ==
                                                                                      header.BillingDocsCriteria &&
                                                                                      o.Version > 0).OrderBy(o => o.Version)
                                           select o;

                                var latestHeaderVersion = 0;
                                var count = sql2.Count();
                                if (count > 0)
                                {
                                    latestHeaderVersion = sql2.ToArray()[count - 1].Version;
                                }

                                var newHeaderVersion = new InvoiceProformaHeader
                                {
                                    BillingNo          = header.BillingNo,
                                    SoldToParty        = header.SoldToParty,
                                    StartDate          = header.BillingDateFrom,
                                    EndDate            = header.BillingDateTo,
                                    BillingBlock       = header.BillingDocsCriteria,
                                    ReasonForRejection = header.ReasonForRejection,
                                    ProformaFlag       = header.ProformaFlag,
                                    Created            = DateTime.Now,
                                    Version            = latestHeaderVersion + 1,
                                    Draft = true
                                };
                                ClassCopier.Instance.Copy(rawHeader, newHeaderVersion);
                                ClassCopier.Instance.Copy(loadedHeaderVersion, newHeaderVersion);
                                // Add newly updated billings to newly version
                                foreach (var b2u in toUpdateList)
                                {
                                    var u                = b2u;
                                    var VBELN            = u.No.Split('#')[0];
                                    var POSNR            = u.No.Split('#')[1];
                                    var getCachedBillSql = from o in dao.InvoiceProformaBillings.Where(o => o.VBAK_VBELN == VBELN && o.VBAK_POSNR == POSNR && o.CachedVersion == 0).OrderByDescending(o => o.No) select o;
                                    var sbil             = getCachedBillSql.FirstOrDefault();
                                    if (sbil == null)
                                    {
                                        continue;
                                    }
                                    // Check if content changed
                                    if (sbil.VBAK_ABGRU_T != b2u.Content)
                                    {
                                        var upbi = new InvoiceProformaBilling();
                                        SAPHandlerHelper.Instance.CopyBillingValues(sbil, upbi);
                                        upbi.VBAK_ABGRU_T = b2u.Content;
                                        upbi.Remarks      = b2u.Remarks;
                                        if (b2u.Content == Properties.Settings.Default.Unblock)
                                        {
                                            upbi.VBAK_ABGRU_T = String.Empty;
                                        }
                                        upbi.CachedVersion = cachedVersion;
                                        newHeaderVersion.Billings.Add(upbi);
                                    }
                                }
                                // Clear updated billings from cached
                                InMemoryCache.Instance.ClearCached(Username + Suffix.BILLINGS_TO_UPDATE);
                                // Persists new header version and all related billings to DB
                                dao.InvoiceProformaHeaders.Add(newHeaderVersion);
                                dao.SaveChanges();
                                resp.Value = int.Parse(newHeaderVersion.No.ToString(CultureInfo.InvariantCulture));
                            }
                        }
                        #endregion
                        #region "UPDATING ABOVE 0 VERSION"
                        else
                        {
                            using (var dao = new BillingDbContext())
                            {
                                System.Diagnostics.Debug.WriteLine("LOADED VER FROM DB = " + vrFromDb);
                                var loadedVersion = vrFromDb;
                                // Query the version which loaded
                                var sql1 = from o in dao.InvoiceProformaHeaders.Where(o => o.BillingNo == header.BillingNo &&
                                                                                      o.ReasonForRejection ==
                                                                                      header.ReasonForRejection &&
                                                                                      o.BillingBlock ==
                                                                                      header.BillingDocsCriteria &&
                                                                                      o.Version == loadedVersion)
                                           .Include(o => o.Billings)
                                           select o;
                                var loadedHeaderVersion = sql1.FirstOrDefault();

                                // Query the latest version from DB
                                var sql2 = from o in dao.InvoiceProformaHeaders.Where(o => o.BillingNo == header.BillingNo &&
                                                                                      o.ReasonForRejection ==
                                                                                      header.ReasonForRejection &&
                                                                                      o.BillingBlock ==
                                                                                      header.BillingDocsCriteria &&
                                                                                      o.Version > 0)
                                           select o;
                                var count = sql2.Count();
                                var latestHeaderVersion = sql2.ToArray()[count - 1];

                                System.Diagnostics.Debug.WriteLine("=========> CREATE NEW HEADER VERSION FOR UPDATED BILLINGS");

                                // Check if the cached version of old header version's billing similar to current
                                // cached version
                                System.Diagnostics.Debug.WriteLine("=========> CREATE NEW HEADER VERSION FOR UPDATED BILLINGS");
                                // If queried billing cache version != current cachedVersion, create new header
                                var newHeaderVersion = new InvoiceProformaHeader
                                {
                                    BillingNo          = header.BillingNo,
                                    SoldToParty        = header.SoldToParty,
                                    StartDate          = header.BillingDateFrom,
                                    EndDate            = header.BillingDateTo,
                                    BillingBlock       = header.BillingDocsCriteria,
                                    ReasonForRejection = header.ReasonForRejection,
                                    ProformaFlag       = header.ProformaFlag,
                                    Created            = DateTime.Now,
                                    Version            = latestHeaderVersion.Version + 1,
                                    Draft = true
                                };
                                ClassCopier.Instance.Copy(rawHeader, newHeaderVersion);
                                ClassCopier.Instance.Copy(loadedHeaderVersion, newHeaderVersion);

                                // Add newly updated billings to newly version
                                foreach (var b2u in toUpdateList)
                                {
                                    var u                = b2u;
                                    var VBELN            = u.No.Split('#')[0];
                                    var POSNR            = u.No.Split('#')[1];
                                    var getCachedBillSql = from o in dao.InvoiceProformaBillings.Where(o => o.VBAK_VBELN == VBELN && o.VBAK_POSNR == POSNR && o.CachedVersion == 0).OrderByDescending(o => o.No) select o;
                                    var sbil             = getCachedBillSql.FirstOrDefault();
                                    if (sbil == null)
                                    {
                                        continue;
                                    }
                                    // Check if content changed
                                    if (sbil.VBAK_ABGRU_T != b2u.Content)
                                    {
                                        var upbi = new InvoiceProformaBilling();
                                        SAPHandlerHelper.Instance.CopyBillingValues(sbil, upbi);
                                        upbi.VBAK_ABGRU_T = b2u.Content;
                                        upbi.Remarks      = b2u.Remarks;
                                        if (b2u.Content == Properties.Settings.Default.Unblock)
                                        {
                                            upbi.VBAK_ABGRU_T = String.Empty;
                                        }
                                        upbi.CachedVersion = cachedVersion;
                                        newHeaderVersion.Billings.Add(upbi);
                                    }
                                }

                                // Add updated billings from previous version to current version
                                foreach (var bi in loadedHeaderVersion.Billings)
                                {
                                    InvoiceProformaBilling bi1 = bi;
                                    var chk =
                                        from o in
                                        newHeaderVersion.Billings.Where(
                                            o =>
                                            o.VBAK_VBELN == bi1.VBAK_VBELN &&
                                            o.VBAK_POSNR == bi1.VBAK_POSNR)
                                        select o;
                                    if (chk.Count() == 0)
                                    {
                                        var nbi = new InvoiceProformaBilling();
                                        SAPHandlerHelper.Instance.CopyBillingValues(bi, nbi);
                                        nbi.CachedVersion = cachedVersion;
                                        newHeaderVersion.Billings.Add(nbi);
                                    }
                                }

                                // Clear updated billings from cached
                                InMemoryCache.Instance.ClearCached(Username + Suffix.BILLINGS_TO_UPDATE);
                                // Persists new header version and all related billings to DB
                                dao.InvoiceProformaHeaders.Add(newHeaderVersion);
                                dao.SaveChanges();
                                resp.Value = int.Parse(newHeaderVersion.No.ToString(CultureInfo.InvariantCulture));
                            }
                        }
                        #endregion
                        System.Diagnostics.Debug.WriteLine("=========> FROM DB");
                    }
                    #endregion
                    #region "CREATE OR UPDATES DATA LOADED FROM SAP"
                    else
                    {
                        using (var dao = new BillingDbContext())
                        {
                            System.Diagnostics.Debug.WriteLine("=========> FROM SAP");
                            // Query any version above 0
                            var sql1 = from o in dao.InvoiceProformaHeaders.Where(o => o.BillingNo == header.BillingNo &&
                                                                                  o.ReasonForRejection ==
                                                                                  header.ReasonForRejection &&
                                                                                  o.BillingBlock ==
                                                                                  header.BillingDocsCriteria &&
                                                                                  o.Version > 0)
                                       select o;

                            var count = sql1.Count();
                            if (count > 0)
                            {
                                // If there is an older version which is above 0 get latest header
                                System.Diagnostics.Debug.WriteLine("=========> OLD HEADER EXISTS");
                                var oldHeaderVersion = sql1.ToArray()[count - 1];
                                #region "WORKING ON HEADER THAT HAS UPDATED BILLINGS"
                                var sample = 0;
                                // Check if the cached version of old header version's billing similar to current
                                // cached version
                                #region "CREATE NEW HEADER VERSION"
                                if (sample == 0)
                                {
                                    System.Diagnostics.Debug.WriteLine("=========> CREATE NEW HEADER VERSION FOR UPDATED BILLINGS");
                                    // If queried billing cache version != current cachedVersion, create new header
                                    var newHeaderVersion = new InvoiceProformaHeader
                                    {
                                        BillingNo          = header.BillingNo,
                                        SoldToParty        = header.SoldToParty,
                                        StartDate          = header.BillingDateFrom,
                                        EndDate            = header.BillingDateTo,
                                        BillingBlock       = header.BillingDocsCriteria,
                                        ReasonForRejection = header.ReasonForRejection,
                                        ProformaFlag       = header.ProformaFlag,
                                        Created            = DateTime.Now,
                                        Version            = oldHeaderVersion.Version + 1,
                                        Draft = true
                                    };
                                    ClassCopier.Instance.Copy(rawHeader, newHeaderVersion);
                                    ClassCopier.Instance.Copy(oldHeaderVersion, newHeaderVersion);

                                    // Add newly updated billings to newly version
                                    foreach (var b2u in toUpdateList)
                                    {
                                        var u                = b2u;
                                        var VBELN            = u.No.Split('#')[0];
                                        var POSNR            = u.No.Split('#')[1];
                                        var getCachedBillSql = from o in dao.InvoiceProformaBillings.Where(o => o.VBAK_VBELN == VBELN && o.VBAK_POSNR == POSNR && o.CachedVersion == 0) select o;
                                        var sbil             = getCachedBillSql.FirstOrDefault();
                                        if (sbil == null)
                                        {
                                            continue;
                                        }
                                        // Check if content changed
                                        if (sbil.VBAK_ABGRU_T != b2u.Content)
                                        {
                                            var upbi = new InvoiceProformaBilling();
                                            SAPHandlerHelper.Instance.CopyBillingValues(sbil, upbi);
                                            upbi.VBAK_ABGRU_T = b2u.Content;
                                            upbi.Remarks      = b2u.Remarks;
                                            if (b2u.Content == Properties.Settings.Default.Unblock)
                                            {
                                                upbi.VBAK_ABGRU_T = String.Empty;
                                            }
                                            upbi.CachedVersion = cachedVersion;
                                            newHeaderVersion.Billings.Add(upbi);
                                        }
                                    }

                                    // Add updated billings from previous version to current version
                                    foreach (var bi in oldHeaderVersion.Billings)
                                    {
                                        InvoiceProformaBilling bi1 = bi;
                                        var chk =
                                            from o in
                                            newHeaderVersion.Billings.Where(
                                                o =>
                                                o.VBAK_VBELN == bi1.VBAK_VBELN &&
                                                o.VBAK_POSNR == bi1.VBAK_POSNR)
                                            select o;
                                        if (chk.ToList().Count == 0)
                                        {
                                            var nbi = new InvoiceProformaBilling();
                                            SAPHandlerHelper.Instance.CopyBillingValues(bi, nbi);
                                            nbi.CachedVersion = cachedVersion;
                                            newHeaderVersion.Billings.Add(nbi);
                                        }
                                    }

                                    // Clear update billings list from cache
                                    InMemoryCache.Instance.ClearCached(Username + Suffix.BILLINGS_TO_UPDATE);
                                    // Persists new header version and all related billings to DB
                                    dao.InvoiceProformaHeaders.Add(newHeaderVersion);
                                    dao.SaveChanges();
                                    resp.Value = int.Parse(newHeaderVersion.No.ToString(CultureInfo.InvariantCulture));
                                }
                                #endregion
                                #region "UPDATE HEADER DATA"
                                else
                                {
                                    // If old header sample billing cached version equals to current cached version
                                    // add newly updated billings to old header version as add items
                                    System.Diagnostics.Debug.WriteLine("=========> UPDATE OLD HEADER WITH UPDATED BILLINGS");
                                    foreach (var b2u in toUpdateList)
                                    {
                                        var u                = b2u;
                                        var VBELN            = u.No.Split('#')[0];
                                        var POSNR            = u.No.Split('#')[1];
                                        var getCachedBillSql = from o in dao.InvoiceProformaBillings.Where(o => o.VBAK_VBELN == VBELN && o.VBAK_POSNR == POSNR && o.CachedVersion == 0) select o;
                                        var sbil             = getCachedBillSql.FirstOrDefault();
                                        if (sbil == null)
                                        {
                                            continue;
                                        }
                                        // Check if content changed
                                        if (sbil.VBAK_ABGRU_T != b2u.Content)
                                        {
                                            var upbi = new InvoiceProformaBilling();
                                            SAPHandlerHelper.Instance.CopyBillingValues(sbil, upbi);
                                            dao.Entry(upbi).State = EntityState.Added;
                                            upbi.CachedVersion    = cachedVersion;
                                            upbi.VBAK_ABGRU_T     = b2u.Content;
                                            upbi.Remarks          = b2u.Remarks;
                                            if (b2u.Content == Properties.Settings.Default.Unblock)
                                            {
                                                upbi.VBAK_ABGRU_T = String.Empty;
                                            }
                                            oldHeaderVersion.Billings.Add(upbi);
                                        }
                                    }
                                    // Clear update billings list from cache
                                    InMemoryCache.Instance.ClearCached(Username + Suffix.BILLINGS_TO_UPDATE);
                                    // Persists old header version and all newly added updated billings to DB
                                    dao.Entry(oldHeaderVersion).State = EntityState.Modified;
                                    dao.SaveChanges();
                                    resp.Value = int.Parse(oldHeaderVersion.No.ToString(CultureInfo.InvariantCulture));
                                }
                                #endregion
                            }
                            #endregion
                            #region "WORKING ON DATA THAT HAS NO VERSION ABOVE 0 IN DB"
                            else
                            {
                                System.Diagnostics.Debug.WriteLine("=========> NO OLD HEADER ABOVE 0 EXISTS");
                                System.Diagnostics.Debug.WriteLine("=========> CREATE 1st HEADER VERSION WITH UPDATED BILLINGS");
                                // If there is no version above 0
                                var newHeaderVersion = new InvoiceProformaHeader
                                {
                                    BillingNo          = header.BillingNo,
                                    SoldToParty        = header.SoldToParty,
                                    StartDate          = header.BillingDateFrom,
                                    EndDate            = header.BillingDateTo,
                                    BillingBlock       = header.BillingDocsCriteria,
                                    ReasonForRejection = header.ReasonForRejection,
                                    ProformaFlag       = header.ProformaFlag,
                                    Created            = DateTime.Now,
                                    Version            = 1,
                                    Draft = true
                                };
                                ClassCopier.Instance.Copy(rawHeader, newHeaderVersion);
                                dao.InvoiceProformaHeaders.Add(newHeaderVersion);

                                dao.SaveChanges();
                                // Add newly updated billings to newly version
                                foreach (var b2u in toUpdateList)
                                {
                                    var u = b2u;
                                    var getCachedBillSql = from o in dao.CachedBillings.Where(o => o.NO == u.No) select o;
                                    var sbil             = getCachedBillSql.FirstOrDefault();
                                    if (sbil == null)
                                    {
                                        continue;
                                    }
                                    // Check if content changed
                                    if (sbil.VBAK_ABGRU_T != b2u.Content)
                                    {
                                        var upbi = SAPHandlerHelper.Instance.FromBillingDTO2Model(sbil);
                                        upbi.CachedVersion = cachedVersion;
                                        upbi.VBAK_ABGRU_T  = b2u.Content;
                                        upbi.Remarks       = b2u.Remarks;
                                        if (b2u.Content == Properties.Settings.Default.Unblock)
                                        {
                                            upbi.VBAK_ABGRU_T = String.Empty;
                                        }
                                        newHeaderVersion.Billings.Add(upbi);
                                    }
                                }
                                dao.SaveChanges();

                                var isSaved = InMemoryCache.Instance.GetCached(Username + Suffix.PERFORMED_INITIAL_SAVE) is bool && (bool)InMemoryCache.Instance.GetCached(Username + Suffix.PERFORMED_INITIAL_SAVE);
                                if (isSaved == false)
                                {
                                    System.Diagnostics.Debug.WriteLine("<CREATE_ZERO_VERSION CALL = 'FROM SAVE BILLINGS UPDATES' />");
                                    CreateOrOverwriteZeroVersion(false, dao);
                                    InMemoryCache.Instance.ClearCached(Username + Suffix.PERFORMED_INITIAL_SAVE);
                                }

                                // Clear update billings list from cache
                                InMemoryCache.Instance.ClearCached(Username + Suffix.BILLINGS_TO_UPDATE);
                                // Persists new header version and all related billings to DB
                                resp.Value = int.Parse(newHeaderVersion.No.ToString(CultureInfo.InvariantCulture));
                            }
                            #endregion
                        }
                    }

                    #endregion
                }

                InMemoryCache.Instance.ClearCached(Username + Suffix.BILLINGS_TO_UPDATE);
            }
            #endregion
            #region "CREATING OR UPDATING HEADER AS FINAL HEADER"
            else
            {
                System.Diagnostics.Debug.WriteLine("=========> CREATE FINAL VERSION....");
                using (var dao = new BillingDbContext())
                {
                    var rawHeader = InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_PROFORMA_HEADER) as InvoiceProformaHeaderDto;
                    var header    = InMemoryCache.Instance.GetCached(Username + Suffix.REQUEST_HEADER) as RunInvoiceHeaderDTO;
                    if (rawHeader != null && header != null)
                    {
                        var vrFromDb = InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_VERSION_FROM_DB) is int?(int)InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_VERSION_FROM_DB) : 0;

                        // Query any version above 0
                        var sql1 = from o in dao.InvoiceProformaHeaders.Where(o => o.BillingNo == header.BillingNo &&
                                                                              o.ReasonForRejection ==
                                                                              header.ReasonForRejection &&
                                                                              o.BillingBlock ==
                                                                              header.BillingDocsCriteria &&
                                                                              o.Version == vrFromDb &&
                                                                              o.Version > 0)
                                   .Include(o => o.Billings)
                                   select o;
                        var count = sql1.Count();
                        #region "UPDATES THE LATEST HEADER TO FINAL"
                        if (count > 0)
                        {
                            // If there is an older version which is above 0, get latest header
                            System.Diagnostics.Debug.WriteLine("=========> OLD HEADER EXISTS");
                            System.Diagnostics.Debug.WriteLine("=========> UPDATES OLD HEADER AS FINAL");
                            var oldHeaderVersion = sql1.ToArray()[count - 1];
                            if (oldHeaderVersion != null)
                            {
                                oldHeaderVersion.Draft            = false;
                                dao.Entry(oldHeaderVersion).State = EntityState.Modified;
                                dao.SaveChanges();
                                resp.Value = int.Parse(oldHeaderVersion.No.ToString(CultureInfo.InvariantCulture));
                            }
                        }
                        #endregion
                        #region "CREATE A NEW FIRST VERSION AS FINAL"
                        else
                        {
                            System.Diagnostics.Debug.WriteLine("=========> NO OLD HEADER EXISTS");
                            System.Diagnostics.Debug.WriteLine("=========> CREATE 1st HEADER VERSION AS FINAL");
                            // If there is no version above 0
                            var sql2 = from o in dao.InvoiceProformaHeaders.Where(o => o.BillingNo == header.BillingNo &&
                                                                                  o.ReasonForRejection ==
                                                                                  header.ReasonForRejection &&
                                                                                  o.BillingBlock ==
                                                                                  header.BillingDocsCriteria
                                                                                  ).OrderByDescending(o => o.Version) select o;
                            var latestHeaderVersion = sql2.ToArray()[0].Version;

                            var finalHeaderVersion = new InvoiceProformaHeader
                            {
                                BillingNo          = header.BillingNo,
                                SoldToParty        = header.SoldToParty,
                                StartDate          = header.BillingDateFrom,
                                EndDate            = header.BillingDateTo,
                                BillingBlock       = header.BillingDocsCriteria,
                                ReasonForRejection = header.ReasonForRejection,
                                ProformaFlag       = header.ProformaFlag,
                                Created            = DateTime.Now,
                                Version            = latestHeaderVersion + 1,
                                Draft = false
                            };
                            ClassCopier.Instance.Copy(rawHeader, finalHeaderVersion);
                            InMemoryCache.Instance.ClearCached(Username + Suffix.BILLINGS_TO_UPDATE);
                            // Persists new header version and all related billings to DB
                            dao.InvoiceProformaHeaders.Add(finalHeaderVersion);
                            dao.SaveChanges();

                            InMemoryCache.Instance.Cache(Username + Suffix.QUERIED_VERSION_FROM_DB, latestHeaderVersion + 1);
                            resp.Value = int.Parse(finalHeaderVersion.No.ToString(CultureInfo.InvariantCulture));
                        }
                        #endregion
                    }
                }
            }
            #endregion
            return(resp);
        }
        //updates price, quantity, bed charges etc.
        public static void UpdateBillingTransactionItems(BillingDbContext billingDbContext, BillingTransactionItemModel txnItmFromClient)
        {
            if (txnItmFromClient != null && txnItmFromClient.BillingTransactionItemId != 0)
            {
                using (var dbContextTransaction = billingDbContext.Database.BeginTransaction())
                {
                    try
                    {
                        BillingTransactionItemModel txnItmFromDb = billingDbContext.BillingTransactionItems
                                                                   .Where(itm => itm.BillingTransactionItemId == txnItmFromClient.BillingTransactionItemId).FirstOrDefault();

                        txnItmFromDb.Price    = txnItmFromClient.Price;
                        txnItmFromDb.Quantity = txnItmFromClient.Quantity;
                        txnItmFromDb.SubTotal = txnItmFromClient.SubTotal;

                        txnItmFromDb.DiscountAmount     = txnItmFromClient.DiscountAmount;
                        txnItmFromDb.DiscountPercent    = txnItmFromClient.DiscountPercent;
                        txnItmFromDb.TotalAmount        = txnItmFromClient.TotalAmount;
                        txnItmFromDb.ProviderId         = txnItmFromClient.ProviderId;
                        txnItmFromDb.ProviderName       = txnItmFromClient.ProviderName;
                        txnItmFromDb.DiscountPercentAgg = txnItmFromClient.DiscountPercentAgg;
                        txnItmFromDb.TaxableAmount      = txnItmFromClient.TaxableAmount;
                        txnItmFromDb.NonTaxableAmount   = txnItmFromClient.NonTaxableAmount;
                        txnItmFromDb.ModifiedBy         = txnItmFromClient.CreatedBy;
                        txnItmFromDb.ModifiedOn         = DateTime.Now;

                        billingDbContext.Entry(txnItmFromDb).Property(a => a.Price).IsModified              = true;
                        billingDbContext.Entry(txnItmFromDb).Property(a => a.Quantity).IsModified           = true;
                        billingDbContext.Entry(txnItmFromDb).Property(a => a.SubTotal).IsModified           = true;
                        billingDbContext.Entry(txnItmFromDb).Property(a => a.DiscountAmount).IsModified     = true;
                        billingDbContext.Entry(txnItmFromDb).Property(a => a.DiscountPercent).IsModified    = true;
                        billingDbContext.Entry(txnItmFromDb).Property(a => a.DiscountPercentAgg).IsModified = true;
                        billingDbContext.Entry(txnItmFromDb).Property(a => a.TotalAmount).IsModified        = true;
                        billingDbContext.Entry(txnItmFromDb).Property(a => a.ProviderId).IsModified         = true;
                        billingDbContext.Entry(txnItmFromDb).Property(a => a.ProviderName).IsModified       = true;
                        billingDbContext.Entry(txnItmFromDb).Property(a => a.TaxableAmount).IsModified      = true;
                        billingDbContext.Entry(txnItmFromDb).Property(a => a.NonTaxableAmount).IsModified   = true;
                        billingDbContext.Entry(txnItmFromDb).Property(a => a.ModifiedBy).IsModified         = true;
                        billingDbContext.Entry(txnItmFromDb).Property(a => a.ModifiedOn).IsModified         = true;

                        //Salakha: commented code, After update qty, date should not be update
                        ////check if bed item was edited.
                        //BillItemPrice billItem = (from item in billingDbContext.BillItemPrice
                        //                          join srvDept in billingDbContext.ServiceDepartment on item.ServiceDepartmentId equals srvDept.ServiceDepartmentId
                        //                          where item.ServiceDepartmentId == txnItmFromDb.ServiceDepartmentId
                        //                          && item.ItemId == txnItmFromClient.ItemId
                        //                          && srvDept.IntegrationName.ToLower() == "bed charges"
                        //                          select item).FirstOrDefault();
                        //if (billItem != null)
                        //{
                        //    PatientBedInfo selBedInfo = (from selBed in billingDbContext.PatientBedInfos
                        //                                 where selBed.PatientVisitId == txnItmFromClient.PatientVisitId
                        //                                 && selBed.BedFeatureId == txnItmFromClient.ItemId
                        //                                 select selBed).OrderByDescending(a=> a.PatientBedInfoId).FirstOrDefault();
                        //    if (selBedInfo != null)
                        //    {
                        //        PatientBedInfo nextBedInfo = (from nextBed in billingDbContext.PatientBedInfos
                        //                                      where nextBed.PatientVisitId == txnItmFromClient.PatientVisitId
                        //                                       && nextBed.StartedOn == selBedInfo.EndedOn
                        //                                       //sud/Yub:11Feb'19--if startedon/endedon is same then nextbed and current bed are same. adding bedinfoId != logic.
                        //                                       && selBedInfo.PatientBedInfoId != nextBed.PatientBedInfoId
                        //                                      select nextBed).FirstOrDefault();

                        //        DateTime endDate = Convert.ToDateTime(selBedInfo.StartedOn).AddDays(Convert.ToInt32(txnItmFromClient.Quantity - 1));
                        //        selBedInfo.EndedOn = endDate;
                        //        billingDbContext.Entry(selBedInfo).Property(a => a.EndedOn).IsModified = true;
                        //        if (nextBedInfo != null)
                        //        {
                        //            nextBedInfo.StartedOn = selBedInfo.EndedOn;
                        //            billingDbContext.Entry(nextBedInfo).Property(a => a.StartedOn).IsModified = true;
                        //        }
                        //    }
                        //}

                        billingDbContext.SaveChanges();

                        dbContextTransaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        //rollback all changes if any error occurs
                        dbContextTransaction.Rollback();
                        throw ex;
                    }
                }
            }
        }
示例#21
0
        public string Put()
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            try
            {
                BillingDbContext billingDbContext = new BillingDbContext(connString);
                string           str     = this.ReadPostData();
                string           reqType = this.ReadQueryStringData("reqType");
                if (reqType == "update-adtItems-duration")
                {
                    List <BedDurationTxnDetailsVM> bedDurationDetails = DanpheJSONConvert.DeserializeObject <List <BedDurationTxnDetailsVM> >(str);
                    if (bedDurationDetails != null && bedDurationDetails.Count > 0)
                    {
                        double totalDuration  = bedDurationDetails[0].TotalDays;
                        int    patientVisitId = bedDurationDetails[0].PatientVisitId;
                        BillingTransactionItemModel billItem = new BillingTransactionItemModel();

                        //foreach (var bedItem in bedDurationDetails)
                        //{
                        //    billItem = (from bill in billingDbContext.BillingTransactionItems
                        //                where bill.PatientVisitId == bedItem.PatientVisitId
                        //                && bill.ServiceDepartmentName.ToLower() == "bed charges"
                        //                && bill.ItemId == bedItem.BedFeatureId
                        //                select bill).FirstOrDefault();
                        //    if (billItem != null)
                        //    {
                        //        billItem.Quantity = bedItem.Days;
                        //        billItem.SubTotal = bedItem.SubTotal;
                        //        billItem.TaxableAmount = bedItem.TaxableAmount;
                        //        billItem.NonTaxableAmount = bedItem.NonTaxableAmount;
                        //        //sud,Yub : 11Feb'19 -- Re-Calculate DiscountAmount based on Existing Discount Percent.
                        //        billItem.DiscountAmount = (bedItem.SubTotal * billItem.DiscountPercent) / 100;
                        //        billItem.TotalAmount = billItem.SubTotal - billItem.DiscountAmount;
                        //        billingDbContext.Entry(billItem).Property(a => a.Quantity).IsModified = true;
                        //        billingDbContext.Entry(billItem).Property(a => a.SubTotal).IsModified = true;
                        //        billingDbContext.Entry(billItem).Property(a => a.TaxableAmount).IsModified = true;
                        //        billingDbContext.Entry(billItem).Property(a => a.NonTaxableAmount).IsModified = true;
                        //        billingDbContext.Entry(billItem).Property(a => a.DiscountAmount).IsModified = true;
                        //        billingDbContext.Entry(billItem).Property(a => a.TotalAmount).IsModified = true;
                        //    }
                        //}

                        //update duration for Medical and Resident officer/Nursing Charges
                        billItem = (from bill in billingDbContext.BillingTransactionItems
                                    join itmCfg in billingDbContext.BillItemPrice on new { bill.ServiceDepartmentId, bill.ItemId } equals new { itmCfg.ServiceDepartmentId, itmCfg.ItemId }
                                    where bill.PatientVisitId == patientVisitId && itmCfg.IntegrationName == "Medical and Resident officer/Nursing Charges"
                                    select bill).FirstOrDefault();
                        if (billItem != null)
                        {
                            billItem.Quantity = totalDuration > 0 ? totalDuration : 1;
                            billItem.SubTotal = billItem.Price * billItem.Quantity;
                            //sud,Yub : 11Feb'19 -- Re-Calculate DiscountAmount based on Existing Discount Percent.
                            billItem.DiscountAmount = (billItem.SubTotal * billItem.DiscountPercent) / 100;
                            billItem.TotalAmount    = billItem.SubTotal - billItem.DiscountAmount;
                            // billItem.TotalAmount = billItem.NonTaxableAmount = billItem.SubTotal;//removed: sud:11Feb'19--this is incorrect.
                            billingDbContext.Entry(billItem).Property(a => a.Quantity).IsModified         = true;
                            billingDbContext.Entry(billItem).Property(a => a.SubTotal).IsModified         = true;
                            billingDbContext.Entry(billItem).Property(a => a.DiscountAmount).IsModified   = true;
                            billingDbContext.Entry(billItem).Property(a => a.TotalAmount).IsModified      = true;
                            billingDbContext.Entry(billItem).Property(a => a.NonTaxableAmount).IsModified = true;
                        }
                        responseData.Status = "OK";
                        billingDbContext.SaveChanges();
                        responseData.Results = "quantity updated";
                    }

                    else
                    {
                        responseData.Status       = "Failed";
                        responseData.ErrorMessage = "Unable to upadate bed duration details.";
                    }
                }

                else if (reqType == "update-billtxnItem")
                {
                    List <BillingTransactionItemModel> txnItems = DanpheJSONConvert.DeserializeObject <List <BillingTransactionItemModel> >(str);
                    if (txnItems != null)
                    {
                        txnItems.ForEach(item =>
                        {
                            BillingTransactionBL.UpdateBillingTransactionItems(billingDbContext, item);
                        });
                    }

                    responseData.Status = "OK";
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
        //post to BIL_TXN_BillingTransaction
        public static BillingTransactionModel PostBillingTransaction(BillingDbContext dbContext,
                                                                     string connString,
                                                                     BillingTransactionModel billingTransaction,
                                                                     int userId,
                                                                     DateTime currentDate)
        {
            List <BillingTransactionItemModel> newTxnItems = new List <BillingTransactionItemModel>();

            if (billingTransaction.BillingTransactionItems != null && billingTransaction.BillingTransactionItems.Count > 0)
            {
                foreach (var txnItem in billingTransaction.BillingTransactionItems)
                {
                    newTxnItems.Add(BillingTransactionItemModel.GetClone(txnItem));
                }
                billingTransaction.BillingTransactionItems = null;
            }
            //if paymentmode is credit, paiddate and paidamount should be null
            //handle this in client side as well.
            billingTransaction.CreatedBy = userId;
            if (billingTransaction.BillStatus == "unpaid")
            {
                billingTransaction.PaidDate          = null;
                billingTransaction.PaidAmount        = null;
                billingTransaction.PaymentReceivedBy = null;
                billingTransaction.PaidCounterId     = null;
            }
            else if (billingTransaction.BillStatus == "paid")
            {
                billingTransaction.PaidDate          = currentDate;
                billingTransaction.PaidCounterId     = billingTransaction.CounterId;
                billingTransaction.PaymentReceivedBy = billingTransaction.CreatedBy;
            }

            BillingFiscalYear fiscYear = BillingBL.GetFiscalYear(connString);

            //ashim: 26Aug2018: Moved from client side to server side.
            billingTransaction.CreatedOn    = currentDate;
            billingTransaction.CreatedBy    = userId;
            billingTransaction.FiscalYearId = fiscYear.FiscalYearId;
            billingTransaction.InvoiceNo    = BillingBL.GetInvoiceNumber(connString);
            //billingTransaction.InvoiceCode = BillingBL.InvoiceCode;
            billingTransaction.InvoiceCode = billingTransaction.IsInsuranceBilling == true ? "INS" : BillingBL.InvoiceCode;
            dbContext.BillingTransactions.Add(billingTransaction);
            dbContext.SaveChanges();

            PostUpdateBillingTransactionItems(dbContext,
                                              connString,
                                              newTxnItems,
                                              userId, currentDate,
                                              billingTransaction.BillStatus,
                                              billingTransaction.CounterId,
                                              billingTransaction.BillingTransactionId);
            dbContext.SaveChanges();
            //step:3-- if there's deposit deduction, then add to deposit table.
            if (billingTransaction.PaymentMode != "credit" && billingTransaction.DepositReturnAmount != null && billingTransaction.DepositReturnAmount > 0)
            {
                BillingDeposit dep = new BillingDeposit()
                {
                    DepositType = "depositdeduct",
                    Remarks     = "Deposit used in InvoiceNo. " + billingTransaction.InvoiceCode + billingTransaction.InvoiceNo,
                    //Remarks = "depositdeduct" + " for transactionid:" + billingTransaction.BillingTransactionId,
                    IsActive             = true,
                    Amount               = billingTransaction.DepositReturnAmount,
                    BillingTransactionId = billingTransaction.BillingTransactionId,
                    DepositBalance       = billingTransaction.DepositBalance,
                    FiscalYearId         = billingTransaction.FiscalYearId,
                    CounterId            = billingTransaction.CounterId,
                    CreatedBy            = billingTransaction.CreatedBy,
                    CreatedOn            = currentDate,
                    PatientId            = billingTransaction.PatientId,
                    PatientVisitId       = billingTransaction.PatientVisitId,
                    PaymentMode          = billingTransaction.PaymentMode,
                    PaymentDetails       = billingTransaction.PaymentDetails,
                    ReceiptNo            = BillingBL.GetDepositReceiptNo(connString)
                };
                billingTransaction.ReceiptNo = dep.ReceiptNo + 1;
                dbContext.BillingDeposits.Add(dep);
                dbContext.SaveChanges();
            }
            billingTransaction.FiscalYear = fiscYear.FiscalYearFormatted;
            return(billingTransaction);
        }
        //post to BIL_TXN_BillingTransactionItems
        public static List <BillingTransactionItemModel> PostUpdateBillingTransactionItems(BillingDbContext dbContext, string connString,
                                                                                           List <BillingTransactionItemModel> billingTransactionItems,
                                                                                           int userId,
                                                                                           DateTime currentDate,
                                                                                           string billStatus,
                                                                                           int?counterId,
                                                                                           int?billingTransactionId = null)
        {
            BillingFiscalYear fiscYear = BillingBL.GetFiscalYear(connString);

            var srvDepts = dbContext.ServiceDepartment.ToList();

            //var empList = masterDbContext.Employees.ToList();
            if (billingTransactionItems != null && billingTransactionItems.Count > 0)
            {
                var ProvisionalReceiptNo = BillingBL.GetProvisionalReceiptNo(connString);
                for (int i = 0; i < billingTransactionItems.Count; i++)
                {
                    var txnItem = billingTransactionItems[i];
                    if (txnItem.BillingTransactionItemId == 0)
                    {
                        txnItem.CreatedOn            = currentDate;
                        txnItem.CreatedBy            = userId;
                        txnItem.RequisitionDate      = currentDate;
                        txnItem.CounterId            = counterId;
                        txnItem.BillingTransactionId = billingTransactionId;
                        if (txnItem.BillStatus == "provisional")
                        {
                            txnItem.ProvisionalReceiptNo    = ProvisionalReceiptNo;
                            txnItem.ProvisionalFiscalYearId = fiscYear.FiscalYearId;
                            txnItem.ProvFiscalYear          = fiscYear.FiscalYearFormatted; //not mapped
                        }
                        //assign providername and servicedepartmentname to each of the incoming transaction items.
                        //Needs Revision: 12-12-17: sud: I think we don't need to get providername since that property already comes from client side:
                        //txnItem.ProviderName = (from a in empList where a.EmployeeId == txnItem.ProviderId select a.FullName).FirstOrDefault();
                        txnItem.ServiceDepartmentName = (from b in srvDepts where b.ServiceDepartmentId == txnItem.ServiceDepartmentId select b.ServiceDepartmentName).FirstOrDefault();

                        txnItem = GetBillStatusMapped(txnItem, billStatus, currentDate, userId, counterId);
                        UpdateRequisitionItemsBillStatus(dbContext, txnItem.ServiceDepartmentName, billStatus, userId, txnItem.RequisitionId, currentDate);
                        dbContext.BillingTransactionItems.Add(txnItem);
                    }
                    else
                    {
                        txnItem = UpdateTxnItemBillStatus(dbContext, txnItem, billStatus, userId, currentDate, counterId, billingTransactionId);
                    }


                    //update the Requisitions billingstatus as 'paid' for above items.
                    //List<Int32?> requisitionIds = (from a in billTranItems select a.BillItemRequisitionId).ToList();
                    BillItemRequisition billItemRequisition = (from bill in dbContext.BillItemRequisitions
                                                               where bill.RequisitionId == txnItem.RequisitionId &&
                                                               bill.ServiceDepartmentId == txnItem.ServiceDepartmentId
                                                               select bill).FirstOrDefault();
                    if (billItemRequisition != null)
                    {
                        billItemRequisition.BillStatus             = "paid";
                        dbContext.Entry(billItemRequisition).State = EntityState.Modified;
                    }
                }
                dbContext.SaveChanges();
            }
            else
            {
                throw new Exception("BillingTranscation Items is null");
            }
            return(billingTransactionItems);
        }
        protected void CreateOrOverwriteZeroVersion(bool doOverride, BillingDbContext dao)
        {
            var header        = InMemoryCache.Instance.GetCached(Username + Suffix.REQUEST_HEADER) as RunInvoiceHeaderDTO;
            var total         = InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_PROFORMA_TOTAL_RECS) is int?(int)InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_PROFORMA_TOTAL_RECS) : 0;
            var cachedVersion = InMemoryCache.Instance.GetCached(Username + Suffix.CACHED_VERSION) is long?(long)InMemoryCache.Instance.GetCached(Username + Suffix.CACHED_VERSION) : 0;


            if (GetTotalCached(cachedVersion) >= total)
            {
                InMemoryCache.Instance.ClearCached(Username + Suffix.QUERIED_FROM_DB);
                InMemoryCache.Instance.Cache(Username + Suffix.QUERIED_FROM_DB, true);
                InMemoryCache.Instance.Cache(Username + Suffix.QUERIED_VERSION_FROM_DB, 0);

                var rawHeader   = InMemoryCache.Instance.GetCached(Username + Suffix.QUERIED_PROFORMA_HEADER) as InvoiceProformaHeaderDto;
                var cachedBills = GetCachedBillings(cachedVersion);
                if (CountZeroVersion(header, dao) <= 0 && header != null && rawHeader != null)
                {
                    var newZeroHeaderVersion = new InvoiceProformaHeader
                    {
                        Version            = 0,
                        SoldToParty        = header.SoldToParty,
                        BillingBlock       = header.BillingDocsCriteria,
                        ReasonForRejection = header.ReasonForRejection,
                        ProformaFlag       = header.ProformaFlag,
                        BillingNo          = header.BillingNo,
                        Created            = DateTime.Now,
                        StartDate          = header.BillingDateFrom,
                        EndDate            = header.BillingDateTo,
                        Draft      = true,
                        CITY1      = rawHeader.CITY1,
                        ERDAT      = rawHeader.ERDAT,
                        ERNAM      = rawHeader.ERNAM,
                        ERZET      = rawHeader.ERZET,
                        FKDAT      = rawHeader.FKDAT,
                        FPAJAK_NO  = rawHeader.FPAJAK_NO,
                        HTOTAL1    = rawHeader.HTOTAL1,
                        HTOTAL2    = rawHeader.HTOTAL2,
                        HTOTAL3    = rawHeader.HTOTAL3,
                        HTOTAL4    = rawHeader.HTOTAL4,
                        HTOTAL5    = rawHeader.HTOTAL5,
                        KUNRG      = rawHeader.KUNRG,
                        KURRF      = rawHeader.KURRF,
                        NAME1      = rawHeader.NAME1,
                        NAME2      = rawHeader.NAME2,
                        NAME3      = rawHeader.NAME3,
                        NAME4      = rawHeader.NAME4,
                        POST_CODE1 = rawHeader.POST_CODE1,
                        STCEG      = rawHeader.STCEG,
                        STREET     = rawHeader.STREET,
                        TDLINE     = rawHeader.TDLINE,
                        TEXT1      = rawHeader.TEXT1,
                        VBELN      = rawHeader.VBELN,
                        VTEXT      = rawHeader.VTEXT,
                        WAERK      = rawHeader.WAERK,
                        ZTERM      = rawHeader.ZTERM,
                    };
                    // Add new header
                    dao.InvoiceProformaHeaders.Add(newZeroHeaderVersion);
                    dao.SaveChanges();

                    // Add newly retrieved billings
                    var createZeroSql = createZero.Replace("@no", newZeroHeaderVersion.No + "").Replace("@cachedVersion", cachedVersion + "");
                    dao.Database.ExecuteSqlCommand(createZeroSql);
                }
                else
                {
                    if (!doOverride)
                    {
                        return;
                    }
                    if (cachedBills.Count <= 0 || rawHeader == null || header == null)
                    {
                        return;
                    }
                    var sql1 =
                        from o in
                        dao.InvoiceProformaHeaders.Where(
                            o => o.BillingBlock == header.BillingDocsCriteria &&
                            o.ReasonForRejection ==
                            header.ReasonForRejection &&
                            o.ProformaFlag == header.ProformaFlag &&
                            o.BillingNo == header.BillingNo &&
                            o.SoldToParty == header.SoldToParty)
                        select o;
                    InvoiceProformaHeader oldZeroHeaderVersion = sql1.FirstOrDefault();
                    if (oldZeroHeaderVersion != null)
                    {
                        // Deletes old billings
                        dao.Database.ExecuteSqlCommand("DELETE FROM dbo.InvoiceProformaBilling WHERE InvoiceProformaHeader_No = " + oldZeroHeaderVersion.No);
                        var createZeroSql = createZero.Replace("@no", oldZeroHeaderVersion.No + "").Replace("@cachedVersion", cachedVersion + "");
                        // Add newly retrieved billings
                        dao.Database.ExecuteSqlCommand(createZeroSql);
                    }
                }
            }
            else
            {
                Thread.Sleep(2000);
                CreateOrOverwriteZeroVersion(doOverride, dao);
            }
        }