Exemple #1
0
        ///<summary>Gets the description for the specified permisssion.  Already translated.</summary>
        public static string GetDesc(Permissions perm)
        {
            //No need to check RemotingRole; no call to db.
            switch (perm)
            {
            case Permissions.Accounting:
                return(Lans.g("enumPermissions", "Accounting"));

            case Permissions.AccountingCreate:
                return(Lans.g("enumPermissions", "Accounting Create Entry"));

            case Permissions.AccountingEdit:
                return(Lans.g("enumPermissions", "Accounting Edit Entry"));

            case Permissions.AccountModule:
                return(Lans.g("enumPermissions", "Account Module"));

            case Permissions.AdjustmentCreate:
                return(Lans.g("enumPermissions", "Adjustment Create"));

            case Permissions.AdjustmentEdit:
                return(Lans.g("enumPermissions", "Adjustment Edit"));

            case Permissions.AdjustmentEditZero:
                return(Lans.g("enumPermissions", "Adjustment Edit Zero Amount"));

            case Permissions.AnesthesiaIntakeMeds:
                return(Lans.g("enumPermissions", "Intake Anesthetic Medications into Inventory"));

            case Permissions.AnesthesiaControlMeds:
                return(Lans.g("enumPermissions", "Edit Anesthetic Records; Edit/Adjust Inventory Counts"));

            case Permissions.AppointmentCreate:
                return(Lans.g("enumPermissions", "Appointment Create"));

            case Permissions.AppointmentEdit:
                return(Lans.g("enumPermissions", "Appointment Edit"));

            case Permissions.AppointmentMove:
                return(Lans.g("enumPermissions", "Appointment Move"));

            case Permissions.AppointmentsModule:
                return(Lans.g("enumPermissions", "Appointments Module"));

            case Permissions.AutoNoteQuickNoteEdit:
                return(Lans.g("enumPermissions", "Auto/Quick Note Edit"));

            case Permissions.EcwAppointmentRevise:
                return(Lans.g("enumPermissions", "eCW Appointment Revise"));

            case Permissions.Backup:
                return(Lans.g("enumPermissions", "Backup"));

            case Permissions.Billing:
                return(Lans.g("enumPermissions", "Billing"));

            case Permissions.Blockouts:
                return(Lans.g("enumPermissions", "Blockouts"));

            case Permissions.ChartModule:
                return(Lans.g("enumPermissions", "Chart Module"));

            case Permissions.CarrierCreate:
                return(Lans.g("enumPermissions", "Carrier Create"));

            case Permissions.ChooseDatabase:
                return(Lans.g("enumPermissions", "Choose Database"));

            case Permissions.ClaimSentEdit:
                return(Lans.g("enumPermissions", "Claim Sent Edit"));

            case Permissions.CommlogEdit:
                return(Lans.g("enumPermissions", "Commlog Edit"));

            case Permissions.DepositSlips:
                return(Lans.g("enumPermissions", "Deposit Slips"));

            case Permissions.EhrEmergencyAccess:
                return(Lans.g("enumPermissions", "EHR Emergency Access"));

            //case Permissions.EhrInfoButton:
            //	return Lans.g("enumPermissions","EHR Access Info Button");
            //case Permissions.EhrShowCDS:
            //	return Lans.g("enumPermissions","EHR Show Clinical Decision Support");
            case Permissions.EquipmentDelete:
                return(Lans.g("enumPermissions", "Equipment Delete"));

            case Permissions.EquipmentSetup:
                return(Lans.g("enumPermissions", "Equipment Setup"));

            case Permissions.FamilyModule:
                return(Lans.g("enumPermissions", "Family Module"));

            case Permissions.ImageDelete:
                return(Lans.g("enumPermissions", "Image Delete"));

            case Permissions.ImagesModule:
                return(Lans.g("enumPermissions", "Images Module"));

            case Permissions.InsPayCreate:
                return(Lans.g("enumPermissions", "Insurance Payment Create"));

            case Permissions.InsPayEdit:
                return(Lans.g("enumPermissions", "Insurance Payment Edit"));

            case Permissions.InsPlanChangeSubsc:
                return(Lans.g("enumPermissions", "Insurance Plan Change Subscriber"));

            case Permissions.ManageModule:
                return(Lans.g("enumPermissions", "Manage Module"));

            case Permissions.None:
                return("");

            case Permissions.PaymentCreate:
                return(Lans.g("enumPermissions", "Payment Create"));

            case Permissions.PaymentEdit:
                return(Lans.g("enumPermissions", "Payment Edit"));

            case Permissions.PerioEdit:
                return(Lans.g("enumPermissions", "Perio Chart Edit"));

            case Permissions.ProblemEdit:
                return(Lans.g("enumPermissions", "Problem Edit"));

            case Permissions.ProcComplCreate:
                return(Lans.g("enumPermissions", "Create Completed Procedure (or set complete)"));

            case Permissions.ProcedureNote:
                return(Lans.g("enumPermissions", "Procedure Note"));

            case Permissions.ProcDelete:
                return(Lans.g("enumPermissions", "Delete Procedure"));

            case Permissions.ProcComplEdit:
                return(Lans.g("enumPermissions", "Edit Completed Procedure"));

            case Permissions.ProcEditShowFee:
                return(Lans.g("enumPermissions", "Show Procedure Fee"));

            case Permissions.Providers:
                return(Lans.g("enumPermissions", "Providers"));

            case Permissions.Reports:
                return(Lans.g("enumPermissions", "Reports"));

            case Permissions.RefAttachAdd:
                return(Lans.g("enumPermissions", "Referral, Add to Patient"));

            case Permissions.RefAttachDelete:
                return(Lans.g("enumPermissions", "Referral, Delete from Patient"));

            case Permissions.ReferralAdd:
                return(Lans.g("enumPermissions", "Referral Add"));

            case Permissions.RxCreate:
                return(Lans.g("enumPermissions", "Rx Create"));

            case Permissions.Schedules:
                return(Lans.g("enumPermissions", "Schedules - Practice and Provider"));

            case Permissions.SecurityAdmin:
                return(Lans.g("enumPermissions", "Security Admin"));

            case Permissions.Setup:
                return(Lans.g("enumPermissions", "Setup - Covers a wide variety of setup functions"));

            case Permissions.SheetEdit:
                return(Lans.g("enumPermissions", "Sheet Edit"));

            case Permissions.TimecardDeleteEntry:
                return(Lans.g("enumPermissions", "Timecard Delete Entry"));

            case Permissions.TimecardsEditAll:
                return(Lans.g("enumPermissions", "Edit All Timecards"));

            case Permissions.TPModule:
                return(Lans.g("enumPermissions", "TreatmentPlan Module"));

            case Permissions.TreatPlanEdit:
                return(Lans.g("enumPermissions", "Edit Treatment Plan"));

            case Permissions.UserQuery:
                return(Lans.g("enumPermissions", "User Query"));

            case Permissions.ReportProdInc:
                return(Lans.g("enumPermissions", "Reports - Production and Income, Aging"));

            case Permissions.ReportDashboard:
                return(Lans.g("enumPermissions", "Reports - Dashboard"));

            case Permissions.TaskEdit:
                return(Lans.g("enumPermissions", "Task Edit"));

            case Permissions.WikiListSetup:
                return(Lans.g("enumPermissions", "Wiki List Setup"));
            }
            return("");           //should never happen
        }
Exemple #2
0
        ///<summary>Gets data for the history grid in the SendClaims window.</summary>
        public static DataTable RefreshHistory(DateTime dateFrom, DateTime dateTo)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetTable(MethodBase.GetCurrentMethod(), dateFrom, dateTo));
            }
            string command = "Select CONCAT(CONCAT(patient.LName,', '),patient.FName) AS PatName,carrier.CarrierName,"
                             + "clearinghouse.Description AS Clearinghouse,DateTimeTrans,etrans.OfficeSequenceNumber,"
                             + "etrans.CarrierTransCounter,Etype,etrans.ClaimNum,etrans.EtransNum,etrans.AckCode,etrans.Note "
                             + "FROM etrans "
                             + "LEFT JOIN carrier ON etrans.CarrierNum=carrier.CarrierNum "
                             + "LEFT JOIN patient ON patient.PatNum=etrans.PatNum "
                             + "LEFT JOIN clearinghouse ON clearinghouse.ClearinghouseNum=etrans.ClearinghouseNum WHERE "
                             //if(DataConnection.DBtype==DatabaseType.Oracle){
                             //	command+="TO_";
                             //}
                             + DbHelper.DateColumn("DateTimeTrans") + " >= " + POut.Date(dateFrom) + " AND "
                             //if(DataConnection.DBtype==DatabaseType.Oracle){
                             //	command+="TO_";
                             //}
                             + DbHelper.DateColumn("DateTimeTrans") + " <= " + POut.Date(dateTo) + " "
                             + "AND Etype!=" + POut.Long((int)EtransType.Acknowledge_997) + " "
                             + "AND Etype!=" + POut.Long((int)EtransType.BenefitInquiry270) + " "
                             + "AND Etype!=" + POut.Long((int)EtransType.BenefitResponse271) + " "
                             + "AND Etype!=" + POut.Long((int)EtransType.AckError) + " "
                                                                                                   //We exclude canadian transaction response types, since the responses can be accessed from the request transaction inside of the claim history portion of FormSendClaims.
                             + "AND Etype!=" + POut.Long((int)EtransType.ClaimAck_CA) + " "        //Could be attached to a claim, cob claim or ROT.
                             + "AND Etype!=" + POut.Long((int)EtransType.ClaimEOB_CA) + " "        //Could be attached to a claim, cob claim or ROT.
                             + "AND Etype!=" + POut.Long((int)EtransType.EligResponse_CA) + " "    //Will always be attached to an Eligibility request.
                             + "AND Etype!=" + POut.Long((int)EtransType.EmailResponse_CA) + " "   //Will always be attached to a Request for Outstanding Transactions (ROT).
                             + "AND Etype!=" + POut.Long((int)EtransType.OutstandingAck_CA) + " "  //Will always be attached to an ROT.
                             + "AND Etype!=" + POut.Long((int)EtransType.PaymentResponse_CA) + " " //Will always be attached to a Request for Payment Reconciliation (RPR).
                             + "AND Etype!=" + POut.Long((int)EtransType.PredetermAck_CA) + " "    //Could be attached to a Predetermination request or an ROT.
                             + "AND Etype!=" + POut.Long((int)EtransType.PredetermEOB_CA) + " "    //Could be attached to a Predetermination request or an ROT.
                             + "AND Etype!=" + POut.Long((int)EtransType.ReverseResponse_CA) + " " //Will always be attached to a Reversal request.
                             + "AND Etype!=" + POut.Long((int)EtransType.SummaryResponse_CA) + " " //Will always be attached to a Request for Summary Reconciliation (RSR).
                             + "ORDER BY DateTimeTrans";
            DataTable table = Db.GetTable(command);
            DataTable tHist = new DataTable("Table");

            tHist.Columns.Add("patName");
            tHist.Columns.Add("CarrierName");
            tHist.Columns.Add("Clearinghouse");
            tHist.Columns.Add("dateTimeTrans");
            tHist.Columns.Add("OfficeSequenceNumber");
            tHist.Columns.Add("CarrierTransCounter");
            tHist.Columns.Add("etype");
            tHist.Columns.Add("Etype");
            tHist.Columns.Add("ClaimNum");
            tHist.Columns.Add("EtransNum");
            tHist.Columns.Add("ack");
            tHist.Columns.Add("Note");
            DataRow row;
            string  etype;

            for (int i = 0; i < table.Rows.Count; i++)
            {
                row                         = tHist.NewRow();
                row["patName"]              = table.Rows[i]["PatName"].ToString();
                row["CarrierName"]          = table.Rows[i]["CarrierName"].ToString();
                row["Clearinghouse"]        = table.Rows[i]["Clearinghouse"].ToString();
                row["dateTimeTrans"]        = PIn.DateT(table.Rows[i]["DateTimeTrans"].ToString()).ToShortDateString();
                row["OfficeSequenceNumber"] = table.Rows[i]["OfficeSequenceNumber"].ToString();
                row["CarrierTransCounter"]  = table.Rows[i]["CarrierTransCounter"].ToString();
                row["Etype"]                = table.Rows[i]["Etype"].ToString();
                etype                       = Lans.g("enumEtransType", ((EtransType)PIn.Long(table.Rows[i]["Etype"].ToString())).ToString());
                if (etype.EndsWith("_CA"))
                {
                    etype = etype.Substring(0, etype.Length - 3);
                }
                row["etype"]     = etype;
                row["ClaimNum"]  = table.Rows[i]["ClaimNum"].ToString();
                row["EtransNum"] = table.Rows[i]["EtransNum"].ToString();
                if (table.Rows[i]["AckCode"].ToString() == "A")
                {
                    row["ack"] = Lans.g("Etrans", "Accepted");
                }
                else if (table.Rows[i]["AckCode"].ToString() == "R")
                {
                    row["ack"] = Lans.g("Etrans", "Rejected");
                }
                row["Note"] = table.Rows[i]["Note"].ToString();
                tHist.Rows.Add(row);
            }
            return(tHist);
        }
Exemple #3
0
 ///<summary>Checks dependencies first.  Throws exception if can't delete.</summary>
 public static void Delete(Clinic clinic)
 {
     if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
     {
         Meth.GetVoid(MethodBase.GetCurrentMethod(), clinic);
         return;
     }
     //Check FK dependencies.
     #region Patients
     string command = "SELECT LName,FName FROM patient WHERE ClinicNum ="
                      + POut.Long(clinic.ClinicNum);
     DataTable table = Db.GetTable(command);
     if (table.Rows.Count > 0)
     {
         string pats = "";
         for (int i = 0; i < table.Rows.Count; i++)
         {
             pats += "\r";
             if (i == 15)
             {
                 pats += Lans.g("Clinics", "And") + " " + (table.Rows.Count - i) + " " + Lans.g("Clinics", "others");
                 break;
             }
             pats += table.Rows[i]["LName"].ToString() + ", " + table.Rows[i]["FName"].ToString();
         }
         throw new Exception(Lans.g("Clinics", "Cannot delete clinic because it is in use by the following patients:") + pats);
     }
     #endregion
     #region Payments
     command = "SELECT patient.LName,patient.FName FROM patient,payment "
               + "WHERE payment.ClinicNum =" + POut.Long(clinic.ClinicNum)
               + " AND patient.PatNum=payment.PatNum";
     table = Db.GetTable(command);
     if (table.Rows.Count > 0)
     {
         string pats = "";
         for (int i = 0; i < table.Rows.Count; i++)
         {
             pats += "\r";
             if (i == 15)
             {
                 pats += Lans.g("Clinics", "And") + " " + (table.Rows.Count - i) + " " + Lans.g("Clinics", "others");
                 break;
             }
             pats += table.Rows[i]["LName"].ToString() + ", " + table.Rows[i]["FName"].ToString();
         }
         throw new Exception(Lans.g("Clinics", "Cannot delete clinic because the following patients have payments using it:") + pats);
     }
     #endregion
     #region ClaimPayments
     command = "SELECT patient.LName,patient.FName FROM patient,claimproc,claimpayment "
               + "WHERE claimpayment.ClinicNum =" + POut.Long(clinic.ClinicNum)
               + " AND patient.PatNum=claimproc.PatNum"
               + " AND claimproc.ClaimPaymentNum=claimpayment.ClaimPaymentNum "
               + "GROUP BY patient.LName,patient.FName,claimpayment.ClaimPaymentNum";
     table = Db.GetTable(command);
     if (table.Rows.Count > 0)
     {
         string pats = "";
         for (int i = 0; i < table.Rows.Count; i++)
         {
             pats += "\r";
             if (i == 15)
             {
                 pats += Lans.g("Clinics", "And") + " " + (table.Rows.Count - i) + " " + Lans.g("Clinics", "others");
                 break;
             }
             pats += table.Rows[i]["LName"].ToString() + ", " + table.Rows[i]["FName"].ToString();
         }
         throw new Exception(Lans.g("Clinics", "Cannot delete clinic because the following patients have claim payments using it:") + pats);
     }
     #endregion
     #region Appointments
     command = "SELECT patient.LName,patient.FName FROM patient,appointment "
               + "WHERE appointment.ClinicNum =" + POut.Long(clinic.ClinicNum)
               + " AND patient.PatNum=appointment.PatNum";
     table = Db.GetTable(command);
     if (table.Rows.Count > 0)
     {
         string pats = "";
         for (int i = 0; i < table.Rows.Count; i++)
         {
             pats += "\r";
             if (i == 15)
             {
                 pats += Lans.g("Clinics", "And") + " " + (table.Rows.Count - i) + " " + Lans.g("Clinics", "others");
                 break;
             }
             pats += table.Rows[i]["LName"].ToString() + ", " + table.Rows[i]["FName"].ToString();
         }
         throw new Exception(Lans.g("Clinics", "Cannot delete clinic because the following patients have appointments using it:") + pats);
     }
     #endregion
     #region Procedures
     //reassign procedure.ClinicNum=0 if the procs are status D.
     command = "SELECT ProcNum FROM procedurelog WHERE ProcStatus=" + POut.Int((int)ProcStat.D) + " AND ClinicNum=" + POut.Long(clinic.ClinicNum);
     List <long> listProcNums = Db.GetListLong(command);
     if (listProcNums.Count > 0)
     {
         command = "UPDATE procedurelog SET ClinicNum=0 WHERE ProcNum IN (" + string.Join(",", listProcNums.Select(x => POut.Long(x))) + ")";
         Db.NonQ(command);
     }
     command = "SELECT patient.LName,patient.FName FROM patient,procedurelog "
               + "WHERE procedurelog.ClinicNum =" + POut.Long(clinic.ClinicNum)
               + " AND patient.PatNum=procedurelog.PatNum";
     table = Db.GetTable(command);
     if (table.Rows.Count > 0)
     {
         string pats = "";
         for (int i = 0; i < table.Rows.Count; i++)
         {
             pats += "\r";
             if (i == 15)
             {
                 pats += Lans.g("Clinics", "And") + " " + (table.Rows.Count - i) + " " + Lans.g("Clinics", "others");
                 break;
             }
             pats += table.Rows[i]["LName"].ToString() + ", " + table.Rows[i]["FName"].ToString();
         }
         throw new Exception(Lans.g("Clinics", "Cannot delete clinic because the following patients have procedures using it:") + pats);
     }
     #endregion
     #region Operatories
     command = "SELECT OpName FROM operatory "
               + "WHERE ClinicNum =" + POut.Long(clinic.ClinicNum);
     table = Db.GetTable(command);
     if (table.Rows.Count > 0)
     {
         string ops = "";
         for (int i = 0; i < table.Rows.Count; i++)
         {
             ops += "\r";
             if (i == 15)
             {
                 ops += Lans.g("Clinics", "And") + " " + (table.Rows.Count - i) + " " + Lans.g("Clinics", "others");
                 break;
             }
             ops += table.Rows[i]["OpName"].ToString();
         }
         throw new Exception(Lans.g("Clinics", "Cannot delete clinic because the following operatories are using it:") + ops);
     }
     #endregion
     #region Userod
     command = "SELECT UserName FROM userod "
               + "WHERE ClinicNum =" + POut.Long(clinic.ClinicNum);
     table = Db.GetTable(command);
     if (table.Rows.Count > 0)
     {
         string userNames = "";
         for (int i = 0; i < table.Rows.Count; i++)
         {
             userNames += "\r";
             if (i == 15)
             {
                 userNames += Lans.g("Clinics", "And") + " " + (table.Rows.Count - i) + " " + Lans.g("Clinics", "others");
                 break;
             }
             userNames += table.Rows[i]["UserName"].ToString();
         }
         throw new Exception(Lans.g("Clinics", "Cannot delete clinic because the following Open Dental users are using it:") + userNames);
     }
     #endregion
     #region AlertSub
     command = "SELECT DISTINCT UserNum FROM AlertSub "
               + "WHERE ClinicNum =" + POut.Long(clinic.ClinicNum);
     table = Db.GetTable(command);
     if (table.Rows.Count > 0)
     {
         List <string> listUsers = new List <string>();
         for (int i = 0; i < table.Rows.Count; i++)
         {
             long   userNum = PIn.Long(table.Rows[i]["UserNum"].ToString());
             Userod user    = Userods.GetUser(userNum);
             if (user == null)                   //Should not happen.
             {
                 continue;
             }
             listUsers.Add(user.UserName);
         }
         throw new Exception(Lans.g("Clinics", "Cannot delete clinic because the following Open Dental users are subscribed to it:") + "\r" + String.Join("\r", listUsers.OrderBy(x => x).ToArray()));
     }
     #endregion
     #region UserClinics
     command = "SELECT userod.UserName FROM userclinic INNER JOIN userod ON userclinic.UserNum=userod.UserNum "
               + "WHERE userclinic.ClinicNum=" + POut.Long(clinic.ClinicNum);
     table = Db.GetTable(command);
     if (table.Rows.Count > 0)
     {
         string users = "";
         for (int i = 0; i < table.Rows.Count; i++)
         {
             if (i > 0)
             {
                 users += ",";
             }
             users += table.Rows[i][0].ToString();
         }
         throw new Exception(
                   Lans.g("Clinics", "Cannot delete clinic because the following users are restricted to this clinic in security setup:") + " " + users);
     }
     #endregion
     //End checking for dependencies.
     //Clinic is not being used, OK to delete.
     //Delete clinic specific program properties.
     command = "DELETE FROM programproperty WHERE ClinicNum=" + POut.Long(clinic.ClinicNum) + " AND ClinicNum!=0";      //just in case a programming error tries to delete an invalid clinic.
     Db.NonQ(command);
     Crud.ClinicCrud.Delete(clinic.ClinicNum);
 }
Exemple #4
0
        ///<summary>CAUTION.  This does not perform all validations.  Throws exceptions.</summary>
        public static void Delete(Def def)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                Meth.GetVoid(MethodBase.GetCurrentMethod(), def);
                return;
            }
            string        command;
            List <string> listCommands = new List <string>();

            switch (def.Category)
            {
            case DefCat.ClaimCustomTracking:
                listCommands.Add("SELECT COUNT(*) FROM securitylog WHERE DefNum=" + POut.Long(def.DefNum));
                listCommands.Add("SELECT COUNT(*) FROM claim WHERE CustomTracking=" + POut.Long(def.DefNum));
                break;

            case DefCat.ClaimErrorCode:
                listCommands.Add("SELECT COUNT(*) FROM claimtracking WHERE TrackingErrorDefNum=" + POut.Long(def.DefNum));
                break;

            case DefCat.InsurancePaymentType:
                listCommands.Add("SELECT COUNT(*) FROM claimpayment WHERE PayType=" + POut.Long(def.DefNum));
                break;

            case DefCat.SupplyCats:
                listCommands.Add("SELECT COUNT(*) FROM supply WHERE Category=" + POut.Long(def.DefNum));
                break;

            case DefCat.AccountQuickCharge:
                break;                        //Users can delete AcctProcQuickCharge entries.  Nothing has an FKey to a AcctProcQuickCharge Def so no need to check anything.

            case DefCat.AutoNoteCats:
                AutoNotes.RemoveFromCategory(def.DefNum);                                                  //set any autonotes assinged to this category to 0 (unassigned), user already warned about this
                listCommands.Add("SELECT COUNT(*) FROM autonote WHERE Category=" + POut.Long(def.DefNum)); //just in case update failed or concurrency issue
                break;

            case DefCat.WebSchedNewPatApptTypes:
                //Do not let the user delete the last WebSchedNewPatApptTypes definition.  Must be at least one.
                command = "SELECT COUNT(*) FROM definition WHERE Category=" + POut.Int((int)DefCat.WebSchedNewPatApptTypes);
                if (PIn.Int(Db.GetCount(command), false) <= 1)
                {
                    throw new ApplicationException("NOT Allowed to delete the last def of this type.");
                }
                break;

            default:
                throw new ApplicationException("NOT Allowed to delete this type of def.");
            }
            for (int i = 0; i < listCommands.Count; i++)
            {
                if (Db.GetCount(listCommands[i]) != "0")
                {
                    throw new ApplicationException(Lans.g("Defs", "Def is in use.  Not allowed to delete."));
                }
            }
            command = "DELETE FROM definition WHERE DefNum=" + POut.Long(def.DefNum);
            Db.NonQ(command);
            command = "UPDATE definition SET ItemOrder=ItemOrder-1 "
                      + "WHERE Category=" + POut.Long((int)def.Category)
                      + " AND ItemOrder > " + POut.Long(def.ItemOrder);
            Db.NonQ(command);
        }
Exemple #5
0
        ///<summary>Returns the number of subscribers moved.</summary>
        public static long MoveSubscribers(long insPlanNumFrom, long insPlanNumTo)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetLong(MethodBase.GetCurrentMethod(), insPlanNumFrom, insPlanNumTo));
            }
            List <InsSub> listInsSubsFrom    = GetListForPlanNum(insPlanNumFrom);
            List <long>   listBlockedPatNums = new List <long>();

            //Perform the same validation as when the user manually drops insplans from FormInsPlan using the Drop button.
            for (int i = 0; i < listInsSubsFrom.Count; i++)
            {
                InsSub         insSubFrom      = listInsSubsFrom[i];
                List <PatPlan> listPatPlanFrom = PatPlans.Refresh(insSubFrom.Subscriber);
                for (int j = 0; j < listPatPlanFrom.Count; j++)
                {
                    PatPlan patPlanFrom = listPatPlanFrom[j];
                    //The following comments and logic are copied from the FormInsPlan Drop button...
                    //If they have a claim for this ins with today's date, don't let them drop.
                    //We already have code in place to delete claimprocs when we drop ins, but the claimprocs attached to claims are protected.
                    //The claim clearly needs to be deleted if they are dropping.  We need the user to delete the claim before they drop the plan.
                    //We also have code in place to add new claimprocs when they add the correct insurance.
                    List <Claim> listClaims = Claims.Refresh(patPlanFrom.PatNum);                 //Get all claims for patient.
                    for (int k = 0; k < listClaims.Count; k++)
                    {
                        if (listClaims[k].PlanNum != insPlanNumFrom)                       //Make sure the claim is for the insurance plan we are about to change, not any other plans the patient might have.
                        {
                            continue;
                        }
                        if (listClaims[k].DateService != DateTime.Today)                       //not today
                        {
                            continue;
                        }
                        //Patient currently has a claim for the insplan they are trying to drop.
                        if (!listBlockedPatNums.Contains(patPlanFrom.PatNum))
                        {
                            listBlockedPatNums.Add(patPlanFrom.PatNum);
                        }
                    }
                }
            }
            if (listBlockedPatNums.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < listBlockedPatNums.Count; i++)
                {
                    sb.Append("\r\n");
                    Patient pat = Patients.GetPat(listBlockedPatNums[i]);
                    sb.Append("#" + listBlockedPatNums[i] + " " + pat.GetNameFLFormal());
                }
                throw new ApplicationException(Lans.g("InsSubs", "Before changing the subscribers on the insurance plan being moved from, please delete all of today's claims related to the insurance plan being moved from for the following patients") + ":" + sb.ToString());
            }
            //This loop mimics some of the logic in PatPlans.Delete().
            int insSubMovedCount = 0;

            for (int i = 0; i < listInsSubsFrom.Count; i++)
            {
                InsSub inssub       = listInsSubsFrom[i];
                long   oldInsSubNum = inssub.InsSubNum;
                inssub.InsSubNum     = 0;          //This will allow us to insert a new record.
                inssub.PlanNum       = insPlanNumTo;
                inssub.DateEffective = DateTime.MinValue;
                inssub.BenefitNotes  = "";
                inssub.SubscNote     = "";
                //Security.CurUser.UserNum gets set on MT by the DtoProcessor so it matches the user from the client WS.
                inssub.SecUserNumEntry = Security.CurUser.UserNum;
                long      insSubNumNew       = InsSubs.Insert(inssub);
                string    command            = "SELECT PatNum FROM patplan WHERE InsSubNum=" + POut.Long(oldInsSubNum);
                DataTable tablePatsForInsSub = Db.GetTable(command);
                if (tablePatsForInsSub.Rows.Count == 0)
                {
                    continue;
                }
                insSubMovedCount++;
                for (int j = 0; j < tablePatsForInsSub.Rows.Count; j++)
                {
                    long           patNum       = PIn.Long(tablePatsForInsSub.Rows[j]["PatNum"].ToString());
                    List <PatPlan> listPatPlans = PatPlans.Refresh(patNum);
                    for (int k = 0; k < listPatPlans.Count; k++)
                    {
                        PatPlan patPlan = listPatPlans[k];
                        if (patPlan.InsSubNum == oldInsSubNum)
                        {
                            command = "DELETE FROM benefit WHERE PatPlanNum=" + POut.Long(patPlan.PatPlanNum);                         //Delete patient specific benefits (rare).
                            Db.NonQ(command);
                            patPlan.InsSubNum = insSubNumNew;
                            PatPlans.Update(patPlan);
                        }
                    }
                    //Now that the plan has changed for the current subscriber, recalculate estimates.
                    bool prefChanged = false;
                    //Forcefully set pref false to prevent creating new estimates for all procs (including completed, sent procs)
                    if (Prefs.UpdateBool(PrefName.ClaimProcsAllowedToBackdate, false))
                    {
                        prefChanged = true;                      //We will turn the preference back on for the user after we finish our computations.
                    }
                    Family           fam            = Patients.GetFamily(patNum);
                    Patient          pat            = fam.GetPatient(patNum);
                    List <ClaimProc> listClaimProcs = ClaimProcs.Refresh(patNum);
                    List <Procedure> listProcs      = Procedures.GetProcsByStatusForPat(patNum, ProcStat.TP, ProcStat.TPi);
                    listPatPlans = PatPlans.Refresh(patNum);
                    List <InsSub>  listInsSubs  = InsSubs.RefreshForFam(fam);
                    List <InsPlan> listInsPlans = InsPlans.RefreshForSubList(listInsSubs);
                    List <Benefit> listBenefits = Benefits.Refresh(listPatPlans, listInsSubs);
                    Procedures.ComputeEstimatesForAll(patNum, listClaimProcs, listProcs, listInsPlans, listPatPlans, listBenefits, pat.Age, listInsSubs);
                    if (prefChanged)
                    {
                        Prefs.UpdateBool(PrefName.ClaimProcsAllowedToBackdate, true);                       //set back to original value if changed.
                    }
                }
            }
            InsPlan insPlanFrom = InsPlans.RefreshOne(insPlanNumFrom);
            InsPlan planOld     = insPlanFrom.Copy();

            insPlanFrom.IsHidden = true;
            InsPlans.Update(insPlanFrom, planOld);
            return(insSubMovedCount);
        }
Exemple #6
0
        ///<summary>Gets a filtered list of all labcases.</summary>
        public static DataTable Refresh(DateTime aptStartDate, DateTime aptEndDate, bool showCompleted, bool ShowUnattached)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetTable(MethodBase.GetCurrentMethod(), aptStartDate, aptEndDate, showCompleted, ShowUnattached));
            }
            DataTable table = new DataTable();
            DataRow   row;

            //columns that start with lowercase are altered for display rather than being raw data.
            table.Columns.Add("AptDateTime", typeof(DateTime));
            table.Columns.Add("aptDateTime");
            table.Columns.Add("AptNum");
            table.Columns.Add("lab");
            table.Columns.Add("LabCaseNum");
            table.Columns.Add("patient");
            table.Columns.Add("phone");
            table.Columns.Add("ProcDescript");
            table.Columns.Add("status");
            table.Columns.Add("Instructions");
            List <DataRow> rows = new List <DataRow>();
            //the first query only gets labcases that are attached to scheduled appointments
            string command = "SELECT AptDateTime,appointment.AptNum,DateTimeChecked,DateTimeRecd,DateTimeSent,"
                             + "LabCaseNum,laboratory.Description,LName,FName,Preferred,MiddleI,Phone,ProcDescript,Instructions "
                             + "FROM labcase "
                             + "LEFT JOIN appointment ON labcase.AptNum=appointment.AptNum "
                             + "LEFT JOIN patient ON labcase.PatNum=patient.PatNum "
                             + "LEFT JOIN laboratory ON labcase.LaboratoryNum=laboratory.LaboratoryNum "
                             + "WHERE AptDateTime > " + POut.Date(aptStartDate) + " "
                             + "AND AptDateTime < " + POut.Date(aptEndDate.AddDays(1)) + " ";

            if (!showCompleted)
            {
                command += "AND (AptStatus=" + POut.Long((int)ApptStatus.ASAP)
                           + " OR AptStatus=" + POut.Long((int)ApptStatus.Broken)
                           + " OR AptStatus=" + POut.Long((int)ApptStatus.None)
                           + " OR AptStatus=" + POut.Long((int)ApptStatus.Scheduled)
                           + " OR AptStatus=" + POut.Long((int)ApptStatus.UnschedList) + ") ";
            }
            DataTable raw = Db.GetTable(command);
            DateTime  AptDateTime;
            DateTime  date;

            for (int i = 0; i < raw.Rows.Count; i++)
            {
                row                = table.NewRow();
                AptDateTime        = PIn.DateT(raw.Rows[i]["AptDateTime"].ToString());
                row["AptDateTime"] = AptDateTime;
                row["aptDateTime"] = AptDateTime.ToShortDateString() + " " + AptDateTime.ToShortTimeString();
                row["AptNum"]      = raw.Rows[i]["AptNum"].ToString();
                row["lab"]         = raw.Rows[i]["Description"].ToString();
                row["LabCaseNum"]  = raw.Rows[i]["LabCaseNum"].ToString();
                row["patient"]     = PatientLogic.GetNameLF(raw.Rows[i]["LName"].ToString(), raw.Rows[i]["FName"].ToString(),
                                                            raw.Rows[i]["Preferred"].ToString(), raw.Rows[i]["MiddleI"].ToString());
                row["phone"]        = raw.Rows[i]["Phone"].ToString();
                row["ProcDescript"] = raw.Rows[i]["ProcDescript"].ToString();
                row["Instructions"] = raw.Rows[i]["Instructions"].ToString();
                date = PIn.DateT(raw.Rows[i]["DateTimeChecked"].ToString());
                if (date.Year > 1880)
                {
                    row["status"] = Lans.g("FormLabCases", "Quality Checked");
                }
                else
                {
                    date = PIn.DateT(raw.Rows[i]["DateTimeRecd"].ToString());
                    if (date.Year > 1880)
                    {
                        row["status"] = Lans.g("FormLabCases", "Received");
                    }
                    else
                    {
                        date = PIn.DateT(raw.Rows[i]["DateTimeSent"].ToString());
                        if (date.Year > 1880)
                        {
                            row["status"] = Lans.g("FormLabCases", "Sent");                         //sent but not received
                        }
                        else
                        {
                            row["status"] = Lans.g("FormLabCases", "Not Sent");
                        }
                    }
                }
                rows.Add(row);
            }
            if (ShowUnattached)
            {
                //Then, this second query gets labcases not attached to appointments.  No date filter.  No date displayed.
                command = "SELECT DateTimeChecked,DateTimeRecd,DateTimeSent,"
                          + "LabCaseNum,laboratory.Description,LName,FName,Preferred,MiddleI,Phone,Instructions "
                          + "FROM labcase "
                          + "LEFT JOIN patient ON labcase.PatNum=patient.PatNum "
                          + "LEFT JOIN laboratory ON labcase.LaboratoryNum=laboratory.LaboratoryNum "
                          + "WHERE AptNum=0";
                raw = Db.GetTable(command);
                for (int i = 0; i < raw.Rows.Count; i++)
                {
                    row = table.NewRow();
                    row["AptDateTime"] = DateTime.MinValue;
                    row["aptDateTime"] = "";
                    row["AptNum"]      = 0;
                    row["lab"]         = raw.Rows[i]["Description"].ToString();
                    row["LabCaseNum"]  = raw.Rows[i]["LabCaseNum"].ToString();
                    row["patient"]     = PatientLogic.GetNameLF(raw.Rows[i]["LName"].ToString(), raw.Rows[i]["FName"].ToString(),
                                                                raw.Rows[i]["Preferred"].ToString(), raw.Rows[i]["MiddleI"].ToString());
                    row["phone"]        = raw.Rows[i]["Phone"].ToString();
                    row["ProcDescript"] = "";
                    row["status"]       = "";
                    row["Instructions"] = raw.Rows[i]["Instructions"].ToString();
                    date = PIn.DateT(raw.Rows[i]["DateTimeChecked"].ToString());
                    if (date.Year > 1880)
                    {
                        row["status"] = Lans.g("FormLabCases", "Quality Checked");
                    }
                    else
                    {
                        date = PIn.DateT(raw.Rows[i]["DateTimeRecd"].ToString());
                        if (date.Year > 1880)
                        {
                            row["status"] = Lans.g("FormLabCases", "Received");
                        }
                        else
                        {
                            date = PIn.DateT(raw.Rows[i]["DateTimeSent"].ToString());
                            if (date.Year > 1880)
                            {
                                row["status"] = Lans.g("FormLabCases", "Sent");                             //sent but not received
                            }
                            else
                            {
                                row["status"] = Lans.g("FormLabCases", "Not Sent");
                            }
                        }
                    }
                    rows.Add(row);
                }
            }
            LabCaseComparer comparer = new LabCaseComparer();

            rows.Sort(comparer);
            for (int i = 0; i < rows.Count; i++)
            {
                table.Rows.Add(rows[i]);
            }
            return(table);
        }
Exemple #7
0
        ///<summary>only if ClientWeb</summary>
        public static void FillCache(DataSet ds, string itypesStr)
        {
            List <int> itypes = new List <int>();

            string[] strArray = itypesStr.Split(',');
            for (int i = 0; i < strArray.Length; i++)
            {
                itypes.Add(PIn.Int(strArray[i]));
            }
            bool isAll = false;

            if (itypes.Contains((int)InvalidType.AllLocal))
            {
                isAll = true;
            }
            if (itypes.Contains((int)InvalidType.AccountingAutoPays) || isAll)
            {
                AccountingAutoPays.FillCache(ds.Tables["AccountingAutoPay"]);
            }
            if (itypes.Contains((int)InvalidType.AutoCodes) || isAll)
            {
                AutoCodes.FillCache(ds.Tables["AutoCode"]);
                AutoCodeItems.FillCache(ds.Tables["AutoCodeItem"]);
                AutoCodeConds.FillCache(ds.Tables["AutoCodeCond"]);
            }
            if (itypes.Contains((int)InvalidType.Automation) || isAll)
            {
                Automations.FillCache(ds.Tables["Automation"]);
            }
            if (itypes.Contains((int)InvalidType.AutoNotes) || isAll)
            {
                AutoNotes.FillCache(ds.Tables["AutoNote"]);
                AutoNoteControls.FillCache(ds.Tables["AutoNoteControl"]);
            }
            if (itypes.Contains((int)InvalidType.Carriers) || isAll)
            {
                Carriers.FillCache(ds.Tables["Carrier"]);                //run on startup, after telephone reformat, after list edit.
            }
            if (itypes.Contains((int)InvalidType.ClaimForms) || isAll)
            {
                ClaimFormItems.FillCache(ds.Tables["ClaimFormItem"]);
                ClaimForms.FillCache(ds.Tables["ClaimForm"]);
            }
            if (itypes.Contains((int)InvalidType.ClearHouses) || isAll)
            {
                Clearinghouses.FillCache(ds.Tables["Clearinghouse"]);                //kh wants to add an EasyHideClearHouses to disable this
            }
            if (itypes.Contains((int)InvalidType.Computers) || isAll)
            {
                Computers.FillCache(ds.Tables["Computer"]);
                Printers.FillCache(ds.Tables["Printer"]);
            }
            if (itypes.Contains((int)InvalidType.Defs) || isAll)
            {
                Defs.FillCache(ds.Tables["Def"]);
            }
            if (itypes.Contains((int)InvalidType.DentalSchools) || isAll)
            {
                SchoolClasses.FillCache(ds.Tables["SchoolClass"]);
                SchoolCourses.FillCache(ds.Tables["SchoolCourse"]);
            }
            if (itypes.Contains((int)InvalidType.DictCustoms) || isAll)
            {
                DictCustoms.FillCache(ds.Tables["DictCustom"]);
            }
            if (itypes.Contains((int)InvalidType.Diseases) || isAll)
            {
                DiseaseDefs.FillCache(ds.Tables["DiseaseDef"]);
                ICD9s.FillCache(ds.Tables["ICD9"]);
            }
            if (itypes.Contains((int)InvalidType.DisplayFields) || isAll)
            {
                DisplayFields.FillCache(ds.Tables["DisplayField"]);
            }
            if (itypes.Contains((int)InvalidType.ElectIDs) || isAll)
            {
                ElectIDs.FillCache(ds.Tables["ElectID"]);
            }
            if (itypes.Contains((int)InvalidType.Email) || isAll)
            {
                EmailAddresses.FillCache(ds.Tables["EmailAddress"]);
                EmailTemplates.FillCache(ds.Tables["EmailTemplate"]);
            }
            if (itypes.Contains((int)InvalidType.Employees) || isAll)
            {
                Employees.FillCache(ds.Tables["Employee"]);
                PayPeriods.FillCache(ds.Tables["PayPeriod"]);
            }
            if (itypes.Contains((int)InvalidType.Employers) || isAll)
            {
                Employers.FillCache(ds.Tables["Employer"]);
            }
            if (itypes.Contains((int)InvalidType.Fees) || isAll)
            {
                Fees.FillCache(ds.Tables["Fee"]);
            }
            if (itypes.Contains((int)InvalidType.FeeScheds) || isAll)
            {
                FeeScheds.FillCache(ds.Tables["FeeSched"]);
            }
            if (itypes.Contains((int)InvalidType.HL7Defs) || isAll)
            {
                HL7Defs.FillCache(ds.Tables["HL7Def"]);
                HL7DefMessages.FillCache(ds.Tables["HL7DefMessage"]);
                HL7DefSegments.FillCache(ds.Tables["HL7DefSegment"]);
                HL7DefFields.FillCache(ds.Tables["HL7DefField"]);
            }
            if (itypes.Contains((int)InvalidType.InsCats) || isAll)
            {
                CovCats.FillCache(ds.Tables["CovCat"]);
                CovSpans.FillCache(ds.Tables["CovSpan"]);
            }
            if (itypes.Contains((int)InvalidType.InsFilingCodes) || isAll)
            {
                InsFilingCodes.FillCache(ds.Tables["InsFilingCode"]);
                InsFilingCodeSubtypes.FillCache(ds.Tables["InsFilingCodeSubtype"]);
            }
            if (itypes.Contains((int)InvalidType.Languages) || isAll)
            {
                Lans.FillCache(ds.Tables["Language"]);
            }
            if (itypes.Contains((int)InvalidType.Letters) || isAll)
            {
                Letters.FillCache(ds.Tables["Letter"]);
            }
            if (itypes.Contains((int)InvalidType.LetterMerge) || isAll)
            {
                LetterMergeFields.FillCache(ds.Tables["LetterMergeField"]);
                LetterMerges.FillCache(ds.Tables["LetterMerge"]);
            }
            if (itypes.Contains((int)InvalidType.Operatories) || isAll)
            {
                Operatories.FillCache(ds.Tables["Operatory"]);
            }
            if (itypes.Contains((int)InvalidType.PatFields) || isAll)
            {
                PatFieldDefs.FillCache(ds.Tables["PatFieldDef"]);
                ApptFieldDefs.FillCache(ds.Tables["ApptFieldDef"]);
            }
            if (itypes.Contains((int)InvalidType.Pharmacies) || isAll)
            {
                Pharmacies.FillCache(ds.Tables["Pharmacy"]);
            }
            if (itypes.Contains((int)InvalidType.Prefs) || isAll)
            {
                Prefs.FillCache(ds.Tables["Pref"]);
            }
            if (itypes.Contains((int)InvalidType.ProcButtons) || isAll)
            {
                ProcButtons.FillCache(ds.Tables["ProcButton"]);
                ProcButtonItems.FillCache(ds.Tables["ProcButtonItem"]);
            }
            if (itypes.Contains((int)InvalidType.ProcCodes) || isAll)
            {
                ProcedureCodes.FillCache(ds.Tables["ProcedureCode"]);
                ProcCodeNotes.FillCache(ds.Tables["ProcCodeNote"]);
            }
            if (itypes.Contains((int)InvalidType.Programs) || isAll)
            {
                Programs.FillCache(ds.Tables["Program"]);
                ProgramProperties.FillCache(ds.Tables["ProgramProperty"]);
            }
            if (itypes.Contains((int)InvalidType.ProviderIdents) || isAll)
            {
                ProviderIdents.FillCache(ds.Tables["ProviderIdent"]);
            }
            if (itypes.Contains((int)InvalidType.Providers) || isAll)
            {
                Providers.FillCache(ds.Tables["Provider"]);
            }
            if (itypes.Contains((int)InvalidType.QuickPaste) || isAll)
            {
                QuickPasteNotes.FillCache(ds.Tables["QuickPasteNote"]);
                QuickPasteCats.FillCache(ds.Tables["QuickPasteCat"]);
            }
            if (itypes.Contains((int)InvalidType.RecallTypes) || isAll)
            {
                RecallTypes.FillCache(ds.Tables["RecallType"]);
                RecallTriggers.FillCache(ds.Tables["RecallTrigger"]);
            }
            if (itypes.Contains((int)InvalidType.ReplicationServers) || isAll)
            {
                ReplicationServers.FillCache(ds.Tables["ReplicationServer"]);
            }
            if (itypes.Contains((int)InvalidType.Security) || isAll)
            {
                Userods.FillCache(ds.Tables["Userod"]);
                UserGroups.FillCache(ds.Tables["UserGroup"]);
            }
            if (itypes.Contains((int)InvalidType.Sheets) || isAll)
            {
                SheetDefs.FillCache(ds.Tables["SheetDef"]);
                SheetFieldDefs.FillCache(ds.Tables["SheetFieldDef"]);
            }
            if (itypes.Contains((int)InvalidType.Signals) || isAll)
            {
                SigElementDefs.FillCache(ds.Tables["SigElementDef"]);
                SigButDefs.FillCache(ds.Tables["SigButDef"]);                //includes SigButDefElements.Refresh()
            }
            if (itypes.Contains((int)InvalidType.Sites) || isAll)
            {
                Sites.FillCache(ds.Tables["Site"]);
            }
            if (itypes.Contains((int)InvalidType.Sops) || isAll)
            {
                Sops.FillCache(ds.Tables["Sop"]);
            }
            if (itypes.Contains((int)InvalidType.TimeCardRules) || isAll)
            {
                TimeCardRules.FillCache(ds.Tables["TimeCardRule"]);
            }
            //InvalidTypes.Tasks not handled here.
            if (itypes.Contains((int)InvalidType.ToolBut) || isAll)
            {
                ToolButItems.FillCache(ds.Tables["ToolButItem"]);
            }
            if (itypes.Contains((int)InvalidType.Vaccines) || isAll)
            {
                VaccineDefs.FillCache(ds.Tables["VaccineDef"]);
                DrugManufacturers.FillCache(ds.Tables["DrugManufacturer"]);
                DrugUnits.FillCache(ds.Tables["DrugUnit"]);
            }
            if (itypes.Contains((int)InvalidType.Views) || isAll)
            {
                ApptViews.FillCache(ds.Tables["ApptView"]);
                ApptViewItems.FillCache(ds.Tables["ApptViewItem"]);
                AppointmentRules.FillCache(ds.Tables["AppointmentRule"]);
                ProcApptColors.FillCache(ds.Tables["ProcApptColor"]);
            }
            if (itypes.Contains((int)InvalidType.Wiki) || isAll)
            {
                WikiListHeaderWidths.FillCache(ds.Tables["WikiListHeaderWidth"]);
                WikiPages.FillCache(ds.Tables["WikiPage"]);
            }
            if (itypes.Contains((int)InvalidType.ZipCodes) || isAll)
            {
                ZipCodes.FillCache(ds.Tables["ZipCode"]);
            }
        }
Exemple #8
0
        ///<summary>Only called once from FormPayment when trying to change an amount or an account on a payment that's already linked to the Accounting section or when trying to create a new link.  This automates updating the Accounting section.  Do not surround with try-catch, because it was already validated in ValidateLinkedEntries above.  Use -1 for newAcct to indicate no changed. The name is required to give descriptions to new entries.</summary>
        public static void AlterLinkedEntries(double oldAmt, double newAmt, bool isNew, long payNum, long newAcct, DateTime payDate,
                                              string patName)
        {
            //No need to check RemotingRole; no call to db.
            if (!Accounts.PaymentsLinked())
            {
                return;                //user has not even set up accounting links.
            }
            bool amtChanged = false;

            if (oldAmt != newAmt)
            {
                amtChanged = true;
            }
            Transaction trans  = Transactions.GetAttachedToPayment(payNum); //this gives us the oldAcctNum
            double      absNew = newAmt;                                    //absolute value of the new amount

            if (newAmt < 0)
            {
                absNew = -newAmt;
            }
            //if(trans==null && (newAcct==0 || newAcct==-1)) {//then this method will not even be called
            if (trans == null)           //no previous link, but user is trying to create one.
            //this is the only case where a new trans is required.
            {
                trans         = new Transaction();
                trans.PayNum  = payNum;
                trans.UserNum = Security.CurUser.UserNum;
                Transactions.Insert(trans);                //sets entry date
                //first the deposit entry
                JournalEntry je = new JournalEntry();
                je.AccountNum    = newAcct;        //DepositAccounts[comboDepositAccount.SelectedIndex];
                je.CheckNumber   = Lans.g("Payments", "DEP");
                je.DateDisplayed = payDate;        //it would be nice to add security here.
                if (absNew == newAmt)              //amount is positive
                {
                    je.DebitAmt = newAmt;
                }
                else
                {
                    je.CreditAmt = absNew;
                }
                je.Memo           = Lans.g("Payments", "Payment -") + " " + patName;
                je.Splits         = Accounts.GetDescript(PrefC.GetLong(PrefName.AccountingCashIncomeAccount));
                je.TransactionNum = trans.TransactionNum;
                JournalEntries.Insert(je);
                //then, the income entry
                je            = new JournalEntry();
                je.AccountNum = PrefC.GetLong(PrefName.AccountingCashIncomeAccount);
                //je.CheckNumber=;
                je.DateDisplayed = payDate;         //it would be nice to add security here.
                if (absNew == newAmt)               //amount is positive
                {
                    je.CreditAmt = newAmt;
                }
                else
                {
                    je.DebitAmt = absNew;
                }
                je.Memo           = Lans.g("Payments", "Payment -") + " " + patName;
                je.Splits         = Accounts.GetDescript(newAcct);
                je.TransactionNum = trans.TransactionNum;
                JournalEntries.Insert(je);
                return;
            }
            //at this point, we have established that there is a previous transaction.
            List <JournalEntry> jeL  = JournalEntries.GetForTrans(trans.TransactionNum);
            long         oldAcct     = 0;
            JournalEntry jeDebit     = null;
            JournalEntry jeCredit    = null;
            bool         signChanged = false;
            double       absOld      = oldAmt;//the absolute value of the old amount

            if (oldAmt < 0)
            {
                absOld = -oldAmt;
            }
            if (oldAmt < 0 && newAmt > 0)
            {
                signChanged = true;
            }
            if (oldAmt > 0 && newAmt < 0)
            {
                signChanged = true;
            }
            for (int i = 0; i < 2; i++)
            {
                if (Accounts.GetAccount(jeL[i].AccountNum).AcctType == AccountType.Asset)
                {
                    oldAcct = jeL[i].AccountNum;
                }
                if (jeL[i].DebitAmt == absOld)
                {
                    jeDebit = jeL[i];
                }
                //old credit entry
                if (jeL[i].CreditAmt == absOld)
                {
                    jeCredit = jeL[i];
                }
            }
            //Already validated that both je's are not null, and that oldAcct is not 0.
            if (newAcct == 0)          //detaching it from a linked transaction. We will delete the transaction
            //we don't care about the amount
            {
                Transactions.Delete(trans);                //we need to make sure this doesn't throw any exceptions by carefully checking all
                //possibilities in the validation routine above.
                return;
            }
            //Either the amount or the account changed on an existing linked transaction.
            bool acctChanged = false;

            if (newAcct != -1 && oldAcct != newAcct)
            {
                acctChanged = true;              //changing linked acctNum
            }
            if (amtChanged)
            {
                if (signChanged)
                {
                    jeDebit.DebitAmt   = 0;
                    jeDebit.CreditAmt  = absNew;
                    jeCredit.DebitAmt  = absNew;
                    jeCredit.CreditAmt = 0;
                }
                else
                {
                    jeDebit.DebitAmt   = absNew;
                    jeCredit.CreditAmt = absNew;
                }
            }
            if (acctChanged)
            {
                if (jeDebit.AccountNum == oldAcct)
                {
                    jeDebit.AccountNum = newAcct;
                }
                if (jeCredit.AccountNum == oldAcct)
                {
                    jeCredit.AccountNum = newAcct;
                }
            }
            JournalEntries.Update(jeDebit);
            JournalEntries.Update(jeCredit);
        }
Exemple #9
0
        ///<summary>For orderBy, use 0 for BillingType and 1 for PatientName.</summary>
        public static DataTable GetBilling(bool isSent, int orderBy, DateTime dateFrom, DateTime dateTo, long clinicNum)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetTable(MethodBase.GetCurrentMethod(), isSent, orderBy, dateFrom, dateTo, clinicNum));
            }
            DataTable table = new DataTable();
            DataRow   row;

            //columns that start with lowercase are altered for display rather than being raw data.
            table.Columns.Add("amountDue");
            table.Columns.Add("balTotal");
            table.Columns.Add("billingType");
            table.Columns.Add("insEst");
            table.Columns.Add("IsSent");
            table.Columns.Add("lastStatement");
            table.Columns.Add("mode");
            table.Columns.Add("name");
            table.Columns.Add("PatNum");
            table.Columns.Add("payPlanDue");
            table.Columns.Add("StatementNum");
            List <DataRow> rows    = new List <DataRow>();
            string         command = "SELECT BalTotal,BillingType,FName,InsEst,statement.IsSent,"
                                     + "IFNULL(MAX(s2.DateSent)," + POut.Date(DateTime.MinValue) + ") LastStatement,"
                                     + "LName,MiddleI,statement.Mode_,PayPlanDue,Preferred,"
                                     + "statement.PatNum,statement.StatementNum "
                                     + "FROM statement "
                                     + "LEFT JOIN patient ON statement.PatNum=patient.PatNum "
                                     + "LEFT JOIN statement s2 ON s2.PatNum=patient.PatNum "
                                     + "AND s2.IsSent=1 ";

            if (PrefC.GetBool(PrefName.BillingIgnoreInPerson))
            {
                command += "AND s2.Mode_ !=1 ";
            }
            if (orderBy == 0)          //BillingType
            {
                command += "LEFT JOIN definition ON patient.BillingType=definition.DefNum ";
            }
            command += "WHERE statement.IsSent=" + POut.Bool(isSent) + " ";
            //if(dateFrom.Year>1800){
            command += "AND statement.DateSent>=" + POut.Date(dateFrom) + " ";      //greater than midnight this morning
            //}
            //if(dateFrom.Year>1800){
            command += "AND statement.DateSent<" + POut.Date(dateTo.AddDays(1)) + " ";      //less than midnight tonight
            //}
            if (clinicNum > 0)
            {
                command += "AND patient.ClinicNum=" + clinicNum + " ";
            }
            command += "GROUP BY BalTotal,BillingType,FName,InsEst,statement.IsSent,"
                       + "LName,MiddleI,statement.Mode_,PayPlanDue,Preferred,"
                       + "statement.PatNum,statement.StatementNum ";
            if (orderBy == 0)          //BillingType
            {
                command += "ORDER BY definition.ItemOrder,LName,FName,MiddleI,PayPlanDue";
            }
            else
            {
                command += "ORDER BY LName,FName";
            }
            DataTable     rawTable = Db.GetTable(command);
            Patient       pat;
            StatementMode mode;
            double        balTotal;
            double        insEst;
            double        payPlanDue;
            DateTime      lastStatement;

            for (int i = 0; i < rawTable.Rows.Count; i++)
            {
                row                = table.NewRow();
                balTotal           = PIn.Double(rawTable.Rows[i]["BalTotal"].ToString());
                insEst             = PIn.Double(rawTable.Rows[i]["InsEst"].ToString());
                payPlanDue         = PIn.Double(rawTable.Rows[i]["PayPlanDue"].ToString());
                row["amountDue"]   = (balTotal - insEst).ToString("F");
                row["balTotal"]    = balTotal.ToString("F");;
                row["billingType"] = DefC.GetName(DefCat.BillingTypes, PIn.Long(rawTable.Rows[i]["BillingType"].ToString()));
                if (insEst == 0)
                {
                    row["insEst"] = "";
                }
                else
                {
                    row["insEst"] = insEst.ToString("F");
                }
                row["IsSent"] = rawTable.Rows[i]["IsSent"].ToString();
                lastStatement = PIn.Date(rawTable.Rows[i]["LastStatement"].ToString());
                if (lastStatement.Year < 1880)
                {
                    row["lastStatement"] = "";
                }
                else
                {
                    row["lastStatement"] = lastStatement.ToShortDateString();
                }
                mode          = (StatementMode)PIn.Long(rawTable.Rows[i]["Mode_"].ToString());
                row["mode"]   = Lans.g("enumStatementMode", mode.ToString());
                pat           = new Patient();
                pat.LName     = rawTable.Rows[i]["LName"].ToString();
                pat.FName     = rawTable.Rows[i]["FName"].ToString();
                pat.Preferred = rawTable.Rows[i]["Preferred"].ToString();
                pat.MiddleI   = rawTable.Rows[i]["MiddleI"].ToString();
                row["name"]   = pat.GetNameLF();
                row["PatNum"] = rawTable.Rows[i]["PatNum"].ToString();
                if (payPlanDue == 0)
                {
                    row["payPlanDue"] = "";
                }
                else
                {
                    row["payPlanDue"] = payPlanDue.ToString("F");
                }
                row["StatementNum"] = rawTable.Rows[i]["StatementNum"].ToString();
                rows.Add(row);
            }
            for (int i = 0; i < rows.Count; i++)
            {
                table.Rows.Add(rows[i]);
            }
            return(table);
        }
Exemple #10
0
        ///<summary>Gets the full list to display in the Chart of Accounts, including balances.</summary>
        public static DataTable GetFullList(DateTime asOfDate, bool showInactive)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetTable(MethodBase.GetCurrentMethod(), asOfDate, showInactive));
            }
            DataTable table = new DataTable("Accounts");
            DataRow   row;

            //columns that start with lowercase are altered for display rather than being raw data.
            table.Columns.Add("type");
            table.Columns.Add("Description");
            table.Columns.Add("balance");
            table.Columns.Add("BankNumber");
            table.Columns.Add("inactive");
            table.Columns.Add("color");
            table.Columns.Add("AccountNum");
            //but we won't actually fill this table with rows until the very end.  It's more useful to use a List<> for now.
            List <DataRow> rows = new List <DataRow>();
            //first, the entire history for the asset, liability, and equity accounts (except Retained Earnings)-----------
            string command = "SELECT account.AcctType, account.Description, account.AccountNum, "
                             + "SUM(DebitAmt) AS SumDebit, SUM(CreditAmt) AS SumCredit, account.BankNumber, account.Inactive, account.AccountColor "
                             + "FROM account "
                             + "LEFT JOIN journalentry ON journalentry.AccountNum=account.AccountNum AND "
                             + "DateDisplayed <= " + POut.Date(asOfDate) + " WHERE AcctType<=2 ";

            if (!showInactive)
            {
                command += "AND Inactive=0 ";
            }
            command += "GROUP BY account.AccountNum, account.AcctType, account.Description, account.BankNumber,"
                       + "account.Inactive, account.AccountColor ORDER BY AcctType, Description";
            DataTable   rawTable = Db.GetTable(command);
            AccountType aType;
            decimal     debit  = 0;
            decimal     credit = 0;

            for (int i = 0; i < rawTable.Rows.Count; i++)
            {
                row                = table.NewRow();
                aType              = (AccountType)PIn.Long(rawTable.Rows[i]["AcctType"].ToString());
                row["type"]        = Lans.g("enumAccountType", aType.ToString());
                row["Description"] = rawTable.Rows[i]["Description"].ToString();
                debit              = PIn.Decimal(rawTable.Rows[i]["SumDebit"].ToString());
                credit             = PIn.Decimal(rawTable.Rows[i]["SumCredit"].ToString());
                if (DebitIsPos(aType))
                {
                    row["balance"] = (debit - credit).ToString("N");
                }
                else
                {
                    row["balance"] = (credit - debit).ToString("N");
                }
                row["BankNumber"] = rawTable.Rows[i]["BankNumber"].ToString();
                if (rawTable.Rows[i]["Inactive"].ToString() == "0")
                {
                    row["inactive"] = "";
                }
                else
                {
                    row["inactive"] = "X";
                }
                row["color"]      = rawTable.Rows[i]["AccountColor"].ToString();         //it will be an unsigned int at this point.
                row["AccountNum"] = rawTable.Rows[i]["AccountNum"].ToString();
                rows.Add(row);
            }
            //now, the Retained Earnings (auto) account-----------------------------------------------------------------
            DateTime firstofYear = new DateTime(asOfDate.Year, 1, 1);

            command = "SELECT AcctType, SUM(DebitAmt) AS SumDebit, SUM(CreditAmt) AS SumCredit "
                      + "FROM account,journalentry "
                      + "WHERE journalentry.AccountNum=account.AccountNum "
                      + "AND DateDisplayed < " + POut.Date(firstofYear) //all from previous years
                      + " AND (AcctType=3 OR AcctType=4) "              //income or expenses
                      + "GROUP BY AcctType ORDER BY AcctType";          //income first, but could return zero rows.
            rawTable = Db.GetTable(command);
            decimal balance = 0;

            for (int i = 0; i < rawTable.Rows.Count; i++)
            {
                aType  = (AccountType)PIn.Long(rawTable.Rows[i]["AcctType"].ToString());
                debit  = PIn.Decimal(rawTable.Rows[i]["SumDebit"].ToString());
                credit = PIn.Decimal(rawTable.Rows[i]["SumCredit"].ToString());
                //this works for both income and expenses, because we are subracting expenses, so signs cancel
                balance += credit - debit;
            }
            row                = table.NewRow();
            row["type"]        = Lans.g("enumAccountType", AccountType.Equity.ToString());
            row["Description"] = Lans.g("Accounts", "Retained Earnings (auto)");
            row["balance"]     = balance.ToString("N");
            row["BankNumber"]  = "";
            row["color"]       = Color.White.ToArgb();
            row["AccountNum"]  = "0";
            rows.Add(row);
            //finally, income and expenses------------------------------------------------------------------------------
            command = "SELECT account.AcctType, account.Description, account.AccountNum, "
                      + "SUM(DebitAmt) AS SumDebit, SUM(CreditAmt) AS SumCredit, account.BankNumber, account.Inactive, account.AccountColor "
                      + "FROM account "
                      + "LEFT JOIN journalentry ON journalentry.AccountNum=account.AccountNum "
                      + "AND DateDisplayed <= " + POut.Date(asOfDate)
                      + " AND DateDisplayed >= " + POut.Date(firstofYear)       //only for this year
                      + " WHERE (AcctType=3 OR AcctType=4) ";
            if (!showInactive)
            {
                command += "AND Inactive=0 ";
            }
            command += "GROUP BY account.AccountNum, account.AcctType, account.Description, account.BankNumber,"
                       + "account.Inactive, account.AccountColor ORDER BY AcctType, Description";
            rawTable = Db.GetTable(command);
            for (int i = 0; i < rawTable.Rows.Count; i++)
            {
                row                = table.NewRow();
                aType              = (AccountType)PIn.Long(rawTable.Rows[i]["AcctType"].ToString());
                row["type"]        = Lans.g("enumAccountType", aType.ToString());
                row["Description"] = rawTable.Rows[i]["Description"].ToString();
                debit              = PIn.Decimal(rawTable.Rows[i]["SumDebit"].ToString());
                credit             = PIn.Decimal(rawTable.Rows[i]["SumCredit"].ToString());
                if (DebitIsPos(aType))
                {
                    row["balance"] = (debit - credit).ToString("N");
                }
                else
                {
                    row["balance"] = (credit - debit).ToString("N");
                }
                row["BankNumber"] = rawTable.Rows[i]["BankNumber"].ToString();
                if (rawTable.Rows[i]["Inactive"].ToString() == "0")
                {
                    row["inactive"] = "";
                }
                else
                {
                    row["inactive"] = "X";
                }
                row["color"]      = rawTable.Rows[i]["AccountColor"].ToString();         //it will be an unsigned int at this point.
                row["AccountNum"] = rawTable.Rows[i]["AccountNum"].ToString();
                rows.Add(row);
            }
            for (int i = 0; i < rows.Count; i++)
            {
                table.Rows.Add(rows[i]);
            }
            return(table);
        }
Exemple #11
0
        ///<summary>This does all the validation before calling AlterLinkedEntries.  It had to be separated like this because of the complexity of saving a payment.  Surround with try-catch.  Will throw an exception if user is trying to change, but not allowed.  Will return false if no synch with accounting is needed.  Use -1 for newAcct to indicate no change.</summary>
        public static bool ValidateLinkedEntries(double oldAmt, double newAmt, bool isNew, long payNum, long newAcct)
        {
            //No need to check RemotingRole; no call to db.
            if (!Accounts.PaymentsLinked())
            {
                return(false);               //user has not even set up accounting links, so no need to check any of this.
            }
            bool amtChanged = false;

            if (oldAmt != newAmt)
            {
                amtChanged = true;
            }
            Transaction trans = Transactions.GetAttachedToPayment(payNum); //this gives us the oldAcctNum

            if (trans == null && (newAcct == 0 || newAcct == -1))          //if there was no previous link, and there is no attempt to create a link
            {
                return(false);                                             //no synch needed
            }
            if (trans == null)                                             //no previous link, but user is trying to create one. newAcct>0.
            {
                return(true);                                              //new transaction will be required
            }
            //at this point, we have established that there is a previous transaction.
            //If payment is attached to a transaction which is more than 48 hours old, then not allowed to change.
            if (amtChanged && trans.DateTimeEntry < MiscData.GetNowDateTime().AddDays(-2))
            {
                throw new ApplicationException(Lans.g("Payments", "Not allowed to change amount that is more than 48 hours old.  This payment is already attached to an accounting transaction.  You will need to detach it from within the accounting section of the program."));
            }
            if (amtChanged && Transactions.IsReconciled(trans))
            {
                throw new ApplicationException(Lans.g("Payments", "Not allowed to change amount.  This payment is attached to an accounting transaction that has been reconciled.  You will need to detach it from within the accounting section of the program."));
            }
            List <JournalEntry> jeL = JournalEntries.GetForTrans(trans.TransactionNum);
            long         oldAcct    = 0;
            JournalEntry jeDebit    = null;
            JournalEntry jeCredit   = null;
            double       absOld     = oldAmt;//the absolute value of the old amount

            if (oldAmt < 0)
            {
                absOld = -oldAmt;
            }
            for (int i = 0; i < jeL.Count; i++)       //we make sure down below that this count is exactly 2.
            {
                if (Accounts.GetAccount(jeL[i].AccountNum).AcctType == AccountType.Asset)
                {
                    oldAcct = jeL[i].AccountNum;
                }
                if (jeL[i].DebitAmt == absOld)
                {
                    jeDebit = jeL[i];
                }
                //old credit entry
                if (jeL[i].CreditAmt == absOld)
                {
                    jeCredit = jeL[i];
                }
            }
            if (jeCredit == null || jeDebit == null)
            {
                throw new ApplicationException(Lans.g("Payments", "Not able to automatically make changes in the accounting section to match the change made here.  You will need to detach it from within the accounting section."));
            }
            if (oldAcct == 0)          //something must have gone wrong.  But this should never happen
            {
                throw new ApplicationException(Lans.g("Payments", "Could not locate linked transaction.  You will need to detach it manually from within the accounting section of the program."));
            }
            if (newAcct == 0)          //detaching it from a linked transaction.
            //We will delete the transaction
            {
                return(true);
            }
            bool acctChanged = false;

            if (newAcct != -1 && oldAcct != newAcct)
            {
                acctChanged = true;              //changing linked acctNum
            }
            if (!amtChanged && !acctChanged)
            {
                return(false);               //no changes being made to amount or account, so no synch required.
            }
            if (jeL.Count != 2)
            {
                throw new ApplicationException(Lans.g("Payments", "Not able to automatically change the amount in the accounting section to match the change made here.  You will need to detach it from within the accounting section."));
            }
            //Amount or account changed on an existing linked transaction.
            return(true);
        }
Exemple #12
0
        ///<summary>If not using clinics then supply an empty list of clinicNums.</summary>
        public static DataTable GetAppointmentTable(DateTime dateStart, DateTime dateEnd, List <long> listProvNums, List <long> listClinicNums,
                                                    bool hasClinicsEnabled, bool isShowRecall, bool isShowNewPat, bool isShowASAP, SortAndFilterBy sortBy, List <ApptStatus> listApptStatusesToExclude,
                                                    List <long> listConfirmationStatuses, string formSender)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetTable(MethodBase.GetCurrentMethod(), dateStart, dateEnd, listProvNums, listClinicNums, hasClinicsEnabled,
                                     isShowRecall, isShowNewPat, isShowASAP, sortBy, listApptStatusesToExclude, listConfirmationStatuses, formSender));
            }
            //Appointment status conditions
            string whereApptStatus = "";

            if (listApptStatusesToExclude.Count > 0)
            {
                whereApptStatus += " appointment.AptStatus NOT IN (" + string.Join(",", listApptStatusesToExclude.Select(x => POut.Int((int)x))) + ") AND ";
            }
            //Provider Conditions
            string whereProv = "";

            if (listProvNums.Count > 0)
            {
                whereProv += " (appointment.ProvNum IN(" + string.Join(",", listProvNums) + ") "
                             + " OR appointment.ProvHyg IN(" + string.Join(",", listProvNums) + ")) AND ";
            }
            //Clinic Conditions
            string whereClinics = "";

            if (hasClinicsEnabled && listClinicNums.Count > 0)
            {
                whereClinics += " appointment.ClinicNum IN(" + string.Join(",", listClinicNums) + ") AND ";
            }
            //Appointment confirmation conditions
            string whereConfStatus = "";

            if (listConfirmationStatuses.Count > 0)
            {
                whereConfStatus += " appointment.Confirmed IN (" + string.Join(",", listConfirmationStatuses) + ") AND ";
            }
            //WebSched Appointments
            string            innerJoinWebSchedBoth = "";
            List <LogSources> listSources           = new List <LogSources>();

            if (isShowNewPat)
            {
                listSources.Add(LogSources.WebSchedNewPatAppt);
            }
            if (isShowRecall)
            {
                listSources.Add(LogSources.WebSched);
            }
            if (isShowASAP)
            {
                listSources.Add(LogSources.WebSchedASAP);
            }
            if (listSources.Count > 0)
            {
                List <int> listPerms = new List <int>()
                {
                    (int)Permissions.AppointmentCreate
                };
                if (sortBy == SortAndFilterBy.SecurityLogDate)
                {
                    listPerms.Add((int)Permissions.AppointmentEdit);
                    listPerms.Add((int)Permissions.AppointmentMove);
                }
                innerJoinWebSchedBoth = " INNER JOIN securitylog ON appointment.AptNum=securitylog.FKey"
                                        + " AND securitylog.PermType IN (" + string.Join(",", listPerms.Select(x => POut.Int(x))) + ") "
                                        + " AND securitylog.LogSource IN (" + string.Join(",", listSources.Select(x => (int)x)) + ") ";
            }
            //Query
            string command = @"SELECT ";

            if (sortBy == SortAndFilterBy.SecDateTEntry)
            {
                command += "appointment.SecDateTEntry,";
            }
            if (sortBy == SortAndFilterBy.SecurityLogDate)
            {
                command += "securitylog.LogDateTime,";
            }
            command +=
                @"appointment.AptDateTime,
				patient.PatNum,
				TRIM(CONCAT(CONCAT(CONCAT(CONCAT(CONCAT(patient.LName,', '),CASE WHEN LENGTH(patient.Preferred) > 0 THEN CONCAT(CONCAT('(',patient.Preferred),') ') ELSE '' END),patient.FName), ' '),patient.MiddleI)) PatName,
				patient.Birthdate,
				appointment.AptDateTime,
				LENGTH(appointment.Pattern)*5,
				appointment.ProcDescript,
				patient.HmPhone,
				patient.WkPhone,
				patient.WirelessPhone,
				COALESCE(clinic.Description,'"                 + POut.String(Lans.g("formSender", "Unassigned")) + @"') ClinicDesc,
				appointment.SecDateTEntry AS 'DateTimeCreated',
				appointment.Confirmed,
				appointment.Note,
				appointment.AptNum
				FROM appointment
				INNER JOIN patient ON appointment.PatNum=patient.PatNum "
                + innerJoinWebSchedBoth +
                @" LEFT JOIN clinic ON appointment.ClinicNum=clinic.ClinicNum 
				WHERE "
                + whereApptStatus
                + whereProv
                + whereClinics
                + whereConfStatus;
            if (sortBy == SortAndFilterBy.SecDateTEntry)
            {
                command += " " + DbHelper.BetweenDates("appointment.SecDateTEntry", dateStart, dateEnd)
                           + " ORDER BY appointment.ClinicNum,appointment.SecDateTEntry,PatName";
            }
            else if (sortBy == SortAndFilterBy.AptDateTime)
            {
                command += " appointment.AptDateTime BETWEEN " + POut.Date(dateStart) + " AND " + POut.Date(dateEnd.AddDays(1))
                           + " ORDER BY appointment.ClinicNum,appointment.AptDateTime,PatName";
            }
            else if (sortBy == SortAndFilterBy.SecurityLogDate && listSources.Count > 0)
            {
                command += " securitylog.LogDateTime BETWEEN " + POut.Date(dateStart) + " AND " + POut.Date(dateEnd.AddDays(1))
                           + " ORDER BY securitylog.LogDateTime,appointment.AptDateTime,PatName";
            }
            DataTable table = ReportsComplex.RunFuncOnReportServer(() => ReportsComplex.GetTable(command));

            return(table);
        }
Exemple #13
0
        private static void MakeCommlog(Patient pat, string phoneNumber, int statusCode)
        {
            string commText = "";

            //Status code meanings:
            //		-100: Patient had no phone number
            //		-200: Patient can't text and had no email
            //		2XX: Successfully sent message
            //		422: Message has already been sent for patient
            //		Anything else: Failure of some sort.
            switch (statusCode / 100)           //Get general http status codes e.g. -100=-1, 203=2
            {
            case -1:                            //Failure, no phone number
                commText = Lans.g("Podium", "Podium review invitation request failed because there was no phone number.  Error code:") + " " + statusCode;
                break;

            case -2:                            //Failure, no email
                commText = Lans.g("Podium", "Podium review invitation request failed because the patient doesn't accept texts "
                                  + "and there was no email address.  Error code:") + " " + statusCode;
                break;

            case 2:                     //Success https://httpstatusdogs.com/200-ok
                commText = Lans.g("Podium", "Podium review invitation request successfully sent.");
                break;

            case 4:                     //Client side communication failure https://httpstatusdogs.com/400-bad-request
                if (statusCode == 422)  //422 is Unprocessable Entity, which is sent in this case when a phone number has received an invite already.
                {
                    commText = Lans.g("Podium", "The request failed because an identical request was previously sent.");
                }
                else
                {
                    commText = Lans.g("Podium", "The request failed to reach Podium with error code:") + " " + statusCode;
                }
                break;

            case 5:                     //Server side internal failure. https://httpstatusdogs.com/500-internal-server-error
                commText = Lans.g("Podium", "The request was rejected by the Podium server with error code:") + " " + statusCode;
                break;

            default:                            //General Failure
                commText = Lans.g("Podium", "The request failed to send with error code:") + " " + statusCode;
                break;
            }
            if (!string.IsNullOrEmpty(commText))
            {
                commText += "\r\n";
            }
            commText += Lans.g("Podium", "The information sent in the request was") + ": \r\n"
                        + Lans.g("Podium", "First name") + ": \"" + pat.FName + "\", "
                        + Lans.g("Podium", "Last name") + ": \"" + pat.LName + "\", "
                        + Lans.g("Podium", "Email") + ": \"" + pat.Email + "\"";
            if (phoneNumber != "")           //If "successful".
            {
                commText += ", " + Lans.g("Podium", "Phone number") + ": \"" + phoneNumber + "\"";
            }
            else
            {
                string        wirelessPhone = new string(pat.WirelessPhone.Where(x => char.IsDigit(x)).ToArray());
                string        homePhone = new string(pat.HmPhone.Where(x => char.IsDigit(x)).ToArray());
                List <string> phonesTried = new List <string> {
                    wirelessPhone, homePhone
                }.FindAll(x => x != "");
                string phoneNumbersTried = ", " + Lans.g("Podium", "No valid phone number found.");
                if (pat.TxtMsgOk == YN.No || (pat.TxtMsgOk == YN.Unknown && PrefC.GetBool(PrefName.TextMsgOkStatusTreatAsNo)))             //Used email
                {
                    phoneNumbersTried = "";
                }
                else if (phonesTried.Count > 0)
                {
                    phoneNumbersTried = ", " + Lans.g("Podium", "Phone numbers tried") + ": " + string.Join(", ", phonesTried);
                }
                commText += phoneNumbersTried;
            }
            long    programNum = Programs.GetProgramNum(ProgramName.Podium);
            Commlog commlogCur = new Commlog();

            commlogCur.CommDateTime   = DateTime.Now;
            commlogCur.DateTimeEnd    = DateTime.Now;
            commlogCur.PatNum         = pat.PatNum;
            commlogCur.UserNum        = 0;   //run from server, no valid CurUser
            commlogCur.CommSource     = CommItemSource.ProgramLink;
            commlogCur.ProgramNum     = programNum;
            commlogCur.CommType       = Commlogs.GetTypeAuto(CommItemTypeAuto.MISC);
            commlogCur.Note           = commText;
            commlogCur.Mode_          = CommItemMode.Text;
            commlogCur.SentOrReceived = CommSentOrReceived.Sent;
            Commlogs.Insert(commlogCur);
        }
Exemple #14
0
        ///<summary>Returns true if we got a URL from PDMP.
        ///If true, the response will be the URL.
        ///If false, the response will be the error.</summary>
        public static bool TrySendData(Program programCur, Patient pat, out string response)
        {
            string        result    = "";
            StringBuilder sbErrors  = new StringBuilder();
            bool          isSuccess = false;

            ODProgress.ShowAction(() => {
                if (!programCur.Enabled)
                {
                    sbErrors.AppendLine(programCur.ProgName + Lans.g("PDMP", " must be enabled in Program Links."));
                    result = sbErrors.ToString();
                    return;
                }
                if (pat == null)
                {
                    sbErrors.AppendLine(Lans.g("PDMP", "Please select a patient."));
                    result = sbErrors.ToString();
                    return;
                }
                Provider prov = Providers.GetProv(pat.PriProv);
                if (prov == null)
                {
                    sbErrors.AppendLine(Lans.g("PDMP", "Patient does not have a primary provider."));
                    result = sbErrors.ToString();
                    return;
                }
                string strDeaNum = ProviderClinics.GetDEANum(prov.ProvNum, Clinics.ClinicNum);             //If no result found, retries using clinicNum=0.
                if (string.IsNullOrWhiteSpace(strDeaNum))
                {
                    sbErrors.AppendLine(Lans.g("PDMP", "Patient's provider does not have a DEA number."));
                }
                string stateWhereLicensed = ProviderClinics.GetStateWhereLicensed(pat.PriProv, Clinics.ClinicNum);
                if (string.IsNullOrWhiteSpace(stateWhereLicensed))
                {
                    sbErrors.AppendLine(Lans.g("PDMP", "Patient's provider is not licensed for any state."));
                }
                string facilityIdPropDesc = "";
                string userNamePropDesc   = "";
                string passwordPropDesc   = "";
                try {
                    facilityIdPropDesc = GetFacilityIdPropDesc(stateWhereLicensed);
                    userNamePropDesc   = GetClientUserNamePropDesc(stateWhereLicensed);
                    passwordPropDesc   = GetClientPasswordPropDesc(stateWhereLicensed);
                }
                catch (NotImplementedException niex) {
                    sbErrors.AppendLine(niex.Message);
                }
                //Validation failed.  We gave the user as much information to fix as possible.
                if (!string.IsNullOrWhiteSpace(sbErrors.ToString()))
                {
                    result = sbErrors.ToString();
                    return;
                }
                //Validation passed and we can now call the PDMP API.
                string facilityId     = ProgramProperties.GetPropVal(programCur.ProgramNum, facilityIdPropDesc);
                string clientUsername = ProgramProperties.GetPropVal(programCur.ProgramNum, userNamePropDesc);
                string clientPassword = ProgramProperties.GetPropVal(programCur.ProgramNum, passwordPropDesc);
                try {
                    //Each state may use a different API for its PDMP services.  Implement appropriate classes to handle each state we support.
                    switch (stateWhereLicensed)
                    {
                    case "IL":
                        PDMPLogicoy pdmp = new PDMPLogicoy(clientUsername, clientPassword, pat, prov, stateWhereLicensed, strDeaNum, facilityId);
                        result           = pdmp.GetURL();
                        isSuccess        = true;
                        break;

                    default:
                        result = Lans.g("PDMP", "PDMP program link has not been implemented for state: ") + stateWhereLicensed;
                        return;
                    }
                }
                catch (Exception ex) {
                    result = ex.Message;
                    return;
                }
            }, startingMessage: Lans.g("PDMP", "Fetching data..."));
            response = result;
            return(isSuccess);
        }
Exemple #15
0
        ///<summary>Takes a screening sheet that is associated to a patient and processes any corresponding ScreenCharts found.
        ///Processing will create treatment planned or completed procedures for the patient.
        ///Supply the sheet and then a bitwise enum of screen chart types to digest.
        ///procOrigVals MUST be two items long, nulls are allowed, the first represents the fluoride field, second is assessment field.</summary>
        public static void ProcessScreenChart(Sheet sheet, ScreenChartType chartTypes, long provNum, long sheetNum, List <SheetField> listChartOrigVals
                                              , List <SheetField> listProcOrigVals)
        {
            //No need to check RemotingRole; no call to db.
            if (sheet == null || sheet.PatNum == 0)
            {
                return;                //An invalid screening sheet was passed in.
            }
            List <string> listToothVals    = new List <string>();
            List <string> listToothValsOld = new List <string>();

            //Process treatment planned sealants.
            foreach (SheetField field in sheet.SheetFields)             //Go through the supplied sheet's fields and find the field.
            {
                if (chartTypes.HasFlag(ScreenChartType.TP) && field.FieldType == SheetFieldType.ScreenChart && field.FieldName == "ChartSealantTreatment")
                {
                    listToothVals = field.FieldValue.Split(';').ToList();
                    if (listToothVals[0] == "1")         //Primary tooth chart
                    {
                        continue;                        //Skip primary tooth charts because we do not need to create any TP procedures for them.
                    }
                    listToothVals.RemoveAt(0);           //Remove the toothchart type value
                    if (listChartOrigVals[0] != null)    //Shouldn't be null if ChartSealantTreatment exists
                    {
                        listToothValsOld = listChartOrigVals[0].FieldValue.Split(';').ToList();
                        listToothValsOld.RemoveAt(0);                        //Remove the toothchart type value
                    }
                    ScreenChartType chartType = ScreenChartType.TP;
                    ProcessScreenChartHelper(sheet.PatNum, listToothVals, chartType, provNum, sheetNum, listToothValsOld);
                    break;
                }
            }
            listToothVals = new List <string>();            //Clear out the tooth values for the next tooth chart.
            //Process completed sealants.
            foreach (SheetField field in sheet.SheetFields) //Go through the supplied sheet's fields and find the field.
            {
                if (chartTypes.HasFlag(ScreenChartType.C) && field.FieldType == SheetFieldType.ScreenChart && field.FieldName == "ChartSealantComplete")
                {
                    listToothVals = field.FieldValue.Split(';').ToList();
                    if (listToothVals[0] == "1")         //Primary tooth chart
                    {
                        continue;                        //Skip primary tooth charts because we do not need to create any TP procedures for them.
                    }
                    listToothVals.RemoveAt(0);           //Remove the toothchart type value
                    if (listChartOrigVals[1] != null)    //Shouldn't be null if ChartSealantTreatment exists
                    {
                        listToothValsOld = listChartOrigVals[1].FieldValue.Split(';').ToList();
                        listToothValsOld.RemoveAt(0);                        //Remove the toothchart type value
                    }
                    ScreenChartType chartType = ScreenChartType.C;
                    ProcessScreenChartHelper(sheet.PatNum, listToothVals, chartType, provNum, sheetNum, listToothValsOld);
                    break;
                }
            }
            //Process if the user wants to TP fluoride and / or assessment procedures.
            foreach (SheetField field in sheet.SheetFields)
            {
                if (field.FieldType != SheetFieldType.CheckBox)
                {
                    continue;                    //Only care about check box types.
                }
                if (field.FieldName != "FluorideProc" && field.FieldName != "AssessmentProc")
                {
                    continue;                    //Field name must be one of the two hard coded values.
                }
                //Make D1206 proc with provNum and patNum
                if (field.FieldName == "FluorideProc" && listProcOrigVals[1] != null && listProcOrigVals[1].FieldValue == "" && field.FieldValue == "X")
                {
                    //Original value was blank, new value is "checked", make the D1206 (fluoride) proc.
                    Procedure proc = Procedures.CreateProcForPat(sheet.PatNum, ProcedureCodes.GetCodeNum("D1206"), "", "", ProcStat.C, provNum);
                    if (proc != null)
                    {
                        SecurityLogs.MakeLogEntry(Permissions.ProcEdit, sheet.PatNum, "D1206 " + Lans.g("Screens", "treatment planned during screening"));
                    }
                }
                //Make D0191 proc with provNum and patNum
                if (field.FieldName == "AssessmentProc" && listProcOrigVals[0] != null && listProcOrigVals[0].FieldValue == "" && field.FieldValue == "X")
                {
                    //Original value was blank, new value is "checked", make the D0191 (assessment) proc.
                    Procedure proc = Procedures.CreateProcForPat(sheet.PatNum, ProcedureCodes.GetCodeNum("D0191"), "", "", ProcStat.C, provNum);
                    if (proc != null)
                    {
                        SecurityLogs.MakeLogEntry(Permissions.ProcEdit, sheet.PatNum, "D0191 " + Lans.g("Screens", "treatment planned during screening."));
                    }
                }
            }
        }
Exemple #16
0
        ///<summary>Modified Sync pattern for the OrthoChart.  We cannot use the standard Sync pattern because we have to perform logging when updating
        ///or deleting.</summary>
        public static void Sync(Patient patCur, List <OrthoChart> listNew, List <DisplayField> listOrthDisplayFields, DisplayField displayFieldSignature)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                Meth.GetVoid(MethodBase.GetCurrentMethod(), patCur, listNew, listOrthDisplayFields, displayFieldSignature);
                return;
            }
            List <OrthoChart> listDB = GetAllForPatient(patCur.PatNum);
            //Inserts, updates, or deletes database rows to match supplied list.
            //Adding items to lists changes the order of operation. All inserts are completed first, then updates, then deletes.
            List <OrthoChart> listIns      = new List <OrthoChart>();
            List <OrthoChart> listUpdNew   = new List <OrthoChart>();
            List <OrthoChart> listUpdDB    = new List <OrthoChart>();
            List <OrthoChart> listDel      = new List <OrthoChart>();
            List <string>     listColNames = new List <string>();

            //Remove fields from the DB list that are not currently set to display.
            for (int i = 0; i < listOrthDisplayFields.Count; i++)
            {
                listColNames.Add(listOrthDisplayFields[i].Description);
            }
            for (int i = listDB.Count - 1; i >= 0; i--)
            {
                if (!listColNames.Contains(listDB[i].FieldName))
                {
                    listDB.RemoveAt(i);
                }
            }
            listNew.Sort(OrthoCharts.SortDateField);
            listDB.Sort(OrthoCharts.SortDateField);
            int        idxNew = 0;
            int        idxDB  = 0;
            OrthoChart fieldNew;
            OrthoChart fieldDB;

            //Because both lists have been sorted using the same criteria, we can now walk each list to determine which list contians the next element.  The next element is determined by Primary Key.
            //If the New list contains the next item it will be inserted.  If the DB contains the next item, it will be deleted.  If both lists contain the next item, the item will be updated.
            while (idxNew < listNew.Count || idxDB < listDB.Count)
            {
                fieldNew = null;
                if (idxNew < listNew.Count)
                {
                    fieldNew = listNew[idxNew];
                }
                fieldDB = null;
                if (idxDB < listDB.Count)
                {
                    fieldDB = listDB[idxDB];
                }
                //begin compare
                if (fieldNew != null && fieldDB == null)             //listNew has more items, listDB does not.
                {
                    listIns.Add(fieldNew);
                    idxNew++;
                    continue;
                }
                else if (fieldNew == null && fieldDB != null)             //listDB has more items, listNew does not.
                {
                    listDel.Add(fieldDB);
                    idxDB++;
                    continue;
                }
                else if (fieldNew.DateService < fieldDB.DateService)               //newPK less than dbPK, newItem is 'next'
                {
                    listIns.Add(fieldNew);
                    idxNew++;
                    continue;
                }
                else if (fieldNew.DateService > fieldDB.DateService)               //dbPK less than newPK, dbItem is 'next'
                {
                    listDel.Add(fieldDB);
                    idxDB++;
                    continue;
                }
                else if (fieldNew.FieldName.CompareTo(fieldDB.FieldName) < 0)               //New Fieldname Comes First
                {
                    listIns.Add(fieldNew);
                    idxNew++;
                    continue;
                }
                else if (fieldNew.FieldName.CompareTo(fieldDB.FieldName) > 0)               //DB Fieldname Comes First
                {
                    listDel.Add(fieldDB);
                    idxDB++;
                    continue;
                }
                //Both lists contain the 'next' item, update required
                listUpdNew.Add(fieldNew);
                listUpdDB.Add(fieldDB);
                idxNew++;
                idxDB++;
            }
            //Commit changes to DB
            for (int i = 0; i < listIns.Count; i++)
            {
                if (listIns[i].FieldValue == "")               //do not insert new blank values. This happens when fields from today are not used.
                {
                    continue;
                }
                listIns[i].UserNum = Security.CurUser.UserNum;
                Insert(listIns[i]);
            }
            for (int i = 0; i < listUpdNew.Count; i++)
            {
                if (listUpdDB[i].FieldValue == listUpdNew[i].FieldValue)
                {
                    continue;                       //values equal. do not update/create log entry.
                }
                if (listUpdNew[i].FieldValue != "") //Actually update rows that have a new value.
                {
                    Update(listUpdNew[i], listUpdDB[i]);
                }
                else                  //instead of updating to a blank value, we delete the row from the DB.
                {
                    listDel.Add(listUpdDB[i]);
                }
                #region security log entry
                string logText = Lans.g("OrthoCharts", "Ortho chart field edited.  Field date") + ": " + listUpdNew[i].DateService.ToShortDateString() + "  "
                                 + Lans.g("OrthoCharts", "Field name") + ": " + listUpdNew[i].FieldName + "\r\n";
                //Do not log the Base64 information into the audit trail if this is a signature column, log some short descriptive text instead.
                if (displayFieldSignature != null && listUpdNew[i].FieldName == displayFieldSignature.Description)             //This is the signature box
                {
                    if (listUpdDB[i].FieldValue != "" && listUpdNew[i].FieldValue != "")
                    {
                        logText += Lans.g("OrthoCharts", "Signature modified.") + " ";
                    }
                    else if (listUpdDB[i].FieldValue != "" && listUpdNew[i].FieldValue == "")
                    {
                        logText += Lans.g("OrthoCharts", "Signature deleted.") + " ";
                    }
                }
                else                  //Not a signature
                {
                    logText += Lans.g("OrthoCharts", "Old value") + ": \"" + listUpdDB[i].FieldValue + "\"  "
                               + Lans.g("OrthoCharts", "New value") + ": \"" + listUpdNew[i].FieldValue + "\" ";
                }
                logText += listUpdDB[i].DateService.ToString("yyyyMMdd");              //This date stamp must be the last 8 characters for new OrthoEdit audit trail entries.
                SecurityLogs.MakeLogEntry(Permissions.OrthoChartEditFull, patCur.PatNum, logText);
                #endregion
            }
            for (int i = 0; i < listDel.Count; i++)       //All logging should have been performed above in the "Update block"
            {
                Delete(listDel[i].OrthoChartNum);
            }
        }
Exemple #17
0
 ///<summary>Helper method so that we do not have to duplicate code.  The length of toothValues must match the length of chartOrigVals.</summary>
 private static void ProcessScreenChartHelper(long patNum, List <string> toothValues, ScreenChartType chartType, long provNum, long sheetNum
                                              , List <string> chartOrigVals)
 {
     //No need to check RemotingRole; no call to db.
     for (int i = 0; i < toothValues.Count; i++)       //toothValues is in the order from low to high tooth number in the chart
     {
         if (!toothValues[i].Contains("S"))            //No sealant, nothing to do.
         {
             continue;
         }
         //Logic to determine if the "S" changed surfaces or was erased between the time the toothchart was opened and when it was submitted.
         string[] newSurfaces  = toothValues[i].Split(',');
         string[] origSurfaces = chartOrigVals[i].Split(',');
         bool     isDiff       = false;
         for (int j = 0; j < origSurfaces.Length; j++)                                                                   //Both arrays have the same length unless the chart doesn't exist in the original.
         {
             if ((newSurfaces[j] == "S" && origSurfaces[j] != "S") || (newSurfaces[j] != "S" && origSurfaces[j] == "S")) //"S" changed surfaces or was removed.
             {
                 isDiff = true;
                 break;
             }
         }
         //If there is no difference don't make any duplicates.  We don't care if they changed a surface from N to PS for example, only S surfaces are important.
         if (!isDiff)
         {
             continue;                    //All the "S" surfaces are the same.
         }
         string surf     = "";
         int    toothNum = 0;
         bool   isMolar  = false;
         bool   isRight  = false;
         bool   isLing   = false;
         string tooth    = "";
         #region Parse ScreenChart FieldValues
         if (i <= 1)               //Top left quadrant of toothchart
         {
             toothNum = i + 2;
             isMolar  = true;
             isRight  = true;
             isLing   = true;
         }
         else if (i > 1 && i <= 3)             //Top middle-left quadrant of toothchart
         {
             toothNum = i + 2;
             isMolar  = false;
             isRight  = true;
             isLing   = true;
         }
         else if (i > 3 && i <= 5)             //Top middle-right quadrant of toothchart
         {
             toothNum = i + 8;
             isMolar  = false;
             isRight  = false;
             isLing   = true;
         }
         else if (i > 5 && i <= 7)             //Top right quadrant of toothchart
         {
             toothNum = i + 8;
             isMolar  = true;
             isRight  = false;
             isLing   = true;
         }
         else if (i > 7 && i <= 9)             //Lower right quadrant of toothchart
         {
             toothNum = i + 10;
             isMolar  = true;
             isRight  = false;
             isLing   = false;
         }
         else if (i > 9 && i <= 11)             //Lower middle-right quadrant of toothchart
         {
             toothNum = i + 10;
             isMolar  = false;
             isRight  = false;
             isLing   = false;
         }
         else if (i > 11 && i <= 13)             //Lower middle-left quadrant of toothchart
         {
             toothNum = i + 16;
             isMolar  = false;
             isRight  = true;
             isLing   = false;
         }
         else if (i > 13)               //Lower left quadrant of toothchart
         {
             toothNum = i + 16;
             isMolar  = true;
             isRight  = true;
             isLing   = false;
         }
         if (isMolar)
         {
             if (isRight)
             {
                 if (newSurfaces[0] == "S")
                 {
                     surf += "D";
                 }
                 if (newSurfaces[1] == "S")
                 {
                     surf += "M";
                 }
             }
             else                      //Is Left side
             {
                 if (newSurfaces[0] == "S")
                 {
                     surf += "M";
                 }
                 if (newSurfaces[1] == "S")
                 {
                     surf += "D";
                 }
             }
             if (isLing && newSurfaces[2] == "S")
             {
                 surf += "L";
             }
             if (!isLing && newSurfaces[2] == "S")
             {
                 surf += "B";
             }
         }
         else                  //Front teeth, only look at 3rd surface position in control as that's the only one the user can see.
         {
             if (newSurfaces[2] == "S")
             {
                 surf = "O";                      //NOTE: Not sure what surface to enter here... This is just a placeholder for now until we figure it out...
             }
         }
         if (toothNum != 0)
         {
             tooth = toothNum.ToString();
         }
         #endregion Parse Toothchart FieldValues
         surf = Tooth.SurfTidyForDisplay(surf, tooth);
         if (chartType == ScreenChartType.TP)               //Create TP'd sealant procs if they don't already exist for this patient.
         {
             if (Procedures.GetProcForPatByToothSurfStat(patNum, toothNum, surf, ProcStat.TP) != null)
             {
                 continue;
             }
             Procedure proc = Procedures.CreateProcForPat(patNum, ProcedureCodes.GetCodeNum("D1351"), surf, tooth, ProcStat.TP, provNum);
             if (proc != null)
             {
                 SecurityLogs.MakeLogEntry(Permissions.ProcEdit, patNum, "D1351 " + Lans.g("Screens", "treatment planned during screening with tooth")
                                           + " " + proc.ToothNum.ToString() + " " + Lans.g("Screens", "and surface") + " " + proc.Surf);
             }
         }
         else if (chartType == ScreenChartType.C)
         {
             Procedure proc = Procedures.GetProcForPatByToothSurfStat(patNum, toothNum, surf, ProcStat.TP);
             if (proc == null)                   //A TP procedure does not already exist.
             {
                 proc = Procedures.CreateProcForPat(patNum, ProcedureCodes.GetCodeNum("D1351"), surf, tooth, ProcStat.C, provNum);
             }
             else                      //TP proc already exists, set it complete.
             {
                 Procedure procOld = proc.Copy();
                 proc.ProcStatus = ProcStat.C;
                 proc.DateEntryC = DateTime.Now;
                 Procedures.Update(proc, procOld);
             }
             if (proc != null)
             {
                 SecurityLogs.MakeLogEntry(Permissions.ProcComplCreate, patNum, "D1351 " + Lans.g("Screens", "set complete during screening with tooth")
                                           + " " + proc.ToothNum.ToString() + " " + Lans.g("Screens", "and surface") + " " + proc.Surf);
             }
         }
     }
     if (chartType == ScreenChartType.C)
     {
         Recalls.Synch(patNum);
     }
 }
Exemple #18
0
        ///<summary>Backs up the database to the same directory as the original just in case the user did not have sense enough to do a backup first.
        ///Does not work for Oracle, due to some MySQL specific commands inside.</summary>
        public static long MakeABackup()
        {
            //This function should always make the backup on the server itself, and since no directories are
            //referred to (all handled with MySQL), this function will always be referred to the server from
            //client machines.
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetLong(MethodBase.GetCurrentMethod()));
            }
            //UpdateStreamLinePassword is purposefully named poorly and used in an odd fashion to sort of obfuscate it from our users.
            //GetStringNoCache() will return blank if pref does not exist.
            if (PrefC.GetStringNoCache(PrefName.UpdateStreamLinePassword) == "abracadabra")
            {
                return(0);
            }
            //only used in two places: upgrading version, and upgrading mysql version.
            //Both places check first to make sure user is using mysql.
            //we have to be careful to throw an exception if the backup is failing.
            DataConnection dcon    = new DataConnection();
            string         command = "SELECT database()";
            DataTable      table   = dcon.GetTable(command);
            string         oldDb   = PIn.String(table.Rows[0][0].ToString());
            string         newDb   = oldDb + "backup_" + DateTime.Today.ToString("MM_dd_yyyy");

            command = "SHOW DATABASES";
            table   = dcon.GetTable(command);
            string[] databases = new string[table.Rows.Count];
            for (int i = 0; i < table.Rows.Count; i++)
            {
                databases[i] = table.Rows[i][0].ToString();
            }
            if (Contains(databases, newDb))            //if the new database name already exists
            //find a unique one
            {
                int    uniqueID      = 1;
                string originalNewDb = newDb;
                do
                {
                    newDb = originalNewDb + "_" + uniqueID.ToString();
                    uniqueID++;
                }while(Contains(databases, newDb));
            }
            command = "CREATE DATABASE `" + newDb + "` CHARACTER SET utf8";
            dcon.NonQ(command);
            command = "SHOW FULL TABLES WHERE Table_type='BASE TABLE'";          //Tables, not views.  Does not work in MySQL 4.1, however we test for MySQL version >= 5.0 in PrefL.
            table   = dcon.GetTable(command);
            string[] tableName = new string[table.Rows.Count];
            for (int i = 0; i < table.Rows.Count; i++)
            {
                tableName[i] = table.Rows[i][0].ToString();
            }
            //switch to using the new database
            DataConnection newDcon = new DataConnection(newDb);

            for (int i = 0; i < tableName.Length; i++)
            {
                //Alert anyone that cares that we are backing up this table.
                ODEvent.Fire(new ODEventArgs("BackupProgress", Lans.g("MiscData", "Backing up table") + ": " + tableName[i]));
                command = "SHOW CREATE TABLE `" + oldDb + "`.`" + tableName[i] + "`";      //also works with views. Added backticks around table name for unusual characters.
                table   = newDcon.GetTable(command);
                command = PIn.ByteArray(table.Rows[0][1]);
                newDcon.NonQ(command);                                              //this has to be run using connection with new database
                command = "INSERT INTO `" + newDb + "`.`" + tableName[i] + "` "
                          + "SELECT * FROM `" + oldDb + "`.`" + tableName[i] + "`"; //Added backticks around table name for unusual characters.
                newDcon.NonQ(command);
            }
            return(0);
        }
Exemple #19
0
        ///<summary>Returns an empty string for invalid AppointmentTypeNum.  Appends (hidden) to the end of the name if necessary.</summary>
        public static string GetName(long AppointmentTypeNum)
        {
            //No need to check RemotingRole; no call to db.
            string          retVal          = "";
            AppointmentType appointmentType = GetFirstOrDefault(x => x.AppointmentTypeNum == AppointmentTypeNum);

            if (appointmentType != null)
            {
                retVal = appointmentType.AppointmentTypeName + (appointmentType.IsHidden ? " " + Lans.g("AppointmentTypes", "(hidden)") : "");
            }
            return(retVal);
        }
Exemple #20
0
            ///<summary>Returns true if the patient should be sent a text. If false, the reason why the patient can't receive a text is
            ///added to the details dictionary.</summary>
            internal bool DoSendText(long patNum, long fkey, AsapCommFKeyType fkeyType)
            {
                PatComm patComm;

                _dictPatComms.TryGetValue(patNum, out patComm);
                if (patComm == null)
                {
                    return(false);
                }
                PatientDetail patDetail;

                _dictPatDetails.TryGetValue(patNum, out patDetail);
                if (patDetail == null)
                {
                    patDetail = new PatientDetail {
                        PatNum = patNum
                    };
                    _dictPatDetails[patNum] = patDetail;
                }
                //Local function to evaluate if the patient should be sent a text.
                Func <bool> funcSendText = new Func <bool>(() => {
                    if (_sendMode == SendMode.Email)
                    {
                        return(false);                       //No need to note the reason.
                    }
                    if (_dictPatAsapComms.ContainsKey(patNum))
                    {
                        if (_dictPatAsapComms[patNum]
                            .Any(x => x.FKey == fkey && x.FKeyType == fkeyType && x.ResponseStatus == AsapRSVPStatus.DeclinedStopComm))
                        {
                            string text_type = fkeyType == AsapCommFKeyType.Recall ? "recall" : "appointment";
                            patDetail.AppendNote(Lans.g(_lanThis, "Not sending text because this patient has requested to not be texted or emailed about this "
                                                        + text_type + "."));
                            return(false);
                        }
                        int textsSent = _dictPatAsapComms[patNum]
                                        .Count(x => (x.SmsSendStatus == AutoCommStatus.SendNotAttempted && x.DateTimeSmsScheduled.Date == DtStartSendText.Date) ||
                                               (x.SmsSendStatus == AutoCommStatus.SendSuccessful && x.DateTimeSmsSent.Date == DtStartSendText.Date));
                        if (textsSent >= _maxTextsPerDay)
                        {
                            patDetail.AppendNote(Lans.g(_lanThis, "Not sending text because this patient has received") + " " + _maxTextsPerDay + " "
                                                 + Lans.g(_lanThis, "texts today."));
                            return(false);
                        }
                    }
                    bool isWithin30Minutes = (GetNextTextSendTime() < _dtSlotStart && (_dtSlotStart - GetNextTextSendTime()).TotalMinutes < TextMinMinutesBefore);
                    bool isAfterSlot       = (GetNextTextSendTime() > _dtSlotStart);
                    if (isWithin30Minutes)
                    {
                        patDetail.AppendNote(Lans.g(_lanThis, "Not sending text because the text would be sent less than") + " " + TextMinMinutesBefore + " "
                                             + Lans.g(_lanThis, "before the time slot."));
                        return(false);
                    }
                    if (isAfterSlot)
                    {
                        patDetail.AppendNote(Lans.g(_lanThis, "Not sending text because the text would be sent after the time slot."));
                        return(false);
                    }
                    switch (_sendMode)
                    {
                    case SendMode.TextAndEmail:
                    case SendMode.Text:
                        if (string.IsNullOrEmpty(patComm.SmsPhone))
                        {
                            patDetail.AppendNote(Lans.g(_lanThis, "Not sending text because this patient does not have a wireless phone entered."));
                        }
                        else if (!patComm.IsSmsAnOption)
                        {
                            patDetail.AppendNote(Lans.g(_lanThis, "Not sending text because this patient is not able to receive texts."));
                        }
                        return(patComm.IsSmsAnOption);

                    case SendMode.Email:
                        return(false);

                    case SendMode.PreferredContact:
                        if (patComm.PreferContactMethod != ContactMethod.TextMessage)
                        {
                            patDetail.AppendNote(Lans.g(_lanThis, "Not sending text because this patient's preferred contact method is not text message."));
                        }
                        else if (string.IsNullOrEmpty(patComm.SmsPhone))
                        {
                            patDetail.AppendNote(Lans.g(_lanThis, "Not sending text because this patient does not have a wireless phone entered."));
                        }
                        else if (!patComm.IsSmsAnOption)
                        {
                            patDetail.AppendNote(Lans.g(_lanThis, "Not sending text because this patient is not able to receive texts."));
                        }
                        return(patComm.IsSmsAnOption && patComm.PreferContactMethod == ContactMethod.TextMessage);

                    default:
                        return(false);
                    }
                });
                bool doSendText = funcSendText();

                patDetail.IsSendingText = doSendText;
                return(doSendText);
            }
Exemple #21
0
        ///<summary>If ClientWeb, then this method is instead run on the server, and the result passed back to the client.  And since it's ClientWeb, FillCache will be run on the client.</summary>
        public static DataSet GetCacheDs(string itypesStr)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetDS(MethodBase.GetCurrentMethod(), itypesStr));
            }
            //so this part below only happens if direct or server------------------------------------------------
            List <int> itypes = new List <int>();

            string[] strArray = itypesStr.Split(',');
            for (int i = 0; i < strArray.Length; i++)
            {
                itypes.Add(PIn.Int(strArray[i]));
            }
            bool isAll = false;

            if (itypes.Contains((int)InvalidType.AllLocal))
            {
                isAll = true;
            }
            DataSet ds = new DataSet();

            if (itypes.Contains((int)InvalidType.AccountingAutoPays) || isAll)
            {
                ds.Tables.Add(AccountingAutoPays.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.AutoCodes) || isAll)
            {
                ds.Tables.Add(AutoCodes.RefreshCache());
                ds.Tables.Add(AutoCodeItems.RefreshCache());
                ds.Tables.Add(AutoCodeConds.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Automation) || isAll)
            {
                ds.Tables.Add(Automations.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.AutoNotes) || isAll)
            {
                ds.Tables.Add(AutoNotes.RefreshCache());
                ds.Tables.Add(AutoNoteControls.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Carriers) || isAll)
            {
                ds.Tables.Add(Carriers.RefreshCache());                //run on startup, after telephone reformat, after list edit.
            }
            if (itypes.Contains((int)InvalidType.ClaimForms) || isAll)
            {
                ds.Tables.Add(ClaimFormItems.RefreshCache());
                ds.Tables.Add(ClaimForms.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.ClearHouses) || isAll)
            {
                ds.Tables.Add(Clearinghouses.RefreshCache());                //kh wants to add an EasyHideClearHouses to disable this
            }
            if (itypes.Contains((int)InvalidType.Computers) || isAll)
            {
                ds.Tables.Add(Computers.RefreshCache());
                ds.Tables.Add(Printers.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Defs) || isAll)
            {
                ds.Tables.Add(Defs.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.DentalSchools) || isAll)
            {
                ds.Tables.Add(SchoolClasses.RefreshCache());
                ds.Tables.Add(SchoolCourses.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.DictCustoms) || isAll)
            {
                ds.Tables.Add(DictCustoms.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Diseases) || isAll)
            {
                ds.Tables.Add(DiseaseDefs.RefreshCache());
                ds.Tables.Add(ICD9s.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.DisplayFields) || isAll)
            {
                ds.Tables.Add(DisplayFields.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.ElectIDs) || isAll)
            {
                ds.Tables.Add(ElectIDs.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Email) || isAll)
            {
                ds.Tables.Add(EmailAddresses.RefreshCache());
                ds.Tables.Add(EmailTemplates.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Employees) || isAll)
            {
                ds.Tables.Add(Employees.RefreshCache());
                ds.Tables.Add(PayPeriods.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Employers) || isAll)
            {
                ds.Tables.Add(Employers.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Fees) || isAll)
            {
                ds.Tables.Add(Fees.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.FeeScheds) || isAll)
            {
                ds.Tables.Add(FeeScheds.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.HL7Defs) || isAll)
            {
                ds.Tables.Add(HL7Defs.RefreshCache());
                ds.Tables.Add(HL7DefMessages.RefreshCache());
                ds.Tables.Add(HL7DefSegments.RefreshCache());
                ds.Tables.Add(HL7DefFields.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.InsCats) || isAll)
            {
                ds.Tables.Add(CovCats.RefreshCache());
                ds.Tables.Add(CovSpans.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.InsFilingCodes) || isAll)
            {
                ds.Tables.Add(InsFilingCodes.RefreshCache());
                ds.Tables.Add(InsFilingCodeSubtypes.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Languages) || isAll)
            {
                if (CultureInfo.CurrentCulture.Name != "en-US")
                {
                    ds.Tables.Add(Lans.RefreshCache());
                }
            }
            if (itypes.Contains((int)InvalidType.Letters) || isAll)
            {
                ds.Tables.Add(Letters.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.LetterMerge) || isAll)
            {
                ds.Tables.Add(LetterMergeFields.RefreshCache());
                ds.Tables.Add(LetterMerges.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Operatories) || isAll)
            {
                ds.Tables.Add(Operatories.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.PatFields) || isAll)
            {
                ds.Tables.Add(PatFieldDefs.RefreshCache());
                ds.Tables.Add(ApptFieldDefs.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Pharmacies) || isAll)
            {
                ds.Tables.Add(Pharmacies.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Prefs) || isAll)
            {
                ds.Tables.Add(Prefs.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.ProcButtons) || isAll)
            {
                ds.Tables.Add(ProcButtons.RefreshCache());
                ds.Tables.Add(ProcButtonItems.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.ProcCodes) || isAll)
            {
                ds.Tables.Add(ProcedureCodes.RefreshCache());
                ds.Tables.Add(ProcCodeNotes.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Programs) || isAll)
            {
                ds.Tables.Add(Programs.RefreshCache());
                ds.Tables.Add(ProgramProperties.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.ProviderIdents) || isAll)
            {
                ds.Tables.Add(ProviderIdents.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Providers) || isAll)
            {
                ds.Tables.Add(Providers.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.QuickPaste) || isAll)
            {
                ds.Tables.Add(QuickPasteNotes.RefreshCache());
                ds.Tables.Add(QuickPasteCats.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.RecallTypes) || isAll)
            {
                ds.Tables.Add(RecallTypes.RefreshCache());
                ds.Tables.Add(RecallTriggers.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.ReplicationServers) || isAll)
            {
                ds.Tables.Add(ReplicationServers.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Security) || isAll)
            {
                ds.Tables.Add(Userods.RefreshCache());
                ds.Tables.Add(UserGroups.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Sheets) || isAll)
            {
                ds.Tables.Add(SheetDefs.RefreshCache());
                ds.Tables.Add(SheetFieldDefs.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Signals) || isAll)
            {
                ds.Tables.Add(SigElementDefs.RefreshCache());
                ds.Tables.Add(SigButDefs.RefreshCache());                //includes SigButDefElements.Refresh()
            }
            if (itypes.Contains((int)InvalidType.Sites) || isAll)
            {
                ds.Tables.Add(Sites.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Sops) || isAll)
            {
                ds.Tables.Add(Sops.RefreshCache());
            }
            //InvalidTypes.Tasks not handled here.
            if (itypes.Contains((int)InvalidType.TimeCardRules) || isAll)
            {
                ds.Tables.Add(TimeCardRules.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.ToolBut) || isAll)
            {
                ds.Tables.Add(ToolButItems.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Vaccines) || isAll)
            {
                ds.Tables.Add(VaccineDefs.RefreshCache());
                ds.Tables.Add(DrugManufacturers.RefreshCache());
                ds.Tables.Add(DrugUnits.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Views) || isAll)
            {
                ds.Tables.Add(ApptViews.RefreshCache());
                ds.Tables.Add(ApptViewItems.RefreshCache());
                ds.Tables.Add(AppointmentRules.RefreshCache());
                ds.Tables.Add(ProcApptColors.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.Wiki) || isAll)
            {
                ds.Tables.Add(WikiListHeaderWidths.RefreshCache());
                ds.Tables.Add(WikiPages.RefreshCache());
            }
            if (itypes.Contains((int)InvalidType.ZipCodes) || isAll)
            {
                ds.Tables.Add(ZipCodes.RefreshCache());
            }
            return(ds);
        }
Exemple #22
0
            ///<summary>Returns true if the patient should be sent an email. If false, the reason why the patient can't receive an email is
            ///added to the details dictionary.</summary>
            internal bool DoSendEmail(long patNum, long fkey, AsapCommFKeyType fkeyType)
            {
                PatComm patComm;

                _dictPatComms.TryGetValue(patNum, out patComm);
                if (patComm == null)
                {
                    return(false);
                }
                PatientDetail patDetail;

                _dictPatDetails.TryGetValue(patNum, out patDetail);
                if (patDetail == null)
                {
                    patDetail = new PatientDetail {
                        PatNum = patNum
                    };
                    _dictPatDetails[patNum] = patDetail;
                }
                //Local function to evaluate if the patient should be sent an email.
                Func <bool> funcSendEmail = new Func <bool>(() => {
                    if (_sendMode == SendMode.Text)
                    {
                        return(false);                       //No need to note the reason.
                    }
                    if (_dictPatAsapComms.ContainsKey(patNum) && _dictPatAsapComms[patNum]
                        .Any(x => x.FKey == fkey && x.FKeyType == fkeyType && x.ResponseStatus == AsapRSVPStatus.DeclinedStopComm))
                    {
                        string email_type = fkeyType == AsapCommFKeyType.Recall ? "recall" : "appointment";
                        patDetail.AppendNote(Lans.g(_lanThis, "Not sending email because this patient has requested to not be texted or emailed about this "
                                                    + email_type + "."));
                        return(false);
                    }
                    bool isWithin30Minutes = (DtSendEmail < _dtSlotStart && (_dtSlotStart - DtSendEmail).TotalMinutes < TextMinMinutesBefore);
                    bool isAfterSlot       = (DtSendEmail > _dtSlotStart);
                    if (isWithin30Minutes)
                    {
                        patDetail.AppendNote(Lans.g(_lanThis, "Not sending email because the email would be sent less than") + " " + TextMinMinutesBefore + " "
                                             + Lans.g(_lanThis, "before the time slot."));
                        return(false);
                    }
                    if (isAfterSlot)
                    {
                        patDetail.AppendNote(Lans.g(_lanThis, "Not sending email because the email would be sent after the time slot."));
                        return(false);
                    }
                    switch (_sendMode)
                    {
                    case SendMode.TextAndEmail:
                    case SendMode.Email:
                        if (!patComm.IsEmailAnOption)
                        {
                            patDetail.AppendNote(Lans.g(_lanThis, "Not sending email because this patient does not have an email address."));
                        }
                        return(patComm.IsEmailAnOption);

                    case SendMode.Text:
                        return(false);

                    case SendMode.PreferredContact:
                        if (patComm.PreferContactMethod != ContactMethod.Email)
                        {
                            patDetail.AppendNote(Lans.g(_lanThis, "Not sending email because this patient's preferred contact method is not email."));
                        }
                        else if (!patComm.IsEmailAnOption)
                        {
                            patDetail.AppendNote(Lans.g(_lanThis, "Not sending email because this patient does not have an email address."));
                        }
                        return(patComm.IsEmailAnOption && patComm.PreferContactMethod == ContactMethod.Email);

                    default:
                        return(false);
                    }
                });
                bool doSendEmail = funcSendEmail();

                patDetail.IsSendingEmail = doSendEmail;
                return(doSendEmail);
            }
Exemple #23
0
        ///<summary>Used when printing or emailing recall to make a commlog entry without any display.
        ///Set commSource to the corresponding entity that is making this recall.  E.g. Web Sched.
        ///If the commSource is a 3rd party, set it to ProgramLink and make an overload that accepts the ProgramNum.</summary>
        public static Commlog InsertForRecallOrReactivation(long patNum, CommItemMode _mode, int numberOfReminders, long defNumNewStatus, CommItemSource commSource, long userNum, DateTime dateTimeNow, CommItemTypeAuto type = CommItemTypeAuto.RECALL)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <Commlog>(MethodBase.GetCurrentMethod(), patNum, _mode, numberOfReminders, defNumNewStatus, commSource, userNum,
                                                dateTimeNow, type));
            }
            long   commType    = Commlogs.GetTypeAuto(type);
            string commTypeStr = type == CommItemTypeAuto.RECALL?"Recall":"Reactivation";
            string command;
            string datesql = "CURDATE()";

            if (DataConnection.DBtype == DatabaseType.Oracle)
            {
                datesql = "(SELECT CURRENT_DATE FROM dual)";
            }
            if (commType != 0)
            {
                command  = "SELECT * FROM commlog WHERE ";
                command += DbHelper.DtimeToDate("CommDateTime") + " = " + datesql;
                command += " AND PatNum=" + POut.Long(patNum) + " AND CommType=" + POut.Long(commType)
                           + " AND Mode_=" + POut.Long((int)_mode)
                           + " AND SentOrReceived=1";
                List <Commlog> listComms = Crud.CommlogCrud.SelectMany(command).OrderByDescending(x => x.CommDateTime).ToList();
                if (listComms.Count > 0)
                {
                    return(listComms[0]);
                }
            }
            Commlog com = new Commlog();

            com.PatNum         = patNum;
            com.CommDateTime   = dateTimeNow;
            com.CommType       = commType;
            com.Mode_          = _mode;
            com.SentOrReceived = CommSentOrReceived.Sent;
            com.Note           = "";
            if (numberOfReminders == 0)
            {
                com.Note = Lans.g("FormRecallList", $"{commTypeStr} reminder.");
            }
            else if (numberOfReminders == 1)
            {
                com.Note = Lans.g("FormRecallList", $"Second {commTypeStr} reminder.");
            }
            else if (numberOfReminders == 2)
            {
                com.Note = Lans.g("FormRecallList", $"Third {commTypeStr} reminder.");
            }
            else
            {
                com.Note = Lans.g("FormRecallList", $"{commTypeStr} reminder:") + " " + (numberOfReminders + 1).ToString();
            }
            if (defNumNewStatus == 0)
            {
                com.Note += "  " + Lans.g("Commlogs", "Status None");
            }
            else
            {
                com.Note += "  " + Defs.GetName(DefCat.RecallUnschedStatus, defNumNewStatus);
            }
            com.UserNum    = userNum;
            com.CommSource = commSource;
            com.CommlogNum = Insert(com);
            EhrMeasureEvent newMeasureEvent = new EhrMeasureEvent();

            newMeasureEvent.DateTEvent = com.CommDateTime;
            newMeasureEvent.EventType  = EhrMeasureEventType.ReminderSent;
            newMeasureEvent.PatNum     = com.PatNum;
            newMeasureEvent.MoreInfo   = com.Note;
            EhrMeasureEvents.Insert(newMeasureEvent);
            return(com);
        }
Exemple #24
0
        ///<summary>Will throw an error if not authorized and message not suppressed.</summary>
        public static bool IsAuthorized(Permissions perm, DateTime date, bool suppressMessage, bool suppressLockDateMessage, Userod curUser,
                                        long procCodeNum, double procFee, long sheetDefNum, long fKey)
        {
            //No need to check RemotingRole; no call to db.
            date = date.Date;           //Remove the time portion of date so we can compare strictly as a date later.
            //Check eConnector permission first.
            if (IsValidEServicePermission(perm))
            {
                return(true);
            }
            if (!GroupPermissions.HasPermission(curUser, perm, fKey))
            {
                if (!suppressMessage)
                {
                    throw new Exception(Lans.g("Security", "Not authorized.") + "\r\n"
                                        + Lans.g("Security", "A user with the SecurityAdmin permission must grant you access for") + ":\r\n" + GroupPermissions.GetDesc(perm));
                }
                return(false);
            }
            if (perm == Permissions.AccountingCreate || perm == Permissions.AccountingEdit)
            {
                if (date <= PrefC.GetDate(PrefName.AccountingLockDate))
                {
                    if (!suppressMessage && !suppressLockDateMessage)
                    {
                        throw new Exception(Lans.g("Security", "Locked by Administrator."));
                    }
                    return(false);
                }
            }
            //Check the global security lock------------------------------------------------------------------------------------
            if (IsGlobalDateLock(perm, date, suppressMessage || suppressLockDateMessage, procCodeNum, procFee, sheetDefNum))
            {
                return(false);
            }
            //Check date/days limits on individual permission----------------------------------------------------------------
            if (!GroupPermissions.PermTakesDates(perm))
            {
                return(true);
            }
            //Include CEMT users, as a CEMT user could be logged in when this is checked.
            DateTime dateLimit = GetDateLimit(perm, curUser.GetGroups(true).Select(x => x.UserGroupNum).ToList());

            if (date > dateLimit)          //authorized
            {
                return(true);
            }
            //Prevents certain bugs when 1/1/1 dates are passed in and compared----------------------------------------------
            //Handling of min dates.  There might be others, but we have to handle them individually to avoid introduction of bugs.
            if (perm == Permissions.ClaimDelete ||      //older versions did not have SecDateEntry
                perm == Permissions.ClaimSentEdit ||              //no date sent was entered before setting claim received
                perm == Permissions.ProcComplEdit ||              //a completed procedure with a min date.
                perm == Permissions.ProcComplEditLimited ||              //because ProcComplEdit was in this list
                perm == Permissions.ProcExistingEdit ||              //a completed EO or EC procedure with a min date.
                perm == Permissions.InsPayEdit ||              //a claim payment with no date.
                perm == Permissions.InsWriteOffEdit ||              //older versions did not have SecDateEntry or DateEntryC
                perm == Permissions.TreatPlanEdit ||
                perm == Permissions.AdjustmentEdit ||
                perm == Permissions.CommlogEdit ||              //usually from a conversion
                perm == Permissions.ProcDelete ||              //because older versions did not set the DateEntryC.
                perm == Permissions.ImageDelete ||              //In case an image has a creation date of DateTime.MinVal.
                perm == Permissions.PerioEdit ||              //In case perio chart exam has a creation date of DateTime.MinValue.
                perm == Permissions.PreAuthSentEdit ||              //older versions did not have SecDateEntry
                perm == Permissions.ClaimProcReceivedEdit)                 //
            {
                if (date.Year < 1880 && dateLimit.Year < 1880)
                {
                    return(true);
                }
            }
            if (!suppressMessage)
            {
                throw new Exception(Lans.g("Security", "Not authorized for") + "\r\n"
                                    + GroupPermissions.GetDesc(perm) + "\r\n" + Lans.g("Security", "Date limitation"));
            }
            return(false);
        }
Exemple #25
0
        public static string GetChangesDescription(TaskHist taskCur, TaskHist taskNext)
        {
            if (taskCur.Descript.StartsWith("This task was cut from task list ") || taskCur.Descript.StartsWith("This task was copied from task "))
            {
                return(taskCur.Descript);
            }
            if (taskCur.DateTimeEntry == DateTime.MinValue)
            {
                return(Lans.g("TaskHists", "New task."));
            }
            StringBuilder strb = new StringBuilder();

            strb.Append("");
            if (taskNext.TaskListNum != taskCur.TaskListNum)
            {
                string   descOne  = Lans.g("TaskHists", "(DELETED)");
                string   descTwo  = Lans.g("TaskHists", "(DELETED)");
                TaskList taskList = TaskLists.GetOne(taskCur.TaskListNum);
                if (taskList != null)
                {
                    descOne = taskList.Descript;
                }
                taskList = TaskLists.GetOne(taskNext.TaskListNum);
                if (taskList != null)
                {
                    descTwo = taskList.Descript;
                }
                strb.Append(Lans.g("TaskHists", "Task list changed from") + " " + descOne + " " + Lans.g("TaskHists", "to") + " " + descTwo + ".\r\n");
            }
            if (taskNext.ObjectType != taskCur.ObjectType)
            {
                strb.Append(Lans.g("TaskHists", "Task attachment changed from") + " "
                            + taskCur.ObjectType.ToString() + " " + Lans.g("TaskHists", "to") + " " + taskNext.ObjectType.ToString() + ".\r\n");
            }
            if (taskNext.KeyNum != taskCur.KeyNum)
            {
                strb.Append(Lans.g("TaskHists", "Task account attachment changed.") + "\r\n");
            }
            if (taskNext.Descript != taskCur.Descript && !taskNext.Descript.StartsWith("This task was cut from task list ") &&
                !taskNext.Descript.StartsWith("This task was copied from task "))
            {
                //We change the description of a task when it is cut/copied.
                //This prevents the history grid from showing a description changed when it wasn't changed by the user.
                strb.Append(Lans.g("TaskHists", "Task description changed.") + "\r\n");
            }
            if (taskNext.TaskStatus != taskCur.TaskStatus)
            {
                strb.Append(Lans.g("TaskHists", "Task status changed from") + " "
                            + taskCur.TaskStatus.ToString() + " " + Lans.g("TaskHists", "to") + " " + taskNext.TaskStatus.ToString() + ".\r\n");
            }
            if (taskNext.DateTimeEntry != taskCur.DateTimeEntry)
            {
                strb.Append(Lans.g("TaskHists", "Task date added changed from") + " "
                            + taskCur.DateTimeEntry.ToString()
                            + " " + Lans.g("TaskHists", "to") + " "
                            + taskNext.DateTimeEntry.ToString() + ".\r\n");
            }
            if (taskNext.UserNum != taskCur.UserNum)
            {
                strb.Append(Lans.g("TaskHists", "Task author changed from ")
                            + Userods.GetUser(taskCur.UserNum).UserName
                            + " " + Lans.g("TaskHists", "to") + " "
                            + Userods.GetUser(taskNext.UserNum).UserName + ".\r\n");
            }
            if (taskNext.DateTimeFinished != taskCur.DateTimeFinished)
            {
                strb.Append(Lans.g("TaskHists", "Task date finished changed from") + " "
                            + taskCur.DateTimeFinished.ToString()
                            + " " + Lans.g("TaskHists", "to") + " "
                            + taskNext.DateTimeFinished.ToString() + ".\r\n");
            }
            if (taskNext.PriorityDefNum != taskCur.PriorityDefNum)
            {
                strb.Append(Lans.g("TaskHists", "Task priority changed from") + " "
                            + Defs.GetDef(DefCat.TaskPriorities, taskCur.PriorityDefNum).ItemName
                            + " " + Lans.g("TaskHists", "to") + " "
                            + Defs.GetDef(DefCat.TaskPriorities, taskNext.PriorityDefNum).ItemName + ".\r\n");
            }
            if (taskCur.IsNoteChange)              //Using taskOld because the notes changed from the old one to the new one.
            {
                strb.Append(Lans.g("TaskHists", "Task notes changed."));
            }
            return(strb.ToString());
        }
Exemple #26
0
        ///<summary>Surrond with Try/Catch. Error messages will be thrown to caller.</summary>
        public static bool IsGlobalDateLock(Permissions perm, DateTime date, bool isSilent = false, long codeNum = 0, double procFee = -1, long sheetDefNum = 0)
        {
            if (!(new[] {
                Permissions.AdjustmentCreate
                , Permissions.AdjustmentEdit
                , Permissions.PaymentCreate
                , Permissions.PaymentEdit
                , Permissions.ProcComplCreate
                , Permissions.ProcComplEdit
                , Permissions.ProcExistingEdit
                //,Permissions.ProcComplEditLimited
                //,Permissions.ImageDelete
                , Permissions.InsPayCreate
                , Permissions.InsPayEdit
                //,Permissions.InsWriteOffEdit//per Nathan 7/5/2016 this should not be affected by the global date lock
                , Permissions.SheetEdit
                , Permissions.SheetDelete
                , Permissions.CommlogEdit
                //,Permissions.ClaimDelete //per Nathan 01/18/2018 this should not be affected by the global date lock
                , Permissions.PayPlanEdit
                //,Permissions.ClaimHistoryEdit //per Nathan & Mark 03/01/2018 this should not be affected by the global lock date, not financial data.
            }).Contains(perm))
            {
                return(false);               //permission being checked is not affected by global lock date.
            }
            if (date.Year == 1)
            {
                return(false);               //Invalid or MinDate passed in.
            }
            if (!PrefC.GetBool(PrefName.SecurityLockIncludesAdmin) && GroupPermissions.HasPermission(Security.CurUser, Permissions.SecurityAdmin, 0))
            {
                return(false);               //admins are never affected by global date limitation when preference is false.
            }
            if (perm.In(Permissions.ProcComplCreate, Permissions.ProcComplEdit, Permissions.ProcExistingEdit) &&
                ProcedureCodes.CanBypassLockDate(codeNum, procFee))
            {
                return(false);
            }
            if (perm.In(Permissions.SheetEdit, Permissions.SheetDelete) && sheetDefNum > 0 && SheetDefs.CanBypassLockDate(sheetDefNum))
            {
                return(false);
            }
            //If global lock is Date based.
            if (date <= PrefC.GetDate(PrefName.SecurityLockDate))
            {
                if (!isSilent)
                {
                    MessageBox.Show(Lans.g("Security", "Locked by Administrator before ") + PrefC.GetDate(PrefName.SecurityLockDate).ToShortDateString());
                }
                return(true);
            }
            //If global lock is days based.
            int lockDays = PrefC.GetInt(PrefName.SecurityLockDays);

            if (lockDays > 0 && date <= DateTime.Today.AddDays(-lockDays))
            {
                if (!isSilent)
                {
                    MessageBox.Show(Lans.g("Security", "Locked by Administrator before ") + lockDays.ToString() + " days.");
                }
                return(true);
            }
            return(false);
        }
Exemple #27
0
        ///<summary>Throws exception if anything about the practice information is not valid.
        ///All intended exceptions are Exceptions and are already translated.</summary>
        public static void ValidateProv(Provider prov)
        {
            if (prov == null)
            {
                throw new Exception(Lans.g("Erx", "Provider not found"));
            }
            if (!prov.IsErxEnabled)
            {
                throw new ODException(Lans.g("Erx", "Erx is disabled for provider") + ": " + prov.Abbr + ".  " + Lans.g("Erx", "To enable, edit provider in Lists | Providers and acknowledge Electronic Prescription fees."));
            }
            if (prov.IsHidden)
            {
                throw new ODException(Lans.g("Erx", "Provider") + ": " + prov.Abbr + " " + Lans.g("Erx", "is hidden") + ".  " + Lans.g("Erx", "Unhide the provider to use Erx features."));
            }
            if (prov.IsNotPerson)
            {
                throw new ODException(Lans.g("Erx", "Provider must be a person") + ": " + prov.Abbr);
            }
            string fname = prov.FName.Trim();

            if (fname == "")
            {
                throw new ODException(Lans.g("Erx", "Provider first name missing") + ": " + prov.Abbr);
            }
            if (Regex.Replace(fname, "[^A-Za-z\\- ]*", "") != fname)
            {
                throw new ODException(Lans.g("Erx", "Provider first name can only contain letters, dashes, or spaces.") + ": " + prov.Abbr);
            }
            string lname = prov.LName.Trim();

            if (lname == "")
            {
                throw new ODException(Lans.g("Erx", "Provider last name missing") + ": " + prov.Abbr);
            }
            if (Regex.Replace(lname, "[^A-Za-z\\- ]*", "") != lname)          //Will catch situations such as "Dale Jr. III" and "Ross DMD".
            {
                throw new ODException(Lans.g("Erx", "Provider last name can only contain letters, dashes, or spaces.  Use the suffix box for I, II, III, Jr, or Sr") + ": " + prov.Abbr);
            }
            //prov.Suffix is not validated here. In ErxXml.cs, the suffix is converted to the appropriate suffix enumeration value, or defaults to DDS if the suffix does not make sense.
            if (prov.DEANum.ToLower() != "none" && !Regex.IsMatch(prov.DEANum, "^[A-Za-z]{2}[0-9]{7}$"))
            {
                throw new ODException(Lans.g("Erx", "Provider DEA Number must be 2 letters followed by 7 digits.  If no DEA Number, enter NONE.") + ": " + prov.Abbr);
            }
            string npi = Regex.Replace(prov.NationalProvID, "[^0-9]*", "");        //NPI with all non-numeric characters removed.

            if (npi.Length != 10)
            {
                throw new ODException(Lans.g("Erx", "Provider NPI must be exactly 10 digits") + ": " + prov.Abbr);
            }
            if (prov.StateLicense == "")
            {
                throw new ODException(Lans.g("Erx", "Provider state license missing") + ": " + prov.Abbr);
            }
            if (StateCodes.IndexOf(prov.StateWhereLicensed.ToUpper()) < 0)
            {
                throw new ODException(Lans.g("Erx", "Provider state where licensed invalid") + ": " + prov.Abbr);
            }
        }
Exemple #28
0
        ///<summary>Will throw an error if not authorized and message not suppressed.</summary>
        public static bool IsAuthorized(Permissions perm, DateTime date, bool suppressMessage, long userGroupNum)
        {
            //No need to check RemotingRole; no call to db.
            if (!GroupPermissions.HasPermission(userGroupNum, perm))
            {
                if (!suppressMessage)
                {
                    throw new Exception(Lans.g("Security", "Not authorized for") + "\r\n" + GroupPermissions.GetDesc(perm));
                }
                return(false);
            }
            if (perm == Permissions.AccountingCreate || perm == Permissions.AccountingEdit)
            {
                if (date <= PrefC.GetDate(PrefName.AccountingLockDate))
                {
                    if (!suppressMessage)
                    {
                        throw new Exception(Lans.g("Security", "Locked by Administrator."));
                    }
                    return(false);
                }
            }
            //the list below is NOT the list of permissions that take dates. See GroupPermissions.PermTakesDates().
            if (perm == Permissions.AdjustmentCreate ||
                perm == Permissions.AdjustmentEdit ||
                perm == Permissions.PaymentCreate ||
                perm == Permissions.PaymentEdit ||
                perm == Permissions.ProcComplCreate ||
                perm == Permissions.ProcComplEdit ||
                perm == Permissions.ImageDelete ||
                perm == Permissions.InsPayCreate ||
                perm == Permissions.InsPayEdit ||
                perm == Permissions.SheetEdit ||
                perm == Permissions.CommlogEdit
                )
            {
                if (date.Year > 1 &&          //if a valid date was passed in
                    date <= PrefC.GetDate(PrefName.SecurityLockDate))                       //and that date is earlier than the lock
                {
                    if (PrefC.GetBool(PrefName.SecurityLockIncludesAdmin) ||                //if admins are locked out too
                        !GroupPermissions.HasPermission(userGroupNum, Permissions.SecurityAdmin))                          //or is not an admin
                    {
                        if (!suppressMessage)
                        {
                            throw new Exception(Lans.g("Security", "Locked by Administrator before ") + PrefC.GetDate(PrefName.SecurityLockDate).ToShortDateString());
                        }
                        return(false);
                    }
                }
                if (date.Year > 1 &&          //if a valid date was passed in
                    PrefC.GetInt(PrefName.SecurityLockDays) > 0 &&
                    date <= DateTime.Today.AddDays(-PrefC.GetInt(PrefName.SecurityLockDays)))                       //and that date is earlier than the lock
                {
                    if (PrefC.GetBool(PrefName.SecurityLockIncludesAdmin) ||                //if admins are locked out too
                        !GroupPermissions.HasPermission(userGroupNum, Permissions.SecurityAdmin))                          //or is not an admin
                    {
                        if (!suppressMessage)
                        {
                            throw new Exception(Lans.g("Security", "Locked by Administrator before ") + PrefC.GetInt(PrefName.SecurityLockDays).ToString() + " days.");
                        }
                        return(false);
                    }
                }
            }
            if (!GroupPermissions.PermTakesDates(perm))
            {
                return(true);
            }
            DateTime dateLimit = GetDateLimit(perm, userGroupNum);

            if (date > dateLimit)          //authorized
            {
                return(true);
            }
            //Handling of min dates.  There might be others, but we have to handle them individually to avoid introduction of bugs.
            if (perm == Permissions.ClaimSentEdit ||      //no date sent was entered before setting claim received
                perm == Permissions.ProcComplEdit ||              //a completed procedure with a min date.
                perm == Permissions.InsPayEdit ||              //a claim payment with no date.
                perm == Permissions.TreatPlanEdit ||
                perm == Permissions.AdjustmentEdit ||
                perm == Permissions.CommlogEdit ||              //usually from a conversion
                perm == Permissions.ProcDelete)                 //because older versions did not set the DateEntryC.
            {
                if (date.Year < 1880 && dateLimit.Year < 1880)
                {
                    return(true);
                }
            }
            if (!suppressMessage)
            {
                throw new Exception(Lans.g("Security", "Not authorized for") + "\r\n"
                                    + GroupPermissions.GetDesc(perm) + "\r\n" + Lans.g("Security", "Date limitation"));
            }
            return(false);
        }
Exemple #29
0
        ///<summary>Surround with try/catch, because it will throw an exception if any patient is using this def.</summary>
        public static void Delete(DiseaseDef def)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                Meth.GetVoid(MethodBase.GetCurrentMethod(), def);
                return;
            }
            if (PrefC.GetLong(PrefName.ProblemsIndicateNone) == def.DiseaseDefNum)
            {
                throw new ApplicationException(Lans.g("DiseaseDef", "Not allowed to delete. In use as preference \"ProblemsIndicateNone\" in Setup>>Modules."));
            }
            //Validate patient attached
            string command = "SELECT LName,FName,patient.PatNum FROM patient,disease WHERE "
                             + "patient.PatNum=disease.PatNum "
                             + "AND disease.DiseaseDefNum='" + POut.Long(def.DiseaseDefNum) + "' ";

            if (DataConnection.DBtype == DatabaseType.MySql)
            {
                command += "GROUP BY patient.PatNum";
            }
            else              //Oracle
            {
                command += "GROUP BY LName,FName,patient.PatNum";
            }
            DataTable table = Db.GetTable(command);

            if (table.Rows.Count > 0)
            {
                string s = Lans.g("DiseaseDef", "Not allowed to delete. Already in use by ") + table.Rows.Count.ToString()
                           + " " + Lans.g("DiseaseDef", "patients, including") + " \r\n";
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    if (i > 5)
                    {
                        break;
                    }
                    s += table.Rows[i][0].ToString() + ", " + table.Rows[i][1].ToString() + "\r\n";
                }
                throw new ApplicationException(s);
            }
            //Validate edu resource attached
            command = "SELECT COUNT(*) FROM eduresource WHERE eduresource.DiseaseDefNum='" + POut.Long(def.DiseaseDefNum) + "'";
            int num = PIn.Int(Db.GetCount(command));

            if (num > 0)
            {
                string s = Lans.g("DiseaseDef", "Not allowed to delete.  Already attached to an EHR educational resource.");
                throw new ApplicationException(s);
            }
            //Validate family health history attached
            command = "SELECT LName,FName,patient.PatNum FROM patient,familyhealth "
                      + "WHERE patient.PatNum=familyhealth.PatNum "
                      + "AND familyhealth.DiseaseDefNum='" + POut.Long(def.DiseaseDefNum) + "' ";
            if (DataConnection.DBtype == DatabaseType.MySql)
            {
                command += "GROUP BY patient.PatNum";
            }
            else              //Oracle
            {
                command += "GROUP BY LName,FName,patient.PatNum";
            }
            table = Db.GetTable(command);
            if (table.Rows.Count > 0)
            {
                string s = Lans.g("DiseaseDef", "Not allowed to delete. Already in use by") + " " + table.Rows.Count.ToString()
                           + " " + Lans.g("DiseaseDef", "patients' family history, including") + ": \r\n";
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    if (i > 5)
                    {
                        break;
                    }
                    s += "#" + table.Rows[i]["PatNum"].ToString() + " " + table.Rows[i]["LName"].ToString() + ", " + table.Rows[i]["FName"].ToString() + "\r\n";
                }
                throw new ApplicationException(s);
            }
            //End of validation
            command = "DELETE FROM diseasedef WHERE DiseaseDefNum =" + POut.Long(def.DiseaseDefNum);
            Db.NonQ(command);
        }
Exemple #30
0
 protected override void FillCacheIfNeeded()
 {
     Lans.GetTableFromCache(false);
 }