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