LCOV - code coverage report
Current view: top level - matchscore/application/event - create.clj Coverage Total Hit
Test: lcov.info Lines: 97.1 % 206 200
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.application.event.create
       2              :   "Application service for event creation.
       3              :    Orchestrates across user, participant, class, and event domains."
       4              :   (:require
       5              :    [cats.core :as c]
       6              :    [cats.monad.either :as either]
       7              :    [matchscore.db.postgres.host :as host-db]
       8              :    [matchscore.db.postgres.template-automation :as automation-db]
       9              :    [matchscore.domain.class-participant.repository.postgres :as class-participant-postgres-repo]
      10              :    [matchscore.domain.class-template-participant.repository.postgres
      11              :     :as
      12              :     class-template-participant-postgres-repo]
      13              :    [matchscore.domain.class-template.repository.postgres :as class-template-postgres-repo]
      14              :    [matchscore.domain.class.command :as class-command]
      15              :    [matchscore.domain.class.repository.postgres :as class-postgres-repo]
      16              : 
      17              :    [matchscore.domain.event-participant.command :as event-participant-command]
      18              :    [matchscore.domain.event-participant.repository.postgres :as event-participant-postgres-repo]
      19              :    [matchscore.domain.event.command :as event-command]
      20              :    [matchscore.domain.event.repository.postgres :as event-postgres-repo]
      21              :    [matchscore.domain.participant.repository.postgres :as participant-postgres-repo]
      22              :    [matchscore.domain.template-participant.repository.postgres
      23              :     :as
      24              :     template-participant-postgres-repo]
      25              :    [matchscore.domain.template.repository.postgres :as template-postgres-repo]
      26              :    [matchscore.domain.user.repository.postgres :as user-postgres-repo]
      27              :    [matchscore.jobs.telegram-match-notifications :as match-notification-jobs]
      28              :    [matchscore.media.db :as media-db]
      29              :    [matchscore.telegram.notifications-trigger :as notifications-trigger]
      30              :    [matchscore.utils.errors :as utils.errors]
      31              :    [matchscore.utils.nanoid :as nanoid]
      32              :    [matchscore.utils.uuid :as uuid-utils]
      33              :    [next.jdbc :as jdbc]
      34              :    [next.jdbc.result-set :as rs]
      35              :    [next.jdbc.transaction :as transaction]
      36              :    [taoensso.telemere :as t])
      37              :   (:import
      38              :    (java.time Instant)))
      39              : 
      40              : 
      41            4 : (defn- find-current-user
      42              :   [repos current-user-id]
      43           33 :   (if-let [user (user-postgres-repo/find-by-id (:user-postgres-repo repos) current-user-id)]
      44            9 :     (either/right user)
      45            2 :     (either/left
      46            3 :      (utils.errors/build-error
      47              :       :check
      48            5 :       {:code    :error.event/user-not-found
      49              :        :message "Current user not found."}))))
      50              : 
      51              : 
      52            4 : (defn- find-or-create-participant!
      53              :   [repos user-id]
      54           12 :   (let [repo (:participant-postgres-repo repos)
      55           18 :         existing-participant (first (participant-postgres-repo/find-by-user-id repo user-id))]
      56            6 :     (if existing-participant
      57            9 :       (either/right existing-participant)
      58            9 :       (let [save-result (participant-postgres-repo/save!
      59            3 :                          repo
      60           30 :                          {:uuid      (uuid-utils/generate-uuid7-str)
      61            9 :                           :public-id (nanoid/generate 15)
      62              :                           :source    "matchscore"
      63            3 :                           :user-id   user-id
      64              :                           :type      "person"})]
      65           12 :         (if (either/left? save-result)
      66            0 :           (if-let [refetched (first (participant-postgres-repo/find-by-user-id repo user-id))]
      67            0 :             (either/right refetched)
      68            0 :             save-result)
      69            3 :           save-result)))))
      70              : 
      71              : 
      72            4 : (defn- make-tx-repos
      73              :   [repos tx-opts]
      74            6 :   (merge
      75            3 :    repos
      76           42 :    {:event-postgres-repo (event-postgres-repo/make-repository tx-opts)
      77            9 :     :template-postgres-repo (template-postgres-repo/make-repository tx-opts)
      78            9 :     :event-participant-postgres-repo (event-participant-postgres-repo/make-repository tx-opts)
      79            9 :     :class-template-postgres-repo (class-template-postgres-repo/make-repository tx-opts)
      80              :     :class-template-participant-postgres-repo
      81            9 :     (class-template-participant-postgres-repo/make-repository tx-opts)
      82            9 :     :class-postgres-repo (class-postgres-repo/make-repository tx-opts)
      83            9 :     :class-participant-postgres-repo (class-participant-postgres-repo/make-repository tx-opts)
      84            9 :     :participant-postgres-repo (participant-postgres-repo/make-repository tx-opts)
      85            9 :     :template-participant-postgres-repo (template-participant-postgres-repo/make-repository tx-opts)
      86            9 :     :user-postgres-repo (user-postgres-repo/make-repository tx-opts)}))
      87              : 
      88              : 
      89            4 : (defn- -default-class-data
      90              :   [event max-players]
      91           36 :   {:uuid        (uuid-utils/generate-uuid7-str)
      92            9 :    :public-id   (nanoid/generate 15)
      93            9 :    :event-id    (:uuid event)
      94              :    :name        "Default"
      95            3 :    :max-players max-players
      96            9 :    :created-by  (:created-by event)
      97              :    :source      "matchscore"})
      98              : 
      99              : 
     100            4 : (defn- -class-template->-class-data
     101              :   [event class-template]
     102           24 :   {:uuid              (uuid-utils/generate-uuid7-str)
     103            6 :    :public-id         (nanoid/generate 15)
     104            6 :    :event-id          (:uuid event)
     105            6 :    :class-template-id (:uuid class-template)
     106            6 :    :name              (:name class-template)
     107            6 :    :max-players       (:max-players class-template)
     108            6 :    :created-by        (:created-by event)
     109              :    :source            "matchscore"})
     110              : 
     111              : 
     112           16 : (defn- -create-event-class! [tx-ctx class-data] (class-command/create-class! tx-ctx class-data))
     113              : 
     114              : 
     115            4 : (defn- -copy-template-participants!
     116              :   [repos event-id template-id]
     117           12 :   (let [ep-repo  (:event-participant-postgres-repo repos)
     118            9 :         tp-repo  (:template-participant-postgres-repo repos)
     119           12 :         t-parts  (template-participant-postgres-repo/find-by-template-id tp-repo template-id)
     120            6 :         existing (set
     121            9 :                   (map
     122              :                    :participant-id
     123           12 :                    (event-participant-postgres-repo/find-by-event-id ep-repo event-id)))
     124           24 :         to-copy  (remove #(contains? existing (:participant-id %)) t-parts)
     125            6 :         now      (Instant/now)]
     126            6 :     (reduce
     127            3 :      (fn [acc tp]
     128           16 :       (c/mlet [count acc]
     129            4 :         (c/fmap
     130            8 :          (constantly (inc count))
     131            4 :          (event-participant-postgres-repo/save!
     132            2 :           ep-repo
     133           22 :           {:event-id       event-id
     134            6 :            :participant-id (:participant-id tp)
     135              :            :status         "registered"
     136           14 :            :roles          (or (:roles tp) [])
     137           14 :            :extra          (or (:extra tp) {})
     138            2 :            :registered-at  now
     139              :            :source         "matchscore"}))))
     140            9 :      (either/right 0)
     141            3 :      to-copy)))
     142              : 
     143              : 
     144            4 : (defn- -template-class-participant->-class-participant
     145              :   [now class-id tp]
     146           11 :   {:class-id       class-id
     147            3 :    :participant-id (:participant-id tp)
     148            3 :    :seed           (:seed tp)
     149              :    :status         "registered"
     150            7 :    :extra          (or (:extra tp) {})
     151            1 :    :registered-at  now
     152              :    :source         "matchscore"})
     153              : 
     154              : 
     155            4 : (defn- -copy-template-class-participants!
     156              :   "Copies participants from each template class into its newly-created event class.
     157              :    `classes` is a seq of created event-class data maps carrying :uuid and
     158              :    :class-template-id. Returns Either<Error, {:inserted-count int}>."
     159              :   [repos classes]
     160           12 :   (let [cp-repo      (:class-participant-postgres-repo repos)
     161            9 :         ctp-repo     (:class-template-participant-postgres-repo repos)
     162           12 :         tmpl-classes (filter :class-template-id classes)
     163            9 :         by-ct        (group-by
     164            5 :                       #(str (:class-template-id %))
     165            6 :                       (class-template-participant-postgres-repo/find-by-class-template-ids
     166            3 :                        ctp-repo
     167           12 :                        (mapv :class-template-id tmpl-classes)))
     168            6 :         now          (Instant/now)
     169          119 :         rows         (for [class tmpl-classes
     170           14 :                            tp    (get by-ct (str (:class-template-id class)))]
     171            7 :                        (-template-class-participant->-class-participant now (:uuid class) tp))]
     172           12 :     (if (seq rows)
     173            4 :       (class-participant-postgres-repo/bulk-insert! cp-repo rows)
     174           15 :       (either/right {:inserted-count 0}))))
     175              : 
     176              : 
     177            4 : (defn- -create-initial-classes!
     178              :   "Creates event classes from the template's class templates (or a single default
     179              :    class when there is no template). Returns Either<Error, [class-data]> where each
     180              :    class-data carries :uuid and :class-template-id for downstream participant copying."
     181              :   [tx-ctx event default-class-max-players]
     182           18 :   (let [class-templates (when (:template-id event)
     183            6 :                           (class-template-postgres-repo/find-by-template-id
     184           18 :                            (get-in tx-ctx [:repos :class-template-postgres-repo])
     185            9 :                            (:template-id event)))]
     186           12 :     (if (seq class-templates)
     187            4 :       (reduce
     188            2 :        (fn [acc class-template]
     189           44 :         (c/mlet [classes    acc
     190           14 :                  class-data (either/right (-class-template->-class-data event class-template))
     191            8 :                  _ (-create-event-class! tx-ctx class-data)]
     192           12 :           (c/return (conj classes class-data))))
     193            6 :        (either/right [])
     194            2 :        class-templates)
     195            6 :       (c/fmap
     196            9 :        (constantly [])
     197           21 :        (-create-event-class! tx-ctx (-default-class-data event default-class-max-players))))))
     198              : 
     199              : 
     200            4 : (defn- inherited-event-settings
     201              :   [settings]
     202            6 :   (apply
     203            3 :    dissoc
     204            3 :    settings
     205           27 :    [:telegram-match-notifications-enabled
     206              :     :telegram_match_notifications_enabled
     207              :     "telegram-match-notifications-enabled"
     208              :     "telegram_match_notifications_enabled"
     209              :     :payment-reminder
     210              :     :payment_reminder
     211              :     "payment-reminder"
     212              :     "payment_reminder"]))
     213              : 
     214              : 
     215            4 : (defn- -resolve-template-settings
     216              :   "Copies template defaults that the event did not override. Match notification
     217              :    settings remain inherited so later template changes continue to affect events."
     218              :   [repos event-data]
     219            3 :   (if
     220           15 :     (and
     221            9 :      (:template-id event-data)
     222           36 :      (some #(not (contains? event-data %)) [:settings :score-entry-mode :score-entry-default]))
     223            9 :     (let [tmpl (template-postgres-repo/find-by-id
     224            9 :                 (:template-postgres-repo repos)
     225            9 :                 (:template-id event-data)
     226            3 :                 {})]
     227            6 :       (if tmpl
     228            6 :         (either/right
     229           33 :          (cond-> event-data
     230           27 :            (not (contains? event-data :settings))         (assoc :settings
     231            6 :                                                            (inherited-event-settings
     232            9 :                                                             (:settings tmpl)))
     233              : 
     234           27 :            (not (contains? event-data :score-entry-mode)) (assoc :score-entry-mode
     235            9 :                                                            (:score-entry-mode tmpl))
     236              : 
     237           21 :            (not (contains? event-data :score-entry-default)) (assoc :score-entry-default
     238            9 :                                                               (:score-entry-default tmpl))))
     239            0 :         (either/left
     240            0 :          (utils.errors/build-error
     241              :           :check
     242            0 :           {:code    :error.template/not-found
     243              :            :message "Template not found."}))))
     244            9 :     (either/right event-data)))
     245              : 
     246              : 
     247            4 : (defn create-in-transaction!
     248              :  "Create the complete event aggregate on an existing transaction. The caller commits
     249              :    before sending notifications. Shared by manual and automatic creation."
     250              :  [{:keys [repos pg]
     251              :    :as   ctx}
     252              :   event-data
     253              :   current-user-id]
     254           30 :  (binding [transaction/*nested-tx* :ignore]
     255           33 :    (when (:template-id event-data) (automation-db/lock-template! pg (:template-id event-data)))
     256           20 :    (let [default-class-max-players (or
     257            9 :                                     (:default-class-max-players event-data)
     258              :                                     ;; Compatibility for clients deployed before the
     259              :                                     ;; event-level capacity was removed.
     260            3 :                                     (:max-players event-data))
     261           15 :          event-data (dissoc event-data :default-class-max-players :max-players)
     262           18 :          tx-opts (jdbc/with-options pg {:builder-fn rs/as-kebab-maps})
     263           12 :          tx-repos (make-tx-repos repos tx-opts)
     264           15 :          tx-ctx (assoc ctx :repos tx-repos)
     265              :          result
     266          201 :          (c/mlet [event-data  (-resolve-template-settings tx-repos event-data)
     267           33 :                   user        (find-current-user tx-repos current-user-id)
     268           24 :                   event       (event-command/create-event!
     269            3 :                                tx-ctx
     270           18 :                                (assoc event-data
     271            6 :                                 :uuid       (uuid-utils/generate-uuid7-str)
     272            6 :                                 :public-id  (nanoid/generate)
     273            9 :                                 :created-by (:uuid user)))
     274           18 :                   _ (do
     275            9 :                       (media-db/attach-created-gallery!
     276            3 :                        pg
     277              :                        :event
     278            9 :                        (:uuid event)
     279            9 :                        (:uuid user)
     280            3 :                        event-data)
     281            9 :                       (either/right nil))
     282           27 :                   classes     (-create-initial-classes! tx-ctx event default-class-max-players)
     283           27 :                   participant (find-or-create-participant! tx-repos (:uuid user))
     284           12 :                   _ (event-participant-command/register-participant!
     285            3 :                      tx-ctx
     286           39 :                      {:event-id       (:uuid event)
     287            9 :                       :participant-id (:uuid participant)
     288              :                       :status         "registered"
     289            6 :                       :roles          ["admin"]
     290            3 :                       :extra          {}
     291            6 :                       :registered-at  (Instant/now)
     292              :                       :source         "matchscore"})
     293           15 :                   _ (if (:template-id event)
     294           27 :                       (-copy-template-participants! tx-repos (:uuid event) (:template-id event))
     295            9 :                       (either/right nil))
     296           12 :                   _ (if (:template-id event)
     297           12 :                       (-copy-template-class-participants! tx-repos classes)
     298            9 :                       (either/right nil))]
     299            6 :            (c/return
     300           12 :             (if (:template-id event)
     301           12 :               (assoc event
     302           27 :                :host-user-id (host-db/inherit-template-host! pg (:uuid event) (:template-id event)))
     303            3 :               event)))]
     304           12 :      (if (either/left? result)
     305           21 :        (throw (ex-info "Event creation rolled back" {::result result}))
     306            9 :        (c/extract result)))))
     307              : 
     308              : 
     309            4 : (defn notify-created!
     310              :  "Run notification side effects only after the event transaction commits."
     311              :  [ctx event]
     312           15 :  (when (:template-id event)
     313            3 :    (try
     314           18 :      (notifications-trigger/trigger-now! ctx (:uuid event))
     315              :      (catch Throwable e
     316           92 :        (t/log!
     317              :         :error
     318            5 :         {:message    "Failed to enqueue event participants refresh notification"
     319            3 :          :event-uuid (:uuid event)
     320            1 :          :exception  e}))))
     321           24 :  (match-notification-jobs/schedule-event-sync! (:goose ctx) (:uuid event)))
     322              : 
     323              : 
     324            4 : (defn execute!
     325              :  "Creates an event, its classes and participants atomically."
     326              :  [{:keys [pg]
     327              :    :as   ctx}
     328              :   event-data
     329              :   current-user-id]
     330            6 :  (let [result (try
     331            6 :                 (either/right
     332           12 :                  (jdbc/with-transaction
     333            3 :                   [tx pg]
     334           27 :                   (create-in-transaction! (assoc ctx :pg tx) event-data current-user-id)))
     335              :                 (catch clojure.lang.ExceptionInfo e
     336           36 :                   (if (contains? (ex-data e) ::result) (::result (ex-data e)) (throw e))))]
     337           33 :    (when (either/right? result) (notify-created! ctx (c/extract result)))
     338            3 :    result))
        

Generated by: LCOV version 2.0-1