Line data Source code
1 4 : (ns matchscore.application.stage.reset-rules
2 : (:require
3 : [cats.monad.either :as either]
4 : [matchscore.application.stage.helpers :as stage-helpers]
5 : [matchscore.domain.advancement-rule.repository.postgres :as advancement-rule-postgres-repo]
6 : [matchscore.domain.stage.repository.postgres :as stage-postgres-repo]
7 : [next.jdbc :as jdbc]
8 : [next.jdbc.result-set :as rs]))
9 :
10 :
11 4 : (defn execute!
12 : "Deletes all advancement rules for a stage and removes :advancement-type from its config.
13 : Both mutations run in a single transaction. Returns Either<error, nil>."
14 : [{:keys [repos pg]} stage-uuid]
15 2 : (try
16 8 : (jdbc/with-transaction
17 2 : [tx pg]
18 14 : (let [tx-opts (jdbc/with-options tx {:builder-fn rs/as-kebab-maps})
19 8 : tx-repos (stage-helpers/make-tx-repos repos tx-opts)
20 6 : ar-repo (:advancement-rule-postgres-repo tx-repos)
21 6 : s-repo (:stage-postgres-repo tx-repos)
22 8 : stage (stage-postgres-repo/find-by-id s-repo stage-uuid)]
23 11 : (when (nil? stage)
24 1 : (throw
25 3 : (ex-info
26 : "tx-rollback"
27 4 : {::result (either/left
28 5 : {:type :not-found
29 : :message "Stage not found"})})))
30 8 : (advancement-rule-postgres-repo/delete-by-stage-id! ar-repo stage-uuid)
31 14 : (let [new-cfg (dissoc (:config stage) :advancement-type)
32 16 : [ok?] (stage-postgres-repo/upsert! s-repo (assoc stage :config new-cfg))
33 4 : result (if ok?
34 6 : (either/right nil)
35 2 : (either/left
36 5 : {:type :db-error
37 : :message "Failed to update stage config"}))]
38 17 : (if (either/left? result) (throw (ex-info "tx-rollback" {::result result})) result))))
39 : (catch clojure.lang.ExceptionInfo e
40 12 : (if (contains? (ex-data e) ::result) (::result (ex-data e)) (throw e)))))
|