Line data Source code
1 4 : (ns matchscore.application.event.update-participant
2 : "Updates the status and roles of an event participant.
3 : Only admins may be in an event without a class, so the admin role cannot be taken
4 : from a participant who is in none."
5 : (:require
6 : [cats.core :as c]
7 : [cats.monad.either :as either]
8 : [matchscore.domain.class-participant.repository.postgres :as class-participant-postgres-repo]
9 : [matchscore.domain.class.repository.postgres :as class-postgres-repo]
10 : [matchscore.domain.event-participant.command :as event-participant-command]
11 : [matchscore.domain.event-participant.repository.postgres :as event-participant-postgres-repo]
12 : [matchscore.utils.errors :as utils.errors]))
13 :
14 :
15 10 : (defn- admin? [roles] (boolean (some #{"admin"} roles)))
16 :
17 :
18 4 : (defn- left-without-class?
19 : "True when the event has classes and the participant is in none of them."
20 : [repos event-id participant-id]
21 2 : (let [class-ids (->>
22 6 : (class-postgres-repo/find-by-event-id (:class-postgres-repo repos) event-id)
23 6 : (map (comp str :uuid))
24 1 : set)]
25 4 : (and
26 3 : (seq class-ids)
27 1 : (not-any?
28 5 : (comp class-ids str :class-id)
29 2 : (class-participant-postgres-repo/find-by-participant-id
30 3 : (:class-participant-postgres-repo repos)
31 1 : participant-id)))))
32 :
33 :
34 4 : (defn- check-admin-role-not-dropped-without-class
35 : [repos {:keys [event-id participant-id roles]}]
36 3 : (let [existing (event-participant-postgres-repo/find-by-id
37 3 : (:event-participant-postgres-repo repos)
38 1 : event-id
39 1 : participant-id)]
40 1 : (if
41 16 : (and
42 1 : existing
43 3 : (some? roles)
44 5 : (admin? (:roles existing))
45 5 : (not (admin? roles))
46 4 : (left-without-class? repos event-id participant-id))
47 2 : (either/left
48 3 : (utils.errors/build-error
49 : :check
50 5 : {:code :error.event-participant/class-required
51 : :message "Add the participant to a class before removing the admin role."}))
52 3 : (either/right nil))))
53 :
54 :
55 4 : (defn execute!
56 : "Returns Either<Error, {:code kw :data EventParticipant}>."
57 : [{:keys [repos]
58 : :as ctx}
59 : participant-data]
60 11 : (c/mlet [_ (check-admin-role-not-dropped-without-class repos participant-data)]
61 4 : (event-participant-command/update-participant! ctx participant-data)))
|