Line data Source code
1 4 : (ns matchscore.application.group-participants.sync-matches
2 : (:require
3 : [cats.monad.either :as either]
4 : [matchscore.domain.group-participant.repository.postgres :as gp-postgres-repo]
5 : [matchscore.domain.match.repository.postgres :as match-postgres-repo]
6 : [matchscore.utils.errors :as utils.errors]))
7 :
8 :
9 4 : (defn execute!
10 : "Syncs home/away participant IDs on group matches to reflect current group participant slots.
11 : Pair order mirrors create-group-matches!: all (i,j) with i<j, ordered by slot index.
12 : Returns Either<Error, nil>."
13 : [repos group-uuid]
14 12 : (let [gp-repo (:group-participant-postgres-repo repos)
15 9 : match-repo (:match-postgres-repo repos)
16 12 : group-participants (gp-postgres-repo/find-by-group-id gp-repo group-uuid)
17 30 : slot-map (into {} (map (juxt :slot :participant-id)) group-participants)
18 15 : slots (sort (keys slot-map))
19 207 : pairs (for [[i & rest-slots] (take-while seq (iterate rest slots))
20 3 : j rest-slots]
21 9 : [i j])
22 6 : matches (->>
23 12 : (match-postgres-repo/find-by-group-id match-repo group-uuid)
24 3 : (sort-by :match-order))]
25 36 : (if (and (seq matches) (not= (count pairs) (count matches)))
26 2 : (either/left
27 3 : (utils.errors/build-error
28 : :database
29 4 : {:code :error.match/pair-match-count-mismatch
30 6 : :message (str
31 : "Pair/match count mismatch for group "
32 1 : group-uuid
33 : ": "
34 2 : (count pairs)
35 : " pairs vs "
36 2 : (count matches)
37 : " matches")}))
38 18 : (loop [remaining (map vector matches pairs)]
39 12 : (if (empty? remaining)
40 9 : (either/right nil)
41 8 : (let [[match [i j]] (first remaining)
42 6 : home-id (get slot-map i)
43 6 : away-id (get slot-map j)
44 : result
45 16 : (match-postgres-repo/update-participants! match-repo (:uuid match) home-id away-id)]
46 10 : (if (nil? result)
47 0 : (either/left
48 0 : (utils.errors/build-error
49 : :database
50 0 : {:code :error.match/update-participants-failed
51 0 : :message (str "Failed to update participants for match " (:uuid match))}))
52 2 : (recur (rest remaining)))))))))
|