Line data Source code
1 4 : (ns matchscore.domain.event.repository.postgres
2 : (:require
3 : [cats.monad.either :as either]
4 : [cheshire.core :as json]
5 : [clojure.string :as str]
6 : [honey.sql :as sql]
7 : [next.jdbc :as jdbc])
8 : (:require
9 : [matchscore.domain.club.entity :as club-entity]
10 : [matchscore.domain.event.entity :as entity]
11 : [matchscore.domain.telegram-chat-member.repository.postgres :as telegram-chat-member-repo]
12 : [matchscore.utils.audit :as audit]
13 : [matchscore.utils.db :as utils.db]
14 : [matchscore.utils.errors :as utils.errors]
15 : [matchscore.utils.nanoid :as nanoid]
16 : [matchscore.utils.pagination :as qh]))
17 :
18 :
19 4 : (defn- -parse-datetime-filter
20 : [datetime-filter]
21 8 : (when datetime-filter
22 4 : (update-vals
23 2 : datetime-filter
24 2 : (fn [v]
25 9 : (cond (string? v)
26 2 : (try
27 10 : (java.sql.Timestamp/from (java.time.Instant/parse v))
28 0 : (catch java.time.format.DateTimeParseException _ v)
29 0 : (catch IllegalArgumentException _ v))
30 :
31 7 : (instance? java.time.Instant v) (java.sql.Timestamp/from v)
32 0 : :else v)))))
33 :
34 :
35 4 : (defprotocol
36 : EventPostgresRepository
37 : (find-by-id
38 : [this id ctx]
39 : "Find event by UUID string. Returns Event map or nil.")
40 : (find-by-public-id
41 : [this public-id]
42 : [this public-id ctx]
43 : "Find event by 12-char public_id. Returns Event map or nil.")
44 : (find-by-template-id
45 : [this template-id ctx]
46 : "Find events by event template UUID string. Returns a vector of Event maps.")
47 : (find-active-by-template-id
48 : [this template-id]
49 : "Find the active event for an event template UUID string. Returns Event map or nil.")
50 : (find-by-creator-id
51 : [this creator-id ctx]
52 : "Find events by creator UUID string. Returns a vector of Event maps.")
53 : (find-by-ids
54 : [this ids]
55 : "Find events by a collection of UUID strings (batch). Returns a vector of Event maps.")
56 : (find-by-stage-ids
57 : [this stage-ids]
58 : "Find the owning event for each stage UUID (via stages -> event_classes -> events).
59 : Returns a seq of {:stage-id \"uuid\" :event {..event fields..}}.")
60 : (search
61 : [this filters pagination]
62 : "Search events by filters and pagination.
63 : filters: {:templateId {:eq \"uuid\"}}
64 : pagination: {:limit 20 :cursor \"base64...\" :sort-by :datetime-start :sort-dir :asc}
65 : Returns {:items [...] :has-next-page bool :end-cursor \"base64-or-nil\"}")
66 : (save!
67 : [this event]
68 : "Persists an event (insert or update). Returns Either<Error, Event>.")
69 : (delete!
70 : [this id]
71 : "Deletes an event by UUID. Returns Either<Error, nil>."))
72 :
73 :
74 12 : (declare -extract-club -parse-clubs-json)
75 :
76 :
77 4 : (defn- row->event
78 : "Converts a database row to a domain Event map."
79 : [row]
80 12 : (when row
81 16 : (let [from-qualified? (:events/uuid row)
82 12 : unq (utils.db/unqualify-keys row)
83 20 : clubs (-parse-clubs-json (:clubs-json unq))
84 : ;; retain single :club for backward compatibility
85 42 : club (when (or (:clubs/uuid row) (:c/uuid row))
86 5 : (club-entity/make-club (-extract-club row)))
87 8 : event (->
88 4 : (if
89 4 : from-qualified?
90 16 : (entity/make-event row true)
91 0 : (entity/make-event unq))
92 16 : (assoc :clubs clubs)
93 28 : (assoc :club-ids (mapv :uuid clubs))
94 34 : (assoc :club (or (first clubs) club)))]
95 4 : event)))
96 :
97 :
98 4 : (defn- -parse-clubs-json
99 : "Parses the clubs-json aggregate column into a vector of ClubRecord maps.
100 : The PGobject extension already auto-parses JSON, so v is a Clojure value."
101 : [v]
102 20 : (when (sequential? v)
103 4 : (->>
104 4 : v
105 12 : (filter identity)
106 4 : (mapv
107 4 : (fn [club-map]
108 4 : (club-entity/make-club
109 12 : (assoc club-map
110 14 : :location (or (:location club-map) {})
111 14 : :working-hours (or (:working-hours club-map) [])
112 14 : :images (or (:images club-map) []))))))))
113 :
114 :
115 4 : (defn- -decode-json-if-needed
116 : [value]
117 4 : (if (string? value)
118 0 : (try
119 0 : (json/parse-string value)
120 0 : (catch Exception _ value))
121 1 : value))
122 :
123 :
124 4 : (defn- -extract-club
125 : [row]
126 3 : (let [club-data (reduce-kv
127 1 : (fn [acc k v]
128 15 : (if (and (keyword? k) (contains? #{"clubs" "c"} (namespace k)))
129 8 : (let [key-name (str/replace (name k) #"_" "-")
130 3 : key (keyword key-name)
131 7 : shape? (contains? #{"location" "working-hours" "images"} key-name)
132 6 : value (if shape? (-decode-json-if-needed v) v)]
133 15 : (if (and shape? (nil? value)) acc (assoc acc key value)))
134 1 : acc))
135 1 : {}
136 1 : row)]
137 5 : (when (seq club-data)
138 2 : (merge
139 5 : {:location {}
140 1 : :working-hours []
141 1 : :images []}
142 1 : club-data))))
143 :
144 :
145 4 : (defn- event->row
146 : "Converts a domain Event map to a database row for upsert."
147 : [event]
148 4 : (let [{:keys [uuid
149 : public-id
150 : template-id
151 : datetime-start
152 : datetime-end
153 : state
154 : visibility
155 : name
156 : fee
157 : fee-type
158 : currency
159 : duration
160 : score-entry-mode
161 : score-entry-default
162 : timezone
163 : language
164 : source
165 : created-by
166 : description
167 : sport-code
168 : activity-type-code
169 : settings]}
170 4 : event]
171 24 : (cond->
172 108 : {:uuid [:cast uuid :uuid]
173 28 : :public_id (or public-id (nanoid/generate))
174 16 : :template_id [:cast template-id :uuid]
175 20 : :datetime_start (if (instance? java.time.Instant datetime-start)
176 12 : (java.sql.Timestamp/from datetime-start)
177 4 : datetime-start)
178 20 : :datetime_end (if (instance? java.time.Instant datetime-end)
179 12 : (java.sql.Timestamp/from datetime-end)
180 4 : datetime-end)
181 4 : :state state
182 24 : :visibility (or visibility "public")
183 4 : :name name
184 32 : :club_id [:cast (first (:club-ids event)) :uuid]
185 4 : :fee fee
186 4 : :fee_type fee-type
187 4 : :currency currency
188 4 : :duration duration
189 24 : :score_entry_mode (or score-entry-mode "either")
190 24 : :score_entry_default (or score-entry-default "game")
191 4 : :timezone timezone
192 24 : :language (or language "en")
193 23 : :source (or source "matchscore")
194 16 : :created_by [:cast created-by :uuid]
195 4 : :description description
196 4 : :sport_code sport-code
197 4 : :activity_type_code activity-type-code}
198 20 : (contains? event :settings) (assoc :settings
199 41 : [:cast (json/generate-string (or settings {})) :jsonb]))))
200 :
201 :
202 4 : (defn- filters->specs
203 : [{:keys
204 : [templateId eventTemplateId state visibility datetimeStart datetimeEnd createdBy created-by]
205 : :as filters}]
206 38 : (let [created-by-id (or createdBy created-by (:created-by filters))
207 17 : template-id (or templateId eventTemplateId)
208 9 : start-filter (-parse-datetime-filter datetimeStart)
209 9 : end-filter (-parse-datetime-filter datetimeEnd)]
210 6 : (qh/typed-filters->specs
211 30 : {:template-id (utils.db/cast-uuid-filter template-id)
212 9 : :created-by (utils.db/cast-uuid-filter created-by-id)
213 3 : :state state
214 3 : :visibility visibility
215 3 : :datetime-start start-filter
216 3 : :datetime-end end-filter})))
217 :
218 :
219 4 : (def ^:private participant-role-clauses
220 24 : {:player [:raw "ep.roles @> '[\"player\"]'::jsonb"]
221 12 : :admin [:raw "ep.roles @> '[\"admin\"]'::jsonb"]})
222 :
223 :
224 4 : (defn- participating-user-clause
225 : "Matches events where user-id participates; role (:player or :admin) narrows it to
226 : participants holding that role, nil matches any role."
227 : [user-id role]
228 27 : [:exists {:select [1]
229 12 : :from [[:event_participants :ep]]
230 24 : :join [[:participants :p] [:= :ep.participant-id :p.uuid]]
231 53 : :where (cond-> [:and [:= :ep.event-id :eo.uuid] [:= :p.user-id [:cast user-id :uuid]]]
232 15 : role (conj (participant-role-clauses role)))}])
233 :
234 :
235 4 : (defn- managing-user-clause
236 : "Matches events user-id created or holds the admin participant role in."
237 : [user-id]
238 26 : [:or [:= :eo.created-by [:cast user-id :uuid]] (participating-user-clause user-id :admin)])
239 :
240 :
241 4 : (defn- profile-visible-to-user-clause
242 : [user-id]
243 4 : [:or
244 8 : [:= :eo.visibility "public"]
245 14 : [:= :eo.created-by [:cast user-id :uuid]]
246 8 : (participating-user-clause user-id nil)
247 16 : [:exists {:select [1]
248 8 : :from [[:users :profile-viewer]]
249 4 : :where [:and
250 14 : [:= :profile-viewer.uuid [:cast user-id :uuid]]
251 6 : [:raw "profile_viewer.roles @> '[\"root\"]'::jsonb"]]}]
252 16 : [:exists {:select [1]
253 8 : :from [[:telegram-chat-members :tcm]]
254 4 : :where [:and
255 14 : [:= :tcm.user-id [:cast user-id :uuid]]
256 6 : (telegram-chat-member-repo/fresh-membership-clause :tcm.checked-at)
257 4 : [:or
258 4 : [:exists
259 12 : {:select [1]
260 8 : :from [[:telegram-event-links :tel]]
261 20 : :where [:and [:= :tel.chat-id :tcm.chat-id] [:= :tel.event-id :eo.uuid]]}]
262 16 : [:exists {:select [1]
263 8 : :from [[:telegram-template-links :ttl]]
264 4 : :where [:and
265 8 : [:= :ttl.chat-id :tcm.chat-id]
266 8 : [:= :ttl.template-id :eo.template-id]]}]]]}]])
267 :
268 :
269 4 : (def ^:private valid-sort-fields
270 20 : #{:datetime-start :datetime-end :created-datetime :updated-datetime})
271 :
272 :
273 8 : (def ^:private default-sort :datetime-start)
274 :
275 :
276 4 : (def ^:private sort-field-casts
277 36 : {:datetime-start :timestamptz
278 : :datetime-end :timestamptz
279 : :created-datetime :timestamptz
280 : :updated-datetime :timestamptz})
281 :
282 :
283 4 : (def ^:private clubs-agg-sql
284 : "Correlated subquery: JSON array of clubs for each event row (kebab-case keys for auto-parse)."
285 76 : (str
286 : "COALESCE("
287 : "(SELECT json_agg(json_build_object(" "'uuid',c.uuid::text,"
288 : "'public-id',c.public_id," "'sl-uuid',c.sl_uuid::text,"
289 : "'name',c.name," "'network',c.network,"
290 : "'country',c.country," "'city',c.city,"
291 : "'phone-number',c.phone_number," "'location',c.location,"
292 : "'working-hours',c.working_hours," "'images',c.images,"
293 : "'is-active',c.is_active" ")) FROM event_clubs ec JOIN clubs c ON c.uuid=ec.club_id"
294 : " WHERE ec.event_id=eo.uuid AND c.is_active)," "'[]'::json)"))
295 :
296 :
297 4 : (def ^:private base-query
298 40 : {:select [:* [[:raw clubs-agg-sql] :clubs-json]]
299 16 : :from [[:events :eo]]})
300 :
301 :
302 32 : (def ^:private regular-event-clause [:not-in :eo.source ["psa" "fsu" "esf"]])
303 :
304 :
305 52 : (def ^:private available-joins {:club [:left-join [[:clubs :c] [:= :eo.club-id :c.uuid]]]})
306 :
307 :
308 4 : (defrecord
309 : PostgresEventRepository
310 : [ds]
311 : EventPostgresRepository
312 :
313 : (find-by-id
314 : [_ id {:keys [joins]}]
315 20 : (let [joins-to-apply (select-keys available-joins joins)
316 16 : query (->
317 4 : base-query
318 40 : (assoc :where [:= :eo.uuid [:cast id :uuid]])
319 20 : (cond-> (seq joins-to-apply) (into (vals joins-to-apply))))
320 4 : result (->>
321 12 : (sql/format query)
322 12 : (jdbc/execute! ds)
323 4 : first)]
324 12 : (row->event result)))
325 :
326 20 : (find-by-public-id [this public-id] (find-by-public-id this public-id nil))
327 : (find-by-public-id
328 : [_ public-id {:keys [joins]}]
329 40 : (let [joins-to-apply (select-keys available-joins (or joins []))
330 12 : query (->
331 32 : (assoc base-query :where [:= :eo.public-id public-id])
332 12 : (cond-> (seq joins-to-apply) (into (vals joins-to-apply))))
333 4 : result (->>
334 12 : (sql/format query)
335 12 : (jdbc/execute! ds)
336 4 : first)]
337 12 : (row->event result)))
338 :
339 : (find-by-template-id
340 : [_ template-id {:keys [joins include-imported?]}]
341 15 : (let [joins-to-apply (select-keys available-joins joins)
342 9 : query (->
343 3 : base-query
344 48 : (assoc :where (cond-> [:and [:= :eo.template-id [:cast template-id :uuid]]]
345 15 : (not include-imported?) (conj regular-event-clause)))
346 21 : (assoc :order-by [[:eo.datetime-start :asc]])
347 9 : (cond-> (seq joins-to-apply) (into (vals joins-to-apply))))]
348 3 : (->>
349 9 : (sql/format query)
350 9 : (jdbc/execute! ds)
351 6 : (mapv row->event))))
352 :
353 : (find-active-by-template-id
354 : [_ template-id]
355 12 : (let [query (->
356 3 : base-query
357 15 : (assoc :where [:and
358 21 : [:= :eo.template-id [:cast template-id :uuid]]
359 12 : [:= :eo.state "active"]])
360 3 : (assoc :limit 1))
361 3 : result (->>
362 9 : (sql/format query)
363 9 : (jdbc/execute! ds)
364 3 : first)]
365 9 : (row->event result)))
366 :
367 : (find-by-creator-id
368 : [_ creator-id {:keys [joins include-imported?]}]
369 0 : (let [joins-to-apply (select-keys available-joins joins)
370 0 : query (->
371 0 : base-query
372 0 : (assoc :where (cond-> [:and [:= :eo.created-by [:cast creator-id :uuid]]]
373 0 : (not include-imported?) (conj regular-event-clause)))
374 0 : (assoc :order-by [[:eo.datetime-start :asc]])
375 0 : (cond-> (seq joins-to-apply) (into (vals joins-to-apply))))]
376 0 : (->>
377 0 : (sql/format query)
378 0 : (jdbc/execute! ds)
379 0 : (mapv row->event))))
380 :
381 : (find-by-ids
382 : [_ ids]
383 4 : (if (empty? ids)
384 0 : []
385 3 : (let [query (->
386 1 : base-query
387 13 : (assoc :where [:in :eo.uuid (mapv #(vector :cast % :uuid) ids)]))]
388 1 : (->>
389 3 : (sql/format query)
390 3 : (jdbc/execute! ds)
391 2 : (mapv row->event)))))
392 :
393 : (find-by-stage-ids
394 : [_ stage-ids]
395 4 : (if (empty? stage-ids)
396 0 : []
397 11 : (let [query {:select [[:s.uuid :stage-id-key] :e.*]
398 4 : :from [[:stages :s]]
399 4 : :join [[:event_classes :c]
400 4 : [:= :s.class-id :c.uuid]
401 3 : [:events :e]
402 4 : [:= :c.event-id :e.uuid]]
403 12 : :where [:in :s.uuid (mapv #(vector :cast % :uuid) stage-ids)]}]
404 1 : (->>
405 3 : (sql/format query)
406 3 : (jdbc/execute! ds)
407 1 : (mapv
408 1 : (fn [row]
409 4 : (let [u (utils.db/unqualify-keys row)]
410 11 : {:stage-id (some->
411 3 : (:stage-id-key u)
412 1 : str)
413 3 : :event (row->event row)})))))))
414 :
415 : (search
416 : [_ filters pagination]
417 12 : (let [participating-user-id (:participating-user-id filters)
418 8 : participating (when participating-user-id
419 8 : (participating-user-clause participating-user-id :player))
420 9 : managing-user-id (:managing-user-id filters)
421 14 : managing (when managing-user-id (managing-user-clause managing-user-id))
422 9 : hosted-user-id (:hosted-user-id filters)
423 7 : hosted (when hosted-user-id
424 2 : [:or
425 7 : [:= :eo.host-user-id [:cast hosted-user-id :uuid]]
426 2 : [:and
427 4 : [:= :eo.host-user-id nil]
428 3 : (managing-user-clause hosted-user-id)]])
429 9 : profile-viewer-id (:profile-visible-to-user-id filters)
430 8 : profile-visible (when profile-viewer-id
431 6 : (profile-visible-to-user-clause profile-viewer-id))
432 6 : club-conds (reduce
433 3 : (fn [acc f]
434 8 : (cond-> acc
435 15 : (:eq f) (conj [:= :ec.club-id [:cast (:eq f) :uuid]])
436 6 : (seq (:in f)) (conj
437 3 : [:in
438 : :ec.club-id
439 11 : (mapv #(vector :cast % :uuid) (:in f))])))
440 3 : []
441 30 : (remove nil? [(:clubId filters) (:clubIds filters)]))
442 13 : club-exists (when (seq club-conds)
443 8 : [:exists {:select [1]
444 4 : :from [[:event-clubs :ec]]
445 9 : :where (into [:and [:= :ec.event-id :eo.uuid]] club-conds)}])
446 42 : base (cond-> base-query
447 24 : (not (:include-imported? filters)) (qh/add-where-clause
448 3 : regular-event-clause)
449 11 : participating (qh/add-where-clause participating)
450 11 : managing (qh/add-where-clause managing)
451 7 : hosted (qh/add-where-clause hosted)
452 11 : profile-visible (qh/add-where-clause profile-visible)
453 5 : club-exists (qh/add-where-clause club-exists))
454 9 : specs (filters->specs filters)
455 6 : query (qh/build-search-query
456 3 : base
457 3 : specs
458 3 : valid-sort-fields
459 3 : default-sort
460 3 : pagination
461 9 : {:sort-field-casts sort-field-casts})
462 3 : rows (->>
463 9 : (sql/format query)
464 9 : (jdbc/execute! ds)
465 6 : (mapv row->event))
466 17 : opts (when-not (:cursor pagination)
467 15 : (let [cnt-query (qh/build-count-query base specs)
468 9 : total (->>
469 9 : (sql/format cnt-query)
470 9 : (jdbc/execute-one! ds)
471 3 : utils.db/unqualify-keys
472 : :total)]
473 9 : {:total-count total}))]
474 21 : (qh/paginate-results rows valid-sort-fields default-sort pagination opts)))
475 :
476 : (save!
477 : [_ event]
478 4 : (try
479 24 : (let [club-ids (seq (:club-ids event))
480 12 : event-uuid (:uuid event)
481 : result
482 16 : (jdbc/with-transaction
483 4 : [tx ds]
484 32 : (let [query {:insert-into :events
485 16 : :values [(event->row event)]
486 8 : :on-conflict [:uuid]
487 32 : :do-update-set {:fields (cond->
488 80 : [:datetime_start
489 : :datetime_end
490 : :state
491 : :visibility
492 : :name
493 : :club_id
494 : :fee
495 : :fee_type
496 : :currency
497 : :duration
498 : :score_entry_mode
499 : :score_entry_default
500 : :timezone
501 : :language
502 : :updated_datetime
503 : :source
504 : :description
505 : :sport_code
506 : :activity_type_code]
507 20 : (contains? event :settings) (conj :settings))}
508 8 : :returning [:*]}
509 4 : row (->>
510 20 : (sql/format (audit/stamp query))
511 12 : (jdbc/execute! tx)
512 4 : first)]
513 12 : (when event-uuid
514 8 : (jdbc/execute!
515 4 : tx
516 8 : (sql/format
517 16 : {:delete-from :event-clubs
518 28 : :where [:= :event-id [:cast event-uuid :uuid]]}))
519 10 : (when club-ids
520 4 : (jdbc/execute!
521 2 : tx
522 4 : (sql/format
523 8 : {:insert-into :event-clubs
524 6 : :values (mapv
525 8 : #(hash-map
526 8 : :event-id [:cast event-uuid :uuid]
527 8 : :club-id [:cast % :uuid])
528 2 : club-ids)}))))
529 4 : row))]
530 8 : (if result
531 32 : (let [saved-uuid (str (:uuid (utils.db/unqualify-keys result)))
532 4 : full-row (->>
533 8 : (sql/format
534 44 : (assoc base-query :where [:= :eo.uuid [:cast saved-uuid :uuid]]))
535 12 : (jdbc/execute! ds)
536 4 : first)]
537 20 : (either/right (row->event full-row)))
538 0 : (either/left
539 0 : (utils.errors/build-error
540 : :postgres
541 0 : {:message "No row returned"
542 0 : :context {:table :events
543 : :op :upsert
544 0 : :uuid event-uuid}}))))
545 : (catch Exception e
546 21 : (let [constraint (when (instance? org.postgresql.util.PSQLException e)
547 39 : (some->
548 3 : ^org.postgresql.util.PSQLException e
549 : .getServerErrorMessage
550 : .getConstraint))
551 10 : conflict (case constraint
552 : "idx_events_one_active_per_template"
553 0 : {:code :error.event/active-template-conflict
554 : :message "Template already has an active event."}
555 : "one_unfinished_automatic_template_event"
556 0 : {:code :error.event/unfinished-template-conflict
557 : :message "Template already has an unfinished event."}
558 : "unique_automatic_template_occurrence"
559 5 : {:code :error.event/template-occurrence-conflict
560 : :message "An event already exists for this scheduled occurrence."}
561 : "skipped_template_occurrence"
562 5 : {:code :error.event/skipped-template-occurrence
563 : :message "This scheduled occurrence has been skipped."}
564 : nil)]
565 6 : (either/left
566 9 : (utils.errors/build-error
567 : :postgres
568 6 : (merge
569 12 : {:message (.getMessage e)
570 21 : :context {:table :events
571 : :op :upsert
572 9 : :uuid (:uuid event)
573 9 : :template-id (:template-id event)}}
574 3 : conflict)))))))
575 :
576 :
577 : (delete!
578 : [_ id]
579 1 : (try
580 2 : (jdbc/execute!
581 1 : ds
582 2 : (sql/format
583 4 : {:delete-from :events
584 7 : :where [:= :uuid [:cast id :uuid]]}))
585 3 : (either/right nil)
586 : (catch Exception e
587 0 : (either/left
588 0 : (utils.errors/build-error
589 : :postgres
590 0 : {:message (.getMessage e)
591 0 : :context {:table :events
592 : :op :delete
593 0 : :uuid id}}))))))
594 :
595 :
596 4 : (defn make-repository
597 : "Creates a PostgresEventRepository from a ds."
598 : [ds]
599 12 : (->PostgresEventRepository ds))
|