92 lines
2.6 KiB
Ruby
92 lines
2.6 KiB
Ruby
class CustomersController < ApplicationController
|
|
before_action :set_company
|
|
before_action :set_customer, only: %i[show edit update destroy]
|
|
|
|
# GET /customers or /customers.json
|
|
def index
|
|
@customers = Customer.all
|
|
end
|
|
|
|
# GET /customers/1 or /customers/1.json
|
|
def show; end
|
|
|
|
# GET /customers/new
|
|
def new
|
|
@customer = Customer.new
|
|
end
|
|
|
|
# GET /customers/1/edit
|
|
def edit; end
|
|
|
|
# POST /customers or /customers.json
|
|
def create
|
|
@customer = Customer.new(customer_params)
|
|
@customer.company = Company.first # Set the first company
|
|
|
|
respond_to do |format|
|
|
if @customer.save
|
|
format.html { redirect_to customer_url(@customer), notice: t('.customer_created') }
|
|
format.json { render :show, status: :created, location: @customer }
|
|
else
|
|
format.html { render :new, status: :unprocessable_entity }
|
|
format.json { render json: @customer.errors, status: :unprocessable_entity }
|
|
end
|
|
end
|
|
end
|
|
|
|
# PATCH/PUT /customers/1 or /customers/1.json
|
|
def update
|
|
respond_to do |format|
|
|
if @customer.update(customer_params)
|
|
format.html { redirect_to customer_url(@customer), notice: t('.customer_updated') }
|
|
format.json { render :show, status: :ok, location: @customer }
|
|
else
|
|
format.html { render :edit, status: :unprocessable_entity }
|
|
format.json { render json: @customer.errors, status: :unprocessable_entity }
|
|
end
|
|
end
|
|
end
|
|
|
|
# DELETE /customers/1 or /customers/1.json
|
|
def destroy
|
|
@customer.destroy!
|
|
|
|
respond_to do |format|
|
|
format.html { redirect_to customers_url, notice: t('.customer_destroyed') }
|
|
format.json { head :no_content }
|
|
end
|
|
end
|
|
|
|
def search
|
|
@customers = @company.customers.where(
|
|
"LOWER(first_name) LIKE :query OR LOWER(surname) LIKE :query OR original_phone LIKE :query",
|
|
query: "%#{params[:q].downcase}%"
|
|
).limit(10)
|
|
|
|
render json: @customers.map { |c|
|
|
{
|
|
id: "#{c.first_name}_#{c.surname}_#{c.original_phone}",
|
|
label: "#{c.full_name} (#{c.original_phone})",
|
|
birthyear: c.birthyear
|
|
}
|
|
}
|
|
end
|
|
|
|
private
|
|
|
|
# Use callbacks to share common setup or constraints between actions.
|
|
def set_customer
|
|
first_name, surname, original_phone = params[:composite_key].split('_')
|
|
@customer = Customer.find_by!(
|
|
first_name: first_name,
|
|
surname: surname,
|
|
original_phone: original_phone
|
|
)
|
|
end
|
|
|
|
# Only allow a list of trusted parameters through.
|
|
def customer_params
|
|
params.require(:customer).permit(:first_name, :surname, :phone, :notes, :email, :birthyear)
|
|
end
|
|
end
|