module Comee module Core class ClientPricesController < ApplicationController include Common def index super do ClientPrice.includes(:client, :product, :unit, :product_lookup).all end end def create super do price = ClientPrice.new(model_params) master_price = MasterPrice.find_by(product_id: price.product_id, primary: true) price.price = master_price&.selling_price if price.price price.price = price.margin_increase? ? price.price * (1 + price.margin / 100) : price.price * (1 - price.margin / 100) end price end end def update if @obj.draft? product_id = model_params[:product_id] || @obj.product_id master_price = MasterPrice.find_by(product_id: product_id, primary: true) @obj.price = master_price&.selling_price @obj.valid_from = model_params[:valid_from] if model_params[:valid_from] @obj.valid_to = model_params[:valid_to] if model_params[:valid_to] @obj.margin = model_params[:margin] if model_params[:margin] @obj.margin_type = model_params[:margin_type] if model_params[:margin_type] if @obj.price @obj.price = @obj.margin_increase? ? @obj.price * (1 + @obj.margin / 100) : @obj.price * (1 - @obj.margin / 100) @obj.price = @obj.price.round(2) end if @obj.save render_content(@obj) else render json: {success: false, error: @obj.errors.full_messages[0]}, status: :unprocessable_entity end else error = "Client price should be in draft state to edit." render json: {success: false, error: error}, status: :unprocessable_entity end rescue StandardError => e render json: {success: false, error: e.message} end def extend_validity price = ClientPrice.find(params[:id]) if price.draft? render json: {success: false, error: "Price must be an approved price for validity extension."} else price.valid_to = extend_params[:valid_to] price.save! render_content(price) end rescue StandardError => e render json: {success: false, error: e.message} end def fetch_for_client client = Client.find(params[:id]) client_id = client.parent_id || client.id prices = ClientPrice.includes(:client, :product, :unit, :product_lookup) .where(client_id: client_id) render_content(prices) end def fetch_one price = ClientPrice.includes(:client, :product, :unit, :product_lookup) .find_by( client_id: params[:id], product_id: fetch_one_params[:product_id], status: Price.statuses[:current] ) render_content(price) end def approve price = ClientPrice.find(params[:id]) price = price.approve render_content(price) rescue StandardError => e render json: {success: false, error: e.message}, status: :unprocessable_entity end def filter prices = ClientPrice.includes(:client, :product, :unit, :product_lookup) .ransack(params[:q]).result render_content(prices) end private def model_params params.require(:payload).permit(:valid_from, :valid_to, :product_id, :margin, :margin_type, :client_id, :previous_price, :unit_id) end def fetch_one_params params.permit(:product_id) end def extend_params params.require(:payload).permit(:valid_to) end end end end