Ejemplo n.º 1
0
        ///<summary>Adds the xml for one statement. Validation is performed here. Throws an exception if there is a validation failure.</summary>
        public static void GenerateOneStatement(XmlWriter writer, Statement stmt, Patient pat, Family fam, DataSet dataSet)
        {
            DataTable tableMisc    = dataSet.Tables["misc"];
            DataTable tableAccount = dataSet.Tables.OfType <DataTable>().FirstOrDefault(x => x.TableName.StartsWith("account"));
            Patient   guar         = fam.ListPats[0];

            if (!Regex.IsMatch(guar.State, "^[A-Z]{2}$"))
            {
                throw new ApplicationException(Lan.g("EHG_Statements", "Guarantor state must be two uppercase characters.") + " " + guar.FName + " " + guar.LName + " #" + guar.PatNum);
            }
            writer.WriteStartElement("EisStatement");
            writer.WriteAttributeString("OutputFormat", "StmOut_Blue6Col");
            writer.WriteAttributeString("CreditCardChoice", PrefC.GetString(PrefName.BillingElectCreditCardChoices));
            writer.WriteStartElement("Patient");
            writer.WriteElementString("Name", guar.GetNameFLFormal());
            writer.WriteElementString("Account", guar.PatNum.ToString());
            writer.WriteElementString("Address1", guar.Address);
            writer.WriteElementString("Address2", guar.Address2);
            writer.WriteElementString("City", guar.City);
            writer.WriteElementString("State", guar.State);
            writer.WriteElementString("Zip", guar.Zip);
            writer.WriteElementString("EMail", guar.Email);
            //Account summary-----------------------------------------------------------------------
            writer.WriteStartElement("AccountSummary");
            if (stmt.DateRangeFrom.Year < 1880)           //make up a statement date.
            {
                writer.WriteElementString("PriorStatementDate", DateTime.Today.AddMonths(-1).ToString("MM/dd/yyyy"));
            }
            else
            {
                writer.WriteElementString("PriorStatementDate", stmt.DateRangeFrom.AddDays(-1).ToString("MM/dd/yyyy"));
            }
            DateTime dueDate;

            if (PrefC.GetLong(PrefName.StatementsCalcDueDate) == -1)
            {
                dueDate = DateTime.Today.AddDays(10);
            }
            else
            {
                dueDate = DateTime.Today.AddDays(PrefC.GetLong(PrefName.StatementsCalcDueDate));
            }
            writer.WriteElementString("DueDate", dueDate.ToString("MM/dd/yyyy"));
            writer.WriteElementString("StatementDate", stmt.DateSent.ToString("MM/dd/yyyy"));
            double balanceForward = tableMisc.Rows.OfType <DataRow>().Where(x => x["descript"].ToString() == "balanceForward")
                                    .Select(x => PIn.Double(x["value"].ToString())).FirstOrDefault();//defaults to 0

            writer.WriteElementString("PriorBalance", balanceForward.ToString("F2"));
            writer.WriteElementString("RunningBalance", "");      //for future use
            writer.WriteElementString("PerPayAdj", "");           //optional
            writer.WriteElementString("InsPayAdj", "");           //optional
            writer.WriteElementString("Adjustments", "");         //for future use
            double charges = tableAccount.Rows.OfType <DataRow>().Sum(x => PIn.Double(x["chargesDouble"].ToString()));

            writer.WriteElementString("NewCharges", charges.ToString("F2")); //optional
            writer.WriteElementString("FinanceCharges", "");                 //for future use
            double credits = tableAccount.Rows.OfType <DataRow>().Sum(x => PIn.Double(x["creditsDouble"].ToString()));

            writer.WriteElementString("Credits", credits.ToString("F2"));
            //On a regular printed statement, the amount due at the top might be different from the balance at the middle right due to payplan balances.
            //But in e-bills, there is only one amount due.  Insurance estimate is already subtracted, and payment plan balance is already added.
            double amountDue = guar.BalTotal;

            if (PrefC.GetInt(PrefName.PayPlansVersion) == 1)           //with version 2, payplan debits/credits are aged individually and are included in guar.BalTotal
            {
                amountDue += tableMisc.Rows.OfType <DataRow>().Where(x => x["descript"].ToString() == "payPlanDue")
                             .Select(x => PIn.Double(x["value"].ToString())).DefaultIfEmpty(0).Sum();           //add payplan(s) due amt
            }
            double insEst = 0;

            if (!PrefC.GetBool(PrefName.BalancesDontSubtractIns))             //this is typical
            {
                insEst = guar.InsEst;
            }
            InstallmentPlan installPlan = InstallmentPlans.GetOneForFam(guar.PatNum);

            if (installPlan != null && installPlan.MonthlyPayment < (amountDue - insEst))
            {
                amountDue = installPlan.MonthlyPayment;
                insEst    = 0;
            }
            writer.WriteElementString("EstInsPayments", insEst.ToString("F2"));    //optional.
            writer.WriteElementString("PatientShare", (amountDue - insEst).ToString("F2"));
            writer.WriteElementString("CurrentBalance", amountDue.ToString("F2")); //this is ambiguous.  It seems to be AmountDue, but it could be 0-30 days aging
            writer.WriteElementString("PastDue30", guar.Bal_31_60.ToString("F2")); //optional
            writer.WriteElementString("PastDue60", guar.Bal_61_90.ToString("F2")); //optional
            writer.WriteElementString("PastDue90", guar.BalOver90.ToString("F2")); //optional
            writer.WriteElementString("PastDue120", "");                           //optional
            writer.WriteEndElement();                                              //AccountSummary
            //Notes-----------------------------------------------------------------------------------
            writer.WriteStartElement("Notes");
            if (stmt.NoteBold != "")
            {
                writer.WriteStartElement("Note");
                writer.WriteAttributeString("FgColor", "Red"); //ColorToHexString(Color.DarkRed));
                //writer.WriteAttributeString("BgColor",ColorToHexString(Color.White));
                writer.WriteCData(stmt.NoteBold.Left(500));    //Limit of 500 char on notes.
                writer.WriteEndElement();                      //Note
            }
            if (stmt.Note != "")
            {
                writer.WriteStartElement("Note");
                //writer.WriteAttributeString("FgColor",ColorToHexString(Color.Black));
                //writer.WriteAttributeString("BgColor",ColorToHexString(Color.White));
                writer.WriteCData(stmt.Note.Left(500)); //Limit of 500 char on notes.
                writer.WriteEndElement();               //Note
            }
            writer.WriteEndElement();                   //Notes
            //Detail items------------------------------------------------------------------------------
            writer.WriteStartElement("DetailItems");
            List <string> lines;
            int           seq = 0;
            //Jessica at DentalXchange says limit is 120.  Specs say limit is 30.
            //If we send more than 50 characters, DentalXChange will break the line at the 50th character, even if it is in the middle of a word, and wrap
            //the rest of the line, so up to 70 chars onto line 2, which could easily extend past the end of the description field.  The wrapped line will
            //also have a different line spacing than if sent as a separate xml element.  See the examples in
            //...\Programmers Documents\eClaims Clearinghouse and Carrier Specific Details\DentalXChange ClaimConnect\ClaimConnect - EHG - WebClaim\EHG Statements\Examples
            //Example: original description:
            //line 1: 'D6103 5  bone graft for repair of periimplant defect - does not include flap entry and closure.  Placement of a barrier membrane or biologic materials to aid in osseous regeneration are reported separately'
            //version 16.2 sent as:
            //line 1: 'D6103 5  bone graft for repair of periimplant defect - does not include flap entry and closure.  Placement of a barrier '
            //line 2: 'membrane or biologic materials to aid in osseous regeneration are reported separately'
            //DentalXChange displayed lines as (with line 2 extended past the end of the description field):
            //line 1: 'D6103 5 bone graft for repair of periimplant defe -'
            //line 2: 'ct - does not include flap entry and closure. Placement of a barrier'
            //line 3: 'membrane or biologic materials to aid in osseous r -'
            //line 4: 'egeneration are reported separately'
            //version 16.3 and up sent and displayed as:
            //line 1: 'D6103 5  bone graft for repair of periimplant'
            //line 2: 'defect - does not include flap entry and closure.'
            //line 3: 'Placement of a barrier membrane or biologic'
            //line 4: 'materials to aid in osseous regeneration are'
            //line 5: 'reported separately'
            const int lineMaxLen = 50;
            int       firstIndexNewLine;
            string    lineCur;

            foreach (DataRow rowCur in tableAccount.Rows)
            {
                //There are frequently CRs within a procedure description for things like ins est.
                lines = string.Join(" ", new[] { rowCur["ProcCode"].ToString(), rowCur["tth"].ToString(), rowCur["description"].ToString() })
                        .Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()).ToList();
                for (int li = 0; li < lines.Count; li++)
                {
                    lineCur = lines[li];
                    if (lineCur.Length < 1 || lineCur.All(x => char.IsWhiteSpace(x)))                   //nothing to write
                    {
                        continue;
                    }
                    writer.WriteStartElement("DetailItem");                    //has a child item. We won't add optional child note
                    writer.WriteAttributeString("sequence", seq.ToString());
                    writer.WriteStartElement("Item");
                    writer.WriteElementString("Date", li == 0?PIn.Date(rowCur["DateTime"].ToString()).ToString("MM/dd/yyyy"):"");
                    writer.WriteElementString("PatientName", li == 0?rowCur["patient"].ToString():"");
                    if (lineCur.Length > lineMaxLen)
                    {
                        firstIndexNewLine = lineMaxLen;
                        for (int c = lineMaxLen - 2; c > -1; c--)                 //-2, 1 for length to index and 1 so we can safely check index and index+1
                        {
                            if (!char.IsWhiteSpace(lineCur[c]) && char.IsWhiteSpace(lineCur[c + 1]))
                            {
                                firstIndexNewLine = c + 1;
                                break;
                            }
                        }
                        lines.Insert(li + 1, lineCur.Substring(firstIndexNewLine).Trim());
                        lines[li] = lineCur.Left(firstIndexNewLine);
                    }
                    writer.WriteStartElement("Description");
                    writer.WriteCData(lines[li]);                //CData to allow any string, including punctuation, syntax characters and special characters.
                    writer.WriteEndElement();                    //Description
                    writer.WriteElementString("Charges", li == 0?rowCur["charges"].ToString():"");
                    writer.WriteElementString("Credits", li == 0?rowCur["credits"].ToString():"");
                    writer.WriteElementString("Balance", li == 0?rowCur["balance"].ToString():"");
                    writer.WriteEndElement();                    //Item
                    writer.WriteEndElement();                    //DetailItem
                    seq++;
                }
                #region Notes Don't Display On Statements

                /*The code below just didn't work because notes don't get displayed on the statement.
                 * linedesc=lines[0];
                 * note="";
                 * if(linedesc.Length>30) {
                 *      note=linedesc.Substring(30);
                 *      linedesc=linedesc.Substring(0,30);
                 * }
                 * for(int l=1;l<lines.Length;l++) {
                 *      if(note!="") {
                 *              note+="\r\n";
                 *      }
                 *      note+=lines[l];
                 * }
                 *
                 * if(note!="") {
                 *      writer.WriteStartElement("Note");
                 *      //we're not going to specify colors here since they're optional
                 *      writer.WriteCData(note);
                 *      writer.WriteEndElement();//Note
                 * }*/
                #endregion Notes Don't Display On Statements
            }
            writer.WriteEndElement();            //DetailItems
            writer.WriteEndElement();            //Patient
            writer.WriteEndElement();            //EisStatement
        }
Ejemplo n.º 2
0
		///<summary>raised for each page to be printed.</summary>
		private void pdCards_PrintPage(object sender, PrintPageEventArgs ev){
			int totalPages=(int)Math.Ceiling((double)AddrTable.Rows.Count/(double)PrefC.GetLong(PrefName.RecallPostcardsPerSheet));
			Graphics g=ev.Graphics;
			int yAdj=(int)(PrefC.GetDouble(PrefName.RecallAdjustDown)*100);
			int xAdj=(int)(PrefC.GetDouble(PrefName.RecallAdjustRight)*100);
			float yPos=0+yAdj;//these refer to the upper left origin of each postcard
			float xPos=0+xAdj;
			string str;
			while(yPos<ev.PageBounds.Height-100 && patientsPrinted<AddrTable.Rows.Count){
				//Return Address--------------------------------------------------------------------------
				if(PrefC.GetBool(PrefName.RecallCardsShowReturnAdd)){
					if(PrefC.GetBool(PrefName.EasyNoClinics) || PIn.Long(AddrTable.Rows[patientsPrinted]["ClinicNum"].ToString())==0) {//No clinics or no clinic selected for this appt
						str=PrefC.GetString(PrefName.PracticeTitle)+"\r\n";
						g.DrawString(str,new Font(FontFamily.GenericSansSerif,9,FontStyle.Bold),Brushes.Black,xPos+45,yPos+60);
						str=PrefC.GetString(PrefName.PracticeAddress)+"\r\n";
						if(PrefC.GetString(PrefName.PracticeAddress2)!="") {
							str+=PrefC.GetString(PrefName.PracticeAddress2)+"\r\n";
						}
						str+=PrefC.GetString(PrefName.PracticeCity)+",  "+PrefC.GetString(PrefName.PracticeST)+"  "+PrefC.GetString(PrefName.PracticeZip)+"\r\n";
						string phone=PrefC.GetString(PrefName.PracticePhone);
						if(CultureInfo.CurrentCulture.Name=="en-US"&& phone.Length==10) {
							str+="("+phone.Substring(0,3)+")"+phone.Substring(3,3)+"-"+phone.Substring(6);
						}
						else {//any other phone format
							str+=phone;
						}
					}
					else {//Clinics enabled and clinic selected
						Clinic clinic=Clinics.GetClinic(PIn.Long(AddrTable.Rows[patientsPrinted]["ClinicNum"].ToString()));
						str=clinic.Description+"\r\n";
						g.DrawString(str,new Font(FontFamily.GenericSansSerif,9,FontStyle.Bold),Brushes.Black,xPos+45,yPos+60);
						str=clinic.Address+"\r\n";
						if(clinic.Address2!="") {
							str+=clinic.Address2+"\r\n";
						}
						str+=clinic.City+",  "+clinic.State+"  "+clinic.Zip+"\r\n";
						string phone=clinic.Phone;
						if(CultureInfo.CurrentCulture.Name=="en-US"&& phone.Length==10) {
							str+="("+phone.Substring(0,3)+")"+phone.Substring(3,3)+"-"+phone.Substring(6);
						}
						else {//any other phone format
							str+=phone;
						}
					}
					g.DrawString(str,new Font(FontFamily.GenericSansSerif,8),Brushes.Black,xPos+45,yPos+75);
				}
				//Body text-------------------------------------------------------------------------------
				str=PrefC.GetString(PrefName.ConfirmPostcardMessage);
					//textPostcardMessage.Text;
				str=str.Replace("[date]",PIn.Date(AddrTable.Rows[patientsPrinted]["AptDateTime"].ToString()).ToShortDateString());
				str=str.Replace("[time]",PIn.Date(AddrTable.Rows[patientsPrinted]["AptDateTime"].ToString()).ToShortTimeString());
				g.DrawString(str,new Font(FontFamily.GenericSansSerif,10),Brushes.Black,new RectangleF(xPos+45,yPos+180,250,190));
				//Patient's Address-----------------------------------------------------------------------
				str=AddrTable.Rows[patientsPrinted]["FName"].ToString()+" "
						+AddrTable.Rows[patientsPrinted]["MiddleI"].ToString()+" "
						+AddrTable.Rows[patientsPrinted]["LName"].ToString()+"\r\n"
						+AddrTable.Rows[patientsPrinted]["Address"].ToString()+"\r\n";
					if(AddrTable.Rows[patientsPrinted]["Address2"].ToString()!=""){
						str+=AddrTable.Rows[patientsPrinted]["Address2"].ToString()+"\r\n";
					}
					str+=AddrTable.Rows[patientsPrinted]["City"].ToString()+", "
						+AddrTable.Rows[patientsPrinted]["State"].ToString()+"   "
						+AddrTable.Rows[patientsPrinted]["Zip"].ToString()+"\r\n";
				g.DrawString(str,new Font(FontFamily.GenericSansSerif,11),Brushes.Black,xPos+320,yPos+240);
				if(PrefC.GetLong(PrefName.RecallPostcardsPerSheet)==1){
					yPos+=400;
				}
				else if(PrefC.GetLong(PrefName.RecallPostcardsPerSheet)==3){
					yPos+=366;
				}
				else{//4
					xPos+=550;
					if(xPos>1000){
						xPos=0+xAdj;
						yPos+=425;
					}
				}
				patientsPrinted++;
			}//while
			pagesPrinted++;
			if(pagesPrinted==totalPages){
				ev.HasMorePages=false;
				pagesPrinted=0;
				patientsPrinted=0;
			}
			else{
				ev.HasMorePages=true;
			}
		}
Ejemplo n.º 3
0
        ///<summary>Might be able to use newer Dentalxchange2016 web reference instead of using com.dentalexchange.webservices.</summary>
        public static string Benefits270(Clearinghouse clearinghouseClin, string x12message)
        {
            com.dentalxchange.webservices.Credentials cred = new com.dentalxchange.webservices.Credentials();
            if (PrefC.GetBool(PrefName.CustomizedForPracticeWeb))             //even though they currently use code from a different part of the program.
            {
                cred.client    = "Practice-Web";
                cred.serviceID = "DCI Web Service ID: 001513";
            }
            else
            {
                cred.client    = "OpenDental";
                cred.serviceID = "DCI Web Service ID: 002778";
            }
            cred.version  = Application.ProductVersion;
            cred.username = clearinghouseClin.LoginID;
            cred.password = clearinghouseClin.Password;
            com.dentalxchange.webservices.Request request = new com.dentalxchange.webservices.Request();
            request.content = HttpUtility.HtmlEncode(x12message);          //get rid of ampersands, etc.
            com.dentalxchange.webservices.WebServiceService service = new com.dentalxchange.webservices.WebServiceService();
#if DEBUG
            //service.Url = "https://prelive2.dentalxchange.com/dws/services/dciservice.svl"; // testing
            service.Url = "https://webservices.dentalxchange.com/dws/services/dciservice.svl";             // production
#else
            service.Url = "https://webservices.dentalxchange.com/dws/services/dciservice.svl";             //always use production. So I don't forget
#endif
            string strResponse = "";
            try {
                com.dentalxchange.webservices.Response response = service.lookupEligibility(cred, request);
                strResponse = response.content;
            }
            catch (SoapException ex) {
                strResponse = "If this is a new customer, this error might be due to an invalid Username or Password.  Servers may need a few hours before ready to accept new user information.\r\n"
                              + "Error message received directly from Claim Connect:  " + ex.Message + "\r\n\r\n" + ex.Detail.InnerText;
            }
            //cleanup response.  Seems to start with \n and 4 spaces.  Ends with trailing \n.
            strResponse = strResponse.TrimStart('\n');
            //strResponse.Replace("\n","");
            strResponse = strResponse.TrimStart(' ');
            //CodeBase.MsgBoxCopyPaste msgbox=new CodeBase.MsgBoxCopyPaste(response.content);
            //msgbox.ShowDialog();
            return(strResponse);

            /*
             * string strRawResponse="";
             * string strRawResponseNormal="ISA*00*          *00*          *30*330989922      *29*AA0989922      *030606*0936*U*00401*000013966*0*T*:~GS*HB*330989922*AA0989922*20030606*0936*13966*X*004010X092~ST*271*0001~BHT*0022*11*ASX012145WEB*20030606*0936~HL*1**20*1~NM1*PR*2*ACME INC*****PI*12345~HL*2*1*21*1~NM1*1P*1*PROVLAST*PROVFIRST****SV*5558006~HL*3*2*22*0~TRN*2*100*1330989922~NM1*IL*1*SMITH*JOHN*B***MI*123456789~REF*6P*XYZ123*GROUPNAME~REF*18*2484568*TEST PLAN NAME~N3*29 FREMONT ST*~N4*PEACE*NY*10023~DMG*D8*19570515*M~DTP*307*RD8*19910712-19920525~EB*1*FAM*30~SE*17*0001~GE*1*13966~IEA*1*000013966~";
             * string strRawResponseFailureAuth=@"<?xml version=""1.0"" encoding=""UTF-8""?>
             * <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
             * <soapenv:Body>
             * <soapenv:Fault>
             * <faultcode>soapenv:Server.userException</faultcode>
             * <faultstring>Authentication failed.</faultstring>
             * <faultactor/>
             * <detail>
             *      <string>Authentication failed.</string>
             * </detail>
             * </soapenv:Fault>
             * </soapenv:Body>
             * </soapenv:Envelope>";
             * string strRawResponseFailure997=@"<?xml version=""1.0"" encoding=""UTF-8""?>
             * <soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">
             * <soapenv:Body>
             * <soapenv:Fault>
             * <faultcode>soapenv:Server.userException</faultcode>
             * <faultstring>Malformed document sent. Please insure that the format is correct and all required data is present.</faultstring>
             * <faultactor/>
             * <detail>
             *      <string>ISA*00*          *00*          *30*330989922      *30*BB0989922      *030606*1351*U*00401*000014066*0*T*:~GS*FA*330989922**20030606*1351*14066*X*004010~ST*997*0001~AK1*HR*100~AK2*276*0001~AK3*DMG*10**8~AK4*2**8*20041210~AK5*R*5~AK9*R*0*0*0*3~SE*8*0001~GE*1*14066~IEA*1*000014066~</string>
             * </detail>
             * </soapenv:Fault>
             * </soapenv:Body>
             * </soapenv:Envelope>";
             * return strRawResponseNormal;*/

            /*
             * XmlDocument doc=new XmlDocument();
             * doc.LoadXml(strRawResponse);
             * //StringReader strReader=new StringReader(strRawResponseNormal);
             * //XmlReader xmlReader=XmlReader.Create(strReader);
             * //xmlReader...MoveToElement(
             * XmlNode node=doc.SelectSingleNode("//lookupEligibilityReturn");
             * if(node!=null) {
             *      return node.InnerText;//271
             * }
             * node=doc.SelectSingleNode("//detail/string");
             * if(node==null) {
             *      throw new ApplicationException("Returned data not in expected format: "+strRawResponse);
             * }
             * if(node.InnerText=="Authentication failed.") {
             *      throw new ApplicationException("Authentication failed.");
             * }
             * return node.InnerText;//997
             */
        }
Ejemplo n.º 4
0
        ///<summary>Draws all the blockouts for the entire period.</summary>
        public static void DrawBlockouts(Graphics g, DateTime startTime, DateTime stopTime, int colsPerPage, int pageColumn, int fontSize, bool isPrinting)
        {
            Schedule[] schedForType = Schedules.GetForType(SchedListPeriod, ScheduleType.Blockout, 0);
            SolidBrush blockBrush;
            Pen        blockOutlinePen = new Pen(Color.Black, 1);
            Pen        penOutline;
            Font       blockFont = new Font("Arial", fontSize);
            string     blockText;
            RectangleF rect;

            for (int i = 0; i < schedForType.Length; i++)
            {
                blockBrush = new SolidBrush(DefC.GetColor(DefCat.BlockoutTypes, schedForType[i].BlockoutType));
                penOutline = new Pen(DefC.GetColor(DefCat.BlockoutTypes, schedForType[i].BlockoutType), 2);
                blockText  = DefC.GetName(DefCat.BlockoutTypes, schedForType[i].BlockoutType) + "\r\n" + schedForType[i].Note;
                for (int o = 0; o < schedForType[i].Ops.Count; o++)
                {
                    int startHour = startTime.Hour;
                    if (isPrinting)                     //Filtering logic for printing.
                    {
                        int stopHour = stopTime.Hour;
                        if (stopHour == 0)
                        {
                            stopHour = 24;
                        }
                        if (schedForType[i].StartTime.Hours >= stopHour)
                        {
                            continue;                            //Blockout starts after the current time frame.
                        }
                        if (schedForType[i].StopTime.Hours <= stopHour)
                        {
                            stopHour = schedForType[i].StopTime.Hours;
                        }
                        if (GetIndexOp(schedForType[i].Ops[o]) >= (colsPerPage * pageColumn + colsPerPage) ||
                            GetIndexOp(schedForType[i].Ops[o]) < colsPerPage * pageColumn)
                        {
                            continue;                            //Blockout not on current page.
                        }
                    }
                    if (IsWeeklyView)
                    {
                        if (GetIndexOp(schedForType[i].Ops[o]) == -1)
                        {
                            continue;                            //don't display if op not visible
                        }
                        //this is a workaround because we start on Monday:
                        int dayofweek = (int)schedForType[i].SchedDate.DayOfWeek - 1;
                        if (dayofweek == -1)
                        {
                            dayofweek = 6;
                        }
                        rect = new RectangleF(
                            TimeWidth + 1 + (dayofweek) * ColDayWidth
                            + ColAptWidth * (GetIndexOp(schedForType[i].Ops[o], VisOps) - (colsPerPage * pageColumn))
                            , (schedForType[i].StartTime.Hours - startHour) * LineH * RowsPerHr
                            + schedForType[i].StartTime.Minutes * LineH / MinPerRow
                            , ColAptWidth - 1
                            , (schedForType[i].StopTime - schedForType[i].StartTime).Hours * LineH * RowsPerHr
                            + (schedForType[i].StopTime - schedForType[i].StartTime).Minutes * LineH / MinPerRow);
                    }
                    else
                    {
                        if (GetIndexOp(schedForType[i].Ops[o]) == -1)
                        {
                            continue;                            //don't display if op not visible
                        }
                        rect = new RectangleF(
                            TimeWidth + ProvWidth * ProvCount
                            + ColWidth * (GetIndexOp(schedForType[i].Ops[o], VisOps) - (colsPerPage * pageColumn))
                            + ProvWidth * 2                         //so they don't overlap prov bars
                            , (schedForType[i].StartTime.Hours - startHour) * LineH * RowsPerHr
                            + schedForType[i].StartTime.Minutes * LineH / MinPerRow
                            , ColWidth - 1 - ProvWidth * 2
                            , (schedForType[i].StopTime - schedForType[i].StartTime).Hours * LineH * RowsPerHr
                            + (schedForType[i].StopTime - schedForType[i].StartTime).Minutes * LineH / MinPerRow);
                    }
                    //paint either solid block or outline
                    if (PrefC.GetBool(PrefName.SolidBlockouts))
                    {
                        g.FillRectangle(blockBrush, rect);
                        g.DrawLine(blockOutlinePen, rect.X, rect.Y + 1, rect.Right - 1, rect.Y + 1);
                    }
                    else
                    {
                        g.DrawRectangle(penOutline, rect.X + 1, rect.Y + 2, rect.Width - 2, rect.Height - 3);
                    }
                    g.DrawString(blockText, blockFont, new SolidBrush(DefC.Short[(int)DefCat.AppointmentColors][5].ItemColor), rect);
                }
                blockBrush.Dispose();
                penOutline.Dispose();
            }
            blockOutlinePen.Dispose();
        }
Ejemplo n.º 5
0
 private void FormReportSetup_Load(object sender, EventArgs e)
 {
     checkPatientFormsShowConsent.Checked = PrefC.GetBool(PrefName.PatientFormsShowConsent);
 }
Ejemplo n.º 6
0
        ///<summary>The DataTable used to fill the grid will only be refreshed from the db if isFromDb is true.  Otherwise the grid will be refilled using
        ///the existing table.  Only get from the db on load or if the Refresh button is pressed, not when the user is selecting the clinic(s).</summary>
        private void FillGrid(bool isFromDb = false)
        {
            Cursor = Cursors.WaitCursor;
            if (isFromDb)
            {
                _charger.FillCharges(_listUserClinics);
            }
            List <long> listSelectedClinicNums = listClinics.SelectedIndices.OfType <int>().Select(x => _listUserClinics[x].ClinicNum).ToList();
            List <RecurringChargeData> listChargesCur;

            if (PrefC.HasClinicsEnabled)
            {
                listChargesCur = _charger.ListRecurringChargeData.Where(x => listSelectedClinicNums.Contains(x.RecurringCharge.ClinicNum)).ToList();
            }
            else
            {
                listChargesCur = _charger.ListRecurringChargeData;
            }
            gridMain.BeginUpdate();
            gridMain.ListGridColumns.Clear();
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableRecurring", "PatNum"), 55));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableRecurring", "Name"), PrefC.HasClinicsEnabled?190:220));
            if (PrefC.HasClinicsEnabled)
            {
                gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableRecurring", "Clinic"), 65));
            }
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableRecurring", "Date"), PrefC.HasClinicsEnabled?80:80, HorizontalAlignment.Right));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableRecurring", "Family Bal"), PrefC.HasClinicsEnabled?70:85, HorizontalAlignment.Right));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableRecurring", "PayPlan Due"), PrefC.HasClinicsEnabled?75:85, HorizontalAlignment.Right));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableRecurring", "Total Due"), PrefC.HasClinicsEnabled?65:80, HorizontalAlignment.Right));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableRecurring", "Repeat Amt"), PrefC.HasClinicsEnabled?75:90, HorizontalAlignment.Right));         //RptChrgAmt
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableRecurring", "Charge Amt"), PrefC.HasClinicsEnabled?85:100, HorizontalAlignment.Right));
            if (Programs.HasMultipleCreditCardProgramsEnabled())
            {
                if (Programs.IsEnabled(ProgramName.Xcharge))
                {
                    gridMain.ListGridColumns.Add(new GridColumn("X-Charge", PrefC.HasClinicsEnabled ? 70 : 80, HorizontalAlignment.Center));
                }
                if (Programs.IsEnabled(ProgramName.PayConnect))
                {
                    gridMain.ListGridColumns.Add(new GridColumn("PayConnect", PrefC.HasClinicsEnabled ? 85 : 95, HorizontalAlignment.Center));
                }
                if (Programs.IsEnabled(ProgramName.PaySimple))
                {
                    gridMain.ListGridColumns.Add(new GridColumn("PaySimple", PrefC.HasClinicsEnabled ? 80 : 90, HorizontalAlignment.Center));
                }
            }
            gridMain.ListGridRows.Clear();
            GridRow row;

            foreach (RecurringChargeData chargeCur in listChargesCur)
            {
                row = new GridRow();
                double famBalTotal  = chargeCur.RecurringCharge.FamBal;             //pat bal+payplan due, but if pat bal<0 and payplan due>0 then just payplan due
                double payPlanDue   = chargeCur.RecurringCharge.PayPlanDue;
                double chargeAmt    = chargeCur.RecurringCharge.ChargeAmt;
                double rptChargeAmt = chargeCur.RecurringCharge.RepeatAmt;              //includes repeat charge (from procs if ODHQ) and attached payplan
                row.Cells.Add(chargeCur.RecurringCharge.PatNum.ToString());
                row.Cells.Add(chargeCur.PatName);
                if (PrefC.HasClinicsEnabled)
                {
                    Clinic clinicCur = _listUserClinics.FirstOrDefault(x => x.ClinicNum == chargeCur.RecurringCharge.ClinicNum);
                    row.Cells.Add(clinicCur != null?clinicCur.Description:"");                  //get description from cache if clinics are enabled
                }
                int billingDay = 0;
                if (PrefC.GetBool(PrefName.BillingUseBillingCycleDay))
                {
                    billingDay = chargeCur.BillingCycleDay;
                }
                else
                {
                    billingDay = chargeCur.RecurringChargeDate.Day;
                }
                DateTime startBillingCycle = DateTimeOD.GetMostRecentValidDate(DateTime.Today.Year, DateTime.Today.Month, billingDay);
                if (startBillingCycle > DateTime.Today)
                {
                    startBillingCycle = startBillingCycle.AddMonths(-1);             //Won't give a date with incorrect day.  AddMonths will give the end of the month if needed.
                }
                DateTime dateExcludeIfBefore = PIn.Date(textDate.Text);              //If entry is invalid, all charges will be included because this will be MinDate.
                if (startBillingCycle < dateExcludeIfBefore)
                {
                    continue;                    //Don't show row in grid
                }
                row.Cells.Add(startBillingCycle.ToShortDateString());
                row.Cells.Add(famBalTotal.ToString("c"));
                if (!payPlanDue.IsZero())
                {
                    row.Cells.Add(payPlanDue.ToString("c"));
                }
                else
                {
                    row.Cells.Add("");
                }
                row.Cells.Add(chargeCur.RecurringCharge.TotalDue.ToString("c"));
                row.Cells.Add(rptChargeAmt.ToString("c"));
                row.Cells.Add(chargeAmt.ToString("c"));
                if (!checkHideBold.Checked)
                {
                    double diff = (Math.Max(famBalTotal, 0) + Math.Max(payPlanDue, 0)) - rptChargeAmt;
                    if (diff.IsZero() || (diff < 0 && RecurringCharges.CanChargeWhenNoBal(chargeCur.CanChargeWhenNoBal)))
                    {
                        //don't bold anything
                    }
                    else if (diff > 0)
                    {
                        row.Cells[6].Bold = YN.Yes;                      //"Repeating Amt"
                        row.Cells[7].Bold = YN.Yes;                      //"Charge Amt"
                    }
                    else if (diff < 0)
                    {
                        row.Cells[5].Bold = YN.Yes;                      //"Total Due"
                        row.Cells[7].Bold = YN.Yes;                      //"Charge Amt"
                    }
                }
                if (Programs.HasMultipleCreditCardProgramsEnabled())
                {
                    if (Programs.IsEnabled(ProgramName.Xcharge))
                    {
                        row.Cells.Add(!string.IsNullOrEmpty(chargeCur.XChargeToken) ? "X" : "");
                    }
                    if (Programs.IsEnabled(ProgramName.PayConnect))
                    {
                        row.Cells.Add(!string.IsNullOrEmpty(chargeCur.PayConnectToken) ? "X" : "");
                    }
                    if (Programs.IsEnabled(ProgramName.PaySimple))
                    {
                        row.Cells.Add(!string.IsNullOrEmpty(chargeCur.PaySimpleToken) ? "X" : "");
                    }
                }
                row.Tag = chargeCur;
                gridMain.ListGridRows.Add(row);
            }
            gridMain.EndUpdate();
            labelTotal.Text    = Lan.g(this, "Total=") + gridMain.ListGridRows.Count.ToString();
            labelSelected.Text = Lan.g(this, "Selected=") + gridMain.SelectedIndices.Length.ToString();
            Cursor             = Cursors.Default;
        }
Ejemplo n.º 7
0
        private void butOK_Click(object sender, System.EventArgs e)
        {
            if (textDate.errorProvider1.GetError(textDate) != "" ||
                textAPR.errorProvider1.GetError(textAPR) != "")
            {
                MessageBox.Show(Lan.g(this, "Please fix data entry errors first."));
                return;
            }
            DateTime date = PIn.Date(textDate.Text);

            if (PrefC.GetDate(PrefName.FinanceChargeLastRun).AddDays(25) > date)
            {
                if (!MsgBox.Show(this, true, "Warning.  Finance charges should not be run more than once per month.  Continue?"))
                {
                    return;
                }
            }
            else if (PrefC.GetDate(PrefName.BillingChargeLastRun).AddDays(25) > date)
            {
                if (!MsgBox.Show(this, true, "Warning.  Billing charges should not be run more than once per month.  Continue?"))
                {
                    return;
                }
            }
            if (listBillType.SelectedIndices.Count == 0)
            {
                MsgBox.Show(this, "Please select at least one billing type first.");
                return;
            }
            if (PIn.Long(textAPR.Text) < 2)
            {
                if (!MsgBox.Show(this, true, "The APR is much lower than normal. Do you wish to proceed?"))
                {
                    return;
                }
            }
            if (PrefC.GetBool(PrefName.AgingCalculatedMonthlyInsteadOfDaily) && PrefC.GetDate(PrefName.DateLastAging).AddMonths(1) <= DateTime.Today)
            {
                if (!MsgBox.Show(this, MsgBoxButtons.OKCancel, "It has been more than a month since aging has been run.  It is recommended that you update the aging date and run aging before continuing."))
                {
                    return;
                }
                //we might also consider a warning if textDate.Text does not match DateLastAging.  Probably not needed for daily aging, though.
            }
            PatAging[] AgingList = Patients.GetAgingListArray();
            double     OverallBalance;
            int        rowsAffected = 0;
            bool       billingMatch;

            for (int i = 0; i < AgingList.Length; i++) //loop through each guarantor that owes money.
            {
                OverallBalance = 0;                    //this WILL NOT be the same as the patient's total balance
                if (radio30.Checked)
                {
                    OverallBalance = AgingList[i].Bal_31_60 + AgingList[i].Bal_61_90 + AgingList[i].BalOver90;
                }
                else if (radio60.Checked)
                {
                    OverallBalance = AgingList[i].Bal_61_90 + AgingList[i].BalOver90;
                }
                else if (radio90.Checked)
                {
                    OverallBalance = AgingList[i].BalOver90;
                }
                if (OverallBalance <= .01d)
                {
                    continue;
                }
                billingMatch = false;
                for (int b = 0; b < listBillType.SelectedIndices.Count; b++)
                {
                    if (DefC.Short[(int)DefCat.BillingTypes][listBillType.SelectedIndices[b]].DefNum == AgingList[i].BillingType)
                    {
                        billingMatch = true;
                        break;
                    }
                }
                if (!billingMatch)
                {
                    continue;
                }
                if (radioFinanceCharge.Checked)
                {
                    AddFinanceCharge(AgingList[i].PatNum, date, textAPR.Text, OverallBalance, AgingList[i].PriProv);
                }
                else if (radioBillingCharge.Checked)
                {
                    AddBillingCharge(AgingList[i].PatNum, date, textBillingCharge.Text, AgingList[i].PriProv);
                }
                rowsAffected++;
            }
            if (radioFinanceCharge.Checked)
            {
                if (Prefs.UpdateString(PrefName.FinanceChargeAPR, textAPR.Text)
                    | Prefs.UpdateString(PrefName.FinanceChargeLastRun, POut.Date(date, false)))
                {
                    DataValid.SetInvalid(InvalidType.Prefs);
                }
                if (Prefs.UpdateString(PrefName.BillingChargeOrFinanceIsDefault, "Finance"))
                {
                    DataValid.SetInvalid(InvalidType.Prefs);
                }
                MessageBox.Show(Lan.g(this, "Finance Charges Added: ") + rowsAffected.ToString());
                Ledgers.RunAging();
                DialogResult = DialogResult.OK;
            }
            else if (radioBillingCharge.Checked)
            {
                if (Prefs.UpdateString(PrefName.BillingChargeAmount, textBillingCharge.Text)
                    | Prefs.UpdateString(PrefName.BillingChargeLastRun, POut.Date(date, false)))
                {
                    DataValid.SetInvalid(InvalidType.Prefs);
                }
                if (Prefs.UpdateString(PrefName.BillingChargeOrFinanceIsDefault, "Billing"))
                {
                    DataValid.SetInvalid(InvalidType.Prefs);
                }
                MessageBox.Show(Lan.g(this, "Billing Charges Added: ") + rowsAffected.ToString());
                Ledgers.RunAging();
                DialogResult = DialogResult.OK;
            }
        }
Ejemplo n.º 8
0
        ///<summary>Supply pd so that we know the paper size and margins.</summary>
        public static void CreateDocument(FormRpStatement sender, MigraDoc.DocumentObjectModel.Document doc, PrintDocument pd, Family fam, Patient pat, DataSet dataSet, Statement Stmt)
        {
            //doc= new MigraDoc.DocumentObjectModel.Document();//don't do this or the reference to the original doc will be lost.
            doc.DefaultPageSetup.PageWidth    = Unit.FromInch((double)pd.DefaultPageSettings.PaperSize.Width / 100);
            doc.DefaultPageSetup.PageHeight   = Unit.FromInch((double)pd.DefaultPageSettings.PaperSize.Height / 100);
            doc.DefaultPageSetup.TopMargin    = Unit.FromInch((double)pd.DefaultPageSettings.Margins.Top / 100);
            doc.DefaultPageSetup.LeftMargin   = Unit.FromInch((double)pd.DefaultPageSettings.Margins.Left / 100);
            doc.DefaultPageSetup.RightMargin  = Unit.FromInch((double)pd.DefaultPageSettings.Margins.Right / 100);
            doc.DefaultPageSetup.BottomMargin = Unit.FromInch((double)pd.DefaultPageSettings.Margins.Bottom / 100);
            MigraDoc.DocumentObjectModel.Section section = doc.AddSection();          //so that Swiss will have different footer for each patient.
            string text;

            MigraDoc.DocumentObjectModel.Font font;
            //GetPatGuar(PatNums[famIndex][0]);
            //Family fam=Patients.GetFamily(Stmt.PatNum);
            Patient PatGuar = fam.ListPats[0];          //.Copy();
            //Patient pat=fam.GetPatient(Stmt.PatNum);
            DataTable tableMisc = dataSet.Tables["misc"];

            //HEADING------------------------------------------------------------------------------
            #region Heading
            Paragraph       par       = section.AddParagraph();
            ParagraphFormat parformat = new ParagraphFormat();
            parformat.Alignment = ParagraphAlignment.Center;
            par.Format          = parformat;
            font = MigraDocHelper.CreateFont(14, true);
            text = "This statement was generated from the plug-in";
            par.AddFormattedText(text, font);
            text = DateTime.Today.ToShortDateString();
            font = MigraDocHelper.CreateFont(10);
            par.AddLineBreak();
            par.AddFormattedText(text, font);
            text = Lan.g("FormRpStatement", "Account Number") + " ";
            if (PrefC.GetBool(PrefName.StatementAccountsUseChartNumber))
            {
                text += PatGuar.ChartNumber;
            }
            else
            {
                text += PatGuar.PatNum;
            }
            par.AddLineBreak();
            par.AddFormattedText(text, font);
            TextFrame frame;
            #endregion
            //Practice Address----------------------------------------------------------------------
            #region Practice Address
            if (PrefC.GetBool(PrefName.StatementShowReturnAddress))
            {
                font  = MigraDocHelper.CreateFont(10);
                frame = section.AddTextFrame();
                frame.RelativeVertical   = RelativeVertical.Page;
                frame.RelativeHorizontal = RelativeHorizontal.Page;
                frame.MarginLeft         = Unit.Zero;
                frame.MarginTop          = Unit.Zero;
                frame.Top   = TopPosition.Parse("0.5 in");
                frame.Left  = LeftPosition.Parse("0.3 in");
                frame.Width = Unit.FromInch(3);
                if (!PrefC.GetBool(PrefName.EasyNoClinics) && Clinics.List.Length > 0 &&           //if using clinics
                    Clinics.GetClinic(PatGuar.ClinicNum) != null)                             //and this patient assigned to a clinic
                {
                    Clinic clinic = Clinics.GetClinic(PatGuar.ClinicNum);
                    par             = frame.AddParagraph();
                    par.Format.Font = font;
                    par.AddText(clinic.Description);
                    par.AddLineBreak();
                    par.AddText(clinic.Address);
                    par.AddLineBreak();
                    if (clinic.Address2 != "")
                    {
                        par.AddText(clinic.Address2);
                        par.AddLineBreak();
                    }
                    if (CultureInfo.CurrentCulture.Name.EndsWith("CH"))                     //CH is for switzerland. eg de-CH
                    {
                        par.AddText(clinic.Zip + " " + clinic.City);
                    }
                    else
                    {
                        par.AddText(clinic.City + ", " + clinic.State + " " + clinic.Zip);
                    }
                    par.AddLineBreak();
                    text = clinic.Phone;
                    if (text.Length == 10)
                    {
                        text = "(" + text.Substring(0, 3) + ")" + text.Substring(3, 3) + "-" + text.Substring(6);
                    }
                    par.AddText(text);
                    par.AddLineBreak();
                }
                else
                {
                    par             = frame.AddParagraph();
                    par.Format.Font = font;
                    par.AddText(PrefC.GetString(PrefName.PracticeTitle));
                    par.AddLineBreak();
                    if (CultureInfo.CurrentCulture.Name == "en-AU")                   //English (Australia)
                    {
                        Provider defaultProv = Providers.GetProv(PrefC.GetLong(PrefName.PracticeDefaultProv));
                        par.AddText("ABN: " + defaultProv.NationalProvID);
                        par.AddLineBreak();
                    }
                    par.AddText(PrefC.GetString(PrefName.PracticeAddress));
                    par.AddLineBreak();
                    if (PrefC.GetString(PrefName.PracticeAddress2) != "")
                    {
                        par.AddText(PrefC.GetString(PrefName.PracticeAddress2));
                        par.AddLineBreak();
                    }
                    if (CultureInfo.CurrentCulture.Name.EndsWith("CH"))                     //CH is for switzerland. eg de-CH
                    {
                        par.AddText(PrefC.GetString(PrefName.PracticeZip) + " " + PrefC.GetString(PrefName.PracticeCity));
                    }
                    else
                    {
                        par.AddText(PrefC.GetString(PrefName.PracticeCity) + ", " + PrefC.GetString(PrefName.PracticeST) + " " + PrefC.GetString(PrefName.PracticeZip));
                    }
                    par.AddLineBreak();
                    text = PrefC.GetString(PrefName.PracticePhone);
                    if (text.Length == 10)
                    {
                        text = "(" + text.Substring(0, 3) + ")" + text.Substring(3, 3) + "-" + text.Substring(6);
                    }
                    par.AddText(text);
                    par.AddLineBreak();
                }
            }
            #endregion
            //AMOUNT ENCLOSED------------------------------------------------------------------------------------------------------
            #region Amount Enclosed
            Table  table;
            Column col;
            Row    row;
            Cell   cell;
            frame = MigraDocHelper.CreateContainer(section, 450, 110, 330, 29);
            if (!Stmt.HidePayment)
            {
                table = MigraDocHelper.DrawTable(frame, 0, 0, 29);
                col   = table.AddColumn(Unit.FromInch(1.1));
                col   = table.AddColumn(Unit.FromInch(1.1));
                col   = table.AddColumn(Unit.FromInch(1.1));
                row   = table.AddRow();
                row.Format.Alignment = ParagraphAlignment.Center;
                row.Borders.Color    = Colors.Black;
                row.Shading.Color    = Colors.LightGray;
                row.TopPadding       = Unit.FromInch(0);
                row.BottomPadding    = Unit.FromInch(0);
                font = MigraDocHelper.CreateFont(8, true);
                cell = row.Cells[0];
                par  = cell.AddParagraph();
                par.AddFormattedText(Lan.g("FormRpStatement", "Amount Due"), font);
                cell = row.Cells[1];
                par  = cell.AddParagraph();
                par.AddFormattedText(Lan.g("FormRpStatement", "Date Due"), font);
                cell = row.Cells[2];
                par  = cell.AddParagraph();
                par.AddFormattedText(Lan.g("FormRpStatement", "Amount Enclosed"), font);
                row = table.AddRow();
                row.Format.Alignment     = ParagraphAlignment.Center;
                row.Borders.Left.Color   = Colors.Gray;
                row.Borders.Bottom.Color = Colors.Gray;
                row.Borders.Right.Color  = Colors.Gray;
                font = MigraDocHelper.CreateFont(9);
                double balTotal = PatGuar.BalTotal;
                if (!PrefC.GetBool(PrefName.BalancesDontSubtractIns))                 //this is typical
                {
                    balTotal -= PatGuar.InsEst;
                }
                for (int m = 0; m < tableMisc.Rows.Count; m++)
                {
                    if (tableMisc.Rows[m]["descript"].ToString() == "payPlanDue")
                    {
                        balTotal += PIn.Double(tableMisc.Rows[m]["value"].ToString());
                        //payPlanDue;//PatGuar.PayPlanDue;
                    }
                }
                text = balTotal.ToString("F");
                cell = row.Cells[0];
                par  = cell.AddParagraph();
                par.AddFormattedText(text, font);
                if (PrefC.GetLong(PrefName.StatementsCalcDueDate) == -1)
                {
                    text = Lan.g("FormRpStatement", "Upon Receipt");
                }
                else
                {
                    text = DateTime.Today.AddDays(PrefC.GetLong(PrefName.StatementsCalcDueDate)).ToShortDateString();
                }
                cell = row.Cells[1];
                par  = cell.AddParagraph();
                par.AddFormattedText(text, font);
            }
            #endregion
            //Credit Card Info--------------------------------------------------------------------------------------------------------
            #region Credit Card Info
            if (!Stmt.HidePayment)
            {
                if (PrefC.GetBool(PrefName.StatementShowCreditCard))
                {
                    float yPos = 60;
                    font = MigraDocHelper.CreateFont(7, true);
                    text = Lan.g("FormRpStatement", "CREDIT CARD TYPE");
                    MigraDocHelper.DrawString(frame, text, font, 0, yPos);
                    float rowHeight            = 26;
                    System.Drawing.Font  wfont = new System.Drawing.Font("Arial", 7, FontStyle.Bold);
                    System.Drawing.Image img   = new Bitmap(500, 30);
                    Graphics             g     = Graphics.FromImage(img);  //just to measure strings
                    MigraDocHelper.DrawLine(frame, System.Drawing.Color.Black, g.MeasureString(text, wfont).Width,
                                            yPos + wfont.GetHeight(g), 326, yPos + wfont.GetHeight(g));
                    yPos += rowHeight;
                    text  = Lan.g("FormRpStatement", "#");
                    MigraDocHelper.DrawString(frame, text, font, 0, yPos);
                    MigraDocHelper.DrawLine(frame, System.Drawing.Color.Black, g.MeasureString(text, wfont).Width,
                                            yPos + wfont.GetHeight(g), 326, yPos + wfont.GetHeight(g));
                    yPos += rowHeight;
                    text  = Lan.g("FormRpStatement", "3 DIGIT CSV");
                    MigraDocHelper.DrawString(frame, text, font, 0, yPos);
                    MigraDocHelper.DrawLine(frame, System.Drawing.Color.Black, g.MeasureString(text, wfont).Width,
                                            yPos + wfont.GetHeight(g), 326, yPos + wfont.GetHeight(g));
                    yPos += rowHeight;
                    text  = Lan.g("FormRpStatement", "EXPIRES");
                    MigraDocHelper.DrawString(frame, text, font, 0, yPos);
                    MigraDocHelper.DrawLine(frame, System.Drawing.Color.Black, g.MeasureString(text, wfont).Width,
                                            yPos + wfont.GetHeight(g), 326, yPos + wfont.GetHeight(g));
                    yPos += rowHeight;
                    text  = Lan.g("FormRpStatement", "AMOUNT APPROVED");
                    MigraDocHelper.DrawString(frame, text, font, 0, yPos);
                    MigraDocHelper.DrawLine(frame, System.Drawing.Color.Black, g.MeasureString(text, wfont).Width,
                                            yPos + wfont.GetHeight(g), 326, yPos + wfont.GetHeight(g));
                    yPos += rowHeight;
                    text  = Lan.g("FormRpStatement", "NAME");
                    MigraDocHelper.DrawString(frame, text, font, 0, yPos);
                    MigraDocHelper.DrawLine(frame, System.Drawing.Color.Black, g.MeasureString(text, wfont).Width,
                                            yPos + wfont.GetHeight(g), 326, yPos + wfont.GetHeight(g));
                    yPos += rowHeight;
                    text  = Lan.g("FormRpStatement", "SIGNATURE");
                    MigraDocHelper.DrawString(frame, text, font, 0, yPos);
                    MigraDocHelper.DrawLine(frame, System.Drawing.Color.Black, g.MeasureString(text, wfont).Width,
                                            yPos + wfont.GetHeight(g), 326, yPos + wfont.GetHeight(g));
                    yPos -= rowHeight;
                    text  = Lan.g("FormRpStatement", "(As it appears on card)");
                    wfont = new System.Drawing.Font("Arial", 5);
                    font  = MigraDocHelper.CreateFont(5);
                    MigraDocHelper.DrawString(frame, text, font, 625 - g.MeasureString(text, wfont).Width / 2 + 5, yPos + 13);
                    g.Dispose();
                    img = null;
                }
            }
            #endregion
            //Patient's Billing Address---------------------------------------------------------------------------------------------
            #region Patient Billing Address
            font            = MigraDocHelper.CreateFont(11);
            frame           = MigraDocHelper.CreateContainer(section, 62.5f + 12.5f, 225 + 1, 300, 200);
            par             = frame.AddParagraph();
            par.Format.Font = font;
            if (Stmt.SinglePatient)
            {
                par.AddText(fam.GetNameInFamFL(Stmt.PatNum));
            }
            else
            {
                par.AddText(PatGuar.GetNameFLFormal());
            }
            par.AddLineBreak();
            par.AddText(PatGuar.Address);
            par.AddLineBreak();
            if (PatGuar.Address2 != "")
            {
                par.AddText(PatGuar.Address2);
                par.AddLineBreak();
            }
            if (CultureInfo.CurrentCulture.Name.EndsWith("CH"))             //CH is for switzerland. eg de-CH
            {
                par.AddText(PatGuar.Zip + " " + PatGuar.City);
            }
            else
            {
                par.AddText(PatGuar.City + ", " + PatGuar.State + " " + PatGuar.Zip);
            }
            //perforated line------------------------------------------------------------------------------------------------------
            //yPos=350;//3.62 inches from top, 1/3 page down
            frame = MigraDocHelper.CreateContainer(section, 0, 350, 850, 30);
            if (!Stmt.HidePayment)
            {
                MigraDocHelper.DrawLine(frame, System.Drawing.Color.LightGray, 0, 0, 850, 0);
                text = Lan.g("FormRpStatement", "PLEASE DETACH AND RETURN THE UPPER PORTION WITH YOUR PAYMENT");
                font = MigraDocHelper.CreateFont(6, true, System.Drawing.Color.Gray);
                par  = frame.AddParagraph();
                par.Format.Alignment = ParagraphAlignment.Center;
                par.Format.Font      = font;
                par.AddText(text);
            }
            #endregion
            //Australian Provider Legend
            #region Australian Provider Legend
            int legendOffset = 0;
            if (CultureInfo.CurrentCulture.Name == "en-AU")           //English (Australia)
            {
                Providers.RefreshCache();
                legendOffset = 25 + 15 * (1 + ProviderC.List.Length);
                MigraDocHelper.InsertSpacer(section, legendOffset);
                frame           = MigraDocHelper.CreateContainer(section, 45, 390, 250, legendOffset);
                par             = frame.AddParagraph();
                par.Format.Font = MigraDocHelper.CreateFont(8, true);
                par.AddLineBreak();
                par.AddText("PROVIDERS:");
                par             = frame.AddParagraph();
                par.Format.Font = MigraDocHelper.CreateFont(8, false);
                for (int i = 0; i < ProviderC.List.Length; i++)           //All non-hidden providers are added to the legend.
                {
                    Provider prov   = ProviderC.List[i];
                    string   suffix = "";
                    if (prov.Suffix.Trim() != "")
                    {
                        suffix = ", " + prov.Suffix.Trim();
                    }
                    par.AddText(prov.Abbr + " - " + prov.FName + " " + prov.LName + suffix + " - " + prov.MedicaidID);
                    par.AddLineBreak();
                }
                par.AddLineBreak();
            }
            #endregion
            //Aging-----------------------------------------------------------------------------------
            #region Aging
            MigraDocHelper.InsertSpacer(section, 275);
            frame = MigraDocHelper.CreateContainer(section, 55, 390 + legendOffset, 250, 29);
            if (!Stmt.HidePayment)
            {
                table = MigraDocHelper.DrawTable(frame, 0, 0, 29);
                col   = table.AddColumn(Unit.FromInch(1.1));
                col   = table.AddColumn(Unit.FromInch(1.1));
                col   = table.AddColumn(Unit.FromInch(1.1));
                col   = table.AddColumn(Unit.FromInch(1.1));
                row   = table.AddRow();
                row.Format.Alignment = ParagraphAlignment.Center;
                row.Borders.Color    = Colors.Black;
                row.Shading.Color    = Colors.LightGray;
                row.TopPadding       = Unit.FromInch(0);
                row.BottomPadding    = Unit.FromInch(0);
                font = MigraDocHelper.CreateFont(8, true);
                cell = row.Cells[0];
                par  = cell.AddParagraph();
                par.AddFormattedText(Lan.g("FormRpStatement", "0-30"), font);
                cell = row.Cells[1];
                par  = cell.AddParagraph();
                par.AddFormattedText(Lan.g("FormRpStatement", "31-60"), font);
                cell = row.Cells[2];
                par  = cell.AddParagraph();
                par.AddFormattedText(Lan.g("FormRpStatement", "61-90"), font);
                cell = row.Cells[3];
                par  = cell.AddParagraph();
                par.AddFormattedText(Lan.g("FormRpStatement", "over 90"), font);
                row = table.AddRow();
                row.Format.Alignment     = ParagraphAlignment.Center;
                row.Borders.Left.Color   = Colors.Gray;
                row.Borders.Bottom.Color = Colors.Gray;
                row.Borders.Right.Color  = Colors.Gray;
                font = MigraDocHelper.CreateFont(9);
                text = PatGuar.Bal_0_30.ToString("F");
                cell = row.Cells[0];
                par  = cell.AddParagraph();
                par.AddFormattedText(text, font);
                text = PatGuar.Bal_31_60.ToString("F");
                cell = row.Cells[1];
                par  = cell.AddParagraph();
                par.AddFormattedText(text, font);
                text = PatGuar.Bal_61_90.ToString("F");
                cell = row.Cells[2];
                par  = cell.AddParagraph();
                par.AddFormattedText(text, font);
                text = PatGuar.BalOver90.ToString("F");
                cell = row.Cells[3];
                par  = cell.AddParagraph();
                par.AddFormattedText(text, font);
            }
            #endregion
            //Floating Balance, Ins info-------------------------------------------------------------------
            #region FloatingBalance
            frame = MigraDocHelper.CreateContainer(section, 460, 380 + legendOffset, 250, 200);
            //table=MigraDocHelper.DrawTable(frame,0,0,90);
            par                 = frame.AddParagraph();
            parformat           = new ParagraphFormat();
            parformat.Alignment = ParagraphAlignment.Right;
            par.Format          = parformat;
            font                = MigraDocHelper.CreateFont(10, false);
            MigraDoc.DocumentObjectModel.Font fontBold = MigraDocHelper.CreateFont(10, true);
            if (PrefC.GetBool(PrefName.BalancesDontSubtractIns))
            {
                text = Lan.g("FormRpStatement", "Balance:");
                par.AddFormattedText(text, fontBold);
                //par.AddLineBreak();
                //text = Lan.g(this, "Ins Pending:");
                //par.AddFormattedText(text, font);
                //par.AddLineBreak();
                //text = Lan.g(this, "After Ins:");
                //par.AddFormattedText(text, font);
                //par.AddLineBreak();
            }
            else              //this is more common
            {
                if (PrefC.GetBool(PrefName.FuchsOptionsOn))
                {
                    text = Lan.g("FormRpStatement", "Balance:");
                    par.AddFormattedText(text, font);
                    par.AddLineBreak();
                    text = Lan.g("FormRpStatement", "-Ins Estimate:");
                    par.AddFormattedText(text, font);
                    par.AddLineBreak();
                    text = Lan.g("FormRpStatement", "=Owed Now:");
                    par.AddFormattedText(text, fontBold);
                    par.AddLineBreak();
                }
                else
                {
                    text = Lan.g("FormRpStatement", "Total:");
                    par.AddFormattedText(text, font);
                    par.AddLineBreak();
                    text = Lan.g("FormRpStatement", "-Ins Estimate:");
                    par.AddFormattedText(text, font);
                    par.AddLineBreak();
                    text = Lan.g("FormRpStatement", "=Balance:");
                    par.AddFormattedText(text, fontBold);
                    par.AddLineBreak();
                }
            }
            frame = MigraDocHelper.CreateContainer(section, 730, 380 + legendOffset, 100, 200);
            //table=MigraDocHelper.DrawTable(frame,0,0,90);
            par                 = frame.AddParagraph();
            parformat           = new ParagraphFormat();
            parformat.Alignment = ParagraphAlignment.Left;
            par.Format          = parformat;
            font                = MigraDocHelper.CreateFont(10, false);
            //numbers:
            if (PrefC.GetBool(PrefName.BalancesDontSubtractIns))
            {
                text = PatGuar.BalTotal.ToString("c");
                par.AddFormattedText(text, fontBold);
                //par.AddLineBreak();
                //text = PatGuar.InsEst.ToString("c");
                //par.AddFormattedText(text, font);
                //par.AddLineBreak();
                //text = (PatGuar.BalTotal - PatGuar.InsEst).ToString("c");
                //par.AddFormattedText(text, font);
                //par.AddLineBreak();
            }
            else              //more common
            {
                if (Stmt.SinglePatient)
                {
                    double patInsEst = 0;
                    for (int m = 0; m < tableMisc.Rows.Count; m++)
                    {
                        if (tableMisc.Rows[m]["descript"].ToString() == "patInsEst")
                        {
                            patInsEst = PIn.Double(tableMisc.Rows[m]["value"].ToString());
                        }
                    }
                    double patBal = pat.EstBalance - patInsEst;
                    text = pat.EstBalance.ToString("c");
                    par.AddFormattedText(text, font);
                    par.AddLineBreak();
                    text = patInsEst.ToString("c");
                    par.AddFormattedText(text, font);
                    par.AddLineBreak();
                    text = patBal.ToString("c");
                    par.AddFormattedText(text, fontBold);
                }
                else
                {
                    text = PatGuar.BalTotal.ToString("c");
                    par.AddFormattedText(text, font);
                    par.AddLineBreak();
                    text = PatGuar.InsEst.ToString("c");
                    par.AddFormattedText(text, font);
                    par.AddLineBreak();
                    text = (PatGuar.BalTotal - PatGuar.InsEst).ToString("c");
                    par.AddFormattedText(text, fontBold);
                    par.AddLineBreak();
                }
            }
            MigraDocHelper.InsertSpacer(section, 80);
            #endregion FloatingBalance
            //Bold note-------------------------------------------------------------------------------
            #region Bold note
            if (Stmt.NoteBold != "")
            {
                MigraDocHelper.InsertSpacer(section, 7);
                font            = MigraDocHelper.CreateFont(10, true, System.Drawing.Color.DarkRed);
                par             = section.AddParagraph();
                par.Format.Font = font;
                par.AddText(Stmt.NoteBold);
                MigraDocHelper.InsertSpacer(section, 8);
            }
            #endregion Bold note
            //Payment plan grid definition---------------------------------------------------------------------------------
            #region PayPlan grid definition
            ODGridColumn gcol;
            ODGridRow    grow;
            ODGrid       gridPP = new ODGrid();
            //this.Controls.Add(gridPP);
            gridPP.BeginUpdate();
            gridPP.Columns.Clear();
            gcol = new ODGridColumn(Lan.g("FormRpStatement", "Date"), 73);
            gridPP.Columns.Add(gcol);
            gcol = new ODGridColumn(Lan.g("FormRpStatement", "Description"), 270);
            gridPP.Columns.Add(gcol);
            gcol = new ODGridColumn(Lan.g("FormRpStatement", "Charges"), 60, HorizontalAlignment.Right);
            gridPP.Columns.Add(gcol);
            gcol = new ODGridColumn(Lan.g("FormRpStatement", "Credits"), 60, HorizontalAlignment.Right);
            gridPP.Columns.Add(gcol);
            gcol = new ODGridColumn(Lan.g("FormRpStatement", "Balance"), 60, HorizontalAlignment.Right);
            gridPP.Columns.Add(gcol);
            gridPP.Width = gridPP.WidthAllColumns + 20;
            gridPP.EndUpdate();
            #endregion PayPlan grid definition
            //Payment plan grid.  There will be only one, if any-----------------------------------------------------------------
            #region PayPlan grid
            DataTable  tablePP = dataSet.Tables["payplan"];
            ODGridCell gcell;
            if (tablePP.Rows.Count > 0)
            {
                //MigraDocHelper.InsertSpacer(section,5);
                par                  = section.AddParagraph();
                par.Format.Font      = MigraDocHelper.CreateFont(10, true);
                par.Format.Alignment = ParagraphAlignment.Center;
                //par.Format.SpaceBefore=Unit.FromInch(.05);
                //par.Format.SpaceAfter=Unit.FromInch(.05);
                par.AddText(Lan.g("FormRpStatement", "Payment Plans"));
                MigraDocHelper.InsertSpacer(section, 2);
                gridPP.BeginUpdate();
                gridPP.Rows.Clear();
                for (int p = 0; p < tablePP.Rows.Count; p++)
                {
                    grow = new ODGridRow();
                    grow.Cells.Add(tablePP.Rows[p]["date"].ToString());
                    grow.Cells.Add(tablePP.Rows[p]["description"].ToString());
                    grow.Cells.Add(tablePP.Rows[p]["charges"].ToString());
                    grow.Cells.Add(tablePP.Rows[p]["credits"].ToString());
                    gcell = new ODGridCell(tablePP.Rows[p]["balance"].ToString());
                    if (p == tablePP.Rows.Count - 1)
                    {
                        gcell.Bold = YN.Yes;
                    }
                    else if (tablePP.Rows[p + 1]["balance"].ToString() == "")                 //if next row balance is blank.
                    {
                        gcell.Bold = YN.Yes;
                    }
                    grow.Cells.Add(gcell);
                    gridPP.Rows.Add(grow);
                }
                gridPP.EndUpdate();
                MigraDocHelper.DrawGrid(section, gridPP);
                MigraDocHelper.InsertSpacer(section, 2);
                par                    = section.AddParagraph();
                par.Format.Font        = MigraDocHelper.CreateFont(10, true);
                par.Format.Alignment   = ParagraphAlignment.Right;
                par.Format.RightIndent = Unit.FromInch(0.25);
                double payPlanDue = 0;
                for (int m = 0; m < tableMisc.Rows.Count; m++)
                {
                    if (tableMisc.Rows[m]["descript"].ToString() == "payPlanDue")
                    {
                        payPlanDue = PIn.Double(tableMisc.Rows[m]["value"].ToString());
                    }
                }
                par.AddText(Lan.g("FormRpStatement", "Payment Plan Amount Due: ") + payPlanDue.ToString("c"));             //PatGuar.PayPlanDue.ToString("c"));
                MigraDocHelper.InsertSpacer(section, 10);
            }
            #endregion PayPlan grid
            //Body Table definition--------------------------------------------------------------------------------------------------------
            #region Body Table definition
            ODGrid gridPat = new ODGrid();
            //this.Controls.Add(gridPat);
            gridPat.BeginUpdate();
            gridPat.Columns.Clear();
            gcol = new ODGridColumn(Lan.g("FormRpStatement", "Date"), 73);
            gridPat.Columns.Add(gcol);
            gcol = new ODGridColumn(Lan.g("FormRpStatement", "Patient"), 100);
            gridPat.Columns.Add(gcol);
            //prov
            gcol = new ODGridColumn(Lan.g("FormRpStatement", "Code"), 45);
            gridPat.Columns.Add(gcol);
            gcol = new ODGridColumn(Lan.g("FormRpStatement", "Tooth"), 42);
            gridPat.Columns.Add(gcol);
            gcol = new ODGridColumn(Lan.g("FormRpStatement", "Description"), 270);
            gridPat.Columns.Add(gcol);
            gcol = new ODGridColumn(Lan.g("FormRpStatement", "Charges"), 60, HorizontalAlignment.Right);
            gridPat.Columns.Add(gcol);
            gcol = new ODGridColumn(Lan.g("FormRpStatement", "Credits"), 60, HorizontalAlignment.Right);
            gridPat.Columns.Add(gcol);
            gcol = new ODGridColumn(Lan.g("FormRpStatement", "Balance"), 60, HorizontalAlignment.Right);
            gridPat.Columns.Add(gcol);
            gridPat.Width = gridPat.WidthAllColumns + 20;
            gridPat.EndUpdate();
            #endregion Body Table definition
            //Loop through each table.  Could be one intermingled, or one for each patient-----------------------------------------
            DataTable tableAccount;
            string    tablename;
            long      patnum;
            for (int i = 0; i < dataSet.Tables.Count; i++)
            {
                tableAccount = dataSet.Tables[i];
                tablename    = tableAccount.TableName;
                if (!tablename.StartsWith("account"))
                {
                    continue;
                }
                par                    = section.AddParagraph();
                par.Format.Font        = MigraDocHelper.CreateFont(10, true);
                par.Format.SpaceBefore = Unit.FromInch(.05);
                par.Format.SpaceAfter  = Unit.FromInch(.05);
                patnum                 = 0;
                if (tablename != "account")               //account123 etc.
                {
                    patnum = PIn.Long(tablename.Substring(7));
                }
                if (patnum != 0)
                {
                    par.AddText(fam.GetNameInFamFLnoPref(patnum));
                }
                //if(FamilyStatementDataList[famIndex].PatAboutList[i].ApptDescript!=""){
                //	par=section.AddParagraph();
                //	par.Format.Font=MigraDocHelper.CreateFont(9);//same as body font
                //	par.AddText(FamilyStatementDataList[famIndex].PatAboutList[i].ApptDescript);
                //}
                gridPat.BeginUpdate();
                gridPat.Rows.Clear();
                //lineData=FamilyStatementDataList[famIndex].PatDataList[i].PatData;
                for (int p = 0; p < tableAccount.Rows.Count; p++)
                {
                    grow = new ODGridRow();
                    grow.Cells.Add(tableAccount.Rows[p]["date"].ToString());
                    grow.Cells.Add(tableAccount.Rows[p]["patient"].ToString());
                    grow.Cells.Add(tableAccount.Rows[p]["ProcCode"].ToString());
                    grow.Cells.Add(tableAccount.Rows[p]["tth"].ToString());
                    if (CultureInfo.CurrentCulture.Name == "en-AU")                   //English (Australia)
                    {
                        if (tableAccount.Rows[p]["prov"].ToString().Trim() != "")
                        {
                            grow.Cells.Add(tableAccount.Rows[p]["prov"].ToString() + " - " + tableAccount.Rows[p]["description"].ToString());
                        }
                        else                          //No provider on this account row item, so don't put the extra leading characters.
                        {
                            grow.Cells.Add(tableAccount.Rows[p]["description"].ToString());
                        }
                    }
                    else                      //Assume English (United States)
                    {
                        grow.Cells.Add(tableAccount.Rows[p]["description"].ToString());
                    }
                    grow.Cells.Add(tableAccount.Rows[p]["charges"].ToString());
                    grow.Cells.Add(tableAccount.Rows[p]["credits"].ToString());
                    grow.Cells.Add(tableAccount.Rows[p]["balance"].ToString());
                    gridPat.Rows.Add(grow);
                }
                gridPat.EndUpdate();
                MigraDocHelper.DrawGrid(section, gridPat);
                //Total
                frame = MigraDocHelper.CreateContainer(section);
                font  = MigraDocHelper.CreateFont(9, true);
                float totalPos = ((float)(doc.DefaultPageSetup.PageWidth.Inch //-doc.DefaultPageSetup.LeftMargin.Inch
                                                                              //-doc.DefaultPageSetup.RightMargin.Inch)
                                          ) * 100f) / 2f + (float)gridPat.WidthAllColumns / 2f + 7;
                RectangleF rectF = new RectangleF(0, 0, totalPos, 16);
                if (patnum != 0)
                {
                    MigraDocHelper.DrawString(frame, " ",
                                              //I decided this was unnecessary:
                                              //dataSet.Tables["patient"].Rows[fam.GetIndex(patnum)]["balance"].ToString(),
                                              font, rectF, ParagraphAlignment.Right);
                    //MigraDocHelper.DrawString(frame,FamilyStatementDataList[famIndex].PatAboutList[i].Balance.ToString("F"),font,rectF,
                    //	ParagraphAlignment.Right);
                }
            }
            gridPat.Dispose();
            //Future appointments---------------------------------------------------------------------------------------------
            #region Future appointments
            font = MigraDocHelper.CreateFont(9);
            DataTable tableAppt = dataSet.Tables["appts"];
            if (tableAppt.Rows.Count > 0)
            {
                par             = section.AddParagraph();
                par.Format.Font = font;
                par.AddText(Lan.g("FormRpStatement", "Scheduled Appointments:"));
            }
            for (int i = 0; i < tableAppt.Rows.Count; i++)
            {
                par.AddLineBreak();
                par.AddText(tableAppt.Rows[i]["descript"].ToString());
            }
            if (tableAppt.Rows.Count > 0)
            {
                MigraDocHelper.InsertSpacer(section, 10);
            }
            #endregion Future appointments
            //Note------------------------------------------------------------------------------------------------------------
            font            = MigraDocHelper.CreateFont(9);
            par             = section.AddParagraph();
            par.Format.Font = font;
            par.AddText(Stmt.Note);
            //bold note
            if (Stmt.NoteBold != "")
            {
                MigraDocHelper.InsertSpacer(section, 10);
                font            = MigraDocHelper.CreateFont(10, true, System.Drawing.Color.DarkRed);
                par             = section.AddParagraph();
                par.Format.Font = font;
                par.AddText(Stmt.NoteBold);
            }
            //return doc;
        }
Ejemplo n.º 9
0
        private void butOK_Click(object sender, System.EventArgs e)
        {
            bool   usingEcw     = Programs.UsingEcwTightOrFullMode();
            Userod selectedUser = null;

            if (PrefC.GetBool(PrefName.UserNameManualEntry))
            {
                for (int i = 0; i < listUser.Items.Count; i++)
                {
                    //Check the user name typed in using ToLower and Trim because Open Dental is case insensitive and does not allow white-space in regards to user names.
                    if (textUser.Text.Trim().ToLower() == listUser.Items[i].ToString().Trim().ToLower())
                    {
                        selectedUser = (Userod)listUser.Items[i];                      //Found the typed username
                        break;
                    }
                }
                if (selectedUser == null)
                {
                    MsgBox.Show(this, "Login failed");
                    return;
                }
            }
            else
            {
                selectedUser = (Userod)listUser.SelectedItem;
            }
            string password = textPassword.Text;

            if (usingEcw)             //ecw requires hash, but non-ecw requires actual password
            {
                password = Userods.HashPassword(password, true);
            }
            if (selectedUser.UserName == "Stay Open" && IsSimpleSwitch && PrefC.IsODHQ)
            {
                // No need to check password when changing task users at HQ to user "Stay Open".
            }
            else
            {
                try {
                    Userods.CheckUserAndPassword(selectedUser.UserName, password, usingEcw);
                }
                catch (Exception ex) {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
            if (RemotingClient.RemotingRole == RemotingRole.ClientWeb && selectedUser.Password == "" && textPassword.Text == "")
            {
                MsgBox.Show(this, "When using the web service, not allowed to log in with no password.  A password should be added for this user.");
                return;
            }
            //successful login.
            if (!IsSimpleSwitch)
            {
                Security.CurUser        = selectedUser.Copy();
                Security.IsUserLoggedIn = true;
                //Jason approved always storing the cleartext password that the user typed in
                //since this is necessary for Reporting Servers over middle tier and was already happening when a user logged in over middle tier.
                Security.PasswordTyped = password;
                if (PrefC.GetBool(PrefName.PasswordsMustBeStrong) && PrefC.GetBool(PrefName.PasswordsWeakChangeToStrong))
                {
                    if (Userods.IsPasswordStrong(textPassword.Text) != "")                   //Password is not strong
                    {
                        MsgBox.Show(this, "You must change your password to a strong password due to the current Security settings.");
                        FormOpenDental FormOD = Application.OpenForms.OfType <FormOpenDental>().ToList()[0]; //There always should be exactly 1.
                        if (!FormOD.ChangePassword(true))                                                    //Failed password update.
                        {
                            return;
                        }
                    }
                }
            }
            else
            {
                CurUserSimpleSwitch = selectedUser.Copy();
            }
            if (!IsSimpleSwitch)
            {
                SecurityLogs.MakeLogEntry(Permissions.UserLogOnOff, 0, "User: "******" has logged on.");
            }
            Plugins.HookAddCode(this, "FormLogOn.butOK_Click_end");
            DialogResult = DialogResult.OK;
        }
Ejemplo n.º 10
0
 private void FormRxEdit_Load(object sender, System.EventArgs e)
 {
     if (IsNew)
     {
         butView.Visible   = false;
         labelView.Visible = false;
         sheet             = null;
         if (PrefC.GetBool(PrefName.ShowFeatureEhr) && Security.CurUser.ProvNum != 0)               //Is CPOE
         {
             labelCPOE.Visible    = true;
             comboProvNum.Enabled = false;
             butPickProv.Enabled  = false;
             RxPatCur.ProvNum     = Security.CurUser.ProvNum;
         }
     }
     else
     {
         sheet = Sheets.GetRx(RxPatCur.PatNum, RxPatCur.RxNum);
         if (sheet == null)
         {
             butView.Visible   = false;
             labelView.Visible = false;
         }
         else
         {
             butPrint.Visible = false;
         }
     }
     //security is handled on the Rx button click in the Chart module
     _provNumSelected = RxPatCur.ProvNum;
     comboProvNum.Items.Clear();
     for (int i = 0; i < ProviderC.ListShort.Count; i++)
     {
         comboProvNum.Items.Add(ProviderC.ListShort[i].GetLongDesc());                //Only visible provs added to combobox.
         if (ProviderC.ListShort[i].ProvNum == RxPatCur.ProvNum)
         {
             comboProvNum.SelectedIndex = i;                  //Sets combo text too.
         }
     }
     if (_provNumSelected == 0)           //Is new
     {
         comboProvNum.SelectedIndex = 0;
         _provNumSelected           = ProviderC.ListShort[0].ProvNum;
     }
     if (comboProvNum.SelectedIndex == -1)                            //The provider exists but is hidden
     {
         comboProvNum.Text = Providers.GetLongDesc(_provNumSelected); //Appends "(hidden)" to the end of the long description.
     }
     textDate.Text           = RxPatCur.RxDate.ToString("d");
     checkControlled.Checked = RxPatCur.IsControlled;
     for (int i = 0; i < Enum.GetNames(typeof(RxSendStatus)).Length; i++)
     {
         comboSendStatus.Items.Add(Enum.GetNames(typeof(RxSendStatus))[i]);
     }
     comboSendStatus.SelectedIndex = (int)RxPatCur.SendStatus;
     textDrug.Text    = RxPatCur.Drug;
     textSig.Text     = RxPatCur.Sig;
     textDisp.Text    = RxPatCur.Disp;
     textRefills.Text = RxPatCur.Refills;
     if (PrefC.GetBool(PrefName.ShowFeatureEhr))
     {
         textDosageCode.Text = RxPatCur.DosageCode;
     }
     else
     {
         labelDosageCode.Visible = false;
         textDosageCode.Visible  = false;
     }
     textNotes.Text    = RxPatCur.Notes;
     textPharmacy.Text = Pharmacies.GetDescription(RxPatCur.PharmacyNum);
 }
Ejemplo n.º 11
0
        ///<summary>Adds the xml for one statement.</summary>
        public static void GenerateOneStatement(XmlWriter writer, Statement stmt, Patient pat, Family fam, DataSet dataSet)
        {
            writer.WriteStartElement("EisStatement");
            writer.WriteAttributeString("OutputFormat", "StmOut_Blue6Col");
            writer.WriteAttributeString("CreditCardChoice", PrefC.GetString(PrefName.BillingElectCreditCardChoices));
            writer.WriteStartElement("Patient");
            Patient guar = fam.ListPats[0];

            writer.WriteElementString("Name", guar.GetNameFLFormal());
            writer.WriteElementString("Account", guar.PatNum.ToString());
            writer.WriteElementString("Address1", guar.Address);
            writer.WriteElementString("Address2", guar.Address2);
            writer.WriteElementString("City", guar.City);
            writer.WriteElementString("State", guar.State);
            writer.WriteElementString("Zip", guar.Zip);
            string email      = "";
            Def    billingDef = DefC.GetDef(DefCat.BillingTypes, guar.BillingType);

            if (billingDef.ItemValue == "E")
            {
                email = guar.Email;
            }
            writer.WriteElementString("EMail", email);
            //Account summary-----------------------------------------------------------------------
            writer.WriteStartElement("AccountSummary");
            if (stmt.DateRangeFrom.Year < 1880)           //make up a statement date.
            {
                writer.WriteElementString("PriorStatementDate", DateTime.Today.AddMonths(-1).ToString("MM/dd/yyyy"));
            }
            else
            {
                writer.WriteElementString("PriorStatementDate", stmt.DateRangeFrom.AddDays(-1).ToString("MM/dd/yyyy"));
            }
            DateTime dueDate;

            if (PrefC.GetLong(PrefName.StatementsCalcDueDate) == -1)
            {
                dueDate = DateTime.Today.AddDays(10);
            }
            else
            {
                dueDate = DateTime.Today.AddDays(PrefC.GetLong(PrefName.StatementsCalcDueDate));
            }
            writer.WriteElementString("DueDate", dueDate.ToString("MM/dd/yyyy"));
            writer.WriteElementString("StatementDate", stmt.DateSent.ToString("MM/dd/yyyy"));
            double balanceForward = 0;

            for (int r = 0; r < dataSet.Tables["misc"].Rows.Count; r++)
            {
                if (dataSet.Tables["misc"].Rows[r]["descript"].ToString() == "balanceForward")
                {
                    balanceForward = PIn.Double(dataSet.Tables["misc"].Rows[r]["value"].ToString());
                }
            }
            writer.WriteElementString("PriorBalance", balanceForward.ToString("F2"));
            writer.WriteElementString("RunningBalance", "");      //for future use
            writer.WriteElementString("PerPayAdj", "");           //optional
            writer.WriteElementString("InsPayAdj", "");           //optional
            writer.WriteElementString("Adjustments", "");         //for future use
            writer.WriteElementString("NewCharges", "");          //optional
            writer.WriteElementString("FinanceCharges", "");      //for future use
            DataTable tableAccount = null;

            for (int i = 0; i < dataSet.Tables.Count; i++)
            {
                if (dataSet.Tables[i].TableName.StartsWith("account"))
                {
                    tableAccount = dataSet.Tables[i];
                }
            }
            double credits = 0;

            for (int i = 0; i < tableAccount.Rows.Count; i++)
            {
                credits += PIn.Double(tableAccount.Rows[i]["creditsDouble"].ToString());
            }
            writer.WriteElementString("Credits", credits.ToString("F2"));
            //on a regular printed statement, the amount due at the top might be different from the balance at the middle right.
            //This is because of payment plan balances.
            //But in e-bills, there is only one amount due.
            //Insurance estimate is already subtracted, and payment plan balance is already added.
            double amountDue = guar.BalTotal;

            //add payplan due amt:
            for (int m = 0; m < dataSet.Tables["misc"].Rows.Count; m++)
            {
                if (dataSet.Tables["misc"].Rows[m]["descript"].ToString() == "payPlanDue")
                {
                    amountDue += PIn.Double(dataSet.Tables["misc"].Rows[m]["value"].ToString());
                }
            }
            if (PrefC.GetBool(PrefName.BalancesDontSubtractIns))
            {
                writer.WriteElementString("EstInsPayments", "");               //optional.
                writer.WriteElementString("PatientShare", amountDue.ToString("F2"));
                //this is ambiguous.  It seems to be AmountDue, but it could possibly be 0-30 days aging
                writer.WriteElementString("CurrentBalance", amountDue.ToString("F2"));
            }
            else                                                                         //this is typical
            {
                writer.WriteElementString("EstInsPayments", guar.InsEst.ToString("F2")); //optional.
                amountDue -= guar.InsEst;
                writer.WriteElementString("PatientShare", amountDue.ToString("F2"));
                writer.WriteElementString("CurrentBalance", amountDue.ToString("F2"));
            }
            writer.WriteElementString("PastDue30", guar.Bal_31_60.ToString("F2")); //optional
            writer.WriteElementString("PastDue60", guar.Bal_61_90.ToString("F2")); //optional
            writer.WriteElementString("PastDue90", guar.BalOver90.ToString("F2")); //optional
            writer.WriteElementString("PastDue120", "");                           //optional
            writer.WriteEndElement();                                              //AccountSummary
            //Notes-----------------------------------------------------------------------------------
            writer.WriteStartElement("Notes");
            if (stmt.NoteBold != "")
            {
                writer.WriteStartElement("Note");
                writer.WriteAttributeString("FgColor", "Red");               //ColorToHexString(Color.DarkRed));
                //writer.WriteAttributeString("BgColor",ColorToHexString(Color.White));
                writer.WriteCData(stmt.NoteBold);
                writer.WriteEndElement();                //Note
            }
            if (stmt.Note != "")
            {
                writer.WriteStartElement("Note");
                //writer.WriteAttributeString("FgColor",ColorToHexString(Color.Black));
                //writer.WriteAttributeString("BgColor",ColorToHexString(Color.White));
                writer.WriteCData(stmt.Note);
                writer.WriteEndElement();        //Note
            }
            writer.WriteEndElement();            //Notes
            //Detail items------------------------------------------------------------------------------
            writer.WriteStartElement("DetailItems");
            //string note;
            string descript;
            string fulldesc;
            string procCode;
            string tth;

            //string linedesc;
            string[]      lineArray;
            List <string> lines;
            DateTime      date;
            int           seq = 0;

            for (int i = 0; i < tableAccount.Rows.Count; i++)
            {
                procCode  = tableAccount.Rows[i]["ProcCode"].ToString();
                tth       = tableAccount.Rows[i]["tth"].ToString();
                descript  = tableAccount.Rows[i]["description"].ToString();
                fulldesc  = procCode + " " + tth + " " + descript;
                lineArray = fulldesc.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                lines     = new List <string>(lineArray);
                //The specs say that the line limit is 30 char.  But in testing, it will take 50 char.
                //We will use 40 char to be safe.
                if (lines[0].Length > 40)
                {
                    string newline = lines[0].Substring(40);
                    lines[0] = lines[0].Substring(0, 40);       //first half
                    lines.Insert(1, newline);                   //second half
                }
                for (int li = 0; li < lines.Count; li++)
                {
                    writer.WriteStartElement("DetailItem");                    //has a child item. We won't add optional child note
                    writer.WriteAttributeString("sequence", seq.ToString());
                    writer.WriteStartElement("Item");
                    if (li == 0)
                    {
                        date = (DateTime)tableAccount.Rows[i]["DateTime"];
                        writer.WriteElementString("Date", date.ToString("MM/dd/yyyy"));
                        writer.WriteElementString("PatientName", tableAccount.Rows[i]["patient"].ToString());
                    }
                    else
                    {
                        writer.WriteElementString("Date", "");
                        writer.WriteElementString("PatientName", "");
                    }
                    writer.WriteElementString("Description", lines[li]);
                    if (li == 0)
                    {
                        writer.WriteElementString("Charges", tableAccount.Rows[i]["charges"].ToString());
                        writer.WriteElementString("Credits", tableAccount.Rows[i]["credits"].ToString());
                        writer.WriteElementString("Balance", tableAccount.Rows[i]["balance"].ToString());
                    }
                    else
                    {
                        writer.WriteElementString("Charges", "");
                        writer.WriteElementString("Credits", "");
                        writer.WriteElementString("Balance", "");
                    }
                    writer.WriteEndElement();                    //Item
                    writer.WriteEndElement();                    //DetailItem
                    seq++;
                }

                /*The code below just didn't work because notes don't get displayed on the statement.
                 * linedesc=lines[0];
                 * note="";
                 * if(linedesc.Length>30) {
                 *      note=linedesc.Substring(30);
                 *      linedesc=linedesc.Substring(0,30);
                 * }
                 * for(int l=1;l<lines.Length;l++) {
                 *      if(note!="") {
                 *              note+="\r\n";
                 *      }
                 *      note+=lines[l];
                 * }
                 *
                 * if(note!="") {
                 *      writer.WriteStartElement("Note");
                 *      //we're not going to specify colors here since they're optional
                 *      writer.WriteCData(note);
                 *      writer.WriteEndElement();//Note
                 * }*/
            }
            writer.WriteEndElement();            //DetailItems
            writer.WriteEndElement();            //Patient
            writer.WriteEndElement();            //EisStatement
        }
        private void FillTabWebSchedRecall()
        {
            switch (PrefC.GetInt(PrefName.WebSchedAutomaticSendSetting))
            {
            case (int)WebSchedAutomaticSend.DoNotSend:
                radioDoNotSend.Checked = true;
                break;

            case (int)WebSchedAutomaticSend.SendToEmail:
                radioSendToEmail.Checked = true;
                break;

            case (int)WebSchedAutomaticSend.SendToEmailNoPreferred:
                radioSendToEmailNoPreferred.Checked = true;
                break;

            case (int)WebSchedAutomaticSend.SendToEmailOnlyPreferred:
                radioSendToEmailOnlyPreferred.Checked = true;
                break;
            }
            switch (PrefC.GetInt(PrefName.WebSchedAutomaticSendTextSetting))
            {
            case (int)WebSchedAutomaticSend.DoNotSend:
                radioDoNotSendText.Checked = true;
                break;

            case (int)WebSchedAutomaticSend.SendToText:
                radioSendText.Checked = true;
                break;
            }
            textWebSchedPerBatch.Text  = PrefC.GetString(PrefName.WebSchedTextsPerBatch);
            textWebSchedDateStart.Text = DateTime.Today.ToShortDateString();
            comboWebSchedClinic.Items.Clear();
            comboWebSchedClinic.Items.Add(Lan.g(this, "Unassigned"));
            _listWebSchedClinics = Clinics.GetDeepCopy();
            for (int i = 0; i < _listWebSchedClinics.Count; i++)
            {
                comboWebSchedClinic.Items.Add(_listWebSchedClinics[i].Abbr);
            }
            comboWebSchedClinic.SelectedIndex = 0;
            _listWebSchedProviders            = Providers.GetDeepCopy(true);
            comboWebSchedProviders.Items.Clear();
            comboWebSchedProviders.Items.Add(Lan.g(this, "All"));
            for (int i = 0; i < _listWebSchedProviders.Count; i++)
            {
                comboWebSchedProviders.Items.Add(_listWebSchedProviders[i].GetLongDesc());
            }
            comboWebSchedProviders.SelectedIndex = 0;
            if (PrefC.GetBool(PrefName.EasyNoClinics))
            {
                labelWebSchedClinic.Visible   = false;
                comboWebSchedClinic.Visible   = false;
                butWebSchedPickClinic.Visible = false;
            }
            FillListBoxWebSchedBlockoutTypes(PrefC.GetString(PrefName.WebSchedRecallIgnoreBlockoutTypes).Split(new char[] { ',' }), listboxWebSchedRecallIgnoreBlockoutTypes);
            FillGridWebSchedRecallTypes();
            FillGridWebSchedOperatories();
            FillGridWebSchedTimeSlotsThreaded();
            listBoxWebSchedProviderPref.SelectedIndex = PrefC.GetInt(PrefName.WebSchedProviderRule);
            checkRecallAllowProvSelection.Checked     = PrefC.GetBool(PrefName.WebSchedRecallAllowProvSelection);
            long       defaultStatus = PrefC.GetLong(PrefName.WebSchedRecallConfirmStatus);
            List <Def> listDefs      = Defs.GetDefsForCategory(DefCat.ApptConfirmed, true);

            for (int i = 0; i < listDefs.Count; i++)
            {
                int idx = comboWSRConfirmStatus.Items.Add(listDefs[i].ItemName);
                if (listDefs[i].DefNum == defaultStatus)
                {
                    comboWSRConfirmStatus.SelectedIndex = idx;
                }
            }
            comboWSRConfirmStatus.IndexSelectOrSetText(listDefs.ToList().FindIndex(x => x.DefNum == defaultStatus),
                                                       () => { return(defaultStatus == 0 ? "" : Defs.GetName(DefCat.ApptConfirmed, defaultStatus) + " (" + Lan.g(this, "hidden") + ")"); });
        }
Ejemplo n.º 13
0
        private void FillGrid()
        {
            this.Cursor = Cursors.WaitCursor;
            string order = "";

            switch (comboOrder.SelectedIndex)
            {
            case 0:
                order = "status";
                break;

            case 1:
                order = "alph";
                break;

            case 2:
                order = "date";
                break;
            }
            long provNum = 0;

            if (comboProv.SelectedIndex != 0)
            {
                provNum = ProviderC.ListShort[comboProv.SelectedIndex - 1].ProvNum;
            }
            long siteNum = 0;

            if (!PrefC.GetBool(PrefName.EasyHidePublicHealth) && comboSite.SelectedIndex != 0)
            {
                siteNum = SiteC.List[comboSite.SelectedIndex - 1].SiteNum;
            }
            long clinicNum = 0;

            if (comboClinic.SelectedIndex > 0)
            {
                clinicNum = Clinics.List[comboClinic.SelectedIndex - 1].ClinicNum;
            }
            bool showBrokenAppts;

            showBrokenAppts = checkBrokenAppts.Checked;
            ListUn          = Appointments.RefreshUnsched(order, provNum, siteNum, showBrokenAppts, clinicNum);
            int scrollVal = grid.ScrollValue;

            grid.BeginUpdate();
            grid.Columns.Clear();
            ODGridColumn col = new ODGridColumn(Lan.g("TableUnsched", "Patient"), 140);

            grid.Columns.Add(col);
            col = new ODGridColumn(Lan.g("TableUnsched", "Date"), 65);
            grid.Columns.Add(col);
            col = new ODGridColumn(Lan.g("TableUnsched", "Status"), 110);
            grid.Columns.Add(col);
            col = new ODGridColumn(Lan.g("TableUnsched", "Prov"), 50);
            grid.Columns.Add(col);
            col = new ODGridColumn(Lan.g("TableUnsched", "Procedures"), 150);
            grid.Columns.Add(col);
            col = new ODGridColumn(Lan.g("TableUnsched", "Notes"), 200);
            grid.Columns.Add(col);
            grid.Rows.Clear();
            ODGridRow row;

            for (int i = 0; i < ListUn.Length; i++)
            {
                row = new ODGridRow();
                row.Cells.Add(patientNames[ListUn[i].PatNum]);
                if (ListUn[i].AptDateTime.Year < 1880)
                {
                    row.Cells.Add("");
                }
                else
                {
                    row.Cells.Add(ListUn[i].AptDateTime.ToShortDateString());
                }
                row.Cells.Add(DefC.GetName(DefCat.RecallUnschedStatus, ListUn[i].UnschedStatus));
                row.Cells.Add(Providers.GetAbbr(ListUn[i].ProvNum));
                row.Cells.Add(ListUn[i].ProcDescript);
                row.Cells.Add(ListUn[i].Note);
                grid.Rows.Add(row);
            }
            grid.EndUpdate();
            grid.ScrollValue = scrollVal;
            Cursor           = Cursors.Default;
        }
Ejemplo n.º 14
0
        ///<summary>Surround with try catch.  The "data" is the previously constructed xml.  If the internet connection is lost or unavailable, then the exception thrown will be a 404 error similar to the following: "The remote server returned an error: (404) Not Found"</summary>
        public static void Send(string data, long clinicNum)
        {
            //Validate the structure of the XML before sending.
            StringReader sr = new StringReader(data);

            try {
                XmlReader xmlr = XmlReader.Create(sr);
                while (xmlr.Read())                  //Read every node an ensure that there are no exceptions thrown.
                {
                }
            }
            catch (Exception ex) {
                throw new ApplicationException("Invalid XML in statement batch: " + ex.Message);
            }
            finally {
                sr.Dispose();
            }
            string strHistoryFile = "";

            if (PrefC.GetBool(PrefName.BillingElectSaveHistory))
            {
                string strHistoryDir = CodeBase.ODFileUtils.CombinePaths(ImageStore.GetPreferredAtoZpath(), "EHG_History");
                if (!Directory.Exists(strHistoryDir))
                {
                    Directory.CreateDirectory(strHistoryDir);
                }
                strHistoryFile = CodeBase.ODFileUtils.CreateRandomFile(strHistoryDir, ".txt");
                File.WriteAllText(strHistoryFile, data);
            }
            //Step 1: Post authentication request:
            Version        myVersion = new Version(Application.ProductVersion);
            HttpWebRequest webReq;
            WebResponse    response;
            StreamReader   readStream;
            string         str;

            string[] responseParams;
            string   status             = "";
            string   group              = "";
            string   userid             = "";
            string   authid             = "";
            string   errormsg           = "";
            string   alertmsg           = "";
            string   curParam           = "";
            string   serverName         = "https://claimconnect.dentalxchange.com/dci/upload.svl";//live URL for claims (According to phone call with Dentalxchange)
            string   serverNameOverride = PrefC.GetString(PrefName.BillingElectStmtUploadURL);

            if (!string.IsNullOrEmpty(serverNameOverride))
            {
                serverName = serverNameOverride;
            }
#if DEBUG
            //serverName="https://prelive.dentalxchange.com/dci/upload.svl";      //test URL for claims
            //serverName="https://claimconnect.dentalxchange.com/dci/upload.svl"; //live URL for claims
            //serverName="https://prelive.dentalxchange.com/dci/upload.svl";      //test URL for Stmts
            //serverName="https://billconnect.dentalxchange.com/dci/upload.svl";  //live URL for Stmts; probably the correct one to use.
#endif
            webReq = (HttpWebRequest)WebRequest.Create(serverName);
            Ebill  ebillDefault    = Ebills.GetForClinic(0);
            string billingUserName = ebillDefault.ElectUserName;
            string billingPassword = ebillDefault.ElectPassword;
            if (PrefC.HasClinicsEnabled && clinicNum != 0)
            {
                Ebill eBill = Ebills.GetForClinic(clinicNum);
                if (eBill != null)               //eBill entry exists, check the fields for overrides.
                {
                    if (eBill.ElectUserName != "")
                    {
                        billingUserName = eBill.ElectUserName;
                    }
                    if (eBill.ElectPassword != "")
                    {
                        billingPassword = eBill.ElectPassword;
                    }
                }
            }
            string postData =
                "Function=Auth"                                                                                                          //CONSTANT; signifies that this is an authentication request
                + "&Source=STM"                                                                                                          //CONSTANT; file format
                + "&UploaderName=OpenDental"                                                                                             //CONSTANT
                + "&UploaderVersion=" + myVersion.Major.ToString() + "." + myVersion.Minor.ToString() + "." + myVersion.Build.ToString() //eg 12.3.24
                + "&Username="******"&Password="******"POST";
            webReq.ContentType   = "application/x-www-form-urlencoded";
            webReq.ContentLength = postData.Length;
            ASCIIEncoding encoding  = new ASCIIEncoding();
            byte[]        bytes     = encoding.GetBytes(postData);
            Stream        streamOut = webReq.GetRequestStream();
            streamOut.Write(bytes, 0, bytes.Length);
            streamOut.Close();
            response = webReq.GetResponse();
            //Process the authentication response:
            readStream = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
            str        = readStream.ReadToEnd();
            readStream.Close();
            if (strHistoryFile != "")           //Tack the response onto the end of the saved history file if one was created above.
            {
                File.AppendAllText(strHistoryFile, "\r\n\r\nCONNECTION REQUEST: postData.Length=" + postData.Length + " bytes.Length=" + bytes.Length + "==============\r\n"
                                   + " RESPONSE TO CONNECTION REQUEST================================================================\r\n" + str);
            }
            //Debug.WriteLine(str);
            //MessageBox.Show(str);
            responseParams = str.Split('&');
            for (int i = 0; i < responseParams.Length; i++)
            {
                curParam = GetParam(responseParams[i]);
                switch (curParam)
                {
                case "Status":
                    status = GetParamValue(responseParams[i]);
                    break;

                case "GROUP":
                    group = GetParamValue(responseParams[i]);
                    break;

                case "UserID":
                    userid = GetParamValue(responseParams[i]);
                    break;

                case "AuthenticationID":
                    authid = GetParamValue(responseParams[i]);
                    break;

                case "ErrorMessage":
                    errormsg = GetParamValue(responseParams[i]);
                    break;

                case "AlertMessage":
                    alertmsg = GetParamValue(responseParams[i]);
                    break;

                default:
                    throw new Exception("Unexpected parameter: " + curParam);
                }
            }
            //Process response for errors:
            if (alertmsg != "")
            {
                MessageBox.Show(alertmsg);
            }
            switch (status)
            {
            case "0":
                //MessageBox.Show("Authentication successful.");
                break;

            case "1":
                throw new Exception("Authentication failed. " + errormsg);

            case "2":
                throw new Exception("Cannot authenticate at this time. " + errormsg);

            case "3":
                throw new Exception("Invalid authentication request. " + errormsg);

            case "4":
                throw new Exception("Invalid program version. " + errormsg);

            case "5":
                throw new Exception("No customer contract. " + errormsg);

            default:                    //some as-yet-undefined error
                throw new Exception("Error " + status + ". " + errormsg);
            }
            //Step 2: Post upload request:
            //string fileName=Directory.GetFiles(clearhouse.ExportPath)[0];
            string boundary = "------------7d13e425b00d0";
            postData =
                "--" + boundary + "\r\n"
                + "Content-Disposition: form-data; name=\"Function\"\r\n"
                + "\r\n"
                + "Upload\r\n"
                + "--" + boundary + "\r\n"
                + "Content-Disposition: form-data; name=\"Source\"\r\n"
                + "\r\n"
                + "STM\r\n"
                + "--" + boundary + "\r\n"
                + "Content-Disposition: form-data; name=\"AuthenticationID\"\r\n"
                + "\r\n"
                + authid + "\r\n"
                + "--" + boundary + "\r\n"
                + "Content-Disposition: form-data; name=\"File\"; filename=\"" + "stmt.xml" + "\"\r\n"
                + "Content-Type: text/plain\r\n"
                + "\r\n"
                //using(StreamReader sr=new StreamReader(fileName)) {
                //	postData+=sr.ReadToEnd()+"\r\n"
                + data + "\r\n"
                + "--" + boundary + "--";
            //}
            //Debug.WriteLine(postData);
            //MessageBox.Show(postData);
            webReq = (HttpWebRequest)WebRequest.Create(serverName);
            //Timeout documentation: https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.timeout(v=vs.110).aspx.
            //Timeout: "Gets or sets the time-out value in milliseconds for the GetResponse and GetRequestStream methods."
            //Timeout default is 100 seconds, which should be sufficient in waiting for a reply from dentalxchange, since the reply is small.
            //ReadWriteTimeout documentation: https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.readwritetimeout%28v=vs.110%29.aspx
            //ReadWriteTimeout: "Gets or sets a time-out in milliseconds when writing to or reading from a stream."
            //ReadWriteTimeout default is 300 seconds (5 minutes).
            //Our message box that tells the user to wait up to 10 minutes for bills to send, therefore we need at least a 10 minute ReadWriteTimeout.
            //The user sees progress in the UI when sending.  We can increase timeouts as much as we want without making the program look like it crashed.
            webReq.ReadWriteTimeout = 600000;          //10 minutes = 10*60 seconds = 600 seconds = 600*1000 milliseconds = 600,000 milliseconds.
            webReq.KeepAlive        = false;
            webReq.Method           = "POST";
            webReq.ContentType      = "multipart/form-data; boundary=" + boundary;
            webReq.ContentLength    = postData.Length;
            bytes     = encoding.GetBytes(postData);
            streamOut = webReq.GetRequestStream();
            streamOut.Write(bytes, 0, bytes.Length);
            streamOut.Close();
            response = webReq.GetResponse();
            //Process the response
            readStream = new StreamReader(response.GetResponseStream(), Encoding.ASCII);
            str        = readStream.ReadToEnd();
            readStream.Close();
            if (strHistoryFile != "")           //Tack the response onto the end of the saved history file if one was created above.
            {
                File.AppendAllText(strHistoryFile, "\r\n\r\nUPLOAD REQUEST: postData.Length=" + postData.Length + " bytes.Length=" + bytes.Length + "==============\r\n"
                                   + " RESPONSE TO DATA UPLOAD================================================================\r\n" + str);
            }
            errormsg = "";
            status   = "";
            str      = str.Replace("\r\n", "");
            //Debug.Write(str);
            if (str.Length > 300)
            {
                throw new Exception("Unknown lengthy error message received.");
            }
            responseParams = str.Split('&');
            for (int i = 0; i < responseParams.Length; i++)
            {
                curParam = GetParam(responseParams[i]);
                switch (curParam)
                {
                case "Status":
                    status = GetParamValue(responseParams[i]);
                    break;

                case "Error Message":
                case "ErrorMessage":
                    errormsg = GetParamValue(responseParams[i]);
                    break;

                case "Filename":
                case "Timestamp":
                    break;

                case "":                        //errorMessage blank
                    break;

                default:
                    throw new Exception(str);                            //"Unexpected parameter: "+str);//curParam+"*");
                }
            }
            switch (status)
            {
            case "0":
                //MessageBox.Show("Upload successful.");
                break;

            case "1":
                throw new Exception("Authentication failed. " + errormsg);

            case "2":
                throw new Exception("Cannot upload at this time. " + errormsg);
            }
        }
Ejemplo n.º 15
0
        private void butNote_Click(object sender, EventArgs e)
        {
            if (!Security.IsAuthorized(Permissions.AppointmentCreate))
            {
                return;
            }
            if (PatRestrictionL.IsRestricted(_patCur.PatNum, PatRestrict.ApptSchedule))
            {
                return;
            }
            Appointment aptCur = new Appointment();

            aptCur.PatNum = _patCur.PatNum;
            if (_patCur.DateFirstVisit.Year < 1880 &&
                !Procedures.AreAnyComplete(_patCur.PatNum))                   //this only runs if firstVisit blank
            {
                aptCur.IsNewPatient = true;
            }
            aptCur.Pattern = "/X/";
            if (_patCur.PriProv == 0)
            {
                aptCur.ProvNum = PrefC.GetLong(PrefName.PracticeDefaultProv);
            }
            else
            {
                aptCur.ProvNum = _patCur.PriProv;
            }
            aptCur.ProvHyg    = _patCur.SecProv;
            aptCur.AptStatus  = ApptStatus.PtNote;
            aptCur.ClinicNum  = _patCur.ClinicNum;
            aptCur.TimeLocked = PrefC.GetBool(PrefName.AppointmentTimeIsLocked);
            if (IsInitialDoubleClick)             //initially double clicked on appt module
            {
                aptCur.AptDateTime = DateTimeClicked;
                aptCur.Op          = OpNumClicked;
            }
            else
            {
                //new appt will be placed on pinboard instead of specific time
            }
            try {
                if (!AppointmentL.IsSpecialtyMismatchAllowed(_patCur.PatNum, aptCur.ClinicNum))
                {
                    return;
                }
                Appointments.Insert(aptCur);
            }
            catch (ApplicationException ex) {
                MessageBox.Show(ex.Message);
                return;
            }
            FormApptEdit formApptEdit = new FormApptEdit(aptCur.AptNum);

            formApptEdit.IsNew = true;
            formApptEdit.ShowDialog();
            if (formApptEdit.DialogResult != DialogResult.OK)
            {
                return;
            }
            ListAptNumsSelected.Add(aptCur.AptNum);
            if (IsInitialDoubleClick)
            {
                _otherResult = OtherResult.CreateNew;
            }
            else
            {
                _otherResult = OtherResult.NewToPinBoard;
            }
            DialogResult = DialogResult.OK;
        }
Ejemplo n.º 16
0
 private void FormUserEdit_Load(object sender, System.EventArgs e)
 {
     checkIsHidden.Checked = UserCur.IsHidden;
     textUserName.Text     = UserCur.UserName;
     for (int i = 0; i < UserGroups.List.Length; i++)
     {
         listUserGroup.Items.Add(UserGroups.List[i].Description);
         if (UserCur.UserGroupNum == UserGroups.List[i].UserGroupNum)
         {
             listUserGroup.SelectedIndex = i;
         }
     }
     if (listUserGroup.SelectedIndex == -1)          //never allowed to delete last group, so this won't fail
     {
         listUserGroup.SelectedIndex = 0;
     }
     listEmployee.Items.Clear();
     listEmployee.Items.Add(Lan.g(this, "none"));
     listEmployee.SelectedIndex = 0;
     for (int i = 0; i < Employees.ListShort.Length; i++)
     {
         listEmployee.Items.Add(Employees.GetNameFL(Employees.ListShort[i]));
         if (UserCur.EmployeeNum == Employees.ListShort[i].EmployeeNum)
         {
             listEmployee.SelectedIndex = i + 1;
         }
     }
     listProv.Items.Clear();
     listProv.Items.Add(Lan.g(this, "none"));
     listProv.SelectedIndex = 0;
     for (int i = 0; i < ProviderC.ListShort.Count; i++)
     {
         listProv.Items.Add(ProviderC.ListShort[i].GetLongDesc());
         if (UserCur.ProvNum == ProviderC.ListShort[i].ProvNum)
         {
             listProv.SelectedIndex = i + 1;
         }
     }
     if (PrefC.GetBool(PrefName.EasyNoClinics))
     {
         labelClinic.Visible             = false;
         listClinic.Visible              = false;
         checkClinicIsRestricted.Visible = false;
     }
     else
     {
         listClinic.Items.Clear();
         listClinic.Items.Add(Lan.g(this, "all"));
         listClinic.SelectedIndex = 0;
         for (int i = 0; i < Clinics.List.Length; i++)
         {
             listClinic.Items.Add(Clinics.List[i].Description);
             if (UserCur.ClinicNum == Clinics.List[i].ClinicNum)
             {
                 listClinic.SelectedIndex = i + 1;
             }
         }
         checkClinicIsRestricted.Checked = UserCur.ClinicIsRestricted;
     }
     if (UserCur.Password == "")
     {
         butPassword.Text = Lan.g(this, "Create Password");
     }
 }
Ejemplo n.º 17
0
        ///<summary>Fills grid based on values in _listEtrans.
        ///Set isRefreshNeeded to true when we need to reinitialize local dictionarys after in memory list is also updated. Required true for first time running.
        ///Also allows you to passed in predetermined filter options.</summary>
        private void FillGrid(bool isRefreshNeeded, List <string> listSelectedStatuses, List <long> listSelectedClinicNums,
                              string carrierName, string checkTraceNum, string amountMin, string amountMax, string controlId)
        {
            Cursor = Cursors.WaitCursor;
            labelControlId.Visible = PrefC.GetBool(PrefName.EraShowControlIdFilter);
            textControlId.Visible  = PrefC.GetBool(PrefName.EraShowControlIdFilter);
            Action actionCloseProgress = null;

            if (isRefreshNeeded)
            {
                actionCloseProgress = ODProgress.Show(ODEventType.Etrans, typeof(EtransEvent), Lan.g(this, "Gathering data") + "...");
                _dictEtrans835s.Clear();
                _dictEtransClaims.Clear();
                List <Etrans835Attach>    listAttached        = Etrans835Attaches.GetForEtrans(_listAllEtrans.Select(x => x.EtransNum).ToArray());
                Dictionary <long, string> dictEtransMessages  = new Dictionary <long, string>();
                List <X12ClaimMatch>      list835ClaimMatches = new List <X12ClaimMatch>();
                Dictionary <long, int>    dictClaimMatchCount = new Dictionary <long, int>(); //1:1 with _listEtranss. Stores how many claim matches each 835 has.
                int batchQueryInterval = 500;                                                 //Every 500 rows we get the next 500 message texts to save memory.
                int rowCur             = 0;
                foreach (Etrans etrans in _listAllEtrans)
                {
                    if (rowCur % batchQueryInterval == 0)
                    {
                        int range = Math.Min(batchQueryInterval, _listAllEtrans.Count - rowCur);                   //Either the full batchQueryInterval amount or the remaining amount of etrans.
                        dictEtransMessages = EtransMessageTexts.GetMessageTexts(_listAllEtrans.GetRange(rowCur, range).Select(x => x.EtransMessageTextNum).ToList(), false);
                    }
                    rowCur++;
                    EtransEvent.Fire(ODEventType.Etrans, Lan.g(this, "Processing 835: ") + ": " + rowCur + " out of " + _listAllEtrans.Count);
                    List <Etrans835Attach> listAttachedTo835 = listAttached.FindAll(x => x.EtransNum == etrans.EtransNum);
                    X835 x835 = new X835(etrans, dictEtransMessages[etrans.EtransMessageTextNum], etrans.TranSetId835, listAttachedTo835, true);
                    _dictEtrans835s.Add(etrans.EtransNum, x835);
                    List <X12ClaimMatch> listClaimMatches = x835.GetClaimMatches();
                    dictClaimMatchCount.Add(etrans.EtransNum, listClaimMatches.Count);
                    list835ClaimMatches.AddRange(listClaimMatches);
                }
                #region Set 835 unattached in batch and build _dictEtransClaims and _dictClaimPayCheckNums.
                EtransEvent.Fire(ODEventType.Etrans, Lan.g(this, "Gathering internal claim matches."));
                List <long> listClaimNums = Claims.GetClaimFromX12(list835ClaimMatches);             //Can return null.
                EtransEvent.Fire(ODEventType.Etrans, Lan.g(this, "Building data sets."));
                int         claimIndexCur        = 0;
                List <long> listMatchedClaimNums = new List <long>();
                foreach (Etrans etrans in _listAllEtrans)
                {
                    X835 x835 = _dictEtrans835s[etrans.EtransNum];
                    if (listClaimNums != null)
                    {
                        x835.SetClaimNumsForUnattached(listClaimNums.GetRange(claimIndexCur, dictClaimMatchCount[etrans.EtransNum]));
                    }
                    claimIndexCur += dictClaimMatchCount[etrans.EtransNum];
                    listMatchedClaimNums.AddRange(x835.ListClaimsPaid.FindAll(x => x.ClaimNum != 0).Select(x => x.ClaimNum).ToList());
                }
                List <Claim> listClaims = Claims.GetClaimsFromClaimNums(listMatchedClaimNums.Distinct().ToList());
                //The following line includes manually detached and split attaches.
                _listAllAttaches   = Etrans835Attaches.GetForEtransNumOrClaimNums(false, _listAllEtrans.Select(x => x.EtransNum).ToList(), listMatchedClaimNums.ToArray());
                _listAllClaimProcs = ClaimProcs.RefreshForClaims(listMatchedClaimNums);
                foreach (Etrans etrans in _listAllEtrans)
                {
                    X835 x835 = _dictEtrans835s[etrans.EtransNum];
                    #region _dictEtransClaims, _dictClaimPayCheckNums
                    _dictEtransClaims.Add(etrans.EtransNum, new List <Claim>());
                    List <long>  listSubClaimNums = x835.ListClaimsPaid.FindAll(x => x.ClaimNum != 0).Select(y => y.ClaimNum).ToList();
                    List <Claim> listClaimsFor835 = listClaims.FindAll(x => listSubClaimNums.Contains(x.ClaimNum));
                    foreach (Hx835_Claim claim in x835.ListClaimsPaid)
                    {
                        Claim claimCur = listClaimsFor835.FirstOrDefault(x => x.ClaimNum == claim.ClaimNum);                    //Can be null.
                        _dictEtransClaims[etrans.EtransNum].Add(claimCur);
                    }
                    #endregion
                }
                EtransEvent.Fire(ODEventType.Etrans, Lan.g(this, "Filling Grid."));
                #endregion
            }
            gridMain.BeginUpdate();
            #region Initilize columns
            gridMain.ListGridColumns.Clear();
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableEtrans835s", "Patient Name"), 250));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableEtrans835s", "Carrier Name"), 190));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableEtrans835s", "Status"), 80));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableEtrans835s", "Date"), 80, GridSortingStrategy.DateParse));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableEtrans835s", "Amount"), 80, GridSortingStrategy.AmountParse));
            if (PrefC.HasClinicsEnabled)
            {
                gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableEtrans835s", "Clinic"), 70));
            }
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableEtrans835s", "Code"), 37, HorizontalAlignment.Center));
            if (PrefC.GetBool(PrefName.EraShowControlIdFilter))
            {
                gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableEtrans835s", "ControlID"), -1));
            }
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableEtrans835s", "Note"), -2));
            #endregion
            gridMain.ListGridRows.Clear();
            foreach (Etrans etrans in _listAllEtrans)
            {
                X835 x835 = _dictEtrans835s[etrans.EtransNum];
                #region Filter: Carrier Name
                if (carrierName != "" && !x835.PayerName.ToLower().Contains(carrierName.ToLower().Trim()))
                {
                    continue;
                }
                #endregion
                string status = GetStringStatus(etrans.EtransNum);
                #region Filter: Status
                if (!listSelectedStatuses.Contains(status.Replace("*", "")))                //The filter will ignore finalized with detached claims.
                {
                    continue;
                }
                #endregion
                //List of ClinicNums for the current etrans.ListClaimsPaid from the DB.
                List <long> listClinicNums = _dictEtransClaims[etrans.EtransNum].Select(x => x == null? 0 :x.ClinicNum).Distinct().ToList();
                #region Filter: Clinics
                if (PrefC.HasClinicsEnabled && !listClinicNums.Exists(x => listSelectedClinicNums.Contains(x)))
                {
                    continue;                    //The ClinicNums associated to the 835 do not match any of the selected ClinicNums, so nothing to show in this 835.
                }
                #endregion
                #region Filter: Check and Trace Value
                if (checkTraceNum != "" && !x835.TransRefNum.ToLower().Contains(checkTraceNum.ToLower().Trim()))               //Trace Number does not match
                {
                    continue;
                }
                #endregion
                #region Filter: Insurance Check Range Min and Max
                if (amountMin != "" && x835.InsPaid < PIn.Decimal(amountMin) || amountMax != "" && x835.InsPaid > PIn.Decimal(amountMax))
                {
                    continue;                    //Either the InsPaid is below or above our range.
                }
                #endregion
                #region Filter: ControlID
                if (controlId != "" && !x835.ControlId.ToLower().Contains(controlId.ToLower()))
                {
                    continue;
                }
                #endregion
                GridRow row = new GridRow();
                #region Column: Patient Name
                List <string> listPatNames = x835.ListClaimsPaid.Select(x => x.PatientName.ToString()).Distinct().ToList();
                string        patName      = (listPatNames.Count > 0 ? listPatNames[0] : "");
                if (listPatNames.Count > 1)
                {
                    patName = "(" + POut.Long(listPatNames.Count) + ")";
                }
                row.Cells.Add(patName);
                #endregion
                row.Cells.Add(x835.PayerName);
                row.Cells.Add(status);                //See GetStringStatus(...) for possible values.
                row.Cells.Add(POut.Date(etrans.DateTimeTrans));
                row.Cells.Add(POut.Decimal(x835.InsPaid));
                #region Column: Clinic
                if (PrefC.HasClinicsEnabled)
                {
                    string clinicAbbr = "";
                    if (listClinicNums.Count == 1)
                    {
                        if (listClinicNums[0] == 0)
                        {
                            clinicAbbr = Lan.g(this, "Unassigned");
                        }
                        else
                        {
                            clinicAbbr = Clinics.GetAbbr(listClinicNums[0]);
                        }
                    }
                    else if (listClinicNums.Count > 1)
                    {
                        clinicAbbr = "(" + Lan.g(this, "Multiple") + ")";
                    }
                    row.Cells.Add(clinicAbbr);
                }
                #endregion
                row.Cells.Add(x835._paymentMethodCode);
                if (PrefC.GetBool(PrefName.EraShowControlIdFilter))
                {
                    row.Cells.Add(x835.ControlId);
                }
                row.Cells.Add(etrans.Note);
                row.Tag = etrans;
                gridMain.ListGridRows.Add(row);
            }
            gridMain.EndUpdate();
            actionCloseProgress?.Invoke();            //When this function executes quickly this can fail rarely, fail silently because of WaitCursor.
            Cursor = Cursors.Default;
        }
Ejemplo n.º 18
0
        /*private void butDelete_Click(object sender, System.EventArgs e) {
         *      if(IsNew){
         *              DialogResult=DialogResult.Cancel;
         *              return;
         *      }
         *      try{
         *              UserCur.Delete();
         *      }
         *      catch(Exception ex){
         *              MessageBox.Show(ex.Message);
         *              return;
         *      }
         *      DialogResult=DialogResult.OK;
         * }*/

        private void butOK_Click(object sender, System.EventArgs e)
        {
            if (textUserName.Text == "")
            {
                MsgBox.Show(this, "Please enter a username.");
                return;
            }
            if (listEmployee.SelectedIndex > 0 && listProv.SelectedIndex > 0)
            {
                MsgBox.Show(this, "Cannot set an employee and a provider for the same user.");
                return;
            }
            UserCur.IsHidden     = checkIsHidden.Checked;
            UserCur.UserName     = textUserName.Text;
            UserCur.UserGroupNum = UserGroups.List[listUserGroup.SelectedIndex].UserGroupNum;
            if (listEmployee.SelectedIndex == 0)
            {
                UserCur.EmployeeNum = 0;
            }
            else
            {
                UserCur.EmployeeNum = Employees.ListShort[listEmployee.SelectedIndex - 1].EmployeeNum;
            }
            if (listProv.SelectedIndex == 0)
            {
                UserCur.ProvNum = 0;
            }
            else
            {
                UserCur.ProvNum = ProviderC.ListShort[listProv.SelectedIndex - 1].ProvNum;
            }
            if (PrefC.GetBool(PrefName.EasyNoClinics))
            {
                UserCur.ClinicNum          = 0;
                UserCur.ClinicIsRestricted = false;
            }
            else
            {
                if (listClinic.SelectedIndex == 0)
                {
                    UserCur.ClinicNum = 0;
                }
                else
                {
                    UserCur.ClinicNum = Clinics.List[listClinic.SelectedIndex - 1].ClinicNum;
                }
                UserCur.ClinicIsRestricted = checkClinicIsRestricted.Checked;
            }
            try{
                if (IsNew)
                {
                    Userods.Insert(UserCur);
                }
                else
                {
                    Userods.Update(UserCur);
                }
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
                return;
            }
            DialogResult = DialogResult.OK;
        }
Ejemplo n.º 19
0
 public void SetAllowDigitalSig(bool allowDigitalSig)
 {
     butESign.Visible = allowDigitalSig && PrefC.GetBool(PrefName.SignatureAllowDigital);
 }
Ejemplo n.º 20
0
        ///<summary>Adds the xml for one statement.</summary>
        public static void GenerateOneStatement(XmlWriter writer, Statement stmt, Patient pat, Family fam, DataSet dataSet)
        {
            Patient guar = fam.ListPats[0];

            writer.WriteStartElement("Statement");
            //writer.WriteAttributeString("CreditCardChoice",PrefC.GetString(PrefName.BillingElectCreditCardChoices"));
            //remit address----------------------------------------------------------
            writer.WriteStartElement("RemitAddress");
            if (!PrefC.GetBool(PrefName.EasyNoClinics) && Clinics.List.Length > 0 &&       //if using clinics
                Clinics.GetClinic(guar.ClinicNum) != null)                 //and this guar is assigned to a clinic
            {
                Clinic clinic = Clinics.GetClinic(guar.ClinicNum);
                writer.WriteElementString("Name", clinic.Description);
                writer.WriteElementString("Address", clinic.Address);
                writer.WriteElementString("Address2", clinic.Address2);
                writer.WriteElementString("City", clinic.City);
                writer.WriteElementString("State", clinic.State);
                writer.WriteElementString("Zip", clinic.Zip);
                string phone = "";
                if (clinic.Phone.Length == 10)
                {
                    phone = "(" + clinic.Phone.Substring(0, 3) + ")" + clinic.Phone.Substring(3, 3) + "-" + clinic.Phone.Substring(6);
                }
                writer.WriteElementString("Phone", phone);
            }
            else             //not using clinics
            {
                writer.WriteElementString("Name", PrefC.GetString(PrefName.PracticeTitle));
                writer.WriteElementString("Address", PrefC.GetString(PrefName.PracticeAddress));
                writer.WriteElementString("Address2", PrefC.GetString(PrefName.PracticeAddress2));
                writer.WriteElementString("City", PrefC.GetString(PrefName.PracticeCity));
                writer.WriteElementString("State", PrefC.GetString(PrefName.PracticeST));
                writer.WriteElementString("Zip", PrefC.GetString(PrefName.PracticeZip));
                writer.WriteElementString("Phone", PrefC.GetString(PrefName.PracticePhone));
            }
            writer.WriteEndElement();            //RemitAddress
            //Patient-------------------------------------------------------------------------------
            writer.WriteStartElement("Patient");
            writer.WriteElementString("Name", guar.GetNameFLFormal());
            writer.WriteElementString("AccountNum", guar.PatNum.ToString());
            writer.WriteElementString("Address", guar.Address);
            writer.WriteElementString("Address2", guar.Address2);
            writer.WriteElementString("City", guar.City);
            writer.WriteElementString("State", guar.State);
            writer.WriteElementString("Zip", guar.Zip);
            writer.WriteEndElement();            //Patient
            //Account summary-----------------------------------------------------------------------
            writer.WriteStartElement("AccountSummary");
            if (PrefC.GetLong(PrefName.StatementsCalcDueDate) == -1)
            {
                writer.WriteElementString("DueDate", Lan.g("FormRpStatement", "Upon Receipt"));
            }
            else
            {
                DateTime dueDate = DateTime.Today.AddDays(PrefC.GetLong(PrefName.StatementsCalcDueDate));
                writer.WriteElementString("DueDate", dueDate.ToString("MM/dd/yyyy"));
            }
            writer.WriteElementString("StatementDate", stmt.DateSent.ToString("MM/dd/yyyy"));
            DataTable tableAccount = null;

            for (int i = 0; i < dataSet.Tables.Count; i++)
            {
                if (dataSet.Tables[i].TableName.StartsWith("account"))
                {
                    tableAccount = dataSet.Tables[i];
                }
            }
            //on a regular printed statement, the amount due at the top might be different from the balance at the middle right.
            //This is because of payment plan balances.
            //But in e-bills, there is only one amount due.
            //Insurance estimate is already subtracted, and payment plan balance is already added.
            double amountDue = guar.BalTotal;

            //add payplan due amt:
            for (int m = 0; m < dataSet.Tables["misc"].Rows.Count; m++)
            {
                if (dataSet.Tables["misc"].Rows[m]["descript"].ToString() == "payPlanDue")
                {
                    amountDue += PIn.Double(dataSet.Tables["misc"].Rows[m]["value"].ToString());
                }
            }
            if (PrefC.GetBool(PrefName.BalancesDontSubtractIns))
            {
                writer.WriteElementString("EstInsPayments", "");                         //optional.
            }
            else                                                                         //this is typical
            {
                writer.WriteElementString("EstInsPayments", guar.InsEst.ToString("F2")); //optional.
                amountDue -= guar.InsEst;
            }
            InstallmentPlan installPlan = InstallmentPlans.GetOneForFam(guar.PatNum);

            if (installPlan != null)
            {
                //show lesser of normal total balance or the monthly payment amount.
                if (installPlan.MonthlyPayment < amountDue)
                {
                    amountDue = installPlan.MonthlyPayment;
                }
            }
            writer.WriteElementString("AmountDue", amountDue.ToString("F2"));
            writer.WriteElementString("Bal_0_30", guar.Bal_0_30.ToString("F2"));
            writer.WriteElementString("Bal_31_60", guar.Bal_31_60.ToString("F2"));
            writer.WriteElementString("Bal_61_90", guar.Bal_61_90.ToString("F2"));
            writer.WriteElementString("BalOver90", guar.BalOver90.ToString("F2"));
            writer.WriteEndElement();            //AccountSummary
            //Notes-----------------------------------------------------------------------------------
            writer.WriteStartElement("Notes");
            if (stmt.NoteBold != "")
            {
                writer.WriteStartElement("Note");
                writer.WriteAttributeString("FgColor", ColorToHexString(Color.DarkRed));
                writer.WriteCData(stmt.NoteBold);
                writer.WriteEndElement();                //Note
            }
            if (stmt.Note != "")
            {
                writer.WriteStartElement("Note");
                writer.WriteAttributeString("FgColor", ColorToHexString(Color.Black));
                writer.WriteCData(stmt.Note);
                writer.WriteEndElement();        //Note
            }
            writer.WriteEndElement();            //Notes
            //Detail items------------------------------------------------------------------------------
            writer.WriteStartElement("DetailItems");
            string descript;
            string fulldesc;
            string procCode;
            string tth;

            string[]      lineArray;
            List <string> lines;
            DateTime      date;
            int           seq = 0;

            for (int i = 0; i < tableAccount.Rows.Count; i++)
            {
                procCode  = tableAccount.Rows[i]["ProcCode"].ToString();
                tth       = tableAccount.Rows[i]["tth"].ToString();
                descript  = tableAccount.Rows[i]["description"].ToString();
                fulldesc  = procCode + " " + tth + " " + descript;
                lineArray = fulldesc.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                lines     = new List <string>(lineArray);
                //We assume that the line limit is 40 char.
                if (lines[0].Length > 40)
                {
                    string newline = lines[0].Substring(40);
                    lines[0] = lines[0].Substring(0, 40);       //first half
                    lines.Insert(1, newline);                   //second half
                }
                for (int li = 0; li < lines.Count; li++)
                {
                    writer.WriteStartElement("Item");
                    writer.WriteAttributeString("sequence", seq.ToString());
                    if (li == 0)
                    {
                        date = (DateTime)tableAccount.Rows[i]["DateTime"];
                        writer.WriteElementString("Date", date.ToString("MM/dd/yyyy"));
                        writer.WriteElementString("PatientName", tableAccount.Rows[i]["patient"].ToString());
                    }
                    else
                    {
                        writer.WriteElementString("Date", "");
                        writer.WriteElementString("PatientName", "");
                    }
                    writer.WriteElementString("Description", lines[li]);
                    if (li == 0)
                    {
                        writer.WriteElementString("Charges", tableAccount.Rows[i]["charges"].ToString());
                        writer.WriteElementString("Credits", tableAccount.Rows[i]["credits"].ToString());
                        writer.WriteElementString("Balance", tableAccount.Rows[i]["balance"].ToString());
                    }
                    else
                    {
                        writer.WriteElementString("Charges", "");
                        writer.WriteElementString("Credits", "");
                        writer.WriteElementString("Balance", "");
                    }
                    writer.WriteEndElement();                    //Item
                    seq++;
                }
            }
            writer.WriteEndElement();            //DetailItems
            writer.WriteEndElement();            //Statement
        }
Ejemplo n.º 21
0
 private void FormPractice_Load(object sender, System.EventArgs e)
 {
     checkIsMedicalOnly.Checked = PrefC.GetBool(PrefName.PracticeIsMedicalOnly);
     if (Programs.UsingEcwTightOrFullMode())
     {
         checkIsMedicalOnly.Visible = false;
     }
     textPracticeTitle.Text = PrefC.GetString(PrefName.PracticeTitle);
     textAddress.Text       = PrefC.GetString(PrefName.PracticeAddress);
     textAddress2.Text      = PrefC.GetString(PrefName.PracticeAddress2);
     textCity.Text          = PrefC.GetString(PrefName.PracticeCity);
     textST.Text            = PrefC.GetString(PrefName.PracticeST);
     textZip.Text           = PrefC.GetString(PrefName.PracticeZip);
     textPhone.Text         = TelephoneNumbers.ReFormat(PrefC.GetString(PrefName.PracticePhone));
     textFax.Text           = TelephoneNumbers.ReFormat(PrefC.GetString(PrefName.PracticeFax));
     checkUseBillingAddressOnClaims.Checked = PrefC.GetBool(PrefName.UseBillingAddressOnClaims);
     textBillingAddress.Text  = PrefC.GetString(PrefName.PracticeBillingAddress);
     textBillingAddress2.Text = PrefC.GetString(PrefName.PracticeBillingAddress2);
     textBillingCity.Text     = PrefC.GetString(PrefName.PracticeBillingCity);
     textBillingST.Text       = PrefC.GetString(PrefName.PracticeBillingST);
     textBillingZip.Text      = PrefC.GetString(PrefName.PracticeBillingZip);
     textPayToAddress.Text    = PrefC.GetString(PrefName.PracticePayToAddress);
     textPayToAddress2.Text   = PrefC.GetString(PrefName.PracticePayToAddress2);
     textPayToCity.Text       = PrefC.GetString(PrefName.PracticePayToCity);
     textPayToST.Text         = PrefC.GetString(PrefName.PracticePayToST);
     textPayToZip.Text        = PrefC.GetString(PrefName.PracticePayToZip);
     textBankNumber.Text      = PrefC.GetString(PrefName.PracticeBankNumber);
     if (CultureInfo.CurrentCulture.Name.EndsWith("CH"))             //CH is for switzerland. eg de-CH
     {
         textBankRouting.Text = PrefC.GetString(PrefName.BankRouting);
         textBankAddress.Text = PrefC.GetString(PrefName.BankAddress);
     }
     else
     {
         groupSwiss.Visible = false;
     }
     listProvider.Items.Clear();
     _listProviders = Providers.GetDeepCopy(true);
     for (int i = 0; i < _listProviders.Count; i++)
     {
         listProvider.Items.Add(_listProviders[i].GetLongDesc());
         if (_listProviders[i].ProvNum == PrefC.GetLong(PrefName.PracticeDefaultProv))
         {
             listProvider.SelectedIndex = i;
         }
     }
     listBillType.Items.Clear();
     _listBillingTypeDefs = Defs.GetDefsForCategory(DefCat.BillingTypes, true);
     for (int i = 0; i < _listBillingTypeDefs.Count; i++)
     {
         listBillType.Items.Add(_listBillingTypeDefs[i].ItemName);
         if (_listBillingTypeDefs[i].DefNum == PrefC.GetLong(PrefName.PracticeDefaultBillType))
         {
             listBillType.SelectedIndex = i;
         }
     }
     if (PrefC.GetBool(PrefName.EasyHidePublicHealth))
     {
         labelPlaceService.Visible = false;
         listPlaceService.Visible  = false;
     }
     listPlaceService.Items.Clear();
     for (int i = 0; i < Enum.GetNames(typeof(PlaceOfService)).Length; i++)
     {
         listPlaceService.Items.Add(Lan.g("enumPlaceOfService", Enum.GetNames(typeof(PlaceOfService))[i]));
     }
     listPlaceService.SelectedIndex = PrefC.GetInt(PrefName.DefaultProcedurePlaceService);
     _selectedBillingProvNum        = PrefC.GetLong(PrefName.InsBillingProv);
     _insBillingProvNum             = _selectedBillingProvNum;
     FillComboInsBillingProv();
 }
Ejemplo n.º 22
0
 private void FormEtrans834Preview_Load(object sender, EventArgs e)
 {
     checkDropExistingIns.Checked = PrefC.GetBool(PrefName.Ins834DropExistingPatPlans);
     checkIsPatientCreate.Checked = PrefC.GetBool(PrefName.Ins834IsPatientCreate);
     FillGridInsPlans();
 }
Ejemplo n.º 23
0
        private void FillEmps()
        {
            gridEmp.BeginUpdate();
            gridEmp.ListGridColumns.Clear();
            GridColumn col;

            col = new GridColumn(Lan.g("TableEmpClock", "Ext"), 25);
            gridEmp.ListGridColumns.Add(col);
            col = new GridColumn(Lan.g("TableEmpClock", "Employee"), 60);
            gridEmp.ListGridColumns.Add(col);
            col = new GridColumn(Lan.g("TableEmpClock", "Status"), 80);
            gridEmp.ListGridColumns.Add(col);
            col = new GridColumn(Lan.g("TableEmpClock", "Phone"), 50);
            gridEmp.ListGridColumns.Add(col);
            col = new GridColumn(Lan.g("TableEmpClock", "InOut"), 35);
            gridEmp.ListGridColumns.Add(col);
            col = new GridColumn(Lan.g("TableEmpClock", "Customer"), 90);
            gridEmp.ListGridColumns.Add(col);
            col = new GridColumn(Lan.g("TableEmpClock", "Time"), 70);
            gridEmp.ListGridColumns.Add(col);
            gridEmp.ListGridRows.Clear();
            UI.GridRow row;
            PhoneList = Phones.GetPhoneList();
            DateTime dateTimeStart;
            TimeSpan span;
            DateTime timeOfDay;            //because TimeSpan does not have good formatting.

            for (int i = 0; i < PhoneList.Count; i++)
            {
                row = new OpenDental.UI.GridRow();
                row.Cells.Add(PhoneList[i].Extension.ToString());
                row.Cells.Add(PhoneList[i].EmployeeName);
                if (PhoneList[i].ClockStatus == ClockStatusEnum.None)
                {
                    row.Cells.Add("");
                }
                else if (!PrefC.GetBool(PrefName.ClockEventAllowBreak) && PhoneList[i].ClockStatus == ClockStatusEnum.Lunch)
                {
                    row.Cells.Add(ClockStatusEnum.Break.GetDescription());                    //Breaks turned off, Lunch is now "Break", but maintains Lunch functionality.
                }
                else
                {
                    row.Cells.Add(PhoneList[i].ClockStatus.ToString());
                }
                row.Cells.Add(PhoneList[i].Description);
                row.Cells.Add(PhoneList[i].InOrOut);
                row.Cells.Add(PhoneList[i].CustomerNumber);
                dateTimeStart = PhoneList[i].DateTimeStart;
                if (dateTimeStart.Date == DateTime.Today)
                {
                    span      = DateTime.Now - dateTimeStart + timeDelta;
                    timeOfDay = DateTime.Today + span;
                    row.Cells.Add(timeOfDay.ToString("H:mm:ss"));
                }
                else
                {
                    row.Cells.Add("");
                }
                row.ColorBackG = PhoneList[i].ColorBar;
                row.ColorText  = PhoneList[i].ColorText;
                gridEmp.ListGridRows.Add(row);
            }
            gridEmp.EndUpdate();
            gridEmp.SetSelected(false);
        }
Ejemplo n.º 24
0
        private void butOK_Click(object sender, System.EventArgs e)
        {
            if (!checkAllProv.Checked && listProv.SelectedIndices.Count == 0)
            {
                MsgBox.Show(this, "At least one provider must be selected.");
                return;
            }
            if (!PrefC.GetBool(PrefName.EasyNoClinics))
            {
                if (!checkAllClin.Checked && listClin.SelectedIndices.Count == 0)
                {
                    MsgBox.Show(this, "At least one clinic must be selected.");
                    return;
                }
            }
            if (!checkAllTypes.Checked && listTypes.SelectedIndices.Count == 0 && !checkIns.Checked)
            {
                MsgBox.Show(this, "At least one type must be selected.");
                return;
            }
            string whereProv = "";

            if (!checkAllProv.Checked)
            {
                for (int i = 0; i < listProv.SelectedIndices.Count; i++)
                {
                    if (i == 0)
                    {
                        whereProv += " AND (";
                    }
                    else
                    {
                        whereProv += "OR ";
                    }
                    whereProv += "claimproc.ProvNum = " + POut.Long(ProviderC.ListShort[listProv.SelectedIndices[i]].ProvNum) + " ";
                }
                whereProv += ") ";
            }
            string whereClin = "";

            if (!checkAllClin.Checked)
            {
                for (int i = 0; i < listClin.SelectedIndices.Count; i++)
                {
                    if (i == 0)
                    {
                        whereClin += " AND (";
                    }
                    else
                    {
                        whereClin += "OR ";
                    }
                    if (listClin.SelectedIndices[i] == 0)
                    {
                        whereClin += "claimproc.ClinicNum = 0 ";
                    }
                    else
                    {
                        whereClin += "claimproc.ClinicNum = " + POut.Long(Clinics.List[listClin.SelectedIndices[i] - 1].ClinicNum) + " ";
                    }
                }
                whereClin += ") ";
            }
            string queryIns =
                @"SELECT CONVERT(" + DbHelper.DateFormatColumn("claimproc.DateCP", "%c/%d/%Y") + ",CHAR(25)) DateCP,MAX("
                + DbHelper.Concat("patient.LName", "', '", "patient.FName", "' '", "patient.MiddleI") + @") lfname,
carrier.CarrierName,provider.Abbr,
clinic.Description clinicDesc,
claimpayment.CheckNum,FORMAT(SUM(claimproc.InsPayAmt),2) amt,claimproc.ClaimNum 
FROM claimproc
LEFT JOIN insplan ON claimproc.PlanNum = insplan.PlanNum 
LEFT JOIN patient ON claimproc.PatNum = patient.PatNum
LEFT JOIN carrier ON carrier.CarrierNum = insplan.CarrierNum
LEFT JOIN provider ON provider.ProvNum=claimproc.ProvNum
LEFT JOIN claimpayment ON claimproc.ClaimPaymentNum = claimpayment.ClaimPaymentNum
LEFT JOIN clinic ON clinic.ClinicNum=claimproc.ClinicNum
WHERE (claimproc.Status=1 OR claimproc.Status=4) "//received or supplemental
                + whereProv
                + whereClin
                + "AND claimpayment.CheckDate >= " + POut.Date(date1.SelectionStart) + " "
                + "AND claimpayment.CheckDate <= " + POut.Date(date2.SelectionStart) + " "
                + @"GROUP BY CONVERT(" + DbHelper.DateFormatColumn("claimproc.DateCP", "%c/%d/%Y") + @",CHAR(25)),
claimproc.ClaimPaymentNum,provider.ProvNum,
claimproc.ClinicNum,carrier.CarrierName,provider.Abbr,
clinic.Description,claimpayment.CheckNum";

            if (radioPatient.Checked)
            {
                queryIns += ",patient.PatNum";
            }
            queryIns += " ORDER BY claimproc.DateCP,lfname";
            if (!checkIns.Checked)
            {
                queryIns = DbHelper.LimitOrderBy(queryIns, 0);
            }
            //patient payments-----------------------------------------------------------------------------------------
            whereProv = "";
            if (!checkAllProv.Checked)
            {
                for (int i = 0; i < listProv.SelectedIndices.Count; i++)
                {
                    if (i == 0)
                    {
                        whereProv += " AND (";
                    }
                    else
                    {
                        whereProv += "OR ";
                    }
                    whereProv += "paysplit.ProvNum = " + POut.Long(ProviderC.ListShort[listProv.SelectedIndices[i]].ProvNum) + " ";
                }
                whereProv += ") ";
            }
            whereClin = "";
            if (!checkAllClin.Checked)
            {
                for (int i = 0; i < listClin.SelectedIndices.Count; i++)
                {
                    if (i == 0)
                    {
                        whereClin += " AND (";
                    }
                    else
                    {
                        whereClin += "OR ";
                    }
                    if (listClin.SelectedIndices[i] == 0)
                    {
                        whereClin += "payment.ClinicNum = 0 ";
                    }
                    else
                    {
                        whereClin += "payment.ClinicNum = " + POut.Long(Clinics.List[listClin.SelectedIndices[i] - 1].ClinicNum) + " ";
                    }
                }
                whereClin += ") ";
            }
            string queryPat =
                @"SELECT CONVERT(" + DbHelper.DateFormatColumn("payment.PayDate", "%c/%d/%Y") + ",CHAR(25)) AS DatePay,MAX("
                + DbHelper.Concat("patient.LName", "', '", "patient.FName", "' '", "patient.MiddleI") + @") AS lfname,
payment.PayType,provider.Abbr,
clinic.Description clinicDesc,
payment.CheckNum,
FORMAT(SUM(paysplit.SplitAmt),2) amt, payment.PayNum,ItemName 
FROM payment
LEFT JOIN paysplit ON payment.PayNum=paysplit.PayNum
LEFT JOIN patient ON payment.PatNum=patient.PatNum
LEFT JOIN provider ON paysplit.ProvNum=provider.ProvNum
LEFT JOIN definition ON payment.PayType=definition.DefNum 
LEFT JOIN clinic ON payment.ClinicNum=clinic.ClinicNum
WHERE 1 "
                + whereProv
                + whereClin
                + "AND paysplit.DatePay >= " + POut.Date(date1.SelectionStart) + " "
                + "AND paysplit.DatePay <= " + POut.Date(date2.SelectionStart) + " ";

            if (listTypes.SelectedIndices.Count > 0)
            {
                queryPat += "AND (";
                for (int i = 0; i < listTypes.SelectedIndices.Count; i++)
                {
                    if (i > 0)
                    {
                        queryPat += "OR ";
                    }
                    queryPat += "payment.PayType = " + POut.Long(DefC.Short[(int)DefCat.PaymentTypes][listTypes.SelectedIndices[i]].DefNum) + " ";
                }
                queryPat += ") ";
            }
            queryPat += @"GROUP BY "
                        + "payment.PayNum,payment.PayDate,provider.ProvNum,payment.ClinicNum"
                        + ",provider.Abbr,clinic.Description,payment.CheckNum,definition.ItemName";
            if (radioPatient.Checked)
            {
                queryPat += ",patient.PatNum";
            }
            queryPat += " ORDER BY paysplit.DatePay,lfname";
            if (!checkAllTypes.Checked && listTypes.SelectedIndices.Count == 0)
            {
                queryPat = DbHelper.LimitOrderBy(queryPat, 0);
            }
            DataTable tableIns  = Reports.GetTable(queryIns);
            DataTable tablePat  = Reports.GetTable(queryPat);
            DataTable tablePref = Reports.GetTable("SELECT ValueString FROM preference WHERE PrefName='PracticeTitle'");
            DataRow   row       = tablePref.NewRow();

            if (checkAllProv.Checked)
            {
                row[0] = Lan.g(this, "All Providers");
            }
            else
            {
                string provNames = "";
                for (int i = 0; i < listProv.SelectedIndices.Count; i++)
                {
                    if (i > 0)
                    {
                        provNames += ", ";
                    }
                    provNames += ProviderC.ListShort[listProv.SelectedIndices[i]].Abbr;
                }
                row[0] = provNames;
            }
            tablePref.Rows.Add(row);
            if (!PrefC.GetBool(PrefName.EasyNoClinics))
            {
                row = tablePref.NewRow();
                if (checkAllClin.Checked)
                {
                    row[0] = Lan.g(this, "All Clinics");
                }
                else
                {
                    string clinNames = "";
                    for (int i = 0; i < listClin.SelectedIndices.Count; i++)
                    {
                        if (i > 0)
                        {
                            clinNames += ", ";
                        }
                        if (listClin.SelectedIndices[i] == 0)
                        {
                            clinNames += Lan.g(this, "Unassigned");
                        }
                        else
                        {
                            clinNames += Clinics.List[listClin.SelectedIndices[i] - 1].Description;
                        }
                    }
                    row[0] = clinNames;
                }
                tablePref.Rows.Add(row);
            }
            FormReportForRdl FormR = new FormReportForRdl();

            FormR.SourceRdlString = Properties.Resources.PaymentsRDL;
            FormR.RdlReport.DataSets["Data"].SetData(tableIns);
            FormR.RdlReport.DataSets["DataPatPay"].SetData(tablePat);
            FormR.RdlReport.DataSets["DataPracticeTitle"].SetData(tablePref);
            FormR.ShowDialog();
            DialogResult = DialogResult.OK;
        }
Ejemplo n.º 25
0
        private void butOK_Click(object sender, System.EventArgs e)
        {
            if (!checkAllProv.Checked && listProv.SelectedIndices.Count == 0)
            {
                MsgBox.Show(this, "At least one provider must be selected.");
                return;
            }
            if (!PrefC.GetBool(PrefName.EasyNoClinics))
            {
                if (!checkAllClin.Checked && listClin.SelectedIndices.Count == 0)
                {
                    MsgBox.Show(this, "At least one clinic must be selected.");
                    return;
                }
            }
            string whereProv = "";

            if (!checkAllProv.Checked)
            {
                for (int i = 0; i < listProv.SelectedIndices.Count; i++)
                {
                    if (i == 0)
                    {
                        whereProv += " AND (";
                    }
                    else
                    {
                        whereProv += "OR ";
                    }
                    whereProv += "claimproc.ProvNum = "
                                 + POut.Long(ProviderC.ListShort[listProv.SelectedIndices[i]].ProvNum) + " ";
                }
                whereProv += ") ";
            }
            string whereClin = "";

            if (!checkAllClin.Checked)
            {
                for (int i = 0; i < listClin.SelectedIndices.Count; i++)
                {
                    if (i == 0)
                    {
                        whereClin += " AND (";
                    }
                    else
                    {
                        whereClin += "OR ";
                    }
                    if (listClin.SelectedIndices[i] == 0)
                    {
                        whereClin += "claimproc.ClinicNum = 0 ";
                    }
                    else
                    {
                        whereClin += "claimproc.ClinicNum = " + POut.Long(Clinics.List[listClin.SelectedIndices[i] - 1].ClinicNum) + " ";
                    }
                }
                whereClin += ") ";
            }
            ReportSimpleGrid report = new ReportSimpleGrid();

            report.Query = "SET @FromDate=" + POut.Date(date1.SelectionStart) + ", @ToDate=" + POut.Date(date2.SelectionStart) + ";";
            if (radioWriteoffPay.Checked)
            {
                report.Query += "SELECT " + DbHelper.DateColumn("claimproc.DateCP") + " date,"
                                + DbHelper.Concat("patient.LName", "', '", "patient.FName", "' '", "patient.MiddleI") + ","
                                + "carrier.CarrierName,"
                                + "provider.Abbr,";
                if (!PrefC.GetBool(PrefName.EasyNoClinics))
                {
                    report.Query += "clinic.Description,";
                }
                if (DataConnection.DBtype == DatabaseType.MySql)
                {
                    report.Query += "SUM(claimproc.WriteOff) $amount,";
                }
                else                  //Oracle needs quotes.
                {
                    report.Query += "SUM(claimproc.WriteOff) \"$amount\",";
                }
                report.Query += "claimproc.ClaimNum "
                                + "FROM claimproc "       //,insplan,patient,carrier,provider "
                                + "LEFT JOIN insplan ON claimproc.PlanNum = insplan.PlanNum "
                                + "LEFT JOIN patient ON claimproc.PatNum = patient.PatNum "
                                + "LEFT JOIN carrier ON carrier.CarrierNum = insplan.CarrierNum "
                                + "LEFT JOIN provider ON provider.ProvNum = claimproc.ProvNum "
                                + "LEFT JOIN clinic ON clinic.ClinicNum=claimproc.ClinicNum "
                                + "WHERE (claimproc.Status=1 OR claimproc.Status=4) "        /*received or supplemental*/
                                + whereProv
                                + whereClin
                                + "AND claimproc.DateCP >= @FromDate "
                                + "AND claimproc.DateCP <= @ToDate "
                                + "AND claimproc.WriteOff > 0 "
                                + "GROUP BY claimproc.ProvNum,claimproc.DateCP,claimproc.ClinicNum,claimproc.PatNum "
                                + "ORDER BY claimproc.DateCP,claimproc.PatNum";
            }
            else             //using procedure date
            {
                report.Query += "SELECT " + DbHelper.DateColumn("claimproc.ProcDate") + " date, "
                                + DbHelper.Concat("patient.LName", "', '", "patient.FName", "' '", "patient.MiddleI") + ", "
                                + "carrier.CarrierName, "
                                + "provider.Abbr,";
                if (!PrefC.GetBool(PrefName.EasyNoClinics))
                {
                    report.Query += "clinic.Description,";
                }
                if (DataConnection.DBtype == DatabaseType.MySql)
                {
                    report.Query += "SUM(claimproc.WriteOff) $amount, ";
                }
                else                  //Oracle needs quotes.
                {
                    report.Query += "SUM(claimproc.WriteOff) \"$amount\", ";
                }
                report.Query += "claimproc.ClaimNum "
                                + "FROM claimproc "       //,insplan,patient,carrier,provider "
                                + "LEFT JOIN insplan ON claimproc.PlanNum = insplan.PlanNum "
                                + "LEFT JOIN patient ON claimproc.PatNum = patient.PatNum "
                                + "LEFT JOIN carrier ON carrier.CarrierNum = insplan.CarrierNum "
                                + "LEFT JOIN provider ON provider.ProvNum = claimproc.ProvNum "
                                + "LEFT JOIN clinic ON clinic.ClinicNum=claimproc.ClinicNum "
                                + "WHERE (claimproc.Status=1 OR claimproc.Status=4 OR claimproc.Status=0) "        /*received or supplemental or notreceived*/
                                + whereProv
                                + whereClin
                                + "AND claimproc.ProcDate >= @FromDate "
                                + "AND claimproc.ProcDate <= @ToDate "
                                + "AND claimproc.WriteOff > 0 "
                                + "GROUP BY claimproc.ProvNum,claimproc.ProcDate,claimproc.ClinicNum,claimproc.PatNum "
                                + "ORDER BY claimproc.ProcDate,claimproc.PatNum";
            }
            FormQuery2          = new FormQuery(report);
            FormQuery2.IsReport = true;
            FormQuery2.SubmitReportQuery();
            report.Title = "Daily Writeoffs";
            report.SubTitle.Add(PrefC.GetString(PrefName.PracticeTitle));
            report.SubTitle.Add(date1.SelectionStart.ToString("d") + " - " + date2.SelectionStart.ToString("d"));
            if (checkAllProv.Checked)
            {
                report.SubTitle.Add(Lan.g(this, "All Providers"));
            }
            else
            {
                string provNames = "";
                for (int i = 0; i < listProv.SelectedIndices.Count; i++)
                {
                    if (i > 0)
                    {
                        provNames += ", ";
                    }
                    provNames += ProviderC.ListShort[listProv.SelectedIndices[i]].Abbr;
                }
                report.SubTitle.Add(provNames);
            }
            if (!PrefC.GetBool(PrefName.EasyNoClinics))
            {
                if (checkAllClin.Checked)
                {
                    report.SubTitle.Add(Lan.g(this, "All Clinics"));
                }
                else
                {
                    string clinNames = "";
                    for (int i = 0; i < listClin.SelectedIndices.Count; i++)
                    {
                        if (i > 0)
                        {
                            clinNames += ", ";
                        }
                        if (listClin.SelectedIndices[i] == 0)
                        {
                            clinNames += Lan.g(this, "Unassigned");
                        }
                        else
                        {
                            clinNames += Clinics.List[listClin.SelectedIndices[i] - 1].Description;
                        }
                    }
                    report.SubTitle.Add(clinNames);
                }
            }
            report.SetColumn(this, 0, "Date", 100);
            report.SetColumn(this, 1, "Patient Name", 150);
            report.SetColumn(this, 2, "Carrier", 225);
            report.SetColumn(this, 3, "Provider", 60);
            if (!PrefC.GetBool(PrefName.EasyNoClinics))
            {
                report.SetColumn(this, 4, "Clinic", 80);
                report.SetColumn(this, 5, "Amount", 75, HorizontalAlignment.Right);
                report.SetColumn(this, 6, "", 280, HorizontalAlignment.Right);
            }
            else
            {
                report.SetColumn(this, 4, "Amount", 75, HorizontalAlignment.Right);
                report.SetColumn(this, 5, "", 280, HorizontalAlignment.Right);
            }
            FormQuery2.ShowDialog();
            DialogResult = DialogResult.OK;
        }
Ejemplo n.º 26
0
        private void butOK_Click(object sender, System.EventArgs e)
        {
            if (textDate.Text == "")
            {
                MsgBox.Show(this, "Please enter a date first.");
                return;
            }
            if (PIn.Date(textDate.Text).Date > DateTime.Today.Date && !PrefC.GetBool(PrefName.FutureTransDatesAllowed) &&
                !PrefC.GetBool(PrefName.AllowFutureInsPayments))
            {
                MsgBox.Show(this, "Payments cannot be for a date in the future.");
                return;                 //probably not necesasary since this is an old form, but just in case we use it again
            }
            if (textDate.errorProvider1.GetError(textDate) != "")
            {
                MsgBox.Show(this, "Please fix data entry errors first.");
                return;
            }
            if (gridMain.SelectedIndices.Length == 0)
            {
                MessageBox.Show(Lan.g(this, "At least one item must be selected, or use the delete button."));
                return;
            }
            if (IsNew)
            {
                //prevents backdating of initial check
                if (!Security.IsAuthorized(Permissions.InsPayCreate, PIn.Date(textDate.Text)))
                {
                    return;
                }
                //prevents attaching claimprocs with a date that is older than allowed by security.
            }
            else
            {
                //Editing an old entry will already be blocked if the date was too old, and user will not be able to click OK button.
                //This catches it if user changed the date to be older.
                if (!Security.IsAuthorized(Permissions.InsPayEdit, PIn.Date(textDate.Text)))
                {
                    return;
                }
            }
            if (comboClinic.SelectedIndex == 0)
            {
                ClaimPaymentCur.ClinicNum = 0;
            }
            else
            {
                ClaimPaymentCur.ClinicNum = _listClinics[comboClinic.SelectedIndex - 1].ClinicNum;
            }
            ClaimPaymentCur.CheckAmt    = PIn.Double(textAmount.Text);
            ClaimPaymentCur.CheckDate   = PIn.Date(textDate.Text);
            ClaimPaymentCur.CheckNum    = textCheckNum.Text;
            ClaimPaymentCur.BankBranch  = textBankBranch.Text;
            ClaimPaymentCur.CarrierName = textCarrierName.Text;
            ClaimPaymentCur.Note        = textNote.Text;
            try{
                ClaimPayments.Update(ClaimPaymentCur);                //error thrown if trying to change amount and already attached to a deposit.
            }
            catch (ApplicationException ex) {
                MessageBox.Show(ex.Message);
                return;
            }
            //this could be optimized to only save changes.
            //Would require a starting list to compare to.
            //But this isn't bad, since changes all saved at the very end
            List <int> selectedRows = new List <int>();

            for (int i = 0; i < gridMain.SelectedIndices.Length; i++)
            {
                selectedRows.Add(gridMain.SelectedIndices[i]);
            }
            for (int i = 0; i < splits.Count; i++)
            {
                if (selectedRows.Contains(i))                //row is selected
                {
                    ClaimProcs.SetForClaimOld(splits[i].ClaimNum, ClaimPaymentCur.ClaimPaymentNum, ClaimPaymentCur.CheckDate, true);
                    //Audit trail isn't perfect, since it doesn't make an entry if you remove a claim from a payment.
                    //And it always makes more audit trail entries when you click OK, even if you didn't actually attach new claims.
                    //But since this will cover the vast majority if situations.
                    if (IsNew)
                    {
                        SecurityLogs.MakeLogEntry(Permissions.InsPayCreate, splits[i].PatNum,
                                                  Patients.GetLim(splits[i].PatNum).GetNameLF() + ", "
                                                  + Lan.g(this, "Total Amt: ") + ClaimPaymentCur.CheckAmt.ToString("c") + ", "
                                                  + Lan.g(this, "Claim Split: ") + splits[i].InsPayAmt.ToString("c"));
                    }
                    else
                    {
                        SecurityLogs.MakeLogEntry(Permissions.InsPayEdit, splits[i].PatNum,
                                                  Patients.GetLim(splits[i].PatNum).GetNameLF() + ", "
                                                  + Lan.g(this, "Total Amt: ") + ClaimPaymentCur.CheckAmt.ToString("c") + ", "
                                                  + Lan.g(this, "Claim Split: ") + splits[i].InsPayAmt.ToString("c"));
                    }
                }
                else                 //row not selected
                                     //If user had not been attaching their inspayments to checks, then this will cause such payments to annoyingly have their
                                     //date changed to the current date.  This prompts them to call us.  Then, we tell them to attach to checks.
                {
                    ClaimProcs.SetForClaimOld(splits[i].ClaimNum, ClaimPaymentCur.ClaimPaymentNum, ClaimPaymentCur.CheckDate, false);
                }
            }
            DialogResult = DialogResult.OK;
        }
Ejemplo n.º 27
0
		private void butText_Click(object sender,EventArgs e) {
			long patNum;
			string wirelessPhone;
			YN txtMsgOk;
			if(grid.Rows.Count==0) {
				MsgBox.Show(this,"There are no Patients in the table.  Must have at least one.");
				return;
			}
			if(PrefC.GetLong(PrefName.ConfirmStatusTextMessaged)==0) {
				MsgBox.Show(this,"You need to set a status first for confirmation text messages in the Recall Setup window.");
				return;
			}
			if(grid.SelectedIndices.Length==0) {//None selected. Select all of type text that are not yet confirmed by text message.
				ContactMethod cmeth;
				for(int i=0;i<Table.Rows.Count;i++) {
					cmeth=(ContactMethod)PIn.Int(Table.Rows[i]["PreferConfirmMethod"].ToString());
					if(cmeth!=ContactMethod.TextMessage) {
						continue;
					}
					if(Table.Rows[i]["confirmed"].ToString()==DefC.GetName(DefCat.ApptConfirmed,PrefC.GetLong(PrefName.ConfirmStatusTextMessaged))) {//Already confirmed by text
						continue;
					}
					if(!Table.Rows[i]["contactMethod"].ToString().StartsWith("Text:")) {//Check contact method
						continue;
					}
					grid.SetSelected(i,true);
				}
				if(grid.SelectedIndices.Length==0) {
					MsgBox.Show(this,"All patients of text message type have been sent confirmations.");
					return;
				}
			}
			//deselect the ones that do not have text messages specified or are not OK to send texts to or have already been texted
			int skipped=0;
			for(int i=grid.SelectedIndices.Length-1;i>=0;i--) {
				wirelessPhone=Table.Rows[grid.SelectedIndices[i]]["WirelessPhone"].ToString();
				if(wirelessPhone=="") {//Check for wireless number
					skipped++;
					grid.SetSelected(grid.SelectedIndices[i],false);
					continue;
				}
				txtMsgOk=(YN)PIn.Int(Table.Rows[grid.SelectedIndices[i]]["TxtMsgOk"].ToString());
				if(txtMsgOk==YN.Unknown	&& PrefC.GetBool(PrefName.TextMsgOkStatusTreatAsNo)) {//Check if OK to text
					skipped++;
					grid.SetSelected(grid.SelectedIndices[i],false);
					continue;
				}
				if(txtMsgOk==YN.No){//Check if OK to text
					skipped++;
					grid.SetSelected(grid.SelectedIndices[i],false);
					continue;
				}
			}
			if(grid.SelectedIndices.Length==0) {
				MsgBox.Show(this,"None of the selected patients have wireless phone numbers and are OK to text.");
				return;
			}
			if(skipped>0) {
				MessageBox.Show(Lan.g(this,"Selected patients skipped: ")+skipped.ToString());
			}
			if(!MsgBox.Show(this,MsgBoxButtons.YesNo,"Send text message to all of the selected patients?")) {
				return;
			}
			Cursor=Cursors.WaitCursor;
			FormTxtMsgEdit FormTME=new FormTxtMsgEdit();
			string message="";
			//Appointment apt;
			for(int i=0;i<grid.SelectedIndices.Length;i++){
				patNum=PIn.Long(Table.Rows[grid.SelectedIndices[i]]["PatNum"].ToString());
				wirelessPhone=PIn.String(Table.Rows[grid.SelectedIndices[i]]["WirelessPhone"].ToString());
				txtMsgOk=((YN)PIn.Int(Table.Rows[grid.SelectedIndices[i]]["TxtMsgOk"].ToString()));
				message=PrefC.GetString(PrefName.ConfirmTextMessage);
				message=message.Replace("[NameF]",Table.Rows[grid.SelectedIndices[i]]["nameF"].ToString());
				message=message.Replace("[NameFL]",Table.Rows[grid.SelectedIndices[i]]["nameFL"].ToString());
				message=message.Replace("[date]",((DateTime)Table.Rows[grid.SelectedIndices[i]]["AptDateTime"]).ToShortDateString());
				message=message.Replace("[time]",((DateTime)Table.Rows[grid.SelectedIndices[i]]["AptDateTime"]).ToShortTimeString());
				FormTME.SendText(patNum,wirelessPhone,message,txtMsgOk);
				Appointments.SetConfirmed(PIn.Long(Table.Rows[grid.SelectedIndices[i]]["AptNum"].ToString()),PrefC.GetLong(PrefName.ConfirmStatusTextMessaged));
			}
			FillMain();
			Cursor=Cursors.Default;
		}
Ejemplo n.º 28
0
 /// <summary>Sets UI for preferences that we know for sure will exist.</summary>
 private void FillStandardPrefs()
 {
     #region Account Tab
     checkAgingMonthly.Checked = PrefC.GetBool(PrefName.AgingCalculatedMonthlyInsteadOfDaily);
     foreach (PayClinicSetting prompt in Enum.GetValues(typeof(PayClinicSetting)))
     {
         comboPaymentClinicSetting.Items.Add(Lan.g(this, prompt.GetDescription()));
     }
     comboPaymentClinicSetting.SelectedIndex = PrefC.GetInt(PrefName.PaymentClinicSetting);
     checkPaymentsPromptForPayType.Checked   = PrefC.GetBool(PrefName.PaymentsPromptForPayType);
     for (int i = 0; i < Enum.GetNames(typeof(AutoSplitPreference)).Length; i++)
     {
         comboAutoSplitPref.Items.Add(Lans.g(this, Enum.GetNames(typeof(AutoSplitPreference))[i]));
     }
     comboAutoSplitPref.SelectedIndex    = PrefC.GetInt(PrefName.AutoSplitLogic);
     checkBillShowTransSinceZero.Checked = PrefC.GetBool(PrefName.BillingShowTransSinceBalZero);
     textClaimIdentifier.Text            = PrefC.GetString(PrefName.ClaimIdPrefix);
     checkReceiveReportsService.Checked  = PrefC.GetBool(PrefName.ClaimReportReceivedByService);
     _claimReportReceiveInterval         = PrefC.GetInt(PrefName.ClaimReportReceiveInterval);
     if (_claimReportReceiveInterval == 0)
     {
         radioTime.Checked = true;
         DateTime fullDateTime = PrefC.GetDateT(PrefName.ClaimReportReceiveTime);
         textReportCheckTime.Text = fullDateTime.ToShortTimeString();
     }
     else
     {
         textReportCheckInterval.Text = POut.Int(_claimReportReceiveInterval);
         radioInterval.Checked        = true;
     }
     List <RigorousAccounting> listEnums = Enum.GetValues(typeof(RigorousAccounting)).OfType <RigorousAccounting>().ToList();
     for (int i = 0; i < listEnums.Count; i++)
     {
         comboRigorousAccounting.Items.Add(listEnums[i].GetDescription());
     }
     comboRigorousAccounting.SelectedIndex = PrefC.GetInt(PrefName.RigorousAccounting);
     List <RigorousAdjustments> listAdjEnums = Enum.GetValues(typeof(RigorousAdjustments)).OfType <RigorousAdjustments>().ToList();
     for (int i = 0; i < listAdjEnums.Count; i++)
     {
         comboRigorousAdjustments.Items.Add(listAdjEnums[i].GetDescription());
     }
     comboRigorousAdjustments.SelectedIndex = PrefC.GetInt(PrefName.RigorousAdjustments);
     checkHidePaysplits.Checked             = PrefC.GetBool(PrefName.PaymentWindowDefaultHideSplits);
     foreach (PayPlanVersions version in Enum.GetValues(typeof(PayPlanVersions)))
     {
         comboPayPlansVersion.Items.Add(Lan.g("enumPayPlanVersions", version.GetDescription()));
     }
     comboPayPlansVersion.SelectedIndex = PrefC.GetInt(PrefName.PayPlansVersion) - 1;
     textBillingElectBatchMax.Text      = PrefC.GetInt(PrefName.BillingElectBatchMax).ToString();
     checkBillingShowProgress.Checked   = PrefC.GetBool(PrefName.BillingShowSendProgress);
     #endregion Account Tab
     #region Advanced Tab
     checkPasswordsMustBeStrong.Checked         = PrefC.GetBool(PrefName.PasswordsMustBeStrong);
     checkPasswordsStrongIncludeSpecial.Checked = PrefC.GetBool(PrefName.PasswordsStrongIncludeSpecial);
     checkPasswordForceWeakToStrong.Checked     = PrefC.GetBool(PrefName.PasswordsWeakChangeToStrong);
     checkLockIncludesAdmin.Checked             = PrefC.GetBool(PrefName.SecurityLockIncludesAdmin);
     textLogOffAfterMinutes.Text      = PrefC.GetInt(PrefName.SecurityLogOffAfterMinutes).ToString();
     checkUserNameManualEntry.Checked = PrefC.GetBool(PrefName.UserNameManualEntry);
     textDateLock.Text = PrefC.GetDate(PrefName.SecurityLockDate).ToShortDateString();
     textDaysLock.Text = PrefC.GetInt(PrefName.SecurityLockDays).ToString();
     long signalInactive = PrefC.GetLong(PrefName.SignalInactiveMinutes);
     textInactiveSignal.Text = (signalInactive == 0 ? "" : signalInactive.ToString());
     long sigInterval = PrefC.GetLong(PrefName.ProcessSigsIntervalInSecs);
     textSigInterval.Text = (sigInterval == 0 ? "" : sigInterval.ToString());
     string patSearchMinChars = PrefC.GetString(PrefName.PatientSelectSearchMinChars);
     textPatSelectMinChars.Text = Math.Min(10, Math.Max(1, PIn.Int(patSearchMinChars, false))).ToString();       //enforce minimum 1 maximum 10
     string patSearchPauseMs = PrefC.GetString(PrefName.PatientSelectSearchPauseMs);
     textPatSelectPauseMs.Text = Math.Min(10000, Math.Max(1, PIn.Int(patSearchPauseMs, false))).ToString();      //enforce minimum 1 maximum 10000
     checkPatientSelectFilterRestrictedClinics.Checked = PrefC.GetBool(PrefName.PatientSelectFilterRestrictedClinics);
     YN searchEmptyParams = PIn.Enum <YN>(PrefC.GetInt(PrefName.PatientSelectSearchWithEmptyParams));
     if (searchEmptyParams != YN.Unknown)
     {
         checkPatSearchEmptyParams.CheckState = CheckState.Unchecked;
         checkPatSearchEmptyParams.Checked    = searchEmptyParams == YN.Yes;
     }
     _usePhonenumTable = PrefC.GetEnum <YN>(PrefName.PatientPhoneUsePhonenumberTable);
     if (_usePhonenumTable != YN.Unknown)
     {
         checkUsePhoneNumTable.CheckState = CheckState.Unchecked;
         checkUsePhoneNumTable.Checked    = _usePhonenumTable == YN.Yes;
     }
     #endregion Advanced Tab
     #region Appts Tab
     checkApptsRequireProcs.Checked  = PrefC.GetBool(PrefName.ApptsRequireProc);
     checkUseOpHygProv.Checked       = PrefC.GetBool(PrefName.ApptSecondaryProviderConsiderOpOnly);
     checkEnterpriseApptList.Checked = PrefC.GetBool(PrefName.EnterpriseApptList);
     checkEnableNoneView.Checked     = PrefC.GetBool(PrefName.EnterpriseNoneApptViewDefaultDisabled);
     #endregion Appts Tab
     #region Family Tab
     checkSuperFam.Checked            = PrefC.GetBool(PrefName.ShowFeatureSuperfamilies);
     checkPatClone.Checked            = PrefC.GetBool(PrefName.ShowFeaturePatientClone);
     checkShowFeeSchedGroups.Checked  = PrefC.GetBool(PrefName.ShowFeeSchedGroups);
     checkSuperFamCloneCreate.Checked = PrefC.GetBool(PrefName.CloneCreateSuperFamily);
     //users should only see the snapshot trigger and service runtime if they have it set to something other than ClaimCreate.
     //if a user wants to be able to change claimsnapshot settings, the following MySQL statement should be run:
     //UPDATE preference SET ValueString = 'Service'	 WHERE PrefName = 'ClaimSnapshotTriggerType'
     if (PIn.Enum <ClaimSnapshotTrigger>(PrefC.GetString(PrefName.ClaimSnapshotTriggerType), true) == ClaimSnapshotTrigger.ClaimCreate)
     {
         groupClaimSnapshot.Visible = false;
     }
     foreach (ClaimSnapshotTrigger trigger in Enum.GetValues(typeof(ClaimSnapshotTrigger)))
     {
         comboClaimSnapshotTrigger.Items.Add(trigger.GetDescription());
     }
     comboClaimSnapshotTrigger.SelectedIndex = (int)PIn.Enum <ClaimSnapshotTrigger>(PrefC.GetString(PrefName.ClaimSnapshotTriggerType), true);
     textClaimSnapshotRunTime.Text           = PrefC.GetDateT(PrefName.ClaimSnapshotRunTime).ToShortTimeString();
     #endregion Family Tab
     #region Reports Tab
     checkUseReportServer.Checked = (PrefC.GetString(PrefName.ReportingServerCompName) != "" || PrefC.GetString(PrefName.ReportingServerURI) != "");
     textServerName.Text          = PrefC.GetString(PrefName.ReportingServerCompName);
     comboDatabase.Text           = PrefC.GetString(PrefName.ReportingServerDbName);
     textMysqlUser.Text           = PrefC.GetString(PrefName.ReportingServerMySqlUser);
     string decryptedPass;
     CDT.Class1.Decrypt(PrefC.GetString(PrefName.ReportingServerMySqlPassHash), out decryptedPass);
     textMysqlPass.Text     = decryptedPass;
     textMiddleTierURI.Text = PrefC.GetString(PrefName.ReportingServerURI);
     FillComboDatabases();
     SetReportServerUIEnabled();
     #endregion Reports Tab
 }
Ejemplo n.º 29
0
        public static bool Retrieve(Clearinghouse clearinghouse, IODProgressExtended progress = null)
        {
            progress = progress ?? new ODProgressExtendedNull();
            progress.UpdateProgress(Lans.g(progress.LanThis, "Contacting web server and downloading reports"), "reports", "17%", 17);
            if (progress.IsPauseOrCancel())
            {
                progress.UpdateProgress(Lans.g(progress.LanThis, "Canceled by user."));
                return(false);
            }
            Dentalxchange2016.Credentials cred = new Dentalxchange2016.Credentials();
            if (PrefC.GetBool(PrefName.CustomizedForPracticeWeb))             //even though they currently use code from a different part of the program.
            {
                cred.Client    = "Practice-Web";
                cred.ServiceID = "DCI Web Service ID: 001513";
            }
            else
            {
                cred.Client    = "OpenDental";
                cred.ServiceID = "DCI Web Service ID: 002778";
            }
            cred.Username = clearinghouse.LoginID;
            cred.Password = clearinghouse.Password;
            Dentalxchange2016.unProcessedEraRequest request = new Dentalxchange2016.unProcessedEraRequest();
            Dentalxchange2016.DwsService            service = new Dentalxchange2016.DwsService();
#if DEBUG
            service.Url = "https://prelive2.dentalxchange.com/dws/DwsService?wsdl";
#else
            service.Url = "https://webservices.dentalxchange.com/dws/DwsService?wsdl";
#endif
            ErrorMessage = "";
            List <string> listEraStrings = new List <string>();
            try {
                Dentalxchange2016.UnProcessedEraResponse response;
                do
                {
                    response = service.getUnProcessedEra(cred, request);
                    if (response.Status.code == 0 && response.ClaimPaymentAdvice.EdiContent != null)
                    {
                        listEraStrings.Add(response.ClaimPaymentAdvice.EdiContent);                        //X12 835 ERA raw content
                    }
                } while(response.Status.code == 0 && response.ClaimPaymentAdvice != null && response.ClaimPaymentAdvice.AdditionalEraExists);
                if (response.Status.code != 0)               //!=Approved
                //If the following error message changes, then also see if FormClaimReports.RetrieveReports() needs to change as well.
                {
                    ErrorMessage = "Era request unsuccessful."
                                   + "\r\nError message received directly from Claim Connect: " + response.Status.code
                                   + "\r\n\r\n" + response.Status.description;
                    return(false);
                }

                /*
                 * Code Description
                 * 0    Approved
                 * 1    Operation Failed
                 * 90   Invalid Group
                 * 100  Invalid User
                 * 110  Invalid Client
                 * 120  Service Not Allowed
                 * 130  User Not Allowed
                 * 140  Invalid PMS
                 * 150  Service Not Contracted by User
                 * 1000 Internal server error has occurred. The problem is being investigated.
                 * 2000 Generic Host Error
                 * 2001 Malformed document sent. Please insure that the format is correct and all required data is present.
                 * 2002 Deficient request - required data is missing.
                 * 2003 No insurers found for this selection.
                 * 2004 Unable to contact the payer at this time. Please try again later.
                 * 2005 Only the relationship self is supported at this time.
                 * 2007 Original request patient info reflected back
                 * 2008 Claim submission failed.
                 */
            }
            catch (Exception ex) {
                ErrorMessage = Lans.g(progress.LanThis, "If this is a new customer, this error might be due to an invalid Username or Password.  "
                                      + "Servers may need a few hours before ready to accept new user information.") + "\r\n"
                               + Lans.g(progress.LanThis, "Error message received directly from Claim Connect:") + "  " + ex.ToString();
                return(false);
            }
            progress.UpdateProgress(Lans.g(progress.LanThis, "Web server contact successful."));
            string path = clearinghouse.ResponsePath;
            progress.UpdateProgress(Lans.g(progress.LanThis, "Writing files"), "reports", "40%", 40);
            if (progress.IsPauseOrCancel())
            {
                progress.UpdateProgress(Lans.g(progress.LanThis, "Canceled by user."));
                return(false);
            }
            //write each message to a distinct file in the export path.
            listEraStrings.ForEach(x => File.WriteAllText(ODFileUtils.CreateRandomFile(path, ".txt"), x));
            progress.UpdateProgress(Lans.g(progress.LanThis, "Files written successfully."));
            progress.UpdateProgress(Lans.g(progress.LanThis, "Finalizing"), "reports", "50%", 50);
            if (progress.IsPauseOrCancel())
            {
                progress.UpdateProgress(Lans.g(progress.LanThis, "Canceled by user."));
                return(false);
            }
            return(true);
        }
Ejemplo n.º 30
0
        private void butAdd_Click(object sender, EventArgs e)
        {
            if (!PrefC.GetBool(PrefName.StoreCCnumbers))
            {
                bool hasXCharge    = false;
                bool hasPayConnect = false;
                bool hasPaySimple  = false;
                Dictionary <string, int> dictEnabledProcessors = new Dictionary <string, int>();
                int  idx = 0;
                bool hasXChargePreventCcAdd = PIn.Bool(ProgramProperties.GetPropVal(Programs.GetCur(ProgramName.Xcharge).ProgramNum,
                                                                                    ProgramProperties.PropertyDescs.XCharge.XChargePreventSavingNewCC, Clinics.ClinicNum));
                if (Programs.IsEnabled(ProgramName.Xcharge) && !hasXChargePreventCcAdd)
                {
                    dictEnabledProcessors["X-Charge"] = idx++;
                }
                bool hasPayConnectPreventCcAdd = PIn.Bool(ProgramProperties.GetPropVal(Programs.GetCur(ProgramName.PayConnect).ProgramNum,
                                                                                       PayConnect.ProgramProperties.PayConnectPreventSavingNewCC, Clinics.ClinicNum));
                if (Programs.IsEnabled(ProgramName.PayConnect) && !hasPayConnectPreventCcAdd)
                {
                    dictEnabledProcessors["PayConnect"] = idx++;
                }
                bool hasPaySimplePreventCCAdd = PIn.Bool(ProgramProperties.GetPropVal(Programs.GetCur(ProgramName.PaySimple).ProgramNum,
                                                                                      PaySimple.PropertyDescs.PaySimplePreventSavingNewCC, Clinics.ClinicNum));
                if (Programs.IsEnabled(ProgramName.PaySimple) && !hasPaySimplePreventCCAdd)
                {
                    dictEnabledProcessors["PaySimple"] = idx++;
                }
                if (dictEnabledProcessors.Count > 1)
                {
                    List <string> listCCProcessors = dictEnabledProcessors.Select(x => x.Key).ToList();
                    InputBox      chooseProcessor  =
                        new InputBox(Lan.g(this, "For which credit card processing company would you like to add this card?"), listCCProcessors, true);
                    if (chooseProcessor.ShowDialog() == DialogResult.Cancel)
                    {
                        return;
                    }
                    hasXCharge    = dictEnabledProcessors.ContainsKey("X-Charge") && chooseProcessor.SelectedIndices.Contains(dictEnabledProcessors["X-Charge"]);
                    hasPayConnect = dictEnabledProcessors.ContainsKey("PayConnect") && chooseProcessor.SelectedIndices.Contains(dictEnabledProcessors["PayConnect"]);
                    hasPaySimple  = dictEnabledProcessors.ContainsKey("PaySimple") && chooseProcessor.SelectedIndices.Contains(dictEnabledProcessors["PaySimple"]);
                }
                else if (Programs.IsEnabled(ProgramName.Xcharge) && !hasXChargePreventCcAdd)
                {
                    hasXCharge = true;
                }
                else if (Programs.IsEnabled(ProgramName.PayConnect) && !hasPayConnectPreventCcAdd)
                {
                    hasPayConnect = true;
                }
                else if (Programs.IsEnabled(ProgramName.PaySimple) && !hasPaySimplePreventCCAdd)
                {
                    hasPaySimple = true;
                }
                else                  //not storing CC numbers and both PayConnect and X-Charge are disabled
                {
                    MsgBox.Show(this, "Not allowed to store credit cards.");
                    return;
                }
                CreditCard creditCardCur = null;
                if (hasXCharge)
                {
                    if (ODBuild.IsWeb())
                    {
                        MsgBox.Show(this, "XCharge is not available while viewing through the web.");
                        return;
                    }
                    Program prog      = Programs.GetCur(ProgramName.Xcharge);
                    string  path      = Programs.GetProgramPath(prog);
                    string  xUsername = ProgramProperties.GetPropVal(prog.ProgramNum, "Username", Clinics.ClinicNum).Trim();
                    string  xPassword = ProgramProperties.GetPropVal(prog.ProgramNum, "Password", Clinics.ClinicNum).Trim();
                    //Force user to retry entering information until it's correct or they press cancel
                    while (!File.Exists(path) || string.IsNullOrEmpty(xPassword) || string.IsNullOrEmpty(xUsername))
                    {
                        MsgBox.Show(this, "The Path, Username, and/or Password for X-Charge have not been set or are invalid.");
                        if (!Security.IsAuthorized(Permissions.Setup))
                        {
                            return;
                        }
                        FormXchargeSetup FormX = new FormXchargeSetup();                 //refreshes program and program property caches on OK click
                        FormX.ShowDialog();
                        if (FormX.DialogResult != DialogResult.OK)                       //if user presses cancel, return
                        {
                            return;
                        }
                        prog      = Programs.GetCur(ProgramName.Xcharge);                 //refresh local variable prog to reflect any changes made in setup window
                        path      = Programs.GetProgramPath(prog);
                        xUsername = ProgramProperties.GetPropVal(prog.ProgramNum, "Username", Clinics.ClinicNum).Trim();
                        xPassword = ProgramProperties.GetPropVal(prog.ProgramNum, "Password", Clinics.ClinicNum).Trim();
                    }
                    xPassword = CodeBase.MiscUtils.Decrypt(xPassword);
                    ProcessStartInfo info       = new ProcessStartInfo(path);
                    string           resultfile = PrefC.GetRandomTempFile("txt");
                    try {
                        File.Delete(resultfile);                        //delete the old result file.
                    }
                    catch {
                        MsgBox.Show(this, "Could not delete XResult.txt file.  It may be in use by another program, flagged as read-only, or you might not have sufficient permissions.");
                        return;
                    }
                    info.Arguments  = "";
                    info.Arguments += "/TRANSACTIONTYPE:ArchiveVaultAdd /LOCKTRANTYPE ";
                    info.Arguments += "/RESULTFILE:\"" + resultfile + "\" ";
                    info.Arguments += "/USERID:" + xUsername + " ";
                    info.Arguments += "/PASSWORD:"******" ";
                    info.Arguments += "/VALIDATEARCHIVEVAULTACCOUNT ";
                    info.Arguments += "/STAYONTOP ";
                    info.Arguments += "/SMARTAUTOPROCESS ";
                    info.Arguments += "/AUTOCLOSE ";
                    info.Arguments += "/HIDEMAINWINDOW ";
                    info.Arguments += "/SMALLWINDOW ";
                    info.Arguments += "/NORESULTDIALOG ";
                    info.Arguments += "/TOOLBAREXITBUTTON ";
                    Cursor          = Cursors.WaitCursor;
                    Process process = new Process();
                    process.StartInfo           = info;
                    process.EnableRaisingEvents = true;
                    process.Start();
                    while (!process.HasExited)
                    {
                        Application.DoEvents();
                    }
                    Thread.Sleep(200);                    //Wait 2/10 second to give time for file to be created.
                    Cursor = Cursors.Default;
                    string resulttext    = "";
                    string line          = "";
                    string xChargeToken  = "";
                    string accountMasked = "";
                    string exp           = "";;
                    bool   insertCard    = false;
                    try {
                        using (TextReader reader = new StreamReader(resultfile)) {
                            line = reader.ReadLine();
                            while (line != null)
                            {
                                if (resulttext != "")
                                {
                                    resulttext += "\r\n";
                                }
                                resulttext += line;
                                if (line.StartsWith("RESULT="))
                                {
                                    if (line != "RESULT=SUCCESS")
                                    {
                                        throw new Exception();
                                    }
                                    insertCard = true;
                                }
                                if (line.StartsWith("XCACCOUNTID="))
                                {
                                    xChargeToken = PIn.String(line.Substring(12));
                                }
                                if (line.StartsWith("ACCOUNT="))
                                {
                                    accountMasked = PIn.String(line.Substring(8));
                                }
                                if (line.StartsWith("EXPIRATION="))
                                {
                                    exp = PIn.String(line.Substring(11));
                                }
                                line = reader.ReadLine();
                            }
                            if (insertCard && xChargeToken != "")                           //Might not be necessary but we've had successful charges with no tokens returned before.
                            {
                                creditCardCur = new CreditCard();
                                List <CreditCard> itemOrderCount = CreditCards.Refresh(PatCur.PatNum);
                                creditCardCur.PatNum         = PatCur.PatNum;
                                creditCardCur.ItemOrder      = itemOrderCount.Count;
                                creditCardCur.CCNumberMasked = accountMasked;
                                creditCardCur.XChargeToken   = xChargeToken;
                                creditCardCur.CCExpiration   = new DateTime(Convert.ToInt32("20" + PIn.String(exp.Substring(2, 2))), Convert.ToInt32(PIn.String(exp.Substring(0, 2))), 1);
                                creditCardCur.Procedures     = PrefC.GetString(PrefName.DefaultCCProcs);
                                creditCardCur.CCSource       = CreditCardSource.XServer;
                                creditCardCur.ClinicNum      = Clinics.ClinicNum;
                                CreditCards.Insert(creditCardCur);
                            }
                        }
                    }
                    catch (Exception) {
                        MsgBox.Show(this, "There was a problem adding the credit card.  Please try again.");
                    }
                }
                if (hasPayConnect)
                {
                    FormPayConnect FormPC = new FormPayConnect(Clinics.ClinicNum, PatCur, (decimal)0.01, creditCardCur, true);
                    FormPC.ShowDialog();
                }
                if (hasPaySimple)
                {
                    FormPaySimple formPS = new FormPaySimple(Clinics.ClinicNum, PatCur, (decimal)0.01, creditCardCur, true);
                    formPS.ShowDialog();
                }
                FillGrid();
                if (gridMain.ListGridRows.Count > 0 && creditCardCur != null)
                {
                    gridMain.SetSelected(gridMain.ListGridRows.Count - 1, true);
                }
                return;
            }
            //storing CC numbers allowed from here down
            FormCreditCardEdit FormCCE = new FormCreditCardEdit(PatCur);

            FormCCE.CreditCardCur            = new CreditCard();
            FormCCE.CreditCardCur.IsNew      = true;
            FormCCE.CreditCardCur.Procedures = PrefC.GetString(PrefName.DefaultCCProcs);
            FormCCE.ShowDialog();
            if (FormCCE.DialogResult == DialogResult.OK)
            {
                FillGrid();
                if (gridMain.ListGridRows.Count > 0)
                {
                    gridMain.SetSelected(gridMain.ListGridRows.Count - 1, true);
                }
            }
        }