require_dependency 'application_controller' module Logistics module Core class RoutesController < ApplicationController before_action :set_route, only: [:update] # GET /routes # GET /routes.json def index @routes = Route.fetch_all response = Mks::Common::MethodResponse.new(true, nil, @routes, nil, nil) render json: response end # POST /routes # POST /routes.json def create route_type = params[:route][:route_type] if route_type == "Inter City" new_route = {from_id: route_params['from_id'], to_id: route_params['to_id'], description: route_params['description'], margin: route_params['margin'], route_type: route_params['route_type']} route = InterCityRoute.new(new_route) elsif route_type == "Within City" new_route = {node_id: route_params['node_id'], zone: route_params['zone'], radius: route_params['radius'], description: route_params['description'], margin: route_params['margin'], route_type: route_params['route_type']} route = WithinCityRoute.new(new_route) end if route.save response = Mks::Common::MethodResponse.new(true, "Route information saved successfully!", route, nil, nil) else errors = Mks::Common::Util.error_messages route, "Route Setup" response = Mks::Common::MethodResponse.new(false, nil, nil, errors, nil) end render json: response end # PATCH/PUT /routes/1 # PATCH/PUT /routes/1.json def update old_route = set_route route_type = params[:route][:route_type] if route_type == "Inter City" update_route = {from_id: route_params['from_id'], to_id: route_params['to_id'], description: route_params['description'], margin: route_params['margin'], route_type: route_params['route_type']} route = InterCityRoute.new(update_route) elsif route_type == "Within City" update_route = {node_id: route_params['node_id'], zone: route_params['zone'], radius: route_params['radius'], description: route_params['description'], margin: route_params['margin'], route_type: route_params['route_type']} route = WithinCityRoute.new(update_route) end if route.valid? if old_route.update(update_route) response = Mks::Common::MethodResponse.new(true, "Route information updated successfully!", old_route, nil, nil) end elsif old_route.id.to_s == params[:id] if old_route.update(update_route) response = Mks::Common::MethodResponse.new(true, "Route information updated successfully!", old_route, nil, nil) end else errors = Mks::Common::Util.error_messages route, "Route Setup" response = Mks::Common::MethodResponse.new(false, nil, nil, errors, nil) end render json: response end private def set_route @route = Route.find(params[:id]) end def route_params params.require(:route).permit(:from_id, :to_id, :node_id, :zone, :radius, :description, :margin, :route_type) end end end end