badar_madeena/app/controllers/incomes_controller.rb

103 lines
3.1 KiB
Ruby

class IncomesController < ApplicationController
before_action :set_income, only: %i[ show edit update destroy ]
# GET /incomes
def index
@incomes = Income.all
end
# GET /incomes/report
def report
# @incomes = Income.all
# # Group incomes
# @daily_income = @incomes.where(date: Date.today).sum(:amount)
# @weekly_income = @incomes.where(date: Date.today.beginning_of_week..Date.today.end_of_week).sum(:amount)
# @monthly_income = @incomes.where(date: Date.today.beginning_of_month..Date.today.end_of_month).sum(:amount)
# # List items
# @daily_income_items = @incomes.where(date: Date.today)
# @weekly_income_items = @incomes.where(date: Date.today.beginning_of_week..Date.today.end_of_week)
# @monthly_income_items = @incomes.where(date: Date.today.beginning_of_month..Date.today.end_of_month)
# # Chart (Group by Month)
# grouped = @incomes.group_by { |i| i.date.strftime("%b") }
# @chart_labels = grouped.keys
# @chart_data = grouped.values.map { |items| items.sum(&:amount) }
@incomes = Income.all
# Daily incomes
@daily_income_items = Income.where(date: Date.today)
@daily_income = @daily_income_items.sum(:amount)
# Weekly incomes
@weekly_income_items = Income.where(date: Date.today.beginning_of_week..Date.today.end_of_week)
@weekly_income = @weekly_income_items.sum(:amount)
# Monthly incomes
@monthly_income_items = Income.where(date: Date.today.beginning_of_month..Date.today.end_of_month)
@monthly_income = @monthly_income_items.sum(:amount)
# For charts - last 7 days
@chart_labels = (0..6).map { |i| (Date.today - i).strftime("%d %b") }.reverse
@chart_data = @chart_labels.map { |date_str|
date = Date.parse(date_str)
Income.where(date: date).sum(:amount)
}
end
def show
end
def new
@income = Income.new
end
def edit; end
def create
@income = Income.new(income_params)
respond_to do |format|
if @income.save
format.html { redirect_to @income, notice: "Income was successfully created." }
format.json { render :show, status: :created, location: @income }
else
format.html { render :new, status: :unprocessable_entity }
format.json { render json: @income.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @income.update(income_params)
format.html { redirect_to @income, notice: "Income was successfully updated.", status: :see_other }
format.json { render :show, status: :ok, location: @income }
else
format.html { render :edit, status: :unprocessable_entity }
format.json { render json: @income.errors, status: :unprocessable_entity }
end
end
end
def destroy
@income.destroy!
respond_to do |format|
format.html { redirect_to incomes_path, notice: "Income was successfully destroyed.", status: :see_other }
format.json { head :no_content }
end
end
private
def set_income
@income = Income.find(params[:id])
end
def income_params
params.require(:income).permit(:title, :amount, :date, :category, :description)
end
end