2024-05-29 18:03:58 +02:00
|
|
|
{% set relevant_document_statuses = "('PAID', 'AUTHORISED')" %}
|
|
|
|
|
|
|
|
|
|
with
|
|
|
|
|
xero__invoices as (select * from {{ ref("xero__invoices") }}),
|
2025-04-25 11:55:14 +02:00
|
|
|
xero__credit_note_line_items as (
|
|
|
|
|
select * from {{ ref("xero__credit_note_line_items") }}
|
|
|
|
|
),
|
2024-05-29 18:03:58 +02:00
|
|
|
xero__contacts as (select * from {{ ref("xero__contacts") }}),
|
|
|
|
|
fees_invoiced as (
|
|
|
|
|
select
|
|
|
|
|
cast(
|
|
|
|
|
date_trunc('month', i.invoice_issued_date_utc) as date
|
|
|
|
|
) as invoice_issued_year_month,
|
2024-05-30 10:00:39 +02:00
|
|
|
c.id_deal,
|
2024-05-29 18:03:58 +02:00
|
|
|
sum(i.total_amount_wo_tax_in_gbp) as fees_invoiced
|
|
|
|
|
from xero__invoices i
|
|
|
|
|
left join xero__contacts c on i.id_contact = c.id_contact
|
2024-05-30 10:00:39 +02:00
|
|
|
where i.invoice_status in {{ relevant_document_statuses }}
|
|
|
|
|
group by date_trunc('month', i.invoice_issued_date_utc), c.id_deal
|
2024-05-29 18:03:58 +02:00
|
|
|
),
|
|
|
|
|
fees_credited as (
|
|
|
|
|
select
|
|
|
|
|
cast(
|
2025-04-25 11:55:14 +02:00
|
|
|
date_trunc('month', cnli.credit_note_issued_at_utc) as date
|
2024-05-29 18:03:58 +02:00
|
|
|
) as credit_note_issued_year_month,
|
2024-05-30 10:00:39 +02:00
|
|
|
c.id_deal,
|
2025-04-25 11:55:14 +02:00
|
|
|
sum(cnli.line_amount_wo_taxes_in_gbp) as fees_credited
|
|
|
|
|
from xero__credit_note_line_items cnli
|
|
|
|
|
left join xero__contacts c on cnli.id_contact = c.id_contact
|
|
|
|
|
where cnli.credit_note_status in {{ relevant_document_statuses }}
|
|
|
|
|
group by date_trunc('month', cnli.credit_note_issued_at_utc), c.id_deal
|
2024-05-29 18:03:58 +02:00
|
|
|
)
|
|
|
|
|
select
|
|
|
|
|
coalesce(
|
|
|
|
|
i.invoice_issued_year_month, c.credit_note_issued_year_month
|
|
|
|
|
) as issued_year_month,
|
2024-05-30 10:00:39 +02:00
|
|
|
coalesce(i.id_deal, c.id_deal) as id_deal,
|
2024-05-29 18:03:58 +02:00
|
|
|
coalesce(i.fees_invoiced, 0) as fees_invoiced_in_gbp,
|
|
|
|
|
coalesce(c.fees_credited, 0) as fees_credited_in_gbp,
|
|
|
|
|
(coalesce(i.fees_invoiced, 0) - coalesce(c.fees_credited, 0)) as net_fees_in_gbp
|
|
|
|
|
from fees_invoiced i
|
|
|
|
|
full outer join
|
|
|
|
|
fees_credited c
|
|
|
|
|
on i.invoice_issued_year_month = c.credit_note_issued_year_month
|
2024-05-30 10:00:39 +02:00
|
|
|
and i.id_deal = c.id_deal
|