diff --git a/backend/app/Exceptions/AlertClosed.php b/backend/app/Exceptions/AlertClosed.php new file mode 100644 index 0000000..d98d135 --- /dev/null +++ b/backend/app/Exceptions/AlertClosed.php @@ -0,0 +1,10 @@ +closed) { + try { + Alerts::updateAlertResponse($id, $request->input('response')); + } catch(AlertClosed $e) { return response()->json([ 'status' => 'error', - 'message' => 'L\'allertamento è stata chiusa.', + 'message' => 'La chiamata è stata chiusa.', + ], 400); + } catch(AlertResponseAlreadySet $e) { + return response()->json([ + 'status' => 'error', + 'message' => 'Hai già risposto a questa chiamata.', ], 400); - } - - foreach($alert->crew as $crew) { - if($crew->user->id == auth()->user()->id) { - if($crew->accepted != null) { - return response()->json([ - 'status' => 'error', - 'message' => 'Hai già risposto a questo allertamento.', - ], 400); - } else { - $crew->accepted = $request->input('response', $crew->accepted); - $crew->save(); - } - } } } } diff --git a/backend/app/Utils/Alerts.php b/backend/app/Utils/Alerts.php new file mode 100644 index 0000000..21235dc --- /dev/null +++ b/backend/app/Utils/Alerts.php @@ -0,0 +1,68 @@ +closed) { + throw new AlertClosed(); + } + + if(is_null($userId)) { + $userId = auth()->user()->id; + } + + foreach($alert->crew as $crew) { + if($crew->user->id == $userId) { + if($crew->accepted != null) { + throw new AlertResponseAlreadySet(); + } else { + $crew->accepted = $response; + $crew->save(); + } + } + } + + $user = User::find($userId); + + //Add to logs + Logger::log( + "Risposta ad allertamento: ".($response ? "presente" : "non presente"), + $user, + $fromTelegram ? $user : null, + $fromTelegram ? "telegram" : "web" + ); + + //Send message to the user via Telegram to notify the response + $chatRows = TelegramBotLogins::join("users", "users.id", "=", "telegram_bot_logins.user") + ->select("users.id", "chat_id", "users.available") + ->where("users.id", $userId) + ->whereNotNull("chat_id") + ->get(); + + foreach ($chatRows as $chatRow) { + //Get chat by id + $chat = Telegraph::chat($chatRow["chat_id"]); + + $chat + ->message( + "La tua risposta all'allertamento è stata registrata.\n". + "Sei ".($response ? "presente" : "assente").".\n". + "Rimani in attesa di nuove istruzioni." + ) + ->send(); + } + + } +}