Line data Source code
1 4 : (ns matchscore.domain.class-participant.command
2 : (:require
3 : [cats.core :as c]
4 : [cats.monad.either :as either]
5 : [matchscore.domain.class-participant.entity :as entity]
6 : [matchscore.domain.class-participant.repository.postgres :as class-participant-postgres-repo]
7 : [matchscore.utils.errors :as utils.errors]))
8 :
9 :
10 4 : (defn register-participant!
11 : "Registers a participant into a class. Checks for composite key conflicts atomically.
12 : Returns Either<Error, ClassParticipant>."
13 : [{:keys [repos]} participant-data]
14 16 : (let [repo (:class-participant-postgres-repo repos)]
15 16 : (class-participant-postgres-repo/insert! repo participant-data)))
16 :
17 :
18 4 : (defn- find-by-composite-key-or-fail
19 : [repo class-id participant-id]
20 7 : (if-let [existing (class-participant-postgres-repo/find-by-class-and-participant
21 1 : repo
22 1 : class-id
23 1 : participant-id)]
24 3 : (either/right existing)
25 2 : (either/left
26 3 : (utils.errors/build-error
27 : :check
28 5 : {:code :error.class-participant/not-found
29 : :message "Class participant not found."}))))
30 :
31 :
32 4 : (defn- check-status
33 : [{:keys [status]
34 : :as participant-data}]
35 11 : (if (or (nil? status) (entity/valid-status? status))
36 3 : (either/right participant-data)
37 2 : (either/left
38 3 : (utils.errors/build-error
39 : :check
40 6 : {:code :error.class-participant/invalid-status
41 : :message "Unknown participant status."
42 3 : :context {:status status}}))))
43 :
44 :
45 4 : (defn- save-if-changed
46 : [repo existing participant-data]
47 5 : (if (entity/has-changes? existing participant-data)
48 3 : (c/fmap
49 6 : #(hash-map :code :success.class-participant/ok :data %)
50 7 : (class-participant-postgres-repo/save! repo (entity/merge-updates existing participant-data)))
51 2 : (either/right
52 4 : {:code :success.class-participant/no-changes
53 1 : :data existing})))
54 :
55 :
56 4 : (defn update-participant!
57 : "Updates an existing class participant. Checks for existence first and rejects statuses
58 : a participant cannot hold. Returns Either<Error, {:code kw :data ClassParticipant}>."
59 : [{:keys [repos]} participant-data]
60 4 : (let [repo (:class-participant-postgres-repo repos)
61 23 : result (c/mlet [existing (find-by-composite-key-or-fail
62 1 : repo
63 3 : (:class-id participant-data)
64 3 : (:participant-id participant-data))
65 4 : _ (check-status participant-data)
66 5 : result (save-if-changed repo existing participant-data)]
67 3 : (c/return result))]
68 1 : result))
|