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); } } private static string BillingAwareControlId(string controlId, bool isBilling) { if (!isBilling) return controlId; if (controlId.StartsWith("hf", StringComparison.Ordinal)) return "hfBilling" + controlId.Substring(2); if (controlId.StartsWith("lbl", StringComparison.Ordinal)) return "lblBilling" + controlId.Substring(3); return controlId; } private static T FindBillingAwareControl(RepeaterItem item, string controlId, bool isBilling) where T : Control { return item.FindControl(BillingAwareControlId(controlId, isBilling)) as T; } /// /// Item Databound Event /// /// /// protected void rptAccounts_ItemDataBound(object sender, RepeaterItemEventArgs e) { try { bool isBilling = string.Equals((sender as Repeater)?.ID, "rptBillingAccounts", StringComparison.Ordinal); HiddenField hfType = FindBillingAwareControl(e.Item, "hfType", isBilling); if (hfType != null) { //amount field Label lblAmount = FindBillingAwareControl