WITH rescheduled AS (
SELECT
cap.customer_id AS customer_id,
cap.created_at::date AS date_of_reschedule,
old_loan.id AS old_loan_id,
new_loan.id AS new_loan_id
FROM loan_app_loan AS new_loan
INNER JOIN crm_app_purchase cap
ON new_loan.id = cap.loan_id
INNER JOIN crm_app_purchase cap2
ON cap2.id = cap.parent_purchase_id
INNER JOIN loan_app_loan AS old_loan
ON old_loan.id = cap2.loan_id
WHERE
cap2.is_rescheduled = TRUE
AND cap.created_at::date BETWEEN {'date':'start_date'} AND {'date':'end_date'}
),
old_enr AS (
SELECT
i.loan_id,
MIN(i.remaining_principal_expected) AS old_loan_enr
FROM loan_app_installment i
JOIN rescheduled r
ON r.old_loan_id = i.loan_id
WHERE i.day >= r.date_of_reschedule
GROUP BY i.loan_id
),
old_interest AS (
SELECT
i.loan_id,
SUM(i.interest_expected)::numeric AS old_loan_interest
FROM new_lms_installmentextension ie
join loan_app_installment i on i.id = ie.installment_ptr_id
JOIN rescheduled r
ON r.old_loan_id = i.loan_id
WHERE
i.day <= r.date_of_reschedule
AND ie.is_interest_paid = FALSE
GROUP BY i.loan_id
),
old_late_fees AS (
SELECT
i.loan_id,
SUM(lf.amount)::numeric AS old_loan_late_fees
FROM new_lms_installmentlatefees lf
JOIN new_lms_installmentextension ie
ON lf.installment_extension_id = ie.installment_ptr_id
join loan_app_installment i on i.id = lf.installment_extension_id
JOIN rescheduled r
ON r.old_loan_id = i.loan_id
WHERE
lf.is_paid = FALSE
AND lf.is_cancelled = FALSE
AND lf.is_disabled = FALSE
AND lf.day <= r.date_of_reschedule
GROUP BY i.loan_id
)
SELECT
r.customer_id AS "Customer ID",
r.date_of_reschedule AS "Date of Reschedule",
old_loan.id AS "Old Loan ID",
COALESCE(oe.old_loan_enr, old_loan.principle) AS "Old Loan ENR",
COALESCE(oi.old_loan_interest, 0) AS "Old Loan Interest",
COALESCE(ol.old_loan_late_fees, 0) AS "Old Loan Late Fees",
old_loan.principle AS "Old Loan Principal",
old_loan.period_installment AS "Old Installment",
old_loan.num_months AS "Old Loan Tenor",
old_loan.period_interest_rate AS "Old Loan Period Interest Rate",
old_loan.yearly_interest AS "Old Loan Yearly Interest",
old_status.name AS "Old Loan Status",
new_loan.id AS "New Loan ID",
new_loan.principle AS "New Loan Principal",
new_loan.period_installment AS "New Installment",
new_loan.num_months AS "New Loan Tenor",
new_loan.period_interest_rate AS "New Loan Period Interest Rate",
new_loan.yearly_interest AS "New Loan Yearly Interest",
new_status.name AS "New Loan Status"
FROM rescheduled r
JOIN loan_app_loan old_loan
ON old_loan.id = r.old_loan_id
JOIN loan_app_loan new_loan
ON new_loan.id = r.new_loan_id
JOIN loan_app_loanstatus old_status
ON old_status.id = old_loan.status_id
JOIN loan_app_loanstatus new_status
ON new_status.id = new_loan.status_id
LEFT JOIN old_enr oe
ON oe.loan_id = r.old_loan_id
LEFT JOIN old_interest oi
ON oi.loan_id = r.old_loan_id
LEFT JOIN old_late_fees ol
ON ol.loan_id = r.old_loan_id
ORDER BY
r.date_of_reschedule,
r.customer_id,
r.old_loan_id;