Skip to content

Commit

Permalink
feat: add option to list disabled subscriptions at the bottom
Browse files Browse the repository at this point in the history
  • Loading branch information
Miguel Ribeiro committed Aug 5, 2024
1 parent 1767709 commit 6bbb754
Show file tree
Hide file tree
Showing 25 changed files with 181 additions and 40 deletions.
34 changes: 34 additions & 0 deletions endpoints/settings/disabled_to_bottom.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
<?php
require_once '../../includes/connect_endpoint.php';

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
die(json_encode([
"success" => false,
"message" => translate('session_expired', $i18n)
]));
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
$postData = file_get_contents("php://input");
$data = json_decode($postData, true);

$disabled_to_bottom = $data['value'];

$stmt = $db->prepare('UPDATE settings SET disabled_to_bottom = :disabled_to_bottom WHERE user_id = :userId');
$stmt->bindParam(':disabled_to_bottom', $disabled_to_bottom, SQLITE3_INTEGER);
$stmt->bindParam(':userId', $userId, SQLITE3_INTEGER);

if ($stmt->execute()) {
die(json_encode([
"success" => true,
"message" => translate("success", $i18n)
]));
} else {
die(json_encode([
"success" => false,
"message" => translate("error", $i18n)
]));
}
}

?>
74 changes: 53 additions & 21 deletions endpoints/subscriptions/get.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,24 +19,11 @@
}

if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {


$sort = "next_payment";
$sortOrder = $sort;
$order = "ASC";
$sql = "SELECT * FROM subscriptions ORDER BY next_payment ASC, inactive ASC";
if (isset($_COOKIE['sortOrder']) && $_COOKIE['sortOrder'] != "") {
$sort = $_COOKIE['sortOrder'];
$sortOrder = $sort;
$allowedSortCriteria = ['name', 'id', 'next_payment', 'price', 'payer_user_id', 'category_id', 'payment_method_id', 'inactive', 'alphanumeric'];
if ($sort == "price" || $sort == "id") {
$order = "DESC";
}
if ($sort == "alphanumeric") {
$sort = "name";
}
if (!in_array($sort, $allowedSortCriteria)) {
$sort = "next_payment";
}
}

$params = array();
$sql = "SELECT * FROM subscriptions WHERE user_id = :userId";
Expand All @@ -61,12 +48,41 @@
$params[':inactive'] = $_GET['state'];
}

$sql .= " ORDER BY LOWER($sort) $order";
if ($sort != "next_payment") {
$sql .= ", next_payment ASC";
}
if ($sort != "state") {
$sql .= ", inactive ASC";
if (isset($_COOKIE['sortOrder']) && $_COOKIE['sortOrder'] != "") {
$sort = $_COOKIE['sortOrder'];
$allowedSortCriteria = ['name', 'id', 'next_payment', 'price', 'payer_user_id', 'category_id', 'payment_method_id', 'inactive', 'alphanumeric'];
$order = ($sort == "price" || $sort == "id") ? "DESC" : "ASC";

if ($sort == "alphanumeric") {
$sort = "name";
}

if (!in_array($sort, $allowedSortCriteria)) {
$sort = "next_payment";
}

$orderByClauses = [];

if ($settings['disabledToBottom'] === 'true') {
if (in_array($sort, ["payer_user_id", "category_id", "payment_method_id"])) {
$orderByClauses[] = "$sort $order";
$orderByClauses[] = "inactive ASC";
} else {
$orderByClauses[] = "inactive ASC";
$orderByClauses[] = "$sort $order";
}
} else {
$orderByClauses[] = "$sort $order";
if ($sort != "inactive") {
$orderByClauses[] = "inactive ASC";
}
}

if ($sort != "next_payment") {
$orderByClauses[] = "next_payment ASC";
}

$sql .= " ORDER BY " . implode(", ", $orderByClauses);
}

$stmt = $db->prepare($sql);
Expand Down Expand Up @@ -123,6 +139,22 @@
usort($print, function ($a, $b) {
return strnatcmp(strtolower($a['name']), strtolower($b['name']));
});
if ($settings['disabledToBottom'] === 'true') {
usort($print, function ($a, $b) {
return $a['inactive'] - $b['inactive'];
});
}
}

if ($sort === "price") {
usort($subscriptions, function ($a, $b) {
return $a['price'] < $b['price'] ? 1 : -1;
});
if ($settings['disabledToBottom'] === 'true') {
usort($print, function ($a, $b) {
return $a['inactive'] - $b['inactive'];
});
}
}

if (isset($print)) {
Expand Down
1 change: 1 addition & 0 deletions includes/getsettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
$settings['convertCurrency'] = $settings['convert_currency'] ? 'true': 'false';
$settings['removeBackground'] = $settings['remove_background'] ? 'true': 'false';
$settings['hideDisabledSubscriptions'] = $settings['hide_disabled'] ? 'true': 'false';
$settings['disabledToBottom'] = $settings['disabled_to_bottom'] ? 'true': 'false';
}

$query = "SELECT * FROM custom_colors WHERE user_id = :userId";
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/de.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "Berechne und zeige monatlichen Preis für alle Abonnements an",
"convert_prices" => "Preise immer in meine Hauptwährung umrechnen und darin anzeigen (langsamer)",
"hide_disabled_subscriptions" => "Deaktivierte Abonnements verstecken",
"show_disabled_subscriptions_at_the_bottom" => "Deaktivierte Abonnements am Ende anzeigen",
"experimental_settings" => "Experimentelle Einstellungen",
"remove_background" => "Versuchen den Hintergrund von Logos aus der Bildersuche zu entfernen (experimentell)",
"experimental_info" => "Experimentelle Einstellungen funktionieren möglicherweise nicht perfekt.",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/el.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "Υπολογισμός και εμφάνιση της μηνιαίας τιμής για όλες τις συνδρομές",
"convert_prices" => "Πάντα να μετατρέπει και να εμφανίζει τις τιμές στο κύριο νόμισμά μου (πιο αργό)",
"hide_disabled_subscriptions" => "Απόκρυψη απενεργοποιημένων συνδρομών",
"show_disabled_subscriptions_at_the_bottom" => "Εμφάνιση απενεργοποιημένων συνδρομών στο τέλος",
"experimental_settings" => "Πειραματικές ρυθμίσεις",
"remove_background" => "Προσπάθεια αφαίρεσης του φόντου των λογότυπων από την αναζήτηση εικόνας (πειραματικά)",
"experimental_info" => "Οι πειραματικές ρυθμίσεις πιθανότατα δεν θα λειτουργούν τέλεια.",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/en.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "Calculate and show monthly price for all subscriptions",
"convert_prices" => "Always convert and show prices on my main currency (slower)",
"hide_disabled_subscriptions" => "Hide disabled subscriptions",
"show_disabled_subscriptions_at_the_bottom" => "Show disabled subscriptions at the bottom",
"experimental_settings" => "Experimental Settings",
"remove_background" => "Attempt to remove background of logos from image search (experimental)",
"experimental_info" => "Experimental settings will probably not work perfectly.",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/fr.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "Calculer et afficher le prix mensuel pour tous les abonnements",
"convert_prices" => "Convertir toujours et afficher les prix dans ma devise principale (plus lent)",
"hide_disabled_subscriptions" => "Masquer les abonnements désactivés",
"show_disabled_subscriptions_at_the_bottom" => "Afficher les abonnements désactivés en bas",
"experimental_settings" => "Paramètres expérimentaux",
"remove_background" => "Tenter de supprimer l'arrière-plan des logos de la recherche d'images (expérimental)",
"experimental_info" => "Les paramètres expérimentaux ne fonctionneront probablement pas parfaitement.",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/it.php
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@
'calculate_monthly_price' => 'Calcola e mostra il prezzo mensile per tutti gli abbonamenti',
'convert_prices' => 'Converti sempre e mostra i prezzi nella mia valuta principale (più lento)',
"hide_disabled_subscriptions" => 'Nascondi gli abbonamenti disattivati',
"show_disabled_subscriptions_at_the_bottom" => 'Mostra gli abbonamenti disattivati in fondo',
'experimental_settings' => 'Impostazioni sperimentali',
'remove_background' => 'Prova a rimuovere lo sfondo dei loghi dalla ricerca delle immagini (sperimentale)',
'experimental_info' => 'Le impostazioni sperimentali potrebbero non funzioneranno perfettamente.',
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/jp.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "すべての定期購入の月額料金を計算して表示する",
"convert_prices" => "常にメイン通貨で価格を換算して表示する (遅い)",
"hide_disabled_subscriptions" => "無効な定期購入を非表示にする",
"show_disabled_subscriptions_at_the_bottom" => "無効な定期購入を一番下に表示する",
"experimental_settings" => "実験的な設定",
"remove_background" => "画像検索からロゴの背景を削除する (実験)",
"experimental_info" => "実験的な設定は、おそらく完全には機能しません。",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/ko.php
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@
"calculate_monthly_price" => "모든 구독에 대한 월별 요금을 계산하고 표시",
"convert_prices" => "항상 기본 통화로 가격을 환산하고 표시 (느림)",
"hide_disabled_subscriptions" => "비활성화된 구독 숨기기",
"show_disabled_subscriptions_at_the_bottom" => "비활성화된 구독을 하단에 표시",
"experimental_settings" => "실험적 설정",
"remove_background" => "로고 이미지 검색에서 배경 삭제 (실험적)",
"experimental_info" => "실험적 설정은 제대로 작동하지 않을 수 있습니다.",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/pl.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "Oblicz i pokaż miesięczną cenę wszystkich subskrypcji",
"convert_prices" => "Zawsze przeliczaj i pokazuj ceny w mojej głównej walucie (wolniej)",
"hide_disabled_subscriptions" => "Ukryj wyłączone subskrypcje",
"show_disabled_subscriptions_at_the_bottom" => "Pokaż wyłączone subskrypcje na dole",
"experimental_settings" => "Ustawienia eksperymentalne",
"remove_background" => "Próba usunięcia tła logo z wyszukiwania obrazów (eksperymentalnie)",
"experimental_info" => "Ustawienia eksperymentalne prawdopodobnie nie będą działać idealnie.",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/pt.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "Calcular e mostrar preço mensal para todas as subscrições",
"convert_prices" => "Converter e mostrar todas as subscrições na moeda principal (mais lento)",
"hide_disabled_subscriptions" => "Esconder subscrições desactivadas",
"show_disabled_subscriptions_at_the_bottom" => "Mostrar subscrições desactivadas no fundo da lista",
"experimental_settings" => "Definições Experimentais",
"remove_background" => "Tentar remover o fundo dos logos na pesquisa de imagem (experimental)",
"experimental_info" => "Definições experimentais provavelmente não funcionarão correctamente.",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/pt_br.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "Calcular e exibir o custo mensal para todas as assinaturas",
"convert_prices" => "Sempre converter e exibir preços na moeda principal (mais lento)",
"hide_disabled_subscriptions" => "Ocultar assinaturas desativadas",
"show_disabled_subscriptions_at_the_bottom" => "Mostre as assinaturas desativadas no final da lista",
"experimental_settings" => "Configurações experimentais",
"remove_background" => "Tentar remover o fundo de logos na pesquisa de imagem",
"experimental_info" => "As configurações experimentais provavelmente não funcionarão corretamente",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/ru.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "Рассчитать и показать ежемесячную цену для всех подписок",
"convert_prices" => "Всегда конвертировать и показывать цены в моей основной валюте (медленнее)",
"hide_disabled_subscriptions" => "Скрыть отключенные подписки",
"show_disabled_subscriptions_at_the_bottom" => "Показать отключенные подписки внизу списка",
"experimental_settings" => "Экспериментальные настройки",
"remove_background" => "Попытка удалить фон логотипов из поиска изображений (экспериментально).",
"experimental_info" => "Экспериментальные настройки, вероятно, не будут работать идеально.",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/sl.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "Izračunaj in prikaži mesečno ceno za vse naročnine",
"convert_prices" => "Vedno pretvori in prikaži cene v moji glavni valuti (počasneje)",
"hide_disabled_subscriptions" => "Skrij onemogočene naročnine",
"show_disabled_subscriptions_at_the_bottom" => "Prikaži onemogočene naročnine na dnu seznama",
"experimental_settings" => "Eksperimentalne nastavitve",
"remove_background" => "Poskusi odstraniti ozadje logotipov iz iskanja slik (eksperimentalno)",
"experimental_info" => "Poskusne nastavitve verjetno ne bodo popolnoma delovale.",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/sr.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "Израчунајте и прикажите месечну цену за све претплате",
"convert_prices" => "Увек конвертујте и прикажите цене на мојој главној валути (спорије)",
"hide_disabled_subscriptions" => "Сакриј онемогућене претплате",
"show_disabled_subscriptions_at_the_bottom" => "Прикажи онемогућене претплате на дну",
"experimental_settings" => "Експериментална подешавања",
"remove_background" => "Покушајте уклонити позадину логотипа са слика претраге (експериментално)",
"experimental_info" => "Експериментална подешавања вероватно неће радити савршено.",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/sr_lat.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "Izračunaj i prikaži mesečnu cenu za sve pretplate",
"convert_prices" => "Uvek konvertuj i prikaži cene u mojoj glavnoj valuti (sporije)",
"hide_disabled_subscriptions" => "Sakrij onemogućene pretplate",
"show_disabled_subscriptions_at_the_bottom" => "Prikaži onemogućene pretplate na dnu",
"experimental_settings" => "Eksperimentalna podešavanja",
"remove_background" => "Pokušajte ukloniti pozadinu logotipa sa pretrage slika (eksperimentalno)",
"experimental_info" => "Eksperimentalna podešavanja verovatno neće savršeno funkcionisati.",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/tr.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "Tüm aboneliklerin aylık fiyatını hesaplayın ve gösterin",
"convert_prices" => "Fiyatları her zaman ana para birimimde dönüştürün ve gösterin (daha yavaş)",
"hide_disabled_subscriptions" => "Devre dışı bırakılan abonelikleri gizle",
"show_disabled_subscriptions_at_the_bottom" => "Devre dışı bırakılan abonelikleri altta göster",
"experimental_settings" => "Deneysel Ayarlar",
"remove_background" => "Görsel aramadan logoların arka planını kaldırmayı deneyin (deneysel)",
"experimental_info" => "Deneysel ayarlar muhtemelen mükemmel çalışmayacak.",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/zh_cn.php
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@
"calculate_monthly_price" => "计算并显示所有订阅的月价格",
"convert_prices" => "始终按我的主要货币转换和显示价格(较慢)",
"hide_disabled_subscriptions" => "隐藏已停用的订阅",
"show_disabled_subscriptions_at_the_bottom" => "在订阅列表底部显示已停用的订阅",
"experimental_settings" => "实验性设置",
"remove_background" => "尝试从图片搜索中移除标志的背景(实验性)",
"experimental_info" => "实验性设置,可能存在问题。",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/zh_tw.php
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@
"calculate_monthly_price" => "計算並顯示所有訂閱的每月價格",
"convert_prices" => "始終按照我的主要貨幣單位轉換和顯示價格(較慢)",
"hide_disabled_subscriptions" => "隱藏已停用的訂閱",
"show_disabled_subscriptions_at_the_bottom" => "將已停用的訂閱顯示在底部",
"experimental_settings" => "實驗性設定",
"remove_background" => "嘗試從圖片搜尋中移除圖示的背景顏色(實驗性)",
"experimental_info" => "實驗性設定,可能存在問題。",
Expand Down
6 changes: 0 additions & 6 deletions includes/list_subscriptions.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,6 @@ function getPriceConverted($price, $currency, $database) {
}

function printSubscriptions($subscriptions, $sort, $categories, $members, $i18n, $colorTheme, $imagePath) {
if ($sort === "price") {
usort($subscriptions, function($a, $b) {
return $a['price'] < $b['price'] ? 1 : -1;
});
}

$currentCategory = 0;
$currentPayerUserId = 0;
$currentPaymentMethodId = 0;
Expand Down
Loading

0 comments on commit 6bbb754

Please sign in to comment.