Skip to content

Commit

Permalink
feat: add email for notifications to household members
Browse files Browse the repository at this point in the history
  • Loading branch information
ellite authored Feb 25, 2024
1 parent f8defb6 commit 26363dd
Show file tree
Hide file tree
Showing 16 changed files with 93 additions and 39 deletions.
82 changes: 49 additions & 33 deletions endpoints/cronjobs/sendnotifications.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,58 +30,74 @@
$currencies[$currencyId] = $row;
}

$querySubscriptions = "SELECT * FROM subscriptions WHERE notify = 1 AND inactive = 0";
$resultSubscriptions = $db->query($querySubscriptions);
$stmt = $db->prepare('SELECT * FROM subscriptions WHERE notify = :notify AND inactive = :inactive ORDER BY payer_user_id ASC');
$stmt->bindValue(':notify', 1, SQLITE3_INTEGER);
$stmt->bindValue(':inactive', 0, SQLITE3_INTEGER);
$resultSubscriptions = $stmt->execute();

$notify = []; $i = 0;
$currentDate = new DateTime('now');
while ($rowSubscription = $resultSubscriptions->fetchArray(SQLITE3_ASSOC)) {
$nextPaymentDate = new DateTime($rowSubscription['next_payment']);
$difference = $currentDate->diff($nextPaymentDate)->days + 1;
if ($difference === $days) {
$notify[$i]['name'] = $rowSubscription['name'];
$notify[$i]['price'] = $rowSubscription['price'] . $currencies[$rowSubscription['currency_id']]['symbol'];
$notify[$rowSubscription['payer_user_id']][$i]['name'] = $rowSubscription['name'];
$notify[$rowSubscription['payer_user_id']][$i]['price'] = $rowSubscription['price'] . $currencies[$rowSubscription['currency_id']]['symbol'];
$i++;
}
}

if (!empty($notify)) {

require $webPath . 'libs/PHPMailer/PHPMailer.php';
require $webPath . 'libs/PHPMailer/SMTP.php';
require $webPath . 'libs/PHPMailer/Exception.php';

$dayText = $days == 1 ? "tomorrow" : "in " . $days . " days";
$message = "The following subscriptions are up for renewal " . $dayText . ":\n";
foreach ($notify as $subscription) {
$message .= $subscription['name'] . " for " . $subscription['price'] . "\n";
}

$mail = new PHPMailer(true);
$mail->CharSet="UTF-8";
$mail->isSMTP();
$stmt = $db->prepare('SELECT * FROM user WHERE id = :id');
$stmt->bindValue(':id', 1, SQLITE3_INTEGER);
$result = $stmt->execute();
$defaultUser = $result->fetchArray(SQLITE3_ASSOC);
$defaultEmail = $defaultUser['email'];
$defaultName = $defaultUser['username'];

$mail->Host = $smtpAddress;
$mail->SMTPAuth = true;
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
$mail->SMTPSecure = 'tls';
$mail->Port = $smtpPort;
foreach ($notify as $userId => $perUser) {
$dayText = $days == 1 ? "tomorrow" : "in " . $days . " days";
$message = "The following subscriptions are up for renewal " . $dayText . ":\n";

$getUser = "SELECT * FROM user WHERE id = 1";
$user = $db->querySingle($getUser, true);
$email = $user['email'];
$name = $user['username'];

$mail->setFrom($fromEmail, 'Wallos App');
$mail->addAddress($email, $name);

$mail->Subject = 'Wallos Notification';
$mail->Body = $message;
foreach ($perUser as $subscription) {
$message .= $subscription['name'] . " for " . $subscription['price'] . "\n";
}

$mail = new PHPMailer(true);
$mail->CharSet="UTF-8";
$mail->isSMTP();

$mail->Host = $smtpAddress;
$mail->SMTPAuth = true;
$mail->Username = $smtpUsername;
$mail->Password = $smtpPassword;
$mail->SMTPSecure = 'tls';
$mail->Port = $smtpPort;

$stmt = $db->prepare('SELECT * FROM household WHERE id = :userId');
$stmt->bindValue(':userId', $userId, SQLITE3_INTEGER);
$result = $stmt->execute();
$user = $result->fetchArray(SQLITE3_ASSOC);

if ($mail->send()) {
echo "Notifications sent";
} else {
echo "Error sending notifications: " . $mail->ErrorInfo;
$email = !empty($user['email']) ? $user['email'] : $defaultEmail;
$name = !empty($user['name']) ? $user['name'] : $defaultName;

$mail->setFrom($fromEmail, 'Wallos App');
$mail->addAddress($email, $name);

$mail->Subject = 'Wallos Notification';
$mail->Body = $message;

if ($mail->send()) {
echo "Notifications sent";
} else {
echo "Error sending notifications: " . $mail->ErrorInfo;
}
}
} else {
echo "Nothing to notify.";
Expand Down
5 changes: 4 additions & 1 deletion endpoints/household/household.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,12 @@
if (isset($_GET['memberId']) && $_GET['memberId'] != "" && isset($_GET['name']) && $_GET['name'] != "") {
$memberId = $_GET['memberId'];
$name = validate($_GET['name']);
$sql = "UPDATE household SET name = :name WHERE id = :memberId";
$email = $_GET['email'] ? $_GET['email'] : "";
$email = validate($email);
$sql = "UPDATE household SET name = :name, email = :email WHERE id = :memberId";
$stmt = $db->prepare($sql);
$stmt->bindParam(':name', $name, SQLITE3_TEXT);
$stmt->bindParam(':email', $email, SQLITE3_TEXT);
$stmt->bindParam(':memberId', $memberId, SQLITE3_INTEGER);
$result = $stmt->execute();

Expand Down
1 change: 1 addition & 0 deletions includes/i18n/de.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"delete_member" => "Mitglied löschen",
"cant_delete_member" => "Hauptmitglied kann nicht gelöscht werden",
"cant_delete_member_in_use" => "Mitglied mit Abonnement kann nicht gelöscht werden",
'household_info' => "Über das E-Mail-Feld können die Haushaltsmitglieder über auslaufende Abonnements benachrichtigt werden.",
"notifications" => "Benachrichtigungen",
"enable_email_notifications" => "E-Mail Benachrichtigung aktivieren",
"notify_me" => "Benachrichtige mich",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/el.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"delete_member" => "Διαγραφή μέλους",
"cant_delete_member" => "Δεν ειναι δυνατή η διαγραφή του βασικού μέλους",
"cant_delete_member_in_use" => "Δεν ειναι δυνατή η διαγραφή μέλους που χρησιμοποιείται",
'household_info' => "Το πεδίο ηλεκτρονικού ταχυδρομείου επιτρέπει στα μέλη του νοικοκυριού να ειδοποιούνται για συνδρομές που πρόκειται να λήξουν.",
"notifications" => "Ειδοποιήσεις",
"enable_email_notifications" => "Ενεργοποίηση ειδοποιήσεων με email",
"notify_me" => "Ειδοποίησε με",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/en.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"delete_member" => "Delete Member",
"cant_delete_member" => "Can't delete main member",
"cant_delete_member_in_use" => "Can't delete member in use in subscription",
'household_info' => "Email field allows for household members to be notified of subscriptions about to expire.",
"notifications" => "Notifications",
"enable_email_notifications" => "Enable email notifications",
"notify_me" => "Notify me",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/es.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"delete_member" => "Eliminar Miembro",
"cant_delete_member" => "No se puede eliminar el miembro principal",
"cant_delete_member_in_use" => "No se puede eliminar el miembro en uso en la suscripción",
"household_info" => "El campo de correo electrónico permite notificar a los miembros del hogar las suscripciones que están a punto de caducar.",
"notifications" => "Notificaciones",
"enable_email_notifications" => "Habilitar notificaciones por correo electrónico",
"notify_me" => "Notificarme",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/fr.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"delete_member" => "Supprimer le membre",
"cant_delete_member" => "Impossible de supprimer le membre principal",
"cant_delete_member_in_use" => "Impossible de supprimer le membre utilisé dans l'abonnement",
"household_info" => "Le champ Courriel permet aux membres du ménage d'être informés des abonnements arrivant à expiration.",
"notifications" => "Notifications",
"enable_email_notifications" => "Activer les notifications par courriel",
"notify_me" => "Me prevenir",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/jp.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"delete_member" => "世帯員を削除",
"cant_delete_member" => "世帯主は削除出ません",
"cant_delete_member_in_use" => "定期購入を使用中の世帯員は削除できません",
"household_info" => "Eメールフィールドでは、世帯のメンバーに購読期限が近づいたことを通知することができます。",
"notifications" => "通知",
"enable_email_notifications" => "電子メール通知を有効にする",
"notify_me" => "通知",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/pt.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"delete_member" => "Apagar Membro",
"cant_delete_member" => "Não pode apagar o membro principal",
"cant_delete_member_in_use" => "Não pode apagar membro em uso em subscrição",
"household_info" => "O campo E-mail permite que os membros do agregado sejam notificados das subscrições que estão prestes a expirar.",
"notifications" => "Notificações",
"enable_email_notifications" => "Activar notificações por email",
"notify_me" => "Notificar-me",
Expand Down
1 change: 1 addition & 0 deletions includes/i18n/tr.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"delete_member" => "Üyeyi Sil",
"cant_delete_member" => "Ana üyeyi silemezsiniz",
"cant_delete_member_in_use" => "Abonelikte kullanılan üyeyi silemezsiniz",
"household_info" => "E-posta alanı, hane üyelerinin süresi dolmak üzere olan aboneliklerden haberdar edilmesini sağlar.",
"notifications" => "Bildirimler",
"enable_email_notifications" => "E-posta bildirimlerini etkinleştir",
"notify_me" => "Beni bilgilendir",
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 @@ -103,6 +103,7 @@
"delete_member" => "删除成员",
"cant_delete_member" => "不能删除主要成员",
"cant_delete_member_in_use" => "不能删除拥有订阅的成员",
"household_info" => "电子邮件字段允许通知家庭成员订阅即将过期。",
"notifications" => "通知",
"enable_email_notifications" => "启用电子邮件通知",
"notify_me" => "通知提前时间",
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 @@ -103,6 +103,7 @@
"delete_member" => "刪除成員",
"cant_delete_member" => "無法刪除主要成員",
"cant_delete_member_in_use" => "無法刪除擁有訂閱的成員",
"household_info" => "電子郵件欄位允許家庭成員收到訂閱即將到期的通知。",
"notifications" => "通知",
"enable_email_notifications" => "啟用電子信箱通知",
"notify_me" => "通知提前時間",
Expand Down
2 changes: 1 addition & 1 deletion includes/version.php
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
<?php
$version = "v1.6.0";
$version = "v1.7.0";
?>
11 changes: 11 additions & 0 deletions migrations/000009.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php
// This migration adds an "email" column to the members table.
// It allows the household member to receive notifications when their subscriptions are about to expire.

/** @noinspection PhpUndefinedVariableInspection */
$columnQuery = $db->query("SELECT * FROM pragma_table_info('household') where name='email'");
$columnRequired = $columnQuery->fetchArray(SQLITE3_ASSOC) === false;

if ($columnRequired) {
$db->exec('ALTER TABLE household ADD COLUMN email TEXT DEFAULT ""');
}
10 changes: 6 additions & 4 deletions scripts/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -113,12 +113,14 @@ function removeMember(memberId) {

function editMember(memberId) {
var saveButton = document.querySelector(`div[data-memberid="${memberId}"] button[name="save"]`);
var inputElement = document.querySelector(`div[data-memberid="${memberId}"] input[name="member"]`);
var memberNameElement = document.querySelector(`div[data-memberid="${memberId}"] input[name="member"]`);
var memberEmailElement = document.querySelector(`div[data-memberid="${memberId}"] input[name="email"]`);
saveButton.classList.add("disabled");
saveButton.disabled = true;
if (inputElement) {
var memberName = encodeURIComponent(inputElement.value);
var url = `endpoints/household/household.php?action=edit&memberId=${memberId}&name=${memberName}`;
if (memberNameElement) {
var memberName = encodeURIComponent(memberNameElement.value);
var memberEmail = memberEmailElement ? encodeURIComponent(memberEmailElement.value) : '';
var url = `endpoints/household/household.php?action=edit&memberId=${memberId}&name=${memberName}&email=${memberEmail}`;

fetch(url)
.then(response => {
Expand Down
12 changes: 12 additions & 0 deletions settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,13 @@
?>
<div class="form-group-inline" data-memberid="<?= $member['id'] ?>">
<input type="text" name="member" value="<?= $member['name'] ?>" placeholder="Member">
<?php
if ($member['id'] !== 1) {
?>
<input type="text" name="email" value="<?= $member['email'] ?? "" ?>" placeholder="<?= translate("email", $i18n) ?>">
<?php
}
?>
<button class="image-button medium" onClick="editMember(<?= $member['id'] ?>)" name="save">
<img src="images/siteicons/save.png" title="<?= translate('save_member', $i18n) ?>">
</button>
Expand All @@ -142,6 +149,11 @@
}
?>
</div>
<div class="settings-notes">
<p>
<i class="fa-solid fa-circle-info"></i> <?= translate('household_info', $i18n) ?></p>
<p>
</div>
<div class="buttons">
<input type="submit" value="<?= translate('add', $i18n) ?>" id="addMember" onClick="addMemberButton()"/>
</div>
Expand Down

0 comments on commit 26363dd

Please sign in to comment.