Line data Source code
1 4 : (ns matchscore.jobs.telegram-callbacks
2 : (:require
3 : [cats.core :as c]
4 : [cats.monad.either :as either]
5 : [clojure.string :as str]
6 : [honey.sql :as sql]
7 : [matchscore.application.event-creation-access :as event-creation-access]
8 : [matchscore.application.event.add-participant :as add-participant]
9 : [matchscore.application.event.remove-participant :as remove-participant]
10 : [matchscore.db.postgres.payment-tracking :as payment-tracking]
11 : [matchscore.domain.class-participant.command :as class-participant-command]
12 : [matchscore.domain.class-participant.repository.postgres :as class-participant-postgres-repo]
13 : [matchscore.domain.event-participant.repository.postgres :as event-participant-postgres-repo]
14 : [matchscore.domain.event.command :as event-command]
15 : [matchscore.domain.event.repository.postgres :as event-postgres-repo]
16 : [matchscore.domain.user.command :as user-command]
17 : [matchscore.domain.user.query :as user-query]
18 : [matchscore.jobs.telegram-name-reminder :as name-jobs]
19 : [matchscore.telegram.commands :as commands]
20 : [matchscore.telegram.localization :as l10n]
21 : [matchscore.telegram.notifications-trigger :as notifications-trigger]
22 : [matchscore.utils.audit :as audit]
23 : [matchscore.utils.db :as utils.db]
24 : [matchscore.utils.nanoid :as nanoid]
25 : [matchscore.utils.uuid :as uuid-utils]
26 : [next.jdbc :as jdbc]
27 : [taoensso.carmine :as car]
28 : [taoensso.telemere :as t]
29 : [telegrambot-lib.core :as tbot])
30 : (:import
31 : (java.time Instant)))
32 :
33 :
34 4 : (defn- jdbc-rows
35 : [pg query-map]
36 8 : (let [ds (or (:datasource pg) pg)]
37 1 : (->>
38 3 : (sql/format query-map)
39 3 : (jdbc/execute! ds)
40 2 : (mapv utils.db/unqualify-keys))))
41 :
42 :
43 4 : (defn- message-event-id
44 : [pg chat-id thread-id message-id]
45 6 : (when message-id
46 12 : (let [effective-thread (or thread-id -1)]
47 48 : (some->
48 4 : (jdbc-rows
49 2 : pg
50 16 : {:select [:event-id]
51 4 : :from [:telegram-chat-messages]
52 4 : :where [:and
53 8 : [:= :chat-id chat-id]
54 8 : [:= :thread-id effective-thread]
55 8 : [:= :message-id message-id]
56 8 : [:is-not :event-id nil]]
57 : :limit 1})
58 2 : first
59 : :event-id
60 2 : str))))
61 :
62 :
63 4 : (defn- resolve-chat-event
64 : "Resolves the event for a callback. The clicked participant-list message wins.
65 : A destination may hold several event links next to template links, so the link
66 : fallback is used only when the directly linked events and the active/scheduled
67 : events of the linked templates amount to exactly one event; otherwise the
68 : callback is ambiguous and must not be routed to an arbitrary event."
69 : [{:keys [pg repos]} chat-id thread-id message-id]
70 12 : (let [effective-thread (or thread-id -1)
71 6 : event-repo (:event-postgres-repo repos)
72 12 : message-event-id (message-event-id pg chat-id thread-id message-id)]
73 9 : (or
74 16 : (when message-event-id (event-postgres-repo/find-by-id event-repo message-event-id {}))
75 10 : (let [destination [:and [:= :chat-id chat-id] [:= :thread-id effective-thread]]
76 1 : direct-events (->>
77 2 : (jdbc-rows
78 1 : pg
79 7 : {:select [:event-id]
80 2 : :from [:telegram_event_links]
81 1 : :where destination
82 4 : :order-by [[:created-datetime :asc]]})
83 2 : (keep
84 9 : #(event-postgres-repo/find-by-id event-repo (str (:event-id %)) {})))
85 1 : template-events (->>
86 2 : (jdbc-rows
87 1 : pg
88 7 : {:select [:template-id]
89 2 : :from [:telegram_template_links]
90 1 : :where destination
91 4 : :order-by [[:created-datetime :asc]]})
92 3 : (mapcat
93 2 : #(event-postgres-repo/find-by-template-id
94 1 : event-repo
95 5 : (str (:template-id %))
96 1 : {}))
97 10 : (filter #(contains? #{"active" "scheduled"} (:state %))))
98 1 : events (->>
99 4 : (concat direct-events template-events)
100 9 : (into {} (map (juxt :uuid identity)))
101 1 : vals)]
102 9 : (when (= 1 (count events)) (first events))))))
103 :
104 :
105 4 : (defn- decode-data
106 : "Decodes callback data 'j:<pid?>' or 'l:<pid?>' into {:op :join|:leave :class-pid <str?>}."
107 : [data]
108 5 : (when (string? data)
109 6 : (let [[op pid] (str/split data #":" 2)
110 12 : class-pid (when (and pid (not= "" pid)) pid)]
111 4 : (case op
112 4 : "j" {:op :join
113 1 : :class-pid class-pid}
114 4 : "l" {:op :leave
115 1 : :class-pid class-pid}
116 : nil))))
117 :
118 :
119 4 : (defn- answer-callback!
120 : "Calls answerCallbackQuery. Silently logs failures. With `url` (a t.me/<bot>?start=
121 : link) Telegram opens the bot's private chat; `alert?` shows the text as a dialog."
122 12 : ([bot callback-id text] (answer-callback! bot callback-id text nil))
123 : ([bot callback-id text {:keys [url alert?]}]
124 2 : (try
125 4 : (tbot/answer-callback-query
126 2 : bot
127 25 : (cond-> {:callback_query_id callback-id}
128 10 : text (assoc :text text)
129 5 : alert? (assoc :show_alert true)
130 4 : url (assoc :url url)))
131 : (catch Exception e
132 0 : (t/log!
133 : :warn
134 0 : {:message "answer-callback-query failed"
135 0 : :exception e})))))
136 :
137 :
138 4 : (defn- close-access-request-message!
139 : [bot {:keys [chat-id message-id message-text]} request]
140 11 : (when (and chat-id message-id message-text)
141 1 : (try
142 2 : (tbot/edit-message-text
143 1 : bot
144 6 : {:chat_id chat-id
145 1 : :message_id message-id
146 3 : :text (str
147 1 : message-text
148 : "\n\n"
149 7 : (if (= "approved" (:status request)) "✅ Approved" "❌ Declined"))
150 3 : :reply_markup {:inline_keyboard []}})
151 : (catch Exception e
152 0 : (t/log!
153 : :warn
154 0 : {:message "Failed to close event creation access request message"
155 0 : :request-id (:uuid request)
156 0 : :exception e})))))
157 :
158 :
159 4 : (defn- process-access-request-callback!
160 : [{:keys [repos telegram-bot]
161 : :as ctx}
162 : {:keys [callback-id sender-tg-id]
163 : :as payload}
164 : {:keys [request-id decision]}]
165 3 : (let [reviewer-id (user-query/find-uuid-by-telegram-id
166 3 : (:user-postgres-repo repos)
167 3 : (:user-redis-repo repos)
168 1 : sender-tg-id)
169 3 : result (when reviewer-id
170 6 : (event-creation-access/review-request! ctx request-id reviewer-id decision))]
171 5 : (case (:outcome result)
172 1 : :reviewed (do
173 2 : (event-creation-access/notify-requester!
174 1 : ctx
175 1 : telegram-bot
176 3 : (:request result))
177 7 : (close-access-request-message! telegram-bot payload (:request result))
178 2 : (answer-callback!
179 1 : telegram-bot
180 1 : callback-id
181 5 : (if (= decision "approved") "Access approved" "Access declined")))
182 :
183 0 : :already-reviewed (do
184 0 : (close-access-request-message! telegram-bot payload (:request result))
185 0 : (answer-callback!
186 0 : telegram-bot
187 0 : callback-id
188 0 : (str "Already " (:status (:request result)))))
189 :
190 0 : :not-found (answer-callback! telegram-bot callback-id "Request not found")
191 :
192 0 : (answer-callback! telegram-bot callback-id "Only root users can review this request"))))
193 :
194 :
195 4 : (defn- send-deep-link!
196 : [{:keys [config telegram-bot]
197 : :as ctx}
198 : chat-id
199 : thread-id
200 : event
201 : sender]
202 7 : (let [bot-username (get-in config [:telegram :bot-username])
203 6 : locale (l10n/message-locale (:repos ctx) event)
204 6 : url (commands/deep-link-url bot-username (:public-id event))
205 2 : body (if url
206 5 : (l10n/t locale :telegram.reply/open-to-register url)
207 0 : (l10n/t locale :telegram.reply/open-to-link))
208 4 : reply (commands/mention-prefixed-text body sender)
209 11 : msg-id (commands/reply! telegram-bot chat-id thread-id (:text reply) (:parse-mode reply))]
210 3 : (when msg-id
211 2 : (commands/record-msg!
212 1 : ctx
213 13 : {:chat-id chat-id
214 1 : :thread-id thread-id
215 1 : :message-id msg-id
216 : :sender-kind "bot"
217 : :kind "reply"
218 3 : :text (:text reply)
219 : :command "join_unauth"
220 3 : :event-id (:uuid event)}))))
221 :
222 :
223 4 : (defn- resolve-callback-class
224 : [ctx event decoded]
225 5 : (when (:class-pid decoded)
226 9 : (commands/resolve-class-by-public-id ctx (:uuid event) (:class-pid decoded))))
227 :
228 :
229 4 : (defn- ensure-user-from-telegram!
230 : "Auto-creates a user from Telegram callback data. Returns the new UUID on success, nil on failure."
231 : [ctx {:keys [sender-tg-id sender-first-name sender-last-name sender-username]}]
232 4 : (let [name (let [n (str/trim
233 9 : (str/join " " (filter seq [sender-first-name sender-last-name])))]
234 5 : (if (str/blank? n) (or sender-username "User") n))
235 14 : user-data {:uuid (uuid-utils/generate-uuid7-str)
236 2 : :public-id (nanoid/generate)
237 1 : :name name
238 1 : :username sender-username
239 : :photo-url nil
240 1 : :telegram-id sender-tg-id
241 2 : :roles ["player"]
242 9 : :settings {:ui {:theme "sky"
243 : :mode "auto"}
244 : :language "en"}
245 : :is-fake false}
246 4 : result (user-command/create-user! ctx user-data)]
247 4 : (if (either/right? result)
248 5 : (:uuid (c/extract result))
249 1 : (do
250 92 : (t/log!
251 : :warn
252 5 : {:message "Failed to auto-create user from telegram callback"
253 1 : :sender-tg-id sender-tg-id
254 3 : :error (c/extract result)})
255 2 : (user-query/find-uuid-by-telegram-id
256 5 : (:user-postgres-repo (:repos ctx))
257 5 : (:user-redis-repo (:repos ctx))
258 1 : sender-tg-id)))))
259 :
260 :
261 4 : (defn- remaining-class-count
262 : [pg event-id participant-id]
263 5 : (if-not pg
264 : 1
265 0 : (let [rows (jdbc-rows
266 0 : pg
267 0 : {:select [[[:count :*] :remaining-count]]
268 0 : :from [[:event_class_participants :cp]]
269 0 : :join [[:event_classes :c] [:= :c.uuid :cp.class_id]]
270 0 : :where [:and
271 0 : [:= :c.event_id [:cast event-id :uuid]]
272 0 : [:= :cp.participant_id [:cast participant-id :uuid]]]
273 : :limit 1})]
274 0 : (or (:remaining-count (first rows)) 0))))
275 :
276 :
277 12 : (defn- admin-participant? [participant] (boolean (some #{"admin"} (:roles participant))))
278 :
279 :
280 4 : (defn- remove-event-registration-if-last-class!
281 : "Removes the event-level participant row once the participant has no classes left.
282 : Admins are never removed from the event participant list this way -- declining a
283 : class only drops their player registration, keeping their admin standing intact."
284 : [{:keys [pg]
285 : :as ctx}
286 : event
287 : participant]
288 4 : (let [participant-id (:participant-id participant)]
289 1 : (if
290 5 : (or
291 3 : (admin-participant? participant)
292 9 : (not (zero? (remaining-class-count pg (:uuid event) participant-id))))
293 3 : (either/right nil)
294 8 : (let [result (remove-participant/execute! ctx (:uuid event) participant-id)]
295 5 : (when (either/left? result)
296 92 : (t/log!
297 : :warn
298 6 : {:message "Failed to remove event participant after leaving last class"
299 3 : :event-id (:uuid event)
300 1 : :participant-id participant-id
301 3 : :error (c/extract result)}))
302 1 : result))))
303 :
304 :
305 4 : (defn- do-join!
306 : "Joins the sender into the event (idempotent) and, when a class is given,
307 : into the requested class (idempotent). A participant may belong to multiple classes;
308 : only the same class twice is treated as a no-op friendly success."
309 : [{:keys [repos]
310 : :as ctx}
311 : event
312 : class
313 : sender-uuid
314 : chat-id
315 : thread-id]
316 8 : (let [add-result (add-participant/execute! ctx (:uuid event) sender-uuid)
317 4 : locale (l10n/message-locale repos event)
318 8 : add-err (when (either/left? add-result) (c/extract add-result))
319 5 : already-event? (= :error.event-participant/conflict (:code add-err))
320 11 : participant-id (cond (either/right? add-result) (:participant-id (c/extract add-result))
321 1 : already-event?
322 2 : (:participant-id
323 2 : (event-participant-postgres-repo/find-by-event-id-and-user-id
324 3 : (:event-participant-postgres-repo repos)
325 3 : (:uuid event)
326 1 : sender-uuid)))
327 4 : user-name (commands/resolve-user-name ctx sender-uuid)
328 1 : notify! (fn [class']
329 2 : (commands/notify-action!
330 1 : ctx
331 10 : {:chat-id chat-id
332 1 : :thread-id thread-id
333 1 : :user-name user-name
334 : :action :joined
335 1 : :locale locale
336 1 : :event event
337 1 : :class class'}))]
338 7 : (cond (nil? participant-id)
339 9 : [:fail (or (:message add-err) (l10n/t locale :telegram.callback/could-not-join))]
340 :
341 4 : (nil? class) [:fail (l10n/t locale :telegram.callback/choose-class-join)]
342 : :else
343 3 : (let [cp-result (class-participant-command/register-participant!
344 1 : ctx
345 11 : {:class-id (:uuid class)
346 1 : :participant-id participant-id
347 : :status "registered"
348 2 : :registered-at (Instant/now)
349 : :source "matchscore"})
350 8 : cp-err (when (either/left? cp-result) (c/extract cp-result))]
351 6 : (cond (either/right? cp-result)
352 1 : (do
353 3 : (notify! class)
354 9 : [:ok (l10n/t locale :telegram.callback/joined-class (:name class))])
355 :
356 5 : (= :error.class-participant/conflict (:code cp-err))
357 9 : [:ok (l10n/t locale :telegram.callback/already-in-class (:name class))]
358 :
359 : :else
360 2 : [:fail
361 4 : (or
362 3 : (:message cp-err)
363 0 : (l10n/t locale :telegram.callback/could-not-join-class))])))))
364 :
365 :
366 4 : (defn- do-leave!
367 : [{:keys [repos]
368 : :as ctx}
369 : event
370 : class
371 : sender-uuid
372 : chat-id
373 : thread-id]
374 3 : (let [existing (event-participant-postgres-repo/find-by-event-id-and-user-id
375 3 : (:event-participant-postgres-repo repos)
376 3 : (:uuid event)
377 1 : sender-uuid)
378 4 : locale (l10n/message-locale repos event)
379 1 : notify! (fn [class']
380 5 : (let [user-name (commands/resolve-user-name ctx sender-uuid)]
381 2 : (commands/notify-action!
382 1 : ctx
383 10 : {:chat-id chat-id
384 1 : :thread-id thread-id
385 1 : :user-name user-name
386 : :action :left
387 1 : :locale locale
388 1 : :event event
389 1 : :class class'})))]
390 6 : (cond (nil? existing) [:fail (l10n/t locale :telegram.callback/not-registered)]
391 1 : class
392 3 : (let [class-participant (class-participant-postgres-repo/find-by-class-and-participant
393 3 : (:class-participant-postgres-repo repos)
394 3 : (:uuid class)
395 3 : (:participant-id existing))]
396 2 : (if class-participant
397 1 : (do
398 2 : (class-participant-postgres-repo/delete-by-class-and-participant!
399 3 : (:class-participant-postgres-repo repos)
400 3 : (:uuid class)
401 3 : (:participant-id existing))
402 6 : (let [cleanup-result (remove-event-registration-if-last-class! ctx event existing)]
403 4 : (if (either/left? cleanup-result)
404 2 : [:fail
405 4 : (or
406 5 : (:message (c/extract cleanup-result))
407 0 : (l10n/t locale :telegram.callback/could-not-leave-class))]
408 1 : (do
409 3 : (notify! class)
410 9 : [:ok (l10n/t locale :telegram.callback/left-class (:name class))]))))
411 6 : [:fail (l10n/t locale :telegram.callback/not-registered-class)]))
412 :
413 0 : :else [:fail (l10n/t locale :telegram.callback/choose-class-leave)])))
414 :
415 :
416 4 : (defn- process-payment-claim!
417 : "\"I paid\" on the live payment post: marks the sender's unpaid registrations
418 : in the event as claimed for the organizer to confirm, and refreshes the post."
419 : [{:keys [pg repos telegram-bot]
420 : :as ctx}
421 : {:keys [callback-id chat-id thread-id message-id sender-tg-id]}]
422 22 : (if-let [event (resolve-chat-event ctx chat-id thread-id message-id)]
423 18 : (let [ds (or (:datasource pg) pg)
424 8 : locale (l10n/message-locale repos event)
425 8 : answer! #(answer-callback! telegram-bot callback-id (l10n/t locale %))
426 16 : user-id (some->
427 4 : (user-query/find-uuid-by-telegram-id
428 6 : (:user-postgres-repo repos)
429 6 : (:user-redis-repo repos)
430 2 : sender-tg-id)
431 2 : str)
432 6 : own (when user-id
433 6 : (filterv
434 2 : #(=
435 2 : user-id
436 34 : (some->
437 : %
438 : :user-id
439 2 : str))
440 12 : (payment-tracking/registrations ds (:uuid event))))]
441 13 : (cond (event-command/imported-event? event)
442 2 : (answer-callback!
443 1 : telegram-bot
444 1 : callback-id
445 4 : (:message (event-command/imported-event-read-only-error)))
446 :
447 10 : (not (true? (get-in event [:settings :payments-enabled])))
448 0 : (answer! :payment-tracking/claim-disabled)
449 :
450 6 : (empty? own) (answer! :payment-tracking/claim-not-participant)
451 :
452 9 : (every? #(= "paid" (:payment-status %)) own)
453 0 : (answer! :payment-tracking/claim-already-paid)
454 :
455 18 : (pos? (audit/with-actor user-id (payment-tracking/claim! ds (:uuid event) user-id)))
456 1 : (do
457 6 : (notifications-trigger/trigger-payment-refresh! ctx (:uuid event))
458 3 : (answer! :payment-tracking/claim-thanks))
459 :
460 3 : :else (answer! :payment-tracking/claim-already-claimed)))
461 0 : (answer-callback! telegram-bot callback-id (l10n/t :en :telegram.callback/chat-not-linked))))
462 :
463 :
464 4 : (defn process-callback-job
465 : "Goose job: handles a single Telegram inline-button callback_query.
466 :
467 : payload keys:
468 : :callback-id – Telegram callback_query id (string)
469 : :chat-id – chat id (long)
470 : :thread-id – message thread id (long or nil)
471 : :message-id – id of the participants message (long)
472 : :sender-tg-id – Telegram user id of the clicker (long)
473 : :sender-username, :sender-first-name, :sender-last-name – Telegram user display data
474 : :data – callback data string (e.g. 'j:abc123')"
475 : [system-components payload]
476 4 : (let [{:keys [pg redis repos goose telegram-bot config]} system-components
477 2 : {:keys [callback-id chat-id thread-id message-id sender-tg-id data]} payload
478 16 : ctx {:pg pg
479 2 : :redis redis
480 2 : :repos repos
481 2 : :goose goose
482 2 : :config config
483 2 : :telegram-bot telegram-bot}
484 8 : idempotency-key (str "tg:cb:processed:" callback-id)]
485 4 : (cond
486 92 : (not= "OK" (car/wcar redis (car/set idempotency-key "1" :nx :ex 86400)))
487 22 : (t/log! :debug (str "Duplicate TG callback skipped: " idempotency-key))
488 :
489 : :else
490 2 : (try
491 14 : (if-let [access-decision (event-creation-access/callback-decision data)]
492 5 : (process-access-request-callback! ctx payload access-decision)
493 8 : (if (= "p" data)
494 8 : (process-payment-claim! ctx payload)
495 4 : (let [decoded (decode-data data)
496 6 : event (resolve-chat-event ctx chat-id thread-id message-id)]
497 8 : (cond (nil? decoded)
498 2 : (answer-callback!
499 1 : telegram-bot
500 1 : callback-id
501 4 : (l10n/t :en :telegram.callback/unknown-action))
502 :
503 4 : (nil? event)
504 2 : (answer-callback!
505 1 : telegram-bot
506 1 : callback-id
507 4 : (l10n/t :en :telegram.callback/chat-not-linked))
508 :
509 3 : (event-command/imported-event? event)
510 2 : (answer-callback!
511 1 : telegram-bot
512 1 : callback-id
513 4 : (:message (event-command/imported-event-read-only-error)))
514 :
515 : :else
516 5 : (let [locale (l10n/message-locale repos event)
517 5 : class (resolve-callback-class ctx event decoded)]
518 3 : (cond
519 6 : (nil? (:class-pid decoded))
520 2 : (answer-callback!
521 1 : telegram-bot
522 1 : callback-id
523 4 : (l10n/t locale :telegram.callback/choose-class))
524 :
525 4 : (nil? class)
526 2 : (answer-callback!
527 1 : telegram-bot
528 1 : callback-id
529 4 : (l10n/t locale :telegram.callback/class-not-found))
530 :
531 : :else
532 3 : (let [found-uuid (user-query/find-uuid-by-telegram-id
533 3 : (:user-postgres-repo repos)
534 3 : (:user-redis-repo repos)
535 1 : sender-tg-id)
536 6 : sender-uuid (if (= :join (:op decoded))
537 9 : (or found-uuid (ensure-user-from-telegram! ctx payload))
538 1 : found-uuid)]
539 6 : (cond (nil? sender-uuid)
540 6 : (if (= :join (:op decoded))
541 1 : (do
542 2 : (answer-callback!
543 1 : telegram-bot
544 1 : callback-id
545 4 : (l10n/t locale :telegram.callback/open-to-register))
546 7 : (send-deep-link! ctx chat-id thread-id event payload))
547 2 : (answer-callback!
548 1 : telegram-bot
549 1 : callback-id
550 4 : (l10n/t locale :telegram.callback/not-registered)))
551 :
552 : :else
553 6 : (let [cmd-ctx (assoc ctx :sender-uuid sender-uuid)
554 9 : [status text] (audit/with-actor
555 1 : sender-uuid
556 5 : (case (:op decoded)
557 : :join
558 2 : (do-join!
559 1 : cmd-ctx
560 1 : event
561 1 : class
562 1 : sender-uuid
563 1 : chat-id
564 1 : thread-id)
565 :
566 : :leave
567 2 : (do-leave!
568 1 : cmd-ctx
569 1 : event
570 1 : class
571 1 : sender-uuid
572 1 : chat-id
573 1 : thread-id)))]
574 : ;; A player whose name still needs confirming gets
575 : ;; a private nudge instead (at most weekly) that
576 : ;; opens the bot chat, where the name message waits.
577 5 : (if-let [nudge
578 14 : (when (and (= :join (:op decoded)) (= :ok status))
579 6 : (name-jobs/join-nudge cmd-ctx locale sender-uuid text))]
580 2 : (answer-callback!
581 1 : telegram-bot
582 1 : callback-id
583 3 : (:text nudge)
584 7 : {:url (:url nudge)
585 : :alert? true})
586 5 : (answer-callback! telegram-bot callback-id text))
587 5 : (when (= status :fail)
588 22 : (t/log!
589 : :debug
590 0 : (str
591 0 : "Callback " (:op decoded)
592 0 : " failed for user " sender-uuid
593 0 : ": " text))))))))))))
594 : (catch Exception e
595 92 : (t/log!
596 : :error
597 6 : {:message "process-callback-job failed"
598 1 : :callback-id callback-id
599 1 : :sender-tg-id sender-tg-id
600 1 : :exception e})
601 8 : (answer-callback! telegram-bot callback-id (l10n/t :en :telegram.callback/error)))))))
|