电子数据交换EDI 835 的处理

news2024/9/28 23:02:00

电子数据交换 (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);

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;
        }
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2175040.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

如何快速降低文章重复率?试试芝士AI,智能降痕省时省力

论文查重的原理是连续出现13个字符类似就判断为重复部分&#xff0c;并将重复的内容计算到论文的重复率之中。 芝士AI官网&#xff1a;https://www.paperzz.cn/ 芝士AI论文查重系统会对内容进行分层处理&#xff0c;按照篇章&#xff0c;段落&#xff0c;句子等层级分别创建指…

江科大笔记——新建工程

STM32的开发方式 目前STM32的开发方式主要有基于寄存器的方式、基于标准库的方式&#xff08;库函数的方式&#xff09;、基于HAL库的方式&#xff1a; 基于库函数的方式是使用ST官方提供的封装好的函数&#xff0c;通过调用这些函数来间接地配置寄存器。基于HAL库的方式可以…

8000多道超全题库+高频题+大厂面试官原创题解+真实面经,绝对的求职秘密武器

正在找工作或者想要提升技术的程序员都可以去试试这款刷题神器【面试鸭】。你能想到的各种题目都被整理得明明白白&#xff0c;再也不用自己到处找七零八落的资料。8000多道超全题库高频题大厂面试官原创题解真实面经&#xff0c;绝对的求职秘密武器&#xff0c;扫码即可体验⬇…

数据结构:树、森林

二叉树与树结构差异 树&#xff08;一般树&#xff09;&#xff1a;树是一种数据结构&#xff0c;其中每个节点可以有任意数量的子节点&#xff08;除了根节点和叶子节点外&#xff09;。因此&#xff0c;一般树的节点在数组中的表示并不是那么直接&#xff0c;特别是当树不是完…

赵长鹏今日获释,下一步会做什么?币安透露2024年加密货币牛市的投资策略!

中国时间2024年9月28日&#xff0c;加密货币行业的风云人物赵长鹏&#xff08;Changpeng Zhao&#xff0c;简称CZ&#xff09;终于从监狱获释。他因在担任币安首席执行官期间未能有效执行反洗钱(AML)计划而被判刑四个月。赵长鹏的获释引发了广泛关注&#xff0c;不仅因为他是全…

一不小心,给腾讯云提了一个Bug

大家好&#xff0c;这里是程序员晚枫。 我使用腾讯的cos服务2年多了&#xff0c;一直都是在网页手动管理资源。 最近身边有高人”突发奇想“&#xff1a;要不自己封装一个专用的api&#xff1f;于是苦命打工人晚枫上线&#xff0c;吭哧吭哧把腾讯已经封装很好的Python SDK又包…

企业微信(企微)审批与影刀RPA结合

企业微信审批与影刀RPA结合 效果先看视频&#xff1a; 影刀与企业微信审批结合 具体步骤&#xff1a; 1、登录企微管理后台&#xff0c;新建一个审批流。 添加模板→自定义模板&#xff0c;根据需求添加审批节点。 添加完之后&#xff0c;回到审批界面&#xff0c;可以看…

Java新手指南:从菜鸟到编程大师的趣味之路-多态

这里是Themberfue 本章讲的是Java三大特性之一的多态&#xff0c;也是最后一个特性 多态概念 既然我们要学习多态&#xff0c;首先得知道这玩意儿到底是个什么东西&#xff1f; 通俗地说&#xff0c;多态其实就是多种形态。具体来说就是去完成某个行为&#xff0c;当不同的对象…

win11电脑长时间锁屏会变得非常卡(rundll.32过多)——解决方法

一、问题 当你长时间锁屏后&#xff0c;电脑会变得十分的卡&#xff0c;有些甚至会死机崩溃&#xff0c;这个时候你可能并不需要修改电源的计划设置&#xff0c;也可能并不需要修改电脑注册表之类的东西。 赶紧打开你的任务管理器&#xff0c;winx&#xff0c;选择任务管理器…

利士策分享,攀登职场高峰:成功者的十大特质

利士策分享&#xff0c;攀登职场高峰&#xff1a;成功者的十大特质 在职场这个竞争激烈的舞台上&#xff0c;那些能够迅速崛起、实现职业辉煌的佼佼者&#xff0c;往往凭借一系列独特且鲜明的特质脱颖而出。以下是对这些特质的深入探讨&#xff1a; 第一章&#xff1a;高情商的…

Elasticsearch学习笔记(1)

初识 Elasticsearch 认识和安装 Elasticsearch 是由 Elastic 公司开发的一套强大的搜索引擎技术&#xff0c;属于 Elastic 技术栈的一部分。完整的技术栈包括&#xff1a; Elasticsearch&#xff1a;用于数据存储、计算和搜索。Logstash/Beats&#xff1a;用于数据收集。Kib…

代码为笔,合作作墨,共绘共赢画卷———未来之窗行业应用跨平台架构

合作共赢&#xff0c;代码同创&#xff0c;成就非凡 一、资源整合方面 1.1. 技术资源共享 - 不同的合作伙伴可能在技术领域各有所长。例如&#xff0c;一方可能擅长前端用户界面设计&#xff0c;具有丰富的交互设计经验&#xff0c;能够打造出美观、易用的预订界面&#xff…

云舟观测:集成开源Grafana Faro构建前端页面性能监控平台

在当今互联网时代&#xff0c;面对纷乱繁杂的网上资源&#xff0c;用户的耐心和注意力是极为宝贵的资源&#xff0c;当用户访问一个网站或应用时&#xff0c;他们期望的是快速且无缝的体验&#xff0c;任何加载延迟或功能故障都可能导致用户流失&#xff0c;影响品牌体验。因此…

MySQL 中的 FOREIGN KEY 约束:确保数据完整性的关键

在 MySQL 数据库中&#xff0c;FOREIGN KEY&#xff08;外键&#xff09;约束是一种非常重要的机制&#xff0c;它可以帮助我们确保数据的完整性和一致性。那么&#xff0c;FOREIGN KEY 约束究竟是什么呢&#xff1f;让我们一起来深入了解一下。 一、什么是 FOREIGN KEY 约束&…

计算机毕业设计 招生宣传管理系统的设计与实现 Java实战项目 附源码+文档+视频讲解

博主介绍&#xff1a;✌从事软件开发10年之余&#xff0c;专注于Java技术领域、Python人工智能及数据挖掘、小程序项目开发和Android项目开发等。CSDN、掘金、华为云、InfoQ、阿里云等平台优质作者✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精…

支付宝远程收款api之小荷包跳转码

想要生成小荷包跳转码的二维码&#xff0c;需要进行以下步骤&#xff1a; 1、开通支付宝小荷包的收款功能权限 2、获取支付宝的小荷包收款码和支付宝账户的UID已经手机号等相应信息&#xff08;可能会有变动&#xff09; 3、可能需要一定的代码基础&#xff0c;讲所需信息填…

基于python+控制台+txt文档实现学生成绩管理系统(含课程实训报告)

目录 第一章 需求分析 第二章 系统设计 2.1 系统功能结构 2.1.1 学生信息管理系统的七大模块 2.1.2 系统业务流程 2.2 系统开发必备环境 第三章 主函数设计 3.1 主函数界面运行效果图 3.2 主函数的业务流程 3.3 函数设计 第四章 详细设计及实现 4.1 学生信息录入模块的设计与实…

2024.9.28 作业+思维导图

widget.cpp #include "widget.h"Widget::Widget(QWidget *parent): QWidget(parent) {this->setFixedSize(320,448);this->setWindowFlag(Qt::FramelessWindowHint);//QPushButtonQPushButton *PushButton1 new QPushButton("登录",this);PushButto…

先进封装技术 Part02---TSV科普

一、引言 随着电子设备向更小型化、更高性能的方向发展,传统的芯片互连技术已经无法满足日益增长的需求。在这样的背景下,TSV(Through-Silicon Via,硅通孔)技术应运而生,成为先进封装技术中的核心之一。 如果我们看大多数主板,可以看到两件事:第一,芯片之间的大多数连…

《深度学习》自然语言处理 统计、神经语言模型 结构、推导解析

目录 一、语言转换方法 1、如何将语言转换为模型可以直接识别的内容 1&#xff09;数据预处理 2&#xff09;特征提取 3&#xff09;模型输入 4&#xff09;模型推理 二、语言模型 1、统计语言模型 1&#xff09; 案例&#xff1a; • 运行结果&#xff1a; • 稀疏…