LCOV - code coverage report
Current view: top level - matchscore/api - events.clj Coverage Total Hit
Test: lcov.info Lines: 88.4 % 251 222
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.api.events
       2              :   (:require
       3              :    [cats.core :as c]
       4              :    [cats.monad.either :as either]
       5              :    [matchscore.access.resource :as access-resource]
       6              :    [matchscore.application.event.create :as app-event-create]
       7              :    [matchscore.application.event.end :as app-event-end]
       8              :    [matchscore.application.event.join :as app-event-join]
       9              :    [matchscore.application.event.leave :as app-event-leave]
      10              :    [matchscore.application.event.remove-participant :as app-event-remove-participant]
      11              :    [matchscore.application.event.telegram-invite :as app-telegram-invite]
      12              :    [matchscore.application.event.update-participant :as app-event-update-participant]
      13              :    [matchscore.domain.event.command :as event-cmd]
      14              :    [matchscore.domain.event.repository.postgres :as event-repo]
      15              :    [matchscore.jobs.telegram-match-notifications :as match-notification-jobs]
      16              :    [matchscore.media.db :as media-db]
      17              :    [matchscore.media.service :as media]
      18              :    [matchscore.telegram.notifications-trigger :as notifications-trigger]
      19              :    [next.jdbc :as jdbc]
      20              :    [next.jdbc.result-set :as rs]
      21              :    [next.jdbc.transaction :as transaction]
      22              :    [ring.util.http-status :as status]
      23              :    [schemas.api.core :as api-schemas]
      24              :    [taoensso.telemere :as t])
      25              :   (:import
      26              :    (java.time Instant)))
      27              : 
      28              : 
      29            4 : (defn- parse-datetimes
      30              :   [data]
      31           20 :   (cond-> data
      32           20 :     (:datetime-start data) (update :datetime-start #(Instant/parse %))
      33           16 :     (:datetime-end data)   (update :datetime-end #(Instant/parse %))))
      34              : 
      35              : 
      36            4 : (defn- normalize-club-ids
      37              :   "Normalizes club-id / club-ids into :club-ids.
      38              :   Accepts the deprecated :club-id (single) and promotes it to [:club-id] if no :club-ids given."
      39              :   [data]
      40            4 :   (let [{:keys [club-id club-ids]} data]
      41           18 :     (cond-> data
      42           10 :       (and club-id (nil? club-ids)) (assoc :club-ids [club-id])
      43            2 :       :always (dissoc :club-id))))
      44              : 
      45              : 
      46           24 : (def ^:private supported-event-states #{"scheduled" "active" "completed" "cancelled"})
      47              : 
      48              : 
      49            4 : (defn- event-state-authorization-object
      50              :   [{:keys [ctx auth-headers route-params]}]
      51            2 :   (access-resource/template-event-management-obj
      52            5 :    (assoc ctx :auth-headers auth-headers)
      53            3 :    (:event-uuid route-params)))
      54              : 
      55              : 
      56            4 : (defn event-create-handler
      57              :  {:malli/schema [:=>
      58              :                  [:cat api-schemas/RingRequest api-schemas/EventCreateRequestSchema]
      59              :                  api-schemas/EventCreateResponseSchema]
      60              :   :authz        {:obj     :event
      61              :                  :act     :create
      62              :                  :create? true}
      63              :   :summary      "Create event"
      64              :   :description  "Creates a new event with the provided data. Returns the created event on success."}
      65              :  [{:keys [ctx auth-headers]
      66              :    :as   _request}
      67              :   event-data]
      68           16 :  (when (contains? event-data :image-ids) (media/ensure-gallery-mutations-enabled! (:config ctx)))
      69            6 :  (let [event-data (->
      70            2 :                     event-data
      71           19 :                     (update :state #(or % "active"))
      72            2 :                     parse-datetimes
      73            2 :                     normalize-club-ids)
      74           14 :        result     (app-event-create/execute! ctx event-data (:user/uuid auth-headers))]
      75            8 :    (if (either/right? result)
      76            8 :      (let [created (c/extract result)]
      77           14 :        {:body   {:message "Event has been successfully created."
      78           10 :                  :data    (media/with-gallery ctx :event created)}
      79            2 :         :status status/created})
      80            4 :      (let [error (c/extract result)]
      81            9 :        {:body   {:message (:message error)
      82            1 :                  :error   error}
      83            5 :         :status (case (:code error)
      84            1 :                   :error.event/not-found status/not-found
      85            0 :                   status/bad-request)}))))
      86              : 
      87              : 
      88            4 : (defn- trigger-telegram-refresh!
      89              :   "The Telegram main post shows the event's name, time, location and fee."
      90              :   [ctx event-uuid]
      91            2 :   (try
      92            8 :     (notifications-trigger/trigger-debounced! ctx event-uuid)
      93              :     (catch Throwable e
      94            0 :       (t/log!
      95              :        :error
      96            0 :        {:message    "Failed to enqueue Telegram refresh after event update"
      97            0 :         :event-uuid event-uuid
      98            0 :         :exception  e}))))
      99              : 
     100              : 
     101            4 : (defn event-update-handler
     102              :  {:malli/schema [:=>
     103              :                  [:cat api-schemas/RingRequest api-schemas/EventRequestSchema]
     104              :                  api-schemas/EventUpdateResponseSchema]
     105              :   :authz {:obj :event
     106              :           :act :update
     107              :           :id  :body/uuid}
     108              :   :summary "Update event"
     109              :   :description
     110              :   "Updates an existing event with the provided data. Returns the updated event on success."}
     111              :  [{:keys [ctx auth-headers]
     112              :    :as   _request}
     113              :   event-data]
     114           16 :  (when (contains? event-data :image-ids) (media/ensure-gallery-mutations-enabled! (:config ctx)))
     115            6 :  (let [event-data   (->
     116            2 :                       event-data
     117            2 :                       parse-datetimes
     118            2 :                       normalize-club-ids)
     119            8 :        gallery?     (contains? event-data :image-ids)
     120           10 :        command-data (dissoc event-data :image-ids :images-version)
     121            4 :        result       (if gallery?
     122           10 :                       (binding [transaction/*nested-tx* :ignore]
     123            4 :                         (jdbc/with-transaction
     124            3 :                          [tx (:pg ctx)]
     125            3 :                          (let [tx-repo (event-repo/make-repository
     126            6 :                                         (jdbc/with-options tx {:builder-fn rs/as-kebab-maps}))
     127            7 :                                tx-ctx  (assoc-in ctx [:repos :event-postgres-repo] tx-repo)
     128            4 :                                result  (event-cmd/update-event! tx-ctx command-data)]
     129            5 :                            (when (either/right? result)
     130            3 :                              (media-db/replace-gallery!
     131            1 :                               tx
     132              :                               :event
     133            3 :                               (:uuid event-data)
     134            3 :                               (:user/uuid auth-headers)
     135            3 :                               (:image-ids event-data)
     136            3 :                               (:images-version event-data)))
     137            1 :                            result)))
     138            4 :                       (event-cmd/update-event! ctx command-data))]
     139            8 :    (if (either/right? result)
     140            8 :      (let [{:keys [code data only-settings-changed?]} (c/extract result)
     141            6 :            code (if gallery? :success.event/ok code)
     142            4 :            data (if gallery?
     143            4 :                   (or
     144            3 :                    (event-repo/find-by-id
     145            6 :                     (get-in ctx [:repos :event-postgres-repo])
     146            3 :                     (:uuid data)
     147              :                     nil)
     148              :                    data)
     149            1 :                   data)
     150           10 :            data (media/with-gallery ctx :event data)]
     151           16 :        (match-notification-jobs/schedule-event-sync! (:goose ctx) (:uuid data))
     152              :        ;; The main post re-sends itself (and pings the chat), so only for what it shows:
     153              :        ;; a settings-only save (e.g. the stage planner's court plan) leaves it alone.
     154           23 :        (when (and (= code :success.event/ok) (not only-settings-changed?))
     155           12 :          (trigger-telegram-refresh! ctx (:uuid data)))
     156           10 :        (cond (= code :success.event/ok)
     157           14 :              {:body   {:message "Event updated successfully."
     158            2 :                        :data    data}
     159            2 :               :status status/ok}
     160              : 
     161            3 :              (= code :success.event/no-changes)
     162            7 :              {:body   {:message "No changes detected."
     163            1 :                        :data    data}
     164            1 :               :status status/ok}
     165              : 
     166              :              :else
     167            7 :              {:body   {:message "Unexpected event update result."
     168            4 :                        :error   {:code code
     169            1 :                                  :data data}}
     170            1 :               :status status/bad-request}))
     171            0 :      (let [error (c/extract result)]
     172            0 :        {:body   {:message (:message error)
     173            0 :                  :error   error}
     174            0 :         :status status/bad-request}))))
     175              : 
     176              : 
     177            4 : (defn event-images-handler
     178              :  {:malli/parameters {:path api-schemas/EventPathParamsSchema}
     179              :   :authz   {:public? true}
     180              :   :summary "Get an event image gallery"}
     181              :  [{:keys [ctx route-params]}]
     182            3 :  (let [event (event-repo/find-by-id
     183            6 :               (get-in ctx [:repos :event-postgres-repo])
     184            3 :               (:event-uuid route-params)
     185            3 :               {:joins #{}})]
     186            7 :    (if-not (access-resource/event-readable? ctx event)
     187            4 :      {:status status/not-found
     188            3 :       :body   {:message "Event not found."}}
     189            6 :      (let [{:keys [images cover-image images-version]} (media/with-gallery ctx :event event)]
     190            4 :        {:status status/ok
     191            7 :         :body   {:data {:images         images
     192            1 :                         :cover-image    cover-image
     193            1 :                         :images-version images-version}}}))))
     194              : 
     195              : 
     196            4 : (defn event-delete-handler
     197              :  {:malli/parameters {:path api-schemas/EventPathParamsSchema}
     198              :   :authz   {:obj :event
     199              :             :act :delete
     200              :             :id  :route-params/event-uuid}
     201              :   :summary "Delete event"}
     202              :  [{:keys [ctx route-params]
     203              :    :as   _request}]
     204            4 :  (let [event-id (:event-uuid route-params)
     205            4 :        result   (jdbc/with-transaction
     206            3 :                  [tx (:pg ctx)]
     207            6 :                  (let [asset-ids (media-db/gallery-asset-ids tx :event event-id)
     208            2 :                        tx-repo   (event-repo/make-repository
     209            6 :                                   (jdbc/with-options tx {:builder-fn rs/as-kebab-maps}))
     210            2 :                        result    (event-cmd/delete-event!
     211            7 :                                   (assoc-in ctx [:repos :event-postgres-repo] tx-repo)
     212            1 :                                   event-id)]
     213            9 :                    (when (either/right? result) (media-db/mark-orphans! tx asset-ids))
     214            1 :                    result))]
     215            4 :    (if (either/right? result)
     216            3 :      {:status status/no-content}
     217            4 :      (let [error (c/extract result)]
     218            9 :        {:body   {:message (:message error)
     219            1 :                  :error   error}
     220            1 :         :status status/bad-request}))))
     221              : 
     222              : 
     223            4 : (defn event-join-handler
     224              :  {:malli/parameters {:path api-schemas/EventPathParamsSchema}
     225              :   :authz {:obj          :event
     226              :           :act          :join
     227              :           :id           :route-params/event-uuid
     228              :           :participant? false}
     229              :   :summary "Join event"
     230              :   :description
     231              :   "Registers the current user for the event. With a single class the user is added to it automatically; with several classes the optional `class_uuid` body field is required and a 400 with `error.event/class-required` lists the classes to choose from."}
     232              :  [{:keys [auth-headers body bot ctx route-params]
     233              :    :as   _request}]
     234           13 :  (let [class-uuid (when (map? body) (or (:class_uuid body) (:class-uuid body)))
     235            2 :        result     (app-event-join/execute!
     236            1 :                    ctx
     237            3 :                    (:event-uuid route-params)
     238            3 :                    (:user/uuid auth-headers)
     239            1 :                    class-uuid)]
     240            4 :    (if (either/right? result)
     241            4 :      (let [{:keys [event-participant class-participant]} (c/extract result)]
     242            9 :        {:body   {:message "Joined event successfully."
     243            1 :                  :data event-participant
     244            1 :                  :class-participant class-participant
     245            2 :                  :telegram-invite (app-telegram-invite/create-for-event!
     246            1 :                                    ctx
     247            1 :                                    bot
     248            3 :                                    (:event-uuid route-params))}
     249            1 :         :status status/created})
     250            1 :      (let [{:keys [code message]
     251              :             :as   error}
     252            3 :            (c/extract result)]
     253            7 :        {:body   {:message message
     254            1 :                  :error   error}
     255            6 :         :status (if (= code :error.class/not-found) status/not-found status/bad-request)}))))
     256              : 
     257              : 
     258            4 : (defn event-telegram-invite-handler
     259              :  {:malli/parameters {:path api-schemas/EventPathParamsSchema}
     260              :   :authz {:obj :event
     261              :           :act :read
     262              :           :id  :route-params/event-uuid}
     263              :   :summary "Create a Telegram chat invite for an event participant"
     264              :   :description
     265              :   "Creates a short-lived, single-use invite for the event's linked Telegram chat. Event or template-level links are supported."}
     266              :  [{:keys [bot ctx route-params]
     267              :    :as   _request}]
     268            7 :  {:body   {:message         "Telegram invitation checked."
     269            2 :            :telegram-invite (app-telegram-invite/create-for-event!
     270            1 :                              ctx
     271            1 :                              bot
     272            3 :                              (:event-uuid route-params))}
     273            1 :   :status status/ok})
     274              : 
     275              : 
     276            4 : (defn event-leave-handler
     277              :  {:malli/parameters {:path api-schemas/EventPathParamsSchema}
     278              :   :authz {:obj          :event
     279              :           :act          :leave
     280              :           :id           :route-params/event-uuid
     281              :           :participant? false}
     282              :   :summary "Leave event"
     283              :   :description
     284              :   "Removes the current user's registration from the event and all of its classes. Event admins keep their admin participant record."}
     285              :  [{:keys [auth-headers ctx route-params]
     286              :    :as   _request}]
     287           10 :  (let [result (app-event-leave/execute! ctx (:event-uuid route-params) (:user/uuid auth-headers))]
     288            4 :    (if (either/right? result)
     289            6 :      {:body   {:message "Left event successfully."}
     290            1 :       :status status/ok}
     291            4 :      (let [error (c/extract result)]
     292            9 :        {:body   {:message (:message error)
     293            1 :                  :error   error}
     294            1 :         :status status/bad-request}))))
     295              : 
     296              : 
     297            4 : (defn event-add-participant-handler
     298              :  {:malli/schema [:=>
     299              :                  [:cat api-schemas/RingRequest api-schemas/EventAddParticipantRequestSchema]
     300              :                  api-schemas/EventAddParticipantResponseSchema]
     301              :   :malli/parameters {:path api-schemas/EventPathParamsSchema}
     302              :   :authz {:obj :event
     303              :           :act :update
     304              :           :id  :route-params/event-uuid}
     305              :   :summary "Add participant to event"
     306              :   :description
     307              :   "Adds a user to the event with `roles` (default `[\"player\"]`) and to each of `class_uuid` / `class_uuids`, creating a participant record if needed. A player needs a class: with a single class the user is added to it automatically; with several classes and none given a 400 with `error.event/class-required` lists the classes to choose from. A participant without the `player` role (an admin) may be added without a class. Returns 400 if the user is already in one of the classes."}
     308              :  [{:keys [ctx route-params]
     309              :    :as   _request}
     310              :   {:keys [user-uuid class-uuid class-uuids roles]}]
     311            3 :  (let [result (app-event-join/add!
     312            1 :                ctx
     313            3 :                (:event-uuid route-params)
     314            1 :                user-uuid
     315           14 :                {:class-uuids (cond->> (vec class-uuids) class-uuid (cons class-uuid))
     316            1 :                 :roles       roles})]
     317            4 :    (if (either/right? result)
     318            4 :      (let [{:keys [event-participant class-participants]} (c/extract result)]
     319            9 :        {:body   {:message "Participant added successfully."
     320            1 :                  :data event-participant
     321            3 :                  :class-participant (first class-participants)
     322            1 :                  :class-participants class-participants}
     323            1 :         :status status/created})
     324            1 :      (let [{:keys [code message]
     325              :             :as   error}
     326            3 :            (c/extract result)]
     327            7 :        {:body   {:message message
     328            1 :                  :error   error}
     329            5 :         :status (if (= code :error.class/not-found) status/not-found status/bad-request)}))))
     330              : 
     331              : 
     332            4 : (defn event-end-handler
     333              :  {:malli/parameters {:path api-schemas/EventPathParamsSchema}
     334              :   :malli/schema [:=> [:cat api-schemas/RingRequest] api-schemas/EventEndResponseSchema]
     335              :   :authz {:obj :event
     336              :           :act :update
     337              :           :id  :route-params/event-uuid}
     338              :   :summary "End event"
     339              :   :description
     340              :   "Ends an event by verifying all matches are in a terminal state, then transitioning the event to 'completed'."}
     341              :  [{:keys [ctx route-params auth-headers]
     342              :    :as   _request}]
     343            0 :  (let [result (app-event-end/execute! ctx (:event-uuid route-params) (:user/uuid auth-headers))]
     344            0 :    (if (either/right? result)
     345            0 :      (let [{:keys [code data]} (c/extract result)]
     346            0 :        {:body   {:message (if (= code :success.event/ok)
     347              :                             "Event ended successfully."
     348              :                             "Event already completed.")
     349            0 :                  :data    data}
     350            0 :         :status status/ok})
     351            0 :      (let [error (c/extract result)]
     352            0 :        {:body   {:message (:message error)
     353            0 :                  :error   error}
     354            0 :         :status (case (:code error)
     355            0 :                   :error.event/not-found status/not-found
     356            0 :                   :error.event/matches-not-completed status/bad-request
     357            0 :                   status/bad-request)}))))
     358              : 
     359              : 
     360            4 : (defn event-state-update-handler
     361              :  {:malli/parameters {:path api-schemas/EventPathParamsSchema}
     362              :   :malli/schema [:=>
     363              :                  [:cat api-schemas/RingRequest api-schemas/EventStateUpdateRequestSchema]
     364              :                  api-schemas/EventStateUpdateResponseSchema]
     365              :   :authz {:obj          :event
     366              :           :act          :update
     367              :           :obj-resolver #'event-state-authorization-object}
     368              :   :summary "Update event state"
     369              :   :description
     370              :   "Changes an event to scheduled, active, completed, or cancelled. Completing an event verifies that all playable matches are terminal; terminal states run the normal automation and Telegram side effects."}
     371              :  [{:keys [ctx route-params auth-headers]
     372              :    :as   _request}
     373              :   {:keys [state]
     374              :    :as   state-data}]
     375            7 :  (if-not (contains? supported-event-states state)
     376            7 :    {:body   {:message "Invalid event state."
     377            4 :              :error   {:code    :error.event/invalid-state
     378            3 :                        :context {:state state}}}
     379            1 :     :status status/bad-request}
     380            4 :    (let [event-id (:event-uuid route-params)
     381            3 :          user-id  (:user/uuid auth-headers)
     382            4 :          result   (if (= "completed" state)
     383            0 :                     (app-event-end/execute! ctx event-id user-id)
     384            3 :                     (event-cmd/update-event-state!
     385           18 :                      (update ctx :pg #(if (and (map? %) (:datasource %)) % {:datasource %}))
     386            5 :                      (assoc state-data :uuid event-id)
     387              :                      :user-uuid
     388            1 :                      user-id))]
     389            4 :      (if (either/right? result)
     390            4 :        (let [{:keys [code data]} (c/extract result)]
     391            8 :          (match-notification-jobs/schedule-event-sync! (:goose ctx) (:uuid data))
     392           11 :          {:body   {:message (if (= code :success.event/no-changes)
     393              :                               "Event state is already up to date."
     394              :                               "Event state updated successfully.")
     395            1 :                    :data    data}
     396            1 :           :status status/ok})
     397            0 :        (let [error (c/extract result)]
     398            0 :          {:body   {:message (:message error)
     399            0 :                    :error   error}
     400            0 :           :status (case (:code error)
     401            0 :                     :error.event/not-found status/not-found
     402            0 :                     status/bad-request)})))))
     403              : 
     404              : 
     405            4 : (defn event-remove-participant-handler
     406              :  {:malli/parameters {:path api-schemas/EventParticipantPathParamsSchema}
     407              :   :authz {:obj :event
     408              :           :act :update
     409              :           :id  :route-params/event-uuid}
     410              :   :summary "Remove participant from event"
     411              :   :description
     412              :   "Removes a user from the event and all classes of that event they are registered in."}
     413              :  [{:keys [ctx route-params]
     414              :    :as   _request}]
     415            3 :  (let [result (app-event-remove-participant/execute!
     416            1 :                ctx
     417            3 :                (:event-uuid route-params)
     418            3 :                (:participant-uuid route-params))]
     419            4 :    (if (either/right? result)
     420            6 :      {:body   {:message "Participant removed successfully."}
     421            1 :       :status status/ok}
     422            4 :      (let [error (c/extract result)]
     423            9 :        {:body   {:message (:message error)
     424            1 :                  :error   error}
     425            1 :         :status status/bad-request}))))
     426              : 
     427              : 
     428            4 : (defn event-update-participant-handler
     429              :  {:malli/schema [:=>
     430              :                  [:cat api-schemas/RingRequest api-schemas/EventUpdateParticipantRequestSchema]
     431              :                  api-schemas/EventUpdateParticipantResponseSchema]
     432              :   :malli/parameters {:path api-schemas/EventParticipantPathParamsSchema}
     433              :   :authz {:obj :event
     434              :           :act :update
     435              :           :id  :route-params/event-uuid}
     436              :   :summary "Update event participant"
     437              :   :description
     438              :   "Updates status and/or roles for an existing event participant. Returns 400 with `error.event-participant/class-required` when the admin role is removed from a participant who is in no class of the event."}
     439              :  [{:keys [ctx route-params]
     440              :    :as   _request}
     441              :   update-data]
     442            6 :  (let [participant-data (assoc update-data
     443            3 :                          :event-id       (:event-uuid route-params)
     444            3 :                          :participant-id (:participant-uuid route-params))
     445            4 :        result (app-event-update-participant/execute! ctx participant-data)]
     446            4 :    (if (either/right? result)
     447            4 :      (let [{:keys [code data]} (c/extract result)]
     448           12 :        {:body   {:message (if (= code :success.event-participant/ok)
     449              :                             "Participant updated successfully."
     450              :                             "No changes detected.")
     451            1 :                  :data    data}
     452            1 :         :status status/ok})
     453            4 :      (let [error (c/extract result)]
     454            9 :        {:body   {:message (:message error)
     455            1 :                  :error   error}
     456            6 :         :status (if (= (:code error) :error.event-participant/not-found)
     457            1 :                   status/not-found
     458            1 :                   status/bad-request)}))))
        

Generated by: LCOV version 2.0-1