CREATE OR REPLACE VIEW C_PAYSELECTION_CHECK_VT
AS 
SELECT psc.AD_Client_ID AS AD_Client_ID, psc.AD_Org_ID AS AD_Org_ID,
    l.AD_Language AS AD_Language,
    psc.C_PaySelection_ID AS C_PaySelection_ID, psc.C_PaySelectionCheck_ID AS C_PaySelectionCheck_ID,
    oi.C_Location_ID AS Org_Location_ID, oi.TaxID AS TaxID, 0 AS C_DocType_ID,
    bp.C_BPartner_ID AS C_BPartner_ID, bp.Value AS BPValue, bp.TaxID AS BPTaxID,
    bp.NAICS AS NAICS, bp.DUNS AS DUNS,  bpg.Greeting AS BPGreeting,  bp.Name AS Name, bp.Name2 AS Name2,
    bpartnerRemitLocation(bp.C_BPartner_ID) AS C_Location_ID,
    bp.ReferenceNo AS ReferenceNo, bp.POReference AS POReference,
    ps.PayDate AS PayDate,  psc.PayAmt AS PayAmt, psc.PayAmt AS AmtInWords,
    psc.Qty AS Qty, psc.PaymentRule AS PaymentRule, psc.DocumentNo AS DocumentNo,
	NVL(ps.Description,p.Description) as Description,
	CASE WHEN psc.IsReceipt='Y' THEN bka.AccountNO
		ELSE bpbka.ACCOUNTNO 
	END  as AccountNO,
	CASE WHEN psc.IsReceipt='Y' THEN bka.BankAccountType 
		ELSE bpbka.BANKACCOUNTTYPE 
	END as BankAccountType, 
	CASE WHEN psc.IsReceipt='Y' THEN bka.BRANCHNAME
		ELSE bpbka.BRANCHNAME 
	END as BranchName,
	CASE WHEN psc.IsReceipt='Y' THEN bka.C_BANK_ID
		ELSE bpbka.C_BANK_ID 
	END as C_BANK_ID,
	CASE WHEN psc.IsReceipt='Y' THEN bka.A_NAME
		ELSE bpbka.A_NAME 
	END as AccountName,
	us.Name as OrgLastName, 
	us.FirstName as OrgFirstName, 
	us.Phone as OrgPhone,
	us.Fax as OrgFax

FROM  C_PaySelectionCheck psc
    INNER JOIN C_PaySelection ps ON (psc.C_PaySelection_ID=ps.C_PaySelection_ID)
    INNER JOIN C_BPartner bp ON (psc.C_BPartner_ID=bp.C_BPartner_ID)
	LEFT JOIN C_PAYMENT p on (psc.C_PAYMENT_ID=p.C_PAYMENT_ID)
    INNER JOIN AD_OrgInfo oi ON (psc.AD_Org_ID=oi.AD_Org_ID)
    LEFT OUTER JOIN AD_Language l ON (l.IsSystemLanguage='Y')
    LEFT OUTER JOIN C_Greeting_Trl bpg on (bp.C_Greeting_ID=bpg.C_Greeting_ID AND bpg.AD_Language=l.AD_Language)
	LEFT OUTER JOIN (SELECT obka.*, mbka.AD_ORG_ID as ORG_ID FROM C_BANKACCOUNT obka, 
		(SELECT MAX(C_BANKACCOUNT_ID) as C_BANKACCOUNT_ID, AD_CLIENT_ID, AD_ORG_ID FROM
			(SELECT BKA.C_BANKACCOUNT_ID, BKA.AD_CLIENT_ID, O.AD_ORG_ID
			FROM C_BANKACCOUNT BKA, AD_ORG O
			WHERE BKA.AD_CLIENT_ID = O.AD_CLIENT_ID
			AND BKA.AD_ORG_ID = 0
			AND BKA.ISACTIVE = 'Y'
			AND BKA.ISDEFAULT = 'Y'
			UNION
			SELECT BKA.C_BANKACCOUNT_ID, BKA.AD_CLIENT_ID, BKA.AD_ORG_ID
			FROM C_BANKACCOUNT BKA
			WHERE BKA.AD_ORG_ID<>0
			AND BKA.ISACTIVE = 'Y'
			AND BKA.ISDEFAULT = 'Y')
			GROUP BY AD_CLIENT_ID, AD_ORG_ID) mbka 
		WHERE obka.C_BANKACCOUNT_ID = mbka.C_BANKACCOUNT_ID ) bka on (psc.AD_ORG_ID=bka.ORG_ID)
	LEFT OUTER JOIN C_BP_BANKACCOUNT bpbka on (bp.C_BPartner_ID=bpbka.C_BPARTNER_ID AND bpbka.ISACTIVE='Y')
	LEFT OUTER JOIN AD_USER us on (us.AD_USER_ID=oi.SUPERVISOR_ID)
/
