2025-01-13 20:38:47 +00:00
|
|
|
# Copyright (C) 2024 Manuel Bustillo
|
|
|
|
|
2025-01-13 21:37:02 +01:00
|
|
|
# Copyright (C) 2024-2025 LibreWeddingPlanner contributors
|
2024-10-28 22:02:49 +00:00
|
|
|
|
2024-12-28 18:37:47 +01:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2024-10-28 22:38:47 +01:00
|
|
|
module Expenses
|
|
|
|
class TotalQuery
|
2024-12-11 09:00:45 +01:00
|
|
|
private attr_reader :wedding
|
|
|
|
def initialize(wedding:)
|
|
|
|
@wedding = wedding
|
|
|
|
end
|
|
|
|
|
2024-10-28 22:38:47 +01:00
|
|
|
def call
|
2024-12-11 09:00:45 +01:00
|
|
|
ActiveRecord::Base.connection.execute(
|
|
|
|
ActiveRecord::Base.sanitize_sql_array([query, { wedding_id: wedding.id }])
|
|
|
|
).first
|
2024-10-28 22:38:47 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
def query
|
2024-12-28 18:16:36 +01:00
|
|
|
<<~SQL.squish
|
2024-10-28 22:57:03 +01:00
|
|
|
WITH guest_count AS (#{guest_count_per_status}),
|
|
|
|
expense_summary AS (#{expense_summary})
|
2024-12-11 09:00:45 +01:00
|
|
|
SELECT guest_count.confirmed as confirmed_guests,
|
|
|
|
guest_count.projected as projected_guests,
|
|
|
|
expense_summary.fixed + expense_summary.variable * guest_count.confirmed as total_confirmed,
|
|
|
|
expense_summary.fixed + expense_summary.variable * guest_count.projected as total_projected
|
2024-10-28 22:57:03 +01:00
|
|
|
FROM guest_count, expense_summary;
|
|
|
|
SQL
|
|
|
|
end
|
|
|
|
|
|
|
|
def expense_summary
|
2024-12-28 18:16:36 +01:00
|
|
|
<<~SQL.squish
|
2024-10-28 22:57:03 +01:00
|
|
|
SELECT coalesce(sum(amount) filter (where pricing_type = 'fixed'), 0) as fixed,
|
2024-12-11 09:00:45 +01:00
|
|
|
coalesce(sum(amount) filter (where pricing_type = 'per_person'), 0) as variable
|
2024-10-28 22:57:03 +01:00
|
|
|
FROM expenses
|
2024-12-11 09:00:45 +01:00
|
|
|
WHERE wedding_id = :wedding_id
|
2024-10-28 22:57:03 +01:00
|
|
|
SQL
|
|
|
|
end
|
|
|
|
|
|
|
|
def guest_count_per_status
|
2024-12-28 18:16:36 +01:00
|
|
|
<<~SQL.squish
|
2024-12-11 09:00:45 +01:00
|
|
|
SELECT COALESCE(count(*) filter(where status = #{Guest.statuses['confirmed']}), 0) as confirmed,
|
|
|
|
COALESCE(count(*) filter(where status IN (#{Guest.statuses.values_at('confirmed', 'invited', 'tentative').join(',')})), 0) as projected
|
2024-10-28 22:57:03 +01:00
|
|
|
FROM guests
|
2024-12-11 09:00:45 +01:00
|
|
|
WHERE wedding_id = :wedding_id
|
2024-10-28 22:38:47 +01:00
|
|
|
SQL
|
|
|
|
end
|
|
|
|
end
|
2024-12-11 09:00:45 +01:00
|
|
|
end
|