Line data Source code
1 4 : (ns matchscore.application.advancement.common
2 : (:require
3 : [matchscore.domain.advancement.repository.postgres :as advancement-repo]
4 : [matchscore.domain.bracket-match-slot.repository.postgres :as bms-repo]
5 : [matchscore.domain.bracket-match.repository.postgres :as bracket-match-repo]
6 : [matchscore.domain.bracket-round.repository.postgres :as bracket-round-repo]
7 : [matchscore.domain.bracket.repository.postgres :as bracket-repo]
8 : [matchscore.domain.group-participant.repository.postgres :as gp-repo]
9 : [matchscore.domain.group.repository.postgres :as group-repo]
10 : [matchscore.domain.match-result.repository.postgres :as match-result-repo]
11 : [matchscore.domain.match-segment.repository.postgres :as match-segment-repo]
12 : [matchscore.domain.match.repository.postgres :as match-repo]
13 : [matchscore.utils.uuid :as uuid-utils]))
14 :
15 :
16 4 : (defn reset-bracket-match-results!
17 : "Deletes match results and segments and resets match state to 'scheduled'
18 : for every completed match linked to bracket-match-id. Called when a slot's
19 : participant changes and any recorded result is no longer valid."
20 : [repos bracket-match-id]
21 28 : (let [matches (match-repo/find-by-bracket-match-id (:match-postgres-repo repos) bracket-match-id)]
22 104 : (doseq [{:keys [uuid state]} matches]
23 18 : (when (= state "completed")
24 16 : (match-result-repo/delete-by-match-id! (:match-result-postgres-repo repos) (str uuid))
25 16 : (match-segment-repo/delete-by-match-id! (:match-segment-postgres-repo repos) (str uuid))
26 18 : (match-repo/update-state! (:match-postgres-repo repos) (str uuid) "scheduled")))))
27 :
28 :
29 4 : (defn wins-by-pid
30 : "Returns {pid-str → win-count} from results."
31 : [results-by-match-id]
32 8 : (reduce
33 4 : (fn [acc {:keys [winner-id]}]
34 49 : (if winner-id (update acc (str winner-id) (fnil inc 0)) acc))
35 4 : {}
36 12 : (vals results-by-match-id)))
37 :
38 :
39 4 : (defn remaining-by-pid
40 : "Returns {pid-str → count of group matches with no recorded result}
41 : for the participants in a group. A match is considered remaining when
42 : no match_result row exists yet (a result with a nil winner — a draw —
43 : counts as decided)."
44 : [participants matches results-by-match-id]
45 28 : (let [pids (set (keep :participant-id participants))
46 8 : remaining (remove
47 4 : (fn [m]
48 36 : (some? (get results-by-match-id (str (:uuid m)))))
49 4 : matches)]
50 8 : (reduce
51 4 : (fn [acc m]
52 4 : (let [home (:home-participant-id m)
53 3 : away (:away-participant-id m)]
54 : ;; A match missing either side is a phantom against an empty slot; it can
55 : ;; never be played, so it must not count as a remaining match for anyone.
56 7 : (if (and home away)
57 6 : (cond-> acc
58 14 : (contains? pids home) (update (str home) (fnil inc 0))
59 12 : (contains? pids away) (update (str away) (fnil inc 0)))
60 1 : acc)))
61 4 : {}
62 4 : remaining)))
63 :
64 :
65 4 : (defn rank-group-participants
66 : "Returns participant-ids sorted by wins desc, set-diff desc, slot asc."
67 : [participants matches results-by-match-id]
68 12 : (let [wins (reduce
69 4 : (fn [acc {:keys [winner-id]}]
70 48 : (if winner-id (update acc (str winner-id) (fnil inc 0)) acc))
71 4 : {}
72 12 : (vals results-by-match-id))
73 8 : set-diff (reduce
74 4 : (fn [acc {:keys [uuid home-participant-id away-participant-id]}]
75 24 : (let [result (get results-by-match-id (str uuid))
76 12 : hs (:home-score result)
77 12 : as (:away-score result)]
78 42 : (if (and hs as home-participant-id away-participant-id)
79 2 : (->
80 2 : acc
81 24 : (update (str home-participant-id) (fnil + 0) (- hs as))
82 22 : (update (str away-participant-id) (fnil + 0) (- as hs)))
83 4 : acc)))
84 4 : {}
85 4 : matches)
86 16 : pids (keep :participant-id participants)]
87 8 : (sort-by
88 4 : (fn [pid]
89 32 : [(- (get wins (str pid) 0))
90 28 : (- (get set-diff (str pid) 0))
91 68 : (or (:slot (first (filter #(= pid (:participant-id %)) participants))) 0)])
92 4 : pids)))
93 :
94 :
95 4 : (defn load-ranked-groups
96 : "Returns a seq of:
97 : {:group group
98 : :participants <gps>
99 : :matches <matches>
100 : :results-by-match-id <map>
101 : :ranked-participants [pid ...]
102 : :wins-by-pid {pid-str → wins}
103 : :remaining-by-pid {pid-str → remaining}}
104 : for the given draw."
105 : [repos source-draw-id]
106 28 : (let [groups (group-repo/find-by-draw-id (:group-postgres-repo repos) source-draw-id)
107 16 : group-ids (mapv :uuid groups)
108 8 : gps (gp-repo/find-by-group-ids
109 12 : (:group-participant-postgres-repo repos)
110 4 : group-ids)
111 24 : matches (match-repo/find-by-group-ids (:match-postgres-repo repos) group-ids)
112 16 : match-ids (mapv :uuid matches)
113 8 : results (match-result-repo/find-by-match-ids
114 12 : (:match-result-postgres-repo repos)
115 4 : match-ids)
116 8 : results-by-match-id (into
117 4 : {}
118 8 : (map
119 4 : (fn [r]
120 28 : [(str (:match-id r)) r])
121 4 : results))
122 16 : gps-by-group (group-by :group-id gps)
123 16 : matches-by-group (group-by :group-id matches)]
124 8 : (mapv
125 4 : (fn [group]
126 16 : (let [group-id (:uuid group)
127 16 : group-gps (get gps-by-group group-id [])
128 16 : group-matches (get matches-by-group group-id [])
129 40 : group-results (select-keys results-by-match-id (map (comp str :uuid) group-matches))
130 20 : ranked (rank-group-participants group-gps group-matches group-results)]
131 36 : {:group group
132 4 : :participants group-gps
133 4 : :matches group-matches
134 4 : :results-by-match-id group-results
135 4 : :ranked-participants ranked
136 12 : :wins-by-pid (wins-by-pid group-results)
137 20 : :remaining-by-pid (remaining-by-pid group-gps group-matches group-results)}))
138 4 : groups)))
139 :
140 :
141 : ;; ---------------------------------------------------------------------------
142 : ;; IO: place participants in target group (rank_range + group-by-rank)
143 : ;; ---------------------------------------------------------------------------
144 :
145 :
146 4 : (defn place-in-target-group-at-slot!
147 : "Upserts the existing group_participant row at (target-group-id, slot)
148 : with participant-id. Returns [ok? result err gp]. Errors with
149 : :slot-not-found when no row exists at that slot."
150 : [repos target-group-id slot participant-id]
151 4 : (let [gp-impl (:group-participant-postgres-repo repos)
152 4 : existing (gp-repo/find-by-group-id gp-impl target-group-id)
153 11 : target-gp (first (filter #(= slot (:slot %)) existing))]
154 5 : (if (nil? target-gp)
155 0 : [false :slot-not-found (str "No slot " slot " in target group " target-group-id) nil]
156 6 : (let [updated (assoc target-gp :participant-id participant-id)
157 5 : [ok? result err] (gp-repo/bulk-upsert! gp-impl [updated])]
158 5 : [ok? result err updated]))))
159 :
160 :
161 4 : (defn place-in-target-group!
162 : "Places participants into empty slots of target-group. Returns
163 : [ok? result error placed-gps] where placed-gps preserves the
164 : participants order and carries :slot for each placement."
165 : [repos target-group-id participants]
166 6 : (let [existing-gps (gp-repo/find-by-group-id
167 6 : (:group-participant-postgres-repo repos)
168 2 : target-group-id)
169 26 : empty-slots (sort-by :slot (filter #(nil? (:participant-id %)) existing-gps))
170 10 : pairs (map vector participants empty-slots)]
171 12 : (if (< (count empty-slots) (count participants))
172 5 : [false :not-enough-slots "Not enough empty slots in target group" []]
173 6 : (let [updated (mapv
174 2 : (fn [[pid gp]]
175 10 : (assoc gp :participant-id pid))
176 2 : pairs)
177 12 : [ok? result err] (gp-repo/bulk-upsert! (:group-participant-postgres-repo repos) updated)]
178 10 : [ok? result err updated]))))
179 :
180 :
181 : ;; ---------------------------------------------------------------------------
182 : ;; Advancement record builders
183 : ;; ---------------------------------------------------------------------------
184 :
185 :
186 4 : (defn make-advancement-records
187 : [rule-id to-draw-id participants-with-placement]
188 8 : (mapv
189 4 : (fn [{:keys [participant-id to-group-id to-bracket-match-id assigned-seed assigned-slot]}]
190 52 : {:uuid (uuid-utils/generate-uuid7-str)
191 4 : :rule-id rule-id
192 4 : :participant-id participant-id
193 4 : :to-draw-id to-draw-id
194 4 : :to-group-id to-group-id
195 4 : :to-bracket-match-id to-bracket-match-id
196 4 : :assigned-seed assigned-seed
197 4 : :assigned-slot assigned-slot
198 : :source "matchscore"})
199 4 : participants-with-placement))
200 :
201 :
202 : ;; ---------------------------------------------------------------------------
203 : ;; IO: place participants in target bracket (top_n → seed slots)
204 : ;; ---------------------------------------------------------------------------
205 :
206 :
207 4 : (defn find-round1-slots-for-brackets
208 : "Returns all bracket-match-slot records for round 1 of the given bracket-ids,
209 : regardless of source-type. Shared by find-round1-slots (every bracket under
210 : a draw) and callers that need a single bracket in isolation (e.g. filling
211 : just one bracket among several siblings under the same draw)."
212 : [repos bracket-ids]
213 12 : (let [rounds (bracket-round-repo/find-by-bracket-ids
214 12 : (:bracket-round-postgres-repo repos)
215 4 : bracket-ids)
216 48 : round1-ids (mapv :uuid (filter #(= 1 (:round-number %)) rounds))
217 8 : matches (bracket-match-repo/find-by-bracket-round-ids
218 12 : (:bracket-match-postgres-repo repos)
219 4 : round1-ids)
220 16 : match-ids (mapv :uuid matches)]
221 24 : (bms-repo/find-by-bracket-match-ids (:bracket-match-slot-postgres-repo repos) match-ids)))
222 :
223 :
224 4 : (defn find-round1-slots
225 : "Returns all bracket-match-slot records for round 1 of target draw,
226 : regardless of source-type."
227 : [repos target-draw-id]
228 28 : (let [brackets (bracket-repo/find-by-draw-id (:bracket-postgres-repo repos) target-draw-id)
229 16 : bracket-ids (mapv :uuid brackets)]
230 16 : (find-round1-slots-for-brackets repos bracket-ids)))
231 :
232 :
233 4 : (defn find-round1-slots-for-bracket
234 : "Like find-round1-slots, but scoped to a single bracket-id rather than every
235 : bracket under its draw."
236 : [repos bracket-id]
237 5 : (find-round1-slots-for-brackets repos [bracket-id]))
238 :
239 :
240 4 : (defn find-seed-slots
241 : "Returns bracket-match-slot records for round 1 of target draw, source-type=seed, sorted by source-seed."
242 : [repos target-draw-id]
243 6 : (sort-by
244 : :source-seed
245 24 : (filter #(= "seed" (:source-type %)) (find-round1-slots repos target-draw-id))))
246 :
247 :
248 4 : (defn target-bracket-size
249 : "Number of round-1 seed slots in the target bracket draw (bracket size M),
250 : counting both filled and unfilled seed slots so it stays stable across
251 : incremental reconciles. Seed-origin round-1 slots are those with no
252 : source-match-id (loser_of slots carry a source-match-id)."
253 : [repos target-draw-id]
254 56 : (count (filter #(nil? (:source-match-id %)) (find-round1-slots repos target-draw-id))))
255 :
256 :
257 : ;; ---------------------------------------------------------------------------
258 : ;; Seed distribution: default "by_place" (interleaved) vs "standard" (mirror)
259 : ;; ---------------------------------------------------------------------------
260 :
261 :
262 4 : (defn power-of-two?
263 : [n]
264 31 : (and (pos? n) (zero? (bit-and n (dec n)))))
265 :
266 :
267 4 : (defn standard-seed-order
268 : "Vector of length m (m a power of 2). Element at 0-based physical-slot index
269 : is the 1-based seed rank that belongs at that slot. Adjacent pairs are
270 : round-1 opponents, matching create-match-slots! sequential pairing.
271 : m=2 → [1 2]; m=4 → [1 4 2 3]; m=8 → [1 8 4 5 2 7 3 6]."
272 : [m]
273 9 : (loop [order [1]]
274 15 : (if (>= (count order) m)
275 3 : order
276 15 : (let [len (* 2 (count order))]
277 3 : (recur
278 : (vec
279 : (mapcat
280 : (fn [s]
281 : [s (- (inc len) s)])
282 : order)))))))
283 :
284 :
285 4 : (defn seed-rank->slot
286 : "1-based physical slot (= bracket_match_slot source-seed) for a 1-based
287 : logical seed rank under standard mirror seeding in a bracket of size m.
288 : Falls back to identity when m is not a power of two or the rank is out of
289 : range (defensive; leaves current behavior intact)."
290 : [m seed-rank]
291 37 : (if (and (power-of-two? m) (<= 1 seed-rank m))
292 18 : (inc (.indexOf ^java.util.List (standard-seed-order m) seed-rank))
293 1 : seed-rank))
294 :
295 :
296 4 : (defn by-place-seed-order
297 : "Vector of length m. Element at 0-based index (logical-seed - 1) is the
298 : 1-based physical slot assigned to that logical seed under the 'by_place'
299 : spread. Visits the first slot of every round-1 pair before the second, so
300 : no two logical seeds share a pair until every pair already has one —
301 : avoiding a fully-empty match when real participants run short.
302 : m=8 → [1 3 5 7 2 4 6 8]."
303 : [m]
304 64 : (vec (concat (range 1 (inc m) 2) (range 2 (inc m) 2))))
305 :
306 :
307 4 : (defn by-place-seed->slot
308 : "1-based physical slot for a 1-based logical seed under the 'by_place'
309 : spread in a bracket of size m. Falls back to identity when m is odd or
310 : the seed is out of range (defensive; leaves current behavior intact)."
311 : [m logical-seed]
312 49 : (if (and (even? m) (<= 1 logical-seed m))
313 24 : (nth (by-place-seed-order m) (dec logical-seed))
314 1 : logical-seed))
315 :
316 :
317 4 : (defn distribution
318 : "The distribution strategy configured on a rule via extra, defaulting to
319 : the current interleaved behavior."
320 : [rule]
321 28 : (get-in rule [:extra :distribution] "by_place"))
322 :
323 :
324 4 : (defn apply-distribution-seed
325 : "Maps a logical place-then-group seed rank to the physical seed/slot for the
326 : rule's distribution in a bracket of size m. Spreads holes evenly for the
327 : default 'by_place'; standard mirror layout for 'standard'."
328 : [rule m logical-seed]
329 24 : (if (= "standard" (distribution rule))
330 12 : (seed-rank->slot m logical-seed)
331 16 : (by-place-seed->slot m logical-seed)))
332 :
333 :
334 : ;; ---------------------------------------------------------------------------
335 : ;; Logical seed formulas — shared by reconcile's real promotion (once a
336 : ;; participant is locked at a rank) and rule-target-assignments below (a
337 : ;; preview of the same mapping before any participant is decided)
338 : ;; ---------------------------------------------------------------------------
339 :
340 :
341 4 : (defn top-n-seed
342 : "1-based place-then-group logical seed for the r'th (0-based) rank across
343 : ng groups, at 0-based group index g."
344 : [ng r g]
345 12 : (inc (+ (* r ng) g)))
346 :
347 :
348 4 : (defn rank-range-bracket-seed
349 : "1-based place-then-group logical seed for `rank` (within a rule's
350 : rank-from..rank-to) at 1-based group-order group-ord, spread across
351 : num-groups sibling rules sharing one target draw."
352 : [num-groups rank-from group-ord rank]
353 30 : (+ (* (- rank rank-from) num-groups) (dec group-ord) 1))
354 :
355 :
356 : ;; ---------------------------------------------------------------------------
357 : ;; Preview: (rank[, source-group]) -> physical target slot, before results
358 : ;; ---------------------------------------------------------------------------
359 :
360 :
361 4 : (defn- preview-source-draw-id
362 : "A rule's own source draw for preview purposes: source-group-id rules
363 : source from that group's draw; wildcard/draw-source rules carry
364 : source-draw-id directly."
365 : [repos rule]
366 11 : (or
367 6 : (:source-draw-id rule)
368 3 : (when-let [gid (:source-group-id rule)]
369 0 : (:draw-id (group-repo/find-by-id (:group-postgres-repo repos) gid)))))
370 :
371 :
372 4 : (defn rank-range-to-group?
373 : "True for a rank_range rule that moves a range of places from one source
374 : group into one target group, without pinning a single slot or seed —
375 : e.g. \"Group A, places 1–3 → group '1-3'\" as authored in the stage
376 : advancements editor."
377 : [{:keys [selector-type source-group-id target-group-id target-slot target-seed]}]
378 3 : (boolean
379 42 : (and
380 9 : (= "rank_range" selector-type)
381 3 : source-group-id
382 3 : target-group-id
383 8 : (nil? target-slot)
384 1 : (nil? target-seed))))
385 :
386 :
387 4 : (defn rank-range-target-group-slots
388 : "{rank -> slot} for a rank-range-to-group? rule: places rank-from..rank-to
389 : map, in order, onto the target group's slots sorted ascending — rank-from
390 : lands in the lowest slot, rank-from+1 in the next, and so on. Ranks beyond
391 : the target group's slot count get no entry."
392 : [repos {:keys [rank-from rank-to target-group-id]}]
393 16 : (if-not (and rank-from target-group-id)
394 0 : {}
395 6 : (let [slots (->>
396 12 : (gp-repo/find-by-group-id (:group-participant-postgres-repo repos) target-group-id)
397 6 : (keep :slot)
398 2 : distinct
399 2 : sort)]
400 24 : (zipmap (range rank-from (inc (or rank-to rank-from))) slots))))
401 :
402 :
403 4 : (defn- rank-range-to-group-assignments
404 : "Preview for a rank-range-to-group? rule: each place in the range resolves
405 : to its fixed target-group slot (see rank-range-target-group-slots)."
406 : [repos
407 : {:keys [source-group-id target-group-id]
408 : :as rule}]
409 2 : (mapv
410 1 : (fn [[rank slot]]
411 8 : {:source-group-id (str source-group-id)
412 1 : :rank rank
413 3 : :group-id (str target-group-id)
414 1 : :slot slot})
415 7 : (sort-by key (rank-range-target-group-slots repos rule))))
416 :
417 :
418 4 : (defn- logical-assignments
419 : "Every (rank[, source-group]) position a rule could ever fill, with its
420 : logical (pre-distribution) seed — independent of whether any participant
421 : is locked there yet. Returns nil for rule shapes with no bracket-seeding
422 : ambiguity to preview (explicit single target-slot, group targets,
423 : bracket_match-source rules)."
424 : [repos rule]
425 3 : (let [{:keys [selector-type
426 : extra
427 : source-group-id
428 : target-group-id
429 : target-slot
430 : rank-from
431 : rank-to
432 : take
433 : target-seed]}
434 3 : rule]
435 58 : (cond (and (= selector-type "rank_range") (contains? extra :draw-by-rank) rank-from)
436 0 : (when-let [source-draw-id (preview-source-draw-id repos rule)]
437 0 : (map-indexed
438 0 : (fn [idx group]
439 0 : {:source-group-id (str (:uuid group))
440 0 : :rank rank-from
441 0 : :assigned-seed (inc idx)})
442 0 : (group-repo/find-by-draw-id (:group-postgres-repo repos) source-draw-id)))
443 :
444 33 : (and
445 9 : (= selector-type "rank_range")
446 3 : source-group-id
447 22 : (not (and target-group-id target-slot))
448 4 : (not target-seed))
449 14 : (let [group (group-repo/find-by-id (:group-postgres-repo repos) source-group-id)
450 4 : num-groups (max
451 : 1
452 2 : (count
453 4 : (group-repo/find-by-draw-id
454 6 : (:group-postgres-repo repos)
455 6 : (:draw-id group))))
456 2 : from rank-from
457 10 : to (or rank-to rank-from)
458 14 : group-ord (or (:order group) 1)]
459 6 : (when from
460 66 : (for [rank (range from (inc to))]
461 14 : {:source-group-id (str source-group-id)
462 2 : :rank rank
463 12 : :assigned-seed (rank-range-bracket-seed num-groups from group-ord rank)})))
464 :
465 16 : (and (= selector-type "top_n") source-group-id)
466 6 : (let [seed-base (or target-seed 1)]
467 31 : (for [r (range take)]
468 7 : {:source-group-id (str source-group-id)
469 2 : :rank (inc r)
470 3 : :assigned-seed (+ seed-base r)}))
471 :
472 6 : (= selector-type "top_n")
473 20 : (when-let [source-draw-id (preview-source-draw-id repos rule)]
474 6 : (let [groups (vec
475 12 : (group-repo/find-by-draw-id (:group-postgres-repo repos) source-draw-id))
476 4 : ng (count groups)]
477 8 : (when (pos? ng)
478 128 : (for [r (range take)
479 8 : [g group] (map-indexed vector groups)]
480 18 : {:source-group-id (str (:uuid group))
481 4 : :rank (inc r)
482 10 : :assigned-seed (top-n-seed ng r g)}))))
483 :
484 : :else nil)))
485 :
486 :
487 4 : (defn seed->round1-slot
488 : "Map of {physical-seed -> bracket-match-slot} for round-1 seed-origin slots
489 : of target-draw-id. Only includes slots still carrying source-type=seed —
490 : once a slot is filled (explicit_participant), its source-seed is cleared
491 : by the promoting code (see fill-from-class/promote-bracket!), so a filled
492 : slot silently drops out of this map. Callers that need to resolve a
493 : physical seed regardless of fill state (e.g. checking whether a seed is
494 : already occupied) must use round1-slot-by-physical-seed instead."
495 : [repos target-draw-id]
496 6 : (into
497 3 : {}
498 6 : (keep
499 3 : (fn [s]
500 36 : (when-let [seed (:source-seed s)] [seed s])))
501 12 : (find-round1-slots repos target-draw-id)))
502 :
503 :
504 4 : (defn round1-slot-by-physical-seed
505 : "Resolves a 1-based physical round-1 seed number to its current
506 : bracket-match-slot row for target-draw-id, regardless of whether that
507 : slot is still source-type=seed or has since been filled to
508 : explicit_participant (which clears source-seed — see seed->round1-slot's
509 : docstring for why that map can't answer this question). Re-derives the
510 : (match, slot) pair structurally from round-1 match-number ordering
511 : instead, which is assigned once at bracket creation
512 : (stage.helpers/create-match-slots!) and never changes: physical seed N
513 : belongs to the round-1 match at 0-based index (quot (dec N) 2), slot 1 if
514 : N is odd else slot 2. Returns nil if the seed is out of range for this
515 : bracket or the bracket structure isn't fully created yet."
516 : [repos target-draw-id seed]
517 8 : (when (and seed (pos? seed))
518 7 : (let [brackets (bracket-repo/find-by-draw-id (:bracket-postgres-repo repos) target-draw-id)
519 4 : bracket-ids (mapv :uuid brackets)
520 2 : rounds (bracket-round-repo/find-by-bracket-ids
521 3 : (:bracket-round-postgres-repo repos)
522 1 : bracket-ids)
523 12 : round1-ids (mapv :uuid (filter #(= 1 (:round-number %)) rounds))
524 3 : matches (sort-by
525 : :match-number
526 2 : (bracket-match-repo/find-by-bracket-round-ids
527 3 : (:bracket-match-postgres-repo repos)
528 1 : round1-ids))
529 4 : match-idx (quot (dec seed) 2)
530 6 : slot-num (if (odd? seed) 1 2)
531 4 : match (nth matches match-idx nil)]
532 3 : (when match
533 3 : (some
534 8 : #(when (= slot-num (:slot %)) %)
535 2 : (bms-repo/find-by-bracket-match-id
536 3 : (:bracket-match-slot-postgres-repo repos)
537 3 : (:uuid match)))))))
538 :
539 :
540 4 : (defn- bracket-match-rule-assignments
541 : "Preview for a source-type=bracket_match rule. The item only carries
542 : {bracket-match-id/group-id, slot}: the source (sourceBracketMatch,
543 : selectorType) is already on the parent rule, so callers format the label
544 : from there — mirrors the parent-rule-driven label the frontend already
545 : builds for the single-pinned-slot path.
546 :
547 : 'winner' pins a single already-physical seed via target-seed directly —
548 : unlike group/draw-sourced rules, no place-then-group distribution remap
549 : applies here, since there's only ever one candidate. Resolved purely from
550 : rule + bracket structure, so it's available before the source bracket
551 : match is even played.
552 :
553 : 'loser' has a deterministic DESTINATION GROUP (always the first group, by
554 : order, of target-draw-id — see desired-for-bracket-match-rule) but NOT a
555 : deterministic slot within it: unlike group-by-rank (whose ordering key is
556 : the static source-group order), a loser's slot is assigned first-come-
557 : first-served as sibling 'loser' rules' source matches complete in
558 : whatever order they're actually played — genuinely unknowable ahead of
559 : time, not just 'not yet resolved'. The item's :slot is nil to reflect
560 : that; callers can still use :group-id for a group-level (not per-slot)
561 : annotation."
562 : [repos rule]
563 4 : (let [{:keys [selector-type target-draw-id target-seed]} rule]
564 26 : (cond (and (= selector-type "winner") target-draw-id target-seed)
565 22 : (if-let [slot (get (seed->round1-slot repos target-draw-id) target-seed)]
566 18 : [{:bracket-match-id (str (:bracket-match-id slot))
567 6 : :slot (:slot slot)}]
568 0 : [])
569 :
570 7 : (and (= selector-type "loser") target-draw-id)
571 5 : (if-let [group
572 2 : (first
573 3 : (sort-by
574 : :order
575 6 : (group-repo/find-by-draw-id (:group-postgres-repo repos) target-draw-id)))]
576 10 : [{:group-id (str (:uuid group))
577 : :slot nil}]
578 1 : [])
579 :
580 0 : :else [])))
581 :
582 :
583 4 : (defn- advanced-source-group-slots
584 : "{source-group-uuid → target slot} for source groups whose rank-from
585 : finisher this rule has already advanced into target-group. The source
586 : group is found by the advanced participant's membership; the slot is the
587 : advancement's :assigned-slot, falling back to the target slot the
588 : participant occupies. {} when repos carries no advancement repo (e.g.
589 : transaction-scoped repos)."
590 : [repos rule target-group target-gps source-groups]
591 16 : (if-let [adv-repo (:advancement-postgres-repo repos)]
592 8 : (let [advancements (filter
593 11 : #(= (str (:to-group-id %)) (str (:uuid target-group)))
594 12 : (advancement-repo/find-by-rule-id adv-repo (:uuid rule)))
595 4 : source-gps (gp-repo/find-by-group-ids
596 6 : (:group-participant-postgres-repo repos)
597 8 : (mapv :uuid source-groups))
598 4 : group-by-pid (into
599 2 : {}
600 4 : (keep
601 2 : (fn [gp]
602 18 : (when-let [pid (:participant-id gp)] [(str pid) (str (:group-id gp))])))
603 2 : source-gps)
604 4 : target-slot-by (into
605 2 : {}
606 4 : (keep
607 2 : (fn [gp]
608 22 : (when-let [pid (:participant-id gp)] [(str pid) (:slot gp)])))
609 2 : target-gps)]
610 4 : (into
611 2 : {}
612 4 : (keep
613 2 : (fn [{:keys [participant-id assigned-slot]}]
614 4 : (let [pid (str participant-id)
615 3 : group-id (get group-by-pid pid)
616 5 : slot (or assigned-slot (get target-slot-by pid))]
617 10 : (when (and group-id slot) [group-id slot]))))
618 2 : advancements))
619 0 : {}))
620 :
621 :
622 4 : (defn- rank-range-by-group-rank-assignments
623 : "Preview for a wildcard rank_range rule with extra.group-by-rank: each
624 : source group's rank-from finisher fills one of the target group's empty
625 : slots, in source-group order (see desired-for-rank-range-by-group-rank /
626 : place-in-target-group!). Unlike bracket_match 'loser' rules, this IS
627 : deterministic ahead of any result: the pairing depends only on source
628 : group order and the target group's existing empty-slot layout, never on
629 : who ends up occupying a rank. Source groups this rule has already
630 : advanced keep the slot their finisher actually landed in; only the
631 : remaining source groups are paired with the remaining empty slots, so
632 : placeholders keep naming the right group as groups finish out of order.
633 : Truncates to (min pending-source-groups empty-slots) — a misconfigured
634 : rule with more source groups than target slots just leaves the extra
635 : source groups without an assignment, rather than failing outright
636 : (unlike the real promote path, which is all-or-nothing per batch)."
637 : [repos rule]
638 4 : (let [{:keys [extra rank-from target-draw-id]} rule
639 6 : target-group-order (:group-by-rank extra)]
640 24 : (if-not (and rank-from target-group-order target-draw-id)
641 0 : []
642 8 : (let [target-group (some
643 16 : #(when (= target-group-order (:order %)) %)
644 4 : (group-repo/find-by-draw-id
645 6 : (:group-postgres-repo repos)
646 2 : target-draw-id))
647 8 : source-draw-id (preview-source-draw-id repos rule)
648 6 : source-groups (when source-draw-id
649 4 : (group-repo/find-by-draw-id
650 6 : (:group-postgres-repo repos)
651 2 : source-draw-id))]
652 21 : (if-not (and target-group (seq source-groups))
653 1 : []
654 6 : (let [target-gps (gp-repo/find-by-group-id
655 6 : (:group-participant-postgres-repo repos)
656 6 : (:uuid target-group))
657 4 : empty-slots (->>
658 2 : target-gps
659 18 : (filter #(nil? (:participant-id %)))
660 2 : (sort-by :slot))
661 : advanced-slots
662 14 : (advanced-source-group-slots repos rule target-group target-gps source-groups)
663 24 : pending-groups (remove #(contains? advanced-slots (str (:uuid %))) source-groups)
664 26 : pending-slots (zipmap (map (comp str :uuid) pending-groups) (map :slot empty-slots))
665 8 : slot-by-group (merge pending-slots advanced-slots)]
666 4 : (vec
667 4 : (keep
668 2 : (fn [source-group]
669 26 : (when-let [slot (get slot-by-group (str (:uuid source-group)))]
670 20 : {:source-group-id (str (:uuid source-group))
671 2 : :rank rank-from
672 10 : :group-id (str (:uuid target-group))
673 2 : :slot slot}))
674 2 : source-groups))))))))
675 :
676 :
677 4 : (defn rule-target-assignments
678 : "Deterministic target slot preview for a rule, independent of whether the
679 : source stage's/match's result is final — the same computation the real
680 : reconcile path applies once a participant locks, just without requiring
681 : anything to be decided yet.
682 :
683 : For group/draw-sourced top_n and rank_range rules targeting a bracket:
684 : (rank[, source-group]) -> physical target slot, applying the same seed
685 : arithmetic and distribution remap as reconcile.
686 : For a wildcard rank_range rule targeting a group (extra.group-by-rank):
687 : see rank-range-by-group-rank-assignments.
688 : For a source-group rank_range rule targeting a group without an explicit
689 : slot: see rank-range-to-group-assignments.
690 : For bracket_match-sourced rules: see bracket-match-rule-assignments.
691 :
692 : Returns [] for rule shapes with no ambiguity to preview — rules that
693 : already carry a single, explicit target-slot. bracket_match 'loser' rules
694 : are a partial case: they resolve to a deterministic destination group
695 : with a nil slot, since which physical slot they land in is genuinely
696 : undecidable ahead of time (see bracket-match-rule-assignments)."
697 : [repos rule]
698 35 : (cond (= "bracket_match" (:source-type rule)) (bracket-match-rule-assignments repos rule)
699 :
700 44 : (and (= "rank_range" (:selector-type rule)) (contains? (:extra rule) :group-by-rank))
701 8 : (rank-range-by-group-rank-assignments repos rule)
702 :
703 13 : (rank-range-to-group? rule) (rank-range-to-group-assignments repos rule)
704 :
705 : :else
706 12 : (let [target-draw-id (:target-draw-id rule)]
707 15 : (if (nil? target-draw-id)
708 1 : []
709 15 : (let [logical (logical-assignments repos rule)]
710 12 : (if (empty? logical)
711 2 : []
712 15 : (let [m (target-bracket-size repos target-draw-id)
713 12 : seed->slot (seed->round1-slot repos target-draw-id)]
714 6 : (mapv
715 3 : (fn
716 : [{:keys [assigned-seed]
717 : :as a}]
718 18 : (let [physical-seed (apply-distribution-seed rule m assigned-seed)
719 9 : slot (get seed->slot physical-seed)]
720 12 : (->
721 3 : a
722 9 : (dissoc :assigned-seed)
723 6 : (assoc :seed physical-seed
724 : :bracket-match-id
725 50 : (some->
726 3 : slot
727 : :bracket-match-id
728 3 : str)
729 :
730 9 : :slot (:slot slot)))))
731 3 : logical))))))))
|