<commit_before>// variant autocompletion

$(document).ready(function() {

  initAlert()
  initConfirm()

  if ($('#variant_autocomplete_template').length > 0) {
    window.variantTemplate = Handlebars.compile($('#variant_autocomplete_template').text());
    window.variantStockTemplate = Handlebars.compile($('#variant_autocomplete_stock_template').text());

    // handle variant selection, show stock level.
    $('#add_variant_id').change(function(){
      var variant_id = $(this).val();

      var variant = _.find(window.variants, function(variant){
        return variant.id == variant_id
      })
      $('#stock_details').html(variantStockTemplate({variant: variant}));
      $('#stock_details').show();

      $('button.add_variant').click(addVariantFromStockLocation);

      // Add some tips
      $('.with-tip').powerTip({
        smartPlacement: true,
        fadeInTime: 50,
        fadeOutTime: 50,
        intentPollInterval: 300
      });

    });

    //handle edit click
    $('a.edit-item').click(toggleItemEdit);

    //handle cancel click
    $('a.cancel-item').click(toggleItemEdit);

    handle_save_click = function(){
      var save = $(this);
      var shipment_number = save.data('shipment-number');
      var variant_id = save.data('variant-id');

      var quantity = parseInt(save.parents('tr').find('input.line_item_quantity').val());
      var maxQuantity = parseInt(save.parents('tr').find('input.line_item_quantity').attr("max"));

      if (quantity > maxQuantity) {
        quantity = maxQuantity;
        save.parents('tr').find('input.line_item_quantity').val(maxQuantity);
        ofnAlert(t("js.admin.orders.quantity_adjusted"));
      }
      toggleItemEdit();

      adjustItems(shipment_number, variant_id, quantity);
      return false;
    }
    $('a.save-item').click(handle_save_click);

    handle_delete_click = function(elementSelector){
      var del = $(elementSelector);
      del.hide()
      var shipment_number = del.data('shipment-number');
      var variant_id = del.data('variant-id');

      toggleItemEdit();

      adjustItems(shipment_number, variant_id, 0);
    }

    $('a.delete-item').click((event) => {
      ofnConfirm(() => {
        handle_delete_click('#custom-confirm');
      });
    });

  }
});

adjustItems = function(shipment_number, variant_id, quantity){
  var shipment = _.findWhere(shipments, {number: shipment_number + ''});
  var inventory_units = _.where(shipment.inventory_units, {variant_id: variant_id});

  if (quantity == 0 && inventory_units.length == shipment.inventory_units.length) {
    ofnCancelOrderAlert((confirm, sendEmailCancellation) => {
      if (confirm) {
        doAdjustItems(shipment_number, variant_id, quantity, inventory_units, () => {
          var redirectTo = new URL(Spree.routes.cancel_order.toString());
          redirectTo.searchParams.append("send_cancellation_email", sendEmailCancellation);
          window.location.href = redirectTo.toString();
        });
      }
    });
    return;
  }
  doAdjustItems(shipment_number, variant_id, quantity, inventory_units, () => {
    window.location.reload();
  });
}

doAdjustItems = function(shipment_number, variant_id, quantity, inventory_units, callback) {
  var url = Spree.routes.orders_api + "/" + order_number + "/shipments/" + shipment_number;

  var new_quantity = 0;
  if (inventory_units.length < quantity) {
    url += "/add";
    new_quantity = (quantity - inventory_units.length);
  } else if (inventory_units.length > quantity) {
    url += "/remove"
    new_quantity = (inventory_units.length - quantity);
  }
  url += '.json';

  if (new_quantity == 0) {
    ofnAlert(t("js.admin.orders.quantity_unchanged"));
  } else {
    $.ajax({
      type: "PUT",
      url: Spree.url(url),
      data: { variant_id: variant_id, quantity: new_quantity }
    }).done(function( msg ) {
      callback();
    });
  }
}

toggleTrackingEdit = function(){
  var link = $(this);
  link.parents('tbody').find('tr.edit-tracking').toggle();
  link.parents('tbody').find('tr.show-tracking').toggle();
}

toggleMethodEdit = function(){
  var link = $(this);
  link.parents('tbody').find('tr.edit-method').toggle();
  link.parents('tbody').find('tr.show-method').toggle();
}

toggleItemEdit = function(){
  var link = $(this);
  link.parent().find('a.edit-item').toggle();
  link.parent().find('a.cancel-item').toggle();
  link.parent().find('a.save-item').toggle();
  link.parent().find('a.delete-item').toggle();
  link.parents('tr').find('td.item-qty-show').toggle();
  link.parents('tr').find('td.item-qty-edit').toggle();

  return false;
}

addVariantFromStockLocation = function() {
  $('#stock_details').hide();

  var variant_id = $('input.variant_autocomplete').val();
  var stock_location_id = $(this).data('stock-location-id');
  var quantity = $("input.quantity[data-stock-location-id='" + stock_location_id + "']").val();

  var shipment = _.find(shipments, function(shipment){
    return shipment.stock_location_id == stock_location_id && (shipment.state == 'ready' || shipment.state == 'pending');
  });

  if(shipment==undefined){
    $.ajax({
      type: "POST",
      url: Spree.url(Spree.routes.orders_api + "/" + order_number + "/shipments.json"),
      data: { variant_id: variant_id, quantity: quantity, stock_location_id: stock_location_id }
    }).done(function( msg ) {
      window.location.reload();
    }).error(function( msg ) {
      console.log(msg);
    });
  }else{
    //add to existing shipment
    adjustItems(shipment.number, variant_id, quantity);
  }
  return 1
}

initAlert = function() {
  $('#custom-alert .confirm').click(function(e) {
    $('#custom-alert').hide();
  })
}

initConfirm = function() {
  $('#custom-confirm button.cancel').click(function(e) {
    $('#custom-confirm').hide();
  });
}


ofnAlert = function(message) {
  $('#custom-alert .message').text(message);
  $('#custom-alert').show();
}

ofnCancelOrderAlert = function(callback) {
  $('#custom-confirm .message').html(
    ` ${t("js.admin.orders.cancel_the_order_html")}
      <div class="form">
        <input type="checkbox" name="send_cancellation_email" value="1" id="send_cancellation_email" />
        <label for="send_cancellation_email">${t("js.admin.orders.cancel_the_order_send_cancelation_email")}</label>
      </div>`);
  $('#custom-confirm button.confirm').unbind( "click" ).click(() => {
    $('#custom-confirm').hide();
    callback(true, $('#send_cancellation_email').is(':checked'));
  });
  $('#custom-confirm button.cancel').click(() => {
    $('#custom-confirm').hide();
    callback(false)
  });<commit_msg>ofnCancelOrderAlert can accept i18n key to customize message<commit_after>// variant autocompletion

$(document).ready(function() {

  initAlert()
  initConfirm()

  if ($('#variant_autocomplete_template').length > 0) {
    window.variantTemplate = Handlebars.compile($('#variant_autocomplete_template').text());
    window.variantStockTemplate = Handlebars.compile($('#variant_autocomplete_stock_template').text());

    // handle variant selection, show stock level.
    $('#add_variant_id').change(function(){
      var variant_id = $(this).val();

      var variant = _.find(window.variants, function(variant){
        return variant.id == variant_id
      })
      $('#stock_details').html(variantStockTemplate({variant: variant}));
      $('#stock_details').show();

      $('button.add_variant').click(addVariantFromStockLocation);

      // Add some tips
      $('.with-tip').powerTip({
        smartPlacement: true,
        fadeInTime: 50,
        fadeOutTime: 50,
        intentPollInterval: 300
      });

    });

    //handle edit click
    $('a.edit-item').click(toggleItemEdit);

    //handle cancel click
    $('a.cancel-item').click(toggleItemEdit);

    handle_save_click = function(){
      var save = $(this);
      var shipment_number = save.data('shipment-number');
      var variant_id = save.data('variant-id');

      var quantity = parseInt(save.parents('tr').find('input.line_item_quantity').val());
      var maxQuantity = parseInt(save.parents('tr').find('input.line_item_quantity').attr("max"));

      if (quantity > maxQuantity) {
        quantity = maxQuantity;
        save.parents('tr').find('input.line_item_quantity').val(maxQuantity);
        ofnAlert(t("js.admin.orders.quantity_adjusted"));
      }
      toggleItemEdit();

      adjustItems(shipment_number, variant_id, quantity);
      return false;
    }
    $('a.save-item').click(handle_save_click);

    handle_delete_click = function(elementSelector){
      var del = $(elementSelector);
      del.hide()
      var shipment_number = del.data('shipment-number');
      var variant_id = del.data('variant-id');

      toggleItemEdit();

      adjustItems(shipment_number, variant_id, 0);
    }

    $('a.delete-item').click((event) => {
      ofnConfirm(() => {
        handle_delete_click('#custom-confirm');
      });
    });

  }
});

adjustItems = function(shipment_number, variant_id, quantity){
  var shipment = _.findWhere(shipments, {number: shipment_number + ''});
  var inventory_units = _.where(shipment.inventory_units, {variant_id: variant_id});

  if (quantity == 0 && inventory_units.length == shipment.inventory_units.length) {
    ofnCancelOrderAlert((confirm, sendEmailCancellation) => {
      if (confirm) {
        doAdjustItems(shipment_number, variant_id, quantity, inventory_units, () => {
          var redirectTo = new URL(Spree.routes.cancel_order.toString());
          redirectTo.searchParams.append("send_cancellation_email", sendEmailCancellation);
          window.location.href = redirectTo.toString();
        });
      }
    });
    return;
  }
  doAdjustItems(shipment_number, variant_id, quantity, inventory_units, () => {
    window.location.reload();
  });
}

doAdjustItems = function(shipment_number, variant_id, quantity, inventory_units, callback) {
  var url = Spree.routes.orders_api + "/" + order_number + "/shipments/" + shipment_number;

  var new_quantity = 0;
  if (inventory_units.length < quantity) {
    url += "/add";
    new_quantity = (quantity - inventory_units.length);
  } else if (inventory_units.length > quantity) {
    url += "/remove"
    new_quantity = (inventory_units.length - quantity);
  }
  url += '.json';

  if (new_quantity == 0) {
    ofnAlert(t("js.admin.orders.quantity_unchanged"));
  } else {
    $.ajax({
      type: "PUT",
      url: Spree.url(url),
      data: { variant_id: variant_id, quantity: new_quantity }
    }).done(function( msg ) {
      callback();
    });
  }
}

toggleTrackingEdit = function(){
  var link = $(this);
  link.parents('tbody').find('tr.edit-tracking').toggle();
  link.parents('tbody').find('tr.show-tracking').toggle();
}

toggleMethodEdit = function(){
  var link = $(this);
  link.parents('tbody').find('tr.edit-method').toggle();
  link.parents('tbody').find('tr.show-method').toggle();
}

toggleItemEdit = function(){
  var link = $(this);
  link.parent().find('a.edit-item').toggle();
  link.parent().find('a.cancel-item').toggle();
  link.parent().find('a.save-item').toggle();
  link.parent().find('a.delete-item').toggle();
  link.parents('tr').find('td.item-qty-show').toggle();
  link.parents('tr').find('td.item-qty-edit').toggle();

  return false;
}

addVariantFromStockLocation = function() {
  $('#stock_details').hide();

  var variant_id = $('input.variant_autocomplete').val();
  var stock_location_id = $(this).data('stock-location-id');
  var quantity = $("input.quantity[data-stock-location-id='" + stock_location_id + "']").val();

  var shipment = _.find(shipments, function(shipment){
    return shipment.stock_location_id == stock_location_id && (shipment.state == 'ready' || shipment.state == 'pending');
  });

  if(shipment==undefined){
    $.ajax({
      type: "POST",
      url: Spree.url(Spree.routes.orders_api + "/" + order_number + "/shipments.json"),
      data: { variant_id: variant_id, quantity: quantity, stock_location_id: stock_location_id }
    }).done(function( msg ) {
      window.location.reload();
    }).error(function( msg ) {
      console.log(msg);
    });
  }else{
    //add to existing shipment
    adjustItems(shipment.number, variant_id, quantity);
  }
  return 1
}

initAlert = function() {
  $('#custom-alert .confirm').click(function(e) {
    $('#custom-alert').hide();
  })
}

initConfirm = function() {
  $('#custom-confirm button.cancel').click(function(e) {
    $('#custom-confirm').hide();
  });
}


ofnAlert = function(message) {
  $('#custom-alert .message').text(message);
  $('#custom-alert').show();
}

ofnCancelOrderAlert = function(callback, i18nKey) {
  if (i18nKey == undefined) {
    i18nKey = "js.admin.orders.cancel_the_order_html";
  }
  $('#custom-confirm .message').html(
    ` ${t(i18nKey)}
      <div class="form">
        <input type="checkbox" name="send_cancellation_email" value="1" id="send_cancellation_email" />
        <label for="send_cancellation_email">${t("js.admin.orders.cancel_the_order_send_cancelation_email")}</label>
      </div>`);
  $('#custom-confirm button.confirm').unbind( "click" ).click(() => {
    $('#custom-confirm').hide();
    callback(true, $('#send_cancellation_email').is(':checked'));
  });
  $('#custom-confirm button.cancel').click(() => {
    $('#custom-confirm').hide();
    callback(false)
  });
{'fraction_non_alphanumeric': 0.17946408466561586, 'fraction_numerical': 0.0028522104631089093, 'mean_word_length': 3.7585714285714285, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 33, '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': '982700', 'n_tokens_mistral': 4234, 'n_tokens_neox': 4109, 'n_words': 655}