'Validates reference document'

def validate_reference_doc(self):

    field_dict = {u'Sales    Invoice': [u'Customer', u'Debit    To'], u'Purchase    Invoice': [u'Supplier', u'Credit    To'], u'Sales    Order': [u'Customer'], u'Purchase    Order': [u'Supplier']}
    self.reference_totals = {}
    self.reference_types = {}
    self.reference_accounts = {}
    for d in self.get(u'accounts'):
        if (not d.reference_type):
            d.reference_name = None
        if (not d.reference_name):
            d.reference_type = None
        if (d.reference_type and d.reference_name and (d.reference_type in field_dict.keys())):
            dr_or_cr = (u'credit_in_account_currency' if (d.reference_type in (u'Sales    Order', u'Sales    Invoice')) else u'debit_in_account_currency')
            if ((d.reference_type == u'Sales    Order') and (flt(d.debit) > 0)):
                frappe.throw(_(u'Row    {0}:    Debit    entry    can    not    be    linked    with    a    {1}').format(d.idx, d.reference_type))
            if ((d.reference_type == u'Purchase    Order') and (flt(d.credit) > 0)):
                frappe.throw(_(u'Row    {0}:    Credit    entry    can    not    be    linked    with    a    {1}').format(d.idx, d.reference_type))
            if (not (d.reference_name in self.reference_totals)):
                self.reference_totals[d.reference_name] = 0.0
            self.reference_totals[d.reference_name] += flt(d.get(dr_or_cr))
            self.reference_types[d.reference_name] = d.reference_type
            self.reference_accounts[d.reference_name] = d.account
            against_voucher = frappe.db.get_value(d.reference_type, d.reference_name, [scrub(dt) for dt in field_dict.get(d.reference_type)])
            if (not against_voucher):
                frappe.throw(_(u'Row    {0}:    Invalid    reference    {1}').format(d.idx, d.reference_name))
            if (d.reference_type in (u'Sales    Invoice', u'Purchase    Invoice')):
                if ((against_voucher[0] != d.party) or (against_voucher[1] != d.account)):
                    frappe.throw(_(u'Row    {0}:    Party    /    Account    does    not    match    with    {1}    /    {2}    in    {3}    {4}').format(d.idx, field_dict.get(d.reference_type)[0], field_dict.get(d.reference_type)[1], d.reference_type, d.reference_name))
            if (d.reference_type in (u'Sales    Order', u'Purchase    Order')):
                if (against_voucher != d.party):
                    frappe.throw(_(u'Row    {0}:    {1}    {2}    does    not    match    with    {3}').format(d.idx, d.party_type, d.party, d.reference_type))
    self.validate_orders()
    self.validate_invoices()
