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 = '0'
  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 = '0'
  ORDER BY target_date ASC;
>>

getInvoicesBySubscription() ::= <<
  SELECT i.record_id as invoice_number, <invoiceFields("i.")>
  FROM invoices i
  JOIN invoice_items ii ON i.id = ii.invoice_id
  WHERE ii.subscription_id = :subscriptionId AND i.migrated = '0';
>>

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

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

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

getInvoiceIdByPaymentId() ::= <<
  SELECT i.id
    FROM invoices i, invoice_payments ip
   WHERE ip.invoice_id = i.id
     AND ip.payment_id = :paymentId
>>


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;
>>
;
