LCOV - code coverage report
Current view: top level - matchscore/domain/class_participant/repository - postgres.clj Coverage Total Hit
Test: lcov.info Lines: 82.4 % 222 183
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.domain.class-participant.repository.postgres
       2              :   (:require
       3              :    [cats.monad.either :as either]
       4              :    [cheshire.core :as json]
       5              :    [honey.sql :as sql]
       6              :    [matchscore.domain.class-participant.entity :as entity]
       7              :    [matchscore.utils.audit :as audit]
       8              :    [matchscore.utils.db :as utils.db]
       9              :    [matchscore.utils.errors :as utils.errors]
      10              :    [matchscore.utils.pagination :as qh]
      11              :    [next.jdbc :as jdbc]))
      12              : 
      13              : 
      14            4 : (defprotocol
      15              :   ClassParticipantPostgresRepository
      16              :   (find-by-class-and-participant
      17              :    [this class-id participant-id]
      18              :    "Find by composite PK. Returns record or nil.")
      19              :   (find-by-class-id
      20              :    [this class-id]
      21              :    "Find all participants for a class. Returns seq.")
      22              :   (find-by-class-ids
      23              :    [this class-ids]
      24              :    "Find all participants for class ids. Returns seq.")
      25              :   (find-by-participant-id
      26              :    [this participant-id]
      27              :    "Find all class entries for a participant. Returns seq.")
      28              :   (insert!
      29              :    [this participant]
      30              :    "Inserts a class participant. Returns Either<Error, ClassParticipant>.
      31              :       Returns left with :error.class-participant/conflict when the composite key already exists.")
      32              :   (bulk-insert!
      33              :    [this participants]
      34              :    "Inserts multiple class participants atomically, skipping conflicts.
      35              :       Returns Either<Error, {:inserted-count int}>.")
      36              :   (save!
      37              :    [this participant]
      38              :    "Persists a class participant (insert or update).
      39              :       Returns Either<Error, ClassParticipant>.")
      40              :   (delete-by-participant-and-event!
      41              :    [this participant-id event-id]
      42              :    "Deletes all class participants for a participant across classes of a given event. Idempotent.")
      43              :   (delete-by-class-and-participant!
      44              :    [this class-id participant-id]
      45              :    "Deletes a single class participant by composite PK. Idempotent.")
      46              :   (bulk-delete-by-class-and-participants!
      47              :    [this class-id participant-ids]
      48              :    "Deletes multiple class participants for a given class by participant IDs. Idempotent.")
      49              :   (search
      50              :    [this filters pagination]
      51              :    "Search. filters: {:classId {...} :participantId {...} :status {...}}. sort: #{:registered-at :status}, default: :registered-at. OFFSET-ONLY pagination (no cursor)."))
      52              : 
      53              : 
      54            4 : (defn- filters->specs
      55              :   "Converts a GraphQL filters map to a seq of [column op value] specs."
      56              :   [{:keys [classId participantId status]}]
      57            2 :   (qh/typed-filters->specs
      58            7 :    {:class-id       (utils.db/cast-uuid-filter classId)
      59            3 :     :participant-id (utils.db/cast-uuid-filter participantId)
      60            1 :     :status         status}))
      61              : 
      62              : 
      63            4 : (defn- row->class-participant
      64              :   "Converts a database row to a domain ClassParticipant map."
      65              :   [row]
      66           32 :   (when row (entity/make-class-participant (utils.db/unqualify-keys row))))
      67              : 
      68              : 
      69            4 : (defn- participant->row
      70              :   "Converts a domain ClassParticipant map to a database row for upsert."
      71              :   [participant]
      72            4 :   (let [{:keys [class-id
      73              :                 participant-id
      74              :                 seed
      75              :                 status
      76              :                 registered-at
      77              :                 confirmed-at
      78              :                 extra
      79              :                 source
      80              :                 payment-status
      81              :                 payment-amount
      82              :                 payment-currency
      83              :                 paid-at
      84              :                 payment-marked-by]}
      85            4 :         participant]
      86           58 :     (cond->
      87           52 :       {:class_id       [:cast class-id :uuid]
      88           16 :        :participant_id [:cast participant-id :uuid]
      89            4 :        :seed           seed
      90           20 :        :status         (or status "registered")
      91           12 :        :registered_at  (when registered-at
      92           20 :                          (if (instance? java.time.Instant registered-at)
      93           12 :                            (java.sql.Timestamp/from registered-at)
      94            2 :                            registered-at))
      95            8 :        :confirmed_at   (when confirmed-at
      96            0 :                          (if (instance? java.time.Instant confirmed-at)
      97            0 :                            (java.sql.Timestamp/from confirmed-at)
      98            0 :                            confirmed-at))
      99           40 :        :extra          [:cast (json/generate-string (or extra {})) :jsonb]
     100           20 :        :source         (or source "matchscore")}
     101           22 :       (contains? participant :payment-status)    (assoc :payment_status
     102           10 :                                                   (or payment-status "unpaid"))
     103           24 :       (contains? participant :payment-amount)    (assoc :payment_amount payment-amount)
     104           24 :       (contains? participant :payment-currency)  (assoc :payment_currency payment-currency)
     105           22 :       (contains? participant :paid-at)           (assoc :paid_at
     106            5 :                                                   (when paid-at
     107            5 :                                                     (if (instance? java.time.Instant paid-at)
     108            3 :                                                       (java.sql.Timestamp/from paid-at)
     109            0 :                                                       paid-at)))
     110           18 :       (contains? participant :payment-marked-by) (assoc :payment_marked_by
     111            5 :                                                   (when payment-marked-by
     112            4 :                                                     [:cast payment-marked-by :uuid])))))
     113              : 
     114              : 
     115           16 : (def ^:private valid-sort-fields #{:registered-at :status})
     116              : 
     117              : 
     118            8 : (def ^:private default-sort :registered-at)
     119              : 
     120              : 
     121            4 : (defn- resolve-sort
     122              :   [{:keys [sort-by sort-dir]}]
     123           11 :   [(if (valid-sort-fields sort-by) sort-by default-sort) (if (= sort-dir :desc) :desc :asc)])
     124              : 
     125              : 
     126            4 : (def ^:private base-query
     127           28 :   {:select [[:cp.class-id :class-id]
     128           12 :             [:cp.participant-id :participant-id]
     129           12 :             [:cp.seed :seed]
     130           12 :             [:cp.status :status]
     131           12 :             [:cp.registered-at :registered-at]
     132           12 :             [:cp.confirmed-at :confirmed-at]
     133           12 :             [:cp.extra :extra]
     134           12 :             [:cp.created-datetime :created-datetime]
     135           12 :             [:cp.updated-datetime :updated-datetime]
     136           12 :             [:cp.source :source]
     137           12 :             [:cp.payment-status :payment-status]
     138           12 :             [:cp.payment-amount :payment-amount]
     139           12 :             [:cp.payment-currency :payment-currency]
     140           12 :             [:cp.paid-at :paid-at]
     141           12 :             [:cp.payment-marked-by :payment-marked-by]]
     142           16 :    :from   [[:event_class_participants :cp]]})
     143              : 
     144              : 
     145            4 : (defrecord
     146              :   PostgresClassParticipantRepository
     147              :   [ds]
     148              :   ClassParticipantPostgresRepository
     149              : 
     150              :   (find-by-class-and-participant
     151              :    [_ class-id participant-id]
     152           15 :    (let [query  (assoc base-query
     153            6 :                  :where [:and
     154           21 :                          [:= :cp.class-id [:cast class-id :uuid]]
     155           21 :                          [:= :cp.participant-id [:cast participant-id :uuid]]])
     156            3 :          result (->>
     157            9 :                   (sql/format query)
     158            9 :                   (jdbc/execute! ds)
     159            3 :                   first)]
     160            9 :      (row->class-participant result)))
     161              : 
     162              :   (find-by-class-id
     163              :    [_ class-id]
     164            4 :    (->>
     165           44 :      (assoc base-query :where [:= :cp.class-id [:cast class-id :uuid]])
     166            4 :      sql/format
     167           16 :      (jdbc/execute! ds)
     168            8 :      (mapv row->class-participant)))
     169              : 
     170              :   (find-by-class-ids
     171              :    [_ class-ids]
     172            4 :    (if (empty? class-ids)
     173            0 :      []
     174            1 :      (->>
     175           16 :        (assoc base-query :where [:in :cp.class-id (mapv #(vector :cast % :uuid) class-ids)])
     176            1 :        sql/format
     177            4 :        (jdbc/execute! ds)
     178            2 :        (mapv row->class-participant))))
     179              : 
     180              :   (find-by-participant-id
     181              :    [_ participant-id]
     182            2 :    (->>
     183           22 :      (assoc base-query :where [:= :cp.participant-id [:cast participant-id :uuid]])
     184            2 :      sql/format
     185            8 :      (jdbc/execute! ds)
     186            4 :      (mapv row->class-participant)))
     187              : 
     188              :   (insert!
     189              :    [_ participant]
     190            4 :    (try
     191           36 :      (let [query  {:insert-into :event_class_participants
     192           16 :                    :values      [(participant->row participant)]
     193           12 :                    :on-conflict [:class_id :participant_id]
     194              :                    :do-nothing  true
     195            8 :                    :returning   [:*]}
     196            4 :            result (->>
     197           20 :                     (sql/format (audit/stamp query))
     198           12 :                     (jdbc/execute! ds)
     199            4 :                     first)]
     200            8 :        (if result
     201           20 :          (either/right (row->class-participant result))
     202            2 :          (either/left
     203            3 :           (utils.errors/build-error
     204              :            :check
     205            6 :            {:code    :error.class-participant/conflict
     206              :             :message "Participant is already registered for this class"
     207            6 :             :context {:class-id       (:class-id participant)
     208            3 :                       :participant-id (:participant-id participant)}}))))
     209              :      (catch Exception e
     210            0 :        (either/left
     211            0 :         (utils.errors/build-error
     212              :          :postgres
     213            0 :          {:message (.getMessage e)
     214            0 :           :context {:table          :event_class_participants
     215              :                     :op             :insert
     216            0 :                     :class-id       (:class-id participant)
     217            0 :                     :participant-id (:participant-id participant)}})))))
     218              : 
     219              :   (bulk-insert!
     220              :    [_ participants]
     221            8 :    (if (empty? participants)
     222            5 :      (either/right {:inserted-count 0})
     223            2 :      (try
     224           18 :        (let [query   {:insert-into :event_class_participants
     225            8 :                       :values      (mapv participant->row participants)
     226            6 :                       :on-conflict [:class_id :participant_id]
     227              :                       :do-nothing  true
     228            4 :                       :returning   [:*]}
     229            2 :              results (->>
     230           10 :                        (sql/format (audit/stamp query))
     231            4 :                        (jdbc/execute! ds))]
     232           12 :          (either/right {:inserted-count (count results)}))
     233              :        (catch Exception e
     234            0 :          (either/left
     235            0 :           (utils.errors/build-error
     236              :            :postgres
     237            0 :            {:message (.getMessage e)
     238            0 :             :context {:table :event_class_participants
     239              :                       :op    :bulk-insert}}))))))
     240              : 
     241              :   (save!
     242              :    [_ participant]
     243            2 :    (try
     244           30 :      (let [payment-fields (cond-> []
     245           14 :                             (contains? participant :payment-status)    (conj :payment_status)
     246           14 :                             (contains? participant :payment-amount)    (conj :payment_amount)
     247           14 :                             (contains? participant :payment-currency)  (conj :payment_currency)
     248           14 :                             (contains? participant :paid-at)           (conj :paid_at)
     249           10 :                             (contains? participant :payment-marked-by) (conj :payment_marked_by))
     250           14 :            query          {:insert-into   :event_class_participants
     251            8 :                            :values        [(participant->row participant)]
     252            6 :                            :on-conflict   [:class_id :participant_id]
     253            8 :                            :do-update-set {:fields (into
     254           14 :                                                     [:seed
     255              :                                                      :status
     256              :                                                      :confirmed_at
     257              :                                                      :extra
     258              :                                                      :source
     259              :                                                      :updated_datetime]
     260            2 :                                                     payment-fields)}
     261            4 :                            :returning     [:*]}
     262            2 :            result         (->>
     263           10 :                             (sql/format (audit/stamp query))
     264            6 :                             (jdbc/execute! ds)
     265            2 :                             first)]
     266           10 :        (either/right (row->class-participant result)))
     267              :      (catch Exception e
     268            0 :        (either/left
     269            0 :         (utils.errors/build-error
     270              :          :postgres
     271            0 :          {:message (.getMessage e)
     272            0 :           :context {:table          :event_class_participants
     273              :                     :op             :upsert
     274            0 :                     :class-id       (:class-id participant)
     275            0 :                     :participant-id (:participant-id participant)}})))))
     276              : 
     277              :   (delete-by-participant-and-event!
     278              :    [_ participant-id event-id]
     279            2 :    (try
     280           10 :      (let [query {:delete-from :event_class_participants
     281            4 :                   :where       [:and
     282           14 :                                 [:= :participant_id [:cast participant-id :uuid]]
     283            6 :                                 [:in
     284              :                                  :class_id
     285           12 :                                  {:select [:uuid]
     286            4 :                                   :from   [:event_classes]
     287           14 :                                   :where  [:= :event_id [:cast event-id :uuid]]}]]}]
     288           12 :        (jdbc/execute! ds (sql/format query))
     289            6 :        (either/right nil))
     290              :      (catch Exception e
     291            0 :        (either/left
     292            0 :         (utils.errors/build-error
     293              :          :postgres
     294            0 :          {:message (.getMessage e)
     295            0 :           :context {:table          :event_class_participants
     296              :                     :op             :delete-by-participant-and-event
     297            0 :                     :participant-id participant-id
     298            0 :                     :event-id       event-id}})))))
     299              : 
     300              :   (delete-by-class-and-participant!
     301              :    [_ class-id participant-id]
     302            1 :    (try
     303            5 :      (let [query {:delete-from :event_class_participants
     304            2 :                   :where       [:and
     305            7 :                                 [:= :class_id [:cast class-id :uuid]]
     306            7 :                                 [:= :participant_id [:cast participant-id :uuid]]]}]
     307            6 :        (jdbc/execute! ds (sql/format query))
     308            3 :        (either/right nil))
     309              :      (catch Exception e
     310            0 :        (either/left
     311            0 :         (utils.errors/build-error
     312              :          :postgres
     313            0 :          {:message (.getMessage e)
     314            0 :           :context {:table          :event_class_participants
     315              :                     :op             :delete-by-class-and-participant
     316            0 :                     :class-id       class-id
     317            0 :                     :participant-id participant-id}})))))
     318              : 
     319              :   (bulk-delete-by-class-and-participants!
     320              :    [_ class-id participant-ids]
     321            4 :    (if (empty? participant-ids)
     322            0 :      (either/right {:deleted-count 0})
     323            1 :      (try
     324            1 :        (let [query
     325            4 :              {:delete-from :event_class_participants
     326            2 :               :where       [:and
     327            7 :                             [:= :class_id [:cast class-id :uuid]]
     328           12 :                             [:in :participant_id (mapv #(vector :cast % :uuid) participant-ids)]]}]
     329            2 :          (either/right
     330           12 :           {:deleted-count (:next.jdbc/update-count (first (jdbc/execute! ds (sql/format query))))}))
     331              : 
     332              :        (catch Exception e
     333            0 :          (either/left
     334            0 :           (utils.errors/build-error
     335              :            :postgres
     336            0 :            {:message (.getMessage e)
     337            0 :             :context {:table    :event_class_participants
     338              :                       :op       :bulk-delete-by-class-and-participants
     339            0 :                       :class-id class-id}}))))))
     340              : 
     341              :   (search
     342              :    [_ filters pagination]
     343            5 :    (let [pagination'   (dissoc pagination :cursor)
     344            3 :          specs         (filters->specs filters)
     345            8 :          take-n        (or (:limit pagination') 20)
     346            3 :          [sort-col direction] (resolve-sort pagination')
     347            6 :          query         (cond->
     348            3 :                          (->
     349            4 :                            (qh/apply-filters base-query specs)
     350            5 :                            (assoc :order-by [[sort-col direction]
     351            3 :                                              [:cp.class-id direction]
     352            3 :                                              [:cp.participant-id direction]]
     353            2 :                                   :limit    (inc take-n)))
     354           11 :                          (and (:offset pagination') (pos? (:offset pagination')))
     355            4 :                          (assoc :offset (:offset pagination')))
     356            1 :          rows          (->>
     357            3 :                          (sql/format query)
     358            3 :                          (jdbc/execute! ds)
     359            2 :                          (mapv row->class-participant))
     360            4 :          cnt-query     (qh/build-count-query base-query specs)
     361            3 :          total         (->>
     362            3 :                          (sql/format cnt-query)
     363            3 :                          (jdbc/execute-one! ds)
     364            1 :                          utils.db/unqualify-keys
     365              :                          :total)
     366            4 :          has-next-page (> (count rows) take-n)
     367            8 :          items         (if has-next-page (subvec rows 0 take-n) rows)]
     368            7 :      {:items         items
     369            1 :       :has-next-page has-next-page
     370              :       :end-cursor    nil
     371            1 :       :total-count   total})))
     372              : 
     373              : 
     374            4 : (defn make-repository
     375              :  "Creates a PostgresClassParticipantRepository from a ds."
     376              :  [ds]
     377           12 :  (->PostgresClassParticipantRepository ds))
        

Generated by: LCOV version 2.0-1