Line data Source code
1 4 : (ns matchscore.domain.match-result.command
2 : (:require
3 : [cats.core :as c]
4 : [cats.monad.either :as either]
5 : [clojure.set]
6 : [matchscore.db.postgres.outbox :as outbox]
7 : [matchscore.domain.class.repository.postgres :as class-postgres-repo]
8 : [matchscore.domain.event.repository.postgres :as event-postgres-repo]
9 : [matchscore.domain.match-result.repository.postgres :as match-result-postgres-repo]
10 : [matchscore.domain.match-segment.repository.postgres :as match-segment-postgres-repo]
11 : [matchscore.domain.match.repository.postgres :as match-postgres-repo]
12 : [matchscore.domain.stage.repository.postgres :as stage-postgres-repo]
13 : [matchscore.utils.domain-events :as domain-events]
14 : [matchscore.utils.errors :as utils.errors]
15 : [matchscore.utils.uuid :as uuid]
16 : [next.jdbc :as jdbc]
17 : [next.jdbc.result-set :as rs]))
18 :
19 :
20 4 : (defn- find-match-or-fail
21 : [match-repo match-id]
22 18 : (if-let [match (match-postgres-repo/find-by-id match-repo match-id)]
23 6 : (either/right match)
24 2 : (either/left
25 3 : (utils.errors/build-error
26 : :check
27 6 : {:code :error.match-result/match-not-found
28 : :message "Match not found"
29 3 : :context {:match-id match-id}}))))
30 :
31 :
32 4 : (defn- resolve-event-uuid
33 : "Returns the owning event UUID (string) for a match. Group and bracket
34 : matches carry a null event_id, so the event is resolved through the
35 : stage -> class chain. Returns nil when it cannot be determined."
36 : [repos match]
37 9 : (or
38 30 : (some->
39 6 : (:event-id match)
40 1 : str
41 1 : not-empty)
42 28 : (let [stage (some->>
43 6 : (:stage-id match)
44 1 : str
45 4 : (stage-postgres-repo/find-by-id (:stage-postgres-repo repos)))
46 29 : class-id (some->
47 2 : stage
48 : :class-id
49 1 : str)
50 5 : klass (when class-id
51 6 : (class-postgres-repo/find-by-id (:class-postgres-repo repos) class-id))]
52 42 : (some->
53 2 : klass
54 : :event-id
55 1 : str
56 1 : not-empty))))
57 :
58 :
59 14 : (defn- blank-segment? [{:keys [home-score away-score]}] (and (= 0 home-score) (= 0 away-score)))
60 :
61 :
62 4 : (defn- validation-error
63 : [message context]
64 2 : (either/left
65 3 : (utils.errors/build-error
66 : :check
67 5 : {:code :error.match-result/invalid-result
68 1 : :message message
69 1 : :context context})))
70 :
71 :
72 21 : (defn- nonnegative-score? [value] (or (nil? value) (and (integer? value) (<= 0 value))))
73 :
74 :
75 4 : (defn- validate-user-submission
76 : "Validates client result data against the pairing currently stored on the
77 : match. Rejects matches with an unresolved slot. Synthetic internal bye
78 : results bypass this by omitting user-uuid."
79 : [match {:keys [winner-id loser-id outcome home-score away-score segments]}]
80 10 : (let [home-id (some->
81 3 : (:home-participant-id match)
82 1 : str)
83 9 : away-id (some->
84 3 : (:away-participant-id match)
85 1 : str)
86 5 : participants (set [home-id away-id])
87 9 : winner-id (some->
88 1 : winner-id
89 1 : str)
90 7 : loser-id (some->
91 1 : loser-id
92 0 : str)
93 6 : complete-pairing? (and home-id away-id)
94 3 : valid-segments? (every?
95 4 : #(and
96 5 : (nonnegative-score? (:home-score %))
97 4 : (nonnegative-score? (:away-score %)))
98 6 : (or segments []))]
99 6 : (cond
100 : ;; A slot still waiting on an earlier match ("TBD", "Group A ยท 1st place")
101 : ;; has nobody to credit. Synthetic bye results skip this check because they
102 : ;; are saved without a user-uuid; deleting a result stays allowed.
103 3 : (not complete-pairing?)
104 2 : (either/left
105 3 : (utils.errors/build-error
106 : :check
107 6 : {:code :error.match-result/participants-pending
108 : :message "Both participants must be known before a result can be entered."
109 5 : :context {:match-id (:uuid match)}}))
110 :
111 10 : (or
112 5 : (and winner-id (not (contains? participants winner-id)))
113 5 : (and loser-id (not (contains? participants loser-id)))
114 1 : (and winner-id loser-id (= winner-id loser-id)))
115 0 : (validation-error
116 : "Winner and loser must be the participants currently assigned to the match."
117 0 : {:match-id (:uuid match)})
118 :
119 15 : (not (and (nonnegative-score? home-score) (nonnegative-score? away-score) valid-segments?))
120 0 : (validation-error "Scores must be non-negative integers." {:match-id (:uuid match)})
121 :
122 22 : (and (= "normal" outcome) (some? home-score) (some? away-score) (= home-score away-score))
123 0 : (validation-error "A normal match result cannot be tied." {:match-id (:uuid match)})
124 :
125 7 : (and
126 3 : (= "normal" outcome)
127 1 : winner-id
128 0 : (some? home-score)
129 0 : (some? away-score)
130 0 : (not= winner-id (if (> home-score away-score) home-id away-id)))
131 0 : (validation-error "The winner does not match the submitted score." {:match-id (:uuid match)})
132 :
133 3 : :else (either/right true))))
134 :
135 :
136 4 : (defn- validate-score-entry-mode
137 : [repos event-uuid {:keys [home-score away-score outcome]} segments]
138 10 : (let [event (when (and event-uuid (:event-postgres-repo repos))
139 7 : (event-postgres-repo/find-by-id (:event-postgres-repo repos) event-uuid nil))
140 7 : mode (or (:score-entry-mode event) "either")
141 4 : valid? (case mode
142 3 : "sets" (seq segments)
143 10 : "game" (and (some? home-score) (some? away-score))
144 : true)]
145 10 : (if (or (#{"walkover" "bye"} outcome) valid?)
146 3 : (either/right true)
147 2 : (validation-error
148 5 : (case mode
149 : "sets" "Per-set scores are required for this event."
150 : "game" "A final game score is required for this event.")
151 4 : {:event-id event-uuid
152 1 : :score-entry-mode mode}))))
153 :
154 :
155 4 : (defn- validate-segment-ownership
156 : "Existing segment UUIDs are editable only through their own match. Without
157 : this check an upsert could update a segment from another match."
158 : [repos match-id segments]
159 2 : (let [incoming-ids (->>
160 6 : (or segments [])
161 3 : (keep :uuid)
162 3 : (map str)
163 1 : set)]
164 4 : (if (empty? incoming-ids)
165 3 : (either/right true)
166 2 : (let [existing-ids (->>
167 2 : (match-segment-postgres-repo/find-by-match-id
168 3 : (:match-segment-postgres-repo repos)
169 1 : match-id)
170 6 : (map (comp str :uuid))
171 1 : set)]
172 5 : (if (clojure.set/subset? incoming-ids existing-ids)
173 3 : (either/right true)
174 3 : (validation-error
175 : "Submitted score segments must belong to this match."
176 3 : {:match-id match-id}))))))
177 :
178 :
179 4 : (defn save-match-result!
180 : "Upserts a match result. Sets match state to 'completed'.
181 : Emits outbox event with event-uuid for broadcasting.
182 : Returns Either<Error, {:code <kw> :data <MatchResult>}>."
183 : [{:keys [repos pg]}
184 : {:keys [match-id winner-id loser-id outcome home-score away-score ended-at extra segments]
185 : :as submission}
186 : &
187 : {:keys [user-uuid]}]
188 8 : (let [match-repo (:match-postgres-repo repos)
189 15 : segments (when (some? segments) (filterv (complement blank-segment?) segments))]
190 78 : (c/mlet [match (find-match-or-fail match-repo match-id)
191 18 : event-uuid (either/right (resolve-event-uuid repos match))
192 18 : _ (if user-uuid (validate-user-submission match submission) (either/right true))
193 6 : _ (if user-uuid
194 7 : (validate-segment-ownership repos match-id (:segments submission))
195 6 : (either/right true))
196 4 : _ (if user-uuid
197 6 : (validate-score-entry-mode repos event-uuid submission segments)
198 6 : (either/right true))]
199 8 : (jdbc/with-transaction
200 6 : [tx (:datasource pg)]
201 14 : (let [tx-opts (jdbc/with-options tx {:builder-fn rs/as-kebab-maps})
202 6 : tx-mr-repo (match-result-postgres-repo/make-repository tx-opts)
203 6 : tx-ms-repo (match-segment-postgres-repo/make-repository tx-opts)
204 6 : tx-match-repo (match-postgres-repo/make-repository tx-opts)
205 28 : result-data {:uuid (uuid/generate-uuid7-str)
206 6 : :match-id (str match-id)
207 12 : :winner-id (when winner-id (str winner-id))
208 4 : :loser-id (when loser-id (str loser-id))
209 2 : :outcome outcome
210 2 : :home-score home-score
211 2 : :away-score away-score
212 2 : :ended-at ended-at
213 2 : :extra extra
214 : :source "matchscore"}
215 8 : result (match-result-postgres-repo/save! tx-mr-repo result-data)]
216 10 : (when (either/right? result)
217 10 : (match-postgres-repo/update-state! tx-match-repo match-id "completed")
218 : ;; Sync segments: diff-based upsert/insert/delete
219 9 : (when (some? segments)
220 5 : (let [existing (match-segment-postgres-repo/find-by-match-id tx-ms-repo match-id)
221 6 : existing-ids (set (map :uuid existing))
222 6 : incoming-ids (set (keep :uuid segments))
223 4 : to-delete (clojure.set/difference existing-ids incoming-ids)]
224 4 : (match-segment-postgres-repo/delete-by-ids! tx-ms-repo to-delete)
225 29 : (doseq [[idx seg] (map-indexed vector segments)]
226 2 : (match-segment-postgres-repo/save!
227 1 : tx-ms-repo
228 21 : {:uuid (or (:uuid seg) (uuid/generate-uuid7-str))
229 3 : :match-id (str match-id)
230 : :type "set"
231 : :state "completed"
232 3 : :home-score (:home-score seg)
233 3 : :away-score (:away-score seg)
234 2 : :order (inc idx)
235 : :source "matchscore"}))))
236 8 : (let [event (domain-events/make-event
237 : "match_result/saved"
238 14 : {:match-id (str match-id)
239 2 : :event-uuid event-uuid
240 6 : :match-result (c/extract result)}
241 6 : {:user-uuid user-uuid})]
242 4 : (outbox/insert-outbox-event!
243 2 : tx
244 14 : {:aggregate-type "match_result"
245 2 : :aggregate-id match-id
246 6 : :event-type (:event-type event)
247 6 : :payload (:payload event)
248 6 : :metadata (:metadata event)})))
249 12 : (let [final-segments (when (either/right? result)
250 2 : (->>
251 8 : (match-segment-postgres-repo/find-by-match-id tx-ms-repo match-id)
252 8 : (mapv #(into {} %))))]
253 6 : (c/fmap
254 12 : #(hash-map
255 : :code :success.match-result/ok
256 22 : :data (cond-> % (some? final-segments) (assoc :segments final-segments))
257 2 : :event-uuid event-uuid)
258 2 : result)))))))
259 :
260 :
261 4 : (defn delete-match-result!
262 : "Deletes a match result and all match segments. Sets match state to 'scheduled'.
263 : Emits outbox event with event-uuid for broadcasting.
264 : Returns Either<Error, {:code <kw> :data <Match>}>."
265 : [{:keys [repos pg]} {:keys [match-id]} & {:keys [user-uuid]}]
266 4 : (let [match-repo (:match-postgres-repo repos)]
267 11 : (c/mlet [match (find-match-or-fail match-repo match-id)]
268 4 : (jdbc/with-transaction
269 3 : [tx (:datasource pg)]
270 7 : (let [tx-opts (jdbc/with-options tx {:builder-fn rs/as-kebab-maps})
271 3 : tx-mr-repo (match-result-postgres-repo/make-repository tx-opts)
272 3 : tx-ms-repo (match-segment-postgres-repo/make-repository tx-opts)
273 3 : tx-match-repo (match-postgres-repo/make-repository tx-opts)]
274 4 : (match-result-postgres-repo/delete-by-match-id! tx-mr-repo match-id)
275 4 : (match-segment-postgres-repo/delete-by-match-id! tx-ms-repo match-id)
276 6 : (let [updated-match (match-postgres-repo/update-state! tx-match-repo match-id "scheduled")
277 4 : event-uuid (resolve-event-uuid repos match)
278 3 : event (domain-events/make-event
279 : "match_result/deleted"
280 6 : {:match-id (str match-id)
281 1 : :event-uuid event-uuid}
282 3 : {:user-uuid user-uuid})]
283 2 : (outbox/insert-outbox-event!
284 1 : tx
285 7 : {:aggregate-type "match_result"
286 1 : :aggregate-id match-id
287 3 : :event-type (:event-type event)
288 3 : :payload (:payload event)
289 3 : :metadata (:metadata event)})
290 2 : (either/right
291 5 : {:code :success.match-result/deleted
292 1 : :data updated-match
293 1 : :event-uuid event-uuid})))))))
|