private async Task MapReactionRelatedFieldsAsync(DatasetInstance e2bInstance, PatientClinicalEvent activeReport, ReportInstance reportInstance, DateTime?onset, DateTime?recovery)
        {
            var terminologyMedDra = reportInstance.TerminologyMedDra;
            var term = terminologyMedDra != null ? terminologyMedDra.DisplayName : "";

            if (!String.IsNullOrWhiteSpace(term))
            {
                var datasetElement = await _datasetElementRepository.GetAsync(dse => dse.DatasetElementGuid.ToString() == "C8DD9A5E-BD9A-488D-8ABF-171271F5D370");

                e2bInstance.SetInstanceValue(datasetElement, term);;
            }
            ;  //Reaction MedDRA LLT

            if (onset != null)
            {
                var datasetElement = await _datasetElementRepository.GetAsync(dse => dse.DatasetElementGuid.ToString() == "1EAD9E11-60E6-4B27-9A4D-4B296B169E90");

                e2bInstance.SetInstanceValue(datasetElement, Convert.ToDateTime(onset).ToString("yyyyMMdd"));
            }
            ;  //Reaction Start Date

            if (recovery != null)
            {
                var datasetElement = await _datasetElementRepository.GetAsync(dse => dse.DatasetElementGuid.ToString() == "3A0F240E-8B36-48F6-9527-77E55F6E7CF1");

                e2bInstance.SetInstanceValue(datasetElement, Convert.ToDateTime(recovery).ToString("yyyyMMdd"));
            }
            ;  // Reaction End Date

            if (onset != null && recovery != null)
            {
                var rduration      = (Convert.ToDateTime(recovery) - Convert.ToDateTime(onset)).Days;
                var datasetElement = await _datasetElementRepository.GetAsync(dse => dse.DatasetElementGuid.ToString() == "0712C664-2ADD-44C0-B8D5-B6E83FB01F42");

                e2bInstance.SetInstanceValue(datasetElement, rduration.ToString()); //Reaction Duration

                datasetElement = await _datasetElementRepository.GetAsync(dse => dse.DatasetElementGuid.ToString() == "F96E702D-DCC5-455A-AB45-CAEFF25BF82A");

                e2bInstance.SetInstanceValue(datasetElement, "804=Day"); //Reaction Duration Unit
            }
        }
        private async Task SetInstanceValuesForActiveRelease2Async(DatasetInstance e2bInstance, PatientClinicalEvent activeReport)
        {
            var reportInstance = await _reportInstanceRepository.GetAsync(ri => ri.ContextGuid == activeReport.PatientClinicalEventGuid, new string[] { "Medications", "TerminologyMedDra" });

            // ************************************* ichicsrmessageheader
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "7FF710CB-C08C-4C35-925E-484B983F2135"), e2bInstance.Id.ToString("D8"));             // Message Number
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "693614B6-D5D5-457E-A03B-EAAFA66E6FBD"), DateTime.Today.ToString("yyyyMMddhhmmss")); // Message Date

            MapSafetyReportRelatedFields(e2bInstance, activeReport, reportInstance);
            MapPrimarySourceRelatedFields(e2bInstance, activeReport);
            MapSenderAndReceivedRelatedFields(e2bInstance);

            DateTime?onset, recovery;

            MapPatientRelatedFields(e2bInstance, activeReport, out onset, out recovery);

            await MapReactionRelatedFieldsAsync(e2bInstance, activeReport, reportInstance, onset, recovery);

            MapTestRelatedFields(e2bInstance, activeReport);
            await MapDrugRelatedFieldsAsync(e2bInstance, activeReport, reportInstance);
        }
Exemplo n.º 3
0
        public ActionResult EditSpontaneous(DatasetInstanceModel model)
        {
            ViewBag.MenuItem = CurrentMenuItem;

            var returnUrl = (TempData["returnUrl"] ?? string.Empty).ToString();

            ViewBag.ReturnUrl = returnUrl;

            DatasetInstance datasetInstance = null;

            var datasetInstanceRepository = _unitOfWork.Repository <DatasetInstance>();

            datasetInstance = datasetInstanceRepository
                              .Queryable()
                              .Include(di => di.Dataset)
                              .Include("DatasetInstanceValues.DatasetInstanceSubValues.DatasetElementSub")
                              .Include("DatasetInstanceValues.DatasetElement")
                              .SingleOrDefault(di => di.Id == model.DatasetInstanceId);

            if (datasetInstance == null)
            {
                ViewBag.Entity = "DatasetInstance";
                return(View("NotFound"));
            }

            if (ModelState.IsValid)
            {
                var datasetElementIds = model.DatasetCategories.SelectMany(dc => dc.DatasetElements.Select(dse => dse.DatasetElementId)).ToArray();

                var datasetElements = _unitOfWork.Repository <DatasetElement>()
                                      .Queryable()
                                      .Where(de => datasetElementIds.Contains(de.Id))
                                      .ToDictionary(e => e.Id);

                var datasetElementSubs = datasetElements
                                         .SelectMany(de => de.Value.DatasetElementSubs)
                                         .ToDictionary(des => des.Id);

                try
                {
                    for (int i = 0; i < model.DatasetCategories.Length; i++)
                    {
                        for (int j = 0; j < model.DatasetCategories[i].DatasetElements.Length; j++)
                        {
                            try
                            {
                                if (!model.DatasetCategories[i].DatasetElements[j].DatasetElementSystem)
                                {
                                    var eleVal = model.DatasetCategories[i].DatasetElements[j].DatasetElementValue != null ? model.DatasetCategories[i].DatasetElements[j].DatasetElementValue : string.Empty;
                                    if (eleVal != string.Empty)
                                    {
                                        datasetInstance.SetInstanceValue(datasetElements[model.DatasetCategories[i].DatasetElements[j].DatasetElementId], eleVal);
                                    }
                                }
                            }
                            catch (DatasetFieldSetException ex)
                            {
                                // Need to rename the key in order for the message to be bound to the correct control.
                                throw new DatasetFieldSetException(string.Format("DatasetCategories[{0}].DatasetElements[{1}].DatasetElementValue", i, j), ex.Message);
                            }
                        }
                    }

                    datasetInstanceRepository.Update(datasetInstance);

                    _unitOfWork.Complete();

                    HttpCookie cookie = new HttpCookie("PopUpMessage");
                    cookie.Value = "Spontaneous record updated successfully";
                    Response.Cookies.Add(cookie);

                    return(Redirect("/Home/Index"));
                }
                catch (DatasetFieldSetException dse)
                {
                    ModelState.AddModelError(dse.Key, dse.Message);
                }
            }

            var groupedDatasetCategoryElements = datasetInstance.Dataset.DatasetCategories
                                                 .SelectMany(dc => dc.DatasetCategoryElements)
                                                 .GroupBy(dce => dce.DatasetCategory)
                                                 .ToList();

            model.DatasetCategories = groupedDatasetCategoryElements
                                      .Select(dsc => new DatasetCategoryEditModel
            {
                DatasetCategoryId          = dsc.Key.Id,
                DatasetCategoryDisplayName = String.IsNullOrWhiteSpace(dsc.Key.FriendlyName) ? dsc.Key.DatasetCategoryName : dsc.Key.FriendlyName,
                DatasetCategoryHelp        = dsc.Key.Help,
                DatasetElements            = dsc.Select(e => new DatasetElementEditModel
                {
                    DatasetElementId          = e.DatasetElement.Id,
                    DatasetElementName        = e.DatasetElement.ElementName,
                    DatasetElementDisplayName = String.IsNullOrWhiteSpace(e.FriendlyName) ? e.DatasetElement.ElementName : e.FriendlyName,
                    DatasetElementHelp        = e.Help,
                    DatasetElementSystem      = e.DatasetElement.System,
                    DatasetElementRequired    = e.DatasetElement.Field.Mandatory,
                    DatasetElementDisplayed   = true,
                    DatasetElementChronic     = false,
                    DatasetElementType        = e.DatasetElement.Field.FieldType.Description,
                    DatasetElementValue       = datasetInstance.GetInstanceValue(e.DatasetElement),
                    DatasetElementSubs        = e.DatasetElement.DatasetElementSubs.Select(es => new DatasetElementSubEditModel
                    {
                        DatasetElementSubId       = es.Id,
                        DatasetElementSubName     = es.ElementName,
                        DatasetElementSubRequired = es.Field.Mandatory,
                        DatasetElementSubType     = es.Field.FieldType.Description //,
                                                                                   //DatasetElementSubValue = datasetInstance.GetInstanceSubValue(es)
                    }).ToArray()
                })
                                             .ToArray()
            })
                                      .ToArray();

            var selectTypeDatasetElements = model.DatasetCategories
                                            .SelectMany(dc => dc.DatasetElements)
                                            .Where(de => de.DatasetElementType == FieldTypes.Listbox.ToString() ||
                                                   de.DatasetElementType == FieldTypes.DropDownList.ToString())
                                            .ToArray();

            var yesNoDatasetElements = model.DatasetCategories
                                       .SelectMany(dc => dc.DatasetElements)
                                       .Where(de => de.DatasetElementType == FieldTypes.YesNo.ToString())
                                       .ToArray();

            var datasetElementRepository    = _unitOfWork.Repository <DatasetElement>();
            var datasetElementSubRepository = _unitOfWork.Repository <DatasetElementSub>();

            foreach (var element in selectTypeDatasetElements)
            {
                var elementFieldValues = datasetElementRepository.Queryable()
                                         .SingleOrDefault(de => de.Id == element.DatasetElementId)
                                         .Field.FieldValues
                                         .ToList();

                var elementFieldValueList = new List <SelectListItem> {
                    { new SelectListItem {
                          Value = "", Text = ""
                      } }
                };
                elementFieldValueList.AddRange(elementFieldValues.Select(ev => new SelectListItem {
                    Value = ev.Value, Text = ev.Value, Selected = element.DatasetElementValue == ev.Value
                }));

                ViewData.Add(element.DatasetElementName, elementFieldValueList.ToArray());
            }

            foreach (var element in yesNoDatasetElements)
            {
                var yesNo = new[] { new SelectListItem {
                                        Value = "", Text = ""
                                    }, new SelectListItem {
                                        Value = "No", Text = "No"
                                    }, new SelectListItem {
                                        Value = "Yes", Text = "Yes"
                                    } };

                var selectedYesNo = yesNo.SingleOrDefault(yn => yn.Value == element.DatasetElementValue);
                if (selectedYesNo != null)
                {
                    selectedYesNo.Selected = true;
                }

                ViewData.Add(element.DatasetElementName, yesNo);
            }

            return(View(model));
        }
Exemplo n.º 4
0
        public ActionResult AddSpontaneous(DatasetInstanceModel model)
        {
            DatasetInstance datasetInstance = null;

            var datasetInstanceRepository = _unitOfWork.Repository <DatasetInstance>();

            datasetInstance = datasetInstanceRepository
                              .Queryable()
                              .Include(di => di.Dataset)
                              .Include("DatasetInstanceValues.DatasetInstanceSubValues.DatasetElementSub")
                              .Include("DatasetInstanceValues.DatasetElement")
                              .SingleOrDefault(di => di.Id == model.DatasetInstanceId);

            if (ModelState.IsValid)
            {
                if (datasetInstance == null)
                {
                    ViewBag.Entity = "DatasetInstance";
                    return(View("NotFound"));
                }

                datasetInstance.Status = DatasetInstanceStatus.COMPLETE;

                var datasetElementIds = model.DatasetCategories.SelectMany(dc => dc.DatasetElements.Select(dse => dse.DatasetElementId)).ToArray();

                var datasetElements = _unitOfWork.Repository <DatasetElement>()
                                      .Queryable()
                                      .Where(de => datasetElementIds.Contains(de.Id))
                                      .ToDictionary(e => e.Id);

                var datasetElementSubs = datasetElements
                                         .SelectMany(de => de.Value.DatasetElementSubs)
                                         .ToDictionary(des => des.Id);

                try
                {
                    for (int i = 0; i < model.DatasetCategories.Length; i++)
                    {
                        for (int j = 0; j < model.DatasetCategories[i].DatasetElements.Length; j++)
                        {
                            try
                            {
                                if (model.DatasetCategories[i].DatasetElements[j].DatasetElementType != "Table")
                                {
                                    datasetInstance.SetInstanceValue(datasetElements[model.DatasetCategories[i].DatasetElements[j].DatasetElementId], model.DatasetCategories[i].DatasetElements[j].DatasetElementValue);
                                }
                            }
                            catch (DatasetFieldSetException ex)
                            {
                                // Need to rename the key in order for the message to be bound to the correct control.
                                throw new DatasetFieldSetException(string.Format("DatasetCategories[{0}].DatasetElements[{1}].DatasetElementValue", i, j), ex.Message);
                            }
                        }
                    }

                    datasetInstanceRepository.Update(datasetInstance);

                    // Instantiate new instance of work flow
                    var patientIdentifier = datasetInstance.GetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Identification Number"));
                    if (String.IsNullOrWhiteSpace(patientIdentifier))
                    {
                        patientIdentifier = datasetInstance.GetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Initials"));
                    }
                    var sourceIdentifier = datasetInstance.GetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Description of reaction"));
                    _workflowService.CreateWorkFlowInstance("New Spontaneous Surveilliance Report", datasetInstance.DatasetInstanceGuid, patientIdentifier, sourceIdentifier);

                    // Prepare medications
                    List <ReportInstanceMedicationListItem> medications = new List <ReportInstanceMedicationListItem>();
                    var sourceProductElement      = _unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Product Information");
                    var destinationProductElement = _unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Medicinal Products");
                    var sourceContexts            = datasetInstance.GetInstanceSubValuesContext(sourceProductElement);
                    foreach (Guid sourceContext in sourceContexts)
                    {
                        var drugItemValues = datasetInstance.GetInstanceSubValues(sourceProductElement, sourceContext);
                        var drugName       = drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Product").InstanceValue;

                        if (drugName != string.Empty)
                        {
                            var item = new ReportInstanceMedicationListItem()
                            {
                                MedicationIdentifier         = drugName,
                                ReportInstanceMedicationGuid = sourceContext
                            };
                            medications.Add(item);
                        }
                    }
                    _workflowService.AddOrUpdateMedicationsForWorkFlowInstance(datasetInstance.DatasetInstanceGuid, medications);

                    _unitOfWork.Complete();

                    return(RedirectToAction("FormAdded", "Public"));
                }
                catch (DatasetFieldSetException dse)
                {
                    ModelState.AddModelError(dse.Key, dse.Message);
                }
            }

            bool[] validCat;
            bool[] validMan;
            var    rule = datasetInstance.Dataset.GetRule(DatasetRuleType.MandatoryFieldsProminent);

            if (rule.RuleActive)
            {
                validCat = new[] { true, false };
                validMan = new[] { true, false };
            }
            else
            {
                validCat = new[] { false };
                validMan = new[] { true, false };
            }

            var groupedDatasetCategoryElements = datasetInstance.Dataset.DatasetCategories.Where(dc => validCat.Contains(dc.System)).OrderBy(dc => dc.CategoryOrder)
                                                 .SelectMany(dc => dc.DatasetCategoryElements).Where(dce => (rule.RuleActive && (dce.DatasetCategory.System == true && dce.DatasetElement.Field.Mandatory == true) || (dce.DatasetCategory.System == false && dce.DatasetElement.Field.Mandatory == false)) || (!rule.RuleActive && validMan.Contains(dce.DatasetElement.Field.Mandatory))).OrderBy(dce => dce.FieldOrder)
                                                 .GroupBy(dce => dce.DatasetCategory)
                                                 .ToList();

            model.DatasetCategories = groupedDatasetCategoryElements
                                      .Select(dsc => new DatasetCategoryEditModel
            {
                DatasetCategoryId          = dsc.Key.Id,
                DatasetCategoryDisplayName = String.IsNullOrWhiteSpace(dsc.Key.FriendlyName) ? dsc.Key.DatasetCategoryName : dsc.Key.FriendlyName,
                DatasetCategoryHelp        = dsc.Key.Help,
                DatasetElements            = dsc.Select(e => new DatasetElementEditModel
                {
                    DatasetElementId          = e.DatasetElement.Id,
                    DatasetElementName        = e.DatasetElement.ElementName,
                    DatasetElementDisplayName = String.IsNullOrWhiteSpace(e.FriendlyName) ? e.DatasetElement.ElementName : e.FriendlyName,
                    DatasetElementHelp        = e.Help,
                    DatasetElementRequired    = e.DatasetElement.Field.Mandatory,
                    DatasetElementDisplayed   = true,
                    DatasetElementChronic     = false,
                    DatasetElementType        = e.DatasetElement.Field.FieldType.Description,
                    DatasetElementValue       = datasetInstance.GetInstanceValue(e.DatasetElement),
                    DatasetElementSubs        = e.DatasetElement.DatasetElementSubs.Select(es => new DatasetElementSubEditModel
                    {
                        DatasetElementSubId       = es.Id,
                        DatasetElementSubName     = es.ElementName,
                        DatasetElementSubRequired = es.Field.Mandatory,
                        DatasetElementSubType     = es.Field.FieldType.Description //,
                                                                                   //DatasetElementSubValue = datasetInstance.GetInstanceSubValue(es)
                    }).ToArray()
                })
                                             .ToArray()
            })
                                      .ToArray();

            var selectTypeDatasetElements = model.DatasetCategories
                                            .SelectMany(dc => dc.DatasetElements)
                                            .Where(de => de.DatasetElementType == FieldTypes.Listbox.ToString() ||
                                                   de.DatasetElementType == FieldTypes.DropDownList.ToString())
                                            .ToArray();

            var yesNoDatasetElements = model.DatasetCategories
                                       .SelectMany(dc => dc.DatasetElements)
                                       .Where(de => de.DatasetElementType == FieldTypes.YesNo.ToString())
                                       .ToArray();

            var datasetElementRepository    = _unitOfWork.Repository <DatasetElement>();
            var datasetElementSubRepository = _unitOfWork.Repository <DatasetElementSub>();

            foreach (var element in selectTypeDatasetElements)
            {
                var elementFieldValues = datasetElementRepository.Queryable()
                                         .SingleOrDefault(de => de.Id == element.DatasetElementId)
                                         .Field.FieldValues
                                         .ToList();

                var elementFieldValueList = new List <SelectListItem> {
                    { new SelectListItem {
                          Value = "", Text = ""
                      } }
                };
                elementFieldValueList.AddRange(elementFieldValues.Select(ev => new SelectListItem {
                    Value = ev.Value, Text = ev.Value, Selected = element.DatasetElementValue == ev.Value
                }));

                ViewData.Add(element.DatasetElementName, elementFieldValueList.ToArray());
            }

            foreach (var element in yesNoDatasetElements)
            {
                var yesNo = new[] { new SelectListItem {
                                        Value = "", Text = ""
                                    }, new SelectListItem {
                                        Value = "No", Text = "No"
                                    }, new SelectListItem {
                                        Value = "Yes", Text = "Yes"
                                    } };

                var selectedYesNo = yesNo.SingleOrDefault(yn => yn.Value == element.DatasetElementValue);
                if (selectedYesNo != null)
                {
                    selectedYesNo.Selected = true;
                }

                ViewData.Add(element.DatasetElementName, yesNo);
            }

            return(View(model));
        }
        private void SetInstanceValuesForSpontaneousRelease3(DatasetInstance e2bInstance, DatasetInstance spontaneousReport, User currentUser)
        {
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "N.1.2 Batch Number"), "MSH.PViMS-B01000" + spontaneousReport.ToString());
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "N.1.5 Date of Batch Transmission"), DateTime.Now.ToString("yyyyMMddHHmmsss"));
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "N.2.r.1 Message Identifier"), "MSH.PViMS-B01000" + spontaneousReport.ToString() + "-" + DateTime.Now.ToString("mmsss"));
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "N.2.r.4 Date of Message Creation"), DateTime.Now.ToString("yyyyMMddHHmmsss"));
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.1.1 Sender’s (case) Safety Report Unique Identifier"), String.Format("US-MSH.PViMS-{0}-{1}", DateTime.Today.ToString("yyyy"), spontaneousReport.Id.ToString()));
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.1.2 Date of Creation"), DateTime.Now.ToString("yyyyMMddHHmmsss"));
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.1.8.1 Worldwide Unique Case Identification Number"), String.Format("US-MSH.PViMS-{0}-{1}", DateTime.Today.ToString("yyyy"), spontaneousReport.Id.ToString()));

            // Default remaining fields
            // C1 Identification
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.1.3 Type of Report"), "1=Spontaneous report");
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.1.4 Date Report Was First Received from Source"), spontaneousReport.Created.ToString("yyyy-MM-dd"));

            // C2 Primary Source
            var fullName = spontaneousReport.GetInstanceValue("Reporter Name");

            if (fullName != string.Empty)
            {
                if (fullName.Contains(" "))
                {
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.2.r.1.2 Reporter’s Given Name"), fullName.Substring(0, fullName.IndexOf(" ")));
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.2.r.1.4 Reporter’s Family Name"), fullName.Substring(fullName.IndexOf(" ") + 1, fullName.Length - (fullName.IndexOf(" ") + 1)));
                }
                else
                {
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.2.r.1.2 Reporter’s Given Name"), fullName);
                }
            }
            var place = spontaneousReport.GetInstanceValue("Reporter Place of Practise");

            if (place != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.2.r.2.1 Reporter’s Organisation"), place);
            }
            var address = spontaneousReport.GetInstanceValue("Reporter Address");

            if (address != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.2.r.2.3 Reporter’s Street"), address.Substring(0, 99));
            }
            var telNo = spontaneousReport.GetInstanceValue("Reporter Telephone Number");

            if (telNo != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.2.r.2.7 Reporter’s Telephone"), telNo);
            }

            // C3 Sender
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.3.3.3 Sender’s Given Name"), currentUser.FirstName);
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.3.3.5 Sender’s Family Name"), currentUser.LastName);
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "C.3.4.8 Sender’s E-mail Address"), currentUser.Email);

            // D Patient
            var dob   = spontaneousReport.GetInstanceValue("Date of Birth");
            var onset = spontaneousReport.GetInstanceValue("Date of Onset");

            if (dob != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.2.1 Date of Birth"), dob);

                if (onset != string.Empty)
                {
                    var age = (Convert.ToDateTime(onset) - Convert.ToDateTime(dob)).Days;
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.2.2a Age at Time of Onset of Reaction / Event"), age.ToString());
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.2.2bAge at Time of Onset of Reaction / Event (unit)"), "Day");
                }
            }
            var weight = spontaneousReport.GetInstanceValue("Weight (kg)");

            if (weight != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.3 Body Weight (kg)"), weight);
            }
            var sex = spontaneousReport.GetInstanceValue("Sex");

            if (sex != string.Empty)
            {
                if (sex == "Male")
                {
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.5 Sex"), "1=Male");
                }
                if (sex == "Female")
                {
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.5 Sex"), "2=Female");
                }
            }
            var death = spontaneousReport.GetInstanceValue("Reaction date of death");

            if (death != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "D.9.1 Date of Death"), death);
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.3.2a Results in Death"), "Yes");
            }

            // E Reaction
            var evnt = spontaneousReport.GetInstanceValue("Description of reaction");

            if (evnt != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.1.1a Reaction / Event as Reported by the Primary Source in Native Language"), evnt);
            }

            var term    = spontaneousReport.GetInstanceValue("TerminologyMedDra");
            var termOut = "NOT SET";

            if (term != string.Empty)
            {
                var termid = Convert.ToInt32(term);
                termOut = _unitOfWork.Repository <TerminologyMedDra>().Queryable().Single(u => u.Id == termid).DisplayName;
            }
            ;
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.2.1b MedDRA Code for Reaction / Event"), termOut);

            if (onset != string.Empty)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.4 Date of Start of Reaction / Event"), onset);
            }

            var outcome = spontaneousReport.GetInstanceValue("Outcome of reaction");

            if (outcome != string.Empty)
            {
                switch (outcome)
                {
                case "Died - Drug may be contributory":
                case "Died - Due to adverse reaction":
                case "Died - Unrelated to drug":
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.7 Outcome of Reaction / Event at the Time of Last Observation"), "5=fatal");
                    break;

                case "Not yet recovered":
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.7 Outcome of Reaction / Event at the Time of Last Observation"), "3=not recovered/not resolved/ongoing");
                    break;

                case "Recovered":
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.7 Outcome of Reaction / Event at the Time of Last Observation"), "1=recovered/resolved");
                    break;

                case "Uncertain outcome":
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "E.i.7 Outcome of Reaction / Event at the Time of Last Observation"), "0=unknown");
                    break;

                default:
                    break;
                }
            }

            for (int i = 1; i <= 6; i++)
            {
                var drugId      = 0;
                var elementName = "";
                var drugName    = "";
                var tempi       = 0;

                if (i < 4)
                {
                    drugId      = i;
                    elementName = string.Format("Suspected Drug {0}", drugId);
                    drugName    = spontaneousReport.GetInstanceValue(elementName);

                    if (drugName != string.Empty)
                    {
                        // Create a new context
                        var context = Guid.NewGuid();

                        e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.1 Characterisation of Drug Role"), "1=Suspect", context);
                        e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.2.2 Medicinal Product Name as Reported by the Primary Source"), drugName, context);

                        elementName = string.Format("Suspected Drug {0} Dosage", drugId);
                        var dosage = spontaneousReport.GetInstanceValue(elementName);
                        if (dosage != string.Empty)
                        {
                            if (Int32.TryParse(dosage, out tempi))
                            {
                                e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.1a Dose (number)"), dosage, context);
                            }
                        }
                        elementName = string.Format("Suspected Drug {0} Dosage Unit", drugId);
                        var dosageUnit = spontaneousReport.GetInstanceValue(elementName);
                        if (dosageUnit != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.1b Dose (unit)"), dosageUnit, context);
                        }
                        elementName = string.Format("Suspected Drug {0} Date Started", drugId);
                        var dateStarted = spontaneousReport.GetInstanceValue(elementName);
                        if (dateStarted != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.4 Date of Start of Drug"), dateStarted, context);
                        }
                        elementName = string.Format("Suspected Drug {0} Date Stopped", drugId);
                        var dateStopped = spontaneousReport.GetInstanceValue(elementName);
                        if (dateStopped != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.5 Date of Last Administration"), dateStopped, context);
                        }
                        elementName = string.Format("Suspected Drug {0} Batch Number", drugId);
                        var batch = spontaneousReport.GetInstanceValue(elementName);
                        if (batch != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.7 Batch / Lot Number"), batch, context);
                        }
                        elementName = string.Format("Suspected Drug {0} Route", drugId);
                        var route = spontaneousReport.GetInstanceValue(elementName);
                        if (route != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.10.1 Route of Administration"), route, context);
                        }
                    }
                }
                else
                {
                    drugId      = i - 3;
                    elementName = string.Format("Concomitant Drug {0}", drugId);
                    drugName    = spontaneousReport.GetInstanceValue(elementName);

                    if (drugName != string.Empty)
                    {
                        // Create a new context
                        var context = Guid.NewGuid();

                        e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.1 Characterisation of Drug Role"), "1=Suspect", context);
                        e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.2.2 Medicinal Product Name as Reported by the Primary Source"), drugName, context);

                        elementName = string.Format("Concomitant Drug {0} Dosage", drugId);
                        var dosage = spontaneousReport.GetInstanceValue(elementName);
                        if (dosage != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.1a Dose (number)"), dosage, context);
                        }
                        elementName = string.Format("Concomitant Drug {0} Dosage Unit", drugId);
                        var dosageUnit = spontaneousReport.GetInstanceValue(elementName);
                        if (dosageUnit != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.1b Dose (unit)"), dosageUnit, context);
                        }
                        elementName = string.Format("Concomitant Drug {0} Date Started", drugId);
                        var dateStarted = spontaneousReport.GetInstanceValue(elementName);
                        if (dateStarted != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.4 Date of Start of Drug"), dateStarted, context);
                        }
                        elementName = string.Format("Concomitant Drug {0} Date Stopped", drugId);
                        var dateStopped = spontaneousReport.GetInstanceValue(elementName);
                        if (dateStopped != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.5 Date of Last Administration"), dateStopped, context);
                        }
                        elementName = string.Format("Concomitant Drug {0} Batch Number", drugId);
                        var batch = spontaneousReport.GetInstanceValue(elementName);
                        if (batch != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.7 Batch / Lot Number"), batch, context);
                        }
                        elementName = string.Format("Concomitant Drug {0} Route", drugId);
                        var route = spontaneousReport.GetInstanceValue(elementName);
                        if (route != string.Empty)
                        {
                            e2bInstance.SetInstanceSubValue(_unitOfWork.Repository <DatasetElementSub>().Queryable().Single(dse => dse.ElementName == "G.k.4.r.10.1 Route of Administration"), route, context);
                        }
                    }
                }
            }
        }
        private void MapSenderAndReceivedRelatedFields(DatasetInstance e2bInstance)
        {
            var sendingAuthority = _siteContactDetailRepository.Get(cd => cd.ContactType == ContactType.SendingAuthority);

            if (sendingAuthority != null)
            {
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Sender Type"), ((int)sendingAuthority.OrganisationType).ToString());
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Sender Organization"), sendingAuthority.OrganisationName);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Sender Department"), sendingAuthority.DepartmentName);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Sender Given Name"), sendingAuthority.ContactFirstName);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Sender Family Name"), sendingAuthority.ContactSurname);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Sender Street Address"), sendingAuthority.StreetAddress);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Sender City"), sendingAuthority.City);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Sender State"), sendingAuthority.State);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Sender Postcode"), sendingAuthority.PostCode);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Sender Tel Number"), sendingAuthority.ContactNumber);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Sender Tel Country Code"), sendingAuthority.CountryCode);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Sender Email Address"), sendingAuthority.ContactEmail);
            }

            var receivingAuthority = _siteContactDetailRepository.Get(cd => cd.ContactType == ContactType.ReceivingAuthority);

            if (receivingAuthority != null)
            {
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Receiver Type"), ((int)receivingAuthority.OrganisationType).ToString());
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Receiver Organization"), receivingAuthority.OrganisationName);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Receiver Department"), receivingAuthority.DepartmentName);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Receiver Given Name"), receivingAuthority.ContactFirstName);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Receiver Family Name"), receivingAuthority.ContactSurname);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Receiver Street Address"), receivingAuthority.StreetAddress);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Receiver City"), receivingAuthority.City);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Receiver State"), receivingAuthority.State);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Receiver Postcode"), receivingAuthority.PostCode);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Receiver Tel"), receivingAuthority.ContactNumber);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Receiver Tel Country Code"), receivingAuthority.CountryCode);
                e2bInstance.SetInstanceValue(_datasetElementRepository.Get(dse => dse.ElementName == "Receiver Email Address"), receivingAuthority.ContactEmail);
            }
        }
        private void SetInstanceValuesForSpontaneousRelease2(DatasetInstance e2bInstance, DatasetInstance spontaneousReport, User currentUser)
        {
            // ************************************* ichicsrmessageheader
            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Message Header").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Message Number").DatasetElement, e2bInstance.Id.ToString("D8"));
            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Message Header").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Message Date").DatasetElement, DateTime.Today.ToString("yyyyMMddhhmmss"));

            // ************************************* safetyreport
            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Safety Report").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Safety Report ID").DatasetElement, string.Format("PH-FDA-{0}", spontaneousReport.Id.ToString("D5")));
            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Safety Report").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Transmission Date").DatasetElement, DateTime.Today.ToString("yyyyMMdd"));
            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Safety Report").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Report Type").DatasetElement, "1");

            var seriousReason = spontaneousReport.GetInstanceValue("Reaction serious details");

            if (!String.IsNullOrWhiteSpace(seriousReason))
            {
                var sd  = "2=No";
                var slt = "2=No";
                var sh  = "2=No";
                var sdi = "2=No";
                var sca = "2=No";
                var so  = "2=No";

                switch (seriousReason)
                {
                case "Resulted in death":
                    sd = "1=Yes";
                    break;

                case "Is life-threatening":
                    slt = "1=Yes";
                    break;

                case "Is a congenital anomaly/birth defect":
                    sca = "1=Yes";
                    break;

                case "Requires hospitalization or longer stay in hospital":
                    sh = "1=Yes";
                    break;

                case "Results in persistent or significant disability/incapacity (as per reporter's opinion)":
                    sdi = "1=Yes";
                    break;

                case "Other medically important condition":
                    so = "1=Yes";
                    break;

                default:
                    break;
                }

                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "B4EA6CBF-2D9C-482D-918A-36ABB0C96EFA"), sd);  //Seriousness Death
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "26C6F08E-B80B-411E-BFDC-0506FE102253"), slt); //Seriousness Life Threatening
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "837154A9-D088-41C6-A9E2-8A0231128496"), sh);  //Seriousness Hospitalization
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "DDEBDEC0-2A90-49C7-970E-B7855CFDF19D"), sdi); //Seriousness Disabling
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "DF89C98B-1D2A-4C8E-A753-02E265841F4F"), sca); //Seriousness Congenital Anomaly
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "33A75547-EF1B-42FB-8768-CD6EC52B24F8"), so);  //Seriousness Other
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "510EB752-2D75-4DC3-8502-A4FCDC8A621A"), "1"); //Serious
            }
            else
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "510EB752-2D75-4DC3-8502-A4FCDC8A621A"), "2"); //Serious
            }

            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Safety Report").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Date report was first received").DatasetElement, spontaneousReport.Created.ToString("yyyyMMdd"));
            e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Safety Report").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Date of most recent info").DatasetElement, spontaneousReport.Created.ToString("yyyyMMdd"));

            // ************************************* primarysource
            var fullName = spontaneousReport.GetInstanceValue("Reporter Name");

            if (!String.IsNullOrWhiteSpace(fullName))
            {
                if (fullName.Contains(" "))
                {
                    e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Primary Source").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Reporter Given Name").DatasetElement, fullName.Substring(0, fullName.IndexOf(" ")));
                    e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Primary Source").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Reporter Family Name").DatasetElement, fullName.Substring(fullName.IndexOf(" ") + 1, fullName.Length - (fullName.IndexOf(" ") + 1)));
                }
                else
                {
                    e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Primary Source").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Reporter Given Name").DatasetElement, fullName);
                }
            }

            MapSenderAndReceivedRelatedFields(e2bInstance);

            // ************************************* patient
            var dob      = spontaneousReport.GetInstanceValue("Date of Birth");
            var onset    = spontaneousReport.GetInstanceValue("Reaction known start date");
            var recovery = spontaneousReport.GetInstanceValue("Reaction date of recovery");

            if (!String.IsNullOrWhiteSpace(dob))
            {
                e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Patient").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Patient Birthdate").DatasetElement, Convert.ToDateTime(dob).ToString("yyyyMMdd"));

                if (!String.IsNullOrWhiteSpace(onset))
                {
                    var age = (Convert.ToDateTime(onset) - Convert.ToDateTime(dob)).Days;
                    e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Patient").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Patient Onset Age").DatasetElement, age.ToString());
                    e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Patient").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Patient Onset Age Unit").DatasetElement, "804=Day");
                }
            }

            // ************************************* reaction
            var term    = spontaneousReport.GetInstanceValue("TerminologyMedDra");
            var termOut = "NOT SET";

            if (!String.IsNullOrWhiteSpace(term))
            {
                var termid = Convert.ToInt32(term);
                termOut = _unitOfWork.Repository <TerminologyMedDra>().Queryable().Single(u => u.Id == termid).DisplayName;
            }
            ;
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.ElementName == "Reaction MedDRA LLT"), termOut);
            if (!String.IsNullOrWhiteSpace(onset))
            {
                e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Reaction").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Reaction Start Date").DatasetElement, Convert.ToDateTime(onset).ToString("yyyyMMdd"));
            }
            ;
            if (!String.IsNullOrWhiteSpace(onset) && !String.IsNullOrWhiteSpace(recovery))
            {
                var rduration = (Convert.ToDateTime(recovery) - Convert.ToDateTime(onset)).Days;
                e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Reaction").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Reaction Duration").DatasetElement, rduration.ToString());
                e2bInstance.SetInstanceValue(e2bInstance.Dataset.DatasetCategories.Single(dc => dc.DatasetCategoryName == "Reaction").DatasetCategoryElements.Single(dce => dce.DatasetElement.ElementName == "Reaction Duration Unit").DatasetElement, "804=Day");
            }

            // ************************************* drug
            var destinationProductElement = _unitOfWork.Repository <DatasetElement>().Queryable().SingleOrDefault(u => u.ElementName == "Medicinal Products");
            var sourceContexts            = spontaneousReport.GetInstanceSubValuesContext("Product Information");

            foreach (Guid sourceContext in sourceContexts)
            {
                var drugItemValues = spontaneousReport.GetInstanceSubValues("Product Information", sourceContext);
                var drugName       = drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Product").InstanceValue;

                if (drugName != string.Empty)
                {
                    Guid?newContext = e2bInstance.GetContextForInstanceSubValue(destinationProductElement, destinationProductElement.DatasetElementSubs.SingleOrDefault(des => des.ElementName == "Medicinal Product"), drugName);
                    if (newContext != null)
                    {
                        var reportInstanceMedication = _unitOfWork.Repository <ReportInstanceMedication>().Queryable().Single(x => x.ReportInstanceMedicationGuid == sourceContext);

                        // Causality
                        if (reportInstanceMedication.WhoCausality != null)
                        {
                            e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Drug Reaction Assessment"), spontaneousReport.GetInstanceValue("Description of reaction"), (Guid)newContext);
                            e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Method of Assessment"), "WHO Causality Scale", (Guid)newContext);
                            e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Assessment Result"), reportInstanceMedication.WhoCausality.ToLowerInvariant() == "ignored" ? "" : reportInstanceMedication.WhoCausality, (Guid)newContext);
                        }
                        else
                        {
                            if (reportInstanceMedication.NaranjoCausality != null)
                            {
                                e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Drug Reaction Assessment"), spontaneousReport.GetInstanceValue("Description of reaction"), (Guid)newContext);
                                e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Method of Assessment"), "Naranjo Causality Scale", (Guid)newContext);
                                e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Assessment Result"), reportInstanceMedication.NaranjoCausality.ToLowerInvariant() == "ignored" ? "" : reportInstanceMedication.NaranjoCausality, (Guid)newContext);
                            }
                        }

                        // Treatment Duration
                        var startValue = drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Drug Start Date");
                        var endValue   = drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Drug End Date");
                        if (startValue != null && endValue != null)
                        {
                            var rduration = (Convert.ToDateTime(endValue.InstanceValue) - Convert.ToDateTime(startValue.InstanceValue)).Days;
                            e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Drug Treatment Duration"), rduration.ToString(), (Guid)newContext);
                            e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Drug Treatment Duration Unit"), "804=Day", (Guid)newContext);
                        }

                        // Dosage
                        if (drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Drug Strength") != null && drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Dose Number") != null)
                        {
                            decimal strength = ConvertValueToDecimal(drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Drug Strength").InstanceValue);
                            decimal dosage   = ConvertValueToDecimal(drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Dose Number").InstanceValue);

                            decimal dosageCalc = strength * dosage;
                            e2bInstance.SetInstanceSubValue(destinationProductElement.DatasetElementSubs.Single(des => des.ElementName == "Structured Dosage"), dosageCalc.ToString(), (Guid)newContext);
                        }
                    }
                }
            }
        }
        private void MapPatientRelatedFields(DatasetInstance e2bInstance, PatientClinicalEvent activeReport, out DateTime?onset, out DateTime?recovery)
        {
            IExtendable activeReportExtended = activeReport;
            IExtendable patientExtended      = activeReport.Patient;

            var init = String.Format("{0}{1}", activeReport.Patient.FirstName.Substring(0, 1), activeReport.Patient.Surname.Substring(0, 1));

            if (!String.IsNullOrWhiteSpace(init))
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "A0BEAB3A-0B0A-457E-B190-1B66FE60CA73"), init);
            }
            ;                                                                                                                                                                                                                               //Patient Initial

            var dob = activeReport.Patient.DateOfBirth;

            onset    = activeReport.OnsetDate;
            recovery = activeReport.ResolutionDate;
            if (dob.HasValue)
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "4F71B7F4-4317-4680-B3A3-9C1C1F72AD6A"), dob.Value.ToString("yyyyMMdd")); //Patient Birthdate

                if (onset.HasValue)
                {
                    var age = onset.Value.Year - dob.Value.Year;
                    if (dob.Value > onset.Value.AddYears(-age))
                    {
                        age--;
                    }

                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "E10C259B-DD2C-4F19-9D41-16FDDF9C5807"), age.ToString()); //Patient Onset Age
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "CA9B94C2-E1EF-407B-87C3-181224AF637A"), "801=Year");     //Patient Onset Age Unit
                }
            }

            var encounter = _unitOfWork.Repository <Encounter>().Queryable().OrderByDescending(e => e.EncounterDate).FirstOrDefault(e => e.Patient.Id == activeReport.Patient.Id && e.Archived == false & e.EncounterDate <= activeReport.OnsetDate);

            if (encounter != null)
            {
                var encounterInstance = _unitOfWork.Repository <DatasetInstance>().Queryable().SingleOrDefault(ds => ds.Dataset.DatasetName == "Chronic Treatment" && ds.ContextId == encounter.Id);
                if (encounterInstance != null)
                {
                    var weight = encounterInstance.GetInstanceValue("Weight (kg)");
                    if (!String.IsNullOrWhiteSpace(weight))
                    {
                        e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "89A6E687-A220-4319-AAC1-AFBB55C81873"), weight);
                    }
                    ;                                                                                                                                                                                                                                   //Patient Weight

                    var height = encounterInstance.GetInstanceValue("Height (cm)");
                    if (!String.IsNullOrWhiteSpace(height))
                    {
                        e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "40DAD435-8282-4B3E-B65E-3478FF55D028"), height);
                    }
                    ;                                                                                                                                                                                                                                   //Patient Height

                    var lmp = encounterInstance.GetInstanceValue("Date of last menstrual period");
                    if (!String.IsNullOrWhiteSpace(lmp))
                    {
                        e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "93253F91-60D1-4161-AF1A-F3ABDD140CB9"), Convert.ToDateTime(lmp).ToString("yyyyMMdd"));
                    }
                    ;                                                                                                                                                                                                                                                                      //Patient Last Menstrual Date

                    var gest = encounterInstance.GetInstanceValue("Estimated gestation (weeks)");
                    if (!String.IsNullOrWhiteSpace(gest))
                    {
                        e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "B6BE9689-B6B2-4FCF-8918-664AFC91A4E0"), gest);       //Gestation Period
                        e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "1F174413-2A1E-45BD-B5C4-0C8F5DFFBFF4"), "803=Week"); //Gestation Period Unit
                    }
                    ;
                }
            }

            var objectValue = activeReportExtended.GetAttributeValue("Weight (kg)");
            var weightKg    = objectValue != null?objectValue.ToString() : "";

            if (!String.IsNullOrWhiteSpace(weightKg))
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "89A6E687-A220-4319-AAC1-AFBB55C81873"), weightKg);
            }
            ;

            objectValue = activeReportExtended.GetAttributeValue("Height (cm)");
            var heightCm = objectValue != null?objectValue.ToString() : "";

            if (!String.IsNullOrWhiteSpace(heightCm))
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "40DAD435-8282-4B3E-B65E-3478FF55D028"), heightCm);
            }
            ;

            objectValue = patientExtended.GetAttributeValue("Gender");
            var patientSex = objectValue != null?objectValue.ToString() : "";

            if (!String.IsNullOrWhiteSpace(patientSex))
            {
                if (patientSex == "1")
                {
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "59498520-172C-42BC-B30C-E249F94E412A"), "1=Male");
                }
                if (patientSex == "2")
                {
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "59498520-172C-42BC-B30C-E249F94E412A"), "2=Female");
                }
            }
            ;
        }
        private object MapPrimarySourceRelatedFields(DatasetInstance e2bInstance, PatientClinicalEvent activeReport)
        {
            IExtendable activeReportExtended = activeReport;

            object objectValue = activeReportExtended.GetAttributeValue("Name of reporter");
            var    fullName    = objectValue != null?objectValue.ToString() : "";

            if (!String.IsNullOrWhiteSpace(fullName))
            {
                if (fullName.Contains(" "))
                {
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "C35D5F5A-D539-4EEE-B080-FF384D5FBE08"), fullName.Substring(0, fullName.IndexOf(" ")));                                                 //Reporter Given Name
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "F214C619-EE0E-433E-8F52-83469778E418"), fullName.Substring(fullName.IndexOf(" ") + 1, fullName.Length - (fullName.IndexOf(" ") + 1))); //Reporter Family Name
                }
                else
                {
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "C35D5F5A-D539-4EEE-B080-FF384D5FBE08"), fullName); //Reporter Given Name
                }
            }

            objectValue = activeReportExtended.GetAttributeValue("Profession");
            var profession = objectValue != null?objectValue.ToString() : "";

            if (!String.IsNullOrWhiteSpace(profession))
            {
                var selectionValue = _unitOfWork.Repository <SelectionDataItem>().Queryable().Single(sdi => sdi.AttributeKey == "Profession" && sdi.SelectionKey == profession).Value;

                switch (selectionValue.Trim())
                {
                case "Dentist":
                case "RN":
                case "Other health professional":
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "1D59E85E-66AF-4E70-B779-6AB873DE1E84"), "3=Other Health Professional");    //Qualification
                    break;

                case "Medical Doctor":
                case "Physician":
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "1D59E85E-66AF-4E70-B779-6AB873DE1E84"), "1=Physician");
                    break;

                case "Patient":
                case "Consumer or other non health professional":
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "1D59E85E-66AF-4E70-B779-6AB873DE1E84"), "5=Consumer or other non health professional");
                    break;

                case "RPh":
                case "Pharmacist":
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "1D59E85E-66AF-4E70-B779-6AB873DE1E84"), "2=Pharmacist");
                    break;

                case "Lawyer":
                    e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "1D59E85E-66AF-4E70-B779-6AB873DE1E84"), "4=Lawyer");
                    break;

                default:
                    break;
                }
            }

            return(objectValue);
        }
Exemplo n.º 10
0
        private void MapSafetyReportRelatedFields(DatasetInstance e2bInstance, PatientClinicalEvent activeReport, ReportInstance reportInstance)
        {
            IExtendable activeReportExtended = activeReport;

            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "6799CAD0-2A65-48A5-8734-0090D7C2D85E"), string.Format("PH.FDA.{0}", reportInstance.Id.ToString("D6"))); //Safety Report ID
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "9C92D382-03AF-4A52-9A2F-04A46ADA0F7E"), DateTime.Today.ToString("yyyyMMdd"));                           //Transmission Date
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "AE53FEB2-FF27-4CD5-AD54-C3FFED1490B5"), "2");                                                           //Report Type

            activeReportExtended = activeReport;
            var objectValue = activeReportExtended.GetAttributeValue("Is the adverse event serious?");
            var serious     = objectValue != null?objectValue.ToString() : "";

            if (!String.IsNullOrWhiteSpace(serious))
            {
                var selectionValue = _unitOfWork.Repository <SelectionDataItem>().Queryable().Single(sdi => sdi.AttributeKey == "Is the adverse event serious?" && sdi.SelectionKey == serious).Value;
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "510EB752-2D75-4DC3-8502-A4FCDC8A621A"), selectionValue == "Yes" ? "1=Yes" : "2=No"); //Serious
            }

            objectValue = activeReportExtended.GetAttributeValue("Seriousness");
            var seriousReason = objectValue != null?objectValue.ToString() : "";

            if (!String.IsNullOrWhiteSpace(seriousReason) && serious == "1")
            {
                var selectionValue = _unitOfWork.Repository <SelectionDataItem>().Queryable().Single(si => si.AttributeKey == "Seriousness" && si.SelectionKey == seriousReason).Value;

                var sd  = "2=No";
                var slt = "2=No";
                var sh  = "2=No";
                var sdi = "2=No";
                var sca = "2=No";
                var so  = "2=No";

                switch (selectionValue)
                {
                case "Death":
                    sd = "1=Yes";
                    break;

                case "Life threatening":
                    slt = "1=Yes";
                    break;

                case "A congenital anomaly or birth defect":
                    sca = "1=Yes";
                    break;

                case "Initial or prolonged hospitalization":
                    sh = "1=Yes";
                    break;

                case "Persistent or significant disability or incapacity":
                    sdi = "1=Yes";
                    break;

                case "A medically important event":
                    so = "1=Yes";
                    break;

                default:
                    break;
                }

                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "B4EA6CBF-2D9C-482D-918A-36ABB0C96EFA"), sd);  //Seriousness Death
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "26C6F08E-B80B-411E-BFDC-0506FE102253"), slt); //Seriousness Life Threatening
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "837154A9-D088-41C6-A9E2-8A0231128496"), sh);  //Seriousness Hospitalization
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "DDEBDEC0-2A90-49C7-970E-B7855CFDF19D"), sdi); //Seriousness Disabling
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "DF89C98B-1D2A-4C8E-A753-02E265841F4F"), sca); //Seriousness Congenital Anomaly
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "33A75547-EF1B-42FB-8768-CD6EC52B24F8"), so);  //Seriousness Other
            }

            objectValue = activeReportExtended.GetAttributeValue("Date of Report");
            var reportDate = objectValue != null?objectValue.ToString() : "";

            DateTime tempdt;

            if (DateTime.TryParse(reportDate, out tempdt))
            {
                e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "65ADEF15-961A-4558-B864-7832D276E0E3"), Convert.ToDateTime(reportDate).ToString("yyyyMMdd")); //Date report was first received
            }
            e2bInstance.SetInstanceValue(_unitOfWork.Repository <DatasetElement>().Queryable().Single(dse => dse.DatasetElementGuid.ToString() == "A10C704D-BC1D-445E-B084-9426A91DB63B"), DateTime.Today.ToString("yyyyMMdd"));                     //Date of most recent info
        }