dawarich/app/controllers/api/v1/visits_controller.rb

107 lines
2.6 KiB
Ruby
Raw Normal View History

2024-08-12 16:18:11 -04:00
# frozen_string_literal: true
2024-08-25 14:19:02 -04:00
class Api::V1::VisitsController < ApiController
2025-03-02 15:24:57 -05:00
def index
start_time = begin
Time.zone.parse(params[:start_at])
rescue StandardError
Time.zone.now.beginning_of_day
end
end_time = begin
Time.zone.parse(params[:end_at])
rescue StandardError
Time.zone.now.end_of_day
end
visits =
Visit
.includes(:place)
.where(user: current_api_user)
.where('started_at >= ? AND ended_at <= ?', start_time, end_time)
.order(started_at: :desc)
serialized_visits = visits.map do |visit|
Api::VisitSerializer.new(visit).call
end
render json: serialized_visits
end
2024-08-12 16:18:11 -04:00
def update
visit = current_api_user.visits.find(params[:id])
visit = update_visit(visit)
2025-03-03 14:11:21 -05:00
render json: Api::VisitSerializer.new(visit).call
2024-08-12 16:18:11 -04:00
end
2025-03-05 14:04:26 -05:00
def merge
# Validate that we have at least 2 visit IDs
visit_ids = params[:visit_ids]
if visit_ids.blank? || visit_ids.length < 2
return render json: { error: 'At least 2 visits must be selected for merging' }, status: :unprocessable_entity
end
# Find all visits that belong to the current user
visits = current_api_user.visits.where(id: visit_ids).order(started_at: :asc)
# Ensure we found all the visits
if visits.length != visit_ids.length
return render json: { error: 'One or more visits not found' }, status: :not_found
end
# Use the service to merge the visits
service = Visits::MergeService.new(visits)
merged_visit = service.call
if merged_visit&.persisted?
render json: Api::VisitSerializer.new(merged_visit).call, status: :ok
else
render json: { error: service.errors.join(', ') }, status: :unprocessable_entity
end
end
def bulk_update
service = Visits::BulkUpdateService.new(
current_api_user,
params[:visit_ids],
params[:status]
)
result = service.call
if result
render json: {
message: "#{result[:count]} visits updated successfully",
updated_count: result[:count]
}, status: :ok
else
render json: { error: service.errors.join(', ') }, status: :unprocessable_entity
end
end
2024-08-12 16:18:11 -04:00
private
def visit_params
2025-03-02 15:24:57 -05:00
params.require(:visit).permit(:name, :place_id, :status)
2024-08-12 16:18:11 -04:00
end
2025-03-05 14:04:26 -05:00
def merge_params
params.permit(visit_ids: [])
end
def bulk_update_params
params.permit(:status, visit_ids: [])
end
2024-08-12 16:18:11 -04:00
def update_visit(visit)
visit_params.each do |key, value|
visit[key] = value
visit.name = visit.place.name if visit_params[:place_id].present?
end
2024-08-25 14:19:02 -04:00
visit.save!
2024-08-12 16:18:11 -04:00
visit
end
end