Exemplo n.º 1
0
        ///<summary>Returns true if the heartbeat is less than 5 seconds old. Also returns the date time of the heartbeat.</summary>
        public static ODTuple <bool, DateTime> IsPhoneTrackingServerHeartbeatValid(DateTime dateTimeLastHeartbeat)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <ODTuple <bool, DateTime> >(MethodBase.GetCurrentMethod(), dateTimeLastHeartbeat));
            }
            //Default to using our local time just in case we can't query MySQL every second (lessens false positives due to query / network failure).
            DateTime  dateTimeNow             = DateTime.Now;
            DateTime  dateTimeRecentHeartbeat = dateTimeLastHeartbeat;
            DataTable table = null;

            //Check to make sure the asterisk server is still processing messages.
            ODException.SwallowAnyException(() => {
                table = DataCore.GetTable("SELECT ValueString,NOW() DateTNow FROM preference WHERE PrefName='AsteriskServerHeartbeat'");
            });
            if (table != null && table.Rows.Count >= 1 && table.Columns.Count >= 2)
            {
                dateTimeRecentHeartbeat = PIn.DateT(table.Rows[0]["ValueString"].ToString());
                dateTimeNow             = PIn.DateT(table.Rows[0]["DateTNow"].ToString());
            }
            //Check to see if the asterisk server heartbeat has stopped beating for the last 5 seconds.
            if ((dateTimeNow - dateTimeRecentHeartbeat).TotalSeconds > 5)
            {
                return(new ODTuple <bool, DateTime>(false, dateTimeRecentHeartbeat));
            }
            return(new ODTuple <bool, DateTime>(true, dateTimeRecentHeartbeat));
        }
Exemplo n.º 2
0
        ///<summary>Surround with try/catch, because it will throw an exception if any appointment is using this def.</summary>
        public static void Delete(ApptFieldDef apptFieldDef)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                Meth.GetVoid(MethodBase.GetCurrentMethod(), apptFieldDef);
                return;
            }
            string command = "SELECT LName,FName,AptDateTime "
                             + "FROM patient,apptfield,appointment WHERE "
                             + "patient.PatNum=appointment.PatNum "
                             + "AND appointment.AptNum=apptfield.AptNum "
                             + "AND FieldName='" + POut.String(apptFieldDef.FieldName) + "'";
            DataTable table = Db.GetTable(command);
            DateTime  aptDateTime;

            if (table.Rows.Count > 0)
            {
                string s = Lans.g("FormApptFieldDefEdit", "Not allowed to delete. Already in use by ") + table.Rows.Count.ToString()
                           + " " + Lans.g("FormApptFieldDefEdit", "appointments, including") + " \r\n";
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    if (i > 5)
                    {
                        break;
                    }
                    aptDateTime = PIn.DateT(table.Rows[i]["AptDateTime"].ToString());
                    s          += table.Rows[i]["LName"].ToString() + ", " + table.Rows[i]["FName"].ToString() + POut.DateT(aptDateTime, false) + "\r\n";
                }
                throw new ApplicationException(s);
            }
            command = "DELETE FROM apptfielddef WHERE ApptFieldDefNum =" + POut.Long(apptFieldDef.ApptFieldDefNum);
            Db.NonQ(command);
        }
Exemplo n.º 3
0
        //there are no methods for deleting or changing log entries because that will never be allowed.



        ///<summary>Used when viewing various audit trails of specific types.</summary>
        public static SecurityLog[] Refresh(long patNum, List <Permissions> permTypes)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <SecurityLog[]>(MethodBase.GetCurrentMethod(), patNum, permTypes));
            }
            string types = "";

            for (int i = 0; i < permTypes.Count; i++)
            {
                if (i > 0)
                {
                    types += " OR";
                }
                types += " PermType=" + POut.Long((int)permTypes[i]);
            }
            string command = "SELECT * FROM securitylog "
                             + "WHERE PatNum= '" + POut.Long(patNum) + "' "
                             + "AND (" + types + ") "
                             + "ORDER BY LogDateTime";
            DataTable table = Db.GetTable(command);

            SecurityLog[] List = new SecurityLog[table.Rows.Count];
            for (int i = 0; i < List.Length; i++)
            {
                List[i] = new SecurityLog();
                List[i].SecurityLogNum = PIn.Long(table.Rows[i][0].ToString());
                List[i].PermType       = (Permissions)PIn.Long(table.Rows[i][1].ToString());
                List[i].UserNum        = PIn.Long(table.Rows[i][2].ToString());
                List[i].LogDateTime    = PIn.DateT(table.Rows[i][3].ToString());
                List[i].LogText        = PIn.String(table.Rows[i][4].ToString());
                List[i].PatNum         = PIn.Long(table.Rows[i][5].ToString());
            }
            return(List);
        }
Exemplo n.º 4
0
        public static List <Etrans835Attach> GetForEtrans(bool isSimple, params long[] listEtrans835Nums)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <List <Etrans835Attach> >(MethodBase.GetCurrentMethod(), isSimple, listEtrans835Nums));
            }
            if (listEtrans835Nums.Length == 0)
            {
                return(new List <Etrans835Attach>());
            }
            string command = "SELECT etrans835attach.* "
                             + (isSimple?"":",etrans.DateTimeTrans ")
                             + "FROM etrans835attach "
                             + (isSimple?"":"INNER JOIN etrans ON etrans.EtransNum=etrans835attach.EtransNum ")
                             + "WHERE etrans835attach.EtransNum IN (" + String.Join(",", listEtrans835Nums.Select(x => POut.Long(x))) + ")";
            DataTable table = Db.GetTable(command);

            if (isSimple)
            {
                return(Crud.Etrans835AttachCrud.TableToList(table));
            }
            List <Etrans835Attach> listAttaches = Crud.Etrans835AttachCrud.TableToList(table);

            for (int i = 0; i < listAttaches.Count; i++)
            {
                Etrans835Attach attach = listAttaches[i];
                DataRow         row    = table.Rows[i];
                attach.DateTimeTrans = PIn.DateT(row["DateTimeTrans"].ToString());
            }
            return(listAttaches);
        }
Exemplo n.º 5
0
 public OutstandingInsClaim(DataRow rowCur)
 {
     CarrierName          = rowCur["CarrierName"].ToString();
     CarrierPhone         = rowCur["CarrierPhone"].ToString();
     ClaimType            = rowCur["ClaimType"].ToString();
     PatFName             = rowCur["PatFName"].ToString();
     PatLName             = rowCur["PatLName"].ToString();
     PatMiddleI           = rowCur["PatMiddleI"].ToString();
     PatNum               = PIn.Long(rowCur["PatNum"].ToString());
     PatDOB               = PIn.DateT(rowCur["PatDOB"].ToString());
     DateService          = PIn.DateT(rowCur["DateService"].ToString());
     DateSent             = PIn.DateT(rowCur["DateSent"].ToString());
     DateOrigSent         = PIn.DateT(rowCur["DateOrigSent"].ToString());
     ClaimFee             = PIn.Decimal(rowCur["ClaimFee"].ToString());
     ClaimNum             = PIn.Long(rowCur["ClaimNum"].ToString());
     ClinicNum            = PIn.Long(rowCur["ClinicNum"].ToString());
     DaysSuppressed       = PIn.Int(rowCur["DaysSuppressed"].ToString());
     DateLog              = PIn.DateT(rowCur["DateLog"].ToString());
     ErrorCodeDefNum      = PIn.Long(rowCur["ErrorCodeDefNum"].ToString());
     GroupNum             = PIn.String(rowCur["GroupNum"].ToString());
     GroupName            = PIn.String(rowCur["GroupName"].ToString());
     SubName              = PIn.String(rowCur["SubName"].ToString());
     SubDOB               = PIn.DateT(rowCur["SubDOB"].ToString());
     SubID                = PIn.String(rowCur["SubID"].ToString());
     CustomTrackingDefNum = PIn.Long(rowCur["CustomTrackingDefNum"].ToString());
     UserNum              = PIn.Long(rowCur["UserNum"].ToString());
 }
Exemplo n.º 6
0
        ///<summary>Gets the current date/Time with milliseconds directly from server.  In Mysql we must query the server until the second rolls over, which may take up to one second.  Used to confirm synchronization in time for EHR.</summary>
        public static DateTime GetNowDateTimeWithMilli()
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <DateTime>(MethodBase.GetCurrentMethod()));
            }
            string command;
            string dbtime;

            if (DataConnection.DBtype == DatabaseType.MySql)
            {
                command = "SELECT NOW()";               //Only up to 1 second precision pre-Mysql 5.6.4.  Does not round milliseconds.
                dbtime  = Db.GetScalar(command);
                int secondInit = PIn.DateT(dbtime).Second;
                int secondCur;
                //Continue querying server for current time until second changes (milliseconds will be close to 0)
                do
                {
                    dbtime    = Db.GetScalar(command);
                    secondCur = PIn.DateT(dbtime).Second;
                }while(secondInit == secondCur);
            }
            else
            {
                command = "SELECT CURRENT_TIMESTAMP(3) FROM DUAL";               //Timestamp with milliseconds
                dbtime  = Db.GetScalar(command);
            }
            return(PIn.DateT(dbtime));
        }
Exemplo n.º 7
0
        ///<summary></summary>
        public static void ClearDuplicates()
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                Meth.GetVoid(MethodBase.GetCurrentMethod());
                return;
            }
            //First, create a temp table with operatories for all blockouts
            string command = "DROP TABLE IF EXISTS tempBlockoutOps";

            Db.NonQ(command);
            command = @"CREATE TABLE tempBlockoutOps
				SELECT ScheduleNum,
				(SELECT "                 + DbHelper.GroupConcat("so1.OperatoryNum", false, true) + @" FROM scheduleop so1 WHERE so1.ScheduleNum=schedule.ScheduleNum) AS ops
				FROM schedule
				WHERE SchedType=2
				GROUP BY ScheduleNum"                ;
            Db.NonQ(command);
            command = "ALTER TABLE tempBlockoutOps ADD INDEX (ScheduleNum)";
            Db.NonQ(command);
            //Get a list of scheduleNums that have duplicates
            //A duplicate is defined as a matching opsList and matching times
            //The result list will contain one random scheduleNum out of the many duplicates
            command = @"SELECT SchedDate,MAX(ScheduleNum),StartTime,StopTime,"          //MAX on id. Cannot GROUP BY id without splitting up duplicates.
                      + @"(SELECT ops FROM tempBlockoutOps WHERE tempBlockoutOps.ScheduleNum=schedule.ScheduleNum) ops_______________ops,
				COUNT(*) countDups
				FROM schedule
				WHERE SchedType=2
				GROUP BY SchedDate,ops_______________ops,StartTime,StopTime
				HAVING countDups > 1"                ;
            DataTable table = Db.GetTable(command);
            DateTime  schedDate;
            DateTime  startTime;
            DateTime  stopTime;
            string    ops;
            long      scheduleNum;

            for (int i = 0; i < table.Rows.Count; i++)
            {
                schedDate   = PIn.Date(table.Rows[i][0].ToString());
                scheduleNum = PIn.Long(table.Rows[i][1].ToString());
                startTime   = PIn.DateT(table.Rows[i][2].ToString());
                stopTime    = PIn.DateT(table.Rows[i][3].ToString());
                ops         = PIn.ByteArray(table.Rows[i][4]);
                command     = "DELETE FROM schedule WHERE "
                              + "SchedDate = " + POut.Date(schedDate) + " "
                              + "AND ScheduleNum != " + POut.Long(scheduleNum) + " "
                              + "AND StartTime = '" + startTime.ToString("hh:mm", new DateTimeFormatInfo()) + ":00' "
                              + "AND StopTime = '" + stopTime.ToString("hh:mm", new DateTimeFormatInfo()) + ":00' "
                              + "AND (SELECT ops FROM tempBlockoutOps WHERE tempBlockoutOps.ScheduleNum=schedule.ScheduleNum) = '" + POut.String(ops) + "' ";
                Db.NonQ(command);
            }
            command = "DROP TABLE IF EXISTS tempBlockoutOps";
            Db.NonQ(command);
            //clear all the orphaned scheduleops
            command = "DELETE FROM scheduleop WHERE NOT EXISTS(SELECT * FROM schedule WHERE scheduleop.ScheduleNum=schedule.ScheduleNum)";
            long result = Db.NonQ(command);          //we can test the result in debug
        }
Exemplo n.º 8
0
        ///<summary>Used to get sheets filled via the web.</summary>
        public static DataTable GetWebFormSheetsTable(DateTime dateFrom, DateTime dateTo)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetTable(MethodBase.GetCurrentMethod(), dateFrom, dateTo));
            }
            DataTable table = new DataTable("");
            DataRow   row;

            //columns that start with lowercase are altered for display rather than being raw data.
            table.Columns.Add("date");
            table.Columns.Add("dateOnly", typeof(DateTime));           //to help with sorting
            table.Columns.Add("dateTime", typeof(DateTime));
            table.Columns.Add("description");
            table.Columns.Add("time");
            table.Columns.Add("timeOnly", typeof(TimeSpan));           //to help with sorting
            table.Columns.Add("PatNum");
            table.Columns.Add("SheetNum");
            List <DataRow> rows    = new List <DataRow>();
            string         command = "SELECT DateTimeSheet,Description,PatNum,SheetNum "
                                     + "FROM sheet WHERE "
                                     + "DateTimeSheet >= " + POut.Date(dateFrom) + " AND DateTimeSheet <= " + POut.Date(dateTo.AddDays(1)) + " "
                                     + "AND IsWebForm = " + POut.Bool(true) + " "
                                     + "AND (SheetType=" + POut.Long((int)SheetTypeEnum.PatientForm) + " OR SheetType=" + POut.Long((int)SheetTypeEnum.MedicalHistory) + ") ";
            DataTable rawSheet = Db.GetTable(command);
            DateTime  dateT;

            for (int i = 0; i < rawSheet.Rows.Count; i++)
            {
                row                = table.NewRow();
                dateT              = PIn.DateT(rawSheet.Rows[i]["DateTimeSheet"].ToString());
                row["date"]        = dateT.ToShortDateString();
                row["dateOnly"]    = dateT.Date;
                row["dateTime"]    = dateT;
                row["description"] = rawSheet.Rows[i]["Description"].ToString();
                row["PatNum"]      = rawSheet.Rows[i]["PatNum"].ToString();
                row["SheetNum"]    = rawSheet.Rows[i]["SheetNum"].ToString();
                if (dateT.TimeOfDay != TimeSpan.Zero)
                {
                    row["time"] = dateT.ToString("h:mm") + dateT.ToString("%t").ToLower();
                }
                row["timeOnly"] = dateT.TimeOfDay;
                rows.Add(row);
            }
            for (int i = 0; i < rows.Count; i++)
            {
                table.Rows.Add(rows[i]);
            }
            DataView view = table.DefaultView;

            view.Sort = "dateOnly,timeOnly";
            table     = view.ToTable();
            return(table);
        }
Exemplo n.º 9
0
        ///<summary>Surround with try/catch.  If there are any dependencies, then this will throw an exception.
        ///This is currently only called from FormCarrierEdit.
        ///No need to pass in usernum, it is set before the remoting role and passed in for logging.</summary>
        public static void Delete(Carrier Cur, long userNum = 0)
        {
            if (RemotingClient.RemotingRole != RemotingRole.ServerWeb)
            {
                userNum = Security.CurUser.UserNum;              //must be before normal remoting role check to get user at workstation
            }
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                Meth.GetVoid(MethodBase.GetCurrentMethod(), Cur, userNum);
                return;
            }
            //look for dependencies in insplan table.
            string command = "SELECT insplan.PlanNum,CONCAT(CONCAT(LName,', '),FName) FROM insplan "
                             + "LEFT JOIN inssub ON insplan.PlanNum=inssub.PlanNum "
                             + "LEFT JOIN patient ON inssub.Subscriber=patient.PatNum "
                             + "WHERE insplan.CarrierNum = " + POut.Long(Cur.CarrierNum) + " "
                             + "ORDER BY LName,FName";
            DataTable table = Db.GetTable(command);
            string    strInUse;

            if (table.Rows.Count > 0)
            {
                strInUse = "";              //new string[table.Rows.Count];
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    if (i > 0)
                    {
                        strInUse += "; ";
                    }
                    strInUse += PIn.String(table.Rows[i][1].ToString());
                }
                throw new ApplicationException(Lans.g("Carriers", "Not allowed to delete carrier because it is in use.  Subscribers using this carrier include ") + strInUse);
            }
            //look for dependencies in etrans table.
            command = "SELECT DateTimeTrans FROM etrans WHERE CarrierNum=" + POut.Long(Cur.CarrierNum)
                      + " OR CarrierNum2=" + POut.Long(Cur.CarrierNum);
            table = Db.GetTable(command);
            if (table.Rows.Count > 0)
            {
                strInUse = "";
                for (int i = 0; i < table.Rows.Count; i++)
                {
                    if (i > 0)
                    {
                        strInUse += ", ";
                    }
                    strInUse += PIn.DateT(table.Rows[i][0].ToString()).ToShortDateString();
                }
                throw new ApplicationException(Lans.g("Carriers", "Not allowed to delete carrier because it is in use in the etrans table.  Dates of claim sent history include ") + strInUse);
            }
            command = "DELETE from carrier WHERE CarrierNum = " + POut.Long(Cur.CarrierNum);
            Db.NonQ(command);
            InsEditLogs.MakeLogEntry(null, Cur, InsEditLogType.Carrier, userNum);
        }
Exemplo n.º 10
0
        ///<summary>Only Gets the current date/Time with microseconds directly from server.  Only works for MySQL 5.6 and up. It will not throw an
        ///exception on 5.5; it will just use precision to the second.</summary>
        public static DateTime GetNowDateTimeWithMicro()
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <DateTime>(MethodBase.GetCurrentMethod()));
            }
            //Converting the datetime to a string because DataConnection.GetScalar calls ToString() which loses microsecond precision on DateTimes.
            string command = "SELECT DATE_FORMAT(CURRENT_TIMESTAMP(6),'%Y-%m-%d %H:%i:%s.%f')";
            string dbtime  = Db.GetScalar(command);

            return(PIn.DateT(dbtime));
        }
Exemplo n.º 11
0
 ///<summary>Gets a pref of type datetime.</summary>
 public static DateTime GetDateT(PrefName prefName)
 {
     if (Dict == null)
     {
         Prefs.RefreshCache();
     }
     if (!Dict.ContainsKey(prefName.ToString()))
     {
         throw new Exception(prefName + " is an invalid pref name.");
     }
     return(PIn.DateT(Dict[prefName.ToString()].ValueString));
 }
Exemplo n.º 12
0
        public static DataTable RefreshOneStudent(long provNum)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetTable(MethodBase.GetCurrentMethod(), provNum));
            }
            DataTable table = new DataTable();
            DataRow   row;

            //columns that start with lowercase are altered for display rather than being raw data.
            table.Columns.Add("appointment");
            table.Columns.Add("course");
            table.Columns.Add("done");
            table.Columns.Add("patient");
            table.Columns.Add("ReqStudentNum");
            table.Columns.Add("requirement");
            string command = "SELECT AptDateTime,CourseID,reqstudent.Descript ReqDescript,"
                             + "schoolcourse.Descript CourseDescript,reqstudent.DateCompleted, "
                             + "patient.LName,patient.FName,patient.MiddleI,patient.Preferred,ProcDescript,reqstudent.ReqStudentNum "
                             + "FROM reqstudent "
                             + "LEFT JOIN schoolcourse ON reqstudent.SchoolCourseNum=schoolcourse.SchoolCourseNum "
                             + "LEFT JOIN patient ON reqstudent.PatNum=patient.PatNum "
                             + "LEFT JOIN appointment ON reqstudent.AptNum=appointment.AptNum "
                             + "WHERE reqstudent.ProvNum=" + POut.Long(provNum)
                             + " ORDER BY CourseID,ReqDescript";
            DataTable raw = Db.GetTable(command);
            DateTime  AptDateTime;
            DateTime  dateCompleted;

            for (int i = 0; i < raw.Rows.Count; i++)
            {
                row         = table.NewRow();
                AptDateTime = PIn.DateT(raw.Rows[i]["AptDateTime"].ToString());
                if (AptDateTime.Year > 1880)
                {
                    row["appointment"] = AptDateTime.ToShortDateString() + " " + AptDateTime.ToShortTimeString()
                                         + " " + raw.Rows[i]["ProcDescript"].ToString();
                }
                row["course"] = raw.Rows[i]["CourseID"].ToString();              //+" "+raw.Rows[i]["CourseDescript"].ToString();
                dateCompleted = PIn.Date(raw.Rows[i]["DateCompleted"].ToString());
                if (dateCompleted.Year > 1880)
                {
                    row["done"] = "X";
                }
                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["ReqStudentNum"] = raw.Rows[i]["ReqStudentNum"].ToString();
                row["requirement"]   = raw.Rows[i]["ReqDescript"].ToString();
                table.Rows.Add(row);
            }
            return(table);
        }
Exemplo n.º 13
0
        ///<summary>For a given date, gets a list of dateTimes of missed calls.  Gets directly from the Asterisk database, hard-coded.</summary>
        public static List <DateTime> GetMissedCalls(DateTime date)
        {
            DataConnection dcon    = new DataConnection("192.168.0.197", "asteriskcdrdb", "opendental", "secret", DatabaseType.MySql);
            string         command = "SELECT calldate FROM cdr WHERE " + DbHelper.DateColumn("calldate") + " = " + POut.Date(date) + " "
                                     + "AND (dcontext='ext-group' OR dcontext='ext-local') AND dst='vmu998'";
            List <DateTime> retVal = new List <DateTime>();
            DataTable       table  = dcon.GetTable(command);

            for (int i = 0; i < table.Rows.Count; i++)
            {
                retVal.Add(PIn.DateT(table.Rows[i][0].ToString()));
            }
            return(retVal);
        }
Exemplo n.º 14
0
        ///<summary>Returns the last known status for the Listener Service.
        ///Returns Critical if a signal has not been entered in the last 5 minutes.
        ///Returns Error if there are ANY error signals that have not been processed.</summary>
        public static eServiceSignalSeverity GetListenerServiceStatus()
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <eServiceSignalSeverity>(MethodBase.GetCurrentMethod()));
            }
            //Additionally, this query will run a subselect to get the count of all unprocessed errors.
            //Running that query as a subselect here simply saves an extra call to the database.
            //This subselect should be fine to run here since the query is limited to one result and the count of unprocessed errors should be small.
            string command = "SELECT eservicesignal.*,"           //eservicesignal.* is required because we will manually call TableToList() later.
                             + "(SELECT COUNT(*) FROM eservicesignal WHERE Severity=" + POut.Int((int)eServiceSignalSeverity.Error) + " AND IsProcessed=0) PendingErrors, "
                             + DbHelper.Now() + " ServerTime "
                             + "FROM eservicesignal WHERE ServiceCode=" + POut.Int((int)eServiceCode.ListenerService) + " "
                             + "AND Severity IN(" + POut.Int((int)eServiceSignalSeverity.NotEnabled) + ","
                             + POut.Int((int)eServiceSignalSeverity.Working) + ","
                             + POut.Int((int)eServiceSignalSeverity.Error) + ","
                             + POut.Int((int)eServiceSignalSeverity.Critical) + ") "
                             + "ORDER BY SigDateTime DESC, Severity DESC ";

            command = DbHelper.LimitOrderBy(command, 1);
            DataTable             table      = Db.GetTable(command);
            List <EServiceSignal> listSignal = Crud.EServiceSignalCrud.TableToList(table);

            if (listSignal.Count == 0)            //No signals means the eConnector has never run. Nothing to report.
            {
                return(eServiceSignalSeverity.None);
            }
            if (listSignal[0].Severity == eServiceSignalSeverity.NotEnabled)            //NotEnabled means they don't care what the status is. Nothing to report.
            {
                return(eServiceSignalSeverity.NotEnabled);
            }
            DateTime dtNow = PIn.DateT(table.Rows[0]["ServerTime"].ToString());

            if (
                //eConnector exited gracefully and inserted its own critical signal.
                listSignal[0].Severity == eServiceSignalSeverity.Critical ||
                //eConnector did not exit gracefully but has not inserted a heartbeat in at least 6 minutes. It is considered critical.
                //Listener is dropping a heartbeat every 5 minutes, so give 1 minute grace period to squelch race condition.
                listSignal[0].SigDateTime < dtNow.AddMinutes(-6))
            {
                return(eServiceSignalSeverity.Critical);
            }
            //We need to flag the service monitor as Error if there are ANY pending errors.
            if (table.Rows[0]["PendingErrors"].ToString() != "0")
            {
                return(eServiceSignalSeverity.Error);
            }
            return(listSignal[0].Severity);
        }
Exemplo n.º 15
0
        /// <summary></summary>
        public static DataTable XmlToTable(string xmlData)
        {
            DataTable   table = new DataTable();
            XmlDocument doc   = new XmlDocument();

            doc.LoadXml(xmlData);
            //<DataTable><Name></Name><Cols><Col>cell00</Col></Cols><Cells><y><x>cell00</x></y></Cells></DataTable>
            XmlNode nodeName = doc.SelectSingleNode("//Name");

            table.TableName = XmlStringUnescape(nodeName.InnerText);
            XmlNode nodeCols = doc.SelectSingleNode("//Cols");

            foreach (XmlNode childNode in nodeCols.ChildNodes)
            {
                DataColumn col = new DataColumn(XmlStringUnescape(childNode.InnerText));
                if (childNode.Attributes.Count > 0)                                                  //if attribute is set for column
                {
                    string dataType = XmlStringUnescape(childNode.Attributes["DataType"].InnerText); //this is safe because we created the xml
                    if (dataType == "decimal")
                    {
                        col.DataType = typeof(decimal);
                    }
                    else if (dataType == "DateTime")
                    {
                        col.DataType = typeof(DateTime);
                    }
                }
                table.Columns.Add(col);
            }
            XmlNodeList nodeListY = doc.SelectSingleNode("//Cells").ChildNodes;

            foreach (XmlNode node in nodeListY)             //loop y rows
            {
                DataRow       row      = table.NewRow();
                List <string> listCols = node.ChildNodes[0].InnerText.Split('|').ToList();             //Break up the XML node which is columns delimited by pipes.
                for (int i = 0; i < listCols.Count; i++)
                {
                    string colUnescaped = XmlStringUnescape(listCols[i]);
                    //Check the type of the current column to make sure we do not try and set a DateTime column to empty string (throws exception).
                    if (table.Columns[i].DataType == typeof(DateTime) && string.IsNullOrEmpty(colUnescaped))
                    {
                        colUnescaped = PIn.DateT(colUnescaped).ToString();                      //PIn.DateT handles empty strings and turns them into DateTime.MinValue
                    }
                    row[i] = colUnescaped;
                }
                table.Rows.Add(row);
            }
            return(table);
        }
Exemplo n.º 16
0
        ///<summary>Returns the time of the oldest task within the Triage task list.  Returns 0 if there is no tasks in the list.</summary>
        public static DateTime GetTriageTime()
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <DateTime>(MethodBase.GetCurrentMethod()));
            }
            string command = "SELECT IFNULL(MIN(DateTimeEntry),0) AS triageTime "
                             + "FROM task "
                             + "WHERE TaskListNum=1697 "                            //Triage task list.
                             + "AND TaskStatus<>2 "                                 //Not done (new or viewed).
                             + "AND TaskNum NOT IN (SELECT TaskNum FROM tasknote) " //Not waiting a call back.
                             + "LIMIT 1";

            return(PIn.DateT(Db.GetScalar(command)));
        }
Exemplo n.º 17
0
        ///<summary>Gets the current date/Time direcly from the server.  Mostly used to prevent uesr from altering the workstation date to bypass security.</summary>
        public static DateTime GetNowDateTime()
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <DateTime>(MethodBase.GetCurrentMethod()));
            }
            string command = "SELECT NOW()";

            if (DataConnection.DBtype == DatabaseType.Oracle)
            {
                command = "SELECT CURRENT_TIMESTAMP FROM DUAL";
            }
            DataTable table = Db.GetTable(command);

            return(PIn.DateT(table.Rows[0][0].ToString()));
        }
Exemplo n.º 18
0
        ///<summary>Returns the time of the oldest task within the Triage task list.  Returns 0 if there is no tasks in the list.</summary>
        public static DateTime GetTriageTime()
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <DateTime>(MethodBase.GetCurrentMethod()));
            }
            string command = "SELECT GREATEST(IFNULL(task.DateTimeEntry,'0001-01-01'), IFNULL((SELECT MAX(DateTimeNote) FROM tasknote WHERE tasknote.tasknum=task.tasknum),'0001-01-01')) AS triageTime "
                             + "FROM task "
                             + "WHERE TaskListNum=1697 "                            //Triage task list.
                             + "AND TaskStatus<>2 "                                 //Not done (new or viewed).
                             + "AND TaskNum NOT IN (SELECT TaskNum FROM tasknote) " //Not waiting a call back.
                             + "AND PriorityDefNum IN(502,501) "                    //Blue and Red tasks only.
                             + "LIMIT 1";

            return(PIn.DateT(Db.GetScalar(command)));
        }
Exemplo n.º 19
0
        ///<summary>Returns true if the heartbeat is less than 6 minutes old.</summary>
        public static bool IsODServiceRunning()
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetBool(MethodBase.GetCurrentMethod()));
            }
            string    command       = "SELECT ValueString,NOW() FROM preference WHERE PrefName='OpenDentalServiceHeartbeat'";
            DataTable table         = DataCore.GetTable(command);
            DateTime  lastHeartbeat = PIn.DateT(table.Rows[0][0].ToString());
            DateTime  dateTimeNow   = PIn.DateT(table.Rows[0][1].ToString());

            if (lastHeartbeat.AddMinutes(6) < dateTimeNow)
            {
                return(false);
            }
            return(true);
        }
Exemplo n.º 20
0
        ///<summary>Tailored for OD HQ.  Gets the most recent commlog.CommDateTime for a given patNum of type "support call or chat".
        ///Returns DateTime.MinValue if no entry found.</summary>
        public static DateTime GetDateTimeOfLastEntryForPat(long patNum)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <DateTime>(MethodBase.GetCurrentMethod(), patNum));
            }
            //no need for Oracle compatibility
            string command = "SELECT CommDateTime "
                             + "FROM commlog "
                             + "WHERE PatNum=" + POut.Long(patNum) + " "
                             + "AND (CommType=292 OR CommType=441) "  //support call or chat, DefNums
                             + "AND CommSource=" + POut.Int((int)CommItemSource.User) + " "
                             + "ORDER BY CommDateTime DESC "
                             + "LIMIT 1";

            return(PIn.DateT(Db.GetScalar(command)));
        }
Exemplo n.º 21
0
        ///<summary>Returns a list of Etrans835Attach for the given list of etransNums and/or listClaimNums.
        ///Set isSimple to false to run a simpiler query and if attach.DateTimeTrans is not needed.
        ///Returned list is ordered by Etrans835Attach.DateTimeEntry, this is very important when identifying claims split from an ERA.</summary>
        public static List <Etrans835Attach> GetForEtransNumOrClaimNums(bool isSimple, List <long> listEtransNum = null, params long[] listClaimNums)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <List <Etrans835Attach> >(MethodBase.GetCurrentMethod(), isSimple, listEtransNum, listClaimNums));
            }
            if ((listEtransNum == null || listEtransNum.Count == 0) && (listClaimNums == null || listClaimNums.Length == 0))
            {
                return(new List <Etrans835Attach>());              //Both are either not defined or contain no information, there would be no WHERE clause.
            }
            List <string> listWhereClauses = new List <string>();

            if (listClaimNums.Length != 0)
            {
                listWhereClauses.Add("etrans835attach.ClaimNum IN (" + String.Join(",", listClaimNums.Select(x => POut.Long(x))) + ")");
            }
            if (!isSimple && listEtransNum != null && listEtransNum.Count > 0)         //Includes manually detached and split attaches created when spliting procs from ERA.
            {
                listWhereClauses.Add("etrans.EtransNum IN (" + string.Join(",", listEtransNum.Select(x => POut.Long(x))) + ")");
            }
            if (listWhereClauses.Count == 0)
            {
                return(new List <Etrans835Attach>());
            }
            string command = "SELECT etrans835attach.* "
                             + (isSimple?"":",etrans.DateTimeTrans ")
                             + "FROM etrans835attach "
                             + (isSimple?"":"INNER JOIN etrans ON etrans.EtransNum=etrans835attach.EtransNum ")
                             + "WHERE " + string.Join(" OR ", listWhereClauses) + " "
                             + "ORDER BY etrans835attach.DateTimeEntry";  //Attaches created from splitting an ERA need to be after the original claim attach.
            DataTable table = Db.GetTable(command);

            if (isSimple)
            {
                return(Crud.Etrans835AttachCrud.TableToList(table));
            }
            List <Etrans835Attach> listAttaches = Crud.Etrans835AttachCrud.TableToList(table);

            for (int i = 0; i < listAttaches.Count; i++)
            {
                Etrans835Attach attach = listAttaches[i];
                DataRow         row    = table.Rows[i];
                attach.DateTimeTrans = PIn.DateT(row["DateTimeTrans"].ToString());
            }
            return(listAttaches);
        }
Exemplo n.º 22
0
        ///<summary>Gets the most recent date and time that the popup was last edited.  Returns min value if no archive was found.</summary>
        public static DateTime GetLastEditDateTimeForPopup(long popupNum)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <DateTime>(MethodBase.GetCurrentMethod(), popupNum));
            }
            string command = "SELECT DateTimeEntry FROM popup"
                             + " WHERE PopupNumArchive = " + POut.Long(popupNum)
                             + " ORDER BY DateTimeEntry DESC"
                             + " LIMIT 1";
            DataTable rawTable = Db.GetTable(command);

            if (rawTable.Rows.Count == 0)
            {
                return(DateTime.MinValue);
            }
            return(PIn.DateT(rawTable.Rows[0]["DateTimeEntry"].ToString()));
        }
Exemplo n.º 23
0
        public static List <Etrans835Attach> GetForEtransNumOrClaimNums(bool isSimple, long etransNum = 0, params long[] listClaimNums)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <List <Etrans835Attach> >(MethodBase.GetCurrentMethod(), isSimple, etransNum, listClaimNums));
            }
            List <string> listWhereClauses = new List <string>();

            if (listClaimNums.Length != 0)
            {
                listWhereClauses.Add("etrans835attach.ClaimNum IN (" + String.Join(",", listClaimNums.Select(x => POut.Long(x))) + ")");
            }
            if (etransNum != 0)           //Manually detached rows will have claimNum 0.
            {
                listWhereClauses.Add("(etrans.EtransNum=" + POut.Long(etransNum) + " AND etrans835attach.ClaimNum=0)");
            }
            if (listWhereClauses.Count == 0)
            {
                return(new List <Etrans835Attach>());
            }
            string command = "SELECT etrans835attach.* "
                             + (isSimple?"":",etrans.DateTimeTrans ")
                             + "FROM etrans835attach "
                             + (isSimple?"":"INNER JOIN etrans ON etrans.EtransNum=etrans835attach.EtransNum ")
                             + "WHERE " + string.Join(" OR ", listWhereClauses);
            DataTable table = Db.GetTable(command);

            if (isSimple)
            {
                return(Crud.Etrans835AttachCrud.TableToList(table));
            }
            List <Etrans835Attach> listAttaches = Crud.Etrans835AttachCrud.TableToList(table);

            for (int i = 0; i < listAttaches.Count; i++)
            {
                Etrans835Attach attach = listAttaches[i];
                DataRow         row    = table.Rows[i];
                attach.DateTimeTrans = PIn.DateT(row["DateTimeTrans"].ToString());
            }
            return(listAttaches);
        }
Exemplo n.º 24
0
        ///<summary>Should only be called from the PhoneTrackingServer which will be invoking this every ~1.6 seconds.
        ///Inserts a new entry into the triage metric table that all workstations will start to select from in order to fill local metrics.</summary>
        public static void InsertTriageMetric()
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                Meth.GetVoid(MethodBase.GetCurrentMethod());
                return;
            }
            //The following query was being run by every workstation in the office every 1.6 seconds which was causing slowness issues.
            //The query might need to be improved but for now we are just removing it from the workstations and having the PTS be the only entity running it.
            string    command = @"SELECT 
				COALESCE(SUM(CASE WHEN PriorityDefNum=502 THEN 1 END),0) AS CountBlueTasks,-- triage blue
				COALESCE(SUM(CASE WHEN PriorityDefNum=503 THEN 1 END),0) AS CountWhiteTasks,-- triage white
				COALESCE(SUM(CASE WHEN PriorityDefNum=501 THEN 1 END),0) AS CountRedTasks,-- triage red
				-- time of oldest triage task or the oldest tasknote if one exists
				COALESCE(MIN(CASE WHEN PriorityDefNum=502 THEN (SELECT GREATEST(IFNULL(task.DateTimeEntry,'0001-01-01'), 
					IFNULL((SELECT MAX(DateTimeNote) 
						FROM tasknote WHERE tasknote.tasknum=task.tasknum),'0001-01-01'))) END),'0001-01-01') AS TimeOfOldestBlueTaskNote,
				-- time of oldest urgent task or the oldest tasknote if one exists
				COALESCE(MIN(CASE WHEN PriorityDefNum=501 THEN (SELECT GREATEST(IFNULL(task.DateTimeEntry,'0001-01-01'), 
					IFNULL((SELECT MAX(DateTimeNote) 
						FROM tasknote WHERE tasknote.tasknum=task.tasknum),'0001-01-01'))) END),'0001-01-01') AS TimeOfOldestRedTaskNote
				FROM task 
				WHERE TaskListNum=1697  -- Triage task list
				AND TaskStatus!=2  -- Not done (new or viewed)"                ;
            DataTable table   = Db.GetTable(command);

            if (table == null || table.Rows == null || table.Rows.Count < 1)
            {
                return;
            }
            TriageMetric triageMetric = new TriageMetric()
            {
                CountBlueTasks  = PIn.Int(table.Rows[0]["CountBlueTasks"].ToString()),
                CountWhiteTasks = PIn.Int(table.Rows[0]["CountWhiteTasks"].ToString()),
                CountRedTasks   = PIn.Int(table.Rows[0]["CountRedTasks"].ToString()),
                DateTimeOldestTriageTaskOrTaskNote = PIn.DateT(table.Rows[0]["TimeOfOldestBlueTaskNote"].ToString()),
                DateTimeOldestUrgentTaskOrTaskNote = PIn.DateT(table.Rows[0]["TimeOfOldestRedTaskNote"].ToString()),
            };

            Crud.TriageMetricCrud.Insert(triageMetric);
        }
Exemplo n.º 25
0
        ///<summary>Most recent date last.  All exams loaded, even if not displayed.</summary>
        public static void Refresh(long patNum)
        {
            //No need to check RemotingRole; no call to db.
            DataTable table = GetExamsTable(patNum);

            ListExams = new List <PerioExam>();
            PerioExam exam;

            for (int i = 0; i < table.Rows.Count; i++)
            {
                exam = new PerioExam();
                exam.PerioExamNum     = PIn.Long(table.Rows[i][0].ToString());
                exam.PatNum           = PIn.Long(table.Rows[i][1].ToString());
                exam.ExamDate         = PIn.Date(table.Rows[i][2].ToString());
                exam.ProvNum          = PIn.Long(table.Rows[i][3].ToString());
                exam.DateTMeasureEdit = PIn.DateT(table.Rows[i][4].ToString());
                ListExams.Add(exam);
            }
            //return list;
            //PerioMeasures.Refresh(patNum);
        }
Exemplo n.º 26
0
        public static DateTime GetDateLastContacted(long patNum)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <DateTime>(MethodBase.GetCurrentMethod(), patNum));
            }
            long commType = Commlogs.GetTypeAuto(CommItemTypeAuto.REACT);

            if (commType == 0)
            {
                return(DateTime.MinValue);
            }
            string cmd =
                @"SELECT
					MAX(commlog.CommDateTime) AS DateLastContacted
					FROM commlog
					WHERE commlog.CommType="                     + POut.Long(commType) + " " +
                "AND commlog.PatNum=" + POut.Long(patNum) + " " +
                "GROUP BY commlog.PatNum";

            return(PIn.DateT(Db.GetScalar(cmd)));
        }
Exemplo n.º 27
0
        ///<summary>Returns true if it is time to retrieve reports.</summary>
        private static bool IsTimeToRetrieveReports(bool isAutomaticMode, out string errorMessage, IODProgressExtended progress = null)
        {
            progress = progress ?? new ODProgressExtendedNull();
            DateTime timeLastReport      = PIn.DateT(PrefC.GetStringNoCache(PrefName.ClaimReportReceiveLastDateTime));
            double   timeReceiveInternal = PIn.Double(PrefC.GetStringNoCache(PrefName.ClaimReportReceiveInterval));        //Interval in minutes.
            DateTime timeToRecieve       = DateTime.Now.Date + PrefC.GetDateT(PrefName.ClaimReportReceiveTime).TimeOfDay;
            double   timeDiff            = DateTime.Now.Subtract(timeLastReport).TotalMinutes;

            errorMessage = "";
            if (isAutomaticMode)
            {
                if (timeReceiveInternal != 0)                //preference is set instead of pref for specific time.
                {
                    if (timeDiff < timeReceiveInternal)
                    {
                        //Automatically retrieving reports from this computer and the report interval has not passed yet.
                        return(false);
                    }
                }
                else                  //pref is set for specific time, not interval
                {
                    if (DateTime.Now.TimeOfDay < timeToRecieve.TimeOfDay ||                 //We haven't reach to the time to retrieve
                        timeLastReport.Date == DateTime.Today)                         //Or we have already retrieved today
                    {
                        //Automatically retrieving reports and the time has not come to pass yet
                        return(false);
                    }
                }
            }
            else if (timeDiff < 1)
            {
                //When the user presses the Get Reports button manually we allow them to get reports up to once per minute
                errorMessage = Lans.g(progress.LanThis, "Reports can only be retrieved once per minute.");
                progress.UpdateProgress(Lans.g(progress.LanThis, "Reports can only be retrieved once per minute. Attempting to import manually downloaded reports."));
                return(false);
            }
            return(true);
        }
Exemplo n.º 28
0
        ///<summary>Gets the list of fees by feeschednums and clinicnums from the db.  Returns an empty list if listFeeSchedNums is null or empty.
        ///Throws an application exception if listClinicNums is null or empty.  Always provide at least one ClinicNum.
        ///We throw instead of returning an empty list which would make it look like there are no fees for the fee schedules passed in.
        ///If this method returns an empty list it is because no valied fee schedules were given or the database truly doesn't have any fees.</summary>
        public static List <FeeLim> GetByFeeSchedNumsClinicNums(List <long> listFeeSchedNums, List <long> listClinicNums)
        {
            if (listFeeSchedNums == null || listFeeSchedNums.Count == 0)
            {
                return(new List <FeeLim>());              //This won't hurt the FeeCache because there will be no corresponding fee schedules to "blank out".
            }
            if (listClinicNums == null || listClinicNums.Count == 0)
            {
                //Returning an empty list here would be detrimental to the FeeCache.
                throw new ApplicationException("Invalid listClinicNums passed into GetByFeeSchedNumsClinicNums()");
            }
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                //Unusual Middle Tier check. This method can cause out of memory exceptions when called over Middle Tier, so we are batching into multiple
                //calls of 100 fee schedules at a time.
                List <FeeLim> listFeeLims = new List <FeeLim>();
                for (int i = 0; i < listFeeSchedNums.Count; i += 100)
                {
                    List <long> listFeeSchedsNumsThisBatch = listFeeSchedNums.GetRange(i, Math.Min(100, listFeeSchedNums.Count - i));
                    listFeeLims.AddRange(Meth.GetObject <List <FeeLim> >(MethodBase.GetCurrentMethod(), listFeeSchedsNumsThisBatch, listClinicNums));
                }
                return(listFeeLims);
            }
            string command = "SELECT FeeNum,Amount,FeeSched,CodeNum,ClinicNum,ProvNum,SecDateTEdit FROM fee "
                             + "WHERE FeeSched IN (" + string.Join(",", listFeeSchedNums.Select(x => POut.Long(x))) + ") "
                             + "AND ClinicNum IN (" + string.Join(",", listClinicNums.Select(x => POut.Long(x))) + ")";

            return(Db.GetTable(command).AsEnumerable()
                   .Select(x => new FeeLim {
                FeeNum = PIn.Long(x["FeeNum"].ToString()),
                Amount = PIn.Double(x["Amount"].ToString()),
                FeeSched = PIn.Long(x["FeeSched"].ToString()),
                CodeNum = PIn.Long(x["CodeNum"].ToString()),
                ClinicNum = PIn.Long(x["ClinicNum"].ToString()),
                ProvNum = PIn.Long(x["ProvNum"].ToString()),
                SecDateTEdit = PIn.DateT(x["SecDateTEdit"].ToString()),
            }).ToList());
        }
Exemplo n.º 29
0
        ///<summary>Used only from FormReferenceSelect to get the list of references.</summary>
        public static DataTable GetReferenceTable(bool limit, long[] billingTypes, bool showBadRefs, bool showUsed, bool showGuarOnly, string city, string state, string zip,
                                                  string areaCode, string specialty, int superFam, string lname, string fname, string patnum, int age)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetTable(MethodBase.GetCurrentMethod(), limit, billingTypes, showBadRefs, showUsed, showGuarOnly, city, state, zip, areaCode, specialty, superFam, lname, fname, patnum, age));
            }
            string billingSnippet = "";

            if (billingTypes.Length != 0)
            {
                for (int i = 0; i < billingTypes.Length; i++)
                {
                    if (i == 0)
                    {
                        billingSnippet += "AND (";
                    }
                    else
                    {
                        billingSnippet += "OR ";
                    }
                    billingSnippet += "BillingType=" + POut.Long(billingTypes[i]) + " ";
                    if (i == billingTypes.Length - 1)
                    {
                        billingSnippet += ") ";
                    }
                }
            }
            string phonedigits = "";

            for (int i = 0; i < areaCode.Length; i++)
            {
                if (Regex.IsMatch(areaCode[i].ToString(), "[0-9]"))
                {
                    phonedigits = phonedigits + areaCode[i];
                }
            }
            string regexp = "";

            for (int i = 0; i < phonedigits.Length; i++)
            {
                if (i < 1)
                {
                    regexp = "^[^0-9]?";                  //Allows phone to start with "("
                }
                regexp += phonedigits[i] + "[^0-9]*";
            }
            DataTable table = new DataTable();
            DataRow   row;

            //columns that start with lowercase are altered for display rather than being raw data.
            table.Columns.Add("CustReferenceNum");
            table.Columns.Add("PatNum");
            table.Columns.Add("FName");
            table.Columns.Add("LName");
            table.Columns.Add("HmPhone");
            table.Columns.Add("State");
            table.Columns.Add("City");
            table.Columns.Add("Zip");
            table.Columns.Add("Specialty");
            table.Columns.Add("age");
            table.Columns.Add("SuperFamily");
            table.Columns.Add("DateMostRecent");
            table.Columns.Add("TimesUsed");
            table.Columns.Add("IsBadRef");
            List <DataRow> rows    = new List <DataRow>();
            string         command = @"SELECT * FROM (SELECT cr.*,p.LName,p.FName,p.HmPhone,p.State,p.City,p.Zip,p.Birthdate,pf.FieldValue,
				(SELECT COUNT(*) FROM patient tempp WHERE tempp.SuperFamily=p.SuperFamily AND tempp.SuperFamily<>0) AS SuperFamily,
				(SELECT COUNT(*) FROM custrefentry tempcre WHERE tempcre.PatNumRef=cr.PatNum) AS TimesUsed
				FROM custreference cr
				INNER JOIN patient p ON cr.PatNum=p.PatNum
				LEFT JOIN patfield pf ON cr.PatNum=pf.PatNum AND pf.FieldName='Specialty' 
				WHERE cr.CustReferenceNum<>0 "                ;                                                                                         //This just makes the following AND statements brainless.

            command += "AND (p.PatStatus=" + POut.Int((int)PatientStatus.Patient) + " OR p.PatStatus=" + POut.Int((int)PatientStatus.NonPatient) + ") " //excludes deleted, etc.
                       + billingSnippet;
            if (age > 0)
            {
                command += "AND p.Birthdate <" + POut.Date(DateTime.Now.AddYears(-age)) + " ";
            }
            if (regexp != "")
            {
                command += "AND (p.HmPhone REGEXP '" + POut.String(regexp) + "' )";
            }
            command += (lname.Length > 0?"AND (p.LName LIKE '" + POut.String(lname) + "%' OR p.Preferred LIKE '" + POut.String(lname) + "%') ":"")
                       + (fname.Length > 0?"AND (p.FName LIKE '" + POut.String(fname) + "%' OR p.Preferred LIKE '" + POut.String(fname) + "%') ":"")
                       + (city.Length > 0?"AND p.City LIKE '" + POut.String(city) + "%' ":"")
                       + (state.Length > 0?"AND p.State LIKE '" + POut.String(state) + "%' ":"")
                       + (zip.Length > 0?"AND p.Zip LIKE '" + POut.String(zip) + "%' ":"")
                       + (patnum.Length > 0?"AND p.PatNum LIKE '" + POut.String(patnum) + "%' ":"")
                       + (specialty.Length > 0?"AND pf.FieldValue LIKE '" + POut.String(specialty) + "%' ":"")
                       + (showBadRefs?"":"AND cr.IsBadRef=0 ")
                       + (showGuarOnly?"AND p.Guarantor=p.PatNum":"");
            if (limit)
            {
                command = DbHelper.LimitOrderBy(command, 40);
            }
            command += @") AS tempcustref WHERE PatNum<>0 ";          //Once again just making AND statements brainless.
            if (superFam > 0)
            {
                command += "AND SuperFamily>" + POut.Int(superFam) + " ";
            }
            if (showUsed)
            {
                command += "AND TimesUsed>0 ";
            }
            DataTable rawtable = Db.GetTable(command);

            for (int i = 0; i < rawtable.Rows.Count; i++)
            {
                row = table.NewRow();
                row["CustReferenceNum"] = rawtable.Rows[i]["CustReferenceNum"].ToString();
                row["PatNum"]           = rawtable.Rows[i]["PatNum"].ToString();
                row["FName"]            = rawtable.Rows[i]["FName"].ToString();
                row["LName"]            = rawtable.Rows[i]["LName"].ToString();
                row["HmPhone"]          = rawtable.Rows[i]["HmPhone"].ToString();
                row["State"]            = rawtable.Rows[i]["State"].ToString();
                row["City"]             = rawtable.Rows[i]["City"].ToString();
                row["Zip"]         = rawtable.Rows[i]["Zip"].ToString();
                row["Specialty"]   = rawtable.Rows[i]["FieldValue"].ToString();
                row["age"]         = Patients.DateToAge(PIn.Date(rawtable.Rows[i]["Birthdate"].ToString())).ToString();
                row["SuperFamily"] = rawtable.Rows[i]["SuperFamily"].ToString();
                DateTime recentDate = PIn.DateT(rawtable.Rows[i]["DateMostRecent"].ToString());
                row["DateMostRecent"] = "";
                if (recentDate.Year > 1880)
                {
                    row["DateMostRecent"] = recentDate.ToShortDateString();
                }
                row["TimesUsed"] = rawtable.Rows[i]["TimesUsed"].ToString();
                row["IsBadRef"]  = rawtable.Rows[i]["IsBadRef"].ToString();
                rows.Add(row);
            }
            for (int i = 0; i < rows.Count; i++)
            {
                table.Rows.Add(rows[i]);
            }
            return(table);
        }
Exemplo n.º 30
0
        public static DataTable GetPatientFormsTable(long patNum)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetTable(MethodBase.GetCurrentMethod(), patNum));
            }
            //DataConnection dcon=new DataConnection();
            DataTable table = new DataTable("");
            DataRow   row;

            //columns that start with lowercase are altered for display rather than being raw data.
            table.Columns.Add("date");
            table.Columns.Add("dateOnly", typeof(DateTime));           //to help with sorting
            table.Columns.Add("dateTime", typeof(DateTime));
            table.Columns.Add("description");
            table.Columns.Add("DocNum");
            table.Columns.Add("imageCat");
            table.Columns.Add("SheetNum");
            table.Columns.Add("showInTerminal");
            table.Columns.Add("time");
            table.Columns.Add("timeOnly", typeof(TimeSpan));           //to help with sorting
            //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>();
            //sheet---------------------------------------------------------------------------------------
            string command = "SELECT DateTimeSheet,SheetNum,Description,ShowInTerminal "
                             + "FROM sheet WHERE IsDeleted=0 "
                             + "AND PatNum =" + POut.Long(patNum) + " "
                             + "AND (SheetType=" + POut.Long((int)SheetTypeEnum.PatientForm) + " OR SheetType=" + POut.Long((int)SheetTypeEnum.MedicalHistory);

            if (PrefC.GetBool(PrefName.PatientFormsShowConsent))
            {
                command += " OR SheetType=" + POut.Long((int)SheetTypeEnum.Consent);            //Show consent forms if pref is true.
            }
            command += ")";
            //+"ORDER BY ShowInTerminal";//DATE(DateTimeSheet),ShowInTerminal,TIME(DateTimeSheet)";
            DataTable rawSheet = Db.GetTable(command);
            DateTime  dateT;

            for (int i = 0; i < rawSheet.Rows.Count; i++)
            {
                row                = table.NewRow();
                dateT              = PIn.DateT(rawSheet.Rows[i]["DateTimeSheet"].ToString());
                row["date"]        = dateT.ToShortDateString();
                row["dateOnly"]    = dateT.Date;
                row["dateTime"]    = dateT;
                row["description"] = rawSheet.Rows[i]["Description"].ToString();
                row["DocNum"]      = "0";
                row["imageCat"]    = "";
                row["SheetNum"]    = rawSheet.Rows[i]["SheetNum"].ToString();
                if (rawSheet.Rows[i]["ShowInTerminal"].ToString() == "0")
                {
                    row["showInTerminal"] = "";
                }
                else
                {
                    row["showInTerminal"] = rawSheet.Rows[i]["ShowInTerminal"].ToString();
                }
                if (dateT.TimeOfDay != TimeSpan.Zero)
                {
                    row["time"] = dateT.ToString("h:mm") + dateT.ToString("%t").ToLower();
                }
                row["timeOnly"] = dateT.TimeOfDay;
                rows.Add(row);
            }
            //document---------------------------------------------------------------------------------------
            command = "SELECT DateCreated,DocCategory,DocNum,Description "
                      + "FROM document,definition "
                      + "WHERE document.DocCategory=definition.DefNum"
                      + " AND PatNum =" + POut.Long(patNum)
                      + " AND definition.ItemValue LIKE '%F%'";
            //+" ORDER BY DateCreated";
            DataTable rawDoc = Db.GetTable(command);
            long      docCat;

            for (int i = 0; i < rawDoc.Rows.Count; i++)
            {
                row                   = table.NewRow();
                dateT                 = PIn.DateT(rawDoc.Rows[i]["DateCreated"].ToString());
                row["date"]           = dateT.ToShortDateString();
                row["dateOnly"]       = dateT.Date;
                row["dateTime"]       = dateT;
                row["description"]    = rawDoc.Rows[i]["Description"].ToString();
                row["DocNum"]         = rawDoc.Rows[i]["DocNum"].ToString();
                docCat                = PIn.Long(rawDoc.Rows[i]["DocCategory"].ToString());
                row["imageCat"]       = Defs.GetName(DefCat.ImageCats, docCat);
                row["SheetNum"]       = "0";
                row["showInTerminal"] = "";
                if (dateT.TimeOfDay != TimeSpan.Zero)
                {
                    row["time"] = dateT.ToString("h:mm") + dateT.ToString("%t").ToLower();
                }
                row["timeOnly"] = dateT.TimeOfDay;
                rows.Add(row);
            }
            //Sorting
            for (int i = 0; i < rows.Count; i++)
            {
                table.Rows.Add(rows[i]);
            }
            DataView view = table.DefaultView;

            view.Sort = "dateOnly,showInTerminal,timeOnly";
            table     = view.ToTable();
            return(table);
        }