LCOV - code coverage report
Current view: top level - matchscore/dev - notification_samples.clj Coverage Total Hit
Test: lcov.info Lines: 12.6 % 183 23
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.dev.notification-samples
       2              :   "LOCAL DEVELOPMENT ONLY. Sends sample update digests to the caller's Telegram and
       3              :   fills / clears sample items in their in-app feed, built from the imported PSA/ESF
       4              :   data of the dev database. Every entry point checks `enabled?` (APP_ENV=dev)."
       5              :   (:require
       6              :    [cheshire.core :as json]
       7              :    [clojure.string :as str]
       8              :    [matchscore.db.postgres.user-updates :as uu]
       9              :    [matchscore.telegram.messages :as messages]
      10              :    [matchscore.telegram.updates :as render]
      11              :    [next.jdbc :as jdbc]
      12              :    [next.jdbc.result-set :as rs]
      13              :    [taoensso.telemere :as t]
      14              :    [telegrambot-lib.core :as tbot])
      15              :   (:import
      16              :    (java.time Instant LocalDate)))
      17              : 
      18              : 
      19            8 : (def sample-prefix
      20              :   "subject_key prefix of feed rows created here, so clearing never touches real rows."
      21              :   "dev-sample:")
      22              : 
      23              : 
      24            4 : (defn enabled?
      25              :  [config]
      26            5 :  (= "development" (:env config)))
      27              : 
      28              : 
      29            4 : (defn- latest-event-day
      30              :   "The detector only looks at recent events, so anchor `today` on the newest imported
      31              :   event that has a draw (dev data goes stale)."
      32              :   [ds]
      33            0 :   (or
      34            0 :    (some->
      35            0 :      (jdbc/execute-one!
      36            0 :       ds
      37            0 :       ["SELECT max(date_end) AS d FROM imported_tournaments
      38              :             WHERE event_id IS NOT NULL AND date_end <= current_date"])
      39              :      :d
      40            0 :      str
      41            0 :      LocalDate/parse)
      42            0 :    (LocalDate/now)))
      43              : 
      44              : 
      45            4 : (defn- detected-rows
      46              :   "Every update the detector would produce for a user subscribed to all of PSA and ESF.
      47              :   Runs in a rolled-back transaction: nothing is stored."
      48              :   [ds user-id]
      49            0 :   (jdbc/with-transaction
      50            0 :    [tx ds {:rollback-only true}]
      51            0 :    (doseq [source ["psa" "esf"]]
      52            0 :      (jdbc/execute-one!
      53            0 :       tx
      54            0 :       ["INSERT INTO tournament_subscriptions (user_id, source, target, target_key, match_scope)
      55              :         VALUES (?::uuid, ?, 'source', NULL, 'all') ON CONFLICT DO NOTHING"
      56            0 :        (str user-id)
      57            0 :        source]))
      58            0 :    (let [opts  {:sources     #{"psa" "esf"}
      59            0 :                 :today       (latest-event-day tx)
      60            0 :                 :video-since (.minusSeconds (Instant/now) (* 60 86400))}
      61            0 :          first (uu/detect tx opts)
      62            0 :          _ (uu/upsert-updates! tx first)
      63            0 :          again (uu/detect tx opts)]
      64            0 :      (vec (concat first again)))))
      65              : 
      66              : 
      67            4 : (defn- payload-map
      68              :   [payload]
      69            0 :   (cond (map? payload)    payload
      70            0 :         (string? payload) (json/parse-string payload true)
      71            0 :         :else             (json/parse-string (str payload) true)))
      72              : 
      73              : 
      74            4 : (defn- as-row
      75              :   [r]
      76            0 :   {:kind       (:kind r)
      77            0 :    :payload    (payload-map (:payload r))
      78              :    :corrected? false})
      79              : 
      80              : 
      81            4 : (defn- follow [row side] (assoc-in row [:payload side :followed] true))
      82              : 
      83              : 
      84            4 : (defn sample-sets
      85              :  "Named sample digests: {:main [...] :videos [...] :long [...]} (any may be empty)."
      86              :  [rows]
      87            0 :  (let [of-kind  (fn [k]
      88            0 :                  (map as-row (filter #(= k (:kind %)) rows)))
      89            0 :        results  (vec (of-kind "result"))
      90            0 :        pairings (vec (of-kind "pairing"))
      91            0 :        winner   (fn [side]
      92            0 :                  (first (filter #(= side (get-in % [:payload :winner])) results)))
      93            0 :        won      (some->
      94            0 :                   (winner "home")
      95            0 :                   (follow :home))
      96            0 :        lost     (some->
      97            0 :                   (winner "away")
      98            0 :                   (follow :home))
      99            0 :        neutral  (get results 5)
     100            0 :        corr     (some->
     101            0 :                   (get results 7)
     102            0 :                   (assoc :corrected? true))
     103            0 :        walkover (some->
     104            0 :                   (get results 9)
     105            0 :                   (assoc-in [:payload :outcome] "walkover")
     106            0 :                   (assoc-in [:payload :games] [])
     107            0 :                   (assoc-in [:payload :total] nil))
     108            0 :        p-timed  (some->
     109            0 :                   (first (filter #(get-in % [:payload :starts-at]) pairings))
     110            0 :                   (follow :away))
     111            0 :        p-plain  (first (remove #(get-in % [:payload :starts-at]) pairings))
     112            0 :        main     (vec
     113            0 :                  (remove
     114            0 :                   nil?
     115            0 :                   [(first (of-kind "tournament_new"))
     116            0 :                    (first (of-kind "draw_published"))
     117            0 :                    won
     118            0 :                    lost
     119            0 :                    neutral
     120            0 :                    corr
     121            0 :                    walkover
     122            0 :                    p-timed
     123            0 :                    p-plain]))]
     124            0 :    {:main   main
     125            0 :     :videos (vec (take 3 (of-kind "video")))
     126            0 :     :long   (vec (concat main (take 30 (drop 10 results))))}))
     127              : 
     128              : 
     129            4 : (defn- user-row
     130              :   [ds user-id]
     131            0 :   (jdbc/execute-one!
     132            0 :    ds
     133            0 :    ["SELECT telegram_id, settings->>'language' AS language, settings->>'timezone' AS timezone
     134              :        FROM users WHERE uuid = ?::uuid"
     135            0 :     (str user-id)]
     136            0 :    {:builder-fn rs/as-unqualified-kebab-maps}))
     137              : 
     138              : 
     139            4 : (def actions
     140              :   "Telegram sample actions, in the order the UI lists them."
     141           36 :   ["all" "show" "spoiler" "off" "videos" "video-edit" "long" "english"])
     142              : 
     143              : 
     144            4 : (defn- digests
     145              :   "[[label render-opts rows] ...] for a Telegram action."
     146              :   [action {:keys [main videos long]}]
     147            0 :   (let [d {"show"       ["Результати: показувати" {:results-mode "show"} main]
     148            0 :            "spoiler"    ["Результати: під спойлером" {:results-mode "spoiler"} main]
     149            0 :            "off"        ["Результати: не надсилати" {:results-mode "off"} main]
     150            0 :            "videos"     ["Нові відео" {:results-mode "show"} videos]
     151            0 :            "video-edit" ["Відео: редагування повідомлення" {:results-mode "show"} videos]
     152            0 :            "long"       ["Довгий дайджест (згортання)" {:results-mode "show"} long]
     153            0 :            "english"    ["English"
     154            0 :                          {:locale       "en"
     155              :                           :results-mode "show"}
     156            0 :                          main]}]
     157            0 :     (if (= "all" action) (mapv d (remove #{"all"} actions)) [(d action)])))
     158              : 
     159              : 
     160            4 : (defn- send!
     161              :   [bot chat-id {:keys [text reply-markup]}]
     162            0 :   (get-in
     163            0 :    (messages/request!
     164            0 :     tbot/send-message
     165            0 :     bot
     166            0 :     (cond->
     167            0 :       {:chat_id    chat-id
     168            0 :        :text       text
     169              :        :parse_mode "HTML"
     170              :        :disable_web_page_preview true}
     171            0 :       reply-markup (assoc :reply_markup reply-markup)))
     172            0 :    [:result :message_id]))
     173              : 
     174              : 
     175            4 : (defn- send-video-edit!
     176              :   "Sends the matches without videos, then edits the message to add them (like video=edit)."
     177              :   [bot chat-id opts rows]
     178            0 :   (let [plain (mapv
     179            0 :                #(->
     180              :                   %
     181            0 :                   (assoc :kind "result")
     182            0 :                   (assoc-in [:payload :videos] []))
     183            0 :                rows)
     184            0 :         full  (mapv #(assoc % :kind "result") rows)
     185            0 :         id    (send! bot chat-id (render/render-digest opts plain))]
     186            0 :     (Thread/sleep 8000)
     187            0 :     (let [{:keys [text reply-markup]} (render/render-digest opts full)]
     188            0 :       (messages/edit!
     189            0 :        bot
     190            0 :        (cond->
     191            0 :          {:chat_id    chat-id
     192            0 :           :message_id id
     193            0 :           :text       text
     194              :           :parse_mode "HTML"
     195              :           :disable_web_page_preview true}
     196            0 :          reply-markup (assoc :reply_markup reply-markup))))))
     197              : 
     198              : 
     199            4 : (defn send-telegram-samples!
     200              :  "Sends the digests for `action` in the background. Returns {:sent n} or {:error msg}."
     201              :  [{:keys [config bot ds user-id action]}]
     202            5 :  (let [user (user-row ds user-id)]
     203            9 :    (cond (not (enabled? config)) {:error "Dev tools are disabled"}
     204            0 :          (not (some #{action} actions)) {:error (str "Unknown action " action)}
     205            0 :          (nil? bot) {:error "No Telegram bot configured"}
     206            0 :          (nil? (:telegram-id user)) {:error "Your account has no linked Telegram"}
     207              :          :else
     208            0 :          (let [sets (sample-sets (detected-rows ds user-id))
     209            0 :                base {:locale       (or (:language user) "uk")
     210            0 :                      :user-tz      (:timezone user)
     211            0 :                      :bot-username (get-in config [:telegram :bot-username])}
     212            0 :                todo (remove
     213            0 :                      (fn [[_ _ rows]]
     214            0 :                       (empty? rows))
     215            0 :                      (digests action sets))]
     216            0 :            (future
     217            0 :             (try
     218            0 :               (doseq [[label opts rows] todo]
     219            0 :                 (send! bot (:telegram-id user) {:text (str "🧪 <b>" label "</b>")})
     220            0 :                 (Thread/sleep 400)
     221            0 :                 (if (= label "Відео: редагування повідомлення")
     222            0 :                   (send-video-edit! bot (:telegram-id user) (merge base opts) rows)
     223            0 :                   (send! bot (:telegram-id user) (render/render-digest (merge base opts) rows)))
     224            0 :                 (Thread/sleep 700))
     225              :               (catch Exception e
     226            0 :                 (t/log!
     227              :                  :warn
     228            0 :                  {:message "Dev notification samples failed"
     229            0 :                   :error   (ex-message e)}))))
     230            0 :            {:sent (count todo)}))))
     231              : 
     232              : 
     233            4 : (defn seed-feed!
     234              :  "Adds the sample rows to the caller's feed (Telegram status 'off', so the job never
     235              :   sends them). Returns the number of rows written."
     236              :  [{:keys [config ds user-id]}]
     237            7 :  (if-not (enabled? config)
     238              :    0
     239            0 :    (let [{:keys [main videos]} (sample-sets (detected-rows ds user-id))]
     240            0 :      (reduce
     241            0 :       (fn [n {:keys [kind payload corrected?]}]
     242            0 :        (+
     243            0 :         n
     244            0 :         (or
     245            0 :          (:next.jdbc/update-count
     246            0 :           (jdbc/execute-one!
     247            0 :            ds
     248            0 :            ["INSERT INTO user_updates
     249              :                  (user_id, source, kind, subject_key, event_id, revision, payload, tg_status,
     250              :                   created_datetime, updated_datetime)
     251              :                VALUES (?::uuid, ?, ?, ?, ?::uuid, 'dev', ?::jsonb, 'off',
     252              :                        now() - (CASE WHEN ? THEN interval '1 hour' ELSE interval '0' END), now())
     253              :                ON CONFLICT (user_id, kind, subject_key) DO UPDATE
     254              :                  SET payload = EXCLUDED.payload, read_at = NULL,
     255              :                      created_datetime = EXCLUDED.created_datetime,
     256              :                      updated_datetime = EXCLUDED.updated_datetime"
     257            0 :             (str user-id)
     258            0 :             (:source payload)
     259            0 :             kind
     260            0 :             (str sample-prefix kind ":" (or (:match-id payload) (:tournament-key payload)))
     261            0 :             (some->
     262            0 :               (:event-id payload)
     263            0 :               str
     264            0 :               not-empty)
     265            0 :             (json/generate-string payload)
     266            0 :             (boolean corrected?)]))
     267              :          0)))
     268              :       0
     269            0 :       (concat main videos)))))
     270              : 
     271              : 
     272            4 : (defn clear-feed!
     273              :  "Deletes the caller's sample feed rows. Returns the number deleted."
     274              :  [{:keys [config ds user-id]}]
     275            7 :  (if-not (enabled? config)
     276              :    0
     277            0 :    (or
     278            0 :     (:next.jdbc/update-count
     279            0 :      (jdbc/execute-one!
     280            0 :       ds
     281            0 :       ["DELETE FROM user_updates WHERE user_id = ?::uuid AND subject_key LIKE ?"
     282            0 :        (str user-id)
     283            0 :        (str (str/replace sample-prefix "_" "\\_") "%")]))
     284              :     0)))
        

Generated by: LCOV version 2.0-1