LCOV - code coverage report
Current view: top level - matchscore/jobs - telegram_payment_reminder.clj Coverage Total Hit
Test: lcov.info Lines: 84.5 % 265 224
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.jobs.telegram-payment-reminder
       2              :   (:require
       3              :    [cats.core :as c]
       4              :    [cats.monad.either :as either]
       5              :    [cheshire.core :as json]
       6              :    [matchscore.db.postgres.payment-methods :as payment-methods]
       7              :    [matchscore.db.postgres.payment-tracking :as payment-tracking]
       8              :    [matchscore.domain.event.repository.postgres :as event-postgres-repo]
       9              :    [matchscore.domain.telegram-chat-message.repository.postgres
      10              :     :as
      11              :     telegram-chat-message-postgres-repo]
      12              :    [matchscore.domain.telegram-link.query :as telegram-link-query]
      13              :    [matchscore.domain.template.repository.postgres :as template-postgres-repo]
      14              :    [matchscore.jobs.telegram-notifications :as notification-jobs]
      15              :    [matchscore.telegram.event-lock :as event-lock]
      16              :    [matchscore.telegram.localization :as l10n]
      17              :    [matchscore.telegram.messages :as messages]
      18              :    [matchscore.telegram.payment-details-message :as payment-message]
      19              :    [matchscore.telegram.payment-reminder-rules :as rules]
      20              :    [taoensso.telemere :as t]
      21              :    [telegrambot-lib.core :as tbot])
      22              :   (:import
      23              :    (java.time Instant OffsetDateTime ZonedDateTime)
      24              :    (java.util Date)))
      25              : 
      26              : 
      27            4 : (defn- ->instant
      28              :   [value]
      29           12 :   (cond (instance? Instant value)        value
      30           10 :         (instance? Date value)           (.toInstant ^Date value)
      31            0 :         (instance? OffsetDateTime value) (.toInstant ^OffsetDateTime value)
      32            0 :         (instance? ZonedDateTime value)  (.toInstant ^ZonedDateTime value)
      33              :         :else                            nil))
      34              : 
      35              : 
      36           11 : (defn- config-value [config key] (or (get config key) (get config (name key))))
      37              : 
      38              : 
      39            4 : (defn- already-sent?
      40              :   [messages {:keys [chat-id thread-id]}]
      41            1 :   (boolean
      42            3 :    (some
      43            9 :     #(and
      44            5 :       (= "payment_details_post" (:kind %))
      45            5 :       (= chat-id (:chat-id %))
      46            4 :       (= thread-id (:thread-id %)))
      47            1 :     messages)))
      48              : 
      49              : 
      50            4 : (defn- require-saved!
      51              :   [result]
      52            8 :   (when (either/left? result)
      53            0 :     (throw
      54            0 :      (ex-info "Failed to save Telegram payment reminder tracking" {:error (c/extract result)})))
      55            2 :   result)
      56              : 
      57              : 
      58            8 : (def ^:private payment-post-kinds payment-message/post-kinds)
      59              : 
      60              : 
      61           20 : (defn- payments-enabled? [event] (true? (get-in event [:settings :payments-enabled])))
      62              : 
      63              : 
      64            4 : (defn- tracking
      65              :   "Who has paid, when the event tracks payments; nil otherwise."
      66              :   [pg event]
      67            9 :   (when (payments-enabled? event)
      68            2 :     (payment-message/tracking-summary
      69            8 :      (payment-message/player-statuses (payment-tracking/registrations pg (:uuid event))))))
      70              : 
      71              : 
      72            4 : (defn- render
      73              :   "Text and keyboard of the live payment post. Once everyone has paid it is
      74              :    closed: no details and no buttons."
      75              :   [repos event template methods tracking]
      76           10 :   (let [locale (l10n/message-locale repos event)]
      77            8 :     (if (:all-paid tracking)
      78            8 :       {:text (payment-message/format-closed-message event locale :all-paid tracking)}
      79           20 :       {:text     (payment-message/format-message event template methods locale tracking)
      80           14 :        :keyboard (payment-message/copy-keyboard methods locale (some? tracking))})))
      81              : 
      82              : 
      83           16 : (def ^:private no-keyboard {:inline_keyboard []})
      84              : 
      85              : 
      86            4 : (defn- edit-post!
      87              :   "Edits a payment post in place; returns :ok or :missing (see `messages/edit!`)."
      88              :   [telegram-bot {:keys [chat-id message-id]} text keyboard]
      89            2 :   (messages/edit!
      90            1 :    telegram-bot
      91            9 :    {:chat_id      chat-id
      92            1 :     :message_id   message-id
      93            1 :     :text         text
      94              :     :parse_mode   "HTML"
      95            3 :     :link_preview_options {:is_disabled true}
      96            8 :     :reply_markup (json/generate-string (or keyboard no-keyboard))}))
      97              : 
      98              : 
      99            4 : (defn- send-to-link!
     100              :   "Posts the payment post to one link and records it. Returns the message id."
     101              :   [repos
     102              :    telegram-bot
     103              :    event
     104              :    kind
     105              :    {:keys [text keyboard]}
     106              :    {:keys [chat-id thread-id]
     107              :     :as   link}]
     108            4 :   (let [result     (try
     109            4 :                      (messages/request!
     110            2 :                       tbot/send-message
     111            2 :                       telegram-bot
     112           14 :                       (cond->
     113           14 :                         {:chat_id    chat-id
     114            2 :                          :text       text
     115              :                          :parse_mode "HTML"
     116            6 :                          :link_preview_options {:is_disabled true}}
     117            2 :                         thread-id (assoc :message_thread_id thread-id)
     118           10 :                         keyboard  (assoc :reply_markup (json/generate-string keyboard))))
     119              :                      (catch clojure.lang.ExceptionInfo e
     120            0 :                        (notification-jobs/record-delivery-failure! repos link e)
     121            0 :                        (throw e)))
     122           12 :         message-id (get-in result [:result :message_id])]
     123            6 :     (when-not message-id
     124            0 :       (throw (ex-info "Telegram send returned no message id" {:chat-id chat-id})))
     125            4 :     (require-saved!
     126            4 :      (telegram-chat-message-postgres-repo/record!
     127            6 :       (:telegram-chat-message-postgres-repo repos)
     128           20 :       {:chat-id     chat-id
     129            2 :        :thread-id   thread-id
     130            2 :        :message-id  message-id
     131              :        :sender-kind "bot"
     132            2 :        :kind        kind
     133            2 :        :text        text
     134            6 :        :event-id    (:uuid event)}))
     135            2 :     message-id))
     136              : 
     137              : 
     138            4 : (defn- retire-post!
     139              :   "Removes a payment post from its chat. One Telegram refuses to delete (older
     140              :    than 48 h) is edited to `fallback-text` without details or buttons instead.
     141              :    Returns true once the post is gone or closed; throws on other failures."
     142              :   [telegram-bot
     143              :    {:keys [chat-id message-id]
     144              :     :as   post}
     145              :    fallback-text]
     146            3 :   (try
     147            4 :     (messages/request!
     148            2 :      tbot/delete-message
     149            2 :      telegram-bot
     150            8 :      {:chat_id    chat-id
     151            2 :       :message_id message-id})
     152              :     true
     153              :     (catch clojure.lang.ExceptionInfo e
     154           13 :       (cond (messages/error-matches? e "message to delete not found") true
     155              : 
     156            8 :             (messages/error-matches? e "message can't be deleted")
     157            8 :             (do (edit-post! telegram-bot post fallback-text nil) true)
     158              : 
     159            2 :             :else (throw e)))))
     160              : 
     161              : 
     162            4 : (defn- mark-retired!
     163              :   [repo event-id posts]
     164            9 :   (when (seq posts)
     165            8 :     (let [saved (telegram-chat-message-postgres-repo/mark-deleted! repo (mapv :uuid posts))]
     166            4 :       (when (either/left? saved)
     167            0 :         (t/log!
     168              :          :warn
     169            0 :          {:message  "Failed to track retired Telegram payment posts"
     170            0 :           :event-id event-id
     171            0 :           :error    (c/extract saved)})))))
     172              : 
     173              : 
     174            4 : (defn- retire-previous!
     175              :   "After a fresh payment post, removes the chat's earlier ones so the chat has a
     176              :    single live post. One Telegram refuses to delete (older than 48 h) is edited
     177              :    to point at the new post instead. Never throws: the new post is already out,
     178              :    and a retry would post it again."
     179              :   [repos telegram-bot event {:keys [chat-id thread-id]} new-message-id]
     180            8 :   (let [repo     (:telegram-chat-message-postgres-repo repos)
     181            8 :         locale   (l10n/message-locale repos event)
     182           12 :         fallback (payment-message/format-closed-message event locale :replaced nil)
     183            6 :         priors   (filterv
     184           22 :                   #(and
     185           10 :                     (payment-post-kinds (:kind %))
     186           10 :                     (= chat-id (:chat-id %))
     187           10 :                     (= thread-id (:thread-id %))
     188           10 :                     (not= new-message-id (:message-id %)))
     189           12 :                   (telegram-chat-message-postgres-repo/find-undeleted-for-event repo (:uuid event)))
     190            4 :         retired  (filterv
     191            2 :                   (fn [prior]
     192            3 :                    (try
     193           10 :                      (retire-post! telegram-bot prior fallback)
     194              :                      (catch Exception e
     195           92 :                        (t/log!
     196              :                         :warn
     197            7 :                         {:message    "Failed to retire an earlier Telegram payment post"
     198            3 :                          :event-id   (:uuid event)
     199            1 :                          :chat-id    chat-id
     200            3 :                          :message-id (:message-id prior)
     201            1 :                          :exception  e})
     202              :                        false)))
     203            2 :                   priors)]
     204           14 :     (mark-retired! repo (:uuid event) retired)))
     205              : 
     206              : 
     207            4 : (defn- load-event
     208              :   "The event (with an Instant start) and its template, or nil."
     209              :   [repos event-id]
     210           26 :   (when-let [event (event-postgres-repo/find-by-id (:event-postgres-repo repos) event-id {})]
     211           10 :     [(assoc event
     212           16 :       :datetime-start (some->
     213            6 :                         (:datetime-start event)
     214            2 :                         ->instant))
     215           15 :      (when-let [template-id (:template-id event)]
     216            7 :        (template-postgres-repo/find-by-id (:template-postgres-repo repos) template-id {}))]))
     217              : 
     218              : 
     219            4 : (defn- live-methods
     220              :   "Live methods among `selected`, grouped by owner, each with the owner's name
     221              :    (when several organizers are involved) and its resolved payment purpose."
     222              :   [pg event template selected]
     223            6 :   (let [methods (payment-methods/grouped-by-owner
     224            2 :                  selected
     225            8 :                  (payment-methods/find-live-by-ids pg selected))
     226           20 :         names   (when (< 1 (count (distinct (map :user-id methods))))
     227            0 :                   (payment-methods/owner-names pg (map :user-id methods)))]
     228            6 :     (mapv
     229           10 :      #(assoc %
     230           10 :        :owner-name       (get names (:user-id %))
     231           10 :        :resolved-purpose (rules/resolve-purpose % event template))
     232            2 :      methods)))
     233              : 
     234              : 
     235            4 : (defn- event-links
     236              :   [system-components event]
     237            4 :   (telegram-link-query/resolve-links-for-event
     238           16 :    (select-keys system-components [:pg :repos :redis :goose])
     239            2 :    event))
     240              : 
     241              : 
     242            4 : (defn- post-to-links!
     243              :   "Posts the payment post to each link, replacing that chat's previous one, and
     244              :    returns the failures. A failed chat does not stop the others."
     245              :   [{:keys [pg repos telegram-bot]} event template methods selected kind links]
     246           14 :   (payment-tracking/save-post-selection! pg (:uuid event) selected)
     247           22 :   (let [post (render repos event template methods (tracking pg event))]
     248            4 :     (reduce
     249            2 :      (fn [errors link]
     250            2 :       (try
     251           18 :         (let [message-id (send-to-link! repos telegram-bot event kind post link)]
     252           14 :           (retire-previous! repos telegram-bot event link message-id))
     253            2 :         errors
     254              :         (catch Exception e
     255            0 :           (t/log!
     256              :            :warn
     257            0 :            {:message   "Failed to send Telegram payment details"
     258            0 :             :kind      kind
     259            0 :             :event-id  (:uuid event)
     260            0 :             :chat-id   (:chat-id link)
     261            0 :             :exception e})
     262            0 :           (conj errors e))))
     263            2 :      []
     264            2 :      links)))
     265              : 
     266              : 
     267            4 : (defn payment-reminder-job
     268              :  [system-components event-id]
     269            2 :  (event-lock/with-lock
     270            3 :   (:pg system-components)
     271            1 :   event-id
     272            1 :   (fn []
     273            2 :    (let [{:keys [pg repos]} system-components
     274            4 :          [event template] (load-event repos event-id)
     275            7 :          config (when event (rules/active-config event template))]
     276           19 :      (when (and (:datetime-start event) config (rules/due? config event (Instant/now)))
     277            8 :        (let [selected (mapv str (config-value config :payment-method-ids))
     278            6 :              methods  (live-methods pg event template selected)]
     279            6 :          (if-not (seq methods)
     280           92 :            (t/log!
     281              :             :info
     282            4 :             {:message  "Telegram payment reminder has no live payment methods"
     283            1 :              :event-id event-id})
     284            3 :            (let [sent     (telegram-chat-message-postgres-repo/find-by-event-id
     285            3 :                            (:telegram-chat-message-postgres-repo repos)
     286            1 :                            event-id)
     287           11 :                  pending  (remove #(already-sent? sent %) (event-links system-components event))
     288            5 :                  failures (when (seq pending)
     289            3 :                             (post-to-links!
     290            1 :                              system-components
     291            1 :                              event
     292            1 :                              template
     293            1 :                              methods
     294            1 :                              selected
     295              :                              "payment_details_post"
     296            1 :                              pending))]
     297            6 :              (when-let [error (first failures)] (throw error))))))))))
     298              : 
     299              : 
     300            4 : (defn send-payment-details-job
     301              :  "Posts the chosen payment methods to every chat linked to the event right
     302              :    away, on an organizer's request, replacing each chat's previous payment post.
     303              :    It is recorded as a separate kind, so the scheduled payment reminder still
     304              :    goes out. Failures are not retried: a retry would post twice to the chats
     305              :    that already got the message."
     306              :  [system-components event-id method-ids]
     307            4 :  (event-lock/with-lock
     308            6 :   (:pg system-components)
     309            2 :   event-id
     310            2 :   (fn []
     311            4 :    (let [{:keys [pg repos]} system-components
     312            8 :          [event template] (load-event repos event-id)
     313            8 :          selected         (mapv str method-ids)
     314           18 :          methods          (when event (live-methods pg event template selected))]
     315           12 :      (cond (not event)
     316            0 :            (t/log!
     317              :             :info
     318            0 :             {:message  "Payment details post skipped: event not found"
     319            0 :              :event-id event-id})
     320              : 
     321            6 :            (empty? methods)
     322            0 :            (t/log!
     323              :             :info
     324            0 :             {:message  "Payment details post skipped: no live payment methods"
     325            0 :              :event-id event-id})
     326              : 
     327              :            :else
     328            6 :            (post-to-links!
     329            2 :             system-components
     330            2 :             event
     331            2 :             template
     332            2 :             methods
     333            2 :             selected
     334              :             "payment_details_manual_post"
     335            8 :             (event-links system-components event)))))))
     336              : 
     337              : 
     338            4 : (defn- remove-settled-posts!
     339              :   "The event is over and everyone has paid: the payment posts have done their
     340              :    job, so they leave the chats. Ones too old to delete keep the closed
     341              :    \"everyone has paid\" text."
     342              :   [{:keys [repos telegram-bot]} event summary posts]
     343            4 :   (let [repo     (:telegram-chat-message-postgres-repo repos)
     344            4 :         locale   (l10n/message-locale repos event)
     345            6 :         fallback (payment-message/format-closed-message event locale :all-paid summary)
     346            2 :         results  (mapv
     347            1 :                   (fn [post]
     348            1 :                    (try
     349            5 :                      (retire-post! telegram-bot post fallback)
     350            1 :                      {:post post}
     351              :                      (catch Exception e
     352            0 :                        (t/log!
     353              :                         :warn
     354            0 :                         {:message   "Failed to remove settled Telegram payment post"
     355            0 :                          :event-id  (:uuid event)
     356            0 :                          :chat-id   (:chat-id post)
     357            0 :                          :exception e})
     358            0 :                        {:post  post
     359            0 :                         :error e})))
     360            1 :                   posts)]
     361           13 :     (mark-retired! repo (:uuid event) (map :post (remove :error results)))
     362            4 :     (keep :error results)))
     363              : 
     364              : 
     365            4 : (defn refresh-payment-posts-job
     366              :  "Re-renders the event's live payment posts after payments, the roster or the
     367              :    event state change: who has paid, the \"I paid\" button, and the closed
     368              :    version once everyone has paid. When the event is completed and everyone has
     369              :    paid, the posts are removed from the chats instead. Posts whose text is
     370              :    unchanged are left alone. Cancelled events are left to the cancellation
     371              :    cleanup."
     372              :  [system-components event-id]
     373            2 :  (event-lock/with-lock
     374            3 :   (:pg system-components)
     375            1 :   event-id
     376            1 :   (fn []
     377            2 :    (let [{:keys [pg repos telegram-bot]} system-components
     378            3 :          repo    (:telegram-chat-message-postgres-repo repos)
     379            4 :          [event template] (load-event repos event-id)
     380           12 :          posts   (when (and event (not= "cancelled" (:state event)))
     381            3 :                    (filterv
     382            5 :                     #(payment-post-kinds (:kind %))
     383            4 :                     (telegram-chat-message-postgres-repo/find-undeleted-for-event repo event-id)))
     384            9 :          summary (when (seq posts) (tracking pg event))]
     385            3 :      (cond
     386            3 :        (empty? posts) nil
     387              : 
     388           12 :        (and (= "completed" (:state event)) (:all-paid summary))
     389           11 :        (when-let [error (first (remove-settled-posts! system-components event summary posts))]
     390            0 :          (throw error))
     391              : 
     392              :        :else
     393            1 :        (let [methods
     394           11 :              (live-methods pg event template (vec (payment-tracking/post-selection pg event-id)))]
     395            9 :          (when (or (seq methods) (:all-paid summary))
     396            8 :            (let [{:keys [text keyboard]} (render repos event template methods summary)
     397              :                  failures
     398            2 :                  (reduce
     399            1 :                   (fn [errors post]
     400            1 :                    (try
     401            9 :                      (if (= :missing (edit-post! telegram-bot post text keyboard))
     402            0 :                        (require-saved!
     403            0 :                         (telegram-chat-message-postgres-repo/mark-deleted! repo [(:uuid post)]))
     404            2 :                        (telegram-chat-message-postgres-repo/update-post!
     405            1 :                         repo
     406            3 :                         (:chat-id post)
     407            3 :                         (:message-id post)
     408            1 :                         text
     409            3 :                         (:kind post)))
     410            1 :                      errors
     411              :                      (catch Exception e
     412            0 :                        (t/log!
     413              :                         :warn
     414            0 :                         {:message   "Failed to refresh Telegram payment post"
     415            0 :                          :event-id  event-id
     416            0 :                          :chat-id   (:chat-id post)
     417            0 :                          :exception e})
     418            0 :                        (conj errors e))))
     419            1 :                   []
     420            9 :                   (remove #(= text (:text %)) posts))]
     421            6 :              (when-let [error (first failures)] (throw error))))))))))
        

Generated by: LCOV version 2.0-1