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