package queries

const OrderListBaseQuery = `
SELECT
    CAST(h.OrderHeaderID AS NVARCHAR(50))           AS OrderHeaderID,
    ISNULL(h.OrderNumber, '')                       AS OrderNumber,
    CONVERT(varchar, h.OrderDate, 23)               AS OrderDate,

    ISNULL(h.CurrAccCode, '')                       AS CurrAccCode,
    ISNULL(ca.CurrAccDescription, '')               AS CurrAccDescription,

    ISNULL(mt.AttributeDescription, '')             AS MusteriTemsilcisi,
    ISNULL(py.AttributeDescription, '')             AS Piyasa,

    CONVERT(varchar, h.CreditableConfirmedDate, 23) AS CreditableConfirmedDate,
    ISNULL(h.DocCurrencyCode, 'TRY')                AS DocCurrencyCode,

    ISNULL(l.TotalAmount, 0)                        AS TotalAmount,

    CASE
        WHEN h.DocCurrencyCode = 'USD'
            THEN ISNULL(l.TotalAmount, 0)
        WHEN h.DocCurrencyCode = 'TRY'
            THEN ISNULL(l.TotalAmount, 0) / NULLIF(er.Rate, 1)
        ELSE 0
    END                                             AS TotalAmountUSD,

    ISNULL(h.IsCreditableConfirmed, 0)              AS IsCreditableConfirmed,
    ISNULL(h.Description, '')                       AS Description,

    ISNULL(er.Rate, 1)                              AS ExchangeRateUSD

FROM dbo.trOrderHeader h

JOIN (
    SELECT OrderHeaderID, SUM(Qty1 * Price) AS TotalAmount
    FROM dbo.trOrderLine
    GROUP BY OrderHeaderID
) l ON l.OrderHeaderID = h.OrderHeaderID

LEFT JOIN dbo.cdCurrAccDesc ca
  ON ca.CurrAccCode = h.CurrAccCode AND ca.LangCode = 'TR'

LEFT JOIN dbo.CustomerAttributes f
  ON f.CurrAccTypeCode = h.CurrAccTypeCode
 AND f.CurrAccCode     = h.CurrAccCode

LEFT JOIN dbo.cdCurrAccAttributeDesc mt
  ON mt.CurrAccTypeCode   = f.CurrAccTypeCode
 AND mt.AttributeTypeCode = 2
 AND mt.AttributeCode     = f.CustomerAtt02
 AND mt.LangCode          = 'TR'

LEFT JOIN dbo.cdCurrAccAttributeDesc py
  ON py.CurrAccTypeCode   = f.CurrAccTypeCode
 AND py.AttributeTypeCode = 3
 AND py.AttributeCode     = f.CustomerAtt03
 AND py.LangCode          = 'TR'

OUTER APPLY (
    SELECT TOP 1 Rate
    FROM dbo.AllExchangeRates er
    WHERE er.CurrencyCode = 'USD'
      AND er.RelationCurrencyCode = 'TRY'
      AND er.ExchangeTypeCode = 6
      AND er.Rate > 0
    ORDER BY ABS(DATEDIFF(DAY, er.Date, GETDATE()))
) er

WHERE
    ISNULL(h.IsCancelOrder, 0) = 0
    AND h.OrderTypeCode = 1
    AND h.ProcessCode   = 'WS'
    AND h.IsClosed      = 0
`
