Rimozione dipendenza UI Autocomplete

Rimozione della dipendenza UI Autocomplete in favore di una libreria indipendente, aggiornamento funzioni JS per la gestione degli allegati.
This commit is contained in:
Dasc3er 2021-07-20 15:23:39 +02:00
parent 67ad05b3a7
commit 10e1301eb7
11 changed files with 508 additions and 258 deletions

View File

@ -81,7 +81,8 @@ input[type=file] {
position: fixed; position: fixed;
} }
.ui-autocomplete { .autocomplete, .ui-autocomplete {
background: white;
z-index: 10000; z-index: 10000;
min-width: 160px; min-width: 160px;
padding: 10px; padding: 10px;
@ -94,8 +95,23 @@ input[type=file] {
border-radius: 5px; border-radius: 5px;
} }
.ui-autocomplete-category { .autocomplete .group, .ui-autocomplete-category {
font-size: 150%; font-size: 1.5em;
background: inherit;
}
.autocomplete > div {
padding: 5px;
}
.highlight {
background: #FFFF66;
}
.autocomplete > div:hover:not(.group),
.autocomplete > div.selected {
background: #F5F5F5;
cursor: pointer;
} }
.ui-autocomplete-scrollable { .ui-autocomplete-scrollable {

View File

@ -138,7 +138,7 @@ $(document).ready(function () {
$(this).attr("data-id_records", ""); $(this).attr("data-id_records", "");
$(this).data("id_records", ""); $(this).data("id_records", "");
} else { } else {
swal(globals.translations.waiting, globals.translations.waiting_msg, "error"); swal(globals.translations.waiting, globals.translations.waitingMessage, "error");
} }
}); });
}); });

View File

@ -17,88 +17,75 @@
*/ */
$(document).ready(function () { $(document).ready(function () {
$('#supersearch').keyup(function () { const searchInput = $('#supersearch');
$(document).ajaxStop(); const searchButton = searchInput.parent().find('i');
const searches = [];
if ($(this).val() == '') { autocomplete({
$(this).removeClass('wait'); minLength: 1,
} else { input: searchInput[0],
$(this).addClass('wait'); emptyMsg: globals.translations.noResults,
} debounceWaitMs: 500,
}); fetch: function(text, update) {
text = text.toLowerCase();
$.widget("custom.supersearch", $.ui.autocomplete, { // Registrazione ricerca
_create: function () { searches.push(text);
this._super(); searchButton
this.widget().menu("option", "items", "> :not(.ui-autocomplete-category)"); .removeClass('fa-search')
}, .addClass('fa-spinner fa-spin');
_renderMenu: function (ul, items) {
if (items[0].value == undefined) {
$('#supersearch').removeClass('wait');
ul.html('');
} else {
var that = this,
currentCategory = "";
ul.addClass('ui-autocomplete-scrollable');
ul.css('z-index', '999');
$.each(items, function (index, item) {
if (item.category != currentCategory) {
ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
currentCategory = item.category;
}
that._renderItemData(ul, item);
});
}
},
_renderItem: function (ul, item) {
return $("<li>")
.append("<a href='" + item.link + "' title='Clicca per aprire'><b>" + item.value + "</b><br/>" + item.label + "</a>")
.appendTo(ul);
}
});
// Configurazione supersearch
var $super = $('#supersearch').supersearch({
minLength: 3,
select: function (event, ui) {
location.href = ui.item.link;
},
source: function (request, response) {
$.ajax({ $.ajax({
url: globals.rootdir + '/ajax_search.php', url: globals.rootdir + '/ajax_search.php',
dataType: "json", dataType: "JSON",
data: { data: {
term: request.term term: text,
}, },
complete: function (jqXHR) {
$('#supersearch').removeClass('wait');
},
success: function (data) { success: function (data) {
if (data == null) { // Fix per gestione risultati null
response($.map(['a'], function (item) { data = data ? data : [];
return false;
}));
} else {
response($.map(data, function (item) {
labels = (item.labels).toString();
labels = labels.replace('<br/>,', '<br/>');
return { // Trasformazione risultati in formato leggibile
label: labels, const results = data.map(function (result) {
category: item.category, return {
link: item.link, label: result.label ? result.label : '<h4>' + result.title + '</h4>' + result.labels
value: item.title .join('').split('<br/>,').join('<br/>'),
} group: result.category,
})); link: result.link,
value: result.title
}
});
// Rimozione ricerca in corso
searches.pop();
if (searches.length === 0) {
searchButton
.removeClass('fa-spinner fa-spin')
.addClass('fa-search');
} }
update(results);
},
error: function (){
searchButton
.removeClass('fa-spinner fa-spin')
.addClass('fa-exclamation-triangle');
} }
}); });
},
preventSubmit: true,
disableAutoSelect: true,
onSelect: function(item) {
window.location.href = item.link;
},
customize: function(input, inputRect, container, maxHeight) {
container.style.width = '600px';
},
render: function(item, currentValue){
const itemElement = document.createElement("div");
itemElement.innerHTML = item.label;
// <a href='" + item.link + "' title='Clicca per aprire'><b>" + item.value + "</b><br/>" + item.label + "</a>
return itemElement;
} }
}); });
}); });

View File

@ -0,0 +1,308 @@
/*
* OpenSTAManager: il software gestionale open source per l'assistenza tecnica e la fatturazione
* Copyright (C) DevCode s.r.l.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
/**
* Restituisce filename ed estensione di un file indicato.
* @param path
* @returns [string, string]
*/
function getFilenameAndExtension(path) {
let filename_extension = path.replace(/^.*[\\\/]/, '');
let filename = filename_extension.substring(0, filename_extension.lastIndexOf('.'));
let ext = filename_extension.split('.').pop();
return [filename, ext];
}
/**
* Inizializza la gestione degli allegati.
* @param gestione
*/
function initGestioneAllegati(gestione) {
const dropzone_id = '#' + gestione.attr('id') + ' .dropzone';
const maxFilesize = gestione.data('max_filesize');
if ($(dropzone_id).length === 0) {
return;
}
let params = new URLSearchParams({
op: "aggiungi-allegato",
id_module: gestione.data('id_module'),
id_plugin: gestione.data('id_plugin'),
id_record: gestione.data('id_record'),
}).toString();
let dragdrop = new Dropzone(dropzone_id, {
dictDefaultMessage: globals.translations.allegati.messaggio + ".<br>(" + globals.translations.allegati.maxFilesize.replace('_SIZE_', maxFilesize) + ")",
paramName: "file",
maxFilesize: maxFilesize, // MB
uploadMultiple: false,
parallelUploads: 2,
addRemoveLinks: false,
autoProcessQueue: true,
autoQueue: true,
url: globals.rootdir + "/actions.php?" + params,
init: function (file, xhr, formData) {
this.on("success", function (file) {
dragdrop.removeFile(file);
});
this.on("complete", function (file) {
// Ricarico solo quando ho finito
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
ricaricaAllegati(gestione);
}
});
}
});
}
/**
* Funzione per l'apertura della schermata di modifica per una categoria di allegati.
* @param gestione
* @param pulsanteModifica
*/
function modificaCategoriaAllegati(gestione, pulsanteModifica) {
const categoria = $(pulsanteModifica).parent().parent();
console.log(categoria)
const nome = categoria.find(".box-title");
nome.addClass('hidden');
$(pulsanteModifica).addClass('hidden');
const pulsanteSalva = categoria.find(".category-save");
const pulsanteAnnulla = categoria.find(".category-cancel");
const inputNome = categoria.find(".category-name");
pulsanteSalva.removeClass("hidden");
pulsanteAnnulla.removeClass("hidden");
inputNome.removeClass("hidden");
}
/**
* Funzione per salvare le modifiche effettuate su una categoria di allegati.
* @param gestione
* @param pulsanteSalva
*/
function salvaCategoriaAllegati(gestione, pulsanteSalva) {
const categoria = $(pulsanteSalva).parent().parent();
const nome = categoria.find(".box-title");
const inputNome = categoria.find(".category-name");
mostraCaricamentoAllegati(gestione);
$.ajax({
url: globals.rootdir + "/actions.php",
cache: false,
type: "POST",
data: {
op: "modifica-categoria-allegato",
id_module: gestione.data('id_module'),
id_plugin: gestione.data('id_plugin'),
id_record: gestione.data('id_record'),
category: nome.text(),
name: inputNome.val(),
},
success: function (data) {
ricaricaAllegati(gestione);
},
error: function (gestione) {
ricaricaAllegati(gestione);
}
});
}
/**
* Funzione per caricare un nuovo allegato.
* @param gestione
*/
function aggiungiAllegato(gestione) {
const id = "#" + gestione.attr('id');
const form = $(id + " #upload-form");
form.ajaxSubmit({
url: globals.rootdir + "/actions.php",
data: data,
type: "post",
uploadProgress: function (event, position, total, percentComplete) {
$(id + " #upload").prop("disabled", true).html(percentComplete + "%").removeClass("btn-success").addClass("btn-info");
},
success: function (data) {
ricaricaAllegati(gestione);
},
error: function (data) {
alert(globals.translations.allegati.errore + ": " + data);
}
});
}
/**
* Funzione per mostrare il loader di caricamento per gli allegati.
* @param gestione
*/
function mostraCaricamentoAllegati(gestione) {
const id = "#" + gestione.attr('id');
localLoading($(id + " .panel-body"), true);
}
/**
* Funzione dedicata al caricamento dinamico degli allegati.
* @param gestione
*/
function ricaricaAllegati(gestione) {
const id = "#" + gestione.attr('id');
let params = new URLSearchParams({
op: "list_attachments",
id_module: gestione.data('id_module'),
id_plugin: gestione.data('id_plugin'),
id_record: gestione.data('id_record'),
}).toString();
$(id).load(globals.rootdir + "/ajax.php?" + params, function () {
localLoading($(id + " .panel-body"), false);
const nuovoAllegato = $(id + " table tr").eq(-1).attr("id");
if (nuovoAllegato !== undefined) {
$("#" + nuovoAllegato).effect("highlight", {}, 1500);
}
});
}
/**
* Funzione per l'apertura della pagina di gestione dei dati dell'allegato.
* @param button
*/
function modificaAllegato(button) {
const gestione = $(button).closest(".gestione-allegati");
const allegato = $(button).closest("tr").data();
let params = new URLSearchParams({
op: "visualizza-modifica-allegato",
id_module: gestione.data('id_module'),
id_plugin: gestione.data('id_plugin'),
id_record: gestione.data('id_record'),
id_allegato: allegato.id,
}).toString();
openModal(globals.translations.allegati.modifica, globals.rootdir + "/actions.php?" + params);
}
/**
* Funzione per gestire il download di un allegato.
* @param button
*/
function saggiungiAllegato(button) {
const gestione = $(button).closest(".gestione-allegati");
const allegato = $(button).closest("tr").data();
let params = new URLSearchParams({
op: "download-allegato",
id_module: gestione.data('id_module'),
id_plugin: gestione.data('id_plugin'),
id_record: gestione.data('id_record'),
id: allegato.id,
filename: allegato.filename,
}).toString();
window.open(globals.rootdir + "/actions.php?" + params, "_blank")
}
/**
* Funzione per l'apertura dell'anteprima di visualizzazione allegato.
* @param button
*/
function visualizzaAllegato(button) {
const allegato = $(button).closest("tr").data();
let params = new URLSearchParams({
file_id: allegato.id,
}).toString();
openModal(allegato.nome + ' <small style="color:white"><i>(' + allegato.filename + ')</i></small>', globals.rootdir + "/view.php?" + params);
}
/**
* Funzione per la gestione della rimozione di un allegato specifico.
*
* @param button
*/
function rimuoviAllegato(button) {
const gestione = $(button).closest(".gestione-allegati");
const allegato = $(button).closest("tr").data();
swal({
title: globals.translations.allegati.elimina,
type: "warning",
showCancelButton: true,
confirmButtonText: globals.translations.allegati.procedi,
}).then(function () {
mostraCaricamentoAllegati(gestione);
// Parametri della richiesta AJAX
let params = new URLSearchParams({
op: "rimuovi-allegato",
id_module: gestione.data('id_module'),
id_plugin: gestione.data('id_plugin'),
id_record: gestione.data('id_record'),
id_allegato: allegato.id,
filename: allegato.filename,
}).toString();
// Richiesta AJAX
$.ajax(globals.rootdir + "/actions.php?" + params)
.then(function () {
ricaricaAllegati(gestione);
});
}).catch(swal.noop);
}
function impostaCategorieAllegatiDisponibili(gestione, categorie) {
// Disabilitazione per rimozione input in aggiunta
return;
const id = "#" + gestione.attr('id');
const input = $("#modifica-allegato #categoria_allegato")[0];
autocomplete({
minLength: 0,
input: input,
emptyMsg: globals.translations.noResults,
fetch: function (text, update) {
text = text.toLowerCase();
const suggestions = categorie.filter(n => n.toLowerCase().startsWith(text));
// Trasformazione risultati in formato leggibile
const results = suggestions.map(function (result) {
return {
label: result,
value: result
}
});
update(results);
},
onSelect: function (item) {
input.value = item.label;
},
});
}

View File

@ -82,9 +82,11 @@ const JS = gulp.parallel(() => {
const vendor = [ const vendor = [
'jquery/dist/jquery.js', 'jquery/dist/jquery.js',
'autosize/dist/autosize.js', 'autosize/dist/autosize.js',
'autocompleter/autocomplete.js',
'html5sortable/dist/html5sortable.js',
'bootstrap-colorpicker/dist/js/bootstrap-colorpicker.js', 'bootstrap-colorpicker/dist/js/bootstrap-colorpicker.js',
'moment/moment.js', 'moment/moment.js',
'components-jqueryui/jquery-ui.js', //'components-jqueryui/jquery-ui.js',
'datatables.net/js/jquery.dataTables.js', 'datatables.net/js/jquery.dataTables.js',
'datatables.net-buttons/js/dataTables.buttons.js', 'datatables.net-buttons/js/dataTables.buttons.js',
'datatables.net-buttons/js/buttons.colVis.js', 'datatables.net-buttons/js/buttons.colVis.js',

View File

@ -56,12 +56,34 @@ $source = array_clean(array_column($categories, 'category'));
echo ' echo '
<script> <script>
var categorie = '.json_encode($source).';
// Auto-completamento categoria // Auto-completamento categoria
$("#modifica-allegato #categoria_allegato").autocomplete({ $(document).ready(function () {
source: '.json_encode($source).', const input = $("#modifica-allegato #categoria_allegato")[0];
minLength: 0
}).focus(function() { autocomplete({
$(this).autocomplete("search", $(this).val()) minLength: 0,
input: input,
emptyMsg: globals.translations.noResults,
fetch: function (text, update) {
text = text.toLowerCase();
const suggestions = categorie.filter(n => n.toLowerCase().startsWith(text));
// Trasformazione risultati in formato leggibile
const results = suggestions.map(function (result) {
return {
label: result,
value: result
}
});
update(results);
},
onSelect: function (item) {
input.value = item.label;
},
});
}); });
</script> </script>
<script>$(document).ready(init)</script>'; <script>$(document).ready(init)</script>';

View File

@ -108,19 +108,28 @@ if (Auth::check()) {
'details' => tr('Dettagli'), 'details' => tr('Dettagli'),
'loading' => tr('Caricamento'), 'loading' => tr('Caricamento'),
'waiting' => tr('Impossibile procedere'), 'waiting' => tr('Impossibile procedere'),
'waiting_msg' => tr('Prima di proseguire devi selezionare alcuni elementi!'), 'waitingMessage' => tr('Prima di proseguire devi selezionare alcuni elementi!'),
'hooksExecuting' => tr('Hooks in esecuzione'), 'hooksExecuting' => tr('Hooks in esecuzione'),
'hookExecuting' => tr('Hook "_NAME_" in esecuzione'), 'hookExecuting' => tr('Hook "_NAME_" in esecuzione'),
'hookMultiple' => tr('Hai _NUM_ notifiche'), 'hookMultiple' => tr('Hai _NUM_ notifiche'),
'hookSingle' => tr('Hai 1 notifica'), 'hookSingle' => tr('Hai 1 notifica'),
'hookNone' => tr('Nessuna notifica'), 'hookNone' => tr('Nessuna notifica'),
'singleCalendar' => tr("E' presente un solo periodo!"), 'singleCalendar' => tr("E' presente un solo periodo!"),
'noResults' => tr("Nessun elemento trovato"),
]; ];
foreach ($translations as $key => $value) { foreach ($translations as $key => $value) {
echo ' echo '
'.$key.': "'.addslashes($value).'",'; '.$key.': "'.addslashes($value).'",';
} }
echo ' echo '
allegati: {
messaggio: "'.tr("Clicca o trascina qui per caricare uno o più file").'",
maxFilesize: "'.tr('Max upload: _SIZE_ MB').'",
errore: "'.tr('Errore').'",
modifica: "'.tr('Modifica allegato').'",
elimina: "'.tr('Vuoi eliminare questo file?').'",
procedi: "'.tr('Procedi').'",
},
ajax: { ajax: {
"missing": { "missing": {
"title": "'.tr('Errore').'", "title": "'.tr('Errore').'",
@ -453,7 +462,8 @@ if (Auth::check()) {
<div class="input-group"> <div class="input-group">
<input type="text" name="q" class="form-control" id="supersearch" placeholder="'.tr('Cerca').'..."/> <input type="text" name="q" class="form-control" id="supersearch" placeholder="'.tr('Cerca').'..."/>
<span class="input-group-btn"> <span class="input-group-btn">
<button class="btn btn-flat" id="search-btn" name="search" type="submit" ><i class="fa fa-search"></i> <button class="btn btn-flat" id="search-btn" name="search" type="submit">
<i class="fa fa-search"></i>
</button> </button>
</span> </span>

View File

@ -158,58 +158,58 @@ echo '
echo ' echo '
<script> <script>
var emails = []; var emails = [];
var id_anagrafica = "'.$id_anagrafica.'";
var pec = "'.$smtp['pec']. '";
$(document).ready(function() {'; $(document).ready(function() {
// Auto-completamento destinatario
if (id_anagrafica) {
$(document).load(globals.rootdir + "/ajax_complete.php?module=Anagrafiche&op=get_email&id_anagrafica=" + id_anagrafica + (pec ? "&type=pec" : ""), function(response) {
emails = JSON.parse(response);
// Autocompletamento destinatario $(".destinatari").each(function(){
if (!empty($id_anagrafica)) { addAutoComplete(this);
echo ' });
$(document).load(globals.rootdir + "/ajax_complete.php?module=Anagrafiche&op=get_email&id_anagrafica='.$id_anagrafica.(($smtp['pec']) ? '&type=pec' : '').'", function(response) {
emails = JSON.parse(response);
$(".destinatari").each(function(){ aggiungiDestinatario();
addAutoComplete(this);
}); });
aggiungiDestinatario();
});';
} }
echo '
}); });
function inviaEmail() { function inviaEmail() {
if($("#email-form").parsley().validate() && confirm("Inviare e-mail?")) { const form = $("#email-form");
$("#email-form").submit();
if (form.parsley().validate() && confirm("Inviare e-mail?")) {
form.submit();
} }
} }
function addAutoComplete(input){ function addAutoComplete(input) {
$(input).autocomplete({ autocomplete({
source: emails,
minLength: 0, minLength: 0,
close: function() { input: input,
emptyMsg: globals.translations.noResults,
fetch: function (text, update) {
text = text.toLowerCase();
const suggestions = emails.filter(n => n.value.toLowerCase().startsWith(text));
update(suggestions);
},
onSelect: function (item) {
input.value = item.value;
aggiungiDestinatario(); aggiungiDestinatario();
}, },
}).focus(function() {
$(this).autocomplete("search", $(this).val());
}); });
} }
function aggiungiDestinatario() { function aggiungiDestinatario() {
var last = $("#lista-destinatari input").last(); const last = $("#lista-destinatari input").last();
if (last.val()) { if (last.val()) {
cleanup_inputs(); const nuovaRiga = aggiungiContenuto("#lista-destinatari", "#template-destinatario", {"-id-": $("#lista-destinatari > div").length});
aggiungiContenuto("#lista-destinatari", "#template-destinatario", {"-id-": $("#lista-destinatari > div").length}); nuovaRiga.find(".destinatari").each(function(){
$(".destinatari").each(function(){
addAutoComplete(this); addAutoComplete(this);
}); });
restart_inputs();
} }
} }
</script>'; </script>';

View File

@ -49,8 +49,8 @@ foreach ($rs as $r) {
$result['link'] = base_path().'/editor.php?id_module='.$link_id.'&id_record='.$r['id']; $result['link'] = base_path().'/editor.php?id_module='.$link_id.'&id_record='.$r['id'];
$result['title'] = 'Preventivo '.$r['numero']; $result['title'] = 'Preventivo '.$r['numero'];
if ($rs[$r]['data_accettazione'] == '0000-00-00') { if ($r['data_accettazione'] == '0000-00-00') {
$result['title'] .= ' del '.Translator::dateToLocale($rs[$r]['data_accettazione']); $result['title'] .= ' del '.Translator::dateToLocale($r['data_accettazione']);
} }
$result['category'] = 'Preventivi'; $result['category'] = 'Preventivi';

View File

@ -3,6 +3,7 @@
"main": "gulpfile.js", "main": "gulpfile.js",
"dependencies": { "dependencies": {
"admin-lte": "^2.4.0", "admin-lte": "^2.4.0",
"autocompleter": "^6.1.1",
"autonumeric": "^4.6.0", "autonumeric": "^4.6.0",
"autosize": "^3.0.21", "autosize": "^3.0.21",
"bootstrap": "^3.3.7", "bootstrap": "^3.3.7",
@ -22,6 +23,7 @@
"fullcalendar": "^3.4.0", "fullcalendar": "^3.4.0",
"geocomplete": "^1.7.0", "geocomplete": "^1.7.0",
"hotkeys-js": "^3.8.5", "hotkeys-js": "^3.8.5",
"html5sortable": "^0.13.2",
"inputmask": "^3.3.9", "inputmask": "^3.3.9",
"jquery": "^3.5.1", "jquery": "^3.5.1",
"jquery-form": "^4.2.1", "jquery-form": "^4.2.1",

View File

@ -21,6 +21,7 @@ namespace HTMLBuilder\Manager;
use Models\Setting; use Models\Setting;
use Models\Upload; use Models\Upload;
use Util\FileSystem;
/** /**
* Gestione allegati. * Gestione allegati.
@ -47,11 +48,14 @@ class FileManager implements ManagerInterface
// ID del form // ID del form
$attachment_id = 'attachments_'.$options['id_module'].'_'.$options['id_plugin']; $attachment_id = 'attachments_'.$options['id_module'].'_'.$options['id_plugin'];
$upload_max_filesize = ini_get('upload_max_filesize');
$upload_max_filesize = substr($upload_max_filesize, 0, -1);
$dbo = database(); $dbo = database();
// Codice HTML // Codice HTML
$result = ' $result = '
<div id="'.$attachment_id.'" >'; <div class="gestione-allegati" id="'.$attachment_id.'" data-id_module="'.$options['id_module'].'" data-id_plugin="'.$options['id_plugin'].'" data-id_record="'.$options['id_record'].'" data-max_filesize="'.$upload_max_filesize.'">';
if (!empty($options['showpanel'])) { if (!empty($options['showpanel'])) {
$result .= ' $result .= '
@ -79,16 +83,20 @@ class FileManager implements ManagerInterface
<div class="box-header with-border"> <div class="box-header with-border">
<h3 class="box-title">'.(!empty($category) ? $category : tr('Generale')).'</h3> <h3 class="box-title">'.(!empty($category) ? $category : tr('Generale')).'</h3>
{[ "type": "text", "class": "hide category-name", "value": "'.$category.'" ]} {[ "type": "text", "class": "hidden category-name", "value": "'.$category.'" ]}
<div class="box-tools pull-right">'; <div class="box-tools pull-right">';
if (!empty($category) && !in_array($category, ['Fattura Elettronica'])) { if (!empty($category) && !in_array($category, ['Fattura Elettronica'])) {
$result .= ' $result .= '
<button type="button" class="btn btn-box-tool category-save hide"> <button type="button" class="btn btn-box-tool category-save hidden">
<i class="fa fa-check"></i> <i class="fa fa-check"></i>
</button> </button>
<button type="button" class="btn btn-box-tool category-cancel hidden">
<i class="fa fa-close"></i>
</button>
<button type="button" class="btn btn-box-tool category-edit"> <button type="button" class="btn btn-box-tool category-edit">
<i class="fa fa-edit"></i> <i class="fa fa-edit"></i>
</button>'; </button>';
@ -115,7 +123,7 @@ class FileManager implements ManagerInterface
$file = Upload::find($r['id']); $file = Upload::find($r['id']);
$result .= ' $result .= '
<tr id="row_'.$r['id'].'" > <tr id="row_'.$r['id'].'" data-id="'.$r['id'].'" data-filename="'.$r['filename'].'">
<td align="left">'; <td align="left">';
if ($file->user && $file->user->photo) { if ($file->user && $file->user->photo) {
@ -133,38 +141,38 @@ class FileManager implements ManagerInterface
<i class="fa fa-external-link"></i> '.$r['name'].' <i class="fa fa-external-link"></i> '.$r['name'].'
</a> </a>
<small> ('.$file->extension.')'.((!empty($file->size)) ? ' ('.\Util\FileSystem::formatBytes($file->size).')' : '').' '.(((setting('Logo stampe') == $r['filename']) || (setting('Filigrana stampe') == $r['filename'])) ? '<i class="fa fa-file-text-o"></i>' : '').'</small>'.' <small> ('.$file->extension.')'.((!empty($file->size)) ? ' ('. FileSystem::formatBytes($file->size).')' : '').' '.(((setting('Logo stampe') == $r['filename']) || (setting('Filigrana stampe') == $r['filename'])) ? '<i class="fa fa-file-text-o"></i>' : '').'</small>'.'
</td> </td>
<td>'.\Translator::timestampToLocale($r['created_at']).'</td> <td>'.timestampFormat($r['created_at']).'</td>
<td class="text-center"> <td class="text-center">
<a class="btn btn-xs btn-primary" href="'.base_path().'/actions.php?id_module='.$options['id_module'].'&op=download-allegato&id='.$r['id'].'&filename='.$r['filename'].'" target="_blank"> <button type="button" class="btn btn-xs btn-primary" onclick="saggiungiAllegato(this)">
<i class="fa fa-download"></i> <i class="fa fa-download"></i>
</a>'; </button>';
// Anteprime supportate dal browser // Anteprime supportate dal browser
if ($file->hasPreview()) { if ($file->hasPreview()) {
$result .= ' $result .= '
<button class="btn btn-xs btn-info" type="button" data-title="'.prepareToField($r['name']).' <small style=\'color:white\'><i>('.$r['filename'].')</i></small>" data-href="'.base_path().'/view.php?file_id='.$r['id'].'"> <button type="button" class="btn btn-xs btn-info" onclick="visualizzaAllegato(this)">
<i class="fa fa-eye"></i> <i class="fa fa-eye"></i>
</button>'; </button>';
} else { } else {
$result .= ' $result .= '
<button class="btn btn-xs btn-default disabled" title="'.tr('Anteprima file non disponibile').'" disabled> <button type="button" class="btn btn-xs btn-default disabled" title="'.tr('Anteprima file non disponibile').'" disabled>
<i class="fa fa-eye"></i> <i class="fa fa-eye"></i>
</button>'; </button>';
} }
if (!$options['readonly']) { if (!$options['readonly']) {
$result .= ' $result .= '
<button type="button" class="btn btn-xs btn-warning" data-href="'.base_path().'/actions.php?op=visualizza-modifica-allegato&id_module='.$options['id_module'].'&id_allegato='.$r['id'].'" data-title="'.tr('Modifica allegato').'"> <button type="button" class="btn btn-xs btn-warning" onclick="modificaAllegato(this)">
<i class="fa fa-edit"></i> <i class="fa fa-edit"></i>
</button> </button>
<a class="btn btn-xs btn-danger ask" data-backto="record-edit" data-msg="'.tr('Vuoi eliminare questo file?').'" data-op="rimuovi-allegato" data-filename="'.$r['filename'].'" data-id_record="'.$r['id_record'].'" data-id_plugin="'.$options['id_plugin'].'" data-before="show_'.$attachment_id.'" data-callback="reload_'.$attachment_id.'"> <button type="button" class="btn btn-xs btn-danger" onclick="rimuoviAllegato(this)">
<i class="fa fa-trash"></i> <i class="fa fa-trash"></i>
</a>'; </button>';
} }
$result .= ' $result .= '
@ -214,147 +222,42 @@ class FileManager implements ManagerInterface
$source = array_clean(array_column($categories, 'category')); $source = array_clean(array_column($categories, 'category'));
$upload_max_filesize = ini_get('upload_max_filesize');
$upload_max_filesize = substr($upload_max_filesize, 0, -1);
$result .= ' $result .= '
<script>$(document).ready(init)</script> <script>$(document).ready(init)</script>
<script> <script>
// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
$(document).ready(function() { $(document).ready(function() {
let dropzone_id = "#'.$attachment_id.' .dropzone"; const container = $("#'.$attachment_id.'");
if ($(dropzone_id).length == 0) {
return;
}
let dragdrop = new Dropzone(dropzone_id, { initGestioneAllegati(container);
dictDefaultMessage: "'.tr('Clicca o trascina qui per caricare uno o più file').'.<br>('.tr('Max upload: _SIZE_', [ impostaCategorieAllegatiDisponibili(container, '.json_encode($source).');
'_SIZE_' => $upload_max_filesize.' MB',
]).')",
paramName: "file",
maxFilesize: '.$upload_max_filesize.', // MB
uploadMultiple: false,
parallelUploads: 2,
addRemoveLinks: false,
autoProcessQueue: true,
autoQueue: true,
url: "'.base_path().'/actions.php?op=aggiungi-allegato&id_module='.$options['id_module'].'&id_record='.$options['id_record'].'&id_plugin='.$options['id_plugin'].'",
init: function (file, xhr, formData) {
this.on("success", function (file) {
dragdrop.removeFile(file);
});
this.on("complete", function (file) {
// Ricarico solo quando ho finito
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
reload_'.$attachment_id.'();
}
});
}
});
// Modifica categoria
$("#'.$attachment_id.' .category-edit").click(function() {
var nome = $(this).parent().parent().find(".box-title");
var save_button = $(this).parent().find(".category-save");
var input = $(this).parent().parent().find(".category-name");
nome.hide();
$(this).hide();
input.removeClass("hide");
save_button.removeClass("hide");
});
$("#'.$attachment_id.' .category-save").click(function() {
var nome = $(this).parent().parent().find(".box-title");
var input = $(this).parent().parent().find(".category-name");
show_'.$attachment_id.'();
$.ajax({
url: globals.rootdir + "/actions.php",
cache: false,
type: "POST",
data: {
id_module: "'.$options['id_module'].'",
id_plugin: "'.$options['id_plugin'].'",
id_record: "'.$options['id_record'].'",
op: "modifica-categoria-allegato",
category: nome.text(),
name: input.val(),
},
success: function(data) {
reload_'.$attachment_id.'();
},
error: function(data) {
reload_'.$attachment_id.'();
}
});
});
function getFilenameAndExtension(path) {
let filename_extension = path.replace(/^.*[\\\/]/, \'\');
let filename = filename_extension.substring(0, filename_extension.lastIndexOf(\'.\'));
let ext = filename_extension.split(\'.\').pop();
return [filename, ext];
}
// Auto-completamento categoria
$("#'.$attachment_id.' #categoria_allegato").autocomplete({
source: '.json_encode($source).',
minLength: 0
}).focus(function() {
$(this).autocomplete("search", $(this).val())
});
var data = {
op: "aggiungi-allegato",
id_module: "'.$options['id_module'].'",
id_plugin: "'.$options['id_plugin'].'",
id_record: "'.$options['id_record'].'",
};
// Upload
$("#'.$attachment_id.' #upload").click(function(){
$form = $("#'.$attachment_id.' #upload-form");
$form.ajaxSubmit({
url: globals.rootdir + "/actions.php",
data: data,
type: "post",
uploadProgress: function(event, position, total, percentComplete) {
$("#'.$attachment_id.' #upload").prop("disabled", true).html(percentComplete + "%").removeClass("btn-success").addClass("btn-info");
},
success: function(data){
reload_'.$attachment_id.'();
},
error: function(data) {
alert("'.tr('Errore').': " + data);
}
});
});
}); });
function show_'.$attachment_id.'() { // Modifica categoria
localLoading($("#'.$attachment_id.' .panel-body"), true); $("#'.$attachment_id.' .category-edit").click(function() {
} const container = $(this).closest(".gestione-allegati");
function reload_'.$attachment_id.'() { modificaCategoriaAllegati(container, this);
$("#'.$attachment_id.'").load(globals.rootdir + "/ajax.php?op=list_attachments&id_module='.$options['id_module'].'&id_record='.$options['id_record'].'&id_plugin='.$options['id_plugin'].'", function() { });
localLoading($("#'.$attachment_id.' .panel-body"), false);
var id = $("#'.$attachment_id.' table tr").eq(-1).attr("id"); $("#'.$attachment_id.' .category-save").click(function() {
if (id !== undefined) { const container = $(this).closest(".gestione-allegati");
$("#" + id).effect("highlight", {}, 1500);
} salvaCategoriaAllegati(container, this);
}); });
}
$("#'.$attachment_id.' .category-cancel").click(function() {
const container = $(this).closest(".gestione-allegati");
ricaricaAllegati(gestione);
});
// Upload
$("#'.$attachment_id.' #upload").click(function(){
const container = $(this).closest(".gestione-allegati");
aggiungiAllegato(container);
});
</script>'; </script>';
return $result; return $result;