public MtsRecord()
 {
     Patient  = new MotPatientRecord();
     Scrip    = new MotPrescriptionRecord();
     Facility = new MotFacilityRecord();
     Doc      = new MotPrescriberRecord();
 }
        // (0)DOE, JOHN ~(1)25731~(2)SPRINGFIELD RETIREMENT CASTLE~(3)~(4)2~(5)201~(6)13~(7)68180041109~(8)AVAPRO 150 MG TABLET~(9)IRBESARTAN 150 MG TABLET~(10)20170204~0730~1~~MICHELLE SMITH ~8880440~INFORME piel o reaccion alergica.~NO conducir si mareado o vision borrosa.~TAKE 1 TABLET DAILY IN THE MORNING ~~~~M~00~28~8880440_00_25/28~
        /// <summary>
        /// <c>Go</c>
        /// </summary>
        /// Built as a bridge interface to BestRx, the method reads a Parada packing machine file and pulls out as
        /// much useable information as it can ad pushes it into the DB.  It's too lightweight to be considered a
        /// true interface, but can be used in a pinch.
        public void Go()
        {
            var rows         = Data.Split('\n');
            var lastScrip    = string.Empty;
            var lastDoseQty  = string.Empty;
            var lastDoseTime = string.Empty;
            var firstScrip   = true;
            var committed    = false;

            var doseTimes   = new List <string>();
            var nameVersion = 1;

            var scrip        = new MotPrescriptionRecord("Add", AutoTruncate);
            var patient      = new MotPatientRecord("Add", AutoTruncate);
            var facility     = new MotFacilityRecord("Add", AutoTruncate);
            var drug         = new MotDrugRecord("Add", AutoTruncate);
            var practitioner = new MotPrescriberRecord("Add", AutoTruncate);

            var writeQueue = new MotWriteQueue();

            patient.LocalWriteQueue                  =
                scrip.LocalWriteQueue                =
                    facility.LocalWriteQueue         =
                        practitioner.LocalWriteQueue =
                            drug.LocalWriteQueue     =
                                writeQueue;

            patient.QueueWrites                  =
                scrip.QueueWrites                =
                    facility.QueueWrites         =
                        practitioner.QueueWrites =
                            drug.QueueWrites     =
                                true;

            writeQueue.SendEof   = false; // Has to be off so we don't lose the socket.
            writeQueue.DebugMode = DebugMode;

            try
            {
                foreach (var row in rows)               // This will generate new records for every row - need to optimize
                {
                    if (row.Length > 0)                 // --- The latest test file has a trailing "\r" and a messed up drug name,  need to address both
                    {
                        var rawRecord = row.Split('~'); // There's no guarantee that each field has data but the count is right

                        if (lastScrip != rawRecord[15]) // Start a new scrip
                        {
                            if (firstScrip == false)    // Commit the previous scrip
                            {
                                if (doseTimes.Count > 1)
                                {
                                    // Build and write TQ Record
                                    var tq = new MotTimesQtysRecord("Add", AutoTruncate)
                                    {
                                        // New name
                                        DoseScheduleName = facility.LocationName?.Substring(0, 3) + nameVersion
                                    };

                                    nameVersion++;

                                    // Fill the record
                                    tq.LocationID    = patient.LocationID;
                                    tq.DoseTimesQtys = scrip.DoseTimesQtys;

                                    // Assign the DoseSchcedulw name to the scrip & clear the scrip DoseTimeSchedule
                                    scrip.DoseScheduleName = tq.DoseScheduleName;
                                    scrip.DoseTimesQtys    = "";

                                    // Write the record
                                    tq.LocalWriteQueue = writeQueue;
                                    tq.AddToQueue();
                                }

                                Console.WriteLine($"Committing on Thread {Thread.CurrentThread.Name}");

                                scrip.Commit(GatewaySocket);
                                // ReSharper disable once RedundantAssignment
                                committed = true;

                                practitioner.Clear();
                                facility.Clear();
                                drug.Clear();
                                patient.Clear();
                                scrip.Clear();
                            }

                            firstScrip = committed = false;
                            lastScrip  = rawRecord[15];
                            doseTimes.Clear();

                            var names = rawRecord[0].Split(',');
                            patient.LastName  = (names[0] ?? "Warning[PFN]").Trim();
                            patient.FirstName = (names[1] ?? "Warning[PLN]").Trim();

                            if (rawRecord[2].Length >= 4)
                            {
                                patient.LocationID = rawRecord[2]?.Trim()?.Substring(0, 4);
                            }

                            patient.PatientID = rawRecord[1];
                            patient.Room      = rawRecord[4];
                            patient.Address1  = "";
                            patient.Address2  = "";
                            patient.City      = "";
                            patient.State     = "NH";
                            patient.Zipcode   = "";
                            patient.Status    = 1;

                            facility.LocationName = rawRecord[2];
                            facility.Address1     = "";
                            facility.Address2     = "";
                            facility.City         = "";
                            facility.State        = "NH";
                            facility.Zipcode      = "";

                            if (rawRecord[2].Length >= 4)
                            {
                                facility.LocationID = rawRecord[2]?.Trim()?.Substring(0, 4);
                            }

                            drug.NDCNum = rawRecord[7];
                            drug.DrugID = rawRecord[7];

                            if (drug.NDCNum == "0")
                            {
                                // It's something goofy like a compound; ignore it
                                EventLogger.Warn($"Ignoring thig with NDC == 0 named {rawRecord[8]}");
                                continue;

                                //__scrip.ChartOnly = "1";
                                //__drug.NDCNum = "00000000000";
                                //var __rand = new Random();
                                //__drug.RxSys_DrugID = __rand.Next().ToString();
                                //__drug.DefaultIsolate = 1;
                            }

                            //
                            // Some funny stuff happens here as the umber of items from the split is varible - we've seen 2,3,4, & 5
                            // Examples
                            //          -- Trade And Generic Pair - Each 4 items, same format {[name][strength][unit][route]}
                            //          AVAPRO 150 MG TABLE
                            //          IRBESARTAN 150 MG TABLET
                            //
                            //          -- Trade and Generic Name - 4 items for each but different strength formats
                            //          CRESTOR 10 MG TABLET
                            //          ROSUVASTATIN TB 10MG 30
                            //
                            //          -- Trade and Generic Name  - 4 items for trade, 5 for Generic
                            //          ZOLOFT 100 MG TABLET
                            //          SERTRALINE HCL 100 MG TABLET
                            //
                            //          -- Trade and Generic Name - 6 items for Trade, 5 for Generic
                            //          500 + D 500-200 MG-IU TABLET
                            //          OYSTER SHELL CALCIUM 500-200 MG
                            //
                            //          Another Trade and Genmeric Name with 4 items for the Trade and 5 for the generic
                            //          FOSAMAX 35 MG TABLET
                            //          ALENDRONATE SODIUM 35 MG TABLET
                            //
                            //  Note that it's also only required to have one or the other, not both
                            //
                            //
                            //  Push everything down into a structure and have it return a struct defining both

                            string tempTradeName = string.Empty;

                            if (DrugName.ParseExact(rawRecord[8]))
                            {
                                drug.TradeName = drug.DrugName = $"{DrugName.Name} {DrugName.Strength} {DrugName.Unit} {DrugName.Form}";
                                drug.ShortName = $"{DrugName.Name} {DrugName.Strength} {DrugName.Unit}";
                                drug.Unit      = DrugName.Unit;
                                drug.Strength  = Convert.ToDouble(DrugName.Strength ?? "0.00");
                                drug.DoseForm  = DrugName.Form;

                                tempTradeName = $"{DrugName.Name} {DrugName.Strength} {DrugName.Unit} {DrugName.Form}";
                            }

                            if (DrugName.ParseExact(rawRecord[9]))
                            {
                                drug.TradeName  = drug.DrugName = $"{DrugName.Name} {DrugName.Strength} {DrugName.Unit} {DrugName.Form}";
                                drug.ShortName  = $"{DrugName.Name} {DrugName.Strength} {DrugName.Unit}";
                                drug.Unit       = DrugName.Unit;
                                drug.Strength   = Convert.ToDouble(DrugName.Strength ?? "0.00");
                                drug.DoseForm   = DrugName.Form;
                                drug.GenericFor = tempTradeName;
                            }

                            if (!string.IsNullOrEmpty(rawRecord[9]) && string.IsNullOrEmpty(drug.TradeName))
                            {
                                drug.DrugName = drug.TradeName = rawRecord[9] ?? "Unknown";
                            }

                            string[] practitionerName = rawRecord[14].Split(' ');
                            practitioner.FirstName = (practitionerName[0] ?? "Warning[DFN]").Trim();
                            practitioner.LastName  = (practitionerName[1] ?? "Warning[DLN]").Trim();
                            practitioner.Address1  = "";
                            practitioner.Address2  = "";
                            practitioner.City      = "";
                            practitioner.State     = "NH";
                            practitioner.Zipcode   = "";

                            try
                            {
                                switch (practitionerName.Length)
                                {
                                case 2:
                                    if (practitionerName[0].Length >= 3 && practitionerName[1].Length >= 3)
                                    {
                                        practitioner.PrescriberID = practitionerName[0]?.Trim()?.Substring(0, 3) + practitionerName[1]?.Trim()?.Substring(0, 3);
                                    }
                                    practitioner.FirstName = (practitionerName[0] ?? "Warning[DFN]").Trim();
                                    practitioner.LastName  = (practitionerName[1] ?? "Warning[DLN]").Trim();
                                    break;

                                case 3:
                                    if (practitionerName[1].Length >= 3 && practitionerName[2].Length >= 3)
                                    {
                                        practitioner.PrescriberID = practitionerName[0]?.Trim()?.Substring(0, 3) + practitionerName[2]?.Trim()?.Substring(0, 3);
                                    }
                                    practitioner.FirstName     = practitionerName[0]?.Trim();
                                    practitioner.MiddleInitial = practitionerName[1].Trim();
                                    practitioner.LastName      = practitionerName[2]?.Trim();
                                    break;

                                default:
                                    practitioner.PrescriberID = new Random(40000).ToString();
                                    break;
                                }
                            }
                            catch
                            {
                                practitioner.PrescriberID = new Random(60000).ToString();
                            }

                            patient.PrimaryPrescriberID = practitioner.PrescriberID;

                            scrip.PrescriptionID = rawRecord[15];
                            scrip.PatientID      = patient.PatientID;
                            scrip.PrescriberID   = patient.PrimaryPrescriberID;
                            scrip.Status         = 1;

                            scrip.RxStartDate = string.IsNullOrEmpty(rawRecord[10]) ? DateTime.Now : scrip.TransformDate(rawRecord[10] ?? "");

                            if (rawRecord[11] != null && rawRecord[12] != null)
                            {
                                scrip.DoseTimesQtys = $"{Convert.ToInt32(rawRecord[11]):0000}{Convert.ToDouble(rawRecord[12]):00.00}";
                            }

                            scrip.QtyPerDose   = Convert.ToDouble(rawRecord[12] ?? "0.00");
                            scrip.QtyDispensed = Convert.ToDouble(rawRecord[24] ?? "0.00");
                            scrip.Sig          = $"{rawRecord[18]}\n{rawRecord[19]}\n{rawRecord[20]}";
                            scrip.Comments     = $"{rawRecord[16]}\n{rawRecord[17]}";
                            scrip.Refills      = Convert.ToInt32(rawRecord[23] ?? "0");
                            scrip.DrugID       = drug.NDCNum;
                            scrip.RxType       = rawRecord[22].Trim().ToUpper() == "P" ? 2 : 1;

                            lastDoseTime = rawRecord[11];
                            lastDoseQty  = rawRecord[12];
                            doseTimes.Add(lastDoseTime);

                            practitioner.AddToQueue();
                            patient.AddToQueue();
                            facility.AddToQueue();
                            drug.AddToQueue();
                            scrip.AddToQueue();
                        }
                        else
                        {
                            if (lastDoseTime != rawRecord[11] || lastDoseQty != rawRecord[12])
                            {
                                if (!doseTimes.Contains(rawRecord[11]))  // Create a new TQ Dose Schedule here!!
                                {
                                    // Kludge
                                    if (rawRecord[11] != null)
                                    {
                                        var tempTest = $"{Convert.ToInt32(rawRecord[11]):0000}";

                                        if (tempTest.Substring(2, 2) == "15" ||
                                            tempTest.Substring(2, 2) == "45")
                                        {
                                            tempTest             = tempTest.Replace(tempTest.Substring(2, 2), "00");
                                            scrip.DoseTimesQtys += $"{tempTest}{Convert.ToDouble(rawRecord[12]):00.00}";
                                        }
                                        else
                                        {
                                            scrip.DoseTimesQtys += $"{Convert.ToInt32(rawRecord[11]):0000}{Convert.ToDouble(rawRecord[12]):00.00}";
                                        }
                                    }
                                    lastDoseQty  = rawRecord[12];
                                    lastDoseTime = rawRecord[11];
                                    doseTimes.Add(lastDoseTime);
                                }
                            }
                        }
                    }
                    else
                    {
                        // Fell through to here because the row length was 0
                        if (committed)
                        {
                            continue;
                        }

                        scrip.Commit(GatewaySocket);
                        committed = true;
                    }
                }
            }
            catch (Exception ex)
            {
                EventLogger.Error($"Error parsing Parada record {Data}: {ex.Message}");
                throw;
            }
        }
        public void ForceIdOverflowWithGuid()
        {
            // This will force a record rejection bu issuing a Guid as an ID
            // Note that the motNext gatewaty returns a 6 (success) even though it fails

            var patientId1   = Guid.NewGuid().ToString();
            var patientId2   = Guid.NewGuid().ToString();
            var prescriberId = Guid.NewGuid().ToString();
            var facilityId   = Guid.NewGuid().ToString();

            using (var localTcpClient = new TcpClient("localhost", 24042))
            {
                using (var stream = localTcpClient.GetStream())
                {
                    try
                    {
                        var facility = new MotFacilityRecord("Add");
                        facility.LocationName = "Banzai Institute";
                        facility.LocationID   = facilityId;
                        facility.logRecords   = logRecords;
                        facility.Write(stream);

                        var doc = new MotPrescriberRecord("Add")
                        {
                            PrescriberID = prescriberId,
                            DEA_ID       = "AD1234567",
                            LastName     = "Lizardo",
                            FirstName    = "Emillio"
                        };

                        doc.Write(stream);

                        using (var AddBuckaroo = new MotPatientRecord("Add"))
                        {
                            AddBuckaroo.PatientID           = patientId1;
                            AddBuckaroo.FirstName           = "Buckaroo";
                            AddBuckaroo.LastName            = "Banzai";
                            AddBuckaroo.PrimaryPrescriberID = prescriberId;
                            AddBuckaroo.DOB        = DateTime.Now;
                            AddBuckaroo.CycleDate  = DateTime.Now;
                            AddBuckaroo.CycleDays  = 30;
                            AddBuckaroo.LocationID = facilityId;
                            AddBuckaroo.logRecords = logRecords;

                            AddBuckaroo.Write(stream);
                        }

                        var AddPenny = new MotPatientRecord("Add")
                        {
                            PatientID           = patientId2,
                            FirstName           = "Penny",
                            LastName            = "Priddy",
                            PrimaryPrescriberID = prescriberId,
                            DOB        = DateTime.Now,
                            CycleDate  = DateTime.Now,
                            CycleDays  = 30,
                            LocationID = facilityId,
                            logRecords = logRecords
                        };

                        AddPenny.Write(stream);

                        using (var deletePenny = new MotPatientRecord("Delete"))
                        {
                            deletePenny.PatientID = patientId2;
                            deletePenny.Write(stream);
                        }

                        using (var deleteBuckaroo = new MotPatientRecord("Delete"))
                        {
                            deleteBuckaroo.PatientID = patientId1;
                            deleteBuckaroo.Write(stream);
                        }

                        using (var deleteLizardo = new MotPrescriberRecord("Delete"))
                        {
                            deleteLizardo.PrescriberID = prescriberId;
                            deleteLizardo.Write(stream);
                        }

                        using (var deleteFacility = new MotFacilityRecord("Delete"))
                        {
                            deleteFacility.LocationID = facilityId;
                            deleteFacility.Write(stream);
                        }
                    }
                    catch (Exception ex)
                    {
                        Assert.Fail(ex.Message);
                    }
                }
            }
        }
        public void RandomDataCycle()
        {
            try
            {
                string StoreId = "1081";

                OpenTestLogDb();

                using (var gateway = new TcpClient(GatewayAddress, GatewayPort))
                {
                    using (var stream = gateway.GetStream())
                    {
                        for (var s = 0; s < 3; s++)
                        {
                            if (!useLegacy)
                            {
                                var Store = new MotStoreRecord("Add")
                                {
                                    AutoTruncate = AutoTruncate,
                                    logRecords   = true,
                                    UseAscii     = UseAscii,

                                    StoreID   = Guid.NewGuid().ToString(),
                                    StoreName = $"{DateTime.Now.ToLongTimeString()}{RandomData.String()}",
                                    Address1  = RandomData.TrimString(),
                                    Address2  = RandomData.TrimString(),
                                    City      = RandomData.TrimString(),
                                    State     = "NH",
                                    Zipcode   = $"{RandomData.Integer(0, 100000).ToString("D5")}-{RandomData.Integer(0, 100000).ToString("D4")}",
                                    DEANum    = RandomData.ShortDEA(),
                                    Phone     = RandomData.USPhoneNumber(),
                                    Fax       = RandomData.USPhoneNumber()
                                };

                                Store.Write(stream);

                                WriteTestLogRecord(new TestRecord()
                                {
                                    Id         = Guid.NewGuid().ToString(),
                                    RecordId   = new Guid(Store.StoreID).ToString(),
                                    RecordType = RecordType.Store,
                                    Name       = Store.StoreName,
                                    TimeStamp  = DateTime.UtcNow
                                });

                                StoreId = Store.StoreID;
                            }

                            for (var i = 0; i < MaxLoops; i++)
                            {
                                var Facility = new MotFacilityRecord("Add")
                                {
                                    AutoTruncate = AutoTruncate,
                                    logRecords   = true,
                                    UseAscii     = UseAscii,

                                    LocationID   = Guid.NewGuid().ToString(),
                                    StoreID      = StoreId,
                                    LocationName = RandomData.String(),
                                    Address1     = RandomData.TrimString(),
                                    Address2     = RandomData.TrimString(),
                                    City         = RandomData.TrimString(),
                                    State        = "NH",
                                    Zipcode      = $"0{RandomData.Integer(1000, 10000)}",
                                    Phone        = RandomData.USPhoneNumber(),
                                    CycleDays    = RandomData.Integer(1, 32),
                                    CycleType    = RandomData.Bit(),
                                    Comments     = RandomData.String(2048)
                                };

                                Facility.Write(stream);

                                WriteTestLogRecord(new TestRecord()
                                {
                                    Id         = Guid.NewGuid().ToString(),
                                    RecordId   = new Guid(Facility.LocationID).ToString(),
                                    RecordType = RecordType.Facility,
                                    Name       = Facility.LocationName,
                                    TimeStamp  = DateTime.UtcNow
                                });

                                var Prescriber = new MotPrescriberRecord("Add")
                                {
                                    AutoTruncate = AutoTruncate,
                                    logRecords   = true,
                                    UseAscii     = UseAscii,

                                    RxSys_DocID   = Guid.NewGuid().ToString(),
                                    LastName      = RandomData.TrimString(),
                                    FirstName     = RandomData.TrimString(),
                                    MiddleInitial = RandomData.TrimString(1),
                                    Address1      = RandomData.TrimString(),
                                    Address2      = RandomData.TrimString(),
                                    City          = RandomData.TrimString(),
                                    State         = "NH",
                                    Zipcode       = $"0{RandomData.Integer(1000, 10000)}",
                                    DEA_ID        = RandomData.ShortDEA(),
                                    TPID          = RandomData.Integer(100000).ToString(),
                                    Phone         = RandomData.USPhoneNumber(),
                                    Comments      = RandomData.String(2048),
                                    Fax           = RandomData.USPhoneNumber()
                                };

                                Prescriber.Write(stream);

                                WriteTestLogRecord(new TestRecord()
                                {
                                    Id         = Guid.NewGuid().ToString(),
                                    RecordId   = new Guid(Prescriber.PrescriberID).ToString(),
                                    RecordType = RecordType.Prescriber,
                                    Name       = $"{Prescriber.LastName}, {Prescriber.FirstName}, {Prescriber.MiddleInitial}",
                                    TimeStamp  = DateTime.UtcNow
                                });

                                for (var f = 0; f < MaxLoops; f++)
                                {
                                    var rxId   = Guid.NewGuid().ToString();
                                    var drugId = Guid.NewGuid().ToString();

                                    var Patient = new MotPatientRecord("Add")
                                    {
                                        AutoTruncate = AutoTruncate,
                                        logRecords   = true,
                                        UseAscii     = UseAscii,

                                        PatientID           = Guid.NewGuid().ToString(),
                                        LocationID          = Facility.LocationID,
                                        PrimaryPrescriberID = Prescriber.PrescriberID,
                                        LastName            = RandomData.TrimString(),
                                        FirstName           = RandomData.TrimString(),
                                        MiddleInitial       = RandomData.TrimString(1),
                                        Address1            = RandomData.TrimString(),
                                        Address2            = RandomData.TrimString(),
                                        City       = RandomData.TrimString(),
                                        State      = "NH",
                                        Zipcode    = $"0{RandomData.Integer(1000, 10000)}",
                                        Gender     = RandomData.TrimString(1),
                                        CycleDate  = RandomData.Date(DateTime.Now.Year),
                                        CycleDays  = RandomData.Integer(0, 32),
                                        CycleType  = RandomData.Bit(),
                                        AdmitDate  = RandomData.Date(),
                                        ChartOnly  = RandomData.Bit().ToString(),
                                        Phone1     = RandomData.USPhoneNumber(),
                                        Phone2     = RandomData.USPhoneNumber(),
                                        WorkPhone  = RandomData.USPhoneNumber(),
                                        DOB        = RandomData.Date(),
                                        SSN        = RandomData.SSN(),
                                        Allergies  = RandomData.String(1024),
                                        Diet       = RandomData.String(1024),
                                        DxNotes    = RandomData.String(1024),
                                        InsName    = RandomData.String(),
                                        InsPNo     = RandomData.Integer().ToString(),
                                        AltInsName = RandomData.String(),
                                        AltInsPNo  = RandomData.Integer().ToString()
                                    };

                                    Patient.Write(stream);

                                    WriteTestLogRecord(new TestRecord()
                                    {
                                        Id         = Guid.NewGuid().ToString(),
                                        RecordId   = new Guid(Patient.PatientID).ToString(),
                                        RecordType = RecordType.Patient,
                                        Name       = $"{Patient.LastName}, {Patient.FirstName}, {Patient.MiddleInitial}",
                                        TimeStamp  = DateTime.UtcNow
                                    });

                                    for (var rx = 0; rx < 8; rx++)
                                    {
                                        var Drug = new MotDrugRecord("Add")
                                        {
                                            AutoTruncate = AutoTruncate,
                                            logRecords   = true,
                                            UseAscii     = UseAscii,

                                            DrugID            = Guid.NewGuid().ToString(),
                                            DrugName          = RandomData.TrimString(),
                                            NDCNum            = RandomData.TrimString().ToUpper(),
                                            ProductCode       = RandomData.TrimString().ToUpper(),
                                            LabelCode         = RandomData.TrimString().ToUpper(),
                                            TradeName         = RandomData.TrimString(),
                                            DrugSchedule      = RandomData.Integer(2, 8),
                                            Strength          = RandomData.Double(100),
                                            Route             = RandomData.TrimString(),
                                            RxOTC             = RandomData.Bit() == 1 ? "R" : "O",
                                            VisualDescription = $"{RandomData.TrimString(3)}/{RandomData.TrimString(3)}/{RandomData.TrimString(3)}",
                                            DoseForm          = RandomData.TrimString(),
                                            DefaultIsolate    = RandomData.Bit(),
                                            ShortName         = RandomData.TrimString(),
                                            ConsultMsg        = RandomData.String()
                                        };

                                        WriteTestLogRecord(new TestRecord()
                                        {
                                            Id         = Guid.NewGuid().ToString(),
                                            RecordId   = new Guid(Drug.DrugID).ToString(),
                                            RecordType = RecordType.Drug,
                                            Name       = $"{Drug.TradeName}",
                                            TimeStamp  = DateTime.UtcNow
                                        });

                                        Drug.Write(stream);

                                        var Rx = new MotPrescriptionRecord("Add")
                                        {
                                            AutoTruncate = AutoTruncate,
                                            logRecords   = true,
                                            UseAscii     = UseAscii,

                                            PatientID        = Patient.PatientID,
                                            PrescriberID     = Prescriber.PrescriberID,
                                            DrugID           = Drug.DrugID,
                                            RxSys_RxNum      = RandomData.Integer(1, 1000000000).ToString(),
                                            RxStartDate      = RandomData.Date(DateTime.Now.Year),
                                            RxStopDate       = RandomData.Date(DateTime.Now.Year),
                                            DoseScheduleName = RandomData.TrimString().ToUpper(),
                                            QtyPerDose       = RandomData.Double(10),
                                            QtyDispensed     = RandomData.Integer(1, 120),
                                            RxType           = RandomData.Integer(1, 21),
                                            DoseTimesQtys    = RandomData.DoseTimes(RandomData.Integer(1, 25)),
                                            Isolate          = RandomData.Bit().ToString(),
                                            Refills          = RandomData.Integer(1, 100),
                                            Sig = RandomData.String()
                                        };

                                        WriteTestLogRecord(new TestRecord()
                                        {
                                            Id         = Guid.NewGuid().ToString(),
                                            RecordId   = Guid.NewGuid().ToString(),
                                            RecordType = RecordType.Prescription,
                                            Name       = $"{Rx.RxSys_RxNum}",
                                            TimeStamp  = DateTime.UtcNow
                                        });

                                        Rx.Write(stream);
                                    }
                                }
                            }
                        }
                    }
                }

                CloseTestLogDb();
            }
            catch (Exception ex)
            {
                Assert.Fail(ex.Message);
            }
            finally
            {
                StartCleaning = true;
            }
        }
        public void CleanDatabase()
        {
            if (!StartCleaning)
            {
                Thread.Yield();

                while (!StartCleaning)
                {
                    Thread.Sleep(10000);
                }
            }

            try
            {
                OpenTestLogDb();

                using (var gateway = new TcpClient(GatewayAddress, GatewayPort))
                {
                    using (var stream = gateway.GetStream())
                    {
                        // Delete Rxs
                        var RxList = GetTestLogRecords(RecordType.Prescription);
                        foreach (var rx in RxList)
                        {
                            var RxToDelete = new MotPrescriptionRecord("Delete")
                            {
                                RxSys_RxNum = rx.Name
                            };

                            RxToDelete.Write(stream);
                        }

                        // Delete Drugs
                        var DrugList = GetTestLogRecords(RecordType.Drug);
                        foreach (var drug in DrugList)
                        {
                            var DrugToDelete = new MotDrugRecord("Delete")
                            {
                                DrugID = drug.RecordId.ToString()
                            };

                            DrugToDelete.Write(stream);
                        }

                        // Delete Patients
                        var PatientList = GetTestLogRecords(RecordType.Patient);
                        foreach (var patient in PatientList)
                        {
                            var PatientToDelete = new MotPatientRecord("Delete")
                            {
                                PatientID = patient.RecordId.ToString()
                            };

                            PatientToDelete.Write(stream);
                        }

                        // Delete Facilities
                        var FacilityList = GetTestLogRecords(RecordType.Facility);
                        foreach (var facility in FacilityList)
                        {
                            var FacilityToDelete = new MotFacilityRecord("Delete")
                            {
                                LocationID = facility.RecordId.ToString()
                            };

                            FacilityToDelete.Write(stream);
                        }

                        // Delete Prescribers
                        var PrescriberList = GetTestLogRecords(RecordType.Prescriber);
                        foreach (var prescriber in PrescriberList)
                        {
                            var PrescriberToDelete = new MotPrescriberRecord("Delete")
                            {
                                PrescriberID = prescriber.RecordId.ToString()
                            };

                            PrescriberToDelete.Write(stream);
                        }

                        // Delete Stores
                        if (!useLegacy)
                        {
                            var StoreList = GetTestLogRecords(RecordType.Store);
                            foreach (var store in StoreList)
                            {
                                var StoreToDelete = new MotStoreRecord("Delete")
                                {
                                    StoreID = store.RecordId.ToString()
                                };

                                StoreToDelete.Write(stream);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Assert.Fail($"Failed to clean database: {ex.Message}");
            }
        }
Example #6
0
        // Missing DEA for Pharmacy and Prescribers
        // NDC-9 with the Manufacturer a short name
        public void Go()
        {
            try
            {
                var workingData = Data.Split('\n');
                var writeQueue  = new MotWriteQueue
                {
                    SendEof   = false, // Has to be off so we don't lose the socket.
                    DebugMode = DebugMode
                };

                string lastPatId = string.Empty;

                foreach (var line in workingData)
                {
                    switch (line.Substring(0, 1))
                    {
                    case "P":
                        var s1 = line.Substring(1);
                        var f1 = s1.Split(',');

                        var store = new MotStoreRecord("Add", AutoTruncate)
                        {
                            LocalWriteQueue = writeQueue,
                            QueueWrites     = true,

                            StoreID   = f1[0].Replace(" ", ""),
                            StoreName = f1[0],
                            Address1  = f1[1],
                            Address2  = f1[2],
                            City      = f1[3],
                            Zipcode   = f1[4],
                            Phone     = f1[5]
                        };

                        store.AddToQueue();
                        break;

                    case "F":
                        var s2      = line.Substring(1);
                        var f2      = s2.Split(',');
                        var patient = new MotPatientRecord("Add", AutoTruncate)
                        {
                            LocalWriteQueue = writeQueue,
                            QueueWrites     = true,

                            PatientID = lastPatId = f2[0],
                            LastName  = f2[1],
                            FirstName = f2[2],
                            Address1  = f2[5],
                            Address2  = f2[6],
                            City      = f2[7],
                            State     = f2[8],
                            Zipcode   = f2[9],
                            Phone1    = f2[10],

                            CycleDays = Convert.ToInt16(f2[12]),
                            Room      = f2[14]
                        };

                        patient.CycleDate = patient.TransformDate(f2[11] ?? "");
                        patient.DOB       = patient.TransformDate(f2[4] ?? "");

                        patient.AddToQueue();
                        break;

                    case "M":
                        var s3   = line.Substring(1);
                        var f3   = s3.Split(',');
                        var rx   = new MotPrescriptionRecord("Add", AutoTruncate);
                        var doc  = new MotPrescriberRecord("Add", AutoTruncate);
                        var drug = new MotDrugRecord("Add", AutoTruncate);

                        rx.LocalWriteQueue = doc.LocalWriteQueue = drug.LocalWriteQueue = writeQueue;
                        rx.QueueWrites     = doc.QueueWrites = drug.QueueWrites = true;

                        doc.PrescriberID  = f3[15]?.Substring(0, 3) + f3[16]?.Substring(0, 3);
                        doc.FirstName     = f3[15];
                        doc.LastName      = f3[16];
                        doc.MiddleInitial = f3[17];
                        doc.Address1      = f3[18];
                        doc.Address2      = f3[19];
                        doc.City          = f3[20];
                        doc.State         = f3[21];
                        doc.Zipcode       = f3[22];
                        doc.Phone         = f3[23];

                        // M8880338,DECADRON TAB .75 MG 100,TAB,,30,TAKE 1 TABLET DAILY|TOME 1 TABLET DAILY,JACK GERARD,00;00;01;00,000060063,4,,,,,,JACK,GERARD,,599 SO.FEDERAL HWY,,CHICAGO,IL,60601,773-222-9999,,

                        drug.DrugID = f3[8];

                        if (f3[8].Length > 9)
                        {
                            drug.NDCNum = f3[8];              // Unlikely, but the NDC is already 11
                        }
                        else if (f3[8].Length == 9)
                        {
                            drug.NDCNum = f3[8] + "00";       // Accepted conversion to NDC11
                        }
                        else
                        {
                            drug.NDCNum = "00000000000";
                        }

                        drug.DrugName          = f3[1];
                        drug.DoseForm          = f3[2];
                        drug.VisualDescription = f3[3];
                        drug.TradeName         = f3[12];

                        rx.PrescriptionID = f3[0];
                        rx.DrugID         = drug.DrugID;
                        rx.PrescriberID   = doc.PrescriberID;
                        rx.PatientID      = lastPatId;
                        rx.Sig            = f3[5];
                        rx.QtyDispensed   = Convert.ToDouble(f3[4] ?? "0.00");
                        rx.Refills        = Convert.ToInt32(f3[9] ?? "0");
                        rx.RxStopDate     = rx.TransformDate(f3[14] ?? ""); // Actually the Expire Date

                        // Intake Code - 00,00,00,00 = 0800[q], 1200[q], 1800[q], 2100[q]
                        var dq = f3[7].Split(';');

                        string[] time =      // Need to get the actual dose times from the RxSystem or User, for now just use defaults
                        {
                            "0800",
                            "1200",
                            "1800",
                            "2100"
                        };

                        var i = 0;

                        foreach (var d in dq)
                        {
                            if (d != "00")
                            {
                                rx.DoseTimesQtys = $"{time[i]}{Convert.ToDouble(d):00.00}";
                            }

                            i++;
                        }
                        rx.DoseScheduleName = "Dispill";

                        doc.AddToQueue();
                        drug.AddToQueue();
                        rx.AddToQueue();
                        break;
                    }
                }

                if (workingData.Length > 0)
                {
                    writeQueue.Write(GatewaySocket);
                }
            }
            catch (Exception ex)
            {
                EventLogger.Error("Failed to parse Dispill file:  {0}", ex.Message);
                throw;
            }
        }