diff --git a/ajax_dataload.php b/ajax_dataload.php index adfb81767..b53ae590f 100644 --- a/ajax_dataload.php +++ b/ajax_dataload.php @@ -3,102 +3,50 @@ include_once __DIR__.'/core.php'; // Informazioni fondamentali -$start = filter('start'); -$length = filter('length'); $columns = filter('columns'); $order = filter('order')[0]; $order['column'] = $order['column'] - 1; array_shift($columns); -$total = App::readQuery($structure); +$total = Util\Query::readQuery($structure); -// Lettura parametri modulo -$result_query = $total['query']; - -// Predisposizione dela risposta -$results = []; -$results['data'] = []; -$results['recordsTotal'] = 0; -$results['recordsFiltered'] = 0; -$results['summable'] = []; - -if (!empty($result_query) && $result_query != 'menu' && $result_query != 'custom') { - // Conteggio totale - $results['recordsTotal'] = $dbo->fetchNum($result_query); - - // Filtri di ricerica - $search_filters = []; - for ($i = 0; $i < count($columns); ++$i) { - if (!empty($columns[$i]['search']['value'])) { - if (str_contains($total['search_inside'][$i], '|search|')) { - $pieces = explode(',', $columns[$i]['search']['value']); - foreach ($pieces as $piece) { - $piece = trim($piece); - $search_filters[] = str_replace('|search|', prepare('%'.$piece.'%'), $total['search_inside'][$i]); - } - } else { - // Per le icone cerco nel campo icon_title - if (preg_match('/^icon_(.+?)$/', $total['fields'][$i], $m)) { - $total['search_inside'][$i] = '`icon_title_'.$m[1].'`'; - } - - // Per i colori cerco nel campo color_title - elseif (preg_match('/^color_(.+?)$/', $total['fields'][$i], $m)) { - $total['search_inside'][$i] = '`color_title_'.$m[1].'`'; - } - - $search_filters[] = $total['search_inside'][$i].' LIKE '.prepare('%'.trim($columns[$i]['search']['value'].'%')); - } - } +// Ricerca +$search = []; +for ($i = 0; $i < count($columns); ++$i) { + if (!empty($columns[$i]['search']['value'])) { + $search[$total['fields'][$i]] = $columns[$i]['search']['value']; } +} - // Ricerca - if (!empty($search_filters)) { - $result_query = str_replace('2=2', '2=2 AND ('.implode(' AND ', $search_filters).') ', $result_query); - } +$limit = [ + 'start' => filter('start'), + 'length' => filter('length'), +]; + +// Predisposizione della risposta +$results = [ + 'data' => [], + 'recordsTotal' => 0, + 'recordsFiltered' => 0, + 'summable' => [], +]; + +$query = Util\Query::getQuery($structure); +if (!empty($query)) { + // CONTEGGIO TOTALE + $results['recordsTotal'] = $dbo->fetchNum($query); + + // RISULTATI VISIBILI + $query = Util\Query::getQuery($structure, $search, $order, $limit); // Filtri derivanti dai permessi (eventuali) if (empty($id_plugin)) { - $result_query = Modules::replaceAdditionals($id_module, $result_query); + $query = Modules::replaceAdditionals($id_module, $query); } - // Ordinamento dei risultati - if (isset($order['dir']) && isset($order['column'])) { - $pieces = explode('ORDER', $result_query); - - $count = count($pieces); - if ($count > 1) { - unset($pieces[$count - 1]); - } - - $result_query = implode('ORDER', $pieces).' ORDER BY '.$total['order_by'][$order['column']].' '.$order['dir']; - } - - // Calcolo di eventuali somme - if (!empty($total['summable'])) { - $sum_query = str_replace_once('SELECT', 'SELECT '.implode(', ', $total['summable']).' FROM(SELECT ', $result_query).') AS `z`'; - $sums = $dbo->fetchArray($sum_query)[0]; - if (!empty($sums)) { - $r = []; - foreach ($sums as $key => $sum) { - if (str_contains($key, 'sum_')) { - $r[str_replace('sum_', '', $key)] = Translator::numberToLocale($sum); - } - } - $results['summable'] = $r; - } - } - - // Paginazione - if ($length > 0) { - $result_query .= ' LIMIT '.$start.', '.$length; - } - - // Query effettiva - $query = str_replace_once('SELECT', 'SELECT SQL_CALC_FOUND_ROWS', $result_query); - - $rs = $dbo->fetchArray($query); + $query = str_replace_once('SELECT', 'SELECT SQL_CALC_FOUND_ROWS', $query); + $rows = $dbo->fetchArray($query); // Conteggio dei record filtrati $count = $dbo->fetchArray('SELECT FOUND_ROWS()'); @@ -106,27 +54,32 @@ if (!empty($result_query) && $result_query != 'menu' && $result_query != 'custom $results['recordsFiltered'] = $count[0]['FOUND_ROWS()']; } - // Creazione della tabella + // SOMME + $results['summable'] = Util\Query::getSums($structure, $search); + + // Allineamento delle righe $align = []; - foreach ($rs as $i => $r) { - if ($i == 0) { - foreach ($total['fields'] as $field) { - $value = trim($r[$field]); + $row = $rows[0] ?: []; + foreach ($row as $field => $value) { + $value = trim($value); - // Allineamento a destra se il valore della prima riga risulta numerica - if (formatter()->isStandardNumber($value)) { - $align[$field] = 'text-right'; - } - - // Allineamento al centro se il valore della prima riga risulta relativo a date o icone - elseif (formatter()->isStandardDate($value) || preg_match('/^icon_(.+?)$/', $field)) { - $align[$field] = 'text-center'; - } - } + // Allineamento a destra se il valore della prima riga risulta numerica + if (formatter()->isStandardNumber($value)) { + $align[$field] = 'text-right'; } - $result = []; - $result[] = ''; + // Allineamento al centro se il valore della prima riga risulta relativo a date o icone + elseif (formatter()->isStandardDate($value) || preg_match('/^icon_(.+?)$/', $field)) { + $align[$field] = 'text-center'; + } + } + + // Creazione della tabella + foreach ($rows as $i => $r) { + $result = [ + '', // Colonna ID + ]; + foreach ($total['fields'] as $pos => $field) { $column = []; @@ -219,5 +172,5 @@ if (!empty($result_query) && $result_query != 'menu' && $result_query != 'custom } } -$rows = json_encode($results); -echo $rows; +$json = json_encode($results); +echo $json; diff --git a/editor.php b/editor.php index 5bd1aa69a..03994e103 100755 --- a/editor.php +++ b/editor.php @@ -12,33 +12,17 @@ if (empty($id_record) && !empty($id_module)) { include_once App::filepath('include|custom|', 'top.php'); -// Inclusione gli elementi fondamentali -include_once $docroot.'/actions.php'; +$query = Util\Query::getQuery($structure, [ + 'id' => $id_record, +]); +$has_access = $dbo->fetchNum($query); -// Widget in alto -echo '{( "name": "widgets", "id_module": "'.$id_module.'", "id_record": "'.$id_record.'", "position": "top", "place": "editor" )}'; - -$advanced_sessions = setting('Attiva notifica di presenza utenti sul record'); -if (!empty($advanced_sessions)) { - $dbo->query('DELETE FROM zz_semaphores WHERE id_utente='.prepare(Auth::user()['id']).' AND posizione='.prepare($id_module.', '.$id_record)); - - $dbo->query('INSERT INTO zz_semaphores (id_utente, posizione, updated) VALUES ('.prepare(Auth::user()['id']).', '.prepare($id_module.', '.$id_record).', NOW())'); - - echo ' -
-
-

'.tr('Attenzione!').'

-
-
-

'.tr('I seguenti utenti stanno visualizzando questa pagina').':

- -

'.tr('Prestare attenzione prima di effettuare modifiche, poichè queste potrebbero essere perse a causa di multipli salvataggi contemporanei').'.

-
-
'; +if ($has_access) { + // Inclusione gli elementi fondamentali + include_once $docroot.'/actions.php'; } -if (empty($record)) { +if (empty($record) || !$has_access) { echo '

'. @@ -53,6 +37,29 @@ if (empty($record)) {

'; } else { + // Widget in alto + echo '{( "name": "widgets", "id_module": "'.$id_module.'", "id_record": "'.$id_record.'", "position": "top", "place": "editor" )}'; + + $advanced_sessions = setting('Attiva notifica di presenza utenti sul record'); + if (!empty($advanced_sessions)) { + $dbo->query('DELETE FROM zz_semaphores WHERE id_utente='.prepare(Auth::user()['id']).' AND posizione='.prepare($id_module.', '.$id_record)); + + $dbo->query('INSERT INTO zz_semaphores (id_utente, posizione, updated) VALUES ('.prepare(Auth::user()['id']).', '.prepare($id_module.', '.$id_record).', NOW())'); + + echo ' +
+
+

'.tr('Attenzione!').'

+
+
+

'.tr('I seguenti utenti stanno visualizzando questa pagina').':

+ +

'.tr('Prestare attenzione prima di effettuare modifiche, poichè queste potrebbero essere perse a causa di multipli salvataggi contemporanei').'.

+
+
'; + } + echo ' '; if ($options != '' && $options != 'menu' && $options != 'custom') { - $total = App::readQuery(Modules::get($id_record)); - $module_query = $total['query']; + $module_query = Util\Query::getQuery(Module::find($id_record)); echo '
diff --git a/plugins/importFE/edit.php b/plugins/importFE/edit.php index 253d20aee..c1ac8f6f2 100644 --- a/plugins/importFE/edit.php +++ b/plugins/importFE/edit.php @@ -39,8 +39,8 @@ echo ' } buttonRestore(btn, restore); }, - error: function(data) { - alert("'.tr('Errore').': " + data); + error: function(xhr) { + alert("'.tr('Errore').': " + xhr.responseJSON.error.message); buttonRestore(btn, restore); } diff --git a/plugins/importFE/list.php b/plugins/importFE/list.php index a09314e80..d308f0268 100644 --- a/plugins/importFE/list.php +++ b/plugins/importFE/list.php @@ -62,11 +62,10 @@ function download(button, file) { title: "'.tr('Fattura già importata.').'", type: "info", }); + buttonRestore(button, restore); $(button).prop("disabled", true); } - - } }); } diff --git a/plugins/pianificazione_interventi/actions.php b/plugins/pianificazione_interventi/actions.php index 347718b59..37af4d332 100644 --- a/plugins/pianificazione_interventi/actions.php +++ b/plugins/pianificazione_interventi/actions.php @@ -272,7 +272,7 @@ switch (filter('op')) { case 'unlink_articolo': $idriga = post('idriga'); - $dbo->query('DELETE FROM co_promemoria_articoli WHERE id='.prepare($idriga).' '.Modules::getAdditionalsQuery($id_module)); + $dbo->query('DELETE FROM co_promemoria_articoli WHERE id='.prepare($idriga)); break; @@ -350,7 +350,7 @@ switch (filter('op')) { case 'delriga': $idriga = post('idriga'); - $dbo->query('DELETE FROM co_promemoria_righe WHERE id='.prepare($idriga).' '.Modules::getAdditionalsQuery($id_module)); + $dbo->query('DELETE FROM co_promemoria_righe WHERE id='.prepare($idriga)); break; } diff --git a/plugins/pianificazione_interventi/ajax_articoli.php b/plugins/pianificazione_interventi/ajax_articoli.php index 455991d0a..351d9f0a6 100644 --- a/plugins/pianificazione_interventi/ajax_articoli.php +++ b/plugins/pianificazione_interventi/ajax_articoli.php @@ -7,7 +7,7 @@ $is_add = filter('add') ? true : false; $pricing = Auth::admin() || Auth::user()['gruppo'] != 'Tecnici'; -$rs = $dbo->fetchArray('SELECT * FROM co_promemoria_articoli WHERE id_promemoria = '.prepare($id_record).' '.Modules::getAdditionalsQuery('Magazzino').' ORDER BY id ASC'); +$rs = $dbo->fetchArray('SELECT * FROM co_promemoria_articoli WHERE id_promemoria = '.prepare($id_record).' ORDER BY id ASC'); if (!empty($rs)) { echo ' diff --git a/plugins/pianificazione_interventi/ajax_righe.php b/plugins/pianificazione_interventi/ajax_righe.php index b8353299f..1295f20cc 100644 --- a/plugins/pianificazione_interventi/ajax_righe.php +++ b/plugins/pianificazione_interventi/ajax_righe.php @@ -7,7 +7,7 @@ $is_add = filter('add') ? true : false; $pricing = Auth::admin() || Auth::user()['gruppo'] != 'Tecnici'; -$rs2 = $dbo->fetchArray('SELECT * FROM co_promemoria_righe WHERE id_promemoria='.prepare($id_record).' '.Modules::getAdditionalsQuery('Magazzino').' ORDER BY id ASC'); +$rs2 = $dbo->fetchArray('SELECT * FROM co_promemoria_righe WHERE id_promemoria='.prepare($id_record).' ORDER BY id ASC'); if (!empty($rs2)) { echo ' diff --git a/src/App.php b/src/App.php index 8b93f149f..d46726576 100644 --- a/src/App.php +++ b/src/App.php @@ -198,69 +198,6 @@ class App return $assets; } - /** - * Restituisce un'insieme di array comprendenti le informazioni per la costruzione della query del modulo indicato. - * - * @param array $element - * - * @return array - */ - public static function readQuery($element) - { - if (str_contains($element['option'], '|select|')) { - $result = self::readNewQuery($element); - } else { - $result = self::readOldQuery($element); - } - - return $result; - } - - /** - * Sostituisce i valori previsti all'interno delle query di moduli/plugin. - * - * @param string $query - * @param int $custom - * - * @return string - */ - public static function replacePlaceholder($query) - { - $id_parent = filter('id_parent'); - - $id_module = Modules::getCurrent()['id']; - $segment = $_SESSION['module_'.$id_module]['id_segment']; - - $user = Auth::user(); - - // Elenco delle sostituzioni - $replace = [ - // Identificatori - '|id_anagrafica|' => prepare($user['idanagrafica']), - '|id_utente|' => prepare($user['id']), - '|id_parent|' => prepare($id_parent), - - // Date - '|period_start|' => $_SESSION['period_start'], - '|period_end|' => $_SESSION['period_end'], - - // Segmenti - '|segment|' => !empty($segment) ? ' AND id_segment = '.prepare($segment) : '', - ]; - - // Sostituzione dei formati - $patterns = formatter()->getSQLPatterns(); - - foreach ($patterns as $key => $value) { - $replace['|'.$key.'_format|'] = "'".$value."'"; - } - - // Sostituzione effettiva - $query = replace($query, $replace); - - return $query; - } - /** * Restituisce il codice HTML per il form contenente il file indicato. * @@ -352,132 +289,4 @@ class App return get_defined_vars(); } - - /** - * Interpreta lo standard modulare per l'individuazione delle query di un modulo/plugin del progetto. - * - * @param array $element - * - * @return array - */ - protected static function readNewQuery($element) - { - $fields = []; - $summable = []; - $search_inside = []; - $search = []; - $format = []; - $slow = []; - $order_by = []; - - $query = $element['option']; - $views = self::getViews($element); - - $select = []; - - foreach ($views as $view) { - $select[] = $view['query'].(!empty($view['name']) ? " AS '".$view['name']."'" : ''); - - if (!empty($view['visible'])) { - $view['name'] = trim($view['name']); - $view['search_inside'] = trim($view['search_inside']); - $view['order_by'] = trim($view['order_by']); - - $fields[] = trim($view['name']); - - $search_inside[] = !empty($view['search_inside']) ? $view['search_inside'] : '`'.$view['name'].'`'; - $order_by[] = !empty($view['order_by']) ? $view['order_by'] : '`'.$view['name'].'`'; - $search[] = $view['search']; - $slow[] = $view['slow']; - $format[] = $view['format']; - - if ($view['summable']) { - $summable[] = 'SUM(`'.trim($view['name']."`) AS 'sum_".(count($fields) - 1)."'"); - } - } - } - - $select = empty($select) ? '*' : implode(', ', $select); - - $query = str_replace('|select|', $select, $query); - - return [ - 'query' => self::replacePlaceholder($query), - 'fields' => $fields, - 'search_inside' => $search_inside, - 'order_by' => $order_by, - 'search' => $search, - 'slow' => $slow, - 'format' => $format, - 'summable' => $summable, - ]; - } - - /** - * Interpreta lo standard JSON per l'individuazione delle query di un modulo/plugin del progetto. - * - * @param array $element - * - * @return array - */ - protected static function readOldQuery($element) - { - $options = str_replace(["\r", "\n", "\t"], ' ', $element['option']); - $options = json_decode($options, true); - $options = $options['main_query'][0]; - - $fields = []; - $order_by = []; - - $search = []; - $slow = []; - $format = []; - - $query = $options['query']; - $views = explode(',', $options['fields']); - foreach ($views as $view) { - $fields[] = trim($view); - $order_by[] = '`'.trim($view).'`'; - - $search[] = 1; - $slow[] = 0; - $format[] = 0; - } - - $search_inside = $order_by; - - return [ - 'query' => self::replacePlaceholder($query), - 'fields' => $fields, - 'search_inside' => $search_inside, - 'order_by' => $order_by, - 'search' => $search, - 'slow' => $slow, - 'format' => $format, - 'summable' => [], - ]; - } - - /** - * Restituisce le singole componenti delle query per un determinato modulo/plugin. - * - * @param array $element - * - * @return array - */ - protected static function getViews($element) - { - $database = database(); - - $user = Auth::user(); - - $views = $database->fetchArray('SELECT * FROM `zz_views` WHERE `id_module`='.prepare($element['id']).' AND - `id` IN ( - SELECT `id_vista` FROM `zz_group_view` WHERE `id_gruppo`=( - SELECT `idgruppo` FROM `zz_users` WHERE `id`='.prepare($user['id']).' - )) - ORDER BY `order` ASC'); - - return $views; - } } diff --git a/src/HTMLBuilder/Manager/WidgetManager.php b/src/HTMLBuilder/Manager/WidgetManager.php index 78de1fc82..add04c418 100644 --- a/src/HTMLBuilder/Manager/WidgetManager.php +++ b/src/HTMLBuilder/Manager/WidgetManager.php @@ -74,7 +74,7 @@ class WidgetManager implements ManagerInterface $query = str_replace('1=1', '1=1 '.$additionals, $query); } - $query = \App::replacePlaceholder($query); + $query = \Util\Query::replacePlaceholder($query); // Individuazione del risultato della query $database = database(); @@ -110,7 +110,7 @@ class WidgetManager implements ManagerInterface elseif ($widget['more_link_type'] == 'javascript') { $link = $widget['more_link']; - $link = \App::replacePlaceholder($link); + $link = \Util\Query::replacePlaceholder($link); $result .= 'onclick="'.$link.'"'; } diff --git a/src/Models/Clause.php b/src/Models/Clause.php index 0505227b7..7ac7c2f18 100644 --- a/src/Models/Clause.php +++ b/src/Models/Clause.php @@ -2,7 +2,6 @@ namespace Models; -use App; use Common\Model; class Clause extends Model @@ -23,6 +22,6 @@ class Clause extends Model public function getClauseAttribute($value) { - return App::replacePlaceholder($value); + return Util\Query::replacePlaceholder($value); } } diff --git a/src/Models/View.php b/src/Models/View.php index 36ed05496..a19562a60 100644 --- a/src/Models/View.php +++ b/src/Models/View.php @@ -2,7 +2,6 @@ namespace Models; -use App; use Common\Model; class View extends Model @@ -11,7 +10,7 @@ class View extends Model public function getQueryAttribute($value) { - return App::replacePlaceholder($value); + return Util\Query::replacePlaceholder($value); } /* Relazioni Eloquent */ diff --git a/src/Modules.php b/src/Modules.php index 505a3a752..788ace750 100644 --- a/src/Modules.php +++ b/src/Modules.php @@ -120,7 +120,7 @@ class Modules $results = $database->fetchArray('SELECT * FROM `zz_group_module` WHERE `idgruppo` = (SELECT `idgruppo` FROM `zz_users` WHERE `id` = '.prepare($user['id']).') AND `enabled` = 1 AND `idmodule` = '.prepare($module['id'])); foreach ($results as $result) { if (!empty($result['clause'])) { - $result['clause'] = App::replacePlaceholder($result['clause']); + $result['clause'] = Util\Query::replacePlaceholder($result['clause']); $additionals[$result['position']][] = $result['clause']; } @@ -131,7 +131,7 @@ class Modules $id_segment = $_SESSION['module_'.$module['id']]['id_segment']; foreach ($segments as $result) { if (!empty($result['clause']) && $result['id'] == $id_segment) { - $result['clause'] = App::replacePlaceholder($result['clause']); + $result['clause'] = Util\Query::replacePlaceholder($result['clause']); $additionals[$result['position']][] = $result['clause']; } diff --git a/src/Util/Query.php b/src/Util/Query.php new file mode 100644 index 000000000..ddbcebb1d --- /dev/null +++ b/src/Util/Query.php @@ -0,0 +1,329 @@ + prepare($user['idanagrafica']), + '|id_utente|' => prepare($user['id']), + '|id_parent|' => prepare($id_parent), + + // Date + '|period_start|' => $_SESSION['period_start'], + '|period_end|' => $_SESSION['period_end'], + + // Segmenti + '|segment|' => !empty($segment) ? ' AND id_segment = '.prepare($segment) : '', + ]; + + // Sostituzione dei formati + $patterns = formatter()->getSQLPatterns(); + + foreach ($patterns as $key => $value) { + $replace['|'.$key.'_format|'] = "'".$value."'"; + } + + // Sostituzione effettiva + $query = replace($query, $replace); + + return $query; + } + + /** + * Genera la query prevista dalla struttura indicata. + * + * @param $structure + * @param array $search + * @param array $order + * @param array $limit + * + * @throws \Exception + * + * @return mixed|string + */ + public static function getQuery($structure, $search = [], $order = [], $limit = []) + { + $total = self::readQuery($structure); + + // Lettura parametri modulo + $query = $total['query']; + + if (empty($query) || $query == 'menu' || $query == 'custom') { + return ''; + } + + // Filtri di ricerica + $search_filters = []; + foreach ($search as $field => $value) { + $pos = array_search($field, $total['fields']); + + if (isset($value) && $pos !== false) { + $search_query = $total['search_inside'][$pos]; + + if (str_contains($search_query, '|search|')) { + $pieces = explode(',', $value); + foreach ($pieces as $piece) { + $piece = trim($piece); + $search_filters[] = str_replace('|search|', prepare('%'.$piece.'%'), $search_query); + } + } else { + // Per le icone cerco nel campo icon_title + if (preg_match('/^icon_(.+?)$/', $field, $m)) { + $search_query = '`icon_title_'.$m[1].'`'; + } + + // Per i colori cerco nel campo color_title + elseif (preg_match('/^color_(.+?)$/', $field, $m)) { + $search_query = '`color_title_'.$m[1].'`'; + } + + $search_filters[] = $search_query.' LIKE '.prepare('%'.trim($value.'%')); + } + } + + // Ricerca + if (!empty($search_filters)) { + $query = str_replace('2=2', '2=2 AND ('.implode(' AND ', $search_filters).') ', $query); + } + } + + // Ordinamento dei risultati + if (isset($order['dir']) && isset($order['column'])) { + $pos = array_search($order['column'], total['fields']); + + if ($pos !== false) { + $pieces = explode('ORDER', $query); + + $count = count($pieces); + if ($count > 1) { + unset($pieces[$count - 1]); + } + + $query = implode('ORDER', $pieces).' ORDER BY '.$total['order_by'][$order['column']].' '.$order['dir']; + } + } + + // Paginazione + if (!empty($limit)) { + $query .= ' LIMIT '.$limit['start'].', '.$limit['length']; + } + + return $query; + } + + /** + * Restituisce le somme richieste dalla query prevista dalla struttura. + * + * @param $structure + * @param array $search + * + * @throws \Exception + * + * @return array + */ + public static function getSums($structure, $search = []) + { + $total = self::readQuery($structure, $search); + + // Calcolo di eventuali somme + if (empty($total['summable'])) { + return []; + } + + $result_query = self::getQuery($structure, $search); + + $query = str_replace_once('SELECT', 'SELECT '.implode(', ', $total['summable']).' FROM(SELECT ', $result_query).') AS `z`'; + $sums = database()->fetchOne($query); + + $results = []; + if (!empty($sums)) { + foreach ($sums as $key => $sum) { + if (str_contains($key, 'sum_')) { + $results[str_replace('sum_', '', $key)] = Translator::numberToLocale($sum); + } + } + } + + return $results; + } + + /** + * Interpreta lo standard modulare per l'individuazione delle query di un modulo/plugin del progetto. + * + * @param $element + * + * @throws \Exception + * + * @return array + */ + protected static function readNewQuery($element) + { + $fields = []; + $summable = []; + $search_inside = []; + $search = []; + $format = []; + $slow = []; + $order_by = []; + + $query = $element['option']; + $views = self::getViews($element); + + $select = []; + + foreach ($views as $view) { + $select[] = $view['query'].(!empty($view['name']) ? " AS '".$view['name']."'" : ''); + + if (!empty($view['visible'])) { + $view['name'] = trim($view['name']); + $view['search_inside'] = trim($view['search_inside']); + $view['order_by'] = trim($view['order_by']); + + $fields[] = trim($view['name']); + + $search_inside[] = !empty($view['search_inside']) ? $view['search_inside'] : '`'.$view['name'].'`'; + $order_by[] = !empty($view['order_by']) ? $view['order_by'] : '`'.$view['name'].'`'; + $search[] = $view['search']; + $slow[] = $view['slow']; + $format[] = $view['format']; + + if ($view['summable']) { + $summable[] = 'SUM(`'.trim($view['name']."`) AS 'sum_".(count($fields) - 1)."'"); + } + } + } + + $select = empty($select) ? '*' : implode(', ', $select); + + $query = str_replace('|select|', $select, $query); + + return [ + 'query' => self::replacePlaceholder($query), + 'fields' => $fields, + 'search_inside' => $search_inside, + 'order_by' => $order_by, + 'search' => $search, + 'slow' => $slow, + 'format' => $format, + 'summable' => $summable, + ]; + } + + /** + * Interpreta lo standard JSON per l'individuazione delle query di un modulo/plugin del progetto. + * + * @param array $element + * + * @return array + */ + protected static function readOldQuery($element) + { + $options = str_replace(["\r", "\n", "\t"], ' ', $element['option']); + $options = json_decode($options, true); + $options = $options['main_query'][0]; + + $fields = []; + $order_by = []; + + $search = []; + $slow = []; + $format = []; + + $query = $options['query']; + $views = explode(',', $options['fields']); + foreach ($views as $view) { + $fields[] = trim($view); + $order_by[] = '`'.trim($view).'`'; + + $search[] = 1; + $slow[] = 0; + $format[] = 0; + } + + $search_inside = $order_by; + + return [ + 'query' => self::replacePlaceholder($query), + 'fields' => $fields, + 'search_inside' => $search_inside, + 'order_by' => $order_by, + 'search' => $search, + 'slow' => $slow, + 'format' => $format, + 'summable' => [], + ]; + } + + /** + * Restituisce le singole componenti delle query per un determinato modulo/plugin. + * + * @param $element + * + * @throws \Exception + * + * @return array + */ + protected static function getViews($element) + { + $database = database(); + + $user = Auth::user(); + + $views = $database->fetchArray('SELECT * FROM `zz_views` WHERE `id_module`='.prepare($element['id']).' AND + `id` IN ( + SELECT `id_vista` FROM `zz_group_view` WHERE `id_gruppo`=( + SELECT `idgruppo` FROM `zz_users` WHERE `id`='.prepare($user['id']).' + )) + ORDER BY `order` ASC'); + + return $views; + } +} diff --git a/templates/interventi/init.php b/templates/interventi/init.php index 5e98119f1..1692fdbf4 100644 --- a/templates/interventi/init.php +++ b/templates/interventi/init.php @@ -5,7 +5,7 @@ include_once __DIR__.'/../../core.php'; $module_name = 'Interventi'; // carica intervento -$query = 'SELECT in_interventi.*, (SELECT numero FROM co_contratti WHERE id=(SELECT idcontratto FROM co_promemoria WHERE idintervento=in_interventi.id)) AS numero_contratto, (SELECT numero FROM co_preventivi WHERE id=in_interventi.id_preventivo) AS numero_preventivo, (SELECT SUM(prezzo_dirittochiamata) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_dirittochiamata`, (SELECT SUM(km) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_km`, (SELECT SUM(ore*prezzo_ore_unitario) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_ore_consuntivo`, (SELECT SUM(prezzo_km_consuntivo) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_km_consuntivo`, in_interventi.descrizione AS `descrizione_intervento`, richiesta, (SELECT descrizione FROM in_tipiintervento WHERE idtipointervento=in_interventi.idtipointervento) AS tipointervento FROM in_interventi INNER JOIN in_tipiintervento ON in_interventi.idtipointervento=in_tipiintervento.idtipointervento WHERE id='.prepare($id_record).' '.Modules::getAdditionalsQuery('Interventi'); +$query = 'SELECT in_interventi.*, (SELECT numero FROM co_contratti WHERE id=(SELECT idcontratto FROM co_promemoria WHERE idintervento=in_interventi.id)) AS numero_contratto, (SELECT numero FROM co_preventivi WHERE id=in_interventi.id_preventivo) AS numero_preventivo, (SELECT SUM(prezzo_dirittochiamata) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_dirittochiamata`, (SELECT SUM(km) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_km`, (SELECT SUM(ore*prezzo_ore_unitario) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_ore_consuntivo`, (SELECT SUM(prezzo_km_consuntivo) FROM in_interventi_tecnici GROUP BY idintervento HAVING idintervento=in_interventi.id) AS `tot_km_consuntivo`, in_interventi.descrizione AS `descrizione_intervento`, richiesta, (SELECT descrizione FROM in_tipiintervento WHERE idtipointervento=in_interventi.idtipointervento) AS tipointervento FROM in_interventi INNER JOIN in_tipiintervento ON in_interventi.idtipointervento=in_tipiintervento.idtipointervento WHERE id='.prepare($id_record); $records = $dbo->fetchArray($query); $costi_intervento = get_costi_intervento($id_record); diff --git a/templates/riepilogo_interventi/pdfgen.riepilogo_interventi.php b/templates/riepilogo_interventi/pdfgen.riepilogo_interventi.php index f4f7a0efa..eed8578bb 100644 --- a/templates/riepilogo_interventi/pdfgen.riepilogo_interventi.php +++ b/templates/riepilogo_interventi/pdfgen.riepilogo_interventi.php @@ -5,7 +5,7 @@ include_once __DIR__.'/../../core.php'; $module = Modules::get('Interventi'); $id_module = $module['id']; -$total = App::readQuery($module); +$total = Util\Query::readQuery($module); // Lettura parametri modulo $module_query = $total['query'];