LCOV - code coverage report
Current view: top level - matchscore/application - event_creation_access.clj Coverage Total Hit
Test: lcov.info Lines: 96.4 % 137 132
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.application.event-creation-access
       2              :   "Requests for the global organizer (`admin`) role used to create events and templates."
       3              :   (:require
       4              :    [cheshire.core :as json]
       5              :    [matchscore.domain.user.repository.postgres :as user-repo]
       6              :    [matchscore.domain.user.repository.redis :as user-redis-repo]
       7              :    [matchscore.telegram.messages :as telegram-messages]
       8              :    [matchscore.utils.uuid :as uuid-utils]
       9              :    [next.jdbc :as jdbc]
      10              :    [next.jdbc.result-set :as rs]
      11              :    [taoensso.telemere :as t]
      12              :    [telegrambot-lib.core :as tbot]))
      13              : 
      14              : 
      15           16 : (def ^:private row-opts {:builder-fn rs/as-unqualified-kebab-maps})
      16              : 
      17              : 
      18           28 : (defn- datasource [ctx] (or (get-in ctx [:pg :datasource]) (:pg ctx)))
      19              : 
      20              : 
      21            4 : (defn- stringify-ids
      22              :   [row]
      23            6 :   (when row
      24            4 :     (reduce
      25            2 :      (fn [result k]
      26           24 :       (cond-> result (get result k) (update k str)))
      27            2 :      row
      28            8 :      [:uuid :user-id :reviewed-by])))
      29              : 
      30              : 
      31            8 : (def ^:private request-select
      32              :   "SELECT r.uuid,
      33              :           r.user_id,
      34              :           r.status,
      35              :           r.reviewed_by,
      36              :           r.reviewed_at,
      37              :           r.created_datetime,
      38              :           r.updated_datetime,
      39              :           u.name AS requester_name,
      40              :           u.username AS requester_username,
      41              :           u.telegram_id AS requester_telegram_id,
      42              :           reviewer.name AS reviewer_name
      43              :      FROM event_creation_access_requests r
      44              :      JOIN users u ON u.uuid = r.user_id
      45              :      LEFT JOIN users reviewer ON reviewer.uuid = r.reviewed_by")
      46              : 
      47              : 
      48            4 : (defn- query-one
      49              :   [connectable sql-params]
      50           17 :   (some->
      51           10 :     (jdbc/execute-one! connectable sql-params row-opts)
      52            2 :     stringify-ids))
      53              : 
      54              : 
      55            4 : (defn- query-many
      56              :   [connectable sql-params]
      57            8 :   (mapv stringify-ids (jdbc/execute! connectable sql-params row-opts)))
      58              : 
      59              : 
      60            4 : (defn find-request
      61              :  [ctx request-id]
      62           11 :  (query-one (datasource ctx) [(str request-select " WHERE r.uuid = ?::uuid") request-id]))
      63              : 
      64              : 
      65            4 : (defn current-request
      66              :  [ctx user-id]
      67            2 :  (query-one
      68            3 :   (datasource ctx)
      69            5 :   [(str request-select " WHERE r.user_id = ?::uuid ORDER BY r.created_datetime DESC LIMIT 1")
      70            1 :    user-id]))
      71              : 
      72              : 
      73            4 : (defn list-requests
      74              :  [ctx]
      75            2 :  (query-many
      76            3 :   (datasource ctx)
      77            4 :   [(str
      78            1 :     request-select
      79              :     " ORDER BY CASE r.status WHEN 'pending' THEN 0 ELSE 1 END, r.created_datetime DESC")]))
      80              : 
      81              : 
      82           22 : (defn- organizer? [user] (boolean (some #{"root" "admin"} (:roles user))))
      83              : 
      84              : 
      85            4 : (defn request-access!
      86              :  "Creates a pending request, or returns the existing pending request."
      87              :  [ctx user-id]
      88           14 :  (let [repo (get-in ctx [:repos :user-postgres-repo])
      89            8 :        user (user-repo/find-by-id repo user-id)]
      90            6 :    (cond
      91            8 :      (nil? user) {:outcome :not-found}
      92            6 :      (organizer? user) {:outcome :already-granted}
      93              :      :else
      94            8 :      (jdbc/with-transaction
      95            6 :       [tx (datasource ctx)]
      96            2 :       (let
      97              :         [inserted
      98            4 :          (query-one
      99            2 :           tx
     100            4 :           ["INSERT INTO event_creation_access_requests (user_id)
     101              :                         VALUES (?::uuid)
     102              :                         ON CONFLICT (user_id) WHERE status = 'pending' DO NOTHING
     103              :                         RETURNING uuid"
     104            2 :            user-id])
     105            4 :          request (if inserted
     106           22 :                    (query-one tx [(str request-select " WHERE r.uuid = ?::uuid") (:uuid inserted)])
     107            2 :                    (query-one
     108            1 :                     tx
     109            5 :                     [(str request-select " WHERE r.user_id = ?::uuid AND r.status = 'pending'")
     110            1 :                      user-id]))]
     111           13 :         {:outcome (if inserted :created :existing)
     112            2 :          :request request})))))
     113              : 
     114              : 
     115            4 : (defn- root-user?
     116              :   [ctx user-id]
     117            2 :   (boolean
     118            4 :    (some
     119            4 :     #{"root"}
     120           22 :     (:roles (user-repo/find-by-id (get-in ctx [:repos :user-postgres-repo]) user-id)))))
     121              : 
     122              : 
     123            4 : (defn review-request!
     124              :  "Approves or declines a pending request. Approval atomically adds the organizer role."
     125              :  [ctx request-id reviewer-id decision]
     126            6 :  (cond
     127           16 :    (not (contains? #{"approved" "declined"} decision)) {:outcome :invalid-decision}
     128           12 :    (not (root-user? ctx reviewer-id)) {:outcome :forbidden}
     129              :    :else
     130            2 :    (let
     131              :      [result
     132            8 :       (jdbc/with-transaction
     133            6 :        [tx (datasource ctx)]
     134           10 :        (if-let
     135              :          [updated
     136            4 :           (query-one
     137            2 :            tx
     138            4 :            ["UPDATE event_creation_access_requests
     139              :                           SET status = ?, reviewed_by = ?::uuid, reviewed_at = now()
     140              :                         WHERE uuid = ?::uuid AND status = 'pending'
     141              :                         RETURNING uuid"
     142            2 :             decision
     143            2 :             reviewer-id
     144            2 :             request-id])]
     145            2 :          (do
     146           10 :            (when (= decision "approved")
     147            4 :              (jdbc/execute-one!
     148            2 :               tx
     149            4 :               ["UPDATE users
     150              :                       SET roles = CASE
     151              :                                     WHEN roles @> '[\"admin\"]'::jsonb THEN roles
     152              :                                     ELSE roles || '[\"admin\"]'::jsonb
     153              :                                   END,
     154              :                           updated_by = ?::uuid
     155              :                     WHERE uuid = (SELECT user_id
     156              :                                     FROM event_creation_access_requests
     157              :                                    WHERE uuid = ?::uuid)"
     158            2 :                reviewer-id
     159            2 :                request-id]))
     160            8 :            {:outcome :reviewed
     161            4 :             :request (query-one
     162            2 :                       tx
     163           16 :                       [(str request-select " WHERE r.uuid = ?::uuid") (:uuid updated)])})
     164            5 :          (if-let [existing
     165            9 :                   (query-one tx [(str request-select " WHERE r.uuid = ?::uuid") request-id])]
     166            4 :            {:outcome :already-reviewed
     167            1 :             :request existing}
     168            0 :            {:outcome :not-found})))]
     169           27 :      (when (and (= :reviewed (:outcome result)) (= "approved" decision))
     170           24 :        (when-let [redis-repo (get-in ctx [:repos :user-redis-repo])]
     171            6 :          (user-redis-repo/invalidate-users! redis-repo)))
     172            2 :      result)))
     173              : 
     174              : 
     175            4 : (defn- safe-send!
     176              :   [bot params]
     177            5 :   (when bot
     178            1 :     (try
     179            5 :       (telegram-messages/request! tbot/send-message bot params)
     180              :       (catch Exception e
     181            0 :         (t/log!
     182              :          :warn
     183            0 :          {:message   "Failed to send event creation access notification"
     184            0 :           :chat-id   (:chat_id params)
     185            0 :           :exception e})
     186              :         nil))))
     187              : 
     188              : 
     189            4 : (defn notify-roots!
     190              :  [ctx bot request]
     191            1 :  (let
     192            3 :    [ds (datasource ctx)
     193              :     root-ids
     194            2 :     (query-many
     195            1 :      ds
     196            2 :      ["SELECT telegram_id
     197              :                       FROM users
     198              :                      WHERE roles @> '[\"root\"]'::jsonb
     199              :                        AND telegram_id IS NOT NULL"])
     200           16 :     username (when-let [value (not-empty (:requester-username request))] (str " (@" value ")"))
     201            4 :     text (str
     202              :           "Event creation access requested\n\n"
     203            3 :           (:requester-name request)
     204            1 :           username
     205              :           " would like to create events and templates in MatchScore.")
     206            8 :     keyboard {:inline_keyboard [[{:text "Approve"
     207            6 :                                   :callback_data (str "eca:a:" (:uuid request))}
     208            4 :                                  {:text "Decline"
     209            6 :                                   :callback_data (str "eca:d:" (:uuid request))}]]}]
     210           26 :    (doseq [{:keys [telegram-id]} root-ids]
     211            2 :      (safe-send!
     212            1 :       bot
     213            5 :       {:chat_id      telegram-id
     214            1 :        :text         text
     215            3 :        :reply_markup (json/generate-string keyboard)}))))
     216              : 
     217              : 
     218            4 : (defn notify-requester!
     219              :  [ctx bot request]
     220           18 :  (when-let [telegram-id (:requester-telegram-id request)]
     221           24 :    (let [user (user-repo/find-by-id (get-in ctx [:repos :user-postgres-repo]) (:user-id request))
     222           16 :          uk? (= "uk" (get-in user [:settings :language]))
     223           10 :          approved? (= "approved" (:status request))
     224            8 :          text (cond
     225           10 :                 (and uk? approved?)
     226              :                 "Ваш запит схвалено. Тепер ви можете створювати події та шаблони в MatchScore."
     227              : 
     228            2 :                 uk?
     229              :                 "Ваш запит на створення подій відхилено. За деталями зверніться до адміністратора."
     230              : 
     231            2 :                 approved?
     232              :                 "Your request was approved. You can now create events and templates in MatchScore."
     233              : 
     234              :                 :else
     235              :                 "Your event creation request was declined. Contact an administrator for details.")]
     236            4 :      (safe-send!
     237            2 :       bot
     238            8 :       {:chat_id telegram-id
     239            2 :        :text    text}))))
     240              : 
     241              : 
     242            4 : (defn callback-decision
     243              :  [callback-data]
     244           10 :  (when (string? callback-data)
     245           17 :    (when-let [[_ decision request-id] (re-matches #"eca:([ad]):(.+)" callback-data)]
     246            5 :      (when (uuid-utils/uuid-string? request-id)
     247            9 :        {:decision   (if (= decision "a") "approved" "declined")
     248            1 :         :request-id request-id}))))
        

Generated by: LCOV version 2.0-1