Example #1
1
        public void Create810_4010Version()
        {
            var message = new Interchange(Convert.ToDateTime("1/4/99 15:32"), 35, false, '~', '*', '>')
                {
                    SecurityInfoQualifier = "00",
                    InterchangeSenderIdQualifier = "30",
                    InterchangeSenderId = "943274043",
                    InterchangeReceiverIdQualifier = "16",
                    InterchangeReceiverId = "0069088189999"
                };

            var fg = message.AddFunctionGroup("IN", Convert.ToDateTime("1/4/1999 15:32"), 1);
            fg.ApplicationSendersCode = "943274043TO";
            fg.ApplicationReceiversCode = "0069088189999";
            fg.ResponsibleAgencyCode = "X";
            fg.VersionIdentifierCode = "004010";

            var trans = fg.AddTransaction("810", "0001");

            var big = trans.AddSegment(new TypedSegmentBIG());
            big.BIG01_InvoiceDate = Convert.ToDateTime("10/14/1998");
            big.BIG02_InvoiceNumber = "3662";
            big.BIG07_TransactionTypeCode = "N6";

            var billTo = trans.AddLoop(new TypedLoopN1());
            billTo.N101_EntityIdentifierCodeEnum = EntityIdentifierCode.BillToParty;
            billTo.N102_Name = "The Scheduling Coordinator, Inc";

            var billToAddress = billTo.AddSegment(new TypedSegmentN3());
            billToAddress.N301_AddressInformation = "53241 Hamilton Dr";

            var billToLocale = billTo.AddSegment(new TypedSegmentN4());
            billToLocale.N401_CityName = "Palo Alto";
            billToLocale.N402_StateOrProvinceCode = "CA";
            billToLocale.N403_PostalCode = "95622";
            billToLocale.N404_CountryCode = "US";

            var remitTo = trans.AddLoop(new TypedLoopN1());
            remitTo.N101_EntityIdentifierCodeEnum = EntityIdentifierCode.PartyToReceiveCommercialInvoiceRemittance;
            remitTo.N102_Name = "Bank of America- (Mkt and GMC)";

            var remitToAddress = remitTo.AddSegment(new TypedSegmentN3());
            remitToAddress.N301_AddressInformation = "1850 Gateway Boulevard";

            var remitToLocale = remitTo.AddSegment(new TypedSegmentN4());
            remitToLocale.N401_CityName = "Concord";
            remitToLocale.N402_StateOrProvinceCode = "CA";
            remitToLocale.N403_PostalCode = "94520";
            remitToLocale.N404_CountryCode = "US";

            var remitToRef1 = remitTo.AddSegment(new TypedSegmentREF());
            remitToRef1.REF01_ReferenceIdQualifier = "11";
            remitToRef1.REF02_ReferenceId = "1233626208";

            var remitToRef2 = remitTo.AddSegment(new TypedSegmentREF());
            remitToRef2.REF01_ReferenceIdQualifier = "01";
            remitToRef2.REF02_ReferenceId = "026009593";

            var itd = trans.AddSegment(new TypedSegmentITD());
            itd.ITD01_TermsTypeCode = "03";
            itd.ITD06_TermsNetDueDate = Convert.ToDateTime("10/20/1998");

            var it1 = trans.AddLoop(new TypedLoopIT1());
            it1.IT101_AssignedIdentification = "1";
            it1.IT102_QuantityInvoiced = 1;
            it1.IT103_UnitOrBasisForMeasurementCode = UnitOrBasisOfMeasurementCode.Each;
            it1.IT104_UnitPrice = 2896035.3m;

            var pid = it1.AddLoop(new TypedLoopPID());
            pid.PID01_ItemDescriptionType = "X";
            pid.PID05_Description = "RMR Scheduling Coordinator - Estimated RMR";

            var tds = trans.AddSegment(new TypedSegmentTDS());
            tds.TDS01_AmountN2 = 289603530;

            var ctt = trans.AddSegment(new TypedSegmentCTT());
            ctt.CTT01_NumberOfLineItems = 1;

            var x12 = message.SerializeToX12(false);
            Console.WriteLine(x12);
        }
Example #2
0
        static void Main(string[] args)
        {
            string inputFilename = args[0];
            string outputFilename = args[1];
            string isaControlNumber = args.Length > 2 ? args[2] : "999";
            string gsControlNumber = args.Length > 3 ? args[3] : "99";

            var service = new X12AcknowledgmentService();

            using (FileStream fs = new FileStream(inputFilename, FileMode.Open, FileAccess.Read))
            {
                using (X12StreamReader reader = new X12StreamReader(fs, Encoding.UTF8))
                {
                    var firstTrans = reader.ReadNextTransaction();
                    if (reader.LastTransactionCode == "837")
                    {
                        if (reader.TransactionContainsSegment(firstTrans.Transactions[0], "SV2"))
                            service = new InstitutionalClaimAcknowledgmentService();
                        if (reader.TransactionContainsSegment(firstTrans.Transactions[0], "SV1"))
                            service = new X12AcknowledgmentService(new ProfessionalClaimSpecificationFinder());
                    }
                }
            }

            using (FileStream fs = new FileStream(inputFilename, FileMode.Open, FileAccess.Read))
            {
                // Create aknowledgements and identify errors
                var responses = service.AcknowledgeTransactions(fs);

                // Change any acknowledgment codes here to reject transactions with errors
                // CUSTOM BUSINESS LOGIC HERE

                // Transform to outbound interchange for serialization
                var interchange = new Interchange(DateTime.Now, int.Parse(isaControlNumber), true);
                interchange.AuthorInfoQualifier = ConfigurationManager.AppSettings["AuthorInfoQualifier"];
                interchange.AuthorInfo = ConfigurationManager.AppSettings["AuthorInfo"];
                interchange.SecurityInfoQualifier = ConfigurationManager.AppSettings["SecurityInfoQualifier"];
                interchange.SecurityInfo = ConfigurationManager.AppSettings["SecurityInfo"];
                interchange.InterchangeSenderIdQualifier = ConfigurationManager.AppSettings["InterchangeSenderIdQualifier"];
                interchange.InterchangeSenderId = ConfigurationManager.AppSettings["InterchangeSenderId"];
                interchange.InterchangeReceiverIdQualifier = responses.First().SenderIdQualifier;
                interchange.InterchangeReceiverId = responses.First().SenderId;
                interchange.SetElement(12, "00501");

                var group = interchange.AddFunctionGroup("FA", DateTime.Now, int.Parse(gsControlNumber));
                group.ApplicationSendersCode = ConfigurationManager.AppSettings["InterchangeSenderId"];
                group.VersionIdentifierCode = "005010X231A1";

                group.Add999Transaction(responses);

                // This is a demonstration example only, change true to false to create continous x12 without line feeds.
                File.WriteAllText(outputFilename, interchange.SerializeToX12(true));
            }
        }
        public void Acknowledge837ITest()
        {
            var service = new InstitutionalClaimAcknowledgmentService();
            var responses = service.AcknowledgeTransactions(GetEdi("837I_4010_Batch1.txt"));

            Assert.AreEqual(1, responses.Count);
            var response = responses.First();
            Assert.AreEqual("612200041", response.GroupControlNumber);
            Assert.AreEqual(54, response.TransactionSetResponses.Count);

            var interchange = new Interchange(DateTime.Now, 1, true);
            var group = interchange.AddFunctionGroup("FA", DateTime.Now, 1);
            group.VersionIdentifierCode = "005010X231A1";
            group.Add999Transaction(responses);

            Trace.WriteLine(interchange.SerializeToX12(true));
        }
        public void CreatePurchaseOrder850()
        {
            DateTime purcaseOrderDate = new DateTime(2010, 8, 17, 08, 50, 0);
            Interchange interchange = new Interchange(purcaseOrderDate, 245, true)
            {
                InterchangeSenderIdQualifier = "01",
                InterchangeSenderId = "828513080",
                InterchangeReceiverIdQualifier = "01",
                InterchangeReceiverId = "001903202U",
                InterchangeDate = purcaseOrderDate,
            };

            interchange.SetElement(14, "0"); //No Aknowlegement is 0

            FunctionGroup group = interchange.AddFunctionGroup("PO", purcaseOrderDate, 1, "005010X222");
            group.ApplicationSendersCode = "828513080";
            group.ApplicationReceiversCode = "001903202U";
            group.Date = purcaseOrderDate;
            group.ControlNumber = 245;

            Transaction transaction = group.AddTransaction("850", "0001");

            Segment bhtSegment = transaction.AddSegment("BEG");
            bhtSegment.SetElement(1, "05");
            bhtSegment.SetElement(2, "SA");
            bhtSegment.SetElement(3, "S41000439");
            bhtSegment.SetElement(5, "20100810");

            bhtSegment = transaction.AddSegment("CUR");
            bhtSegment.SetElement(1, "BY");
            bhtSegment.SetElement(2, "USD");

            bhtSegment = transaction.AddSegment("PER");
            bhtSegment.SetElement(1, "IC");
            bhtSegment.SetElement(2, "Doe,Jane");
            bhtSegment.SetElement(8, "Doe,Jane");

            var x12 = interchange.SerializeToX12(true);
            System.Diagnostics.Trace.Write(x12);
        }
        public void Create837_5010Version()
        {
            var message = new Interchange(Convert.ToDateTime("01/01/03"), 000905, false)
                              {
                                  InterchangeSenderIdQualifier = "ZZ",
                                  InterchangeSenderId = "SUBMITTERS.ID",
                                  InterchangeReceiverIdQualifier = "ZZ",
                                  InterchangeReceiverId = "RECEIVERS.ID",
                                  SecurityInfo = "SECRET",
                                  SecurityInfoQualifier = "01",
                              };
            message.SetElement(12, "00501");
            message.SetElement(10, "1253");
            message.SetElement(11, "^");

            var group = message.AddFunctionGroup("HC", DateTime.Now, 1, "005010X222");
            group.ApplicationSendersCode = "SENDER CODE";
            group.ApplicationReceiversCode = "RECEIVER CODE";
            group.Date = Convert.ToDateTime("12/31/1999");
            group.ControlNumber = 1;
            group.SetElement(5, "0802");


            var transaction = group.AddTransaction("837", "0021");
            transaction.SetElement(2, "0021");
            transaction.SetElement(3, "005010X222");

            var bhtSegment = transaction.AddSegment("BHT");
            bhtSegment.SetElement(1, "0019");
            bhtSegment.SetElement(2, "00");
            bhtSegment.SetElement(3, "244579");
            bhtSegment.SetElement(4, "20061015");
            bhtSegment.SetElement(5, "1023");
            bhtSegment.SetElement(6, "CH");

            var submitterLoop = transaction.AddLoop(new TypedLoopNM1("41")); //submitter identifier code
            submitterLoop.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity;
            submitterLoop.NM103_NameLastOrOrganizationName = "PREMIER BILLING SERVICE";
            submitterLoop.NM104_NameFirst = "";
            submitterLoop.NM109_IdCode = "TGJ23";
            submitterLoop.NM108_IdCodeQualifier = "46";

            var perSegment = submitterLoop.AddSegment(new TypedSegmentPER());
            perSegment.PER01_ContactFunctionCode = "IC"; //information contact function code
            perSegment.PER02_Name = "JERRY";
            perSegment.PER03_CommunicationNumberQualifier = CommunicationNumberQualifer.Telephone;
            perSegment.PER04_CommunicationNumber = "3055552222";
            perSegment.PER05_CommunicationNumberQualifier = CommunicationNumberQualifer.TelephoneExtension;
            perSegment.PER06_CommunicationNumber = "231";

            var submitterLoop2 = transaction.AddLoop(new TypedLoopNM1("40"));
            submitterLoop2.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity;
            submitterLoop2.NM103_NameLastOrOrganizationName = "KEY INSURANCE COMPANY";
            submitterLoop2.NM104_NameFirst = "";
            submitterLoop2.NM109_IdCode = "66783JJT";
            submitterLoop2.NM108_IdCodeQualifier = "46";

            var provider2000AHLoop = transaction.AddHLoop("1", "20", true); //*********HL 1 ******
            var prvSegment = provider2000AHLoop.AddSegment(new TypedSegmentPRV()); //Specialty Segment
            prvSegment.PRV01_ProviderCode = "BI";
            prvSegment.PRV02_ReferenceIdQualifier = "PXC";
            prvSegment.PRV03_ProviderTaxonomyCode = "203BF0100Y";

            var provider2010ACLoop = provider2000AHLoop.AddLoop(new TypedLoopNM1("85"));
            provider2010ACLoop.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity;
            provider2010ACLoop.NM103_NameLastOrOrganizationName = "BEN KILDARE SERVICE";
            provider2010ACLoop.NM109_IdCode = "9876543210";
            provider2010ACLoop.NM108_IdCodeQualifier = "XX";

            var provider2010AC_N3Segment = provider2010ACLoop.AddSegment(new TypedSegmentN3());
            provider2010AC_N3Segment.N301_AddressInformation = "234 SEAWAY ST";

            var provider2010AC_N4Segment = provider2010ACLoop.AddSegment(new TypedSegmentN4());
            provider2010AC_N4Segment.N401_CityName = "MIAMI";
            provider2010AC_N4Segment.N402_StateOrProvinceCode = "FL";
            provider2010AC_N4Segment.N403_PostalCode = "33111";

            var provider2010AC_REFSegment = provider2010ACLoop.AddSegment(new TypedSegmentREF());
            provider2010AC_REFSegment.REF01_ReferenceIdQualifier = "EI";
            provider2010AC_REFSegment.REF02_ReferenceId = "587654321";

            var provider2010ACLoop2 = provider2000AHLoop.AddLoop(new TypedLoopNM1("87"));
            provider2010ACLoop2.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity;

            var provider2010AC_N3Segment2 = provider2010ACLoop2.AddSegment(new TypedSegmentN3());
            provider2010AC_N3Segment2.N301_AddressInformation = "2345 OCEAN BLVD";

            var provider2010AC_N4Segment2 = provider2010ACLoop2.AddSegment(new TypedSegmentN4());
            provider2010AC_N4Segment2.N401_CityName = "MAIMI";  // MISSPELLED IN COMPARETO DOC
            provider2010AC_N4Segment2.N402_StateOrProvinceCode = "FL";
            provider2010AC_N4Segment2.N403_PostalCode = "33111";

            var subscriber2000BHLoop = provider2000AHLoop.AddHLoop("2", "22", true);  // **** HL 2  ******

            var segmentSBR = subscriber2000BHLoop.AddSegment(new TypedSegmentSBR());
            segmentSBR.SBR01_PayerResponsibilitySequenceNumberCode = "P";
            segmentSBR.SBR03_PolicyOrGroupNumber = "2222-SJ";
            segmentSBR.SBR09_ClaimFilingIndicatorCode = "CI";

            var subscriberName2010BALoop = subscriber2000BHLoop.AddLoop(new TypedLoopNM1("IL"));
            subscriberName2010BALoop.NM102_EntityTypeQualifier = EntityTypeQualifier.Person;
            subscriberName2010BALoop.NM104_NameFirst = "JANE";
            subscriberName2010BALoop.NM103_NameLastOrOrganizationName = "SMITH";
            subscriberName2010BALoop.NM109_IdCode = "JS00111223333";
            subscriberName2010BALoop.NM108_IdCodeQualifier = "MI";

            var subscriber_DMGSegment = subscriberName2010BALoop.AddSegment(new TypedSegmentDMG());
            subscriber_DMGSegment.DMG01_DateTimePeriodFormatQualifier = "D8";
            subscriber_DMGSegment.DMG02_DateOfBirth = DateTime.Parse("5/1/1943");
            subscriber_DMGSegment.DMG03_Gender = Gender.Female;

            var subscriberName2010BALoop2 = subscriber2000BHLoop.AddLoop(new TypedLoopNM1("PR"));
            subscriberName2010BALoop2.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity;
            subscriberName2010BALoop2.NM103_NameLastOrOrganizationName = "KEY INSURANCE COMPANY";
            subscriberName2010BALoop2.NM108_IdCodeQualifier = "PI";
            subscriberName2010BALoop2.NM109_IdCode = "999996666";

            var refSegment2 = subscriberName2010BALoop2.AddSegment(new TypedSegmentREF());
            refSegment2.REF01_ReferenceIdQualifier = "G2";
            refSegment2.REF02_ReferenceId = "KA6663";

            var HL3Loop = subscriber2000BHLoop.AddHLoop("3", "23", false);   // **** HL 3  ******

            var HL3PATSegment = HL3Loop.AddSegment(new TypedSegmentPAT());
            HL3PATSegment.PAT01_IndividualRelationshipCode = "19";

            var HL3NM1Segment = HL3Loop.AddLoop(new TypedLoopNM1("QC"));
            HL3NM1Segment.NM102_EntityTypeQualifier = EntityTypeQualifier.Person;
            HL3NM1Segment.NM104_NameFirst = "TED";
            HL3NM1Segment.NM103_NameLastOrOrganizationName = "SMITH";


            // add N3 and N4 segments under the above NM1 loop

            var HL3NM1_N3_Segment = HL3NM1Segment.AddSegment(new TypedSegmentN3());
            HL3NM1_N3_Segment.N301_AddressInformation = "236 N MAIN ST";

            var HL3NM1_N4_Segment = HL3NM1Segment.AddSegment(new TypedSegmentN4());
            HL3NM1_N4_Segment.N401_CityName = "MIAMI";
            HL3NM1_N4_Segment.N402_StateOrProvinceCode = "FL";
            HL3NM1_N4_Segment.N403_PostalCode = "33413";

            var HL3NM1_DMG_Segment = HL3NM1Segment.AddSegment(new TypedSegmentDMG());
            HL3NM1_DMG_Segment.DMG01_DateTimePeriodFormatQualifier = "D8";
            HL3NM1_DMG_Segment.DMG02_DateOfBirth = Convert.ToDateTime("5/1/1973");
            HL3NM1_DMG_Segment.DMG03_Gender = Gender.Male;

            var claim2300Loop = HL3Loop.AddLoop(new TypedLoopCLM());
            claim2300Loop.CLM01_PatientControlNumber = "26463774";
            claim2300Loop.CLM02_TotalClaimChargeAmount = Convert.ToDecimal(100);
            claim2300Loop.CLM05._1_FacilityCodeValue = "11";
            claim2300Loop.CLM05._2_FacilityCodeQualifier = "B";
            claim2300Loop.CLM05._3_ClaimFrequencyTypeCode = "1";
            claim2300Loop.CLM06_ProviderOrSupplierSignatureIndicator = true;
            claim2300Loop.CLM07_ProviderAcceptAssignmentCode = "A";
            claim2300Loop.CLM08_BenefitsAssignmentCerficationIndicator = "Y";
            claim2300Loop.CLM09_ReleaseOfInformationCode = "I";

            var refSegment = claim2300Loop.AddSegment(new TypedSegmentREF());
            refSegment.REF01_ReferenceIdQualifier = "D9";
            refSegment.REF02_ReferenceId = "17312345600006351";

            var hiSegment = claim2300Loop.AddSegment(new TypedSegmentHI());
            hiSegment.HI01_HealthCareCodeInformation = "BK:0340";
            hiSegment.HI02_HealthCareCodeInformation = "BF:V7389";

            var lxLoop = claim2300Loop.AddLoop(new TypedLoopLX("LX"));
            lxLoop.LX01_AssignedNumber = "1";

            var sv1Segment = lxLoop.AddSegment(new TypedSegmentSV1());
            sv1Segment.SV101_CompositeMedicalProcedure = "HC:99213";
            sv1Segment.SV102_MonetaryAmount = "40";
            sv1Segment.SV103_UnitBasisMeasCode = "UN";
            sv1Segment.SV104_Quantity = "1";
            sv1Segment.SV107_CompDiagCodePoint = "1";

            var dtpSegment = lxLoop.AddSegment(new TypedSegmentDTP());
            dtpSegment.DTP01_DateTimeQualifier  = DTPQualifier.Service;
            dtpSegment.DTP02_DateTimePeriodFormatQualifier = DTPFormatQualifier.CCYYMMDD;
            DateTime theDate = DateTime.ParseExact("20061003", "yyyyMMdd", null);
            dtpSegment.DTP03_Date = new DateTimePeriod(theDate);

            var lxLoop2 = claim2300Loop.AddLoop(new TypedLoopLX("LX"));
            lxLoop2.LX01_AssignedNumber = "2";

            var sv1Segment2 = lxLoop2.AddSegment(new TypedSegmentSV1());
            sv1Segment2.SV101_CompositeMedicalProcedure = "HC:87070";
            sv1Segment2.SV102_MonetaryAmount = "15";
            sv1Segment2.SV103_UnitBasisMeasCode = "UN";
            sv1Segment2.SV104_Quantity = "1";
            sv1Segment2.SV107_CompDiagCodePoint = "1";

            var dtpSegment2 = lxLoop2.AddSegment(new TypedSegmentDTP());
            dtpSegment2.DTP01_DateTimeQualifier = DTPQualifier.Service;
            dtpSegment2.DTP02_DateTimePeriodFormatQualifier = DTPFormatQualifier.CCYYMMDD;
            DateTime theDate2 = DateTime.ParseExact("20061003", "yyyyMMdd", null);
            dtpSegment2.DTP03_Date = new DateTimePeriod(theDate2);

            var lxLoop3 = claim2300Loop.AddLoop(new TypedLoopLX("LX"));
            lxLoop3.LX01_AssignedNumber = "3";

            var sv1Segment3 = lxLoop3.AddSegment(new TypedSegmentSV1());
            sv1Segment3.SV101_CompositeMedicalProcedure = "HC:99214";
            sv1Segment3.SV102_MonetaryAmount = "35";
            sv1Segment3.SV103_UnitBasisMeasCode = "UN";
            sv1Segment3.SV104_Quantity = "1";
            sv1Segment3.SV107_CompDiagCodePoint = "2";

            var dtpSegment3 = lxLoop3.AddSegment(new TypedSegmentDTP());
            dtpSegment3.DTP01_DateTimeQualifier = DTPQualifier.Service;
            dtpSegment3.DTP02_DateTimePeriodFormatQualifier = DTPFormatQualifier.CCYYMMDD;
            DateTime theDate3 = DateTime.ParseExact("20061010", "yyyyMMdd", null);
            dtpSegment3.DTP03_Date = new DateTimePeriod(theDate3);

            var lxLoop4 = claim2300Loop.AddLoop(new TypedLoopLX("LX"));
            lxLoop4.LX01_AssignedNumber = "4";

            var sv1Segment4 = lxLoop4.AddSegment(new TypedSegmentSV1());
            sv1Segment4.SV101_CompositeMedicalProcedure = "HC:86663";
            sv1Segment4.SV102_MonetaryAmount = "10";
            sv1Segment4.SV103_UnitBasisMeasCode = "UN";
            sv1Segment4.SV104_Quantity = "1";
            sv1Segment4.SV107_CompDiagCodePoint = "2";

            var dtpSegment4 = lxLoop4.AddSegment(new TypedSegmentDTP());
            dtpSegment4.DTP01_DateTimeQualifier = DTPQualifier.Service;
            dtpSegment4.DTP02_DateTimePeriodFormatQualifier = DTPFormatQualifier.CCYYMMDD_CCYYMMDD;
            DateTime theDate4 = DateTime.ParseExact("20061010", "yyyyMMdd", null);
            dtpSegment4.DTP03_Date = new DateTimePeriod(theDate4, DateTime.ParseExact("20061025", "yyyyMMdd", null));
            var x12 = message.SerializeToX12(true);
            Assert.AreEqual(new StreamReader(Extensions.GetEdi("INS._837P._5010.Example1_HealthInsurance.txt")).ReadToEnd(), message.SerializeToX12(true));

            //Trace.Write(new StreamReader(Extensions.GetEdi("INS._837P._5010.Example1_HealthInsurance.txt")).ReadToEnd());
            //Trace.Write(x12);
        }
Example #6
0
        /// <summary>
        /// Generates the health care claim837 professional.
        /// </summary>
        /// <returns>A _healthCareClaim837Professional message.</returns>
        public virtual HealthCareClaim837Professional GenerateHealthCareClaim837Professional( )
        {
            var healthCareClaim837ProfessionalFactory = IoC.CurrentContainer.Resolve<IHealthCareClaim837ProfessionalFactory> ();

            var currenDateTime = DateTime.Now;
            var autoIncrementedHierarchicalIDNumber = 1; // NOTE: The first HL01 within each ST-SE envelope must begin with "1".

            var interchangeCopntrolNumber = GetInterchangeControlNumber ( Key );

            // Interchange.
            var message = new Interchange (
                currenDateTime,
                interchangeCopntrolNumber,
                false, // TODO: Use web.config to set InterchangeUsageIndicator.
                PayorType.HealthCareClaim837Setup.X12Delimiters.SegmentDelimiter,
                PayorType.HealthCareClaim837Setup.X12Delimiters.ElementDelimiter,
                PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter )
                {
                    InterchangeSenderIdQualifier = InterchangeIDQualifier.MutuallyDefined,
                    InterchangeSenderId = PayorType.HealthCareClaim837Setup.InterchangeSenderNumber,
                    InterchangeReceiverIdQualifier = InterchangeIDQualifier.MutuallyDefined,
                    InterchangeReceiverId = PayorType.HealthCareClaim837Setup.InterchangeReceiverNumber,
                };

            message.SetElement ( 11, PayorType.HealthCareClaim837Setup.X12Delimiters.RepetitionDelimiter.ToString ( CultureInfo.InvariantCulture ) );
            message.SetElement ( 12, InterchangeVersionControlNumber.ApprovedForPublicationByASCX12ProceduresReviewBoardThroughOctober2003 );
            message.SetElement ( 14, AcknowledgmentRequested.InterchangeAcknowledgmentRequested );

            // Functional group.
            var group = message.AddFunctionGroup ( FunctionalIdentifierCode.HealthCareClaim, currenDateTime, interchangeCopntrolNumber, ImplementationConventionReference.Version5010);

            group.ApplicationSendersCode = PayorType.HealthCareClaim837Setup.InterchangeSenderNumber;
            group.ApplicationReceiversCode = PayorType.HealthCareClaim837Setup.InterchangeReceiverNumber;
            group.ResponsibleAgencyCode = ResponsibleAgencyCode.AccreditedStandardsCommitteeX12;

            var interchangeControlNumberString = interchangeCopntrolNumber.ToString ( CultureInfo.InvariantCulture );
            var transactionControlIdentifier = interchangeControlNumberString.Length < 4
                                                   ? interchangeControlNumberString.PadLeft ( 4, '0' )
                                                   : interchangeControlNumberString;

            // Transaction set.
            var transaction = group.AddTransaction ( TransactionSetIdentifierCode.HealthCareClaim, transactionControlIdentifier );
            transaction.SetElement ( 3, ImplementationConventionReference.Version5010 );

            // Beginning of hierarchical transaction.
            var bhtSegment = transaction.AddSegment ( BeginningOfHierarchicalTransaction );
            bhtSegment.SetElement ( 1, HierarchicalStructureCode.InformationSourceOrSubscriberOrDependent );
            bhtSegment.SetElement ( 2, TransactionSetPurposeCode.Original );
            bhtSegment.SetElement ( 3, BatchControlNumber.ToString ( CultureInfo.InvariantCulture ) );
            bhtSegment.SetElement ( 4, currenDateTime.Date.ToString ( "yyyyMMdd" ) );
            bhtSegment.SetElement ( 5, currenDateTime.ToString ( "HHmm" ) );
            bhtSegment.SetElement ( 6, TransactionTypeCode.Chargeable );

            // Submitter name.
            var submitterLoop = transaction.AddLoop ( new TypedLoopNM1 ( EntityIdentifierCode.Submitter ) );
            submitterLoop.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity;
            submitterLoop.NM103_NameLastOrOrganizationName = PayorType.BillingOffice.Agency.AgencyProfile.AgencyName.LegalName;
            submitterLoop.NM108_IdCodeQualifier = IdentificationCodeQualifier.ElectronicTransmitterIdentificationNumber;
            submitterLoop.NM109_IdCode = PayorType.BillingOffice.ElectronicTransmitterIdentificationNumber;

            // Submitter EDI contact information.
            var perSegment = submitterLoop.AddSegment ( new TypedSegmentPER () );
            perSegment.PER01_ContactFunctionCode = ContactFunctionCode.InfromationContact;

            // NOTE: PER02_Name is situational. But, as we have provided a nonperson entity for submitter, this field is required.
            perSegment.PER02_Name = PayorType.BillingOffice.AdministratorStaff.StaffProfile.StaffName.Complete;

            perSegment.PER03_CommunicationNumberQualifier = CommunicationNumberQualifer.Telephone;

            var staffPhone =
                PayorType.BillingOffice.AdministratorStaff.PhoneNumbers.FirstOrDefault (
                    phoneNumber => phoneNumber.StaffPhoneType.WellKnownName == StaffPhoneType.Work );
            if ( staffPhone == null || staffPhone.Phone == null )
            {
                throw new ArgumentException (
                    string.Format (
                        "Unable to find '{0}' staff work phone number",
                        PayorType.BillingOffice.AdministratorStaff.StaffProfile.StaffName.Complete ) );
            }

            perSegment.PER04_CommunicationNumber = staffPhone.Phone.PhoneNumber.RemoveNonAlphanumericChar();
            if ( !string.IsNullOrEmpty ( staffPhone.Phone.PhoneExtensionNumber ) )
            {
                perSegment.PER05_CommunicationNumberQualifier = CommunicationNumberQualifer.TelephoneExtension;
                perSegment.PER06_CommunicationNumber = staffPhone.Phone.PhoneExtensionNumber;
            }

            // Receiver name.
            var receiverLoop = transaction.AddLoop ( new TypedLoopNM1 ( EntityIdentifierCode.Receiver ) );
            receiverLoop.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity;
            receiverLoop.NM103_NameLastOrOrganizationName = PayorType.Name;
            receiverLoop.NM108_IdCodeQualifier = IdentificationCodeQualifier.ElectronicTransmitterIdentificationNumber;
            receiverLoop.NM109_IdCode = PayorType.SubmitterIdentifier;

            // Billing provider hierarchical level. ***** HL1 *****
            var provider2000AHierachicalLoop = transaction.AddHLoop (
                autoIncrementedHierarchicalIDNumber.ToString ( CultureInfo.InvariantCulture ),
                HierarchicalLevelCode.InformationSource,
                HierarchicalChildCode.AdditionalSubordinateHLDataSegmentInThisHierarchicalStructure );

            // Billing provide specialty information.
            var prvSegment = provider2000AHierachicalLoop.AddSegment ( new TypedSegmentPRV () );
            prvSegment.PRV01_ProviderCode = ProviderCode.Billing;
            prvSegment.PRV02_ReferenceIdQualifier = ReferenceIdentificationQualifier.HealthCareProviderTaxonomyCode;
            prvSegment.PRV03_ProviderTaxonomyCode = ProviderTaxonomyCode;

            // Billing provider Name
            var provider2010AaLoop = provider2000AHierachicalLoop.AddLoop ( new TypedLoopNM1 ( EntityIdentifierCode.BillingProvider ) );
            provider2010AaLoop.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity;
            provider2010AaLoop.NM103_NameLastOrOrganizationName = PayorType.BillingOffice.Agency.AgencyProfile.AgencyName.LegalName;
            provider2010AaLoop.NM108_IdCodeQualifier = IdentificationCodeQualifier.CentersForMedicareAndMedicaidServicesNationalProviderIdentifier;

            var agencyNpi =
                PayorType.BillingOffice.Agency.AgencyIdentifiers.FirstOrDefault (
                    identifier => identifier.AgencyIdentifierType.WellKnownName == AgencyIdentifierType.Npi );
            if ( agencyNpi == null || agencyNpi.IdentifierNumber == null )
            {
                throw new ArgumentException (
                    string.Format (
                        "Unable to find '{0}' agency NPI identifier number", PayorType.BillingOffice.Agency.AgencyProfile.AgencyName.LegalName ) );
            }

            provider2010AaLoop.NM109_IdCode = agencyNpi.IdentifierNumber;

            var agencyBillingAddressAndPhone =
                PayorType.BillingOffice.Agency.AddressesAndPhones.FirstOrDefault (
                    address => address.AgencyAddress.AgencyAddressType.WellKnownName == AgencyAddressType.Billing );
            if ( agencyBillingAddressAndPhone == null || agencyBillingAddressAndPhone.AgencyAddress == null )
            {
                throw new ArgumentException (
                    string.Format (
                        "Unable to find '{0}' agency Billing address", PayorType.BillingOffice.Agency.AgencyProfile.AgencyName.LegalName ) );
            }

            // Billing provider address.
            var provider2010AaN3Segment = provider2010AaLoop.AddSegment ( new TypedSegmentN3 () );
            provider2010AaN3Segment.N301_AddressInformation = agencyBillingAddressAndPhone.AgencyAddress.Address.FirstStreetAddress
                                                              +
                                                              ( string.IsNullOrWhiteSpace (
                                                                  agencyBillingAddressAndPhone.AgencyAddress.Address.SecondStreetAddress )
                                                                    ? string.Empty
                                                                    : " "
                                                                      + agencyBillingAddressAndPhone.AgencyAddress.Address.SecondStreetAddress );

            // Billing provider City,State,Zip code
            var provider2010AaN4Segment = provider2010AaLoop.AddSegment ( new TypedSegmentN4 () );
            provider2010AaN4Segment.N401_CityName = agencyBillingAddressAndPhone.AgencyAddress.Address.CityName;
            provider2010AaN4Segment.N402_StateOrProvinceCode = agencyBillingAddressAndPhone.AgencyAddress.Address.StateProvince.ShortName;
            provider2010AaN4Segment.N403_PostalCode = agencyBillingAddressAndPhone.AgencyAddress.Address.PostalCode.Code;

            var agencyFederalTaxID =
                PayorType.BillingOffice.Agency.AgencyIdentifiers.FirstOrDefault (
                    identifier => identifier.AgencyIdentifierType.WellKnownName == AgencyIdentifierType.FederalTaxId );
            if ( agencyFederalTaxID == null || agencyFederalTaxID.IdentifierNumber == null )
            {
                throw new ArgumentException (
                    string.Format (
                        "Unable to find '{0}' agency Federal Tax ID", PayorType.BillingOffice.Agency.AgencyProfile.AgencyName.LegalName ) );
            }

            // Billing provider - tax identification
            var provider2010AaRefSegment = provider2010AaLoop.AddSegment ( new TypedSegmentREF () );
            provider2010AaRefSegment.REF01_ReferenceIdQualifier = ReferenceIdentificationQualifier.EmployersIdentificationNumber;
            provider2010AaRefSegment.REF02_ReferenceId = agencyFederalTaxID.IdentifierNumber;

            //If it is the same as Billing provider, no need.
            /*
            var provider2010ABLoop = provider2000AHierachicalLoop.AddLoop ( new TypedLoopNM1 ( EntityIdentifierCode.PayToProvider ) );
            provider2010ABLoop.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity;

            // NOTE: Pay-To address is same as Billing provider address ie., same N3 and N4 segments.
            provider2010ABLoop.AddSegment ( provider2010AAN3Segment );
            provider2010ABLoop.AddSegment ( provider2010AAN4Segment );
             */

            var claimDictionary = GroupClaimsByPrimaryPayorCoverage ( Claims );

            //TODO: needs confirm if this loop pulling the correct data *** need bill every insurance or just the primary???
            foreach (var keyValuePair in claimDictionary)
            {
                var payorCoverage = keyValuePair.Key;
                var claimList = keyValuePair.Value;

                var isPatientTheSubscriber =
                    payorCoverage.PayorSubscriber.PayorSubscriberRelationshipType.WellKnownName.Equals ( PayorSubscriberRelationshipType.Self );

                autoIncrementedHierarchicalIDNumber++;

                // Subscriber hierarchical level. **** HL 2  ******
                var subscriber2000BHierarchicalLoop =
                    provider2000AHierachicalLoop.AddHLoop (
                        autoIncrementedHierarchicalIDNumber.ToString ( CultureInfo.InvariantCulture ),
                        HierarchicalLevelCode.Subscriber,
                        isPatientTheSubscriber
                            ? HierarchicalChildCode.NoSubordinateHLSegmentInThisHierarchicalStructure
                            : HierarchicalChildCode.AdditionalSubordinateHLDataSegmentInThisHierarchicalStructure );

                // Subscriber information.
                var sbrSegment = subscriber2000BHierarchicalLoop.AddSegment ( new TypedSegmentSBR () );

                sbrSegment.SBR01_PayerResponsibilitySequenceNumberCode = payorCoverage.PayorCoverageType.ShortName;

                if ( isPatientTheSubscriber )
                {
                    sbrSegment.SBR02_IndividualRelationshipCode = payorCoverage.PayorSubscriber.PayorSubscriberRelationshipType.ShortName;
                }

                // Subscriber Name
                var subscriberName2010BaLoop =
                    subscriber2000BHierarchicalLoop.AddLoop ( new TypedLoopNM1 ( EntityIdentifierCode.InsuredOrSubscriber ) );
                subscriberName2010BaLoop.NM102_EntityTypeQualifier = EntityTypeQualifier.Person;
                subscriberName2010BaLoop.NM104_NameFirst = payorCoverage.PayorSubscriber.Name.First;
                subscriberName2010BaLoop.NM103_NameLastOrOrganizationName = payorCoverage.PayorSubscriber.Name.Last;
                subscriberName2010BaLoop.NM108_IdCodeQualifier = IdentificationCodeQualifier.MemberIdentificationNumber;
                subscriberName2010BaLoop.NM109_IdCode = payorCoverage.MemberNumber;

                if ( isPatientTheSubscriber )
                {
                    // Subscriber address
                    var provider2010BaN3Segment = subscriberName2010BaLoop.AddSegment ( new TypedSegmentN3 () );
                    provider2010BaN3Segment.N301_AddressInformation = payorCoverage.PayorSubscriber.Address.FirstStreetAddress +
                                                                      ( string.IsNullOrWhiteSpace (
                                                                          payorCoverage.PayorSubscriber.Address.SecondStreetAddress )
                                                                            ? string.Empty
                                                                            : " "
                                                                              + payorCoverage.PayorSubscriber.Address.SecondStreetAddress );

                    // Subscriber city,state,postal code.
                    var provider2010BaN4Segment = subscriberName2010BaLoop.AddSegment ( new TypedSegmentN4 () );
                    provider2010BaN4Segment.N401_CityName = payorCoverage.PayorSubscriber.Address.CityName;
                    provider2010BaN4Segment.N402_StateOrProvinceCode = payorCoverage.PayorSubscriber.Address.StateProvince.ShortName;
                    provider2010BaN4Segment.N403_PostalCode = payorCoverage.PayorSubscriber.Address.PostalCode.Code;

                    // Demographic information
                    var subscriberDmgSegment = subscriberName2010BaLoop.AddSegment ( new TypedSegmentDMG () );
                    subscriberDmgSegment.DMG01_DateTimePeriodFormatQualifier = DateTimePeriodFormatQualifier.DateExpressedAsCCYYMMDD;
                    subscriberDmgSegment.DMG02_DateOfBirth = payorCoverage.PayorSubscriber.BirthDate;
                    subscriberDmgSegment.DMG03_Gender =
                        ConvertToGenderCodeFromAdministrativeGender ( payorCoverage.PayorSubscriber.AdministrativeGender );
                }

                // Loop 2010BB - Payer Name.
                var subscriberName2010BbLoop = subscriber2000BHierarchicalLoop.AddLoop ( new TypedLoopNM1 ( EntityIdentifierCode.Payer ) );
                subscriberName2010BbLoop.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity;
                subscriberName2010BbLoop.NM103_NameLastOrOrganizationName = payorCoverage.Payor.Name;
                subscriberName2010BbLoop.NM108_IdCodeQualifier = IdentificationCodeQualifier.PayorIdentification;
                subscriberName2010BbLoop.NM109_IdCode = payorCoverage.Payor.ElectronicTransmitterIdentificationNumber;

                // TODO: Kate needs to get back on this.
                HierarchicalLoop parentHierarchicalLoop = subscriber2000BHierarchicalLoop;
                if ( !isPatientTheSubscriber )
                {
                    autoIncrementedHierarchicalIDNumber++;

                    // PATIENT HIERARCHICAL LEVEL Loop Repeat: >1  **** HL 3  ******
                    var patientDetailLoop2000CLoop =
                        subscriber2000BHierarchicalLoop.AddHLoop (
                            autoIncrementedHierarchicalIDNumber.ToString ( CultureInfo.InvariantCulture ),
                            HierarchicalLevelCode.Dependent,
                            HierarchicalChildCode.NoSubordinateHLSegmentInThisHierarchicalStructure );

                    parentHierarchicalLoop = patientDetailLoop2000CLoop;

                    var hl3PatSegment = patientDetailLoop2000CLoop.AddSegment ( new TypedSegmentPAT () );
                    hl3PatSegment.PAT01_IndividualRelationshipCode =
                        payorCoverage.PayorSubscriber.PayorSubscriberRelationshipType.ShortName;

                    var hl3Nm1Segment = patientDetailLoop2000CLoop.AddLoop ( new TypedLoopNM1 ( EntityIdentifierCode.Patient ) );
                    hl3Nm1Segment.NM102_EntityTypeQualifier = EntityTypeQualifier.Person;
                    hl3Nm1Segment.NM104_NameFirst = payorCoverage.PatientAccount.Name.First; //TODO: confirm it comes from primaryPayorCoverage.PatientAccount, not from Claim.PatientAccount, the later make more sense
                    hl3Nm1Segment.NM103_NameLastOrOrganizationName = payorCoverage.PatientAccount.Name.Last;

                    var hl3Nm1N3Segment = hl3Nm1Segment.AddSegment ( new TypedSegmentN3 () );
                    hl3Nm1N3Segment.N301_AddressInformation = payorCoverage.PatientAccount.HomeAddress.FirstStreetAddress
                                                                +
                                                                ( string.IsNullOrWhiteSpace (
                                                                    payorCoverage.PatientAccount.HomeAddress.SecondStreetAddress )
                                                                      ? string.Empty
                                                                      : " " + payorCoverage.PatientAccount.HomeAddress.SecondStreetAddress );

                    var hl3Nm1N4Segment = hl3Nm1Segment.AddSegment ( new TypedSegmentN4 () );
                    hl3Nm1N4Segment.N401_CityName = payorCoverage.PatientAccount.HomeAddress.CityName;
                    hl3Nm1N4Segment.N402_StateOrProvinceCode = payorCoverage.PatientAccount.HomeAddress.StateProvince.ShortName;
                    hl3Nm1N4Segment.N403_PostalCode = payorCoverage.PatientAccount.HomeAddress.PostalCode.Code;

                    var hl3Nm1DmgSegment = hl3Nm1Segment.AddSegment ( new TypedSegmentDMG () );
                    hl3Nm1DmgSegment.DMG01_DateTimePeriodFormatQualifier = DateTimePeriodFormatQualifier.DateExpressedAsCCYYMMDD;
                    hl3Nm1DmgSegment.DMG02_DateOfBirth = payorCoverage.PatientAccount.BirthDate;
                    hl3Nm1DmgSegment.DMG03_Gender =
                        ConvertToGenderCodeFromAdministrativeGender ( payorCoverage.PatientAccount.AdministrativeGender );
                }

                // 2300 Claim Information loop repeat 100
                // LX loop repeat 50 => total 5000 claims in a HCC837 message or a Subscriber HL? ( seems the later  make more sense)
                // TODO: confirm it with Kate and how to handle it if exceed the max loop repeat
                foreach ( var claim in claimList )
                {
                    var claim2300Loop = parentHierarchicalLoop.AddLoop ( new TypedLoopCLM () ); // Claim 2300 loop: repeat 100
                    claim2300Loop.CLM01_PatientControlNumber = claim.Key.ToString ( CultureInfo.InvariantCulture );
                    claim2300Loop.CLM02_TotalClaimChargeAmount = decimal.Parse ( X12Utility.ConvertToDecimalString ( claim.ChargeAmount.Amount ) );
                    claim2300Loop.CLM05._1_FacilityCodeValue = PlaceOfServiceCode.Office;
                    claim2300Loop.CLM05._2_FacilityCodeQualifier = FacilityCodeQualifier.PlaceOfServiceCodesForProfessionalOrDentalService;
                    claim2300Loop.CLM05._3_ClaimFrequencyTypeCode = ClaimFrequencyTypeCode.Original;
                    claim2300Loop.CLM06_ProviderOrSupplierSignatureIndicator = YesOrNoConditionResponseCode.YesIndicator;
                    claim2300Loop.CLM07_ProviderAcceptAssignmentCode = ProviderAcceptAssignementCode.Assigned;
                    claim2300Loop.CLM08_BenefitsAssignmentCerficationIndicator = YesOrNoConditionResponseCode.Yes;
                    claim2300Loop.CLM09_ReleaseOfInformationCode = ReleaseOfInformationCode.Yes;

                    // TODO: diagnosis code -- Diagnosis is associated with Claim Line Item
                    // List the principal Dx with BK and others with BF, like HI✽BK:8901✽BF:87200✽BF:5559~, up to 12 diagnosis
                    // assume the 1st Dx is the principal Dx

                    var hiSegment = claim2300Loop.AddSegment ( new TypedSegmentHI () );
                    var index = 0;
                    foreach (var claimLineItem in claim.ClaimLineItems)
                    {
                        index++;
                        if (index == 1)
                        {
                            hiSegment.HI01_HealthCareCodeInformation =
                                X12Utility.BuildCompositeElement (
                                    PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter,
                                    CodeListQualifierCode.ICD9CMPrincipleDiagnostics,
                                    claimLineItem.Diagnosis.CodedConceptCode );
                        }
                        else if (index == 2)
                        {
                            hiSegment.HI02_HealthCareCodeInformation =
                                X12Utility.BuildCompositeElement(
                                    PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter,
                                    CodeListQualifierCode.ICD9CMDiagnostics,
                                    claimLineItem.Diagnosis.CodedConceptCode);
                        }
                        else if (index == 3)
                        {
                            hiSegment.HI03_HealthCareCodeInformation =
                                X12Utility.BuildCompositeElement(
                                    PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter,
                                    CodeListQualifierCode.ICD9CMDiagnostics,
                                    claimLineItem.Diagnosis.CodedConceptCode);
                        }
                        else if (index == 4)
                        {
                            hiSegment.HI04_HealthCareCodeInformation =
                                X12Utility.BuildCompositeElement(
                                    PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter,
                                    CodeListQualifierCode.ICD9CMDiagnostics,
                                    claimLineItem.Diagnosis.CodedConceptCode);
                        }
                        else if (index == 5)
                        {
                            hiSegment.HI05_HealthCareCodeInformation =
                                X12Utility.BuildCompositeElement(
                                    PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter,
                                    CodeListQualifierCode.ICD9CMDiagnostics,
                                    claimLineItem.Diagnosis.CodedConceptCode);
                        }
                        else if (index == 6)
                        {
                            hiSegment.HI06_HealthCareCodeInformation =
                                X12Utility.BuildCompositeElement(
                                    PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter,
                                    CodeListQualifierCode.ICD9CMDiagnostics,
                                    claimLineItem.Diagnosis.CodedConceptCode);
                        }
                        else if (index == 7)
                        {
                            hiSegment.HI07_HealthCareCodeInformation =
                                X12Utility.BuildCompositeElement(
                                    PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter,
                                    CodeListQualifierCode.ICD9CMDiagnostics,
                                    claimLineItem.Diagnosis.CodedConceptCode);
                        }
                        else if (index == 8)
                        {
                            hiSegment.HI08_HealthCareCodeInformation =
                                X12Utility.BuildCompositeElement(
                                    PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter,
                                    CodeListQualifierCode.ICD9CMDiagnostics,
                                    claimLineItem.Diagnosis.CodedConceptCode);
                        }
                        else if (index == 9)
                        {
                            hiSegment.HI09_HealthCareCodeInformation =
                                X12Utility.BuildCompositeElement(
                                    PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter,
                                    CodeListQualifierCode.ICD9CMDiagnostics,
                                    claimLineItem.Diagnosis.CodedConceptCode);
                        }
                        else if (index == 10)
                        {
                            hiSegment.HI10_HealthCareCodeInformation =
                                X12Utility.BuildCompositeElement(
                                    PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter,
                                    CodeListQualifierCode.ICD9CMDiagnostics,
                                    claimLineItem.Diagnosis.CodedConceptCode);
                        }
                        else if (index == 11)
                        {
                            hiSegment.HI11_HealthCareCodeInformation =
                                X12Utility.BuildCompositeElement(
                                    PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter,
                                    CodeListQualifierCode.ICD9CMDiagnostics,
                                    claimLineItem.Diagnosis.CodedConceptCode);
                        }
                        else if (index == 12)
                        {
                            hiSegment.HI12_HealthCareCodeInformation =
                                X12Utility.BuildCompositeElement(
                                    PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter,
                                    CodeListQualifierCode.ICD9CMDiagnostics,
                                    claimLineItem.Diagnosis.CodedConceptCode);
                        }
                    }

                    var autoIncrementedServiceLineNumber = 0;
                    foreach ( var claimLineItem in claim.ClaimLineItems )
                    {
                        autoIncrementedServiceLineNumber++;

                        var lxLoop = claim2300Loop.AddLoop ( new TypedLoopLX ( string.Empty ) ); // LX loop repeat: 50
                        lxLoop.LX01_AssignedNumber = autoIncrementedServiceLineNumber.ToString ( CultureInfo.InvariantCulture );

                        var sv1Segment = lxLoop.AddSegment ( new TypedSegmentSV1 () );
                        sv1Segment.SV101_CompositeMedicalProcedure =
                            X12Utility.BuildCompositeElement (
                                PayorType.HealthCareClaim837Setup.X12Delimiters.CompositeDelimiter,
                                ProductOrServiceIDQualifier.HCPCS, //TODO: Confirm with Kate if we can use HCPCS for all procedures.
                                claimLineItem.Procedure.CodedConceptCode );

                        sv1Segment.SV102_MonetaryAmount = X12Utility.ConvertToDecimalString ( claimLineItem.ChargeAmount.Amount );
                        sv1Segment.SV103_UnitBasisMeasCode = UnitsOrBasisOfMeasurementCode.Unit;
                        sv1Segment.SV104_Quantity = claimLineItem.BillingUnitCount.Count.ToString ( CultureInfo.InvariantCulture );
                        sv1Segment.SV107_CompDiagCodePoint = DiagnosisCodePointer;

                        var dtpSegment = lxLoop.AddSegment ( new TypedSegmentDTP () );
                        dtpSegment.DTP01_DateTimeQualifier = DateTimeQualifier.Service;
                        dtpSegment.DTP02_DateTimePeriodFormatQualifier = DateTimePeriodFormatQualifier.DateExpressedAsCCYYMMDD;
                        dtpSegment.DTP03_Date = claim.ServiceDate;
                    }
                }
            }

            var healthCareClaim837ProfessionalX12Message = message.SerializeToX12 ( true ); //TODO: Configure the whitespace option.
            var healthCareClaim837Professional = healthCareClaim837ProfessionalFactory.CreateHealthCareClaim837Professional ( this, Encoding.ASCII.GetBytes ( healthCareClaim837ProfessionalX12Message ) );

            var lookupValueRepository = IoC.CurrentContainer.Resolve<ILookupValueRepository>();
            ReviseClaimBatchStatus ( lookupValueRepository.GetLookupByWellKnownName<ClaimBatchStatus>(WellKnownNames.ClaimModule.ClaimBatchStatus.Hcc837PGenerated) );

            return healthCareClaim837Professional;
        }
        public void CreatePurchaseOrderChangeNotice860()
        {
            DateTime purcaseOrderDate = new DateTime(2010, 8, 17, 08, 50, 0);
            DateTime changeOrderDate = DateTime.Now;
            DateTime requestedShipDate = DateTime.Now.AddDays(2d);

            Interchange interchange = new Interchange(changeOrderDate , 245, true)
            {
                InterchangeSenderIdQualifier = "01",
                InterchangeSenderId = "828513080",
                InterchangeReceiverIdQualifier = "01",
                InterchangeReceiverId = "001903202U",
                InterchangeDate = changeOrderDate,
            };
            interchange.SetElement(14, "0"); //No Aknowlegement is 0

            FunctionGroup group = interchange.AddFunctionGroup("PO", changeOrderDate, 1, "005010X222");
            group.ApplicationSendersCode = "828513080";
            group.ApplicationReceiversCode = "001903202U";
            group.Date = changeOrderDate;
            group.ControlNumber = 245;

            Transaction transaction = group.AddTransaction("860", "0001");

            //BCH - Beginning Segment for Purchase Order Change
            //Mandatory / Max Use=1 time
            Segment bhtSegment = transaction.AddSegment("BCH");
            bhtSegment.SetElement((int)BeginningSegmentPurchaseOrderChangeIndex.TransactionSetPurpose , "01");  //01 is cancelllation  04 is change
            bhtSegment.SetElement((int)BeginningSegmentPurchaseOrderChangeIndex.TransactionSetTypeCode, "SA");
            bhtSegment.SetElement((int)BeginningSegmentPurchaseOrderChangeIndex.PurchaseOrderDate, purcaseOrderDate.ToString("yyyyMMdd"));
            bhtSegment.SetElement((int)BeginningSegmentPurchaseOrderChangeIndex.ChangeRequestDate, changeOrderDate.ToString("yyyyMMdd"));

            //REF- Reference Identification
            //Optional / Max Use=1 time
            bhtSegment = transaction.AddSegment("REF");
            bhtSegment.SetElement((int)ReferenceIdentificationIndex.ReferenceIdentificationQualifier , "IA");
            bhtSegment.SetElement((int)ReferenceIdentificationIndex.ReferenceNumber, "1to30chars");

            //DTM – Date/Time Reference
            //Optional/ Max Use=1 time
            bhtSegment = transaction.AddSegment("DTM");
            bhtSegment.SetElement((int)DateTimeReferenceIndex.TermsTypeCode, "010");
            bhtSegment.SetElement((int)DateTimeReferenceIndex.RequestedShipDate, requestedShipDate.ToString("yyyyMMdd"));

            //Add to test
            //N1 – Name
            //Optional / Max Use=1

            //N3 – Address Information
            //Conditional – use if N1 used/ Max Use=2

            //N4 – Geographic Location
            //Conditional – use if N3 used / Max Use=1 time

            //POC – Line Item Change
            //Mandatory / Max Use=1 times per loop / Max Loop=99 times

            //DTM – Date/Time Reference
            //Mandatory / Max Use=1 times per loop

            //CTT – Transaction Totals
            //Mandatory / Max Use=1 time

            var x12 = interchange.SerializeToX12(true);
            System.Diagnostics.Trace.Write(x12);
        }
Example #8
0
        public void PatientIsSelfInsuredTest()
        {
            var creationDateTime = new DateTime ( 2011, 02, 13, 12, 53, 00 ); //DateTime.Now.
            int autoIncrementedControlNumber = 1; //Must be persisted, so that it will be unique per interchange.
            int autoIncrementedHierarchicalIDNumber = 1; //The first HL01 within each ST-SE envelope must begin with “1”.
            int autoIncrementedServiceLineNumber = 1;

            var message = new Interchange ( creationDateTime, autoIncrementedControlNumber, IS_PRODUCTION )
                {
                    //When Authorization information is not provided, it chooses 00 as qualifier with empty value. Refer 'Authorization Information Qualifier' code table.

                    //SecurityInfoQualifier = SECURITY_INFORMATION_CODE_PASSWORD, //Refer 'Security Information Qualifier'. What does WITS do ?
                    //SecurityInfo = "THEPASSWORD", //What does WITS do ?

                    InterchangeSenderIdQualifier = INTERCHANGE_IDENTIFIER_CODE_MUTUALLY_DEFINED,
                    //Need to a code table for 'Interchange ID Qualifier'. Pg: 638. ZZ - 'Mutually Defined'.
                    InterchangeSenderId = "SUBMITTERS.ID",
                    //HealthCareClaim837Setup.InterchangeSenderNumber

                    InterchangeReceiverIdQualifier = INTERCHANGE_IDENTIFIER_CODE_MUTUALLY_DEFINED,
                    //Refer 'Interchange ID Qualifier'. Can we reuse the same code table ?
                    InterchangeReceiverId = "RECEIVERS.ID" //HealthCareClaim837Setup.InterchangeRecieverNumber
                };

            message.SetElement ( 12, INTERCHANGE_CONTROL_VERSION_NUMBER );
                //Refer 'Interchange Control Version Number' code table. It has only 1 value.
            //message.SetElement(10, "1253"); //Interchange time, can be part of 'interchangeDateTime' variable declared above.
            message.SetElement ( 11, REPITITION_SEPARATOR ); //Repetition separator.
            message.SetElement(14, "1");

            var group = message.AddFunctionGroup (
                FUNCTIONAL_IDENTIFIER_CODE, creationDateTime, autoIncrementedControlNumber, IMPLEMENTATION_GUIDE_VERSION_NAME );
            group.ApplicationSendersCode = "SENDER CODE"; //HealthCareClaim837Setup.InterchangeSenderNumber
            group.ApplicationReceiversCode = "RECEIVER CODE"; //HealthCareClaim837Setup.InterchangeRecieverNumber
            group.ResponsibleAgencyCode = "X";
            //group.Date = Convert.ToDateTime("12/31/1999"); //Overwriting given DateTime.Now value. Functional Group Creation Date.
            //group.ControlNumber = 1; //Control number overwritten. Same as 'autoIncrementedFunctionalGroupControlNumber' variable.
            //group.SetElement(5, "0802"); //Overwriting given DateTime.Now value. Functional Group Creation Time. hh:mm

            string interchangeControlNumber = autoIncrementedControlNumber.ToString ( CultureInfo.InvariantCulture );
            interchangeControlNumber = interchangeControlNumber.Length < 4 ? interchangeControlNumber.PadLeft ( 4, '0' ) : interchangeControlNumber;
            var transaction = group.AddTransaction ( TRANSACTIONSET_IDENTIFIER_CODE, interchangeControlNumber ); //Pg: 70.
            //transaction.SetElement(2, transactionSetControlNumber);
            transaction.SetElement ( 3, IMPLEMENTATION_GUIDE_VERSION_NAME );
                //It is the Implementation Guide Version Name. Refer 'Version / Release / Industry Identifier' Code table

            var bhtSegment = transaction.AddSegment ( BEGINING_OF_HIERARCHICAL_TRANSACTION );
            bhtSegment.SetElement ( 1, HIERARCHICAL_STRUCTURE_CODE_INFORMATIONSOURCE_SUBSCRIBER_DEPENDENT );
                //Refer 'Hierarchical Structure' Code table.
            bhtSegment.SetElement ( 2, TRANSACTIONSET_PURPOSE_CODE_ORIGINAL ); //Refer 'Transaction Set Purpose' code table.
            bhtSegment.SetElement(3, REFERENCE_IDENTIFICATION_BATCH_CONTROL_NUMBER); //Acts as batch control number. 30 chars.
            bhtSegment.SetElement(4, "20061015"); //date that the original submitter created the claim file from their business application system.
            bhtSegment.SetElement(5, "1023"); //- time that the original submitter created the claim file from their business application system.
            bhtSegment.SetElement(6, "CH"); // - indicates that the transaction contains only fee for service claims or claims with at least one chargeable line item. Refer code table 'Transaction Type'.

            //Submitter Name
            var submitterLoop = transaction.AddLoop ( new TypedLoopNM1 ( EntityIdentifierCodes.SUBMITTER ) );
                //submitter identifier code. See 'Entity Identifier' code table
            submitterLoop.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity; //See 'Entity Type Qualifier' code table.
            submitterLoop.NM103_NameLastOrOrganizationName = "SAFE HARBOR"; //BillingOffice.Agency.LegalName
            //submitterLoop.NM104_NameFirst = ""; //Always empty when EntityTypeQualifier is Non-Person entity.
            submitterLoop.NM108_IdCodeQualifier = IdentificationCodes.ELECTRONIC_TRANSMITTER_IDENTIFICATION_NUMBER;
                //See code table 'Identification Code Qualifier' - Electronic Transmitter Identification Number - established by trading partner agreement.
            submitterLoop.NM109_IdCode = "SAFEHARBOR_ETIN"; //BillingOffice.ElectronicTransmitterIdentificationNumber.

            //SUBMITTER EDI CONTACT INFORMATION.
            var perSegment = submitterLoop.AddSegment ( new TypedSegmentPER () );
            perSegment.PER01_ContactFunctionCode = INFORMATION_CONTACT; //information contact function code
            perSegment.PER02_Name = "JERRY";
                //BillingOffice.Administrator - Situational - required when the person to contact is different from the subscriber. As we provided a nonperson entity we need to provide the person name.
            perSegment.PER03_CommunicationNumberQualifier = CommunicationNumberQualifer.Telephone; //See code table 'Communication Number Qualifier'.
            perSegment.PER04_CommunicationNumber = "3055552222"; //telephone. //BillingOffice.Administrator.TelephoneNumber
            //if(There is telephone extension)
            perSegment.PER05_CommunicationNumberQualifier = CommunicationNumberQualifer.TelephoneExtension;
                //See code table 'Communication Number Qualifier'.
            perSegment.PER06_CommunicationNumber = "231"; //telephone extension //BillingOffice.Administrator.TelephoneNumberExtension

            //RECEIVER NAME
            var receiverLoop = transaction.AddLoop ( new TypedLoopNM1 ( EntityIdentifierCodes.RECEIVER ) );
                //receiver identifier code. See 'Entity Identifier' code table
            receiverLoop.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity; //See 'Entity Type Qualifier' code table.
            receiverLoop.NM103_NameLastOrOrganizationName = "KEY INSURANCE COMPANY"; //Payor.Name
            //receiverLoop.NM104_NameFirst = ""; //Always empty when EntityTypeQualifier is Non-Person entity.
            receiverLoop.NM108_IdCodeQualifier = IdentificationCodes.ELECTRONIC_TRANSMITTER_IDENTIFICATION_NUMBER;
                //See code table 'Identification Code Qualifier' - Electronic Transmitter Identification Number - established by trading partner agreement.
            receiverLoop.NM109_IdCode = "KEY_INSURANCE_ETIN"; //Payor.ElectronicTransmitterIdentificationNumber.

            //Billing Provider Hierarchical Level.
            var provider2000AHierachicalLoop = transaction.AddHLoop (
                autoIncrementedHierarchicalIDNumber.ToString ( CultureInfo.InvariantCulture ),
                HierarchicalLevelCodes.INFORMATIONSOURCE,
                BILLING_PROVIDER_HIERARCHICAL_LOOP_CAN_HOLD_CHILD_HIERARCHICAL_LOOPS ); //*********HL 1 ******.
            var prvSegment = provider2000AHierachicalLoop.AddSegment ( new TypedSegmentPRV () );
                //Specialty Segment. PRV - BILLING PROVIDER SPECIALTY INFORMATION.
            prvSegment.PRV01_ProviderCode = PROVIDER_CODE_BILLING; //Refer 'Provider Code' code table.
            prvSegment.PRV02_ReferenceIdQualifier = ReferenceIdentificationCodes.HEALTHCARE_PROVIDER_TAXONOMY;
                //Refer 'Reference Identification Qualifier' code table
            prvSegment.PRV03_ProviderTaxonomyCode = HEALTHCARE_PROVIDER_TAXONOMY_VALUE;

            //Billing provider Name
            var provider2010AALoop = provider2000AHierachicalLoop.AddLoop ( new TypedLoopNM1 ( BILLING_PROVIDER ) );
            provider2010AALoop.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity;
            provider2010AALoop.NM103_NameLastOrOrganizationName = "Safe Harbor"; //BillingOffice.Agency.LegalName
            provider2010AALoop.NM108_IdCodeQualifier = IdentificationCodes.CENTERS_FOR_MEDICARE_AND_MEDICAID_SERVICES_NATIONAL_PROVIDER_IDENTIFIER;
            provider2010AALoop.NM109_IdCode = "9876543210"; //BillingOffice.Agency.Identifiers.NPINumber

            //Billing provider address
            var provider2010AA_N3Segment = provider2010AALoop.AddSegment ( new TypedSegmentN3 () );
            provider2010AA_N3Segment.N301_AddressInformation = "234 SEAWAY ST";
                //BillingOffice.Agency.Address.FirstStreetAddress & SecondStreetAddress

            //Billing provider City,State,Zipcode
            var provider2010AA_N4Segment = provider2010AALoop.AddSegment ( new TypedSegmentN4 () );
            provider2010AA_N4Segment.N401_CityName = "MIAMI"; //BillingOffice.Agency.Address.CityName
            provider2010AA_N4Segment.N402_StateOrProvinceCode = "FL"; //BillingOffice.Agency.Address.StateProvince
            provider2010AA_N4Segment.N403_PostalCode = "33111"; //BillingOffice.Agency.Address.PostalCode

            //Billing provider - tax identification
            var provider2010AA_REFSegment = provider2010AALoop.AddSegment ( new TypedSegmentREF () );
            provider2010AA_REFSegment.REF01_ReferenceIdQualifier = ReferenceIdentificationCodes.EMPLOYERS_IDENTIFICATION_NUMBER;
            provider2010AA_REFSegment.REF02_ReferenceId = "587654321"; //BillingOffice.Agency.Identifiers.FederalTaxID

            var provider2010ABLoop = provider2000AHierachicalLoop.AddLoop ( new TypedLoopNM1 ( EntityIdentifierCodes.PAY_TO_PROVIDER ) );
            provider2010ABLoop.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity;

            var provider2010AB_N3Segment = provider2010ABLoop.AddSegment ( new TypedSegmentN3 () );
            provider2010AB_N3Segment.N301_AddressInformation = "234 SEAWAY ST";
                //BillingOffice.Agency.Address.FirstStreetAddress & SecondStreetAddress

            var provider2010AB_N4Segment = provider2010ABLoop.AddSegment ( new TypedSegmentN4 () );
            provider2010AB_N4Segment.N401_CityName = "MIAMI"; //BillingOffice.Agency.Address.CityName
            provider2010AB_N4Segment.N402_StateOrProvinceCode = "FL"; //BillingOffice.Agency.Address.StateProvince
            provider2010AB_N4Segment.N403_PostalCode = "33111"; //BillingOffice.Agency.Address.PostalCode

            autoIncrementedHierarchicalIDNumber++;
            var subscriber2000BHierarchicalLoop =
                provider2000AHierachicalLoop.AddHLoop (
                    autoIncrementedHierarchicalIDNumber.ToString ( CultureInfo.InvariantCulture ),
                    HierarchicalLevelCodes.SUBSCRIBER,
                    false /*SUBSCRIBER_HIERARCHICAL_LOOP_CAN_HOLD_CHILD_HIERARCHICAL_LOOPS*/ ); // **** HL 2  ****** No Child HL

            //Subscriber information
            var segmentSBR = subscriber2000BHierarchicalLoop.AddSegment ( new TypedSegmentSBR () );
            segmentSBR.SBR01_PayerResponsibilitySequenceNumberCode = PayerResponsibilitySequenceCodes.PRIMARY;
            segmentSBR.SBR02_IndividualRelationshipCode = IndividualRelationshipCodes.SELF;
            //segmentSBR.SBR03_PolicyOrGroupNumber = "2222-SJ"; //Required when the subscriber’s identification card for the destination payer (Loop ID-2010BB) shows a group number.
            //segmentSBR.SBR09_ClaimFilingIndicatorCode = "CI"; //Not in practical use.

            //Patient information - Required when the patient is the subscriber.
            //var segmentPAT = subscriber2000BHierarchicalLoop.AddSegment ( new TypedSegmentPAT () );
            //segmentPAT.PAT09_PregnancyIndicator = false;

            //Loop 2010BA - Subscriber Name
            var subscriberName2010BALoop = subscriber2000BHierarchicalLoop.AddLoop (
                new TypedLoopNM1 ( EntityIdentifierCodes.INSURED_OR_SUBSCRIBER ) );
            subscriberName2010BALoop.NM102_EntityTypeQualifier = EntityTypeQualifier.Person;
            subscriberName2010BALoop.NM104_NameFirst = "JANE"; //PayorSubscriber.LastName
            subscriberName2010BALoop.NM103_NameLastOrOrganizationName = "SMITH"; //PayorSubscriber.FirstName
            subscriberName2010BALoop.NM109_IdCode = "JS00111223333"; //PayorSubscriber.PayorCoverage.MemberNumber
            subscriberName2010BALoop.NM108_IdCodeQualifier = IdentificationCodes.MEMBER_IDENTIFICATION_NUMBER;

            //Loop 2010BA - Subscriber address
            var provider2010BA_N3Segment = subscriberName2010BALoop.AddSegment ( new TypedSegmentN3 () );
            provider2010BA_N3Segment.N301_AddressInformation = "234 SEAWAY ST"; //PayorSubscriber.Address.FirstStreetAddress & SecondStreetAddress

            //Loop 2010BA - Subscriber city,state,postal code.
            var provider2010BA_N4Segment = subscriberName2010BALoop.AddSegment ( new TypedSegmentN4 () );
            provider2010BA_N4Segment.N401_CityName = "MIAMI"; //PayorSubscriber.Address.CityName
            provider2010BA_N4Segment.N402_StateOrProvinceCode = "FL"; //PayorSubscriber.Address.StateProvince
            provider2010BA_N4Segment.N403_PostalCode = "33413"; //PayorSubscriber.Address.PostalCode

            //Loop 2010BA - Demographic information
            var subscriber_DMGSegment = subscriberName2010BALoop.AddSegment ( new TypedSegmentDMG () );
            subscriber_DMGSegment.DMG01_DateTimePeriodFormatQualifier = DATE_TIME_PERIOD_FORMAT_QUALIFIER_DATE_EXPRESSED_IN_FORMAT_CCYYMMDD;
            subscriber_DMGSegment.DMG02_DateOfBirth = DateTime.Parse ( "5/1/1943" ); //PayorSubscriber.BirthDate
            subscriber_DMGSegment.DMG03_Gender = Gender.Female; //PayorSubscriber.AdministrativeGender

            //Loop 2010BB - Payer Name.
            var subscriberName2010BBLoop = subscriber2000BHierarchicalLoop.AddLoop ( new TypedLoopNM1 ( EntityIdentifierCodes.PAYER ) );
            subscriberName2010BBLoop.NM102_EntityTypeQualifier = EntityTypeQualifier.NonPersonEntity;
            subscriberName2010BBLoop.NM103_NameLastOrOrganizationName = "KEY INSURANCE COMPANY"; //Payor.Name
            subscriberName2010BBLoop.NM108_IdCodeQualifier = IdentificationCodes.PAYOR_IDENTIFICATION;
            subscriberName2010BBLoop.NM109_IdCode = "999996666"; //NPI? Kate needs time to check.

            //optional.
            //var refSegment2 = subscriberName2010BBLoop.AddSegment(new TypedSegmentREF());
            //refSegment2.REF01_ReferenceIdQualifier = ReferenceIdentificationCodes.PROVIDER_COMMERCIAL_NUMBER;
            //refSegment2.REF02_ReferenceId = "KA6663";

            //autoIncrementedHierarchicalIDNumber++;
            //PATIENT HIERARCHICAL LEVEL Loop Repeat: >1
            //var patientDetailLoop2000CLoop = subscriber2000BHierarchicalLoop.AddHLoop(autoIncrementedHierarchicalIDNumber.ToString(CultureInfo.InvariantCulture), HierarchicalLevelCodes.DEPENDENT, PATIENT_HIERARCHICAL_LOOP_CAN_HOLD_CHILD_HIERARCHICAL_LOOPS);   // **** HL 3  ******

            //var HL3PATSegment = subscriber2000BHierarchicalLoop.AddSegment(new TypedSegmentPAT());
            //HL3PATSegment.PAT01_IndividualRelationshipCode = IndividualRelationshipCodes.CHILD;

            //How does the billing side access patient information on the clinical side.
            //var HL3NM1Segment = subscriber2000BHierarchicalLoop.AddLoop(new TypedLoopNM1(EntityIdentifierCodes.PATIENT));
            //HL3NM1Segment.NM102_EntityTypeQualifier = EntityTypeQualifier.Person;
            //HL3NM1Segment.NM104_NameFirst = "TED"; //Patinet.FirstName
            //HL3NM1Segment.NM103_NameLastOrOrganizationName = "SMITH"; //Patinet.LastName

            //// add N3 and N4 segments under the above NM1 loop

            //var HL3NM1_N3_Segment = HL3NM1Segment.AddSegment(new TypedSegmentN3());
            //HL3NM1_N3_Segment.N301_AddressInformation = "236 N MAIN ST"; //Patient.Address.FirstStreetAddress & SecondStreetAddress

            //var HL3NM1_N4_Segment = HL3NM1Segment.AddSegment(new TypedSegmentN4());
            //HL3NM1_N4_Segment.N401_CityName = "MIAMI"; //Patient.Address.CityName
            //HL3NM1_N4_Segment.N402_StateOrProvinceCode = "FL"; //Patient.Address.StateProvince
            //HL3NM1_N4_Segment.N403_PostalCode = "33413"; //Patient.Address.PostalCode

            //var HL3NM1_DMG_Segment = HL3NM1Segment.AddSegment(new TypedSegmentDMG());
            //HL3NM1_DMG_Segment.DMG01_DateTimePeriodFormatQualifier = DATE_TIME_PERIOD_FORMAT_QUALIFIER_DATE_EXPRESSED_IN_FORMAT_CCYYMMDD;
            //HL3NM1_DMG_Segment.DMG02_DateOfBirth = Convert.ToDateTime("5/1/1973"); //Patinet.BirthDate
            //HL3NM1_DMG_Segment.DMG03_Gender = Gender.Male; //Patinet.AdministrativeGender

            var claim2300Loop = subscriber2000BHierarchicalLoop.AddLoop ( new TypedLoopCLM () );
            claim2300Loop.CLM01_PatientControlNumber = "26463774"; //BillingOffice.PlaceOfService.Claims[0].Key
            claim2300Loop.CLM02_TotalClaimChargeAmount = Convert.ToDecimal ( 100 ); //BillingOffice.PlaceOfService.Claims[0].ChargeAmount
            claim2300Loop.CLM05._1_FacilityCodeValue = PLACE_OF_SERVICE_CODE_OFFICE;
            claim2300Loop.CLM05._2_FacilityCodeQualifier = PLACE_OF_SERVICE_CODES_FOR_PROFESSIONAL_OR_DENTAL_SERVICES;
            claim2300Loop.CLM05._3_ClaimFrequencyTypeCode = CLAIM_FREQUENCY_TYPE_CODE_ORIGINAL;
            claim2300Loop.CLM06_ProviderOrSupplierSignatureIndicator = PROVIDER_OR_SUPPLIER_SIGNATURE_INDICATOR_CODE_YES;
            claim2300Loop.CLM07_ProviderAcceptAssignmentCode = PROVIDER_ACCEPTANCE_ASSIGNMENT_CODE_ASSIGNED;
            claim2300Loop.CLM08_BenefitsAssignmentCerficationIndicator = BENIFITS_ASSIGNMENT_CERTIFICATION_INDICATOR_CODE_YES;
            claim2300Loop.CLM09_ReleaseOfInformationCode = RELEASE_OF_INFORMATION_CODE_YES; //Kate says 'I don't think it matters too much'

            //Claim Identifier for Transmission Intermediaries is the new name for the Claim Identification Number for Clearinghouses
            //and Other Transmission Intermediaries segment. The qualifier (REF01 = D9) did not change. ??? Do we use the intermediaries ? Kate says 'Not Yet'.
            //var refSegment = claim2300Loop.AddSegment(new TypedSegmentREF());
            //refSegment.REF01_ReferenceIdQualifier = "D9";
            //refSegment.REF02_ReferenceId = "17312345600006351";

            var hiSegment = claim2300Loop.AddSegment ( new TypedSegmentHI () );
            //Which value to use ?
            hiSegment.HI01_HealthCareCodeInformation =
                X12Utility.BuildCompositeElement ( x12Delimiters.CompositeDelimiter,  INTERNATIONAL_CLASSIFICATION_OF_DISEASES_CLINICAL_MODIFICATION_ICD9CM_PRINCIPLE_DIAGNOSTICS, "0340" );
            //hiSegment.HI02_HealthCareCodeInformation = hiSegment.X12Utility.BuildCompositeElement("BF", "V7389"); - optional

            var lxLoop = claim2300Loop.AddLoop ( new TypedLoopLX ( "LX" ) );
            lxLoop.LX01_AssignedNumber = autoIncrementedServiceLineNumber.ToString ( CultureInfo.InvariantCulture );

            var sv1Segment = lxLoop.AddSegment ( new TypedSegmentSV1 () );
            sv1Segment.SV101_CompositeMedicalProcedure = X12Utility.BuildCompositeElement ( x12Delimiters.CompositeDelimiter,  SERVICE_ID_QUALIFIER_CODE_HCPCS, "99213" );
                //HC for HCPCS - constant for now. BillingOffice.PlaceOfService.Claims[0].ClaimLineItem[0].Procedure.
            sv1Segment.SV102_MonetaryAmount = "40"; //BillingOffice.PlaceOfService.Claims[0].ClaimLineItem[0].ChargeAmount
            sv1Segment.SV103_UnitBasisMeasCode = UNIT_OR_BASIS_FOR_MEASUREMENT_CODE_UNIT; //Constant.
            sv1Segment.SV104_Quantity = "1"; //BillingOffice.PlaceOfService.Claims[0].ClaimLineItem[0].BillingUnitCount
            sv1Segment.SV107_CompDiagCodePoint = "1"; //No functionality in REM. Default to 1.

            var dtpSegment = lxLoop.AddSegment ( new TypedSegmentDTP () );
            dtpSegment.DTP01_DateTimeQualifier = DATE_TIME_QUALIFIER_CODE_SERVICE;
            dtpSegment.DTP02_DateTimePeriodFormatQualifier = DATE_TIME_PERIOD_FORMAT_QUALIFIER_DATE_EXPRESSED_IN_FORMAT_CCYYMMDD;
            DateTime theDate = DateTime.ParseExact ( "20061003", "yyyyMMdd", null ); //BillingOffice.PlaceOfService.Claims[0].ServiceDate
            dtpSegment.DTP03_Date = theDate;

            autoIncrementedServiceLineNumber++;
            var lxLoop2 = claim2300Loop.AddLoop ( new TypedLoopLX ( "LX" ) );
            lxLoop2.LX01_AssignedNumber = autoIncrementedServiceLineNumber.ToString ( CultureInfo.InvariantCulture );

            var sv1Segment2 = lxLoop2.AddSegment ( new TypedSegmentSV1 () );
            sv1Segment2.SV101_CompositeMedicalProcedure = X12Utility.BuildCompositeElement ( x12Delimiters.CompositeDelimiter,  SERVICE_ID_QUALIFIER_CODE_HCPCS, "87070" );
                //HC for HCPCS - constant for now. BillingOffice.PlaceOfService.Claims[0].ClaimLineItem[0].Procedure.
            sv1Segment2.SV102_MonetaryAmount = "15"; //BillingOffice.PlaceOfService.Claims[0].ClaimLineItem[0].ChargeAmount
            sv1Segment2.SV103_UnitBasisMeasCode = UNIT_OR_BASIS_FOR_MEASUREMENT_CODE_UNIT; //
            sv1Segment2.SV104_Quantity = "1"; //BillingOffice.PlaceOfService.Claims[0].ClaimLineItem[0].BillingUnitCount
            sv1Segment2.SV107_CompDiagCodePoint = "1"; //No functionality in REM. Default to 1.

            var dtpSegment2 = lxLoop2.AddSegment ( new TypedSegmentDTP () );
            dtpSegment2.DTP01_DateTimeQualifier = DATE_TIME_QUALIFIER_CODE_SERVICE;
            dtpSegment2.DTP02_DateTimePeriodFormatQualifier = DATE_TIME_PERIOD_FORMAT_QUALIFIER_DATE_EXPRESSED_IN_FORMAT_CCYYMMDD;
            DateTime theDate2 = DateTime.ParseExact ( "20061003", "yyyyMMdd", null ); //BillingOffice.PlaceOfService.Claims[0].ServiceDate
            dtpSegment2.DTP03_Date = theDate2;

            autoIncrementedServiceLineNumber++;
            var lxLoop3 = claim2300Loop.AddLoop ( new TypedLoopLX ( "LX" ) );
            lxLoop3.LX01_AssignedNumber = autoIncrementedServiceLineNumber.ToString ( CultureInfo.InvariantCulture );

            var sv1Segment3 = lxLoop3.AddSegment ( new TypedSegmentSV1 () );
            sv1Segment3.SV101_CompositeMedicalProcedure = X12Utility.BuildCompositeElement ( x12Delimiters.CompositeDelimiter,  SERVICE_ID_QUALIFIER_CODE_HCPCS, "99214" );
                //HC for HCPCS - constant for now. BillingOffice.PlaceOfService.Claims[0].ClaimLineItem[0].Procedure.
            sv1Segment3.SV102_MonetaryAmount = "35";
            sv1Segment3.SV103_UnitBasisMeasCode = UNIT_OR_BASIS_FOR_MEASUREMENT_CODE_UNIT;
            sv1Segment3.SV104_Quantity = "1"; //BillingOffice.PlaceOfService.Claims[0].ClaimLineItem[0].BillingUnitCount
            sv1Segment3.SV107_CompDiagCodePoint = "1"; //No functionality in REM. Default to 1.

            var dtpSegment3 = lxLoop3.AddSegment ( new TypedSegmentDTP () );
            dtpSegment3.DTP01_DateTimeQualifier = DATE_TIME_QUALIFIER_CODE_SERVICE;
            dtpSegment3.DTP02_DateTimePeriodFormatQualifier = DATE_TIME_PERIOD_FORMAT_QUALIFIER_DATE_EXPRESSED_IN_FORMAT_CCYYMMDD;
            DateTime theDate3 = DateTime.ParseExact ( "20061010", "yyyyMMdd", null ); //BillingOffice.PlaceOfService.Claims[0].ServiceDate
            dtpSegment3.DTP03_Date = theDate3;

            autoIncrementedServiceLineNumber++;
            var lxLoop4 = claim2300Loop.AddLoop ( new TypedLoopLX ( "LX" ) );
            lxLoop4.LX01_AssignedNumber = autoIncrementedServiceLineNumber.ToString ( CultureInfo.InvariantCulture );

            var sv1Segment4 = lxLoop4.AddSegment ( new TypedSegmentSV1 () );
            sv1Segment4.SV101_CompositeMedicalProcedure = X12Utility.BuildCompositeElement ( x12Delimiters.CompositeDelimiter,  SERVICE_ID_QUALIFIER_CODE_HCPCS, "86663" );
                //HC for HCPCS - constant for now. BillingOffice.PlaceOfService.Claims[0].ClaimLineItem[0].Procedure.
            sv1Segment4.SV102_MonetaryAmount = "10";
            sv1Segment4.SV103_UnitBasisMeasCode = UNIT_OR_BASIS_FOR_MEASUREMENT_CODE_UNIT;
            sv1Segment4.SV104_Quantity = "1"; //BillingOffice.PlaceOfService.Claims[0].ClaimLineItem[0].BillingUnitCount
            sv1Segment4.SV107_CompDiagCodePoint = "1"; //No functionality in REM. Default to 1.

            var dtpSegment4 = lxLoop4.AddSegment ( new TypedSegmentDTP () );
            dtpSegment4.DTP01_DateTimeQualifier = DATE_TIME_QUALIFIER_CODE_SERVICE;
            dtpSegment4.DTP02_DateTimePeriodFormatQualifier = DATE_TIME_PERIOD_FORMAT_QUALIFIER_DATE_EXPRESSED_IN_FORMAT_CCYYMMDD;
            DateTime theDate4 = DateTime.ParseExact ( "20061010", "yyyyMMdd", null ); //BillingOffice.PlaceOfService.Claims[0].ServiceDate
            dtpSegment4.DTP03_Date = theDate4;

            var x12 = message.SerializeToX12 ( true );
            var ediString = Pillar.Common.Utility.EmbeddedResourceUtil.GetEmbeddedResourceValue("Rem.Domain.Billing.Tests.TestData._837p.Example2_SelfInsured.txt", Assembly.GetExecutingAssembly());
            Assert.AreEqual(ediString, x12);
        }
        private String InterchangeSenderId = "828513080"; // need a mutually agreed up ID

        #endregion Fields

        #region Methods

        public void CreatePurchaseOrder850(PurchaseOrder purchaseOrder,string fileName)
        {
            DateTime purcaseOrderDate = DateTime.Now;
            Interchange interchange = new Interchange(purcaseOrderDate, Convert.ToInt32(purchaseOrder.Number), true)
            {
                InterchangeSenderIdQualifier = "ZZ",
                InterchangeSenderId = InterchangeSenderId,
                InterchangeReceiverIdQualifier = "ZZ",
                InterchangeReceiverId = InterchangeReceiverId,
                InterchangeDate = purcaseOrderDate,
            };

            interchange.SetElement(14, "0"); //No Aknowlegement is 0

            FunctionGroup group = interchange.AddFunctionGroup("PO", purcaseOrderDate, Convert.ToInt32(purchaseOrder.Number), "004010");
            group.ApplicationSendersCode = InterchangeSenderId;
            group.ApplicationReceiversCode = InterchangeReceiverId;
               // group.Date = purcaseOrderDate;
               // group.ControlNumber = Convert.ToInt32(purchaseOrder.Number);

            Transaction transaction = group.AddTransaction("850", "0001");

            Segment bhtSegment = transaction.AddSegment("BEG");
            bhtSegment.SetElement(1, "00");
            bhtSegment.SetElement(2, "SA");
            bhtSegment.SetElement(3, purchaseOrder.Number);
            bhtSegment.SetElement(5, purcaseOrderDate.ToString("yyyyMMdd"));

            //bhtSegment = transaction.AddSegment("CUR");
            //bhtSegment.SetElement(1, "BY");
            //bhtSegment.SetElement(2, "USD");

            //bhtSegment = transaction.AddSegment("PER");
            //bhtSegment.SetElement(1, "IC");
            //bhtSegment.SetElement(2, "Doe,Jane");
            //bhtSegment.SetElement(8, "Doe,Jane");

            //bill to section
            Loop loop = transaction.AddLoop("N1");
            loop.SetElement(1, "BT");
            loop.SetElement(2, purchaseOrder.Customer.BillingName);
            loop.SetElement(3,92);
            loop.SetElement(4,purchaseOrder.Customer.BillingAddress.Id);

            Segment segment = loop.AddSegment("N3");
            segment.SetElement(1, purchaseOrder.Customer.BillingAddress.Street);
            segment.SetElement(2, purchaseOrder.Customer.BillingAddress.City + " " + purchaseOrder.Customer.BillingAddress.State + " " + purchaseOrder.Customer.BillingAddress.PostalCode + " " + purchaseOrder.Customer.BillingAddress.Country);
            segment = loop.AddSegment("N4");
            segment.SetElement(1, purchaseOrder.Customer.BillingAddress.City);
            segment.SetElement(2, purchaseOrder.Customer.BillingAddress.ShortState); // short state
            segment.SetElement(3, purchaseOrder.Customer.BillingAddress.PostalCode);
            segment.SetElement(4, purchaseOrder.Customer.BillingAddress.ShortCountry); //short country

            //ship to to section
            loop = transaction.AddLoop("N1");
            loop.SetElement(1, "ST");
            loop.SetElement(2, purchaseOrder.Customer.ShippingName);
            loop.SetElement(3, 92);
            loop.SetElement(4, purchaseOrder.Customer.ShippingAddress.Id);

            segment = loop.AddSegment("N3");
            segment.SetElement(1, purchaseOrder.Customer.ShippingAddress.Street);
            segment.SetElement(2, purchaseOrder.Customer.ShippingAddress.City + " " + purchaseOrder.Customer.ShippingAddress.State + " " + purchaseOrder.Customer.ShippingAddress.PostalCode + " " + purchaseOrder.Customer.ShippingAddress.Country);
            segment = loop.AddSegment("N4");
            segment.SetElement(1, purchaseOrder.Customer.ShippingAddress.City);
            segment.SetElement(2, purchaseOrder.Customer.BillingAddress.ShortState); // short state
            segment.SetElement(3, purchaseOrder.Customer.BillingAddress.PostalCode);
            segment.SetElement(4, purchaseOrder.Customer.BillingAddress.ShortCountry); //short country

            int count = 1;
            foreach(LineItem lineItem in purchaseOrder.Items)
            {
                loop = transaction.AddLoop("PO1");
                loop.SetElement(1, count++);
                loop.SetElement(2, lineItem.Quantity);
                loop.SetElement(3, "EA");
                loop.SetElement(4, lineItem.Price);
                loop.SetElement(6, "CGT");
                loop.SetElement(7, lineItem.SupplierItemNumber);
            }

            loop = transaction.AddLoop("CTT");
            loop.SetElement(1, --count);

            var x12 = interchange.SerializeToX12(true);
            Console.WriteLine(x12);
            // Write the string to a file.
            fileName += purchaseOrder.Number + ".850";
            System.IO.StreamWriter file = new System.IO.StreamWriter(fileName);
            file.WriteLine(x12);

            file.Close();
        }
Example #10
0
        public void CreatePurchaseOrder850()
        {
            DateTime purcaseOrderDate = DateTime.Now;
            Interchange interchange = new Interchange(purcaseOrderDate, 245, true)
            {
                InterchangeSenderIdQualifier = "01",
                InterchangeSenderId = "828513080",
                InterchangeReceiverIdQualifier = "01",
                InterchangeReceiverId = "001903202U",
                InterchangeDate = purcaseOrderDate,
            };

            interchange.SetElement(14, "0"); //No Aknowlegement is 0

            FunctionGroup group = interchange.AddFunctionGroup("PO", purcaseOrderDate, 1, "005010X222");
            group.ApplicationSendersCode = "828513080";
            group.ApplicationReceiversCode = "001903202U";
            group.Date = purcaseOrderDate;
            group.ControlNumber = 245;

            Transaction transaction = group.AddTransaction("850", "0001");

            Segment bhtSegment = transaction.AddSegment("BEG");
            bhtSegment.SetElement(1, "00");
            bhtSegment.SetElement(2, "SA");
            bhtSegment.SetElement(3, "S41000439");
            bhtSegment.SetElement(5, "20100810");

            bhtSegment = transaction.AddSegment("CUR");
            bhtSegment.SetElement(1, "BY");
            bhtSegment.SetElement(2, "USD");

            bhtSegment = transaction.AddSegment("PER");
            bhtSegment.SetElement(1, "IC");
            bhtSegment.SetElement(2, "Doe,Jane");
            bhtSegment.SetElement(8, "Doe,Jane");

            // Bill to address
            Loop loop= transaction.AddLoop("N1");
            loop.SetElement(1, "BT");
            loop.SetElement(2,"Doe Jane");
            loop.SetElement(3, 92);
            loop.SetElement(4, 10001);
            Segment segment=loop.AddSegment("N3");
            segment.SetElement(1, "Street");
            segment.SetElement(2, "City State Pin Country");
            segment = loop.AddSegment("N4");
            segment.SetElement(1,"City");
            segment.SetElement(2,"SS");
            segment.SetElement(3,"PIN");
            segment.SetElement(4,"SC");

            // ship to address
            loop = transaction.AddLoop("N1");
            loop.SetElement(1, "ST");
            loop.SetElement(2, "Doe Jane");
            loop.SetElement(3, 92);
            loop.SetElement(4, 10001);

            segment = loop.AddSegment("N3");
            segment.SetElement(1, "Street");
            segment.SetElement(2, "City State Pin Country");
            segment = loop.AddSegment("N4");
            segment.SetElement(1, "City");
            segment.SetElement(2, "SS");
            segment.SetElement(3, "PIN");
            segment.SetElement(4, "SC");

            // add products ordered

            loop = transaction.AddLoop("PO1");
            loop.SetElement(1,"1");
            loop.SetElement(2, 10);
            loop.SetElement(3, "EA");
            loop.SetElement(4, "10.2");
            loop.SetElement(6, "IB");
            loop.SetElement(7,"100001");

            var x12 = interchange.SerializeToX12(true);
            Console.WriteLine(x12);
        }