group InvoiceDao: EntitySqlDao;

tableName() ::= "invoices"

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

tableValues() ::= <<
  :accountId
, :invoiceDate
, :targetDate
, :currency
, :migrated
, :createdBy
, :createdDate
>>

extraTableFieldsWithComma(prefix) ::= <<
, <prefix>record_id as invoice_number
>>

getInvoicesByAccount() ::= <<
  SELECT <allTableFields()>
  FROM <tableName()>
  WHERE account_id = :accountId AND migrated = '0'
  <AND_CHECK_TENANT()>
  ORDER BY target_date ASC;
>>

getAllInvoicesByAccount() ::= <<
  SELECT <allTableFields()>
  FROM <tableName()>
  WHERE account_id = :accountId
  <AND_CHECK_TENANT()>
  ORDER BY target_date ASC;
>>

getInvoicesByAccountAfterDate() ::= <<
  SELECT <allTableFields()>
  FROM <tableName()>
  WHERE account_id = :accountId AND target_date >= :fromDate AND migrated = '0'
  <AND_CHECK_TENANT()>
  ORDER BY target_date ASC;
>>

getInvoicesBySubscription() ::= <<
  SELECT <allTableFields("i.")>
  FROM <tableName()> i
  JOIN invoice_items ii ON i.id = ii.invoice_id
  WHERE ii.subscription_id = :subscriptionId AND i.migrated = '0'
  <AND_CHECK_TENANT("i.")>
  <AND_CHECK_TENANT("ii.")>
  ;
>>

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