using framework_business; using framework_library; using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Reflection; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; public partial class controls_module_enquiry : ICanvasBase, IControlBase { MediSwitch mediswitch; decimal dTotalAmount = 0, dTotalMedicalLiable = 0, dTotalPatientLiable = 0; public oAccount Account { get { if (ViewState["account"] == null) return null; else return (oAccount)ViewState["account"]; } set { ViewState["account"] = value; } } public string NotesFieldName { get { if (ViewState["notesFieldName"] == null) return ""; else return ViewState["notesFieldName"].ToString(); } set { ViewState["notesFieldName"] = value; } } public void ReloadControl() { try { if (utils.verifySession("account")) this.Account = (oAccount)Session["account"]; if (utils.verifySession("noteSurfaceFieldName")) { this.NotesFieldName = Session["noteSurfaceFieldName"].ToString(); utils.disposeSession("noteSurfaceFieldName"); } oAccount acc = this.Account; SetMultiplePatient(acc); PopulatePageFormValues(ref acc); SetupControl(acc); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } public void SaveControlData() { } #region methods /// /// Method to Bind Account Data /// private void BindAccountData(oAccount acc) { try { Session["bal"] = 0; ArrayList tempList = xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "surfaceItemId,isVisible", acc.surfaceItemId.ToString() + ",1", "dateOfService,sequence"); ArrayList accountList = new ArrayList(); ArrayList assitedList = new ArrayList(); //temp update missing records foreach (oAccount accnt in tempList) { if (accnt.procedureType != "PA" && accnt.procedureType != "CA") { accountList.Add(accnt); } if (accnt.modifier1 == "0008" || accnt.modifier1 == "0009" || accnt.procedureType == "PA" || accnt.procedureType == "CA")//add mofier lines and the associated payments { assitedList.Add(accnt); } //check is mediswitch is enabled if (((oSetup)handler.ReturnSetup()).isMediswitch) { //check if mediswitch claimable account foreach (oMedicalScheme medScheme in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalScheme), "code", accnt.medCode)) { if (medScheme.msDestinationCode.Length > 0) { btnNewClaim.Visible = true; } } } } //bind Account view grid rptAccounts.DataSource = accountList; rptAccounts.DataBind(); //bind Assistant View Grid rptAccountsAssisted.DataSource = assitedList; rptAccountsAssisted.DataBind(); upAccounts.Update(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// Bind Billing Lines /// private void BindTariffs(oAccount acc) { try { DataTable tariffData = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oTariffPlan), "", "", "name"); ddBillingTariff.DataSource = tariffData; ddBillingTariff.DataTextField = "name"; ddBillingTariff.DataValueField = "code"; ddBillingTariff.DataBind(); ddEditLineTariff.DataSource = tariffData; ddEditLineTariff.DataTextField = "name"; ddEditLineTariff.DataValueField = "code"; ddEditLineTariff.DataBind(); foreach (oMedicalScheme schm in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalScheme), "code", acc.medCode)) { if (schm.planCode != String.Empty) { if (ddBillingTariff.Items.FindByValue(schm.planCode) != null) ddBillingTariff.SelectedValue = schm.planCode; if (ddEditLineTariff.Items.FindByValue(schm.planCode) != null) ddEditLineTariff.SelectedValue = schm.planCode; break; } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Bind Fees /// private void BindFeesNew(string feeCode, string description) { try { DataTable feeData = new DataTable(); if (feeCode != String.Empty) { feeData = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oMedicalProcedure), "code", feeCode, "description"); } else if (description != String.Empty) { feeData = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oMedicalProcedure), "description", description, "description"); } else { feeData = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oMedicalProcedure), "", "", "description"); } if (feeData.Rows.Count == 0) { txtBillingCode.Text = "Invalid Code"; txtBillingCode.ForeColor = System.Drawing.Color.Red; return; } else { txtBillingCode.ForeColor = System.Drawing.Color.Black; } //for (int i = feeData.Rows.Count - 1; i >= 0; i--) //{ // if (feeData.Rows[i]["codeType"].ToString() == "3") // feeData.Rows.RemoveAt(i); //} ddBillingDescription.DataSource = feeData; ddBillingDescription.DataTextField = "description"; ddBillingDescription.DataValueField = "code"; ddBillingDescription.DataBind(); if (description == String.Empty && feeCode == String.Empty) { ddBillingDescription.Items.Insert(0, new ListItem("select a procedure..", "")); btnMods.Enabled = false; } else { CalculateAmount(true); btnMods.Enabled = true; lblModProcedure.Text = txtBillingCode.Text + " - " + ddBillingDescription.SelectedItem.Text; } /* CVH 2016-09-30 To be loaded on procedure selection */ ddBillingAdditionalDescription.Enabled = false; ddBillingAdditionalDescription.Items.Clear(); ddBillingAdditionalDescription.ClearSelection(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } private void BindFeesEdit(string feeCode, string description) { try { DataTable feeData = new DataTable(); if (feeCode != String.Empty) { feeData = xData.GetTypedByCriteriaBeginsTable("recId", typeof(oMedicalProcedure), "code", feeCode, "description"); } else if (description != String.Empty) { feeData = xData.GetTypedByCriteriaBeginsTable("recId", typeof(oMedicalProcedure), "description", description, "description"); } else { feeData = xData.GetTypedByCriteriaBeginsTable("recId", typeof(oMedicalProcedure), "", "", "description"); } if (feeData.Rows.Count == 0) { txtEditLineCode.Text = "Invalid Code"; txtEditLineCode.ForeColor = System.Drawing.Color.Red; return; } else { txtEditLineCode.ForeColor = System.Drawing.Color.Black; } ddEditLineDescription.DataSource = feeData; ddEditLineDescription.DataTextField = "description"; ddEditLineDescription.DataValueField = "code"; ddEditLineDescription.DataBind(); if (description == String.Empty && feeCode == String.Empty) ddEditLineDescription.Items.Insert(0, new ListItem("select a procedure..", "")); else { CalculateAmountEditLine(true); } /* CVH 2016-09-30 To be loaded on procedure selection */ ddEditLineAdditionalDescription.Enabled = false; ddEditLineAdditionalDescription.Items.Clear(); ddEditLineAdditionalDescription.ClearSelection(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Bind Modifiers /// private void BindModifiers() { try { DataTable modData = new DataTable(); modData = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oMedicalProcedure), "codeType", "2", "description"); ddBillingModifier.DataSource = modData; ddBillingModifier.DataTextField = "description"; ddBillingModifier.DataValueField = "code"; ddBillingModifier.DataBind(); ddBillingModifier.Items.Insert(0, new ListItem("select a modifier..", "")); ddEditLineModifier.DataSource = modData; ddEditLineModifier.DataTextField = "description"; ddEditLineModifier.DataValueField = "code"; ddEditLineModifier.DataBind(); ddEditLineModifier.Items.Insert(0, new ListItem("select a modifier..", "")); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } private void BindTransactionTypes() { try { DataTable transactionTypeData = new DataTable(); transactionTypeData = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oTransactionType), "", ""); ddTransactionType.DataSource = transactionTypeData; ddTransactionType.DataTextField = "transactionType"; ddTransactionType.DataValueField = "recId"; ddTransactionType.DataBind(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Bind Service Sites /// private void BindServiceSites() { try { DataTable siteData = new DataTable(); siteData = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oPlaceOfService), "isActive", "1", "display"); ddPlaceOfservice.DataSource = siteData; ddPlaceOfservice.DataTextField = "display"; ddPlaceOfservice.DataValueField = "indicator"; ddPlaceOfservice.DataBind(); ddEditLineServiceSite.DataSource = siteData; ddEditLineServiceSite.DataTextField = "display"; ddEditLineServiceSite.DataValueField = "indicator"; ddEditLineServiceSite.DataBind(); //default to office ddPlaceOfservice.SelectedValue = "11"; ddEditLineServiceSite.SelectedValue = "11"; } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Bind Assistants /// private void BindAssistants(int assistantType) { try { //only load assistants DataTable dt = xData.GetDynamicByCriteriaSpecific("recId", typeof(oMedicalDoctor), "isAssistant,assistantType", "1," + assistantType, "surname"); foreach (DataRow row in dt.Rows) { row["BHFRegNo"] = row["recId"].ToString() + "_" + row["BHFRegNo"].ToString(); } ddModAssistant.Items.Clear(); ddModAssistant.DataSource = dt; ddModAssistant.DataTextField = "surname"; ddModAssistant.DataValueField = "BHFRegNo"; ddModAssistant.DataBind(); ddModAssistant.Items.Insert(0, new ListItem("select an assistant...", "0")); ddEditModAssistant.Items.Clear(); ddEditModAssistant.DataSource = dt; ddEditModAssistant.DataTextField = "surname"; ddEditModAssistant.DataValueField = "BHFRegNo"; ddEditModAssistant.DataBind(); ddEditModAssistant.Items.Insert(0, new ListItem("select an assistant...", "0")); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Bind Doctors /// private void BindDoctors() { try { DataTable docDataTemp = new DataTable(); docDataTemp = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oMedicalDoctor), "isMember", "1", "surname"); /* CVH 2016-05-06 Filter out assistants, must use <> 1, possible values are 0,1,NULL */ //check for null and set to false before doing comparison IEnumerable query = from doc in docDataTemp.AsEnumerable() where (doc.Field("isAssistant") == null ? false : doc.Field("isAssistant")) == false select doc; DataTable docData = new DataTable(); if (query.Count() > 0) docData = query.CopyToDataTable(); else docData = docDataTemp.Clone(); ddBillingDoctor.DataSource = docData; ddBillingDoctor.DataTextField = "surname"; ddBillingDoctor.DataValueField = "recId"; ddBillingDoctor.DataBind(); ddEditLineDoctor.DataSource = docData; ddEditLineDoctor.DataTextField = "surname"; ddEditLineDoctor.DataValueField = "recId"; ddEditLineDoctor.DataBind(); ddPaymentDoctor.DataSource = docData; ddPaymentDoctor.DataTextField = "surname"; ddPaymentDoctor.DataValueField = "recId"; ddPaymentDoctor.DataBind(); ddPaymentAssistDoctor.DataSource = docData; ddPaymentAssistDoctor.DataTextField = "surname"; ddPaymentAssistDoctor.DataValueField = "recId"; ddPaymentAssistDoctor.DataBind(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Bind ICD10 codes dropdown /// private void BindICD10s() { try { DataTable icd10Data = new DataTable(); icd10Data = xData.GetTypedByCriteriaBeginsTable("recId", typeof(oMedicalICD10), "isActive", "1", "icdCode"); icd10Data.Columns.Add("CodeDescription", typeof(string), "icdCode + ' - ' + icdDescription"); ddBillingICD10.DataSource = icd10Data; ddBillingICD10.DataTextField = "CodeDescription"; ddBillingICD10.DataValueField = "icdCode"; ddBillingICD10.DataBind(); ddBillingICD10.Items.Insert(0, new ListItem("select a code..", "0")); lstBillingICd10.DataSource = icd10Data; lstBillingICd10.DataTextField = "CodeDescription"; lstBillingICd10.DataValueField = "icdCode"; lstBillingICd10.DataBind(); ddEditLineICD10.DataSource = icd10Data; ddEditLineICD10.DataTextField = "CodeDescription"; ddEditLineICD10.DataValueField = "icdCode"; ddEditLineICD10.DataBind(); ddEditLineICD10.Items.Insert(0, new ListItem("select a code..", "0")); lstEditLineICD10.DataSource = icd10Data; lstEditLineICD10.DataTextField = "CodeDescription"; lstEditLineICD10.DataValueField = "icdCode"; lstEditLineICD10.DataBind(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Bind Billing Lines /// private void BindBillingLines() { ArrayList billings = new ArrayList(); try { if (utils.verifySession("billingLines")) { billings = (ArrayList)Session["billingLines"]; //handle 0005 Modifiers ApplyModifier5toBillings(ref billings); Session["billingLines"] = billings; } Session["bal"] = 0; rptBillingAccounts.DataSource = billings; if (billings.Count > 0) { ViewState["dateOfService"] = ((oAccount)billings[0]).dateOfService; } rptBillingAccounts.DataBind(); //upBillingAccounts.Update(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } //setup modified line values private void SetupModifedLine(ref oAccount billing) { //handle quantity after modifications if (billing.qty > 1) { billing.amount = billing.amount * billing.qty; } //default to scheme liable billing.liableMed = billing.amount; billing.liablePat = 0; //now check the trf the account is on to determine the liability foreach (oTariffPlan pln in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffPlan), "code", billing.planCode)) { if (pln.liableIndicator == 0) { billing.liableMed = billing.amount; billing.liablePat = 0; } else { billing.liableMed = 0; billing.liablePat = billing.amount; } } if (billing.allocated > 0)//we need to undo allocations then { //get payment references and remove billing reference string[] references = billing.allocatedReference.Split(char.Parse(",")); foreach (string rf in references) { int payId = 0; if (rf.Contains(":")) { int.TryParse(rf.Substring(0, rf.IndexOf(":")), out payId); } else { int.TryParse(rf, out payId); } if (payId > 0) {//get associated payment foreach (oAccount payLine in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", payId.ToString())) { //get the billing references and remove this billing rec id string[] billRefs = payLine.allocatedReference.Split(char.Parse(",")); payLine.allocatedReference = String.Empty; foreach (string billRef in billRefs) { int bId = 0; if (billRef.Contains(":")) { int.TryParse(billRef.Substring(0, billRef.IndexOf(":")), out bId); } else { int.TryParse(billRef, out bId); } if (bId > 0) { if (bId != billing.recId) { if (payLine.allocatedReference == String.Empty) { payLine.allocatedReference = bId.ToString(); } else { payLine.allocatedReference += "," + bId.ToString(); } } } } //update payment line xData.UpdateTyped("recId", payLine.recId.ToString(), typeof(oAccount), payLine); } } } billing.allocated = 0; billing.allocatedReference = ""; //if (billing.recId > 0)//edit of billings already existing //{ // //update billing line // xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oAccount), billing); //} } } /// /// Apply Modifier 5 rule on billings /// /// private void ApplyModifier5toBillings(ref ArrayList billings) { try { if (billings.Count > 0) { ArrayList modifiedBillings = new ArrayList(); List modList = new List(); if (utils.verifySession("modList")) modList = (List)Session["modList"]; modList.Sort(); if (modList.Any(r => r.Substring(0, 4) == "0005")) //we have a 0005 now apply logic to modifify each record { //ensure sequences for billings to get order back after applying mofications int seqCounter = 0; foreach (oAccount billing in billings) { seqCounter++; billing.sequence = seqCounter; } DataTable bt = new DataTable(); bt = utils.ConvertListToDataTable(billings); //sort by expensive first DataView dv = bt.DefaultView; dv.Sort = "unitFee DESC"; DataTable sortedTable = dv.ToTable(); ArrayList sortedBillings = utils.ConvertDataTableToList(sortedTable, typeof(oAccount)); int billCounter = 0; foreach (oAccount billing in sortedBillings) { if (billing.modifier1 == String.Empty)//exclude modifiers in the initial counter { foreach (oMedicalProcedure proc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "code", billing.procedureCode)) { decimal modifier = 0; decimal modAmount = 0; if (proc.codeType == 0 && !proc.nonSurgical)//verify if not a non surgical procedure and consumable , only modifier 5 can be applied to surgical procedures { billing.modifier4 = "0005"; billCounter++; switch (billCounter) { case 1: //100% modifier = 100; break; case 2: //75% modifier = 75; break; case 3: //50% modifier = 50; break; default: //25% modifier = 25; break; } } else { billing.modifier4 = String.Empty; modifier = 100; } modAmount = (billing.unitFee * ((modifier - 100) / 100)); billing.amount = billing.unitFee + modAmount; oAccount bill = (oAccount)utils.CloneObject(billing); SetupModifedLine(ref bill); modifiedBillings.Add(bill); //check for any modified instances of this line foreach (oAccount possibleMod in sortedBillings) { if (possibleMod.procedureCode == billing.procedureCode && possibleMod.modifier1 != String.Empty) { //apply any modifications on orginal line if (possibleMod.modifier1 == "0011" && possibleMod.modifier2 != String.Empty) { decimal RVU = 16.998M; decimal modMinutes = Convert.ToDecimal(possibleMod.modifier2); modAmount = (modMinutes / 30) * (12 * RVU); possibleMod.amount = modAmount; } else { foreach (oMedicalProcedure modProc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "code", possibleMod.modifier1)) { if (modProc.modifier > 0) { modAmount = (billing.amount * ((modProc.modifier - 100) / 100)); possibleMod.amount = billing.amount + modAmount; } } } oAccount billMod = (oAccount)utils.CloneObject(possibleMod); SetupModifedLine(ref billMod); modifiedBillings.Add(billMod); } } } } } if (modifiedBillings.Count > 0) { //sort back to sequence order bt = new DataTable(); bt = utils.ConvertListToDataTable(modifiedBillings); //sort by expensive first dv = bt.DefaultView; dv.Sort = "sequence"; sortedTable = dv.ToTable(); //cast back to billings ArrayList billings = utils.ConvertDataTableToList(sortedTable, typeof(oAccount)); } } } } catch (Exception ex) { exception.HandleException("canvas:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Bind User Types /// private void BindBillingsToAllocate() { try { if (this.Account != null) { oAccount acc = this.Account; ArrayList billingsTemp = xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "surfaceItemId,isVisible", acc.surfaceItemId.ToString() + ",1", "dateOfService,sequence"); ArrayList billings = new ArrayList(); foreach (oAccount bill in billingsTemp) { if (bill.amount > 0 && bill.amount > bill.allocated) { if (bill.procedureType == "TI") { bill.procedureDescription = "d:" + bill.dateOfService.ToString("dd/MM/yyyy") + "-p:" + bill.procedureCode + "-m:" + bill.modifier1 + "- R" + utils.returnFormattedDecimal(Convert.ToString(bill.amount)); } if (bill.procedureType == "DJ") { bill.procedureDescription = "d:" + bill.dateOfService.ToString("dd/MM/yyyy") + "-p:" + bill.procedureCode + "- R" + utils.returnFormattedDecimal(Convert.ToString(bill.amount)); } billings.Add(bill); } } lstBillings.DataSource = billings; lstBillings.DataTextField = "procedureDescription"; lstBillings.DataValueField = "recId"; lstBillings.DataBind(); } } catch (Exception ex) { exception.HandleException("canvas:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Bind User Types /// private void BindAssistedBillingsToAllocate() { try { if (this.Account != null) { oAccount acc = this.Account; //CVH 2016-11-17 Get list of practices, need to subtract vat if the practice is setup to pay assistants ex vat ArrayList practices = xData.GetTypedCollection("recId", typeof(oMedicalPractice)); oSetup setup = handler.ReturnSetup(); ArrayList billingsTemp = xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "surfaceItemId,isVisible", acc.surfaceItemId.ToString() + ",1", "dateOfService,sequence"); ArrayList billings = new ArrayList(); foreach (oAccount bill in billingsTemp) { oMedicalPractice practice = new oMedicalPractice(); foreach (oMedicalPractice prac in practices) { if (prac.recId == bill.practiceNo) practice = prac; } decimal amount = bill.amount; decimal allocated = bill.allocatedAssist; if (setup.vatRegistered && practice.isAstPaymentExVat) { amount = bill.amount / ((100m + bill.vatRate) / 100m); allocated = bill.allocatedAssist / ((100m + bill.vatRate) / 100m); } //if (bill.amount > 0 && bill.amount > bill.allocatedAssist && bill.procedureType == "TI" && (bill.modifier1 == "0008" || bill.modifier1 == "0009")) if (amount > 0m && amount > allocated && bill.procedureType == "TI" && (bill.modifier1 == "0008" || bill.modifier1 == "0009")) { bill.procedureDescription = "d:" + bill.dateOfService.ToString("dd/MM/yyyy") + "-p:" + bill.procedureCode + "-m:" + bill.modifier1 + " " + bill.modifier3 + "- R" + utils.returnFormattedDecimal(Convert.ToString(amount)); billings.Add(bill); } } lstBillingsAssist.DataSource = billings; lstBillingsAssist.DataTextField = "procedureDescription"; lstBillingsAssist.DataValueField = "recId"; lstBillingsAssist.DataBind(); } } catch (Exception ex) { exception.HandleException("canvas:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Populate Form Values /// /// private void PopulatePageFormValues(ref oAccount _Account) { try { txtTitle.Value = _Account.title; txtInitials.Value = _Account.initials; txtName.Value = _Account.name; txtSurname.Value = _Account.surname; //calculate account balance _Account.runningBal = xData.GetAccountBalance(_Account.surfaceItemId); txtAccBalance.Value = utils.returnFormattedDecimal(Convert.ToString(_Account.runningBal)); if (utils.verifySession("loadType") && Session["loadType"].ToString() == "Redirected") lnkBack.Visible = true; else lnkBack.Visible = false; upAccounts.Update(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } private void SetMultiplePatient(oAccount acc) { try { ddlSwitch.Items.Clear(); foreach (oSurfaceItem item in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceItem), "recId", acc.surfaceItemId.ToString())) { if (item.userLink > 0) { foreach (oSurfaceItem linkedItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceItem), "userLink,isDeleted", item.userLink.ToString() + ",0")) { bool existingBilling = false; foreach (oAccount linkedAccount in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "surfaceItemId", linkedItem.recId.ToString())) { AddSwitchDropdownItem(linkedAccount); existingBilling = true; break; } if (!existingBilling) { if (ddlSwitch.Items.FindByValue(linkedItem.recId.ToString()) == null) { oAccount accWithoutBilling = xDebtors.SetAccountItem(linkedItem.recId, linkedItem.surfaceId, new oUser()); AddSwitchDropdownItem(accWithoutBilling); } } } } } divSwitch.Visible = ddlSwitch.Items.Count > 1; if (ddlSwitch.Items.FindByValue(acc.surfaceItemId.ToString()) == null) AddSwitchDropdownItem(acc); foreach (ListItem item in ddlSwitch.Items) { if (item.Value == this.Account.surfaceItemId.ToString()) item.Selected = true; } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } private void SetMultiplePatientStatement(oAccount acc) { try { ddlStatementFor.Items.Clear(); foreach (oSurfaceItem item in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceItem), "recId", acc.surfaceItemId.ToString())) { foreach (oSurface surface in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "recId", item.surfaceId.ToString())) { if (surface.linkUser) { foreach (oSurfaceItem linkedItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceItem), "userLink", item.userLink.ToString())) { foreach (oAccount linkedAccount in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "surfaceItemId", linkedItem.recId.ToString())) { ListItem listItem = new ListItem(); listItem.Text = linkedAccount.patientName + " " + linkedAccount.patientSurname; listItem.Value = linkedAccount.surfaceItemId.ToString(); ddlStatementFor.Items.Add(listItem); break; } } } else { ListItem listItem = new ListItem(); listItem.Text = acc.patientName + " " + acc.patientSurname; listItem.Value = acc.surfaceItemId.ToString(); ddlStatementFor.Items.Add(listItem); } } } divStatementFor.Visible = ddlStatementFor.Items.Count > 1; foreach (ListItem item in ddlStatementFor.Items) { if (item.Value == this.Account.surfaceItemId.ToString()) item.Selected = true; } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } private void AddSwitchDropdownItem(oAccount linkedAccount) { try { ListItem item = new ListItem(); item.Text = linkedAccount.patientName + " " + linkedAccount.patientSurname; item.Value = linkedAccount.surfaceItemId.ToString(); ddlSwitch.Items.Add(item); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// Populate Form Values /// /// private void PopulateEditLineValues(ref oAccount _Account, bool isLocked = false) { try { pnlResultEditLine.Visible = false; txtEditLineDate.Value = _Account.dateOfService.ToString("dd/MM/yyyy"); txtEditLineCode.Text = _Account.procedureCode; if (ddEditLineDescription.Items.FindByValue(_Account.procedureCode) != null) { ddEditLineDescription.SelectedValue = _Account.procedureCode; //CVH 2016-09-30 Populate tendons drop down if applicable, and select tendon PopulateDiagnosisEdit(_Account.procedureCode); if (ddEditLineAdditionalDescription.Enabled) { string tendon = _Account.procedureDescription.Replace(ddEditLineDescription.SelectedItem.Text + " - ", ""); if (ddEditLineAdditionalDescription.Items.FindByText(tendon) != null) ddEditLineAdditionalDescription.Items.FindByText(tendon).Selected = true; } } if (_Account.doctorNo > 0) ddEditLineDoctor.SelectedValue = _Account.doctorNo.ToString(); //txtEditLineICD10.Value = _Account.icd1; if (ddEditLineICD10.Items.FindByValue(_Account.icd1) != null) ddEditLineICD10.SelectedValue = _Account.icd1; if (lstEditLineICD10.Items.FindByValue(_Account.icd2) != null) lstEditLineICD10.SelectedValue = _Account.icd2; txtEditLineExternalCause.Text = _Account.externalCause; if (txtEditLineExternalCause.Text != "") { divEditLineExternalCause.Visible = true; reqtxtEditLineExternalCause.Enabled = true; } txtEditLineAuthNo.Text = _Account.authorisationNo; txtEditLineRefDocName.Text = _Account.referringDoctor; txtEditLineRefDocNo.Text = _Account.referringDocNo; txtEditLineQty.Text = utils.returnFormattedDecimal(Convert.ToString(_Account.qty)); if (_Account.planCode != string.Empty) ddEditLineTariff.SelectedValue = _Account.planCode; txtEditLineUnitPrice.Text = utils.returnFormattedDecimal(Convert.ToString(_Account.unitFee)); string[] icd10s = _Account.icd2.Split(char.Parse(",")); foreach (string code in icd10s) { foreach (ListItem item in lstEditLineICD10.Items) { if (code == item.Value) { item.Selected = true; break; } } } if (_Account.placeOfService > 0) ddEditLineServiceSite.SelectedValue = _Account.placeOfService.ToString(); ddEditLineModifier.SelectedValue = _Account.modifier1; /* CVH 2016-05-06 Load edit text boxes based on modifier code txtEditLineModMinutes.Text = _Account.modifier2;//using modifier2 column as time entry if (ddEditLineModifier.SelectedValue == "0011") divEditModMinutes.Visible = true; else divEditModMinutes.Visible = false;*/ switch (_Account.modifier1) { case "0011": divEditModBMI.Visible = false; divEditModAssistant.Visible = false; divEditModMinutes.Visible = true; txtEditLineModMinutes.Text = _Account.modifier2; break; case "0018": divEditModBMI.Visible = true; divEditModAssistant.Visible = false; divEditModMinutes.Visible = false; txtEditModHeight.Text = _Account.modifier2; txtEditModWeight.Text = _Account.modifier3; break; case "0008": case "0009": BindAssistants(_Account.modifier1 == "0009" ? 1 : 2); txtEditModRegistration.Text = _Account.modifier2; txtEditModSurname.Text = _Account.modifier3; divEditModBMI.Visible = false; divEditModAssistant.Visible = true; divEditModMinutes.Visible = false; break; default: divEditModBMI.Visible = false; divEditModAssistant.Visible = false; divEditModMinutes.Visible = false; break; } CalculateAmountEditLine(false); if (isLocked) { ddEditLineDoctor.Enabled = false; txtEditLineCode.Enabled = false; ddEditLineDescription.Enabled = false; ddEditLineAdditionalDescription.Enabled = false; txtEditLineQty.Enabled = false; ddEditLineTariff.Enabled = false; ddEditLineServiceSite.Enabled = false; ddEditLineICD10.Enabled = false; lstEditLineICD10.Attributes.Add("disabled", ""); txtEditLineUnitPrice.Enabled = false; ddEditLineModifier.Enabled = false; txtEditLineModMinutes.Enabled = false; ddEditModAssistant.Enabled = false; txtEditModRegistration.Enabled = false; txtEditModSurname.Enabled = false; txtEditModHeight.Enabled = false; txtEditModWeight.Enabled = false; } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Populate Form Values /// /// private void SaveEditLineValues(ref oAccount _Account, ref DateTime changedDateOfService) { try { //get prcoedure oMedicalProcedure editProc = new oMedicalProcedure(); foreach (oMedicalProcedure proc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "code", txtEditLineCode.Text)) { editProc = proc; break; } //get tariff oTariffPlan editTariff = new oTariffPlan(); foreach (oTariffPlan trf in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffPlan), "code", ddEditLineTariff.SelectedValue)) { editTariff = trf; break; } //get doctor oMedicalDoctor editDoc = new oMedicalDoctor(); foreach (oMedicalDoctor doc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalDoctor), "recId", ddEditLineDoctor.SelectedValue)) { editDoc = doc; break; } if (editProc.code != String.Empty) { //procedure info _Account.procedureCode = editProc.code; _Account.procedureDescription = editProc.description; /* CVH 2016-09-30 Add tendon to description */ if (editProc.additionalDescription && ddEditLineAdditionalDescription.SelectedItem != null) _Account.procedureDescription += " - " + ddEditLineAdditionalDescription.SelectedItem.Text; _Account.consumableCode = editProc.consumableCode; _Account.procedureNAPPI = editProc.nappi + editProc.nappiSuffix; //icd10 _Account.icd1 = ddEditLineICD10.SelectedValue; _Account.icd2 = String.Empty; foreach (ListItem item in lstEditLineICD10.Items) { if (item.Selected) { if (_Account.icd2 == String.Empty) _Account.icd2 = item.Value; else _Account.icd2 += "," + item.Value; } } _Account.externalCause = txtEditLineExternalCause.Text; //Tax Invoice _Account.procedureType = "TI"; //quantity decimal qty = 0; decimal.TryParse(txtEditLineQty.Text, out qty); if (qty > 0) _Account.qty = qty; else _Account.qty = 1; //unit fee decimal unitFee = 0; decimal.TryParse(txtEditLineUnitPrice.Text, out unitFee); _Account.unitFee = unitFee; //modifier /* CVH 2016-05-06 Reset modifier fields */ _Account.modifier1 = ""; _Account.modifier2 = ""; _Account.modifier3 = ""; _Account.modifier4 = ""; if (ddEditLineModifier.SelectedValue != null) { if (ddEditLineModifier.SelectedValue == "0005") _Account.modifier4 = ddEditLineModifier.SelectedValue; else _Account.modifier1 = ddEditLineModifier.SelectedValue; /* CVH 2016-05-06 Save modifier values based on modifier code selected if (ddEditLineModifier.SelectedValue == "0011") _Account.modifier2 = txtEditLineModMinutes.Text;//using modifier2 column as time entry else _Account.modifier2 = ""; */ switch (_Account.modifier1) { case "0008": case "0009": _Account.modifier2 = utils.stripCharacters(txtEditModRegistration.Text.Trim()); _Account.modifier3 = txtEditModSurname.Text.Trim(); break; case "0011": _Account.modifier2 = txtEditLineModMinutes.Text; break; case "0018": _Account.modifier2 = txtEditModHeight.Text; _Account.modifier3 = txtEditModWeight.Text; break; } } //service date changedDateOfService = _Account.dateOfService = utils.formatStringToDate(txtEditLineDate.Value); //place of service if (ddEditLineServiceSite.SelectedValue != null && ddEditLineServiceSite.SelectedValue != String.Empty) _Account.placeOfService = int.Parse(ddEditLineServiceSite.SelectedValue); //TO DO Theses will be selectable from setup and billing screen _Account.vatRate = 14; _Account.serviceType = "T"; _Account.inHospital = false; _Account.category = 0; _Account.authorisationNo = txtEditLineAuthNo.Text; _Account.referringDocNo = txtEditLineRefDocNo.Text; _Account.referringDoctor = txtEditLineRefDocName.Text; //date of capture //JR we should NOT bedoing this on edit! //_Account.dateOfCapture = DateTime.Now; //amounts decimal amount = 0; decimal.TryParse(txtEditLineTotal.Value, out amount); //balance if (amount > _Account.amount)// amount greater than previous { //so lets increase the running balance by that differenc _Account.runningBal = _Account.runningBal += (amount - _Account.amount); } else if (amount < _Account.amount)//amount less than previous { //so lets decrease the balance by tat difference _Account.runningBal = _Account.runningBal -= (_Account.amount - amount); } _Account.amount = amount; //liabilities decimal patAmount = 0; decimal.TryParse(txtEditLineLiablePat.Text, out patAmount); _Account.liablePat = patAmount; _Account.liableMed = _Account.amount - _Account.liablePat; //plan code _Account.planCode = editTariff.code; //set claim activated flag _Account.claimSend = editTariff.claimActivated; //doctor _Account.doctor = editDoc.surname + ", " + editDoc.title + " " + editDoc.initials; _Account.doctorNo = editDoc.recId; //practice _Account.practiceNo = editDoc.practiceId; //check if invoiceNo should change _Account.invoiceNo = xData.GetInvoiceNo(_Account.dateOfService, _Account.surfaceItemId, _Account.placeOfService, _Account.icd1); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Method to Toggle Panels /// /// private void TogglePanels(string panelName) { switch (panelName) { case "pnlAccountPage": break; case "pnlAccountList": break; } //clear result pnlResult.Visible = false; } /// /// Post Billing Line /// /// private bool PostBillingLine() { bool result = false; ArrayList billings = new ArrayList(); try { if (this.Account != null) { oAccount acc = this.Account; if (utils.verifySession("billingLines")) { billings = (ArrayList)Session["billingLines"]; } //create a new billing oAccount accBilling = (oAccount)utils.CloneObject(acc); //get prcoedure oMedicalProcedure billingProc = new oMedicalProcedure(); foreach (oMedicalProcedure proc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "code", txtBillingCode.Text)) { if (proc.codeType == 3)//macro { string macroProcList = proc.macroProcedures; foreach (string macro in macroProcList.Split(',')) { string macroProc = macro.Split('|')[0]; string macroQty = macro.Split('|')[1]; string macroRate = macro.Split('|')[2]; foreach (oMedicalProcedure mProc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "recId", macroProc)) { accBilling = (oAccount)utils.CloneObject(acc); billingProc = new oMedicalProcedure(); billingProc = mProc; CreateNewBilling(ref result, ref billings, accBilling, billingProc, true, Convert.ToDecimal(macroQty), proc.useMacroRate, Convert.ToDecimal(macroRate)); } } } else { billingProc = proc; CreateNewBilling(ref result, ref billings, accBilling, billingProc); } break; } Session["billingLines"] = billings; } else { Response.Redirect("/home", false); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } return result; } private void CreateNewBilling(ref bool result, ref ArrayList billings, oAccount accBilling, oMedicalProcedure billingProc, bool isMacro = false, decimal qty = 1, bool useMacroRate = false, decimal macroItemRate = 0) { //get tariff oTariffPlan billingTariff = new oTariffPlan(); foreach (oTariffPlan trf in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffPlan), "code", ddBillingTariff.SelectedValue)) { billingTariff = trf; break; } //get doctor oMedicalDoctor billingDoc = new oMedicalDoctor(); foreach (oMedicalDoctor doc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalDoctor), "recId", ddBillingDoctor.SelectedValue)) { billingDoc = doc; break; } if (billingProc.code != String.Empty) { //procedure info accBilling.procedureCode = billingProc.code; accBilling.procedureDescription = billingProc.description; /* CVH 2016-09-30 Add tendon to description */ if (billingProc.additionalDescription && ddBillingAdditionalDescription.SelectedItem != null) accBilling.procedureDescription += " - " + ddBillingAdditionalDescription.SelectedItem.Text; accBilling.consumableCode = billingProc.consumableCode; accBilling.procedureNAPPI = billingProc.nappi + billingProc.nappiSuffix; //icd10 accBilling.icd1 = ddBillingICD10.SelectedValue; //apply allocations foreach (ListItem item in lstBillingICd10.Items) { if (item.Selected) { if (accBilling.icd2 == String.Empty) accBilling.icd2 = item.Value; else accBilling.icd2 += "," + item.Value; } } accBilling.externalCause = txtExternalCause.Text; //Tax Invoice accBilling.procedureType = "TI"; //quantity if (!isMacro) decimal.TryParse(txtBillingQty.Text, out qty); accBilling.qty = qty; //unit fee decimal unitFee = 0; if (!isMacro) { decimal.TryParse(txtBillingUnitPrice.Text, out unitFee); accBilling.unitFee = unitFee; } else { //get unit price if (useMacroRate) { accBilling.unitFee = macroItemRate; } else { foreach (oTariffRate rate in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffRate), "planCode,procedureCode", ddBillingTariff.SelectedValue + "," + billingProc.code)) { foreach (oPlaceOfService poc in xData.GetTypedByCriteriaSpecific("recId", typeof(oPlaceOfService), "indicator", ddPlaceOfservice.SelectedValue.ToString())) { if (rate.procedureCode == "C2" || rate.procedureCode == "3602") { unitFee = rate.rate; } else { if (poc.rateType == "IH") unitFee = rate.iHRate; if (poc.rateType == "OH") unitFee = rate.oHRate; } } accBilling.unitFee = unitFee; break; } } } //modifier - done seperately //if (ddBillingModifier.SelectedValue != null) // accBilling.modifier1 = ddBillingModifier.SelectedValue; DateTime serviceDate = accBilling.dateOfService = utils.formatStringToDate(txtBillingDate.Value); //place of service if (ddPlaceOfservice.SelectedValue != null && ddPlaceOfservice.SelectedValue != String.Empty) accBilling.placeOfService = int.Parse(ddPlaceOfservice.SelectedValue); //TO DO Theses will be selectable from setup and billing screen accBilling.vatRate = 14; accBilling.serviceType = "T"; accBilling.inHospital = false; accBilling.category = 0; accBilling.authorisationNo = txtAuthNo.Text; accBilling.referringDocNo = txtRefDocNo.Text; accBilling.referringDoctor = txtRefDocName.Text; //date of capture accBilling.dateOfCapture = DateTime.Now; //JR 2017-03-03 date of transaction accBilling.dateOfTransaction = DateTime.Now; //amounts decimal amount = 0; if (!isMacro) { decimal.TryParse(txtBillingTotal.Value, out amount); } else { amount = accBilling.unitFee * qty; } accBilling.amount = amount; //liabilities decimal patAmount = 0; if (!isMacro) { decimal.TryParse(txtBillingLiablePat.Text, out patAmount); accBilling.liablePat = patAmount; accBilling.liableMed = accBilling.amount - accBilling.liablePat; } else { if (billingTariff.liableIndicator == 0) { accBilling.liablePat = 0; accBilling.liableMed = amount; } else { accBilling.liablePat = amount; accBilling.liableMed = 0; } } //visible on statement accBilling.isVisible = true; //plan code accBilling.planCode = billingTariff.code; //set claim activated flag accBilling.claimSend = billingTariff.claimActivated; //sequence and invoice no is in finalise procedure decimal bal = 0; foreach (oAccount billBal in billings) { bal += billBal.amount; } //running balance accBilling.runningBal += accBilling.amount + bal; //doctor accBilling.doctor = billingDoc.surname + ", " + billingDoc.title + " " + billingDoc.initials; accBilling.doctorNo = billingDoc.recId; //practice accBilling.practiceNo = billingDoc.practiceId; billings.Add(accBilling); //to do modifier 0014 will be treated if (!billingProc.nonSurgical) { AddModifierLines(accBilling, ref billings); } //Session["billingLines"] = billings; result = true; } else { //invalid code pnlResultBilling.Visible = true; lblResultBilling.Text = "Please provide a valid code"; } } /// /// Add Modifier Lines /// /// /// private void AddModifierLines(oAccount accBilling, ref ArrayList billings) { List modList = new List(); if (utils.verifySession("modList")) modList = (List)Session["modList"]; modList.Sort(); string modEntry = "", mod = ""; decimal modMinutes = 0, totalAmount = accBilling.amount, modAmount = 0; ; int sequenceNo = accBilling.sequence; oAccount acc = (oAccount)utils.CloneObject(accBilling); /* Emergency procedure - every 30 mins should be equal to 12RVU's (1 RVU = 16.998, so R12RVU's = R2013.98) */ if (modList.Any(r => r.Substring(0, 4) == "0011")) { modEntry = modList.Single(r => r.Substring(0, 4) == "0011"); mod = modEntry.Split(';')[0]; if (mod.Length > 0) { if (modEntry.Contains(';')) { modMinutes = Convert.ToDecimal(modEntry.Split(';')[1]); } decimal RVU = 16.998M; modAmount = (modMinutes / 30) * (12 * RVU); acc = (oAccount)utils.CloneObject(accBilling); acc.modifier1 = mod; acc.modifier2 = modMinutes.ToString(); acc.amount = modAmount; //default to scheme liable acc.liableMed = modAmount; acc.liablePat = 0; //now check the trf the account is on to determine the liability foreach (oTariffPlan pln in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffPlan), "code", accBilling.planCode)) { if (pln.liableIndicator == 0) { acc.liableMed = modAmount; acc.liablePat = 0; } else { acc.liableMed = 0; acc.liablePat = modAmount; } } sequenceNo++; acc.sequence = sequenceNo; totalAmount += acc.amount; billings.Add(acc); } } /* Obese patient - All operational procedures should be 50% more */ if (modList.Any(r => r.Substring(0, 4) == "0018")) { modEntry = modList.Single(r => r.Substring(0, 4) == "0018"); mod = modEntry.Split(';')[0]; string modHeight = modEntry.Split(';')[1]; string modWeight = modEntry.Split(';')[2]; if (mod.Length > 0) { acc = (oAccount)utils.CloneObject(accBilling); acc.modifier1 = mod; acc.modifier2 = modHeight; acc.modifier3 = modWeight; foreach (oMedicalProcedure proc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "code", mod)) { if (proc.modifier > 0) { modAmount = (accBilling.amount * ((proc.modifier - 100) / 100)); } } acc.amount = accBilling.amount + modAmount; //default to scheme liable acc.liableMed = accBilling.amount + modAmount; acc.liablePat = 0; //now check the trf the account is on to determine the liability foreach (oTariffPlan pln in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffPlan), "code", accBilling.planCode)) { if (pln.liableIndicator == 0) { acc.liableMed = accBilling.amount + modAmount; acc.liablePat = 0; } else { acc.liableMed = 0; acc.liablePat = accBilling.amount + modAmount; } } sequenceNo++; acc.sequence = sequenceNo; totalAmount += acc.amount; billings.Add(acc); } } /* Specialist Assistant = 33.3% of the procedure costs the Specialist was involved in */ if (modList.Any(r => r.Substring(0, 4) == "0008")) { modEntry = modList.Single(r => r.Substring(0, 4) == "0008"); mod = modEntry.Split(';')[0]; string modAssistReg = modEntry.Split(';')[1]; string modAssistSur = modEntry.Split(';')[2]; if (mod.Length > 0) { acc = (oAccount)utils.CloneObject(accBilling); acc.modifier1 = mod; acc.modifier2 = modAssistReg; acc.modifier3 = modAssistSur; foreach (oMedicalProcedure proc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "code", mod)) { if (proc.modifier > 0) { modAmount = (totalAmount * ((proc.modifier - 100) / 100)); } } acc.amount = totalAmount + modAmount; //default to scheme liable acc.liableMed = totalAmount + modAmount; acc.liablePat = 0; //now check the trf the account is on to determine the liability foreach (oTariffPlan pln in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffPlan), "code", accBilling.planCode)) { if (pln.liableIndicator == 0) { acc.liableMed = totalAmount + modAmount; acc.liablePat = 0; } else { acc.liableMed = 0; acc.liablePat = totalAmount + modAmount; } } sequenceNo++; acc.sequence = sequenceNo; billings.Add(acc); } } /* Assistant = 20% of the procedure costs that the Assistant was involved in */ if (modList.Any(r => r.Substring(0, 4) == "0009")) { modEntry = modList.Single(r => r.Substring(0, 4) == "0009"); mod = modEntry.Split(';')[0]; string modAssistReg = modEntry.Split(';')[1]; string modAssistSur = modEntry.Split(';')[2]; if (mod.Length > 0) { acc = (oAccount)utils.CloneObject(accBilling); acc.modifier1 = mod; acc.modifier2 = modAssistReg; acc.modifier3 = modAssistSur; foreach (oMedicalProcedure proc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "code", mod)) { if (proc.modifier > 0) { modAmount = (totalAmount * ((proc.modifier - 100) / 100)); } } acc.amount = totalAmount + modAmount; //default to scheme liable acc.liableMed = totalAmount + modAmount; acc.liablePat = 0; //now check the trf the account is on to determine the liability foreach (oTariffPlan pln in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffPlan), "code", accBilling.planCode)) { if (pln.liableIndicator == 0) { acc.liableMed = totalAmount + modAmount; acc.liablePat = 0; } else { acc.liableMed = 0; acc.liablePat = totalAmount + modAmount; } } sequenceNo++; acc.sequence = sequenceNo; // billings.Add(acc); } } //0014 if (modList.Any(r => r.Substring(0, 4) == "0014")) { modEntry = modList.Single(r => r.Substring(0, 4) == "0014"); mod = modEntry.Split(';')[0]; if (mod.Length > 0) { acc = (oAccount)utils.CloneObject(accBilling); foreach (oMedicalProcedure proc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "code", mod)) { if (proc.modifier > 0) { modAmount = (acc.amount * proc.modifier / 100); } else { modAmount = 0; } } acc.modifier1 = mod; acc.amount = modAmount; //default to scheme liable acc.liableMed = modAmount; acc.liablePat = 0; sequenceNo++; acc.sequence = sequenceNo; billings.Add(acc); } } } /// /// Update all running totals for account /// /// private void UpdateRunningTotals(oAccount acc) { decimal bal = 0; foreach (oAccount account in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "surfaceItemId", acc.surfaceItemId.ToString(), "dateOfService,sequence")) { if (account.procedureType != "PA" && account.procedureType != "CA") { bal += account.amount; account.runningBal = bal; xData.UpdateTyped("recId", account.recId.ToString(), typeof(oAccount), account); } } } /// /// Reset all sequences in accounts to captured order /// - only use once - /// private void ResetSequences() { int seq = 0, surfID = 0; DateTime dateOfServ = utils.formatStringToDate("1900-01-01"); foreach (oAccount account in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "", "", "surfaceItemId,dateOfService,recId")) { if (surfID != account.surfaceItemId || dateOfServ != account.dateOfService) seq = 0; surfID = account.surfaceItemId; dateOfServ = account.dateOfService; seq++; account.sequence = seq; xData.UpdateTyped("recId", account.recId.ToString(), typeof(oAccount), account); } } /// /// bool to finalise a billing session /// /// private bool FinaliseBilling() { bool result = false; ArrayList billings = new ArrayList(); try { if (utils.verifySession("billingLines")) { billings = (ArrayList)Session["billingLines"]; //GR - Added the sequence to increment on each line int nextSequence = 0; int invNo = 0; bool mod5 = false; foreach (oAccount bill in billings) { if (nextSequence == 0) { invNo = xData.GetInvoiceNo(utils.formatStringToDate(txtBillingDate.Value), bill.surfaceItemId, bill.placeOfService, bill.icd1); bill.invoiceNo = invNo; nextSequence = xData.GetNextSequence(utils.formatStringToDate(txtBillingDate.Value), bill.surfaceItemId); bill.sequence = nextSequence; } else { bill.invoiceNo = invNo; nextSequence++; bill.sequence = nextSequence; } if (bill.modifier4 == "0005") mod5 = true; } xData.SaveTypedCollection("recId", typeof(oAccount), billings); ViewState["dateOfService"] = null; txtBillingDate.Value = String.Empty; txtBillingDate.Disabled = false; if (this.Account != null) { oAccount acc = this.Account; if (mod5) { //get lines for this invoice and apply modifier ArrayList billingsToModify = xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "surfaceItemId,invoiceNo,procedureType,isVisible", acc.surfaceItemId + "," + invNo + ",TI,1", "sequence"); ApplyModifier5toBillings(ref billingsToModify); foreach (oAccount billModified in billingsToModify) { xData.UpdateTyped("recId", billModified.recId.ToString(), typeof(oAccount), billModified); } } foreach (oCalendar cal in xData.GetTypedByCriteriaSpecific("recId", typeof(oCalendar), "billingModule,isActive", "1,1")) { foreach (oCalendarEvent calEv in xData.GetTypedByCriteriaContains("recId", typeof(oCalendarEvent), "users", acc.surfaceItemId.ToString())) { //only update appointments to billed if same date or earlier if (calEv.calendarId == cal.recId && !calEv.isBilled && calEv.start.Date <= utils.formatStringToDate(txtBillingDate.Value).Date) { calEv.isBilled = true; xData.UpdateTyped("recId", calEv.recId.ToString(), typeof(oCalendarEvent), calEv); } } } UpdateRunningTotals(acc); PopulatePageFormValues(ref acc); BindAccountData(acc); result = true; } else { Response.Redirect("/home", false); } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } return result; } /// /// Post Payment Line /// /// private bool PostPaymentLine() { bool result = false; oNote updateNote = new oNote(); updateNote.recId = 0; try { if (this.Account != null) { oAccount acc = this.Account; oAccount accPayment = new oAccount(); if (utils.verifySession("AllocPayment")) { //pick up payment for allocation accPayment = (oAccount)Session["AllocPayment"]; if (ddPaymentMethod.SelectedValue == "CRED") { accPayment.procedureDescription = accPayment.procedureDescription.Replace("Payment - ", "Credit - "); } } else { //create a new payment accPayment = (oAccount)utils.CloneObject(acc); //get doctor oMedicalDoctor paymentDoc = new oMedicalDoctor(); foreach (oMedicalDoctor doc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalDoctor), "recId", ddPaymentDoctor.SelectedValue)) { paymentDoc = doc; break; } if (ddPaymentMethod.SelectedValue != null && ddPaymentMethod.SelectedValue != String.Empty) { //unit fee decimal unitFee = 0; decimal.TryParse(txtPaymentAmount.Value, out unitFee); txtPaymentAmount.Value = utils.returnFormattedDecimal(Convert.ToString(unitFee)); //procedure info accPayment.procedureCode = ddPaymentMethod.SelectedValue; string noteCaption = "A payment was receipted to the value of R " + utils.returnFormattedDecimal((unitFee * -1).ToString()); switch (ddPaymentMethod.SelectedValue) { case "CRED": accPayment.procedureDescription = "Credit - " + ddPaymentMethod.SelectedItem.Text; accPayment.procedureType = "CJ"; //amounts accPayment.amount = unitFee * -1; //receipt number accPayment.receiptNo = xData.GetNextRecNo(); noteCaption = "A credit note was captured to the value of R " + utils.returnFormattedDecimal((unitFee * -1).ToString()); break; case "DEB": accPayment.procedureDescription = "Debit - " + ddPaymentMethod.SelectedItem.Text; accPayment.procedureType = "DJ"; //amounts accPayment.amount = unitFee; //invoice number accPayment.invoiceNo = xData.GetNextInvNo(); noteCaption = "A debit note was captured to the value of R " + utils.returnFormattedDecimal((unitFee).ToString()); break; default: accPayment.procedureDescription = "Payment - " + ddPaymentMethod.SelectedItem.Text; accPayment.procedureType = "PM"; //amounts accPayment.amount = unitFee * -1; //receipt number accPayment.receiptNo = xData.GetNextRecNo(); break; } accPayment.qty = 1; //service date accPayment.dateOfService = utils.formatStringToDate(txtPaymentDate.Value); //TO DO Theses will be selectable from setup and billing screen accPayment.vatRate = 14; accPayment.serviceType = "T"; accPayment.placeOfService = 11; accPayment.inHospital = false; accPayment.category = 0; accPayment.authorisationNo = ""; accPayment.referringDocNo = ""; accPayment.referringDoctor = ""; //date of capture accPayment.dateOfCapture = DateTime.Now; //JR 2017-03-03 date of transaction accPayment.dateOfTransaction = accPayment.dateOfService; //liabilities accPayment.liablePat = 0; accPayment.liableMed = 0; //visible on statement accPayment.isVisible = true; //plan code accPayment.planCode = ""; //running balance accPayment.runningBal += accPayment.amount; //set sequence on payment accPayment.sequence = xData.GetNextSequence(utils.formatStringToDate(txtPaymentDate.Value), accPayment.surfaceItemId); //doctor accPayment.doctor = paymentDoc.surname + ", " + paymentDoc.title + " " + paymentDoc.initials; accPayment.doctorNo = paymentDoc.recId; //practice accPayment.practiceNo = paymentDoc.practiceId; accPayment.recId = xData.SaveTyped("recId", typeof(oAccount), accPayment); /* CVH 2016-04-20 Add new note of type "Payment" */ oNote note = new oNote(); note.moduleId = pNums.Module.Surface.GetHashCode(); note.typeId = pNums.NoteType.Payment.GetHashCode(); note.entityId = acc.surfaceItemId; note.title = accPayment.procedureDescription; note.caption = noteCaption; note.dateSaved = DateTime.Now; note.userIdSaved = ((oUser)(Session["user"])).recId; note.isActive = true; note.fieldName = this.NotesFieldName; note.recId = xData.SaveTyped("recId", typeof(oNote), note); updateNote = note; } else { //invalid code pnlResultPayment.Visible = true; lblResultPayment.Text = "Please provide a payment method"; } } if (accPayment.recId > 0) { bool billingsAllocated = false; decimal ToAllocate = Math.Abs(accPayment.amount); //apply allocations foreach (ListItem item in lstBillings.Items) { if (item.Selected && ToAllocate > 0) { int billingId = int.Parse(item.Value.ToString()); if (billingId > 0) { foreach (oAccount billing in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", billingId.ToString(), "dateOfService,sequence")) { accPayment.procedureDescription += " -" + billing.procedureCode; decimal availToAlloc = billing.amount - billing.allocated; if (availToAlloc == ToAllocate)//the amount is the same { billing.allocated = billing.amount; billing.liableMed = 0; billing.liablePat = 0; if (billing.allocatedReference == String.Empty) { billing.allocatedReference = accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); } else { billing.allocatedReference += "," + accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); } if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oAccount), billing)) { //update allocated reference to payment if (accPayment.allocatedReference == String.Empty) { accPayment.allocatedReference = billing.recId.ToString(); } else { accPayment.allocatedReference += "," + billing.recId.ToString() + ":" + Convert.ToString(availToAlloc); } ToAllocate = 0; } } else if (availToAlloc > ToAllocate)//then we want to partially allocate the billing { billing.allocated += ToAllocate; billing.liableMed = 0; billing.liablePat = billing.amount - billing.allocated; if (billing.allocatedReference == String.Empty) { billing.allocatedReference = accPayment.recId.ToString() + ":" + Convert.ToString(ToAllocate); } else { billing.allocatedReference += "," + accPayment.recId.ToString() + ":" + Convert.ToString(ToAllocate); } if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oAccount), billing)) { //update allocated reference to payment if (accPayment.allocatedReference == String.Empty) { accPayment.allocatedReference = billing.recId.ToString(); } else { accPayment.allocatedReference += "," + billing.recId.ToString(); } ToAllocate = 0; } } else if (ToAllocate > availToAlloc)//we have more to allcoate so will allocate in full and use left over for next billing { billing.allocated = billing.amount; billing.liableMed = 0; billing.liablePat = 0; if (billing.allocatedReference == String.Empty) { billing.allocatedReference = accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); } else { billing.allocatedReference += "," + accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); } if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oAccount), billing)) { //update allocated reference to payment if (accPayment.allocatedReference == String.Empty) { accPayment.allocatedReference = billing.recId.ToString(); } else { accPayment.allocatedReference += "," + billing.recId.ToString(); } ToAllocate -= availToAlloc;//deduct from whats availabel to allocate } } } billingsAllocated = true; } } } if (ToAllocate > 0 && billingsAllocated)//then split payment to allow for allocation later { if (ddPaymentMethod.SelectedValue == "CRED") { accPayment.procedureType = "CJ"; } accPayment.amount = (Math.Abs(accPayment.amount) - ToAllocate) * -1; if (xData.UpdateTyped("recId", accPayment.recId.ToString(), typeof(oAccount), accPayment)) { //create a new payment oAccount accPaymentNew = (oAccount)utils.CloneObject(accPayment); accPaymentNew.recId = 0; accPaymentNew.allocatedReference = ""; accPaymentNew.amount = ToAllocate * -1; accPayment.sequence += 1; accPaymentNew.recId = xData.SaveTyped("recId", typeof(oAccount), accPaymentNew); /* CVH 2016-04-20 Add new note of type "Payment" */ oNote note = new oNote(); note.moduleId = pNums.Module.Surface.GetHashCode(); note.typeId = pNums.NoteType.Payment.GetHashCode(); note.entityId = acc.surfaceItemId; note.title = accPayment.procedureDescription; note.caption = "A payment was receipted to the value of R " + utils.returnFormattedDecimal((accPayment.amount * -1).ToString()); note.dateSaved = DateTime.Now; note.userIdSaved = ((oUser)(Session["user"])).recId; note.isActive = true; note.fieldName = this.NotesFieldName; note.recId = xData.SaveTyped("recId", typeof(oNote), note); } } else { if (xData.UpdateTyped("recId", accPayment.recId.ToString(), typeof(oAccount), accPayment)) { /* CVH 2016-05-03 Update the title of the note if the payment has been distributed to procedures */ //JR check if updateNote.recId >0 if (updateNote.recId > 0) { updateNote.caption = updateNote.caption + "
Procedures " + accPayment.procedureDescription.Replace(updateNote.title, ""); xData.UpdateTyped("recId", updateNote.recId.ToString(), typeof(oNote), updateNote); } } } result = true; utils.disposeSession("AllocPayment"); } } else { Response.Redirect("/home", false); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } return result; } /// /// Post Payment Assistant Line /// /// private bool PostPaymentAssistLine() { bool result = false; try { if (this.Account != null) { oAccount acc = this.Account; oAccount accPayment = new oAccount(); //get vat from company setup, but default to 14 if 0 oSetup setup = handler.ReturnSetup(); decimal setupVatRate = setup.vatRate; if (setup.vatRegistered && setupVatRate <= 0m) setupVatRate = 14m; if (utils.verifySession("AllocPaymentAssist")) { //pick up payment for allocation accPayment = (oAccount)Session["AllocPaymentAssist"]; if (ddPaymentMethod.SelectedValue == "CRED") { accPayment.procedureDescription = accPayment.procedureDescription.Replace("Assistant Payment - ", "Assistant Credit - "); } } else { //create a new payment accPayment = (oAccount)utils.CloneObject(acc); //get doctor oMedicalDoctor paymentDoc = new oMedicalDoctor(); foreach (oMedicalDoctor doc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalDoctor), "recId", ddPaymentAssistDoctor.SelectedValue)) { paymentDoc = doc; break; } //get practice oMedicalPractice paymentPrac = new oMedicalPractice(); foreach (oMedicalPractice prac in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalPractice), "recId", paymentDoc.practiceId.ToString())) { paymentPrac = prac; break; } if (ddPaymentAssistMethod.SelectedValue != null && ddPaymentAssistMethod.SelectedValue != String.Empty) { //procedure info accPayment.procedureCode = ddPaymentAssistMethod.SelectedValue; if (ddPaymentMethod.SelectedValue == "CRED") { accPayment.procedureDescription = "Assistant Credit - " + ddPaymentAssistMethod.SelectedItem.Text; } else { accPayment.procedureDescription = "Assistant Payment - " + ddPaymentAssistMethod.SelectedItem.Text; } //Payment accPayment.procedureType = "PA"; accPayment.qty = 1; //unit fee decimal unitFee = 0; decimal.TryParse(txtPaymentAssistAmount.Value, out unitFee); txtPaymentAssistAmount.Value = utils.returnFormattedDecimal(Convert.ToString(unitFee)); //service date accPayment.dateOfService = utils.formatStringToDate(txtPaymentAssistDate.Value); //TO DO Theses will be selectable from setup and billing screen //CVH 2016-11-17 Set payment vat rate, for it to calculate and show it ex vat in grid accPayment.vatRate = setupVatRate; accPayment.serviceType = "T"; accPayment.placeOfService = 11; accPayment.inHospital = false; accPayment.category = 0; accPayment.authorisationNo = ""; accPayment.referringDocNo = ""; accPayment.referringDoctor = ""; //date of capture accPayment.dateOfCapture = DateTime.Now; //JR 2017-03-03 date of transaction accPayment.dateOfTransaction = accPayment.dateOfService; //CVH 2016-11-17 If company is vat registered, and practice setup AST payments captured ex vat, add vat now, save Incl VAT //amounts if (setup.vatRegistered && paymentPrac.isAstPaymentExVat) accPayment.amount = Math.Round((unitFee * ((100m + setupVatRate) / 100m)) * -1m, 2); else accPayment.amount = unitFee * -1m; //liabilities accPayment.liablePat = 0; accPayment.liableMed = 0; //visible on statement accPayment.isVisible = true; //plan code accPayment.planCode = ""; //receipt number accPayment.receiptNo = 0; //running balance //accPayment.runningBal += accPayment.amount; //set sequence on payment accPayment.sequence = xData.GetNextSequence(utils.formatStringToDate(txtPaymentAssistDate.Value), accPayment.surfaceItemId); //doctor accPayment.doctor = paymentDoc.surname + ", " + paymentDoc.title + " " + paymentDoc.initials; accPayment.doctorNo = paymentDoc.recId; //practice accPayment.practiceNo = paymentDoc.practiceId; accPayment.recId = xData.SaveTyped("recId", typeof(oAccount), accPayment); } else { //invalid code pnlResultPaymentAssist.Visible = true; lblResultPaymentAssist.Text = "Please provide a payment method"; } } if (accPayment.recId > 0) { bool billingsAllocated = false; decimal ToAllocate = Math.Abs(accPayment.amount); //apply allocations foreach (ListItem item in lstBillingsAssist.Items) { if (item.Selected && ToAllocate > 0) { int billingId = int.Parse(item.Value.ToString()); if (billingId > 0) { foreach (oAccount billing in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", billingId.ToString(), "dateOfService,sequence")) { accPayment.procedureDescription += " -" + billing.procedureCode; decimal availToAlloc = billing.amount - billing.allocatedAssist; if (availToAlloc == ToAllocate)//the amount is the same { billing.allocatedAssist = billing.amount; if (billing.allocatedAssistReference == String.Empty) { billing.allocatedAssistReference = accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); } else { billing.allocatedAssistReference += "," + accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); } if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oAccount), billing)) { //update allocated reference to payment if (accPayment.allocatedAssistReference == String.Empty) { accPayment.allocatedAssistReference = billing.recId.ToString(); } else { accPayment.allocatedAssistReference += "," + billing.recId.ToString() + ":" + Convert.ToString(availToAlloc); } ToAllocate = 0; } } else if (availToAlloc > ToAllocate)//then we want to partially allocate the billing { billing.allocatedAssist += ToAllocate; if (billing.allocatedAssistReference == String.Empty) { billing.allocatedAssistReference = accPayment.recId.ToString() + ":" + Convert.ToString(ToAllocate); } else { billing.allocatedAssistReference += "," + accPayment.recId.ToString() + ":" + Convert.ToString(ToAllocate); } if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oAccount), billing)) { //update allocated reference to payment if (accPayment.allocatedAssistReference == String.Empty) { accPayment.allocatedAssistReference = billing.recId.ToString(); } else { accPayment.allocatedAssistReference += "," + billing.recId.ToString(); } ToAllocate = 0; } } else if (ToAllocate > availToAlloc)//we have more to allcoate so will allocate in full and use left over for next billing { billing.allocatedAssist = billing.amount; if (billing.allocatedAssistReference == String.Empty) { billing.allocatedAssistReference = accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); } else { billing.allocatedAssistReference += "," + accPayment.recId.ToString() + ":" + Convert.ToString(availToAlloc); } if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oAccount), billing)) { //update allocated reference to payment if (accPayment.allocatedAssistReference == String.Empty) { accPayment.allocatedAssistReference = billing.recId.ToString(); } else { accPayment.allocatedAssistReference += "," + billing.recId.ToString(); } ToAllocate -= availToAlloc;//deduct from whats availabel to allocate } } } billingsAllocated = true; } } } if (ToAllocate > 0 && billingsAllocated)//then split payment to allow for allocation later { if (ddPaymentAssistMethod.SelectedValue == "CRED") { accPayment.procedureType = "CA"; } accPayment.amount = (Math.Abs(accPayment.amount) - ToAllocate) * -1; if (xData.UpdateTyped("recId", accPayment.recId.ToString(), typeof(oAccount), accPayment)) { //create a new payment oAccount accPaymentNew = (oAccount)utils.CloneObject(accPayment); accPaymentNew.recId = 0; accPaymentNew.allocatedAssistReference = ""; accPaymentNew.amount = ToAllocate * -1; accPayment.sequence += 1; accPaymentNew.recId = xData.SaveTyped("recId", typeof(oAccount), accPaymentNew); } } else { if (xData.UpdateTyped("recId", accPayment.recId.ToString(), typeof(oAccount), accPayment)) { } } result = true; utils.disposeSession("AllocPaymentAssist"); } } else { Response.Redirect("/home", false); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } return result; } /// /// Calculate amount /// private void CalculateAmount(bool includeTrf) { decimal qty = 0; decimal.TryParse(txtBillingQty.Text, out qty); decimal unitFee = 0; //decimal modUnitFee = 0; //bool isModifier = false; if (includeTrf) { foreach (oTariffRate rate in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffRate), "planCode,procedureCode", ddBillingTariff.SelectedValue + "," + txtBillingCode.Text)) { foreach (oPlaceOfService poc in xData.GetTypedByCriteriaSpecific("recId", typeof(oPlaceOfService), "indicator", ddPlaceOfservice.SelectedValue.ToString())) { if (rate.procedureCode == "C2" || rate.procedureCode == "3602") { unitFee = rate.rate; } else { if (poc.rateType == "IH") unitFee = rate.iHRate; if (poc.rateType == "OH") unitFee = rate.oHRate; } } //unitFee = rate.rate; txtBillingUnitPrice.Text = utils.returnFormattedDecimal(Convert.ToString(unitFee)); //modUnitFee = rate.rate; break; } } else { decimal.TryParse(txtBillingUnitPrice.Text, out unitFee); //decimal.TryParse(txtBillingUnitPrice.Text, out modUnitFee); } decimal amount = 0; decimal modAmount = 0; //decimal modTotalAmount = 0; //check if modifier is being used if (ddBillingModifier.SelectedValue != null && ddBillingModifier.SelectedValue != "") { //apply mmodifier //isModifier = true; foreach (oMedicalProcedure mod in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "code", ddBillingModifier.SelectedValue)) { if (mod.modifier > 0) { //modAmount = (modUnitFee * ((mod.modifier - 100) / 100)); modAmount = (unitFee * ((mod.modifier - 100) / 100)); } } if (modAmount != 0) { //modUnitFee += modAmount; unitFee += modAmount; } } if (qty > 0) { amount = unitFee * qty; //if (isModifier) // modTotalAmount = modUnitFee * qty; } else { amount = unitFee; //if (isModifier) // modTotalAmount = modUnitFee; txtBillingQty.Text = "1"; } txtBillingTotal.Value = utils.returnFormattedDecimal(Convert.ToString(amount)); //if (isModifier) //txtBillingModifierTotal.Value = utils.returnFormattedDecimal(Convert.ToString(modTotalAmount)); //get tariff oTariffPlan billingTariff = new oTariffPlan(); foreach (oTariffPlan trf in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffPlan), "code", ddBillingTariff.SelectedValue)) { if (trf.liableIndicator == 0) { txtBillingLiableScheme.Text = utils.returnFormattedDecimal(Convert.ToString(amount)); txtBillingLiablePat.Text = utils.returnFormattedDecimal(Convert.ToString(0)); //txtBillingModifierLiableScheme.Text = utils.returnFormattedDecimal(Convert.ToString(modTotalAmount)); //txtBillingModifierLiablePat.Text = utils.returnFormattedDecimal(Convert.ToString(0)); } else { txtBillingLiableScheme.Text = utils.returnFormattedDecimal(Convert.ToString(0)); txtBillingLiablePat.Text = utils.returnFormattedDecimal(Convert.ToString(amount)); //txtBillingModifierLiableScheme.Text = utils.returnFormattedDecimal(Convert.ToString(0)); //txtBillingModifierLiablePat.Text = utils.returnFormattedDecimal(Convert.ToString(modTotalAmount)); } break; } //upBillingExtras.Update(); //upBillingAmounts.Update(); } /// /// Calculate amount /// private void CalculateAmountEditLine(bool includeTrf) { decimal qty = 0; decimal.TryParse(txtEditLineQty.Text, out qty); decimal unitFee = 0; if (includeTrf) { foreach (oTariffRate rate in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffRate), "planCode,procedureCode", ddEditLineTariff.SelectedValue + "," + txtEditLineCode.Text)) { foreach (oPlaceOfService poc in xData.GetTypedByCriteriaSpecific("recId", typeof(oPlaceOfService), "indicator", ddEditLineServiceSite.SelectedValue.ToString())) { if (rate.procedureCode == "C2" || rate.procedureCode == "3602") { unitFee = rate.rate; } else { if (poc.rateType == "IH") unitFee = rate.iHRate; if (poc.rateType == "OH") unitFee = rate.oHRate; } } //unitFee = rate.rate; txtEditLineUnitPrice.Text = utils.returnFormattedDecimal(Convert.ToString(unitFee)); break; } } else { decimal.TryParse(txtEditLineUnitPrice.Text, out unitFee); } decimal amount = 0; decimal modAmount = 0; //check if modifier is being used if (ddEditLineModifier.SelectedValue != null && ddEditLineModifier.SelectedValue != "") { //apply mmodifier if (ddEditLineModifier.SelectedValue == "0011") { decimal RVU = 16.998M; /* CVH 2016-05-06 Check for blank string */ //unitFee = (Convert.ToDecimal(txtEditLineModMinutes.Text) / 30) * (12 * RVU); unitFee = (Convert.ToDecimal(txtEditLineModMinutes.Text == "" ? "0" : txtEditLineModMinutes.Text) / 30) * (12 * RVU); } else { foreach (oMedicalProcedure mod in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "code", ddEditLineModifier.SelectedValue)) { if (mod.modifier > 0) { modAmount = (unitFee * ((mod.modifier - 100) / 100)); } } } if (modAmount != 0) { unitFee += modAmount; } } if (qty > 0) { amount = unitFee * qty; } else { amount = unitFee; txtEditLineQty.Text = "1"; } txtEditLineTotal.Value = utils.returnFormattedDecimal(Convert.ToString(amount)); //get tariff oTariffPlan billingTariff = new oTariffPlan(); foreach (oTariffPlan trf in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffPlan), "code", ddEditLineTariff.SelectedValue)) { if (trf.liableIndicator == 0) { txtEditLineLiableScheme.Text = utils.returnFormattedDecimal(Convert.ToString(amount)); txtEditLineLiablePat.Text = utils.returnFormattedDecimal(Convert.ToString(0)); } else { txtEditLineLiableScheme.Text = utils.returnFormattedDecimal(Convert.ToString(0)); txtEditLineLiablePat.Text = utils.returnFormattedDecimal(Convert.ToString(amount)); } break; } //upBillingExtras.Update(); //upBillingAmounts.Update(); } /// /// Calculate amount /// private void PopulateDiagnosisNew(string code) { try { foreach (oMedicalProcedure feeCode in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "code", code)) { /* CVH 2016-09-30 Load tendons */ ddBillingAdditionalDescription.ClearSelection(); ddBillingAdditionalDescription.Enabled = false; ddBillingAdditionalDescription.Items.Clear(); divNonMacro.Visible = feeCode.codeType != 3;//marcro if (feeCode.additionalDescription) { ddBillingAdditionalDescription.Enabled = true; int count = 0; DataTable dt = new DataTable(); dt.Columns.Add("Text"); dt.Columns.Add("Value"); DataRow rowNA = dt.NewRow(); rowNA["Text"] = "Select"; rowNA["Value"] = count; dt.Rows.Add(rowNA); foreach (string tendon in feeCode.additionalDescriptionOptions.Split('~')) { count++; DataRow row = dt.NewRow(); row["Text"] = tendon; row["Value"] = count; dt.Rows.Add(row); } ddBillingAdditionalDescription.DataSource = dt; ddBillingAdditionalDescription.DataTextField = "Text"; ddBillingAdditionalDescription.DataValueField = "Value"; ddBillingAdditionalDescription.DataBind(); } if (feeCode.icd1 != String.Empty) { if (ddEditLineICD10.Items.FindByValue(feeCode.icd1) != null) ddEditLineICD10.SelectedValue = feeCode.icd1; break; } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Calculate amount /// private void PopulateDiagnosisEdit(string code) { try { foreach (oMedicalProcedure feeCode in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "code", code)) { /* CVH 2016-09-30 Load tendons */ ddEditLineAdditionalDescription.ClearSelection(); ddEditLineAdditionalDescription.Enabled = false; ddEditLineAdditionalDescription.Items.Clear(); if (feeCode.codeType == 3)//macro { } if (feeCode.additionalDescription) { ddEditLineAdditionalDescription.Enabled = true; int count = 0; DataTable dt = new DataTable(); dt.Columns.Add("Text"); dt.Columns.Add("Value"); DataRow rowNA = dt.NewRow(); rowNA["Text"] = "Select"; rowNA["Value"] = count; dt.Rows.Add(rowNA); foreach (string tendon in feeCode.additionalDescriptionOptions.Split('~')) { count++; DataRow row = dt.NewRow(); row["Text"] = tendon; row["Value"] = count; dt.Rows.Add(row); } ddEditLineAdditionalDescription.DataSource = dt; ddEditLineAdditionalDescription.DataTextField = "Text"; ddEditLineAdditionalDescription.DataValueField = "Value"; ddEditLineAdditionalDescription.DataBind(); } if (feeCode.icd1 != String.Empty) { if (ddEditLineICD10.Items.FindByValue(feeCode.icd1) != null) ddEditLineICD10.SelectedValue = feeCode.icd1; break; } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Method to create a test account /// private void CreateTestAccount() { oUser usr = new oUser(); if (utils.verifySession("user")) { usr = (oUser)Session["user"]; } oAccount account = new oAccount(); account.surfaceItemId = 1; account.name = "Graham"; account.surname = "Rook"; account.title = "Mr"; account.initials = "GM"; account.idNumber = "8001295098081"; account.birthDate = new DateTime(1980, 1, 29); account.patientCode = "01"; account.gender = "M"; account.planCode = "DISC"; account.medCode = "DISC"; account.userId = usr.recId; this.Account = account; } /// /// Clear Posting values /// private void ClearPostings() { try { if (ViewState["dateOfService"] != null) { txtBillingDate.Value = ((DateTime)ViewState["dateOfService"]).ToString("dd/MM/yyyy"); txtBillingDate.Disabled = true; } else { txtBillingDate.Value = String.Empty; txtBillingDate.Disabled = false; } txtBillingCode.Text = String.Empty; BindFeesNew("", ""); txtBillingQty.Text = "1"; txtBillingUnitPrice.Text = "0.00"; txtBillingTotal.Value = "0.00"; txtBillingLiablePat.Text = "0.00"; txtBillingLiableScheme.Text = "0.00"; ddBillingModifier.SelectedValue = ""; List modList = new List(); if (utils.verifySession("modList")) modList = (List)Session["modList"]; List newmodList = new List(); foreach (string mod in modList) { if (mod.Length > 3) { if (mod.Substring(0, 4) != "0011") { newmodList.Add(mod); } } } if (newmodList.Count > 0) { Session["modList"] = newmodList; } else { Session["modList"] = null; } BindModList(); btnMods.Enabled = false; } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Bind the modifier repeater /// private void BindModList() { List modList = new List(); if (utils.verifySession("modList")) modList = (List)Session["modList"]; rptModifier.DataSource = modList; rptModifier.DataBind(); } private void AddClaimNote(int noteEntityId, string noteTitle, string noteCaption) { try { oNote note = new oNote(); note.moduleId = pNums.Module.Surface.GetHashCode(); note.typeId = pNums.NoteType.Claim.GetHashCode(); note.entityId = noteEntityId; note.title = noteTitle; note.caption = noteCaption; note.dateSaved = DateTime.Now; note.userIdSaved = ((oUser)(Session["user"])).recId; note.isActive = true; note.fieldName = this.NotesFieldName; note.recId = xData.SaveTyped("recId", typeof(oNote), note); } catch (Exception ex) { //log don't redirect exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); } } /// /// Check if credit notes are allowed /// /// private bool AllowCreditNotes() { bool returnValue = false; try { if (utils.verifySession("user")) { oUser user = (oUser)Session["user"]; foreach (oUserAccess userAccess in xData.GetTypedByCriteriaSpecific("recId", typeof(oUserAccess), "userId", user.recId.ToString())) { if (userAccess.allowCredit) { returnValue = true; } } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } return returnValue; } #endregion #region events /// /// Page Load Event /// /// /// protected void Page_Load(object sender, EventArgs e) { try { if (utils.verifySession("account")) this.Account = (oAccount)Session["account"]; else { return; } oAccount acc = this.Account; // PopulatePageFormValues(ref acc); if (!Page.IsPostBack) { if (utils.verifySession("noteSurfaceFieldName")) { this.NotesFieldName = Session["noteSurfaceFieldName"].ToString(); utils.disposeSession("noteSurfaceFieldName"); } SetMultiplePatient(acc); SetupControl(acc); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } private void SetupControl(oAccount acc) { //clear sessions for billings and payments Session["billingLines"] = null; Session["modList"] = null; Session["AllocPayment"] = null; txtPaymentDate.Disabled = false; ddPaymentDoctor.Enabled = true; ddPaymentMethod.Enabled = true; txtPaymentAmount.Disabled = false; UpdateAccountDataFromProfile(acc); BindAccountData(acc); BindTariffs(acc); //bind fees BindFeesNew("", ""); BindFeesEdit("", ""); BindModifiers(); BindDoctors(); BindServiceSites(); BindICD10s(); //txtBillingDate.Value = DateTime.Now.ToString("dd/MM/yyyy"); txtPaymentDate.Value = DateTime.Now.ToString("dd/MM/yyyy"); txtPaymentAssistDate.Value = DateTime.Now.ToString("dd/MM/yyyy"); txtStatementDate.Value = DateTime.Now.ToString("dd/MM/yyyy"); txtStatementDateFrom.Value = GetFirstDateForStatement(); txtStatementDateTo.Value = DateTime.Now.ToString("dd/MM/yyyy"); //GR Ugly hardcoded check here to include Credit option on the payment modal, //I must find a better solution to this as this one sux!! //JR - created table UserAccess to define credit access if (utils.verifySession("user")) { //JR set visibility on actions so users can see their history. oUser user = (oUser)Session["user"]; //if (user.userType == pNums.UserType.PowerUser.GetHashCode()) if ((user.userType >= (int)pNums.UserType.PowerUser && user.userType != (int)pNums.UserType.CustomUser) || (user.mimicUserType >= (int)pNums.UserType.PowerUser && user.userType == (int)pNums.UserType.CustomUser)) divActions.Visible = true; else divActions.Visible = false; foreach (oUserAccess userAccess in xData.GetTypedByCriteriaSpecific("recId", typeof(oUserAccess), "userId", user.recId.ToString())) { if (!userAccess.allowCredit) { ddTransactionType.Items.Remove(ddTransactionType.Items.FindByText("Journal")); } } //switch (user.recId) //{ // case 15://Christelle // creditAllowed = true; // break; // case 2://Graham // creditAllowed = true; // break; // case 3://Jas // creditAllowed = true; // break; // case 17://Alison // creditAllowed = true; // break; // case 39://Kyle // creditAllowed = true; // break; //} } } private string GetFirstDateForStatement() { DateTime dtFirstDate = DateTime.Now; foreach (oAccount accountItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "surfaceItemId", this.Account.surfaceItemId.ToString(), "dateOfService")) { dtFirstDate = accountItem.dateOfService; break; } return dtFirstDate.ToString("dd/MM/yyyy"); } /// /// Update unclaimed account item from patient profile /// /// private void UpdateAccountDataFromProfile(oAccount acc) { bool changeAccount = false; foreach (oAccount accountItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "surfaceItemId,isVisible,claimSend", acc.surfaceItemId.ToString() + ",1,1")) { changeAccount = true; if (accountItem.claimSent) { foreach (oMSClaimResponse response in xData.GetTypedByCriteriaSpecific("recId", typeof(oMSClaimResponse), "claimRefNo", accountItem.invoiceNo.ToString(), "recId DESC")) { if (response.respondingParty == "02" || response.msDeliveryTypeInd == "03") changeAccount = false; break; } } if (changeAccount) { accountItem.title = acc.title; accountItem.name = acc.name; accountItem.surname = acc.surname; accountItem.initials = acc.initials; accountItem.idNumber = acc.idNumber; accountItem.gender = acc.gender; accountItem.postalAddress = acc.postalAddress; accountItem.birthDate = acc.birthDate; accountItem.email = acc.email; accountItem.patientNumber = acc.patientNumber; accountItem.patientTitle = acc.patientTitle; accountItem.patientName = acc.patientName; accountItem.patientSurname = acc.patientSurname; accountItem.patientInitials = acc.patientInitials; accountItem.medAidNumber = acc.medAidNumber; accountItem.patientCode = acc.patientCode; accountItem.medCode = acc.medCode; accountItem.medAidName = acc.medAidName; accountItem.iodEmployerName = acc.iodEmployerName; accountItem.iodEmployerRegNo = acc.iodEmployerRegNo; accountItem.iodEmployeeNo = acc.iodEmployeeNo; accountItem.isIOD = acc.isIOD; accountItem.iodRefNo = acc.iodRefNo; accountItem.iodDate = acc.iodDate; xData.UpdateTyped("recId", accountItem.recId.ToString(), typeof(oAccount), accountItem); } } } #region menu events /// /// Click event to perform a new billing /// /// /// protected void btnNewBilling_Click(object sender, EventArgs e) { try { BindBillingLines(); ArrayList billingNotes = new ArrayList(); if (this.Account != null) { oAccount acc = this.Account; foreach (oAccount accountItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "surfaceItemId", acc.surfaceItemId.ToString(), "recId DESC")) { if (accountItem.referringDocNo != "0" && accountItem.referringDocNo != string.Empty) { txtRefDocNo.Text = accountItem.referringDocNo; txtRefDocName.Text = accountItem.referringDoctor; break; } } billingNotes = xData.GetTypedByCriteriaSpecific("recId", typeof(oNote), "moduleId,entityId,typeId", (int)pNums.Module.Calendar + "," + acc.surfaceItemId + "," + (int)pNums.NoteType.Billing, "recId DESC"); foreach (oNote billNote in billingNotes) { lblBillingNote.Text = billNote.caption; upBillingNote.Update(); break; } } txtBillingCode.Focus(); pnlResultBilling.Visible = false; ViewState["dateOfService"] = null; txtBillingDate.Value = String.Empty; txtBillingDate.Disabled = false; ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myBillingModal", "$('#modBilling').modal();", true); if (billingNotes.Count > 0) { ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myBillingNoteModal", "$('#modBillingNote').modal();", true); } ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "billingPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true); upBilling.Update(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// New Payment /// /// /// protected void lnkNewPayment_Click(object sender, EventArgs e) { try { BindBillingsToAllocate(); BindTransactionTypes(); if (ddTransactionType.Items.FindByText("Payment") != null) ddTransactionType.SelectedIndex = ddTransactionType.Items.IndexOf(ddTransactionType.Items.FindByText("Payment")); BindPaymentMethods(ddTransactionType.SelectedValue); ddPaymentMethod.Focus(); pnlResultPayment.Visible = false; txtPaymentAmount.Value = ""; Session["AllocPayment"] = null; txtPaymentDate.Disabled = false; ddPaymentDoctor.Enabled = true; ddPaymentMethod.Enabled = true; txtPaymentAmount.Disabled = false; btnTakePayment.Text = "Process Transaction"; lblPaymentHeading.Text = "New Transaction"; txtPaymentBalance.Text = utils.returnFormattedDecimal(Convert.ToString(txtAccBalance.Value)); upPayment.Update(); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myPaymentModal", "$('#modPayment').modal();", true); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "paymentPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Create a Statement /// /// /// protected void lnkStatement_Click(object sender, EventArgs e) { try { lblEmailResultMedical.Text = ""; lblEmailResultPatient.Text = ""; lblEmailResultPractice.Text = ""; chkEmailPatient.Checked = false; chkEmailMedicalAid.Visible = true; chkEmailPractice.Visible = true; btnCreateStatement.Visible = true; SetMultiplePatientStatement(this.Account); upStatement.Update(); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myStatementModal", "$('#modStatement').modal();", true); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "statementPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } #endregion #region accounts events /// /// Toggle To Account History /// /// /// protected void lnkAccountHistory_Click(object sender, EventArgs e) { try { pnlAccountHistory.Visible = true; pnlAssistedBillings.Visible = false; upAccounts.Update(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Toggle To Assisted Billings /// /// /// protected void lnkAssistedBillings_Click(object sender, EventArgs e) { try { pnlAccountHistory.Visible = false; pnlAssistedBillings.Visible = true; upAccounts.Update(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Item Databound Event /// /// /// protected void rptAccounts_ItemDataBound(object sender, RepeaterItemEventArgs e) { try { HiddenField hfType = e.Item.FindControl("hfType") as HiddenField; if (hfType != null) { //amount field Label lblAmount = (Label)e.Item.FindControl("lblAmount"); decimal amount = 0; decimal.TryParse(lblAmount.Text, out amount); //running balance decimal bal = 0; if (utils.verifySession("bal")) decimal.TryParse(Session["bal"].ToString(), out bal); Label lblRunBal = (Label)e.Item.FindControl("lblRunBal"); lblRunBal.Text = utils.returnFormattedDecimal(Convert.ToString(amount + bal)); Session["bal"] = amount + bal; //option links LinkButton lnkCreditNote = (LinkButton)e.Item.FindControl("lnkCreditNote"); LinkButton lnkReversal = (LinkButton)e.Item.FindControl("lnkReversal"); LinkButton lnkEditFinal = (LinkButton)e.Item.FindControl("lnkEditFinal"); LinkButton lnkAllocate = (LinkButton)e.Item.FindControl("lnkAllocate"); LinkButton lnkCopy = (LinkButton)e.Item.FindControl("lnkCopy"); Label lblLiablePatient = (Label)e.Item.FindControl("lblLiablePatient"); Label lblLiableScheme = (Label)e.Item.FindControl("lblLiableScheme"); Label lblAllocated = (Label)e.Item.FindControl("lblAllocated"); HiddenField hfAllocRef = e.Item.FindControl("hfAllocRef") as HiddenField; if (lnkCreditNote != null && lnkReversal != null && lnkEditFinal != null && lnkCopy != null && lnkAllocate != null) { lnkCreditNote.Visible = AllowCreditNotes(); lnkReversal.Visible = false; lnkEditFinal.Visible = false; lnkCopy.Visible = false; switch (hfType.Value) { case "TI"://Tax Invoice decimal liableP = Convert.ToDecimal(lblLiablePatient.Text); if (liableP > 0) { lblLiablePatient.ForeColor = System.Drawing.Color.Red; } decimal liableS = Convert.ToDecimal(lblLiableScheme.Text); if (liableS > 0) { lblLiableScheme.ForeColor = System.Drawing.Color.Red; } decimal Allocated = Convert.ToDecimal(lblAllocated.Text); if (Allocated > 0 && Allocated == amount) { lblAllocated.ForeColor = System.Drawing.Color.Blue; } else if (Allocated > 0 && Allocated < amount) { lblAllocated.ForeColor = System.Drawing.Color.Orange; } lnkCreditNote.Visible = AllowCreditNotes(); lnkReversal.Visible = false; lnkEditFinal.Visible = true; lnkAllocate.Visible = false; lnkCopy.Visible = handler.ReturnSetup().billingAllowCopy; break; case "PM"://Payment if (amount < 0) { if (hfAllocRef.Value == String.Empty) { lnkAllocate.Visible = true; lblAmount.ForeColor = System.Drawing.Color.Red; } else { lnkAllocate.Visible = false; lblAmount.ForeColor = System.Drawing.Color.Blue; } lnkCreditNote.Visible = false; lnkReversal.Visible = true; } else { lblAmount.ForeColor = System.Drawing.Color.Purple; lnkAllocate.Visible = false; } break; case "DJ": if (Convert.ToDecimal(lblAllocated.Text) > 0 && Convert.ToDecimal(lblAllocated.Text) == amount) { lblAllocated.ForeColor = System.Drawing.Color.Blue; } else if (Convert.ToDecimal(lblAllocated.Text) > 0 && Convert.ToDecimal(lblAllocated.Text) < amount) { lblAllocated.ForeColor = System.Drawing.Color.Orange; } lnkCreditNote.Visible = AllowCreditNotes(); lnkAllocate.Visible = false; break; case "CJ": if (amount < 0) { if (hfAllocRef.Value == String.Empty) { lnkAllocate.Visible = true; lblAmount.ForeColor = System.Drawing.Color.Red; } else { lnkAllocate.Visible = false; lblAmount.ForeColor = System.Drawing.Color.Blue; } lnkCreditNote.Visible = false; lnkReversal.Visible = true; } else { lblAmount.ForeColor = System.Drawing.Color.Purple; lnkAllocate.Visible = false; } break; } } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// remove an account entry /// /// /// protected void lnkRemove_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { LinkButton lnkRemove = (LinkButton)sender; int recId = int.Parse(lnkRemove.CommandArgument); xData.DeleteTyped("recId", recId.ToString(), typeof(oAccount)); if (this.Account != null) { oAccount acc = this.Account; BindAccountData(acc); PopulatePageFormValues(ref acc); pnlResult.Visible = true; lblResult.Text = "The line was removed successfully."; } else { Response.Redirect("/home", false); } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Click event to perform a Tax Credit Note /// /// /// protected void lnkCreditNote_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { LinkButton lnkRemove = (LinkButton)sender; int recId = int.Parse(lnkRemove.CommandArgument); if (this.Account != null) { oAccount acc = this.Account; PopulatePageFormValues(ref acc); foreach (oAccount billAcc in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", recId.ToString())) { if (billAcc.amount > 0 && billAcc.isVisible && (billAcc.procedureType == "TI" || billAcc.procedureType == "DJ")) { oAccount creditNote = (oAccount)utils.CloneObject(billAcc); //set the reverse creditNote.recId = 0; creditNote.amount = creditNote.amount * -1; creditNote.procedureType = "CN"; creditNote.dateOfCapture = DateTime.Now; //JR 2017-03-03 date of transaction creditNote.dateOfTransaction = DateTime.Now; creditNote.procedureDescription = "Credit Note"; creditNote.invoiceNo = xData.GetInvoiceNo(creditNote.dateOfCapture, acc.surfaceItemId, billAcc.placeOfService, billAcc.icd1); creditNote.isVisible = false; creditNote.userId = acc.userId; creditNote.allocatedReference = billAcc.recId.ToString(); creditNote.recId = xData.SaveTyped("recId", typeof(oAccount), creditNote); if (creditNote.recId > 0) { //update payment to hidden too billAcc.isVisible = false; billAcc.allocated = billAcc.amount; billAcc.allocatedReference = creditNote.recId.ToString(); if (billAcc.allocatedAssistReference != String.Empty)//we ned to undo the assisted payment { string[] assistedPayments = billAcc.allocatedAssistReference.Split(char.Parse(",")); foreach (string sId in assistedPayments) { int asspayId = 0; if (sId.Contains(":")) { int.TryParse(sId.Substring(0, sId.IndexOf(":")), out asspayId); } else { int.TryParse(sId, out asspayId); } if (asspayId > 0) { foreach (oAccount assistedPay in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", asspayId.ToString())) { string[] references = assistedPay.allocatedAssistReference.Split(char.Parse(",")); string adjustedReferences = String.Empty; foreach (string sref in references) { int billId = 0; if (sref.Contains(":")) { billId = int.Parse(sref.Substring(0, sref.IndexOf(":"))); } else { billId = int.Parse(sref); } if (billId != billAcc.recId)//only put back the other billing references { if (adjustedReferences == String.Empty) { adjustedReferences = sref; } else { adjustedReferences += "," + sref; } } } assistedPay.allocatedAssistReference = adjustedReferences; //update alloc reference on assisted payment line if (xData.UpdateTyped("recId", assistedPay.recId.ToString(), typeof(oAccount), assistedPay)) { } } } } } billAcc.liablePat = 0; billAcc.liableMed = 0; if (xData.UpdateTyped("recId", billAcc.recId.ToString(), typeof(oAccount), billAcc)) { pnlResult.Visible = true; lblResult.Text = "The Credit Note was successfully applied."; PopulatePageFormValues(ref acc); BindAccountData(acc); } } } else { pnlResult.Visible = true; lblResult.Text = "A Credit could not be applied. It could be zero amount or the line has already been credited."; } } } else { Response.Redirect("/home", false); } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Click event to perform a reversal /// /// /// protected void lnkReversal_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { LinkButton lnkRemove = (LinkButton)sender; int recId = int.Parse(lnkRemove.CommandArgument); if (this.Account != null) { oAccount acc = this.Account; foreach (oAccount payAcc in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", recId.ToString())) { if (payAcc.amount < 0 && payAcc.isVisible && (payAcc.procedureType == "PM" || payAcc.procedureType == "CJ")) { if (payAcc.allocatedReference != String.Empty) { //then we need to undo these allocations string[] allocBillingIds = payAcc.allocatedReference.Split(char.Parse(",")); decimal amountAllocated = Math.Abs(payAcc.amount); foreach (string sId in allocBillingIds) { int billId = 0; if (sId.Contains(":")) { int.TryParse(sId.Substring(0, sId.IndexOf(":")), out billId); } else { int.TryParse(sId, out billId); } foreach (oAccount billing in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", billId.ToString())) { string[] references = billing.allocatedReference.Split(char.Parse(",")); string adjustedReferences = String.Empty; foreach (string sref in references) { if (sref.Contains(":")) { int payId = int.Parse(sref.Substring(0, sref.IndexOf(":"))); if (payId == payAcc.recId) { decimal amount = Convert.ToDecimal(sref.Substring(sref.IndexOf(":") + 1)); amountAllocated -= amount; billing.liableMed += amount + billing.liablePat; billing.liablePat = 0; billing.allocated -= amount; } else { if (adjustedReferences == String.Empty) { adjustedReferences = sref; } else { adjustedReferences += "," + sref; } } } } billing.allocatedReference = adjustedReferences; //update alloc reference on billing line if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oAccount), billing)) { } } } } oAccount reversal = (oAccount)utils.CloneObject(payAcc); //set the reverse reversal.recId = 0; reversal.amount = reversal.amount * -1; reversal.procedureType = "PM"; reversal.dateOfCapture = DateTime.Now; //JR 2017-03-03 date of transaction reversal.dateOfTransaction = reversal.dateOfService; reversal.procedureDescription = "Payment Reversal"; reversal.isVisible = false; reversal.userId = acc.userId; reversal.receiptNo = xData.GetNextRecNo(); reversal.allocated = reversal.amount; reversal.allocatedReference = recId.ToString(); reversal.liableMed = 0; reversal.liablePat = 0; reversal.recId = xData.SaveTyped("recId", typeof(oAccount), reversal); if (reversal.recId > 0) { //update payment to hidden too payAcc.isVisible = false; payAcc.allocatedReference = reversal.recId.ToString(); if (xData.UpdateTyped("recId", payAcc.recId.ToString(), typeof(oAccount), payAcc)) { pnlResult.Visible = true; lblResult.Text = "The Reversal was successfully applied."; BindAccountData(acc); PopulatePageFormValues(ref acc); upAccounts.Update(); } } } else { pnlResult.Visible = true; lblResult.Text = "A Reversal could not be applied. It could be zero amount or the line has already been reversed."; } } } else { Response.Redirect("/home", false); } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } protected void lnkAllocate_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { BindTransactionTypes(); LinkButton lnkRemove = (LinkButton)sender; int recId = int.Parse(lnkRemove.CommandArgument); if (this.Account != null) { oAccount acc = this.Account; foreach (oAccount payLine in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", recId.ToString())) { if (payLine.procedureCode == "CRED") { if (ddTransactionType.Items.FindByText("Journal") != null) ddTransactionType.SelectedIndex = ddTransactionType.Items.IndexOf(ddTransactionType.Items.FindByText("Journal")); } else { if (ddTransactionType.Items.FindByText("Payment") != null) ddTransactionType.SelectedIndex = ddTransactionType.Items.IndexOf(ddTransactionType.Items.FindByText("Payment")); } BindPaymentMethods(ddTransactionType.SelectedValue); txtPaymentDate.Disabled = true; ddPaymentDoctor.Enabled = false; //ddPaymentMethod.Enabled = false; txtPaymentAmount.Disabled = true; Session["AllocPayment"] = payLine; //populate payline into modal btnTakePayment.Text = "Apply Allocation"; lblPaymentHeading.Text = "New Allocation"; txtPaymentDate.Value = payLine.dateOfService.ToString("dd/MM/yyyy"); ddPaymentDoctor.SelectedValue = payLine.doctorNo.ToString(); if (ddPaymentMethod.Items.FindByValue(payLine.procedureCode) != null) ddPaymentMethod.SelectedValue = payLine.procedureCode; txtPaymentAmount.Value = utils.returnFormattedDecimal(Convert.ToString(Math.Abs(payLine.amount))); BindBillingsToAllocate(); ddPaymentMethod.Focus(); pnlResultPayment.Visible = false; upPayment.Update(); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myPaymentModal", "$('#modPayment').modal();", true); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "paymentPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true); } } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// PreRender Event for Repeater /// /// /// protected void rptAccounts_PreRender(object sender, EventArgs e) { Repeater rpt = (Repeater)sender; int entryCount = 0; foreach (RepeaterItem item in rptAccounts.Items) { HiddenField hfClaimSent = (HiddenField)item.FindControl("hfClaimSent"); HiddenField hfInvoice = (HiddenField)item.FindControl("hfInvoice"); HiddenField hfLocked = (HiddenField)item.FindControl("hfLocked"); LinkButton lnkEditFinal = (LinkButton)item.FindControl("lnkEditFinal"); LinkButton lnkCreditNote = (LinkButton)item.FindControl("lnkCreditNote"); LinkButton lnkReversal = (LinkButton)item.FindControl("lnkReversal"); LinkButton lnkAllocate = (LinkButton)item.FindControl("lnkAllocate"); LinkButton lnkNoEdit = (LinkButton)item.FindControl("lnkNoEdit"); LinkButton lnkLocked = (LinkButton)item.FindControl("lnkLocked"); if (hfLocked.Value == "True") { lnkEditFinal.Visible = lnkCreditNote.Visible = lnkReversal.Visible = lnkAllocate.Visible = lnkNoEdit.Visible = false; lnkLocked.Visible = true; } else { if (hfClaimSent.Value == "True") { foreach (oMSClaimResponse response in xData.GetTypedByCriteriaSpecific("recId", typeof(oMSClaimResponse), "claimRefNo", hfInvoice.Value, "recId DESC")) { if (response.respondingParty == "02" || response.msDeliveryTypeInd == "03" || response.responseResultCode == "01" || response.responseResultCode == "02") { lnkEditFinal.Visible = false; lnkCreditNote.Visible = false; lnkReversal.Visible = false; lnkAllocate.Visible = false; lnkNoEdit.Visible = true; } break; } } } } for (int rowIndex = rpt.Items.Count - 2; rowIndex >= 0; rowIndex--) { RepeaterItem row = rpt.Items[rowIndex]; RepeaterItem previousRow = rpt.Items[rowIndex + 1]; Label lblDateOfService = (Label)row.FindControl("lblDateOfService"); Label lblDateOfServicePrev = (Label)previousRow.FindControl("lblDateOfService"); if (lblDateOfService.Text == lblDateOfServicePrev.Text) { entryCount++; } else { if (entryCount == 0) { if (rowIndex == 0) { LinkButton lnkMoveUp = (LinkButton)row.FindControl("lnkMoveUp"); lnkMoveUp.Visible = false; LinkButton lnkMoveDown = (LinkButton)row.FindControl("lnkMoveDown"); lnkMoveDown.Visible = false; } LinkButton lnkMoveUpPrev = (LinkButton)previousRow.FindControl("lnkMoveUp"); lnkMoveUpPrev.Visible = false; LinkButton lnkMoveDownPrev = (LinkButton)previousRow.FindControl("lnkMoveDown"); lnkMoveDownPrev.Visible = false; } entryCount = 0; } if (rowIndex == 0 && lblDateOfService.Text != lblDateOfServicePrev.Text) { LinkButton lnkMoveUp = (LinkButton)row.FindControl("lnkMoveUp"); lnkMoveUp.Visible = false; LinkButton lnkMoveDown = (LinkButton)row.FindControl("lnkMoveDown"); lnkMoveDown.Visible = false; } } } #endregion #region payment events protected void ddTransactionType_SelectedIndexChanged(object sender, EventArgs e) { BindPaymentMethods(ddTransactionType.SelectedValue); } protected void ddPaymentMethod_SelectedIndexChanged(object sender, EventArgs e) { foreach (oPaymentType paymentType in xData.GetTypedByCriteriaSpecific("recId", typeof(oPaymentType), "paymentCode", ddPaymentMethod.SelectedValue)) { divAllocateTo.Visible = paymentType.allowAllocations; } } private void BindPaymentMethods(string transactionTypeId) { try { ddPaymentMethod.Items.Clear(); DataTable paymentTypeData = new DataTable(); paymentTypeData = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oPaymentType), "transactionTypeId", transactionTypeId); ddPaymentMethod.DataSource = paymentTypeData; ddPaymentMethod.DataTextField = "paymentType"; ddPaymentMethod.DataValueField = "paymentCode"; ddPaymentMethod.DataBind(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Take Payment /// /// /// protected void btnTakePayment_Click(object sender, EventArgs e) { try { if (PostPaymentLine()) { if (this.Account != null) { oAccount acc = this.Account; BindAccountData(acc); PopulatePageFormValues(ref acc); pnlResultPayment.Visible = true; lblResultPayment.Text = lblPaymentHeading.Text + " was successfully posted."; txtPaymentAmount.Value = ""; ddPaymentMethod.Focus(); //enable payment fields for allocations txtPaymentDate.Disabled = false; ddPaymentDoctor.Enabled = true; ddPaymentMethod.Enabled = true; txtPaymentAmount.Disabled = false; /* CVH 2016-07-05 If account balance is zero, show statement modal with email option available */ decimal accBal = xData.GetAccountBalance(acc.surfaceItemId); txtPaymentBalance.Text = utils.returnFormattedDecimal(Convert.ToString(accBal)); if (accBal == 0) { lblEmailResultMedical.Text = ""; lblEmailResultPatient.Text = ""; lblEmailResultPractice.Text = ""; chkEmailPatient.Checked = true; chkEmailMedicalAid.Visible = false; chkEmailPractice.Visible = false; btnCreateStatement.Visible = false; upStatement.Update(); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myAutoStatementModal", "$('#modStatement').modal();", true); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "autoStatementPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true); } } else { Response.Redirect("/home", false); } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } #endregion #region billing events /// /// modifier selected index changed event /// /// /// protected void ddBillingModifier_SelectedIndexChanged(object sender, EventArgs e) { try { if (sender.GetType() == typeof(DropDownList)) { DropDownList dd = (DropDownList)sender; switch (dd.ID) { case "ddEditLineModifier": if (dd.SelectedValue == "0011") { divEditModBMI.Visible = false; divEditModAssistant.Visible = false; divEditModMinutes.Visible = true; txtEditLineModMinutes.Text = ""; } else if (dd.SelectedValue == "0018") { divEditModBMI.Visible = true; divEditModAssistant.Visible = false; divEditModMinutes.Visible = false; txtEditModHeight.Text = ""; txtEditModWeight.Text = ""; } else if (dd.SelectedValue == "0008" || dd.SelectedValue == "0009") { //assistant = 0009 = 1. specialized assistant = 0008 = 2. BindAssistants(dd.SelectedValue == "0009" ? 1 : 2); txtEditModSurname.Text = ""; txtEditModRegistration.Text = ""; divEditModBMI.Visible = false; divEditModAssistant.Visible = true; divEditModMinutes.Visible = false; ddEditModAssistant.Focus(); } else { divEditModBMI.Visible = false; divEditModAssistant.Visible = false; divEditModMinutes.Visible = false; } CalculateAmountEditLine(false); break; default: if (dd.SelectedValue == "0011") { divModBMI.Visible = false; divModAssistant.Visible = false; divModMinutes.Visible = true; txtModMinutes.Focus(); } else if (dd.SelectedValue == "0018") { divModBMI.Visible = true; divModAssistant.Visible = false; divModMinutes.Visible = false; txtModHeight.Text = ""; txtModWeight.Text = ""; txtModHeight.Focus(); } else if (dd.SelectedValue == "0008" || dd.SelectedValue == "0009") { //assistant = 0009 = 1. specialized assistant = 0008 = 2. BindAssistants(dd.SelectedValue == "0009" ? 1 : 2); txtModAssistantSurname.Text = ""; txtModAssistantRegistration.Text = ""; divModBMI.Visible = false; divModAssistant.Visible = true; divModMinutes.Visible = false; ddModAssistant.Focus(); } else { divModBMI.Visible = false; divModAssistant.Visible = false; divModMinutes.Visible = false; txtModMinutes.Value = ""; } break; } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// uinit price Text changed event /// /// /// protected void txtBillingUnitPrice_TextChanged(object sender, EventArgs e) { try { if (sender.GetType() == typeof(TextBox)) { TextBox unitFee = (TextBox)sender; switch (unitFee.ID) { case "txtEditLineUnitPrice": CalculateAmountEditLine(false); break; default: CalculateAmount(false); break; } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Qty Text Changed Event /// /// /// protected void txtBillingQty_TextChanged(object sender, EventArgs e) { try { if (sender.GetType() == typeof(TextBox)) { TextBox qty = (TextBox)sender; switch (qty.ID) { case "txtEditLineQty": CalculateAmountEditLine(false); break; default: CalculateAmount(false); break; } upBilling.Update(); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Tariff Selection Change /// /// /// protected void ddBillingTariff_SelectedIndexChanged(object sender, EventArgs e) { try { if (sender.GetType() == typeof(DropDownList)) { DropDownList dd = (DropDownList)sender; switch (dd.ID) { case "ddEditLineDescription": CalculateAmountEditLine(true); break; default: CalculateAmount(true); break; } upBilling.Update(); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Description Selection Changed event /// /// /// protected void ddDescription_SelectedIndexChanged(object sender, EventArgs e) { try { if (sender.GetType() == typeof(DropDownList)) { DropDownList dd = (DropDownList)sender; string code = dd.SelectedValue; switch (dd.ID) { case "ddEditLineDescription": CalculateAmountEditLine(true); txtEditLineCode.Text = code; PopulateDiagnosisEdit(code); break; default: txtBillingCode.Text = code; PopulateDiagnosisNew(code); CalculateAmount(true); break; } if (dd.SelectedValue != "0") { btnMods.Enabled = true; lblModProcedure.Text = txtBillingCode.Text + " - " + ddBillingDescription.SelectedItem.Text; } else btnMods.Enabled = false; } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// remove billing line in posting session /// /// /// protected void lnkRemoveBilling_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { LinkButton lnkRemoveBilling = (LinkButton)sender; string code = lnkRemoveBilling.CommandArgument; if (utils.verifySession("billingLines")) { ArrayList currentBillings = (ArrayList)Session["billingLines"]; ArrayList newBillings = new ArrayList(); //enumerate current billings foreach (oAccount bill in currentBillings) { if (bill.procedureCode != code) { newBillings.Add(bill); } } Session["billingLines"] = newBillings; BindBillingLines(); } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Fee code text changed event /// /// /// protected void txtBillingCode_TextChanged(object sender, EventArgs e) { try { if (sender.GetType() == typeof(TextBox)) { TextBox billingCode = (TextBox)sender; if (billingCode.Text.Length >= 2) { switch (billingCode.ID) { case "txtEditLineUnitPrice": BindFeesEdit(billingCode.Text, ""); CalculateAmountEditLine(false); PopulateDiagnosisEdit(billingCode.Text); break; default: BindFeesNew(billingCode.Text, ""); CalculateAmount(true); PopulateDiagnosisNew(billingCode.Text); break; } } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Pat Liable Text change event /// /// /// protected void txtBillingLiablePat_TextChanged(object sender, EventArgs e) { try { decimal liable = 0; decimal patLiable = 0; decimal amount = 0; decimal.TryParse(txtBillingLiablePat.Text, out patLiable); decimal.TryParse(txtBillingTotal.Value, out amount); if (patLiable >= amount) { patLiable = amount; liable = 0; } else if (patLiable >= 0)//set med liable to the balance { liable = amount - patLiable; } else//less than 0 { patLiable = 0; liable = amount; } txtBillingLiablePat.Text = utils.returnFormattedDecimal(Convert.ToString(patLiable)); txtBillingLiableScheme.Text = utils.returnFormattedDecimal(Convert.ToString(liable)); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Med liable text changed event /// /// /// protected void txtBillingLiableScheme_TextChanged(object sender, EventArgs e) { try { decimal liable = 0; decimal patLiable = 0; decimal amount = 0; decimal.TryParse(txtBillingLiableScheme.Text, out liable); decimal.TryParse(txtBillingTotal.Value, out amount); if (liable >= amount) { liable = amount; patLiable = 0; } else if (liable >= 0)//set pat liable to the balance { patLiable = amount - liable; } else//less than 0 { liable = 0; patLiable = amount; } txtBillingLiablePat.Text = utils.returnFormattedDecimal(Convert.ToString(patLiable)); txtBillingLiableScheme.Text = utils.returnFormattedDecimal(Convert.ToString(liable)); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Modifier button click /// /// /// protected void btnMods_Click(object sender, EventArgs e) { try { ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myModifierModal", "$('#modModifiers').modal();", true); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Post line to billing grid /// /// /// protected void btnPost_Click(object sender, EventArgs e) { try { if (PostBillingLine()) { BindBillingLines(); ClearPostings(); txtBillingCode.Focus(); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Finalise Billing /// /// /// protected void btnFinaliseBill_Click(object sender, EventArgs e) { try { if (FinaliseBilling()) { pnlResultBilling.Visible = true; lblResultBilling.Text = "Billing was successfully finalised."; Session["billingLines"] = null; Session["modList"] = null; BindModList(); btnMods.Enabled = false; BindBillingLines(); txtBillingCode.Text = String.Empty; txtBillingUnitPrice.Text = "0.00"; CalculateAmount(false); BindFeesNew("", ""); txtBillingCode.Focus(); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Add Modifier /// /// /// protected void btnAddModifier_Click(object sender, EventArgs e) { //ArrayList modList = new ArrayList(); //if (utils.verifySession("modList")) // modList = (ArrayList)Session["modList"]; List modList = new List(); if (utils.verifySession("modList")) modList = (List)Session["modList"]; string mod = ddBillingModifier.SelectedValue; string modMinutes = txtModMinutes.Value; string modAssistantReg = utils.stripCharacters(txtModAssistantRegistration.Text.Trim()); string modAssistantSurname = txtModAssistantSurname.Text.Trim(); string modHeight = txtModHeight.Text; string modWeight = txtModWeight.Text; //if (!modList.Any(x => x == mod)) if (!modList.Any(x => x.StartsWith(mod))) { //if (modMinutes.Length > 0) // modList.Add(mod + ";" + modMinutes); //else // modList.Add(mod); /* CVH 2016-05-05 Add palDoctor.recId if modifier is Assistant or Specialized Assistant */ switch (mod) { case "0008": case "0009": modList.Add(mod + ";" + modAssistantReg + ";" + modAssistantSurname); break; case "0011": modList.Add(mod + ";" + modMinutes); break; case "0018": modList.Add(mod + ";" + modHeight + ";" + modWeight); break; default: modList.Add(mod); break; } } Session["modList"] = modList; BindModList(); ddBillingModifier.ClearSelection(); if (ddBillingModifier.Items.Count > 0) ddBillingModifier.Items[0].Selected = true; ddBillingModifier_SelectedIndexChanged(ddBillingModifier, new EventArgs()); } /// /// Remove modifier /// /// /// protected void lnkModRemove_Click(object sender, EventArgs e) { List modList = new List(); if (utils.verifySession("modList")) modList = (List)Session["modList"]; LinkButton lnkModRemove = (LinkButton)sender; string modToRemove = lnkModRemove.CommandArgument; var itemToRemove = modList.Single(r => r == modToRemove); modList.Remove(itemToRemove); Session["modList"] = modList; BindModList(); } /// /// ICD10 Selected index change /// /// /// protected void ddBillingICD10_SelectedIndexChanged(object sender, EventArgs e) { divExternalCause.Visible = false; reqtxtExternalCause.Enabled = false; ; txtExternalCause.Text = ""; foreach (ListItem icd10Item in ddBillingICD10.Items) { if (icd10Item.Selected) { foreach (oMedicalICD10 icd10 in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalICD10), "icdCode", icd10Item.Value)) { if (icd10.isExternal) { divExternalCause.Visible = true; reqtxtExternalCause.Enabled = true; txtExternalCause.Focus(); break; } } } } if (ddBillingDescription.SelectedValue != "0") { btnMods.Enabled = true; lblModProcedure.Text = txtBillingCode.Text + " - " + ddBillingDescription.SelectedItem.Text; } else btnMods.Enabled = false; upBilling.Update(); } protected void lstBillingICd10_SelectedIndexChanged(object sender, EventArgs e) { } /// /// change place of service /// /// /// protected void ddPlaceOfservice_SelectedIndexChanged(object sender, EventArgs e) { CalculateAmount(true); upBilling.Update(); } #endregion #region assisted events /// /// Item Data Bound /// /// /// protected void rptAccountsAssisted_ItemDataBound(object sender, RepeaterItemEventArgs e) { try { HiddenField hfType = e.Item.FindControl("hfType") as HiddenField; if (hfType != null) { //amount field Label lblAmount = (Label)e.Item.FindControl("lblAmount"); decimal amountTmp = 0m; decimal.TryParse(lblAmount.Text, out amountTmp); //option links LinkButton lnkPayAssisted = (LinkButton)e.Item.FindControl("lnkPayAssisted"); LinkButton lnkASTReversal = (LinkButton)e.Item.FindControl("lnkASTReversal"); LinkButton lnkASTAllocate = (LinkButton)e.Item.FindControl("lnkASTAllocate"); Label lblAllocated = (Label)e.Item.FindControl("lblAllocated"); decimal AllocatedTmp = 0m; decimal.TryParse(lblAllocated.Text, out AllocatedTmp); //CVH 2016-11-17 Determine whether practice saves assistant payments ex vat, then need to calculate and show ex vat amount oSetup setup = handler.ReturnSetup(); HiddenField hfPracticeId = e.Item.FindControl("hfPracticeId") as HiddenField; string practiceId = "0"; if (hfPracticeId != null) practiceId = hfPracticeId.Value; oMedicalPractice prac = new oMedicalPractice(); foreach (oMedicalPractice practice in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalPractice), "recId", practiceId)) { prac = practice; break; } HiddenField hfAllocRef = e.Item.FindControl("hfAllocRef") as HiddenField; HiddenField hfVatRate = e.Item.FindControl("hfVatRate") as HiddenField; decimal vatRate = 0m; decimal.TryParse(hfVatRate.Value, out vatRate); decimal amount = 0m; if (setup.vatRegistered && prac.isAstPaymentExVat) amount = amountTmp / ((100m + vatRate) / 100m); else amount = amountTmp; decimal Allocated = 0m; if (setup.vatRegistered && prac.isAstPaymentExVat) Allocated = AllocatedTmp / ((100m + vatRate) / 100m); else Allocated = AllocatedTmp; lblAmount.Text = utils.returnFormattedDecimal(Convert.ToString(amount)); lblAllocated.Text = utils.returnFormattedDecimal(Convert.ToString(Allocated)); if (lnkPayAssisted != null && lnkASTReversal != null && lnkASTAllocate != null) { lnkPayAssisted.Visible = false; lnkASTReversal.Visible = false; lnkASTAllocate.Visible = false; switch (hfType.Value) { case "TI"://Tax Invoice if (Allocated > 0m && Allocated == amount) { lblAllocated.ForeColor = System.Drawing.Color.Blue; } else if (Allocated > 0m && Allocated < amount) { lblAllocated.ForeColor = System.Drawing.Color.Orange; } lnkPayAssisted.Visible = true; lnkASTReversal.Visible = false; lnkASTAllocate.Visible = false; break; case "PA"://Payment Assistant if (amount < 0m) { if (hfAllocRef.Value == String.Empty) { lnkASTAllocate.Visible = true; lblAmount.ForeColor = System.Drawing.Color.Red; } else { lnkASTAllocate.Visible = false; lblAmount.ForeColor = System.Drawing.Color.Blue; } lnkPayAssisted.Visible = false; lnkASTReversal.Visible = true; } else { lblAmount.ForeColor = System.Drawing.Color.Purple; lnkASTAllocate.Visible = false; } break; } } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Reverse Assisted Payment /// /// /// protected void lnkASTReversal_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { LinkButton lnkRemove = (LinkButton)sender; int recId = int.Parse(lnkRemove.CommandArgument); if (this.Account != null) { oAccount acc = this.Account; foreach (oAccount payAcc in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", recId.ToString())) { if (payAcc.amount < 0 && payAcc.procedureType == "PA" && payAcc.isVisible) { if (payAcc.allocatedAssistReference != String.Empty) { //then we need to undo these allocations string[] allocBillingIds = payAcc.allocatedAssistReference.Split(char.Parse(",")); decimal amountAllocated = Math.Abs(payAcc.amount); foreach (string sId in allocBillingIds) { int billId = 0; if (sId.Contains(":")) { int.TryParse(sId.Substring(0, sId.IndexOf(":")), out billId); } else { int.TryParse(sId, out billId); } foreach (oAccount billing in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", billId.ToString())) { string[] references = billing.allocatedAssistReference.Split(char.Parse(",")); string adjustedReferences = String.Empty; foreach (string sref in references) { if (sref.Contains(":")) { int payId = int.Parse(sref.Substring(0, sref.IndexOf(":"))); if (payId == payAcc.recId) { decimal amount = Convert.ToDecimal(sref.Substring(sref.IndexOf(":") + 1)); amountAllocated -= amount; billing.allocatedAssist -= amount; } else { if (adjustedReferences == String.Empty) { adjustedReferences = sref; } else { adjustedReferences += "," + sref; } } } } billing.allocatedAssistReference = adjustedReferences; //update alloc reference on billing line if (xData.UpdateTyped("recId", billing.recId.ToString(), typeof(oAccount), billing)) { } } } } oAccount reversal = (oAccount)utils.CloneObject(payAcc); //set the reverse reversal.recId = 0; reversal.amount = reversal.amount * -1; reversal.procedureType = "PA"; reversal.dateOfCapture = DateTime.Now; //JR 2017-03-03 date of transaction reversal.dateOfTransaction = reversal.dateOfTransaction; reversal.procedureDescription = "Payment Assistant Reversal"; reversal.isVisible = false; reversal.userId = acc.userId; reversal.receiptNo = 0; reversal.allocatedAssist = reversal.amount; reversal.allocatedAssistReference = recId.ToString(); reversal.liableMed = 0; reversal.liablePat = 0; reversal.recId = xData.SaveTyped("recId", typeof(oAccount), reversal); if (reversal.recId > 0) { //update payment to hidden too payAcc.isVisible = false; payAcc.allocatedAssistReference = reversal.recId.ToString(); if (xData.UpdateTyped("recId", payAcc.recId.ToString(), typeof(oAccount), payAcc)) { pnlResult.Visible = true; lblResult.Text = "The Assisted Reversal was successfully applied."; BindAccountData(acc); PopulatePageFormValues(ref acc); upAccounts.Update(); } } } else { pnlResult.Visible = true; lblResult.Text = "A Reversal could not be applied. It could be zero amount or the line has already been reversed."; } } } else { Response.Redirect("/home", false); } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// allocate Assisted Payment line /// /// /// protected void lnkASTAllocate_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { LinkButton lnkRemove = (LinkButton)sender; int recId = int.Parse(lnkRemove.CommandArgument); if (this.Account != null) { oAccount acc = this.Account; foreach (oAccount payLine in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", recId.ToString())) { txtPaymentAssistDate.Disabled = true; ddPaymentAssistDoctor.Enabled = false; //ddPaymentMethod.Enabled = false; txtPaymentAssistAmount.Disabled = true; Session["AllocPaymentAssist"] = payLine; //populate payline into modal btnTakePaymentAssist.Text = "Apply Allocation"; lblPaymentAssistedHeading.Text = "New Assistant Allocation"; txtPaymentAssistDate.Value = payLine.dateOfService.ToString("dd/MM/yyyy"); ddPaymentAssistDoctor.SelectedValue = payLine.doctorNo.ToString(); ddPaymentAssistMethod.SelectedValue = payLine.procedureCode; txtPaymentAssistAmount.Value = utils.returnFormattedDecimal(Convert.ToString(Math.Abs(payLine.amount))); BindAssistedBillingsToAllocate(); ddPaymentAssistMethod.Focus(); pnlResultPaymentAssist.Visible = false; upPaymentAssist.Update(); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myAllocateAssistModal", "$('#modPaymentAssist').modal();", true); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "AllocateAssistPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true); } } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Make a Payment to Assistant /// /// /// protected void lnkPayAssisted_Click(object sender, EventArgs e) { try { BindAssistedBillingsToAllocate(); ddPaymentAssistMethod.Focus(); pnlResultPaymentAssist.Visible = false; txtPaymentAssistAmount.Value = "0.00"; Session["AllocPaymentAssist"] = null; txtPaymentAssistDate.Disabled = false; ddPaymentAssistDoctor.Enabled = true; ddPaymentAssistMethod.Enabled = true; txtPaymentAssistAmount.Disabled = false; btnTakePaymentAssist.Text = "Take Payment"; lblPaymentAssistedHeading.Text = "New Assistant Payment"; upPaymentAssist.Update(); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myPaymentAssistModal", "$('#modPaymentAssist').modal();", true); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "PaymentAssistPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Take Assisted Payment /// /// /// protected void btnTakePaymentAssist_Click(object sender, EventArgs e) { if (PostPaymentAssistLine()) { if (this.Account != null) { oAccount acc = this.Account; BindAccountData(acc); PopulatePageFormValues(ref acc); pnlResultPaymentAssist.Visible = true; lblResultPaymentAssist.Text = lblPaymentAssistedHeading.Text + " was successfully posted."; txtPaymentAssistAmount.Value = "0.00"; ddPaymentAssistMethod.Focus(); //enable payment fields for allocations txtPaymentAssistDate.Disabled = false; ddPaymentAssistDoctor.Enabled = true; ddPaymentAssistMethod.Enabled = true; txtPaymentAssistAmount.Disabled = false; } else { Response.Redirect("/home", false); } } } #endregion #region edit line events /// /// Edit click for Finalised billings /// /// /// protected void lnkEditFinal_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { LinkButton lnkEditFinal = (LinkButton)sender; int recId = int.Parse(lnkEditFinal.CommandArgument); ViewState["dateOfService"] = null; foreach (oAccount accEdit in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", recId.ToString())) { oAccount acc = accEdit; Session["accountEdit"] = acc; PopulateEditLineValues(ref acc); upEdit.Update(); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myEditFinalModal", "$('#modEdit').modal();", true); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "editFinalPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true); break; } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Edit Line Event /// /// /// protected void lnkEdit_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { LinkButton lnkEdit = (LinkButton)sender; if (lnkEdit.Parent.GetType() == typeof(RepeaterItem)) { RepeaterItem item = (RepeaterItem)(lnkEdit).Parent; if (this.Account != null) { Session["editIndex"] = item.ItemIndex; oAccount acc = this.Account; oAccount editLine = (oAccount)utils.CloneObject(acc); //get values from row Label lblDateOfService = (Label)item.FindControl("lblDateOfService"); if (lblDateOfService != null) { editLine.dateOfService = utils.formatStringToDate(lblDateOfService.Text); } Label lblInvoiceNo = (Label)item.FindControl("lblInvoiceNo"); if (lblInvoiceNo != null) { editLine.invoiceNo = int.Parse(lblInvoiceNo.Text); } Label lblProcedureCode = (Label)item.FindControl("lblProcedureCode"); if (lblProcedureCode != null) { editLine.procedureCode = lblProcedureCode.Text; } Label lblProcedureDescription = (Label)item.FindControl("lblProcedureDescription"); if (lblProcedureDescription != null) { editLine.procedureDescription = lblProcedureDescription.Text; } Label lblICD10 = (Label)item.FindControl("lblICD10"); if (lblICD10 != null) { editLine.icd1 = lblICD10.Text; } Label lblQty = (Label)item.FindControl("lblQty"); if (lblQty != null) { editLine.qty = Decimal.Parse(lblQty.Text); } Label lblUnitFee = (Label)item.FindControl("lblUnitFee"); if (lblUnitFee != null) { editLine.unitFee = Decimal.Parse(lblUnitFee.Text); } Session["accountEdit"] = editLine; PopulateEditLineValues(ref editLine); upEdit.Update(); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myEditLineModal", "$('#modEdit').modal();", true); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "editLinePicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true); } else { Response.Redirect("/home", false); } } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// PAtient Liable Text Changed /// /// /// protected void txtEditLineLiablePat_TextChanged(object sender, EventArgs e) { try { decimal liable = 0; decimal patLiable = 0; decimal amount = 0; decimal.TryParse(txtEditLineLiablePat.Text, out patLiable); decimal.TryParse(txtEditLineTotal.Value, out amount); if (patLiable >= amount) { patLiable = amount; liable = 0; } else if (patLiable >= 0)//set med liable to the balance { liable = amount - patLiable; } else//less than 0 { patLiable = 0; liable = amount; } txtEditLineLiablePat.Text = utils.returnFormattedDecimal(Convert.ToString(patLiable)); txtEditLineLiableScheme.Text = utils.returnFormattedDecimal(Convert.ToString(liable)); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Scheme liable text changed /// /// /// protected void txtEditLineLiableScheme_TextChanged(object sender, EventArgs e) { try { decimal liable = 0; decimal patLiable = 0; decimal amount = 0; decimal.TryParse(txtEditLineLiableScheme.Text, out liable); decimal.TryParse(txtEditLineTotal.Value, out amount); if (liable >= amount) { liable = amount; patLiable = 0; } else if (liable >= 0)//set pat liable to the balance { patLiable = amount - liable; } else//less than 0 { liable = 0; patLiable = amount; } txtEditLineLiablePat.Text = utils.returnFormattedDecimal(Convert.ToString(patLiable)); txtEditLineLiableScheme.Text = utils.returnFormattedDecimal(Convert.ToString(liable)); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// apply edit /// /// /// protected void btnSaveEdit_Click(object sender, EventArgs e) { ArrayList billings = new ArrayList(); try { if (this.Account != null) { oAccount acc = this.Account; if (utils.verifySession("accountEdit")) { oAccount editLine = (oAccount)Session["accountEdit"]; DateTime changedDateOfService = new DateTime(); SaveEditLineValues(ref editLine,ref changedDateOfService); if (editLine.modifier4 == "0005") { List modList = new List(); if (utils.verifySession("modList")) modList = (List)Session["modList"]; string mod = "0005"; string modMinutes = ""; if (!modList.Any(x => x == mod)) { if (modMinutes.Length > 0) modList.Add(mod + ";" + modMinutes); else modList.Add(mod); } Session["modList"] = modList; } if (editLine.recId > 0)//this is a finalised line we are editing { if (xData.UpdateTyped("recId", editLine.recId.ToString(), typeof(oAccount), editLine)) { if (editLine.modifier4 == "0005") { //get lines for this invoice and apply modifier ArrayList billingsToModify = xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "surfaceItemId,invoiceNo,procedureType,isVisible", editLine.surfaceItemId + "," + editLine.invoiceNo + ",TI,1", "sequence"); ApplyModifier5toBillings(ref billingsToModify); foreach (oAccount billModified in billingsToModify) { xData.UpdateTyped("recId", billModified.recId.ToString(), typeof(oAccount), billModified); } } BindAccountData(acc); } } else//posting line not yet commited { if (utils.verifySession("billingLines")) { billings = (ArrayList)Session["billingLines"]; } if (utils.verifySession("editIndex")) { int index = int.Parse(Session["editIndex"].ToString()); int count = 0; ArrayList newBillings = new ArrayList(); foreach (oAccount billing in billings) { billing.dateOfService = changedDateOfService; if (index == count) { editLine.isVisible = true; newBillings.Add(editLine); } else { newBillings.Add(billing); } count++; } Session["billingLines"] = newBillings; BindBillingLines(); upBilling.Update(); } } Session["accountEdit"] = editLine; pnlResultEditLine.Visible = true; lblResultEditLine.Text = "The edit has been applied successfully."; } } else { Response.Redirect("/home", false); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Move sequence up /// /// /// protected void lnkMoveUp_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { LinkButton lnkMoveUp = (LinkButton)sender; string[] commandArgs = lnkMoveUp.CommandArgument.ToString().Split(new char[] { ',' }); int recId = int.Parse(commandArgs[0]); int surfaceItemId = int.Parse(commandArgs[1]); string dateOfService = commandArgs[2]; int sequence = int.Parse(commandArgs[3]); int swopSeqOld = 0; int swopSeqNew = 0; bool setNext = false; foreach (oAccount acc in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "surfaceItemId,dateOfService,isVisible", surfaceItemId.ToString() + "," + dateOfService.ToString() + ",1", "sequence desc")) { if (setNext) { swopSeqNew = acc.sequence; acc.sequence = swopSeqOld; xData.UpdateTyped("recId", acc.recId.ToString(), typeof(oAccount), acc); foreach (oAccount account in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", recId.ToString())) { account.sequence = swopSeqNew; xData.UpdateTyped("recId", recId.ToString(), typeof(oAccount), account); } break; } if (recId == acc.recId && acc.sequence > 1) { //acc.sequence--; //xData.UpdateTyped("recId", acc.recId.ToString(), typeof(oAccount), acc); setNext = true; swopSeqOld = acc.sequence; } } if (this.Account != null) { oAccount acc = this.Account; UpdateRunningTotals(acc); BindAccountData(acc); PopulatePageFormValues(ref acc); } else { Response.Redirect("/home", false); } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Move sequence down /// /// /// protected void lnkMoveDown_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { LinkButton lnkMoveDown = (LinkButton)sender; string[] commandArgs = lnkMoveDown.CommandArgument.ToString().Split(new char[] { ',' }); int recId = int.Parse(commandArgs[0]); int surfaceItemId = int.Parse(commandArgs[1]); string dateOfService = commandArgs[2]; int sequence = int.Parse(commandArgs[3]); int swopSeqOld = 0; int swopSeqNew = 0; bool setNext = false; foreach (oAccount acc in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "surfaceItemId,dateOfService,isVisible", surfaceItemId.ToString() + "," + dateOfService.ToString() + ",1", "sequence")) { if (setNext) { swopSeqNew = acc.sequence; acc.sequence = swopSeqOld; xData.UpdateTyped("recId", acc.recId.ToString(), typeof(oAccount), acc); foreach (oAccount account in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", recId.ToString())) { account.sequence = swopSeqNew; xData.UpdateTyped("recId", recId.ToString(), typeof(oAccount), account); } break; } if (recId == acc.recId) { setNext = true; swopSeqOld = acc.sequence; } } if (this.Account != null) { oAccount acc = this.Account; UpdateRunningTotals(acc); BindAccountData(acc); PopulatePageFormValues(ref acc); } else { Response.Redirect("/home", false); } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } /// /// Edit Line ModMinutes change /// /// /// protected void txtEditLineModMinutes_TextChanged(object sender, EventArgs e) { CalculateAmountEditLine(false); } /// /// Edit Line ICD10 index change /// /// /// protected void ddEditLineICD10_SelectedIndexChanged(object sender, EventArgs e) { divEditLineExternalCause.Visible = false; reqtxtEditLineExternalCause.Enabled = false; txtEditLineExternalCause.Text = ""; foreach (ListItem icd10Item in ddEditLineICD10.Items) { if (icd10Item.Selected) { foreach (oMedicalICD10 icd10 in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalICD10), "icdCode", icd10Item.Value)) { if (icd10.isExternal) { divEditLineExternalCause.Visible = true; reqtxtEditLineExternalCause.Enabled = true; txtEditLineExternalCause.Focus(); break; } } } } upEdit.Update(); } protected void lstEditLineICD10_SelectedIndexChanged(object sender, EventArgs e) { } /// /// change placeofservice /// /// /// protected void ddEditLineServiceSite_SelectedIndexChanged(object sender, EventArgs e) { CalculateAmountEditLine(true); upEdit.Update(); } #endregion #region statement events /// /// Create the Statement /// /// /// protected void btnCreateStatement_Click(object sender, EventArgs e) { try { string file = String.Empty; string path = string.Empty; string additionalEmailMessage = txtEmailBodyMessage.Value; int bbfDays = 0; if (txtBBF.Value != "") bbfDays = int.Parse(txtBBF.Value); bool showCorrections = chkShowHidden.Checked; int maxLines = 15; if (txtLineCount.Value != "") maxLines = int.Parse(txtLineCount.Value); bool fromZeroBalance = chkLatZero.Checked; DateTime statementDate = DateTime.Now; if (txtStatementDate.Value != "") statementDate = utils.formatStringToDate(txtStatementDate.Value); DateTime statementDateFrom = DateTime.Now; if (txtStatementDateFrom.Value != "") statementDateFrom = utils.formatStringToDate(txtStatementDateFrom.Value); DateTime statementDateTo = DateTime.Now; if (txtStatementDateTo.Value != "") statementDateTo = utils.formatStringToDate(txtStatementDateTo.Value); bool useDateRange = false; if (txtStatementDateFrom.Value != "" && txtStatementDateTo.Value != "") { useDateRange = true; } oAccount statementAccount = this.Account; if (divStatementFor.Visible) { if (ddlStatementFor.SelectedValue == "0") { //get all linked patients } else { int surfaceItemId = Convert.ToInt32(ddlStatementFor.SelectedValue); int surfaceId = 0; foreach (oSurfaceItem item in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceItem), "recId", surfaceItemId.ToString())) { surfaceId = item.surfaceId; } oUser usr = new oUser(); if (utils.verifySession("user")) { usr = (oUser)Session["user"]; } statementAccount = xDebtors.SetAccountItem(surfaceItemId, surfaceId, usr); } } bool success = xDebtors.CreateStatement(statementAccount, ConfigurationManager.AppSettings["WebAddy"], additionalEmailMessage, bbfDays, showCorrections, maxLines, fromZeroBalance, statementDate, useDateRange, statementDateFrom, statementDateTo, ref path, ref file); if (success) { Response.Clear(); //Set the appropriate ContentType. Response.ContentType = "Application/pdf"; Response.AppendHeader("Content-Disposition", "attachment; filename=" + file); Response.TransmitFile(path + file); Response.Flush(); Response.SuppressContent = true; ApplicationInstance.CompleteRequest(); //add note if (this.Account != null) { int userId = 0; if (utils.verifySession("user")) { userId = ((oUser)Session["user"]).recId; } xDebtors.AddCreateStatementNote(this.Account.surfaceItemId, "Medical Statement", "A medical statement was created.", path, file, userId, this.NotesFieldName); } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } /// /// Email statement /// /// /// protected void btnEmailStatement_Click(object sender, EventArgs e) { try { /* CVH 2016-07-05 Methods EmailStatement, CreateStatement etc moved to xDebtors class */ if (!utils.verifySession("user")) { Response.Redirect("/home", false); return; } oAccount acc = this.Account; int userId = ((oUser)Session["user"]).recId; string additionalEmailMessage = txtEmailBodyMessage.Value; int bbfDays = 0; if (txtBBF.Value != "") bbfDays = int.Parse(txtBBF.Value); bool showCorrections = chkShowHidden.Checked; int maxLines = 15; if (txtLineCount.Value != "") maxLines = int.Parse(txtLineCount.Value); bool fromZeroBalance = chkLatZero.Checked; bool emailPatient = chkEmailPatient.Checked; bool emailPractice = chkEmailPractice.Checked; bool emailMedicalAid = chkEmailMedicalAid.Checked; bool validMedicalAidEmail = false; bool validAccountEmail = false; bool validPracticeEmail = false; DateTime statementDate = DateTime.Now; if (txtStatementDate.Value != "") statementDate = utils.formatStringToDate(txtStatementDate.Value); DateTime statementDateFrom = DateTime.Now; if (txtStatementDateFrom.Value != "") statementDateFrom = utils.formatStringToDate(txtStatementDateFrom.Value); DateTime statementDateTo = DateTime.Now; if (txtStatementDateTo.Value != "") statementDateTo = utils.formatStringToDate(txtStatementDateTo.Value); bool useDateRange = false; if (txtStatementDateFrom.Value != "" && txtStatementDateTo.Value != "") { useDateRange = true; } bool success = xDebtors.EmailAccountStatement(acc, ConfigurationManager.AppSettings["from"], ConfigurationManager.AppSettings["bcc"], ConfigurationManager.AppSettings["admin"], ConfigurationManager.AppSettings["WebAddy"], additionalEmailMessage, bbfDays, showCorrections, maxLines, fromZeroBalance, userId, statementDate, useDateRange, statementDateFrom, statementDateTo, "", emailPatient, emailPractice, emailMedicalAid, out validAccountEmail, out validPracticeEmail, out validMedicalAidEmail, this.NotesFieldName); if (emailMedicalAid && !validMedicalAidEmail) { lblEmailResultMedical.Text = "Invalid email for medical aid, or no email has been provided."; lblEmailResultMedical.ForeColor = System.Drawing.Color.Red; } if (emailPatient && !validAccountEmail) { lblEmailResultPatient.Text = "Invalid email for the account holder, or no email has been provided."; lblEmailResultPatient.ForeColor = System.Drawing.Color.Red; } if (success) { emailResults.Attributes["display"] = "normal"; if (validPracticeEmail) { lblEmailResultPractice.Text = "Email to Practice: Successful."; lblEmailResultPractice.ForeColor = System.Drawing.Color.Green; } if (validAccountEmail) { lblEmailResultPatient.Text = "Email to Account Holder: Successful."; lblEmailResultPatient.ForeColor = System.Drawing.Color.Green; } if (validMedicalAidEmail) { lblEmailResultMedical.Text = "Email to Medical Aid: Successful."; lblEmailResultMedical.ForeColor = System.Drawing.Color.Green; } } else { emailResults.Attributes["display"] = "normal"; lblEmailResultMedical.Text = "Email sending failed."; } upStatement.Update(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, Session["user"]); Response.Redirect("/error", false); } } #endregion #region claim events /// /// new claim click /// /// /// protected void btnNewClaim_Click(object sender, EventArgs e) { try { mediswitch = new MediSwitch(); if (mediswitch.isOnline()) { globe.ForeColor = System.Drawing.Color.Green; globe.ToolTip = "Mediswitch Online"; btnSubmitClaims.Enabled = true; } else { globe.ForeColor = System.Drawing.Color.Red; globe.ToolTip = "Mediswitch Offline"; btnSubmitClaims.Enabled = false; } BindClaimHistory(); BindClaimables(); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myClaimModal", "$('#modClaim').modal();", true); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// submit claims /// /// /// protected void btnSubmitClaims_Click(object sender, EventArgs e) { try { if (mediswitch == null) mediswitch = new MediSwitch(); bool gotError = false; foreach (RepeaterItem item in rptClaimable.Items) { var checkBox = (CheckBox)item.FindControl("chkId"); if (checkBox.Checked) { var lblInvoiceNo = (Label)item.FindControl("lblInvoiceNo"); string invoiceNo = lblInvoiceNo.Text; oAccount account = new oAccount(); foreach (oAccount acc in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "invoiceNo,isVisible", invoiceNo + ",1")) { account = acc; break; } string result = mediswitch.ClaimPatientDataSingle(account, true); if (!result.Contains("|"))//no pipes == error { gotError = true; var lblError = (Label)item.FindControl("lblError"); lblError.Text = result; } else { AddClaimNote(account.surfaceItemId, "Claim Submitted", "Claim Submitted through Mediswitch"); } } } if (!gotError) { BindClaimHistory(); BindClaimables(); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// claim history prerender /// /// /// protected void rptClaimHistory_PreRender(object sender, EventArgs e) { try { Repeater rpt = (Repeater)sender; foreach (RepeaterItem item in rpt.Items) { Label lblClaimResponse = (Label)item.FindControl("lblClaimResponse"); HiddenField hfClaimResultCode = (HiddenField)item.FindControl("hfClaimResultCode"); HiddenField hfClaimResponseParty = (HiddenField)item.FindControl("hfClaimResponseParty"); HiddenField hfReversalAllowed = (HiddenField)item.FindControl("hfReversalAllowed"); LinkButton btnClaimReverse = (LinkButton)item.FindControl("btnClaimReverse"); LinkButton btnClaimForceResponse = (LinkButton)item.FindControl("btnClaimForceResponse"); LinkButton btnClaimResubmit = (LinkButton)item.FindControl("btnClaimResubmit"); if (lblClaimResponse.Text == "Queued") { btnClaimForceResponse.Visible = true; btnClaimResubmit.Visible = false; btnClaimReverse.Visible = false; } else { btnClaimForceResponse.Visible = false; if (hfClaimResponseParty.Value == "02" && (hfClaimResultCode.Value == "03" || hfClaimResultCode.Value == "04" || hfClaimResultCode.Value == "05" || hfClaimResultCode.Value == "07")) { btnClaimReverse.Visible = true; btnClaimResubmit.Visible = false; } else if (hfClaimResponseParty.Value == "01" && (hfClaimResultCode.Value == "03")) { btnClaimReverse.Visible = false; btnClaimResubmit.Visible = true; } else { btnClaimReverse.Visible = false; btnClaimResubmit.Visible = false; } } if (hfReversalAllowed.Value == "False") btnClaimReverse.Visible = false; } for (int rowIndex = rpt.Items.Count - 2; rowIndex >= 0; rowIndex--) { RepeaterItem row = rpt.Items[rowIndex]; RepeaterItem previousRow = rpt.Items[rowIndex + 1]; Label lblInvoiceNo = (Label)row.FindControl("lblInvoiceNo"); Label lblInvoiceNoPrev = (Label)previousRow.FindControl("lblInvoiceNo"); Label lblDateOfService = (Label)row.FindControl("lblDateOfService"); Label lblDateOfServicePrev = (Label)previousRow.FindControl("lblDateOfService"); Label lblICD = (Label)row.FindControl("lblICD"); Label lblICDPrev = (Label)previousRow.FindControl("lblICD"); LinkButton btnClaimReversePrev = (LinkButton)previousRow.FindControl("btnClaimReverse"); if (lblInvoiceNo.Text == lblInvoiceNoPrev.Text) { lblInvoiceNoPrev.Visible = false; btnClaimReversePrev.Visible = false; } if (lblDateOfService.Text == lblDateOfServicePrev.Text) lblDateOfServicePrev.Visible = false; if (lblICD.Text == lblICDPrev.Text) lblICDPrev.Visible = false; } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// claim reverse /// /// /// protected void btnClaimReverse_Click(object sender, EventArgs e) { try { if (mediswitch == null) mediswitch = new MediSwitch(); LinkButton lnkReverse = (LinkButton)sender; string claimLogId = lnkReverse.CommandArgument; string result = mediswitch.ReverseClaim(claimLogId); BindClaimHistory(); BindClaimables(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// claim force response /// /// /// protected void btnClaimForceResponse_Click(object sender, EventArgs e) { try { if (mediswitch == null) mediswitch = new MediSwitch(); mediswitch.ProcessDelayed(); BindClaimHistory(); BindClaimables(); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// claim history databinding /// /// /// protected void rptClaimHistoryDetails_DataBinding(object sender, EventArgs e) { try { Repeater rptClaimHistoryDetails = (Repeater)sender; int invoiceNo = (int)(Eval("invoiceNo")); List StoredProcParams = new List(); oDynamicParam param = new oDynamicParam(); param.paramDisplayName = "invoiceNo"; param.paramObject = invoiceNo; StoredProcParams.Add(param); ArrayList claimHistory = xData.GetTypedCollectionByProc("surfaceItemId", typeof(ovAccountsClaimable), "sp_GetClaimResultDetails", StoredProcParams, "pal_"); rptClaimHistoryDetails.DataSource = claimHistory; } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// claim history prerender /// /// /// protected void rptClaimHistoryDetails_PreRender(object sender, EventArgs e) { try { Repeater rpt = (Repeater)sender; foreach (RepeaterItem item in rpt.Items) { Label lblClaimResponse = (Label)item.FindControl("lblClaimResponse"); if (lblClaimResponse.Text != "") { lblClaimResponse.Text += "
"; } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// close claims modal /// /// /// protected void btnCloseClaims_Click(object sender, EventArgs e) { rptAccounts.DataBind(); upAccounts.Update(); } /// /// claim resubmit /// /// /// protected void btnClaimResubmit_Click(object sender, EventArgs e) { try { if (mediswitch == null) mediswitch = new MediSwitch(); LinkButton lnkResubmit = (LinkButton)sender; string invoiceNo = lnkResubmit.CommandArgument; oAccount account = new oAccount(); foreach (oAccount acc in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "invoiceNo", invoiceNo)) { account = acc; break; } string result = mediswitch.ClaimPatientDataSingle(account, true); RepeaterItem item = (RepeaterItem)lnkResubmit.NamingContainer; if (!result.Contains("|"))//no pipes == error { var lblError = (Label)item.FindControl("lblClaimHistoryError"); lblError.Text = result; } else { BindClaimHistory(); BindClaimables(); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// claim response header databinding /// /// /// protected void rptClaimResponseHeader_DataBinding(object sender, EventArgs e) { try { Repeater rptClaimResponseHeader = (Repeater)sender; int claimLogId = (int)(Eval("claimLogId")); ArrayList claimResponseHeaderList = xData.GetTypedByCriteriaSpecific("recId", typeof(ovAccountClaimResponseHeader), "claimLogId", claimLogId.ToString(), "recId DESC", "pal_"); ArrayList claimResponseHeader = new ArrayList(); foreach (var item in claimResponseHeaderList) { claimResponseHeader.Add(item); break; } rptClaimResponseHeader.DataSource = claimResponseHeader; } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// claim response detail databinding /// /// /// protected void rptClaimResponseDetail_DataBinding(object sender, EventArgs e) { try { Repeater rptClaimResponseDetail = (Repeater)sender; int responseId = (int)(Eval("responseId")); ArrayList claimResponseDetail = xData.GetTypedByCriteriaSpecific("recId", typeof(ovAccountClaimResponseDetail), "responseId", responseId.ToString(), "recId", "pal_"); rptClaimResponseDetail.DataSource = claimResponseDetail; } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// claim response errors databinding /// /// /// protected void rptClaimResponseErrors_DataBinding(object sender, EventArgs e) { try { Repeater rptClaimResponseErrors = (Repeater)sender; int tRecId = (int)(Eval("recId")); ArrayList claimResponseErrors = xData.GetTypedByCriteriaSpecific("recId", typeof(ovAccountClaimResponseErrors), "recId", tRecId.ToString(), "recId", "pal_"); rptClaimResponseErrors.DataSource = claimResponseErrors; } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// claim history log databinding /// /// /// protected void rptClaimHistoryLog_DataBinding(object sender, EventArgs e) { try { Repeater rptClaimHistoryLog = (Repeater)sender; int invoiceNo = (int)(Eval("invoiceNo")); ArrayList claimHistoryLog = xData.GetTypedByCriteriaSpecific("claimLogId", typeof(ovAccountClaimHistoryLog), "invoiceNo", invoiceNo.ToString(), "claimLogId DESC", "pal_"); rptClaimHistoryLog.DataSource = claimHistoryLog; } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// claim response detail itemdatabound /// /// /// protected void rptClaimResponseDetail_ItemDataBound(object sender, RepeaterItemEventArgs e) { try { switch (e.Item.ItemType) { case ListItemType.Header: dTotalAmount = 0; dTotalMedicalLiable = 0; dTotalPatientLiable = 0; break; case ListItemType.Footer: Label lblTotalAmount = (Label)e.Item.FindControl("lblTotalAmount"); if (lblTotalAmount != null) { lblTotalAmount.Text = dTotalAmount.ToString(); } Label lblTotalMedicalLiable = (Label)e.Item.FindControl("lblTotalMedicalLiable"); if (lblTotalMedicalLiable != null) { lblTotalMedicalLiable.Text = dTotalMedicalLiable.ToString(); } Label lblTotalPatientLiable = (Label)e.Item.FindControl("lblTotalPatientLiable"); if (lblTotalPatientLiable != null) { lblTotalPatientLiable.Text = dTotalPatientLiable.ToString(); } break; case ListItemType.Item: Label lblTreatmentClaimedAmount = (Label)e.Item.FindControl("lblTreatmentClaimedAmount"); if (lblTreatmentClaimedAmount != null) { dTotalAmount += Convert.ToDecimal(lblTreatmentClaimedAmount.Text); } Label lblAuthAmountToProvider = (Label)e.Item.FindControl("lblAuthAmountToProvider"); if (lblAuthAmountToProvider != null) { dTotalMedicalLiable += Convert.ToDecimal(lblAuthAmountToProvider.Text); } Label lblPatientLiableAmount = (Label)e.Item.FindControl("lblPatientLiableAmount"); if (lblPatientLiableAmount != null) { dTotalPatientLiable += Convert.ToDecimal(lblPatientLiableAmount.Text); } break; case ListItemType.AlternatingItem: Label lblTreatmentClaimedAmountA = (Label)e.Item.FindControl("lblTreatmentClaimedAmount"); if (lblTreatmentClaimedAmountA != null) { dTotalAmount += Convert.ToDecimal(lblTreatmentClaimedAmountA.Text); } Label lblAuthAmountToProviderA = (Label)e.Item.FindControl("lblAuthAmountToProvider"); if (lblAuthAmountToProviderA != null) { dTotalMedicalLiable += Convert.ToDecimal(lblAuthAmountToProviderA.Text); } Label lblPatientLiableAmountA = (Label)e.Item.FindControl("lblPatientLiableAmount"); if (lblPatientLiableAmountA != null) { dTotalPatientLiable += Convert.ToDecimal(lblPatientLiableAmountA.Text); } break; case ListItemType.SelectedItem: break; case ListItemType.EditItem: break; case ListItemType.Separator: break; case ListItemType.Pager: break; default: break; } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } #endregion #endregion private void BindClaimHistory() { try { if (this.Account != null) { oAccount acc = this.Account; lblClaimHeading.Text = "for " + acc.patientName + " " + acc.patientSurname; ArrayList claimHistoryMain = xData.GetTypedByCriteriaSpecific("surfaceItemId", typeof(ovAccountClaimHistory), "surfaceItemId", acc.surfaceItemId.ToString(), "claimLogId DESC", "pal_"); rptClaimHistoryMain.DataSource = claimHistoryMain; rptClaimHistoryMain.DataBind(); //List StoredProcParams = new List(); //oDynamicParam param = new oDynamicParam(); //param.paramDisplayName = "surfaceItemId"; //param.paramObject = acc.surfaceItemId; //StoredProcParams.Add(param); //ArrayList claimHistory = xData.GetTypedCollectionByProc("surfaceItemId", typeof(oAccountsClaimable), "sp_GetClaimResults", StoredProcParams, "v_"); //rptClaimHistory.DataSource = claimHistory; //rptClaimHistory.DataBind(); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } private void BindClaimables() { try { if (this.Account != null) { oAccount acc = this.Account; ArrayList accountsClaimableList = xData.GetTypedByCriteriaSpecific("recId", typeof(ovAccountsClaimable), "surfaceItemId", acc.surfaceItemId.ToString(), "dateOfService", "pal_"); rptClaimable.DataSource = accountsClaimableList; rptClaimable.DataBind(); //verify MSV if (xData.GetTypedByCriteriaSpecific("surfaceItemId", typeof(ovAccountsVerifiedMSV), "surfaceItemId", acc.surfaceItemId.ToString(), "", "pal_").Count == 0) lblMSVVerified.Visible = true; } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } /// /// Post Modifier and post line /// /// /// protected void btnPostModifier_Click(object sender, EventArgs e) { try { if (PostBillingLine()) { BindBillingLines(); ClearPostings(); txtBillingCode.Focus(); upBilling.Update(); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "HideModModal", "$('#modModifiers').modal('hide')", true); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } protected void ddModAssistant_SelectedIndexChanged(object sender, EventArgs e) { try { if (ddModAssistant.SelectedItem.Text != "select an assistant...") { txtModAssistantRegistration.Text = ddModAssistant.SelectedValue.Substring(ddModAssistant.SelectedValue.IndexOf("_") + 1); txtModAssistantSurname.Text = ddModAssistant.SelectedItem.Text; } else { txtModAssistantRegistration.Text = ""; txtModAssistantSurname.Text = ""; } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } protected void ddEditModAssistant_SelectedIndexChanged(object sender, EventArgs e) { try { if (ddEditModAssistant.SelectedItem.Text != "select an assistant...") { txtEditModRegistration.Text = ddEditModAssistant.SelectedValue.Substring(ddEditModAssistant.SelectedValue.IndexOf("_") + 1); txtEditModSurname.Text = ddEditModAssistant.SelectedItem.Text; } else { txtEditModRegistration.Text = ""; txtEditModSurname.Text = ""; } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } protected void ddlSwitch_SelectedIndexChanged(object sender, EventArgs e) { try { int surfaceItemId = Convert.ToInt32(ddlSwitch.SelectedValue); int surfaceId = 0; foreach (oSurfaceItem item in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceItem), "recId", surfaceItemId.ToString())) { surfaceId = item.surfaceId; } oUser usr = new oUser(); if (utils.verifySession("user")) { usr = (oUser)Session["user"]; } oAccount account = xDebtors.SetAccountItem(surfaceItemId, surfaceId, usr); Session["account"] = account; this.Account = account; oAccount acc = this.Account; PopulatePageFormValues(ref acc); SetupControl(acc); } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, this.Account); Response.Redirect("/error", false); } } protected void lnkCopy_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { LinkButton lnkCopy = (LinkButton)sender; int invoiceNo = int.Parse(lnkCopy.CommandArgument); ArrayList billingLines = new ArrayList(); foreach (oAccount accToClone in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "invoiceNo", invoiceNo.ToString())) { oAccount acc = accToClone; acc.dateOfCapture = DateTime.Now; acc.dateOfService = DateTime.Now; //JR 2017-03-03 date of transaction acc.dateOfTransaction = DateTime.Now; acc.recId = 0; acc.invoiceNo = 0; billingLines.Add(acc); } Session["billingLines"] = billingLines; BindBillingLines(); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myBillingModal", "$('#modBilling').modal();", true); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "billingPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true); upBilling.Update(); } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } protected void lnkLocked_Click(object sender, EventArgs e) { try { if (sender.GetType() == typeof(LinkButton)) { LinkButton lnkLocked = (LinkButton)sender; int recId = int.Parse(lnkLocked.CommandArgument); foreach (oAccount accEdit in xData.GetTypedByCriteriaSpecific("recId", typeof(oAccount), "recId", recId.ToString())) { oAccount acc = accEdit; Session["accountEdit"] = acc; PopulateEditLineValues(ref acc, true); upEdit.Update(); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "myEditFinalModal", "$('#modEdit').modal();", true); ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "editFinalPicker", "$('.palette-datepicker').datepicker({format: 'dd/mm/yyyy'}); ; ", true); ScriptManager.RegisterStartupScript(Page, Page.GetType(), "setLoadOptions", "if(typeof(setLoadOptions) == \"function\"){window.onload = setLoadOptions()};", true); break; } } } catch (Exception ex) { exception.HandleException("enquiry:", MethodBase.GetCurrentMethod().Name, ex, 0); Response.Redirect("/error", false); } } }