电子数据交换EDI 835 的处理

电子数据交换 (EDI) 835

电子数据交换 (EDI) 835 医疗保健索赔付款和汇款通知

电子数据交换 835 专注于交换医疗保健付款和福利信息。HIPAA 标准的更新版本 HIPAA 5010 指定了此交易集的格式、结构、数据字段和元素。医疗保险计划在与医疗保健提供者沟通以付款、提供福利说明 (EOB) 或两者结合时使用此文档。它包含以下信息:

  • 费用详情(已支付、拒绝或减少的费用)
  • 关于免赔额、共付额或共同保险的信息(如果适用)
  • 是否有任何索赔或项目被捆绑或拆分
  • 付款是直接从保险提供商支付给医疗保健提供商还是间接支付(通过清算机构)

前些年,俺们做过Billing服务,就是帮美国的医院处理一些医保的工作。有点类似国内的医保科把事情外包出去。每笔报销收取报销金额3%-5%的作为服务费。下面那个图就是当时的流程设计。前几年,俺们又开始接触国内的医保,感觉国内的医保比美国领先10年。就是很多东西不规范,还有郁闷的异地医保。美国那边的医保是个奇葩,协议啊,标准啊,这些很规范,大家也遵循,对接也简单。病人的各种数据生成文本文件(EDI HL7)丢过去就ok。国内的东软、中软还有各个市的协议各不相同(题外话,国内医保一般是dll。上饶的那个医保dll超级简单,俺曾经拿到dll后几个小时内就写了一个医保模拟器,还写了一个医保接口)。美国的医保的方式非常多,有些公司只接受 纸张的(CMS1500红纸 套打)。另外流程也极其不规范。

举个例子:

一个病人离开医院3个星期了,美国保险公司才返回报销结果。病人知道了报销金额,打电话到医保公司吵了一架,吵架的目的是要求多报销点。过了几天,保险公司又给出了最新的结果,比原来多报销了15块钱。又过了2月,医院又收到这个保险公司的新的消息,上次那个多报销15块的要撤作废,医保公司最多只能报销10块钱,请医院返5块钱回去。在对账时那个郁闷啊,今天的账平了,明天说不定还会倒找钱出去。

再举个例子:

联邦保险 州保险 第二保险 第三保险 穷人免除其他金额。反正那个乱啊。有时几个保险公司之间扯很多天。

使用OopFactory.X12解析 EDI 835数据

string x12 = System.IO.File.ReadAllText(fn);

X12EdiParsingService edip = new X12EdiParsingService(true);

string xml = edip.Transform(x12);

cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OopFactory.X12.Parsing;
using OopFactory.X12.Parsing.Model;
using OopFactory.X12.Transformations;
using System.Xml;
using System.Data;

namespace Business.Billing
{
    public class AdjustmentItem
    {
        public string GroupCode = "";
        public string Group = "";
        public string ReasonCode = "";
        public string Amount = "";
        public string paynote = "";
    }
    public class EDITranItem
    {
        public string SvcDate = "";
        public string CPT = "";
        public string CPT_Seq ="1" ;
        public string Modifiers = "";
        public string ChargeAmt = "";
        public string PaymentAmt = "";
        public string TotalAdjAmt = "";
        public string Remarks = "";
        public List<AdjustmentItem> AdjustmentItems = new List<AdjustmentItem>();
        public string AllowedAmount = "";
        public string Deductible = "";
        public string Reduction = "";
        public string Copay = "";
        public string CoInsurance = "";
        public string Other_pay = "";
        public string Capitation_amount = "";
        public string Adjustment = "";
        public string Balance = "";
        public string OtherAdjustment = "";
        public string LQ = "";
        public Boolean is_capitation()
        {
            foreach (AdjustmentItem i in AdjustmentItems)
            {
                if ((i.GroupCode == "CO") && (i.ReasonCode == "24"))
                {
                    return true;
                }
            }
            return false;
        }
    }
    public class EDITran
    {
        public string Date;
        public string Check;
        public string PatientID;
        public string Last;
        public string First;
        public string NPIorTaxID;
        public string Payee;
        public string ChargeAmt;
        public string PaymentAmt;
        public string Accnt;
        public string Status;
        public string Payer;
        public string PayerID;
        public string claim_status;
        public string PayerClaimControlNumber;
        public string forwarded_payer;
        public string note;
        public EDITranItem note_item =null;
        public List<EDITranItem> Items = new List<EDITranItem>();
        public void add_EDITran(EDITran v)
        {
            Items.AddRange(v.Items);
            if (v.Check != "")
            {
                if (Check != "")
                    Check = v.Check + ",";
                Check = Check + v.Check;
            }
        }
      
        public string get_acct_code()
        {
            if (string.IsNullOrEmpty(Accnt))
                return "";
            if (Accnt.Length < 4)
                return "";
            return Accnt.Substring(0, 4);
        }
        public string get_claim_no()
        {
            if (Accnt.Length < 12)
                return "";
            return Accnt.Substring(4, 8);
        }
        public Boolean is_job_no()
        {
            if (Accnt.Length == 12)
                return true;

            return false;
        }
        public void move_CoInsurance_to_Reduction_Discount()
        {
            foreach (EDITranItem ei in Items)
            {
                if (ei.CoInsurance == "")
                    continue;
                if (ei.CoInsurance == "0")
                    continue;
                if (ei.CoInsurance == "0.00")
                    continue;

                foreach (AdjustmentItem ai in ei.AdjustmentItems)
                {
                    if (string.Compare(ai.GroupCode + ai.ReasonCode, "OA209", true) == 0)
                    {
                        ei.Reduction = EDI.add_float_str(ei.Reduction,ai.Amount);
                        ei.CoInsurance = EDI.add_float_str(ei.CoInsurance, "-"+ai.Amount);
                    }
                }
            }
        }
    }
    public class EDI
    {
        public static Dictionary<string, string> txt2dict(string txt)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            string sp = "------------------------------";
            string[] lines = txt.Split(new string[] { sp }, StringSplitOptions.RemoveEmptyEntries);
            string check_str = "";
            foreach (string s in lines)
            {
                string pn_k = "Payer Claim Control Number:";
                int i = s.IndexOf(pn_k);
                if (i > 0)
                {
                    string pn = s.Substring(i + pn_k.Length);
                    pn = pn.Trim();
                    i = pn.IndexOf("\r");
                    if (i > 0)
                        pn = pn.Substring(0, i).Trim();
                    i = pn.IndexOf("  ");
                    if (i > 0)
                        pn = pn.Substring(0, i).Trim();
                    string t = s;
                    i = t.IndexOf("--");
                    if (i == 0)
                        t = t.Substring(2);
                    string before = "";
                    if (dict.ContainsKey(pn.Trim().ToUpper()))
                    {
                        before = dict[pn.Trim().ToUpper()];
                        if (before != "")
                            before = before + "\r\n--------------------------------------------------------------------------------------------------------------------------------------------------------\r\n";
                    }
                    dict[pn.Trim().ToUpper()] = before+t;
                     
                } else {
                    i = s.IndexOf("NPI or Tax ID");
                    if (i > 0)
                    {
                        if (check_str == "")
                            check_str = s;
                    }
                }
            }
            int ni = check_str.IndexOf("==================================================");
            if (ni > 0)
                check_str = check_str.Substring(ni);

            string[] cs = check_str.Split(new string[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
            int c_idx_begin = 0;
            for (int m = 0; m <= cs.Length; m++)
            {
                if (cs[m].IndexOf("Check#") >= 0)
                {
                    c_idx_begin = m + 2;
                    break;
                }
            }
            Dictionary<string, string> dict_cs = new Dictionary<string, string>();
            for (int k= c_idx_begin;k<cs.Length;k++)
            {
                StringBuilder sb = new StringBuilder();
                if (c_idx_begin >= 3)
                {
                    sb.AppendLine("==================================================");
                    sb.AppendLine("------- HEALTH CARE CLAIM PAYMENT/ADVICE -------");
                    sb.AppendLine("==================================================");
                    for (int m = c_idx_begin-3; m < c_idx_begin; m++)
                        sb.AppendLine(cs[m]);
                }
                sb.AppendLine(cs[k]);
                string s = cs[k].Trim();
                int n = s.IndexOf(" ");
                if (n>0)
                {
                    s = s.Substring(0, n);
                }
                dict_cs[s] = sb.ToString();

            }
            Dictionary<string, string> dict_pn_check = new Dictionary<string, string>();
            foreach (KeyValuePair<string,string> kv in dict )
            {
                string c = "";
                string v = kv.Value;
                int k = v.IndexOf("Check#");
                if (k>=0)
                {
                    k = v.IndexOf("\r", k + 1);
                    if (k>=0)
                    {
                        c = v.Substring(k).Trim();
                        k = c.IndexOf(" ");
                        if (k>=0)
                        {
                            c = c.Substring(0, k);
                        }
                    }
                }
                if (c == "")
                    continue;
                dict_pn_check[kv.Key] = c;
            }
            foreach (KeyValuePair<string, string> kv in dict_pn_check)
            {
                if (dict_cs.ContainsKey(kv.Value))
                {
                    string s = dict_cs[kv.Value] + "\r\n--------------------------------------------------------------------------------------------------------------------------------------------------------\r\n" + dict[kv.Key];
                    dict[kv.Key] = s;
                }
            }
            return dict;
        }
        public static string add_float_str( string s1,string s2)
        {
            float f1 = 0;
            if (!float.TryParse(s1, out f1))
                f1 = 0;
            float f2 = 0;
            if (!float.TryParse(s2, out f2))
                f2 = 0;
            return (f1 + f2).ToString("0.00");
        }
        public static string get_real_modify(string v, List<string> Ignore_Modify_List)
        {
            if (Ignore_Modify_List.IndexOf(v.Trim().ToUpper() )>= 0)
                return "";
            return v;
        }
        public static Boolean import_edi(Business.UserLoginData loginUser, EDITran edi, string cpt_batchid, string FindPayerByTaxID,string Ignore_Modify, out bool will_set_revise_payment, out string msg)
        {
            msg = "";
            will_set_revise_payment = false;
            Boolean result = false;
            string acct_code = edi.get_acct_code();
            string claim_no = edi.get_claim_no();
            string payer_flag = "";
            List<string> Ignore_Modify_List = new List<string>();
            string[] ssim = Ignore_Modify.Split(new string[] { " ", ",", ";", "\t", "\r", "\n", "|" }, StringSplitOptions.RemoveEmptyEntries);
            foreach(string im in ssim)
            {
                if (im.Trim() != "")
                    Ignore_Modify_List.Add(im.Trim().ToUpper());
            }

            bool is_Revise_payment = false;
            if (!EDI.ClaimStatus.TryGetValue(edi.claim_status, out payer_flag))
                payer_flag = "";
            if (acct_code == "")
            {
                msg = "Acct Code is Empty (" + edi.Accnt + ")";
                return result;
            }
            if (claim_no == "")
            {
                msg = "Claim # is Empty (" + edi.Accnt + ")";
                return result;
            }
            if (edi.is_job_no())
            {
                msg = "Claim # is Job  (" + edi.Accnt + ")";
                return result;
            }
            string select_claim_no = DBUtils.select_str_Gene(loginUser, "select claim_no from " + Business.Billing.Common.get_bill_table(acct_code, "claims") + " where claim_no=" + DBUtils.QuotedStr(claim_no));
            if (string.IsNullOrEmpty(select_claim_no))
            {
                msg = "The claim(" + acct_code + claim_no + ") not exists.";
                return result;
            }
                       
            DataRow datarow_claim_old = Business.Billing.Claim.get_claim(loginUser, acct_code, claim_no);
            string claim_status = DBUtils.get_str(datarow_claim_old, "status");
            string payment_pay_status = "";
            string payment_no = "";// DBUtils.select_str_Gene(loginUser, "select payment_no from " + Business.Billing.Common.get_bill_table(acct_code, "payment") + " where claim_no=" + DBUtils.QuotedStr(claim_no) + " and isnull(payment.payer,'')=" + DBUtils.QuotedStr(edi.Payer) + " and isnull(payer_flag,'')=" + DBUtils.QuotedStr(payer_flag));
            //For each ERA posting, we will need to always create a new payment


            Boolean is_Reversal_of_Previous_Payment = false;
            string old_claim_status = edi.claim_status;
            if (edi.claim_status == "22")//'Reversal of Previous Payment'
            {
                payment_no = "";// DBUtils.select_str_Gene(loginUser, "select payment_no from " + Business.Billing.Common.get_bill_table(acct_code, "payment") + " where claim_no=" + DBUtils.QuotedStr(claim_no) + " and isnull(payment.payer,'')=" + DBUtils.QuotedStr(edi.Payer) + " and isnull(payer_flag,'')<>" + DBUtils.QuotedStr("Reversal of Previous Payment"));
                //For each ERA posting, we will need to always create a new payment
                is_Reversal_of_Previous_Payment = true;

                if ((string.Compare(claim_status, "Deleted", true) == 0) || (string.Compare(claim_status, "Denied", true) == 0) || (string.Compare(claim_status, "Write-Off", true) == 0) || (string.Compare(claim_status, "Completed", true) == 0))
                {
                    is_Revise_payment = true;
                    will_set_revise_payment = true;
                    payment_no = "";
                }
                if (payment_no != "")
                {
                    payment_pay_status = DBUtils.select_str_Gene(loginUser, "select pay_status from " + Business.Billing.Common.get_bill_table(acct_code, "payment") + " where payment_no=" + DBUtils.QuotedStr(payment_no));
                    if ((string.Compare(payment_pay_status, "Completed", true) == 0) || (string.Compare(payment_pay_status, "Deleted", true) == 0))
                    {
                        is_Revise_payment = true;
                        will_set_revise_payment = true;
                        payment_no = "";
                    }
                    if ((edi.PaymentAmt.IndexOf("-")>=0)|| (edi.PaymentAmt== "0"))
                    {
                        is_Revise_payment = true;
                        will_set_revise_payment = true;
                        payment_no = "";
                    }
                }
            }
            else
            {
                if ((string.Compare(claim_status, "Deleted", true) == 0) || (string.Compare(claim_status, "Denied", true) == 0) || (string.Compare(claim_status, "Write-Off", true) == 0) || (string.Compare(claim_status, "Completed", true) == 0))
                {
                    bool have_old_check = false;
                    DataTable dt_p_old = DBUtils.select_Gene(loginUser, "select * from " + Business.Billing.Common.get_bill_table(acct_code, "payment") + " where claim_no=" + DBUtils.QuotedStr(claim_no));
                    foreach (DataRow dr in dt_p_old.Rows)
                    {
                        string s_check = DBUtils.get_str(dr, "ticketnumber");
                        if (s_check != "")
                            if (string.Compare(s_check, edi.Check, true) == 0)
                            {
                                have_old_check = true;
                                break;
                            }
                    }
                    if (!have_old_check)
                    {
                        is_Revise_payment = true;
                        will_set_revise_payment = true;
                        payment_no = "";
                    }
                    else
                    {
                        is_Revise_payment = true;
                        will_set_revise_payment = true;
                        msg = "The claim " + claim_no + " is " + claim_status + ".";
                    }
                }
                if (payment_no != "")
                {
                    payment_pay_status = DBUtils.select_str_Gene(loginUser, "select pay_status from " + Business.Billing.Common.get_bill_table(acct_code, "payment") + " where payment_no=" + DBUtils.QuotedStr(payment_no));
                    //if ((string.Compare(payment_pay_status, "Completed", true) == 0) || (string.Compare(payment_pay_status, "Deleted", true) == 0))
                    //{ 
                    //    is_Revise_payment = true;
                    //    will_set_revise_payment = true;
                    //    payment_no = "";
                    //}
                }
            }
            {//if the patient has "Active" Secondary Insurance, then we need to post this "OA 209" amount to "CoInsurance" field so biller can bill the secondary insurance, but if the patient don't have secondary insurance, then put this amount into "Reduction/Discount" field
                string job_no = DBUtils.select_str_Gene(loginUser, "select job_no from " + Business.Billing.Common.get_bill_table(acct_code, "claims") + " where claim_no=" + DBUtils.QuotedStr(claim_no));
                string mr_no = DBUtils.select_str_Gene(loginUser, "select mr_no from " + Business.Billing.Common.get_bill_table(acct_code, "BillingJob") + " where job_no=" + DBUtils.QuotedStr(job_no));
                string Secondary_Insurance = DBUtils.select_str_Gene(loginUser, "select mr_no from " + Business.Billing.Common.get_bill_table(acct_code, "PatInsurance") + " where  status=1 and insurance_level='Secondary' and mr_no=" + DBUtils.QuotedStr(mr_no));
                if (Secondary_Insurance == "")
                {
                    edi.move_CoInsurance_to_Reduction_Discount();
                }
            }
            string postingdate = edi.Date;
            string payertype = "I";
            string paymentmethod = "K";
            string ticketnumber = edi.Check;
            string paymentamount = "";
            string unappliedamount = "";
            string appliedpaymentamount = "";
            string refundstotalamount = "";
            string capitatedtotalamount = "";
            string adjustmentstotalamount = "";
            string allowableamount = "";
            string adjudicationdate = DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss");
            string balance = "";
            string copay = "";
            string coinsurance = "";
            string description = "";
            string reduction = "";
            string deductible = "";
            string insur_fullname = "";
            string Group_no = "";
            string Group_Name = "";
            DataRow dr_claim = Business.Billing.Common.get_dr_by_claim_no(loginUser, acct_code, claim_no);
            Dictionary<string, object> dict = new Dictionary<string, object>();
            if (dr_claim != null)
            {
                string mr_no = DBUtils.get_str(dr_claim, "mr_no");
                int totalCount = 0;
                DataTable dt = Business.Billing.Common.select_patient_insurance(loginUser, acct_code, mr_no, "", "", DBUtils.get_str(dr_claim, "address_payer_id"), "", "", "", "", 0, 2000, out totalCount);
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    Group_no = DBUtils.get_str(dr, "Group_no");
                    Group_Name = DBUtils.get_str(dr, "Group_Name");
                    insur_fullname = DBUtils.get_str(dr, "healthplan");
                }
            }
            if (payment_no != "")
            {
                DataRow dr = DBUtils.select_dr_Gene(loginUser, "select * from " + Business.Billing.Common.get_bill_table(acct_code, "payment") + " where payment_no=" + DBUtils.QuotedStr(payment_no));
                if (dr != null)
                {
                    Group_no = DBUtils.get_str(dr, "Group_no");
                    Group_Name = DBUtils.get_str(dr, "Group_Name");
                    insur_fullname = DBUtils.get_str(dr, "insur_fullname");
                }
            }
            else
            {
                string insurance_level = "";
                if (payer_flag.ToLower().IndexOf("Primary".ToLower()) >= 0)
                    insurance_level = "Primary";
                if (payer_flag.ToLower().IndexOf("Secondary".ToLower()) >= 0)
                    insurance_level = "Secondary";
                string mr_no = DBUtils.get_str(dr_claim, "mr_no");
                DataTable dt = DBUtils.select_Gene(loginUser, "select * from " + Business.Billing.Common.get_bill_table(acct_code, "PatInsurance") + " where mr_no=" + DBUtils.QuotedStr(mr_no) + " and insurance_level=" + DBUtils.QuotedStr(insurance_level));
                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    Group_no = DBUtils.get_str(dr, "Group_no");
                    Group_Name = DBUtils.get_str(dr, "Group_Name");
                    insur_fullname = DBUtils.get_str(dr, "healthplan");
                }
            };
            msg = "Acct Code:" + acct_code + " Claim#:" + claim_no;
            float float_sum_billed = 0;
            float float_sum_applied = 0;
            float float_sum_deductible = 0;
            float float_sum_reduction = 0;
            float float_sum_other = 0;
            float float_sum_coinsurance = 0;
            float float_sum_adjustment = 0;
            float float_sum_allowableamount = 0;
            float float_sum_item_balance = 0;
            List<Dictionary<string, string>> detail = new List<Dictionary<string, string>>();
            DataTable dt_payment_default = Business.Billing.Pay.get_payment_default(loginUser, acct_code, claim_no, "");
            DataTable dt_payment_detail = Business.Billing.Pay.get_payment_default(loginUser, acct_code, claim_no, payment_no);
            foreach (DataRow row in dt_payment_detail.Rows)
            {
                Dictionary<string, string> dr = new Dictionary<string, string>();
                row2dict(row, dr);
                detail.Add(dr);
                string s_p = DBUtils.get_str(row, "payment_no");
                if (s_p == "")
                    dr["billed"] = "0";
            }
            Dictionary<string, int> dict_c_k = new Dictionary<string, int>();
            foreach (DataRow row in dt_payment_default.Rows)
            {
                Dictionary<string, string> dr = new Dictionary<string, string>();
                string key = DBUtils.get_str(row, "code") + "|"+ get_real_modify(DBUtils.get_str(row, "modifiers"),Ignore_Modify_List) + "|" + DBUtils.get_str_date_format(row, "date_of_svc_from", "MM/dd/yyyy");
                string seq="1";
                if (dict_c_k.ContainsKey(key))
                {
                    seq = (dict_c_k[key] + 1).ToString();
                } else
                {
                    seq = "1";
                }
                dict_c_k[key] = int.Parse(seq);
                int idx = indexofcode(detail, DBUtils.get_str(row, "code"), DBUtils.get_str(row, "modifiers"), DBUtils.get_str_date_format(row, "date_of_svc_from", "MM/dd/yyyy"), seq,Ignore_Modify_List);
                if (idx < 0)
                {
                    row2dict(row, dr);
                    dr["applied"] = "0";
                    dr["billed"] = "0";
                    detail.Add(dr);
                }
               
            }

            Dictionary<string, EDITranItem> dict_ei = new Dictionary<string, EDITranItem>();
            for (int i = 0; i < edi.Items.Count; i++)
            {
                Dictionary<string, string> dr = null;
                EDITranItem ei = edi.Items[i];
                int idx = indexofcode(detail, ei.CPT, ei.Modifiers, ei.SvcDate,ei.CPT_Seq,Ignore_Modify_List);
                if (idx < 0)
                {
                    dr = new Dictionary<string, string>();
                    dr["line_item_id"] = (detail.Count + 1).ToString();
                    dr["code"] = ei.CPT;
                    dr["units"] = "";
                    dr["units_price"] = "";
                    dr["allowable"] = "";
                    dr["reduction"] = "";
                    dr["adjustment"] = ei.Adjustment;
                    dr["other_pay"] = ei.Other_pay;
                    dr["capitation_amount"] = ei.Capitation_amount;
                    dr["item_balance"] = ei.Balance;
                    dr["capitation"] = "0";
                    dr["batch_no"] = cpt_batchid;
                    dr["date_of_svc_from"] = ei.SvcDate;
                    dr["date_of_svc_to"] = ei.SvcDate;                   

                    dr["billed"] ="0";
                    dr["applied"] = "0";
                    dr["deductible"] = "0";
                    dr["reduction"] = "0";
                    dr["other"] = "0";
                    dr["coinsurance"] = "0";
                    dr["allowable"] = "0";
                    dr["adjustment"] = "0";
                    dr["other_pay"] = "0";
                    dr["capitation_amount"] = "0";
                    dr["item_balance"] = "0";

                    detail.Add(dr);
                }
                else
                {
                    dr = detail[idx];
                    dr["batch_no"] = cpt_batchid;
                }
                dict_ei[dr["line_item_id"]] = ei;
                dr["modifiers"] = ei.Modifiers;
                
                //2017-11-07
                Boolean will_add_to_old = false;
                if ((is_Reversal_of_Previous_Payment) && (payment_no != ""))
                    will_add_to_old = true;
                if (! (will_add_to_old))
                {
                    dr["billed"] = ei.ChargeAmt;
                    dr["applied"] = ei.PaymentAmt;
                    dr["deductible"] = ei.Deductible;
                    dr["reduction"] = ei.Reduction;
                    dr["other"] = ei.Copay;
                    dr["coinsurance"] = ei.CoInsurance;
                    if ((ei.is_capitation()))
                        dr["capitation"] = "1";
                    dr["allowable"] = ei.AllowedAmount;
                    dr["adjustment"] = ei.Adjustment;
                    dr["other_pay"] = ei.Other_pay;
                    dr["capitation_amount"] = ei.Capitation_amount;
                    dr["item_balance"] = ei.Balance;
                }
                else
                {
                    dr["billed"] = add_float_str(dr["billed"], ei.ChargeAmt); 
                    dr["applied"] = add_float_str(dr["applied"] , ei.PaymentAmt);
                    dr["deductible"] = add_float_str(dr["deductible"], ei.Deductible);
                    dr["reduction"] = add_float_str(dr["reduction"], ei.Reduction);
                    dr["other"] = add_float_str(dr["other"], ei.Copay);
                    dr["coinsurance"] = add_float_str(dr["coinsurance"], ei.CoInsurance);
                    if ((ei.is_capitation()))
                        dr["capitation"] = "1";
                    dr["allowable"] = add_float_str(dr["allowable"], ei.AllowedAmount);
                    dr["adjustment"] = add_float_str(dr["adjustment"], ei.Adjustment);
                    dr["other_pay"] = add_float_str(dr["other_pay"], ei.Other_pay);
                    dr["capitation_amount"] = add_float_str(dr["capitation_amount"], ei.Capitation_amount);
                    dr["item_balance"] = add_float_str(dr["item_balance"], ei.Balance);
                }

                float float_billed = 0;
                float float_applied = 0;
                float float_deductible = 0;
                float float_reduction = 0;
                float float_other = 0;
                float float_coinsurance = 0;
                float float_allowable = 0;
                float float_adjustment = 0;
                float float_other_pay = 0;
                float float_item_balance = 0;
                if (!float.TryParse(dr["billed"], out float_billed))
                    float_billed = 0;
                if (!float.TryParse(dr["applied"], out float_applied))
                    float_applied = 0;
                if (!float.TryParse(dr["deductible"], out float_deductible))
                    float_deductible = 0;
                if (!float.TryParse(dr["reduction"], out float_reduction))
                    float_reduction = 0;                
                if (!float.TryParse(dr["other"], out float_other))
                    float_other = 0;
                if (!float.TryParse(dr["coinsurance"], out float_coinsurance))
                    float_coinsurance = 0;
                if (!float.TryParse(dr["allowable"], out float_allowable))
                    float_allowable = 0;
                if (!float.TryParse(dr["adjustment"], out float_adjustment))
                    float_adjustment = 0;
                if (!float.TryParse(dr["other_pay"], out float_other_pay))
                    float_other_pay = 0;
                if (!float.TryParse(dr["item_balance"], out float_item_balance))
                    float_item_balance = 0;
                  float_adjustment = float_billed - float_applied - float_deductible - float_other - float_coinsurance;
                //float_adjustment = float_billed - float_allowable;
                (parseFloat(s_allowable) - parseFloat(s) - parseFloat(s_deductible) - parseFloat(s_reduction) - parseFloat(s_other) - parseFloat(s_coinsurance)
                //float_item_balance = float_allowable - float_applied - float_deductible - float_reduction- float_other - float_coinsurance;
                //dr["adjustment"] = float_adjustment.ToString("0.00");
                //dr["item_balance"] = float_item_balance.ToString("0.00");

                msg = msg + " " + ei.CPT + ":" + ei.PaymentAmt;
                string sd = "";
                if (ei.AdjustmentItems.Count > 0)
                {
                    string sr = "";
                    foreach (AdjustmentItem ai in ei.AdjustmentItems)
                    {
                        sr = DBUtils.select_str_Gene(loginUser, "select popup_name from FieldPopup where table_name='claims' and field_name='reason_code' and  field_value=" +DBUtils.QuotedStr(ai.ReasonCode));
                        if (sr.Length>100)
                        {
                            int k = sr.IndexOf(". ", 95);
                            if (k > 0)
                                sr = sr.Substring(0, k + 1);
                        }
                        
                        if (sd != "")
                            sd = sd + "; ";
                        sd = sd + ei.CPT + ":<font color='blue'>" + ai.GroupCode + " "+ ai.ReasonCode + "</font> " + sr + " (" + ai.Amount + ")";
                    }
                }
                if (ei.LQ != "")
                    sd = sd + " LQ: " + ei.LQ;
                dr["description"] = sd;
            }
            if ((detail.Count==1)&& (edi.Items.Count == 0) &&(edi.note_item!=null))
            {
                Dictionary<string, string> dr = detail[0];
                EDITranItem ei = edi.note_item;
                dr["billed"] = edi.ChargeAmt;
                dr["applied"] = edi.PaymentAmt;
                dr["deductible"] = ei.Deductible;
                dr["reduction"] = ei.Reduction;
                dr["other"] = ei.Copay;
                dr["coinsurance"] = ei.CoInsurance;
                if ((ei.is_capitation()))
                    dr["capitation"] = "1";
                dr["allowable"] = edi.PaymentAmt;
                dr["adjustment"] = ei.Adjustment;
                dr["other_pay"] = ei.Other_pay;
                dr["capitation_amount"] = ei.Capitation_amount;
                dr["item_balance"] = ei.Balance;
            }
            for (int i = 0; i < detail.Count; i++)
            {
                Dictionary<string, string> dr = detail[i];
                dr["line_item_id"] = (i + 1).ToString();
                float float_billed = 0;
                float float_applied = 0;
                float float_deductible = 0;
                float float_reduction = 0;
                float float_other = 0;
                float float_coinsurance = 0;
                float float_adjustment = 0;
                float float_allowable = 0;
                float float_item_balance = 0;
                if (!float.TryParse(dr["billed"], out float_billed))
                    float_billed = 0;
                if (!float.TryParse(dr["applied"], out float_applied))
                    float_applied = 0;
                if (!float.TryParse(dr["deductible"], out float_deductible))
                    float_deductible = 0;
                if (!float.TryParse(dr["reduction"], out float_reduction))
                    float_reduction = 0;                
                if (!float.TryParse(dr["other"], out float_other))
                    float_other = 0;
                if (!float.TryParse(dr["coinsurance"], out float_coinsurance))
                    float_coinsurance = 0;
                if (!float.TryParse(dr["allowable"], out float_allowable))
                    float_allowable = 0;
                if (!float.TryParse(dr["adjustment"], out float_adjustment))
                    float_adjustment = 0;
                if (!float.TryParse(dr["item_balance"], out float_item_balance))
                    float_item_balance = 0;

                //float_adjustment = float_billed - float_applied - float_deductible - float_other - float_coinsurance;
                dr["allowable"] = float_allowable.ToString("0.00");
                dr["adjustment"] = float_adjustment.ToString("0.00");
                dr["item_balance"] = float_item_balance.ToString("0.00");
                float_sum_billed = float_sum_billed + float_billed;
                float_sum_applied = float_sum_applied + float_applied;
                float_sum_deductible = float_sum_deductible + float_deductible;
                float_sum_reduction = float_sum_reduction + float_reduction;
                float_sum_other = float_sum_other + float_other;
                float_sum_coinsurance = float_sum_coinsurance + float_coinsurance;
                float_sum_adjustment = float_sum_adjustment + float_adjustment;
                float_sum_allowableamount = float_sum_allowableamount + float_allowable;
                float_sum_item_balance = float_sum_item_balance + float_item_balance;
            }
            paymentamount = float_sum_billed.ToString("0.00");
            appliedpaymentamount = float_sum_applied.ToString("0.00");
            deductible = float_sum_deductible.ToString("0.00");
            reduction = float_sum_reduction.ToString("0.00");
            copay = float_sum_other.ToString("0.00");
            coinsurance = float_sum_coinsurance.ToString("0.00");
            adjustmentstotalamount = float_sum_adjustment.ToString("0.00");
            allowableamount = float_sum_allowableamount.ToString("0.00");
            balance = float_sum_item_balance.ToString("0.00");
            if (edi.forwarded_payer != "")
                description = "Forwarded Payer: " + edi.forwarded_payer;
            string payment_no_saved = "";
            string msg_save = "";
            string batchid = "";
            if (payment_no != "")
            {
                batchid = DBUtils.select_str_Gene(loginUser, "select batchid from " + Business.Billing.Common.get_bill_table(acct_code, "payment") + " where payment_no=" + DBUtils.QuotedStr(payment_no));
            }
            if (edi.Items.Count== 0)
            {
                //cpt_batchid
                foreach(Dictionary<string, string> dr in detail )
                {
                    dr["batch_no"] = cpt_batchid;
                }
                string note = "";

                string[] ss = edi.note.Split(';');
                foreach(string s in ss)
                {
                    string[] ls = s.Split('|');
                    if (ls.Length>=3)
                    {
                        string GroupCode = ls[0];
                        string ReasonCode = ls[1];
                        string Amount = ls[2];
                        string sr = DBUtils.select_str_Gene(loginUser, "select popup_name from FieldPopup where table_name='claims' and field_name='reason_code' and  field_value=" + DBUtils.QuotedStr(ReasonCode));
                        if (sr.Length > 100)
                        {
                            int k = sr.IndexOf(". ", 95);
                            if (k > 0)
                                sr = sr.Substring(0, k + 1);
                        }
                        if (note != "")
                            note = note + "; ";
                        note = note + GroupCode + " " + ReasonCode +" "+ sr + " (" + Amount + ")";
                    }
                }
                description = note;
            }
            Boolean success = Business.Billing.Pay.save_payment(loginUser, payment_no, acct_code, claim_no, batchid, postingdate, payertype, paymentmethod, ticketnumber, paymentamount, adjustmentstotalamount, adjudicationdate, description, unappliedamount, appliedpaymentamount, refundstotalamount, capitatedtotalamount, balance, copay, coinsurance, deductible, reduction, insur_fullname, Group_no, Group_Name, allowableamount, out payment_no_saved, ref msg_save);
            if (payment_no_saved != "")
            {
                DBUtils.exec_Gene(loginUser, "update HOSP" + acct_code + "..payment set PayerClaimControlNumber=" + DBUtils.QuotedStr(edi.PayerClaimControlNumber) +"  where payment_no="+DBUtils.QuotedStr(payment_no_saved) );
            }
            if (FindPayerByTaxID == "1")
            {
                string TaxID = edi.PayerID;
                TaxID = TaxID.Replace("-", "").Replace(" ", "");
                if (TaxID!="")
                {                    
                    string sql_p = "select EDI_Payer_no,EDI_Payer_name from HOSP"+acct_code+ "..InsuranceMas where isnull(EDI_Payer_no,'')<>'' and  REPLACE(REPLACE(isnull(TaxID,'') ,'-',''),' ','')=" + DBUtils.QuotedStr(TaxID);
                    DataRow dr_p = DBUtils.select_dr_Gene(loginUser, sql_p);
                    if (dr_p != null)
                    {
                        string EDI_Payer_no = DBUtils.get_str(dr_p, "EDI_Payer_no");
                        string EDI_Payer_name = DBUtils.get_str(dr_p, "EDI_Payer_name");
                        if (EDI_Payer_no != "")
                        {
                            edi.PayerID = EDI_Payer_no;
                            edi.Payer = EDI_Payer_name;
                        }
                    }
                    else
                    {
                        sql_p = "select  payer_id,payer_name  from PayerList where isnull(payer_id,'')<>'' and REPLACE(REPLACE(isnull(TaxID,'') ,'-',''),' ','')=" + DBUtils.QuotedStr(TaxID);
                        dr_p = DBUtils.select_dr_Gene(loginUser, sql_p);
                        if (dr_p != null)
                        {
                            string payer_id = DBUtils.get_str(dr_p, "payer_id");
                            string payer_name = DBUtils.get_str(dr_p, "payer_name");
                            if (payer_id != "")
                            {
                                edi.PayerID = payer_id;
                                edi.Payer = payer_name;
                            }
                        }
                    }
                }
            }
            if (!is_Reversal_of_Previous_Payment)
            {
                DBUtils.exec_Gene(loginUser, "update " + Business.Billing.Common.get_bill_table_no_as(acct_code, "payment") + " set payer_id=" + DBUtils.QuotedStr(edi.PayerID) + ", payer=" + DBUtils.QuotedStr(edi.Payer) + ", payer_flag=" + DBUtils.QuotedStr(payer_flag) + " where payment_no=" + DBUtils.QuotedStr(payment_no_saved));
            } else
            {
                if (payment_no == payment_no_saved)
                {
                    DBUtils.exec_Gene(loginUser, "update " + Business.Billing.Common.get_bill_table_no_as(acct_code, "payment") + " set payer_id=" + DBUtils.QuotedStr(edi.PayerID) + ", payer=" + DBUtils.QuotedStr(edi.Payer) + " where payment_no=" + DBUtils.QuotedStr(payment_no_saved));
                } 
                else
                {
                    DBUtils.exec_Gene(loginUser, "update " + Business.Billing.Common.get_bill_table_no_as(acct_code, "payment") + " set payer_id=" + DBUtils.QuotedStr(edi.PayerID) + ", payer=" + DBUtils.QuotedStr(edi.Payer)+ ", payer_flag=" + DBUtils.QuotedStr("Reversal of Previous Payment")  + " where payment_no=" + DBUtils.QuotedStr(payment_no_saved));
                }

            }
          

            Business.Billing.Pay.check_payment_insur_health_plan(loginUser, insur_fullname);           
            Business.Billing.Pay.save_payment_detail(loginUser, acct_code, payment_no_saved, detail);
            
            foreach (KeyValuePair<string,EDITranItem> kv in dict_ei)
            {
                StringBuilder sb_ei = new StringBuilder();
                sb_ei.AppendLine("delete HOSP"+acct_code+"..payment_detail_adj where payment_no="+DBUtils.QuotedStr(payment_no_saved) +" and line_item_id="+DBUtils.QuotedStr(kv.Key));
                for(int i=0;i< kv.Value.AdjustmentItems.Count; i++)
                {
                    AdjustmentItem aji = kv.Value.AdjustmentItems[i];
                    string cpt = kv.Value.CPT;
                    sb_ei.AppendLine("insert into HOSP" + acct_code + "..payment_detail_adj (payment_no,cpt,line_item_id,idx,groupcode,reasoncode,amount,paynote) values(" + DBUtils.QuotedStr(payment_no_saved) + ","+ DBUtils.QuotedStr(cpt)+","  + DBUtils.QuotedStr(kv.Key)+ "," +DBUtils.QuotedStr(i.ToString())+","+DBUtils.QuotedStr(aji.GroupCode)+","+DBUtils.QuotedStr(aji.ReasonCode)+","+DBUtils.QuotedStr(aji.Amount)+","+DBUtils.QuotedStr(aji.paynote) + ")");
                }
                DBUtils.exec_Gene(loginUser, sb_ei.ToString());
            }

            Business.Billing.Pay.save_payment_batchid(loginUser, acct_code, payment_no_saved, batchid);
            DBUtils.exec_Gene(loginUser, "update Genedbs..ClaimPool set Payer_Claim_no=" + DBUtils.QuotedStr(edi.PayerClaimControlNumber) + " where acct_code=" + DBUtils.QuotedStr(acct_code) + " and claim_no=" + DBUtils.QuotedStr(claim_no));

            string sql_sp = Common.get_bill_sp(acct_code, "sp_payment_after_import")+" "+DBUtils.QuotedStr(payment_no_saved);
            DBUtils.exec_Gene(loginUser, sql_sp);
            Business.Billing.Pay.after_save_payment(loginUser, acct_code, payment_no_saved);

            msg = msg + " " + msg_save;
            float float_appliedpaymentamount = 0;
            float float_balance = 0;
            if (float.TryParse(appliedpaymentamount, out float_appliedpaymentamount))
                if (float.TryParse(balance, out float_balance))
                {
                    if (float_appliedpaymentamount > -0.0001)
                    {
                        if (false) //(float_balance < 0.0001)
                        {
                            string reason = "";
                            Business.Billing.Claim.claim_denied_complete_partial(loginUser, loginUser.UserId, acct_code, claim_no, reason, "Completed", false, false);
                            msg = msg + " " + "Claim status change to 'Completed'.";
                        }
                        else
                        {
                            string reason = "";
                            DataRow dr_claim_old = Business.Billing.Claim.get_claim(loginUser, acct_code, claim_no);
                            if (dr_claim_old != null)
                            {
                                string status = DBUtils.get_str(dr_claim_old, "status");
                                //if ((string.Compare(status, "Submitted", true) == 0)
                                //    || (string.Compare(status, "Transmitted", true) == 0)
                                //    || (string.Compare(status, "Accepted", true) == 0)
                                //    || (string.Compare(status, "Pending", true) == 0)
                                //    || (string.Compare(status, "Rejected", true) == 0)
                                //    || (string.Compare(status, "Processing", true) == 0)
                                //)
                                    Business.Billing.Claim.claim_denied_complete_partial(loginUser, loginUser.UserId, acct_code, claim_no, reason, "Partial", false, false);
                            }
                            msg = msg + " " + "Claim status change to 'Partial/in Appeal'.";
                        }
                    }
                }
            if (is_Revise_payment)
            {
                string reason = "";
                Business.Billing.Claim.claim_denied_complete_partial(loginUser, loginUser.UserId, acct_code, claim_no, reason, "Partial", false, false);

                //2017-11-28
                if (is_Reversal_of_Previous_Payment)
                {
                    if (payment_no == payment_no_saved)
                    {
                        DBUtils.exec_Gene(loginUser, "update " + Business.Billing.Common.get_bill_table_no_as(acct_code, "payment") + " set pay_status=null  where payment_no=" + DBUtils.QuotedStr(payment_no_saved));
                    } else {
                        DBUtils.exec_Gene(loginUser, "update " + Business.Billing.Common.get_bill_table_no_as(acct_code, "payment") + " set pay_status=null,payer_flag='Reversal of Previous Payment'  where payment_no=" + DBUtils.QuotedStr(payment_no_saved));
                    }
                    DBUtils.exec_Gene(loginUser, "update ClaimPool set paymentchangedate=getdate() where acct_code=" + DBUtils.QuotedStr(acct_code) + " and claim_no=" + DBUtils.QuotedStr(claim_no));
                }
                else
                {
                    string str_tmp_p = "Revised Payment";
                    string old_s = "";
                    if (!EDI.ClaimStatus.TryGetValue(edi.claim_status, out old_s))
                        old_s = "";
                    if (old_s.ToLower().IndexOf("Primary".ToLower()) >= 0)
                        str_tmp_p = "Processed as Primary, Revised";
                    if (old_s.ToLower().IndexOf("Secondary".ToLower()) >= 0)
                        str_tmp_p = "Processed as Secondary, Revised";
                    if (old_s.ToLower().IndexOf("Denied".ToLower()) >= 0)
                        str_tmp_p = "Denied";
                    DBUtils.exec_Gene(loginUser, "update " + Business.Billing.Common.get_bill_table_no_as(acct_code, "payment") + " set pay_status=null, payer_flag="+DBUtils.QuotedStr(str_tmp_p)+"  where payment_no=" + DBUtils.QuotedStr(payment_no_saved));
                    DBUtils.exec_Gene(loginUser, "update ClaimPool set paymentchangedate=getdate() where acct_code=" + DBUtils.QuotedStr(acct_code) + " and claim_no=" + DBUtils.QuotedStr(claim_no));
                }
                if (old_claim_status == "22")
                {
                    DBUtils.exec_Gene(loginUser, "update " + Business.Billing.Common.get_bill_table_no_as(acct_code, "payment") + " set payer_flag=" + DBUtils.QuotedStr("Reversal of Previous Payment") + " where payment_no=" + DBUtils.QuotedStr(payment_no_saved));

                }

                string job_no = DBUtils.select_str_Gene(loginUser ,"select job_no from HOSP"+acct_code+"..claims where claim_no="+DBUtils.QuotedStr(claim_no));
                // Billing.Common.restore_job(loginUser,acct_code,job_no);
                string sql_job = " update HOSP" + acct_code + "..BillingJob set status=4 where job_no=" + DBUtils.QuotedStr(job_no);
                DBUtils.exec_Gene(loginUser, sql_job);
                string payment_status = DBUtils.select_str_Gene(loginUser, "select payment_status from HOSP" + acct_code + "..BillingJob where job_no=" + DBUtils.QuotedStr(job_no));
                if (string.Compare(payment_status, "Completed", true)==0)
                {
                    string sql = "update " + Billing.Common.get_bill_table_no_as(acct_code, "BillingJob") + "  set payment_status=null where job_no=" + DBUtils.QuotedStr(job_no);
                    DBUtils.exec_Gene(loginUser, sql);
                    Business.Billing.Claim.save_claim_note(loginUser, loginUser.UserId, "", acct_code, job_no, claim_no, "Undo 'Complete Job' by Payment Poster", "");
                    DBUtils.exec_Gene(loginUser, "update ClaimPool set paymentchangedate=getdate() where acct_code=" + DBUtils.QuotedStr(acct_code) + " and claim_no=" + DBUtils.QuotedStr(claim_no));
                }

            }
            else
            {
                if (old_claim_status == "22")
                {
                    DBUtils.exec_Gene(loginUser, "update " + Business.Billing.Common.get_bill_table_no_as(acct_code, "payment") + " set payer_flag=" + DBUtils.QuotedStr("Reversal of Previous Payment") + " where payment_no=" + DBUtils.QuotedStr(payment_no_saved));

                }
            }
            
            result = true;
            return result;
        }

     
        public static string get_key(string v)
        {
            string s = v;
            s = s.Replace(" ", "");
            s = s.Replace(",", "");
            s = s.Replace(";", "");
            s = s.Replace("|", "");
            s = s.ToLower();
            return s;
        }
        public static int indexofcode(List<Dictionary<string, string>> list, string code, string modifiers, string srvc_date,string seq, List<string> Ignore_Modify_List)
        {
            int c = 0;
            for (int i = 0; i < list.Count; i++)
            {
                if ((string.Compare(code, list[i]["code"], true) == 0)
                     && (string.Compare(   get_key(get_real_modify(modifiers,Ignore_Modify_List)), get_key(get_real_modify( list[i]["modifiers"],Ignore_Modify_List)), true) == 0)
                     && (string.Compare(srvc_date, list[i]["date_of_svc_from"], true) == 0))
                {
                    if ((seq == "") || (seq == "1"))
                    {
                        return i;
                    }
                    c = c + 1;
                    if (c.ToString() == seq)
                    {
                        return i;
                    }
                }
            }
            return -1;
        }
        public static void row2dict(DataRow row, Dictionary<string, string> dr)
        {
            dr["line_item_id"] = DBUtils.get_str(row, "line_item_id");
            dr["code"] = DBUtils.get_str(row, "code");
            dr["modifiers"] = DBUtils.get_str(row, "modifiers");
            dr["units"] = DBUtils.get_str(row, "units");
            dr["units_price"] = DBUtils.get_str(row, "units_price");
            dr["billed"] = DBUtils.get_str(row, "billed");
            dr["allowable"] = DBUtils.get_str(row, "allowable");
            if (DBUtils.get_str(row, "allowable") == "")
                dr["allowable"] = "0.00";
            dr["applied"] = DBUtils.get_str(row, "applied");
            dr["deductible"] = DBUtils.get_str(row, "deductible");
            dr["reduction"] = DBUtils.get_str(row, "reduction");
            dr["other"] = DBUtils.get_str(row, "other");
            dr["coinsurance"] = DBUtils.get_str(row, "coinsurance");
            dr["adjustment"] = DBUtils.get_str(row, "adjustment");
            dr["item_balance"] = DBUtils.get_str(row, "item_balance");
            dr["date_of_svc_from"] = DBUtils.get_str_date_format(row, "date_of_svc_from", "MM/dd/yyyy");
            dr["date_of_svc_to"] = DBUtils.get_str_date_format(row, "date_of_svc_to", "MM/dd/yyyy");


            dr["capitation"] = "";
            if (row.Table.Columns.Contains("capitation"))
                dr["capitation"] = DBUtils.get_str(row, "capitation");

            dr["batch_no"] = "";
            if (row.Table.Columns.Contains("batch_no"))
                dr["batch_no"] = DBUtils.get_str(row, "batch_no");

            dr["description"] = "";
            if (row.Table.Columns.Contains("description"))
                dr["description"] = DBUtils.get_str(row, "description");

            dr["other_pay"] = "";
            if (row.Table.Columns.Contains("other_pay"))
                dr["other_pay"] = DBUtils.get_str(row, "other_pay");

            dr["capitation_amount"] = "";
            if (row.Table.Columns.Contains("capitation_amount"))
                dr["capitation_amount"] = DBUtils.get_str(row, "capitation_amount");

        }
        public static string editoxml(string x12)
        {
            X12EdiParsingService edip = new X12EdiParsingService(true);
            string xml = edip.Transform(x12);
            return xml;
        }
        public static string editohtml(string x12)
        {
            var htmlService = new X12HtmlTransformationService(new X12EdiParsingService(suppressComments: true));

            string html = htmlService.Transform(x12);
            return html;
        }
        public static string getnode_txt(XmlNode node, string path)
        {
            if (node == null)
                return "";
            XmlNode n = node.SelectSingleNode(path);
            if (n == null)
            {
                return "";
            }
            else
            {
                return n.InnerText.Trim();
            }
        }
        public static string strYYYYMMDD2date(string s)
        {
            if (string.IsNullOrEmpty(s))
                return DateTime.Now.ToString("MM/dd/yyyy");
            if (s.Length == 8)
            {
                string v = s.Substring(4, 2) + "/" + s.Substring(6, 2) + "/" + s.Substring(0, 4);
                DateTime d;
                if (DateTime.TryParse(v, out d))
                {
                    return d.ToString("MM/dd/yyyy");
                }
            }
            return DateTime.Now.ToString("MM/dd/yyyy");
        }
        public static string str2float_add(string v1,string v2)
        {
            float f1 = 0;
            float f2 = 0;
            if (!float.TryParse(v1, out f1))
                f1 = 0;
            if (!float.TryParse(v2, out f2))
                f2 = 0;
            return (f1 + f2).ToString("0.00");
        }
        public static Boolean in_code(string group, string code, string code_list)
        {
            string slist = code_list.Trim().Replace(" ", "");
            string[] ss = slist.Split(new string[] { ",", ";", "|" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string s in ss)
            {
                if (string.Compare(code, s, true) == 0)
                    return true;
                if (string.Compare(group.Trim()+code.Trim(), s, true) == 0)
                    return true;
            }
            return false;
        }
        public static Boolean in_group_code(string group, string code, string group_code_list)
        {
            string slist = group_code_list.Trim().Replace(" ", "");
            string[] ss = slist.Split(new string[] { ",", ";", "|" }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string s in ss)
            {
                if (string.Compare(group, s, true) == 0)
                    return true;
                if (string.Compare(group.Trim() + code.Trim(), s, true) == 0)
                    return true;
            }
            return false;
        }
        public static EDITran node2EDIItem(XmlNode node, string Ded_PR_Code, string Adj_PR_Code, string Red_CO_Code, string Oth_OA_Code, string Cap_CO_Code, string CoInsur_Code, string Copay_Code, string PTResp_Code, string PTResp_Group, string Adjustment_Group, string OtherAdjustment_Group)
        {
            EDITran e = new EDITran();
            e.Payer = getnode_txt(node.ParentNode.ParentNode, "Loop[@LoopId='1000B']/N1/N104");
            e.Check = getnode_txt(node.ParentNode.ParentNode.SelectSingleNode("TRN"), "TRN02");
            e.Date = strYYYYMMDD2date(getnode_txt(node.ParentNode.ParentNode.SelectSingleNode("BPR"), "BPR16"));
            e.PatientID = getnode_txt(node, "NM1/NM109");
            e.Last = getnode_txt(node, "NM1/NM103");
            e.First = getnode_txt(node, "NM1/NM104");
            e.NPIorTaxID = getnode_txt(node.ParentNode.ParentNode, "Loop[@LoopId='1000B']/N1/N104");
            e.Payee = getnode_txt(node.ParentNode.ParentNode, "Loop[@LoopId='1000B']/N1/N102");
            e.ChargeAmt = getnode_txt(node, "CLP/CLP03");
            e.PaymentAmt = getnode_txt(node, "CLP/CLP04");
            e.Accnt = getnode_txt(node, "CLP/CLP01");
            e.Status = "";
            e.Payer = getnode_txt(node.ParentNode.ParentNode, "Loop[@LoopId='1000A']/N1/N102");
            e.claim_status = getnode_txt(node, "CLP/CLP02");

            e.forwarded_payer = getnode_txt(node, "NM1[NM101='TT']/NM103");

            // e.PayerID = getnode_txt(node.ParentNode.ParentNode, "Loop[@LoopId='1000A']/N4/N403");
            string taxid = getnode_txt(node.ParentNode.ParentNode, "TRN/TRN03");
            if (taxid.StartsWith("1"))
                taxid = taxid.Substring(1);
            if (taxid.Length > 2)
                taxid = taxid.Insert(2, "-");
            e.PayerID = taxid;
            e.PayerClaimControlNumber = getnode_txt(node, "CLP/CLP07");
            XmlNodeList nodelist = node.SelectNodes("Loop[@LoopId='2110']");

            Dictionary<string, int> cpt_count = new Dictionary<string, int>();
            foreach (XmlNode ni in nodelist)
            {
                EDITranItem ti = new EDITranItem();
                string s = getnode_txt(ni, "DTM/DTM02");
                if (s == "")
                    s = getnode_txt(node, "DTM/DTM02");
                ti.SvcDate = strYYYYMMDD2date(s);

                ti.CPT = getnode_txt(ni, "SVC/SVC01/SVC0102");
                ti.Modifiers = getnode_txt(ni, "SVC/SVC01/SVC0103");
                ti.ChargeAmt = getnode_txt(ni, "SVC/SVC02");
                ti.PaymentAmt = getnode_txt(ni, "SVC/SVC03");
                ti.AllowedAmount = getnode_txt(ni, "AMT/AMT02");
                string key = ti.SvcDate + "|" + ti.CPT + "|" + ti.Modifiers;
                if (cpt_count.ContainsKey(key))
                {
                    ti.CPT_Seq = (cpt_count[key] + 1).ToString();
                }
                else
                {
                    ti.CPT_Seq = "1";
                }
                cpt_count[key] = int.Parse(ti.CPT_Seq);
                XmlNodeList cas = ni.SelectNodes("CAS");
                foreach (XmlNode ci in cas)
                {

                    for (int k = 0; k < 10; k++)
                    {
                        int m = k * 3 + 2;
                        string ReasonCode = getnode_txt(ci, "CAS" + m.ToString().PadLeft(2, '0'));
                        string Amount = getnode_txt(ci, "CAS" + (m + 1).ToString().PadLeft(2, '0'));
                        if (Amount == "")
                            break;
                        AdjustmentItem ai = new AdjustmentItem();
                        ai.GroupCode = getnode_txt(ci, "CAS01");
                        ai.ReasonCode = ReasonCode;
                        ai.Amount = Amount;
                       
                        if (ai.GroupCode == "CO")
                        {
                            ai.Group = "Contractual Obligations";
                        }
                        if (ai.GroupCode == "OA")
                        {
                            ai.Group = "Other Adjustments";
                        }
                        if (ai.GroupCode == "PI")
                        {
                            ai.Group = "Payer Initiated Reductions";
                        }
                        if (ai.GroupCode == "PR")
                        {
                            ai.Group = "Patient Responsibility";
                        }
                        ti.AdjustmentItems.Add(ai);
                    }
                }

                ti.TotalAdjAmt = "";
                ti.Remarks = "";
                ti.LQ = "";
                XmlNodeList lqlist = ni.SelectNodes("LQ");
                foreach (XmlNode lq in lqlist)
                {
                    string slq = getnode_txt(lq, "LQ02");
                    if (slq != "")
                    {
                        if (ti.LQ != "")
                            ti.LQ = ti.LQ + ", ";
                        ti.LQ = ti.LQ + slq;
                    }
                }
                e.Items.Add(ti);

                //CO  - Contractual Obligations 
                // This group code should be used when a joint contractual agreement between the payer and payee, or a regulatory requirement, resulted in an adjustment. Generally, these adjustments are considered a write off for the provider and are not billed to the patient. 
                //•  OA  - Other Adjustments 
                // This group code should be used when no other group code applies to the adjustment. Refer to the ASC X12 005010X221A1 Health Care Claim Payment/Advice (835) Sections 1.10.2.6, 1.10.2.7 and 1.10.2.13 for business situations that describe the usage of the code. 
                //•  PI  - Payer Initiated Reductions 
                // This group code should be used when, in the opinion of the payer, the adjustment is not the responsibility of the patient, but there is no supporting contract between the provider and the payer (i.e., medical review or professional review organization adjustments). 
                //•  PR  - Patient Responsibility 

                //PR 1 Deductible AMTDeduct 
                //PR 2 Coinsurance AMTCoins 
                //PR 3 Copay AMTCoPay 
                //OA 23 COB (AMTPAY-M + AmtTPP--Apply) 
                //CO 104 Risk AMT Risk 
                //CO 131 Discount AMT Discount 
                //CO 24 Fee For Service AMT--FFS 
                //CO/PI 45 Balance Paid to Charged Amount N/A--Balance to Charged Amount if payment is less than submitted charge 
                //CO/PI 94 Balance Paid to Charged Amount N/A--Balance to Charged Amount if payment is greater than submitted charge 
                //OA -45 Balance Paid to Charged Amount for COB Claim N/A--Balance to Charged Amount if payment is less than or greater than submitted charge for COB claim 

                //CO = Contracted; PI = Not Contracted Allowed = Amount Paid

            }
            e.note = "";
            if (nodelist.Count == 0)
            {
                EDITranItem ti = new EDITranItem();
                e.note_item = ti;
                string note = "";
                XmlNodeList cas = node.SelectNodes("CAS");
                foreach (XmlNode ci in cas)
                {

                    for (int k = 0; k < 10; k++)
                    {
                        int m = k * 3 + 2;
                        string ReasonCode = getnode_txt(ci, "CAS" + m.ToString().PadLeft(2, '0'));
                        string Amount = getnode_txt(ci, "CAS" + (m + 1).ToString().PadLeft(2, '0'));
                        if (Amount == "")
                            break;
                        string GroupCode = getnode_txt(ci, "CAS01");
                        note = note + GroupCode + "|" + ReasonCode + "|" + Amount + ";";
                    }
                }
                foreach (XmlNode ci in cas)
                {

                    for (int k = 0; k < 10; k++)
                    {
                        int m = k * 3 + 2;
                        string ReasonCode = getnode_txt(ci, "CAS" + m.ToString().PadLeft(2, '0'));
                        string Amount = getnode_txt(ci, "CAS" + (m + 1).ToString().PadLeft(2, '0'));
                        if (Amount == "")
                            break;
                        AdjustmentItem ai = new AdjustmentItem();
                        ai.GroupCode = getnode_txt(ci, "CAS01");
                        ai.ReasonCode = ReasonCode;
                        ai.Amount = Amount;                      
                        ti.AdjustmentItems.Add(ai);
                    }
                }
                e.note = note;
            }
            check_edi_adjustment(e,  Ded_PR_Code,  Adj_PR_Code,  Red_CO_Code,  Oth_OA_Code,  Cap_CO_Code,  CoInsur_Code,  Copay_Code,  PTResp_Code,  PTResp_Group,  Adjustment_Group,  OtherAdjustment_Group);
            return e;
        }
        public static void check_item_adjustment(EDITranItem ti, string Ded_PR_Code, string Adj_PR_Code, string Red_CO_Code, string Oth_OA_Code, string Cap_CO_Code, string CoInsur_Code, string Copay_Code, string PTResp_Code, string PTResp_Group, string Adjustment_Group, string OtherAdjustment_Group)
        {
            ti.Deductible = "";
            ti.Reduction = "";
            ti.Copay = "";
            ti.CoInsurance = "";
            ti.Other_pay = "";
            ti.Capitation_amount = "";
            ti.Adjustment = "";
            ti.Balance = "";
            ti.OtherAdjustment = "";
            for (int i=0;i<ti.AdjustmentItems.Count;i++)
            {
                AdjustmentItem ai = ti.AdjustmentItems[i];
                if (in_code(ai.GroupCode, ai.ReasonCode, Ded_PR_Code))
                {
                    ti.Deductible = str2float_add(ti.Deductible, ai.Amount);
                    ai.paynote = "Deductible";
                    continue;
                }
                if (in_code(ai.GroupCode, ai.ReasonCode, CoInsur_Code))
                {
                    ti.CoInsurance = str2float_add(ti.CoInsurance, ai.Amount);
                    ai.paynote = "CoInsurance";
                    continue;
                }
                if (in_code(ai.GroupCode, ai.ReasonCode, Copay_Code))
                {
                    ti.Copay = str2float_add(ti.Copay, ai.Amount);
                    ai.paynote = "Copay";
                    continue;
                }
                if (in_code(ai.GroupCode, ai.ReasonCode, Red_CO_Code))
                {
                    ti.Reduction = str2float_add(ti.Reduction, ai.Amount);
                    ai.paynote = "Reduction/Discount";
                    continue;
                }
                if (in_code(ai.GroupCode, ai.ReasonCode, Cap_CO_Code))
                {
                    ti.Capitation_amount = str2float_add(ti.Capitation_amount, ai.Amount);
                    ai.paynote = "Capitation";
                    continue;
                }
                if (in_code(ai.GroupCode, ai.ReasonCode, Oth_OA_Code))
                {
                    ti.Other_pay = str2float_add(ti.Other_pay, ai.Amount);
                    ai.paynote = "Other Insurance";
                    continue;
                }
                if (in_code(ai.GroupCode, ai.ReasonCode, Adj_PR_Code))
                {
                    ti.Adjustment = str2float_add(ti.Adjustment, ai.Amount);
                    ai.paynote = "Adjusted";
                    continue;
                }
                if (in_code(ai.GroupCode, ai.ReasonCode, PTResp_Code))
                {
                    ti.Balance = str2float_add(ti.Balance, ai.Amount);
                    ai.paynote = "Other Patient Resp";
                    continue;
                }
                if (in_group_code(ai.GroupCode, ai.ReasonCode, PTResp_Group))
                {
                    ti.Balance = str2float_add(ti.Balance, ai.Amount);
                    ai.paynote = "Other Patient Resp";
                    continue;
                }
                if (in_group_code(ai.GroupCode, ai.ReasonCode, Adjustment_Group))
                {
                    ti.Adjustment = str2float_add(ti.Adjustment, ai.Amount);
                    ai.paynote = "Adjusted";
                    continue;
                }
                if (in_group_code(ai.GroupCode, ai.ReasonCode, OtherAdjustment_Group))
                {
                    ti.OtherAdjustment = str2float_add(ti.OtherAdjustment, ai.Amount);
                    ai.paynote = "Other Adjustment";
                    continue;
                }
                ti.Adjustment = str2float_add(ti.Adjustment, ai.Amount);
                ai.paynote = "Adjusted";
            }
            
        }
        public static void check_edi_adjustment(EDITran edi, string Ded_PR_Code, string Adj_PR_Code, string Red_CO_Code, string Oth_OA_Code, string Cap_CO_Code, string CoInsur_Code, string Copay_Code, string PTResp_Code, string PTResp_Group, string Adjustment_Group, string OtherAdjustment_Group)
        {
            if (edi.Items.Count>0)
            {
                for(int i=0;i< edi.Items.Count; i++)
                {
                    check_item_adjustment(edi.Items[i], Ded_PR_Code, Adj_PR_Code, Red_CO_Code, Oth_OA_Code, Cap_CO_Code, CoInsur_Code, Copay_Code, PTResp_Code, PTResp_Group, Adjustment_Group, OtherAdjustment_Group);
                }
            }
            else
            {
                if (edi.note_item != null)
                    check_item_adjustment(edi.note_item, Ded_PR_Code, Adj_PR_Code, Red_CO_Code, Oth_OA_Code, Cap_CO_Code, CoInsur_Code, Copay_Code, PTResp_Code, PTResp_Group, Adjustment_Group, OtherAdjustment_Group);
            }
            
        }
        public static EDITran node2EDIItem_old(XmlNode node,string Ded_PR_Code, string Adj_PR_Code, string Red_CO_Code,string Oth_OA_Code,string Cap_CO_Code, string CoInsur_Code,string Copay_Code,string PTResp_Code, string PTResp_Group, string Adjustment_Group, string OtherAdjustment_Group )
        {
            EDITran e = new EDITran();
            e.Payer = getnode_txt(node.ParentNode.ParentNode, "Loop[@LoopId='1000B']/N1/N104");
            e.Check = getnode_txt(node.ParentNode.ParentNode.SelectSingleNode("TRN"), "TRN02");
            e.Date = strYYYYMMDD2date(getnode_txt(node.ParentNode.ParentNode.SelectSingleNode("BPR"), "BPR16"));
            e.PatientID = getnode_txt(node, "NM1/NM109");
            e.Last = getnode_txt(node, "NM1/NM103");
            e.First = getnode_txt(node, "NM1/NM104");
            e.NPIorTaxID = getnode_txt(node.ParentNode.ParentNode, "Loop[@LoopId='1000B']/N1/N104");
            e.Payee = getnode_txt(node.ParentNode.ParentNode, "Loop[@LoopId='1000B']/N1/N102");
            e.ChargeAmt = getnode_txt(node, "CLP/CLP03");
            e.PaymentAmt = getnode_txt(node, "CLP/CLP04");
            e.Accnt = getnode_txt(node, "CLP/CLP01");
            e.Status = "";
            e.Payer = getnode_txt(node.ParentNode.ParentNode, "Loop[@LoopId='1000A']/N1/N102");
            e.claim_status = getnode_txt(node, "CLP/CLP02");

            e.forwarded_payer = getnode_txt(node, "NM1[NM101='TT']/NM103");

            // e.PayerID = getnode_txt(node.ParentNode.ParentNode, "Loop[@LoopId='1000A']/N4/N403");
            string taxid= getnode_txt(node.ParentNode.ParentNode, "TRN/TRN03");
            if (taxid.StartsWith("1"))
                taxid = taxid.Substring(1);
            if (taxid.Length > 2)
                taxid = taxid.Insert(2, "-");
            e.PayerID = taxid;
            e.PayerClaimControlNumber = getnode_txt(node, "CLP/CLP07");
            XmlNodeList nodelist = node.SelectNodes("Loop[@LoopId='2110']");
          
            Dictionary<string, int> cpt_count = new Dictionary<string, int>();
            foreach (XmlNode ni in nodelist)
            {
                EDITranItem ti = new EDITranItem();
                string s = getnode_txt(ni, "DTM/DTM02");
                if (s == "")
                    s = getnode_txt(node, "DTM/DTM02");
                ti.SvcDate = strYYYYMMDD2date(s);

                ti.CPT = getnode_txt(ni, "SVC/SVC01/SVC0102");
                ti.Modifiers = getnode_txt(ni, "SVC/SVC01/SVC0103");
                ti.ChargeAmt = getnode_txt(ni, "SVC/SVC02");
                ti.PaymentAmt = getnode_txt(ni, "SVC/SVC03");
                ti.AllowedAmount = getnode_txt(ni, "AMT/AMT02");
                string key = ti.SvcDate + "|" + ti.CPT + "|" + ti.Modifiers;
                if (cpt_count.ContainsKey(key))
                {
                    ti.CPT_Seq = (cpt_count[key] + 1).ToString();
                }
                else
                {
                    ti.CPT_Seq = "1";
                }
                cpt_count[key] = int.Parse(ti.CPT_Seq);
                XmlNodeList cas = ni.SelectNodes("CAS");
                foreach (XmlNode ci in cas)
                {

                    for (int k = 0; k < 10; k++)
                    {
                        int m = k * 3 + 2;
                        string ReasonCode = getnode_txt(ci, "CAS" + m.ToString().PadLeft(2, '0'));
                        string Amount = getnode_txt(ci, "CAS" + (m + 1).ToString().PadLeft(2, '0'));
                        if (Amount == "")
                            break;
                        AdjustmentItem ai = new AdjustmentItem();
                        ai.GroupCode = getnode_txt(ci, "CAS01");
                        ai.ReasonCode = ReasonCode;
                        ai.Amount = Amount;
                        if (ai.Amount != "")
                        {
                            Boolean isAdjusted = true;
                            Boolean must_Adjusted = false;

                            if (ai.ReasonCode == "96")
                            {
                                // if allowed <> 0 then put this PR96 into "other patient Resp.".  
                                float f1 = 0;
                                if (!float.TryParse(ti.AllowedAmount, out f1))
                                    f1 = 0;
                                if (f1.ToString("0.00") != "0.00")
                                {
                                    ti.Balance = str2float_add(ti.Balance, ai.Amount);
                                    isAdjusted = false;
                                } else
                                {
                                    must_Adjusted = true;
                                }
                            }
                            else if (in_code(ai.GroupCode, ai.ReasonCode, Ded_PR_Code))
                            {
                                ti.Deductible = str2float_add(ti.Deductible, ai.Amount);
                                isAdjusted = false;
                            }
                            else if (in_code(ai.GroupCode,ai.ReasonCode, Red_CO_Code))
                            {
                                ti.Reduction = str2float_add(ti.Reduction, ai.Amount);
                                isAdjusted = false;
                            }
                            else if (in_code(ai.GroupCode,ai.ReasonCode, Oth_OA_Code))
                            {
                                ti.Other_pay = str2float_add(ti.Other_pay, ai.Amount);
                                isAdjusted = false;
                            }
                            else if (in_code(ai.GroupCode,ai.ReasonCode, Cap_CO_Code))
                            {
                                ti.Capitation_amount = str2float_add(ti.Capitation_amount, ai.Amount);
                                isAdjusted = false;
                            }
                            else if (in_code(ai.GroupCode, ai.ReasonCode, CoInsur_Code))
                            {
                                ti.CoInsurance = str2float_add(ti.CoInsurance, ai.Amount);
                                isAdjusted = false;
                            }
                            if ((isAdjusted )&&(!must_Adjusted)) {//((ai.GroupCode == "PR")&&(isAdjusted)) {
                                                                
                                if (ai.ReasonCode == "2")
                                {
                                    ti.CoInsurance = str2float_add(ti.CoInsurance, ai.Amount);
                                    isAdjusted = false;
                                }
                                else if (ai.ReasonCode == "3")
                                {
                                    ti.Copay = str2float_add(ti.Copay, ai.Amount);
                                    isAdjusted = false;
                                }
                                else if ((!(in_code(ai.GroupCode,ai.ReasonCode,Adj_PR_Code))) && (ai.GroupCode == "PR") )
                                {
                                    ti.Balance = str2float_add(ti.Balance, ai.Amount);
                                    isAdjusted = false;
                                }
                            }
                            if (isAdjusted)
                                if ((ai.GroupCode == "PI") || (ai.GroupCode == "CR"))
                                {
                                    ti.Reduction = str2float_add(ti.Reduction, ai.Amount);
                                    isAdjusted = false;
                                }
                            if (isAdjusted)
                                ti.Adjustment = str2float_add(ti.Adjustment, ai.Amount);
                        }
                        if (ai.GroupCode == "CO")
                        {
                            ai.Group = "Contractual Obligations";
                        }
                        if (ai.GroupCode == "OA")
                        {
                            ai.Group = "Other Adjustments";
                        }
                        if (ai.GroupCode == "PI")
                        {
                            ai.Group = "Payer Initiated Reductions";
                        }
                        if (ai.GroupCode == "PR")
                        {
                            ai.Group = "Patient Responsibility";
                        }
                        ti.AdjustmentItems.Add(ai);
                    }
                }
               
                ti.TotalAdjAmt = "";
                ti.Remarks = "";
                ti.LQ = "";
                XmlNodeList lqlist = ni.SelectNodes("LQ");
                foreach (XmlNode lq in lqlist)
                {
                   string slq= getnode_txt(lq, "LQ02");
                    if (slq != "")
                    {
                        if (ti.LQ != "")
                            ti.LQ = ti.LQ + ", ";
                        ti.LQ = ti.LQ + slq;
                    }
                }
                e.Items.Add(ti);

                //CO  - Contractual Obligations 
                // This group code should be used when a joint contractual agreement between the payer and payee, or a regulatory requirement, resulted in an adjustment. Generally, these adjustments are considered a write off for the provider and are not billed to the patient. 
                //•  OA  - Other Adjustments 
                // This group code should be used when no other group code applies to the adjustment. Refer to the ASC X12 005010X221A1 Health Care Claim Payment/Advice (835) Sections 1.10.2.6, 1.10.2.7 and 1.10.2.13 for business situations that describe the usage of the code. 
                //•  PI  - Payer Initiated Reductions 
                // This group code should be used when, in the opinion of the payer, the adjustment is not the responsibility of the patient, but there is no supporting contract between the provider and the payer (i.e., medical review or professional review organization adjustments). 
                //•  PR  - Patient Responsibility 

                //PR 1 Deductible AMTDeduct 
                //PR 2 Coinsurance AMTCoins 
                //PR 3 Copay AMTCoPay 
                //OA 23 COB (AMTPAY-M + AmtTPP--Apply) 
                //CO 104 Risk AMT Risk 
                //CO 131 Discount AMT Discount 
                //CO 24 Fee For Service AMT--FFS 
                //CO/PI 45 Balance Paid to Charged Amount N/A--Balance to Charged Amount if payment is less than submitted charge 
                //CO/PI 94 Balance Paid to Charged Amount N/A--Balance to Charged Amount if payment is greater than submitted charge 
                //OA -45 Balance Paid to Charged Amount for COB Claim N/A--Balance to Charged Amount if payment is less than or greater than submitted charge for COB claim 

                //CO = Contracted; PI = Not Contracted Allowed = Amount Paid

            }
            e.note = "";
            if (nodelist.Count==0)
            {
                EDITranItem ti = new EDITranItem();
                e.note_item = ti;
                string note = "";
                XmlNodeList cas = node.SelectNodes("CAS");                
                foreach (XmlNode ci in cas)
                {

                    for (int k = 0; k < 10; k++)
                    {
                        int m = k * 3 + 2;
                        string ReasonCode = getnode_txt(ci, "CAS" + m.ToString().PadLeft(2, '0'));
                        string Amount = getnode_txt(ci, "CAS" + (m + 1).ToString().PadLeft(2, '0'));
                        if (Amount == "")
                            break;
                        string GroupCode = getnode_txt(ci, "CAS01");
                        note = note + GroupCode + "|" + ReasonCode + "|" + Amount + ";";
                    }
                }
                foreach (XmlNode ci in cas)
                {

                    for (int k = 0; k < 10; k++)
                    {
                        int m = k * 3 + 2;
                        string ReasonCode = getnode_txt(ci, "CAS" + m.ToString().PadLeft(2, '0'));
                        string Amount = getnode_txt(ci, "CAS" + (m + 1).ToString().PadLeft(2, '0'));
                        if (Amount == "")
                            break;
                        AdjustmentItem ai = new AdjustmentItem();
                        ai.GroupCode = getnode_txt(ci, "CAS01");
                        ai.ReasonCode = ReasonCode;
                        ai.Amount = Amount;
                        if (ai.Amount != "")
                        {
                            Boolean isAdjusted = true;
                            Boolean must_Adjusted = false;

                            if (ai.ReasonCode == "96")
                            {
                                // if allowed <> 0 then put this PR96 into "other patient Resp.".  
                                float f1 = 0;
                                if (!float.TryParse(ti.AllowedAmount, out f1))
                                    f1 = 0;
                                if (f1.ToString("0.00") != "0.00")
                                {
                                    ti.Balance = str2float_add(ti.Balance, ai.Amount);
                                    isAdjusted = false;
                                }
                                else
                                {
                                    must_Adjusted = true;
                                }
                            }
                            else if (in_code(ai.GroupCode, ai.ReasonCode, Ded_PR_Code))
                            {
                                ti.Deductible = str2float_add(ti.Deductible, ai.Amount);
                                isAdjusted = false;
                            }
                            else if (in_code(ai.GroupCode, ai.ReasonCode, Red_CO_Code))
                            {
                                ti.Reduction = str2float_add(ti.Reduction, ai.Amount);
                                isAdjusted = false;
                            }
                            else if (in_code(ai.GroupCode, ai.ReasonCode, Oth_OA_Code))
                            {
                                ti.Other_pay = str2float_add(ti.Other_pay, ai.Amount);
                                isAdjusted = false;
                            }
                            else if (in_code(ai.GroupCode, ai.ReasonCode, Cap_CO_Code))
                            {
                                ti.Capitation_amount = str2float_add(ti.Capitation_amount, ai.Amount);
                                isAdjusted = false;
                            }
                            else if (in_code(ai.GroupCode, ai.ReasonCode, CoInsur_Code))
                            {
                                ti.CoInsurance = str2float_add(ti.CoInsurance, ai.Amount);
                                isAdjusted = false;
                            }
                            if ((isAdjusted) && (!must_Adjusted))
                            {//((ai.GroupCode == "PR")&&(isAdjusted)) {

                                if (ai.ReasonCode == "2")
                                {
                                    ti.CoInsurance = str2float_add(ti.CoInsurance, ai.Amount);
                                    isAdjusted = false;
                                }
                                else if (ai.ReasonCode == "3")
                                {
                                    ti.Copay = str2float_add(ti.Copay, ai.Amount);
                                    isAdjusted = false;
                                }
                                else if ((!(in_code(ai.GroupCode, ai.ReasonCode, Adj_PR_Code))) && (ai.GroupCode == "PR"))
                                {
                                    ti.Balance = str2float_add(ti.Balance, ai.Amount);
                                    isAdjusted = false;
                                }
                            }
                            if (isAdjusted)
                                if ((ai.GroupCode == "PI") || (ai.GroupCode == "CR"))
                                {
                                    ti.Reduction = str2float_add(ti.Reduction, ai.Amount);
                                    isAdjusted = false;
                                }
                            if (isAdjusted)
                                ti.Adjustment = str2float_add(ti.Adjustment, ai.Amount);
                        }
                        if (ai.GroupCode == "CO")
                        {
                            ai.Group = "Contractual Obligations";
                        }
                        if (ai.GroupCode == "OA")
                        {
                            ai.Group = "Other Adjustments";
                        }
                        if (ai.GroupCode == "PI")
                        {
                            ai.Group = "Payer Initiated Reductions";
                        }
                        if (ai.GroupCode == "PR")
                        {
                            ai.Group = "Patient Responsibility";
                        }
                        ti.AdjustmentItems.Add(ai);
                    }
                }
                e.note = note;
            }
            return e;
        }
        public static List<EDITran> edilist_join(List<EDITran> old_list)
        {
            return old_list;
            //
            List<EDITran> list = new List<EDITran>();
            foreach (EDITran edi_old in old_list)
            {
                EDITran edi_new = null;
                foreach (EDITran i in list)
                {
                    if ((i.Payer == edi_old.Payer) && (i.get_acct_code() == edi_old.get_acct_code()) && (i.get_claim_no() == edi_old.get_claim_no()) && (i.claim_status == edi_old.claim_status))
                    {
                        edi_new = i;
                        break;
                    }
                }
                if (edi_new == null)
                {
                    list.Add(edi_old);
                }
                else
                {
                    edi_new.add_EDITran(edi_old);
                }
            }
            //list.Sort(delegate (EDITran i1, EDITran i2)
            //{
            //    String s1 = i1.get_acct_code() + i1.get_claim_no() + i1.PayerClaimControlNumber.PadLeft(10, '0');
            //    String s2 = i2.get_acct_code() + i2.get_claim_no() + i2.PayerClaimControlNumber.PadLeft(10, '0');
            //    return s1.CompareTo(s2);
            //});
            return list;
        }
        public static List<EDITran> edixml2list(string xml,string Ded_PR_Code, string Adj_PR_Code, string Red_CO_Code, string Oth_OA_Code, string Cap_CO_Code,string CoInsur_Code, string Copay_Code, string PTResp_Code, string PTResp_Group, string Adjustment_Group, string OtherAdjustment_Group)
        {
            List<EDITran> list = new List<EDITran>();
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);
            XmlNodeList nodelist = doc.SelectNodes("//Loop[@LoopId='2100']");
            foreach (XmlNode node in nodelist)
            {
                EDITran i = node2EDIItem(node, Ded_PR_Code,Adj_PR_Code, Red_CO_Code,  Oth_OA_Code,  Cap_CO_Code, CoInsur_Code,  Copay_Code,  PTResp_Code,  PTResp_Group,  Adjustment_Group,  OtherAdjustment_Group);
                if (i != null)
                    list.Add(i);
            }
            return list;
        }
       
        public static Dictionary<string, string> ClaimStatus = get_ClaimStatus();
        public static Dictionary<string, string> get_ClaimStatus()
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict["1"] = "Processed as Primary";
            dict["2"] = "Processed as Secondary";
            dict["3"] = "Processed as Tertiary";
            dict["4"] = "Denied";
            dict["19"] = "Processed as Primary, Forwarded";
            dict["20"] = "Processed as Secondary, Forwarded";
            dict["21"] = "Processed as Tertiary, Forwarded";
            dict["22"] = "Reversal of Previous Payment";
            dict["23"] = "Not Our Claim, Forwarded";
            dict["25"] = "Predetermination Pricing Only";

            dict["99"] = "Revised Payment";
            return dict;
        }
    }
}
相关推荐
2401_857439691 小时前
SSM 架构下 Vue 电脑测评系统:为电脑性能评估赋能
开发语言·php
SoraLuna2 小时前
「Mac畅玩鸿蒙与硬件47」UI互动应用篇24 - 虚拟音乐控制台
开发语言·macos·ui·华为·harmonyos
xlsw_2 小时前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
Dream_Snowar3 小时前
速通Python 第三节
开发语言·python
高山我梦口香糖4 小时前
[react]searchParams转普通对象
开发语言·前端·javascript
信号处理学渣4 小时前
matlab画图,选择性显示legend标签
开发语言·matlab
红龙创客4 小时前
某狐畅游24校招-C++开发岗笔试(单选题)
开发语言·c++
jasmine s4 小时前
Pandas
开发语言·python
biomooc5 小时前
R 语言 | 绘图的文字格式(绘制上标、下标、斜体、文字标注等)
开发语言·r语言
骇客野人5 小时前
【JAVA】JAVA接口公共返回体ResponseData封装
java·开发语言