2023-11-09 23:58:20 +08:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Lists
|
|
|
|
class BaseService
|
|
|
|
def initialize(raw_data, params, user: nil)
|
|
|
|
@raw_data = raw_data
|
|
|
|
@params = params
|
|
|
|
@user = user
|
2023-12-11 22:41:03 +08:00
|
|
|
@filters = params[:filters] || {}
|
2023-12-12 19:17:38 +08:00
|
|
|
@records = []
|
2023-11-09 23:58:20 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def call
|
2023-12-12 19:17:38 +08:00
|
|
|
fetch_records
|
|
|
|
filter_records
|
|
|
|
sort_records
|
|
|
|
paginate_records
|
|
|
|
@records
|
2023-11-09 23:58:20 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2024-02-28 04:00:11 +08:00
|
|
|
def fetch_records
|
|
|
|
raise NotImplementedError
|
|
|
|
end
|
|
|
|
|
2023-11-09 23:58:20 +08:00
|
|
|
def order_params
|
|
|
|
@order_params ||= @params.require(:order).permit(:column, :dir).to_h
|
|
|
|
end
|
|
|
|
|
2023-12-12 19:17:38 +08:00
|
|
|
def paginate_records
|
|
|
|
@records = @records.page(@params[:page]).per(@params[:per_page])
|
2023-11-09 23:58:20 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def sort_direction(order_params)
|
|
|
|
order_params[:dir] == 'asc' ? 'ASC' : 'DESC'
|
|
|
|
end
|
|
|
|
|
2023-12-12 19:17:38 +08:00
|
|
|
def sort_records
|
2024-03-21 16:08:55 +08:00
|
|
|
return unless @params[:order] && sortable_columns[order_params[:column].to_sym].present?
|
2023-11-09 23:58:20 +08:00
|
|
|
|
|
|
|
sort_by = "#{sortable_columns[order_params[:column].to_sym]} #{sort_direction(order_params)}"
|
2024-03-15 01:20:26 +08:00
|
|
|
@records = @records.order(sort_by).order(:id)
|
2023-11-09 23:58:20 +08:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|