group InvoiceDao;

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

get() ::= <<
  SELECT record_id as invoice_number, <invoiceFields()>
  FROM invoices
  ORDER BY target_date ASC;
>>

getInvoicesByAccount() ::= <<
  SELECT record_id as invoice_number, <invoiceFields()>
  FROM invoices
  WHERE account_id = :accountId AND migrated = 'FALSE'
  ORDER BY target_date ASC;
>>

getAllInvoicesByAccount() ::= <<
  SELECT record_id as invoice_number, <invoiceFields()>
  FROM invoices
  WHERE account_id = :accountId
  ORDER BY target_date ASC;
>>

getInvoicesByAccountAfterDate() ::= <<
  SELECT record_id as invoice_number, <invoiceFields()>
  FROM invoices
  WHERE account_id = :accountId AND target_date >= :fromDate AND migrated = 'FALSE'
  ORDER BY target_date ASC;
>>

getInvoicesBySubscription() ::= <<
  SELECT i.record_id as invoice_number, <invoiceFields("i.")>
  FROM invoices i
  LEFT JOIN invoice_items rii ON i.id = rii.invoice_id
  WHERE rii.subscription_id = :subscriptionId AND migrated = 'FALSE'
  GROUP BY i.record_id, <invoiceFields("i.")>
>>

getById() ::= <<
  SELECT record_id as invoice_number, <invoiceFields()>
  FROM invoices
  WHERE id = :id;
>>

create() ::= <<
  INSERT INTO invoices(<invoiceFields()>)
  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
>>


getRecordId() ::= <<
    SELECT record_id
    FROM invoices
    WHERE id = :id;
>>

auditFields(prefix) ::= <<
    <prefix>table_name,
    <prefix>record_id,
    <prefix>change_type,
    <prefix>change_date,
    <prefix>changed_by,
    <prefix>reason_code,
    <prefix>comments,
    <prefix>user_token
>>

insertAuditFromTransaction() ::= <<
    INSERT INTO audit_log(<auditFields()>)
    VALUES(:tableName, :recordId, :changeType, :createdDate, :userName, :reasonCode, :comment, :userToken);
>>

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