LCOV - code coverage report
Current view: top level - matchscore/telegram - formatting.clj Coverage Total Hit
Test: lcov.info Lines: 98.4 % 444 437
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1              : ;!zprint {:format :off}
       2            4 : (ns matchscore.telegram.formatting
       3              :   (:require
       4              :    [clojure.string :as str]
       5              : 
       6              :    [matchscore.i18n :as i18n])
       7              :   (:import
       8              :    [java.nio.charset StandardCharsets]
       9              :    [java.time Instant ZoneId]
      10              :    [java.time.format DateTimeFormatter]
      11              :    [java.util Base64 Date]))
      12              : 
      13              : 
      14              : ;!zprint {:format :on}
      15              : 
      16              : 
      17           16 : (def ^:private supported-locales #{"en" "uk"})
      18              : 
      19              : 
      20            4 : (defn normalize-locale
      21              :  [locale]
      22          109 :  (let [locale (some->
      23            4 :                 locale
      24            4 :                 name
      25            4 :                 str/lower-case
      26            4 :                 (str/replace "_" "-"))
      27           12 :        locale (case locale
      28              :                 "ua" "uk"
      29           62 :                 (some->
      30            4 :                   locale
      31           12 :                   (str/split #"-")
      32            4 :                   first))]
      33           35 :    (if (contains? supported-locales locale) (keyword locale) :en)))
      34              : 
      35              : 
      36           28 : (defn- t [locale k & args] (apply i18n/translate (normalize-locale locale) k args))
      37              : 
      38              : 
      39            4 : (defn- base64url
      40              :   [s]
      41           18 :   (.encodeToString (.withoutPadding (Base64/getUrlEncoder)) (.getBytes s StandardCharsets/UTF_8)))
      42              : 
      43              : 
      44           16 : (def ^:private datetime-formatter (DateTimeFormatter/ofPattern "dd.MM.yyyy HH:mm"))
      45              : 
      46              : 
      47           16 : (def ^:private time-formatter (DateTimeFormatter/ofPattern "HH:mm"))
      48              : 
      49              : 
      50            4 : (defn- zone-id
      51              :   [timezone]
      52            4 :   (try
      53           30 :     (ZoneId/of (or timezone "UTC"))
      54            0 :     (catch Exception _ (ZoneId/of "UTC"))))
      55              : 
      56              : 
      57            4 : (defn- ->instant
      58              :   [value]
      59           29 :   (cond (instance? Instant value) value
      60           20 :         (instance? Date value)    (.toInstant ^Date value)
      61              :         :else                     nil))
      62              : 
      63              : 
      64            4 : (defn- format-datetime
      65              :   [instant timezone]
      66           36 :   (when-let [instant (->instant instant)]
      67           20 :     (.format datetime-formatter (.atZone ^Instant instant (zone-id timezone)))))
      68              : 
      69              : 
      70            4 : (defn- format-time
      71              :   [instant timezone]
      72           36 :   (when-let [instant (->instant instant)]
      73           20 :     (.format time-formatter (.atZone ^Instant instant (zone-id timezone)))))
      74              : 
      75              : 
      76            4 : (defn- same-local-date?
      77              :   [start end timezone]
      78           16 :   (let [start (->instant start)
      79           12 :         end   (->instant end)]
      80           28 :     (and
      81            4 :      start
      82            4 :      end
      83              :      (=
      84           20 :       (.toLocalDate (.atZone ^Instant start (zone-id timezone)))
      85           20 :       (.toLocalDate (.atZone ^Instant end (zone-id timezone)))))))
      86              : 
      87              : 
      88            4 : (defn- format-datetime-range
      89              :   [{:keys [datetime-start datetime-end timezone]}]
      90           12 :   (when datetime-start
      91            8 :     (if datetime-end
      92           24 :       (if (same-local-date? datetime-start datetime-end timezone)
      93           44 :         (str (format-datetime datetime-start timezone) "-" (format-time datetime-end timezone))
      94            3 :         (str
      95            4 :          (format-datetime datetime-start timezone)
      96              :          " - "
      97            4 :          (format-datetime datetime-end timezone)))
      98            8 :       (format-datetime datetime-start timezone))))
      99              : 
     100              : 
     101            4 : (defn escape-html
     102              :  [s]
     103           12 :  (->
     104            4 :    s
     105           16 :    (str/replace "&" "&")
     106           16 :    (str/replace "<" "&lt;")
     107           16 :    (str/replace ">" "&gt;")
     108           16 :    (str/replace "\"" "&quot;")
     109            4 :    (str/replace "'" "&#39;")))
     110              : 
     111              : 
     112            4 : (defn- format-datetime-detail
     113              :   [{:keys [timezone]
     114              :     :as   event}]
     115           36 :   (when-let [datetime (format-datetime-range event)]
     116           43 :     (cond-> datetime timezone (str " (" (escape-html timezone) ")"))))
     117              : 
     118              : 
     119           18 : (defn- location-coordinate [location & keys] (some #(get location %) keys))
     120              : 
     121              : 
     122            4 : (defn- format-club-location-label
     123              :   [{:keys [country city name network]}]
     124           18 :   (let [place (cond-> name network (str " (" network ")"))
     125           14 :         parts (remove str/blank? [country city place])]
     126           18 :     (when (seq parts) (str/join " / " parts))))
     127              : 
     128              : 
     129            4 : (defn- google-maps-url
     130              :   [{:keys [location]}]
     131           16 :   (let [lat (location-coordinate location :latitude :lat "latitude" "lat")
     132           14 :         lng (location-coordinate location :longitude :lng "longitude" "lng")]
     133           20 :     (when (and lat lng) (str "https://www.google.com/maps?q=" lat "," lng))))
     134              : 
     135              : 
     136            4 : (defn- format-location-detail
     137              :   [{:keys [club-id club clubs]
     138              :     :as   event}]
     139              :   ;; An explicit club list is authoritative, including an empty selection.
     140           28 :   (let [club (if (contains? event :clubs) (first clubs) club)]
     141           38 :     (if-let [label (some->
     142            3 :                      club
     143            2 :                      format-club-location-label)]
     144            8 :       (let [label (escape-html label)]
     145           14 :         (if-let [url (google-maps-url club)]
     146            9 :           (str "<a href=\"" (escape-html url) "\">" label "</a>")
     147            2 :           label))
     148           19 :       (when-not (contains? event :clubs)
     149           33 :         (some->
     150            1 :           club-id
     151            1 :           str
     152            1 :           str/trim
     153            1 :           not-empty
     154            1 :           escape-html)))))
     155              : 
     156              : 
     157            4 : (defn- format-fee-amount
     158              :   [fee]
     159           35 :   (let [amount (cond (integer? fee) (java.math.BigDecimal/valueOf (long fee))
     160           13 :                      (instance? java.math.BigDecimal fee) fee
     161           13 :                      (number? fee)  (java.math.BigDecimal/valueOf (double fee))
     162              :                      :else          nil)]
     163           12 :     (when amount (.toPlainString (.stripTrailingZeros ^java.math.BigDecimal amount)))))
     164              : 
     165              : 
     166            4 : (defn- format-fee-type
     167              :   [locale fee-type]
     168            6 :   (case fee-type
     169            4 :     "total"      (t locale :telegram.participants/fee-type-total)
     170            8 :     "per-person" (t locale :telegram.participants/fee-type-per-person)
     171              :     nil))
     172              : 
     173              : 
     174            4 : (defn format-fee-detail
     175              :  [locale {:keys [fee fee-type currency]}]
     176           24 :  (when-let [amount (format-fee-amount fee)]
     177           60 :    (let [currency (some->
     178            2 :                     currency
     179            2 :                     str
     180            2 :                     str/trim
     181            2 :                     not-empty
     182            2 :                     escape-html)
     183            8 :          type     (format-fee-type locale fee-type)]
     184           36 :      (str amount (when currency (str " " currency)) (when type (str " (" type ")"))))))
     185              : 
     186              : 
     187            4 : (defn- display-class-name
     188              :   [locale name]
     189           18 :   (let [name (some->
     190            1 :                name
     191            1 :                str
     192            1 :                str/trim)]
     193            1 :     (if
     194            2 :       (=
     195              :        "default"
     196            9 :        (some->
     197            1 :          name
     198            1 :          str/lower-case))
     199            4 :       (t locale :telegram.participants/default-class)
     200           11 :       (or (not-empty name) (t locale :telegram.participants/default-class)))))
     201              : 
     202              : 
     203            4 : (defn format-event-datetime
     204              :  "Returns the localized 'When: <range> (timezone)' line for an event, or nil when the
     205              :    event has no start datetime. Same datetime rendering as format-event-details."
     206              :  [locale event]
     207            9 :  (when-let [datetime (format-datetime-detail event)]
     208            5 :    (t locale :telegram.participants/datetime datetime)))
     209              : 
     210              : 
     211            4 : (defn event-datetime-detail
     212              :  "Returns the unlabeled datetime range (with timezone) for an event, or nil when the
     213              :    event has no start datetime. Lets callers attach their own label."
     214              :  [event]
     215           12 :  (format-datetime-detail event))
     216              : 
     217              : 
     218            4 : (defn- format-event-details
     219              :   [locale event]
     220           12 :   (let [datetime (format-datetime-detail event)
     221            9 :         location (format-location-detail event)
     222           12 :         fee      (format-fee-detail locale event)
     223           24 :         lines    (cond-> []
     224           27 :                    datetime (conj (t locale :telegram.participants/datetime datetime))
     225           19 :                    location (conj (t locale :telegram.participants/location location))
     226            9 :                    fee      (conj (t locale :telegram.participants/fee fee)))]
     227           27 :     (when (seq lines) (str/join "\n" lines))))
     228              : 
     229              : 
     230            4 : (defn- participant-label
     231              :   "Escaped participant name. With `link-users?`, a participant with a Telegram account
     232              :    becomes a text mention that opens their profile. A mention in a newly sent message
     233              :    notifies the user, so callers send the plain variant and edit the links in."
     234              :   [link-users? {:keys [name telegram-id]}]
     235           18 :   (let [label (escape-html (or name ""))]
     236           36 :     (if (and link-users? (integer? telegram-id) (not (str/blank? label)))
     237           14 :       (str "<a href=\"tg://user?id=" telegram-id "\">" label "</a>")
     238            2 :       label)))
     239              : 
     240              : 
     241            4 : (defn- format-class-section
     242              :   "Renders a single class block: underlined class name + numbered participant list,
     243              :    with compact empty slots up to the class's :max-players (when set).
     244              :    Participants above :max-players are rendered in a queue section."
     245              :   [locale show-class-name? link-users? {:keys [name max-players participants admins? unassigned?]}]
     246           13 :   (let [max-p        (or max-players 0)
     247           30 :         capped?      (and (not admins?) (not unassigned?) (pos? max-p))
     248           10 :         filled-participants (if capped? (take max-p participants) participants)
     249           10 :         queued-participants (if capped? (drop max-p participants) [])
     250            4 :         filled-count (count filled-participants)
     251           15 :         name         (cond admins?     (t locale :telegram.participants/admins)
     252           10 :                            unassigned? (t locale :telegram.participants/unassigned)
     253            4 :                            :else       (display-class-name locale name))
     254           20 :         title        (when (or show-class-name? admins? unassigned?)
     255           19 :                        (let [tag (if (or admins? unassigned?) "b" "u")]
     256           30 :                          (str "<" tag ">" (escape-html (or name "")) "</" tag ">")))
     257            4 :         filled-lines (if admins?
     258           16 :                        (mapv #(participant-label link-users? %) participants)
     259            4 :                        (map-indexed
     260            2 :                         (fn [i p]
     261           18 :                          (str (inc i) ". " (participant-label link-users? p)))
     262            2 :                         filled-participants))
     263           15 :         empty-slots  (when (> max-p filled-count) (range (inc filled-count) (inc max-p)))
     264           10 :         empty-lines  (case (count empty-slots)
     265              :                        0 nil
     266            7 :                        1 [(str (first empty-slots) ".")]
     267            8 :                        2 (mapv #(str % ".") empty-slots)
     268           14 :                        [(str (first empty-slots) ".") "..." (str (last empty-slots) ".")])
     269            9 :         queue-lines  (when (seq queued-participants)
     270            2 :                        (concat
     271           10 :                         ["" (str "<b>" (t locale :telegram.participants/queue) "</b>")]
     272            2 :                         (map-indexed
     273            1 :                          (fn [i p]
     274            9 :                           (str (inc i) ". " (participant-label link-users? p)))
     275            1 :                          queued-participants)))
     276           16 :         body         (str/join "\n" (concat filled-lines empty-lines queue-lines))]
     277           23 :     (cond (and title (str/blank? body)) title
     278           12 :           title (str title "\n" body)
     279            6 :           (not (str/blank? body)) body
     280              :           :else nil)))
     281              : 
     282              : 
     283            4 : (defn format-participants
     284              :  "Returns the Telegram HTML message text for the current participants list,
     285              :    grouped per class.
     286              : 
     287              :    event        – domain Event map (:name, :datetime-start)
     288              :    class-groups – vec of {:uuid :public-id :name :max-players :participants}
     289              :                   where :participants is a vec of {:name :telegram-id} in registration order.
     290              :    opts         – {:link-users? true} renders names with a Telegram account as
     291              :                   profile links (text mentions)."
     292            5 :  ([event class-groups] (format-participants event class-groups :en))
     293            6 :  ([event class-groups locale] (format-participants event class-groups locale {}))
     294              :  ([event class-groups locale {:keys [link-users?]}]
     295           34 :   (let [event-name        (some->
     296            6 :                             (:name event)
     297            2 :                             str
     298            2 :                             str/trim)
     299            8 :         header            (if (str/blank? event-name)
     300            4 :                             (t locale :telegram.participants/header-no-event)
     301           14 :                             (t locale :telegram.participants/header (escape-html event-name)))
     302            8 :         details           (format-event-details locale event)
     303           19 :         intro             (cond-> header details (str "\n" details))
     304           38 :         real-class-count  (count (remove #(or (:admins? %) (:unassigned? %)) (or class-groups [])))
     305            8 :         show-class-name?  (not= 1 real-class-count)
     306           16 :         admin-groups      (filterv :admins? (or class-groups []))
     307           36 :         participant-groups (remove #(or (:admins? %) (:unassigned? %)) (or class-groups []))
     308           16 :         unassigned-groups (filterv :unassigned? (or class-groups []))
     309            6 :         admin-sections    (keep
     310           12 :                            #(format-class-section locale show-class-name? link-users? %)
     311            2 :                            admin-groups)
     312            6 :         participant-sections (keep
     313           12 :                               #(format-class-section locale show-class-name? link-users? %)
     314            8 :                               (concat participant-groups unassigned-groups))
     315           10 :         participant-block (when (seq participant-sections)
     316            8 :                             (str
     317            8 :                              "<b>"    (t locale :telegram.participants/list)
     318            8 :                              "</b>\n" (str/join "\n\n" participant-sections)))
     319           16 :         sections          (concat admin-sections (when participant-block [participant-block]))]
     320           26 :     (if (seq sections) (str intro "\n\n" (str/join "\n\n" sections)) intro))))
     321              : 
     322              : 
     323            4 : (defn- event-deep-link-url
     324              :   [event bot-username tab]
     325           54 :   (when (and (not (str/blank? bot-username)) (not (str/blank? (:public-id event))))
     326           42 :     (let [path (str "/events/" (:public-id event) (when tab (str "?tab=" tab)))]
     327           24 :       (str "https://t.me/" bot-username "?startapp=" (base64url path)))))
     328              : 
     329              : 
     330            4 : (defn open-event-button
     331              :  "Builds a deep-link URL button that opens the MatchScore mini app on the given
     332              :    event page. The `startapp` payload is a base64url-encoded route path read by
     333              :    the mini app.
     334              :    Returns nil when bot-username or the event public-id is missing."
     335              :  [event bot-username locale]
     336           33 :  (when-let [url (event-deep-link-url event bot-username nil)]
     337           21 :    {:text (t locale :telegram.participants/open-event)
     338            3 :     :url  url}))
     339              : 
     340              : 
     341            8 : (def ^:private message-limit 4096)
     342              : 
     343              : 
     344            4 : (defn- html-text
     345              :   "Decode only after stripping generated tags, so escaped user text is never markup."
     346              :   [html]
     347            6 :   (->
     348            3 :     html
     349           12 :     (str/replace #"<[^>]*>" "")
     350            3 :     (str/replace
     351              :      #"&(?:amp|lt|gt|quot|#39);"
     352           33 :      {"&amp;"  "&"
     353              :       "&lt;"   "<"
     354              :       "&gt;"   ">"
     355              :       "&quot;" "\""
     356              :       "&#39;"  "'"})))
     357              : 
     358              : 
     359            4 : (defn message-length
     360              :  "Rendered UTF-16 length (conservative for Telegram), excluding HTML markup."
     361              :  [html]
     362           12 :  (count (html-text html)))
     363              : 
     364              : 
     365            4 : (defn- truncate-text
     366              :   [text limit]
     367            7 :   (let [end (min (count text) (max 0 limit))
     368           11 :         end (if (and (pos? end) (Character/isHighSurrogate (.charAt ^String text (dec end))))
     369            0 :               (dec end)
     370            1 :               end)]
     371            5 :     (subs text 0 end)))
     372              : 
     373              : 
     374            4 : (defn- app-link
     375            6 :   ([event bot-username label] (app-link event bot-username label nil))
     376              :   ([event bot-username label tab]
     377           30 :    (if-let [url (event-deep-link-url event bot-username tab)]
     378           33 :      (str "<a href=\"" (escape-html url) "\">" (escape-html label) "</a>")
     379            9 :      (escape-html label))))
     380              : 
     381              : 
     382            4 : (defn- changelog-line
     383              :   [event locale show-class? change]
     384           14 :   (let [verb        (case (:action change)
     385              :                       "left" :telegram.notify/left
     386           11 :                       (if (:queued change) :telegram.notify/joined-queue :telegram.notify/joined))
     387            9 :         description (or
     388            6 :                      (:legacy-text change)
     389            2 :                      (str
     390            4 :                       (t
     391            2 :                        locale
     392            2 :                        verb
     393            4 :                        (escape-html
     394           14 :                         (or (:participant-name change) (t locale :telegram.notify/someone))))
     395           18 :                       (when (and show-class? (:class-name change))
     396            3 :                         (str
     397              :                          " · "
     398            8 :                          (escape-html (display-class-name locale (:class-name change)))))))
     399           22 :         timestamp   (when-let [instant (->instant (:created-datetime change))]
     400            2 :                       (.format
     401            6 :                        (DateTimeFormatter/ofPattern "dd.MM HH:mm")
     402           12 :                        (.atZone ^Instant instant (zone-id (:timezone event)))))]
     403           28 :     (str (when timestamp (str timestamp " — ")) (str/replace description #"[\r\n]+" " · "))))
     404              : 
     405              : 
     406            4 : (defn- with-changelog
     407              :   [base event class-groups locale bot-username changes]
     408           46 :   (let [show-class? (not= 1 (count (remove #(or (:admins? %) (:unassigned? %)) class-groups)))
     409              :         ;; Storage returns oldest first (timestamp, then UUID); reverse that stable
     410              :         ;; order for display so even the collapsed preview shows the latest action.
     411           30 :         lines (mapv #(changelog-line event locale show-class? %) (reverse changes))
     412           24 :         heading (str "\n\n<b>" (t locale :telegram.changelog/header) "</b>\n")
     413            3 :         block (fn [entries]
     414           18 :                (str heading "<blockquote expandable>" (str/join "\n" entries) "</blockquote>"))
     415              :         overflow
     416           36 :         (str "\n" (app-link event bot-username (t locale :telegram.changelog/overflow) "telegram"))
     417              :         ;; An already oversized roster must not prevent every future update. Keep valid
     418              :         ;; escaped text and the app link, never cut through an HTML tag or entity.
     419              :         full-fits?
     420           39 :         (<= (message-length (if (seq lines) (str base (block lines)) base)) message-limit)
     421           30 :         base-budget (if (and (seq lines) (not full-fits?))
     422           11 :                       (- message-limit (message-length heading) (message-length overflow) 1)
     423            3 :                       message-limit)
     424           18 :         base (if (<= (message-length base) base-budget)
     425            3 :                base
     426            4 :                (let [suffix (str
     427              :                              "…\n"
     428            2 :                              (app-link
     429            1 :                               event
     430            1 :                               bot-username
     431            4 :                               (t locale :telegram.changelog/participants-overflow)))]
     432            2 :                  (str
     433            2 :                   (escape-html
     434           10 :                    (truncate-text (html-text base) (- base-budget (message-length suffix))))
     435            1 :                   suffix)))
     436           27 :         full (if (seq lines) (str base (block lines)) base)]
     437           18 :     (if (<= (message-length full) message-limit)
     438            3 :       full
     439              :       ;; Keep a prefix of the newest-first entries; never discard a newer entry
     440              :       ;; just to fit an older, shorter entry.
     441            4 :       (let [budget (-
     442            1 :                     message-limit
     443            3 :                     (message-length base)
     444            3 :                     (message-length heading)
     445            3 :                     (message-length overflow))
     446            5 :             kept   (loop [remaining (seq lines)
     447            1 :                           selected  []
     448              :                           used      0]
     449            8 :                      (if-let [line (first remaining)]
     450           11 :                        (let [size (+ (message-length line) (if (seq selected) 1 0))]
     451            6 :                          (if (<= (+ used size) budget)
     452            1 :                            (recur (next remaining) (conj selected line) (+ used size))
     453            1 :                            selected))
     454            0 :                        selected))]
     455           12 :         (str base (when (seq kept) (block kept)) overflow)))))
     456              : 
     457              : 
     458            4 : (defn build-keyboard
     459              :  "Builds an inline-keyboard reply markup for the participants message.
     460              :    Callback data format: 'j:<class_public_id>' for join, 'l:<class_public_id>' for leave.
     461              :    When there is 1 class the keyboard has a single Join/Leave row scoped to that class.
     462              :    With multiple classes a row per class is emitted with class-scoped buttons.
     463              :    When `bot-username` is provided a final 'Open event' deep-link row is appended.
     464              :    Returns nil when there are no rows to show."
     465            6 :  ([event classes] (build-keyboard event classes :en nil))
     466            6 :  ([event classes locale] (build-keyboard event classes locale nil))
     467              :  ([event classes locale bot-username]
     468           20 :   (let [classes   (if (contains? #{"completed" "cancelled"} (:state event))
     469            2 :                     []
     470           16 :                     (filterv :public-id (or classes [])))
     471           12 :         join-rows (cond (empty? classes) []
     472              : 
     473            4 :                         (= 1 (count classes))
     474           11 :                         [[{:text          (t locale :telegram.participants/join)
     475              :                            :style         "success"
     476            8 :                            :callback_data (str "j:" (:public-id (first classes)))}
     477            9 :                           {:text          (t locale :telegram.participants/leave)
     478              :                            :style         "danger"
     479            8 :                            :callback_data (str "l:" (:public-id (first classes)))}]]
     480              : 
     481              :                         :else
     482            2 :                         (mapv
     483            1 :                          (fn [c]
     484            8 :                           (let [pid  (or (:public-id c) "")
     485            6 :                                 name (display-class-name locale (:name c))]
     486           11 :                             [{:text          (t locale :telegram.participants/join-class name)
     487              :                               :style         "success"
     488            4 :                               :callback_data (str "j:" pid)}
     489           10 :                              {:text          (t locale :telegram.participants/leave-class name)
     490              :                               :style         "danger"
     491            4 :                               :callback_data (str "l:" pid)}]))
     492            1 :                          classes))
     493           10 :         view-btn  (open-event-button event bot-username locale)
     494           20 :         rows      (cond-> join-rows view-btn (conj [view-btn]))]
     495           16 :     (when (seq rows) {:inline_keyboard rows}))))
     496              : 
     497              : 
     498            4 : (defn format-participants-message
     499              :  "Returns {:text <html-text> :reply-markup <inline-keyboard>} suitable for
     500              :    tbot/send-message. The inline keyboard scopes Join/Leave buttons by class
     501              :    when more than one class is present, and appends an 'Open event' deep-link
     502              :    button when `bot-username` is provided.
     503              : 
     504              :    When any listed participant has a Telegram account, also returns :linked-text:
     505              :    the same post with those names as profile links. Send :text first and edit in
     506              :    :linked-text, because mentions only notify users in a newly sent message."
     507            6 :  ([event class-groups] (format-participants-message event class-groups :en nil))
     508            0 :  ([event class-groups locale] (format-participants-message event class-groups locale nil))
     509              :  ([event class-groups locale bot-username]
     510            7 :   (format-participants-message event class-groups locale bot-username []))
     511              :  ([event class-groups locale bot-username changes]
     512            4 :   (let [render (fn [link-users?]
     513            4 :                 (with-changelog
     514           16 :                  (format-participants event class-groups locale {:link-users? link-users?})
     515            2 :                  event
     516            2 :                  class-groups
     517            2 :                  locale
     518            2 :                  bot-username
     519            2 :                  changes))
     520            6 :         text   (render false)
     521            6 :         linked (render true)]
     522           12 :     (cond->
     523            8 :       {:text         text
     524           12 :        :reply-markup (build-keyboard event class-groups locale bot-username)}
     525           12 :       (not= text linked) (assoc :linked-text linked)))))
     526              : 
     527              : 
     528            4 : (defn format-closed-event-message
     529              :  "A permanent fallback for a main post that Telegram can no longer delete."
     530              :  [event locale bot-username]
     531            9 :  (let [status (t
     532            3 :                locale
     533           23 :                (if (= "cancelled" (:state event))
     534              :                  :telegram.participants/cancelled
     535              :                  :telegram.participants/completed))
     536           12 :        text   (str
     537              :                "<b>"
     538           27 :                (escape-html (or (:name event) ""))
     539              :                "</b>\n"
     540            3 :                status
     541           42 :                (when-let [details (format-event-details locale event)] (str "\n" details)))
     542           15 :        button (open-event-button event bot-username locale)]
     543           33 :    {:text         (with-changelog text event [] locale bot-username [])
     544           23 :     :reply-markup {:inline_keyboard (if button [[button]] [])}}))
     545              : 
     546              : 
     547            4 : (defn- format-draw-group-section
     548              :   [_locale {:keys [name slots]}]
     549           12 :   (let [title      (str "<b>" (escape-html (or name "")) "</b>")
     550            2 :         slot-lines (mapv
     551            1 :                     (fn [{:keys [place name]}]
     552           18 :                      (let [n (some->
     553            1 :                                name
     554            1 :                                str
     555            1 :                                str/trim)]
     556           12 :                        (str place ". " (if (str/blank? n) "" (escape-html n)))))
     557            1 :                     slots)]
     558            8 :     (str title "\n" (str/join "\n" slot-lines))))
     559              : 
     560              : 
     561            4 : (defn- format-draw-bracket-section
     562              :   [locale {:keys [name matches]}]
     563           12 :   (let [title       (str "<b>" (escape-html (or name "")) "</b>")
     564            2 :         match-lines (mapv
     565            1 :                      (fn [{:keys [home away]}]
     566           19 :                       (let [h (let [s (some->
     567            1 :                                         home
     568            1 :                                         str
     569            1 :                                         str/trim)]
     570           11 :                                 (if (str/blank? s) (t locale :telegram.draws/tbd) (escape-html s)))
     571           16 :                             a (let [s (some->
     572            1 :                                         away
     573            1 :                                         str
     574            1 :                                         str/trim)]
     575            7 :                                 (if (str/blank? s) (t locale :telegram.draws/tbd) (escape-html s)))]
     576           10 :                         (str h " " (t locale :telegram.draws/vs) " " a)))
     577            1 :                      matches)]
     578           12 :     (if (seq match-lines) (str title "\n" (str/join "\n" match-lines)) title)))
     579              : 
     580              : 
     581            4 : (defn- format-draws-class-section
     582              :   [locale show-class-name? {:keys [name draws]}]
     583            3 :   (let [draw-sections (keep
     584            1 :                        (fn [draw]
     585            5 :                         (case (:type draw)
     586            4 :                           "group"   (format-draw-group-section locale draw)
     587            4 :                           "bracket" (format-draw-bracket-section locale draw)
     588              :                           nil))
     589            1 :                        draws)]
     590            5 :     (when (seq draw-sections)
     591            4 :       (let [class-title (when show-class-name?
     592           10 :                           (str "<u>" (escape-html (display-class-name locale name)) "</u>"))
     593            4 :             body        (str/join "\n\n" draw-sections)]
     594            8 :         (if class-title (str class-title "\n\n" body) body)))))
     595              : 
     596              : 
     597            4 : (defn- format-courts-detail
     598              :   "The event's courts for the draws post, from :court-plan
     599              :    [{:from <minutes after start> :names [\"№2\" \"№3\"]} …] in time order:
     600              :    one line when the courts don't change (periods with the same courts as the one
     601              :    before merge, and periods from the event end on are dropped), otherwise a line
     602              :    per period with its clock times (\"10:00–11:00: №2, №3\", the last one up to the event end or
     603              :    \"from 11:00\")."
     604              :   [locale {:keys [court-plan datetime-start datetime-end timezone]}]
     605           10 :   (let [start  (->instant datetime-start)
     606            6 :         end    (->instant datetime-end)
     607              :         ;; Event length in minutes, when both ends are known.
     608           15 :         length (when (and start end)
     609           10 :                  (quot (- (.toEpochMilli ^Instant end) (.toEpochMilli ^Instant start)) 60000))
     610              :         ;; Periods that start at or after the event end have no play time; a period
     611              :         ;; with the same courts as the one before only continues it.
     612            2 :         plan   (->>
     613            2 :                  court-plan
     614           11 :                  (filter #(seq (:names %)))
     615           24 :                  (remove #(and length (pos? (:from %)) (>= (:from %) length)))
     616            2 :                  (reduce
     617            2 :                   (fn [acc period]
     618           15 :                    (if (= (:names (peek acc)) (:names period)) acc (conj acc period)))
     619            2 :                   []))
     620            9 :         names  #(str/join ", " (map escape-html (:names %)))
     621            2 :         at     (fn [minutes]
     622            3 :                 (when start
     623            8 :                   (format-time (.plusSeconds ^Instant start (* 60 (long minutes))) timezone)))]
     624           12 :     (cond (empty? plan) nil
     625              : 
     626           13 :           (= 1 (count plan)) (t locale :telegram.draws/courts (names (first plan)))
     627              : 
     628              :           :else
     629            3 :           (str/join
     630              :            "\n"
     631            2 :            (cons
     632            4 :             (t locale :telegram.draws/courts-plan)
     633            2 :             (map
     634            1 :              (fn
     635              :               [{:keys [from]
     636              :                 :as   period}
     637              :                next-period]
     638            8 :               (let [from-label (or (at from) "")
     639            2 :                     until      (if next-period
     640            5 :                                  (at (:from next-period))
     641            7 :                                  (when datetime-end (format-time datetime-end timezone)))]
     642            3 :                 (str
     643            2 :                  (if until
     644            5 :                    (str from-label "–" until)
     645            5 :                    (t locale :telegram.draws/courts-from from-label))
     646              :                  ": "
     647            3 :                  (names period))))
     648            1 :              plan
     649            7 :              (concat (rest plan) [nil])))))))
     650              : 
     651              : 
     652            4 : (defn format-draws
     653              :  "Returns the Telegram HTML message text for stage-1 draw compositions,
     654              :    grouped per class.
     655              : 
     656              :    event       – domain Event map (:name, :datetime-start, etc.; :court-plan, when
     657              :                  set, adds the courts in use, see format-courts-detail)
     658              :    class-draws – vec of {:name <class-name>
     659              :                           :draws [{:type 'group'|'bracket' :name ... :slots|:matches [...]}]}
     660              :                  produced by load-classes-with-stage1-draws."
     661            0 :  ([event class-draws] (format-draws event class-draws :en))
     662              :  ([event class-draws locale]
     663           32 :   (let [event-name (some->
     664            6 :                      (:name event)
     665            2 :                      str
     666            2 :                      str/trim)
     667            8 :         header     (if (str/blank? event-name)
     668            4 :                      (t locale :telegram.draws/header-no-event)
     669           14 :                      (t locale :telegram.draws/header (escape-html event-name)))
     670            8 :         details    (format-event-details locale event)
     671            8 :         courts     (format-courts-detail locale event)
     672           16 :         intro      (cond-> header
     673           10 :                      details (str "\n" details)
     674            4 :                      courts  (str "\n" courts))
     675           21 :         sections   (keep #(format-draws-class-section locale true %) (or class-draws []))
     676           10 :         sections   (if (= 1 (count sections))
     677           13 :                      (keep #(format-draws-class-section locale false %) (or class-draws []))
     678            2 :                      sections)]
     679           18 :     (if (seq sections) (str intro "\n\n" (str/join "\n\n" sections)) intro))))
     680              : 
     681              : 
     682            4 : (defn format-draws-message
     683              :  "Returns {:text <html-text> :reply-markup <inline-keyboard>} suitable for
     684              :    tbot/send-message. Appends an 'Open event' deep-link button when
     685              :    `bot-username` is provided.
     686              : 
     687              :    No participant change history: the draws are the final lineup, and
     688              :    join/leave entries from registration only add noise under it. The text
     689              :    still goes through with-changelog so an oversized draw is cut to the
     690              :    Telegram limit with an app link."
     691            0 :  ([event class-draws] (format-draws-message event class-draws :en nil))
     692            0 :  ([event class-draws locale] (format-draws-message event class-draws locale nil))
     693              :  ([event class-draws locale bot-username]
     694           12 :   (let [view-btn (open-event-button event bot-username locale)
     695           16 :         kb       (when view-btn {:inline_keyboard [[view-btn]]})]
     696           10 :     {:text         (with-changelog
     697           10 :                     (format-draws event class-draws locale)
     698            2 :                     event
     699            2 :                     class-draws
     700            2 :                     locale
     701            2 :                     bot-username
     702            2 :                     [])
     703            2 :      :reply-markup kb})))
        

Generated by: LCOV version 2.0-1