Line data Source code
1 4 : (ns matchscore.application.template.participant
2 : (:require
3 : [cats.core :as c]
4 : [cats.monad.either :as either]
5 : [matchscore.domain.participant.repository.postgres :as participant-postgres-repo]
6 : [matchscore.domain.template-participant.command :as template-participant-command]
7 : [matchscore.domain.template-participant.repository.postgres
8 : :as
9 : template-participant-postgres-repo]
10 : [matchscore.domain.user.repository.postgres :as user-postgres-repo]
11 : [matchscore.utils.errors :as utils.errors])
12 : (:import
13 : (java.time Instant)))
14 :
15 :
16 : ;; NOTE: `template-uuid` is the internal template UUID. The global
17 : ;; `wrap-resolve-entity-ids` middleware resolves the `:template-uuid` route param
18 : ;; (a public id) to the internal UUID before these handlers run.
19 :
20 :
21 4 : (defn- find-user-or-fail
22 : [repos user-uuid]
23 11 : (if-let [user (user-postgres-repo/find-by-id (:user-postgres-repo repos) user-uuid)]
24 3 : (either/right user)
25 0 : (either/left
26 0 : (utils.errors/build-error
27 : :check
28 0 : {:code :error.template-participant/user-not-found
29 : :message "User not found."}))))
30 :
31 :
32 4 : (defn add!
33 : "Adds a user as a participant in the template. Creates a participant record if needed.
34 : `user-uuid` is the matchscore user UUID; `:roles` defaults to `[\"player\"]`.
35 : Returns Either<Error, EventTemplateParticipant>."
36 6 : ([ctx template-uuid user-uuid] (add! ctx template-uuid user-uuid nil))
37 : ([{:keys [repos]
38 : :as ctx}
39 : template-uuid
40 : user-uuid
41 : {:keys [roles]
42 : :or {roles ["player"]}}]
43 18 : (c/mlet [_ (find-user-or-fail repos user-uuid)
44 2 : participant (participant-postgres-repo/ensure-person-participant-for-user!
45 3 : (:participant-postgres-repo repos)
46 1 : user-uuid)]
47 2 : (template-participant-command/register-participant!
48 1 : ctx
49 11 : {:template-id template-uuid
50 3 : :participant-id (:uuid participant)
51 : :status "registered"
52 1 : :roles roles
53 1 : :extra {}
54 2 : :registered-at (Instant/now)
55 : :source "matchscore"}))))
56 :
57 :
58 4 : (defn remove!
59 : "Removes a participant from the template by participant UUID. Idempotent.
60 : Returns Either<Error, nil>."
61 : [{:keys [repos]
62 : :as _ctx}
63 : template-uuid
64 : participant-uuid]
65 2 : (template-participant-postgres-repo/delete!
66 3 : (:template-participant-postgres-repo repos)
67 1 : template-uuid
68 1 : participant-uuid))
69 :
70 :
71 4 : (defn update!
72 : "Updates status and/or roles for an existing template participant.
73 : Returns Either<Error, {:code kw :data EventTemplateParticipant}>."
74 : [{:as ctx} template-uuid participant-uuid update-data]
75 2 : (template-participant-command/update-participant!
76 1 : ctx
77 5 : (assoc update-data
78 1 : :template-id template-uuid
79 1 : :participant-id participant-uuid)))
|