SELECT
    V.acSequence,
    V.acKey,
    V.acCurrency,
    V.anMileage,
    V.anDailyAllow,
    V.anExpenses,
    V.anReturned,
    V.CalcSKUPAJ,
    V.CalcZaIzplacilo,
    V.CalcDokument,
    COALESCE(TR.acKey, CR.acKey, PO.acKey) AS CalcDocKey,
    COALESCE(TR.acDocType, CR.acDocType, PO.acDocType) AS CalcDocAcDocType,
    CASE
        WHEN NULLIF(LTRIM(RTRIM(V.CalcDokument)), '') IS NULL THEN NULL
        WHEN TR.acKey IS NOT NULL THEN 'travelorder'
        WHEN CR.acKey IS NOT NULL AND CR.acType = 'P' THEN 'receipt'
        WHEN CR.acKey IS NOT NULL AND CR.acType = 'I' THEN 'disbursement'
        WHEN PO.acKey IS NOT NULL THEN 'payorder'
        ELSE NULL
    END AS CalcDocLinkKind
FROM dbo.fHR_TrvlValues(@acKey) V
OUTER APPLY (
    SELECT TOP 1 G.acKey, G.acDocType
    FROM tHR_Trvl G
    WHERE G.acKey <> @acKey
    AND (
        G.acKeyView = LTRIM(RTRIM(V.CalcDokument))
        OR G.acKey = LTRIM(RTRIM(V.CalcDokument))
        OR REPLACE(G.acKey, '-', '') = REPLACE(LTRIM(RTRIM(V.CalcDokument)), '-', '')
        OR G.acKey IN (
            SELECT B.acKey
            FROM vHE_CashReg B
            WHERE B.acKeyView = LTRIM(RTRIM(V.CalcDokument))
        )
    )
) TR
OUTER APPLY (
    SELECT TOP 1 B.acKey, B.acDocType, B.acType
    FROM vHE_CashReg B
    INNER JOIN tHR_LinkTrvlCashRegItem L ON B.acKey = L.acLnkKey AND L.acKey = @acKey
    WHERE (
        B.acKeyView = LTRIM(RTRIM(V.CalcDokument))
        OR B.acKey = LTRIM(RTRIM(V.CalcDokument))
        OR REPLACE(B.acKey, '-', '') = REPLACE(LTRIM(RTRIM(V.CalcDokument)), '-', '')
    )
    AND (
        NULLIF(LTRIM(RTRIM(V.acCurrency)), '') IS NULL
        OR B.acCurrency = V.acCurrency
    )
    AND NOT EXISTS (
        SELECT 1
        FROM tHR_Trvl G
        WHERE G.acKey <> @acKey
        AND (
            G.acKeyView = LTRIM(RTRIM(V.CalcDokument))
            OR G.acKey = B.acKey
        )
    )
) CR
OUTER APPLY (
    SELECT TOP 1 P.acKey, P.acDocType
    FROM vHE_PayOrder P
    INNER JOIN tHR_LinkTrvlPayOrder L ON P.acKey = L.acLnkKey AND L.acKey = @acKey
    WHERE (
        P.acKeyView = LTRIM(RTRIM(V.CalcDokument))
        OR P.acKey = LTRIM(RTRIM(V.CalcDokument))
        OR REPLACE(P.acKey, '-', '') = REPLACE(LTRIM(RTRIM(V.CalcDokument)), '-', '')
    )
    AND (
        NULLIF(LTRIM(RTRIM(V.acCurrency)), '') IS NULL
        OR P.acCurrency = V.acCurrency
    )
) PO
ORDER BY V.acSequence
