ruby on rails - Is this an efficient way of producing sales reporting / analytics? -
i have app receive & ingest daily sales reports multiple sources. structured differently store down postgres db in separate tables.
i'm doing iterate on last 30 days sales 1 report source , seems work quite nicely. concern how efficient & scaleable when add additional report sources way have structured means i'd have add , repeat large amounts of code each new source.
<% = date.today - 30 %> #30 days ago <% = date.today %> #today <% step_date = %> <% source_one_chart_data = [] %> #initialise empty array later pass js chart library <% begin %> <% count = @product.sales_source_one.total.where(:report_date => step_date).count %> #check if there sales product on current step date <% if count != 0 %> <% sale = @product.sum_total_net_by_day(step_date) %> <% source_one_chart_data.push(sale.to_s) %> #push sales total array if sales exist on date <% else %> <% source_one_chart_data.push("0") %> #otherwise push 0 array 30 days map value <% end %> <% step_date += 1.day %> #increase step_date 1 on each iteration of loop <% end while step_date <= %> #stop loop when reach date
can offer guidance on how efficiently bring in additional sales sources without having repeat code? also, if change step day week/month/year , have calculate sales accordingly; if sales source reported daily , step week sum values occur in step week.
why have of code in view? should move of model / controller.
def process_chart_data = 1.month.ago.to_date = date.today step_date = chart_data = [] while step_date <= sales_total = sales_source_one.total.where(report_date: step_date).count if sales_total.zero? chart_data.push(0) else sale = sum_total_net_by_day(step_date) chart_data.push(sale.to_s) end step_date += 1 end return chart_data end
the above refactored further, if place in product
model in controller can do:
@product = product.find(params[:id]) # or whatever @chart_data = @product.process_chart_data
then in view can use @chart_data
.
moving code method allows update quicker, lets want user control how far records retrieved:
def process_chart_data(start_date) = start_date ... end
in controller:
@product = product.find(params[:id]) @chart_data = @product.process_chart_data(params[:start_date])