Exemplo n.º 1
0
        /// <summary>Always saves as bmp.  So the 'paste to mount' logic needs to be changed to prevent conversion to bmp.</summary>
        public static Document ImportImageToMount(Bitmap image, short rotationAngle, long mountItemNum, long docCategory, Patient pat)
        {
            string   patFolder     = GetPatientFolder(pat, GetPreferredAtoZpath());
            string   fileExtention = ".bmp";          //The file extention to save the greyscale image as.
            Document doc           = new Document();

            doc.MountItemNum   = mountItemNum;
            doc.DegreesRotated = rotationAngle;
            doc.ImgType        = ImageType.Radiograph;
            doc.FileName       = fileExtention;
            doc.DateCreated    = DateTime.Today;
            doc.PatNum         = pat.PatNum;
            doc.DocCategory    = docCategory;
            doc.WindowingMin   = PrefC.GetInt(PrefName.ImageWindowingMin);
            doc.WindowingMax   = PrefC.GetInt(PrefName.ImageWindowingMax);
            Documents.Insert(doc, pat);           //creates filename and saves to db
            doc = Documents.GetByNum(doc.DocNum);
            try {
                SaveDocument(doc, image, ImageFormat.Bmp, patFolder);
            }
            catch {
                Documents.Delete(doc);
                throw;
            }
            return(doc);
        }
Exemplo n.º 2
0
        ///<summary>This should be called when the user is changed (excluding temporay logins such as job review logins).
        ///In the future, we could also call this if we detect the office theme has changed via signal preference cache refresh or if
        ///another person using the same login information changes the theme for a group of users.</summary>
        public static void SetThemeForUserIfNeeded()
        {
            OdTheme themeDefault = OdTheme.Standard;

            try {
                themeDefault = (OdTheme)PrefC.GetInt(PrefName.ColorTheme);
            }
            catch {
                //try/catch in case you are trying to convert from an older version of OD and need to update the DB.
            }
            if (Security.CurUser == null)           //no current user, set to the default practice theme.
            {
                ODColorTheme.SetTheme(themeDefault);
                return;
            }
            UserOdPref themePref = UserOdPrefs.GetByUserAndFkeyType(Security.CurUser.UserNum, UserOdFkeyType.UserTheme).FirstOrDefault();

            //user theme not allowed or hasn't been set
            if (!PrefC.GetBool(PrefName.ThemeSetByUser) || themePref == null)
            {
                ODColorTheme.SetTheme(themeDefault);
            }
            else if (themePref != null)           //user theme allowed but needs to update for user pref
            {
                ODColorTheme.SetTheme((OdTheme)themePref.Fkey);
            }
        }
Exemplo n.º 3
0
        ///<summary>Adds procedures to the appointment.</summary>
        ///<returns>First item of tuple is the newly added procedures. Second item is all procedures for the appointment.</returns>
        public static ODTuple <List <Procedure>, List <Procedure> > QuickAddProcs(Appointment apt, Patient pat, List <string> listCodesToAdd, long provNum,
                                                                                  long provHyg, List <InsSub> SubList, List <InsPlan> listInsPlans, List <PatPlan> listPatPlans, List <Benefit> listBenefits)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <ODTuple <List <Procedure>, List <Procedure> > >(MethodBase.GetCurrentMethod(), apt, pat, listCodesToAdd, provNum,
                                                                                       provHyg, SubList, listInsPlans, listPatPlans, listBenefits));
            }
            Procedures.SetDateFirstVisit(apt.AptDateTime.Date, 1, pat);
            List <ClaimProc> ClaimProcList  = ClaimProcs.Refresh(apt.PatNum);
            List <Procedure> listAddedProcs = new List <Procedure>();

            foreach (string code in listCodesToAdd)
            {
                Procedure proc = new Procedure();
                proc.PatNum = apt.PatNum;
                ProcedureCode procCodeCur = ProcedureCodes.GetProcCode(code);
                proc.CodeNum  = procCodeCur.CodeNum;
                proc.ProcDate = apt.AptDateTime.Date;
                proc.DateTP   = DateTime.Today;
                #region ProvNum
                proc.ProvNum = provNum;
                if (procCodeCur.ProvNumDefault != 0)               //Override provider for procedures with a default provider
                //This provider might be restricted to a different clinic than this user.
                {
                    proc.ProvNum = procCodeCur.ProvNumDefault;
                }
                else if (procCodeCur.IsHygiene && provHyg != 0)
                {
                    proc.ProvNum = provHyg;
                }
                #endregion ProvNum
                proc.ClinicNum      = apt.ClinicNum;
                proc.MedicalCode    = procCodeCur.MedicalCode;
                proc.ProcFee        = Procedures.GetProcFee(pat, listPatPlans, SubList, listInsPlans, proc.CodeNum, proc.ProvNum, proc.ClinicNum, proc.MedicalCode);
                proc.ProcStatus     = ProcStat.TP;
                proc.SiteNum        = pat.SiteNum;
                proc.RevCode        = procCodeCur.RevenueCodeDefault;
                proc.BaseUnits      = procCodeCur.BaseUnits;
                proc.DiagnosticCode = PrefC.GetString(PrefName.ICD9DefaultForNewProcs);
                proc.PlaceService   = (PlaceOfService)PrefC.GetInt(PrefName.DefaultProcedurePlaceService);            //Default Proc Place of Service for the Practice is used.
                if (Userods.IsUserCpoe(Security.CurUser))
                {
                    //This procedure is considered CPOE because the provider is the one that has added it.
                    proc.IsCpoe = true;
                }
                proc.Note = ProcCodeNotes.GetNote(proc.ProvNum, proc.CodeNum, proc.ProcStatus);
                Procedures.Insert(proc);                //recall synch not required
                Procedures.ComputeEstimates(proc, pat.PatNum, ClaimProcList, false, listInsPlans, listPatPlans, listBenefits, pat.Age, SubList);
                listAddedProcs.Add(proc);
            }
            return(new ODTuple <List <Procedure>, List <Procedure> >(listAddedProcs, Procedures.GetProcsForApptEdit(apt)));
        }
Exemplo n.º 4
0
        ///<summary>Used in the timecard to track hours worked per week when the week started in a previous time period.  This gets all the hours of the first week before the date listed.  Also adds in any adjustments for that week.</summary>
        public static TimeSpan GetWeekTotal(long empNum, DateTime date)
        {
            //No need to check RemotingRole; no call to db.
            TimeSpan retVal = new TimeSpan(0);

            //If the first day of the pay period is the starting date for the overtime, then there is no need to retrieve any times from the previous pay period.
            if (date.DayOfWeek == (DayOfWeek)PrefC.GetInt(PrefName.TimeCardOvertimeFirstDayOfWeek))
            {
                return(retVal);
            }
            List <ClockEvent> events = Refresh(empNum, date.AddDays(-6), date.AddDays(-1), false);

            //eg, if this is Thursday, then we are getting last Friday through this Wed.
            for (int i = 0; i < events.Count; i++)
            {
                if (events[i].TimeDisplayed1.DayOfWeek > date.DayOfWeek)                //eg, Friday > Thursday, so ignore
                {
                    continue;
                }
                retVal += events[i].TimeDisplayed2 - events[i].TimeDisplayed1;
                if (events[i].AdjustIsOverridden)
                {
                    retVal += events[i].Adjust;
                }
                else
                {
                    retVal += events[i].AdjustAuto;                  //typically zero
                }
                //ot
                if (events[i].OTimeHours != TimeSpan.FromHours(-1))               //overridden
                {
                    retVal -= events[i].OTimeHours;
                }
                else
                {
                    retVal -= events[i].OTimeAuto;                  //typically zero
                }
            }
            //now, adjustments
            List <TimeAdjust> TimeAdjustList = TimeAdjusts.Refresh(empNum, date.AddDays(-6), date.AddDays(-1));

            for (int i = 0; i < TimeAdjustList.Count; i++)
            {
                if (TimeAdjustList[i].TimeEntry.DayOfWeek > date.DayOfWeek)                 //eg, Friday > Thursday, so ignore
                {
                    continue;
                }
                retVal += TimeAdjustList[i].RegHours;
            }
            return(retVal);
        }
Exemplo n.º 5
0
        ///<summary>Builds JOIN clauses appropriate to the type of GlobalFilterType.  Returns empty string if not filtering.  Pass filterClinicFkey=0
        ///to intentionally bypass filtering.</summary>
        public static string BuildFilterJoins(long filterClinicFkey)
        {
            string command = string.Empty;

            //Only add JOINs if filtering.  Filtering will never happen if clinics are turned off, because regions link via clinics.
            if ((GlobalTaskFilterType)PrefC.GetInt(PrefName.TasksGlobalFilterType) == GlobalTaskFilterType.Disabled || filterClinicFkey == 0 ||
                !PrefC.HasClinicsEnabled)
            {
                return(command);
            }
            command += " LEFT JOIN patient ON task.ObjectType=" + POut.Int((int)TaskObjectType.Patient) + " AND task.KeyNum=patient.PatNum ";
            command += " INNER JOIN tasklist tasklistfortask ON task.TaskListNum=tasklistfortask.TaskListNum ";
            command += " LEFT JOIN appointment ON task.ObjectType=" + POut.Int((int)TaskObjectType.Appointment) + " AND task.KeyNum=appointment.AptNum ";
            return(command);
        }
Exemplo n.º 6
0
        ///<summary>Builds WHERE clauses appropriate to the type of GlobalFilterType.  Returns empty string if not filtering.  Pass filterClinicFkey=0
        ///and filterRegionFkey=0 to intentionally bypass filtering.</summary>
        public static string BuildFilterWhereClause(long currentUserNum, long filterClinicFkey, long filterRegionFkey)
        {
            string command = string.Empty;

            //Only add WHERE clauses if filtering.  Filtering will never happen if clinics are turned off, because regions link via clinics.
            if ((GlobalTaskFilterType)PrefC.GetInt(PrefName.TasksGlobalFilterType) == GlobalTaskFilterType.Disabled ||
                (filterClinicFkey == 0 && filterRegionFkey == 0) || !PrefC.HasClinicsEnabled)
            {
                return(command);
            }
            List <Clinic> listUnrestrictedClinics = Clinics.GetAllForUserod(Userods.GetUser(currentUserNum));
            List <long>   listClinicNums          = new List <long>()
            {
                0
            };                                                           //All users can see Tasks associated to HQ clinic or "0" region.
            List <long> listClinicNumsInRegion = new List <long>()
            {
                0
            };                                                                                                          //All users can see Tasks associated to HQ clinic or "0" region.
            List <long> listUnrestrictedClinicNums         = listUnrestrictedClinics.Select(x => x.ClinicNum).ToList(); //User can view these clinicnums.
            List <long> listUnrestrictedClinicNumsInRegion = listUnrestrictedClinics.FindAll(x => x.Region == filterRegionFkey).Select(x => x.ClinicNum).ToList();

            if (filterClinicFkey.In(listUnrestrictedClinicNums))             //Make sure user is not restricted for this clinic.
            {
                listClinicNums.Add(filterClinicFkey);
            }
            listClinicNumsInRegion.AddRange(listUnrestrictedClinicNumsInRegion);
            string strClinicFilterNums = string.Join(",", listClinicNums.Select(x => POut.Long(x)));
            string strRegionFilterNums = string.Join(",", listClinicNumsInRegion.Select(x => POut.Long(x)));
            //Clause for TaskLists that have Default filter.
            string cmdFilterTaskListByDefault = "(tasklistfortask.GlobalTaskFilterType=" + POut.Long((long)GlobalTaskFilterType.Default)
                                                + GetDefaultFilterTypeString((GlobalTaskFilterType)PrefC.GetInt(PrefName.TasksGlobalFilterType), strClinicFilterNums, strRegionFilterNums) + ") ";
            //Clause for TaskLists that have None filter.
            string cmdFilterTaskListByNone = "(tasklistfortask.GlobalTaskFilterType=" + POut.Long((long)GlobalTaskFilterType.None) + ")";
            //Clause for TaskLists that have Clinic filter.
            string cmdFilterTaskListByClinic = "(tasklistfortask.GlobalTaskFilterType=" + POut.Long((long)GlobalTaskFilterType.Clinic)
                                               + " AND (patient.ClinicNum IN (" + strClinicFilterNums + ") OR appointment.ClinicNum IN (" + strClinicFilterNums + "))) ";
            //Clause for TaskLists that have Region filter.
            string cmdFilterTaskListByRegion = "(tasklistfortask.GlobalTaskFilterType=" + POut.Long((long)GlobalTaskFilterType.Region)
                                               + " AND (patient.ClinicNum IN (" + strRegionFilterNums + ") OR appointment.ClinicNum IN (" + strRegionFilterNums + "))) ";
            //Clause for Tasks that are not connected to a patient or clinic.
            string cmdTaskClinicIsNull = "((patient.ClinicNum IS NULL) AND (appointment.ClinicNum IS NULL))";

            command = " AND (" + cmdFilterTaskListByDefault + " OR " + cmdFilterTaskListByNone + " OR " + cmdFilterTaskListByClinic + " OR "
                      + cmdFilterTaskListByRegion + "OR " + cmdTaskClinicIsNull + ") ";
            return(command);
        }
Exemplo n.º 7
0
        ///<summary>Returns number of work weeks spanned by dates.  Example: "11-01-2013"(Friday), to "11-14-2013"(Thursday) spans 3 weeks, if the workweek starts on Sunday it would
        ///return a list containing "10-27-2013"(Sunday),"11-03-2013"(Sunday),and"11-10-2013"(Sunday).  Used to determine which week time adjustments and clock events belong to when totalling timespans.</summary>
        private static List <DateTime> weekStartHelper(DateTime startDate, DateTime stopDate)
        {
            List <DateTime> retVal = new List <DateTime>();
            DayOfWeek       fdow   = (DayOfWeek)PrefC.GetInt(PrefName.TimeCardOvertimeFirstDayOfWeek);

            for (int i = 0; i < 7; i++)       //start date of first week.
            {
                if (startDate.AddDays(-i).DayOfWeek == fdow)
                {
                    retVal.Add(startDate.AddDays(-i));                    //found and added start date of first week.
                    break;
                }
            }
            while (retVal[retVal.Count - 1].AddDays(7) < stopDate)         //add start of each workweek until we are past the dateStop
            {
                retVal.Add(retVal[retVal.Count - 1].AddDays(7));
            }
            return(retVal);
        }
Exemplo n.º 8
0
        ///<summary>MUST be validated by IsValidEntry before coming here. All user entered toothnumbers are run through this method which
        ///automatically checks to see if using international toothnumbers. So the procedurelog class will always contain the american toothnum.</summary>
        public static string GetToothId(string tooth_label)
        {
            ToothNumberingNomenclature nomenclature = (ToothNumberingNomenclature)PrefC.GetInt(PrefName.UseInternationalToothNumbers);

            return(GetToothId(tooth_label, nomenclature));
        }
Exemplo n.º 9
0
        public static List <List <int> > GetProdInc(DateTime dateFrom, DateTime dateTo)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <List <List <int> > >(MethodBase.GetCurrentMethod(), dateFrom, dateTo));
            }
#if DEBUG
            _elapsedTimeProdInc = "";
            System.Diagnostics.Stopwatch stopWatch      = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch stopWatchTotal = new System.Diagnostics.Stopwatch();
            _elapsedTimeProdInc = "Elapsed time for GetProdInc:\r\n";
            stopWatch.Restart();
            stopWatchTotal.Restart();
#endif
            string command;
            command = @"SELECT procedurelog.ProcDate,
				SUM(procedurelog.ProcFee*(procedurelog.UnitQty+procedurelog.BaseUnits))-IFNULL(SUM(claimproc.WriteOff),0)
				FROM procedurelog
				LEFT JOIN claimproc ON procedurelog.ProcNum=claimproc.ProcNum
				AND claimproc.Status='7' /*only CapComplete writeoffs are subtracted here*/
				WHERE procedurelog.ProcStatus = '2'
				AND procedurelog.ProcDate >= "                 + POut.Date(dateFrom) + @"
				AND procedurelog.ProcDate <= "                 + POut.Date(dateTo) + @"
				GROUP BY MONTH(procedurelog.ProcDate)"                ;
            DataTable tableProduction = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProdInc += "tableProduction: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            command = @"SELECT AdjDate,
				SUM(AdjAmt)
				FROM adjustment
				WHERE AdjDate >= "                 + POut.Date(dateFrom) + @"
				AND AdjDate <= "                 + POut.Date(dateTo) + @"
				GROUP BY MONTH(AdjDate)"                ;
            DataTable tableAdj = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProdInc += "tableAdj: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            switch ((PPOWriteoffDateCalc)PrefC.GetInt(PrefName.ReportsPPOwriteoffDefaultToProcDate))
            {
            case PPOWriteoffDateCalc.InsPayDate:
                command = "SELECT "
                          + "claimproc.DateCP,"
                          + "SUM(claimproc.WriteOff) "
                          + "FROM claimproc "
                          + "WHERE claimproc.DateCP >= " + POut.Date(dateFrom) + " "
                          + "AND claimproc.DateCP <= " + POut.Date(dateTo) + " "
                          + "AND claimproc.Status IN (" + (int)ClaimProcStatus.Received + "," + (int)ClaimProcStatus.Supplemental + ") "             //Received or supplemental
                          + "GROUP BY MONTH(claimproc.DateCP)";
                break;

            case PPOWriteoffDateCalc.ProcDate:
                command = "SELECT "
                          + "claimproc.ProcDate,"
                          + "SUM(claimproc.WriteOff) "
                          + "FROM claimproc "
                          + "WHERE claimproc.ProcDate >= " + POut.Date(dateFrom) + " "
                          + "AND claimproc.ProcDate <= " + POut.Date(dateTo) + " "
                          + "AND claimproc.Status IN (" + (int)ClaimProcStatus.Received + "," + (int)ClaimProcStatus.Supplemental + "," + (int)ClaimProcStatus.NotReceived + ") "
                          + "GROUP BY MONTH(claimproc.ProcDate)";
                break;

            case PPOWriteoffDateCalc.ClaimPayDate:                      //Means preference is PPOWriteoffDateCalc.InsDate, or PPOWriteoffDateCalc.ClaimPayDate.
                command = "SELECT "
                          + "claimsnaptshot.DateTEntry,"
                          + "SUM(claimsnapshot.WriteOff) "
                          + "FROM claimproc "
                          + "INNER JOIN claimsnapshot ON claimsnapshot.ClaimProcNum=claimproc.ClaimProcNum "
                          + "AND claimsnapshot.DateTEntry >= " + POut.Date(dateFrom) + " "
                          + "AND claimsnapshot.DateTEntry <= " + POut.Date(dateTo) + " "
                          + "WHERE claimproc.Status IN (" + (int)ClaimProcStatus.Received + "," + (int)ClaimProcStatus.Supplemental + ") "
                          + "GROUP BY MONTH(claimsnaptshot.DateTEntry)";
                break;
            }
            DataTable tableWriteoff = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProdInc += "tableWriteoff: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            command = "SELECT "
                      + "paysplit.DatePay,"
                      + "SUM(paysplit.SplitAmt) "
                      + "FROM paysplit "
                      + "WHERE paysplit.IsDiscount=0 "
                      + "AND paysplit.DatePay >= " + POut.Date(dateFrom) + " "
                      + "AND paysplit.DatePay <= " + POut.Date(dateTo) + " "
                      + "GROUP BY MONTH(paysplit.DatePay)";
            DataTable tablePay = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProdInc += "tablePay: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            command = "SELECT claimpayment.CheckDate,SUM(claimproc.InsPayamt) "
                      + "FROM claimpayment,claimproc WHERE "
                      + "claimproc.ClaimPaymentNum = claimpayment.ClaimPaymentNum "
                      + "AND claimpayment.CheckDate >= " + POut.Date(dateFrom) + " "
                      + "AND claimpayment.CheckDate <= " + POut.Date(dateTo) + " "
                      + " GROUP BY claimpayment.CheckDate ORDER BY checkdate";
            DataTable tableIns = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            stopWatchTotal.Stop();
            _elapsedTimeProdInc += "tableIns: " + stopWatch.Elapsed.ToString() + "\r\n";
            _elapsedTimeProdInc += "Total: " + stopWatchTotal.Elapsed.ToString();
            if (_showElapsedTimesForDebug)
            {
                System.Windows.Forms.MessageBox.Show(_elapsedTimeProdInc);
            }
#endif
            //production--------------------------------------------------------------------
            List <int> listInt;
            listInt = new List <int>();
            for (int i = 0; i < 12; i++)
            {
                decimal  prod        = 0;
                decimal  adjust      = 0;
                decimal  inswriteoff = 0;
                DateTime datePeriod  = dateFrom.AddMonths(i);             //only the month and year are important
                for (int j = 0; j < tableProduction.Rows.Count; j++)
                {
                    if (datePeriod.Year == PIn.Date(tableProduction.Rows[j][0].ToString()).Year &&
                        datePeriod.Month == PIn.Date(tableProduction.Rows[j][0].ToString()).Month)
                    {
                        prod += PIn.Decimal(tableProduction.Rows[j][1].ToString());
                    }
                }
                for (int j = 0; j < tableAdj.Rows.Count; j++)
                {
                    if (datePeriod.Year == PIn.Date(tableAdj.Rows[j][0].ToString()).Year &&
                        datePeriod.Month == PIn.Date(tableAdj.Rows[j][0].ToString()).Month)
                    {
                        adjust += PIn.Decimal(tableAdj.Rows[j][1].ToString());
                    }
                }
                for (int j = 0; j < tableWriteoff.Rows.Count; j++)
                {
                    if (datePeriod.Year == PIn.Date(tableWriteoff.Rows[j][0].ToString()).Year &&
                        datePeriod.Month == PIn.Date(tableWriteoff.Rows[j][0].ToString()).Month)
                    {
                        inswriteoff += PIn.Decimal(tableWriteoff.Rows[j][1].ToString());
                    }
                }
                listInt.Add((int)(prod + adjust - inswriteoff));
            }
            List <List <int> > retVal = new List <List <int> >();
            retVal.Add(listInt);
            //income----------------------------------------------------------------------
            listInt = new List <int>();
            for (int i = 0; i < 12; i++)
            {
                decimal  ptincome   = 0;
                decimal  insincome  = 0;
                DateTime datePeriod = dateFrom.AddMonths(i);              //only the month and year are important
                for (int j = 0; j < tablePay.Rows.Count; j++)
                {
                    if (datePeriod.Year == PIn.Date(tablePay.Rows[j][0].ToString()).Year &&
                        datePeriod.Month == PIn.Date(tablePay.Rows[j][0].ToString()).Month)
                    {
                        ptincome += PIn.Decimal(tablePay.Rows[j][1].ToString());
                    }
                }
                for (int j = 0; j < tableIns.Rows.Count; j++)           //
                {
                    if (datePeriod.Year == PIn.Date(tableIns.Rows[j][0].ToString()).Year &&
                        datePeriod.Month == PIn.Date(tableIns.Rows[j][0].ToString()).Month)
                    {
                        insincome += PIn.Decimal(tableIns.Rows[j][1].ToString());
                    }
                }
                listInt.Add((int)(ptincome + insincome));
            }
            retVal.Add(listInt);
            return(retVal);
        }
Exemplo n.º 10
0
        public static DataTable GetProvList(DateTime dt)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetTable(MethodBase.GetCurrentMethod(), dt));
            }
#if DEBUG
            _elapsedTimeProvList = "";
            System.Diagnostics.Stopwatch stopWatch      = new System.Diagnostics.Stopwatch();
            System.Diagnostics.Stopwatch stopWatchTotal = new System.Diagnostics.Stopwatch();
            _elapsedTimeProvList = "Elapsed time for GetProvList:\r\n";
            stopWatch.Restart();
            stopWatchTotal.Restart();
#endif
            Random rnd    = new Random();
            string rndStr = rnd.Next(1000000).ToString();
            string command;
            command = "DROP TABLE IF EXISTS tempdash" + rndStr + @";";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "DROP TABLE: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            command = @"CREATE TABLE tempdash" + rndStr + @" (
				ProvNum bigint NOT NULL PRIMARY KEY,
				production decimal NOT NULL,
				income decimal NOT NULL
				) DEFAULT CHARSET=utf8"                ;
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "CREATE TABLE: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //providers
            command = @"INSERT INTO tempdash" + rndStr + @" (ProvNum)
				SELECT ProvNum
				FROM provider WHERE IsHidden=0
				ORDER BY ItemOrder"                ;
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "providers: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //production--------------------------------------------------------------------
            //procs
            command = @"UPDATE tempdash" + rndStr + @" 
				SET production=(SELECT SUM(ProcFee*(UnitQty+BaseUnits)) FROM procedurelog 
				WHERE procedurelog.ProvNum=tempdash"                 + rndStr + @".ProvNum
				AND procedurelog.ProcStatus="                 + POut.Int((int)ProcStat.C) + @"
				AND ProcDate="                 + POut.Date(dt) + ")";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "production - procs: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //capcomplete writeoffs were skipped
            //adjustments
            command = @"UPDATE tempdash" + rndStr + @" 
				SET production=production+(SELECT IFNULL(SUM(AdjAmt),0) FROM adjustment 
				WHERE adjustment.ProvNum=tempdash"                 + rndStr + @".ProvNum
				AND AdjDate="                 + POut.Date(dt) + ")";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "production - adjustments: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //insurance writeoffs
            switch ((PPOWriteoffDateCalc)PrefC.GetInt(PrefName.ReportsPPOwriteoffDefaultToProcDate))             //use procdate
            {
            case PPOWriteoffDateCalc.ProcDate:
                command = @"UPDATE tempdash" + rndStr + @" 
					SET production=production-(SELECT IFNULL(SUM(WriteOff),0) FROM claimproc 
					WHERE claimproc.ProvNum=tempdash"                     + rndStr + @".ProvNum
					AND ProcDate="                     + POut.Date(dt) + @" 
					AND (claimproc.Status=1 OR claimproc.Status=4 OR claimproc.Status=0) )"                    ;//received or supplemental or notreceived
                break;

            case PPOWriteoffDateCalc.InsPayDate:
                command = @"UPDATE tempdash" + rndStr + @" 
					SET production=production-(SELECT IFNULL(SUM(WriteOff),0) FROM claimproc 
					WHERE claimproc.ProvNum=tempdash"                     + rndStr + @".ProvNum
					AND DateCP="                     + POut.Date(dt) + @" 
					AND (claimproc.Status=1 OR claimproc.Status=4) )"                    ;//received or supplemental
                break;

            case PPOWriteoffDateCalc.ClaimPayDate:
                command = @"UPDATE tempdash" + rndStr + @" 
					SET production=production-(SELECT IFNULL(SUM(claimsnapshot.WriteOff),0) FROM claimproc cp
					INNER JOIN claimsnapshot ON cp.ClaimProcNum=claimsnapshot.ClaimProcNum
					WHERE claimproc.ProvNum=tempdash"                     + rndStr + @".ProvNum
					AND claimsnapshot.DateTEntry="                     + POut.Date(dt) + @" 
					AND (claimproc.Status=1 OR claimproc.Status=4) )"                    ;//received or supplemental
                break;
            }
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "production - writeoffs: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //income------------------------------------------------------------------------
            //patient income
            command = @"UPDATE tempdash" + rndStr + @" 
				SET income=(SELECT SUM(SplitAmt) FROM paysplit 
				WHERE paysplit.ProvNum=tempdash"                 + rndStr + @".ProvNum
				AND DatePay="                 + POut.Date(dt) + ")";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "income - patient: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //ins income
            command = @"UPDATE tempdash" + rndStr + @" 
				SET income=income+(SELECT IFNULL(SUM(InsPayAmt),0) FROM claimproc 
				WHERE claimproc.ProvNum=tempdash"                 + rndStr + @".ProvNum
				AND DateCP="                 + POut.Date(dt) + ")";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "income - insurance: " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            //final queries
            command = "SELECT * FROM tempdash" + rndStr + @"";
            DataTable table = Db.GetTable(command);
#if DEBUG
            stopWatch.Stop();
            _elapsedTimeProvList += "SELECT * : " + stopWatch.Elapsed.ToString() + "\r\n";
            stopWatch.Restart();
#endif
            command = "DROP TABLE IF EXISTS tempdash" + rndStr + @";";
            Db.NonQ(command);
#if DEBUG
            stopWatch.Stop();
            stopWatchTotal.Stop();
            _elapsedTimeProvList += "DROP TABLE: " + stopWatch.Elapsed.ToString() + "\r\n";
            _elapsedTimeProvList += "Total: " + stopWatchTotal.Elapsed.ToString();
            if (_showElapsedTimesForDebug)
            {
                System.Windows.Forms.MessageBox.Show(_elapsedTimeProvList);
            }
#endif
            return(table);
        }
Exemplo n.º 11
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);
                }
            }
            //Check the global security lock------------------------------------------------------------------------------------
            //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 the global lock is date-based:
                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 the global lock is days-based:
                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);
                    }
                }
            }
            //Check date/days limits on individual permission----------------------------------------------------------------
            if (!GroupPermissions.PermTakesDates(perm))
            {
                return(true);
            }
            DateTime dateLimit = GetDateLimit(perm, userGroupNum);

            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.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);
        }
Exemplo n.º 12
0
        ///<summary>For CPOE.  Used for both manual rx and eRx through NewCrop.  Creates or updates a medical order using the given prescription information.
        ///Since rxCui is not part of the prescription, it must be passed in as a separate parameter.
        ///If isProvOrder is true, then the medical order provNum will be set to the prescription provNum.  If isProvOrder is false, then the medical order provNum will be set to 0.
        ///The MedDescript and ErxGuid will always be copied from the prescription to the medical order and the medical order MedicationNum will be set to 0.
        ///This method return the medOrderNum for the new/updated medicationPat. Unlike most medical orders this does not create an entry in the medical order table.</summary>
        public static long InsertOrUpdateMedOrderForRx(RxPat rxPat, long rxCui, bool isProvOrder)
        {
            long          medOrderNum;
            MedicationPat medOrderOld = null;

            if (!string.IsNullOrWhiteSpace(rxPat.ErxGuid))             //This check prevents an extra db call when making a new prescription manually inside OD.
            {
                medOrderOld = MedicationPats.GetMedicationOrderByErxIdAndPat(rxPat.ErxGuid, rxPat.PatNum);
            }
            MedicationPat medOrder = null;          //The medication order corresponding to the prescription.

            if (medOrderOld == null)
            {
                medOrder = new MedicationPat();
            }
            else
            {
                medOrder = medOrderOld.Clone();              //Maintain primary key and medicationnum for the update below.
            }
            medOrder.DateStart = rxPat.RxDate;
            int numDays = PrefC.GetInt(PrefName.MedDefaultStopDays);

            if (numDays != 0)
            {
                medOrder.DateStop = rxPat.RxDate.AddDays(numDays);
            }
            medOrder.MedDescript = rxPat.Drug;
            medOrder.RxCui       = rxCui;
            if (rxCui != 0)
            {
                //The customer may not have a medication entered for this RxCui the first few times they get this particular medication back from eRx.
                //Once the customer adds the medication to their medication list, then we can automatically attach the order to the medication.
                //The reason we decided not to automatically create the medication if one does not already exist is because we do not want to
                //accidentally bloat the medication list, if for example, the user has the medication entered but has not set the RxCui on it yet.
                List <Medication> listMeds = Medications.GetAllMedsByRxCui(rxCui);
                if (listMeds.Count > 0)
                {
                    medOrder.MedicationNum = listMeds[0].MedicationNum;
                }
            }
            medOrder.ErxGuid = rxPat.ErxGuid;
            medOrder.PatNote = rxPat.Sig;
            medOrder.PatNum  = rxPat.PatNum;
            if (isProvOrder)
            {
                medOrder.ProvNum = rxPat.ProvNum;
                medOrder.IsCpoe  = true;
            }
            if (medOrderOld == null)
            {
                medOrder.IsNew = true;              //Might not be necessary, but does not hurt.
                medOrderNum    = MedicationPats.Insert(medOrder);
                //If the ErxGuid has not been set, and it is a new medication, set the ErxGuid so that the medication can be sent to DoseSpot
                if (Erx.IsManualRx(rxPat.ErxGuid))
                {
                    try {
                        int medPatNumAsInt = (int)medOrderNum;
                        rxPat.ErxGuid = Erx.OpenDentalErxPrefix + medPatNumAsInt;
                        RxPats.Update(rxPat);
                    }
                    catch (Exception ex) {
                        //If we cannot downgrade a long to an int for the ErxGuid we can simply ignore trying to update the rxPat.
                        //This is because this medication would never be sent to eRx because we would attempt this downgrade again in the exact same manner.
                        ex.DoNothing();
                    }
                }
            }
            else              //The medication order was already in our database. Update it.
            {
                medOrder.MedicationPatNum = medOrderOld.MedicationPatNum;
                MedicationPats.Update(medOrder, false);               //Don't ErxGuid here, it was already purposefully set above.
                medOrderNum = medOrder.MedicationPatNum;
            }
            return(medOrderNum);
        }
Exemplo n.º 13
0
        ///<summary>Gets the list of patients that need to be on the reactivation list based on the passed in filters.</summary>
        public static DataTable GetReactivationList(DateTime dateSince, DateTime dateStop, bool groupFamilies, bool showDoNotContact, bool isInactiveIncluded
                                                    , long provNum, long clinicNum, long siteNum, long billingType, ReactivationListSort sortBy, RecallListShowNumberReminders showReactivations)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetTable(MethodBase.GetCurrentMethod(), dateSince, dateStop, groupFamilies, showDoNotContact, isInactiveIncluded, provNum, clinicNum
                                     , siteNum, billingType, sortBy, showReactivations));
            }
            //Get information we will need to do the query
            List <long> listReactCommLogTypeDefNums = Defs.GetDefsForCategory(DefCat.CommLogTypes, isShort: true)
                                                      .FindAll(x => CommItemTypeAuto.REACT.GetDescription(useShortVersionIfAvailable: true).Equals(x.ItemValue)).Select(x => x.DefNum).ToList();
            int contactInterval = PrefC.GetInt(PrefName.ReactivationContactInterval);
            List <PatientStatus> listPatStatuses = new List <PatientStatus>()
            {
                PatientStatus.Patient, PatientStatus.Prospective
            };

            if (isInactiveIncluded)
            {
                listPatStatuses.Add(PatientStatus.Inactive);
            }
            string strPatStatuses = string.Join(",", listPatStatuses.Select(x => POut.Int((int)x)));
            //Get the raw set of patients who should be on the reactivation list
            string cmd =
                $@"SELECT 
						pat.PatNum,
						pat.LName,
						pat.FName,
						pat.MiddleI,
						pat.Preferred,
						pat.Guarantor,
						pat.PatStatus,
						pat.Birthdate,
						pat.PriProv,
						COALESCE(billingtype.ItemName,'') AS BillingType,
						pat.ClinicNum,
						pat.SiteNum,
						pat.PreferRecallMethod,
						'' AS ContactMethod,
						pat.HmPhone,
						pat.WirelessPhone,
						pat.WkPhone,
						{(groupFamilies?"COALESCE(guarantor.Email,pat.Email,'') AS Email,":"pat.Email,")}
						MAX(proc.ProcDate) AS DateLastProc,
						COALESCE(comm.DateLastContacted,'') AS DateLastContacted,
						COALESCE(comm.ContactedCount,0) AS ContactedCount,
						COALESCE(react.ReactivationNum,0) AS ReactivationNum,
						COALESCE(react.ReactivationStatus,0) AS ReactivationStatus,
						COALESCE(react.DoNotContact,0) as DoNotContact,
						react.ReactivationNote,
						guarantor.PatNum as GuarNum,
						guarantor.LName as GuarLName,
						guarantor.FName as GuarFName
					FROM patient pat
					INNER JOIN procedurelog proc ON pat.PatNum=proc.PatNum AND proc.ProcStatus={POut.Int((int)ProcStat.C)}
					LEFT JOIN appointment appt ON pat.PatNum=appt.PatNum AND appt.AptDateTime >= {DbHelper.Curdate()} 
					LEFT JOIN (
						SELECT
							commlog.PatNum,
							MAX(commlog.CommDateTime) AS DateLastContacted,
							COUNT(*) AS ContactedCount
							FROM commlog
							WHERE commlog.CommType IN ({string.Join(",",listReactCommLogTypeDefNums)}) 
							GROUP BY commlog.PatNum
					) comm ON pat.PatNum=comm.PatNum
					LEFT JOIN reactivation react ON pat.PatNum=react.PatNum
					LEFT JOIN definition billingtype ON pat.BillingType=billingtype.DefNum
					INNER JOIN patient guarantor ON pat.Guarantor=guarantor.PatNum
					WHERE pat.PatStatus IN ({strPatStatuses}) "                    ;

            cmd += provNum > 0?" AND pat.PriProv=" + POut.Long(provNum):"";
            cmd += clinicNum > -1?" AND pat.ClinicNum=" + POut.Long(clinicNum):"";      //might still want to get the 0 clinic pats
            cmd += siteNum > 0?" AND pat.SiteNum=" + POut.Long(siteNum):"";
            cmd += billingType > 0?" AND pat.BillingType=" + POut.Long(billingType):"";
            cmd += showDoNotContact?"":" AND (react.DoNotContact IS NULL OR react.DoNotContact=0)";
            cmd += contactInterval > -1?" AND (comm.DateLastContacted IS NULL OR comm.DateLastContacted <= " + POut.DateT(DateTime.Today.AddDays(-contactInterval)) + ") ":"";
            //set number of contact attempts
            int maxReminds = PrefC.GetInt(PrefName.ReactivationCountContactMax);

            if (showReactivations == RecallListShowNumberReminders.SixPlus)
            {
                cmd += " AND ContactedCount>=6 ";               //don't need to look at pref this only shows in UI if the prefvalue allows it
            }
            else if (showReactivations == RecallListShowNumberReminders.Zero)
            {
                cmd += " AND (comm.ContactedCount=0 OR comm.ContactedCount IS NULL) ";
            }
            else if (showReactivations != RecallListShowNumberReminders.All)
            {
                int filter = (int)showReactivations - 1;
                //if the contactmax pref is not -1 or 0, and the contactmax is smaller than the requested filter, replace the filter with the contactmax
                cmd += " AND comm.ContactedCount=" + POut.Int((maxReminds > 0 && maxReminds < filter)?maxReminds:filter) + " ";
            }
            else if (showReactivations == RecallListShowNumberReminders.All)             //get all but filter on the contactmax
            {
                cmd += " AND (comm.ContactedCount < " + POut.Int(maxReminds) + " OR comm.ContactedCount IS NULL) ";
            }
            cmd += $@" GROUP BY pat.PatNum 
							HAVING MAX(proc.ProcDate) < {POut.Date(dateSince)} AND MAX(proc.ProcDate) >= {POut.Date(dateStop)}
							AND MIN(appt.AptDateTime) IS NULL "                            ;
            //set the sort by
            switch (sortBy)
            {
            case ReactivationListSort.Alphabetical:
                cmd += " ORDER BY " + (groupFamilies?"guarantor.LName,guarantor.FName,pat.FName":"pat.LName,pat.FName");
                break;

            case ReactivationListSort.BillingType:
                cmd += " ORDER BY billingtype.ItemName,DateLastContacted" + (groupFamilies?",guarantor.LName,guarantor.FName":"");
                break;

            case ReactivationListSort.LastContacted:
                cmd += " ORDER BY IF(comm.DateLastContacted='' OR comm.DateLastContacted IS NULL,1,0),comm.DateLastContacted" + (groupFamilies?",guarantor.LName,guarantor.FName":"");
                break;

            case ReactivationListSort.LastSeen:
                cmd += " ORDER BY MAX(proc.ProcDate)";
                break;
            }
            DataTable dtReturn = Db.GetTable(cmd);

            foreach (DataRow row in dtReturn.Rows)
            {
                //FOR REVIEW: currently, we are displaying PreferRecallMethod, which is what RecallList also does.  Just want to make sure we don't want to use PreferContactMethod
                row["ContactMethod"] = Recalls.GetContactFromMethod(PIn.Enum <ContactMethod>(row["PreferRecallMethod"].ToString()), groupFamilies
                                                                    , row["HmPhone"].ToString(), row["WkPhone"].ToString(), row["WirelessPhone"].ToString(), row["Email"].ToString() //guarEmail queried as Email
                                                                    , row["Email"].ToString());                                                                                      //Pat.Email is also "Email"
            }
            return(dtReturn);
        }