コード例 #1
0
        public string Get(string department,
                          string reqType,
                          int providerId,
                          int patientId,
                          DateTime requestDate,
                          string status,
                          int membershipTypeId)
        {
            AppointmentDbContext        dbContextAppointment = new AppointmentDbContext(connString);
            DanpheHTTPResponse <object> responseData         = new DanpheHTTPResponse <object>();

            //RbacUser currentUser = HttpContext.Session.Get<RbacUser>("currentuser");
            //if (currentUser == null || !RBAC.UserHasPermission(currentUser.UserId, "APT", "appointment-read"))
            //{
            //    HttpResponseMessage message = new HttpResponseMessage(System.Net.HttpStatusCode.NotFound);
            //    responseData.Status = "Failed";
            //    responseData.ErrorMessage = "Unauthorized access.";
            //    return DanpheJSONConvert.SerializeObject(responseData);
            //}

            #region get request example
            //for reference
            //if (!string.IsNullOrEmpty(fName) || !string.IsNullOrEmpty(doctor) || appointmentId != 0)
            //{
            //    //If nothing is passed during search->Condition in LHS is TRUE and neglects the condition in the RHS
            //    //If some value is passed during search -> LHS will be false and checks if RHS is TRUE
            //    //If both the LHS and RHS in any one of the 3 conditions is false then query returns nothing.
            //    result = (from app in dbContextSearch.Appointments
            //              where (appointmentId == 0 || appointmentId == app.AppointmentId)
            //             && (string.IsNullOrEmpty(fName) || app.FirstName.ToLower().Contains(fName.ToLower()))
            //             && (string.IsNullOrEmpty(doctor) || app.ProviderName.ToLower().Contains(doctor.ToLower()))
            //              select app).ToList();
            //    return JsonConvert.SerializeObject(result);
            //}
            #endregion
            try
            {
                //gets the doctorschedule from appointment table
                if (reqType == "doctorschedule")
                {
                    //.ToList()is done two times,since we can't use requestDate.Date inside IQueryable
                    List <AppointmentModel> apptList = (from d in dbContextAppointment.Appointments
                                                        where d.ProviderId == providerId
                                                        select d).ToList().Where(a => a.AppointmentDate.Date == requestDate.Date).ToList();
                    AppointmentDay apptDay = AppointmentDay.FormatData(apptList);
                    responseData.Status  = "OK";
                    responseData.Results = apptDay;
                }
                //loads appointments with requested status
                else if (reqType == "getAppointments")
                {
                    var date = DateTime.Today;
                    List <AppointmentModel> appointmentList = (from app in dbContextAppointment.Appointments
                                                               select app
                                                               ).OrderByDescending(x => x.AppointmentId).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = appointmentList;
                }
                //get the patient's today's or future's appointments
                else if (reqType == "checkForClashingAppointment")
                {
                    List <AppointmentModel> patAppointmentList = (from app in dbContextAppointment.Appointments
                                                                  where app.PatientId == patientId &&
                                                                  app.AppointmentDate >= DbFunctions.TruncateTime(requestDate.Date) &&
                                                                  app.ProviderId == providerId
                                                                  select app).ToList();

                    VisitDbContext dbContext = new VisitDbContext(base.connString);

                    List <VisitModel> patientvisitList = (from visit in dbContext.Visits
                                                          where visit.PatientId == patientId &&
                                                          DbFunctions.TruncateTime(visit.VisitDate) == DbFunctions.TruncateTime(requestDate.Date) &&
                                                          visit.ProviderId == providerId
                                                          select visit).ToList();

                    if ((patAppointmentList != null && patAppointmentList.Count != 0) || (patientvisitList != null && patientvisitList.Count != 0))
                    {
                        responseData.Status  = "OK";
                        responseData.Results = true;
                    }
                    else
                    {
                        responseData.Status  = "OK";
                        responseData.Results = false;
                    }
                }
                //get the discoutnpercantage using membershipTypeid
                else if (reqType == "GetMembershipDeatils")
                {
                    PatientDbContext patientDbContext = new PatientDbContext(connString);
                    var membershipDeatils             = (from mem in patientDbContext.MembershipTypes
                                                         where mem.MembershipTypeId == membershipTypeId
                                                         select new
                    {
                        MembershipTypeId = mem.MembershipTypeId,
                        DiscountPercent = mem.DiscountPercent,
                        MembershipTypeName = mem.MembershipTypeName
                    }).FirstOrDefault();

                    responseData.Status  = "OK";
                    responseData.Results = membershipDeatils;
                }
                //get the TotalAmount using providerId
                else if (reqType == "GetTotalAmountByProviderId")
                {
                    BillingDbContext billingDbContext = new BillingDbContext(connString);

                    ServiceDepartmentModel srvDept = billingDbContext.ServiceDepartment.Where(s => s.ServiceDepartmentName == "OPD").FirstOrDefault();

                    if (srvDept != null)
                    {
                        ///remove tolist from below query-- one doc will have only one opd-tkt price.. <sudrshan:14jul2017>
                        var billingItemPrice = (from bill in billingDbContext.BillItemPrice
                                                where bill.ServiceDepartmentId == srvDept.ServiceDepartmentId && bill.ItemId == providerId
                                                select bill.Price).ToList();

                        responseData.Status  = "OK";
                        responseData.Results = billingItemPrice;
                    }
                    else
                    {
                        responseData.Status       = "Failed";
                        responseData.ErrorMessage = "Failed to get OPD-Ticket Price";
                    }
                }   //getting appointment list of selected ProvideId
                else if (reqType == "get-appointment-list")
                {
                    ////.ToList()is done two times,since we can't use requestDate.Date inside IQueryable
                    //List<AppointmentModel> apptList = (from d in dbContextAppointment.Appointments
                    //                                   where d.ProviderId == providerId
                    //                                   select d).ToList();
                    //AppointmentDay apptDay = AppointmentDay.FormatData(apptList);

                    ////responseData.Status = "OK";
                    //responseData.Results = apptDay;

                    var apptList = (from apt in dbContextAppointment.Appointments
                                    where apt.ProviderId == providerId && apt.AppointmentDate == requestDate
                                    select new
                    {
                        PatientName = apt.FirstName + " " + (string.IsNullOrEmpty(apt.MiddleName) ? "" : apt.MiddleName + " ") + apt.LastName,
                        Time = apt.AppointmentTime,
                        Date = apt.AppointmentDate,
                    }).ToList();
                    if (apptList != null)
                    {
                        responseData.Status  = "OK";
                        responseData.Results = apptList;
                    }
                    else
                    {
                        responseData.Status = "Failed";
                    }
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #2
0
        public string Get(string reqType, int patientId, int patientVisitId)
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            try
            {
                //this is duplicated from DoctorsController, remove from there and use this one later on.
                if (reqType == "patActiveorders" && patientId != 0)
                {
                    PatientModel     patientModel     = new PatientModel();
                    PatientDbContext dbContextcommand = new PatientDbContext(connString);
                    patientModel = (from pat in dbContextcommand.Patients
                                    where pat.PatientId == patientId
                                    select pat).Include(a => a.Visits.Select(v => v.Vitals))
                                   .Include(a => a.Problems)
                                   .Include(a => a.Allergies)
                                   .Include(a => a.Addresses)
                                   .Include(a => a.LabRequisitions)
                                   //.Include(a => a.ImagingReports)
                                   .Include(a => a.ImagingItemRequisitions)
                                   .Include(a => a.MedicationPrescriptions)
                                   .FirstOrDefault <PatientModel>();

                    //this will remove all other orders from past and only orders which matches visit-id will be shown (lab order / imaging order)
                    if (patientModel != null && patientModel.Visits != null && patientModel.Visits.Count > 0)
                    {
                        patientModel.LabRequisitions         = patientModel.LabRequisitions.Where(a => a.PatientVisitId == patientVisitId && a.BillingStatus != "returned").ToList();
                        patientModel.ImagingItemRequisitions = patientModel.ImagingItemRequisitions.Where(a => a.PatientVisitId == patientVisitId && a.BillingStatus != "returned").ToList();
                    }

                    //add vitals to patient
                    if (patientModel != null && patientModel.Visits != null && patientModel.Visits.Count > 0)
                    {
                        patientModel.Vitals = patientModel.Visits.SelectMany(a => a.Vitals).ToList();
                        //take last three vitals only..
                        patientModel.Vitals = patientModel.Vitals.OrderByDescending(a => a.CreatedOn).Take(3).ToList();
                    }

                    //remove resolved problems
                    if (patientModel != null && patientModel.Problems != null && patientModel.Problems.Count > 0)
                    {
                        patientModel.Problems = patientModel.Problems.Where(p => p.IsResolved == false).ToList();
                    }

                    MasterDbContext   masterDbContext = new MasterDbContext(connString);
                    PharmacyDbContext phrmDbContext   = new PharmacyDbContext(connString);
                    //add medication prescription if any.
                    //need to get it as pharmacy model later on, now we're mapping this as MedicationPrescription model only.
                    if (patientModel != null)
                    {
                        var patPrescriptions = phrmDbContext.PHRMPrescriptionItems.Where(p => p.PatientId == patientModel.PatientId).ToList();
                        if (patPrescriptions != null && patPrescriptions.Count > 0)
                        {
                            var allItems  = phrmDbContext.PHRMItemMaster.ToList();
                            var presItems = (from pres in patPrescriptions
                                             join itm in allItems
                                             on pres.ItemId equals itm.ItemId
                                             select new MedicationPrescriptionModel()
                            {
                                MedicationId = itm.ItemId,
                                MedicationName = itm.ItemName,
                                Frequency = pres.Frequency.HasValue ? pres.Frequency.Value.ToString() : "",
                                Duration = pres.HowManyDays.Value,
                                CreatedOn = pres.CreatedOn
                            }).ToList();

                            patientModel.MedicationPrescriptions = presItems;
                        }
                    }



                    List <PHRMItemMasterModel> medList = phrmDbContext.PHRMItemMaster.ToList();
                    //add name to allergies
                    if (patientModel != null && patientModel.Allergies != null && patientModel.Allergies.Count > 0)
                    {
                        foreach (var allergy in patientModel.Allergies)
                        {
                            if (allergy.AllergenAdvRecId != 0 && allergy.AllergenAdvRecId != null)
                            {
                                allergy.AllergenAdvRecName = medList.Where(a => a.ItemId == allergy.AllergenAdvRecId)
                                                             .FirstOrDefault().ItemName;
                            }
                        }
                    }

                    responseData.Status  = "OK";
                    responseData.Results = patientModel;
                }
                else if (reqType == "allOrderItems")
                {
                    OrdersDbContext orderDbContext = new OrdersDbContext(connString);
                    //concatenate all orderitems into one list.
                    List <OrderItemsVM> allOrderItems = new List <OrderItemsVM>();
                    //allOrderItems = allOrderItems.Concat(GetPhrmItems(orderDbContext)).ToList();
                    allOrderItems = allOrderItems.Concat(GetLabItems(orderDbContext)).ToList();
                    allOrderItems = allOrderItems.Concat(GetPhrmGenericItems(orderDbContext)).ToList();
                    allOrderItems = allOrderItems.Concat(GetImagingItems(orderDbContext)).ToList();
                    allOrderItems = allOrderItems.Concat(GetOtherItems(orderDbContext)).ToList();

                    responseData.Status  = "OK";
                    responseData.Results = allOrderItems;// allOrderItems.OrderBy(itm=>itm.ItemName).ToList();
                }
                else if (reqType == "empPreferences")
                {
                    RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser");

                    int             empId          = currentUser.EmployeeId;
                    OrdersDbContext orderDbContext = new OrdersDbContext(connString);

                    //concatenate all orderitems into one list.
                    List <OrderItemsVM> allPreferences = new List <OrderItemsVM>();
                    allPreferences       = allPreferences.Concat(GetLabPreferences(empId, orderDbContext)).ToList();
                    allPreferences       = allPreferences.Concat(GetMedicationPreferences(empId, orderDbContext)).ToList();
                    allPreferences       = allPreferences.Concat(GetImagingPreferences(empId, orderDbContext)).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = allPreferences;
                }
                else if (reqType == "getGenericMaps")
                {
                    List <PHRMGenericModel> genericList    = new List <PHRMGenericModel>();
                    OrdersDbContext         orderDbContext = new OrdersDbContext(connString);
                    genericList = (from generics in orderDbContext.PharmacyGenericItems
                                   select generics).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = genericList;
                }
                else if (reqType == "otherItems")
                {
                    OrdersDbContext orderDbContext = new OrdersDbContext(connString);
                    var             itemList       = (from itm in orderDbContext.BillItemPrice
                                                      join servceDpt in orderDbContext.ServiceDepartment on itm.ServiceDepartmentId equals servceDpt.ServiceDepartmentId
                                                      where (servceDpt.IntegrationName.ToLower() != "radiology" && servceDpt.IntegrationName.ToLower() != "lab")
                                                      select new {
                        BillItemPriceId = itm.BillItemPriceId,
                        ServiceDepartmentId = itm.ServiceDepartmentId,
                        ItemId = itm.ItemId,
                        ItemName = itm.ItemName,
                        ProcedureCode = itm.ProcedureCode,
                        Price = itm.Price,
                        CreatedBy = itm.CreatedBy,
                        CreatedOn = itm.CreatedOn,
                        ModifiedOn = itm.ModifiedOn,
                        ModifiedBy = itm.ModifiedBy,
                        IsActive = itm.IsActive,
                        IntegrationName = itm.IntegrationName,
                        TaxApplicable = itm.TaxApplicable,
                        Description = itm.Description,
                        DiscountApplicable = itm.DiscountApplicable,
                        IsDoctorMandatory = itm.IsDoctorMandatory,
                        ItemCode = itm.ItemCode,
                        DisplaySeq = itm.DisplaySeq,
                        HasAdditionalBillingItems = itm.HasAdditionalBillingItems,
                        InsuranceApplicable = itm.InsuranceApplicable,
                        GovtInsurancePrice = itm.GovtInsurancePrice,
                        IsInsurancePackage = itm.IsInsurancePackage,
                        IsFractionApplicable = itm.IsFractionApplicable,
                        EHSPrice = itm.EHSPrice,
                        SAARCCitizenPrice = itm.SAARCCitizenPrice,
                        ForeignerPrice = itm.ForeignerPrice,
                        ServiceDepartmentName = servceDpt.ServiceDepartmentName
                    }).OrderBy(item => item.ItemName).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = itemList;
                }
                else
                {
                    responseData.Status       = "Failed";
                    responseData.ErrorMessage = "invalid patient id";
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }

            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #3
0
        public string Put()
        {
            DanpheHTTPResponse <string> responseData = new DanpheHTTPResponse <string>();

            try
            {
                string   str           = this.ReadPostData();
                string   reqType       = this.ReadQueryStringData("reqType");
                string   status        = this.ReadQueryStringData("status");
                int      appointmentId = ToInt(this.ReadQueryStringData("appointmentId"));
                int      patientId     = ToInt(this.ReadQueryStringData("patientId"));
                RbacUser currentUser   = HttpContext.Session.Get <RbacUser>("currentuser");
                //update patientId in Appointment Table
                if (reqType == "updatePatientId" && patientId != 0)
                {
                    AppointmentDbContext dbContextUpdate = new AppointmentDbContext(connString);
                    AppointmentModel     dbAppointment   = dbContextUpdate.Appointments
                                                           .Where(a => a.AppointmentId == appointmentId)
                                                           .FirstOrDefault <AppointmentModel>();

                    dbAppointment.PatientId = patientId;
                    dbContextUpdate.Entry(dbAppointment).State = EntityState.Modified;
                    dbContextUpdate.SaveChanges();

                    responseData.Status  = "OK";
                    responseData.Results = "Appointment information updated successfully.";
                }
                //update appointmentStatus
                else if (reqType == "updateAppStatus" && !string.IsNullOrEmpty(status))
                {
                    AppointmentDbContext dbContextUpdate = new AppointmentDbContext(connString);
                    AppointmentModel     dbAppointment   = dbContextUpdate.Appointments
                                                           .Where(a => a.AppointmentId == appointmentId)
                                                           .FirstOrDefault <AppointmentModel>();
                    dbAppointment.AppointmentStatus            = status.ToLower();
                    dbContextUpdate.Entry(dbAppointment).State = EntityState.Modified;
                    dbContextUpdate.SaveChanges();

                    responseData.Status  = "OK";
                    responseData.Results = "Appointment information updated successfully.";
                }
                else if (reqType == "updateAppointmentStatus")
                {
                    AppointmentDbContext dbContextUpdate = new AppointmentDbContext(connString);
                    AppointmentModel     appointmentData = DanpheJSONConvert.DeserializeObject <AppointmentModel>(str);

                    dbContextUpdate.Appointments.Attach(appointmentData);
                    dbContextUpdate.Entry(appointmentData).State = EntityState.Modified;

                    dbContextUpdate.Entry(appointmentData).Property(x => x.CreatedOn).IsModified = false;
                    dbContextUpdate.Entry(appointmentData).Property(x => x.CreatedBy).IsModified = false;

                    appointmentData.CancelledOn = System.DateTime.Now;
                    appointmentData.CancelledBy = currentUser.EmployeeId;

                    dbContextUpdate.SaveChanges();

                    responseData.Status  = "OK";
                    responseData.Results = "Appointment information updated successfully";
                }
                else
                {
                    //throw new Exception("Cannot match any reqType");
                    //throw new NotImplementedException("cannot match any request type. given requesttype " + reqType + "  is not implemented.");
                    responseData.Status       = "Failed";
                    responseData.ErrorMessage = "Cannot match any reqType";
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #4
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));
        }
コード例 #5
0
        public string Delete(string reqType, string itemId)
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            try
            {
                OrdersDbContext orderDbContext = new OrdersDbContext(connString);

                if (reqType != null && reqType == "DeleteFromPreference")
                {
                    string preferenceType   = this.ReadQueryStringData("preferenceType");
                    string preferenceIdType = null;
                    string preferenceName   = null;
                    if (preferenceType.ToLower() == "lab")
                    {
                        preferenceName   = "Labtestpreferences";
                        preferenceIdType = "//LabTestId";
                    }
                    else if (preferenceType.ToLower() == "imaging")
                    {
                        preferenceName   = "Imagingpreferences";
                        preferenceIdType = "//ImagingItemId";
                    }
                    else if (preferenceType.ToLower() == "medication")
                    {
                        preferenceName   = "Medicationpreferences";
                        preferenceIdType = "//MedicineId";
                    }

                    RbacUser            currentUser        = HttpContext.Session.Get <RbacUser>("currentuser");
                    EmployeePreferences employeePreference = (from pref in orderDbContext.EmployeePreferences
                                                              where pref.EmployeeId == currentUser.EmployeeId && pref.PreferenceName == preferenceName
                                                              select pref).FirstOrDefault();


                    XmlDocument prefXmlDocument = new XmlDocument();
                    prefXmlDocument.LoadXml(employeePreference.PreferenceValue);
                    // selecting the node of xml Document with tag LabTestId
                    XmlNodeList nodes = prefXmlDocument.SelectNodes(preferenceIdType);
                    //looping through the loop and checking the labtestId match or not
                    //if it is matched with LabtestId the delete the node
                    foreach (XmlNode node in nodes)
                    {
                        if (node.InnerXml == itemId.ToString())
                        {
                            node.ParentNode.RemoveChild(node);
                        }
                    }
                    //replacing the old value of employeePreference.PreferenceValue with new one
                    employeePreference.PreferenceValue = prefXmlDocument.InnerXml;
                    employeePreference.ModifiedBy      = currentUser.EmployeeId;
                    employeePreference.ModifiedOn      = DateTime.Now;
                    orderDbContext.SaveChanges();
                    responseData.Status  = "OK";
                    responseData.Results = itemId;
                }
            }

            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #6
0
        public string Put()
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();
            string   reqType     = this.ReadQueryStringData("reqType");
            string   ipStr       = this.ReadPostData();
            RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser");

            try
            {
                LabDbContext     labDbContext  = new LabDbContext(connString);
                BillingDbContext billDbContext = new BillingDbContext(connString);
                if (reqType == "updateLabReport")
                {
                    LabReportTemplateModel labReportTemplate = DanpheJSONConvert.DeserializeObject <LabReportTemplateModel>(ipStr);

                    labDbContext.LabReportTemplates.Attach(labReportTemplate);
                    labDbContext.Entry(labReportTemplate).State = EntityState.Modified;
                    labDbContext.Entry(labReportTemplate).Property(x => x.CreatedOn).IsModified = false;
                    labDbContext.Entry(labReportTemplate).Property(x => x.CreatedBy).IsModified = false;
                    labReportTemplate.ModifiedOn = System.DateTime.Now;
                    labReportTemplate.ModifiedBy = currentUser.EmployeeId;

                    if (labReportTemplate.IsDefault == true)
                    {
                        LabReportTemplateModel rowToUpdate = (from rep in labDbContext.LabReportTemplates
                                                              where rep.IsDefault == true
                                                              select rep
                                                              ).FirstOrDefault();

                        if (rowToUpdate != null)
                        {
                            labDbContext.LabReportTemplates.Attach(rowToUpdate);
                            rowToUpdate.IsDefault = false;
                            labDbContext.SaveChanges();
                        }
                    }

                    labDbContext.SaveChanges();
                    responseData.Results = labReportTemplate;
                    responseData.Status  = "OK";
                }
                else if (reqType == "updateLabTest")
                {
                    LabTestModel  labTest       = DanpheJSONConvert.DeserializeObject <LabTestModel>(ipStr);
                    BillItemPrice billItemPrice = billDbContext.BillItemPrice.Where(a => a.ItemName == labTest.LabTestName && a.ItemName == labTest.LabTestName).FirstOrDefault <BillItemPrice>();

                    using (var dbContextTransaction = labDbContext.Database.BeginTransaction())
                    {
                        try
                        {
                            //First Make all the Previous Mapping of Current Test False
                            List <LabTestComponentMapModel> mappedItemList = labDbContext.LabTestComponentMap.Where(mp => mp.LabTestId == labTest.LabTestId).ToList();
                            mappedItemList.ForEach(x => x.IsActive = false);
                            labDbContext.SaveChanges();

                            if (labTest.TemplateType.ToLower() == "html")
                            {
                                var componentToAdd = labTest.LabTestComponentsJSON[0];
                                List <LabTestJSONComponentModel> allOldComponents = (from test in labDbContext.LabTests
                                                                                     join componentMap in labDbContext.LabTestComponentMap on test.LabTestId equals componentMap.LabTestId
                                                                                     join component in labDbContext.LabTestComponents on componentMap.ComponentId equals component.ComponentId
                                                                                     where test.LabTestId == labTest.LabTestId && component.ComponentName == componentToAdd.ComponentName
                                                                                     select component).ToList();

                                if (allOldComponents.Count() > 0)
                                {
                                    var componentMapToUpdate = labTest.LabTestComponentMap[0];
                                    componentMapToUpdate.ComponentId = allOldComponents[0].ComponentId;
                                    var existMap = labDbContext.LabTestComponentMap.Where(mp => mp.LabTestId == labTest.LabTestId && mp.ComponentId == componentMapToUpdate.ComponentId).FirstOrDefault();

                                    existMap.IsActive        = true;
                                    existMap.DisplaySequence = componentMapToUpdate.DisplaySequence;
                                    existMap.ModifiedBy      = currentUser.EmployeeId;
                                    existMap.ModifiedOn      = System.DateTime.Now;

                                    labDbContext.Entry(existMap).Property(x => x.IsActive).IsModified        = true;
                                    labDbContext.Entry(existMap).Property(x => x.DisplaySequence).IsModified = true;
                                    labDbContext.Entry(existMap).Property(x => x.ModifiedBy).IsModified      = true;
                                    labDbContext.Entry(existMap).Property(x => x.ModifiedBy).IsModified      = true;

                                    labDbContext.SaveChanges();
                                }
                                else
                                {
                                    labDbContext.LabTestComponents.Add(componentToAdd);
                                    labDbContext.SaveChanges();
                                    var compId            = componentToAdd.ComponentId;
                                    var componentMapToAdd = labTest.LabTestComponentMap[0];
                                    componentMapToAdd.ComponentId = compId;
                                    labDbContext.LabTestComponentMap.Add(componentMapToAdd);
                                    labDbContext.SaveChanges();
                                }
                            }
                            else
                            {
                                List <LabTestComponentMapModel> labMapToBeUpdated = labTest.LabTestComponentMap;
                                foreach (var itm in labMapToBeUpdated)
                                {
                                    var existingMap = labDbContext.LabTestComponentMap.Where(mp => mp.LabTestId == labTest.LabTestId && mp.ComponentId == itm.ComponentId).FirstOrDefault();
                                    //Newly added Mapping
                                    if (existingMap == null)
                                    {
                                        itm.ModifiedBy = currentUser.EmployeeId;
                                        itm.ModifiedOn = System.DateTime.Now;
                                        itm.IsActive   = true;
                                        labDbContext.LabTestComponentMap.Add(itm);
                                        labDbContext.SaveChanges();
                                    }
                                    //Update Old Mapping
                                    else
                                    {
                                        existingMap.IsActive         = true;
                                        existingMap.IndentationCount = itm.IndentationCount;
                                        existingMap.DisplaySequence  = itm.DisplaySequence;
                                        existingMap.ModifiedBy       = currentUser.EmployeeId;
                                        existingMap.ModifiedOn       = System.DateTime.Now;

                                        labDbContext.Entry(existingMap).Property(x => x.IsActive).IsModified         = true;
                                        labDbContext.Entry(existingMap).Property(x => x.IndentationCount).IsModified = true;
                                        labDbContext.Entry(existingMap).Property(x => x.DisplaySequence).IsModified  = true;
                                        labDbContext.Entry(existingMap).Property(x => x.ModifiedBy).IsModified       = true;
                                        labDbContext.Entry(existingMap).Property(x => x.ModifiedBy).IsModified       = true;
                                        labDbContext.SaveChanges();
                                    }
                                }
                            }

                            billItemPrice.IsActive = labTest.IsActive;
                            billItemPrice.ItemName = labTest.LabTestName;

                            labDbContext.LabTests.Attach(labTest);
                            labDbContext.BillItemPrice.Attach(billItemPrice);
                            labDbContext.Entry(labTest).State = EntityState.Modified;
                            labDbContext.Entry(labTest).Property(x => x.CreatedOn).IsModified     = false;
                            labDbContext.Entry(labTest).Property(x => x.CreatedBy).IsModified     = false;
                            labDbContext.Entry(labTest).Property(x => x.LabTestCode).IsModified   = false;
                            labDbContext.Entry(labTest).Property(x => x.ProcedureCode).IsModified = false;
                            billItemPrice.TaxApplicable = labTest.IsTaxApplicable;
                            labTest.ModifiedOn          = System.DateTime.Now;
                            labTest.ModifiedBy          = currentUser.EmployeeId;
                            labDbContext.Entry(billItemPrice).Property(x => x.TaxApplicable).IsModified = true;
                            labDbContext.Entry(billItemPrice).Property(x => x.ItemName).IsModified      = true;
                            labDbContext.Entry(billItemPrice).Property(x => x.IsActive).IsModified      = true;
                            labDbContext.SaveChanges();
                            dbContextTransaction.Commit();
                            responseData.Results = labTest;
                            responseData.Status  = "OK";
                        }

                        catch (Exception ex)
                        {
                            dbContextTransaction.Rollback();
                            throw (ex);
                        }
                    }
                }


                else if (reqType == "updateDefaultSignatories")
                {
                    List <AdminParametersModel> AllSignatories = DanpheJSONConvert.DeserializeObject <List <AdminParametersModel> >(ipStr);
                    foreach (AdminParametersModel parameter in AllSignatories)
                    {
                        var parm = (from cfg in labDbContext.AdminParameters
                                    where cfg.ParameterId == parameter.ParameterId
                                    select cfg).FirstOrDefault();

                        parm.ParameterValue = parameter.ParameterValue;
                        labDbContext.Entry(parm).Property(p => p.ParameterValue).IsModified = true;
                        labDbContext.SaveChanges();
                    }

                    responseData.Results = AllSignatories;
                    responseData.Status  = "OK";
                }
                else if (reqType == "updateLabTestComponent")
                {
                    List <LabTestJSONComponentModel> componentList         = DanpheJSONConvert.DeserializeObject <List <LabTestJSONComponentModel> >(ipStr);
                    List <LabTestJSONComponentModel> componentListToReturn = new List <LabTestJSONComponentModel>();
                    using (var dbContextTransaction = labDbContext.Database.BeginTransaction())
                    {
                        try
                        {
                            var allLabComponents = labDbContext.LabTestComponents.ToList();
                            foreach (var comp in componentList)
                            {
                                var duplicateComponent = allLabComponents.FirstOrDefault(x => x.ComponentName == comp.ComponentName && x.DisplayName == comp.DisplayName);

                                if (duplicateComponent == null || (duplicateComponent != null && duplicateComponent.ComponentId == comp.ComponentId))
                                {
                                    var componentId       = comp.ComponentId;
                                    var componentToUpdate = (from component in labDbContext.LabTestComponents
                                                             where component.ComponentId == componentId
                                                             select component).FirstOrDefault();

                                    componentToUpdate.ComponentName    = comp.ComponentName;
                                    componentToUpdate.DisplayName      = comp.DisplayName;
                                    componentToUpdate.ModifiedBy       = currentUser.EmployeeId;
                                    componentToUpdate.ModifiedOn       = System.DateTime.Now;
                                    componentToUpdate.Range            = comp.Range;
                                    componentToUpdate.MaleRange        = comp.MaleRange;
                                    componentToUpdate.FemaleRange      = comp.FemaleRange;
                                    componentToUpdate.ChildRange       = comp.ChildRange;
                                    componentToUpdate.RangeDescription = comp.RangeDescription;
                                    componentToUpdate.MinValue         = comp.MinValue;
                                    componentToUpdate.MaxValue         = comp.MaxValue;
                                    componentToUpdate.Unit             = comp.Unit;
                                    componentToUpdate.ValueLookup      = comp.ValueLookup;
                                    componentToUpdate.ValueType        = comp.ValueType;
                                    componentToUpdate.Method           = comp.Method;
                                    componentToUpdate.ControlType      = comp.ControlType;

                                    labDbContext.Entry(componentToUpdate).State = EntityState.Modified;
                                    labDbContext.Entry(componentToUpdate).Property(x => x.CreatedOn).IsModified = false;
                                    labDbContext.Entry(componentToUpdate).Property(x => x.CreatedBy).IsModified = false;

                                    labDbContext.SaveChanges();
                                }
                            }
                            dbContextTransaction.Commit();

                            responseData.Results = componentList;
                            responseData.Status  = "OK";
                        }
                        catch (Exception ex)
                        {
                            dbContextTransaction.Rollback();
                            throw (ex);
                        }
                    }
                }
                else if (reqType == "updateLabLookUpComponent")
                {
                    CoreCFGLookupModel Lookup         = DanpheJSONConvert.DeserializeObject <CoreCFGLookupModel>(ipStr);
                    CoreCFGLookupModel LookupToReturn = new CoreCFGLookupModel();
                    using (var dbContextTransaction = labDbContext.Database.BeginTransaction())
                    {
                        try
                        {
                            var allLookupComponents = labDbContext.LabLookUps.ToList();
                            var duplicateComponent  = allLookupComponents.FirstOrDefault(x => x.ModuleName == Lookup.ModuleName && x.LookUpName == Lookup.LookUpName && x.LookupDataJson == Lookup.LookupDataJson);

                            if (duplicateComponent == null || (duplicateComponent != null && duplicateComponent.LookUpId == Lookup.LookUpId))
                            {
                                var LookUpId       = Lookup.LookUpId;
                                var LookupToUpdate = (from lookup in labDbContext.LabLookUps
                                                      where lookup.LookUpId == LookUpId
                                                      select lookup).FirstOrDefault();

                                LookupToUpdate.LookUpName     = Lookup.LookUpName;
                                LookupToUpdate.LookupDataJson = Lookup.LookupDataJson;
                                LookupToUpdate.ModuleName     = Lookup.ModuleName;
                                LookupToUpdate.Description    = Lookup.Description;


                                labDbContext.Entry(LookupToUpdate).State = EntityState.Modified;

                                labDbContext.SaveChanges();
                            }

                            dbContextTransaction.Commit();

                            responseData.Results = Lookup;
                            responseData.Status  = "OK";
                        }
                        catch (Exception ex)
                        {
                            dbContextTransaction.Rollback();
                            throw (ex);
                        }
                    }
                }

                else if (reqType == "updateLabVendor")
                {
                    LabVendorsModel vendorFromClient = DanpheJSONConvert.DeserializeObject <LabVendorsModel>(ipStr);
                    LabVendorsModel defaultVendor    = labDbContext.LabVendors.Where(val => val.IsDefault == true).FirstOrDefault();


                    if (vendorFromClient != null && vendorFromClient.LabVendorId != 0)
                    {
                        if (vendorFromClient.IsDefault)
                        {
                            if (defaultVendor != null && defaultVendor.IsDefault)
                            {
                                defaultVendor.IsDefault = false;
                                labDbContext.Entry(defaultVendor).State = EntityState.Modified;
                                labDbContext.Entry(defaultVendor).Property(x => x.IsDefault).IsModified = true;
                            }
                        }



                        var vendorFromServer = (from ven in labDbContext.LabVendors
                                                where ven.LabVendorId == vendorFromClient.LabVendorId
                                                select ven).FirstOrDefault();

                        vendorFromServer.VendorCode     = vendorFromClient.VendorCode;
                        vendorFromServer.VendorName     = vendorFromClient.VendorName;
                        vendorFromServer.ContactAddress = vendorFromClient.ContactAddress;
                        vendorFromServer.ContactNo      = vendorFromClient.ContactNo;
                        vendorFromServer.Email          = vendorFromClient.Email;
                        vendorFromClient.IsActive       = vendorFromClient.IsActive;
                        vendorFromServer.IsExternal     = vendorFromClient.IsExternal;
                        vendorFromServer.IsDefault      = vendorFromClient.IsDefault;

                        labDbContext.Entry(vendorFromServer).Property(v => v.VendorCode).IsModified     = true;
                        labDbContext.Entry(vendorFromServer).Property(v => v.VendorName).IsModified     = true;
                        labDbContext.Entry(vendorFromServer).Property(v => v.ContactAddress).IsModified = true;
                        labDbContext.Entry(vendorFromServer).Property(v => v.ContactNo).IsModified      = true;
                        labDbContext.Entry(vendorFromServer).Property(v => v.Email).IsModified          = true;
                        labDbContext.Entry(vendorFromServer).Property(v => v.IsActive).IsModified       = true;
                        labDbContext.Entry(vendorFromServer).Property(v => v.IsExternal).IsModified     = true;
                        labDbContext.Entry(vendorFromServer).Property(v => v.IsDefault).IsModified      = true;

                        labDbContext.SaveChanges();

                        responseData.Results = vendorFromClient;//return the same data to client.
                        responseData.Status  = "OK";
                    }
                    else
                    {
                        responseData.Status       = "Failed";
                        responseData.ErrorMessage = "Couldn't find vendor.";
                    }
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }

            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
        public string Post()
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            //DanpheTeleMedDbContext dbContext = new DanpheTeleMedDbContext(connString);
            responseData.Status = "OK";
            try
            {
                string str     = new StreamReader(Request.Body).ReadToEnd();
                string reqType = Request.Query["reqType"];
                responseData.Results = str + reqType;
                #region Save User
                if (reqType == "save-user")
                {
                    UserModel user = DanpheJSONConvert.DeserializeObject <UserModel>(str);
                    if (user != null)
                    {
                        var usr = dbContext.User.Where(u => u.UserName == user.UserName).Select(a => a).ToList();
                        if (usr.Count > 0)
                        {
                            responseData.Status       = "Falied";
                            responseData.ErrorMessage = "User already exits";
                        }
                        else
                        {
                            dbContext.User.Add(user);
                            dbContext.SaveChanges();
                            responseData.Results = user;
                            responseData.Status  = "OK";
                        }
                    }
                    else
                    {
                        responseData.Status       = "Failed";
                        responseData.ErrorMessage = "user information not received";
                    }
                }
                #endregion
                #region Save Conference
                else if (reqType == "save-new-conference")
                {
                    ConferenceModel conference = DanpheJSONConvert.DeserializeObject <ConferenceModel>(str);
                    if (conference != null)
                    {
                        ConferenceUserModel conferenceUser = new ConferenceUserModel();
                        conferenceUser.ConferenceRoomId = conference.ConferenceRoomId;
                        conferenceUser.UserName         = GetUserName(dbContext, conference.CreatedBy);
                        conferenceUser.JoinTime         = conference.CreatedOn;

                        dbContext.Conference.Add(conference);
                        dbContext.ConferenceUser.Add(conferenceUser);
                        dbContext.SaveChanges();
                        responseData.Results = conference;
                        responseData.Status  = "OK";
                    }
                }
                #endregion
                #region Add new user in conference
                else if (reqType == "add-conference-user")
                {
                    ConferenceUserModel conferenceUser = DanpheJSONConvert.DeserializeObject <ConferenceUserModel>(str);
                    if (conferenceUser != null)
                    {
                        dbContext.ConferenceUser.Add(conferenceUser);
                        dbContext.SaveChanges();
                        responseData.Results = conferenceUser;
                        responseData.Status  = "OK";
                    }
                }
                #endregion
                #region Save conference chat
                else if (reqType == "save-conference-chat")
                {
                    ConferenceChatModel conferenceChat = DanpheJSONConvert.DeserializeObject <ConferenceChatModel>(str);
                    if (conferenceChat != null)
                    {
                        dbContext.ConferenceChat.Add(conferenceChat);
                        dbContext.SaveChanges();
                        responseData.Results = conferenceChat;
                        responseData.Status  = "OK";
                    }
                }
                #endregion
                #region Save new session of p2p connection
                else if (reqType == "save-new-session")
                {
                    SessionTxnModel sessionTxn = DanpheJSONConvert.DeserializeObject <SessionTxnModel>(str);
                    if (sessionTxn != null)
                    {
                        dbContext.SessionTxns.Add(sessionTxn);
                        dbContext.SaveChanges();

                        SessionUserTxnModel sessionUserTxn = new SessionUserTxnModel();
                        sessionUserTxn.SessionId      = sessionTxn.SessionId;
                        sessionUserTxn.SessionOwnerId = sessionTxn.CreatedBy;
                        sessionUserTxn.OwnerJoinTime  = sessionTxn.CreatedOn;
                        sessionUserTxn.UserId         = sessionTxn.CallingTo;
                        sessionUserTxn.UserJoinTime   = sessionTxn.CreatedOn;
                        dbContext.SessionUserTxns.Add(sessionUserTxn);
                        dbContext.SaveChanges();
                        responseData.Status = "OK";
                    }
                }
                #endregion
                #region Add new user in p2p session
                else if (reqType == "add-session-user")
                {
                    SessionUserTxnModel sessionUserTxn = DanpheJSONConvert.DeserializeObject <SessionUserTxnModel>(str);
                    if (sessionUserTxn != null)
                    {
                        if (sessionUserTxn.SessionOwnerId > 0)
                        {
                            dbContext.SessionUserTxns.Add(sessionUserTxn);
                            dbContext.SaveChanges();
                        }
                        else
                        {
                            var newuser = (from u in dbContext.SessionUserTxns
                                           where u.SessionId == sessionUserTxn.SessionId
                                           select u).FirstOrDefault();
                            newuser.UserId       = sessionUserTxn.UserId;
                            newuser.UserJoinTime = sessionUserTxn.UserJoinTime;
                            dbContext.SessionUserTxns.Attach(newuser);
                            dbContext.Entry(newuser).Property(a => a.UserId).IsModified       = true;
                            dbContext.Entry(newuser).Property(a => a.UserJoinTime).IsModified = true;
                            dbContext.Entry(newuser).State = EntityState.Modified;
                            dbContext.SaveChanges();
                        }
                    }
                    responseData.Results = sessionUserTxn;
                    responseData.Status  = "OK";
                }
                #endregion
                #region Save session chat in p2p connection
                else if (reqType == "save-session-chat")
                {
                    SessionChatModel sessionChat = DanpheJSONConvert.DeserializeObject <SessionChatModel>(str);
                    if (sessionChat != null)
                    {
                        var schat = (from s in dbContext.SessionUserTxns
                                     where s.SessionId == sessionChat.SessionId
                                     select new
                        {
                            s.SessionOwnerId,
                            s.UserId
                        }).FirstOrDefault();
                        sessionChat.ReceiverId = (schat.UserId == sessionChat.SenderId) ? schat.SessionOwnerId : schat.UserId;
                        dbContext.SessionChat.Add(sessionChat);
                        dbContext.SaveChanges();
                        responseData.Results = sessionChat;
                        responseData.Status  = "OK";
                    }
                }
                #endregion
                #region save assessment
                else if (reqType == "save-assessment")
                {
                    ClinicalAssessmentModel assessment = DanpheJSONConvert.DeserializeObject <ClinicalAssessmentModel>(str);
                    if (assessment != null)
                    {
                        dbContext.Assessment.Add(assessment);
                        dbContext.SaveChanges();
                        responseData.Status = "OK";
                    }
                }
                #endregion
                #region save complain
                else if (reqType == "save-complain")
                {
                    ClinicalComplainModel complain = DanpheJSONConvert.DeserializeObject <ClinicalComplainModel>(str);
                    if (complain != null)
                    {
                        dbContext.Complain.Add(complain);
                        dbContext.SaveChanges();
                        responseData.Status = "OK";
                    }
                }
                #endregion
                #region save examination
                else if (reqType == "save-examination")
                {
                    ClinicalExaminationModel examination = DanpheJSONConvert.DeserializeObject <ClinicalExaminationModel>(str);
                    if (examination != null)
                    {
                        dbContext.Examination.Add(examination);
                        dbContext.SaveChanges();
                        responseData.Status = "OK";
                    }
                }
                #endregion
                #region save orders
                else if (reqType == "save-orders")
                {
                    ClinicalOrderModel order = DanpheJSONConvert.DeserializeObject <ClinicalOrderModel>(str);
                    if (order != null)
                    {
                        dbContext.Order.Add(order);
                        dbContext.SaveChanges();
                        responseData.Status = "OK";
                    }
                }
                #endregion
                #region save plan
                else if (reqType == "save-plan")
                {
                    ClinicalPlanModel plan = DanpheJSONConvert.DeserializeObject <ClinicalPlanModel>(str);
                    if (plan != null)
                    {
                        dbContext.Plan.Add(plan);
                        dbContext.SaveChanges();
                        responseData.Status = "OK";
                    }
                }
                #endregion
                #region save consult request
                else if (reqType == "save-consult-request")
                {
                    ConsultRequestModel consult = DanpheJSONConvert.DeserializeObject <ConsultRequestModel>(str);
                    if (consult != null)
                    {
                        dbContext.ConsultRequest.Add(consult);
                        dbContext.SaveChanges();
                        responseData.Status = "OK";
                    }
                }
                #endregion
                #region End Video Call
                else if (reqType == "end-video-call")
                {
                    SessionTxnModel sessionTxn = DanpheJSONConvert.DeserializeObject <SessionTxnModel>(str);
                    var             es         = (from st in dbContext.SessionTxns
                                                  where st.SessionId == sessionTxn.SessionId
                                                  select st).FirstOrDefault();
                    if (es != null)
                    {
                        es.EndTime = sessionTxn.EndTime;
                        dbContext.SessionTxns.Attach(es);
                        dbContext.Entry(es).Property(a => a.EndTime).IsModified = true;
                        dbContext.Entry(es).State = EntityState.Modified;
                        dbContext.SaveChanges();
                    }
                    responseData.Results = es;
                    responseData.Status  = "OK";
                }
                #endregion
                else
                {
                    responseData.Results = "Wrong data";
                    responseData.Status  = "OK";
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + "exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #8
0
        public string Post()
        {
            //if reqtype=employee, then use masterdbcontext.employee.add  and so on for others.

            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
            AccountingDbContext accountingDBContext = new AccountingDbContext(connString);
            RbacUser            currentUser         = HttpContext.Session.Get <RbacUser>("currentuser");

            try
            {
                string str         = this.ReadPostData();
                string reqType     = this.ReadQueryStringData("reqType");
                string companyName = this.ReadQueryStringData("companyName");

                if (reqType == "AddLedgers")
                {
                    LedgerModel ledger = DanpheJSONConvert.DeserializeObject <LedgerModel>(str);
                    if (accountingDBContext.Ledgers.Any(r => r.LedgerGroupId == ledger.LedgerGroupId && r.LedgerName == ledger.LedgerName))
                    {
                        responseData.Status = "Failed";
                    }
                    else
                    {
                        ledger.CreatedOn = System.DateTime.Now;
                        accountingDBContext.Ledgers.Add(ledger);
                        accountingDBContext.SaveChanges();
                        if (ledger.LedgerType == "pharmacysupplier")
                        {
                            LedgerMappingModel ledgerMapping = new LedgerMappingModel();
                            ledgerMapping.LedgerId    = ledger.LedgerId;
                            ledgerMapping.LedgerType  = ledger.LedgerType;
                            ledgerMapping.ReferenceId = (int)ledger.LedgerReferenceId;
                            accountingDBContext.LedgerMappings.Add(ledgerMapping);
                        }
                        accountingDBContext.SaveChanges();
                        responseData.Results = ledger;
                        responseData.Status  = "OK";
                    }
                }
                if (reqType == "AddLedgersList")
                {
                    List <LedgerModel> Ledgrs = DanpheJSONConvert.DeserializeObject <List <LedgerModel> >(str);
                    //if (accountingDBContext.Ledgers.Any(r => r.LedgerGroupId == ledger.LedgerGroupId && r.LedgerName == ledger.LedgerName))
                    //{
                    //    responseData.Status = "Failed";
                    //}
                    //else
                    //{
                    Ledgrs.ForEach(ledger =>
                    {
                        ledger.CreatedOn = System.DateTime.Now;
                        accountingDBContext.Ledgers.Add(ledger);
                        accountingDBContext.SaveChanges();
                        if (ledger.LedgerType == "pharmacysupplier")
                        {
                            LedgerMappingModel ledgerMapping = new LedgerMappingModel();
                            ledgerMapping.LedgerId           = ledger.LedgerId;
                            ledgerMapping.LedgerType         = ledger.LedgerType;
                            ledgerMapping.ReferenceId        = (int)ledger.LedgerReferenceId;
                            accountingDBContext.LedgerMappings.Add(ledgerMapping);
                        }
                    });

                    accountingDBContext.SaveChanges();
                    responseData.Results = Ledgrs;
                    responseData.Status  = "OK";
                    //}
                }
                else if (reqType == "AddVouchers")
                {
                    VoucherModel voucher = DanpheJSONConvert.DeserializeObject <VoucherModel>(str);
                    voucher.CreatedOn = System.DateTime.Now;
                    voucher.CreatedBy = currentUser.UserId;
                    accountingDBContext.Vouchers.Add(voucher);
                    accountingDBContext.SaveChanges();
                    responseData.Results = voucher;
                    responseData.Status  = "OK";
                }

                else if (reqType == "AddVoucherHead")
                {
                    VoucherHeadModel voucherHead = DanpheJSONConvert.DeserializeObject <VoucherHeadModel>(str);
                    if (accountingDBContext.VoucherHeads.Any(x => x.VoucherHeadId == voucherHead.VoucherHeadId && x.VoucherHeadName == voucherHead.VoucherHeadName))
                    {
                        responseData.Status = "Failed";
                    }
                    else
                    {
                        voucherHead.CreatedOn = System.DateTime.Now;
                        voucherHead.CreatedBy = currentUser.UserId;
                        accountingDBContext.VoucherHeads.Add(voucherHead);
                        accountingDBContext.SaveChanges();
                        responseData.Results = voucherHead;
                        responseData.Status  = "OK";
                    }
                }
                else if (reqType == "AddItems")
                {
                    ItemModel item = DanpheJSONConvert.DeserializeObject <ItemModel>(str);
                    item.CreatedOn = System.DateTime.Now;
                    accountingDBContext.Items.Add(item);
                    accountingDBContext.SaveChanges();
                    var itemWithLedgerName = (from led in accountingDBContext.Ledgers
                                              where led.LedgerId == item.LedgerId
                                              select new
                    {
                        ItemId = item.ItemId,
                        ItemName = item.ItemName,
                        AvailableQuantity = item.AvailableQuantity,
                        IsActive = item.IsActive,
                        Description = item.Description,
                        LedgerId = item.LedgerId,
                        LedgerName = led.LedgerName
                    }
                                              );
                    responseData.Results = itemWithLedgerName;
                    responseData.Status  = "OK";
                }
                else if (reqType == "AddLedgersGroup")
                {
                    LedgerGroupModel ledgerGrpData = DanpheJSONConvert.DeserializeObject <LedgerGroupModel>(str);
                    if (accountingDBContext.LedgerGroups.Any(r => r.LedgerGroupName == ledgerGrpData.LedgerGroupName && r.COA == ledgerGrpData.COA && r.PrimaryGroup == ledgerGrpData.PrimaryGroup))
                    {
                        responseData.Status = "Failed";
                    }
                    else
                    {
                        ledgerGrpData.CreatedOn = DateTime.Now;
                        ledgerGrpData.CreatedBy = currentUser.UserId;
                        accountingDBContext.LedgerGroups.Add(ledgerGrpData);
                        accountingDBContext.SaveChanges();
                        responseData.Results = ledgerGrpData;
                        responseData.Status  = "OK";
                    }
                }
                else if (reqType == "manageVoucherWithLedgegroup")
                {
                    List <VoucherLedgerGroupMapModel> mappedData = DanpheJSONConvert.DeserializeObject <List <VoucherLedgerGroupMapModel> >(str);
                    var postMappedLedgerGroup = new List <VoucherLedgerGroupMapModel>();
                    var putMappedLedgerGroup  = new List <VoucherLedgerGroupMapModel>();
                    //map and separate two list for add and update
                    mappedData.ForEach(x =>
                    {
                        if (x.actionName == "post")
                        {
                            x.CreatedOn = DateTime.Now;
                            x.CreatedBy = currentUser.UserId;
                            postMappedLedgerGroup.Add(x);
                        }
                        else if (x.actionName == "put")
                        {
                            putMappedLedgerGroup.Add(x);
                        }
                    });
                    //update
                    foreach (var itm in putMappedLedgerGroup)
                    {
                        accountingDBContext.VoucherLedgerGroupMaps.Attach(itm);
                        accountingDBContext.Entry(itm).Property(x => x.IsActive).IsModified = true;
                    }
                    accountingDBContext.SaveChanges();

                    //add
                    foreach (var itm in postMappedLedgerGroup)
                    {
                        accountingDBContext.VoucherLedgerGroupMaps.Add(itm);
                    }
                    accountingDBContext.SaveChanges();
                    responseData.Status = "OK";
                }
                else if (reqType == "AddFiscalYear")
                {
                    FiscalYearModel fsModel = DanpheJSONConvert.DeserializeObject <FiscalYearModel>(str);

                    var checkFiscalYear = (from fs in accountingDBContext.FiscalYears
                                           where ((fs.FiscalYearName == fsModel.FiscalYearName) && (fs.IsActive == true))
                                           select fs).FirstOrDefault();
                    if (checkFiscalYear != null)
                    {
                        fsModel = null;
                        responseData.Results = fsModel;
                    }
                    else
                    {
                        fsModel.CreatedOn = System.DateTime.Now;
                        fsModel.CreatedBy = currentUser.UserId;
                        accountingDBContext.FiscalYears.Add(fsModel);
                        accountingDBContext.SaveChanges();

                        var fiscalCurtData = (from fisCal in accountingDBContext.FiscalYears
                                              where fisCal.FiscalYearId == fsModel.FiscalYearId
                                              select new
                        {
                            FiscalYearId = fisCal.FiscalYearId,
                            FiscalYearName = fisCal.FiscalYearName,
                            StartYear = fisCal.StartDate,
                            EndYear = fisCal.EndDate,
                            Description = fisCal.Description,
                            IsActive = fisCal.IsActive,
                        });
                        responseData.Results = fiscalCurtData;
                    }
                    responseData.Status = "OK";
                }
                else if (reqType == "AddCostCenterItem")
                {
                    CostCenterItemModel costCenterMod = DanpheJSONConvert.DeserializeObject <CostCenterItemModel>(str);
                    costCenterMod.CreatedOn = System.DateTime.Now;
                    costCenterMod.CreatedBy = currentUser.UserId;
                    accountingDBContext.CostCenterItems.Add(costCenterMod);
                    accountingDBContext.SaveChanges();

                    var curtCostCenterItmData = (from costCenterItm in accountingDBContext.CostCenterItems
                                                 where costCenterItm.CostCenterItemId == costCenterMod.CostCenterItemId
                                                 select new
                    {
                        CostCenterItemId = costCenterItm.CostCenterItemId,
                        CostCenterItemName = costCenterItm.CostCenterItemName,
                        Description = costCenterItm.Description,
                        IsActive = costCenterItm.IsActive,
                    });
                    responseData.Status  = "OK";
                    responseData.Results = curtCostCenterItmData;
                }
                else if (reqType == "AddLedgerGroupCategory")
                {
                    LedgerGroupCategoryModel ledGrpCatMod = DanpheJSONConvert.DeserializeObject <LedgerGroupCategoryModel>(str);
                    ledGrpCatMod.CreatedOn = System.DateTime.Now;
                    ledGrpCatMod.CreatedBy = currentUser.UserId;
                    accountingDBContext.LedgerGroupsCategory.Add(ledGrpCatMod);
                    accountingDBContext.SaveChanges();

                    var curtLedGrpCategoryData = (from ledgrpCat in accountingDBContext.LedgerGroupsCategory
                                                  join chartOfAcc in accountingDBContext.ChartOfAccounts on ledgrpCat.ChartOfAccountId equals chartOfAcc.ChartOfAccountId
                                                  where ledgrpCat.LedgerGroupCategoryId == ledGrpCatMod.LedgerGroupCategoryId
                                                  select new
                    {
                        LedgerGroupCategoryId = ledgrpCat.LedgerGroupCategoryId,
                        LedgerGroupCategoryName = ledgrpCat.LedgerGroupCategoryName,
                        ChartOfAccountName = chartOfAcc.ChartOfAccountName,
                        Description = ledgrpCat.Description,
                        IsActive = ledgrpCat.IsActive,
                        IsDebit = ledgrpCat.IsDebit,
                    });
                    responseData.Status  = "OK";
                    responseData.Results = curtLedGrpCategoryData;
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }

            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #9
0
        public string Get(string reqType, int voucherId, int ledgergroupId)
        {
            DanpheHTTPResponse <object> responseData        = new DanpheHTTPResponse <object>();
            AccountingDbContext         accountingDbContext = new AccountingDbContext(connString);

            try
            {
                if (reqType == "voucherList")
                {
                    List <VoucherModel> voucherList = (from voucherlist in accountingDbContext.Vouchers
                                                       select voucherlist).ToList();
                    responseData.Results = voucherList;
                }
                else if (reqType == "GetVoucherHead")
                {
                    var Voucherhead = (from voc in accountingDbContext.VoucherHeads
                                       select new
                    {
                        VoucherHeadId = voc.VoucherHeadId,
                        VoucherHeadName = voc.VoucherHeadName,
                        IsActive = voc.IsActive,
                        Description = voc.Description,
                        CreatedOn = voc.CreatedOn,
                        CreatedBy = voc.CreatedBy
                    }
                                       ).ToList().OrderBy(a => a.VoucherHeadId);
                    responseData.Results = Voucherhead;
                    responseData.Status  = "OK";
                }

                else if (reqType == "GetVouchers")
                {
                    var Voucher = (from voc in accountingDbContext.Vouchers
                                   select new
                    {
                        VoucherId = voc.VoucherId,
                        VoucherName = voc.VoucherName,
                        VoucherCode = voc.VoucherCode,
                        IsActive = voc.IsActive,
                        Description = voc.Description,
                        CreatedOn = voc.CreatedOn,
                        CreatedBy = voc.CreatedBy
                    }
                                   ).ToList().OrderBy(a => a.VoucherId);
                    responseData.Results = Voucher;
                    responseData.Status  = "OK";
                }
                else if (reqType == "GetVoucherswithVOCMap")
                {
                    var Voucher = (from vMap in accountingDbContext.VoucherLedgerGroupMaps
                                   join voc in accountingDbContext.Vouchers on vMap.VoucherId equals voc.VoucherId
                                   where vMap.LedgerGroupId == ledgergroupId
                                   group vMap by new { voc.VoucherId, voc.VoucherName, vMap.LedgerGroupId } into p
                                   select new
                    {
                        VoucherId = p.Key.VoucherId,
                        VoucherName = p.Key.VoucherName,
                        LedgerGroupId = p.Key.LedgerGroupId,
                    }
                                   ).ToList();
                    responseData.Results = Voucher;
                    responseData.Status  = "OK";
                }
                else if (reqType == "voucher-ledgerList")
                {
                    //List<LedgerModel> ledgerList = (from ledger in accountingDbContext.Ledgers
                    //                                join ledgerGroup in accountingDbContext.LedgerGroups on ledger.LedgerGroupId equals ledgerGroup.LedgerGroupId
                    //                                join voucherLedgerMap in accountingDbContext.VoucherLedgerGroupMaps on ledgerGroup.LedgerGroupId equals voucherLedgerMap.LedgerGroupId
                    //                                where voucherLedgerMap.VoucherId == voucherId
                    //                                select ledger).ToList();
                    //responseData.Results = ledgerList;
                }

                else if (reqType == "itemList")
                {
                    List <ItemModel> items = (from item in accountingDbContext.Items
                                              select item).ToList();
                    responseData.Results = items;
                }
                else if (reqType == "GetLedgers")
                {
                    var ledgers = (from ledger in accountingDbContext.Ledgers
                                   select new
                    {
                        LedgerId = ledger.LedgerId,
                        LedgerName = ledger.LedgerName,
                        IsActive = ledger.IsActive
                    }).ToList().OrderBy(a => a.LedgerId);
                    responseData.Status  = "OK";
                    responseData.Results = ledgers;
                }
                else if (reqType == "GetLedgerGroups")
                {
                    var LedgerGrouplist = (from ledgrp in accountingDbContext.LedgerGroups
                                           select new
                    {
                        ledgrp.LedgerGroupId,
                        ledgrp.PrimaryGroup,
                        ledgrp.COA,
                        ledgrp.LedgerGroupName,
                        ledgrp.IsActive,
                        ledgrp.Description,
                        ledgrp.Name
                    }
                                           ).ToList();
                    responseData.Results = LedgerGrouplist;
                    responseData.Status  = "OK";
                }
                else if (reqType == "GetItems")
                {
                    var itemsList = (from itm in accountingDbContext.Items
                                     //join ledger in accountingDbContext.Ledgers on itm.LedgerId equals ledger.LedgerId
                                     select new
                    {
                        ItemId = itm.ItemId,
                        ItemName = itm.ItemName,
                        AvailableQuantity = itm.AvailableQuantity,
                        IsActive = itm.IsActive,
                        Description = itm.Description,
                        CreatedBy = itm.CreatedBy,
                        CreatedOn = itm.CreatedOn,
                        //LedgerId = itm.LedgerId,
                        //LedgerName = ledger.LedgerName
                    }).ToList().OrderBy(a => a.ItemName);
                    //// responseData.Status = "OK";
                    responseData.Results = itemsList;
                }
                else if (reqType == "GetLedgerGroupsDetails")
                {
                    var LedgerGrouplist = (from ledgrp in accountingDbContext.LedgerGroups
                                           select new
                    {
                        ledgrp.PrimaryGroup,
                        ledgrp.COA,
                        IsActive = ledgrp.IsActive,
                        Description = ledgrp.Description,
                    }
                                           ).ToList();
                    responseData.Results = LedgerGrouplist;
                    responseData.Status  = "OK";
                }
                else if (reqType == "GetLedgerGrpVoucherByLedgerGrpId")
                {
                    var LedgerGrpVoucherByLedGrpIdList = (from ledMap in accountingDbContext.VoucherLedgerGroupMaps
                                                          join ledGrp in accountingDbContext.LedgerGroups on ledMap.LedgerGroupId equals ledGrp.LedgerGroupId
                                                          join voc in accountingDbContext.Vouchers on ledMap.VoucherId equals voc.VoucherId
                                                          where ledMap.LedgerGroupId == ledgergroupId
                                                          select new
                    {
                        VoucherLedgerGroupMapId = ledMap.VoucherLedgerGroupMapId,
                        LedgerGroupName = ledGrp.LedgerGroupName,
                        LedgerGroupId = ledGrp.LedgerGroupId,
                        VoucherId = voc.VoucherId,
                        VoucherName = voc.VoucherName,
                        IsDebit = ledMap.IsDebit,
                        CreatedOn = ledMap.CreatedOn,
                        CreatedBy = ledMap.CreatedBy,
                        IsActive = ledMap.IsActive
                    }
                                                          ).ToList();
                    responseData.Results = LedgerGrpVoucherByLedGrpIdList;
                    responseData.Status  = "OK";
                }
                else if (reqType == "GetFiscalYearList")
                {
                    var fiscalYearList = (from fsYear in accountingDbContext.FiscalYears
                                          select new
                    {
                        FiscalYearId = fsYear.FiscalYearId,
                        FiscalYearName = fsYear.FiscalYearName,
                        StartDate = fsYear.StartDate,
                        EndDate = fsYear.EndDate,
                        Description = fsYear.Description,
                        IsActive = fsYear.IsActive
                    }).ToList().OrderByDescending(p => p.IsActive);
                    responseData.Status  = "OK";
                    responseData.Results = fiscalYearList;
                }
                else if (reqType == "GetCostCenterItemList")
                {
                    var costCenterList = (from costCenter in accountingDbContext.CostCenterItems
                                          select new
                    {
                        CostCenterItemId = costCenter.CostCenterItemId,
                        CostCenterItemName = costCenter.CostCenterItemName,
                        Description = costCenter.Description,
                        IsActive = costCenter.IsActive
                    }).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = costCenterList;
                }
                else if (reqType == "GetChartofAccount")
                {
                    var chartOfAccountList = (from chartofAcc in accountingDbContext.ChartOfAccounts
                                              select new
                    {
                        ChartOfAccountId = chartofAcc.ChartOfAccountId,
                        ChartOfAccountName = chartofAcc.ChartOfAccountName,
                        Description = chartofAcc.Description,
                        IsActive = chartofAcc.IsActive
                    }).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = chartOfAccountList;
                }
                else if (reqType == "LedgersList")
                {
                    var ledgerList = (from ledGroup in accountingDbContext.LedgerGroups
                                      join led in accountingDbContext.Ledgers
                                      on ledGroup.LedgerGroupId equals led.LedgerGroupId
                                      select new
                    {
                        led.LedgerId,
                        led.LedgerGroupId,
                        ledGroup.PrimaryGroup,
                        ledGroup.COA,
                        ledGroup.LedgerGroupName,
                        led.LedgerName,
                        led.LedgerReferenceId,
                        led.SectionId,
                        led.Description,
                        IsActive = led.IsActive,
                        led.OpeningBalance,
                        led.DrCr,
                        led.CreatedBy,
                        led.CreatedOn,
                        led.Name
                    }).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = ledgerList;
                }
                else if (reqType == "phrm-supplier")
                {
                    var supplier = (from s in accountingDbContext.PHRMSupplier
                                    select new
                    {
                        s.SupplierId,
                        s.SupplierName
                    }).ToList();
                    responseData.Results = supplier;
                    responseData.Status  = "OK";
                }
                responseData.Status = "OK";
            }


            catch (Exception ex)
            {
                string str = ex.InnerException.Message.ToString();
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message;
            }
            return(DanpheJSONConvert.SerializeObject(responseData));
        }
コード例 #10
0
        public string Post()
        {
            //return null;
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            try
            {
                string str     = this.ReadPostData();
                string reqType = this.ReadQueryStringData("reqType");
                //MasterDbContext masterDbContext = new MasterDbContext(connString);

                if (reqType == "set-landing-page")
                {
                    RbacDbContext rbacdbContext = new RbacDbContext(connString);
                    RbacUser      user          = DanpheJSONConvert.DeserializeObject <RbacUser>(str);
                    if (user != null)
                    {
                        var currUser = rbacdbContext.Users.Where(a => a.UserId == user.UserId).Select(a => a).FirstOrDefault();
                        currUser.LandingPageRouteId = user.LandingPageRouteId;
                        rbacdbContext.Users.Attach(currUser);
                        rbacdbContext.Entry(currUser).Property(a => a.LandingPageRouteId).IsModified = true;
                        rbacdbContext.SaveChanges();
                        responseData.Status  = "OK";
                        responseData.Results = currUser.LandingPageRouteId;
                    }
                }
                //    if (reqType != null && reqType == "AddToPreference")
                //    {
                //        string preferenceType = this.ReadQueryStringData("preferenceType");
                //        string preferenceName = null;
                //        string preferenceIdType = null;
                //        if (preferenceType == "lab")
                //        {
                //            preferenceName = "Labtestpreferences";
                //            preferenceIdType = "LabTestId";
                //        }
                //        else if (preferenceType == "imaging")
                //        {
                //            preferenceName = "Imagingpreferences";
                //            preferenceIdType = "ImagingItemId";
                //        }
                //        else if(preferenceType == "medication")
                //        {
                //            preferenceName = "Medicationpreferences";
                //            preferenceIdType = "MedicineId";
                //        }
                //        string clientValue = this.ReadPostData();

                //        RbacUser currentUser = HttpContext.Session.Get<RbacUser>("currentuser");

                //        EmployeePreferences employeePreference = (from pref in masterDbContext.EmployeePreferences
                //                                                  where pref.EmployeeId == currentUser.EmployeeId && pref.PreferenceName == preferenceName
                //                                                  select pref).FirstOrDefault();

                //        if (employeePreference == null)
                //        {
                //            //this is used to convert string into xml
                //            XmlDocument xdoc = JsonConvert.DeserializeXmlNode("{\"Row\":{" + preferenceIdType + ":" + clientValue + "}}", "root");
                //            //this is add new perference
                //            EmployeePreferences employeePref = new EmployeePreferences();

                //            employeePref.PreferenceName = preferenceName;
                //            employeePref.PreferenceValue = xdoc.InnerXml;
                //            employeePref.EmployeeId = currentUser.EmployeeId;
                //            employeePref.CreatedBy = currentUser.EmployeeId; ;
                //            employeePref.CreatedOn = DateTime.Now;
                //            employeePref.IsActive = true;
                //            masterDbContext.EmployeePreferences.Add(employeePref);
                //            masterDbContext.SaveChanges();
                //            responseData.Status = "OK";
                //            responseData.Results = clientValue;
                //        }
                //        else
                //        {

                //            //creating object of XmlDocument
                //            XmlDocument prefXmlDoc = new XmlDocument();
                //            //loading the database PreferenceValue in object of XmlDocument(prefXmlDoc)
                //            prefXmlDoc.LoadXml(employeePreference.PreferenceValue);
                //            //creating xmlElement with tag Row
                //            XmlElement Row = prefXmlDoc.CreateElement("Row");
                //            //creating xmlElement with tag LabTestId/ImagingTypeId
                //            XmlElement typeId = prefXmlDoc.CreateElement(preferenceIdType);
                //            //provididng value to the element of LabTestId/ImagingTypeId
                //            typeId.InnerText = clientValue;
                //            //appending LabTestId/ImagingTypeId element ot Row element as child
                //            Row.AppendChild(typeId);
                //            //Appending the Row elemt to the root element of xml
                //            prefXmlDoc.DocumentElement.AppendChild(Row);
                //            //replacing the old value of employeePreference.PreferenceValue with new one
                //            employeePreference.PreferenceValue = prefXmlDoc.InnerXml;
                //            employeePreference.ModifiedBy = currentUser.EmployeeId;
                //            employeePreference.ModifiedOn = DateTime.Now;


                //            masterDbContext.Entry(employeePreference).State = EntityState.Modified;
                //            masterDbContext.SaveChanges();
                //            responseData.Status = "OK";
                //            responseData.Results = clientValue;
                //        }

                //    }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #11
0
        public string Get(int empId, string reqType)
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            try
            {
                //for employeeprofile, get current employeeinformation, fill the employeeProfileVM object and return to the client.
                if (reqType == "employeeProfile")
                {
                    MasterDbContext masterDbContext = new MasterDbContext(connString);
                    EmployeeModel   currEmp         = (from e in masterDbContext.Employees.Include("Department")
                                                       where e.EmployeeId == empId
                                                       select e).FirstOrDefault();
                    RbacUser currUser = (from u in (new RbacDbContext(connString)).Users
                                         where u.EmployeeId == empId
                                         select u).FirstOrDefault();

                    EmployeeProfileVM empProfile = new EmployeeProfileVM();
                    empProfile.EmployeeId = currEmp.EmployeeId;
                    empProfile.FirstName  = currEmp.FirstName;
                    empProfile.LastName   = currEmp.LastName;
                    empProfile.UserName   = currUser != null ? currUser.UserName : "******";
                    //sometimes department could also be null, so handling such cases accordingly.
                    empProfile.Department    = currEmp.Department != null ? currEmp.Department.DepartmentName : "not assigned";
                    empProfile.DateOfBirth   = currEmp.DateOfBirth;
                    empProfile.DateOfJoining = currEmp.DateOfJoining;
                    empProfile.ImageName     = currEmp.ImageName;
                    empProfile.Email         = currEmp.Email;
                    empProfile.ContactNumber = currEmp.ContactNumber;
                    empProfile.ImageFullPath = string.IsNullOrEmpty(currEmp.ImageName) ? "" : fileUploadLocation + "UserProfile\\" + currEmp.ImageName;

                    responseData.Results = empProfile;
                    responseData.Status  = "OK";
                }


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

                //    RbacDbContext rbacDbContext = new RbacDbContext(connString);
                //    MasterDbContext masterDbContext = new MasterDbContext(connString);

                //    RbacUser currUser = rbacDbContext.Users.Where(u => u.UserId == empId).FirstOrDefault();
                //    var UserProfileInfo = (from x in masterDbContext.Employee
                //                           where x.EmployeeId == currUser.EmployeeId
                //                           select new
                //                           {
                //                               UserName = currUser.UserName,
                //                               FirstName = x.FirstName,
                //                               LastName = x.LastName,
                //                               Email = x.Email,
                //                               Department = x.EmployeeDepartment,
                //                               EmployeeId = x.EmployeeId,
                //                               ImageName = x.ImageName
                //                           }).ToList();

                //    responseData.Results = UserProfileInfo;
                //    responseData.Status = "OK";
                //}
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #12
0
        public string Post()
        {
            WardSupplyDbContext         wardSupplyDbContext = new WardSupplyDbContext(connString);
            DanpheHTTPResponse <object> responseData        = new DanpheHTTPResponse <object>();
            RbacUser          currentUser   = HttpContext.Session.Get <RbacUser>("currentuser");
            PharmacyDbContext phrmdbcontext = new PharmacyDbContext(connString);
            string            reqType       = this.ReadQueryStringData("reqType");
            string            str           = this.ReadPostData();

            try
            {
                if (!String.IsNullOrEmpty(str))
                {
                    #region Post:Ward Request
                    if (reqType == "ward-requistion")
                    {
                        WARDRequisitionModel WardReq = DanpheJSONConvert.DeserializeObject <WARDRequisitionModel>(str);
                        WardReq.CreatedOn = DateTime.Now.Date;
                        WardReq.CreatedBy = currentUser.EmployeeId;
                        WardReq.Status    = "pending";
                        wardSupplyDbContext.WARDRequisitionModel.Add(WardReq);
                        wardSupplyDbContext.SaveChanges();
                        responseData.Results = WardReq;
                        responseData.Status  = "OK";
                    }
                    #endregion
                    #region POST: Consumption
                    else if (reqType == "post-consumption")
                    {
                        PHRMInvoiceTransactionItemsModel invoice       = new PHRMInvoiceTransactionItemsModel();
                        List <WARDStockModel>            wardStockList = new List <WARDStockModel>();
                        WARDStockModel wardStock = new WARDStockModel();
                        List <WARDConsumptionModel>    consumptionList   = JsonConvert.DeserializeObject <List <WARDConsumptionModel> >(str);
                        PHRMStockTransactionItemsModel phrmStockTxnItems = new PHRMStockTransactionItemsModel();
                        foreach (var consmption in consumptionList)
                        {
                            //adding invoice in PHRM_TXN_Invoice
                            invoice.ItemId             = consmption.ItemId;
                            invoice.ItemName           = consmption.ItemName;
                            invoice.BatchNo            = consmption.BatchNo;
                            invoice.Quantity           = consmption.Quantity;
                            invoice.Price              = consmption.MRP;
                            invoice.MRP                = consmption.MRP;
                            invoice.SubTotal           = consmption.SubTotal;
                            invoice.TotalAmount        = consmption.SubTotal;
                            invoice.CreatedBy          = consmption.CreatedBy;
                            invoice.CreatedOn          = System.DateTime.Now;
                            invoice.CounterId          = consmption.CounterId;
                            invoice.BilItemStatus      = "wardconsumption";
                            invoice.ExpiryDate         = consmption.ExpiryDate;
                            invoice.PatientId          = consmption.PatientId;
                            invoice.VATPercentage      = 0;
                            invoice.DiscountPercentage = 0;
                            invoice.FreeQuantity       = 0;
                            phrmdbcontext.PHRMInvoiceTransactionItems.Add(invoice);
                            phrmdbcontext.SaveChanges();

                            //adding consumption in WARD_Consumption
                            consmption.InvoiceItemId = invoice.InvoiceItemId;
                            consmption.CreatedOn     = System.DateTime.Now;
                            wardSupplyDbContext.WARDConsumptionModel.Add(consmption);
                            wardSupplyDbContext.SaveChanges();

                            //adding record in list for updating stock available quantity
                            wardStock                   = new WARDStockModel();
                            wardStock.ItemId            = consmption.ItemId;
                            wardStock.MRP               = (float)consmption.MRP;
                            wardStock.ExpiryDate        = consmption.ExpiryDate;
                            wardStock.BatchNo           = consmption.BatchNo;
                            wardStock.WardId            = consmption.WardId;
                            wardStock.DispachedQuantity = consmption.Quantity;
                            wardStockList.Add(wardStock);

                            //adding record in the PHRM_StockTxnItems
                            phrmStockTxnItems.CreatedBy = currentUser.EmployeeId;
                            phrmStockTxnItems.CreatedOn = DateTime.Now;
                            phrmStockTxnItems.BatchNo   = consmption.BatchNo;
                            phrmStockTxnItems.ItemId    = consmption.ItemId;
                            phrmStockTxnItems.Price     = consmption.MRP;
                            phrmStockTxnItems.MRP       = consmption.MRP;
                            phrmStockTxnItems.ReferenceItemCreatedOn = DateTime.Now;
                            phrmStockTxnItems.ReferenceNo            = consmption.InvoiceItemId;
                            phrmStockTxnItems.GoodsReceiptItemId     = null;
                            phrmStockTxnItems.CCCharge           = null;
                            phrmStockTxnItems.Quantity           = consmption.Quantity;
                            phrmStockTxnItems.ExpiryDate         = consmption.ExpiryDate;
                            phrmStockTxnItems.FreeQuantity       = 0;
                            phrmStockTxnItems.DiscountPercentage = 0;
                            phrmStockTxnItems.VATPercentage      = 0;
                            phrmStockTxnItems.InOut           = "out";
                            phrmStockTxnItems.TransactionType = "wardsupply";
                            phrmStockTxnItems.SubTotal        = consmption.SubTotal;
                            phrmStockTxnItems.TotalAmount     = consmption.SubTotal;
                            phrmdbcontext.PHRMStockTransactionModel.Add(phrmStockTxnItems);
                            phrmdbcontext.SaveChanges();
                        }

                        if (WardSupplyBL.UpdateWardSockQuantity(wardStockList, wardSupplyDbContext))
                        {
                            responseData.Status  = "OK";
                            responseData.Results = consumptionList;
                        }
                        else
                        {
                            responseData.Status       = "Failed";
                            responseData.ErrorMessage = "Falied to update stock details.";
                        }
                    }
                    #endregion
                    #region POST: Inventory Consumption
                    else if (reqType == "post-inventory-consumption")
                    {
                        PHRMInvoiceTransactionItemsModel invoice       = new PHRMInvoiceTransactionItemsModel();
                        List <WARDStockModel>            wardStockList = new List <WARDStockModel>();
                        WARDStockModel wardStock = new WARDStockModel();
                        List <WARDInventoryConsumptionModel> consumptionList   = JsonConvert.DeserializeObject <List <WARDInventoryConsumptionModel> >(str);
                        PHRMStockTransactionItemsModel       phrmStockTxnItems = new PHRMStockTransactionItemsModel();
                        foreach (var consmption in consumptionList)
                        {
                            //adding record in list for updating stock available quantity
                            var            AvailableQuantity = consmption.Quantity - consmption.ConsumeQuantity;
                            WARDStockModel stockDetail       = (from stock in wardSupplyDbContext.WARDStockModel
                                                                where stock.ItemId == consmption.ItemId & stock.StockType == "inventory" && stock.DepartmentId == consmption.DepartmentId
                                                                select stock
                                                                ).FirstOrDefault();
                            stockDetail.AvailableQuantity = AvailableQuantity;
                            wardSupplyDbContext.Entry(stockDetail).Property(a => a.AvailableQuantity).IsModified = true;

                            //adding consumption in [WARD_INV_Consumption]
                            AvailableQuantity    = consmption.ConsumeQuantity;
                            consmption.Quantity  = AvailableQuantity;
                            consmption.CreatedOn = System.DateTime.Now;
                            wardSupplyDbContext.WARDInventoryConsumptionModel.Add(consmption);
                            wardSupplyDbContext.SaveChanges();
                        }
                        responseData.Status  = "OK";
                        responseData.Results = consumptionList;
                    }
                    #endregion
                    #region POST : update stock transaction, Post to Stock table and post to Transaction table
                    else if (reqType == "transfer-stock")
                    {
                        WARDStockModel stockManageData = DanpheJSONConvert.DeserializeObject <WARDStockModel>(str);
                        if (stockManageData != null)
                        {
                            Boolean flag = false;


                            flag = WardSupplyBL.StockTransfer(stockManageData, wardSupplyDbContext, currentUser);
                            if (flag)
                            {
                                responseData.Status  = "OK";
                                responseData.Results = 1;
                            }
                            else
                            {
                                responseData.ErrorMessage = "Transfer Item is null or failed to Save";
                                responseData.Status       = "Failed";
                            }
                        }
                    }
                    #endregion
                    #region POST : update stock transaction, Post to Stock table and post to Transaction table
                    else if (reqType == "transfer-inventory-stock")
                    {
                        WARDStockModel stockManageData = DanpheJSONConvert.DeserializeObject <WARDStockModel>(str);
                        if (stockManageData != null)
                        {
                            Boolean flag = false;


                            flag = WardSupplyBL.StockInventoryTransfer(stockManageData, wardSupplyDbContext, currentUser);
                            if (flag)
                            {
                                responseData.Status  = "OK";
                                responseData.Results = 1;
                            }
                            else
                            {
                                responseData.ErrorMessage = "Transfer Item is null or failed to Save";
                                responseData.Status       = "Failed";
                            }
                        }
                    }
                    #endregion
                    #region POST : delete from stock table in wardsupply. add stock in inventory and update in stock transaction
                    else if (reqType == "transfer-back-to-inventory")
                    {
                        WARDStockModel stockManageData = DanpheJSONConvert.DeserializeObject <WARDStockModel>(str);
                        if (stockManageData != null)
                        {
                            Boolean flag = false;


                            flag = WardSupplyBL.BackToInventoryTransfer(stockManageData, wardSupplyDbContext, currentUser);
                            if (flag)
                            {
                                responseData.Status  = "OK";
                                responseData.Results = 1;
                            }
                            else
                            {
                                responseData.ErrorMessage = "Transfer Item is null or failed to Save";
                                responseData.Status       = "Failed";
                            }
                        }
                    }
                    #endregion
                    #region POST : update stock tranaction, Post to Stock table and Transaction Table
                    else if (reqType == "breakage-stock")
                    {
                        WARDStockModel stockManageData = DanpheJSONConvert.DeserializeObject <WARDStockModel>(str);
                        if (stockManageData != null)
                        {
                            Boolean flag = false;

                            flag = WardSupplyBL.StockBreakage(stockManageData, wardSupplyDbContext, currentUser);
                            if (flag)
                            {
                                responseData.Status  = "OK";
                                responseData.Results = 1;
                            }
                            else
                            {
                                responseData.ErrorMessage = "Breakage item is null or failed to save";
                                responseData.Status       = "Failed";
                            }
                        }
                    }
                    #endregion
                    #region POST : Ward To Pharmacy Tranfer of Stock
                    else if (reqType == "returnStockToPharmacy")
                    {
                        List <WARDStockModel> stockManageData = DanpheJSONConvert.DeserializeObject <List <WARDStockModel> >(str);
                        if (stockManageData != null)
                        {
                            Boolean flag = false;

                            flag = WardSupplyBL.StockTransferToPharmacy(stockManageData, wardSupplyDbContext, phrmdbcontext, currentUser);
                            if (flag)
                            {
                                responseData.Status  = "OK";
                                responseData.Results = 1;
                            }
                            else
                            {
                                responseData.ErrorMessage = "Failed to save. Check the items.";
                                responseData.Status       = "Failed";
                            }
                        }
                    }
                    #endregion
                }
                else
                {
                    responseData.Status       = "Failed";
                    responseData.ErrorMessage = "Client Object is empty";
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }

            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #13
0
        public string Get(string reqType, string status, int requisitionId, int wardId, int consumptionId, int patientId, int departmentId, string userName)
        {
            DanpheHTTPResponse <object> responseData        = new DanpheHTTPResponse <object>();
            WardSupplyDbContext         wardSupplyDbContext = new WardSupplyDbContext(connString);
            PharmacyDbContext           phrmdbcontext       = new PharmacyDbContext(connString);

            try
            {
                #region Get Departments
                if (reqType == "get-departments")
                {
                    var departmentlist = wardSupplyDbContext.Departments.ToList();
                    responseData.Status  = "OK";
                    responseData.Results = departmentlist;
                }
                #endregion
                #region GET: get ward list.
                if (reqType == "ward-list")
                {
                    var wardList = wardSupplyDbContext.WardModel.ToList();
                    responseData.Status  = "OK";
                    responseData.Results = wardList;
                }
                #endregion
                #region GET: get ward requisition list.
                else if (reqType == "get-all-ward-requisition-list")
                {
                    string[] poSelectedStatus = status.Split(',');
                    var      wardReqList      = (from wardReq in wardSupplyDbContext.WARDRequisitionModel
                                                 join ward in wardSupplyDbContext.WardModel on wardReq.WardId equals ward.WardId
                                                 join emp in wardSupplyDbContext.Employees on wardReq.CreatedBy equals emp.EmployeeId
                                                 join stats in poSelectedStatus on wardReq.Status equals stats
                                                 where wardReq.WardId == wardId
                                                 orderby wardReq.RequisitionId descending
                                                 select new
                    {
                        WardName = ward.WardName,
                        CreatedBy = emp.FirstName + " " + (string.IsNullOrEmpty(emp.MiddleName) ? "" : emp.MiddleName + " ") + emp.LastName,
                        Date = wardReq.CreatedOn,
                        Status = wardReq.Status,
                        RequisitionId = wardReq.RequisitionId
                    }).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = wardReqList;
                }
                #endregion
                #region GET: get Consumption list.
                else if (reqType == "get-All-Comsumption-List-Details")
                {
                    var consumpList = (from consump in wardSupplyDbContext.WARDConsumptionModel
                                       join pat in wardSupplyDbContext.Patients on consump.PatientId equals pat.PatientId
                                       join ward in wardSupplyDbContext.WardModel on consump.WardId equals ward.WardId
                                       where consump.WardId == wardId
                                       group new { consump, pat } by new
                    {
                        consump.PatientId,
                        pat.FirstName,
                        pat.MiddleName,
                        pat.LastName,
                        pat.Address,
                        pat.PhoneNumber,
                        pat.Gender,
                        ward.WardName,
                        consump.WardId,
                        pat.Age
                    } into t
                                       select new
                    {
                        WardId = t.Key.WardId,
                        WardName = t.Key.WardName,
                        Name = t.Key.FirstName + " " + (string.IsNullOrEmpty(t.Key.MiddleName) ? "" : t.Key.MiddleName + " ") + t.Key.LastName,
                        Address = t.Key.Address,
                        Gender = t.Key.Gender,
                        PhoneNumber = t.Key.PhoneNumber,
                        PatientId = t.Key.PatientId,
                        Quantity = t.Sum(a => a.consump.Quantity),
                        Age = t.Key.Age
                    }).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = consumpList;
                }
                #endregion
                #region GET: get Inventory Consumption list.
                else if (reqType == "get-inventory-conumption-list")
                {
                    var consumpList = (from consump in wardSupplyDbContext.WARDInventoryConsumptionModel
                                       where consump.DepartmentId == departmentId
                                       group consump by consump.UsedBy into t
                                       select new
                    {
                        DepartmentName = t.Select(a => a.DepartmentName).FirstOrDefault(),
                        UsedBy = t.Select(a => a.UsedBy).FirstOrDefault()
                    }).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = consumpList;
                }
                #endregion
                #region ward request items by selected ward.
                else if (reqType == "get-ward-request-items")
                {
                    var warReqItems = (from itm in wardSupplyDbContext.WARDRequisitionItemsModel
                                       join itmReq in wardSupplyDbContext.WARDRequisitionModel on itm.RequisitionId equals itmReq.RequisitionId
                                       join itmName in wardSupplyDbContext.PHRMItemMaster on itm.ItemId equals itmName.ItemId
                                       where itm.RequisitionId == requisitionId
                                       select new
                    {
                        RequisitionItemId = itm.RequisitionItemId,
                        RequisitionId = itm.RequisitionId,
                        ItemId = itm.ItemId,
                        Quantity = itm.Quantity,
                        ItemName = itmName.ItemName,
                    }).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = warReqItems;
                }
                #endregion

                #region consumption items by selected ward.
                else if (reqType == "get-consumption-items-list")
                {
                    var consumpList = (from consump in wardSupplyDbContext.WARDConsumptionModel
                                       where consump.PatientId == patientId && consump.WardId == wardId
                                       select new
                    {
                        ItemName = consump.ItemName,
                        Quantity = consump.Quantity
                    }).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = consumpList;
                }
                #endregion
                #region inventory consumption items by selected department and user.
                else if (reqType == "get-inventory-consumption-itemlist")
                {
                    var consumpList = (from consump in wardSupplyDbContext.WARDInventoryConsumptionModel
                                       where consump.UsedBy == userName && consump.DepartmentId == departmentId
                                       select new
                    {
                        ItemName = consump.ItemName,
                        Quantity = consump.Quantity,
                        UsedBy = consump.UsedBy
                    }).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = consumpList;
                }
                #endregion

                #region GET: Stock Details
                else if (reqType == "get-all-Ward-Items-StockDetails")
                {
                    var totalStock = (from wardstock in wardSupplyDbContext.WARDStockModel
                                      join ward in wardSupplyDbContext.WardModel on wardstock.WardId equals ward.WardId
                                      join item in wardSupplyDbContext.PHRMItemMaster on wardstock.ItemId equals item.ItemId
                                      where wardstock.StockType == "pharmacy"
                                      group wardstock by new { wardstock.ItemId, wardstock.StockId, wardstock.BatchNo, wardstock.MRP, wardstock.ExpiryDate } into x
                                      select new
                    {
                        WardId = x.Select(a => a.WardId).FirstOrDefault(),
                        WardName = wardSupplyDbContext.WardModel.Where(a => a.WardId == x.Select(b => b.WardId).FirstOrDefault()).Select(b => b.WardName).FirstOrDefault(),
                        ItemId = x.Key.ItemId,
                        StockId = x.Key.StockId,
                        ItemName = wardSupplyDbContext.PHRMItemMaster.Where(a => a.ItemId == x.Key.ItemId).Select(a => a.ItemName).FirstOrDefault(),
                        BatchNo = x.Key.BatchNo,
                        AvailableQuantity = x.Sum(a => a.AvailableQuantity),
                        ExpiryDate = x.Key.ExpiryDate,
                        MRP = Math.Round(x.Key.MRP, 2)
                    })
                                     .Where(a => a.ExpiryDate >= DateTime.Now).ToList();

                    responseData.Status  = (totalStock == null) ? "Failed" : "OK";
                    responseData.Results = totalStock;
                }
                #endregion
                else if (reqType == "get-all-inventory-Items-StockDetails")
                {
                    var totalStock = (from wardstock in wardSupplyDbContext.WARDStockModel
                                      join department in wardSupplyDbContext.Departments on wardstock.DepartmentId equals department.DepartmentId
                                      join item in wardSupplyDbContext.INVItemMaster on wardstock.ItemId equals item.ItemId
                                      where wardstock.StockType == "inventory"
                                      group wardstock by new { wardstock.ItemId, item.ItemName, wardstock.DepartmentId, department.DepartmentName, item.ItemType } into t
                                      select new
                    {
                        DepartmentId = t.Key.DepartmentId,
                        DepartmentName = t.Key.DepartmentName,
                        ItemId = t.Key.ItemId,
                        StockId = t.Select(a => a.StockId).FirstOrDefault(),
                        ItemName = t.Key.ItemName,
                        Quantity = t.Sum(a => a.AvailableQuantity),
                        ExpiryDate = t.Select(a => a.ExpiryDate).FirstOrDefault(),
                        MRP = t.Select(a => a.MRP).FirstOrDefault(),
                        BatchNo = t.Select(a => a.BatchNo).FirstOrDefault(),
                        ItemType = t.Key.ItemType
                    }).ToList();

                    responseData.Status  = (totalStock == null) ? "Failed" : "OK";
                    responseData.Results = totalStock;
                }

                #region GET Pharmacy Stock List
                else if (reqType == "phrm-stock")
                {
                    var testdate = DateTime.Now.AddMonths(1);
                    //To calculate stock and add batch and items
                    var totalStock = phrmdbcontext.PHRMStockTransactionModel
                                     .Select(n => new { n.ItemId, MRP = (Math.Round((double)n.MRP, 2)), n.Quantity, n.Price, n.BatchNo, n.ExpiryDate, n.InOut, n.FreeQuantity })
                                     .Where(a => a.ExpiryDate >= testdate).ToList().GroupBy(a => new { a.ItemId, a.BatchNo, a.MRP, a.ExpiryDate }).Select(g =>
                                                                                                                                                          new PHRMStockTransactionItemsModel
                    {
                        ItemId  = g.Key.ItemId,
                        BatchNo = g.Key.BatchNo,
                        //InOut = g.Key.InOut,
                        Quantity = g.Where(w => w.InOut == "in").Sum(q => q.Quantity) + g.Where(w => w.InOut == "in").Sum(f => f.FreeQuantity).Value - g.Where(w => w.InOut == "out")
                                   .Sum(o => o.Quantity) - g.Where(w => w.InOut == "out").Sum(f => f.FreeQuantity).Value,
                        FreeQuantity = g.Where(w => w.InOut == "in").Sum(q => q.Quantity),
                        ExpiryDate   = g.Key.ExpiryDate,
                        MRP          = Convert.ToDecimal(g.Key.MRP),
                        Price        = g.FirstOrDefault().Price,
                    }
                                                                                                                                                          ).Where(a => a.Quantity > 0).GroupJoin(phrmdbcontext.PHRMItemMaster.Where(a => a.IsActive == true).ToList(), a => a.ItemId, b => b.ItemId, (a, b) => new GoodReceiptItemsViewModel
                    {
                        ItemId            = a.ItemId.Value,
                        BatchNo           = a.BatchNo,
                        ExpiryDate        = a.ExpiryDate.Value.Date,
                        ItemName          = b.Select(s => s.ItemName).FirstOrDefault(),
                        AvailableQuantity = a.Quantity,
                        MRP         = a.MRP.Value,
                        GRItemPrice = a.Price.Value,
                        GenericId   = b.Select(s => s.GenericId.Value).FirstOrDefault(),
                        IsActive    = true
                    }
                                                                                                                                                                                                 ).OrderBy(expDate => expDate.ExpiryDate).ToList().Join(phrmdbcontext.PHRMGenericModel.ToList(), a => a.GenericId, b => b.GenericId, (a, b) => new
                                                                                                                                                                                                                                                        { GoodReceiptItemsViewModel = a, PHRMGenericModel = b }).Join(phrmdbcontext.PHRMCategory.ToList(), a => a.PHRMGenericModel.CategoryId, b => b.CategoryId, (a, b) => new { a.GoodReceiptItemsViewModel, a.PHRMGenericModel, PHRMCategory = b })
                                     .Select(s => new GoodReceiptItemsViewModel
                    {
                        ItemId            = s.GoodReceiptItemsViewModel.ItemId,
                        BatchNo           = s.GoodReceiptItemsViewModel.BatchNo,
                        ExpiryDate        = s.GoodReceiptItemsViewModel.ExpiryDate.Date,
                        ItemName          = s.GoodReceiptItemsViewModel.ItemName,
                        AvailableQuantity = s.GoodReceiptItemsViewModel.AvailableQuantity,
                        MRP         = s.GoodReceiptItemsViewModel.MRP,
                        GRItemPrice = s.GoodReceiptItemsViewModel.GRItemPrice,
                        GenericId   = s.GoodReceiptItemsViewModel.GenericId,
                        GenericName = s.PHRMGenericModel.GenericName,
                        //CategoryName = s.PHRMCategory.CategoryName,
                        IsActive = true
                    });

                    responseData.Status  = "OK";
                    responseData.Results = totalStock;
                }
                #endregion

                #region GET Ward Stock List
                else if (reqType == "ward-stock")
                {
                    var wardStock = wardSupplyDbContext.WARDStockModel
                                    .Select(n => new
                    {
                        n.StockId,
                        n.WardId,
                        n.DepartmentId,
                        n.ItemId,
                        n.AvailableQuantity,
                        MRP = (Math.Round(n.MRP, 2)),
                        n.BatchNo,
                        n.ExpiryDate
                    }).ToList();
                    responseData.Status  = "OK";
                    responseData.Results = wardStock;
                }
                #endregion

                #region GET InPatient List
                else if (reqType == "inpatient-list")
                {
                    var InPatients = (from pat in wardSupplyDbContext.Patients
                                      join vst in wardSupplyDbContext.Visits on pat.PatientId equals vst.PatientId
                                      join adm in wardSupplyDbContext.Admissions on vst.PatientVisitId equals adm.PatientVisitId
                                      join pbi in wardSupplyDbContext.PatientBedInfos on pat.PatientId equals pbi.PatientId
                                      where adm.AdmissionStatus == "admitted"
                                      select new
                    {
                        pat.PatientId,
                        pat.PatientCode,
                        pat.FirstName,
                        pat.MiddleName,
                        pat.LastName,
                        pat.Gender,
                        pat.DateOfBirth,
                        pat.Age,
                        pat.Address,
                        pat.PhoneNumber,
                        vst.VisitCode,
                        vst.PatientVisitId,
                        pbi.WardId,
                        ShortName = pat.FirstName + " " + (string.IsNullOrEmpty(pat.MiddleName) ? "" : pat.MiddleName + " ") + pat.LastName,
                    }).OrderByDescending(patient => patient.PatientId).ToList();
                    responseData.Results = InPatients;
                    responseData.Status  = "OK";
                }
                #endregion
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }

            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #14
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));
        }
コード例 #15
0
        public string Post()
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();
            string   reqType     = this.ReadQueryStringData("reqType");
            string   ipStr       = this.ReadPostData();
            RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser");

            try
            {
                LabDbContext     labDbContext  = new LabDbContext(connString);
                BillingDbContext billDbContext = new BillingDbContext(connString);

                if (reqType != null && reqType == "postLabReport")
                {
                    LabReportTemplateModel labReportTemplate = DanpheJSONConvert.DeserializeObject <LabReportTemplateModel>(ipStr);
                    labReportTemplate.CreatedOn = System.DateTime.Now;
                    labReportTemplate.CreatedBy = currentUser.EmployeeId;

                    //Remove Previous Default Template Set and make the current one default by Assigning IsDefault of previous to False and Current to True
                    if (labReportTemplate.IsDefault == true)
                    {
                        LabReportTemplateModel rowToUpdate = (from rep in labDbContext.LabReportTemplates
                                                              where rep.IsDefault == true
                                                              select rep
                                                              ).FirstOrDefault();


                        labDbContext.LabReportTemplates.Attach(rowToUpdate);
                        rowToUpdate.IsDefault = false;
                        labDbContext.SaveChanges();
                    }


                    labDbContext.LabReportTemplates.Add(labReportTemplate);
                    labDbContext.SaveChanges();
                    responseData.Results = labReportTemplate;
                }
                else if (reqType == "postLabTest")
                {
                    using (var dbContextTransaction = labDbContext.Database.BeginTransaction())
                    {
                        try
                        {
                            LabTestModel  labTest       = DanpheJSONConvert.DeserializeObject <LabTestModel>(ipStr);
                            BillItemPrice billItemPrice = new BillItemPrice();
                            labTest.CreatedBy = currentUser.EmployeeId;
                            labTest.CreatedOn = System.DateTime.Now;
                            labDbContext.LabTests.Add(labTest);
                            labDbContext.SaveChanges();

                            var labComponentMapList = labTest.LabTestComponentMap;

                            if (labTest.TemplateType.ToLower() == "html")
                            {
                                var htmlComp = labTest.LabTestComponentsJSON[0];
                                labDbContext.LabTestComponents.Add(htmlComp);
                                labDbContext.SaveChanges();
                                LabTestComponentMapModel htmlCompToMap = new LabTestComponentMapModel();
                                htmlCompToMap.ComponentId = htmlComp.ComponentId;
                                htmlCompToMap.LabTestId   = labTest.LabTestId;
                                htmlCompToMap.CreatedBy   = currentUser.EmployeeId;
                                htmlCompToMap.CreatedOn   = System.DateTime.Now;
                                htmlCompToMap.IsActive    = true;
                                labDbContext.LabTestComponentMap.Add(htmlCompToMap);
                                labDbContext.SaveChanges();
                            }
                            else
                            {
                                foreach (var component in labComponentMapList)
                                {
                                    component.CreatedBy = currentUser.EmployeeId;
                                    component.CreatedOn = System.DateTime.Now;
                                    component.LabTestId = labTest.LabTestId;

                                    labDbContext.LabTestComponentMap.Add(component);
                                    labDbContext.SaveChanges();
                                }
                            }



                            labDbContext.LabTests.Attach(labTest);

                            billItemPrice.ItemName = labTest.LabTestName;
                            //Will Update this hardcode Later
                            billItemPrice.ServiceDepartmentId = labTest.ServiceDepartmentId ?? default(int); //typecase for default int
                            billItemPrice.Price                   = 0;
                            billItemPrice.ItemId                  = Convert.ToInt32(labTest.LabTestId);
                            billItemPrice.TaxApplicable           = labTest.IsTaxApplicable;
                            billItemPrice.DiscountApplicable      = true;
                            billItemPrice.CreatedBy               = currentUser.EmployeeId;
                            billItemPrice.CreatedOn               = System.DateTime.Now;
                            billItemPrice.IsActive                = true;
                            billItemPrice.IsFractionApplicable    = false;
                            billItemPrice.EHSPrice                = 0;
                            billItemPrice.IsNormalPriceApplicable = true;

                            Int64 labTestId = labTest.LabTestId;//LabtestId comes only after this model is saved to database
                            if (string.IsNullOrEmpty(labTest.LabTestCode))
                            {
                                labTest.LabTestCode = "L-" + labTest.LabTestId.ToString("D6");
                            }

                            labTest.ProcedureCode = "LAB-" + labTest.LabTestId.ToString("D6");

                            labDbContext.Entry(labTest).Property(t => t.LabTestCode).IsModified   = true;
                            labDbContext.Entry(labTest).Property(t => t.ProcedureCode).IsModified = true;

                            billItemPrice.ProcedureCode = labTest.ProcedureCode;

                            labDbContext.BillItemPrice.Add(billItemPrice);

                            labDbContext.SaveChanges();
                            dbContextTransaction.Commit();
                            responseData.Results = labTest;
                        }
                        catch (Exception ex)
                        {
                            dbContextTransaction.Rollback();
                            throw (ex);
                        }
                    }
                }
                else if (reqType == "postLabComponents")
                {
                    List <LabTestJSONComponentModel> componentList = DanpheJSONConvert.DeserializeObject <List <LabTestJSONComponentModel> >(ipStr);
                    using (var dbContextTransaction = labDbContext.Database.BeginTransaction())
                    {
                        try
                        {
                            var allLabComponents = labDbContext.LabTestComponents.ToList();

                            foreach (var comp in componentList)
                            {
                                var duplicateComponent = allLabComponents.FirstOrDefault(x => x.ComponentName == comp.ComponentName && x.DisplayName == comp.DisplayName);
                                if (duplicateComponent == null)
                                {
                                    labDbContext.LabTestComponents.Add(comp);
                                    labDbContext.SaveChanges();
                                }
                            }
                            dbContextTransaction.Commit();

                            responseData.Results = componentList;
                            responseData.Status  = "OK";
                        }
                        catch (Exception ex)
                        {
                            dbContextTransaction.Rollback();
                            throw (ex);
                        }
                    }
                }
                else if (reqType == "postLabLookUp")
                {
                    CoreCFGLookupModel Lookup = DanpheJSONConvert.DeserializeObject <CoreCFGLookupModel>(ipStr);
                    using (var dbContextTransaction = labDbContext.Database.BeginTransaction())
                    {
                        try
                        {
                            var allLookUps = labDbContext.LabLookUps.ToList();

                            var duplicateComponent = allLookUps.FirstOrDefault(x => x.ModuleName == Lookup.ModuleName && x.LookUpName == Lookup.LookUpName && x.LookupDataJson == Lookup.LookupDataJson);
                            if (duplicateComponent == null)
                            {
                                labDbContext.LabLookUps.Add(Lookup);
                                labDbContext.SaveChanges();
                            }
                            dbContextTransaction.Commit();

                            responseData.Results = Lookup;
                            responseData.Status  = "OK";
                        }
                        catch (Exception ex)
                        {
                            dbContextTransaction.Rollback();
                            throw (ex);
                        }
                    }
                }

                else if (reqType == "add-vendor")
                {
                    LabVendorsModel vendorFromClient = DanpheJSONConvert.DeserializeObject <LabVendorsModel>(ipStr);

                    LabVendorsModel defaultVendor = labDbContext.LabVendors.Where(val => val.IsDefault == true).FirstOrDefault();

                    if (vendorFromClient.IsDefault)
                    {
                        if (defaultVendor != null && defaultVendor.IsDefault)
                        {
                            defaultVendor.IsDefault = false;
                            labDbContext.Entry(defaultVendor).State = EntityState.Modified;
                            labDbContext.Entry(defaultVendor).Property(x => x.IsDefault).IsModified = true;
                        }
                    }

                    labDbContext.LabVendors.Add(vendorFromClient);

                    labDbContext.SaveChanges();


                    responseData.Results = vendorFromClient;//return same data to client.
                    labDbContext.SaveChanges();
                }

                responseData.Status = "OK";
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }

            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #16
0
        public string Update(/*string reqType*/)
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            AccountingDbContext accountingDBContext = new AccountingDbContext(connString);


            try
            {
                //string str = Request.Form.Keys.First<string>();
                string   str         = this.ReadPostData();
                string   reqType     = this.ReadQueryStringData("reqType");
                RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser");
                if (!String.IsNullOrEmpty(str))
                {
                    if (reqType == "itemISActive")
                    {
                        ItemModel item = DanpheJSONConvert.DeserializeObject <ItemModel>(str);
                        accountingDBContext.Items.Attach(item);
                        accountingDBContext.Entry(item).Property(x => x.IsActive).IsModified = true;
                        accountingDBContext.SaveChanges();
                        responseData.Results = item;
                        responseData.Status  = "OK";
                    }
                    else if (reqType == "ledgerISActive")
                    {
                        LedgerModel ledger = DanpheJSONConvert.DeserializeObject <LedgerModel>(str);
                        accountingDBContext.Ledgers.Attach(ledger);
                        accountingDBContext.Entry(ledger).Property(x => x.IsActive).IsModified = true;
                        accountingDBContext.SaveChanges();
                        responseData.Results = ledger;
                        responseData.Status  = "OK";
                    }
                    else if (reqType == "updateLedgerGrpIsActive")
                    {
                        LedgerGroupModel ledgerGrp = DanpheJSONConvert.DeserializeObject <LedgerGroupModel>(str);
                        accountingDBContext.LedgerGroups.Attach(ledgerGrp);
                        accountingDBContext.Entry(ledgerGrp).Property(x => x.IsActive).IsModified = true;
                        accountingDBContext.SaveChanges();
                        responseData.Status  = "OK";
                        responseData.Results = ledgerGrp;
                    }
                    else if (reqType == "updateLedgerGroup")
                    {
                        LedgerGroupModel ledgerGroup = DanpheJSONConvert.DeserializeObject <LedgerGroupModel>(str);
                        var ledgerGrp = accountingDBContext.LedgerGroups.Where(x => x.LedgerGroupId == ledgerGroup.LedgerGroupId).FirstOrDefault();
                        if (ledgerGrp != null)
                        {
                            ledgerGrp.COA             = ledgerGroup.COA;
                            ledgerGrp.Description     = ledgerGroup.Description;
                            ledgerGrp.IsActive        = ledgerGroup.IsActive;
                            ledgerGrp.LedgerGroupName = ledgerGroup.LedgerGroupName;
                            ledgerGrp.ModifiedBy      = ledgerGroup.ModifiedBy;
                            ledgerGrp.ModifiedOn      = System.DateTime.Now;
                            ledgerGrp.PrimaryGroup    = ledgerGroup.PrimaryGroup;

                            accountingDBContext.LedgerGroups.Attach(ledgerGrp);
                            accountingDBContext.Entry(ledgerGrp).Property(x => x.COA).IsModified             = true;
                            accountingDBContext.Entry(ledgerGrp).Property(x => x.Description).IsModified     = true;
                            accountingDBContext.Entry(ledgerGrp).Property(x => x.IsActive).IsModified        = true;
                            accountingDBContext.Entry(ledgerGrp).Property(x => x.LedgerGroupName).IsModified = true;
                            accountingDBContext.Entry(ledgerGrp).Property(x => x.ModifiedBy).IsModified      = true;
                            accountingDBContext.Entry(ledgerGrp).Property(x => x.ModifiedOn).IsModified      = true;
                            accountingDBContext.Entry(ledgerGrp).Property(x => x.PrimaryGroup).IsModified    = true;
                            accountingDBContext.SaveChanges();
                            responseData.Results = ledgerGrp;
                            responseData.Status  = "OK";
                        }
                        else
                        {
                            responseData.Status = "Failed";
                        }
                    }
                    else if (reqType == "updateFiscalYearStatus")
                    {
                        FiscalYearModel fiscalYearModel = DanpheJSONConvert.DeserializeObject <FiscalYearModel>(str);
                        accountingDBContext.FiscalYears.Attach(fiscalYearModel);
                        accountingDBContext.Entry(fiscalYearModel).Property(x => x.IsActive).IsModified = true;
                        accountingDBContext.SaveChanges();
                        responseData.Status  = "OK";
                        responseData.Results = fiscalYearModel;
                    }
                    else if (reqType == "updateCostCenterItemStatus")
                    {
                        CostCenterItemModel ccImodel = DanpheJSONConvert.DeserializeObject <CostCenterItemModel>(str);
                        accountingDBContext.CostCenterItems.Attach(ccImodel);
                        accountingDBContext.Entry(ccImodel).Property(x => x.IsActive).IsModified = true;
                        accountingDBContext.SaveChanges();
                        responseData.Status  = "OK";
                        responseData.Results = ccImodel;
                    }
                    else if (reqType == "updateLedgerGrpCategoryIsActive")
                    {
                        LedgerGroupCategoryModel ledgerGrpCat = DanpheJSONConvert.DeserializeObject <LedgerGroupCategoryModel>(str);
                        accountingDBContext.LedgerGroupsCategory.Attach(ledgerGrpCat);
                        accountingDBContext.Entry(ledgerGrpCat).Property(x => x.IsActive).IsModified = true;
                        accountingDBContext.SaveChanges();
                        responseData.Status  = "OK";
                        responseData.Results = ledgerGrpCat;
                    }
                    else if (reqType == "UpdateLedger")
                    {
                        LedgerModel ledger = DanpheJSONConvert.DeserializeObject <LedgerModel>(str);
                        var         led    = accountingDBContext.Ledgers.Where(s => s.LedgerId == ledger.LedgerId).FirstOrDefault();
                        if (led != null)
                        {
                            led.IsActive               = ledger.IsActive;
                            led.LedgerName             = ledger.LedgerName;
                            led.OpeningBalance         = ledger.OpeningBalance;
                            led.Description            = ledger.Description;
                            led.IsCostCenterApplicable = ledger.IsCostCenterApplicable;
                            led.DrCr = ledger.DrCr;
                            accountingDBContext.Ledgers.Attach(led);
                            accountingDBContext.Entry(led).Property(x => x.IsActive).IsModified               = true;
                            accountingDBContext.Entry(led).Property(x => x.LedgerName).IsModified             = true;
                            accountingDBContext.Entry(led).Property(x => x.Description).IsModified            = true;
                            accountingDBContext.Entry(led).Property(x => x.DrCr).IsModified                   = true;
                            accountingDBContext.Entry(led).Property(x => x.IsCostCenterApplicable).IsModified = true;
                            accountingDBContext.Entry(led).Property(x => x.OpeningBalance).IsModified         = true;
                            accountingDBContext.SaveChanges();
                            responseData.Status  = "OK";
                            responseData.Results = led;
                        }
                        else
                        {
                            responseData.Status = "Failed";
                        }
                    }

                    else if (reqType == "UpdateVoucherHead")
                    {
                        VoucherHeadModel voucher = DanpheJSONConvert.DeserializeObject <VoucherHeadModel>(str);
                        var voucherHead          = accountingDBContext.VoucherHeads.Where(s => s.VoucherHeadId == voucher.VoucherHeadId).FirstOrDefault();
                        if (voucherHead != null)
                        {
                            voucherHead.IsActive        = voucher.IsActive;
                            voucherHead.VoucherHeadName = voucher.VoucherHeadName;
                            voucherHead.Description     = voucher.Description;
                            voucherHead.ModifiedOn      = System.DateTime.Now;
                            voucherHead.ModifiedBy      = voucher.ModifiedBy;
                            accountingDBContext.VoucherHeads.Attach(voucherHead);
                            accountingDBContext.Entry(voucherHead).Property(x => x.IsActive).IsModified        = true;
                            accountingDBContext.Entry(voucherHead).Property(x => x.VoucherHeadName).IsModified = true;
                            accountingDBContext.Entry(voucherHead).Property(x => x.Description).IsModified     = true;
                            accountingDBContext.Entry(voucherHead).Property(x => x.ModifiedOn).IsModified      = true;
                            accountingDBContext.Entry(voucherHead).Property(x => x.ModifiedBy).IsModified      = true;
                            accountingDBContext.SaveChanges();
                            responseData.Status  = "OK";
                            responseData.Results = voucherHead;
                        }
                        else
                        {
                            responseData.Status = "Failed";
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #17
0
        public string Get(string reqType)
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            try
            {
                LabDbContext labDbContext = new LabDbContext(connString);

                //this get is from OrderLabTests
                if (reqType == "labReportList")//!=null not needed for string.
                {
                    //LabReportTemplateModel allLabReports = new LabReportTemplateModel();
                    List <LabReportTemplateModel> allLabReports = new List <LabReportTemplateModel>();
                    allLabReports = (from rep in labDbContext.LabReportTemplates
                                     select rep).ToList();
                    responseData.Results = allLabReports;
                }
                else if (reqType == "labTestsList")
                {
                    List <LabTestJSONComponentModel> allLabTestComponents = (from labComponent in labDbContext.LabTestComponents
                                                                             where true
                                                                             select labComponent).ToList();
                    var allLabTests = (from test in labDbContext.LabTests
                                       join report in labDbContext.LabReportTemplates on test.ReportTemplateId equals report.ReportTemplateID
                                       join billItem in labDbContext.BillItemPrice on test.LabTestId equals billItem.ItemId
                                       join srv in labDbContext.ServiceDepartment on billItem.ServiceDepartmentId equals srv.ServiceDepartmentId
                                       where srv.IntegrationName.ToLower() == "lab"
                                       select new
                    {
                        LabTestId = test.LabTestId,
                        LabSequence = test.LabSequence,
                        LabTestCode = test.LabTestCode,
                        ProcedureCode = test.ProcedureCode,
                        Description = test.Description,
                        LabTestSynonym = test.LabTestSynonym,
                        LabTestName = test.LabTestName,
                        LabTestSpecimen = test.LabTestSpecimen,
                        LabTestSpecimenSource = test.LabTestSpecimenSource,
                        LabTestComponentsJSON = (from labTest in labDbContext.LabTests
                                                 join componentMap in labDbContext.LabTestComponentMap on labTest.LabTestId equals componentMap.LabTestId
                                                 join component in labDbContext.LabTestComponents on componentMap.ComponentId equals component.ComponentId
                                                 where labTest.LabTestId == test.LabTestId && componentMap.IsActive == true
                                                 select component).ToList(),
                        LabTestComponentMap = (from componentMap in labDbContext.LabTestComponentMap
                                               where componentMap.LabTestId == test.LabTestId && componentMap.IsActive == true
                                               select componentMap).OrderBy(a => a.DisplaySequence).ToList(),
                        LOINC = test.LOINC,
                        ReportTemplateId = test.ReportTemplateId,
                        DisplaySequence = test.DisplaySequence.HasValue ? test.DisplaySequence : 1000,                   //default sequence is 1000
                        IsSelected = false,
                        IsPreference = false,
                        IsValidSampling = test.IsValidSampling,
                        IsActive = test.IsActive,
                        HasNegativeResults = test.HasNegativeResults,
                        NegativeResultText = test.NegativeResultText,
                        ServiceDepartmentId = billItem.ServiceDepartmentId,
                        ReportingName = test.ReportingName,
                        Interpretation = test.Interpretation,
                        ReportTemplateName = report.ReportTemplateName,
                        RunNumberType = test.RunNumberType,
                        IsTaxApplicable = billItem.TaxApplicable
                    }).ToList();


                    responseData.Results = allLabTests;
                }
                else if (reqType == "lab-vendors-list") //sud:22Apr'19
                {
                    List <LabVendorsModel> allLabVendors = labDbContext.LabVendors.ToList();
                    responseData.Results = allLabVendors;
                }
                else if (reqType == "labSignatories")
                {
                    LabSignatoriesViewModel signatoriesData = new LabSignatoriesViewModel();
                    signatoriesData.AllSignatories = (from cfg in labDbContext.AdminParameters
                                                      where cfg.ParameterGroupName.ToLower() == "lab" &&
                                                      (cfg.ParameterName == "DefaultHistoCytoSignatoriesEmpId" || cfg.ParameterName == "DefaultSignatoriesEmpId")
                                                      select cfg
                                                      ).ToList();


                    var departmentId = (from dpt in labDbContext.Department
                                        where (dpt.DepartmentCode.ToLower() == "lab" || dpt.DepartmentCode.ToLower() == "pat")
                                        select dpt.DepartmentId
                                        ).ToList();


                    signatoriesData.AllDoctors = (from doc in labDbContext.Employee
                                                  where departmentId.Contains((int)doc.DepartmentId)
                                                  select doc
                                                  ).ToList();

                    responseData.Results = signatoriesData;
                }
                else if (reqType == "allLabTestComponentList")
                {
                    List <LabTestJSONComponentModel> allLabTestComponents = (from labComponent in labDbContext.LabTestComponents
                                                                             where true
                                                                             select labComponent).ToList();

                    responseData.Results = allLabTestComponents;
                }
                else if (reqType == "allLookUp")
                {
                    List <CoreCFGLookupModel> allLookUps = (from lookup in labDbContext.LabLookUps
                                                            where lookup.ModuleName.ToLower() == "lab"
                                                            select lookup).ToList();
                    responseData.Results = allLookUps;
                }
                else
                {
                }
                responseData.Status = "OK";
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #18
0
        public string Get(string reqType, string status)
        {
            HelpdeskDbContext           dbContextHelpdesk = new HelpdeskDbContext(connString);
            AdmissionDbContext          dbAdmission       = new AdmissionDbContext(connString);
            DanpheHTTPResponse <object> responseData      = new DanpheHTTPResponse <object>();



            try
            {
                //gets the EmployeeInfo from Employee table
                if (reqType == "getHelpdesk")
                {
                    //.ToList()is done two times,since we can't use requestDate.Date inside IQueryable
                    List <EmployeeInfoModel> empsInfoList = dbContextHelpdesk.GetEmployeeInfo();
                    //where d.EmployeeId == employeeId


                    responseData.Status = "OK";
                    //loads EmployeeInfo with requested status
                    responseData.Results = empsInfoList;
                }
                //gets the BedInformation from Bed,Bedtype and Ward tables
                if (reqType == "getBedinfo")
                {
                    //.ToList()is done two times,since we can't use requestDate.Date inside IQueryable
                    DynamicReport bedsInfoList = dbContextHelpdesk.GetBedInformation();

                    responseData.Status  = "OK";
                    responseData.Results = bedsInfoList;
                }
                //gets the BedInformation , Patient Information and Ward Name
                if (reqType == "getBedPatientInfo")
                {
                    var bedpatientinfo = dbAdmission.Beds.ToList().GroupJoin(dbAdmission.PatientBedInfos.ToList().Where(a => a.EndedOn == null), a => a.BedId, b => b.BedId, (a, b) =>
                                                                             new BedPatientViewModel
                    {
                        BedId            = a.BedId,
                        WardId           = a.WardId,
                        BedCode          = a.BedCode,
                        PatientId        = b.Select(s => s.PatientId).FirstOrDefault(),
                        PatientBedInfoId = b.Select(s => s.PatientBedInfoId).FirstOrDefault(),
                        StartedOn        = b.Select(s => s.StartedOn).FirstOrDefault(),
                        EndedOn          = b.Select(s => s.EndedOn).FirstOrDefault(),
                        BedNumber        = a.BedNumber,
                        IsOccupied       = a.IsOccupied
                    }).GroupJoin(dbAdmission.Patients.ToList(), a => a.PatientId, b => b.PatientId, (a, b) =>
                                 new BedPatientViewModel
                    {
                        BedId            = a.BedId,
                        WardId           = a.WardId,
                        BedCode          = a.BedCode,
                        PatientId        = b.Select(s => s.PatientId).FirstOrDefault(),
                        PatientBedInfoId = a.PatientBedInfoId,
                        StartedOn        = a.StartedOn,
                        EndedOn          = a.EndedOn,
                        BedNumber        = a.BedNumber,
                        IsOccupied       = a.IsOccupied,
                        PatientName      = b.Select(s => s.FirstName).FirstOrDefault() + " " + b.Select(s => s.MiddleName).FirstOrDefault() + " " + b.Select(s => s.LastName).FirstOrDefault(),
                        PatientCode      = b.Select(s => s.PatientCode).FirstOrDefault(),
                        Address          = b.Select(s => s.Address).FirstOrDefault()
                    }).GroupJoin(dbAdmission.Wards.ToList(), a => a.WardId, b => b.WardId, (a, b) =>
                                 new BedPatientViewModel
                    {
                        BedId            = a.BedId,
                        WardId           = b.Select(s => s.WardId).FirstOrDefault(),
                        WardName         = b.Select(s => s.WardName).FirstOrDefault(),
                        BedCode          = a.BedCode,
                        PatientId        = a.PatientId,
                        PatientBedInfoId = a.PatientBedInfoId,
                        StartedOn        = a.StartedOn,
                        EndedOn          = a.EndedOn,
                        BedNumber        = a.BedNumber,
                        IsOccupied       = a.IsOccupied,
                        PatientName      = a.PatientName,
                        PatientCode      = a.PatientCode,
                        Address          = a.Address
                    }).GroupJoin(dbAdmission.Admissions.ToList(), a => a.PatientId, b => b.PatientId, (a, b) =>
                                 new BedPatientViewModel
                    {
                        BedId              = a.BedId,
                        WardId             = a.WardId,
                        WardName           = a.WardName,
                        BedCode            = a.BedCode,
                        PatientId          = a.PatientId,
                        PatientBedInfoId   = a.PatientBedInfoId,
                        StartedOn          = a.StartedOn,
                        EndedOn            = a.EndedOn,
                        BedNumber          = a.BedNumber,
                        IsOccupied         = a.IsOccupied,
                        PatientName        = a.PatientName,
                        PatientCode        = a.PatientCode,
                        Address            = a.Address,
                        PatientVisitId     = b.Select(s => s.PatientVisitId).FirstOrDefault(),
                        PatientAdmissionId = b.Select(s => s.PatientAdmissionId).FirstOrDefault(),
                        DischargedDate     = b.Select(s => s.DischargeDate).FirstOrDefault(),
                        AdmittedDate       = b.Select(s => s.AdmissionDate).FirstOrDefault()
                    });

                    responseData.Status  = "OK";
                    responseData.Results = bedpatientinfo;
                }
                //gets the WardInformation from WardBedType and Ward tables
                if (reqType == "getWardinfo")
                {
                    //data from GetWardInformation Method from Dbcontext
                    List <WardInformationModel> wardsInfoList = dbContextHelpdesk.GetWardInformation();

                    responseData.Status  = "OK";
                    responseData.Results = wardsInfoList;
                }
                else if (reqType == "getBedFeature")
                {
                    DanpheHTTPResponse <DataTable> data = new DanpheHTTPResponse <DataTable>();
                    try
                    {
                        HelpdeskDbContext helpdeskDbContext = new HelpdeskDbContext(connString);
                        DataTable         dtResult          = helpdeskDbContext.BedFeatureReprot();
                        data.Status  = "OK";
                        data.Results = dtResult;
                    }
                    catch (Exception ex)
                    {
                        //Insert exception details into database table.
                        data.Status       = "Failed";
                        data.ErrorMessage = ex.Message;
                    }
                    return(DanpheJSONConvert.SerializeObject(data));
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
        public string Get(string reqType, int userid, string usernamelist, string useridlist, string username, string password, int documentid, string sessionid, int conferenceid)
        {
            //DanpheTeleMedDbContext dbContext = new DanpheTeleMedDbContext(connString);
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            try
            {
                #region Get Old chat record for p2p communication
                if (reqType == "get-old-chat")
                {
                    var arr = useridlist.Split(',');
                    if (arr.Length == 2)
                    {
                        var user1id = Convert.ToInt32(arr[0]);
                        var user2id = Convert.ToInt32(arr[1]);
                        var res     = new
                        {
                            chat = (from c in dbContext.SessionChat
                                    where (c.SenderId == user1id && c.ReceiverId == user2id) ||
                                    (c.SenderId == user2id && c.ReceiverId == user1id)
                                    select new
                            {
                                c.SenderId,
                                c.ReceiverId,
                                SenderName = dbContext.User.Where(a => a.UserId == c.SenderId).Select(a => a.UserName).FirstOrDefault(),
                                ReceiverName = dbContext.User.Where(a => a.UserId == c.ReceiverId).Select(a => a.UserName).FirstOrDefault(),
                                c.SentText,
                                c.SentTime,
                            }).ToList(),

                            call = (from st in dbContext.SessionTxns
                                    join si in (from c in dbContext.SessionUserTxns
                                                where (c.SessionOwnerId == user1id && c.UserId == user2id) ||
                                                (c.SessionOwnerId == user2id && c.UserId == user1id)
                                                select c.SessionId).Distinct().ToList()
                                    on st.SessionId equals si
                                    orderby st.SessionTxnId descending
                                    select new
                            {
                                StartTime = st.CreatedOn,
                                st.EndTime
                            }).Take(10).ToList()
                        };
                        responseData.Results = res;
                    }
                    else
                    {
                        responseData.Results = "user";
                    }
                }
                #endregion
                #region Check username and password for login
                else if (reqType == "check-user")
                {
                    if (username != "" || password != "")
                    {
                        var user = (from u in dbContext.User
                                    where u.UserName == username && u.Password == password
                                    select new
                        {
                            u.UserId,
                            u.UserName,
                            u.IsActive,
                            u.Role,
                            u.CreatedOn
                        }).FirstOrDefault();
                        if (user != null)
                        {
                            responseData.Results = user;
                        }
                        else
                        {
                            responseData.ErrorMessage = "Username or Password is wrong!!";
                        }
                    }
                    else
                    {
                        responseData.ErrorMessage = "Username or Password is wrong!!";
                    }
                }
                #endregion
                #region get assessment
                else if (reqType == "get-assessment")
                {
                    var user1id = 0;
                    var user2id = 0;
                    var arr     = useridlist.Split(',');
                    if (arr.Length == 2)
                    {
                        user1id = Convert.ToInt32(arr[0]);
                        user2id = Convert.ToInt32(arr[1]);
                        var sessionlist = (from sl in dbContext.SessionUserTxns.AsEnumerable()
                                           where (sl.SessionOwnerId == user1id &&
                                                  sl.UserId == user2id) ||
                                           (sl.UserId == user1id &&
                                            sl.SessionOwnerId == user2id)
                                           select sl.SessionId).Distinct().ToList();

                        var note = (from n in dbContext.Assessment.AsEnumerable()
                                    join sl in sessionlist on n.SessionId equals sl
                                    select n).ToList();
                        responseData.Results = note;
                    }
                    else
                    {
                        responseData.Results = "not found";
                    }
                }
                #endregion
                #region get complain
                else if (reqType == "get-complain")
                {
                    var user1id = 0;
                    var user2id = 0;
                    var arr     = useridlist.Split(',');
                    if (arr.Length == 2)
                    {
                        user1id = Convert.ToInt32(arr[0]);
                        user2id = Convert.ToInt32(arr[1]);
                        var sessionlist = (from sl in dbContext.SessionUserTxns.AsEnumerable()
                                           where (sl.SessionOwnerId == user1id &&
                                                  sl.UserId == user2id) ||
                                           (sl.UserId == user1id &&
                                            sl.SessionOwnerId == user2id)
                                           select sl.SessionId).Distinct().ToList();

                        var note = (from n in dbContext.Complain.AsEnumerable()
                                    join sl in sessionlist on n.SessionId equals sl
                                    select n).ToList();
                        responseData.Results = note;
                    }
                    else
                    {
                        responseData.Results = "not found";
                    }
                }
                #endregion
                #region get examination
                else if (reqType == "get-examination")
                {
                    var user1id = 0;
                    var user2id = 0;
                    var arr     = useridlist.Split(',');
                    if (arr.Length == 2)
                    {
                        user1id = Convert.ToInt32(arr[0]);
                        user2id = Convert.ToInt32(arr[1]);
                        var sessionlist = (from sl in dbContext.SessionUserTxns.AsEnumerable()
                                           where (sl.SessionOwnerId == user1id &&
                                                  sl.UserId == user2id) ||
                                           (sl.UserId == user1id &&
                                            sl.SessionOwnerId == user2id)
                                           select sl.SessionId).Distinct().ToList();

                        var note = (from n in dbContext.Examination.AsEnumerable()
                                    join sl in sessionlist on n.SessionId equals sl
                                    select n).ToList();
                        responseData.Results = note;
                    }
                    else
                    {
                        responseData.Results = "not found";
                    }
                }
                #endregion
                #region get orders
                else if (reqType == "get-orders")
                {
                    var user1id = 0;
                    var user2id = 0;
                    var arr     = useridlist.Split(',');
                    if (arr.Length == 2)
                    {
                        user1id = Convert.ToInt32(arr[0]);
                        user2id = Convert.ToInt32(arr[1]);
                        var sessionlist = (from sl in dbContext.SessionUserTxns.AsEnumerable()
                                           where (sl.SessionOwnerId == user1id &&
                                                  sl.UserId == user2id) ||
                                           (sl.UserId == user1id &&
                                            sl.SessionOwnerId == user2id)
                                           select sl.SessionId).Distinct().ToList();

                        var note = (from n in dbContext.Order.AsEnumerable()
                                    join sl in sessionlist on n.SessionId equals sl
                                    select n).ToList();
                        responseData.Results = note;
                    }
                    else
                    {
                        responseData.Results = "not found";
                    }
                }
                #endregion
                #region get plan
                else if (reqType == "get-plan")
                {
                    var user1id = 0;
                    var user2id = 0;
                    var arr     = useridlist.Split(',');
                    if (arr.Length == 2)
                    {
                        user1id = Convert.ToInt32(arr[0]);
                        user2id = Convert.ToInt32(arr[1]);
                        var sessionlist = (from sl in dbContext.SessionUserTxns.AsEnumerable()
                                           where (sl.SessionOwnerId == user1id &&
                                                  sl.UserId == user2id) ||
                                           (sl.UserId == user1id &&
                                            sl.SessionOwnerId == user2id)
                                           select sl.SessionId).Distinct().ToList();

                        var note = (from n in dbContext.Plan.AsEnumerable()
                                    join sl in sessionlist on n.SessionId equals sl
                                    select n).ToList();
                        responseData.Results = note;
                    }
                    else
                    {
                        responseData.Results = "not found";
                    }
                }
                #endregion
                #region Get Consult requests
                else if (reqType == "get-consult-request")
                {
                    var sessionlist = GetSessionIdList(dbContext, useridlist);
                    var note        = (from n in dbContext.ConsultRequest.AsEnumerable()
                                       join sl in sessionlist on n.SessionId equals sl
                                       select n).ToList();
                    responseData.Results = note;
                }
                #endregion
                #region get session file
                else if (reqType == "get-document-list")
                {
                    var sessionlist = GetSessionIdList(dbContext, useridlist);

                    var doclist = (from sd in dbContext.SessionDocument.AsEnumerable()
                                   join sl in sessionlist on sd.SessionId equals sl
                                   select new
                    {
                        sd.SessionDocumentId,
                        sd.SessionId,
                        sd.FileName,
                        sd.UploadedOn,
                        sd.UploadedBy,
                        //UploaderName = GetUserName(dbContext, sd.UploadedBy)
                    }).ToList();
                    List <SessionDocumentsModel> docs = new List <SessionDocumentsModel>();
                    doclist.ForEach(a =>
                    {
                        var doc = new SessionDocumentsModel();
                        doc.SessionDocumentId = a.SessionDocumentId;
                        doc.SessionId         = a.SessionId;
                        doc.FileName          = a.FileName;
                        doc.UploadedOn        = a.UploadedOn;
                        doc.UploaderName      = GetUserName(dbContext, a.UploadedBy);
                        docs.Add(doc);
                    });
                    responseData.Results = docs;
                }
                else if (reqType == "get-document")
                {
                    var file = (from d in dbContext.SessionDocument
                                where d.SessionDocumentId == documentid
                                select new
                    {
                        d.FileName,
                        d.FileExtension,
                        d.FileByteArray
                    }).FirstOrDefault();
                    responseData.Results = file;
                }
                #endregion
                #region check valid conference for join
                else if (reqType == "check-valid-conference")
                {
                    var res = (from c in dbContext.Conference
                               where c.ConferenceRoomId == sessionid
                               select c.ConferenceRoomId).FirstOrDefault();
                    if (res != null)
                    {
                        responseData.Results = true;
                    }
                    else
                    {
                        responseData.Results = false;
                    }
                }
                #endregion
                #region get user details
                else if (reqType == "get-user-details")
                {
                    var user = (from u in dbContext.User
                                where u.UserId == userid
                                select new
                    {
                        u.UserId,
                        u.UserName,
                        u.IsActive,
                        u.Role
                    }).FirstOrDefault();
                    if (user != null)
                    {
                        responseData.Results = user;
                    }
                }
                #endregion
                #region get user contacts
                else if (reqType == "get-user-contacts")
                {
                    //var contacts = (from uc in dbContext.User
                    //                select new
                    //                {
                    //                    UserId = userid,
                    //                    ContactId = uc.UserId,
                    //                    ContactName = uc.UserName
                    //                }).ToList();
                    var contacts = (from uc in dbContext.UserContacts
                                    join u in dbContext.User on uc.ContactId equals u.UserId
                                    where uc.UserId == userid
                                    select new
                    {
                        uc.UserId,
                        uc.ContactId,
                        ContactName = u.UserName
                    }).ToList();
                    responseData.Results = contacts;
                }
                #endregion
                #region get user list
                else if (reqType == "get-user-list")
                {
                    var users = (from u in dbContext.User
                                 where u.IsActive == true
                                 select new
                    {
                        u.UserId,
                        u.UserName,
                        u.Role,
                        u.IsActive
                    }).ToList();
                    responseData.Results = users;
                    responseData.Status  = "OK";
                }
                #endregion
                #region get previous meetings
                else if (reqType == "get-previous-meetings")
                {
                    var meetings = (from m in dbContext.Conference
                                    where m.CreatedBy == userid
                                    orderby m.ConferenceId descending
                                    select m).ToList();
                    responseData.Results = meetings;
                }
                else if (reqType == "get-meeting-details")
                {
                    var meeting = (from c in dbContext.Conference
                                   where c.ConferenceId == conferenceid
                                   select new
                    {
                        ConnectedUsers = (from cu in dbContext.ConferenceUser
                                          where cu.ConferenceRoomId == c.ConferenceRoomId
                                          select cu).ToList(),
                        ConferenceChat = (from cc in dbContext.ConferenceChat
                                          where cc.ConferenceRoomId == c.ConferenceRoomId
                                          select cc).ToList()
                    }).FirstOrDefault();
                    responseData.Results = meeting;
                }
                #endregion
                else if (reqType == "get-iceserver-config")
                {
                    responseData.Results = dbContext.Parameters
                                           .Where(a => a.ParameterName == "iceServer" && a.IsActive == true)
                                           .Select(a => a.ParameterValue).FirstOrDefault();
                }
                else
                {
                    responseData.Results = "Request Type not found";
                }
                responseData.Status = "OK";
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #20
0
        public string Post()
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            try
            {
                string          reqType        = this.ReadQueryStringData("reqType");
                OrdersDbContext orderDbContext = new OrdersDbContext(connString);

                if (reqType != null && reqType == "AddToPreference")
                {
                    string preferenceType   = this.ReadQueryStringData("preferenceType");
                    string preferenceName   = null;
                    string preferenceIdType = null;
                    if (preferenceType.ToLower() == "lab")
                    {
                        preferenceName   = "Labtestpreferences";
                        preferenceIdType = "LabTestId";
                    }
                    else if (preferenceType.ToLower() == "imaging")
                    {
                        preferenceName   = "Imagingpreferences";
                        preferenceIdType = "ImagingItemId";
                    }
                    else if (preferenceType.ToLower() == "medication")
                    {
                        preferenceName   = "Medicationpreferences";
                        preferenceIdType = "MedicineId";
                    }

                    string ItemId = this.ReadQueryStringData("itemId");
                    //string clientValue = this.ReadPostData();

                    RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser");

                    EmployeePreferences employeePreference = (from pref in orderDbContext.EmployeePreferences
                                                              where pref.EmployeeId == currentUser.EmployeeId && pref.PreferenceName == preferenceName
                                                              select pref).FirstOrDefault();

                    if (employeePreference == null)
                    {
                        //this is used to convert string into xml
                        XmlDocument xdoc = JsonConvert.DeserializeXmlNode("{\"Row\":{" + preferenceIdType + ":" + ItemId + "}}", "root");
                        //this is add new perference
                        EmployeePreferences employeePref = new EmployeePreferences();

                        employeePref.PreferenceName  = preferenceName;
                        employeePref.PreferenceValue = xdoc.InnerXml;
                        employeePref.EmployeeId      = currentUser.EmployeeId;
                        employeePref.CreatedBy       = currentUser.EmployeeId;;
                        employeePref.CreatedOn       = DateTime.Now;
                        employeePref.IsActive        = true;
                        orderDbContext.EmployeePreferences.Add(employeePref);
                        orderDbContext.SaveChanges();
                        responseData.Status  = "OK";
                        responseData.Results = ItemId;
                    }
                    else
                    {
                        //creating object of XmlDocument
                        XmlDocument prefXmlDoc = new XmlDocument();
                        //loading the database PreferenceValue in object of XmlDocument(prefXmlDoc)
                        prefXmlDoc.LoadXml(employeePreference.PreferenceValue);
                        //creating xmlElement with tag Row
                        XmlElement Row = prefXmlDoc.CreateElement("Row");
                        //creating xmlElement with tag LabTestId/ImagingTypeId
                        XmlElement typeId = prefXmlDoc.CreateElement(preferenceIdType);
                        //provididng value to the element of LabTestId/ImagingTypeId
                        typeId.InnerText = ItemId;
                        //appending LabTestId/ImagingTypeId element ot Row element as child
                        Row.AppendChild(typeId);
                        //Appending the Row elemt to the root element of xml
                        prefXmlDoc.DocumentElement.AppendChild(Row);
                        //replacing the old value of employeePreference.PreferenceValue with new one
                        employeePreference.PreferenceValue = prefXmlDoc.InnerXml;
                        employeePreference.ModifiedBy      = currentUser.EmployeeId;
                        employeePreference.ModifiedOn      = DateTime.Now;


                        orderDbContext.Entry(employeePreference).State = EntityState.Modified;
                        orderDbContext.SaveChanges();
                        responseData.Status  = "OK";
                        responseData.Results = ItemId;
                    }
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #21
0
        public string Get(int userId, string reqType)
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            try
            {
                if (reqType == "loggedInUser")
                {
                    RbacUser        currentUser     = HttpContext.Session.Get <RbacUser>("currentuser");
                    MasterDbContext masterDbContext = new MasterDbContext(connString);
                    string          userImgName     = (from x in masterDbContext.Employees
                                                       where x.EmployeeId == currentUser.EmployeeId
                                                       select x.ImageName).FirstOrDefault();

                    EmployeeModel employee = (from x in masterDbContext.Employees
                                              where x.EmployeeId == currentUser.EmployeeId
                                              select x).FirstOrDefault();

                    string imgLocation = string.IsNullOrEmpty(userImgName) ? "" : fileUploadLocation + "UserProfile\\" + userImgName;

                    //start: to get default route for current user.
                    List <RbacRole> usrAllRoles = RBAC.GetUserAllRoles(currentUser.UserId);
                    RbacRole        defRole     = usrAllRoles != null && usrAllRoles.Count > 0 ? usrAllRoles.OrderBy(r => r.RolePriority).FirstOrDefault() : null;
                    int?            defRouteId  = defRole != null ? defRole.DefaultRouteId : 0;

                    string defaultRoutePath = null;

                    if (defRouteId.HasValue)
                    {
                        List <DanpheRoute> allRoutes = RBAC.GetAllRoutes();
                        DanpheRoute        defRoute  = allRoutes.Where(r => r.RouteId == defRouteId.Value).FirstOrDefault();
                        if (defRoute != null)
                        {
                            defaultRoutePath = defRoute.UrlFullPath;
                        }
                    }

                    //end: to get default route for current user.

                    //Ajay 07 Aug 2019
                    //getting LandingPageRouteId
                    var landingPageRouteId = (new RbacDbContext(connString)).Users
                                             .Where(a => a.UserId == currentUser.UserId)
                                             .Select(a => a.LandingPageRouteId).FirstOrDefault();

                    responseData.Results = new
                    {
                        UserId              = currentUser.UserId,
                        UserName            = currentUser.UserName,
                        EmployeeId          = currentUser.EmployeeId,
                        Profile             = new { ImageLocation = imgLocation },
                        NeedsPasswordUpdate = currentUser.NeedsPasswordUpdate,
                        DefaultPagePath     = defaultRoutePath,
                        Employee            = employee,
                        LandingPageRouteId  = landingPageRouteId
                    };
                    responseData.Status = "OK";
                }
                else if (reqType != null && reqType.ToLower() == "routelist")
                {
                    RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser");
                    if (currentUser != null)
                    {
                        var currentUserId            = currentUser.UserId;
                        List <DanpheRoute> routeList = new List <DanpheRoute>();
                        //we need to get routes with defaultshow=false and no need of hierarchy.
                        routeList            = RBAC.GetRoutesForUser(currentUser.UserId, getHiearrchy: false);
                        responseData.Results = routeList;
                        responseData.Status  = "OK";
                        //set session of Valid routeList for loggedin user
                        HttpContext.Session.Set <List <DanpheRoute> >("validRouteList", routeList);
                    }
                    else
                    {
                        responseData.Status       = "Failed";
                        responseData.ErrorMessage = "User is Not valid";
                    }
                }
                else if (reqType != null && reqType == "validallrouteList")
                {
                    RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser");
                    if (currentUser != null)
                    {
                        var currentUserId            = currentUser.UserId;
                        List <DanpheRoute> routeList = new List <DanpheRoute>();
                        routeList = RBAC.GetRoutesForUser(currentUser.UserId, getHiearrchy: true);

                        var filteredRoutes = routeList.Where(r => r.DefaultShow != false && r.IsActive == true).ToList();
                        filteredRoutes.ForEach(r =>
                        {
                            if (r.ChildRoutes != null)
                            {
                                r.ChildRoutesDefaultShowCount = r.ChildRoutes.Where(c => c.DefaultShow == true).Count();
                            }
                            else
                            {
                                r.ChildRoutesDefaultShowCount = 0;
                            }
                        });
                        responseData.Results = filteredRoutes;
                        responseData.Status  = "OK";
                        HttpContext.Session.Set <List <DanpheRoute> >("validallrouteList", filteredRoutes);
                    }
                    else
                    {
                        responseData.Status       = "Failed";
                        responseData.ErrorMessage = "User is Not valid";
                    }
                }
                else if (reqType != null && reqType == "userPermissionList")
                {
                    RbacUser currentUser = HttpContext.Session.Get <RbacUser>("currentuser");
                    List <RbacPermission> userPermissions = new List <RbacPermission>();
                    if (currentUser != null)
                    {
                        int currentUserId = currentUser.UserId;
                        //get permissions of user
                        userPermissions = RBAC.GetUserAllPermissions(currentUserId);
                        //set session of valid user permission
                        HttpContext.Session.Set <List <RbacPermission> >("userAllPermissions", userPermissions);
                        responseData.Status = "OK";
                    }
                    else
                    {
                        responseData.Status       = "Failed";
                        responseData.ErrorMessage = "Invalid User.";
                    }

                    responseData.Results = userPermissions;
                }
                else if (reqType == "activeBillingCounter")
                {
                    string activeCounterId = HttpContext.Session.Get <string>("activeBillingCounter");
                    int    actCounterId;
                    int.TryParse(activeCounterId, out actCounterId);
                    responseData.Results = actCounterId;
                    responseData.Status  = "OK";
                }
                else if (reqType == "activePharmacyCounter")
                {
                    string activeCounterId = HttpContext.Session.Get <string>("activePharmacyCounter");
                    int    actCounterId;
                    int.TryParse(activeCounterId, out actCounterId);
                    string      activeCounterName = HttpContext.Session.Get <string>("activePharmacyCounterName");
                    PHRMCounter counter           = new PHRMCounter();
                    counter.CounterId    = actCounterId;
                    counter.CounterName  = activeCounterName;
                    responseData.Results = counter;
                    responseData.Status  = "OK";
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            var routelist = DanpheJSONConvert.SerializeObject(responseData, true);

            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }
コード例 #22
0
        public string Get(string reqType, int patientId, int ipVisitId, int?billingTxnId, string billStatus)
        {
            DanpheHTTPResponse <object> responseData = new DanpheHTTPResponse <object>();

            responseData.Status = "OK";//by default status would be OK, hence assigning at the top
            try
            {
                BillingDbContext dbContext = new BillingDbContext(connString);
                //sud:10Sept'18 -- Pending in below function-- get ward/bed details of patient.
                if (reqType == "list-ip-patients")
                {
                    var ipPatients = (from pat in dbContext.Patient
                                      join adm in dbContext.Admissions
                                      on pat.PatientId equals adm.PatientId
                                      where adm.AdmissionStatus == "admitted"
                                      join vis in dbContext.Visit
                                      on adm.PatientVisitId equals vis.PatientVisitId
                                      join doc in dbContext.Employee.DefaultIfEmpty()
                                      on adm.AdmittingDoctorId equals doc.EmployeeId

                                      select new
                    {
                        PatientId = pat.PatientId,
                        PatientNo = pat.PatientCode,
                        pat.DateOfBirth,
                        pat.Gender,
                        pat.PhoneNumber,
                        VisitId = adm.PatientVisitId,
                        IpNumber = vis.VisitCode,
                        PatientName = pat.FirstName + " " + (string.IsNullOrEmpty(pat.MiddleName) ? "" : pat.MiddleName + " ") + pat.LastName,
                        FirstName = pat.FirstName,
                        LastName = pat.LastName,
                        MiddleName = pat.MiddleName,
                        AdmittedDate = adm.AdmissionDate,
                        DischargeDate = adm.AdmissionStatus == "admitted" ? adm.DischargeDate : (DateTime?)DateTime.Now,
                        AdmittingDoctorId = adm.AdmittingDoctorId,
                        AdmittingDoctorName = doc != null ? doc.FirstName + " " + doc.LastName : null,
                        ProvisionalAmount = (
                            dbContext.BillingTransactionItems.Where(itm => itm.PatientId == pat.PatientId &&
                                                                    itm.BillStatus == "provisional").Sum(itm => itm.TotalAmount)
                            ),
                        DepositAdded = (
                            dbContext.BillingDeposits.Where(dep => dep.PatientId == pat.PatientId &&
                                                            dep.PatientVisitId == vis.PatientVisitId &&
                                                            dep.DepositType.ToLower() == "deposit" &&
                                                            dep.IsActive == true)
                            .Sum(dep => dep.Amount)
                            ),

                        DepositReturned = (
                            dbContext.BillingDeposits.Where(dep =>
                                                            dep.PatientId == pat.PatientId &&
                                                            dep.PatientVisitId == vis.PatientVisitId &&
                                                            (dep.DepositType.ToLower() == "depositdeduct" || dep.DepositType.ToLower() == "returndeposit") &&
                                                            dep.IsActive == true).Sum(dep => dep.Amount)
                            ),

                        BedInformation = (from bedInfos in dbContext.PatientBedInfos
                                          where bedInfos.PatientVisitId == adm.PatientVisitId
                                          select new
                        {
                            Ward = bedInfos.Ward.WardName,
                            BedCode = bedInfos.Bed.BedCode,
                            BedNumber = bedInfos.Bed.BedNumber,
                            StartedOn = bedInfos.StartedOn,
                        }).OrderByDescending(a => a.StartedOn).FirstOrDefault()
                    }).ToList();

                    responseData.Results = ipPatients.OrderByDescending(a => a.AdmittedDate);
                }
                else if (reqType == "pat-pending-items")
                {
                    //Check if we can apply ipVisitId condition here..
                    var pendingItems = dbContext.BillingTransactionItems.Where(itm => itm.PatientId == patientId &&
                                                                               itm.BillStatus == "provisional" && itm.Quantity > 0 &&
                                                                               (itm.IsInsurance == false || itm.IsInsurance == null)).AsEnumerable().ToList(); //Excluding insurance items
                    var bedPatInfo = (from bedInfo in dbContext.PatientBedInfos
                                      where bedInfo.PatientVisitId == ipVisitId
                                      select bedInfo).OrderBy(x => x.PatientBedInfoId).ToList().LastOrDefault();
                    DateTime admDate     = dbContext.Admissions.Where(a => a.PatientVisitId == bedPatInfo.PatientVisitId && a.PatientId == bedPatInfo.PatientId).Select(a => a.AdmissionDate).FirstOrDefault();
                    var      tempTime    = admDate.TimeOfDay;
                    var      EndDateTime = DateTime.Now.Date + tempTime;
                    TimeSpan qty;
                    var      checkBedFeatureId = dbContext.PatientBedInfos.Where(a => a.PatientVisitId == bedPatInfo.PatientVisitId && a.PatientId == bedPatInfo.PatientId && bedPatInfo.BedFeatureId == a.BedFeatureId).Select(a => a.BedFeatureId).ToList();
                    pendingItems.ForEach(itm =>
                    {
                        if (itm.ItemId == bedPatInfo.BedFeatureId && bedPatInfo.EndedOn == null && itm.ModifiedBy == null)
                        {
                            //var StartedOn = Convert.ToDateTime(bedPatInfo.StartedOn).Date;
                            //int totalDays = Convert.ToInt32((DateTime.Now.Date - StartedOn).TotalDays);
                            //itm.Quantity = itm.Quantity + totalDays;
                            // TimeSpan qty = DateTime.Now.Subtract(bedPatInfo.StartedOn.Value);
                            // itm.Quantity =  (int)qty.TotalDays + itm.Quantity;
                            itm.IsLastBed = true;
                            if (DateTime.Now > EndDateTime)
                            {
                                qty          = EndDateTime.Subtract(bedPatInfo.StartedOn.Value);
                                itm.Quantity = (checkBedFeatureId.Count > 1) ? ((int)qty.TotalDays + itm.Quantity + 1) : (itm.Quantity = (int)qty.TotalDays + 1);
                                if (bedPatInfo.StartedOn.Value.Date != EndDateTime.Date)
                                {
                                    itm.Quantity = (DateTime.Now.TimeOfDay > EndDateTime.TimeOfDay) ? (itm.Quantity + 1) : itm.Quantity;
                                }
                            }
                            else
                            {
                                qty          = DateTime.Now.Subtract(bedPatInfo.StartedOn.Value);
                                itm.Quantity = (checkBedFeatureId.Count > 1) ? ((int)qty.TotalDays + itm.Quantity + 1) : ((int)qty.TotalDays) + 1;
                            }
                        }
                    });
                    var srvDepts  = dbContext.ServiceDepartment.ToList();
                    var billItems = dbContext.BillItemPrice.ToList();
                    //update integrationName and integrationServiceDepartmentName
                    //required while updating quantity of ADT items.
                    pendingItems.ForEach(penItem =>
                    {
                        var itemIntegrationDetail = (from itm in billItems
                                                     join srv in srvDepts on itm.ServiceDepartmentId equals srv.ServiceDepartmentId
                                                     where itm.ServiceDepartmentId == penItem.ServiceDepartmentId && itm.ItemId == penItem.ItemId
                                                     select new
                        {
                            ItemIntegrationName = itm.IntegrationName,
                            SrvIntegrationName = srv.IntegrationName
                        }).FirstOrDefault();
                        if (itemIntegrationDetail != null)
                        {
                            penItem.ItemIntegrationName    = itemIntegrationDetail.ItemIntegrationName;
                            penItem.SrvDeptIntegrationName = itemIntegrationDetail.SrvIntegrationName;
                        }
                    });
                    var admInfo = (from pat in dbContext.Patient
                                   where pat.PatientId == patientId
                                   join adm in dbContext.Admissions
                                   on pat.PatientId equals adm.PatientId
                                   where adm.PatientVisitId == ipVisitId
                                   join vis in dbContext.Visit
                                   on adm.PatientVisitId equals vis.PatientVisitId
                                   join doc in dbContext.Employee.DefaultIfEmpty()
                                   on adm.AdmittingDoctorId equals doc.EmployeeId

                                   select new
                    {
                        AdmissionPatientId = adm.PatientAdmissionId,
                        PatientId = pat.PatientId,
                        PatientNo = pat.PatientCode,
                        pat.Gender,
                        pat.DateOfBirth,
                        pat.PhoneNumber,
                        VisitId = adm.PatientVisitId,
                        IpNumber = vis.VisitCode,
                        PatientName = pat.FirstName + " " + (string.IsNullOrEmpty(pat.MiddleName) ? "" : pat.MiddleName + " ") + pat.LastName,
                        FirstName = pat.FirstName,
                        LastName = pat.LastName,
                        MiddleName = pat.MiddleName,
                        AdmittedOn = adm.AdmissionDate,
                        DischargedOn = adm.AdmissionStatus == "admitted" ? (DateTime?)DateTime.Now : adm.DischargeDate,
                        AdmittingDoctorId = adm.AdmittingDoctorId,
                        AdmittingDoctorName = doc != null ? (string.IsNullOrEmpty(doc.Salutation) ? "" : doc.Salutation + ". ") + doc.FirstName + " " + (string.IsNullOrEmpty(doc.MiddleName) ? "" : doc.MiddleName + " ") + doc.LastName : null,
                        ProcedureType = adm.ProcedureType,
                        ProvisionalItems = (
                            dbContext.BillingTransactionItems.Where(itm => itm.PatientId == pat.PatientId &&
                                                                    itm.BillStatus == "provisional" && itm.Quantity > 0 &&
                                                                    (itm.IsInsurance == false || itm.IsInsurance == null))).ToList(), //excluding Insurance Items

                        DepositAdded = (
                            dbContext.BillingDeposits.Where(dep => dep.PatientId == pat.PatientId &&
                                                            dep.PatientVisitId == vis.PatientVisitId &&
                                                            dep.DepositType.ToLower() == "deposit" &&
                                                            dep.IsActive == true)
                            .Sum(dep => dep.Amount)
                            ),

                        DepositReturned = (
                            dbContext.BillingDeposits.Where(dep =>
                                                            dep.PatientId == pat.PatientId &&
                                                            dep.PatientVisitId == vis.PatientVisitId &&
                                                            (dep.DepositType.ToLower() == "depositdeduct" || dep.DepositType.ToLower() == "returndeposit") &&
                                                            dep.IsActive == true
                                                            ).Sum(dep => dep.Amount)
                            ),
                        DepositTxns = (
                            dbContext.BillingDeposits.Where(dep => dep.PatientId == pat.PatientId &&
                                                            //dep.PatientVisitId == vis.PatientVisitId &&
                                                            dep.IsActive == true)
                            ).ToList(),

                        BedsInformation = (
                            from bedInfo in dbContext.PatientBedInfos
                            where bedInfo.PatientVisitId == adm.PatientVisitId
                            join ward in dbContext.Wards
                            on bedInfo.WardId equals ward.WardId
                            join bf in dbContext.BedFeatures
                            on bedInfo.BedFeatureId equals bf.BedFeatureId
                            join bed in dbContext.Beds
                            on bedInfo.BedId equals bed.BedId
                            select new
                        {
                            bedInfo.PatientBedInfoId,
                            BedId = bedInfo.BedId,
                            WardId = ward.WardId,
                            WardName = ward.WardName,
                            BedFeatureName = bf.BedFeatureName,
                            bed.BedNumber,
                            PricePerDay = bedInfo.BedPrice,
                            StartedOn = bedInfo.StartedOn,
                            EndedOn = bedInfo.EndedOn.HasValue ? bedInfo.EndedOn : DateTime.Now
                                      //NoOfHours = ((TimeSpan)((bedInfo.EndedOn.HasValue ? bedInfo.EndedOn : DateTime.Now) - bedInfo.StartedOn)).Hours,
                        }).OrderByDescending(a => a.PatientBedInfoId).FirstOrDefault(),

                        BedDetails = (from bedInfos in dbContext.PatientBedInfos
                                      join bedFeature in dbContext.BedFeatures on bedInfos.BedFeatureId equals bedFeature.BedFeatureId
                                      join bed in dbContext.Beds on bedInfos.BedId equals bed.BedId
                                      join ward in dbContext.Wards on bed.WardId equals ward.WardId
                                      where (bedInfos.PatientVisitId == adm.PatientVisitId)
                                      select new BedDetailVM
                        {
                            PatientBedInfoId = bedInfos.PatientBedInfoId,
                            BedFeatureId = bedFeature.BedFeatureId,
                            WardName = ward.WardName,
                            BedCode = bed.BedCode,
                            BedFeature = bedFeature.BedFeatureName,
                            StartDate = bedInfos.StartedOn,
                            EndDate = bedInfos.EndedOn,
                            BedPrice = bedInfos.BedPrice,
                            Action = bedInfos.Action,
                            //calculated in clientSide
                            Days = 0,
                        }).OrderByDescending(a => a.PatientBedInfoId).ToList()
                    }).FirstOrDefault();
                    var patIpInfo = new
                    {
                        AdmissionInfo    = admInfo,
                        PendingBillItems = pendingItems,
                        allBillItem      = billItems
                    };

                    responseData.Results = patIpInfo;
                }
                else if (reqType == "pat-bill-items-for-receipt")
                {
                    try
                    {
                        DataTable patBillItems = dbContext.GetItemsForBillingReceipt(patientId, billingTxnId, billStatus);
                        responseData.Status  = "OK";
                        responseData.Results = patBillItems;
                    }
                    catch (Exception ex)
                    {
                        //Insert exception details into database table.
                        responseData.Status       = "Failed";
                        responseData.ErrorMessage = ex.Message;
                    }
                    //return DanpheJSONConvert.SerializeObject(responseData);
                }
                else if (reqType == "additional-info-discharge-receipt" && ipVisitId != 0)
                {
                    RbacDbContext              rbacDbContext    = new RbacDbContext(connString);
                    AdmissionDetailVM          admInfo          = null;
                    PatientDetailVM            patientDetail    = null;
                    List <DepositDetailVM>     deposits         = null;
                    BillingTransactionDetailVM billingTxnDetail = null;

                    var visitNAdmission = (from visit in dbContext.Visit.Include(v => v.Admission)
                                           where visit.PatientVisitId == ipVisitId
                                           select visit).FirstOrDefault();
                    if (visitNAdmission != null && visitNAdmission.Admission != null)
                    {
                        var patId      = visitNAdmission.PatientId;
                        var patVisitId = visitNAdmission.PatientVisitId;
                        ////invoice is not generated till then IsCurrent is false :: 18th Dec '18
                        //bool isCurrent = billingTxnId != null ? false : true;
                        var billTxn = dbContext.BillingTransactions.Where(a => a.BillingTransactionId == billingTxnId).FirstOrDefault();

                        if (billTxn != null && billTxn.ReturnStatus == false)
                        {
                            deposits = (from deposit in dbContext.BillingDeposits
                                        where deposit.PatientId == patId &&
                                        deposit.PatientVisitId == ipVisitId && deposit.DepositType != "depositcancel" &&
                                        deposit.IsActive == true
                                        join settlement in dbContext.BillSettlements on deposit.SettlementId
                                        equals settlement.SettlementId into settlementTemp
                                        from billSettlement in settlementTemp.DefaultIfEmpty()
                                        select new DepositDetailVM
                            {
                                DepositId = deposit.DepositId,
                                IsActive = deposit.IsActive,
                                ReceiptNo = "DR" + deposit.ReceiptNo.ToString(),
                                ReceiptNum = deposit.ReceiptNo,             //yubraj: to check whether receipt number is null or not for client side use
                                Date = deposit.CreatedOn,
                                Amount = deposit.Amount,
                                Balance = deposit.DepositBalance,
                                DepositType = deposit.DepositType,
                                ReferenceInvoice = deposit.SettlementId != null ? "SR " + billSettlement.SettlementReceiptNo.ToString() : null,
                            }).OrderBy(a => a.Date).ToList();
                        }
                        else
                        {
                            deposits = (from deposit in dbContext.BillingDeposits
                                        where deposit.PatientId == patId &&
                                        deposit.PatientVisitId == ipVisitId &&
                                        ((deposit.IsActive == true && deposit.DepositType == "Deposit") ||
                                         (deposit.BillingTransactionId == billingTxnId && (deposit.DepositType == "depositdeduct" || deposit.DepositType == "ReturnDeposit")))
                                        join settlement in dbContext.BillSettlements on deposit.SettlementId
                                        equals settlement.SettlementId into settlementTemp
                                        from billSettlement in settlementTemp.DefaultIfEmpty()
                                        select new DepositDetailVM
                            {
                                DepositId = deposit.DepositId,
                                IsActive = deposit.IsActive,
                                ReceiptNo = "DR" + deposit.ReceiptNo.ToString(),
                                ReceiptNum = deposit.ReceiptNo,             //yubraj: to check whether receipt number is null or not for client side use
                                Date = deposit.CreatedOn,
                                Amount = deposit.Amount,
                                Balance = deposit.DepositBalance,
                                DepositType = deposit.DepositType,
                                ReferenceInvoice = deposit.SettlementId != null ? "SR " + billSettlement.SettlementReceiptNo.ToString() : null,
                            }).OrderBy(a => a.Date).ToList();
                        }
                        //dischDetail.AdmissionInfo.AdmittingDoctor = "Dr. Anil Shakya";

                        AdmissionDbContext    admDbContext = new AdmissionDbContext(connString);
                        EmployeeModel         admittingDoc = dbContext.Employee.Where(e => e.EmployeeId == visitNAdmission.ProviderId).FirstOrDefault();
                        DepartmentModel       dept         = dbContext.Departments.Where(d => d.DepartmentId == admittingDoc.DepartmentId).FirstOrDefault();
                        List <PatientBedInfo> patBeds      = admDbContext.PatientBedInfos.Where(b => b.PatientVisitId == visitNAdmission.PatientVisitId).OrderByDescending(a => a.PatientBedInfoId).ToList();

                        WardModel ward = null;
                        //we're getting first ward from admission info as WardName. <needs revision>
                        if (patBeds != null && patBeds.Count > 0)
                        {
                            int wardId = patBeds.ElementAt(0).WardId;
                            ward = admDbContext.Wards.Where(w => w.WardId == wardId).FirstOrDefault();
                        }

                        admInfo = new AdmissionDetailVM()
                        {
                            AdmissionDate   = visitNAdmission.Admission.AdmissionDate,
                            DischargeDate   = visitNAdmission.Admission.DischargeDate.HasValue ? visitNAdmission.Admission.DischargeDate.Value : DateTime.Now,
                            Department      = dept != null ? dept.DepartmentName : "",//need to change this and get this from ADT-Bed Info table--sud: 20Aug'18
                            RoomType        = ward != null ? ward.WardName : "",
                            LengthOfStay    = CalculateBedStayForAdmission(visitNAdmission.Admission),
                            AdmittingDoctor = visitNAdmission.ProviderName,
                            ProcedureType   = visitNAdmission.Admission.ProcedureType
                        };

                        patientDetail = (from pat in dbContext.Patient
                                         join sub in dbContext.CountrySubdivisions on pat.CountrySubDivisionId equals sub.CountrySubDivisionId
                                         where pat.PatientId == visitNAdmission.PatientId
                                         select new PatientDetailVM
                        {
                            PatientId = pat.PatientId,
                            PatientName = pat.FirstName + " " + (string.IsNullOrEmpty(pat.MiddleName) ? "" : pat.MiddleName + " ") + pat.LastName,
                            HospitalNo = pat.PatientCode,
                            DateOfBirth = pat.DateOfBirth,
                            Gender = pat.Gender,
                            Address = pat.Address,
                            ContactNo = pat.PhoneNumber,
                            InpatientNo = visitNAdmission.VisitCode,
                            CountrySubDivision = sub.CountrySubDivisionName
                        }).FirstOrDefault();
                    }

                    //ashim: 14Sep2018 : BillingDetail for Discharge Bill

                    billingTxnDetail = (from bil in dbContext.BillingTransactions
                                        join emp in dbContext.Employee on bil.CreatedBy equals emp.EmployeeId
                                        join fiscalYear in dbContext.BillingFiscalYears on bil.FiscalYearId equals fiscalYear.FiscalYearId
                                        where bil.BillingTransactionId == billingTxnId
                                        select new BillingTransactionDetailVM
                    {
                        FiscalYear = fiscalYear.FiscalYearFormatted,
                        ReceiptNo = bil.InvoiceNo,
                        InvoiceNumber = bil.InvoiceCode + bil.InvoiceNo.ToString(),
                        BillingDate = bil.CreatedOn,
                        PaymentMode = bil.PaymentMode,
                        DepositBalance = bil.DepositBalance + bil.DepositReturnAmount,
                        CreatedBy = bil.CreatedBy,
                        DepositDeductAmount = bil.DepositReturnAmount,
                        TotalAmount = bil.TotalAmount,
                        Discount = bil.DiscountAmount,
                        SubTotal = bil.SubTotal,
                        Quantity = bil.TotalQuantity,
                        User = "",
                        Remarks = bil.Remarks,
                        PrintCount = bil.PrintCount,
                        ReturnStatus = bil.ReturnStatus,
                        OrganizationId = bil.OrganizationId,
                        ExchangeRate = bil.ExchangeRate
                    }).FirstOrDefault();
                    if (billingTxnDetail != null)
                    {
                        billingTxnDetail.User = rbacDbContext.Users.Where(usr => usr.EmployeeId == billingTxnDetail.CreatedBy).Select(a => a.UserName).FirstOrDefault();
                        if (billingTxnDetail.OrganizationId != null)
                        {
                            billingTxnDetail.OrganizationName = dbContext.CreditOrganization.Where(a => a.OrganizationId == billingTxnDetail.OrganizationId).Select(b => b.OrganizationName).FirstOrDefault();
                        }
                    }


                    var dischargeBillInfo = new
                    {
                        AdmissionInfo    = admInfo,
                        DepositInfo      = deposits,
                        BillingTxnDetail = billingTxnDetail,
                        PatientDetail    = patientDetail
                    };

                    responseData.Results = dischargeBillInfo;
                    responseData.Status  = "OK";
                }
            }
            catch (Exception ex)
            {
                responseData.Status       = "Failed";
                responseData.ErrorMessage = ex.Message + " exception details:" + ex.ToString();
            }
            return(DanpheJSONConvert.SerializeObject(responseData, true));
        }