LCOV - code coverage report
Current view: top level - matchscore/db/postgres - user_updates.clj Coverage Total Hit
Test: lcov.info Lines: 94.9 % 411 390
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.db.postgres.user-updates
       2              :   (:require
       3              :    [cheshire.core :as json]
       4              :    [clojure.string :as str]
       5              :    [matchscore.domain.country-exclusion :as country-exclusion]
       6              :    [next.jdbc :as jdbc]
       7              :    [next.jdbc.result-set :as rs])
       8              :   (:import
       9              :    (java.nio.charset StandardCharsets)
      10              :    (java.time        Instant LocalDate)
      11              :    (java.util        Base64)))
      12              : 
      13              : 
      14           16 : (def ^:private options {:builder-fn rs/as-unqualified-kebab-maps})
      15              : 
      16              : 
      17           16 : (def ^:private allowed-sources #{"psa" "esf"})
      18              : 
      19              : 
      20            4 : (def ^:private catalog-allowed-sql
      21           28 :   (str
      22              :    "(CASE WHEN t.source = 'psa' THEN EXISTS ("
      23              :    "SELECT 1 FROM psa_tournaments pt WHERE pt.psa_id::text = t.tournament_key AND "
      24           12 :    (country-exclusion/allowed-sql "substring(pt.location from ', *([A-Za-z]{3}) *$')")
      25              :    ") WHEN t.source = 'esf' THEN EXISTS ("
      26              :    "SELECT 1 FROM esf_tournaments et WHERE et.ts_id::text = t.tournament_key AND "
      27           12 :    (country-exclusion/allowed-sql "et.country_code")
      28              :    ") ELSE false END)"))
      29              : 
      30              : 
      31            4 : (def ^:private match-allowed-sql
      32           20 :   (str
      33              :    "(mc.home_followed OR mc.away_followed OR ("
      34           12 :    (country-exclusion/allowed-sql "mc.home_country")
      35              :    " AND "
      36           12 :    (country-exclusion/allowed-sql "mc.away_country")
      37              :    "))"))
      38              : 
      39              : 
      40           25 : (defn- placeholders [n] (str/join ", " (repeat n "?")))
      41              : 
      42              : 
      43            4 : (defn- selected-sources
      44              :   [sources]
      45            9 :   (->>
      46            3 :     sources
      47            9 :     (filter allowed-sources)
      48            3 :     distinct
      49            3 :     sort
      50            3 :     vec))
      51              : 
      52              : 
      53            8 : (def ^:private context-ctes
      54              :   "WITH selected_tournaments AS (
      55              :      SELECT i.*, e.public_id AS event_public_id, e.name AS event_name,
      56              :             e.timezone AS venue_tz, e.state AS event_state
      57              :        FROM imported_tournaments i
      58              :        LEFT JOIN events e ON e.uuid = i.event_id
      59              :       WHERE i.source IN (%s)
      60              :         AND (i.event_id IS NULL OR e.state <> 'completed' OR i.date_end >= ?::date - 1)
      61              :    ),
      62              :    match_context AS (
      63              :      SELECT t.*, m.uuid AS match_id, m.home_participant_id, m.away_participant_id,
      64              :             m.datetime_start AS starts_at, m.state AS match_state,
      65              :             COALESCE(gd.name, bd.name, ec.name) AS draw_name,
      66              :             COALESCE(NULLIF(bm.label, ''), NULLIF(br.name, ''), NULLIF(g.name, ''),
      67              :                      NULLIF(s.name, '')) AS round_label,
      68              :             CASE WHEN t.source = 'psa' THEN hpp.psa_id::text
      69              :                  WHEN t.source = 'esf' THEN hru.rankedin_id::text END AS home_player_key,
      70              :             CASE WHEN t.source = 'psa' THEN app.psa_id::text
      71              :                  WHEN t.source = 'esf' THEN aru.rankedin_id::text END AS away_player_key,
      72              :             COALESCE(hpp.full_name,
      73              :                      NULLIF(trim(concat_ws(' ', hru.first_name, hru.last_name)), '')) AS home_name,
      74              :             COALESCE(app.full_name,
      75              :                      NULLIF(trim(concat_ws(' ', aru.first_name, aru.last_name)), '')) AS away_name,
      76              :             COALESCE(hpp.country_code, hru.country_code) AS home_country,
      77              :             COALESCE(app.country_code, aru.country_code) AS away_country,
      78              :             mr.uuid AS result_id, mr.winner_id, mr.outcome, mr.home_score, mr.away_score,
      79              :             COALESCE(seg.games, '[]'::jsonb) AS games,
      80              :             EXISTS (
      81              :               SELECT 1 FROM bracket_match_slots bms
      82              :                WHERE bms.bracket_match_id = m.bracket_match_id
      83              :                  AND bms.source_type = 'bye') AS has_bye
      84              :        FROM selected_tournaments t
      85              :        JOIN matches m ON m.event_id = t.event_id
      86              :        LEFT JOIN stages s ON s.uuid = m.stage_id
      87              :        LEFT JOIN event_classes ec ON ec.uuid = s.class_id
      88              :        LEFT JOIN groups g ON g.uuid = m.group_id
      89              :        LEFT JOIN draws gd ON gd.uuid = g.draw_id
      90              :        LEFT JOIN bracket_matches bm ON bm.uuid = m.bracket_match_id
      91              :        LEFT JOIN bracket_rounds br ON br.uuid = bm.bracket_round_id
      92              :        LEFT JOIN brackets b ON b.uuid = br.bracket_id
      93              :        LEFT JOIN draws bd ON bd.uuid = b.draw_id
      94              :        LEFT JOIN participants hp ON hp.uuid = m.home_participant_id
      95              :        LEFT JOIN rankedin_users hru ON hru.uuid = hp.user_id_rankedin
      96              :        LEFT JOIN psa_players hpp ON t.source = 'psa' AND hpp.rankedin_user_id = hp.user_id_rankedin
      97              :        LEFT JOIN participants ap ON ap.uuid = m.away_participant_id
      98              :        LEFT JOIN rankedin_users aru ON aru.uuid = ap.user_id_rankedin
      99              :        LEFT JOIN psa_players app ON t.source = 'psa' AND app.rankedin_user_id = ap.user_id_rankedin
     100              :        LEFT JOIN match_results mr ON mr.match_id = m.uuid
     101              :        LEFT JOIN LATERAL (
     102              :          SELECT jsonb_agg(jsonb_build_array(ms.home_score, ms.away_score)
     103              :                           ORDER BY ms.\"order\") AS games
     104              :            FROM match_segments ms WHERE ms.match_id = m.uuid) seg ON true
     105              :    ),
     106              :    coverage AS (
     107              :      SELECT s.user_id, t.source, t.tournament_key,
     108              :             bool_or(s.match_scope = 'all') AS all_scope
     109              :        FROM selected_tournaments t
     110              :        JOIN tournament_subscriptions s ON s.source = t.source
     111              :         AND (s.target = 'source'
     112              :           OR (s.target = 'tier' AND s.target_key = t.tier)
     113              :           OR (s.target = 'tournament' AND s.target_key = t.tournament_key))
     114              :       GROUP BY s.user_id, t.source, t.tournament_key
     115              :    ),
     116              :    follows AS (
     117              :      SELECT f.user_id, 'psa'::text AS source, f.psa_player_id::text AS player_key
     118              :        FROM psa_player_follows f
     119              :      UNION ALL
     120              :      SELECT f.user_id, 'esf', f.esid::text FROM esf_player_follows f
     121              :    ),
     122              :    recipients AS (
     123              :      SELECT mc.match_id, c.user_id, c.all_scope,
     124              :             EXISTS (SELECT 1 FROM follows f WHERE f.user_id = c.user_id
     125              :                      AND f.source = mc.source AND f.player_key = mc.home_player_key) AS home_followed,
     126              :             EXISTS (SELECT 1 FROM follows f WHERE f.user_id = c.user_id
     127              :                      AND f.source = mc.source AND f.player_key = mc.away_player_key) AS away_followed
     128              :        FROM match_context mc
     129              :        JOIN coverage c ON c.source = mc.source AND c.tournament_key = mc.tournament_key
     130              :      UNION
     131              :      SELECT mc.match_id, f.user_id, false,
     132              :             bool_or(f.player_key = mc.home_player_key),
     133              :             bool_or(f.player_key = mc.away_player_key)
     134              :        FROM match_context mc
     135              :        JOIN follows f ON f.source = mc.source
     136              :         AND f.player_key IN (mc.home_player_key, mc.away_player_key)
     137              :       GROUP BY mc.match_id, f.user_id
     138              :    ),
     139              :    match_candidates AS (
     140              :      SELECT r.user_id, mc.*,
     141              :             bool_or(r.all_scope) AS all_scope,
     142              :             bool_or(r.home_followed) AS home_followed,
     143              :             bool_or(r.away_followed) AS away_followed
     144              :        FROM recipients r JOIN match_context mc ON mc.match_id = r.match_id
     145              :       GROUP BY r.user_id, mc.source, mc.tournament_key, mc.name, mc.date_start,
     146              :                mc.date_end, mc.location, mc.tier, mc.event_id, mc.event_public_id,
     147              :                mc.event_name, mc.venue_tz, mc.event_state, mc.match_id,
     148              :                mc.home_participant_id, mc.away_participant_id, mc.starts_at,
     149              :                mc.match_state, mc.draw_name, mc.round_label, mc.home_player_key,
     150              :                mc.away_player_key, mc.home_name, mc.away_name, mc.home_country,
     151              :                mc.away_country, mc.result_id, mc.winner_id, mc.outcome, mc.home_score,
     152              :                mc.away_score, mc.games, mc.has_bye
     153              :    ),
     154              :    raw_candidates AS (
     155              :      SELECT s.user_id, t.source, 'tournament_new'::text AS kind,
     156              :             t.source || ':' || t.tournament_key AS subject_key, t.event_id,
     157              :             '1'::text AS revision,
     158              :             jsonb_build_object(
     159              :               'source', t.source, 'tournament-key', t.tournament_key,
     160              :               'tournament-name', t.name, 'event-id', t.event_id,
     161              :               'event-public-id', t.event_public_id, 'date-start', t.date_start,
     162              :               'date-end', t.date_end, 'location', t.location, 'tier-code', t.tier,
     163              :               'tier-label-en', tt.label_en, 'tier-label-uk', tt.label_uk) AS payload
     164              :        FROM selected_tournaments t
     165              :        JOIN tournament_subscriptions s ON s.source = t.source
     166              :         AND (s.target = 'source' OR (s.target = 'tier' AND s.target_key = t.tier))
     167              :        LEFT JOIN tournament_tiers tt ON tt.code = t.tier
     168              :       WHERE t.date_end >= ?::date AND %s
     169              :      UNION ALL
     170              :      SELECT c.user_id, t.source, 'draw_published', t.source || ':' || t.tournament_key,
     171              :             t.event_id, '1',
     172              :             jsonb_build_object(
     173              :               'source', t.source, 'tournament-key', t.tournament_key,
     174              :               'tournament-name', t.name, 'event-id', t.event_id,
     175              :               'event-public-id', t.event_public_id, 'date-start', t.date_start,
     176              :               'date-end', t.date_end)
     177              :        FROM selected_tournaments t
     178              :        JOIN coverage c ON c.source = t.source AND c.tournament_key = t.tournament_key
     179              :       WHERE %s AND EXISTS (SELECT 1 FROM match_context mc
     180              :                      WHERE mc.source = t.source AND mc.tournament_key = t.tournament_key
     181              :                        AND mc.home_participant_id IS NOT NULL
     182              :                        AND mc.away_participant_id IS NOT NULL AND NOT mc.has_bye)
     183              :      UNION ALL
     184              :      SELECT mc.user_id, mc.source, 'pairing', mc.match_id::text, mc.event_id,
     185              :             md5(coalesce(mc.home_player_key, '') || '|' || coalesce(mc.away_player_key, '')),
     186              :             jsonb_build_object(
     187              :               'source', mc.source, 'tournament-key', mc.tournament_key,
     188              :               'tournament-name', mc.name, 'event-id', mc.event_id,
     189              :               'event-public-id', mc.event_public_id, 'match-id', mc.match_id,
     190              :               'event-name', mc.event_name, 'draw-name', mc.draw_name,
     191              :               'round-label', mc.round_label,
     192              :               'home', jsonb_build_object('name', mc.home_name, 'country', mc.home_country,
     193              :                         'player-key', mc.home_player_key, 'followed', mc.home_followed),
     194              :               'away', jsonb_build_object('name', mc.away_name, 'country', mc.away_country,
     195              :                         'player-key', mc.away_player_key, 'followed', mc.away_followed),
     196              :               'starts-at', mc.starts_at, 'venue-tz', mc.venue_tz, 'videos', '[]'::jsonb)
     197              :        FROM match_candidates mc JOIN users u ON u.uuid = mc.user_id
     198              :       WHERE mc.home_participant_id IS NOT NULL AND mc.away_participant_id IS NOT NULL
     199              :         AND NOT mc.has_bye AND mc.result_id IS NULL AND %s
     200              :         AND (mc.all_scope OR ((mc.home_followed OR mc.away_followed)
     201              :              AND (?::boolean OR
     202              :                   (u.settings -> 'notifications' ->> 'followed-pairings') IS DISTINCT FROM 'false')))
     203              :      UNION ALL
     204              :      SELECT mc.user_id, mc.source, 'result', mc.match_id::text, mc.event_id,
     205              :             md5(coalesce(mc.home_participant_id::text, mc.home_player_key, '') || '|' ||
     206              :                 coalesce(mc.away_participant_id::text, mc.away_player_key, '') || '|' ||
     207              :                 coalesce(mc.winner_id::text, '') || '|' || coalesce(mc.outcome, '') || '|' ||
     208              :                 coalesce(mc.home_score::text, '') || ':' || coalesce(mc.away_score::text, '') ||
     209              :                 '|' || mc.games::text),
     210              :             jsonb_build_object(
     211              :               'source', mc.source, 'tournament-key', mc.tournament_key,
     212              :               'tournament-name', mc.name, 'event-id', mc.event_id,
     213              :               'event-public-id', mc.event_public_id, 'match-id', mc.match_id,
     214              :               'event-name', mc.event_name, 'draw-name', mc.draw_name,
     215              :               'round-label', mc.round_label,
     216              :               'home', jsonb_build_object('name', mc.home_name, 'country', mc.home_country,
     217              :                         'player-key', mc.home_player_key, 'followed', mc.home_followed),
     218              :               'away', jsonb_build_object('name', mc.away_name, 'country', mc.away_country,
     219              :                         'player-key', mc.away_player_key, 'followed', mc.away_followed),
     220              :               'starts-at', mc.starts_at, 'venue-tz', mc.venue_tz, 'videos', '[]'::jsonb,
     221              :               'winner', CASE WHEN mc.winner_id = mc.home_participant_id THEN 'home'
     222              :                              WHEN mc.winner_id = mc.away_participant_id THEN 'away' END,
     223              :               'outcome', mc.outcome, 'total', jsonb_build_array(mc.home_score, mc.away_score),
     224              :               'games', mc.games)
     225              :        FROM match_candidates mc JOIN users u ON u.uuid = mc.user_id
     226              :       WHERE mc.home_participant_id IS NOT NULL AND mc.away_participant_id IS NOT NULL
     227              :         AND NOT mc.has_bye AND mc.result_id IS NOT NULL AND %s
     228              :         AND (?::boolean OR
     229              :              (u.settings -> 'notifications' ->> 'results') IS DISTINCT FROM 'off')
     230              :         AND (mc.all_scope OR ((mc.home_followed OR mc.away_followed)
     231              :              AND (?::boolean OR
     232              :                   (u.settings -> 'notifications' ->> 'followed-results') IS DISTINCT FROM 'false')))
     233              :      UNION ALL
     234              :      SELECT uu.user_id, 'psa', 'video', v.match_id::text || ':' || v.video_id,
     235              :             uu.event_id, v.video_id,
     236              :             uu.payload || jsonb_build_object(
     237              :               'videos', jsonb_build_array(jsonb_build_object(
     238              :                 'kind', v.kind, 'video-id', v.video_id,
     239              :                 'url', 'https://www.youtube.com/watch?v=' || v.video_id)))
     240              :        FROM psa_match_videos v
     241              :        JOIN youtube_videos y ON y.video_id = v.video_id
     242              :        JOIN LATERAL (
     243              :          SELECT DISTINCT ON (candidate.user_id) candidate.*
     244              :            FROM user_updates candidate
     245              :           WHERE candidate.source = 'psa'
     246              :             AND candidate.subject_key = v.match_id::text
     247              :             AND candidate.kind IN ('pairing', 'result')
     248              :             AND (?::boolean OR NOT candidate.seeded)
     249              :             AND ((candidate.payload -> 'home' ->> 'followed') = 'true'
     250              :               OR (candidate.payload -> 'away' ->> 'followed') = 'true'
     251              :               OR (%s AND %s))
     252              :           ORDER BY candidate.user_id,
     253              :                    CASE candidate.kind WHEN 'result' THEN 0 ELSE 1 END
     254              :        ) uu ON true
     255              :        JOIN users u ON u.uuid = uu.user_id
     256              :       WHERE ?::boolean AND COALESCE(y.published_at, v.created_datetime) >= ?::timestamptz
     257              :         AND (?::boolean OR COALESCE(u.settings -> 'notifications' ->> 'video', 'new') = 'new')
     258              :    )
     259              :    SELECT DISTINCT ON (r.user_id, r.kind, r.subject_key)
     260              :           r.user_id, r.source, r.kind, r.subject_key, r.event_id, r.revision, r.payload,
     261              :           CASE WHEN u.telegram_id IS NOT NULL
     262              :                     AND u.telegram_bot_access_status NOT IN ('denied', 'blocked')
     263              :                     AND (u.settings -> 'notifications' ->> 'telegram') IS DISTINCT FROM 'false'
     264              :                THEN 'pending' ELSE 'off' END AS tg_status
     265              :      FROM raw_candidates r
     266              :      JOIN users u ON u.uuid = r.user_id
     267              :      LEFT JOIN user_updates old ON old.user_id = r.user_id AND old.kind = r.kind
     268              :       AND old.subject_key = r.subject_key
     269              :     WHERE ?::boolean OR old.uuid IS NULL OR old.revision <> r.revision
     270              :     ORDER BY r.user_id, r.kind, r.subject_key")
     271              : 
     272              : 
     273            4 : (defn detect
     274              :  [ds {:keys [sources today video-since seeding?]}]
     275           12 :  (let [sources (selected-sources sources)]
     276           12 :    (if (empty? sources)
     277            0 :      []
     278            6 :      (jdbc/execute!
     279            3 :       ds
     280            6 :       (into
     281            9 :        [(format
     282            3 :          context-ctes
     283           12 :          (placeholders (count sources))
     284            3 :          catalog-allowed-sql
     285            3 :          catalog-allowed-sql
     286            3 :          match-allowed-sql
     287            3 :          match-allowed-sql
     288            9 :          (country-exclusion/allowed-sql "candidate.payload -> 'home' ->> 'country'")
     289            9 :          (country-exclusion/allowed-sql "candidate.payload -> 'away' ->> 'country'"))]
     290            6 :        (concat
     291            3 :         sources
     292           24 :         [(str (or today (LocalDate/now)))
     293           21 :          (str (or today (LocalDate/now)))
     294            6 :          (boolean seeding?)
     295            6 :          (boolean seeding?)
     296            6 :          (boolean seeding?)
     297            6 :          (boolean seeding?)
     298           18 :          (contains? (set sources) "psa")
     299           21 :          (str (or video-since (.minusSeconds (Instant/now) (* 14 86400))))
     300            6 :          (boolean seeding?)
     301            6 :          (boolean seeding?)]))
     302            3 :       options))))
     303              : 
     304              : 
     305           28 : (defn- update-count [result] (long (or (:next.jdbc/update-count result) 0)))
     306              : 
     307              : 
     308            4 : (def ^:private visible-change-sql
     309              :   "True when a revised row changes what the user sees. A result only counts as changed
     310              :   when its players, winner, outcome or score differ; any other revision change (for
     311              :   example a new revision formula) must not show it as corrected, unread or re-sent."
     312            4 :   (let [visible
     313            4 :         (fn [t]
     314           52 :          (str
     315              :           "("
     316            4 :           t
     317              :           ".payload -> 'winner', "
     318            4 :           t
     319              :           ".payload -> 'outcome', "
     320            4 :           t
     321              :           ".payload -> 'total', "
     322            4 :           t
     323              :           ".payload -> 'games', "
     324              :           "COALESCE("
     325            4 :           t
     326              :           ".payload #> '{home,player-key}', "
     327            4 :           t
     328              :           ".payload #> '{home,name}'), "
     329              :           "COALESCE("
     330            4 :           t
     331              :           ".payload #> '{away,player-key}', "
     332            4 :           t
     333              :           ".payload #> '{away,name}'))"))]
     334           20 :     (str
     335              :      "(user_updates.kind <> 'result' OR "
     336           12 :      (visible "user_updates")
     337              :      " IS DISTINCT FROM "
     338           12 :      (visible "EXCLUDED")
     339              :      ")")))
     340              : 
     341              : 
     342            4 : (def ^:private upsert-sql
     343            4 :   (let [when-visible
     344            4 :         (fn [changed unchanged]
     345           24 :          (format "CASE WHEN %s THEN %s ELSE %s END" visible-change-sql changed unchanged))]
     346           36 :     (str
     347              :      "INSERT INTO user_updates
     348              :         (user_id, source, kind, subject_key, event_id, revision, payload, tg_status)
     349              :       VALUES (?::uuid, ?, ?, ?, ?::uuid, ?, ?::jsonb, ?)
     350              :       ON CONFLICT (user_id, kind, subject_key) DO UPDATE
     351              :         SET source = EXCLUDED.source, event_id = EXCLUDED.event_id,
     352              :             revision = EXCLUDED.revision, payload = EXCLUDED.payload,
     353              :             read_at = "
     354           16 :      (when-visible "NULL" "user_updates.read_at")
     355              :      ",
     356              :             tg_status = "
     357           16 :      (when-visible "EXCLUDED.tg_status" "user_updates.tg_status")
     358              :      ",
     359              :             seeded = "
     360           16 :      (when-visible "false" "user_updates.seeded")
     361              :      ",
     362              :             tg_attempts = "
     363           16 :      (when-visible "0" "user_updates.tg_attempts")
     364              :      ",
     365              :             tg_last_error = "
     366           16 :      (when-visible "NULL" "user_updates.tg_last_error")
     367              :      ",
     368              :             updated_datetime = "
     369           16 :      (when-visible "now()" "user_updates.updated_datetime")
     370              :      "
     371              :       WHERE user_updates.revision <> EXCLUDED.revision")))
     372              : 
     373              : 
     374            4 : (defn upsert-updates!
     375              :  [ds rows]
     376            9 :  (reduce
     377            3 :   (fn [n {:keys [user-id source kind subject-key event-id revision payload tg-status]}]
     378            1 :    (+
     379            1 :     n
     380            2 :     (update-count
     381            2 :      (jdbc/execute-one!
     382            1 :       ds
     383            2 :       [upsert-sql
     384            3 :        (str user-id)
     385            1 :        source
     386            1 :        kind
     387            1 :        subject-key
     388            8 :        (some->
     389            1 :          event-id
     390            1 :          str)
     391            1 :        revision
     392            7 :        (if (string? payload) payload (json/generate-string payload))
     393            1 :        tg-status]))))
     394              :   0
     395            3 :   rows))
     396              : 
     397              : 
     398            4 : (defn scan-and-store!
     399              :  "Persist normal candidates in two passes; videos can depend on a stored match row."
     400              :  [ds opts user-id]
     401            6 :  (let [for-user (fn [rows]
     402           28 :                  (if user-id (filterv #(= (str user-id) (str (:user-id %))) rows) rows))
     403           18 :        rows     (for-user (detect ds opts))
     404           12 :        stored   (upsert-updates! ds rows)
     405           24 :        videos   (if (pos? stored) (for-user (detect ds opts)) [])]
     406           24 :    {:detected (+ (count rows) (count videos))
     407           25 :     :stored   (+ stored (if (seq videos) (upsert-updates! ds videos) 0))}))
     408              : 
     409              : 
     410            4 : (defn flush-user!
     411              :  "Persist already-covered candidates before a new subscription or follow expands coverage."
     412              :  [tx user-id source]
     413            6 :  (:stored
     414            6 :   (scan-and-store!
     415            3 :    tx
     416           18 :    {:sources     #{source}
     417            6 :     :today       (LocalDate/now)
     418           18 :     :video-since (.minusSeconds (Instant/now) (* 14 86400))}
     419            3 :    user-id)))
     420              : 
     421              : 
     422            4 : (defn refresh-pairing-times!
     423              :  [ds {:keys [sources]}]
     424            8 :  (let [sources (selected-sources sources)]
     425            8 :    (if (empty? sources)
     426              :      0
     427            4 :      (update-count
     428            4 :       (jdbc/execute-one!
     429            2 :        ds
     430            4 :        (into
     431            8 :         [(format
     432              :           "UPDATE user_updates uu
     433              :               SET payload = jsonb_set(
     434              :                     jsonb_set(uu.payload, '{starts-at}',
     435              :                               COALESCE(to_jsonb(m.datetime_start), 'null'::jsonb), true),
     436              :                     '{venue-tz}', COALESCE(to_jsonb(e.timezone), 'null'::jsonb), true)
     437              :              FROM matches m
     438              :              JOIN imported_tournaments i ON i.event_id = m.event_id
     439              :              JOIN events e ON e.uuid = i.event_id
     440              :             WHERE uu.kind = 'pairing' AND uu.source = i.source
     441              :               AND uu.subject_key = m.uuid::text AND uu.source IN (%s)
     442              :               AND (uu.payload -> 'starts-at' IS DISTINCT FROM
     443              :                    COALESCE(to_jsonb(m.datetime_start), 'null'::jsonb)
     444              :                 OR uu.payload -> 'venue-tz' IS DISTINCT FROM
     445              :                    COALESCE(to_jsonb(e.timezone), 'null'::jsonb))"
     446            8 :           (placeholders (count sources)))]
     447            2 :         sources))))))
     448              : 
     449              : 
     450            4 : (defn- cursor-encode
     451              :   [row]
     452           20 :   (let [raw (str (:updated-datetime row) "|" (:uuid row))]
     453            2 :     (.encodeToString
     454            6 :      (.withoutPadding (Base64/getUrlEncoder))
     455            4 :      (.getBytes raw StandardCharsets/UTF_8))))
     456              : 
     457              : 
     458            4 : (defn- cursor-decode
     459              :   [cursor]
     460            6 :   (when cursor
     461           14 :     (let [raw (String. (.decode (Base64/getUrlDecoder) cursor) StandardCharsets/UTF_8)
     462           10 :           [timestamp uuid] (str/split raw #"\|" 2)]
     463            6 :       [timestamp uuid])))
     464              : 
     465              : 
     466            4 : (defn feed-page
     467              :  "One page of the user's feed, newest first. `unread-only?` leaves out the
     468              :    rows already read."
     469              :  [ds user-id {:keys [cursor limit retention-days unread-only?]}]
     470            2 :  (let
     471            4 :    [limit (->
     472           12 :             (or limit 30)
     473              :             long
     474            6 :             (max 1)
     475              :             (min 100))
     476            6 :     [timestamp uuid] (cursor-decode cursor)
     477              :     rows
     478            4 :     (jdbc/execute!
     479            2 :      ds
     480            4 :      ["SELECT * FROM user_updates
     481              :                 WHERE user_id = ?::uuid AND NOT seeded
     482              :                   AND updated_datetime >= now() - (? * interval '1 day')
     483              :                   AND (NOT ?::boolean OR read_at IS NULL)
     484              :                   AND (?::timestamptz IS NULL OR (updated_datetime, uuid) < (?::timestamptz, ?::uuid))
     485              :                 ORDER BY updated_datetime DESC, uuid DESC LIMIT ?"
     486            6 :       (str user-id)
     487           13 :       (long (or retention-days 90))
     488            4 :       (boolean unread-only?)
     489            2 :       timestamp
     490            2 :       timestamp
     491            2 :       uuid
     492            4 :       (inc limit)]
     493            2 :      options)
     494            8 :     more? (> (count rows) limit)
     495           12 :     items (vec (take limit rows))]
     496            8 :    {:items       items
     497           16 :     :next-cursor (when more? (cursor-encode (last items)))}))
     498              : 
     499              : 
     500            4 : (defn unread-count
     501            5 :  ([ds user-id] (unread-count ds user-id 90))
     502              :  ([ds user-id retention-days]
     503            4 :   (:count
     504            4 :    (jdbc/execute-one!
     505            2 :     ds
     506            4 :     ["SELECT count(*)::int AS count FROM user_updates
     507              :        WHERE user_id = ?::uuid AND NOT seeded AND read_at IS NULL
     508              :          AND updated_datetime >= now() - (? * interval '1 day')"
     509            6 :      (str user-id)
     510            4 :      (long retention-days)]
     511            2 :     options))))
     512              : 
     513              : 
     514            4 : (defn mark-read!
     515              :  [ds user-id up-to-or-nil]
     516            4 :  (update-count
     517            4 :   (jdbc/execute-one!
     518            2 :    ds
     519            4 :    ["UPDATE user_updates SET read_at = now()
     520              :       WHERE user_id = ?::uuid AND NOT seeded AND read_at IS NULL
     521              :         AND (?::timestamptz IS NULL OR updated_datetime <= ?::timestamptz)"
     522            6 :     (str user-id)
     523           16 :     (some->
     524            2 :       up-to-or-nil
     525            1 :       str)
     526           16 :     (some->
     527            2 :       up-to-or-nil
     528            1 :       str)])))
     529              : 
     530              : 
     531            4 : (defn set-read!
     532              :  "Marks the user's own feed items `ids` read (`read?` true) or unread again
     533              :    (false). Rows already in that state, seeded rows and other users' rows are
     534              :    left alone. Returns how many rows changed."
     535              :  [ds user-id ids read?]
     536            6 :  (let [ids (->>
     537            2 :              ids
     538            6 :              (keep
     539           32 :               #(some->
     540              :                  %
     541            2 :                  str
     542            2 :                  parse-uuid))
     543            2 :              distinct
     544            2 :              vec)]
     545            9 :    (if (empty? ids)
     546              :      0
     547            4 :      (update-count
     548            4 :       (jdbc/execute-one!
     549            2 :        ds
     550            4 :        (into
     551            8 :         [(format
     552              :           "UPDATE user_updates
     553              :               SET read_at = %s
     554              :             WHERE user_id = ?::uuid AND NOT seeded
     555              :               AND read_at IS %s NULL
     556              :               AND uuid IN (%s)"
     557            8 :           (if read? "now()" "NULL")
     558            8 :           (if read? "" "NOT")
     559           16 :           (str/join ", " (repeat (count ids) "?::uuid")))
     560            6 :          (str user-id)]
     561            8 :         (map str ids)))))))
     562              : 
     563              : 
     564            4 : (defn deliverable
     565              :  [ds {:keys [limit max-attempts sources]}]
     566            8 :  (let [sources (selected-sources sources)
     567           16 :        in-sql  (if (seq sources) (placeholders (count sources)) "NULL")]
     568            8 :    (jdbc/with-transaction
     569            2 :     [tx ds]
     570            4 :     (jdbc/execute-one!
     571            2 :      tx
     572            4 :      (into
     573           10 :       [(str
     574              :         "UPDATE user_updates uu SET tg_status = 'off', tg_edit_pending = false
     575              :            FROM users u
     576              :           WHERE u.uuid = uu.user_id AND uu.tg_status IN ('pending', 'failed')
     577              :             AND (uu.source NOT IN ("
     578            2 :         in-sql
     579              :         ") OR u.telegram_id IS NULL
     580              :               OR u.telegram_bot_access_status IN ('denied', 'blocked')
     581              :               OR (u.settings -> 'notifications' ->> 'telegram') = 'false')")]
     582            2 :       sources))
     583            8 :     (if (empty? sources)
     584            0 :       []
     585            4 :       (jdbc/execute!
     586            2 :        tx
     587            4 :        (into
     588            8 :         [(format
     589              :           "SELECT uu.*, u.telegram_id, u.telegram_bot_access_status,
     590              :            u.settings ->> 'language' AS language,
     591              :            u.settings ->> 'timezone' AS timezone,
     592              :            u.settings -> 'notifications' AS notifications
     593              :       FROM user_updates uu JOIN users u ON u.uuid = uu.user_id
     594              :      WHERE uu.tg_status IN ('pending', 'failed') AND uu.tg_attempts < ?
     595              :        AND NOT uu.seeded AND uu.source IN (%s) AND u.telegram_id IS NOT NULL
     596              :        AND u.telegram_bot_access_status IS DISTINCT FROM 'denied'
     597              :        AND u.telegram_bot_access_status IS DISTINCT FROM 'blocked'
     598              :        AND (u.settings -> 'notifications' ->> 'telegram') IS DISTINCT FROM 'false'
     599              :      ORDER BY uu.user_id, uu.created_datetime, uu.uuid LIMIT ?"
     600            2 :           in-sql)
     601           12 :          (long (or max-attempts 5))]
     602           20 :         (concat sources [(long (or limit 100))]))
     603            2 :        options)))))
     604              : 
     605              : 
     606            4 : (defn claim-deliverable!
     607              :  "Revalidate stale batch ids and lock eligible rows for the send transaction."
     608              :  [tx update-uuids max-attempts]
     609            4 :  (if (empty? update-uuids)
     610            0 :    []
     611            2 :    (jdbc/execute!
     612            1 :     tx
     613            2 :     (into
     614            5 :      [(str
     615              :        "SELECT uu.*, u.telegram_id, u.telegram_bot_access_status,
     616              :                 u.settings ->> 'language' AS language,
     617              :                 u.settings ->> 'timezone' AS timezone,
     618              :                 u.settings -> 'notifications' AS notifications
     619              :            FROM user_updates uu JOIN users u ON u.uuid = uu.user_id
     620              :           WHERE uu.uuid IN ("
     621            8 :        (str/join ", " (repeat (count update-uuids) "?::uuid"))
     622              :        ")
     623              :             AND uu.tg_status IN ('pending', 'failed') AND uu.tg_attempts < ?
     624              :             AND NOT uu.seeded AND u.telegram_id IS NOT NULL
     625              :             AND u.telegram_bot_access_status IS DISTINCT FROM 'denied'
     626              :             AND u.telegram_bot_access_status IS DISTINCT FROM 'blocked'
     627              :             AND (u.settings -> 'notifications' ->> 'telegram') IS DISTINCT FROM 'false'
     628              :           ORDER BY uu.created_datetime, uu.uuid FOR UPDATE OF uu SKIP LOCKED")]
     629            9 :      (concat (map str update-uuids) [(long max-attempts)]))
     630            1 :     options)))
     631              : 
     632              : 
     633            8 : (declare message-rows)
     634              : 
     635              : 
     636            4 : (defn edit-pending
     637              :  [ds {:keys [limit sources]}]
     638            8 :  (let [sources (selected-sources sources)
     639           16 :        in-sql  (if (seq sources) (placeholders (count sources)) "NULL")]
     640            8 :    (jdbc/with-transaction
     641            2 :     [tx ds]
     642            4 :     (jdbc/execute-one!
     643            2 :      tx
     644            4 :      (into
     645           10 :       [(str
     646              :         "UPDATE user_updates uu SET tg_edit_pending = false
     647              :            FROM users u
     648              :           WHERE u.uuid = uu.user_id AND uu.tg_edit_pending
     649              :             AND (uu.source NOT IN ("
     650            2 :         in-sql
     651              :         ") OR u.telegram_id IS NULL
     652              :               OR u.telegram_bot_access_status IN ('denied', 'blocked')
     653              :               OR (u.settings -> 'notifications' ->> 'telegram') = 'false'
     654              :               OR COALESCE(u.settings -> 'notifications' ->> 'video', 'new') = 'off')")]
     655            2 :       sources))
     656            8 :     (if (empty? sources)
     657            0 :       []
     658            2 :       (let
     659              :         [messages
     660            4 :          (jdbc/execute!
     661            2 :           tx
     662            4 :           (into
     663            8 :            [(format
     664              :              "SELECT DISTINCT tm.* FROM telegram_update_messages tm
     665              :                     JOIN user_updates uu ON uu.tg_message_uuid = tm.uuid
     666              :                     JOIN users u ON u.uuid = uu.user_id
     667              :                    WHERE uu.tg_edit_pending AND uu.source IN (%s)
     668              :                      AND u.telegram_id IS NOT NULL
     669              :                      AND u.telegram_bot_access_status IS DISTINCT FROM 'denied'
     670              :                      AND u.telegram_bot_access_status IS DISTINCT FROM 'blocked'
     671              :                      AND (u.settings -> 'notifications' ->> 'telegram') IS DISTINCT FROM 'false'
     672              :                      AND COALESCE(u.settings -> 'notifications' ->> 'video', 'new') <> 'off'
     673              :                    ORDER BY tm.sent_at, tm.uuid LIMIT ?"
     674            2 :              in-sql)]
     675           20 :            (concat sources [(long (or limit 100))]))
     676            2 :           options)]
     677           18 :         (mapv #(assoc % :rows (message-rows tx (:uuid %))) messages))))))
     678              : 
     679              : 
     680            4 : (defn save-message!
     681              :  [tx {:keys [user-id telegram-id message-id locale]}]
     682            4 :  (:uuid
     683            4 :   (jdbc/execute-one!
     684            2 :    tx
     685            4 :    ["INSERT INTO telegram_update_messages (user_id, telegram_id, message_id, locale)
     686              :       VALUES (?::uuid, ?, ?, ?) RETURNING uuid"
     687            6 :     (str user-id)
     688            2 :     telegram-id
     689            2 :     message-id
     690            2 :     locale]
     691            2 :    options)))
     692              : 
     693              : 
     694           20 : (defn- uuid-placeholders [ids] (str/join ", " (repeat (count ids) "?::uuid")))
     695              : 
     696              : 
     697            4 : (defn mark-sent!
     698              :  [tx update-uuids message-uuid]
     699            8 :  (if (empty? update-uuids)
     700              :    0
     701            4 :    (update-count
     702            4 :     (jdbc/execute-one!
     703            2 :      tx
     704            4 :      (into
     705           10 :       [(str
     706              :         "UPDATE user_updates SET tg_status = 'sent', tg_message_uuid = ?::uuid,
     707              :                     tg_last_error = NULL, tg_edit_pending = false
     708              :               WHERE uuid IN ("
     709            6 :         (uuid-placeholders update-uuids)
     710              :         ")")
     711            6 :        (str message-uuid)]
     712            8 :       (map str update-uuids))))))
     713              : 
     714              : 
     715            4 : (defn mark-failed!
     716              :  [ds update-uuids error max-attempts]
     717            4 :  (if (empty? update-uuids)
     718              :    0
     719            2 :    (update-count
     720            2 :     (jdbc/execute-one!
     721            1 :      ds
     722            2 :      (into
     723            5 :       [(str
     724              :         "UPDATE user_updates
     725              :                 SET tg_attempts = tg_attempts + 1, tg_last_error = ?,
     726              :                     tg_status = CASE WHEN tg_attempts + 1 >= ? THEN 'skipped' ELSE 'failed' END
     727              :               WHERE uuid IN ("
     728            3 :         (uuid-placeholders update-uuids)
     729              :         ")")
     730            3 :        (str error)
     731            2 :        (long max-attempts)]
     732            4 :       (map str update-uuids))))))
     733              : 
     734              : 
     735            4 : (defn mark-edit-failed!
     736              :  [ds message-uuid error max-attempts terminal?]
     737            2 :  (update-count
     738            2 :   (jdbc/execute-one!
     739            1 :    ds
     740            2 :    ["UPDATE user_updates
     741              :        SET tg_attempts = tg_attempts + 1, tg_last_error = ?,
     742              :            tg_edit_pending = CASE
     743              :              WHEN tg_edit_pending AND (?::boolean OR tg_attempts + 1 >= ?) THEN false
     744              :              ELSE tg_edit_pending END
     745              :      WHERE tg_message_uuid = ?::uuid"
     746            3 :     (str error)
     747            2 :     (boolean terminal?)
     748            2 :     (long max-attempts)
     749            3 :     (str message-uuid)])))
     750              : 
     751              : 
     752            4 : (defn mark-edited!
     753              :  [ds message-uuid]
     754            0 :  (jdbc/with-transaction
     755            0 :   [tx ds]
     756            0 :   (jdbc/execute-one!
     757            0 :    tx
     758            0 :    ["UPDATE telegram_update_messages SET edited_at = now() WHERE uuid = ?::uuid"
     759            0 :     (str message-uuid)])
     760            0 :   (update-count
     761            0 :    (jdbc/execute-one!
     762            0 :     tx
     763            0 :     ["UPDATE user_updates SET tg_edit_pending = false
     764              :         WHERE tg_message_uuid = ?::uuid AND tg_edit_pending"
     765            0 :      (str message-uuid)]))))
     766              : 
     767              : 
     768            4 : (defn clear-edit-pending!
     769              :  [ds message-uuid]
     770            0 :  (update-count
     771            0 :   (jdbc/execute-one!
     772            0 :    ds
     773            0 :    ["UPDATE user_updates SET tg_edit_pending = false
     774              :      WHERE tg_message_uuid = ?::uuid AND tg_edit_pending"
     775            0 :     (str message-uuid)])))
     776              : 
     777              : 
     778            4 : (defn message-rows
     779              :  [ds message-uuid]
     780            2 :  (jdbc/execute!
     781            1 :   ds
     782            2 :   ["SELECT * FROM user_updates
     783              :      WHERE tg_message_uuid = ?::uuid ORDER BY created_datetime, uuid"
     784            3 :    (str message-uuid)]
     785            1 :   options))
     786              : 
     787              : 
     788            4 : (defn claim-edit-rows!
     789              :  "Lock the complete current digest only while an edit is still pending."
     790              :  [tx message-uuid update-uuids]
     791            4 :  (if (empty? update-uuids)
     792            0 :    []
     793            2 :    (jdbc/execute!
     794            1 :     tx
     795            2 :     (into
     796            5 :      [(str
     797              :        "SELECT uu.* FROM user_updates uu
     798              :               WHERE uu.tg_message_uuid = ?::uuid
     799              :                 AND uu.uuid IN ("
     800            3 :        (uuid-placeholders update-uuids)
     801              :        ")
     802              :                 AND EXISTS (SELECT 1 FROM user_updates pending
     803              :                              WHERE pending.tg_message_uuid = uu.tg_message_uuid
     804              :                                AND pending.tg_edit_pending)
     805              :               ORDER BY uu.created_datetime, uu.uuid
     806              :               FOR UPDATE OF uu SKIP LOCKED")
     807            3 :       (str message-uuid)]
     808            4 :      (map str update-uuids))
     809            1 :     options)))
     810              : 
     811              : 
     812            4 : (defn delete-older-than!
     813              :  [ds days]
     814            2 :  (update-count
     815            2 :   (jdbc/execute-one!
     816            1 :    ds
     817            2 :    ["DELETE FROM user_updates uu
     818              :       WHERE uu.updated_datetime < now() - (? * interval '1 day')
     819              :         AND (CASE WHEN uu.kind = 'tournament_new' THEN
     820              :                NOT EXISTS (SELECT 1 FROM imported_tournaments i
     821              :                             WHERE i.source = uu.source
     822              :                               AND i.tournament_key = split_part(uu.subject_key, ':', 2)
     823              :                               AND i.date_end >= current_date)
     824              :                   WHEN uu.kind = 'draw_published' THEN
     825              :                NOT EXISTS (SELECT 1 FROM imported_tournaments i
     826              :                             LEFT JOIN events e ON e.uuid = i.event_id
     827              :                             WHERE i.source = uu.source
     828              :                               AND i.tournament_key = split_part(uu.subject_key, ':', 2)
     829              :                               AND (i.event_id IS NULL OR e.state <> 'completed'
     830              :                                    OR i.date_end >= current_date - 1))
     831              :                   WHEN uu.kind IN ('pairing', 'result', 'video') THEN
     832              :                NOT EXISTS (SELECT 1 FROM matches m
     833              :                             JOIN imported_tournaments i ON i.event_id = m.event_id
     834              :                             JOIN events e ON e.uuid = m.event_id
     835              :                            WHERE m.uuid::text = split_part(uu.subject_key, ':', 1)
     836              :                              AND i.source = uu.source
     837              :                              AND (e.state <> 'completed'
     838              :                                   OR i.date_end >= current_date - 1))
     839              :                   ELSE true END)"
     840            2 :     (long days)])))
     841              : 
     842              : 
     843           30 : (defn- payload-value [payload key] (or (get payload key) (get payload (name key))))
     844              : 
     845              : 
     846            4 : (defn- subscription-includes?
     847              :   [ds {:keys [source target target-key]} row]
     848           12 :   (let [payload        (:payload row)
     849           18 :         tournament-key (str (payload-value payload :tournament-key))
     850            9 :         target         (name target)]
     851           18 :     (and
     852           15 :      (= source (:source row))
     853            3 :      (case target
     854              :        "source" true
     855           10 :        "tournament" (= (str target-key) tournament-key)
     856              :        "tier"
     857            1 :        (=
     858            3 :         (str target-key)
     859            2 :         (:tier
     860            2 :          (jdbc/execute-one!
     861            1 :           ds
     862            2 :           ["SELECT tier FROM imported_tournaments
     863              :                       WHERE source = ? AND tournament_key = ?"
     864            1 :            source
     865            1 :            tournament-key]
     866            1 :           options)))
     867              :        false))))
     868              : 
     869              : 
     870            4 : (defn- follow-scope-includes?
     871              :   [player-key row]
     872            8 :   (let [payload  (:payload row)
     873           14 :         home-key (payload-value (payload-value payload :home) :player-key)
     874           14 :         away-key (payload-value (payload-value payload :away) :player-key)]
     875            9 :     (and
     876           18 :      (contains? #{"pairing" "result" "video"} (:kind row))
     877           22 :      (contains? #{(str home-key) (str away-key)} (str player-key)))))
     878              : 
     879              : 
     880            4 : (defn- insert-seed!
     881              :   [tx user-id {:keys [source kind subject-key event-id revision payload]}]
     882            6 :   (update-count
     883            6 :    (jdbc/execute-one!
     884            3 :     tx
     885            6 :     ["INSERT INTO user_updates
     886              :            (user_id, source, kind, subject_key, event_id, revision,
     887              :             payload, seeded, tg_status)
     888              :          SELECT ?::uuid, ?, ?, ?, ?::uuid, ?, ?::jsonb, true, 'skipped'
     889              :          WHERE ? <> 'pairing'
     890              :             OR NULLIF(?::jsonb ->> 'starts-at', '')::timestamptz <= now()
     891              :          ON CONFLICT DO NOTHING"
     892            9 :      (str user-id)
     893            3 :      source
     894            3 :      kind
     895            3 :      subject-key
     896           23 :      (some->
     897            3 :        event-id
     898            2 :        str)
     899            3 :      revision
     900            9 :      (json/generate-string payload)
     901            3 :      kind
     902            9 :      (json/generate-string payload)])))
     903              : 
     904              : 
     905            4 : (defn seed!
     906              :  [tx
     907              :   user-id
     908              :   {:keys [type source player-key]
     909              :    :as   scope}]
     910           21 :  (let [video-since (.minusSeconds (Instant/now) (* 14 86400))
     911            3 :        in-scope?   (fn [row]
     912           17 :                     (and
     913           27 :                      (= (str user-id) (str (:user-id row)))
     914            3 :                      (case type
     915            8 :                        :follow       (follow-scope-includes? player-key row)
     916           15 :                        :subscription (subscription-includes? tx scope row)
     917              :                        false)))]
     918            6 :    (reduce
     919            3 :     +
     920          193 :     (for [_ (range 2)
     921            6 :           row (filter
     922            3 :                in-scope?
     923            6 :                (detect
     924            3 :                 tx
     925           24 :                 {:sources     #{source}
     926            6 :                  :today       (LocalDate/now)
     927            3 :                  :video-since video-since
     928              :                  :seeding?    true}))]
     929           15 :       (insert-seed! tx user-id row)))))
     930              : 
     931              : 
     932            4 : (defn attach-videos!
     933              :  [ds {:keys [sources video-since]}]
     934            8 :  (if-not (some #{"psa"} sources)
     935              :    0
     936            4 :    (jdbc/with-transaction
     937            1 :     [tx ds]
     938            1 :     (let
     939            7 :       [since (str (or video-since (.minusSeconds (Instant/now) (* 14 86400))))
     940              :        updated
     941            2 :        (update-count
     942            2 :         (jdbc/execute-one!
     943            1 :          tx
     944            4 :          [(format
     945              :            "WITH targets AS (
     946              :                   SELECT DISTINCT ON (uu.user_id, v.match_id, v.video_id)
     947              :                          uu.uuid, v.video_id, v.kind,
     948              :                          (u.telegram_id IS NOT NULL
     949              :                           AND u.telegram_bot_access_status NOT IN ('denied', 'blocked')
     950              :                           AND (u.settings -> 'notifications' ->> 'telegram') IS DISTINCT FROM 'false')
     951              :                            AS telegram_eligible,
     952              :                          'https://www.youtube.com/watch?v=' || v.video_id AS url
     953              :                     FROM psa_match_videos v
     954              :                     JOIN youtube_videos y ON y.video_id = v.video_id
     955              :                     JOIN user_updates uu ON uu.source = 'psa'
     956              :                      AND uu.subject_key = v.match_id::text
     957              :                      AND uu.kind IN ('result', 'pairing') AND NOT uu.seeded
     958              :                     JOIN users u ON u.uuid = uu.user_id
     959              :                    WHERE COALESCE(y.published_at, v.created_datetime) >= ?::timestamptz
     960              :                      AND ((uu.payload -> 'home' ->> 'followed') = 'true'
     961              :                        OR (uu.payload -> 'away' ->> 'followed') = 'true'
     962              :                        OR (%s AND %s))
     963              :                      AND COALESCE(u.settings -> 'notifications' ->> 'video', 'new') = 'edit'
     964              :                      AND NOT EXISTS (
     965              :                        SELECT 1 FROM jsonb_array_elements(COALESCE(uu.payload -> 'videos', '[]')) x
     966              :                         WHERE x ->> 'video-id' = v.video_id)
     967              :                    ORDER BY uu.user_id, v.match_id, v.video_id,
     968              :                             CASE uu.kind WHEN 'result' THEN 0 ELSE 1 END)
     969              :                 UPDATE user_updates uu
     970              :                    SET payload = jsonb_set(
     971              :                          uu.payload, '{videos}',
     972              :                          COALESCE(uu.payload -> 'videos', '[]'::jsonb) ||
     973              :                          jsonb_build_array(jsonb_build_object(
     974              :                            'kind', t.kind, 'video-id', t.video_id, 'url', t.url))),
     975              :                        tg_edit_pending = uu.tg_status = 'sent' AND t.telegram_eligible
     976              :                   FROM targets t WHERE uu.uuid = t.uuid"
     977            3 :            (country-exclusion/allowed-sql "uu.payload -> 'home' ->> 'country'")
     978            3 :            (country-exclusion/allowed-sql "uu.payload -> 'away' ->> 'country'"))
     979            1 :           since]))
     980              :        inserted
     981            2 :        (update-count
     982            2 :         (jdbc/execute-one!
     983            1 :          tx
     984            4 :          [(format
     985              :            "WITH video_context AS (
     986              :                   SELECT v.match_id, v.video_id, v.kind, y.published_at,
     987              :                          i.tournament_key, i.name AS tournament_name, i.event_id,
     988              :                          e.public_id AS event_public_id, e.name AS event_name,
     989              :                          e.timezone AS venue_tz, m.datetime_start AS starts_at,
     990              :                          hp.user_id_rankedin AS home_rankedin_id,
     991              :                          ap.user_id_rankedin AS away_rankedin_id,
     992              :                          hpp.psa_id::text AS home_player_key,
     993              :                          app.psa_id::text AS away_player_key,
     994              :                          hpp.full_name AS home_name, app.full_name AS away_name,
     995              :                          hpp.country_code AS home_country, app.country_code AS away_country,
     996              :                          mr.winner_id, mr.outcome, mr.home_score, mr.away_score,
     997              :                          COALESCE(seg.games, '[]'::jsonb) AS games
     998              :                     FROM psa_match_videos v
     999              :                     JOIN youtube_videos y ON y.video_id = v.video_id
    1000              :                     JOIN imported_tournaments i ON i.source = 'psa'
    1001              :                      AND i.tournament_key = v.psa_tournament_id::text
    1002              :                     JOIN events e ON e.uuid = i.event_id
    1003              :                     JOIN matches m ON m.uuid = v.match_id
    1004              :                     JOIN participants hp ON hp.uuid = m.home_participant_id
    1005              :                     JOIN participants ap ON ap.uuid = m.away_participant_id
    1006              :                     LEFT JOIN psa_players hpp ON hpp.rankedin_user_id = hp.user_id_rankedin
    1007              :                     LEFT JOIN psa_players app ON app.rankedin_user_id = ap.user_id_rankedin
    1008              :                     LEFT JOIN match_results mr ON mr.match_id = m.uuid
    1009              :                     LEFT JOIN LATERAL (
    1010              :                       SELECT jsonb_agg(jsonb_build_array(ms.home_score, ms.away_score)
    1011              :                                        ORDER BY ms.\"order\") AS games
    1012              :                         FROM match_segments ms WHERE ms.match_id = m.uuid) seg ON true
    1013              :                    WHERE COALESCE(y.published_at, v.created_datetime) >= ?::timestamptz),
    1014              :                 eligible AS (
    1015              :                   SELECT DISTINCT u.uuid AS user_id, vc.*,
    1016              :                          EXISTS (SELECT 1 FROM psa_player_follows f
    1017              :                                   WHERE f.user_id = u.uuid
    1018              :                                     AND f.psa_player_id::text = vc.home_player_key) AS home_followed,
    1019              :                          EXISTS (SELECT 1 FROM psa_player_follows f
    1020              :                                   WHERE f.user_id = u.uuid
    1021              :                                     AND f.psa_player_id::text = vc.away_player_key) AS away_followed
    1022              :                     FROM video_context vc
    1023              :                     JOIN users u ON COALESCE(u.settings -> 'notifications' ->> 'video', 'new') = 'edit'
    1024              :                    WHERE NOT EXISTS (
    1025              :                            SELECT 1 FROM user_updates old
    1026              :                             WHERE old.user_id = u.uuid AND old.source = 'psa'
    1027              :                               AND old.subject_key = vc.match_id::text
    1028              :                               AND old.kind IN ('pairing', 'result') AND NOT old.seeded)
    1029              :                      AND (EXISTS (
    1030              :                            SELECT 1 FROM tournament_subscriptions s
    1031              :                             JOIN imported_tournaments i ON i.source = s.source
    1032              :                              AND i.tournament_key = vc.tournament_key
    1033              :                            WHERE s.user_id = u.uuid AND s.source = 'psa'
    1034              :                              AND s.match_scope = 'all'
    1035              :                              AND (s.target = 'source'
    1036              :                                OR (s.target = 'tier' AND s.target_key = i.tier)
    1037              :                                OR (s.target = 'tournament' AND s.target_key = i.tournament_key)))
    1038              :                        OR EXISTS (SELECT 1 FROM psa_player_follows f
    1039              :                                    WHERE f.user_id = u.uuid
    1040              :                                      AND f.psa_player_id::text IN
    1041              :                                          (vc.home_player_key, vc.away_player_key))))
    1042              :                 INSERT INTO user_updates
    1043              :                       (user_id, source, kind, subject_key, event_id, revision,
    1044              :                        payload, tg_status)
    1045              :                 SELECT eligible.user_id, 'psa', 'video',
    1046              :                        eligible.match_id::text || ':' || eligible.video_id,
    1047              :                        eligible.event_id, eligible.video_id,
    1048              :                        jsonb_build_object(
    1049              :                          'source', 'psa', 'tournament-key', eligible.tournament_key,
    1050              :                          'tournament-name', eligible.tournament_name,
    1051              :                          'event-id', eligible.event_id,
    1052              :                          'event-public-id', eligible.event_public_id,
    1053              :                          'match-id', eligible.match_id,
    1054              :                          'event-name', eligible.event_name, 'draw-name', NULL,
    1055              :                          'round-label', NULL,
    1056              :                          'home', jsonb_build_object(
    1057              :                            'name', eligible.home_name, 'country', eligible.home_country,
    1058              :                            'player-key', eligible.home_player_key,
    1059              :                            'followed', eligible.home_followed),
    1060              :                          'away', jsonb_build_object(
    1061              :                            'name', eligible.away_name, 'country', eligible.away_country,
    1062              :                            'player-key', eligible.away_player_key,
    1063              :                            'followed', eligible.away_followed),
    1064              :                          'starts-at', eligible.starts_at, 'venue-tz', eligible.venue_tz,
    1065              :                          'videos', jsonb_build_array(jsonb_build_object(
    1066              :                            'kind', eligible.kind, 'video-id', eligible.video_id,
    1067              :                            'url', 'https://www.youtube.com/watch?v=' || eligible.video_id)),
    1068              :                          'winner', CASE
    1069              :                            WHEN eligible.winner_id IS NULL THEN NULL
    1070              :                            WHEN eligible.winner_id = (SELECT home_participant_id FROM matches
    1071              :                                                        WHERE uuid = eligible.match_id) THEN 'home'
    1072              :                            ELSE 'away' END,
    1073              :                          'outcome', eligible.outcome,
    1074              :                          'total', jsonb_build_array(eligible.home_score, eligible.away_score),
    1075              :                          'games', eligible.games),
    1076              :                        CASE WHEN u.telegram_id IS NOT NULL
    1077              :                                   AND u.telegram_bot_access_status NOT IN ('denied', 'blocked')
    1078              :                                   AND (u.settings -> 'notifications' ->> 'telegram') IS DISTINCT FROM 'false'
    1079              :                             THEN 'pending' ELSE 'off' END
    1080              :                   FROM eligible JOIN users u ON u.uuid = eligible.user_id
    1081              :                  WHERE eligible.home_followed OR eligible.away_followed
    1082              :                     OR (%s AND %s)
    1083              :                 ON CONFLICT DO NOTHING"
    1084            3 :            (country-exclusion/allowed-sql "eligible.home_country")
    1085            3 :            (country-exclusion/allowed-sql "eligible.away_country"))
    1086            1 :           since]))]
    1087            3 :       (+ updated inserted)))))
        

Generated by: LCOV version 2.0-1