group InvoiceDao;

invoiceFetchFields(prefix) ::= <<
    <prefix>invoice_number,
    <prefix>id,
    <prefix>account_id,
    <prefix>invoice_date,
    <prefix>target_date,
    <prefix>currency,
  	<prefix>migrated,
    <prefix>created_by,
    <prefix>created_date
>>

invoiceSetFields(prefix) ::= <<
    <prefix>id,
    <prefix>account_id,
    <prefix>invoice_date,
    <prefix>target_date,
    <prefix>currency,
    <prefix>migrated,
    <prefix>created_by,
    <prefix>created_date
>>

get() ::= <<
  SELECT <invoiceFetchFields()>
  FROM invoices
  ORDER BY target_date ASC;
>>

getInvoicesByAccount() ::= <<
  SELECT <invoiceFetchFields()>
  FROM invoices
  WHERE account_id = :accountId AND migrated = 'FALSE'
  ORDER BY target_date ASC;
>>

getAllInvoicesByAccount() ::= <<
  SELECT <invoiceFetchFields()>
  FROM invoices
  WHERE account_id = :accountId
  ORDER BY target_date ASC;
>>

getInvoicesByAccountAfterDate() ::= <<
  SELECT <invoiceFetchFields()>
  FROM invoices
  WHERE account_id = :accountId AND target_date >= :fromDate AND migrated = 'FALSE'
  ORDER BY target_date ASC;
>>

getInvoicesBySubscription() ::= <<
  SELECT <invoiceFetchFields("i.")>
  FROM invoices i
  LEFT JOIN recurring_invoice_items rii ON i.id = rii.invoice_id
  WHERE rii.subscription_id = :subscriptionId  AND migrated = 'FALSE'
  GROUP BY <invoiceFetchFields("i.")>;
>>

getById() ::= <<
  SELECT <invoiceFetchFields()>
  FROM invoices
  WHERE id = :id;
>>

getAccountBalance() ::= <<
  SELECT SUM(iis.amount_invoiced) AS amount_invoiced,
         SUM(ips.total_paid) AS amount_paid
  FROM invoices i
  LEFT JOIN invoice_payment_summary ips ON i.id = ips.invoice_id
  LEFT JOIN invoice_item_summary iis ON i.id = iis.invoice_id
  WHERE i.account_id = :accountId
  GROUP BY i.account_id;
>>

create() ::= <<
  INSERT INTO invoices(<invoiceSetFields()>)
  VALUES (:id, :accountId, :invoiceDate, :targetDate, :currency, :migrated, :userName, :createdDate);
>>

getInvoiceIdByPaymentAttemptId() ::= <<
  SELECT i.id
    FROM invoices i, invoice_payments ip
   WHERE ip.invoice_id = i.id
     AND ip.payment_attempt_id = :paymentAttemptId
>>

getUnpaidInvoicesByAccountId() ::= <<
  SELECT <invoiceFetchFields("i.")>
  FROM invoices i
  LEFT JOIN invoice_payment_summary ips ON i.id = ips.invoice_id
  LEFT JOIN invoice_item_summary iis ON i.id = iis.invoice_id
  WHERE i.account_id = :accountId AND NOT (i.target_date > :upToDate) AND migrated = 'FALSE'
  GROUP BY i.id, i.account_id, i.invoice_date, i.target_date, i.currency
  HAVING (SUM(iis.amount_invoiced) > SUM(ips.total_paid)) OR (SUM(ips.total_paid) IS NULL)
  ORDER BY i.target_date ASC;
>>

test() ::= <<
  SELECT 1
  FROM invoices;
>>
;