Subida del módulo y tema de PrestaShop

This commit is contained in:
Kaloyan
2026-04-09 18:31:51 +02:00
parent 12c253296f
commit 16b3ff9424
39262 changed files with 7418797 additions and 0 deletions

15
js/admin/attachments.js Normal file
View File

@@ -0,0 +1,15 @@
/**
* For the full copyright and license information, please view the
* docs/licenses/LICENSE.txt file that was distributed with this source code.
*/
/**
* /!\ This file is deprecated, it will be deleted in next major release /!\
*/
'use strict';
var attachments = {
confirmProductAttached: function(product_list) {
return confirm(confirm_text + '\n\n' + product_list);
}
}

786
js/admin/carrier_wizard.js Normal file
View File

@@ -0,0 +1,786 @@
/**
* For the full copyright and license information, please view the
* docs/licenses/LICENSE.txt file that was distributed with this source code.
*/
var fees_is_hide = false;
$(function() {
carriersRangeInputs.watchCarriersRangeInputChange();
bind_inputs();
initCarrierWizard();
if (parseInt($('input[name="is_free"]:checked').val()))
is_freeClick($('input[name="is_free"]:checked'));
displayRangeType();
$('#attachement_fileselectbutton').on('click', function(e) {
$('#carrier_logo_input').trigger('click');
});
$('#attachement_filename').on('click', function(e) {
$('#carrier_logo_input').trigger('click');
});
$('#carrier_logo_input').on('change', function(e) {
var name = '';
if ($(this)[0].files !== undefined)
{
var files = $(this)[0].files;
$.each(files, function(index, value) {
name += value.name+', ';
});
$('#attachement_filename').val(name.slice(0, -2));
}
else // Internet Explorer 9 Compatibility
{
name = $(this).val().split(/[\\/]/);
$('#attachement_filename').val(name[name.length-1]);
}
});
$('#carrier_logo_remove').on('click', function(e) {
$('#attachement_filename').val('');
});
if ($('#is_free_on').prop('checked') === true)
{
$('#shipping_handling_off').prop('checked', true).prop('disabled', true);
$('#shipping_handling_on').prop('disabled', true).prop('checked', false);
}
$('#is_free_on').on('click', function(e) {
$('#shipping_handling_off').prop('checked', true).prop('disabled', true);
$('#shipping_handling_on').prop('disabled', true).prop('checked', false);
});
$('#is_free_off').on('click', function(e) {
if ($('#shipping_handling_off').prop('disabled') === true)
{
$('#shipping_handling_off').prop('disabled', false).prop('checked', false);
$('#shipping_handling_on').prop('disabled', false).prop('checked', true);
}
});
});
function initCarrierWizard()
{
$("#carrier_wizard").smartWizard({
'labelNext' : labelNext,
'labelPrevious' : labelPrevious,
'labelFinish' : labelFinish,
'fixHeight' : 1,
'onShowStep' : onShowStepCallback,
'onLeaveStep' : onLeaveStepCallback,
'onFinish' : onFinishCallback,
'transitionEffect' : 'slideleft',
'enableAllSteps' : enableAllSteps,
'keyNavigation' : false
});
displayRangeType();
}
function displayRangeType()
{
if ($('input[name="shipping_method"]:checked').val() == 1)
{
string = string_weight;
$('.weight_unit').show();
$('.price_unit').hide();
}
else
{
string = string_price;
$('.price_unit').show();
$('.weight_unit').hide();
}
is_freeClick($('input[name="is_free"]:checked'));
$('.range_type').html(string);
}
function onShowStepCallback()
{
$('.anchor li a').each(function () {
$(this).closest('li').addClass($(this).attr('class'));
});
$('#carrier_logo_block').prependTo($('div.content').filter(function() { return $(this).css('display') != 'none' }).find('.defaultForm').find('fieldset'));
}
function onFinishCallback(obj, context)
{
$('.wizard_error').remove();
$.ajax({
type:"POST",
url : validate_url,
async: false,
dataType: 'json',
data : $('#carrier_wizard .stepContainer .content form').serialize() + '&action=finish_step&ajax=1&step_number='+context.fromStep,
success : function(data) {
if (data.has_error)
{
displayError(data.errors, context.fromStep);
}
else
window.location.href = carrierlist_url;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
jAlert("TECHNICAL ERROR: \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
}
});
}
function onLeaveStepCallback(obj, context)
{
if (context.toStep == nbr_steps)
displaySummary();
return validateSteps(context.fromStep, context.toStep); // return false to stay on step and true to continue navigation
}
function displaySummary()
{
var id_default_lang = typeof default_language !== 'undefined' ? default_language : 1,
id_lang = id_default_lang;
// Try to find current employee language
if (typeof languages !== 'undefined' && typeof iso_user !== 'undefined')
for (var i=0; i<languages.length; i++)
if (languages[i]['iso_code'] == iso_user)
{
id_lang = languages[i]['id_lang'];
break;
}
// used as buffer - you must not replace directly in the translation vars
var tmp,
delay_text = $('#delay_' + id_lang).val();
// Assign text in default language if empty
if (!delay_text)
delay_text = $('#delay_' + id_default_lang).val();
// Carrier name
$('#summary_name').text($('#name').val());
// Delay and pricing
tmp = summary_translation_meta_informations.replace('%2$s', '<strong>' + delay_text + '</strong>');
if ($('#is_free_on').prop('checked'))
tmp = tmp.replace('%1$s', summary_translation_free);
else
tmp = tmp.replace('%1$s', summary_translation_paid);
$('#summary_meta_informations').html(tmp);
// Tax and calculation mode for the shipping cost
tmp = summary_translation_shipping_cost.replace('%2$s', $('#id_tax_rules_group option:selected').text());
if ($('#billing_price').prop('checked'))
tmp = tmp.replace('%1$s', summary_translation_price);
else if ($('#billing_weight').prop('checked'))
tmp = tmp.replace('%1$s', summary_translation_weight);
else
tmp = tmp.replace('%1$s', '<strong>' + summary_translation_undefined + '</strong>');
$('#summary_shipping_cost').text(tmp);
// Weight or price ranges
$('#summary_range').text(summary_translation_range+' '+summary_translation_range_limit);
if ($('input[name="shipping_method"]:checked').val() == 1)
unit = PS_WEIGHT_UNIT;
else
unit = currency_sign;
var range_inf = summary_translation_undefined;
var range_sup = summary_translation_undefined;
$('tr.range_inf td input').each(function()
{
if (!isNaN(parseFloat($(this).val())) && (range_inf == summary_translation_undefined || parseFloat(range_inf) > parseFloat($(this).val())))
range_inf = $(this).val();
});
$('tr.range_sup td input').each(function(){
if (!isNaN(parseFloat($(this).val())) && (range_sup == summary_translation_undefined || parseFloat(range_sup) < parseFloat($(this).val())))
range_sup = $(this).val();
});
$('#summary_range').html(
$('#summary_range').html()
.replace('%1$s', '<strong>' + range_inf +' '+ unit + '</strong>')
.replace('%2$s', '<strong>' + range_sup +' '+ unit + '</strong>')
.replace('%3$s', '<strong>' + $('#range_behavior option:selected').text().toLowerCase() + '</strong>')
);
if ($('#is_free_on').prop('checked'))
$('span.is_free').hide();
// Delivery zones
$('#summary_zones').html('');
$('.input_zone').each(function(){
if ($(this).prop('checked'))
$('#summary_zones').html($('#summary_zones').html() + '<li><strong>' + $(this).closest('tr').find('label').text() + '</strong></li>');
});
// Group restrictions
$('#summary_groups').html('');
$('input[name$="groupBox[]"]').each(function(){
if ($(this).prop('checked'))
$('#summary_groups').html($('#summary_groups').html() + '<li><strong>' + $(this).closest('tr').find('td:eq(2)').text() + '</strong></li>');
});
// shop restrictions
$('#summary_shops').html('');
$('.input_shop').each(function(){
if ($(this).prop('checked'))
$('#summary_shops').html($('#summary_shops').html() + '<li><strong>' + $(this).closest().text() + '</strong></li>');
});
}
function validateSteps(fromStep, toStep)
{
var is_ok = true;
if ((multistore_enable && fromStep == 3) || (!multistore_enable && fromStep == 2))
{
if (toStep > fromStep && !$('#is_free_on').prop('checked'))
{
is_ok = false;
$('.input_zone').each(function () {
if ($(this).prop('checked'))
is_ok = true;
});
if (!is_ok)
{
displayError([select_at_least_one_zone], fromStep);
return;
}
}
if (toStep > fromStep && !$('#is_free_on').prop('checked') && !validateRange(2))
is_ok = false;
}
$('.wizard_error').remove();
if (is_ok && isOverlapping())
is_ok = false;
if (is_ok)
{
form = $('#carrier_wizard #step-'+fromStep+' form');
$.ajax({
type:"POST",
url : validate_url,
async: false,
dataType: 'json',
data : form.serialize()+'&step_number='+fromStep+'&action=validate_step&ajax=1',
success : function(datas)
{
if (datas.has_error)
{
is_ok = false;
$('div.input-group input').on('focus', function () {
$(this).closest('div.input-group').removeClass('has-error');
});
displayError(datas.errors, fromStep);
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
jAlert("TECHNICAL ERROR: \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
}
});
}
return is_ok;
}
function displayError(errors, step_number)
{
$('#carrier_wizard .actionBar a.btn').removeClass('disabled');
$('.wizard_error').remove();
str_error = '<div class="error wizard_error" style="display:none"><ul>';
for (var error in errors)
{
$('#carrier_wizard .actionBar a.btn').addClass('disabled');
$('input[name="'+error+'"]').closest('div.input-group').addClass('has-error');
str_error += '<li>'+errors[error]+'</li>';
}
$('#step-'+step_number).prepend(str_error+'</ul></div>');
$('.wizard_error').fadeIn('fast');
bind_inputs();
}
function bind_inputs()
{
$('input').on('focus', function () {
$(this).closest('div.input-group').removeClass('has-error');
$('#carrier_wizard .actionBar a.btn').removeClass('disabled');
$('.wizard_error').fadeOut('fast', function () { $(this).remove()});
});
$('tr.delete_range td button').off('click').on('click', function () {
if (confirm(delete_range_confirm))
{
index = $(this).closest('td').index();
$('tr.range_sup td:eq('+index+'), tr.range_inf td:eq('+index+'), tr.fees_all td:eq('+index+'), tr.delete_range td:eq('+index+')').remove();
$('tr.fees').each(function () {
$(this).find('td:eq('+index+')').remove();
});
rebuildTabindex();
}
return false;
});
$('tr.fees td input:checkbox').off('change').on('change', function ()
{
if($(this).is(':checked'))
{
$(this).closest('tr').find('td').each(function () {
index = $(this).index();
if ($('tr.fees_all td:eq('+index+')').hasClass('validated'))
{
if($('#is_free_off').prop('checked') === true) {
enableGlobalFees(index);
$(this).find('div.input-group input:text').prop('disabled', false);
}
}
else
disabledGlobalFees(index);
});
}
else
$(this).closest('tr').find('td').find('div.input-group input:text').prop('disabled', true);
return false;
});
$('tr.range_sup td input:text, tr.range_inf td input:text').on('keypress', function (evn) {
index = $(this).closest('td').index();
if (evn.keyCode == 13)
{
if (validateRange(index))
enableRange(index);
else
disableRange(index);
return false;
}
});
$('tr.fees_all td input:text').on('keypress', function (evn) {
index = $(this).parent('td').index();
if (evn.keyCode == 13)
return false;
});
$(document.body).off('change', 'tr.fees_all td input').on('change', 'tr.fees_all td input', function() {
index = $(this).closest('td').index();
val = $(this).val();
$(this).val('');
$('tr.fees').each(function () {
$(this).find('td:eq('+index+') input:text:enabled').val(val);
});
return false;
});
$('input[name="is_free"]').off('click').on('click', function() {
is_freeClick(this);
});
$('input[name="shipping_method"]').off('click').on('click', function() {
$.ajax({
type:"POST",
url : validate_url,
async: false,
dataType: 'html',
data : 'id_carrier='+parseInt($('#id_carrier').val())+'&shipping_method='+parseInt($(this).val())+'&action=changeRanges&ajax=1',
success : function(data) {
$('#zone_ranges').replaceWith(data);
displayRangeType();
bind_inputs();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
jAlert("TECHNICAL ERROR: \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
}
});
});
$('#zones_table td input[type=text]').off('change').on('change', function () {
checkAllFieldIsNumeric();
});
}
function is_freeClick(elt)
{
var is_free = $(elt);
if (parseInt(is_free.val()))
hideFees();
else if (fees_is_hide)
showFees();
}
function hideFees()
{
$('tr.range_inf td, tr.range_sup td, tr.fees_all td, tr.fees td').each(function () {
if ($(this).index() >= 2)
{
$(this).find('input:text, button').prop('disabled', true).css('background-color', '#999999').css('border-color', '#999999');
$(this).css('background-color', '#999999');
}
});
fees_is_hide = true;
}
function showFees()
{
$('tr.range_inf td, tr.range_sup td, tr.fees_all td, tr.fees td').each(function () {
if ($(this).index() >= 2)
{
//enable only if zone is active
tr = $(this).closest('tr');
validate = $('tr.fees_all td:eq('+$(this).index()+')').hasClass('validated');
if ($(tr).index() > 2 && $(tr).find('td:eq(1) input').prop('checked') && validate || !$(tr).hasClass('range_sup') || !$(tr).hasClass('range_inf')) {
if($('#is_free_off').prop('checked') === true)
$(this).find('div.input-group input:text').prop('disabled', false);
}
$(this).find('input:text, button').css('background-color', '').css('border-color', '');
$(this).find('button').css('background-color', '').css('border-color', '').prop('disabled', false);
$(this).css('background-color', '');
}
});
}
function validateRange(index)
{
$('#carrier_wizard .actionBar a.btn').removeClass('disabled');
$('.wizard_error').remove();
var isValid = true;
var $currentRangeSup = $('tr.range_sup td:eq(' + index + ')').find('div.input-group input:text');
var $currentRangeInf = $('tr.range_inf td:eq(' + index + ')').find('div.input-group input:text');
var rangeSup = parseFloat($currentRangeSup.val().trim());
var rangeInf = parseFloat($currentRangeInf.val().trim());
//reset css error
$currentRangeSup.closest('div.input-group').removeClass('has-error');
$currentRangeInf.closest('div.input-group').removeClass('has-error');
if (isNaN(rangeSup) || rangeSup.length === 0) {
$currentRangeSup.closest('div.input-group').addClass('has-error');
isValid = false;
displayError([invalid_range], $("#carrier_wizard").smartWizard('currentStep'));
} else if (isValid && (isNaN(rangeInf) || rangeInf.length === 0)) {
$currentRangeInf.closest('div.input-group').addClass('has-error');
isValid = false;
displayError([invalid_range], $("#carrier_wizard").smartWizard('currentStep'));
} else if (isValid && rangeInf >= rangeSup) {
$currentRangeSup.closest('div.input-group').addClass('has-error');
$currentRangeInf.closest('div.input-group').addClass('has-error');
isValid = false;
displayError([invalid_range], $("#carrier_wizard").smartWizard('currentStep'));
} else if (isValid && (index > 2 || $('tr.range_sup td').not('.range_type, .range_sign').length > 1)) { //check range only if it's not the first range
isValid = !isOverlapping();
if (!isValid) {
$currentRangeSup.closest('div.input-group').addClass('has-error');
$currentRangeInf.closest('div.input-group').addClass('has-error');
displayError([range_is_overlapping], $("#carrier_wizard").smartWizard('currentStep'));
}
}
if (isValid) {
$('tr.range_sup td').not('.range_type, .range_sign').each( function () {
var $this = $(this);
var currentIndex = $this.index();
if ($this.find('.has-error').length > 0 && currentIndex !== index) {
isValid = validateRange(currentIndex);
if (isValid) {
enableRange(currentIndex);
}
}
});
}
isValid = !$currentRangeSup.closest('div.input-group').hasClass('has-error');
return isValid;
}
function enableZone(index)
{
if($('#is_free_off').prop('checked') === true) {
$('tr.fees').each(function () {
if ($(this).find('td:eq(1)').find('input[type=checkbox]:checked').length)
$(this).find('td:eq('+index+')').find('div.input-group input').prop('disabled', false);
});
}
}
function disableZone(index)
{
$('tr.fees').each(function () {
$(this).find('td:eq(' + index + ')').find('div.input-group input').prop('disabled', true);
});
}
function enableRange(index)
{
$('tr.fees').each(function () {
//only enable fees for enabled zones
if ($(this).find('td').find('input:checkbox').prop('checked') && $('#is_free_off').prop('checked') === true)
enableZone(index);
});
$('tr.fees_all td:eq('+index+')').addClass('validated').removeClass('not_validated');
enableGlobalFees(index);
bind_inputs();
}
function enableGlobalFees(index)
{
if($('#is_free_off').prop('checked') === true) {
$('span.fees_all').show();
$('tr.fees_all td:eq('+index+')').find('div.input-group input').show().prop('disabled', false);
$('tr.fees_all td:eq('+index+')').find('div.input-group .currency_sign').show();
}
}
function disabledGlobalFees(index)
{
$('span.fees_all').hide();
$('tr.fees_all td:eq('+index+')').find('div.input-group input').hide().prop('disabled', true);
$('tr.fees_all td:eq('+index+')').find('div.input-group .currency_sign').hide();
}
function disableRange(index)
{
$('tr.fees').each(function () {
//only enable fees for enabled zones
if ($(this).find('td').find('input:checkbox').prop('checked'))
disableZone(index);
});
$('tr.fees_all td:eq('+index+')').find('div.input-group input').prop('disabled', true);
$('tr.fees_all td:eq('+index+')').removeClass('validated').addClass('not_validated');
}
function add_new_range()
{
if (!$('tr.fees_all td:last').hasClass('validated'))
{
alert(need_to_validate);
return false;
}
last_sup_val = $('tr.range_sup td:last input').val();
//add new rand sup input
$('tr.range_sup td:last').after('<td class="range_data"><div class="input-group fixed-width-md"><span class="input-group-addon weight_unit" style="display: none;">'+PS_WEIGHT_UNIT+'</span><span class="input-group-addon price_unit" style="display: none;">'+currency_sign+'</span><input class="form-control" name="range_sup[]" type="text" autocomplete="off" /></div></td>');
//add new rand inf input
$('tr.range_inf td:last').after('<td class="border_bottom"><div class="input-group fixed-width-md"><span class="input-group-addon weight_unit" style="display: none;">'+PS_WEIGHT_UNIT+'</span><span class="input-group-addon price_unit" style="display: none;">'+currency_sign+'</span><input class="form-control" name="range_inf[]" type="text" value="'+last_sup_val+'" autocomplete="off" /></div></td>');
$('tr.fees_all td:last').after('<td class="border_top border_bottom"><div class="input-group fixed-width-md"><span class="input-group-addon currency_sign" style="display:none" >'+currency_sign+'</span><input class="form-control" style="display:none" type="text" /></div></td>');
$('tr.fees').each(function () {
$(this).find('td:last').after('<td><div class="input-group fixed-width-md"><span class="input-group-addon currency_sign">'+currency_sign+'</span><input class="form-control" disabled="disabled" name="fees['+$(this).data('zoneid')+'][]" type="text" /></div></td>');
});
$('tr.delete_range td:last').after('<td><button class="btn btn-default">'+labelDelete+'</button</td>');
bind_inputs();
rebuildTabindex();
displayRangeType();
return false;
}
function delete_new_range()
{
if ($('#new_range_form_placeholder').find('td').length = 1)
return false;
}
function checkAllFieldIsNumeric()
{
$('#carrier_wizard .actionBar a.btn').removeClass('disabled');
$('#zones_table td input[type=text]').each(function () {
if (!$.isNumeric($(this).val()) && $(this).val() != '')
$(this).closest('div.input-group').addClass('has-error');
});
}
function rebuildTabindex()
{
i = 1;
$('#zones_table tr').each(function ()
{
j = i;
$(this).find('td').each(function ()
{
j = zones_nbr + j;
if ($(this).index() >= 2 && $(this).find('div.input-group input'))
$(this).find('div.input-group input').attr('tabindex', j);
});
i++;
});
}
function repositionRange(current_index, new_index)
{
$('tr.range_sup, tr.range_inf, tr.fees_all, tr.fees, tr.delete_range ').each(function () {
$(this).find('td:eq('+current_index+')').each(function () {
$(this).closest('tr').find('td:eq('+new_index+')').after(this.outerHTML);
$(this).remove();
});
});
}
function checkRangeContinuity(reordering)
{
reordering = typeof reordering !== 'undefined' ? reordering : false;
res = true;
$('tr.range_sup td').not('.range_type, .range_sign').each(function ()
{
index = $(this).index();
if (index > 2)
{
range_sup = parseFloat($('tr.range_sup td:eq('+index+')').find('div.input-group input:text').val().trim());
range_inf = parseFloat($('tr.range_inf td:eq('+index+')').find('div.input-group input:text').val().trim());
prev_index = index-1;
prev_range_sup = parseFloat($('tr.range_sup td:eq('+prev_index+')').find('div.input-group input:text').val().trim());
prev_range_inf = parseFloat($('tr.range_inf td:eq('+prev_index+')').find('div.input-group input:text').val().trim());
if (range_inf < prev_range_inf || range_sup < prev_range_sup)
{
res = false;
if (reordering)
{
new_position = getCorrectRangePosistion(range_inf, range_sup);
if (new_position)
repositionRange(index, new_position);
}
}
}
});
if (res)
$('.ranges_not_follow').fadeOut();
else
$('.ranges_not_follow').fadeIn();
}
function getCorrectRangePosistion(current_inf, current_sup)
{
new_position = false;
$('tr.range_sup td').not('.range_type, .range_sign').each(function ()
{
index = $(this).index();
range_sup = parseFloat($('tr.range_sup td:eq('+index+')').find('div.input-group input:text').val().trim());
next_range_inf = 0
if ($('tr.range_inf td:eq('+index+1+')').length)
next_range_inf = parseFloat($('tr.range_inf td:eq('+index+1+')').find('div.input-group input:text').val().trim());
if (current_inf >= range_sup && current_sup < next_range_inf)
new_position = index;
});
return new_position;
}
function isOverlapping()
{
var isValid = false;
$('#carrier_wizard .actionBar a.btn').removeClass('disabled');
$('tr.range_sup td').not('.range_type, .range_sign').each(function() {
var index = $(this).index();
var currentInf = parseFloat($('.range_inf td:eq(' + index + ') input').val());
var currentSup = parseFloat($('.range_sup td:eq(' + index + ') input').val());
$('tr.range_sup td').not('.range_type, .range_sign').each(function() {
var testingIndex = $(this).index();
if (testingIndex !== index && testingIndex >= (index - 1)) { //do not test himself
var testingInf = parseFloat($('.range_inf td:eq(' + testingIndex + ') input').val());
var testingSup = parseFloat($('.range_sup td:eq(' + testingIndex + ') input').val());
var checkOverLapping = (index < testingIndex) ?
(currentInf >= testingInf || currentInf >= testingSup || currentSup > testingInf || currentSup >= testingSup)
: (currentInf <= testingInf || currentInf < testingSup || currentSup <= testingInf || currentSup <= testingSup);
if (checkOverLapping) {
$('tr.range_sup td:eq(' + testingIndex + ') div.input-group, tr.range_inf td:eq(' + testingIndex + ') div.input-group').addClass('has-error');
disableRange(testingIndex);
displayError([overlapping_range], $("#carrier_wizard").smartWizard('currentStep'));
isValid = true;
}
}
});
});
return isValid;
}
function checkAllZones(elt)
{
if($(elt).is(':checked'))
{
$('.input_zone').prop('checked', true);
$('.fees div.input-group input:text').each(function () {
index = $(this).closest('td').index();
enableGlobalFees(index);
if ($('tr.fees_all td:eq('+index+')').hasClass('validated') && $('#is_free_off').prop('checked') === true)
{
$(this).prop('disabled', false);
$('.fees_all td:eq('+index+') div.input-group input:text').prop('disabled', false);
}
});
}
else
{
$('.input_zone').prop('checked', false);
$('.fees div.input-group input:text, .fees_all div.input-group input:text').prop('disabled', true);
}
}
var carriersRangeInputs = {
/** Check the carriers range inputs after each change */
watchCarriersRangeInputChange: function() {
var $document = $(document);
var inputs = 'tr.range_sup td input:text, tr.range_inf td input:text';
$document.on('focus', inputs, function() {
$(this).closest('div.input-group').removeClass('has-error');
$(this).typeWatch({
captureLength: 0,
highlight: false,
wait: 1000,
callback: function() {
var index = $(this.el).closest('td').index();
var rangeSup = $('tr.range_sup td:eq(' + index + ')').find('div.input-group input:text').val().trim();
var rangeInf = $('tr.range_inf td:eq(' + index + ')').find('div.input-group input:text').val().trim();
if (rangeSup !== '' && rangeInf !== '') {
carriersRangeInputs.checkCarriersRangeValidation(index);
}
}
});
});
$document.on('blur', inputs, function() {
var $this = $(this);
$this.off();
var index = $this.closest('td').index();
var hasError = $('tr.range_sup td:eq(' + index + ') .has-error, tr.range_inf td:eq(' + index + ') .has-error');
if ($('.wizard_error').length === 0 || hasError.length !== 0) {
carriersRangeInputs.checkCarriersRangeValidation(index);
}
});
},
/**
* Check range validation
* @param {number} index
*/
checkCarriersRangeValidation: function(index) {
if (validateRange(index)) {
enableRange(index);
} else {
disableRange(index);
}
}
};

270
js/admin/dashboard.js Normal file
View File

@@ -0,0 +1,270 @@
/**
* For the full copyright and license information, please view the
* docs/licenses/LICENSE.txt file that was distributed with this source code.
*/
// This variables are defined in the dashboard view.tpl
// dashboard_ajax_url
// adminstats_ajax_url
// no_results_translation
// read_more
function refreshDashboard(module_name, extra) {
var module_list = [];
this.getWidget = function(module_id) {
$.ajax({
url : dashboard_ajax_url,
data : {
ajax: true,
action:'refreshDashboard',
module: module_list[module_id],
extra: extra
},
// Ensure to get fresh data
headers: { "cache-control": "no-cache" },
cache: false,
global: false,
dataType: 'json',
success : function(widgets){
for (var widget_name in widgets) {
for (var data_type in widgets[widget_name]) {
window[data_type](widget_name, widgets[widget_name][data_type]);
}
}
},
contentType: 'application/json'
});
};
if (module_name === false) {
$('.widget').each( function () {
module_list.push($(this).attr('id'));
$(this).addClass('loading');
});
} else {
module_list.push(module_name);
$('#'+module_name+' section').each( function (){
$(this).addClass('loading');
});
}
for (var module_id in module_list) {
this.getWidget(module_id);
}
}
function setDashboardDateRange(action) {
$('#datepickerFrom, #datepickerTo').parent('.input-group').removeClass('has-error');
var data = 'ajax=true&action=setDashboardDateRange&submitDatePicker=true&'+$('#calendar_form').serialize()+'&'+action+'=1';
$.ajax({
url : adminstats_ajax_url,
data : data,
dataType: 'json',
type: 'POST',
success : function(jsonData){
if (!jsonData.has_errors) {
refreshDashboard(false);
$('#datepickerFrom').val(jsonData.date_from);
$('#datepickerTo').val(jsonData.date_to);
}
else {
$('#datepickerFrom, #datepickerTo').parent('.input-group').addClass('has-error');
}
}
});
}
function data_value(widget_name, data) {
for (var data_id in data) {
$('#'+data_id+' ').html(data[data_id]);
$('#'+data_id+', #'+widget_name).closest('section').removeClass('loading');
}
}
function data_trends(widget_name, data) {
for (var data_id in data) {
this.el = $('#'+data_id);
this.el.html(data[data_id].value);
if (data[data_id].way === 'up') {
this.el.parent().removeClass('dash_trend_down').removeClass('dash_trend_right').addClass('dash_trend_up');
}
else if (data[data_id].way === 'down') {
this.el.parent().removeClass('dash_trend_up').removeClass('dash_trend_right').addClass('dash_trend_down');
}
else {
this.el.parent().removeClass('dash_trend_down').removeClass('dash_trend_up').addClass('dash_trend_right');
}
this.el.closest('section').removeClass('loading');
}
}
function data_table(widget_name, data) {
for (var data_id in data) {
//fill header
var tr = '<tr>';
for (var header in data[data_id].header) {
var head = data[data_id].header[header];
var th = '<th '+ (head.class ? ' class="'+head.class+'" ' : '' )+ ' '+(head.id ? ' id="'+head.id+'" ' : '' )+'>';
th += (head.wrapper_start ? ' '+head.wrapper_start+' ' : '' );
th += head.title;
th += (head.wrapper_stop ? ' '+head.wrapper_stop+' ' : '' );
th += '</th>';
tr += th;
}
tr += '</tr>';
$('#'+data_id+' thead').html(tr);
//fill body
$('#'+data_id+' tbody').html('');
if(typeof data[data_id].body === 'string') {
$('#'+data_id+' tbody').html('<tr><td class="text-center" colspan="'+data[data_id].header.length+'"><br/>'+data[data_id].body+'</td></tr>');
}
else if (data[data_id].body.length) {
for (var body_content_id in data[data_id].body) {
tr = '<tr>';
for (var body_content in data[data_id].body[body_content_id]) {
var body = data[data_id].body[body_content_id][body_content];
var td = '<td '+ (body.class ? ' class="'+body.class+'" ' : '' )+ ' '+(body.id ? ' id="'+body.id+'" ' : '' )+'>';
td += (body.wrapper_start ? ' '+body.wrapper_start+' ' : '' );
td += body.value;
td += (body.wrapper_stop ? ' '+body.wrapper_stop+' ' : '' );
td += '</td>';
tr += td;
}
tr += '</tr>';
$('#'+data_id+' tbody').append(tr);
}
}
else {
$('#'+data_id+' tbody').html('<tr><td class="text-center" colspan="'+data[data_id].header.length+'">'+no_results_translation+'</td></tr>');
}
}
}
function data_chart(widget_name, charts) {
for (var chart_id in charts) {
window[charts[chart_id].chart_type](widget_name, charts[chart_id]);
}
}
function data_list_small(widget_name, data) {
for (var data_id in data)
{
$('#'+data_id).html('');
for (var item in data[data_id]) {
$('#'+data_id).append('<li><span class="data_label">'+item+'</span><span class="data_value size_s">'+data[data_id][item]+'</span></li>');
}
$('#'+data_id+', #'+widget_name).closest('section').removeClass('loading');
}
}
function toggleDashConfig(widget) {
var func_name = widget + '_toggleDashConfig';
if ($('#'+widget+' section.dash_config').hasClass('hide'))
{
$('#'+widget+' section').not('.dash_config').slideUp(500, function () {
$('#'+widget+' section.dash_config').fadeIn(500).removeClass('hide');
if (window[func_name] != undefined)
window[func_name]();
});
}
else
{
$('#'+widget+' section.dash_config').slideUp(500, function () {
$('#'+widget+' section').not('.dash_config').slideDown(500).removeClass('hide');
$('#'+widget+' section.dash_config').addClass('hide');
if (window[func_name] != undefined)
window[func_name]();
});
}
}
function bindSubmitDashConfig() {
$('.submit_dash_config').on('click', function () {
saveDashConfig($(this).closest('section.widget').attr('id'));
return false;
});
}
function bindCancelDashConfig() {
$('.cancel_dash_config').on('click', function () {
toggleDashConfig($(this).closest('section.widget').attr('id'));
return false;
});
}
function saveDashConfig(widget_name) {
$('section#'+widget_name+' .form-group').removeClass('has-error');
$('#'+widget_name+'_errors').remove();
configs = '';
$('#'+widget_name+' form input, #'+widget_name+' form textarea , #'+widget_name+' form select').each( function () {
if ($(this).attr('type') === 'radio' && !$(this).attr('checked')) {
return;
}
configs += '&configs['+$(this).attr('name')+']='+$(this).val();
});
data = 'ajax=true&action=saveDashConfig&module='+widget_name+configs+'&hook='+$('#'+widget_name).closest('[id^=hook]').attr('id');
$.ajax({
url : dashboard_ajax_url,
data : data,
dataType: 'json',
error: function(XMLHttpRequest, textStatus, errorThrown) {
jAlert("TECHNICAL ERROR: \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
},
success : function(jsonData){
if (!jsonData.has_errors)
{
$('#'+widget_name).find('section').not('.dash_config').remove();
$('#'+widget_name).append($(jsonData.widget_html).find('section').not('.dash_config'));
refreshDashboard(widget_name);
toggleDashConfig(widget_name);
}
else
{
errors_str = '<div class="alert alert-danger" id="'+widget_name+'_errors">';
for (error in jsonData.errors)
{
errors_str += jsonData.errors[error]+'<br/>';
$('#'+error).closest('.form-group').addClass('has-error');
}
errors_str += '</div>';
$('section#'+widget_name+'_config header').after(errors_str);
errors_str += '</div>';
}
}
});
}
$( function () {
$('#calendar_form input[type="submit"]').on('click', function(elt) {
elt.preventDefault();
setDashboardDateRange(elt.currentTarget.name);
});
refreshDashboard(false);
bindSubmitDashConfig();
bindCancelDashConfig();
$('#page-header-desc-configuration-switch_demo i').removeClass('btn-primary');
$('#page-header-desc-configuration-switch_demo').tooltip().on('click', function(e) {
$.ajax({
url : dashboard_ajax_url,
data : {
ajax:true,
action:'setSimulationMode',
PS_DASHBOARD_SIMULATION: $(this).find('i').hasClass('process-icon-toggle-on') ? 0 : 1
},
success : function(result) {
if ($('#page-header-desc-configuration-switch_demo i').hasClass('process-icon-toggle-on')) {
$('#page-header-desc-configuration-switch_demo i').attr('class', 'process-icon-toggle-off switch_demo');
} else {
$('#page-header-desc-configuration-switch_demo i').attr('class', 'process-icon-toggle-on switch_demo');
}
refreshDashboard(false);
}
});
});
});

179
js/admin/dnd.js Normal file
View File

@@ -0,0 +1,179 @@
/**
* For the full copyright and license information, please view the
* docs/licenses/LICENSE.txt file that was distributed with this source code.
*/
$(function() {
initTableDnD();
});
function objToString(obj) {
var str = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + '=' + obj[p] + '&';
}
}
return str;
}
function initTableDnD(table)
{
if (typeof(table) == 'undefined')
table = 'table.tableDnD';
$(table).tableDnD({
onDragStart: function(table, row) {
originalOrder = $.tableDnD.serialize();
reOrder = ':even';
if (table.tBodies[0].rows[1] && $('#' + table.tBodies[0].rows[1].id).hasClass('alt_row'))
reOrder = ':odd';
$(table).find('#' + row.id).parent('tr').addClass('myDragClass');
},
dragHandle: 'dragHandle',
onDragClass: 'myDragClass',
onDrop: function(table, row) {
if (originalOrder != $.tableDnD.serialize()) {
var way = (originalOrder.indexOf(row.id) < $.tableDnD.serialize().indexOf(row.id))? 1 : 0;
var ids = row.id.split('_');
var tableDrag = table;
var params = '';
var tableId = table.id.replace('table-', '');
if (tableId == 'cms_block_0' || tableId == 'cms_block_1')
params = {
updatePositions: true,
configure: 'blockcms'
};
else if (tableId == 'category')
{
params = {
action: 'updatePositions',
id_category_parent: ids[1],
id_category_to_move: ids[2],
way: way
};
}
else if (tableId == 'cms_category')
params = {
action: 'updateCmsCategoriesPositions',
id_cms_category_parent: ids[1],
id_cms_category_to_move: ids[2],
way: way
};
else if (tableId == 'cms')
params = {
action: 'updateCmsPositions',
id_cms_category: ids[1],
id_cms: ids[2],
way: way
};
else if (come_from == 'AdminModulesPositions')
params = {
action: 'updatePositions',
id_hook: ids[0],
id_module: ids[1],
way: way
};
else if (tableId.indexOf('attribute') != -1 && tableId!= 'attribute_group') {
params = {
action: 'updateAttributesPositions',
id_attribute_group: ids[1],
id_attribute: ids[2],
way: way
};
}
else if (tableId == 'attribute_group') {
params = {
action: 'updateGroupsPositions',
id_attribute_group: ids[2],
way: way
}
}
else if (tableId == 'product') {
params = {
action: 'updatePositions',
id_category: ids[1],
id_product: ids[2],
way: way
};
}
else if (tableId.indexOf('module-') != -1) {
module = tableId.replace('module-', '');
params = {
updatePositions: true,
configure: module
};
}
// default
else
{
params = {
action : 'updatePositions',
id : ids[2],
way: way
}
}
params['ajax'] = 1;
params['page'] = parseInt($('input[name=page]').val());
params['selected_pagination'] = parseInt($('input[name=selected_pagination]').val());
var data = $.tableDnD.serialize().replace(/table-/g, '');
if ((tableId == 'category') && (data.indexOf('_0&') != -1))
data += '&found_first=1';
$.ajax({
type: 'POST',
headers: { "cache-control": "no-cache" },
async: false,
url: currentIndex + '&token=' + token + '&' + 'rand=' + new Date().getTime(),
data: data + '&' + objToString(params) ,
success: function(data) {
var nodrag_lines = $(tableDrag).find('tr:not(".nodrag")');
var new_pos;
if (come_from == 'AdminModulesPositions')
{
nodrag_lines.each(function(i) {
$(this).find('.positions').html(i+1);
});
}
else
{
if (tableId == 'product' || tableId.indexOf('attribute') != -1 || tableId == 'attribute_group' || tableId == 'feature')
var reg = /_[0-9][0-9]*$/g;
else
var reg = /_[0-9]$/g;
var up_reg = new RegExp('position=[-]?[0-9]+&');
nodrag_lines.each(function(i) {
if (params['page'] > 1)
new_pos = i + ((params['page'] - 1) * params['selected_pagination']);
else
new_pos = i;
$(this).attr('id', $(this).attr('id').replace(reg, '_' + new_pos));
$(this).find('.positions').text(new_pos + 1);
});
}
nodrag_lines.removeClass('odd');
nodrag_lines.filter(':odd').addClass('odd');
nodrag_lines.children('td.dragHandle').find('a').attr('disabled',false);
if (typeof alternate !== 'undefined' && alternate) {
nodrag_lines.children('td.dragHandle:first').find('a:odd').attr('disabled',true);
nodrag_lines.children('td.dragHandle:last').find('a:even').attr('disabled',true);
}
else {
nodrag_lines.children('td.dragHandle:first').find('a:even').attr('disabled',true);
nodrag_lines.children('td.dragHandle:last').find('a:odd').attr('disabled',true);
}
showSuccessMessage(update_success_msg);
}
});
}
}
});
}

22
js/admin/email.js Normal file
View File

@@ -0,0 +1,22 @@
/**
* For the full copyright and license information, please view the
* docs/licenses/LICENSE.txt file that was distributed with this source code.
*/
/**
* /!\ This file is deprecated, it will be deleted in next major release /!\
*/
$(function() {
if ($('input[name=PS_MAIL_METHOD]:checked').val() == 2)
$('#mail_fieldset_smtp').show();
else
$('#mail_fieldset_smtp').hide();
$('input[name=PS_MAIL_METHOD]').on('click', function() {
if ($(this).val() == 2)
$('#mail_fieldset_smtp').slideDown();
else
$('#mail_fieldset_smtp').slideUp();
});
});

18
js/admin/image.js Normal file
View File

@@ -0,0 +1,18 @@
/**
* For the full copyright and license information, please view the
* docs/licenses/LICENSE.txt file that was distributed with this source code.
*/
$(function(){
const formId = 'image_type_form';
// on submit, re-enable disabled checkbox so that it is properly sent to backend
const form = document.getElementById(formId);
form.onsubmit = () => {
const checkboxes = form.querySelectorAll('input[type="checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.disabled = false;
});
};
});

416
js/admin/import.js Normal file
View File

@@ -0,0 +1,416 @@
/**
* For the full copyright and license information, please view the
* docs/licenses/LICENSE.txt file that was distributed with this source code.
*/
var importCancelRequest = false;
var importContinueRequest = false;
$(function(){
$('#saveImportMatchs').off('click').on('click', function(){
var newImportMatchs = $('#newImportMatchs').val();
if (newImportMatchs == '')
jAlert(errorEmpty);
else
{
var matchFields = '';
$('.type_value').each( function () {
matchFields += '&'+$(this).attr('id')+'='+$(this).val();
});
$.ajax({
type: 'POST',
url: 'index.php',
async: false,
cache: false,
dataType : "json",
data: 'ajax=1&action=saveImportMatchs&controller=AdminImport&token=' + token + '&skip=' + $('input[name=skip]').val() + '&newImportMatchs=' + newImportMatchs + matchFields,
success: function(jsonData)
{
$('#valueImportMatchs').append('<option id="'+jsonData.id+'" value="'+matchFields+'" selected="selected">'+newImportMatchs+'</option>');
$('#selectDivImportMatchs').fadeIn('slow');
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
jAlert('TECHNICAL ERROR Details: ' + html_escape(XMLHttpRequest.responseText));
}
});
}
});
$('#loadImportMatchs').off('click').on('click', function(){
var idToLoad = $('select#valueImportMatchs option:selected').attr('id');
$.ajax({
type: 'POST',
url: 'index.php',
async: false,
cache: false,
dataType : "json",
data: 'ajax=1&action=loadImportMatchs&controller=AdminImport&token=' + token + '&idImportMatchs=' + idToLoad,
success: function(jsonData)
{
var matchs = jsonData.matchs.split('|')
$('input[name=skip]').val(jsonData.skip);
for (i=0;i<matchs.length;i++)
$('#type_value\\['+i+'\\]').val(matchs[i]).attr('selected',true).trigger("chosen:updated");
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
jAlert('TECHNICAL ERROR Details: ' + html_escape(XMLHttpRequest.responseText));
}
});
});
$('#deleteImportMatchs').off('click').on('click', function(){
var idToDelete = $('select#valueImportMatchs option:selected').attr('id');
$.ajax({
type: 'POST',
url: 'index.php',
async: false,
cache: false,
dataType : "json",
data: 'ajax=1&action=deleteImportMatchs&controller=AdminImport&token=' + token + '&idImportMatchs=' + idToDelete ,
success: function(jsonData)
{
$('select#valueImportMatchs option[id=\''+idToDelete+'\']').remove();
if ($('select#valueImportMatchs option').length == 0)
$('#selectDivImportMatchs').fadeOut();
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
jAlert('TECHNICAL ERROR Details: ' + html_escape(XMLHttpRequest.responseText));
}
});
});
$('#import_stop_button').off('click').on('click', function(){
if (importContinueRequest) {
$('#importProgress').modal('hide');
importContinueRequest = false;
window.location.href = window.location.href.split('#')[0]; // reload same URL but do not POST again (so in GET without param)
} else {
importCancelRequest = true;
$('#import_details_progressing').hide();
$('#import_details_finished').hide();
$('#import_details_stop').show();
$('#import_stop_button').hide();
$('#import_close_button').hide();
}
});
$('#import_continue_button').off('click').on('click', function(){
$('#import_continue_button').hide();
importContinueRequest = false;
$('#import_progress_div').show();
$('#import_details_warning ul, #import_details_info ul').html('');
$('#import_details_warning, #import_details_info').hide();
importNow(0, 5, -1, false, {}, 0);
});
});
function validateImportation(mandatory)
{
var type_value = [];
var seted_value = [];
var elem;
var col = 'unknow';
toggle(getE('error_duplicate_type'), false);
toggle(getE('required_column'), false);
for (i = 0; elem = getE('type_value['+i+']'); i++)
{
if ($.inArray(elem.options[elem.selectedIndex].value, seted_value) !== -1)
{
scroll(0,0);
toggle(getE('error_duplicate_type'), true);
return false;
}
else if (elem.options[elem.selectedIndex].value != 'no')
seted_value[elem.options[elem.selectedIndex].value] = true;
}
for (needed in mandatory)
if (!seted_value[mandatory[needed]])
{
scroll(0,0);
toggle(getE('required_column'), true);
getE('missing_column').innerHTML = mandatory[needed];
elem = getE('type_value[0]');
for (i = 0; i < elem.length; ++i)
{
if (elem.options[i].value == mandatory[needed])
{
getE('missing_column').innerHTML = elem.options[i].innerHTML;
break ;
}
}
return false
}
importNow(0, 5, -1, true, {}, 0); // starts with 5 elements to import, but the limit will be adapted for next calls automatically.
return false; // We return false to avoid form to be posted on the old Controller::postProcess() action
}
function importNow(offset, limit, total, validateOnly, crossStepsVariables, moreStep) {
if (offset == 0 && validateOnly) updateProgressionInit(); // first step only, in validation mode
if (offset == 0 && !validateOnly) updateProgression(0, total, limit, false, moreStep, null);
var data = $('form#import_form').serializeArray();
data.push({'name': 'crossStepsVars', 'value': JSON.stringify(crossStepsVariables)});
var startingTime = new Date().getTime();
$.ajax({
type: 'POST',
url: 'index.php?ajax=1&action=import&controller=AdminImport&offset='+offset+'&limit='+limit+'&token='+token+(validateOnly?'&validateOnly=1':'')+((moreStep>0)?'&moreStep='+moreStep:''),
cache: false,
dataType: "json",
data: data,
success: function(jsonData)
{
if (jsonData.totalCount) {
total = jsonData.totalCount;
}
if (jsonData.informations && jsonData.informations.length > 0) {
updateValidationInfo('<li>'+jsonData.informations.join('</li><li>')+'</li>');
}
if (jsonData.warnings && jsonData.warnings.length > 0) {
if (validateOnly)
updateValidationError('<li>'+jsonData.warnings.join('</li><li>')+'</li>', true);
else
updateProgressionError('<li>'+jsonData.warnings.join('</li><li>')+'</li>', true);
}
if (jsonData.errors && jsonData.errors.length > 0) {
if (validateOnly)
updateValidationError('<li>'+jsonData.errors.join('</li><li>')+'</li>', false);
else
updateProgressionError('<li>'+jsonData.errors.join('</li><li>')+'</li>', false);
return; // If errors, stops process
}
// Here, no errors returned
if (!jsonData.isFinished == true) {
// compute time taken by previous call to adapt amount of elements by call.
var previousDelay = new Date().getTime() - startingTime;
var targetDelay = 5000; // try to keep around 5 seconds by call
// acceleration will be limited to 4 to avoid newLimit to increase too fast (NEVER reach 30 seconds by call!).
var acceleration = Math.min(4, (targetDelay / previousDelay));
// keep between 5 to 100 elements to process in one call
var newLimit = Math.min(100, Math.max(5, Math.floor(limit * acceleration)));
var newOffset = offset + limit;
// update progression
if (validateOnly) {
updateValidation(jsonData.doneCount, total, jsonData.doneCount+newLimit);
} else {
updateProgression(jsonData.doneCount, total, jsonData.doneCount+newLimit, false, moreStep, jsonData.moreStepLabel);
}
if (importCancelRequest == true) {
$('#importProgress').modal('hide');
importCancelRequest = false;
window.location.href = window.location.href.split('#')[0]; // reload same URL but do not POST again (so in GET without param)
return; // stops execution
}
// process next group of elements
importNow(newOffset, newLimit, total, validateOnly, jsonData.crossStepsVariables, moreStep);
// checks if we could go over post_max_size setting. Warns when reach 90% of the actual setting
if (jsonData.nextPostSize >= jsonData.postSizeLimit * 0.9) {
var progressionDone = jsonData.doneCount * 100 / total;
var increase = Math.max(7, parseInt(jsonData.postSizeLimit/(progressionDone*1024*1024))) + 1; // min 8MB
$('#import_details_post_limit_value').html(increase+" MB");
$('#import_details_post_limit').show();
}
} else {
if (validateOnly) {
// update validation bar and process real import
updateValidation(total, total, total);
if (!$('#import_details_warning').is(":visible")) {
// no warning, directly import now
$('#import_progress_div').show();
importNow(0, 5, total, false, {}, 0);
} else {
// warnings occured. Ask if should continue to true import now
importContinueRequest = true;
$('#import_continue_button').show();
}
} else {
if (jsonData.oneMoreStep > moreStep) {
updateProgression(total, total, total, false, false, null); // do not close now
importNow(0, 5, total, false, jsonData.crossStepsVariables, jsonData.oneMoreStep);
} else {
updateProgression(total, total, total, true, moreStep, jsonData.moreStepLabel);
}
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
if (textStatus == 'parsererror') {
textStatus = 'Technical error: Unexpected response returned by server. Import stopped.';
}
if (validateOnly) {
updateValidationError(textStatus, false);
} else {
updateProgressionError(textStatus, false);
}
}
});
}
function updateProgressionInit() {
$('#importProgress').modal({backdrop: 'static', keyboard: false, closable: false});
$('#importProgress').modal('show');
$('#importProgress').on('hidden.bs.modal', function () {
window.location.href = window.location.href.split('#')[0]; // reload same URL but do not POST again (so in GET without param)
})
$('#import_details_progressing').show();
$('#import_details_finished').hide();
$('#import_details_error').hide();
$('#import_details_warning, #import_details_info').hide();
$('#import_details_stop').hide();
$('#import_details_post_limit').hide();
$('#import_details_error ul').html('');
$('#import_details_warning ul, #import_details_info ul').html('');
$('#import_validation_details').html($('#import_validation_details').attr('default-value'));
$('#validate_progressbar_done').width('0%');
$('#validate_progressbar_done').parent().addClass('active progress-striped');
$('#validate_progression_done').html('0');
$('#validate_progressbar_done2').width('0%');
$('#validate_progressbar_next').width('0%');
$('#validate_progressbar_next').removeClass('progress-bar-danger');
$('#validate_progressbar_next').addClass('progress-bar-info');
$('#import_progress_div').hide();
$('#import_progression_details').html($('#import_progression_details').attr('default-value'));
$('#import_progressbar_done').width('0%');
$('#import_progressbar_done').parent().addClass('active progress-striped');
$('#import_progression_done').html('0');
$('#import_progressbar_next').width('0%');
$('#import_progressbar_next').removeClass('progress-bar-danger');
$('#import_progressbar_next').addClass('progress-bar-success');
$('#import_stop_button').show();
$('#import_close_button').hide();
$('#import_continue_button').hide();
}
function updateValidation(currentPosition, total, nextPosition) {
if (currentPosition > total) currentPosition = total;
if (nextPosition > total) nextPosition = total;
var progressionDone = currentPosition * 100 / total;
var progressionNext = nextPosition * 100 / total;
if (total > 0) {
$('#import_validate_div').show();
$('#import_validation_details').html(currentPosition + '/' + total);
$('#validate_progressbar_done').width(progressionDone+'%');
$('#validate_progression_done').html(parseInt(progressionDone));
$('#validate_progressbar_next').width((progressionNext-progressionDone)+'%');
}
if (currentPosition == total && total == nextPosition) {
$('#validate_progressbar_done').parent().removeClass('active progress-striped');
}
}
function updateProgression(currentPosition, total, nextPosition, finish, moreStep, moreStepLabel) {
if (currentPosition > total) currentPosition = total;
if (nextPosition > total) nextPosition = total;
var progressionDone = currentPosition * 100 / total;
var progressionNext = nextPosition * 100 / total;
if (total > 0) {
$('#import_progress_div').show();
$('#import_progression_details').html(currentPosition + '/' + total);
if (moreStep == 0) {
$('#import_progressbar_done').width(progressionDone+'%');
$('#import_progression_done').html(parseInt(progressionDone));
$('#import_progressbar_next').width((progressionNext-progressionDone)+'%');
} else {
$('#import_progressbar_next').width('0%');
if (progressionDone === 100) {
$('#import_progressbar_done').width('100%');
$('#import_progressbar_done2').width('0%');
} else {
$('#import_progressbar_done').width((100-progressionDone)+'%');
$('#import_progressbar_done2').width(progressionDone+'%');
}
if (moreStepLabel) $('#import_progressbar_done2 span').html(moreStepLabel);
}
}
if (finish) {
$('#import_progressbar_done').parent().removeClass('active progress-striped');
$('#import_details_post_limit').hide();
$('#import_details_progressing').hide();
$('#import_details_finished').show();
$('#importProgress').modal({keyboard: true, closable: true});
$('#import_stop_button').hide();
$('#import_close_button').show();
}
}
function updateValidationError(message, forWarnings) {
$('#import_details_progressing').hide();
$('#import_details_finished').hide();
if (forWarnings) {
$('#import_details_warning ul').append(message);
$('#import_details_warning').show();
} else {
$('#import_details_error ul').append(message);
$('#import_details_error').show();
$('#validate_progressbar_next').addClass('progress-bar-danger');
$('#validate_progressbar_next').removeClass('progress-bar-info');
$('#import_stop_button').hide();
$('#import_close_button').show();
}
}
function updateValidationInfo(message) {
$('#import_details_progressing').hide();
$('#import_details_finished').hide();
$('#import_details_info ul').append(message);
$('#import_details_info').show();
}
function updateProgressionError(message, forWarnings) {
$('#import_details_progressing').hide();
$('#import_details_finished').hide();
if (forWarnings) {
$('#import_details_warning ul').append(message);
$('#import_details_warning').show();
} else {
$('#import_details_error ul').append(message);
$('#import_details_error').show();
$('#import_progressbar_next').addClass('progress-bar-danger');
$('#import_progressbar_next').removeClass('progress-bar-success');
$('#import_stop_button').hide();
$('#import_close_button').show();
}
}
function html_escape(str) {
return String(str)
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&#39;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}

15
js/admin/index.php Normal file
View File

@@ -0,0 +1,15 @@
<?php
/**
* For the full copyright and license information, please view the
* docs/licenses/LICENSE.txt file that was distributed with this source code.
*/
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Location: ../");
exit;

View File

@@ -0,0 +1,214 @@
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
$(function(){
//
// Used for the modules listing
//
if ($("#position_filer").length != 0)
{
var panel_selection = $("#modules-position-selection-panel");
var panel_selection_single_selection = panel_selection.find("#modules-position-single-selection");
var panel_selection_multiple_selection = panel_selection.find("#modules-position-multiple-selection");
var panel_selection_original_y = panel_selection.offset().top;
var panel_selection_original_y_top_margin = 111;
panel_selection.css("position", "relative").hide();
$(window).on("scroll", function (event) {
var scroll_top = $(window).scrollTop();
panel_selection.css(
"top",
scroll_top < panel_selection_original_y_top_margin
? 0
: scroll_top - panel_selection_original_y + panel_selection_original_y_top_margin
);
});
var modules_list = $(".modules-position-checkbox");
modules_list.on("change", function () {
var checked_count = modules_list.filter(":checked").length;
panel_selection.hide();
panel_selection_single_selection.hide();
panel_selection_multiple_selection.hide();
if (checked_count == 1)
{
panel_selection.show();
panel_selection_single_selection.show();
}
else if (checked_count > 1)
{
panel_selection.show();
panel_selection_multiple_selection.show();
panel_selection_multiple_selection.find("#modules-position-selection-count").html(checked_count);
}
});
panel_selection.find("button").on('click', function () {
$("button[name='unhookform']").trigger("click");
});
var hooks_list = [];
$("section.hook_panel").find(".hook_name").each(function () {
var $this = $(this);
hooks_list.push({
'title': $this.html(),
'element': $this,
'container': $this.parents(".hook_panel")
});
});
var show_modules = $("#show_modules");
show_modules.select2();
show_modules.on("change", function () {
modulesPositionFilterHooks();
});
var hook_position = $("#hook_position");
hook_position.on("change", function () {
modulesPositionFilterHooks();
});
$('#hook_search').on('input', function () {
modulesPositionFilterHooks();
});
function modulesPositionFilterHooks()
{
var id;
var hook_name = $('#hook_search').val();
var module_id = $("#show_modules").val();
var position = hook_position.prop('checked');
var regex = new RegExp("(" + hook_name + ")", "gi");
for (id = 0; id < hooks_list.length; id++)
{
hooks_list[id].container.toggle(hook_name == "" && module_id == "all");
hooks_list[id].element.html(hooks_list[id].title);
hooks_list[id].container.find('.module_list_item').removeClass('highlight');
}
if (hook_name != "" || module_id != "all")
{
var hooks_to_show_from_module = $();
var hooks_to_show_from_hook_name = $();
if (module_id != "all")
for (id = 0; id < hooks_list.length; id++)
{
var current_hooks = hooks_list[id].container.find(".module_position_" + module_id);
if (current_hooks.length > 0)
{
hooks_to_show_from_module = hooks_to_show_from_module.add(hooks_list[id].container);
current_hooks.addClass('highlight');
}
}
if (hook_name != "")
for (id = 0; id < hooks_list.length; id++)
{
var start = hooks_list[id].title.toLowerCase().search(hook_name.toLowerCase());
if (start != -1)
{
hooks_to_show_from_hook_name = hooks_to_show_from_hook_name.add(hooks_list[id].container);
hooks_list[id].element.html(hooks_list[id].title.replace(regex, '<span class="highlight">$1</span>'));
}
}
if (module_id == "all" && hook_name != "")
hooks_to_show_from_hook_name.show();
else if (hook_name == "" && module_id != "all")
hooks_to_show_from_module.show();
else
hooks_to_show_from_hook_name.filter(hooks_to_show_from_module).show();
}
if (!position)
for (id = 0; id < hooks_list.length; id++)
if (hooks_list[id].container.is('.hook_position'))
hooks_list[id].container.hide();
}
}
//
// Used for the anchor module page
//
$("#hook_module_form").find("select[name='id_module']").on('change', function(){
var $this = $(this);
var hook_select = $("select[name='id_hook']");
var optgroup_unregistered = $('#hooks_unregistered');
var optgroup_registered = $('#hooks_registered');
if ($this.val() != 0)
{
hook_select.find("option").remove();
$.ajax({
type: 'POST',
url: 'index.php',
async: true,
dataType: 'json',
data: {
action: 'getPossibleHookingListForModule',
controller: 'AdminModulesPositions',
ajax: 1,
module_id: $this.val(),
token: token
},
success: function (jsonData) {
if (jsonData.hasError)
{
var errors = '';
for (var error in jsonData.errors)
if (error != 'indexOf')
errors += $('<div />').html(jsonData.errors[error]).text() + "\n";
}
else
{
for (var current_hook = 0; current_hook < jsonData.length; current_hook++)
{
var hook_description = '';
if(jsonData[current_hook].description != '')
hook_description = ' ('+jsonData[current_hook].description+')';
var is_registered = jsonData[current_hook].registered;
var optgroup = is_registered ? optgroup_registered : optgroup_unregistered;
optgroup.append('<option value="'+jsonData[current_hook].id_hook+'">'+jsonData[current_hook].name+hook_description+'</option>');
}
hook_select.prop('disabled', false);
}
}
});
}
})
});

140
js/admin/notifications.js Normal file
View File

@@ -0,0 +1,140 @@
/**
* For the full copyright and license information, please view the
* docs/licenses/LICENSE.txt file that was distributed with this source code.
*/
$(function () {
if (youEditFieldFor) {
$('.translatable span.hint').append(`<br /><span class="red">${youEditFieldFor}</span>`);
}
$('.notification.dropdown-toggle').on('click', function () {
$(this).parent().toggleClass('open');
updateEmployeeNotifications();
});
$(document).on('click', function (e) {
if (!$(e.target).closest('#notification').length && $('#notification').hasClass('open')) {
$('#notification').removeClass('open');
getPush();
}
});
$('.notifications .nav-link').on('shown.bs.tab', function () {
updateEmployeeNotifications();
});
// call it once immediately, then use setTimeout
if (parseInt(show_new_orders) || parseInt(show_new_customers) || parseInt(show_new_messages)) {
getPush();
}
});
function updateEmployeeNotifications() {
$.post(
admin_notification_push_link,
{
type: $('.notifications .nav-item.active a').data('type')
}
);
}
function renderOrderNotification(value) {
const carrier = value.carrier !== '' ? ` - ${value.carrier}` : '';
return `
<a class="notif" href="${value.order_view_url}">
<span class="notif__id">#${value.id_order}</span>
<span class="notif__customer">
- ${from_msg} <strong>${value.customer_name}</strong> <span class="notif__iso">(${value.iso_code})</span>
</span>
<span class="notif__order-info">
<span class="notif__carrier">${carrier} -</span> <strong class="notif__total">${value.total_paid}</strong>
</span>
</a>
`;
}
function renderCustomerNotification(value) {
const company = value.company !== '' ? ` (${value.company})` : '';
return `
<a class="notif" href="${value.customer_view_url}">
<span class="notif__id">#${value.id_customer}</span>
<span class="notif__customer">
- <strong>${value.customer_name}</strong> ${company} -
</span>
<span class="notif__registered-date">${customer_name_msg} <strong>${value.date_add}</strong></span>
</a>
`;
}
function renderMessageNotification(value) {
const company = value.company !== '' ? ` (${value.company})` : '';
return `
<a class="notif" href="${value.customer_thread_view_url}">
<span class="notif__status ${value.status}">
<i class="material-icons">fiber_manual_record</i> ${value.status}
</span>
<span class="notif__customer">
- <strong>${value.customer_name}</strong> ${company} -
</span>
<span class="notif__date">
<i class="material-icons">access_time</i> ${value.date_add}
</span>
</a>
`;
}
function renderNotifications(panelId, data, renderFn) {
var panel = $('#' + panelId);
var tabCounter = panel.closest('#notification').find(`a[href="#${panelId}"] .notif-counter`);
if (data.total > 0) {
var html = data.results.map(renderFn).join('')
panel.removeClass('empty').children('.notification-elements').html(html);
tabCounter.text(` (${data.total})`).data('nb', data.total);
} else {
panel.addClass('empty').children('.notification-elements').empty();
tabCounter.text('');
}
}
function getPush() {
$.ajax({
type: 'POST',
headers: { "cache-control": "no-cache" },
url: `${admin_notification_get_link}&rand=${new Date().getTime()}`,
cache: false,
dataType: 'json',
success: function (json) {
setTimeout(getPush, 120000);
if (!json) {
return;
}
var notifCount = 0;
if (json.hasOwnProperty('order')) {
// Add orders notifications to the list
renderNotifications('orders-notifications', json.order, renderOrderNotification);
notifCount += parseInt(json.order.total)
}
if (json.hasOwnProperty('customer')) {
// Add customers notifications to the list
renderNotifications('customers-notifications', json.customer, renderCustomerNotification);
notifCount += parseInt(json.customer.total)
}
if (json.hasOwnProperty('customer_message')) {
// Add messages notifications to the list
renderNotifications('messages-notifications', json.customer_message, renderMessageNotification);
notifCount += parseInt(json.customer_message.total)
}
if (notifCount > 0) {
$("#total_notif_number_wrapper").removeClass('hide');
$('#total_notif_value').text(notifCount);
} else {
$("#total_notif_number_wrapper").addClass('hide');
}
}
});
}

286
js/admin/price.js Normal file
View File

@@ -0,0 +1,286 @@
/**
* For the full copyright and license information, please view the
* docs/licenses/LICENSE.txt file that was distributed with this source code.
*/
function getTax()
{
if (noTax)
return 0;
var selectedTax = document.getElementById('id_tax_rules_group');
var taxId = selectedTax.options[selectedTax.selectedIndex].value;
return taxesArray[taxId].rates[0];
}
function getTaxes()
{
if (noTax)
taxesArray[taxId];
var selectedTax = document.getElementById('id_tax_rules_group');
var taxId = selectedTax.options[selectedTax.selectedIndex].value;
return taxesArray[taxId];
}
function addTaxes(price)
{
var taxes = getTaxes();
var price_with_taxes = price;
if (taxes.computation_method == 0) {
for (i in taxes.rates) {
price_with_taxes *= (1 + taxes.rates[i] / 100);
break;
}
}
else if (taxes.computation_method == 1) {
var rate = 0;
for (i in taxes.rates) {
rate += taxes.rates[i];
}
price_with_taxes *= (1 + rate / 100);
}
else if (taxes.computation_method == 2) {
for (i in taxes.rates) {
price_with_taxes *= (1 + taxes.rates[i] / 100);
}
}
return price_with_taxes;
}
function removeTaxes(price)
{
var taxes = getTaxes();
var price_without_taxes = price;
if (taxes.computation_method == 0) {
for (i in taxes.rates) {
price_without_taxes /= (1 + taxes.rates[i] / 100);
break;
}
}
else if (taxes.computation_method == 1) {
var rate = 0;
for (i in taxes.rates) {
rate += taxes.rates[i];
}
price_without_taxes /= (1 + rate / 100);
}
else if (taxes.computation_method == 2) {
for (i in taxes.rates) {
price_without_taxes /= (1 + taxes.rates[i] / 100);
}
}
return price_without_taxes;
}
function getEcotaxTaxIncluded()
{
return ps_round(ecotax_tax_excl * (1 + ecotaxTaxRate), 2);
}
function getEcotaxTaxExcluded()
{
return ecotax_tax_excl;
}
function formatPrice(price)
{
var fixedToSix = (Math.round(price * 1000000) / 1000000);
return (Math.round(fixedToSix) == fixedToSix + 0.000001 ? fixedToSix + 0.000001 : fixedToSix);
}
function calcPrice()
{
var priceType = $('#priceType').val();
if (priceType == 'TE')
calcPriceTI();
else
calcPriceTE();
}
function calcPriceTI()
{
var priceTE = parseFloat(document.getElementById('priceTEReal').value.replace(/,/g, '.'));
var newPrice = addTaxes(priceTE);
document.getElementById('priceTI').value = (isNaN(newPrice) == true || newPrice < 0) ? '' :
ps_round(newPrice, priceDisplayPrecision);
document.getElementById('finalPrice').innerHTML = (isNaN(newPrice) == true || newPrice < 0) ? '' :
ps_round(newPrice, priceDisplayPrecision).toFixed(priceDisplayPrecision);
document.getElementById('finalPriceWithoutTax').innerHTML = (isNaN(priceTE) == true || priceTE < 0) ? '' :
(ps_round(priceTE, 6)).toFixed(6);
calcReduction();
if (isNaN(parseFloat($('#priceTI').val())))
{
$('#priceTI').val('');
$('#finalPrice').html('');
}
else
{
$('#priceTI').val((parseFloat($('#priceTI').val()) + getEcotaxTaxIncluded()).toFixed(priceDisplayPrecision));
$('#finalPrice').html(parseFloat($('#priceTI').val()).toFixed(priceDisplayPrecision));
}
}
function calcPriceTE()
{
ecotax_tax_excl = $('#ecotax').val() / (1 + ecotaxTaxRate);
var priceTI = parseFloat(document.getElementById('priceTI').value.replace(/,/g, '.'));
var newPrice = removeTaxes(ps_round(priceTI - getEcotaxTaxIncluded(), priceDisplayPrecision));
document.getElementById('priceTE').value = (isNaN(newPrice) == true || newPrice < 0) ? '' :
ps_round(newPrice, 6).toFixed(6);
document.getElementById('priceTEReal').value = (isNaN(newPrice) == true || newPrice < 0) ? 0 : ps_round(newPrice, 9);
document.getElementById('finalPrice').innerHTML = (isNaN(newPrice) == true || newPrice < 0) ? '' :
ps_round(priceTI, priceDisplayPrecision).toFixed(priceDisplayPrecision);
document.getElementById('finalPriceWithoutTax').innerHTML = (isNaN(newPrice) == true || newPrice < 0) ? '' :
(ps_round(newPrice, 6)).toFixed(6);
calcReduction();
}
function calcImpactPriceTI()
{
var priceTE = parseFloat(document.getElementById('attribute_priceTEReal').value.replace(/,/g, '.'));
var newPrice = addTaxes(priceTE);
$('#attribute_priceTI').val((isNaN(newPrice) == true || newPrice < 0) ? '' : ps_round(newPrice, priceDisplayPrecision).toFixed(priceDisplayPrecision));
var total = ps_round((parseFloat($('#attribute_priceTI').val()) * parseInt($('#attribute_price_impact').val()) + parseFloat($('#finalPrice').html())), priceDisplayPrecision);
if (isNaN(total) || total < 0)
$('#attribute_new_total_price').html('0.00');
else
$('#attribute_new_total_price').html(total);
}
function calcImpactPriceTE()
{
var priceTI = parseFloat(document.getElementById('attribute_priceTI').value.replace(/,/g, '.'));
priceTI = (isNaN(priceTI)) ? 0 : ps_round(priceTI);
var newPrice = removeTaxes(ps_round(priceTI, priceDisplayPrecision));
$('#attribute_price').val((isNaN(newPrice) == true || newPrice < 0) ? '' : ps_round(newPrice, 6).toFixed(6));
$('#attribute_priceTEReal').val((isNaN(newPrice) == true || newPrice < 0) ? 0 : ps_round(newPrice, 9));
var total = ps_round((parseFloat($('#attribute_priceTI').val()) * parseInt($('#attribute_price_impact').val()) + parseFloat($('#finalPrice').html())), priceDisplayPrecision);
if (isNaN(total) || total < 0)
$('#attribute_new_total_price').html('0.00');
else
$('#attribute_new_total_price').html(total);
}
function calcReduction()
{
if (parseFloat($('#reduction_price').val()) > 0)
reductionPrice();
else if (parseFloat($('#reduction_percent').val()) > 0)
reductionPercent();
}
function reductionPrice()
{
var price = document.getElementById('priceTI');
var priceWhithoutTaxes = document.getElementById('priceTE');
var newprice = document.getElementById('finalPrice');
var newpriceWithoutTax = document.getElementById('finalPriceWithoutTax');
var curPrice = price.value;
document.getElementById('reduction_percent').value = 0;
if (isInReductionPeriod())
{
var rprice = document.getElementById('reduction_price');
if (parseFloat(curPrice) <= parseFloat(rprice.value))
rprice.value = curPrice;
if (parseFloat(rprice.value) < 0 || isNaN(parseFloat(curPrice)))
rprice.value = 0;
curPrice = curPrice - rprice.value;
}
newprice.innerHTML = (ps_round(parseFloat(curPrice), priceDisplayPrecision) + getEcotaxTaxIncluded()).toFixed(priceDisplayPrecision);
var rpriceWithoutTaxes = ps_round(removeTaxes(rprice.value), priceDisplayPrecision);
newpriceWithoutTax.innerHTML = ps_round(priceWhithoutTaxes.value - rpriceWithoutTaxes, priceDisplayPrecision).toFixed(priceDisplayPrecision);
}
function reductionPercent()
{
var price = document.getElementById('priceTI');
var newprice = document.getElementById('finalPrice');
var newpriceWithoutTax = document.getElementById('finalPriceWithoutTax');
var curPrice = price.value;
document.getElementById('reduction_price').value = 0;
if (isInReductionPeriod())
{
var newprice = document.getElementById('finalPrice');
var rpercent = document.getElementById('reduction_percent');
if (parseFloat(rpercent.value) >= 100)
rpercent.value = 100;
if (parseFloat(rpercent.value) < 0)
rpercent.value = 0;
curPrice = price.value * (1 - (rpercent.value / 100));
}
newprice.innerHTML = (ps_round(parseFloat(curPrice), priceDisplayPrecision) + getEcotaxTaxIncluded()).toFixed(priceDisplayPrecision);
newpriceWithoutTax.innerHTML = ps_round(parseFloat(removeTaxes(ps_round(curPrice, priceDisplayPrecision))), priceDisplayPrecision).toFixed(priceDisplayPrecision);
}
function isInReductionPeriod()
{
var start = document.getElementById('reduction_from').value;
var end = document.getElementById('reduction_to').value;
if (start == end && start != "" && start != "0000-00-00 00:00:00") return true;
var sdate = new Date(start.replace(/-/g,'/'));
var edate = new Date(end.replace(/-/g,'/'));
var today = new Date();
return (sdate <= today && edate >= today);
}
function decimalTruncate(source, decimals)
{
if (typeof(decimals) == 'undefined')
decimals = 6;
source = source.toString();
var pos = source.indexOf('.');
return parseFloat(source.substr(0, pos + decimals + 1));
}
function unitPriceWithTax(type)
{
var priceWithTax = parseFloat(document.getElementById(type+'_price').value.replace(/,/g, '.'));
var newPrice = addTaxes(priceWithTax);
$('#'+type+'_price_with_tax').html((isNaN(newPrice) == true || newPrice < 0) ? '0.00' : ps_round(newPrice, priceDisplayPrecision).toFixed(priceDisplayPrecision));
}
function unitySecond()
{
$('#unity_second').html($('#unity').val());
if ($('#unity').get(0).value.length > 0)
{
$('#unity_third').html($('#unity').val());
$('#tr_unit_impact').show();
}
else
$('#tr_unit_impact').hide();
}
function changeCurrencySpecificPrice(index)
{
var id_currency = $('#spm_currency_' + index).val();
if (id_currency > 0)
$('#sp_reduction_type option[value="amount"]').text($('#spm_currency_' + index + ' option[value= ' + id_currency + ']').text());
else if (typeof currencyName !== 'undefined')
$('#sp_reduction_type option[value="amount"]').text(currencyName);
if (currencies[id_currency]["format"] == 2 || currencies[id_currency]["format"] == 4)
{
$('#spm_currency_sign_pre_' + index).html('');
$('#spm_currency_sign_post_' + index).html(' ' + currencies[id_currency]["sign"]);
}
else if (currencies[id_currency]["format"] == 1 || currencies[id_currency]["format"] == 3)
{
$('#spm_currency_sign_post_' + index).html('');
$('#spm_currency_sign_pre_' + index).html(currencies[id_currency]["sign"] + ' ');
}
}

1823
js/admin/products.js Normal file

File diff suppressed because it is too large Load Diff

47
js/admin/themes.js Normal file
View File

@@ -0,0 +1,47 @@
/**
* For the full copyright and license information, please view the
* docs/licenses/LICENSE.txt file that was distributed with this source code.
*/
function toggleShopModuleCheckbox(id_shop, toggle){
var formGroup = $("[for='to_disable_shop"+id_shop+"']").parent();
if (toggle === true) {
formGroup.removeClass('hide');
formGroup.find('input').each(function(){$(this).prop('checked', 'checked');});
}
else {
formGroup.addClass('hide');
formGroup.find('input').each(function(){$(this).prop('checked', '');});
}
}
$(function(){
$('div.thumbnail-wrapper').on(
'mouseenter',
function() {
var w = $(this).parent('div').outerWidth(true);
var h = $(this).parent('div').outerHeight(true);
$(this).children('.action-wrapper').css('width', w + 'px');
$(this).children('.action-wrapper').css('height', h + 'px');
$(this).children('.action-wrapper').show();
})
.on(
'mouseleave',
function() {
$('.thumbnail-wrapper .action-wrapper').hide();
}
);
$("[name^='checkBoxShopGroupAsso_theme']").on('change', function(){
$(this).parents('.tree-folder').find("[name^='checkBoxShopAsso_theme']").each(function(){
var id = $(this).attr('value');
var checked = $(this).prop('checked');
toggleShopModuleCheckbox(id, checked);
});
});
$("[name^='checkBoxShopAsso_theme']").on('click', function(){
var id = $(this).attr('value');
var checked = $(this).prop('checked');
toggleShopModuleCheckbox(id, checked);
});
});

113
js/admin/tinymce.inc.js Normal file
View File

@@ -0,0 +1,113 @@
/**
* Change default icons to marerial icons
*/
function changeToMaterial() {
var materialIconAssoc = {
'mce-i-code': '<i class="material-icons">code</i>',
'mce-i-none': '<i class="material-icons">format_color_text</i>',
'mce-i-bold': '<i class="material-icons">format_bold</i>',
'mce-i-italic': '<i class="material-icons">format_italic</i>',
'mce-i-underline': '<i class="material-icons">format_underlined</i>',
'mce-i-strikethrough': '<i class="material-icons">format_strikethrough</i>',
'mce-i-blockquote': '<i class="material-icons">format_quote</i>',
'mce-i-link': '<i class="material-icons">link</i>',
'mce-i-alignleft': '<i class="material-icons">format_align_left</i>',
'mce-i-aligncenter': '<i class="material-icons">format_align_center</i>',
'mce-i-alignright': '<i class="material-icons">format_align_right</i>',
'mce-i-alignjustify': '<i class="material-icons">format_align_justify</i>',
'mce-i-bullist': '<i class="material-icons">format_list_bulleted</i>',
'mce-i-numlist': '<i class="material-icons">format_list_numbered</i>',
'mce-i-image': '<i class="material-icons">image</i>',
'mce-i-table': '<i class="material-icons">grid_on</i>',
'mce-i-media': '<i class="material-icons">video_library</i>',
'mce-i-browse': '<i class="material-icons">attachment</i>',
'mce-i-checkbox': '<i class="mce-ico mce-i-checkbox"></i>'
};
$.each(materialIconAssoc, function(index, value) {
$('.' + index).replaceWith(value);
});
}
function tinySetup(config) {
if (typeof tinyMCE === 'undefined') {
setTimeout(function() {
tinySetup(config);
}, 100);
return;
}
if (!config) {
config = {};
}
if (typeof config.editor_selector != 'undefined') {
config.selector = '.' + config.editor_selector;
}
var default_config = {
selector: '.rte',
plugins: 'align colorpicker link image filemanager table media placeholder lists advlist code table autoresize',
browser_spellcheck: true,
toolbar1:
'code,colorpicker,bold,italic,underline,strikethrough,blockquote,link,align,bullist,numlist,table,image,media,formatselect',
toolbar2: '',
external_filemanager_path: baseAdminDir + 'filemanager/',
filemanager_title: 'File manager',
external_plugins: {
filemanager: baseAdminDir + 'filemanager/plugin.min.js'
},
language: iso_user,
content_style: lang_is_rtl === '1' ? 'body {direction:rtl;}' : '',
skin: 'prestashop',
mobile: {
theme: 'mobile',
plugins: ['lists', 'align', 'link', 'table', 'placeholder', 'advlist', 'code'],
toolbar:
'undo code colorpicker bold italic underline strikethrough blockquote link align bullist numlist table formatselect styleselect',
},
menubar: false,
statusbar: false,
relative_urls: false,
convert_urls: false,
entity_encoding: 'raw',
extended_valid_elements: 'em[class|name|id],@[role|data-*|aria-*]',
valid_children: '+*[*]',
valid_elements: '*[*]',
init_instance_callback: 'changeToMaterial',
rel_list: [{title: 'nofollow', value: 'nofollow'}]
};
if (typeof window.defaultTinyMceConfig !== 'undefined') {
Object.assign(default_config, window.defaultTinyMceConfig);
}
$.each(default_config, function(index, el) {
if (config[index] === undefined) config[index] = el;
});
var plugins_arr = config['plugins'].split(/[ ,]/);
var old_plugins_array = ['iespell', 'inlinepopups', 'style', 'xhtmlxtras', 'safari'];
$.each(plugins_arr, function(index, data) {
if (data == 'advhr') plugins_arr[index] = 'hr';
else if (data == 'advlink') plugins_arr[index] = 'link';
else if (data == 'advimage') {
plugins_arr[index] = 'image';
plugins_arr.push('filemanager');
} else if (data == 'emotions') plugins_arr[index] = 'emoticons';
else if (old_plugins_array.indexOf(data) >= 0) {
plugins_arr.splice(index, 1);
}
});
var plugins = plugins_arr.join(',');
config.plugins = plugins;
// Change icons in popups
$('body').on('click', '.mce-btn, .mce-open, .mce-menu-item', function() {
changeToMaterial();
});
tinyMCE.init(config);
}

View File

@@ -0,0 +1,45 @@
/**
* For the full copyright and license information, please view the
* docs/licenses/LICENSE.txt file that was distributed with this source code.
*/
$(function() {
tinySetup({
editor_selector: 'autoload_rte',
setup: function(ed) {
ed.on('loadContent', function(ed, e) {
handleCounterTiny(tinymce.activeEditor.id);
});
ed.on('change', function(ed, e) {
tinyMCE.triggerSave();
handleCounterTiny(tinymce.activeEditor.id);
});
ed.on('blur', function(ed) {
tinyMCE.triggerSave();
});
}
});
function handleCounterTiny(id) {
let textarea = $('#' + id);
let counter = textarea.attr('counter');
let counter_type = textarea.attr('counter_type');
const editor = window.tinyMCE.get(id);
const max = editor.getBody() ? editor.getBody().textContent.length : 0;
textarea
.parent()
.find('span.currentLength')
.text(max);
if ('recommended' !== counter_type && max > counter) {
textarea
.parent()
.find('span.maxLength')
.addClass('text-danger');
} else {
textarea
.parent()
.find('span.maxLength')
.removeClass('text-danger');
}
}
});