LCOV - code coverage report
Current view: top level - matchscore/jobs - telegram_notifications.clj Coverage Total Hit
Test: lcov.info Lines: 67.3 % 563 379
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.jobs.telegram-notifications
       2              :   (:require
       3              :    [cats.core :as c]
       4              :    [cats.monad.either :as either]
       5              :    [cheshire.core :as json]
       6              :    [honey.sql :as sql]
       7              :    [matchscore.application.scoreboard.groups :as scoreboard-groups]
       8              :    [matchscore.application.scoreboard.participants :as scoreboard-participants]
       9              :    [matchscore.domain.bracket-match-slot.repository.postgres :as bracket-match-slot-postgres-repo]
      10              :    [matchscore.domain.bracket-match.repository.postgres :as bracket-match-postgres-repo]
      11              :    [matchscore.domain.bracket-round.repository.postgres :as bracket-round-postgres-repo]
      12              :    [matchscore.domain.bracket.repository.postgres :as bracket-postgres-repo]
      13              :    [matchscore.domain.class.query :as class-query]
      14              :    [matchscore.domain.draw.query :as draw-query]
      15              :    [matchscore.domain.event-telegram-link.repository.postgres :as event-telegram-link-postgres-repo]
      16              :    [matchscore.domain.event.repository.postgres :as event-postgres-repo]
      17              :    [matchscore.domain.resource.query :as resource-query]
      18              :    [matchscore.domain.stage.query :as stage-query]
      19              :    [matchscore.domain.telegram-chat-message.repository.postgres
      20              :     :as
      21              :     telegram-chat-message-postgres-repo]
      22              :    [matchscore.domain.telegram-link.query :as telegram-link-query]
      23              :    [matchscore.domain.template-telegram-link.repository.postgres
      24              :     :as
      25              :     template-telegram-link-postgres-repo]
      26              :    [matchscore.jobs.scheduler :as scheduler]
      27              :    [matchscore.jobs.telegram-cleanup :as telegram-cleanup]
      28              :    [matchscore.telegram.changelog :as changelog]
      29              :    [matchscore.telegram.daily-reminder :as daily-reminder]
      30              :    [matchscore.telegram.draws-revision :as draws-revision]
      31              :    [matchscore.telegram.event-lock :as event-lock]
      32              :    [matchscore.telegram.formatting :as formatting]
      33              :    [matchscore.telegram.localization :as l10n]
      34              :    [matchscore.telegram.messages :as messages]
      35              :    [matchscore.utils.db :as utils.db]
      36              :    [next.jdbc :as jdbc]
      37              :    [taoensso.carmine :as car]
      38              :    [taoensso.telemere :as t]
      39              :    [telegrambot-lib.core :as tbot])
      40              :   (:import
      41              :    (java.time Instant)))
      42              : 
      43              : 
      44           20 : (def ^:private visible-statuses #{"registered" "confirmed" "checked_in"})
      45              : 
      46              : 
      47            4 : (def ^:private participant-telegram-id
      48              :   "Telegram account of a listed participant. Fake users carry made-up ids, so they
      49              :    are never linked."
      50           32 :   [[:case [:not :u.is_fake] :u.telegram_id] :telegram-id])
      51              : 
      52              : 
      53            4 : (defn- load-classes-with-participants
      54              :   "Loads every class of an event plus its registered participants, grouped per
      55              :    class and ordered by class name (then by registration time within a class).
      56              :    Also appends event participants that are not assigned to any class so they
      57              :    remain visible in Telegram even before class placement.
      58              :    Names are coalesced from matchscore users and rankedin_users so imported
      59              :    participants do not render as empty slots.
      60              : 
      61              :    Returns a vec of
      62              :      {:uuid ... :public-id ... :name ... :max-players ...
      63              :       :participants [{:name ... :telegram-id ...}]}
      64              :    plus an optional {:unassigned? true :participants [...]} group."
      65              :   [pg event-uuid]
      66            2 :   (let [rows       (->>
      67            2 :                      (jdbc/execute!
      68            1 :                       pg
      69            2 :                       (sql/format
      70           10 :                        {:select    [[:c.uuid :class-uuid]
      71            3 :                                     [:c.public_id :class-public-id]
      72            3 :                                     [:c.name :class-name]
      73            3 :                                     [:c.max_players :class-max-players]
      74            3 :                                     [:cp.participant_id :participant-id]
      75            1 :                                     participant-telegram-id
      76            5 :                                     [[:coalesce
      77              :                                       :u.name
      78            8 :                                       [:nullif [:concat_ws " " :ru.first_name :ru.last_name] ""]]
      79              :                                      :name]]
      80            4 :                         :from      [[:event_classes :c]]
      81            4 :                         :left-join [[:event_class_participants :cp]
      82            2 :                                     [:and
      83            4 :                                      [:= :cp.class_id :c.uuid]
      84            6 :                                      [:in :cp.status (vec visible-statuses)]]
      85            3 :                                     [:participants :p]
      86            4 :                                     [:= :p.uuid :cp.participant_id]
      87            3 :                                     [:users :u]
      88            4 :                                     [:= :u.uuid :p.user_id]
      89            3 :                                     [:rankedin_users :ru]
      90            4 :                                     [:= :ru.uuid :p.user_id_rankedin]]
      91            7 :                         :where     [:= :c.event_id [:cast event-uuid :uuid]]
      92            4 :                         :order-by  [[:c.name :asc]
      93            3 :                                     [:cp.registered_at :asc]
      94            3 :                                     [:cp.participant_id :asc]]}))
      95            2 :                      (mapv utils.db/unqualify-keys))
      96            6 :         order      (distinct (map :class-uuid rows))
      97            2 :         groups     (reduce
      98            1 :                     (fn
      99              :                      [acc
     100              :                       {:keys [class-uuid
     101              :                               class-public-id
     102              :                               class-name
     103              :                               class-max-players
     104              :                               participant-id
     105              :                               telegram-id
     106              :                               name]}]
     107            0 :                      (let [g (get
     108            0 :                               acc
     109            0 :                               class-uuid
     110            0 :                               {:uuid         (some->
     111            0 :                                                class-uuid
     112            0 :                                                str)
     113            0 :                                :public-id    class-public-id
     114            0 :                                :name         class-name
     115            0 :                                :max-players  class-max-players
     116            0 :                                :participants []})]
     117            0 :                        (assoc acc
     118            0 :                         class-uuid (cond-> g
     119            0 :                                      participant-id (update
     120              :                                                      :participants
     121            0 :                                                      conj
     122            0 :                                                      {:name        name
     123            0 :                                                       :telegram-id telegram-id})))))
     124            1 :                     {}
     125            1 :                     rows)
     126            1 :         admins     (->>
     127            2 :                      (jdbc/execute!
     128            1 :                       pg
     129            2 :                       (sql/format
     130           11 :                        {:select    [[:ep.participant_id :participant-id]
     131            1 :                                     participant-telegram-id
     132            5 :                                     [[:coalesce
     133              :                                       :u.name
     134            8 :                                       [:nullif [:concat_ws " " :ru.first_name :ru.last_name] ""]]
     135              :                                      :name]]
     136            4 :                         :from      [[:event_participants :ep]]
     137            8 :                         :join      [[:participants :p] [:= :p.uuid :ep.participant_id]]
     138            4 :                         :left-join [[:users :u]
     139            4 :                                     [:= :u.uuid :p.user_id]
     140            3 :                                     [:rankedin_users :ru]
     141            4 :                                     [:= :ru.uuid :p.user_id_rankedin]]
     142            2 :                         :where     [:and
     143            7 :                                     [:= :ep.event_id [:cast event-uuid :uuid]]
     144            6 :                                     [:in :ep.status (vec visible-statuses)]
     145            3 :                                     [:raw "jsonb_exists(ep.roles, 'admin')"]]
     146            4 :                         :order-by  [[:ep.registered_at :asc]]}))
     147            3 :                      (mapv utils.db/unqualify-keys)
     148            8 :                      (mapv #(select-keys % [:name :telegram-id])))
     149            1 :         unassigned (->>
     150            2 :                      (jdbc/execute!
     151            1 :                       pg
     152            2 :                       (sql/format
     153           11 :                        {:select    [[:ep.participant_id :participant-id]
     154            1 :                                     participant-telegram-id
     155            5 :                                     [[:coalesce
     156              :                                       :u.name
     157            8 :                                       [:nullif [:concat_ws " " :ru.first_name :ru.last_name] ""]]
     158              :                                      :name]]
     159            4 :                         :from      [[:event_participants :ep]]
     160            8 :                         :join      [[:participants :p] [:= :p.uuid :ep.participant_id]]
     161            4 :                         :left-join [[:users :u]
     162            4 :                                     [:= :u.uuid :p.user_id]
     163            3 :                                     [:rankedin_users :ru]
     164            4 :                                     [:= :ru.uuid :p.user_id_rankedin]]
     165            2 :                         :where     [:and
     166            7 :                                     [:= :ep.event_id [:cast event-uuid :uuid]]
     167            6 :                                     [:in :ep.status (vec visible-statuses)]
     168            5 :                                     [:not [:raw "jsonb_exists(ep.roles, 'admin')"]]
     169            2 :                                     [:not
     170            9 :                                      [:exists {:select [1]
     171            4 :                                                :from   [[:event_class_participants :cp]]
     172            4 :                                                :join   [[:event_classes :c]
     173            4 :                                                         [:= :c.uuid :cp.class_id]]
     174            2 :                                                :where  [:and
     175            4 :                                                         [:= :cp.participant_id :ep.participant_id]
     176            7 :                                                         [:= :c.event_id [:cast event-uuid :uuid]]
     177            6 :                                                         [:in :cp.status (vec visible-statuses)]]}]]]
     178            4 :                         :order-by  [[:ep.registered_at :asc]]}))
     179            3 :                      (mapv utils.db/unqualify-keys)
     180            8 :                      (mapv #(select-keys % [:name :telegram-id])))]
     181           10 :     (cond-> []
     182            6 :       (seq admins) (conj
     183            4 :                     {:admins?      true
     184            1 :                      :participants admins})
     185            7 :       true         (into (mapv groups order))
     186            4 :       (seq unassigned) (conj
     187            4 :                         {:unassigned?  true
     188            1 :                          :participants unassigned}))))
     189              : 
     190              : 
     191            4 : (defn- require-saved!
     192              :   [result]
     193            4 :   (when (either/left? result)
     194            0 :     (throw (ex-info "Failed to save Telegram message tracking" {:error (c/extract result)})))
     195            1 :   result)
     196              : 
     197              : 
     198           12 : (defn- main-post? [message] (contains? #{"participants_post" "draws_post"} (:kind message)))
     199              : 
     200              : 
     201            4 : (defn- main-posts
     202              :   "Tracked, undeleted main posts of this event, oldest first. A link narrows them to
     203              :    its destination."
     204              :   ([repo event]
     205            2 :    (vec
     206            3 :     (sort-by
     207              :      :uuid
     208            2 :      (filter
     209            1 :       main-post?
     210            6 :       (telegram-chat-message-postgres-repo/find-undeleted-for-event repo (:uuid event))))))
     211              :   ([repo event {:keys [chat-id thread-id]}]
     212           20 :    (filterv #(and (= chat-id (:chat-id %)) (= thread-id (:thread-id %))) (main-posts repo event))))
     213              : 
     214              : 
     215            4 : (defn- delete-replaced!
     216              :   "Removes the posts a fresh post supersedes. A failed delete must not fail the
     217              :    job: the fresh post is already sent, so a retry would send another one. A post
     218              :    Telegram refuses to delete stays tracked, so the next post retries it and
     219              :    completion cleanup can still turn it into the closed summary."
     220              :   [repo telegram-bot priors]
     221            1 :   (let [deleted
     222            2 :         (filterv
     223            1 :          (fn [{:keys [chat-id message-id]}]
     224            2 :           (try
     225            2 :             (messages/request!
     226            1 :              tbot/delete-message
     227            1 :              telegram-bot
     228            4 :              {:chat_id    chat-id
     229            1 :               :message_id message-id})
     230              :             true
     231              :             (catch clojure.lang.ExceptionInfo e
     232            6 :               (or
     233            4 :                (messages/error-matches? e "message to delete not found")
     234              :                (do
     235           92 :                  (t/log!
     236              :                   :warn
     237            6 :                   {:message    "Failed to delete replaced Telegram main post"
     238            1 :                    :chat-id    chat-id
     239            1 :                    :message-id message-id
     240            1 :                    :exception  e})
     241              :                  false)))))
     242            1 :          priors)]
     243            9 :     (require-saved! (telegram-chat-message-postgres-repo/mark-deleted! repo (mapv :uuid deleted)))))
     244              : 
     245              : 
     246            4 : (defn- destination-refused?
     247              :   "True for failures that say this chat will not take the post (bot removed, no
     248              :    rights, chat or topic gone, rejected content). Rate limits, Telegram outages
     249              :    and transport errors are transient and left to the job retry."
     250              :   [exception]
     251           47 :   (let [code (:error_code (ex-data exception))] (and code (<= 400 code 499) (not= 429 code))))
     252              : 
     253              : 
     254            4 : (defn record-delivery-failure!
     255              :  "Remembers on the link why Telegram refused the post, so the organizer sees the
     256              :    chat stopped receiving posts. Best effort: the caller rethrows the send error
     257              :    either way."
     258              :  [repos {:keys [kind uuid chat-id]} exception]
     259            8 :  (let [{:keys [error_code description]} (ex-data exception)
     260            8 :        failure {:code        error_code
     261           16 :                 :description (or description (ex-message exception))}
     262           10 :        result  (when (destination-refused? exception)
     263            6 :                  (case kind
     264            4 :                    :event    (event-telegram-link-postgres-repo/record-delivery-failure!
     265            6 :                               (:event-telegram-link-postgres-repo repos)
     266            2 :                               uuid
     267            2 :                               failure)
     268            0 :                    :template (template-telegram-link-postgres-repo/record-delivery-failure!
     269            0 :                               (:template-telegram-link-postgres-repo repos)
     270            0 :                               uuid
     271            0 :                               failure)
     272              :                    nil))]
     273           18 :    (when (and result (either/left? result))
     274            0 :      (t/log!
     275              :       :warn
     276            0 :       {:message "Failed to record Telegram delivery failure"
     277            0 :        :chat-id chat-id
     278            0 :        :error   (c/extract result)}))))
     279              : 
     280              : 
     281            4 : (defn- link-users!
     282              :   "Edits the participant profile links into a just-sent post. A mention notifies the
     283              :    user only in a newly sent message, never in an edit, so sending plain names first
     284              :    keeps every re-post from pinging the whole roster. Best effort: when the edit
     285              :    fails the plain post stays and the job goes on. Returns the text now shown."
     286              :   [telegram-bot chat-id message-id {:keys [text linked-text]} reply-markup-json]
     287            4 :   (if-not linked-text
     288            1 :     text
     289            1 :     (try
     290            2 :       (case
     291            2 :         (messages/edit!
     292            1 :          telegram-bot
     293            9 :          {:chat_id      chat-id
     294            1 :           :message_id   message-id
     295            1 :           :text         linked-text
     296              :           :parse_mode   "HTML"
     297            3 :           :link_preview_options {:is_disabled true}
     298            1 :           :reply_markup reply-markup-json})
     299            1 :         :ok      linked-text
     300            0 :         :missing text)
     301              :       (catch clojure.lang.ExceptionInfo e
     302           92 :         (t/log!
     303              :          :warn
     304            6 :          {:message    "Failed to add participant links to Telegram main post"
     305            1 :           :chat-id    chat-id
     306            1 :           :message-id message-id
     307            1 :           :exception  e})
     308            1 :         text))))
     309              : 
     310              : 
     311            4 : (defn- send-to-link
     312              :   "Sends the event's main post as a fresh message and deletes the ones it replaces,
     313              :    so every update returns the list to the bottom of the chat. A template link may
     314              :    point to another event; only this event's posts are replaced. A refused send is
     315              :    recorded on the link before it is rethrown; a successful one clears it."
     316              :   [repos
     317              :    telegram-bot
     318              :    event
     319              :    {:keys [text reply-markup audit-kind content-revision]
     320              :     :as   post}
     321              :    link]
     322            2 :   (let [{:keys [kind uuid chat-id thread-id]} link
     323            3 :         repo       (:telegram-chat-message-postgres-repo repos)
     324            5 :         audit-kind (or audit-kind "participants_post")
     325            5 :         priors     (main-posts repo event link)
     326           10 :         markup     (json/generate-string (or reply-markup {:inline_keyboard []}))
     327            8 :         params     {:chat_id      chat-id
     328            1 :                     :text         text
     329              :                     :parse_mode   "HTML"
     330            3 :                     :link_preview_options {:is_disabled true}
     331            1 :                     :reply_markup markup}
     332            1 :         result     (try
     333            2 :                      (messages/request!
     334            1 :                       tbot/send-message
     335            1 :                       telegram-bot
     336            5 :                       (cond-> params thread-id (assoc :message_thread_id thread-id)))
     337              :                      (catch clojure.lang.ExceptionInfo e
     338            5 :                        (record-delivery-failure! repos link e)
     339            2 :                        (throw e)))
     340            6 :         message-id (get-in result [:result :message_id])]
     341            3 :     (when-not message-id
     342            0 :       (throw (ex-info "Telegram send returned no message id" {:chat-id chat-id})))
     343            2 :     (require-saved!
     344            2 :      (telegram-chat-message-postgres-repo/record!
     345            1 :       repo
     346           11 :       {:chat-id          chat-id
     347            1 :        :thread-id        thread-id
     348            1 :        :message-id       message-id
     349              :        :sender-kind      "bot"
     350            1 :        :kind             audit-kind
     351            7 :        :text             (link-users! telegram-bot chat-id message-id post markup)
     352            1 :        :content-revision content-revision
     353            3 :        :event-id         (:uuid event)}))
     354            5 :     (delete-replaced! repo telegram-bot priors)
     355            2 :     (require-saved!
     356            3 :      (case kind
     357            2 :        :event    (event-telegram-link-postgres-repo/update-last-message-id!
     358            3 :                   (:event-telegram-link-postgres-repo repos)
     359            1 :                   uuid
     360            1 :                   message-id)
     361            2 :        :template (template-telegram-link-postgres-repo/update-last-message-id!
     362            3 :                   (:template-telegram-link-postgres-repo repos)
     363            1 :                   uuid
     364            1 :                   message-id)))))
     365              : 
     366              : 
     367            4 : (defn- participants-post
     368              :   [{:keys [pg repos config]} event]
     369            4 :   (assoc
     370            2 :    (formatting/format-participants-message
     371            1 :     event
     372            6 :     (load-classes-with-participants pg (:uuid event))
     373            4 :     (l10n/message-locale repos event)
     374            6 :     (get-in config [:telegram :bot-username])
     375            6 :     (changelog/find-for-event pg (:uuid event)))
     376              :    :audit-kind "participants_post"))
     377              : 
     378              : 
     379            4 : (defn post-participants-job
     380              :  "Goose job: fetches the current participant list for the given event and sends
     381              :    it as a fresh Telegram message in every linked chat, deleting the post it
     382              :    replaces.
     383              : 
     384              :    Uses a per-event Redis lock to prevent concurrent runs.
     385              :    Sets a 'dirty' flag when skipped so the final release re-queues the job."
     386              :  [system-components event-uuid]
     387            2 :  (event-lock/with-lock
     388            3 :   (:pg system-components)
     389            1 :   event-uuid
     390            1 :   (fn []
     391            2 :    (let [{:keys [pg redis repos goose telegram-bot]} system-components
     392            6 :          ctx         {:pg    pg
     393            1 :                       :redis redis
     394            1 :                       :repos repos
     395            1 :                       :goose goose}
     396            4 :          lock-key    (str "tg:notify:lock:" event-uuid)
     397            4 :          dirty-key   (str "tg:notify:dirty:" event-uuid)
     398            4 :          lock-token  (str (random-uuid))
     399           43 :          lock-result (car/wcar redis (car/set lock-key lock-token :nx :ex 30))]
     400            6 :      (if-not (= "OK" lock-result)
     401            1 :        (do
     402           42 :          (car/wcar redis (car/set dirty-key "1" :ex 60))
     403           22 :          (t/log! :debug (str "TG notify job skipped (locked), marked dirty for event " event-uuid)))
     404            1 :        (try
     405           96 :          (t/log! :info (str "Starting TG participant broadcast for event " event-uuid))
     406            4 :          (let [event-repo (:event-postgres-repo repos)
     407            8 :                event      (event-postgres-repo/find-by-id event-repo event-uuid {:joins [:club]})
     408            2 :                links      (when
     409           14 :                             (and event (not (contains? #{"completed" "cancelled"} (:state event))))
     410            4 :                             (telegram-link-query/resolve-links-for-event ctx event))]
     411            4 :            (if (seq links)
     412            5 :              (let [post (participants-post system-components event)]
     413           33 :                (doseq [link links] (send-to-link repos telegram-bot event post link))
     414           92 :                (t/log!
     415              :                 :info
     416            8 :                 (str "Sent TG broadcast for event " event-uuid " to " (count links) " chat(s)")))
     417           22 :              (t/log! :debug (str "No TG links for event " event-uuid ", skipping"))))
     418              :          (finally
     419           35 :           (car/wcar
     420            1 :            redis
     421            4 :            (car/eval
     422              :             "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end"
     423              :             1
     424            1 :             lock-key
     425            1 :             lock-token))
     426           40 :           (let [dirty (car/wcar redis (car/get dirty-key))]
     427            3 :             (when dirty
     428           39 :               (car/wcar redis (car/del dirty-key))
     429           22 :               (t/log! :debug (str "TG notify re-queued for event " event-uuid " (was dirty)"))
     430            3 :               (scheduler/schedule-job
     431            1 :                goose
     432              :                `post-participants-job
     433            4 :                {:delay-seconds 2
     434            2 :                 :args [event-uuid]}))))))))))
     435              : 
     436              : 
     437            4 : (defn- load-bracket-draw-matchups
     438              :   "Loads round-1 matchups for a single bracket draw.
     439              :    Returns a vec of {:type 'bracket' :name <bracket-name> :matches [{:home-id pid :away-id pid}]}
     440              :    entries, one per bracket within the draw."
     441              :   [repos draw-uuid]
     442            0 :   (let [bracket-repo   (:bracket-postgres-repo repos)
     443            0 :         round-repo     (:bracket-round-postgres-repo repos)
     444            0 :         match-repo     (:bracket-match-postgres-repo repos)
     445            0 :         slot-repo      (:bracket-match-slot-postgres-repo repos)
     446            0 :         brackets       (bracket-postgres-repo/find-by-draw-id bracket-repo draw-uuid)
     447            0 :         bracket-ids    (mapv :uuid brackets)
     448            0 :         all-rounds     (bracket-round-postgres-repo/find-by-bracket-ids round-repo bracket-ids)
     449            0 :         round1-ids     (->>
     450            0 :                          all-rounds
     451            0 :                          (filter #(= 1 (:round-number %)))
     452            0 :                          (mapv :uuid))
     453            0 :         all-matches    (bracket-match-postgres-repo/find-by-bracket-round-ids match-repo round1-ids)
     454            0 :         match-ids      (mapv :uuid all-matches)
     455            0 :         all-slots      (if (seq match-ids)
     456            0 :                          (bracket-match-slot-postgres-repo/find-by-bracket-match-ids
     457            0 :                           slot-repo
     458            0 :                           match-ids)
     459            0 :                          [])
     460            0 :         slots-by-match (group-by :bracket-match-id all-slots)]
     461            0 :     (mapv
     462            0 :      (fn [bracket]
     463            0 :       (let [bracket-id    (str (:uuid bracket))
     464            0 :             br-round1-ids (->>
     465            0 :                             all-rounds
     466            0 :                             (filter
     467            0 :                              #(and (= (str (:bracket-id %)) bracket-id) (= 1 (:round-number %))))
     468            0 :                             (mapv (comp str :uuid)))
     469            0 :             br-round1-set (set br-round1-ids)
     470            0 :             br-matches    (->>
     471            0 :                             all-matches
     472            0 :                             (filter #(contains? br-round1-set (str (:bracket-round-id %))))
     473            0 :                             (sort-by :match-number))]
     474            0 :         {:type    "bracket"
     475            0 :          :name    (:name bracket)
     476            0 :          :matches (mapv
     477            0 :                    (fn [match]
     478            0 :                     (let [match-slots (get slots-by-match (:uuid match) [])
     479            0 :                           home-slot   (first (filter #(= 1 (:slot %)) match-slots))
     480            0 :                           away-slot   (first (filter #(= 2 (:slot %)) match-slots))]
     481            0 :                       {:home-id (some->
     482            0 :                                   (:participant-id home-slot)
     483            0 :                                   str)
     484            0 :                        :away-id (some->
     485            0 :                                   (:participant-id away-slot)
     486            0 :                                   str)}))
     487            0 :                    br-matches)}))
     488            0 :      brackets)))
     489              : 
     490              : 
     491            4 : (defn- load-classes-with-stage1-draws
     492              :   "Loads every class of an event together with its stage-1 draw compositions.
     493              : 
     494              :    For group draws, participants are listed in their initial slot order per group.
     495              :    For bracket draws, round-1 matchups show who plays whom (initial seeding).
     496              :    Participant names are coalesced via scoreboard-participants/load-enriched-by-ids.
     497              : 
     498              :    Returns a vec of:
     499              :      {:name <class-name>
     500              :       :draws [{:type 'group'   :name <group-name>   :slots   [{:place N :name str-or-nil} ...]}
     501              :               {:type 'bracket' :name <bracket-name> :matches [{:home str-or-nil :away str-or-nil} ...]}]}"
     502              :   [repos event-uuid]
     503            4 :   (let [class-repo (:class-postgres-repo repos)
     504            3 :         stage-repo (:stage-postgres-repo repos)
     505            3 :         draw-repo  (:draw-postgres-repo repos)
     506            4 :         classes    (class-query/get-classes-by-event-id class-repo event-uuid)]
     507            4 :     (if (empty? classes)
     508            1 :       []
     509            0 :       (let [class-ids     (mapv (comp str :uuid) classes)
     510            0 :             all-stages    (stage-query/get-stages-by-class-ids stage-repo class-ids)
     511            0 :             stage1-by-cid (into
     512            0 :                            {}
     513            0 :                            (map
     514            0 :                             (fn [[cid stages]]
     515            0 :                              [cid (first (sort-by :order stages))]))
     516            0 :                            (group-by (comp str :class-id) all-stages))
     517            0 :             stage1-ids    (distinct
     518            0 :                            (keep
     519            0 :                             #(some->
     520              :                                %
     521              :                                :uuid
     522            0 :                                str)
     523            0 :                             (vals stage1-by-cid)))
     524            0 :             all-draws     (if (seq stage1-ids)
     525            0 :                             (draw-query/get-draws-by-stage-ids draw-repo stage1-ids)
     526            0 :                             [])
     527            0 :             draws-by-sid  (group-by (comp str :stage-id) all-draws)
     528              :             ;; Compute raw draw data (participant IDs, not yet resolved to names)
     529            0 :             raw-by-cid    (into
     530            0 :                            {}
     531            0 :                            (map
     532            0 :                             (fn [class]
     533            0 :                              (let [cid    (str (:uuid class))
     534            0 :                                    stage1 (get stage1-by-cid cid)
     535            0 :                                    sid    (when stage1 (str (:uuid stage1)))
     536            0 :                                    draws  (get draws-by-sid sid [])]
     537            0 :                                [cid
     538            0 :                                 (mapcat
     539            0 :                                  (fn [draw]
     540            0 :                                   (case (:type draw)
     541            0 :                                     "group"   (mapv
     542            0 :                                                (fn [g]
     543            0 :                                                 {:type  "group"
     544            0 :                                                  :name  (:name g)
     545            0 :                                                  :slots (mapv
     546            0 :                                                          (fn [{:keys [place participant-id]}]
     547            0 :                                                           {:place place
     548            0 :                                                            :pid   participant-id})
     549            0 :                                                          (:results g))})
     550            0 :                                                (scoreboard-groups/compute-group-placements
     551            0 :                                                 repos
     552            0 :                                                 (:uuid draw)))
     553            0 :                                     "bracket" (load-bracket-draw-matchups repos (:uuid draw))
     554            0 :                                     []))
     555            0 :                                  draws)]))
     556            0 :                             classes))
     557              :             ;; Collect all participant IDs for batch enrichment
     558            0 :             all-pids      (distinct
     559            0 :                            (keep
     560            0 :                             identity
     561            0 :                             (concat
     562            0 :                              (for [draws (vals raw-by-cid)
     563            0 :                                    d     draws
     564            0 :                                    :when (= "group" (:type d))
     565            0 :                                    s     (:slots d)]
     566            0 :                                (:pid s))
     567            0 :                              (for [draws (vals raw-by-cid)
     568            0 :                                    d     draws
     569            0 :                                    :when (= "bracket" (:type d))
     570            0 :                                    m     (:matches d)
     571            0 :                                    id    [(:home-id m) (:away-id m)]]
     572            0 :                                id))))
     573            0 :             enriched      (scoreboard-participants/load-enriched-by-ids repos all-pids)
     574            0 :             resolve-name  (fn [pid]
     575            0 :                            (when pid
     576            0 :                              (let [p (get enriched (str pid))]
     577            0 :                                (or (get-in p [:user :name]) (get-in p [:team :name])))))]
     578            0 :         (mapv
     579            0 :          (fn [class]
     580            0 :           (let [cid   (str (:uuid class))
     581            0 :                 draws (get raw-by-cid cid [])]
     582            0 :             {:name  (:name class)
     583            0 :              :draws (mapv
     584            0 :                      (fn [d]
     585            0 :                       (case (:type d)
     586            0 :                         "group"   {:type  "group"
     587            0 :                                    :name  (:name d)
     588            0 :                                    :slots (mapv
     589            0 :                                            (fn [{:keys [place pid]}]
     590            0 :                                             {:place place
     591            0 :                                              :name  (resolve-name pid)})
     592            0 :                                            (:slots d))}
     593            0 :                         "bracket" {:type    "bracket"
     594            0 :                                    :name    (:name d)
     595            0 :                                    :matches (mapv
     596            0 :                                              (fn [{:keys [home-id away-id]}]
     597            0 :                                               {:home (resolve-name home-id)
     598            0 :                                                :away (resolve-name away-id)})
     599            0 :                                              (:matches d))}
     600            0 :                         d))
     601            0 :                      draws)}))
     602            0 :          classes)))))
     603              : 
     604              : 
     605            4 : (defn- event-court-plan
     606              :   "The event's court plan (settings.courts, set in the stage planner) with court
     607              :    names: [{:from <minutes after start> :names [\"№2\" \"№3\"]} …]. Courts that no
     608              :    longer exist are left out."
     609              :   [repos event]
     610            4 :   (let [settings (:settings event)
     611            1 :         get*     (fn [m k]
     612           11 :                   (or (get m k) (get m (name k))))
     613            4 :         periods  (get* settings :courts)
     614            3 :         repo     (:resource-postgres-repo repos)
     615            2 :         name-of  (memoize
     616            1 :                   (fn [id]
     617            0 :                    (try
     618            0 :                      (:name (resource-query/get-resource repo (str id)))
     619              :                      (catch Exception _ nil))))]
     620            8 :     (when (and repo (sequential? periods))
     621            0 :       (->>
     622            0 :         periods
     623            0 :         (mapv
     624            0 :          (fn [period]
     625            0 :           {:from  (or (get* period :from) 0)
     626            0 :            :names (vec (keep name-of (get* period :ids)))}))
     627            0 :         (sort-by :from)
     628            0 :         vec))))
     629              : 
     630              : 
     631            4 : (defn- draws-post
     632              :   [{:keys [pg repos config]} event]
     633            5 :   (assoc
     634            2 :    (formatting/format-draws-message
     635            8 :     (assoc event :court-plan (event-court-plan repos event))
     636            6 :     (load-classes-with-stage1-draws repos (:uuid event))
     637            4 :     (l10n/message-locale repos event)
     638            6 :     (get-in config [:telegram :bot-username]))
     639              :    :audit-kind       "draws_post"
     640            6 :    :content-revision (draws-revision/revision pg (:uuid event))))
     641              : 
     642              : 
     643            4 : (defn post-draws-job
     644              :  "Goose job: fetches stage-1 draw compositions for the given event and sends them
     645              :    as a fresh Telegram message in every linked chat, deleting the post it replaces.
     646              : 
     647              :    Uses a per-event Redis lock to prevent concurrent runs.
     648              :    Sets a 'dirty' flag when skipped so the final release re-queues the job."
     649              :  [system-components event-uuid]
     650            2 :  (event-lock/with-lock
     651            3 :   (:pg system-components)
     652            1 :   event-uuid
     653            1 :   (fn []
     654            2 :    (let [{:keys [pg redis repos goose telegram-bot]} system-components
     655            6 :          ctx         {:pg    pg
     656            1 :                       :redis redis
     657            1 :                       :repos repos
     658            1 :                       :goose goose}
     659            4 :          lock-key    (str "tg:draws:lock:" event-uuid)
     660            4 :          dirty-key   (str "tg:draws:dirty:" event-uuid)
     661            4 :          lock-token  (str (random-uuid))
     662           43 :          lock-result (car/wcar redis (car/set lock-key lock-token :nx :ex 30))]
     663            6 :      (if-not (= "OK" lock-result)
     664            0 :        (do
     665            0 :          (car/wcar redis (car/set dirty-key "1" :ex 60))
     666            0 :          (t/log! :debug (str "TG draws job skipped (locked), marked dirty for event " event-uuid)))
     667            1 :        (try
     668           96 :          (t/log! :info (str "Starting TG draws broadcast for event " event-uuid))
     669            4 :          (let [event-repo (:event-postgres-repo repos)
     670            8 :                event      (event-postgres-repo/find-by-id event-repo event-uuid {:joins [:club]})
     671            2 :                links      (when
     672           14 :                             (and event (not (contains? #{"completed" "cancelled"} (:state event))))
     673            4 :                             (telegram-link-query/resolve-links-for-event ctx event))]
     674            4 :            (if (seq links)
     675            5 :              (let [post (draws-post system-components event)]
     676           33 :                (doseq [link links] (send-to-link repos telegram-bot event post link))
     677           92 :                (t/log!
     678              :                 :info
     679            5 :                 (str
     680              :                  "Sent TG draws broadcast for event "
     681            1 :                  event-uuid
     682              :                  " to "
     683            2 :                  (count links)
     684              :                  " chat(s)")))
     685           22 :              (t/log! :debug (str "No TG links for event " event-uuid ", skipping"))))
     686              :          (finally
     687           35 :           (car/wcar
     688            1 :            redis
     689            4 :            (car/eval
     690              :             "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end"
     691              :             1
     692            1 :             lock-key
     693            1 :             lock-token))
     694           40 :           (let [dirty (car/wcar redis (car/get dirty-key))]
     695            2 :             (when dirty
     696            0 :               (car/wcar redis (car/del dirty-key))
     697            0 :               (t/log! :debug (str "TG draws re-queued for event " event-uuid " (was dirty)"))
     698            0 :               (scheduler/schedule-job
     699            0 :                goose
     700              :                `post-draws-job
     701            0 :                {:delay-seconds 2
     702            0 :                 :args [event-uuid]}))))))))))
     703              : 
     704              : 
     705            4 : (defn daily-reminder-job
     706              :  "Goose job: the daily reminder. Sends the current main post as a fresh message in
     707              :    every linked chat whose post predates the latest 09:00 Europe/Kyiv, then deletes
     708              :    the post it replaces. Later changes send a fresh post again as usual.
     709              : 
     710              :    Once the scheduled end has passed, an event nobody completed gets no further
     711              :    reminders: its posts from before the boundary are removed instead, while they
     712              :    are still young enough for Telegram to delete.
     713              : 
     714              :    Safe to run repeatedly: a destination already reposted since that boundary is
     715              :    skipped, as is one that never had a main post."
     716              :  [system-components event-uuid]
     717            2 :  (event-lock/with-lock
     718            3 :   (:pg system-components)
     719            1 :   event-uuid
     720            1 :   (fn []
     721            2 :    (let [{:keys [pg redis repos goose telegram-bot]} system-components
     722            3 :          repo     (:telegram-chat-message-postgres-repo repos)
     723            2 :          event    (event-postgres-repo/find-by-id
     724            3 :                    (:event-postgres-repo repos)
     725            1 :                    event-uuid
     726            4 :                    {:joins [:club]})
     727            2 :          now      (Instant/now)
     728            3 :          boundary (daily-reminder/latest-boundary now)
     729            3 :          end      (:datetime-end event)]
     730           19 :      (cond (or (nil? end) (contains? #{"completed" "cancelled"} (:state event))) nil
     731              : 
     732            7 :            (<= (inst-ms end) (inst-ms now))
     733           12 :            (let [stale (filterv #(daily-reminder/due? % boundary) (main-posts repo event))]
     734            5 :              (telegram-cleanup/remove-messages! system-components event stale)
     735            5 :              (when (seq stale)
     736           96 :                (t/log! :info (str "Removed TG main posts of ended event " event-uuid))))
     737              : 
     738              :            :else
     739            7 :            (let [participants (delay (participants-post system-components event))
     740            6 :                  draws        (delay (draws-post system-components event))]
     741           31 :              (doseq [link  (telegram-link-query/resolve-links-for-event
     742            6 :                             {:pg    pg
     743            1 :                              :redis redis
     744            1 :                              :repos repos
     745            1 :                              :goose goose}
     746            1 :                             event)
     747            7 :                      :let  [prior (last (main-posts repo event link))]
     748            9 :                      :when (and prior (daily-reminder/due? prior boundary))]
     749            1 :                (try
     750              :                  ;; Keep published draws published: the reminder repeats what the chat sees
     751              :                  ;; now.
     752            4 :                  (send-to-link
     753            1 :                   repos
     754            1 :                   telegram-bot
     755            1 :                   event
     756            8 :                   @(if (= "draws_post" (:kind prior)) draws participants)
     757            1 :                   link)
     758           92 :                  (t/log!
     759              :                   :info
     760            8 :                   (str "Reposted TG main post for event " event-uuid " in chat " (:chat-id link)))
     761              :                  ;; The scan queues a still-due event again, so it is the retry. Failing
     762              :                  ;; the job as well would stack Goose retries on top of every rescan.
     763              :                  (catch clojure.lang.ExceptionInfo e
     764           92 :                    (t/log!
     765              :                     :warn
     766            6 :                     {:message   "Failed to repost Telegram main post"
     767            1 :                      :event-id  event-uuid
     768            3 :                      :chat-id   (:chat-id link)
     769            1 :                      :exception e}))))))))))
     770              : 
     771              : 
     772            4 : (defn remove-unlinked-posts-job
     773              :  "Goose job: after a chat is unlinked, removes the event's main posts from every
     774              :    destination the event is no longer linked to, so no orphaned list with live
     775              :    buttons stays behind. Finished events are left to completion cleanup."
     776              :  [system-components event-uuid]
     777            2 :  (event-lock/with-lock
     778            3 :   (:pg system-components)
     779            1 :   event-uuid
     780            1 :   (fn []
     781            2 :    (let [{:keys [pg redis repos goose]} system-components
     782            7 :          event (event-postgres-repo/find-by-id (:event-postgres-repo repos) event-uuid {})]
     783           16 :      (when (and event (not (contains? #{"completed" "cancelled"} (:state event))))
     784            3 :        (let [linked   (set
     785            2 :                        (map
     786            4 :                         (juxt :chat-id :thread-id)
     787            2 :                         (telegram-link-query/resolve-links-for-event
     788            6 :                          {:pg    pg
     789            1 :                           :redis redis
     790            1 :                           :repos repos
     791            1 :                           :goose goose}
     792            1 :                          event)))
     793            3 :              orphaned (filterv
     794           12 :                        #(not (contains? linked [(:chat-id %) (:thread-id %)]))
     795            6 :                        (main-posts (:telegram-chat-message-postgres-repo repos) event))
     796            5 :              results  (telegram-cleanup/remove-messages! system-components event orphaned)]
     797           10 :          (when (some #(= :failed (:status %)) results)
     798            0 :            (throw (ex-info "Telegram unlink cleanup requires retry" {:event-id event-uuid})))))))))
        

Generated by: LCOV version 2.0-1