LCOV - code coverage report
Current view: top level - matchscore/api - templates.clj Coverage Total Hit
Test: lcov.info Lines: 87.5 % 224 196
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.api.templates
       2              :   (:require
       3              :    [cats.core :as c]
       4              :    [cats.monad.either :as either]
       5              :    [matchscore.access.resource :as access-resource]
       6              :    [matchscore.application.telegram-access :as app-telegram-access]
       7              :    [matchscore.application.template.common :as template-common]
       8              :    [matchscore.application.template.create :as app-template-create]
       9              :    [matchscore.application.template.occurrence-exceptions :as app-occurrence-exceptions]
      10              :    [matchscore.application.template.participant :as app-template-participant]
      11              :    [matchscore.db.postgres.telegram-match-notifications :as notification-db]
      12              :    [matchscore.domain.template.command :as templates-cmd]
      13              :    [matchscore.domain.template.repository.postgres :as template-repo]
      14              :    [matchscore.jobs.telegram-match-notifications :as match-notification-jobs]
      15              :    [matchscore.media.db :as media-db]
      16              :    [matchscore.media.service :as media]
      17              :    [matchscore.utils.nanoid :as nanoid]
      18              :    [matchscore.utils.uuid :as uuid-utils]
      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              : 
      25              : 
      26            4 : (defn- normalize-club-ids
      27              :   "Normalizes :club-id (single, deprecated) → :club-ids (vector).
      28              :   Passes :club-ids through unchanged."
      29              :   [data]
      30            4 :   (let [{:keys [club-id club-ids]} data]
      31           18 :     (cond-> data
      32           10 :       (and club-id (nil? club-ids)) (assoc :club-ids [club-id])
      33            2 :       :always (dissoc :club-id))))
      34              : 
      35              : 
      36              : ;; Handlers
      37            4 : (defn template-create-handler
      38              :  {:malli/schema [:=>
      39              :                  [:cat api-schemas/RingRequest api-schemas/TemplateCreateRequestSchema]
      40              :                  api-schemas/TemplateResponseSchema]
      41              :   :authz {:obj     :template
      42              :           :act     :create
      43              :           :create? true}
      44              :   :summary "Create event template"
      45              :   :description
      46              :   "Creates a new event template with the provided data. Returns the created event template on success."}
      47              :  [{:keys [ctx parsed-headers]
      48              :    :as   _request}
      49              :   template-data]
      50           16 :  (when (contains? template-data :image-ids) (media/ensure-gallery-mutations-enabled! (:config ctx)))
      51            2 :  (let [template-data   (->
      52            1 :                          template-data
      53            6 :                          (assoc :uuid      (uuid-utils/generate-uuid7-str)
      54            2 :                                 :public-id (nanoid/generate))
      55            1 :                          normalize-club-ids)
      56            3 :        current-user-id (:user/uuid parsed-headers)
      57            5 :        result          (app-template-create/execute! ctx template-data current-user-id)]
      58            4 :    (if (either/right? result)
      59            4 :      (let [created-template (c/extract result)]
      60           10 :        {:body   {:message (str
      61              :                            "Event template with name "
      62            3 :                            (:name created-template)
      63              :                            " created successfully.")
      64            5 :                  :data    (media/with-gallery ctx :template created-template)}
      65            1 :         :status status/created})
      66            4 :      (let [error (c/extract result)]
      67            9 :        {:body   {:message (:message error)
      68            1 :                  :error   error}
      69            1 :         :status status/bad-request}))))
      70              : 
      71              : 
      72            4 : (defn template-update-handler
      73              :  {:malli/schema [:=>
      74              :                  [:cat api-schemas/RingRequest api-schemas/TemplateRequestSchema]
      75              :                  api-schemas/TemplateResponseSchema]
      76              :   :authz {:obj :template
      77              :           :act :update
      78              :           :id  :body/uuid}
      79              :   :summary "Update event template"
      80              :   :description
      81              :   "Updates an existing event template with the provided data. Returns the updated event template on success."}
      82              :  [{:keys [ctx parsed-headers]
      83              :    :as   _request}
      84              :   template-data]
      85           16 :  (when (contains? template-data :image-ids) (media/ensure-gallery-mutations-enabled! (:config ctx)))
      86            6 :  (let [template-data (->
      87            2 :                        template-data
      88            2 :                        normalize-club-ids
      89            2 :                        template-common/with-rrule-json)
      90            8 :        gallery?      (contains? template-data :image-ids)
      91           10 :        command-data  (dissoc template-data :image-ids :images-version)
      92            4 :        result        (if gallery?
      93           10 :                        (binding [transaction/*nested-tx* :ignore]
      94            4 :                          (jdbc/with-transaction
      95            3 :                           [tx (:pg ctx)]
      96            3 :                           (let [tx-repo (template-repo/make-repository
      97            6 :                                          (jdbc/with-options tx {:builder-fn rs/as-kebab-maps}))
      98            7 :                                 tx-ctx  (assoc-in ctx [:repos :template-postgres-repo] tx-repo)
      99            4 :                                 result  (templates-cmd/update-template! tx-ctx command-data)]
     100            5 :                             (when (either/right? result)
     101            3 :                               (media-db/replace-gallery!
     102            1 :                                tx
     103              :                                :template
     104            3 :                                (:uuid template-data)
     105            3 :                                (:user/uuid parsed-headers)
     106            3 :                                (:image-ids template-data)
     107            3 :                                (:images-version template-data)))
     108            1 :                             result)))
     109            4 :                        (templates-cmd/update-template! ctx command-data))]
     110            8 :    (if (either/right? result)
     111            8 :      (let [{:keys [code data]} (c/extract result)
     112            6 :            code (if gallery? :success.template/ok code)
     113            4 :            data (if gallery?
     114            4 :                   (or
     115            3 :                    (template-repo/find-by-id
     116            6 :                     (get-in ctx [:repos :template-postgres-repo])
     117            3 :                     (:uuid data)
     118              :                     nil)
     119              :                    data)
     120            1 :                   data)
     121           10 :            data (media/with-gallery ctx :template data)]
     122           18 :        (when-let [pg (:pg ctx)]
     123           44 :          (doseq [event-id (notification-db/active-event-ids-for-template pg (:uuid data))]
     124            0 :            (match-notification-jobs/schedule-event-sync! (:goose ctx) event-id)))
     125            4 :        (cond
     126            6 :          (= code :success.template/ok)
     127           26 :          {:body   {:message (str "Event template with name " (:name data) " updated successfully.")
     128            2 :                    :data    data}
     129            2 :           :status status/ok}
     130              : 
     131            3 :          (= code :success.template/no-changes)
     132            7 :          {:body   {:message "No changes detected."
     133            1 :                    :data    data}
     134            1 :           :status status/ok}
     135              : 
     136              :          :else
     137            8 :          {:body   {:message "Unexpected template update result."
     138            1 :                    :data    data
     139            1 :                    :code    code}
     140            1 :           :status status/ok}))
     141            4 :      (let [error (c/extract result)]
     142            9 :        {:body   {:message (:message error)
     143            1 :                  :error   error}
     144            5 :         :status (case (:code error)
     145            0 :                   :error.template/not-found status/not-found
     146            1 :                   status/bad-request)}))))
     147              : 
     148              : 
     149            4 : (defn template-images-handler
     150              :  {:malli/parameters {:path api-schemas/TemplatePathParamsSchema}
     151              :   :authz   {:public? true}
     152              :   :summary "Get a template image gallery"}
     153              :  [{:keys [ctx route-params]}]
     154            3 :  (let [template (template-repo/find-by-id
     155            6 :                  (get-in ctx [:repos :template-postgres-repo])
     156            3 :                  (:template-uuid route-params)
     157            3 :                  {:joins #{}})]
     158            7 :    (if-not (access-resource/template-readable? ctx template)
     159            0 :      {:status status/not-found
     160            0 :       :body   {:message "Template not found."}}
     161            6 :      (let [{:keys [images cover-image images-version]} (media/with-gallery ctx :template template)]
     162            4 :        {:status status/ok
     163            7 :         :body   {:data {:images         images
     164            1 :                         :cover-image    cover-image
     165            1 :                         :images-version images-version}}}))))
     166              : 
     167              : 
     168            4 : (defn template-delete-handler
     169              :  {:malli/parameters {:path api-schemas/TemplatePathParamsSchema}
     170              :   :authz            {:obj :template
     171              :                      :act :delete
     172              :                      :id  :route-params/template-uuid}
     173              :   :summary          "Delete event template"
     174              :   :description      "Deletes an existing event template."}
     175              :  [{:keys [ctx route-params]
     176              :    :as   _request}]
     177            4 :  (let [template-id (:template-uuid route-params)
     178            4 :        result      (jdbc/with-transaction
     179            3 :                     [tx (:pg ctx)]
     180            6 :                     (let [asset-ids (media-db/gallery-asset-ids tx :template template-id)
     181            2 :                           tx-repo   (template-repo/make-repository
     182            6 :                                      (jdbc/with-options tx {:builder-fn rs/as-kebab-maps}))
     183            2 :                           result    (templates-cmd/delete-template!
     184            7 :                                      (assoc-in ctx [:repos :template-postgres-repo] tx-repo)
     185            1 :                                      template-id)]
     186            9 :                       (when (either/right? result) (media-db/mark-orphans! tx asset-ids))
     187            1 :                       result))]
     188            4 :    (if (either/right? result)
     189            3 :      {:status status/no-content}
     190            4 :      (let [error (c/extract result)]
     191            9 :        {:body   {:message (:message error)
     192            1 :                  :error   error}
     193            1 :         :status status/bad-request}))))
     194              : 
     195              : 
     196            4 : (defn template-occurrence-exceptions-handler
     197              :  {:malli/schema     [:=>
     198              :                      [:cat api-schemas/RingRequest]
     199              :                      api-schemas/TemplateOccurrenceExceptionListResponseSchema]
     200              :   :malli/parameters {:path api-schemas/TemplatePathParamsSchema}
     201              :   :authz            {:obj :template
     202              :                      :act :read
     203              :                      :id  :route-params/template-uuid}
     204              :   :summary          "List skipped template occurrences"
     205              :   :description      "Returns recurrence occurrences that an administrator has skipped."}
     206              :  [{:keys [ctx route-params]
     207              :    :as   _request}]
     208            7 :  {:body   {:message "Skipped occurrences retrieved successfully."
     209            6 :            :data    (app-occurrence-exceptions/list-for-template ctx (:template-uuid route-params))}
     210            1 :   :status status/ok})
     211              : 
     212              : 
     213            4 : (defn template-occurrence-exception-create-handler
     214              :  {:malli/schema [:=>
     215              :                  [:cat api-schemas/RingRequest api-schemas/TemplateOccurrenceExceptionRequestSchema]
     216              :                  api-schemas/TemplateOccurrenceExceptionResponseSchema]
     217              :   :malli/parameters {:path api-schemas/TemplatePathParamsSchema}
     218              :   :authz {:obj :template
     219              :           :act :update
     220              :           :id  :route-params/template-uuid}
     221              :   :summary "Skip a template occurrence"
     222              :   :description
     223              :   "Prevents manual and automatic event creation for one recurrence occurrence, optionally notifying linked chats and participants."}
     224              :  [{:keys [ctx route-params auth-headers]
     225              :    :as   _request}
     226              :   data]
     227            3 :  (let [result (app-occurrence-exceptions/create!
     228            1 :                ctx
     229            3 :                (:template-uuid route-params)
     230            1 :                data
     231            3 :                (:user/uuid auth-headers))]
     232            4 :    (if (either/right? result)
     233            7 :      {:body   {:message "Occurrence skipped successfully."
     234            3 :                :data    (c/extract result)}
     235            1 :       :status status/created}
     236            4 :      (let [error (c/extract result)]
     237            9 :        {:body   {:message (:message error)
     238            1 :                  :error   error}
     239            5 :         :status (case (:code error)
     240            0 :                   :error.template/not-found status/not-found
     241            1 :                   status/bad-request)}))))
     242              : 
     243              : 
     244            4 : (defn template-occurrence-exception-delete-handler
     245              :  {:malli/schema     [:=>
     246              :                      [:cat api-schemas/RingRequest]
     247              :                      api-schemas/TemplateOccurrenceExceptionResponseSchema]
     248              :   :malli/parameters {:path api-schemas/TemplateOccurrenceExceptionPathParamsSchema}
     249              :   :authz            {:obj :template
     250              :                      :act :update
     251              :                      :id  :route-params/template-uuid}
     252              :   :summary          "Undo a skipped template occurrence"
     253              :   :description      "Removes a recurrence exception so the occurrence can be created again."}
     254              :  [{:keys [ctx route-params]
     255              :    :as   _request}]
     256            3 :  (let [result (app-occurrence-exceptions/delete!
     257            1 :                ctx
     258            3 :                (:template-uuid route-params)
     259            3 :                (:exception-uuid route-params))]
     260            4 :    (if (either/right? result)
     261            7 :      {:body   {:message "Skipped occurrence restored successfully."
     262            3 :                :data    (c/extract result)}
     263            1 :       :status status/ok}
     264            0 :      (let [error (c/extract result)]
     265            0 :        {:body   {:message (:message error)
     266            0 :                  :error   error}
     267            0 :         :status status/not-found}))))
     268              : 
     269              : 
     270            4 : (defn template-join-handler
     271              :  {:malli/parameters {:path api-schemas/TemplatePathParamsSchema}
     272              :   :authz   {:obj          :template
     273              :             :act          :join
     274              :             :id           :route-params/template-uuid
     275              :             :participant? false}
     276              :   :summary "Join event template"}
     277              :  [{:keys [ctx route-params]
     278              :    :as   _request}]
     279            7 :  (let [result (access-resource/join-template! ctx (:template-uuid route-params))]
     280            4 :    (if (either/right? result)
     281            7 :      {:body   {:message "Joined template successfully."
     282            3 :                :data    (c/extract result)}
     283            1 :       :status status/created}
     284            4 :      (let [error (c/extract result)]
     285            9 :        {:body   {:message (:message error)
     286            1 :                  :error   error}
     287            1 :         :status status/bad-request}))))
     288              : 
     289              : 
     290            4 : (defn template-leave-handler
     291              :  {:malli/parameters {:path api-schemas/TemplatePathParamsSchema}
     292              :   :authz   {:obj          :template
     293              :             :act          :leave
     294              :             :id           :route-params/template-uuid
     295              :             :participant? false}
     296              :   :summary "Leave event template"}
     297              :  [{:keys [ctx route-params]
     298              :    :as   _request}]
     299            7 :  (let [result (access-resource/leave-template! ctx (:template-uuid route-params))]
     300            4 :    (if (either/right? result)
     301            6 :      {:body   {:message "Left template successfully."}
     302            1 :       :status status/ok}
     303            4 :      (let [error (c/extract result)]
     304            9 :        {:body   {:message (:message error)
     305            1 :                  :error   error}
     306            1 :         :status status/bad-request}))))
     307              : 
     308              : 
     309            4 : (defn template-telegram-access-handler
     310              :  {:malli/schema
     311              :   [:=> [:cat api-schemas/RingRequest] api-schemas/TemplateTelegramAccessResponseSchema]
     312              :   :malli/parameters {:path [:map
     313              :                             [:template-uuid {:description "Template public id or UUID"}
     314              :                              [:string {:min 1}]]]}
     315              :   :authz {:public? true}
     316              :   :summary "Request Telegram view access to a template"
     317              :   :description
     318              :   "Verifies the caller's membership of the template's linked Telegram chat(s) via getChatMember and caches it. Members of a linked chat are granted view access to the template and its results."}
     319              :  [{:keys [ctx bot route-params auth-headers]
     320              :    :as   _request}]
     321            0 :  (let [result (app-telegram-access/grant-template-access!
     322            0 :                ctx
     323            0 :                bot
     324            0 :                (:template-uuid route-params)
     325            0 :                (:user/uuid auth-headers)
     326            0 :                (:telegram/id auth-headers))]
     327            0 :    (if (either/right? result)
     328            0 :      {:body   (assoc (c/extract result) :message "Telegram access check completed.")
     329            0 :       :status status/ok}
     330            0 :      (let [error (c/extract result)]
     331            0 :        {:body   {:message (:message error)
     332            0 :                  :error   error}
     333            0 :         :status status/bad-request}))))
     334              : 
     335              : 
     336            4 : (defn template-add-participant-handler
     337              :  {:malli/schema [:=>
     338              :                  [:cat api-schemas/RingRequest api-schemas/TemplateAddParticipantRequestSchema]
     339              :                  api-schemas/TemplateAddParticipantResponseSchema]
     340              :   :malli/parameters {:path api-schemas/TemplatePathParamsSchema}
     341              :   :authz {:obj :template
     342              :           :act :update
     343              :           :id  :route-params/template-uuid}
     344              :   :summary "Add participant to event template"
     345              :   :description
     346              :   "Adds a user as a participant in the event template with `roles` (default `[\"player\"]`). Creates a participant record if needed. Returns 400 if already registered."}
     347              :  [{:keys [ctx route-params]
     348              :    :as   _request}
     349              :   {:keys [user-uuid roles]}]
     350            5 :  (let [result (if (seq roles)
     351            0 :                 (app-template-participant/add!
     352            0 :                  ctx
     353            0 :                  (:template-uuid route-params)
     354            0 :                  user-uuid
     355            0 :                  {:roles (vec (distinct roles))})
     356            7 :                 (app-template-participant/add! ctx (:template-uuid route-params) user-uuid))]
     357            4 :    (if (either/right? result)
     358            7 :      {:body   {:message "Participant added successfully."
     359            3 :                :data    (c/extract result)}
     360            1 :       :status status/created}
     361            4 :      (let [error (c/extract result)]
     362            9 :        {:body   {:message (:message error)
     363            1 :                  :error   error}
     364            1 :         :status status/bad-request}))))
     365              : 
     366              : 
     367            4 : (defn template-remove-participant-handler
     368              :  {:malli/parameters {:path api-schemas/TemplateParticipantPathParamsSchema}
     369              :   :authz            {:obj :template
     370              :                      :act :update
     371              :                      :id  :route-params/template-uuid}
     372              :   :summary          "Remove participant from event template"
     373              :   :description      "Removes a participant from the event template."}
     374              :  [{:keys [ctx route-params]
     375              :    :as   _request}]
     376            3 :  (let [result (app-template-participant/remove!
     377            1 :                ctx
     378            3 :                (:template-uuid route-params)
     379            3 :                (:participant-uuid route-params))]
     380            4 :    (if (either/right? result)
     381            6 :      {:body   {:message "Participant removed successfully."}
     382            1 :       :status status/ok}
     383            4 :      (let [error (c/extract result)]
     384            9 :        {:body   {:message (:message error)
     385            1 :                  :error   error}
     386            1 :         :status status/bad-request}))))
     387              : 
     388              : 
     389            4 : (defn template-update-participant-handler
     390              :  {:malli/schema     [:=>
     391              :                      [:cat
     392              :                       api-schemas/RingRequest
     393              :                       api-schemas/TemplateUpdateParticipantRequestSchema]
     394              :                      api-schemas/TemplateUpdateParticipantResponseSchema]
     395              :   :malli/parameters {:path api-schemas/TemplateParticipantPathParamsSchema}
     396              :   :authz            {:obj :template
     397              :                      :act :update
     398              :                      :id  :route-params/template-uuid}
     399              :   :summary          "Update event template participant"
     400              :   :description      "Updates status and/or roles for an existing event template participant."}
     401              :  [{:keys [ctx route-params]
     402              :    :as   _request}
     403              :   update-data]
     404            3 :  (let [result (app-template-participant/update!
     405            1 :                ctx
     406            3 :                (:template-uuid route-params)
     407            3 :                (:participant-uuid route-params)
     408            1 :                update-data)]
     409            4 :    (if (either/right? result)
     410            4 :      (let [{:keys [code data]} (c/extract result)]
     411           12 :        {:body   {:message (if (= code :success.template-participant/ok)
     412              :                             "Participant updated successfully."
     413              :                             "No changes detected.")
     414            1 :                  :data    data}
     415            1 :         :status status/ok})
     416            4 :      (let [error (c/extract result)]
     417            9 :        {:body   {:message (:message error)
     418            1 :                  :error   error}
     419            6 :         :status (if (= (:code error) :error.template-participant/not-found)
     420            1 :                   status/not-found
     421            0 :                   status/bad-request)}))))
        

Generated by: LCOV version 2.0-1