Advertisement
madrahimov

Untitled

Jul 10th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.95 KB | None | 0 0
  1. sql = "
  2. WITH cashbox AS (
  3. SELECT work_date, sum(abs(amount)) as sum_amount
  4. FROM (
  5. SELECT work_date, amount
  6. FROM bill.cashbox_transactions
  7. WHERE is_active = true
  8. AND transaction_type IN (7, 8)
  9. AND restaurant_id = $1
  10. AND supplier_id = $4
  11. UNION ALL
  12. SELECT i.date, i.total
  13. FROM invoice_relocations i
  14. JOIN suppliers s on s.from_restaurant_id = i.send_restaurant_id
  15. WHERE i.is_active = true
  16. AND i.restaurant_id = $1
  17. AND i.is_send = true
  18. AND i.draft = false
  19. AND i.send_status = 2
  20. AND s.id = $4
  21. ) s
  22. GROUP BY work_date
  23. ), invoice AS (
  24. SELECT date, sum(total) as sum_total FROM (
  25. SELECT date, total
  26. FROM invoices
  27. WHERE is_active = true
  28. AND restaurant_id = $1
  29. AND draft = false
  30. AND sender_id = $4
  31. UNION ALL
  32. SELECT i.date, i.total
  33. FROM invoice_relocations i
  34. JOIN suppliers s on s.from_restaurant_id = i.from_restaurant_id
  35. WHERE i.is_active = true
  36. AND i.restaurant_id = $1
  37. AND i.draft = false
  38. AND i.send_status = 2
  39. AND i.is_send = false
  40. AND s.id = $4
  41. UNION ALL
  42. SELECT work_date, amount
  43. FROM bill.cashbox_transactions
  44. WHERE is_active = true
  45. AND transaction_type IN (10, 11)
  46. AND restaurant_id = $1
  47. AND supplier_id = $4
  48. ) s
  49. GROUP BY date
  50. ), cashbox_start AS (
  51. SELECT sum(sum_amount) as sum_amount
  52. FROM cashbox
  53. WHERE work_date < $2
  54. ), cashbox_between AS (
  55. SELECT sum(sum_amount) as sum_amount
  56. FROM cashbox
  57. WHERE work_date BETWEEN $2 AND $3
  58. ), invoice_start AS (
  59. SELECT sum(sum_total) as sum_amount
  60. FROM invoice
  61. WHERE date < $2
  62. ), invoice_between AS (
  63. SELECT sum(sum_total) as sum_amount
  64. FROM invoice
  65. WHERE date BETWEEN $2 AND $3
  66. )
  67. SELECT
  68. (COALESCE(cs.sum_amount, 0) - COALESCE(ins.sum_amount, 0)) AS saldo_start,
  69. COALESCE(cb.sum_amount, 0) AS paid_between,
  70. COALESCE(inb.sum_amount, 0) AS debt_between,
  71. (COALESCE(cs.sum_amount, 0) + COALESCE(cb.sum_amount, 0) - COALESCE(ins.sum_amount, 0) - COALESCE(inb.sum_amount, 0)) as saldo_end
  72. FROM
  73. cashbox_start cs,
  74. invoice_start ins,
  75. cashbox_between cb,
  76. invoice_between inb
  77. "
  78.  
  79. res = ActiveRecord::Base.using(@shard).connection.select_all(sql, "SQL", [[nil, @current_restaurant.id], [nil, @from], [nil, @to], [nil, @supplier.id]])
  80. res[0].symbolize_keys
  81. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement