diff --git a/front/css/app.css b/front/css/app.css index dd6c533e..e8209c24 100755 --- a/front/css/app.css +++ b/front/css/app.css @@ -1245,6 +1245,20 @@ input[readonly] { /* Devices page */ /* ----------------------------------------------------------------- */ + +#columnFilters { + display: flex; + flex-wrap: wrap; + gap: 10px; /* Add spacing between items */ +} + +.filter-group { + flex: 1 100px; + box-sizing: border-box; /* Ensure padding and borders are included in the width */ + padding: 1em; + padding-top: 0; +} + .modal-header .close { display: flex; diff --git a/front/devices.php b/front/devices.php index 8cb26730..a3ee02be 100755 --- a/front/devices.php +++ b/front/devices.php @@ -32,9 +32,8 @@
-
+
-
@@ -42,7 +41,7 @@
-
+

@@ -59,6 +58,15 @@
+ + +
@@ -133,6 +141,8 @@ function main () { showSpinner(); + initFilters(); + // render tiles getDevicesTotals(); @@ -319,6 +329,184 @@ function renderInfoboxes(customData) { } } +// ----------------------------------------------------------------------------- +//Render filters if specified +let columnFilters = []; + +function initFilters() { + // Attempt to fetch data + $.ajax({ + url: '/php/server/query_json.php', + type: "GET", + dataType: "json", + data: { + file: 'table_devices_filters.json', // Pass the file parameter + nocache: Date.now() // Prevent caching with a timestamp + }, + success: function(response) { + if (response && response.data) { + + let resultJSON = response.data; + + // Save the result to cache + setCache("devicesFilters", JSON.stringify(resultJSON)); + + // Get the displayed filters from settings + const displayedFilters = createArray(getSetting("UI_columns_filters")); + + // Clear any existing filters in the DOM + $('#columnFilters').empty(); + + console.log(displayedFilters); + + // Ensure displayedFilters is an array and not empty + if (Array.isArray(displayedFilters) && displayedFilters.length > 0) { + $('#columnFiltersWrap').removeClass("hidden"); + + displayedFilters.forEach(columnHeaderStringKey => { + // Get the column name using the mapping function + const columnName = getColumnNameFromLangString(columnHeaderStringKey); + + // Ensure columnName is valid before proceeding + if (columnName) { + // Add the filter to the columnFilters array as [columnName, columnHeaderStringKey] + columnFilters.push([columnName, columnHeaderStringKey]); + } else { + console.warn(`Invalid column header string key: ${columnHeaderStringKey}`); + } + }); + + // Filter resultJSON to include only entries with columnName in columnFilters + resultJSON = resultJSON.filter(entry => + columnFilters.some(filter => filter[0] === entry.columnName) + ); + + // Expand resultJSON to include the columnHeaderStringKey + resultJSON.forEach(entry => { + // Find the matching columnHeaderStringKey from columnFilters + const matchingFilter = columnFilters.find(filter => filter[0] === entry.columnName); + + // Add the columnHeaderStringKey to the entry + if (matchingFilter) { + entry['columnHeaderStringKey'] = matchingFilter[1]; + } + }); + + console.log(resultJSON); + + // Transforming the data + const transformed = { + filters: [] + }; + + // Group data by columnName + resultJSON.forEach(entry => { + const existingFilter = transformed.filters.find(filter => filter.column === entry.columnName); + + if (existingFilter) { + // Add the unique columnValue to options if not already present + if (!existingFilter.options.includes(entry.columnValue)) { + existingFilter.options.push(entry.columnValue); + } + } else { + // Create a new filter entry + transformed.filters.push({ + column: entry.columnName, + headerKey: entry.columnHeaderStringKey, + options: [entry.columnValue] + }); + } + }); + + // Sort options alphabetically for better readability + transformed.filters.forEach(filter => { + filter.options.sort(); + }); + + // Output the result + transformedJson = transformed + + // Process the fetched data + renderFilters(transformedJson); + } else { + console.log("No filters to display."); + } + } else { + console.error("Invalid response format from API"); + } + }, + error: function(xhr, status, error) { + console.error("Failed to fetch devices data 'table_devices_filters.json':", error); + } + }); +} + + +// ------------------------------------------- +// Server side component +function renderFilters(customData) { + + console.log(JSON.stringify(customData)); + + // Load filter data from the JSON file + $.ajax({ + url: 'php/components/devices_filters.php', // PHP script URL + data: { filterObject: JSON.stringify(customData) }, // Send customData as JSON + type: 'POST', + dataType: 'html', + success: function(response) { + console.log(response); + + $('#columnFilters').html(response); // Replace container content with fetched HTML + $('#columnFilters').removeClass('hidden'); // Show the filters container + + // Trigger the draw after select change + $('.filter-dropdown').on('change', function() { + // Collect filters + const columnFilters = collectFilters(); + + // Update DataTable with the new filters or search value (if applicable) + $('#tableDevices').DataTable().draw(); + + // Optionally, apply column filters (if using filters for individual columns) + const table = $('#tableDevices').DataTable(); + table.columnFilters = columnFilters; // Apply your column filters logic + table.draw(); + }); + + }, + error: function(xhr, status, error) { + console.error('Error fetching filters:', error); + } + }); +} + +// ------------------------------------------- +// Function to collect filters +function collectFilters() { + const columnFilters = []; + + // Loop through each filter group + document.querySelectorAll('.filter-group').forEach(filterGroup => { + const dropdown = filterGroup.querySelector('.filter-dropdown'); + + if (dropdown) { + const filterColumn = dropdown.getAttribute('data-column'); + const filterValue = dropdown.value; + + if (filterValue && filterColumn) { + columnFilters.push({ + filterColumn: filterColumn, + filterValue: filterValue + }); + } + } + }); + + return columnFilters; +} + + // ----------------------------------------------------------------------------- // Map column index to column name for GraphQL query function mapColumnIndexToFieldName(index, tableColumnVisible) { @@ -411,8 +599,6 @@ function initializeDatatable (status) { } // todo: dynamically filter based on status - - var table = $('#tableDevices').DataTable({ "serverSide": true, "processing": true, @@ -469,7 +655,13 @@ function initializeDatatable (status) { `; console.log(d); - + + // Handle empty filters + let columnFilters = collectFilters(); + if (columnFilters.length === 0) { + columnFilters = []; + } + // Prepare query variables for pagination, sorting, and search let query = { @@ -484,7 +676,8 @@ function initializeDatatable (status) { "order": d.order[0].dir.toUpperCase() // Sort direction (ASC/DESC) }] : [], // Default to an empty array if no sorting is defined "search": d.search.value, // Search query - "status": deviceStatus + "status": deviceStatus, + "filters" : columnFilters } } diff --git a/front/js/ui_components.js b/front/js/ui_components.js index c1d7b2eb..12db34f6 100755 --- a/front/js/ui_components.js +++ b/front/js/ui_components.js @@ -508,8 +508,52 @@ function showIconSelection() { } +// "Device_TableHead_Owner", +// "Device_TableHead_Type", +// "Device_TableHead_Group", +// "Device_TableHead_Status", +// "Device_TableHead_Location", +// "Device_TableHead_Vendor", +// "Device_TableHead_SyncHubNodeName", +// "Device_TableHead_NetworkSite", +// "Device_TableHead_SSID", +// "Device_TableHead_SourcePlugin" +// ----------------------------------------------------------------------------- +// Get teh correct db column code name based on table header title string +function getColumnNameFromLangString(headStringKey) { + columnNameMap = { + "Device_TableHead_Name": "devName", + "Device_TableHead_Owner": "devOwner", + "Device_TableHead_Type": "devType", + "Device_TableHead_Icon": "devIcon", + "Device_TableHead_Favorite": "devFavorite", + "Device_TableHead_Group": "devGroup", + "Device_TableHead_FirstSession": "devFirstConnection", + "Device_TableHead_LastSession": "devLastConnection", + "Device_TableHead_LastIP": "devLastIP", + "Device_TableHead_MAC": "devMac", + "Device_TableHead_Status": "devStatus", + "Device_TableHead_MAC_full": "devMac", + "Device_TableHead_LastIPOrder": "devIpLong", + "Device_TableHead_Rowid": "rowid", + "Device_TableHead_Parent_MAC": "devParentMAC", + "Device_TableHead_Connected_Devices": "devParentChildrenCount", + "Device_TableHead_Location": "devLocation", + "Device_TableHead_Vendor": "devVendor", + "Device_TableHead_Port": "devParentPort", + "Device_TableHead_GUID": "devGUID", + "Device_TableHead_SyncHubNodeName": "devSyncHubNode", + "Device_TableHead_NetworkSite": "devSite", + "Device_TableHead_SSID": "devSSID", + "Device_TableHead_SourcePlugin": "devSourcePlugin", + "Device_TableHead_PresentLastScan": "devPresentLastScan", + "Device_TableHead_AlertDown": "devAlertDown", + "Device_TableHead_CustomProps": "devCustomProps" + }; + return columnNameMap[headStringKey] || ""; +} // ----------------------------------------------------------------------------- diff --git a/front/php/components/devices_filters.php b/front/php/components/devices_filters.php new file mode 100755 index 00000000..a620c87a --- /dev/null +++ b/front/php/components/devices_filters.php @@ -0,0 +1,52 @@ +All'; // Default "All" option + foreach ($values as $value) { + $escapedValue = htmlspecialchars($value); + $optionsHtml .= ''; + } + + // Generate the dropdown HTML + return ' +
+ + +
'; +} + +// Get filterObject from POST data +$filterObject = isset($_POST['filterObject']) ? json_decode($_POST['filterObject'], true) : []; + +// Validate filterObject structure +if (!isset($filterObject['filters']) || !is_array($filterObject['filters'])) { + echo '

Invalid filter data provided.

'; + exit(); +} + +// Generate HTML for each filter in the filterObject +$html = ''; +foreach ($filterObject['filters'] as $filter) { + if (isset($filter['column'], $filter['headerKey'], $filter['options'])) { + $html .= renderFilterDropdown($filter['headerKey'], $filter['column'], $filter['options']); + } else { + // Skip invalid entries + continue; + } +} + +// Output the generated HTML +echo $html; +exit(); + +?> diff --git a/front/php/templates/language/ar_ar.json b/front/php/templates/language/ar_ar.json index af855c37..c65ed6af 100755 --- a/front/php/templates/language/ar_ar.json +++ b/front/php/templates/language/ar_ar.json @@ -242,6 +242,7 @@ "Device_Tablelenght": "", "Device_Tablelenght_all": "", "Device_Title": "", + "Devices_Filters": "", "Donations_Others": "", "Donations_Platforms": "", "Donations_Text": "", diff --git a/front/php/templates/language/ca_ca.json b/front/php/templates/language/ca_ca.json index 5b5e9b67..599d6cdb 100755 --- a/front/php/templates/language/ca_ca.json +++ b/front/php/templates/language/ca_ca.json @@ -242,6 +242,7 @@ "Device_Tablelenght": "Veure_entrades_MENU", "Device_Tablelenght_all": "Tot", "Device_Title": "Dispositius", + "Devices_Filters": "", "Donations_Others": "Altres", "Donations_Platforms": "Plataformes patrocinadores", "Donations_Text": "Hola 👋!
Gràcies per fer clic en aquest element de menú 😅

Estic intentant recollir algunes donacions per fer un millor programari. També, m'ajudaria per cremar-me, i així recolzar aquesta aplicació més temps. Qualsevol petit (recurrent o no) patrocini em farà posar més esforç a aquesta aplicació.
M'agradaria escurçar la meva setmana de feina i en el temps restant enfocar-me en el NetAlertX. Així rebries més funcionalitat, una aplicació més neta i menys bugs.

Gràcies per llegir-ho - Agraeixo qualsevol suport ❤🙏

TL;DR: Pel teu suport reps:

  • Actualitzacions regulars per seguir les vostres dades i mantenir la família segura 🔄
  • Menys bugs 🐛🔫
  • Millor i més funcionalitat➕
  • Que no m'arribi el \"burn out\" 🔥🤯
  • Menys actualitzacions d'emergència 💨
  • Millors documentacions📚
  • Suport més ràpid i millor amb les incidències 🆘

📧Correu electrònic jokob@duck.com si vols contactar o si hauria d'afegir altres programes de patrocini.
", diff --git a/front/php/templates/language/cs_cz.json b/front/php/templates/language/cs_cz.json index af855c37..c65ed6af 100755 --- a/front/php/templates/language/cs_cz.json +++ b/front/php/templates/language/cs_cz.json @@ -242,6 +242,7 @@ "Device_Tablelenght": "", "Device_Tablelenght_all": "", "Device_Title": "", + "Devices_Filters": "", "Donations_Others": "", "Donations_Platforms": "", "Donations_Text": "", diff --git a/front/php/templates/language/de_de.json b/front/php/templates/language/de_de.json index 7edd3a4a..513105fb 100755 --- a/front/php/templates/language/de_de.json +++ b/front/php/templates/language/de_de.json @@ -254,6 +254,7 @@ "Device_Tablelenght": "Zeige _MENU_ Einträge", "Device_Tablelenght_all": "Alle", "Device_Title": "Geräte", + "Devices_Filters": "", "Donations_Others": "Andere", "Donations_Platforms": "Sponsor-Platformen", "Donations_Text": "Hey 👋!
Thanks for clicking on this menu item 😅

I'm trying to collect some donations to make you better software. Also, it would help me not to get burned out. Me burning out might mean end of support for this app. Any small (recurring or not) sponsorship makes me want ot put more effort into this app. I don't want to lock features (new plugins) behind paywalls 🔐.
Currently, I'm waking up 2h before work so I contribute to the app a bit. If I had some recurring income I could shorten my workweek and in the remaining time fully focus on NetAlertX. You'd get more functionality, a more polished app and less bugs.

Thanks for reading - I'm super grateful for any support ❤🙏

TL;DR: By supporting me you get:

  • Regular updates to keep your data and family safe 🔄
  • Less bugs 🐛🔫
  • Better and more functionality➕
  • I don't get burned out 🔥🤯
  • Less rushed releases 💨
  • Better docs📚
  • Quicker and better support with issues 🆘
  • Less grumpy me 😄

📧Email me to jokob@duck.com if you want to get in touch or if I should add other sponsorship platforms.
", diff --git a/front/php/templates/language/en_us.json b/front/php/templates/language/en_us.json index 501eb0be..42cfb001 100755 --- a/front/php/templates/language/en_us.json +++ b/front/php/templates/language/en_us.json @@ -242,6 +242,7 @@ "Device_Tablelenght": "Show _MENU_ entries", "Device_Tablelenght_all": "All", "Device_Title": "Devices", + "Devices_Filters": "Filters", "Donations_Others": "Others", "Donations_Platforms": "Sponsor platforms", "Donations_Text": "Hey 👋!
Thanks for clicking on this menu item 😅

I'm trying to collect some donations to make you better software. Also, it would help me not to get burned out, so I can support this app longer. Any small (recurring or not) sponsorship makes me want to put more effort into this app.
I'd love to shorten my work week and in the remaining time fully focus on NetAlertX. You'd get more functionality, a more polished app and less bugs.

Thanks for reading - I'm grateful for any support ❤🙏

TL;DR: By supporting me you get:

  • Regular updates to keep your data and family safe 🔄
  • Less bugs 🐛🔫
  • Better and more functionality➕
  • I don't get burned out 🔥🤯
  • Less rushed releases 💨
  • Better docs📚
  • Quicker and better support with issues 🆘

📧Email me to jokob@duck.com if you want to get in touch or if I should add other sponsorship platforms.
", diff --git a/front/php/templates/language/es_es.json b/front/php/templates/language/es_es.json index 00360a99..814af788 100755 --- a/front/php/templates/language/es_es.json +++ b/front/php/templates/language/es_es.json @@ -252,6 +252,7 @@ "Device_Tablelenght": "Mostrar _MENU_ entradas", "Device_Tablelenght_all": "Todos", "Device_Title": "Dispositivos", + "Devices_Filters": "", "Donations_Others": "Otros", "Donations_Platforms": "Plataforma de patrocinadores", "Donations_Text": "¡Hola! 👋
Gracias por hacer clic en este elemento 😅 del menú

, estoy tratando de recolectar algunas donaciones para mejorar el software. Además, me ayudaría a no quemarse, por lo que puedo apoyar esta aplicación por más tiempo. Cualquier pequeño patrocinio (recurrente o no) me hace querer esforzarme más en esta aplicación.
Me encantaría acortar mi semana de trabajo y en el tiempo que me queda centrarme por completo en NetAlertX. Obtendrías más funcionalidad, una aplicación más pulida y menos errores.

Gracias por leer, agradezco cualquier apoyo ❤🙏

TL; DR: Al apoyarme, obtienes:

  • Actualizaciones periódicas para mantener tus datos y tu familia seguros 🔄
  • Menos errores 🐛🔫
  • Mejor y más funcionalidad➕
  • No me quemo 🔥🤯
  • Lanzamientos 💨menos apresurados
  • Mejores documentos📚
  • Soporte más rápido y mejor con problemas 🆘

📧Envíame un correo electrónico a jokob@duck.com si quieres ponerte en contacto o si debo añadir otras plataformas de patrocinio.
", diff --git a/front/php/templates/language/fr_fr.json b/front/php/templates/language/fr_fr.json index 9878c1c3..771c1d2e 100755 --- a/front/php/templates/language/fr_fr.json +++ b/front/php/templates/language/fr_fr.json @@ -242,6 +242,7 @@ "Device_Tablelenght": "Afficher les entrées _MENU_", "Device_Tablelenght_all": "Tous", "Device_Title": "Appareils", + "Devices_Filters": "", "Donations_Others": "Autres", "Donations_Platforms": "Plateformes de sponsoring", "Donations_Text": "Coucou 👋 !
Merci d'avoir cliqué ici 😅

J'essaie de récolter des donations pour vous faire un meilleur produit. En plus, ça m'aide à éviter le burn-out pour développer cette application plus longtemps. Toute subvention (régulière ou non) me donne envie de poursuivre le développement de cette application.
J'aimerais réduire mon activité principale pour me concentrer plus longuement à NetAlertX. Vous auriez plus de fonctionnalités, une application mieux finie et avec moins de bugs.

Merci de votre lecture - je vous suis reconnaissant pour votre soutien ❤🙏

Version courte : en me soutenant, vous aurez :

  • Des mises à jour régulières pour protéger vos données personnelles et familiales 🔄
  • Moins de bugs 🐛🔫
  • Des fonctionnalités plus riches et plus nombreuses ➕
  • Je ne me retrouve pas en burn-out 🔥🤯
  • Des versions moins à la va-vite 💨
  • une meilleure documentation �
  • Un support meilleur et plus réactif en cas de problème 🆘

📧Envoyez-moi un courriel à jokob@duck.com si vous voulez me contacter ou du je peux ajouter une autre plateforme de soutien.
", diff --git a/front/php/templates/language/it_it.json b/front/php/templates/language/it_it.json index b13e4179..6cd6df4f 100755 --- a/front/php/templates/language/it_it.json +++ b/front/php/templates/language/it_it.json @@ -242,6 +242,7 @@ "Device_Tablelenght": "Mostra _MENU_ elementi", "Device_Tablelenght_all": "Tutti", "Device_Title": "Dispositivi", + "Devices_Filters": "", "Donations_Others": "Altri", "Donations_Platforms": "Piattaforme sponsor", "Donations_Text": "Hey 👋!
Grazie per aver cliccato su questa voce di menu 😅

Sto cercando di ricevere donazioni per poter fornire un software migliore. Inoltre potrebbe aiutarmi a non andare in burnout, in modo da poter supportare questa app più a lungo. Ogni piccola (ricorrente o non) sponsorizzazione mi invoglia a mettere più impegno nello sviluppo di questa app.
Mi piacerebbe accorciare la mia settimana lavorativa e nel tempo rimanente dedicarmi completamente a NetAlertX. Riceverai più funzionalità, un'applicazione più rifinita e con meno bug.

Grazie per aver letto, ti sono grato per ogni tipo di supporto ❤🙏

TL;DR: Supportandomi otterrai:

  • Aggiornamenti più regolari per mantenere i tuoi dati e la tua famiglia sicuri 🔄
  • Meno bug 🐛🔫
  • Funzionalità migliori e più numerose➕
  • Io non vado in burnout 🔥🤯
  • Rilasci meno affrettati 💨
  • Migliore documentazione 📚
  • Supporto migliore e più veloce in caso di problemi 🆘

📧Invia una mail a jokob@duck.com se vuoi contattarmi o chiedermi di aggiungere altre piattaforme di sponsorizzazione.
", @@ -751,4 +752,4 @@ "settings_update_item_warning": "Aggiorna il valore qui sotto. Fai attenzione a seguire il formato precedente. La convalida non viene eseguita.", "test_event_icon": "fa-vial-circle-check", "test_event_tooltip": "Salva le modifiche prima di provare le nuove impostazioni." -} +} \ No newline at end of file diff --git a/front/php/templates/language/nb_no.json b/front/php/templates/language/nb_no.json index 367e512a..68393360 100755 --- a/front/php/templates/language/nb_no.json +++ b/front/php/templates/language/nb_no.json @@ -242,6 +242,7 @@ "Device_Tablelenght": "Show _MENU_ entries", "Device_Tablelenght_all": "Alle", "Device_Title": "Enheter", + "Devices_Filters": "", "Donations_Others": "Andre", "Donations_Platforms": "Sponsorplattformer", "Donations_Text": "Hei 👋!
Takk for at du klikket på dette menyelementet 😅

Jeg prøver å samle inn noen donasjoner for å lage bedre programvare. Dessuten ville det hjelpe meg å ikke bli utbrent, så jeg kan støtte denne appen lenger. Enhver liten (tilbakevendende eller ikke) sponsing gjør at jeg ønsker å legge mer innsats i denne appen.
Jeg vil gjerne forkorte arbeidsuken min og i den gjenværende tiden fokusere fullt ut på NetAlertX. Du vil få mer funksjonalitet, en mer polert app og mindre feil.

Takk for at du leste - jeg er takknemlig for all støtte ❤🙏

TL;DR: Ved å støtte meg får du:

  • Jevne oppdateringer for å holde dataene dine og familien din trygge 🔄
  • Mindre feil 🐛🔫
  • Bedre og mer funksjonalitet➕
  • Jeg blir ikke utbrent 🔥🤯
  • Mindre forhastede utgivelser 💨
  • Bedre dokumenter📚
  • Raskere og bedre støtte med problemer 🆘

📧 Send meg en e-post til jokob@duck.com hvis du ønsker å komme i kontakt eller hvis jeg skal legge til andre sponsorplattformer.
", diff --git a/front/php/templates/language/pl_pl.json b/front/php/templates/language/pl_pl.json index 8056bbb5..15e8b460 100755 --- a/front/php/templates/language/pl_pl.json +++ b/front/php/templates/language/pl_pl.json @@ -242,6 +242,7 @@ "Device_Tablelenght": "Pokaż_wpisy_MENU", "Device_Tablelenght_all": "Wszystkie", "Device_Title": "Urządzenia", + "Devices_Filters": "", "Donations_Others": "Inne", "Donations_Platforms": "Platforma Sponsora", "Donations_Text": "Cześć 👋!
Dziękuje że kliknąłeś w to menu 😅

Próbuje zebrać trochę dotacji by ulepszyć to oprogramowanie. Także pomaga mi to się nie wypalić bym dalej mógł ulepszać to narzędzie. Każdy mały (powtarzający się lub nie) sponsoring sprawia że chce wkładać więcej pracy w tą aplikację.
Chciałbym skrócić mój tydzień pracy i w wolnym czasie skupić się nad NetAlertX. Dostawalibyście wtedy więcej funkcjonalności i były by one ciągle udoskonalane i posiadające mniej błędów.

Dziękuję że to przeczytałeś - Jestem wdzięczny za pomoc ❤🙏

TL;DR: Wspierając mnie otrzymujesz:

  • Regularne aktualizacje by zapewnić twoim danym i rodzinie bezpieczeństwo 🔄
  • Mniej błędów (bugów) 🐛🔫
  • Nowe i lepsze funkcjonalności➕
  • Nie tracę zapału do dalszego tworzenia 🔥🤯
  • Mniej pośpieszne, bardziej dopracowane wydania💨
  • Lepsza dokumentacja📚
  • Szybsza i lepsza pomoc w problemach🆘

📧Napisz E-mail do mnie najokob@duck.com jeżeli chcesz nawiązać kontakt albo czy powinien dodać kolejną platformę z sponsoringiem.
", @@ -751,4 +752,4 @@ "settings_update_item_warning": "Zaktualizuj poniższą wartość. Zachowaj ostrożność i postępuj zgodnie z poprzednim formatem. Walidacja nie jest wykonywana.", "test_event_icon": "fa-vial-circle-check", "test_event_tooltip": "Zapisz zmiany zanim będziesz testować swoje ustawienia." -} +} \ No newline at end of file diff --git a/front/php/templates/language/pt_br.json b/front/php/templates/language/pt_br.json index bace247d..09fc83fc 100755 --- a/front/php/templates/language/pt_br.json +++ b/front/php/templates/language/pt_br.json @@ -242,6 +242,7 @@ "Device_Tablelenght": "Mostrar entradas do _MENU_", "Device_Tablelenght_all": "Todos", "Device_Title": "Dispositivos", + "Devices_Filters": "", "Donations_Others": "Outros", "Donations_Platforms": "Plataformas de patrocinadores", "Donations_Text": "Ei 👋!
Obrigado por clicar neste item de menu 😅

Estou tentando coletar algumas doações para melhorar o software. Além disso, isso me ajudaria a não ficar exausto, para que eu pudesse oferecer suporte a este aplicativo por mais tempo. Qualquer pequeno patrocínio (recorrente ou não) me faz querer colocar mais esforço neste aplicativo.
Eu adoraria encurtar minha semana de trabalho e no tempo restante focar totalmente no NetAlertX. Você obteria mais funcionalidades, um aplicativo mais sofisticado e menos bugs.

Obrigado pela leitura - sou grato por qualquer apoio ❤🙏

TL;DR: Ao me apoiar, você obtém:

  • Atualizações regulares para manter seus dados e sua família seguros 🔄
  • Menos bugs 🐛🔫
  • Melhor e mais funcionalidade➕
  • Eu não fico exausto 🔥🤯
  • Lançamentos menos apressados 💨
  • Documentos melhores📚
  • Suporte melhor e mais rápido com problemas 🆘

📧 Envie-me um e-mail para jokob@duck.com se quiser entrar em contato ou se devo adicionar outras plataformas de patrocínio.
", diff --git a/front/php/templates/language/ru_ru.json b/front/php/templates/language/ru_ru.json index f8044092..6634a160 100755 --- a/front/php/templates/language/ru_ru.json +++ b/front/php/templates/language/ru_ru.json @@ -242,6 +242,7 @@ "Device_Tablelenght": "Показать _MENU_ записей", "Device_Tablelenght_all": "Все", "Device_Title": "Устройства", + "Devices_Filters": "", "Donations_Others": "Другие", "Donations_Platforms": "Спонсорские платформы", "Donations_Text": "Привет 👋!
Спасибо, что нажали на этот пункт меню 😅

Я пытаюсь собрать пожертвования, чтобы сделать ваше программное обеспечение лучше. Кроме того, это поможет мне не перегореть, и я смогу дольше поддерживать это приложение. Любое небольшое спонсорство (периодическое или нет) вызывает у меня желание приложить больше усилий к этому приложению.
Мне бы хотелось сократить свою рабочую неделю и в оставшееся время полностью сосредоточиться на NetAlertX. Вы получите больше функциональности, более усовершенствованное приложение и меньше ошибок.

Спасибо за прочтение – буду благодарен за любую поддержку❤🙏

TL;DR: Поддержав меня, вы получаете:

  • Регулярные обновления для обеспечения безопасности ваших данных и семьи 🔄
  • Меньше ошибок 🐛🔫
  • Лучшую функциональность➕
  • Я не выгораю 🔥🤯
  • Меньше поспешных релизов 💨
  • Лучшая документация📚
  • Быстрее и лучше поддержка по вопросам 🆘

📧Напишите мне на jokob@duck.com если вы хотите связаться или если следует добавить другие спонсорские платформы.
", diff --git a/front/php/templates/language/tr_tr.json b/front/php/templates/language/tr_tr.json index ce7d6128..222229a5 100755 --- a/front/php/templates/language/tr_tr.json +++ b/front/php/templates/language/tr_tr.json @@ -242,6 +242,7 @@ "Device_Tablelenght": "", "Device_Tablelenght_all": "", "Device_Title": "Cihazlar", + "Devices_Filters": "", "Donations_Others": "Diğerleri", "Donations_Platforms": "", "Donations_Text": "", diff --git a/front/php/templates/language/uk_ua.json b/front/php/templates/language/uk_ua.json index c26f52fc..380c4f28 100755 --- a/front/php/templates/language/uk_ua.json +++ b/front/php/templates/language/uk_ua.json @@ -242,6 +242,7 @@ "Device_Tablelenght": "Показати записи _МЕНЮ_", "Device_Tablelenght_all": "все", "Device_Title": "Пристрої", + "Devices_Filters": "", "Donations_Others": "інші", "Donations_Platforms": "Спонсорські платформи", "Donations_Text": "Привіт 👋!
Дякуємо, що натиснули цей пункт меню 😅

Я намагаюся зібрати пожертви, щоб зробити ваше програмне забезпечення кращим. Крім того, це допоможе мені не згоріти, тому я можу підтримувати цю програму довше. Будь-яке невелике (постійне чи ні) спонсорство спонукає мене докласти більше зусиль до цієї програми.
Я хотів би скоротити свій робочий тиждень і в час, що залишився, повністю зосередитися на NetAlertX. Ви отримаєте більше функціональності, досконаліший додаток і менше помилок.

Дякую, що прочитали – я вдячний за будь-яку підтримку ❤🙏

TL;DR: Підтримуючи мене, ви отримуєте:

  • Регулярні оновлення для захисту ваших даних і родини 🔄
  • Менше помилок 🐛🔫
  • Краще та більше функціональність➕
  • Я не згорів 🔥🤯
  • Менш поспішних випусків 💨
  • Кращі документи📚
  • Швидша та краща підтримка із проблемами 🆘

📧Напишіть мені електронною поштою на jokob@duck.com, якщо ви хочете зв’язатися з нами або якщо я маю додати інші платформи спонсорства.
", @@ -751,4 +752,4 @@ "settings_update_item_warning": "Оновіть значення нижче. Слідкуйте за попереднім форматом. Перевірка не виконана.", "test_event_icon": "fa-vial-circle- check", "test_event_tooltip": "Перш ніж перевіряти налаштування, збережіть зміни." -} +} \ No newline at end of file diff --git a/front/php/templates/language/zh_cn.json b/front/php/templates/language/zh_cn.json index cf12068d..b910f7e7 100755 --- a/front/php/templates/language/zh_cn.json +++ b/front/php/templates/language/zh_cn.json @@ -242,6 +242,7 @@ "Device_Tablelenght": "显示 _MENU_ 页", "Device_Tablelenght_all": "所有", "Device_Title": "设备", + "Devices_Filters": "", "Donations_Others": "其他", "Donations_Platforms": "赞助平台", "Donations_Text": "嘿👋!
感谢您点击此菜单项😅

我正在尝试收集一些捐款来为您制作更好的软件。此外,这将有助于我避免精疲力竭,这样我就可以更长时间地支持这个应用程序。任何小额(无论是否经常性)赞助都会让我想在这个应用程序上投入更多精力。
我希望缩短我的工作周,并在剩余的时间里完全专注于 NetAlertX。您将获得更多功能、更精致的应用程序和更少的错误。

感谢阅读 - 我感谢任何支持 ❤🙏

TL;DR:通过支持我,您将获得:

  • 定期更新以确保您的数据和家人安全🔄
  • 更少的错误🐛🔫
  • 更好、更多的功能➕
  • 我不会精疲力竭🔥🤯
  • 更不仓促的发布💨
  • 更好的文档📚
  • 更快、更好地解决问题🆘

📧如果您想联系我或者我应该添加其他赞助平台,请给我发电子邮件至jokob@duck.com
", diff --git a/front/plugins/ui_settings/config.json b/front/plugins/ui_settings/config.json index a49f9d79..052e6449 100755 --- a/front/plugins/ui_settings/config.json +++ b/front/plugins/ui_settings/config.json @@ -393,6 +393,82 @@ } ] }, + { + "function": "columns_filters", + "type": { + "dataType": "array", + "elements": [ + { + "elementType": "select", + "elementOptions": [{ "multiple": "true", "ordeable": "true" }], + "transformers": ["getString"] + }, + { + "elementType": "button", + "elementOptions": [ + { "sourceSuffixes": [] }, + { "separator": "" }, + { "cssClasses": "col-xs-4" }, + { "onClick": "selectAll(this)" }, + { "getStringKey": "Gen_Add_All" } + ], + "transformers": [] + }, + { + "elementType": "button", + "elementOptions": [ + { "sourceSuffixes": [] }, + { "separator": "" }, + { "cssClasses": "col-xs-4" }, + { "onClick": "unselectAll(this)" }, + { "getStringKey": "Gen_Remove_All" } + ], + "transformers": [] + }, + { + "elementType": "button", + "elementOptions": [ + { "sourceSuffixes": [] }, + { "separator": "" }, + { "cssClasses": "col-xs-4" }, + { "onClick": "selectChange(this)" }, + { "getStringKey": "Gen_Change" } + ], + "transformers": [] + } + ] + }, + "maxLength": 50, + "default_value": [ + "Device_TableHead_Type", + "Device_TableHead_SyncHubNodeName", + "Device_TableHead_SourcePlugin" + ], + "options": [ + "Device_TableHead_Owner", + "Device_TableHead_Type", + "Device_TableHead_Group", + "Device_TableHead_Location", + "Device_TableHead_Vendor", + "Device_TableHead_SyncHubNodeName", + "Device_TableHead_NetworkSite", + "Device_TableHead_SSID", + "Device_TableHead_SourcePlugin" + ], + "localized": ["name", "description"], + "name": [ + { + "language_code": "en_us", + "string": "Column Filters" + } + ], + "description": [ + { + "language_code": "en_us", + "string": "Which column filters should be displayed in the main Devices screen." + } + ] + }, { "function": "shown_cards", "type": { diff --git a/server/api.py b/server/api.py index 35bb31fc..fdb61683 100755 --- a/server/api.py +++ b/server/api.py @@ -5,7 +5,7 @@ import datetime # Register NetAlertX modules import conf -from const import (apiPath, sql_appevents, sql_devices_all, sql_events_pending_alert, sql_settings, sql_plugins_events, sql_plugins_history, sql_plugins_objects,sql_language_strings, sql_notifications_all, sql_online_history, sql_devices_tiles) +from const import (apiPath, sql_appevents, sql_devices_all, sql_events_pending_alert, sql_settings, sql_plugins_events, sql_plugins_history, sql_plugins_objects,sql_language_strings, sql_notifications_all, sql_online_history, sql_devices_tiles, sql_devices_filters) from logger import mylog from helper import write_file, get_setting_value, timeNowTZ from app_state import updateState @@ -50,6 +50,7 @@ def update_api(db, all_plugins, forceUpdate, updateOnlyDataSources=[], is_ad_hoc ["notifications", sql_notifications_all], ["online_history", sql_online_history], ["devices_tiles", sql_devices_tiles], + ["devices_filters", sql_devices_filters], ["custom_endpoint", conf.API_CUSTOM_SQL], ] diff --git a/server/const.py b/server/const.py index 7625a3ab..9b4058b1 100755 --- a/server/const.py +++ b/server/const.py @@ -105,6 +105,35 @@ sql_devices_tiles = """ (SELECT COUNT(*) FROM MyDevicesFilter) AS my_devices FROM Statuses; """ +sql_devices_filters = """ + SELECT DISTINCT 'devSite' AS columnName, devSite AS columnValue + FROM Devices WHERE devSite NOT IN ('', 'null') AND devSite IS NOT NULL + UNION + SELECT DISTINCT 'devSourcePlugin' AS columnName, devSourcePlugin AS columnValue + FROM Devices WHERE devSourcePlugin NOT IN ('', 'null') AND devSourcePlugin IS NOT NULL + UNION + SELECT DISTINCT 'devOwner' AS columnName, devOwner AS columnValue + FROM Devices WHERE devOwner NOT IN ('', 'null') AND devOwner IS NOT NULL + UNION + SELECT DISTINCT 'devType' AS columnName, devType AS columnValue + FROM Devices WHERE devType NOT IN ('', 'null') AND devType IS NOT NULL + UNION + SELECT DISTINCT 'devGroup' AS columnName, devGroup AS columnValue + FROM Devices WHERE devGroup NOT IN ('', 'null') AND devGroup IS NOT NULL + UNION + SELECT DISTINCT 'devLocation' AS columnName, devLocation AS columnValue + FROM Devices WHERE devLocation NOT IN ('', 'null') AND devLocation IS NOT NULL + UNION + SELECT DISTINCT 'devVendor' AS columnName, devVendor AS columnValue + FROM Devices WHERE devVendor NOT IN ('', 'null') AND devVendor IS NOT NULL + UNION + SELECT DISTINCT 'devSyncHubNode' AS columnName, devSyncHubNode AS columnValue + FROM Devices WHERE devSyncHubNode NOT IN ('', 'null') AND devSyncHubNode IS NOT NULL + UNION + SELECT DISTINCT 'devSSID' AS columnName, devSSID AS columnValue + FROM Devices WHERE devSSID NOT IN ('', 'null') AND devSSID IS NOT NULL + ORDER BY columnName; + """ sql_devices_stats = """SELECT Online_Devices as online, Down_Devices as down, All_Devices as 'all', Archived_Devices as archived, (select count(*) from Devices a where devIsNew = 1 ) as new, (select count(*) from Devices a where devName = '(unknown)' or devName = '(name not found)' ) as unknown diff --git a/server/graphql_server/graphql_schema.py b/server/graphql_server/graphql_schema.py index e5a88ffd..5437d0a4 100755 --- a/server/graphql_server/graphql_schema.py +++ b/server/graphql_server/graphql_schema.py @@ -20,6 +20,10 @@ class SortOptionsInput(InputObjectType): field = String() order = String() +class FilterOptionsInput(InputObjectType): + filterColumn = String() + filterValue = String() + class PageQueryOptionsInput(InputObjectType): page = Int() @@ -27,6 +31,7 @@ class PageQueryOptionsInput(InputObjectType): sort = List(SortOptionsInput) search = String() status = String() + filters = List(FilterOptionsInput) # Device ObjectType @@ -162,7 +167,14 @@ class Query(ObjectType): elif status == "offline": devices_data = [device for device in devices_data if device["devPresentLastScan"] == 0] - + # additional filters + if options.filters: + for filter in options.filters: + if filter.filterColumn and filter.filterValue: + devices_data = [ + device for device in devices_data + if str(device.get(filter.filterColumn, "")).lower() == str(filter.filterValue).lower() + ] # Filter data if a search term is provided if options.search: