Line data Source code
1 4 : (ns matchscore.application.group-participants.update
2 : (:require
3 : [cats.core :as c]
4 : [cats.monad.either :as either]
5 : [matchscore.application.group-participants.helpers :as helpers]
6 : [matchscore.application.group-participants.sync-matches :as sync-matches]
7 : [matchscore.domain.group-participant.repository.postgres :as group-participant-postgres-repo]
8 : [matchscore.domain.match.repository.postgres :as match-postgres-repo]
9 : [matchscore.utils.errors :as utils.errors]
10 : [next.jdbc :as jdbc]
11 : [next.jdbc.result-set :as rs]))
12 :
13 :
14 4 : (defn execute!
15 : "Fills empty group participant slots with the provided participant IDs.
16 : Returns Either<Error, seq<GroupParticipant>>."
17 : [{:keys [repos pg]} group-uuid draw-uuid participant-ids]
18 12 : (c/mlet [_ (helpers/find-group-or-fail repos group-uuid draw-uuid)]
19 1 : (try
20 4 : (jdbc/with-transaction
21 1 : [tx pg]
22 7 : (let [tx-opts (jdbc/with-options tx {:builder-fn rs/as-unqualified-kebab-maps})
23 3 : tx-repo (group-participant-postgres-repo/make-repository tx-opts)
24 5 : tx-repos (assoc repos
25 1 : :group-participant-postgres-repo tx-repo
26 3 : :match-postgres-repo (match-postgres-repo/make-repository tx-opts))
27 2 : empty-slots (->>
28 4 : (group-participant-postgres-repo/find-by-group-id tx-repo group-uuid)
29 9 : (filter #(nil? (:participant-id %)))
30 1 : (sort-by :slot))
31 10 : assignments (map vector empty-slots (or participant-ids []))
32 2 : rows (map
33 1 : (fn [[empty-slot participant-id]]
34 6 : (assoc empty-slot
35 1 : :participant-id participant-id
36 : :status "active"))
37 1 : assignments)
38 : [ok? results error-message]
39 4 : (group-participant-postgres-repo/bulk-upsert-into-empty-slots! tx-repo rows)
40 2 : result (if ok?
41 11 : (c/mlet [_ (sync-matches/execute! tx-repos group-uuid)]
42 3 : (either/right results))
43 0 : (either/left
44 0 : (utils.errors/build-error
45 : :postgres
46 0 : {:code :error.group-participant/upsert-failed
47 0 : :message (str "Failed to set group participants: " error-message)})))]
48 5 : (if (either/left? result) (throw (ex-info "tx-rollback" {::result result})) result)))
49 : (catch clojure.lang.ExceptionInfo e
50 0 : (if (contains? (ex-data e) ::result) (::result (ex-data e)) (throw e))))))
|