Beispiel #1
0
        ///<summary>Returns current clinic limit minus message usage for current calendar month.</summary>
        public static double GetClinicBalance(long clinicNum)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetDouble(MethodBase.GetCurrentMethod(), clinicNum));
            }
            double limit = 0;

            if (!PrefC.HasClinicsEnabled)
            {
                if (PrefC.GetDate(PrefName.SmsContractDate).Year > 1880)
                {
                    limit = PrefC.GetDouble(PrefName.SmsMonthlyLimit);
                }
            }
            else
            {
                if (clinicNum == 0 && Clinics.GetCount(true) > 0)               //Sending text for "Unassigned" patient.  Use the first non-hidden clinic. (for now)
                {
                    clinicNum = Clinics.GetFirst(true).ClinicNum;
                }
                Clinic clinicCur = Clinics.GetClinic(clinicNum);
                if (clinicCur != null && clinicCur.SmsContractDate.Year > 1880)
                {
                    limit = clinicCur.SmsMonthlyLimit;
                }
            }
            DateTime dtStart = new DateTime(DateTime.Today.Year, DateTime.Today.Month, 1);
            DateTime dtEnd   = dtStart.AddMonths(1);
            string   command = "SELECT SUM(MsgChargeUSD) FROM smstomobile WHERE ClinicNum=" + POut.Long(clinicNum) + " "
                               + "AND DateTimeSent>=" + POut.Date(dtStart) + " AND DateTimeSent<" + POut.Date(dtEnd);

            limit -= PIn.Double(Db.GetScalar(command));
            return(limit);
        }
Beispiel #2
0
        ///<summary>Also updates existing journal entry splits linked to this account that have not been locked.</summary>
        public static void Update(Account acct, Account acctOld)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                Meth.GetVoid(MethodBase.GetCurrentMethod(), acct, acctOld);
                return;
            }
            Crud.AccountCrud.Update(acct, acctOld);
            if (acct.Description == acctOld.Description)
            {
                return;                //No need to update splits on attached journal entries.
            }
            //The account was renamed, so update journalentry.Splits.
            string    command = @"SELECT je2.*,account.Description
					FROM journalentry 
					INNER JOIN journalentry je2 ON je2.TransactionNum=journalentry.TransactionNum
					INNER JOIN account ON account.AccountNum=je2.AccountNum
					WHERE journalentry.AccountNum="                     + POut.Long(acct.AccountNum) + @"
					AND journalentry.DateDisplayed > "                     + POut.Date(PrefC.GetDate(PrefName.AccountingLockDate)) + @"
					ORDER BY je2.TransactionNum"                    ;
            DataTable table   = Db.GetTable(command);

            if (table.Rows.Count == 0)
            {
                return;
            }
            List <JournalEntry> listJournalEntries = Crud.JournalEntryCrud.TableToList(table);
            //Construct a dictionary that has the description for each JournalEntryNum.
            Dictionary <long, string> dictJournalEntryDescriptions = table.Rows.Cast <DataRow>()
                                                                     .GroupBy(x => PIn.Long(x["JournalEntryNum"].ToString()))
                                                                     .ToDictionary(x => x.Key, x => PIn.String(x.First()["Description"].ToString()));
            //Now we will loop through all the journal entries and find the other journal entries that are attached to the same transaction and update
            //those splits.
            List <int> listIndexesForTrans = new List <int>();
            long       curTransactionNum   = listJournalEntries[0].TransactionNum;

            for (int i = 0; i < listJournalEntries.Count; i++)
            {
                if (listJournalEntries[i].TransactionNum == curTransactionNum)
                {
                    listIndexesForTrans.Add(i);
                    continue;
                }
                UpdateJournalEntrySplits(listJournalEntries, listIndexesForTrans, dictJournalEntryDescriptions, acct);
                curTransactionNum = listJournalEntries[i].TransactionNum;
                listIndexesForTrans.Clear();
                listIndexesForTrans.Add(i);
            }
            UpdateJournalEntrySplits(listJournalEntries, listIndexesForTrans, dictJournalEntryDescriptions, acct);
        }
Beispiel #3
0
 ///<summary>This runs aging for all patients.  If using monthly aging, it always just runs the aging as of the last date again.  If using daily aging, it runs it as of today.  This logic used to be in FormAging, but is now centralized.</summary>
 public static void RunAging()
 {
     //No need to check RemotingRole; no call to db.
     if (PrefC.GetBool(PrefName.AgingCalculatedMonthlyInsteadOfDaily))
     {
         ComputeAging(0, PrefC.GetDate(PrefName.DateLastAging), false);
     }
     else
     {
         ComputeAging(0, DateTime.Today, false);
         if (PrefC.GetDate(PrefName.DateLastAging) != DateTime.Today)
         {
             Prefs.UpdateString(PrefName.DateLastAging, POut.Date(DateTime.Today, false));
             //Since this is always called from UI, the above line works fine to keep the prefs cache current.
         }
     }
 }
Beispiel #4
0
        ///<summary>Returns the path to the temporary opendental directory, temp/opendental.  Also performs one-time cleanup, if necessary.  In FormOpenDental_FormClosing, the contents of temp/opendental get cleaned up.</summary>
        public static string GetTempFolderPath()
        {
            //Will clean up entire temp folder for a month after the enhancement of temp file cleanups as long as the temp\opendental folder doesn't already exist.
            string tempPathOD = ODFileUtils.CombinePaths(Path.GetTempPath(), "opendental");

            if (Directory.Exists(tempPathOD))
            {
                //Cleanup has already run for the old temp folder.  Do nothing.
                return(tempPathOD);
            }
            Directory.CreateDirectory(tempPathOD);
            if (DateTime.Today > PrefC.GetDate(PrefName.TempFolderDateFirstCleaned).AddMonths(1))
            {
                return(tempPathOD);
            }
            //This might be used if this is the first time running this version on the computer that did the db update.
            //This might also be used if this is a computer that was turned off for a few weeks around the time of update conversion.
            //We need some sort of time limit just in case it's annoying and keeps happening.
            //So this will have a small risk of missing a computer, but the benefit of limiting outweighs the risk.
            //Empty entire temp folder.  Blank folders will be left behind because they do not matter.
            string[] arrayFileNames = Directory.GetFiles(Path.GetTempPath());
            for (int i = 0; i < arrayFileNames.Length; i++)
            {
                try {
                    if (arrayFileNames[i].Substring(arrayFileNames[i].LastIndexOf('.')) == ".exe" || arrayFileNames[i].Substring(arrayFileNames[i].LastIndexOf('.')) == ".cs")
                    {
                        //Do nothing.  We don't care about .exe or .cs files and don't want to interrupt other programs' files.
                    }
                    else
                    {
                        File.Delete(arrayFileNames[i]);
                    }
                }
                catch {
                    //Do nothing because the file could have been in use or there were not sufficient permissions.
                    //This file will most likely get deleted next time a temp file is created.
                }
            }
            return(tempPathOD);
        }
Beispiel #5
0
 ///<summary>Returns a clinic object with ClinicNum=0, and values filled using practice level preferences.
 /// Caution: do not attempt to save the clinic back to the DB. This should be used for read only purposes.</summary>
 public static Clinic GetPracticeAsClinicZero(string clinicName = null)
 {
     //No need to check RemotingRole; no call to db.
     if (clinicName == null)
     {
         clinicName = PrefC.GetString(PrefName.PracticeTitle);
     }
     return(new Clinic {
         ClinicNum = 0,
         Abbr = clinicName,
         Description = clinicName,
         Address = PrefC.GetString(PrefName.PracticeAddress),
         Address2 = PrefC.GetString(PrefName.PracticeAddress2),
         City = PrefC.GetString(PrefName.PracticeCity),
         State = PrefC.GetString(PrefName.PracticeST),
         Zip = PrefC.GetString(PrefName.PracticeZip),
         BillingAddress = PrefC.GetString(PrefName.PracticeBillingAddress),
         BillingAddress2 = PrefC.GetString(PrefName.PracticeBillingAddress2),
         BillingCity = PrefC.GetString(PrefName.PracticeBillingCity),
         BillingState = PrefC.GetString(PrefName.PracticeBillingST),
         BillingZip = PrefC.GetString(PrefName.PracticeBillingZip),
         PayToAddress = PrefC.GetString(PrefName.PracticePayToAddress),
         PayToAddress2 = PrefC.GetString(PrefName.PracticePayToAddress2),
         PayToCity = PrefC.GetString(PrefName.PracticePayToCity),
         PayToState = PrefC.GetString(PrefName.PracticePayToST),
         PayToZip = PrefC.GetString(PrefName.PracticePayToZip),
         Phone = PrefC.GetString(PrefName.PracticePhone),
         BankNumber = PrefC.GetString(PrefName.PracticeBankNumber),
         DefaultPlaceService = (PlaceOfService)PrefC.GetInt(PrefName.DefaultProcedurePlaceService),
         InsBillingProv = PrefC.GetLong(PrefName.InsBillingProv),
         Fax = PrefC.GetString(PrefName.PracticeFax),
         EmailAddressNum = PrefC.GetLong(PrefName.EmailDefaultAddressNum),
         DefaultProv = PrefC.GetLong(PrefName.PracticeDefaultProv),
         SmsContractDate = PrefC.GetDate(PrefName.SmsContractDate),
         SmsMonthlyLimit = PrefC.GetDouble(PrefName.SmsMonthlyLimit),
         IsMedicalOnly = PrefC.GetBool(PrefName.PracticeIsMedicalOnly)
     });
 }
Beispiel #6
0
        ///<summary>Surrond with Try/Catch. Error messages will be thrown to caller.</summary>
        public static bool IsGlobalDateLock(Permissions perm, DateTime date, bool isSilent = false, long codeNum = 0, double procFee = -1, long sheetDefNum = 0)
        {
            if (!(new[] {
                Permissions.AdjustmentCreate
                , Permissions.AdjustmentEdit
                , Permissions.PaymentCreate
                , Permissions.PaymentEdit
                , Permissions.ProcComplCreate
                , Permissions.ProcComplEdit
                , Permissions.ProcExistingEdit
                //,Permissions.ProcComplEditLimited
                //,Permissions.ImageDelete
                , Permissions.InsPayCreate
                , Permissions.InsPayEdit
                //,Permissions.InsWriteOffEdit//per Nathan 7/5/2016 this should not be affected by the global date lock
                , Permissions.SheetEdit
                , Permissions.SheetDelete
                , Permissions.CommlogEdit
                //,Permissions.ClaimDelete //per Nathan 01/18/2018 this should not be affected by the global date lock
                , Permissions.PayPlanEdit
                //,Permissions.ClaimHistoryEdit //per Nathan & Mark 03/01/2018 this should not be affected by the global lock date, not financial data.
            }).Contains(perm))
            {
                return(false);               //permission being checked is not affected by global lock date.
            }
            if (date.Year == 1)
            {
                return(false);               //Invalid or MinDate passed in.
            }
            if (!PrefC.GetBool(PrefName.SecurityLockIncludesAdmin) && GroupPermissions.HasPermission(Security.CurUser, Permissions.SecurityAdmin, 0))
            {
                return(false);               //admins are never affected by global date limitation when preference is false.
            }
            if (perm.In(Permissions.ProcComplCreate, Permissions.ProcComplEdit, Permissions.ProcExistingEdit) &&
                ProcedureCodes.CanBypassLockDate(codeNum, procFee))
            {
                return(false);
            }
            if (perm.In(Permissions.SheetEdit, Permissions.SheetDelete) && sheetDefNum > 0 && SheetDefs.CanBypassLockDate(sheetDefNum))
            {
                return(false);
            }
            //If global lock is Date based.
            if (date <= PrefC.GetDate(PrefName.SecurityLockDate))
            {
                if (!isSilent)
                {
                    MessageBox.Show(Lans.g("Security", "Locked by Administrator before ") + PrefC.GetDate(PrefName.SecurityLockDate).ToShortDateString());
                }
                return(true);
            }
            //If global lock is days based.
            int lockDays = PrefC.GetInt(PrefName.SecurityLockDays);

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

            if (date > dateLimit)          //authorized
            {
                return(true);
            }
            //Prevents certain bugs when 1/1/1 dates are passed in and compared----------------------------------------------
            //Handling of min dates.  There might be others, but we have to handle them individually to avoid introduction of bugs.
            if (perm == Permissions.ClaimDelete ||      //older versions did not have SecDateEntry
                perm == Permissions.ClaimSentEdit ||              //no date sent was entered before setting claim received
                perm == Permissions.ProcComplEdit ||              //a completed procedure with a min date.
                perm == Permissions.ProcComplEditLimited ||              //because ProcComplEdit was in this list
                perm == Permissions.ProcExistingEdit ||              //a completed EO or EC procedure with a min date.
                perm == Permissions.InsPayEdit ||              //a claim payment with no date.
                perm == Permissions.InsWriteOffEdit ||              //older versions did not have SecDateEntry or DateEntryC
                perm == Permissions.TreatPlanEdit ||
                perm == Permissions.AdjustmentEdit ||
                perm == Permissions.CommlogEdit ||              //usually from a conversion
                perm == Permissions.ProcDelete ||              //because older versions did not set the DateEntryC.
                perm == Permissions.ImageDelete ||              //In case an image has a creation date of DateTime.MinVal.
                perm == Permissions.PerioEdit ||              //In case perio chart exam has a creation date of DateTime.MinValue.
                perm == Permissions.PreAuthSentEdit)                 //older versions did not have SecDateEntry
            {
                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);
        }
Beispiel #8
0
        ///<summary>Returns a SerializableDictionary with key=PatNum, value=PatAgingData with the filters applied.</summary>
        public static SerializableDictionary <long, PatAgingData> GetAgingData(bool isSinglePatient, bool includeChanged, bool excludeInsPending,
                                                                               bool excludeIfUnsentProcs, bool isSuperBills, List <long> listClinicNums)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <SerializableDictionary <long, PatAgingData> >(MethodBase.GetCurrentMethod(), isSinglePatient, includeChanged,
                                                                                     excludeInsPending, excludeIfUnsentProcs, isSuperBills, listClinicNums));
            }
            SerializableDictionary <long, PatAgingData> dictPatAgingData = new SerializableDictionary <long, PatAgingData>();
            string command   = "";
            string guarOrPat = "guar";

            if (isSinglePatient)
            {
                guarOrPat = "patient";
            }
            string whereAndClinNum = "";

            if (!listClinicNums.IsNullOrEmpty())
            {
                whereAndClinNum = $@"AND {guarOrPat}.ClinicNum IN ({string.Join(",",listClinicNums)})";
            }
            if (includeChanged || excludeIfUnsentProcs)
            {
                command = $@"SELECT {guarOrPat}.PatNum,{guarOrPat}.ClinicNum,MAX(procedurelog.ProcDate) MaxProcDate";
                if (excludeIfUnsentProcs)
                {
                    command += ",MAX(CASE WHEN insplan.IsMedical=1 THEN 0 ELSE COALESCE(claimproc.ProcNum,0) END)>0 HasUnsentProcs";
                }
                command += $@" FROM patient
					INNER JOIN patient guar ON guar.PatNum=patient.Guarantor
					INNER JOIN procedurelog ON procedurelog.PatNum = patient.PatNum "                    ;
                if (excludeIfUnsentProcs)
                {
                    command += $@"LEFT JOIN claimproc ON claimproc.ProcNum = procedurelog.ProcNum
						AND claimproc.NoBillIns=0
						AND claimproc.Status = {POut.Int((int)ClaimProcStatus.Estimate)}
						AND procedurelog.ProcDate > CURDATE()-INTERVAL 6 MONTH
					LEFT JOIN insplan ON insplan.PlanNum=claimproc.PlanNum "                    ;
                }
                command += $@"WHERE procedurelog.ProcFee > 0
					AND procedurelog.ProcStatus = {POut.Int((int)ProcStat.C)}
					{whereAndClinNum}
					GROUP BY {guarOrPat}.PatNum
					ORDER BY NULL"                    ;
                using (DataTable tableChangedAndUnsent = Db.GetTable(command)) {
                    foreach (DataRow row in tableChangedAndUnsent.Rows)
                    {
                        long patNum = PIn.Long(row["PatNum"].ToString());
                        if (!dictPatAgingData.ContainsKey(patNum))
                        {
                            dictPatAgingData[patNum] = new PatAgingData(PIn.Long(row["ClinicNum"].ToString()));
                        }
                        if (includeChanged)
                        {
                            dictPatAgingData[patNum].ListPatAgingTransactions
                            .Add(new PatAgingTransaction(PatAgingTransaction.TransactionTypes.Procedure, PIn.Date(row["MaxProcDate"].ToString())));
                        }
                        if (excludeIfUnsentProcs)
                        {
                            dictPatAgingData[patNum].HasUnsentProcs = PIn.Bool(row["HasUnsentProcs"].ToString());
                        }
                    }
                }
            }
            if (includeChanged)
            {
                command = $@"SELECT {guarOrPat}.PatNum,{guarOrPat}.ClinicNum,MAX(claimproc.DateCP) maxDateCP
					FROM claimproc
					INNER JOIN patient ON patient.PatNum = claimproc.PatNum
					INNER JOIN patient guar ON guar.PatNum=patient.Guarantor
					WHERE claimproc.InsPayAmt > 0
					{whereAndClinNum}
					GROUP BY {guarOrPat}.PatNum"                    ;
                using (DataTable tableMaxPayDate = Db.GetTable(command)) {
                    foreach (DataRow row in tableMaxPayDate.Rows)
                    {
                        long patNum = PIn.Long(row["PatNum"].ToString());
                        if (!dictPatAgingData.ContainsKey(patNum))
                        {
                            dictPatAgingData[patNum] = new PatAgingData(PIn.Long(row["ClinicNum"].ToString()));
                        }
                        dictPatAgingData[patNum].ListPatAgingTransactions
                        .Add(new PatAgingTransaction(PatAgingTransaction.TransactionTypes.ClaimProc, PIn.Date(row["maxDateCP"].ToString())));
                    }
                }
                command = $@"SELECT {guarOrPat}.PatNum,{guarOrPat}.ClinicNum,MAX(payplancharge.ChargeDate) maxDatePPC,
						MAX(payplancharge.SecDateTEntry) maxDatePPCSDTE
					FROM payplancharge
					INNER JOIN patient ON patient.PatNum = payplancharge.PatNum
					INNER JOIN patient guar ON guar.PatNum=patient.Guarantor
					INNER JOIN payplan ON payplan.PayPlanNum = payplancharge.PayPlanNum
						AND payplan.PlanNum = 0 "                                                                                                                                                                                                                                                                                                                                                                                            //don't want insurance payment plans to make patients appear in the billing list
                          + $@"WHERE payplancharge.Principal + payplancharge.Interest>0
					AND payplancharge.ChargeType = {(int)PayPlanChargeType.Debit} "
                                                                                                                                                                                                                                                                                                                                                                                                                                             //include all charges in the past or due 'PayPlanBillInAdvance' days into the future.
                          + $@"AND payplancharge.ChargeDate <= {POut.Date(DateTime.Today.AddDays(PrefC.GetDouble(PrefName.PayPlansBillInAdvanceDays)))}
					{whereAndClinNum}
					GROUP BY {guarOrPat}.PatNum"                    ;
                using (DataTable tableMaxPPCDate = Db.GetTable(command)) {
                    foreach (DataRow row in tableMaxPPCDate.Rows)
                    {
                        long patNum = PIn.Long(row["PatNum"].ToString());
                        if (!dictPatAgingData.ContainsKey(patNum))
                        {
                            dictPatAgingData[patNum] = new PatAgingData(PIn.Long(row["ClinicNum"].ToString()));
                        }
                        dictPatAgingData[patNum].ListPatAgingTransactions
                        .Add(new PatAgingTransaction(
                                 PatAgingTransaction.TransactionTypes.PayPlanCharge,
                                 PIn.Date(row["maxDatePPC"].ToString()),
                                 secDateTEntryTrans: PIn.Date(row["maxDatePPCSDTE"].ToString()))
                             );
                    }
                }
            }
            if (excludeInsPending)
            {
                command = $@"SELECT {guarOrPat}.PatNum,{guarOrPat}.ClinicNum
					FROM claim
					INNER JOIN patient ON patient.PatNum=claim.PatNum
					INNER JOIN patient guar ON guar.PatNum=patient.Guarantor
					WHERE claim.ClaimStatus IN ('U','H','W','S')
					AND claim.ClaimType IN ('P','S','Other')
					{whereAndClinNum}
					GROUP BY {guarOrPat}.PatNum"                    ;
                using (DataTable tableInsPending = Db.GetTable(command)) {
                    foreach (DataRow row in tableInsPending.Rows)
                    {
                        long patNum = PIn.Long(row["PatNum"].ToString());
                        if (!dictPatAgingData.ContainsKey(patNum))
                        {
                            dictPatAgingData[patNum] = new PatAgingData(PIn.Long(row["ClinicNum"].ToString()));
                        }
                        dictPatAgingData[patNum].HasPendingIns = true;
                    }
                }
            }
            DateTime dateAsOf = DateTime.Today;                               //used to determine when the balance on this date began

            if (PrefC.GetBool(PrefName.AgingCalculatedMonthlyInsteadOfDaily)) //if aging calculated monthly, use the last aging date instead of today
            {
                dateAsOf = PrefC.GetDate(PrefName.DateLastAging);
            }
            List <PatComm> listPatComms = new List <PatComm>();

            using (DataTable tableDateBalsBegan = Ledgers.GetDateBalanceBegan(null, dateAsOf, isSuperBills, listClinicNums)) {
                foreach (DataRow row in tableDateBalsBegan.Rows)
                {
                    long patNum = PIn.Long(row["PatNum"].ToString());
                    if (!dictPatAgingData.ContainsKey(patNum))
                    {
                        dictPatAgingData[patNum] = new PatAgingData(PIn.Long(row["ClinicNum"].ToString()));
                    }
                    dictPatAgingData[patNum].DateBalBegan = PIn.Date(row["DateAccountAge"].ToString());
                    dictPatAgingData[patNum].DateBalZero  = PIn.Date(row["DateZeroBal"].ToString());
                }
                listPatComms = Patients.GetPatComms(tableDateBalsBegan.Select().Select(x => PIn.Long(x["PatNum"].ToString())).ToList(), null);
            }
            foreach (PatComm pComm in listPatComms)
            {
                if (!dictPatAgingData.ContainsKey(pComm.PatNum))
                {
                    dictPatAgingData[pComm.PatNum] = new PatAgingData(pComm.ClinicNum);
                }
                dictPatAgingData[pComm.PatNum].PatComm = pComm;
            }
            return(dictPatAgingData);
        }
Beispiel #9
0
        ///<summary>Used when viewing securityLog from the security admin window.  PermTypes can be length 0 to get all types.</summary>
        public static SecurityLog[] Refresh(DateTime dateFrom, DateTime dateTo, Permissions permType, long patNum, long userNum,
                                            DateTime datePreviousFrom, DateTime datePreviousTo, bool includeArchived, int limit = 0)
        {
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb)
            {
                return(Meth.GetObject <SecurityLog[]>(MethodBase.GetCurrentMethod(), dateFrom, dateTo, permType, patNum, userNum, datePreviousFrom, datePreviousTo, includeArchived, limit));
            }
            string command = "SELECT securitylog.*,LName,FName,Preferred,MiddleI,LogHash FROM securitylog "
                             + "LEFT JOIN patient ON patient.PatNum=securitylog.PatNum "
                             + "LEFT JOIN securityloghash ON securityloghash.SecurityLogNum=securitylog.SecurityLogNum "
                             + "WHERE LogDateTime >= " + POut.Date(dateFrom) + " "
                             + "AND LogDateTime <= " + POut.Date(dateTo.AddDays(1)) + " "
                             + "AND DateTPrevious >= " + POut.Date(datePreviousFrom) + " "
                             + "AND DateTPrevious <= " + POut.Date(datePreviousTo.AddDays(1));

            if (patNum != 0)
            {
                command += " AND securitylog.PatNum IN (" + string.Join(",",
                                                                        PatientLinks.GetPatNumsLinkedToRecursive(patNum, PatientLinkType.Merge).Select(x => POut.Long(x))) + ")";
            }
            if (permType != Permissions.None)
            {
                command += " AND PermType=" + POut.Long((int)permType);
            }
            if (userNum != 0)
            {
                command += " AND UserNum=" + POut.Long(userNum);
            }
            command += " ORDER BY LogDateTime DESC";          //Using DESC so that the most recent ones appear in the list
            if (limit > 0)
            {
                command = DbHelper.LimitOrderBy(command, limit);
            }
            DataTable          table    = Db.GetTable(command);
            List <SecurityLog> listLogs = Crud.SecurityLogCrud.TableToList(table);

            for (int i = 0; i < listLogs.Count; i++)
            {
                if (table.Rows[i]["PatNum"].ToString() == "0")
                {
                    listLogs[i].PatientName = "";
                }
                else
                {
                    listLogs[i].PatientName = table.Rows[i]["PatNum"].ToString() + "-"
                                              + Patients.GetNameLF(table.Rows[i]["LName"].ToString()
                                                                   , table.Rows[i]["FName"].ToString()
                                                                   , table.Rows[i]["Preferred"].ToString()
                                                                   , table.Rows[i]["MiddleI"].ToString());
                }
                listLogs[i].LogHash = table.Rows[i]["LogHash"].ToString();
            }
            if (includeArchived && dateFrom <= PrefC.GetDate(PrefName.ArchiveDate))           //They are attempting to find security logs that are prior to archived date.
            {
                string decryptedPass;
                CDT.Class1.Decrypt(PrefC.GetString(PrefName.ArchivePassHash), out decryptedPass);
                string         connectionStrOrig = DataConnection.GetCurrentConnectionString();
                DatabaseType   dbTypeOrig        = DataConnection.DBtype;
                DataConnection dcon = new DataConnection();
                //Connect to archive database
                dcon.SetDb(PrefC.GetString(PrefName.ArchiveServerName) == ""?PrefC.GetString(PrefName.ArchiveServerURI):PrefC.GetString(PrefName.ArchiveServerName),
                           "opendentalarchive", PrefC.GetString(PrefName.ArchiveUserName), decryptedPass, "", "", dbTypeOrig);
                DataTable          tableArchive    = Db.GetTable(command);  //Query the archive
                List <SecurityLog> listLogsArchive = Crud.SecurityLogCrud.TableToList(tableArchive);
                dcon.SetDb(connectionStrOrig, "", dbTypeOrig);              //Reconnect to initial db
                Dictionary <long, Patient> dictPats = Patients.GetMultPats(listLogsArchive.Select(x => x.PatNum).Distinct().ToList())
                                                      .ToDictionary(x => x.PatNum);
                for (int i = 0; i < listLogsArchive.Count; i++)
                {
                    Patient pat;
                    if (listLogsArchive[i].PatNum == 0 || !dictPats.TryGetValue(listLogsArchive[i].PatNum, out pat))
                    {
                        listLogsArchive[i].PatientName = "";
                    }
                    else
                    {
                        listLogsArchive[i].PatientName = listLogsArchive[i].PatNum + "-" + pat.GetNameLF();
                    }
                    listLogsArchive[i].LogHash = tableArchive.Rows[i]["LogHash"].ToString();
                }
                listLogs.AddRange(listLogsArchive);                //Add archived entries to returned list.
            }
            return(listLogs.OrderBy(x => x.LogDateTime).ToArray());
        }
Beispiel #10
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);
        }