module Comee module Core class ShipmentItemsController < ApplicationController include Common def index super do [ ShipmentItem.includes(sales_order_item: [sales_order: :client]).all, include: ["sales_order_item.sales_order.client"] ] end end def filter shipment_item = ShipmentItem.includes(:sales_order_item).ransack(params[:q]).result options = {include: ["sales_order_item.sales_order.client", "sales_order_item.product", "sales_order_item.unit"]} render_content(shipment_item, options) end def filter_for_client shipment_items = ShipmentItem.joins(sales_order_item: :sales_order) .where( comee_core_sales_order_items: { comee_core_sales_orders: { client_id: params[:id] } } ) render_content(shipment_items) end def filter_with_status items = ShipmentItem.includes(sales_order_item: %i[sales_order product unit]) .ransack(params[:q]).result statuses = ItemStatus.where(shipment_item_id: items.map(&:id)) .select("MAX(id) AS max_id, shipment_item_id") .group(:shipment_item_id) .all ids = statuses.map(&:max_id) statuses = ItemStatus.where(id: ids).each_with_object({}) { |status, res| res[status.shipment_item_id] = status } result = items.each_with_object([]) do |item, res| status = statuses[item.id] data = { sales_order_no: item.sales_order_item.sales_order.order_number, customer_item_no: item.sales_order_item.customer_item_no, product_code: item.sales_order_item.product.code, unit: item.sales_order_item.unit.code, quantity: item.sales_order_item.quantity, delivery_date: item.sales_order_item.delivery_date, handover_date: item.sales_order_item.sales_order.handover_date, status: status&.status } res << data.merge(status&.details) end render json: {success: true, data: result} end private def model_params params.require(:payload).permit(:sales_order_item_id, :quantity, :shipment_status, :status, :handover_date, :delivery_date, :pallet_no, :consignee, :order_number, :package_type) end end end end