SELECT

  -- Invoice detail.
  IH.CMSInvNo,
  IH.DocumentNumber AS InvNumber,
  IH.DocumentDate,
  IH.AccountBookType,
  IH.AccountBookID,
  IH.DocumentNumber,
  IH.AccountCode,
  IH.Updated,
  IH.Batch,
  IH.AppointmentID,
  IH.InvoiceType,
  IH.DueDate,
  IH.PaymentDate,
  IH.AmountPaid,

  -- Client detail
  IH.ClientID AS CMSClientID,
  IH.TradingName,
  IH.Description,
  IH.TaxTypeID,
  ROUND(IH.TaxRate, 4) AS TaxRate,
  IH.PaymentMethod,
  IH.VATNumber,
  IH.OrderNumber,
  IH.Address1,
  IH.Address2,
  IH.Address3,
  IH.Address4,
  IH.Address5,
  IH.Consultant,
  IH.Contact,
  IH.Postal1,
  IH.Postal2,
  IH.Postal3,
  IH.PostalCode,
  IH.Telephone,
  IH.Fax,

  -- Account Book - Xero
  XE.XeroEntityName,
  CASE IH.TaxTypeID
    WHEN  6 THEN 'ZERORATED'
    WHEN  7 THEN 'EXEMPTOUTPUT'
    WHEN 17 THEN 'BADDEBT'
    ELSE 'OUTPUT3'
  END AS XeroTaxAccount,
  IH.ExternalID,

  -- Account Book - Combined.
  XE.XeroEntityName AS AccountBookName,
  XE.InvoicePrefix AS InvoicePrefix,

  -- Ad Hoc Only
  BE.ImmediateAdhocInvoices,
  BE.IndividualAdhocInvoices,

  -- Amounts
  IH.InvoiceAmountIncl AS InvTotIncl,
  IH.InvoiceAmountExcl AS InvTotExcl,
  IH.InvoiceAmountExcl * IH.TaxRate AS InvTotTax,

  '' AS ErrorDescription
FROM
  taInvoiceHeader AS IH
    INNER JOIN taClients AS BE ON (BE.ClientID = IH.ClientID)
    INNER JOIN taXeroEntity AS XE ON ((XE.XeroEntityID = IH.AccountBookID) AND (IH.AccountBookType = 'Xero'))
WHERE
  (IH.InvoiceType IN ('A','I','R')) AND
  (IH.AccountCode <> 'NONE') AND
  (IH.Updated = 0) AND
  (IH.DocumentNumber <> 'VOID')
  @pAccountBookID
  @pFilter
ORDER BY
  IH.AccountBookID,
  IH.CMSInvNo
