Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- sql = "
- WITH cashbox AS (
- SELECT work_date, sum(abs(amount)) as sum_amount
- FROM (
- SELECT work_date, amount
- FROM bill.cashbox_transactions
- WHERE is_active = true
- AND transaction_type IN (7, 8)
- AND restaurant_id = $1
- AND supplier_id = $4
- UNION ALL
- SELECT i.date, i.total
- FROM invoice_relocations i
- JOIN suppliers s on s.from_restaurant_id = i.send_restaurant_id
- WHERE i.is_active = true
- AND i.restaurant_id = $1
- AND i.is_send = true
- AND i.draft = false
- AND i.send_status = 2
- AND s.id = $4
- ) s
- GROUP BY work_date
- ), invoice AS (
- SELECT date, sum(total) as sum_total FROM (
- SELECT date, total
- FROM invoices
- WHERE is_active = true
- AND restaurant_id = $1
- AND draft = false
- AND sender_id = $4
- UNION ALL
- SELECT i.date, i.total
- FROM invoice_relocations i
- JOIN suppliers s on s.from_restaurant_id = i.from_restaurant_id
- WHERE i.is_active = true
- AND i.restaurant_id = $1
- AND i.draft = false
- AND i.send_status = 2
- AND i.is_send = false
- AND s.id = $4
- UNION ALL
- SELECT work_date, amount
- FROM bill.cashbox_transactions
- WHERE is_active = true
- AND transaction_type IN (10, 11)
- AND restaurant_id = $1
- AND supplier_id = $4
- ) s
- GROUP BY date
- ), cashbox_start AS (
- SELECT sum(sum_amount) as sum_amount
- FROM cashbox
- WHERE work_date < $2
- ), cashbox_between AS (
- SELECT sum(sum_amount) as sum_amount
- FROM cashbox
- WHERE work_date BETWEEN $2 AND $3
- ), invoice_start AS (
- SELECT sum(sum_total) as sum_amount
- FROM invoice
- WHERE date < $2
- ), invoice_between AS (
- SELECT sum(sum_total) as sum_amount
- FROM invoice
- WHERE date BETWEEN $2 AND $3
- )
- SELECT
- (COALESCE(cs.sum_amount, 0) - COALESCE(ins.sum_amount, 0)) AS saldo_start,
- COALESCE(cb.sum_amount, 0) AS paid_between,
- COALESCE(inb.sum_amount, 0) AS debt_between,
- (COALESCE(cs.sum_amount, 0) + COALESCE(cb.sum_amount, 0) - COALESCE(ins.sum_amount, 0) - COALESCE(inb.sum_amount, 0)) as saldo_end
- FROM
- cashbox_start cs,
- invoice_start ins,
- cashbox_between cb,
- invoice_between inb
- "
- res = ActiveRecord::Base.using(@shard).connection.select_all(sql, "SQL", [[nil, @current_restaurant.id], [nil, @from], [nil, @to], [nil, @supplier.id]])
- res[0].symbolize_keys
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement