From fa46874ae38f0d3318ac78f1bbd9db5442a6ae20 Mon Sep 17 00:00:00 2001
From: Erik Thuning <boooink@gmail.com>
Date: Wed, 11 Jan 2023 10:43:57 +0100
Subject: [PATCH] Mail notifications get pushed forward in time when a new loan
 is created if there is a pending notification. This way the user can add
 multiple loans over time without the notification getting sent prematurely.

---
 include/Loan.php     | 12 ++++++++++--
 pending_receipts.sql |  9 ---------
 2 files changed, 10 insertions(+), 11 deletions(-)
 delete mode 100644 pending_receipts.sql

diff --git a/include/Loan.php b/include/Loan.php
index 89b8465..26254ed 100644
--- a/include/Loan.php
+++ b/include/Loan.php
@@ -42,16 +42,24 @@ class Loan extends Event {
 
     protected function queue_receipt($user) {
         $now = time();
+        $sendtime = $now + 3600;
         $pending = prepare('select * from `pending_receipt` where `user` = ?
                                 and `since_time` < ? and `send_time` > ?');
         bind($pending, 'iii', $user->get_id(), $now, $now);
         execute($pending);
-        if(result_single($pending) === null) {
+        $result = result_single($pending);
+        if($result === null) {
             $add = prepare('insert into `pending_receipt`
                                 (`user`, `since_time`, `send_time`)
                                 values(?, ?, ?)');
-            bind($add, 'iii', $user->get_id(), $now, $now + 3600);
+            bind($add, 'iii', $user->get_id(), $now, $sendtime);
             execute($add);
+        } else {
+            $update = prepare('update `pending_receipt` set `send_time` = ?
+                               where `user` = ? and `since_time` < ?
+                                   and `send_time` > ?');
+            bind($update, 'iiii', $sendtime, $user->get_id(), $now, $now);
+            execute($update);
         }
     }
 
diff --git a/pending_receipts.sql b/pending_receipts.sql
deleted file mode 100644
index 550da5b..0000000
--- a/pending_receipts.sql
+++ /dev/null
@@ -1,9 +0,0 @@
-create table `pending_receipt` (
-  `user` bigint(20) not null,
-  primary key (`user`),
-  constraint `pr_f_user`
-    foreign key(`user`) references `user`(`id`),
-  `send_time` bigint(20) not null,
-  `since_time` bigint(20) not null
-) character set utf8mb4,
-  collate utf8mb4_unicode_ci;