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.Threading.Tasks; using System.Web; namespace framework_business { public class xSurfaceCustomAction { private static void AddCreateDocumentNote(int patientItemId, string noteTitle, string noteCaption, string tempPath, int userId, ref ArrayList attList, string fieldName) { try { oNote note = new oNote(); note.moduleId = pNums.Module.Surface.GetHashCode(); note.typeId = pNums.NoteType.General.GetHashCode(); note.entityId = patientItemId; note.title = noteTitle; note.caption = noteCaption; note.dateSaved = DateTime.Now; note.userIdSaved = userId; note.isActive = true; note.fieldName = fieldName; note.recId = xData.SaveTyped("recId", typeof(oNote), note); //add statement as attachment to note foreach (oAttachment noteAtt in attList) { noteAtt.dateSaved = DateTime.Now; noteAtt.entityId = note.recId; noteAtt.folderName = "note/" + note.recId; noteAtt.isActive = true; noteAtt.moduleId = pNums.Module.Notes.GetHashCode(); noteAtt.typeId = pNums.AttachmentType.Document.GetHashCode(); noteAtt.userIdSaved = note.userIdSaved; //CVH 2016-10-28 Save PDF to file folder, not straight in root of note item folder string moveTo = HttpContext.Current.Server.MapPath("~/upload/" + noteAtt.folderName + "/file/"); utils.validateFolder(moveTo); System.IO.File.Move(tempPath + noteAtt.fileName, moveTo + noteAtt.fileName); noteAtt.recId = xData.SaveTyped("recId", typeof(oAttachment), noteAtt); } } catch (Exception ex) { //log don't redirect exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, userId); } } private static string ReplaceTempTagsFromTable(string content, DataTable dt, ArrayList fields) { try { if (dt == null || dt.Rows.Count <= 0) return content; //replace temp tags foreach (DataColumn col in dt.Columns) { string value = dt.Rows[0][col].ToString(); if (col.ColumnName.EndsWith("_PostalAddress")) { value = value.Replace("\n", "
"); } else if (col.ColumnName.EndsWith("_MedicalAidSchemeName")) { string medCode = value; foreach (oMedicalScheme medScheme in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalScheme), "code", medCode)) { value = medScheme.name; } } else { foreach (oSurfaceField field in fields) { if (field.surfaceFieldName == col.ColumnName) { if (field.surfaceFieldTypeId == pNums.FieldType.CheckboxList.GetHashCode()) { string checkSplitValue = value; value = ""; foreach (string checkValue in checkSplitValue.Split(',')) { value += "- " + checkValue + "
"; } } else if (field.surfaceFieldTypeId == pNums.FieldType.Checkbox.GetHashCode()) { if (value == "1") value = field.surfaceFieldDisplay; else if (value == "0") value = ""; } break; } } } content = content.Replace("{" + col.ColumnName + "}", value); } return content; } catch (Exception ex) { exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); return content; } } private static string ReplaceTempTagsFromTableCustom(string content, DataTable dt, ArrayList fields, DataTable dtMap = null) { try { if (dt == null || dt.Rows.Count <= 0) return content; if (!content.Contains("Physio Referral Letter") || dt.Columns["PatientInformation_PatientDetails_Surname"] != null) { //replace temp tags foreach (DataColumn col in dt.Columns) { string value = dt.Rows[0][col].ToString(); if (col.ColumnName.EndsWith("_PostalAddress")) { value = value.Replace("\n", "
"); } else if (col.ColumnName.EndsWith("_CTScanOptions")) { string splitValue = value; value = ""; foreach (string ctOption in splitValue.Split(',')) { if (ctOption.Trim().StartsWith("Glenohumeral")) value += "- Glenohumeral Osteo arthritis - assess glenoid for arthroplasty, rotator cuff muscles atrophy
"; else if (ctOption.Trim().StartsWith("Proximal")) value += "- Proximal humerus fracture plus 3D recon
"; else if (ctOption.Trim().StartsWith("Bony Healing")) value += "- Bony Healing post fracture
"; else if (ctOption.Trim().StartsWith("Post latarjet")) value += "- Post latarjet procedure
"; } } else if (col.ColumnName.EndsWith("_MedicalAidSchemeName")) { string medCode = value; foreach (oMedicalScheme medScheme in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalScheme), "code", medCode)) { value = medScheme.name; } } else if (handler.ReturnSetup().code == "SHOU-1" && col.ColumnName == "GeneralSurgicalNotes_GeneralSurgicalNotesGroup_Date") { value = utils.fixDate(value); if (value.Length > 10) value = value.Substring(0, 10); } else if (handler.ReturnSetup().code == "SHOU-1" && col.ColumnName == "GeneralSurgicalNotes_GeneralSurgicalNotesGroup_Side") { string lookupText = ""; foreach (oSurfaceLookup look in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceLookup), "recId", value)) { lookupText = look.display; break; } value = lookupText; } else { foreach (oSurfaceField field in fields) { if (field.surfaceFieldName == col.ColumnName) { if (field.surfaceFieldTypeId == pNums.FieldType.CheckboxList.GetHashCode()) { if (handler.ReturnSetup().code == "SHOU-1" && field.surfaceFieldName.StartsWith("Letters_PhysiotherapistLetter_")) { //CVH 2017-10-19 Get value from SurfaceFieldData, the published table saves the "Reason" text, not the qt table int itemID = 0; if (dt.Rows[0]["itemID"] != null) int.TryParse(dt.Rows[0]["itemID"].ToString(), out itemID); if (itemID > 0) { foreach (oSurfaceFieldData data in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceFieldData), "surfaceId,surfaceFieldID,surfaceItemId", field.surfaceId + "," + field.recId + "," + itemID)) { value = data.surfaceFieldValueChar; } } string checkSplitValue = value; value = ""; String[] list = null; if (checkSplitValue.IndexOf("~|~") >= 0) list = checkSplitValue.Split(new string[] { "~|~" }, StringSplitOptions.None); else list = checkSplitValue.Split(','); foreach (string checkValue in list) { string lookupId = ""; string reason = ""; if (checkValue.IndexOf("~R~") >= 0) { lookupId = checkValue.Substring(0, checkValue.IndexOf("~R~")); reason = checkValue.Substring(checkValue.IndexOf("~R~") + 3); } else { lookupId = checkValue; } string lookupText = ""; foreach (oSurfaceLookup look in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceLookup), "recId", lookupId)) { lookupText = look.display; } if (lookupText != "") { value += "- " + lookupText + (reason == "" ? "" : ": " + reason) + "
"; } //else if (field.surfaceFieldName == "Letters_PhysiotherapistLetter_EFROZENSHOULDER") else if (field.surfaceFieldName == "Letters_PhysiotherapistLetter_EFROZENSHOULDER" && value == String.Empty) { value += "Not Applicable"; } } } else { string checkSplitValue = value; value = ""; foreach (string checkValue in checkSplitValue.Split(',')) { value += "- " + checkValue + "
"; } } } else if (field.surfaceFieldTypeId == pNums.FieldType.Checkbox.GetHashCode()) { if (value == "1") value = field.surfaceFieldDisplay; else if (value == "0") value = ""; } break; } } } content = content.Replace("{" + col.ColumnName + "}", value); } } else { string customvalue = String.Empty; foreach (oSurfaceField field in fields) { bool isCustom = false; foreach (DataColumn col in dt.Columns) { string value = dt.Rows[0][col].ToString(); if (field.surfaceFieldName == col.ColumnName) { if (field.surfaceFieldTypeId == pNums.FieldType.CheckboxList.GetHashCode()) { if (handler.ReturnSetup().code == "SHOU-1" && field.surfaceFieldName.StartsWith("Letters_PhysiotherapistLetter_")) { //CVH 2017-10-19 Get value from SurfaceFieldData, the published table saves the "Reason" text, not the qt table int itemID = 0; if (dt.Rows[0]["itemID"] != null) int.TryParse(dt.Rows[0]["itemID"].ToString(), out itemID); if (itemID > 0) { foreach (oSurfaceFieldData data in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceFieldData), "surfaceId,surfaceFieldID,surfaceItemId", field.surfaceId + "," + field.recId + "," + itemID)) { value = data.surfaceFieldValueChar; } } string checkSplitValue = value; value = ""; String[] list = null; if (checkSplitValue.IndexOf("~|~") >= 0) list = checkSplitValue.Split(new string[] { "~|~" }, StringSplitOptions.None); else list = checkSplitValue.Split(','); foreach (string checkValue in list) { string lookupId = ""; string reason = ""; if (checkValue.IndexOf("~R~") >= 0) { lookupId = checkValue.Substring(0, checkValue.IndexOf("~R~")); reason = checkValue.Substring(checkValue.IndexOf("~R~") + 3); } else { lookupId = checkValue; } string lookupText = ""; foreach (oSurfaceLookup look in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceLookup), "recId", lookupId)) { lookupText = look.display; } if (lookupText != "") { //CVH 2017-12-13 Check mapping table to see if text needs to be replaced string surfaceText = lookupText; string letterText = lookupText; if (handler.ReturnSetup().code == "SHOU-1" && content.Contains("Physio Referral Letter") && dtMap != null && dtMap.Rows.Count > 0 && dtMap.Columns["ReplacementText_ReplacementText_SurfaceText"] != null && dtMap.Columns["ReplacementText_ReplacementText_LetterText"] != null) { DataRow[] foundRows = dtMap.Select("TRIM(ReplacementText_ReplacementText_SurfaceText) = '" + surfaceText.Trim() + "' "); if (foundRows != null && foundRows.Count() > 0) { letterText = foundRows[0]["ReplacementText_ReplacementText_LetterText"].ToString().Trim(); if (letterText == "") letterText = surfaceText; } } //value += "- " + lookupText + (reason == "" ? "" : ": " + reason) + "
"; value += "- " + letterText + (reason == "" ? "" : ": " + reason) + "
"; } //else if (field.surfaceFieldName == "Letters_PhysiotherapistLetter_EFROZENSHOULDER") else if (field.surfaceFieldName == "Letters_PhysiotherapistLetter_EFROZENSHOULDER" && value == String.Empty) { value += "Not Applicable"; } } } else { string checkSplitValue = value; value = ""; foreach (string checkValue in checkSplitValue.Split(',')) { value += "- " + checkValue + "
"; } } } else if (field.surfaceFieldTypeId == pNums.FieldType.Checkbox.GetHashCode()) { if (value == "1") value = field.surfaceFieldDisplay; else if (value == "0") value = ""; } if (handler.ReturnSetup().code == "SHOU-1" && (col.ColumnName == "Letters_PhysiotherapistLetter_BKindlyAssist" || (field.surfaceFieldName.StartsWith("Letters_PhysiotherapistLetter_") && field.surfaceFieldDisplay.IndexOf(".") > 0 && (field.surfaceFieldDisplay.Substring(0, field.surfaceFieldDisplay.IndexOf(".")).Contains("X") || field.surfaceFieldDisplay.Substring(0, field.surfaceFieldDisplay.IndexOf(".")).Contains("I") || field.surfaceFieldDisplay.Substring(0, field.surfaceFieldDisplay.IndexOf(".")).Contains("V"))))) { isCustom = true; if (field.surfaceFieldTypeId == pNums.FieldType.CheckboxList.GetHashCode() && value.Length > 0) value = field.surfaceFieldDisplay + ":
" + value + "
"; } if (isCustom) { if (customvalue == String.Empty || customvalue.EndsWith("
")) customvalue += value; else customvalue += "

" + value; customvalue = customvalue.Replace("- ", "         "); } else content = content.Replace("{" + col.ColumnName + "}", value); break; } } } if (handler.ReturnSetup().code == "SHOU-1" && customvalue != String.Empty) content = content.Replace("{Letters_PhysiotherapistLetter_BKindlyAssist}", customvalue); } return content; } catch (Exception ex) { exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); return content; } } public static string BuildICDList(int examItemId, int examSurfaceId, ref string secondIcd) { string icd = ""; secondIcd = ""; try { List examFields = (xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceId,isActive", examSurfaceId + ",1")).Cast().ToList(); if (examFields.Count <= 0) return icd; foreach (oSurfaceField diagTab in examFields.Where(r => r.surfaceFieldTypeId == (int)pNums.FieldType.Tab && r.surfaceFieldDisplay == "Diagnosis")) { foreach (oSurfaceField diagGrp in examFields.Where(r => r.surfaceFieldTypeId == (int)pNums.FieldType.Group && r.parentId == diagTab.recId)) { foreach (oSurfaceField diagSurfField in examFields.Where(r => r.surfaceFieldTypeId == (int)pNums.FieldType.Grid && r.parentId == diagGrp.recId)) { foreach (oSurface diagSurf in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "name", diagSurfField.relationalSurface)) { DataTable dtDiag = xData.GetChildSurfaceQueryData(diagSurf.recId, examItemId); DataColumn colYes = null; DataColumn colIcd = null; DataColumn col2nd = null; foreach (DataColumn col in dtDiag.Columns) { if (col.ColumnName.EndsWith("_Yes")) colYes = col; else if (col.ColumnName.EndsWith("_PrimaryICD10")) colIcd = col; else if (col.ColumnName.EndsWith("_SecondaryICD10")) col2nd = col; } if (colYes == null || colIcd == null) continue; foreach (DataRow row in dtDiag.Rows) { if (row[colYes].ToString() == "1") { icd = row[colIcd].ToString(); if (col2nd != null) secondIcd = row[col2nd].ToString(); break; } } if (icd != "") break; } if (icd != "") break; } if (icd != "") break; } break; } return icd; } catch (Exception ex) { exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); return icd; } } public static string BuildDiagnosisList(int examItemId, int examSurfaceId) { string diagnosis = ""; try { List examFields = (xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceId,isActive", examSurfaceId + ",1")).Cast().ToList(); if (examFields.Count <= 0) return diagnosis; foreach (oSurfaceField diagTab in examFields.Where(r => r.surfaceFieldTypeId == (int)pNums.FieldType.Tab && r.surfaceFieldDisplay == "Diagnosis")) { foreach (oSurfaceField diagGrp in examFields.Where(r => r.surfaceFieldTypeId == (int)pNums.FieldType.Group && r.parentId == diagTab.recId)) { foreach (oSurfaceField diagSurfField in examFields.Where(r => r.surfaceFieldTypeId == (int)pNums.FieldType.Grid && r.parentId == diagGrp.recId)) { foreach (oSurface diagSurf in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "name", diagSurfField.relationalSurface)) { DataTable dtDiag = xData.GetChildSurfaceQueryData(diagSurf.recId, examItemId); DataColumn colYes = null; DataColumn colDiag = null; foreach (DataColumn col in dtDiag.Columns) { if (col.ColumnName.EndsWith("_Yes")) colYes = col; else if (col.ColumnName.EndsWith("_Diagnosis")) colDiag = col; } if (colYes == null || colDiag == null ) continue; foreach (DataRow row in dtDiag.Rows) { if (row[colYes].ToString() == "1") { if (diagnosis == "") diagnosis = row[colDiag].ToString(); else diagnosis += ", " + row[colDiag].ToString(); } } } } } break; } return diagnosis; } catch (Exception ex) { exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); return diagnosis; } } public static string BuildSentForList(DataTable dtExam) { string sentFor = ""; try { if (dtExam.Columns["ManagementPlan_SendforXRay_SendforXRay"] != null && dtExam.Rows[0]["ManagementPlan_SendforXRay_SendforXRay"].ToString() == "1") sentFor += "- X-Ray
"; if (dtExam.Columns["ManagementPlan_SendforCTScan_SendforCTScan"] != null && dtExam.Rows[0]["ManagementPlan_SendforCTScan_SendforCTScan"].ToString() == "1") sentFor += "- CT Scan
"; if (dtExam.Columns["ManagementPlan_SendforMRIScan_SendforMRIScan"] != null && dtExam.Rows[0]["ManagementPlan_SendforMRIScan_SendforMRIScan"].ToString() == "1") sentFor += "- MRI Scan
"; return sentFor; } catch (Exception ex) { exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); return sentFor; } } #region Backup //private static string BuildICDList(int examItemId) //{ // string icd = ""; // try // { // foreach (oMedicalPatientDiagnosis pd in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalPatientDiagnosis), "surfaceItemId", examItemId.ToString())) // { // foreach (oMedicalICD10 icd10 in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalICD10), "recId", pd.primaryIcd.ToString())) // { // icd += icd10.icdCode + " - " + icd10.icdDescription + ". "; // } // } // return icd; // } // catch (Exception ex) // { // exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); // return icd; // } //} //private static string BuildICDListOLD(DataTable dtPatientData, DataTable dtPlanData, int patientItemId) //{ // string icd = ""; // try // { // oSurfaceField diagnosisParentSurfaceItemIdField = null; // oSurfaceField childLinkField = null; // //get diagnosis field // foreach (oSurfaceField diagnosisField in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceFieldTypeId,controlledValue", pNums.FieldType.Control.GetHashCode() + "," + pNums.Module.Diagnosis.GetHashCode())) // { // foreach (oSurfaceField diagnosisSurfaceField in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceId", diagnosisField.surfaceId.ToString())) // { // //get linking field between child surfaces // //only process field types text and number // if (diagnosisSurfaceField.surfaceFieldTypeId != pNums.FieldType.Text.GetHashCode() && // diagnosisSurfaceField.surfaceFieldTypeId != pNums.FieldType.Number.GetHashCode()) // continue; // if (diagnosisSurfaceField.surfaceFieldDisplay == "ParentSurfaceItemId") // { // diagnosisParentSurfaceItemIdField = diagnosisSurfaceField; // } // else // { // childLinkField = diagnosisSurfaceField; // break; // } // } // break; // } // if (childLinkField == null) // return icd; // //get plan link field value, same name // string linkValue = ""; // foreach (DataColumn col in dtPlanData.Columns) // { // if (col.ColumnName.EndsWith("_" + utils.stripCharacters(childLinkField.surfaceFieldDisplay).Replace(" ", ""))) // { // linkValue = dtPlanData.Rows[0][col].ToString(); // break; // } // } // if (linkValue == "0") // linkValue = ""; // if (linkValue == "") // return icd; // List list = new List(); // oDynamicParam par1 = new oDynamicParam(); // par1.paramDisplayName = "SurfaceID"; // par1.paramObject = childLinkField.surfaceId; // list.Add(par1); // oDynamicParam par2 = new oDynamicParam(); // par2.paramDisplayName = "ParentSurfaceItemId"; // par2.paramObject = patientItemId; // list.Add(par2); // DataTable dtDiagnosisData = xData.GetTypedTableByProc("recId", typeof(oSurfaceFieldData), "sp_GetChildSurfaceData", list); // if (dtDiagnosisData == null || dtDiagnosisData.Rows.Count <= 0) // return icd; // //get all diagnosis items with same link value as plan item // foreach (DataRow row in dtDiagnosisData.Rows) // { // if (row[childLinkField.surfaceFieldName].ToString() == linkValue) // { // string itemId = row["itemID"].ToString(); // foreach (oMedicalPatientDiagnosis pd in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalPatientDiagnosis), "surfaceItemId", itemId)) // { // foreach (oMedicalICD10 icd10 in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalICD10), "recId", pd.primaryIcd.ToString())) // { // icd += icd10.icdCode + " - " + icd10.icdDescription + ". "; // } // } // } // } // return icd; // } // catch (Exception ex) // { // exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); // return icd; // } //} #endregion private static decimal CalculateProcedureAmount(string medicalAidCode, string procedureCode, int placeOfServiceIndicator) { decimal amount = 0; foreach (oTariffRate rate in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffRate), "planCode,procedureCode", medicalAidCode + "," + procedureCode)) { foreach (oPlaceOfService poc in xData.GetTypedByCriteriaSpecific("recId", typeof(oPlaceOfService), "indicator", placeOfServiceIndicator.ToString())) { //CVH 2017-01-11 Cortisone is a consumable and always charged at standard rate, not iHRate if (rate.procedureCode == "C2" || rate.procedureCode == "3602") { amount = rate.rate; } else { if (poc.rateType == "IH") amount = rate.iHRate; if (poc.rateType == "OH") amount = rate.oHRate; } } break; } return amount; } private static DataTable BuildProcedureCalculation(ArrayList bookings, string planCode) { DataTable dt = new DataTable(); dt.Columns.Add("code", System.Type.GetType("System.String")); dt.Columns.Add("description", System.Type.GetType("System.String")); dt.Columns.Add("quantity", System.Type.GetType("System.Int32")); dt.Columns.Add("rate", System.Type.GetType("System.Decimal")); dt.Columns.Add("amount", System.Type.GetType("System.Decimal")); try { //split bookings between surgical, modifiers to apply to surgical, and other (modifier 0011, and consumables and non-surgical) DataTable dtSurgical = dt.Clone(); List modifierList = new List(); List modEmergency = new List(); //0011 emergency, not applied to each surgical procedure DataTable dtOther = dt.Clone(); //assuming modifier 0005 will always only be applied once bool apply0005 = false; //get procedure master list ArrayList procedures = xData.GetTypedCollection("recId", typeof(oMedicalProcedure)); //get list of surgical procedures with calculated rate foreach (oMedicalPatientProcedureBooking booking in bookings) { //find procedure oMedicalProcedure proc = null; foreach (oMedicalProcedure procedure in procedures) { if (procedure.recId == booking.procedureId) { proc = procedure; break; } } if (proc.codeType == 0 && !proc.nonSurgical) //service item & surgical { decimal rate = decimal.Round(CalculateProcedureAmount(planCode, proc.code, booking.placeOfServiceIndicator), 2); DataRow newRow = dtSurgical.NewRow(); newRow["code"] = proc.code; newRow["description"] = proc.description; newRow["quantity"] = booking.procedureQty; newRow["rate"] = rate; newRow["amount"] = decimal.Round(booking.procedureQty * rate, 2); dtSurgical.Rows.Add(newRow); } else if (proc.codeType == 2 && proc.code != "0005" && proc.code != "0011") //modifier excluding 0005, and excluding emergency (not applied to each procedure) { modifierList.Add(proc); } else if (proc.codeType == 2 && proc.code == "0005") { apply0005 = true; } else if (proc.codeType == 2) { modEmergency.Add(booking); } else { decimal rateOther = decimal.Round(CalculateProcedureAmount(planCode, proc.code, booking.placeOfServiceIndicator), 2); DataRow newOther = dtOther.NewRow(); newOther["code"] = proc.code; newOther["description"] = proc.description; newOther["quantity"] = booking.procedureQty; newOther["rate"] = rateOther; newOther["amount"] = decimal.Round(booking.procedureQty * rateOther, 2); dtOther.Rows.Add(newOther); } } //sort by amount descending dtSurgical = dtSurgical.AsEnumerable() .OrderByDescending(r => r.Field("amount")) .CopyToDataTable(); var sortedRows = dtSurgical.AsEnumerable() .OrderByDescending(r => r.Field("amount")) .CopyToDataTable(); //if modifier 0005, apply discount for multiple procedures if (apply0005) { for (int i = 0; i < dtSurgical.Rows.Count; i++) { if (i == 0) //100% { dtSurgical.Rows[i]["code"] = dtSurgical.Rows[i]["code"].ToString() + " (0005)"; dtSurgical.Rows[i]["rate"] = decimal.Parse(dtSurgical.Rows[i]["rate"].ToString()); dtSurgical.Rows[i]["amount"] = decimal.Parse(dtSurgical.Rows[i]["amount"].ToString()); } else if (i == 1) //75% { dtSurgical.Rows[i]["code"] = dtSurgical.Rows[i]["code"].ToString() + " (0005)"; dtSurgical.Rows[i]["rate"] = decimal.Parse(dtSurgical.Rows[i]["rate"].ToString()) * 0.75m; dtSurgical.Rows[i]["amount"] = decimal.Parse(dtSurgical.Rows[i]["amount"].ToString()) * 0.75m; } else if (i == 2) //50% { dtSurgical.Rows[i]["code"] = dtSurgical.Rows[i]["code"].ToString() + " (0005)"; dtSurgical.Rows[i]["rate"] = decimal.Parse(dtSurgical.Rows[i]["rate"].ToString()) * 0.5m; dtSurgical.Rows[i]["amount"] = decimal.Parse(dtSurgical.Rows[i]["amount"].ToString()) * 0.5m; } else //25% { dtSurgical.Rows[i]["code"] = dtSurgical.Rows[i]["code"].ToString() + " (0005)"; dtSurgical.Rows[i]["rate"] = decimal.Parse(dtSurgical.Rows[i]["rate"].ToString()) * 0.25m; dtSurgical.Rows[i]["amount"] = decimal.Parse(dtSurgical.Rows[i]["amount"].ToString()) * 0.25m; } } } //loop through surgical procedures, and apply modifiers (excl 0005 and 0011) foreach (DataRow surgRow in dtSurgical.Rows) { /* code, description, quantity, rate, amount */ //add surgical procedure string description = surgRow["description"].ToString(); int qty = 0; int.TryParse(surgRow["quantity"].ToString(), out qty); qty = (qty < 1 ? 1 : qty); decimal rate = 0m; decimal.TryParse(surgRow["rate"].ToString(), out rate); decimal amount = 0; decimal.TryParse(surgRow["amount"].ToString(), out amount); DataRow addSurg = dt.NewRow(); addSurg["code"] = surgRow["code"].ToString(); addSurg["description"] = description; addSurg["quantity"] = qty; addSurg["rate"] = rate; addSurg["amount"] = amount; dt.Rows.Add(addSurg); foreach (oMedicalProcedure modProc in modifierList) { switch (modProc.code) { case "0018": //obese, add 50% DataRow addObese = dt.NewRow(); addObese["code"] = "0018"; addObese["description"] = description; addObese["quantity"] = 1; addObese["rate"] = decimal.Round(rate * 0.5m, 2); addObese["amount"] = decimal.Round(amount * 0.5m, 2); dt.Rows.Add(addObese); break; case "0014": //revision, add 50% DataRow addRevision = dt.NewRow(); addRevision["code"] = "0014"; addRevision["description"] = description; addRevision["quantity"] = 1; addRevision["rate"] = decimal.Round(rate * 0.5m, 2); addRevision["amount"] = decimal.Round(amount * 0.5m, 2); dt.Rows.Add(addRevision); break; case "0009": //assistant, add 20% DataRow addAssist = dt.NewRow(); addAssist["code"] = "0009"; addAssist["description"] = description; addAssist["quantity"] = 1; addAssist["rate"] = decimal.Round(rate * 0.2m, 2); addAssist["amount"] = decimal.Round(amount * 0.2m, 2); dt.Rows.Add(addAssist); break; case "0008": //specialist, add 33% DataRow addSpecial = dt.NewRow(); addSpecial["code"] = "0008"; addSpecial["description"] = description; addSpecial["quantity"] = 1; addSpecial["rate"] = decimal.Round(rate * 0.33m, 2); addSpecial["amount"] = decimal.Round(amount * 0.33m, 2); dt.Rows.Add(addSpecial); break; } } } //loop through modifier emergendy, should only be one foreach (oMedicalPatientProcedureBooking emerg in modEmergency) { DataRow addEmerg = dt.NewRow(); addEmerg["code"] = "0011"; addEmerg["description"] = "Emergency Procedure"; addEmerg["quantity"] = emerg.procedureQty; addEmerg["rate"] = 426m; addEmerg["amount"] = 426m * emerg.procedureQty; dt.Rows.Add(addEmerg); } //loop through other rows and add each foreach (DataRow rowOther in dtOther.Rows) { dt.Rows.Add(rowOther.ItemArray); } } catch (Exception ex) { exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); } return dt; } private static DataTable BuildConsultingProcedureCalculation(ArrayList bookings, string planCode) { DataTable dt = new DataTable(); dt.Columns.Add("code", System.Type.GetType("System.String")); dt.Columns.Add("description", System.Type.GetType("System.String")); dt.Columns.Add("quantity", System.Type.GetType("System.Int32")); dt.Columns.Add("rate", System.Type.GetType("System.Decimal")); dt.Columns.Add("amount", System.Type.GetType("System.Decimal")); try { DataTable dtProcedures = dt.Clone(); //get procedure master list ArrayList procedures = xData.GetTypedCollection("recId", typeof(oMedicalProcedure)); //get list of surgical procedures with calculated rate foreach (oMedicalPatientProcedureBooking booking in bookings) { //find procedure oMedicalProcedure proc = null; foreach (oMedicalProcedure procedure in procedures) { if (procedure.recId == booking.procedureId) { proc = procedure; break; } } //CVH 2016-12-19 All procedures to be added decimal rate = decimal.Round(CalculateProcedureAmount(planCode, proc.code, booking.placeOfServiceIndicator), 2); DataRow newRow = dtProcedures.NewRow(); newRow["code"] = proc.code; newRow["description"] = proc.description; newRow["quantity"] = booking.procedureQty; newRow["rate"] = rate; newRow["amount"] = decimal.Round(booking.procedureQty * rate, 2); dtProcedures.Rows.Add(newRow); } foreach (DataRow surgRow in dtProcedures.Rows) { /* code, description, quantity, rate, amount */ //add surgical procedure string description = surgRow["description"].ToString(); int qty = 0; int.TryParse(surgRow["quantity"].ToString(), out qty); qty = (qty < 1 ? 1 : qty); decimal rate = 0m; decimal.TryParse(surgRow["rate"].ToString(), out rate); decimal amount = 0; decimal.TryParse(surgRow["amount"].ToString(), out amount); DataRow addSurg = dt.NewRow(); addSurg["code"] = surgRow["code"].ToString(); addSurg["description"] = description; addSurg["quantity"] = qty; addSurg["rate"] = rate; addSurg["amount"] = amount; dt.Rows.Add(addSurg); } } catch (Exception ex) { exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); } return dt; } private static string BuildInvoiceLines(ArrayList bookings, DateTime date, bool isProForma, string medicalAidCode, ref decimal total) { StringBuilder lineResult = new StringBuilder(); string patient = String.Empty; total = 0; try { //build header lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); //get all procedures //ArrayList procedures = xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "codeType", "0"); //get plan code string planCode = ""; foreach (oMedicalScheme schm in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalScheme), "code", medicalAidCode)) { if (schm.planCode != String.Empty) { planCode = schm.planCode; break; } } //calculate procedure lines DataTable dtLines = new DataTable(); if (isProForma) dtLines = BuildProcedureCalculation(bookings, planCode); else dtLines = BuildConsultingProcedureCalculation(bookings, planCode); //build lines foreach (DataRow row in dtLines.Rows) { //get amount decimal amount = 0m; decimal.TryParse(row["amount"].ToString(), out amount); total += amount; lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); } //end lineResult.AppendLine("
DateCodeDescriptionQuantityRateAmount
" + date.ToString("dd-MMM-yy") + "" + row["code"].ToString() + "" + utils.stripSpecialCharacters(row["description"].ToString()) + "" + utils.returnFormattedDecimal(row["quantity"].ToString()).Replace(" ", ",") + "" + utils.returnFormattedDecimal(row["rate"].ToString()).Replace(" ", ",") + "" + utils.returnFormattedDecimal(Convert.ToString(amount)).Replace(" ", ",") + "
"); } catch (Exception ex) { exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); } return lineResult.ToString(); } /// /// Build Pro Forma invoice lines from Estimations child grid /// /// /// /// /// /// /// private static string BuildInvoiceLinesProForma(int examId, DateTime date, string medicalAidCode, ref decimal total) { StringBuilder lineResult = new StringBuilder(); string patient = String.Empty; total = 0; bool linesSelected = false; try { //build header lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); /* Estimations_Details_ProcedureDescription Estimations_Details_Amount Estimations_Details_Select */ //calculate procedure lines int estimationsSurfaceId = 0; foreach (oSurface est in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "surface", "Estimations")) { estimationsSurfaceId = est.recId; break; } DataTable dtLines = xData.GetChildSurfaceQueryData(estimationsSurfaceId, examId); //build lines foreach (DataRow row in dtLines.Rows) { if (row["Estimations_Details_Select"].ToString() == "1") { linesSelected = true; //get amount decimal amount = 0m; decimal.TryParse(row["Estimations_Details_Amount"].ToString(), out amount); total += amount; lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); lineResult.AppendLine(""); } } //end lineResult.AppendLine("
Procedure DescriptionAmount
" + utils.stripSpecialCharacters(row["Estimations_Details_ProcedureDescription"].ToString()) + "" + utils.returnFormattedDecimal(amount.ToString()).Replace(" ", ",") + "
"); if (!linesSelected) lineResult = new StringBuilder(); } catch (Exception ex) { exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); } return lineResult.ToString(); } private static bool CreateProFormaInvoice(string contentHeader, string contentBody, string fileName, string tempPath, DataTable dtPatient, string webAddress, oMedicalPractice practice, ArrayList bookings, string icd, bool isProForma, int examId) { try { bool result = false; //build header utils.MergeHTMData(ref contentHeader, utils.BuildFieldCodeList(practice, true)); //contentHeader = contentHeader.Replace("{Heading}", "Pro Forma Invoice"); contentHeader = contentHeader.Replace("{WebAddress}", webAddress); contentHeader = contentHeader.Replace("{Date}", utils.fixDate(DateTime.Now)); contentHeader = contentHeader.Replace("{ICD10}", icd); contentHeader = contentHeader.Replace("src=\"/images/", "src=\"" + webAddress + "/images/"); contentHeader = contentHeader.Replace("src=\"/upload/image/", "src=\"" + webAddress + "/upload/image/"); contentHeader = ReplaceTempTagsFromTable(contentHeader, dtPatient, new ArrayList()); //build body decimal total = 0; string medicalAidCode = dtPatient.Columns.Contains("PatientInformation_MedicalAidIfapplicable_MedicalAidSchemeName") ? dtPatient.Rows[0]["PatientInformation_MedicalAidIfapplicable_MedicalAidSchemeName"].ToString() : String.Empty;///medical scheme code if (isProForma) { string invoiceLines = BuildInvoiceLinesProForma(examId, DateTime.Now, medicalAidCode, ref total); if (invoiceLines != "") contentBody = contentBody.Replace("{InvoiceLines}", invoiceLines); else return false; } else contentBody = contentBody.Replace("{InvoiceLines}", BuildInvoiceLines(bookings, DateTime.Now, isProForma, medicalAidCode, ref total)); //totals decimal exclTotal = (100.00m / (100.00m + practice.vatRate)) * total; decimal vatTotal = total - ((100.00m / (100.00m + practice.vatRate)) * total); contentBody = contentBody.Replace("{ExclBalance}", utils.returnFormattedDecimal(Convert.ToString(exclTotal), true)); contentBody = contentBody.Replace("{VATBalance}", utils.returnFormattedDecimal(Convert.ToString(vatTotal), true)); contentBody = contentBody.Replace("{InclBalance}", utils.returnFormattedDecimal(Convert.ToString(total), true)); utils.validateFolder(tempPath); result = utils.ConvertHTMLToPDFFile(contentBody, tempPath + fileName, true, contentHeader, ""); return result; } catch (Exception ex) { exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); return false; } } private static bool CreateEmailDocument(string content, string fileName, string tempPath, DataTable dtSurface, DataTable dtPatient, string webAddress, string icd, oMedicalPractice practice, ArrayList planFields) { try { bool result = false; DataTable dtMap = new DataTable(); foreach (oSurface surf in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "name", "LettersReplacementTextMapping")) { int rows = xData.GetSurfaceQueryDataCount(surf.recId, 0, ""); dtMap = xData.GetSurfaceQueryDataPaged(surf.recId, 0, rows, "", "", handler.ReturnUser().recId); } utils.MergeHTMData(ref content, utils.BuildFieldCodeList(practice, true)); content = content.Replace("{WebAddress}", webAddress); content = content.Replace("{Date}", utils.fixDate(DateTime.Now)); content = content.Replace("{ICD10}", icd); if (content.Contains("{ICD10Description}")) { foreach (oMedicalICD10 icdCode in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalICD10), "icdCode", icd)) { content = content.Replace("{ICD10Description}", icdCode.icdDescription); break; } } //CVH 2018-02-15 TSP-6 Instead of ICD-10 with description, show a list of all Diagnosis (textbox) items ticked. if (content.Contains("{Diagnosis}")) { string diagnosis = ""; int examItemId = 0; if (dtSurface.Rows[0]["itemID"] != null) int.TryParse(dtSurface.Rows[0]["itemID"].ToString(), out examItemId); //if filename doesn't contain "Examinations", then the surface data isn't Exam data, but Surgical Note data, need to get the correct exam Id to get bookings if (!fileName.Contains("Examinations")) { examItemId = 0; if (dtSurface.Rows[0]["ParentSurfaceItemId"] != null) { int patientId = 0; int.TryParse(dtSurface.Rows[0]["ParentSurfaceItemId"].ToString(), out patientId); if (patientId > 0) { int examId = 0; foreach (oSurface surfExams in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "name", "Examinations")) { DataTable dtExam = xData.GetChildSurfaceQueryData(surfExams.recId, patientId); if (dtExam != null && dtExam.Rows.Count > 0) { int.TryParse(dtExam.Rows[dtExam.Rows.Count - 1]["itemID"].ToString(), out examId); } } if (examId > 0) examItemId = examId; } } } if (examItemId > 0) { diagnosis = BuildDiagnosisList(examItemId, 1016); } content = content.Replace("{Diagnosis}", diagnosis); } //CVH 2018-02-15 Add MRI, Xray, CT Scan tick boxes to Post Consultation Letter if (content.Contains("{SentFor}")) { //I'll assume this is only added to Post Consult Letter, which is triggered from Examinations string sentFor = BuildSentForList(dtSurface); string sentForReplace = ""; if (sentFor != "") sentForReplace = "

I have sent him/her for:
" + sentFor; content = content.Replace("{SentFor}", sentForReplace); } if (content.Contains("{ManagementPlan_BookForSurgery_BookforSurgery}") || content.Contains("{ConservativeOrSurgery}")) { string surgeries = ""; string itemId = ""; if (dtSurface.Rows[0]["itemID"] != null) itemId = dtSurface.Rows[0]["itemID"].ToString(); //if filename doesn't contain "Examinations", then the surface data isn't Exam data, but Surgical Note data, need to get the correct exam Id to get bookings if (!fileName.Contains("Examinations")) { itemId = ""; if (dtSurface.Rows[0]["ParentSurfaceItemId"] != null) { int patientId = 0; int.TryParse(dtSurface.Rows[0]["ParentSurfaceItemId"].ToString(), out patientId); if (patientId > 0) { int examId = 0; foreach (oSurface surfExams in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "name", "Examinations")) { DataTable dtExam = xData.GetChildSurfaceQueryData(surfExams.recId, patientId); if (dtExam != null && dtExam.Rows.Count > 0) { int.TryParse(dtExam.Rows[dtExam.Rows.Count - 1]["itemID"].ToString(), out examId); } } if (examId > 0) itemId = examId.ToString(); } } } if (itemId != "") { //CVH 2018-03-15 No longer using Book for Surgery control, using the Estimations child grid //foreach (oMedicalPatientProcedureBooking book in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalPatientProcedureBooking), "surfaceItemId", itemId)) //{ // foreach (oMedicalProcedure proc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "recId", book.macroProcedureId.ToString())) // { // //CVH 2017-12-13 Check mapping table to see if text needs to be replaced // string surfaceText = proc.procedureAbbreviation; // string letterText = ""; // if (handler.ReturnSetup().code == "SHOU-1" && (fileName.Contains("PostConsultationLetter") || fileName.Contains("PostOperationletter"))) // { // letterText = surfaceText; // if (dtMap.Rows.Count > 0 && dtMap.Columns["ReplacementText_ReplacementText_SurfaceText"] != null && dtMap.Columns["ReplacementText_ReplacementText_LetterText"] != null) // { // DataRow[] foundRows = dtMap.Select("TRIM(ReplacementText_ReplacementText_SurfaceText) = '" + surfaceText.Trim() + "' "); // if (foundRows != null && foundRows.Count() > 0) // { // letterText = foundRows[0]["ReplacementText_ReplacementText_LetterText"].ToString().Trim(); // if (letterText == "") // letterText = surfaceText; // } // } // } // else // { // letterText = surfaceText; // } // //if (!surgeries.Contains(proc.procedureAbbreviation)) // //{ // // surgeries += proc.procedureAbbreviation + "
"; // //} // if (!surgeries.Contains(letterText)) // { // surgeries += letterText + "
"; // } // } //} /* Estimations_Details_ProcedureDescription Estimations_Details_Amount Estimations_Details_Select */ //calculate procedure lines int estimationsSurfaceId = 0; foreach (oSurface est in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "surface", "Estimations")) { estimationsSurfaceId = est.recId; break; } int examId = 0; int.TryParse(itemId, out examId); DataTable dtLines = xData.GetChildSurfaceQueryData(estimationsSurfaceId, examId); //build lines foreach (DataRow row in dtLines.Rows) { if (row["Estimations_Details_Select"].ToString() == "1") { //CVH 2017-12-13 Check mapping table to see if text needs to be replaced string surfaceText = row["Estimations_Details_ProcedureDescription"].ToString(); string letterText = ""; if (handler.ReturnSetup().code == "SHOU-1" && (fileName.Contains("PostConsultationLetter") || fileName.Contains("PostOperationletter"))) { letterText = surfaceText; if (dtMap.Rows.Count > 0 && dtMap.Columns["ReplacementText_ReplacementText_SurfaceText"] != null && dtMap.Columns["ReplacementText_ReplacementText_LetterText"] != null) { DataRow[] foundRows = dtMap.Select("TRIM(ReplacementText_ReplacementText_SurfaceText) = '" + surfaceText.Trim() + "' "); if (foundRows != null && foundRows.Count() > 0) { letterText = foundRows[0]["ReplacementText_ReplacementText_LetterText"].ToString().Trim(); if (letterText == "") letterText = surfaceText; } } } else { letterText = surfaceText; } if (!surgeries.Contains(letterText)) { surgeries += letterText + "
"; } } } } if (content.Contains("{ConservativeOrSurgery}")) { string replace = String.Empty; string conservative = String.Empty; if (itemId != "") { DataTable dtCons = xData.GetSurfaceQueryItemData(1016, int.Parse(itemId)); if (dtCons != null && dtCons.Rows.Count > 0 && dtCons.Rows[0]["ManagementPlan_Conservative_ConservativeTreatmentAdministered"] != null) { conservative = dtCons.Rows[0]["ManagementPlan_Conservative_ConservativeTreatmentAdministered"].ToString(); } } if (conservative != String.Empty) { //CVH 2017-12-13 Check mapping table to see if text needs to be replaced if (handler.ReturnSetup().code == "SHOU-1" && fileName.Contains("PostConsultationLetter") && dtMap.Rows.Count > 0 && dtMap.Columns["ReplacementText_ReplacementText_SurfaceText"] != null && dtMap.Columns["ReplacementText_ReplacementText_LetterText"] != null) { string processConservative = conservative; foreach (string s in processConservative.Split(',')) { DataRow[] foundRows = dtMap.Select("TRIM(ReplacementText_ReplacementText_SurfaceText) = '" + s.Trim().Replace("'","''") + "' "); if (foundRows != null && foundRows.Count() > 0) { string surfaceText = s; string letterText = foundRows[0]["ReplacementText_ReplacementText_LetterText"].ToString().Trim(); if (letterText != "") { letterText = surfaceText.Replace(s, letterText); conservative = conservative.Replace(surfaceText.Trim(), letterText); } } } } replace = "

I have treated him/her conservatively with:

" + conservative + "
"; } if (surgeries != String.Empty) { if (replace == String.Empty) replace = "

I have advised the following surgery:

" + surgeries; else replace += "

I have advised the following surgery:

" + surgeries; } content = content.Replace("{ConservativeOrSurgery}", replace); } else { content = content.Replace("{ManagementPlan_BookForSurgery_BookforSurgery}", (surgeries == "" ? "None" : surgeries)); } } //CVH 2017-10-19 Get Referral Letter date & side from Surgical Note if (content.Contains("{GeneralSurgicalNotes_GeneralSurgicalNotesGroup_Side}") || content.Contains("{GeneralSurgicalNotes_GeneralSurgicalNotesGroup_Date}")) { string date = ""; string side = ""; string itemId = ""; if (dtSurface.Rows[0]["itemID"] != null) itemId = dtSurface.Rows[0]["itemID"].ToString(); if (fileName.Contains("Referral")) { itemId = ""; if (dtSurface.Rows[0]["ParentSurfaceItemId"] != null) { int patientId = 0; int.TryParse(dtSurface.Rows[0]["ParentSurfaceItemId"].ToString(), out patientId); if (patientId > 0) { int surgId = 0; foreach (oSurface surfSurg in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "name", "SurgicalNotes")) { //DataTable dtSurg = xData.GetPublishedSurfaceDataPaged(surfSurg.recId, 0, 1, "itemID DESC", "ParentSurfaceItemId = " + patientId, handler.ReturnUser().recId); DataTable dtSurg = xData.GetCustomTypedTable("SELECT TOP 1 * FROM publ_SurgicalNotes WHERE ParentSurfaceItemId = " + patientId + " ORDER BY itemID DESC"); if (dtSurg != null && dtSurg.Rows.Count > 0) { if (dtSurg.Columns["GeneralSurgicalNotes_GeneralSurgicalNotesGroup_Side"] != null) { string temp = dtSurg.Rows[0]["GeneralSurgicalNotes_GeneralSurgicalNotesGroup_Side"].ToString(); foreach (oSurfaceLookup look in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceLookup), "recId", temp)) { side = look.display; } } if (dtSurg.Columns["GeneralSurgicalNotes_GeneralSurgicalNotesGroup_Date"] != null) { DateTime dtTemp = new DateTime(); if (DateTime.TryParse(dtSurg.Rows[0]["GeneralSurgicalNotes_GeneralSurgicalNotesGroup_Date"].ToString(), out dtTemp)) date = dtTemp.ToString(utils.displayDateFormat()); } } } if (surgId > 0) itemId = surgId.ToString(); } } } content = content.Replace("{GeneralSurgicalNotes_GeneralSurgicalNotesGroup_Side}", side); content = content.Replace("{GeneralSurgicalNotes_GeneralSurgicalNotesGroup_Date}", date); } if (content.Contains("{ManagementPlan_PostConsultationLetter_IfnotReferringDr}") && dtSurface.Rows[0]["ManagementPlan_PostConsultationLetter_IfnotReferringDr"] != null) { string doctor = dtSurface.Rows[0]["ManagementPlan_PostConsultationLetter_IfnotReferringDr"].ToString(); if (doctor == "" && dtPatient.Rows[0]["PatientInformation_PatientDetails_ReferringDoctor"] != null) doctor = dtPatient.Rows[0]["PatientInformation_PatientDetails_ReferringDoctor"].ToString(); content = content.Replace("{ManagementPlan_PostConsultationLetter_IfnotReferringDr}", doctor); } if (content.Contains("{Letters_PostOperationletter_IfNotReferringDoctor}") && dtSurface.Rows[0]["Letters_PostOperationletter_IfNotReferringDoctor"] != null) { string doctor = dtSurface.Rows[0]["Letters_PostOperationletter_IfNotReferringDoctor"].ToString(); if (doctor == "" && dtPatient.Rows[0]["PatientInformation_PatientDetails_ReferringDoctor"] != null) doctor = dtPatient.Rows[0]["PatientInformation_PatientDetails_ReferringDoctor"].ToString(); content = content.Replace("{Letters_PostOperationletter_IfNotReferringDoctor}", doctor); } content = content.Replace("src=\"/images/", "src=\"" + webAddress + "/images/"); content = content.Replace("src=\"/upload/image/", "src=\"" + webAddress + "/upload/image/"); content = ReplaceTempTagsFromTableCustom(content, dtPatient, new ArrayList()); content = ReplaceTempTagsFromTableCustom(content, dtSurface, planFields, dtMap); //loop through and replace all remaing temp tags with empty string int tagStart = content.IndexOf("{"); int tagEnd = content.IndexOf("}"); while (tagStart >= 0 && tagEnd > 0 && tagEnd > tagStart && tagEnd < content.Length) { string tempTag = content.Substring(tagStart, tagEnd - tagStart + 1); content = content.Replace(tempTag, ""); tagStart = content.IndexOf("{"); tagEnd = content.IndexOf("}"); } utils.validateFolder(tempPath); result = utils.ConvertHTMLToPDFFile(content, tempPath + fileName, true, "", ""); return result; } catch (Exception ex) { exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); return false; } } /// /// Executed on Surface Item Save /// public static string SurfaceSave(oSurface _surface = null, oSurfaceItem _item = null, int userId = 0, string webAddress = "", string emailTo = "", string emailFrom = "", int parentSurfaceItemId = 0) { //specifies the canvas to redirect to, blank if none string redirect = String.Empty; try { oSetup _setup = handler.ReturnSetup(); //SBF specific if (_setup.code == "STUD-1" || _setup.code == "DISA-1") { if (_surface != null && _item != null) { if (_surface.name == "DeviceManagement") { //get item data DataTable dtDeviceData = xData.GetSurfaceItemData(_item.surfaceId, _item.recId); if (dtDeviceData.Rows.Count > 0) { foreach (DataColumn col in dtDeviceData.Columns) { if (col.ColumnName.EndsWith("Status")) { if (dtDeviceData.Rows[0][col].ToString() == "In For Repairs") //if (dtDeviceData.Rows[0][col].ToString().StartsWith("Broken") || // dtDeviceData.Rows[0][col].ToString().StartsWith("Malfunction")) { foreach (oCanvasMetaData meta in xData.GetTypedByCriteriaSpecific("recId", typeof(oCanvasMetaData), "moduleId", pNums.Module.Jobcards.GetHashCode().ToString())) { foreach (oCanvas canvas in xData.GetTypedByCriteriaSpecific("recId", typeof(oCanvas), "recId", meta.canvasId.ToString())) { redirect = "/pages/" + canvas.name; break; } break; } } break; } } } } } } //TSP specific else if (_setup.code == "EVOL-1" || _setup.code == "SHOU-1") { if (_surface != null && _item != null) { if (_surface.name == "Examinations") { oSurfaceItem mgmtPlanItem = _item; oSurface mgmtPlanSurface = _surface; //get plan data //List planParamList = new List(); //oDynamicParam planPar1 = new oDynamicParam(); //planPar1.paramDisplayName = "SurfaceID"; //planPar1.paramObject = mgmtPlanItem.surfaceId; //planParamList.Add(planPar1); //oDynamicParam planPar2 = new oDynamicParam(); //planPar2.paramDisplayName = "SurfaceItemID"; //planPar2.paramObject = mgmtPlanItem.recId; //planParamList.Add(planPar2); //DataTable dtPlanData = xData.GetTypedTableByProc("recId", typeof(oSurfaceFieldData), "sp_GetSurfaceItemData", planParamList); DataTable dtPlanData = xData.GetSurfaceQueryItemData(mgmtPlanItem.surfaceId, mgmtPlanItem.recId); ArrayList planFields = xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceId", mgmtPlanItem.surfaceId.ToString()); //we know the management plan surface is linked to the patient management surface, so get parent surface linked to this child item oSurfaceItem patientItem = null; if (dtPlanData != null && dtPlanData.Rows.Count > 0 && dtPlanData.Columns["ParentSurfaceItemId"] != null) { foreach (oSurfaceItem parentItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceItem), "recId", dtPlanData.Rows[0]["ParentSurfaceItemId"].ToString())) { patientItem = parentItem; } } if (patientItem != null) { //get patient data List paramList = new List(); oDynamicParam par1 = new oDynamicParam(); par1.paramDisplayName = "SurfaceID"; par1.paramObject = patientItem.surfaceId; paramList.Add(par1); oDynamicParam par2 = new oDynamicParam(); par2.paramDisplayName = "SurfaceItemID"; par2.paramObject = patientItem.recId; paramList.Add(par2); DataTable dtPatientData = xData.GetTypedTableByProc("recId", typeof(oSurfaceFieldData), "sp_GetSurfaceItemData", paramList); if (dtPatientData != null && dtPatientData.Rows.Count > 0) { //get email and document templates string emailBody = ""; string xRayContent = ""; string ctContent = ""; string certificateContent = ""; string mriContent = ""; string notepadContent = ""; string proFormaHeader = ""; string proFormaEstimateBody = ""; string proFormaConsultingRoomBody = ""; string postContent = ""; foreach (oTemplate template in xData.GetTypedCollection("recId", typeof(oTemplate))) { if (template.templateName == mgmtPlanSurface.surface + " Email") { emailBody = template.templateContent; } else if (template.templateName.StartsWith(mgmtPlanSurface.surface) && template.templateName.Contains("X-Ray")) { xRayContent = template.templateContent; } else if (template.templateName.StartsWith(mgmtPlanSurface.surface) && template.templateName.Contains("MRI")) { mriContent = template.templateContent; } else if (template.templateName.StartsWith(mgmtPlanSurface.surface) && template.templateName.Contains("CT")) { ctContent = template.templateContent; } else if (template.templateName.StartsWith(mgmtPlanSurface.surface) && template.templateName.Contains("Certificate")) { certificateContent = template.templateContent; } else if (template.templateName.StartsWith(mgmtPlanSurface.surface) && template.templateName.Contains("Notepad")) { notepadContent = template.templateContent; } else if (template.templateName.Contains("Pro Forma") && template.templateName.Contains("Header")) { proFormaHeader = template.templateContent; } else if (template.templateName.Contains("Pro Forma") && template.templateName.Contains("Consulting Room Body")) { proFormaConsultingRoomBody = template.templateContent; } else if (template.templateName.Contains("Pro Forma") && template.templateName.Contains("Pro Forma Estimate Body")) { proFormaEstimateBody = template.templateContent; } else if (template.templateName.StartsWith(mgmtPlanSurface.surface) && template.templateName.Contains("Post Consultation")) { postContent = template.templateContent; } } //get list of icds linked to same "examination" string secondIcdNotUsed = ""; //used in Surgical Notes published surface string icd = BuildICDList(mgmtPlanItem.recId, mgmtPlanItem.surfaceId, ref secondIcdNotUsed); //get practice oMedicalPractice practice = new oMedicalPractice(); foreach (oMedicalPractice prac in xData.GetTypedCollection("recId", typeof(oMedicalPractice))) { practice = prac; } ArrayList attachments = new ArrayList(); string tempPath = HttpContext.Current.Server.MapPath("~/upload/documents/"); string fileName = mgmtPlanSurface.name + patientItem.recId + "_{DocType}" + "_" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".pdf"; foreach (DataColumn col in dtPlanData.Columns) { if (col.ColumnName.ToUpper().EndsWith("_SENDFORXRAY")) { if (dtPlanData.Rows[0][col].ToString() == "1") { if (CreateEmailDocument(xRayContent, fileName.Replace("{DocType}", "X-Ray"), tempPath, dtPlanData, dtPatientData, webAddress, icd, practice, planFields)) { oAttachment attXray = new oAttachment(); attXray.display = "X-Ray"; attXray.fileName = fileName.Replace("{DocType}", "X-Ray"); attachments.Add(attXray); } } } else if (col.ColumnName.ToUpper().EndsWith("_SENDFORCTSCAN")) { if (dtPlanData.Rows[0][col].ToString() == "1") { if (CreateEmailDocument(ctContent, fileName.Replace("{DocType}", "CTScan"), tempPath, dtPlanData, dtPatientData, webAddress, icd, practice, planFields)) { oAttachment attCt = new oAttachment(); attCt.display = "CT Scan"; attCt.fileName = fileName.Replace("{DocType}", "CTScan"); attachments.Add(attCt); } } } else if (col.ColumnName.ToUpper().EndsWith("_SENDFORMRISCAN")) { if (dtPlanData.Rows[0][col].ToString() == "1") { if (CreateEmailDocument(mriContent, fileName.Replace("{DocType}", "MRI"), tempPath, dtPlanData, dtPatientData, webAddress, icd, practice, planFields)) { oAttachment attMri = new oAttachment(); attMri.display = "MRI"; attMri.fileName = fileName.Replace("{DocType}", "MRI"); attachments.Add(attMri); } } } else if (col.ColumnName.ToUpper().EndsWith("_CREATEMEDICALCERTIFICATE")) { if (dtPlanData.Rows[0][col].ToString() == "1") { if (CreateEmailDocument(certificateContent, fileName.Replace("{DocType}", "MedicalCertificate"), tempPath, dtPlanData, dtPatientData, webAddress, icd, practice, planFields)) { oAttachment attCert = new oAttachment(); attCert.display = "Medical Certificate"; attCert.fileName = fileName.Replace("{DocType}", "MedicalCertificate"); attachments.Add(attCert); } } } else if (col.ColumnName.ToUpper().EndsWith("_CREATENOTEPAD")) { if (dtPlanData.Rows[0][col].ToString() == "1") { if (CreateEmailDocument(notepadContent, fileName.Replace("{DocType}", "Notepad"), tempPath, dtPlanData, dtPatientData, webAddress, icd, practice, planFields)) { oAttachment attNotepad = new oAttachment(); attNotepad.display = "Notepad"; attNotepad.fileName = fileName.Replace("{DocType}", "Notepad"); attachments.Add(attNotepad); } } } else if (col.ColumnName.ToUpper().EndsWith("_CREATELETTER")) { if (dtPlanData.Rows[0][col].ToString() == "1") { if (CreateEmailDocument(postContent, fileName.Replace("{DocType}", "PostConsultationLetter"), tempPath, dtPlanData, dtPatientData, webAddress, icd, practice, planFields)) { oAttachment attPost = new oAttachment(); attPost.display = "Post Consultation Letter"; attPost.fileName = fileName.Replace("{DocType}", "PostConsultationLetter"); attachments.Add(attPost); } } } else if (col.ColumnName.ToUpper().EndsWith("_PROCEDURESADMINISTERED")) { if (dtPlanData.Rows[0][col].ToString() != "") { //build a list of bookings for all the selected procedures ArrayList consultBookings = new ArrayList(); ArrayList procsAll = xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "nonSurgical", "1"); foreach (string consult in dtPlanData.Rows[0][col].ToString().Split(',')) { if (consult.LastIndexOf("-") >= 0) { string procCode = consult.Substring(consult.LastIndexOf("-") + 1, consult.Length - (consult.LastIndexOf("-") + 1)).Trim(); foreach (oMedicalProcedure proc in procsAll) { if (proc.code == procCode) { oMedicalPatientProcedureBooking book = new global::oMedicalPatientProcedureBooking(); book.procedureId = proc.recId; book.procedureQty = 1; book.placeOfServiceIndicator = 11; // Office / Consulting Room consultBookings.Add(book); } } } } string consultFileName = "ConsultingRoomProcedures" + patientItem.recId + "_" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".pdf"; if (CreateProFormaInvoice(proFormaHeader.Replace("{Heading}", "Office / Consulting Room Procedures"), proFormaConsultingRoomBody, consultFileName, tempPath, dtPatientData, webAddress, practice, consultBookings, icd, false, mgmtPlanItem.recId)) { oAttachment attConsult = new oAttachment(); attConsult.display = "Office / Consulting Room Procedures"; attConsult.fileName = consultFileName; attachments.Add(attConsult); } } } } //pro forma invoice //CVH 2018-03-15 No longer using Book for Surgery control, we have a child grid ArrayList bookings = new ArrayList(); string invoiceFileName = "ProFormaEstimation" + patientItem.recId + "_" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".pdf"; if (CreateProFormaInvoice(proFormaHeader.Replace("{Heading}", "Pro Forma Estimation"), proFormaEstimateBody, invoiceFileName, tempPath, dtPatientData, webAddress, practice, bookings, icd, true, mgmtPlanItem.recId)) { oAttachment attInvoice = new oAttachment(); attInvoice.display = "Pro Forma Estimation"; attInvoice.fileName = invoiceFileName; attachments.Add(attInvoice); } //CVH 2016-11-28 Only process email if there are attachments if (attachments != null && attachments.Count > 0) { //CVH 2016-11-17 Find Notes field on patient surface string noteSurfaceFieldName = ""; foreach (oSurfaceField patientField in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceId,surfaceFieldTypeId,isActive", patientItem.surfaceId + "," + pNums.FieldType.Note.GetHashCode() + ",1")) { //noteSurfaceFieldName = patientField.surfaceFieldName; //JR use id noteSurfaceFieldName = patientField.recId.ToString(); break; } //create note with all the attachments, also move it from the temp folder to the note attachment folder AddCreateDocumentNote(patientItem.recId, mgmtPlanSurface.surface + " Documents", mgmtPlanSurface.surface + " Documents have been created.", tempPath, userId, ref attachments, noteSurfaceFieldName); //replace email body patient details emailBody = emailBody.Replace("{Date}", utils.fixDate(DateTime.Now)); emailBody = ReplaceTempTagsFromTable(emailBody, dtPatientData, new ArrayList()); oEmail mail = new oEmail(); mail.Body = emailBody; foreach (oAttachment att in attachments) { mail.Attachments.Add(HttpContext.Current.Server.MapPath("~/upload/" + att.folderName + "/file/" + att.fileName)); } mail.Subject = mgmtPlanSurface.surface + " Documents"; mail.fromAddress = emailFrom; if (ConfigurationManager.AppSettings["practiceAdmin"] != null) emailTo = ConfigurationManager.AppSettings["practiceAdmin"].ToString(); mail.toAddress = emailTo; if (communication.SendAnEmail(mail)) { } } } } } //CVH 2017-10-19 Physio and Post Op letters moved to new Referral Letters surface //else if (_surface.name == "SurgicalNotes") //{ // oSurfaceItem surgItem = _item; // oSurface surgSurface = _surface; // //get surgical data // //DataTable dtSurgData = xData.GetPublishedSurfaceDataPaged(surgItem.surfaceId, 0, 1, "", "", handler.ReturnUser().recId, 0, "itemID = " + surgItem.recId, true, false); // DataTable dtSurgData = xData.GetCustomTypedTable("select * from publ_SurgicalNotes where itemID = " + surgItem.recId); // ArrayList surgFields = xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceId", surgItem.surfaceId.ToString()); // //we know the surface is linked to the patient management surface, so get parent surface linked to this child item // oSurfaceItem patientItem = null; // if (dtSurgData != null && dtSurgData.Rows.Count > 0 && dtSurgData.Columns["ParentSurfaceItemId"] != null) // { // foreach (oSurfaceItem parentItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceItem), "recId", dtSurgData.Rows[0]["ParentSurfaceItemId"].ToString())) // { // patientItem = parentItem; // } // } // //get exam details // int examId = 0; // int examSurfId = 0; // foreach (oSurface surfExams in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "name", "Examinations")) // { // examSurfId = surfExams.recId; // DataTable dtExam = xData.GetChildSurfaceQueryData(surfExams.recId, patientItem.recId); // if (dtExam != null && dtExam.Rows.Count > 0) // { // int.TryParse(dtExam.Rows[dtExam.Rows.Count - 1]["itemID"].ToString(), out examId); // } // } // if (patientItem != null) // { // //get patient data // List paramList = new List(); // oDynamicParam par1 = new oDynamicParam(); // par1.paramDisplayName = "SurfaceID"; // par1.paramObject = patientItem.surfaceId; // paramList.Add(par1); // oDynamicParam par2 = new oDynamicParam(); // par2.paramDisplayName = "SurfaceItemID"; // par2.paramObject = patientItem.recId; // paramList.Add(par2); // DataTable dtPatientData = xData.GetTypedTableByProc("recId", typeof(oSurfaceFieldData), "sp_GetSurfaceItemData", paramList); // if (dtPatientData != null && dtPatientData.Rows.Count > 0) // { // //get email and document templates // string emailBody = ""; // string physioContent = ""; // string postContent = ""; // foreach (oTemplate template in xData.GetTypedCollection("recId", typeof(oTemplate))) // { // if (template.templateName == surgSurface.surface + " Email") // { // emailBody = template.templateContent; // } // else if (template.templateName == "Surgical Physio Referral") // { // physioContent = template.templateContent; // } // else if (template.templateName == "Surgical Post Op Letter") // { // postContent = template.templateContent; // } // } // //get list of icds linked to same "examination" // string secondIcdNotUsed = ""; //used in Surgical Notes published surface // string icd = BuildICDList(examId, examSurfId, ref secondIcdNotUsed); // //get practice // oMedicalPractice practice = new oMedicalPractice(); // foreach (oMedicalPractice prac in xData.GetTypedCollection("recId", typeof(oMedicalPractice))) // { // practice = prac; // } // ArrayList attachments = new ArrayList(); // string tempPath = HttpContext.Current.Server.MapPath("~/upload/documents/"); // string fileName = surgSurface.name + patientItem.recId + "_{DocType}" + "_" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".pdf"; // foreach (DataColumn col in dtSurgData.Columns) // { // if (col.ColumnName == "Letters_PhysiotherapistLetter_CreateLetter") // { // if (dtSurgData.Rows[0][col].ToString() == "1" || dtSurgData.Rows[0][col].ToString() == "True") // { // if (CreateEmailDocument(physioContent, fileName.Replace("{DocType}", "PhysiotherapistLetter"), tempPath, dtSurgData, // dtPatientData, webAddress, icd, practice, surgFields)) // { // oAttachment attPhysio = new oAttachment(); // attPhysio.display = "Physiotherapist Letter"; // attPhysio.fileName = fileName.Replace("{DocType}", "PhysiotherapistLetter"); // attachments.Add(attPhysio); // } // } // } // else if (col.ColumnName == "Letters_PostOperationletter_CreateLetter") // { // if (dtSurgData.Rows[0][col].ToString() == "1" || dtSurgData.Rows[0][col].ToString() == "True") // { // if (CreateEmailDocument(postContent, fileName.Replace("{DocType}", "PostOperationletter"), tempPath, dtSurgData, // dtPatientData, webAddress, icd, practice, surgFields)) // { // oAttachment attCt = new oAttachment(); // attCt.display = "Post Operation Letter"; // attCt.fileName = fileName.Replace("{DocType}", "PostOperationletter"); // attachments.Add(attCt); // } // } // } // } // //CVH 2016-11-28 Only process email if there are attachments // if (attachments != null && attachments.Count > 0) // { // //CVH 2016-11-17 Find Notes field on patient surface // string noteSurfaceFieldName = ""; // foreach (oSurfaceField patientField in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceId,surfaceFieldTypeId,isActive", patientItem.surfaceId + "," + pNums.FieldType.Note.GetHashCode() + ",1")) // { // //noteSurfaceFieldName = patientField.surfaceFieldName; // //JR use id // noteSurfaceFieldName = patientField.recId.ToString(); // break; // } // //create note with all the attachments, also move it from the temp folder to the note attachment folder // AddCreateDocumentNote(patientItem.recId, surgSurface.surface + " Documents", surgSurface.surface + " Documents have been created.", // tempPath, userId, ref attachments, noteSurfaceFieldName); // //replace email body patient details // emailBody = emailBody.Replace("{Date}", utils.fixDate(DateTime.Now)); // emailBody = ReplaceTempTagsFromTable(emailBody, dtPatientData, new ArrayList()); // oEmail mail = new oEmail(); // mail.Body = emailBody; // foreach (oAttachment att in attachments) // { // mail.Attachments.Add(HttpContext.Current.Server.MapPath("~/upload/" + att.folderName + "/file/" + att.fileName)); // } // mail.Subject = surgSurface.surface + " Documents"; // mail.fromAddress = emailFrom; // mail.toAddress = emailTo; // if (communication.SendAnEmail(mail)) // { // } // } // } // } //} else if (_surface.name == "ReferralLetters") { oSurfaceItem refItem = _item; oSurface refSurface = _surface; //get referral data DataTable dtRefData = xData.GetCustomTypedTable("select * from qt_ReferralLetters where itemID = " + refItem.recId); ArrayList refFields = xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceId", refItem.surfaceId.ToString(), "parentId ASC, sequence ASC"); //we know the surface is linked to the patient management surface, so get parent surface linked to this child item oSurfaceItem patientItem = null; if (dtRefData != null && dtRefData.Rows.Count > 0 && dtRefData.Columns["ParentSurfaceItemId"] != null) { foreach (oSurfaceItem parentItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceItem), "recId", dtRefData.Rows[0]["ParentSurfaceItemId"].ToString())) { patientItem = parentItem; } } //get exam details int examId = 0; int examSurfId = 0; foreach (oSurface surfExams in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "name", "Examinations")) { examSurfId = surfExams.recId; DataTable dtExam = xData.GetChildSurfaceQueryData(surfExams.recId, patientItem.recId); if (dtExam != null && dtExam.Rows.Count > 0) { int.TryParse(dtExam.Rows[dtExam.Rows.Count - 1]["itemID"].ToString(), out examId); } } if (patientItem != null) { //get patient data List paramList = new List(); oDynamicParam par1 = new oDynamicParam(); par1.paramDisplayName = "SurfaceID"; par1.paramObject = patientItem.surfaceId; paramList.Add(par1); oDynamicParam par2 = new oDynamicParam(); par2.paramDisplayName = "SurfaceItemID"; par2.paramObject = patientItem.recId; paramList.Add(par2); DataTable dtPatientData = xData.GetTypedTableByProc("recId", typeof(oSurfaceFieldData), "sp_GetSurfaceItemData", paramList); if (dtPatientData != null && dtPatientData.Rows.Count > 0) { //get email and document templates string emailBody = ""; string physioContent = ""; string postContent = ""; foreach (oTemplate template in xData.GetTypedCollection("recId", typeof(oTemplate))) { if (template.templateName == "Surgical Notes Email") { emailBody = template.templateContent; } else if (template.templateName == "Surgical Physio Referral") { physioContent = template.templateContent; } else if (template.templateName == "Surgical Post Op Letter") { postContent = template.templateContent; } } //get list of icds linked to same "examination" string secondIcdNotUsed = ""; //used in Surgical Notes published surface string icd = BuildICDList(examId, examSurfId, ref secondIcdNotUsed); //get practice oMedicalPractice practice = new oMedicalPractice(); foreach (oMedicalPractice prac in xData.GetTypedCollection("recId", typeof(oMedicalPractice))) { practice = prac; } ArrayList attachments = new ArrayList(); string tempPath = HttpContext.Current.Server.MapPath("~/upload/documents/"); string fileName = refSurface.name + patientItem.recId + "_{DocType}" + "_" + DateTime.Now.ToString("yyyy-MM-dd-hh-mm-ss") + ".pdf"; foreach (DataColumn col in dtRefData.Columns) { if (col.ColumnName == "Letters_PhysiotherapistLetter_CreateLetter") { if (dtRefData.Rows[0][col].ToString() == "1" || dtRefData.Rows[0][col].ToString() == "True") { if (CreateEmailDocument(physioContent, fileName.Replace("{DocType}", "PhysiotherapistLetter"), tempPath, dtRefData, dtPatientData, webAddress, icd, practice, refFields)) { oAttachment attPhysio = new oAttachment(); attPhysio.display = "Physiotherapist Letter"; attPhysio.fileName = fileName.Replace("{DocType}", "PhysiotherapistLetter"); attachments.Add(attPhysio); } } } else if (col.ColumnName == "Letters_PostOperationletter_CreateLetter") { if (dtRefData.Rows[0][col].ToString() == "1" || dtRefData.Rows[0][col].ToString() == "True") { if (CreateEmailDocument(postContent, fileName.Replace("{DocType}", "PostOperationletter"), tempPath, dtRefData, dtPatientData, webAddress, icd, practice, refFields)) { oAttachment attCt = new oAttachment(); attCt.display = "Post Operation Letter"; attCt.fileName = fileName.Replace("{DocType}", "PostOperationletter"); attachments.Add(attCt); } } } } //CVH 2016-11-28 Only process email if there are attachments if (attachments != null && attachments.Count > 0) { //CVH 2016-11-17 Find Notes field on patient surface string noteSurfaceFieldName = ""; foreach (oSurfaceField patientField in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceId,surfaceFieldTypeId,isActive", patientItem.surfaceId + "," + pNums.FieldType.Note.GetHashCode() + ",1")) { //noteSurfaceFieldName = patientField.surfaceFieldName; //JR use id noteSurfaceFieldName = patientField.recId.ToString(); break; } //create note with all the attachments, also move it from the temp folder to the note attachment folder AddCreateDocumentNote(patientItem.recId, refSurface.surface + " Documents", refSurface.surface + " Documents have been created.", tempPath, userId, ref attachments, noteSurfaceFieldName); //replace email body patient details emailBody = emailBody.Replace("{Date}", utils.fixDate(DateTime.Now)); emailBody = ReplaceTempTagsFromTable(emailBody, dtPatientData, new ArrayList()); oEmail mail = new oEmail(); mail.Body = emailBody; foreach (oAttachment att in attachments) { mail.Attachments.Add(HttpContext.Current.Server.MapPath("~/upload/" + att.folderName + "/file/" + att.fileName)); if (att.fileName.Contains("PhysiotherapistLetter") && System.IO.File.Exists(tempPath + "Physio Referral - Shoulder Rehabilitation Protocols.pdf")) { //CVH 2017-10-23 Copy Protocols document to temp folder. mail.Attachments.Add(HttpContext.Current.Server.MapPath("~/upload/documents/Physio Referral - Shoulder Rehabilitation Protocols.pdf")); } } mail.Subject = refSurface.surface + " Documents"; mail.fromAddress = emailFrom; if (ConfigurationManager.AppSettings["practiceAdmin"] != null) emailTo = ConfigurationManager.AppSettings["practiceAdmin"].ToString(); mail.toAddress = emailTo; if (communication.SendAnEmail(mail)) { } } } } } //CVH 2017-08-30 If saving Examinations or Follow Up Visits, and charging consulting room procedures, need to build billing lines and redirect to billing module //only redirect on first save of examinations (not update), but redirect on every follow up visit save if (((_surface.name == "Examinations" && _item.dateUpdated.Year < System.DateTime.Now.Year) || _surface.name.StartsWith("Follow")) && parentSurfaceItemId > 0) { DataTable fields = xData.GetTypedByCriteriaSpecificTable("recId", typeof(oSurfaceField), "surfaceId", _surface.recId.ToString()); string fieldNameCreateBill = ""; string fieldNameProcs = ""; var fieldsCreateBill = from grdFields in fields.AsEnumerable() where (grdFields.Field("surfaceFieldDisplay").Equals("Create Billing or No Charge")) select grdFields; if (fieldsCreateBill.Count() > 0) fieldNameCreateBill = fieldsCreateBill.ToList()[0]["surfaceFieldName"].ToString(); var fieldsProcs = from grdFields in fields.AsEnumerable() where (grdFields.Field("surfaceFieldDisplay").Equals("Procedures Administered") || grdFields.Field("surfaceFieldDisplay").Equals("Procedures Administered Follow Up")) select grdFields; if (fieldsProcs.Count() > 0) fieldNameProcs = fieldsProcs.ToList()[0]["surfaceFieldName"].ToString(); DataTable dtBill = xData.GetSurfaceQueryItemData(_surface.recId, _item.recId); if (dtBill.Rows.Count > 0 && dtBill.Columns[fieldNameCreateBill] != null && dtBill.Columns[fieldNameProcs] != null) { if (dtBill.Rows[0][fieldNameCreateBill].ToString() == "Create Billing" && dtBill.Rows[0][fieldNameProcs].ToString() != "No Charge (N/C)") { int examId = 0; int examSurfId = 0; if (_surface.name == "Examinations") { examId = _item.recId; examSurfId = _item.surfaceId; } else { foreach (oSurface surfExams in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurface), "name", "Examinations")) { examSurfId = surfExams.recId; DataTable dtExam = xData.GetChildSurfaceQueryData(surfExams.recId, parentSurfaceItemId); if (dtExam != null && dtExam.Rows.Count > 0) { int.TryParse(dtExam.Rows[dtExam.Rows.Count - 1]["itemID"].ToString(), out examId); } } } string externalCause = ""; DateTime billingDate = System.DateTime.Now; string authorizationNumber = ""; string referringDoctorPracticeNumber = ""; string referringDoctor = ""; string referringDoctorTxt = ""; string secondaryIcd10 = ""; string primaryIcd10 = xSurfaceCustomAction.BuildICDList(examId, examSurfId, ref secondaryIcd10); foreach (DataColumn col in dtBill.Columns) { if (col.ColumnName.EndsWith("_ExternalCauseCode")) externalCause = dtBill.Rows[0][col].ToString(); else if (col.ColumnName.EndsWith("_AuthorizationNumber")) authorizationNumber = dtBill.Rows[0][col].ToString(); else if (col.ColumnName.EndsWith("_ReferringDoctor")) referringDoctor = dtBill.Rows[0][col].ToString(); else if (col.ColumnName.EndsWith("_RefferingDoctor2") || col.ColumnName.EndsWith("_ReferringDoctor2")) referringDoctorTxt = dtBill.Rows[0][col].ToString(); else if (col.ColumnName.EndsWith("_ReferringDoctorPracticeNumber")) referringDoctorPracticeNumber = dtBill.Rows[0][col].ToString(); else if (col.ColumnName.EndsWith("_Date") || col.ColumnName.EndsWith("_PostOpDate")) { if (!DateTime.TryParse(dtBill.Rows[0][col].ToString(), out billingDate)) billingDate = System.DateTime.Now; } } if (referringDoctorTxt != "") referringDoctor = referringDoctorTxt; if (referringDoctor == "") { //if referring doc is blank, get label value from patient, could be label not updated correctly foreach (oSurfaceField referDocField in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceFieldName", "PatientInformation_PatientDetails_ReferringDoctor")) { foreach (oSurfaceFieldData referDoc in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceFieldData), "surfaceId,surfaceFieldID,surfaceItemId", referDocField.surfaceId + "," + referDocField.recId + "," + parentSurfaceItemId)) { referringDoctor = referDoc.surfaceFieldValueChar; } } } int patientItemId = parentSurfaceItemId; oUser usr = handler.ReturnUser(); string fieldName = ""; int fieldId = 0; int patientSurfaceId = 0; foreach (oSurfaceItem parentItem in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceItem), "recId", patientItemId.ToString())) { patientSurfaceId = parentItem.surfaceId; foreach (oSurfaceField field in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceId,surfaceFieldTypeId,isActive", parentItem.surfaceId + "," + (int)pNums.FieldType.Note + ",1")) { fieldName = field.surfaceFieldName; fieldId = field.recId; break; } } HttpContext.Current.Session["noteSurfaceFieldName"] = fieldId; oAccount acc = xDebtors.SetAccountItem(patientItemId, patientSurfaceId, usr); HttpContext.Current.Session["account"] = acc; HttpContext.Current.Session["loadType"] = "Redirected"; oTariffPlan tariffPlan = new oTariffPlan(); foreach (oMedicalScheme med in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalScheme), "code", acc.medCode)) { string code = med.planCode; //CVH 2018-04-13 Default selected tariff to DISC B for TSP where patient is NOT linked to WCA or FedHealth if (handler.ReturnSetup().code == "SHOU-1" && (med.planCode == String.Empty || (med.planCode != "WCA" && !med.name.ToUpper().Contains("FEDHEALTH")))) code = "DISC B"; foreach (oTariffPlan trf in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffPlan), "code", code)) { tariffPlan = trf; break; } break; } oMedicalDoctor billingDoc = new oMedicalDoctor(); foreach (oMedicalDoctor doc in xData.GetTypedCollection("recId", typeof(oMedicalDoctor))) { if (doc.isAssistant == false) { billingDoc = doc; break; } } //build billing lines ArrayList billingLines = new ArrayList(); foreach (string selected in dtBill.Rows[0][fieldNameProcs].ToString().Split(',')) { //Consultation - 0190, Consultation - 0146, Ultra Sound - 5102, Nappi - C2, Injection - 0661 if (selected.Contains("- 0190") || selected.Contains("- 0146") || selected.Contains("- 5102") || selected.Contains("- C2") || selected.Contains("- 0661") || selected.Contains("- 0109")) { string procCode = selected.Contains("- 0190") ? "0190" : selected.Contains("- 0146") ? "0146" : selected.Contains("- 5102") ? "5102" : selected.Contains("- C2") ? "C2" : selected.Contains("- 0661") ? "0661" : selected.Contains("- 0109") ? "0109" : ""; oMedicalProcedure proc = new global::oMedicalProcedure(); foreach (oMedicalProcedure bookProc in xData.GetTypedByCriteriaSpecific("recId", typeof(oMedicalProcedure), "code", procCode)) { proc = bookProc; break; } //skip modifiers if (proc.recId <= 0 || proc.codeType == 2) continue; oAccount newAcc = (oAccount)utils.CloneObject(acc); newAcc.procedureCode = proc.code; newAcc.procedureDescription = proc.description; newAcc.consumableCode = proc.consumableCode; newAcc.procedureNAPPI = proc.nappi + proc.nappiSuffix; //ICD newAcc.icd1 = primaryIcd10; newAcc.icd2 = secondaryIcd10; newAcc.externalCause = externalCause; newAcc.procedureType = "TI"; newAcc.dateOfService = billingDate.Date; newAcc.dateOfCapture = DateTime.Now; newAcc.dateOfTransaction = DateTime.Now; newAcc.placeOfService = 11; newAcc.vatRate = handler.ReturnSetup().vatRate; newAcc.serviceType = "T"; newAcc.inHospital = false; newAcc.category = 0; newAcc.authorisationNo = authorizationNumber; newAcc.referringDocNo = referringDoctorPracticeNumber; newAcc.referringDoctor = referringDoctor; //calcs newAcc.qty = 1; decimal unitFee = 0; foreach (oTariffRate rate in xData.GetTypedByCriteriaSpecific("recId", typeof(oTariffRate), "planCode,procedureCode", tariffPlan.code + "," + proc.code)) { foreach (oPlaceOfService poc in xData.GetTypedByCriteriaSpecific("recId", typeof(oPlaceOfService), "indicator", "11")) { 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; } } break; } newAcc.unitFee = unitFee; newAcc.amount = unitFee * newAcc.qty; if (tariffPlan.liableIndicator == 0) { newAcc.liablePat = 0; newAcc.liableMed = newAcc.amount; } else { newAcc.liablePat = newAcc.amount; newAcc.liableMed = 0; } newAcc.isVisible = true; newAcc.planCode = tariffPlan.code; newAcc.claimSend = tariffPlan.claimActivated; newAcc.doctor = billingDoc.surname + ", " + billingDoc.title + " " + billingDoc.initials; newAcc.doctorNo = billingDoc.recId; newAcc.practiceNo = billingDoc.practiceId; //running balance decimal bal = 0; foreach (oAccount billBal in billingLines) { bal += billBal.amount; } newAcc.runningBal += newAcc.amount + bal; billingLines.Add(newAcc); } } if (billingLines.Count > 0) { redirect = "/pages/enquiry"; HttpContext.Current.Session["billingLinesSurgicalNotes"] = billingLines; } } } } } } } catch (Exception ex) { exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); } return redirect; } /// /// Set up Job Card Task object with given surface item ID /// /// /// public static oTask SetSurfaceItemJobCard(int itemId) { oTask job = new oTask(); try { if (handler.ReturnSetup().code == "STUD-1" || handler.ReturnSetup().code == "DISA-1") { job.custom = itemId.ToString(); ////task subject = device serial number //foreach (oSurfaceField field in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceField), "surfaceId,surfaceFieldDisplay", item.surfaceId + ",Serial Number")) //{ // foreach (oSurfaceFieldData data in xData.GetTypedByCriteriaSpecific("recId", typeof(oSurfaceFieldData), "surfaceId,surfaceItemId,surfaceFieldID", item.surfaceId + "," + item.recId + "," + field.recId)) // { // job.name = "Serial Number " + data.surfaceFieldValueChar.Trim(); // break; // } // break; //} ////task assignee //foreach (oUser user in xData.GetTypedByCriteriaSpecific("recId", typeof(oUser), "customerCode,userType,modules", "STUD-1," + pNums.UserType.AdminUser.GetHashCode() + "," + pNums.Module.Jobcards.GetHashCode(), "", "pal_", true)) //{ // job.assigneeUserId = user.recId; // break; //} } } catch (Exception ex) { exception.HandleException("customAction:", MethodBase.GetCurrentMethod().Name, ex, null); } return job; } } }