<commit_before># frozen_string_literal: true

module Admin
  class OrderCyclesController < Admin::ResourceController
    include OrderCyclesHelper
    include PaperTrailLogging

    prepend_before_action :set_order_cycle_id, only: [:incoming, :outgoing]
    before_action :load_data_for_index, only: :index
    before_action :require_coordinator, only: :new
    before_action :remove_protected_attrs, only: [:update]
    before_action :require_order_cycle_set_params, only: [:bulk_update]
    around_action :protect_invalid_destroy, only: :destroy

    def index
      respond_to do |format|
        format.html
        format.json do
          render_as_json @collection,
                         ams_prefix: params[:ams_prefix],
                         current_user: spree_current_user,
                         subscriptions_count: OrderManagement::Subscriptions::Count.new(@collection)
        end
      end
    end

    def show
      respond_to do |format|
        format.html do
          redirect_to edit_admin_order_cycle_path(@order_cycle)
        end
        format.json do
          render_as_json @order_cycle, current_user: spree_current_user
        end
      end
    end

    def new
      respond_to do |format|
        format.html
        format.json do
          render_as_json @order_cycle, current_user: spree_current_user
        end
      end
    end

    def create
      @order_cycle_form = OrderCycleForm.new(@order_cycle, order_cycle_params, spree_current_user)

      if @order_cycle_form.save
        flash[:notice] = I18n.t(:order_cycles_create_notice)
        render json: { success: true,
                       edit_path: main_app.admin_order_cycle_incoming_path(@order_cycle) }
      else
        render json: { errors: @order_cycle.errors.full_messages }, status: :unprocessable_entity
      end
    end

    def set_order_cycle_id
      params[:id] = params[:order_cycle_id]
    end

    def update
      @order_cycle_form = OrderCycleForm.new(@order_cycle, order_cycle_params, spree_current_user)

      if @order_cycle_form.save
        update_nil_subscription_line_items_price_estimate(@order_cycle)
        respond_to do |format|
          flash[:notice] = I18n.t(:order_cycles_update_notice) if params[:reloading] == '1'
          format.html { redirect_back(fallback_location: root_path) }
          format.json { render json: { success: true } }
        end
      else
        render json: { errors: @order_cycle.errors.full_messages }, status: :unprocessable_entity
      end
    end

    def bulk_update
      if order_cycle_set&.save
        bulk_update_nil_subscription_line_items_price_estimate
        render_as_json @order_cycles,
                       ams_prefix: 'index',
                       current_user: spree_current_user,
                       subscriptions_count: OrderManagement::Subscriptions::Count.new(@collection)
      else
        order_cycle = order_cycle_set.collection.find{ |oc| oc.errors.present? }
        render json: { errors: order_cycle.errors.full_messages }, status: :unprocessable_entity
      end
    end

    def bulk_update_nil_subscription_line_items_price_estimate
      @collection.upcoming.each do |order_cycle|
        update_nil_subscription_line_items_price_estimate(order_cycle)
      end
    end

    def update_nil_subscription_line_items_price_estimate(order_cycle)
      order_cycle.schedules.each do |schedule|
        subscription = Subscription.find_by(schedule_id: schedule.id)
        shop = Enterprise.managed_by(spree_current_user).find_by(id: subscription.shop_id)
        subscription.subscription_line_items.nil_price_estimate.each do |line_item|
          variant = OrderManagement::Subscriptions::VariantsList
            .eligible_variants(shop).find_by(id: line_item.variant_id)
          fee_calculator = OpenFoodNetwork::EnterpriseFeeCalculator.new(shop, order_cycle)
          price = variant.price + fee_calculator.indexed_fees_for(variant)
          line_item.update_column(:price_estimate, price)
        end
      end
    end

    def clone
      @order_cycle = OrderCycle.find params[:id]
      @order_cycle.clone!
      redirect_to main_app.admin_order_cycles_path,
                  notice: I18n.t(:order_cycles_clone_notice, name: @order_cycle.name)
    end

    # Send notifications to all producers who are part of the order cycle
    def notify_producers
      OrderCycleNotificationJob.perform_later params[:id].to_i

      redirect_to main_app.admin_order_cycles_path,
                  notice: I18n.t(:order_cycles_email_to_producers_notice)
    end

    protected

    def collection
      return Enterprise.where("1=0") unless json_request?<commit_msg>Find subscriptions in schedule to recalculate nil estimate price<commit_after># frozen_string_literal: true

module Admin
  class OrderCyclesController < Admin::ResourceController
    include OrderCyclesHelper
    include PaperTrailLogging

    prepend_before_action :set_order_cycle_id, only: [:incoming, :outgoing]
    before_action :load_data_for_index, only: :index
    before_action :require_coordinator, only: :new
    before_action :remove_protected_attrs, only: [:update]
    before_action :require_order_cycle_set_params, only: [:bulk_update]
    around_action :protect_invalid_destroy, only: :destroy

    def index
      respond_to do |format|
        format.html
        format.json do
          render_as_json @collection,
                         ams_prefix: params[:ams_prefix],
                         current_user: spree_current_user,
                         subscriptions_count: OrderManagement::Subscriptions::Count.new(@collection)
        end
      end
    end

    def show
      respond_to do |format|
        format.html do
          redirect_to edit_admin_order_cycle_path(@order_cycle)
        end
        format.json do
          render_as_json @order_cycle, current_user: spree_current_user
        end
      end
    end

    def new
      respond_to do |format|
        format.html
        format.json do
          render_as_json @order_cycle, current_user: spree_current_user
        end
      end
    end

    def create
      @order_cycle_form = OrderCycleForm.new(@order_cycle, order_cycle_params, spree_current_user)

      if @order_cycle_form.save
        flash[:notice] = I18n.t(:order_cycles_create_notice)
        render json: { success: true,
                       edit_path: main_app.admin_order_cycle_incoming_path(@order_cycle) }
      else
        render json: { errors: @order_cycle.errors.full_messages }, status: :unprocessable_entity
      end
    end

    def set_order_cycle_id
      params[:id] = params[:order_cycle_id]
    end

    def update
      @order_cycle_form = OrderCycleForm.new(@order_cycle, order_cycle_params, spree_current_user)

      if @order_cycle_form.save
        update_nil_subscription_line_items_price_estimate(@order_cycle)
        respond_to do |format|
          flash[:notice] = I18n.t(:order_cycles_update_notice) if params[:reloading] == '1'
          format.html { redirect_back(fallback_location: root_path) }
          format.json { render json: { success: true } }
        end
      else
        render json: { errors: @order_cycle.errors.full_messages }, status: :unprocessable_entity
      end
    end

    def bulk_update
      if order_cycle_set&.save
        bulk_update_nil_subscription_line_items_price_estimate
        render_as_json @order_cycles,
                       ams_prefix: 'index',
                       current_user: spree_current_user,
                       subscriptions_count: OrderManagement::Subscriptions::Count.new(@collection)
      else
        order_cycle = order_cycle_set.collection.find{ |oc| oc.errors.present? }
        render json: { errors: order_cycle.errors.full_messages }, status: :unprocessable_entity
      end
    end

    def bulk_update_nil_subscription_line_items_price_estimate
      @collection.upcoming.each do |order_cycle|
        update_nil_subscription_line_items_price_estimate(order_cycle)
      end
    end

    def update_nil_subscription_line_items_price_estimate(order_cycle)
      order_cycle.schedules.each do |schedule|
        Subscription.where(schedule_id: schedule.id).each do |subscription|
          shop = Enterprise.managed_by(spree_current_user).find_by(id: subscription.shop_id)
          subscription.subscription_line_items.nil_price_estimate.each do |line_item|
            variant = OrderManagement::Subscriptions::
                VariantsList.eligible_variants(shop).find_by(id: line_item.variant_id)
            fee_calculator = OpenFoodNetwork::EnterpriseFeeCalculator.new(shop, order_cycle)
            price = variant.price + fee_calculator.indexed_fees_for(variant)
            line_item.update_column(:price_estimate, price)
          end
        end
      end
    end

    def clone
      @order_cycle = OrderCycle.find params[:id]
      @order_cycle.clone!
      redirect_to main_app.admin_order_cycles_path,
                  notice: I18n.t(:order_cycles_clone_notice, name: @order_cycle.name)
    end

    # Send notifications to all producers who are part of the order cycle
    def notify_producers
      OrderCycleNotificationJob.perform_later params[:id].to_i

      redirect_to main_app.admin_order_cycles_path,
                  notice: I18n.t(:order_cycles_email_to_producers_notice)
    end

    protected

    def collection
      return Enterprise.where("1=0") unless json_request?
{'fraction_non_alphanumeric': 0.06770337459007722, 'fraction_numerical': 0.0023273035015339044, 'mean_word_length': 2.882546201232033, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6098410', 'n_tokens_mistral': 2821, 'n_tokens_neox': 2736, 'n_words': 527}