SELECT
    G.acKeyView,
    G.acKey,
    R.acWorker,
    R.adDate,
    R.acCurrency,
    R.anAmount,
    R.anPayed,
    R.anPrePayed,
    R.anReturned,
    R.anPrePayed - R.anReturned AS anForReturn,
    CAST('F' AS CHAR(1)) AS acMarked
FROM vHR_Trvl G
INNER JOIN vHR_TrvlValueRetSum R ON R.acKey = G.acKey
OUTER APPLY (SELECT MAX(adDate) AS adPaymentDate FROM fHR_TrvlValuePayedDate(G.acKey)) QP
WHERE R.anPrePayed - R.anReturned <> 0
  AND G.acKey <> @sourceAcKey
  AND (@acKeyFrom IS NULL OR G.acKey >= @acKeyFrom)
  AND (@acKeyTo IS NULL OR G.acKey <= @acKeyTo)
  AND (@acWorker IS NULL OR G.acWorker = @acWorker)
  AND (@dateFrom IS NULL OR G.adDate >= @dateFrom)
  AND (@dateTo IS NULL OR G.adDate <= @dateTo)
  AND (@travelDateFrom IS NULL AND @travelDateTo IS NULL OR EXISTS (SELECT 1 FROM tHR_TrvlItem I WHERE I.acKey = G.acKey AND (@travelDateFrom IS NULL OR I.adDateHourFrom >= @travelDateFrom) AND (@travelDateTo IS NULL OR I.adDateHourFrom <= @travelDateTo)))
  AND (@paymentDateFrom IS NULL OR CAST(QP.adPaymentDate AS DATE) >= CAST(@paymentDateFrom AS DATE))
  AND (@paymentDateTo IS NULL OR CAST(QP.adPaymentDate AS DATE) <= CAST(@paymentDateTo AS DATE))
  {0}
ORDER BY G.acKey, R.acCurrency
