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

            Line data    Source code
       1            4 : (ns matchscore.domain.user.repository.postgres
       2              :   (:require
       3              :    [camel-snake-kebab.core :as csk]
       4              :    [camel-snake-kebab.extras :as cske]
       5              :    [cats.monad.either :as either]
       6              :    [cheshire.core :as json]
       7              :    [clojure.string :as str]
       8              :    [honey.sql :as sql]
       9              :    [matchscore.domain.user.entity :as entity]
      10              :    [matchscore.utils.audit :as audit]
      11              :    [matchscore.utils.db :as utils.db]
      12              :    [matchscore.utils.errors :as utils.errors]
      13              :    [matchscore.utils.pagination :as qh]
      14              :    [next.jdbc :as jdbc]))
      15              : 
      16              : 
      17            4 : (defprotocol
      18              :   UserPostgresRepository
      19              :   (find-by-id
      20              :    [this id]
      21              :    "Find user by UUID string. Returns User map or nil.")
      22              :   (find-by-ids
      23              :    [this ids]
      24              :    "Find users by multiple UUIDs. Returns seq.")
      25              :   (find-by-username
      26              :    [this username]
      27              :    "Find user by username. Returns User map or nil.")
      28              :   (exists-by-username?
      29              :    [this username]
      30              :    "Returns true if a user with the given username exists.")
      31              :   (get-all
      32              :    [this]
      33              :    "Returns all users as a list of User maps.")
      34              :   (search
      35              :    [this filters pagination]
      36              :    "Search users by filters and pagination.
      37              :     filters: {:name {:eq \"...\"}}
      38              :     Returns {:items [...] :has-next-page bool :end-cursor \"...\" :total-count int}")
      39              :   (search-excluding-event
      40              :    [this event-id filters pagination]
      41              :    "Search users, excluding those already added as participants to the given event.
      42              :     Returns {:items [...] :has-next-page bool :end-cursor \"...\" :total-count int}")
      43              :   (search-excluding-template
      44              :    [this template-id filters pagination]
      45              :    "Search users, excluding those already added as participants to the given template.
      46              :     Returns {:items [...] :has-next-page bool :end-cursor \"...\" :total-count int}")
      47              :   (find-by-telegram-id
      48              :    [this telegram-id]
      49              :    "Find user by telegram_id. Returns User map or nil.")
      50              :   (count-users-with-role
      51              :    [this role]
      52              :    "Counts users with a global role.")
      53              :   (update-roles!
      54              :    [this user-id roles]
      55              :    "Updates global roles for a user. Returns Either<Error, User>.")
      56              :   (update-roles-preserving-last-root!
      57              :    [this user-id roles]
      58              :    "Updates global roles unless that would remove the last root user.
      59              :       Returns Either<Error, User>.")
      60              :   (update-name-locks!
      61              :    [this user-id languages]
      62              :    "Replaces the languages whose name only an admin can change. Any lock also marks the
      63              :     name as confirmed. Returns Either<Error, User>.")
      64              :   (save!
      65              :    [this account]
      66              :    "Persists a user (insert or update). Returns Either<Error, User>."))
      67              : 
      68              : 
      69           16 : (def ^:private valid-sort-fields #{:name :username})
      70              : 
      71              : 
      72            8 : (def ^:private default-sort :name)
      73              : 
      74              : 
      75            4 : (def ^:private base-query
      76           20 :   {:select [:*]
      77            8 :    :from   [:users]})
      78              : 
      79              : 
      80            4 : (defn- filters->specs
      81              :   [{:keys [name username]}]
      82              :   ;; One map so :con terms with the same value are OR-ed via a single CONCAT_WS ILIKE.
      83            4 :   (qh/typed-filters->specs
      84            8 :    (array-map
      85              :     :name
      86            2 :     name
      87            8 :     [:cast :name_localized :text]
      88           10 :     (select-keys name [:con])
      89              :     :username
      90            2 :     username)))
      91              : 
      92              : 
      93            4 : (defn- row->user
      94              :   "Converts a database row to a domain User map."
      95              :   [row]
      96           12 :   (when row
      97           16 :     (let [user (utils.db/unqualify-keys row)]
      98            8 :       (entity/make-user
      99           16 :        (update
     100            4 :         user
     101              :         :name-localized
     102            8 :         #(into
     103            4 :           {}
     104            8 :           (map
     105            4 :            (fn [[language value]]
     106           15 :             [(name language) value]))
     107           20 :           (or % {})))))))
     108              : 
     109              : 
     110            4 : (defn- user->row
     111              :   "Converts a domain User map to a database row for upsert.
     112              :    Settings are serialized to JSONB directly (not snake_cased) so that
     113              :    keys like :language are preserved as-is in the JSON column."
     114              :   [user]
     115           16 :   (let [settings (:settings user)
     116           12 :         name-localized (:name-localized user)
     117              :         {:keys [uuid
     118              :                 public_id
     119              :                 name
     120              :                 username
     121              :                 photo_url
     122              :                 telegram_id
     123              :                 is_fake
     124              :                 name_confirmed_at
     125              :                 telegram_bot_access_status
     126              :                 telegram_bot_access_updated_at]}
     127            8 :         (cske/transform-keys
     128            4 :          csk/->snake_case_keyword
     129           24 :          (dissoc user :settings :roles :name-localized))]
     130           53 :     (cond->
     131           60 :       {:uuid              [:cast uuid :uuid]
     132            4 :        :public_id         public_id
     133            4 :        :name              name
     134            4 :        :username          username
     135            4 :        :photo_url         photo_url
     136            4 :        :telegram_id       telegram_id
     137            8 :        :is_fake           (boolean is_fake)
     138           24 :        :settings          [:cast (json/generate-string settings) :jsonb]
     139           44 :        :name_localized    [:cast (json/generate-string (or name-localized {})) :jsonb]
     140            4 :        :name_confirmed_at name_confirmed_at}
     141           21 :       (some? telegram_bot_access_status) (assoc :telegram_bot_access_status
     142            3 :                                           telegram_bot_access_status)
     143           15 :       (some? telegram_bot_access_updated_at) (assoc :telegram_bot_access_updated_at
     144            1 :                                               telegram_bot_access_updated_at)
     145           60 :       (contains? user :roles) (assoc :roles [:cast (json/generate-string (:roles user)) :jsonb])
     146           28 :       (contains? user :country-code) (assoc :country_code (:country-code user)))))
     147              : 
     148              : 
     149            4 : (defrecord
     150              :   PostgresUserRepository
     151              :   [ds]
     152              :   UserPostgresRepository
     153              : 
     154              :   (get-all
     155              :    [_]
     156           18 :    (let [query {:select [:*]
     157            6 :                 :from   [:users]}]
     158            3 :      (->>
     159            9 :        (sql/format query)
     160            9 :        (jdbc/execute! ds)
     161            6 :        (mapv row->user))))
     162              : 
     163              :   (search
     164              :    [_ filters pagination]
     165            8 :    (let [specs (filters->specs filters)
     166           14 :          query (qh/build-search-query base-query specs valid-sort-fields default-sort pagination)
     167            2 :          rows  (->>
     168            6 :                  (sql/format query)
     169            6 :                  (jdbc/execute! ds)
     170            4 :                  (mapv row->user))
     171           10 :          opts  (when-not (:cursor pagination)
     172           10 :                  (let [cnt-query (qh/build-count-query base-query specs)
     173            6 :                        total     (->>
     174            6 :                                    (sql/format cnt-query)
     175            6 :                                    (jdbc/execute-one! ds)
     176            2 :                                    utils.db/unqualify-keys
     177              :                                    :total)]
     178            6 :                    {:total-count total}))]
     179           14 :      (qh/paginate-results rows valid-sort-fields default-sort pagination opts)))
     180              : 
     181              :   (search-excluding-event
     182              :    [_ event-id filters pagination]
     183            1 :    (let [exclude-clause
     184            3 :          [:not-in
     185              :           :uuid
     186            7 :           {:select [:p.user-id]
     187            4 :            :from   [[:participants :p]]
     188            4 :            :join   [[:event-participants :ep]
     189           13 :                     [:and [:= :ep.participant-id :p.uuid] [:= :ep.event-id [:cast event-id :uuid]]]]
     190            4 :            :where  [:is-not :p.user-id nil]}]
     191            4 :          base-q (qh/add-where-clause base-query exclude-clause)
     192            3 :          specs (filters->specs filters)
     193            7 :          query (qh/build-search-query base-q specs valid-sort-fields default-sort pagination)
     194            1 :          rows (->>
     195            3 :                 (sql/format query)
     196            3 :                 (jdbc/execute! ds)
     197            2 :                 (mapv row->user))
     198            5 :          opts (when-not (:cursor pagination)
     199            5 :                 (let [cnt-query (qh/build-count-query base-q specs)
     200            3 :                       total     (->>
     201            3 :                                   (sql/format cnt-query)
     202            3 :                                   (jdbc/execute-one! ds)
     203            1 :                                   utils.db/unqualify-keys
     204              :                                   :total)]
     205            3 :                   {:total-count total}))]
     206            7 :      (qh/paginate-results rows valid-sort-fields default-sort pagination opts)))
     207              : 
     208              :   (search-excluding-template
     209              :    [_ template-id filters pagination]
     210            1 :    (let [exclude-clause
     211            3 :          [:not-in
     212              :           :uuid
     213            7 :           {:select [:p.user-id]
     214            4 :            :from   [[:participants :p]]
     215            4 :            :join   [[:template-participants :tp]
     216            4 :                     [:= :tp.participant-id :p.uuid]
     217            3 :                     [:templates :t]
     218           10 :                     [:and [:= :t.uuid :tp.template-id] [:= :t.public-id template-id]]]
     219            4 :            :where  [:is-not :p.user-id nil]}]
     220            4 :          base-q (qh/add-where-clause base-query exclude-clause)
     221            3 :          specs (filters->specs filters)
     222            7 :          query (qh/build-search-query base-q specs valid-sort-fields default-sort pagination)
     223            1 :          rows (->>
     224            3 :                 (sql/format query)
     225            3 :                 (jdbc/execute! ds)
     226            2 :                 (mapv row->user))
     227            5 :          opts (when-not (:cursor pagination)
     228            5 :                 (let [cnt-query (qh/build-count-query base-q specs)
     229            3 :                       total     (->>
     230            3 :                                   (sql/format cnt-query)
     231            3 :                                   (jdbc/execute-one! ds)
     232            1 :                                   utils.db/unqualify-keys
     233              :                                   :total)]
     234            3 :                   {:total-count total}))]
     235            7 :      (qh/paginate-results rows valid-sort-fields default-sort pagination opts)))
     236              : 
     237              :   (find-by-id
     238              :    [_ id]
     239           28 :    (let [query  {:select [:*]
     240            8 :                  :from   [:users]
     241           28 :                  :where  [:= :uuid [:cast id :uuid]]}
     242            4 :          result (->>
     243           12 :                   (sql/format query)
     244           12 :                   (jdbc/execute! ds)
     245            4 :                   first)]
     246           12 :      (row->user result)))
     247              : 
     248              :   (find-by-ids
     249              :    [_ ids]
     250           16 :    (if (empty? ids)
     251            0 :      []
     252           12 :      (let [query (->
     253           20 :                    {:select [:*]
     254            8 :                     :from   [:users]}
     255           52 :                    (assoc :where [:in :uuid (mapv #(vector :cast % :uuid) ids)]))]
     256            4 :        (->>
     257           12 :          (sql/format query)
     258           12 :          (jdbc/execute! ds)
     259            8 :          (mapv row->user)))))
     260              : 
     261              :   (find-by-username
     262              :    [_ username]
     263           12 :    (when username
     264           28 :      (let [query  {:select [:*]
     265            8 :                    :from   [:users]
     266           32 :                    :where  [:= [:lower :username] (str/lower-case username)]}
     267            4 :            result (->>
     268           12 :                     (sql/format query)
     269           12 :                     (jdbc/execute! ds)
     270            4 :                     first)]
     271           12 :        (row->user result))))
     272              : 
     273              :   (find-by-telegram-id
     274              :    [_ telegram-id]
     275           28 :    (let [query  {:select [:*]
     276            8 :                  :from   [:users]
     277           16 :                  :where  [:= :telegram_id telegram-id]}
     278            4 :          result (->>
     279           12 :                   (sql/format query)
     280           12 :                   (jdbc/execute! ds)
     281            4 :                   first)]
     282           12 :      (row->user result)))
     283              : 
     284            6 :   (exists-by-username? [this username] (some? (find-by-username this username)))
     285              : 
     286              :   (count-users-with-role
     287              :    [_ role]
     288            3 :    (let [query ["SELECT count(*) AS count FROM users WHERE roles @> ?::jsonb"
     289            4 :                 (json/generate-string [role])]]
     290            3 :      (->>
     291            1 :        query
     292            3 :        (jdbc/execute-one! ds)
     293            1 :        utils.db/unqualify-keys
     294              :        :count)))
     295              : 
     296              :   (update-roles!
     297              :    [_ user-id roles]
     298            3 :    (try
     299           21 :      (let [query  {:update    :users
     300           24 :                    :set       {:roles [:cast (json/generate-string roles) :jsonb]}
     301           21 :                    :where     [:= :uuid [:cast user-id :uuid]]
     302            6 :                    :returning [:*]}
     303            3 :            result (->>
     304           15 :                     (sql/format (audit/stamp query))
     305            9 :                     (jdbc/execute! ds)
     306            3 :                     first)]
     307            6 :        (if result
     308           15 :          (either/right (row->user result))
     309            2 :          (either/left
     310            3 :           (utils.errors/build-error
     311              :            :postgres
     312            4 :            {:message "User not found"
     313            6 :             :context {:table :users
     314              :                       :op    :update-roles
     315            1 :                       :uuid  user-id}}))))
     316              :      (catch Exception e
     317            0 :        (either/left
     318            0 :         (utils.errors/build-error
     319              :          :postgres
     320            0 :          {:message (.getMessage e)
     321            0 :           :context {:table :users
     322              :                     :op    :update-roles
     323            0 :                     :uuid  user-id}})))))
     324              : 
     325              :   (update-name-locks!
     326              :    [_ user-id languages]
     327            2 :    (try
     328           14 :      (let [query  {:update    :users
     329              :                    ;; An admin who locks a name has reviewed it, so it also counts as
     330              :                    ;; confirmed: the user is no longer asked or reminded to confirm it.
     331           11 :                    :set       (cond->
     332           20 :                                 {:name_locks [:cast (json/generate-string (vec languages)) :jsonb]}
     333            8 :                                 (seq languages) (assoc :name_confirmed_at
     334           10 :                                                  [:coalesce :name_confirmed_at [:now]]))
     335           14 :                    :where     [:= :uuid [:cast user-id :uuid]]
     336            4 :                    :returning [:*]}
     337            2 :            result (->>
     338           10 :                     (sql/format (audit/stamp query))
     339            6 :                     (jdbc/execute! ds)
     340            2 :                     first)]
     341            4 :        (if result
     342           10 :          (either/right (row->user result))
     343            0 :          (either/left
     344            0 :           (utils.errors/build-error
     345              :            :postgres
     346            0 :            {:message "User not found"
     347            0 :             :context {:table :users
     348              :                       :op    :update-name-locks
     349            0 :                       :uuid  user-id}}))))
     350              :      (catch Exception e
     351            0 :        (either/left
     352            0 :         (utils.errors/build-error
     353              :          :postgres
     354            0 :          {:message (.getMessage e)
     355            0 :           :context {:table :users
     356              :                     :op    :update-name-locks
     357            0 :                     :uuid  user-id}})))))
     358              : 
     359              :   (update-roles-preserving-last-root!
     360              :    [_ user-id roles]
     361            2 :    (try
     362            2 :      (let
     363            6 :        [roles-json (json/generate-string roles)
     364              :         query
     365            4 :         ["UPDATE users
     366              :                         SET roles = ?::jsonb, updated_by = ?::uuid
     367              :                         WHERE uuid = ?::uuid
     368              :                         AND (
     369              :                           NOT (roles @> '[\"root\"]'::jsonb)
     370              :                           OR ?::jsonb @> '[\"root\"]'::jsonb
     371              :                           OR (SELECT count(*) FROM users WHERE roles @> '[\"root\"]'::jsonb) > 1
     372              :                         )
     373              :                         RETURNING *"
     374            2 :          roles-json
     375            4 :          (audit/actor-id)
     376            2 :          user-id
     377            2 :          roles-json]
     378           12 :         result (first (jdbc/execute! ds query))]
     379            4 :        (if result
     380           10 :          (either/right (row->user result))
     381            2 :          (either/left
     382            3 :           (utils.errors/build-error
     383              :            :postgres
     384            4 :            {:message "Cannot remove the last root user."
     385            6 :             :context {:table :users
     386              :                       :op    :update-roles-preserving-last-root
     387            1 :                       :uuid  user-id}}))))
     388              :      (catch Exception e
     389            0 :        (either/left
     390            0 :         (utils.errors/build-error
     391              :          :postgres
     392            0 :          {:message (.getMessage e)
     393            0 :           :context {:table :users
     394              :                     :op    :update-roles-preserving-last-root
     395            0 :                     :uuid  user-id}})))))
     396              : 
     397              :   (save!
     398              :    [_ user]
     399            4 :    (try
     400              :      ;; Optional columns are only written when the caller passes them, so a save
     401              :      ;; built from partial data (e.g. a fresh Telegram profile) keeps stored values.
     402           37 :      (let [update-fields (cond->
     403           36 :                            [:name
     404              :                             :name_localized
     405              :                             :name_confirmed_at
     406              :                             :username
     407              :                             :photo_url
     408              :                             :telegram_id
     409              :                             :is_fake
     410              :                             :settings]
     411           28 :                            (contains? user :roles)        (conj :roles)
     412           19 :                            (contains? user :country-code) (conj :country_code))
     413            8 :            update-set    (merge
     414           52 :                           (zipmap update-fields (map #(keyword "excluded" (name %)) update-fields))
     415           30 :                           (cond-> {}
     416           20 :                             (some? (:telegram-bot-access-status user))
     417            9 :                             (assoc :telegram_bot_access_status
     418           15 :                              [:case
     419           18 :                               [:= :users.telegram_bot_access_status [:inline "confirmed"]]
     420              :                               :users.telegram_bot_access_status
     421              :                               :else
     422              :                               :excluded.telegram_bot_access_status])
     423              : 
     424           20 :                             (some? (:telegram-bot-access-updated-at user))
     425            1 :                             (assoc :telegram_bot_access_updated_at
     426            5 :                              [:case
     427            6 :                               [:= :users.telegram_bot_access_status [:inline "confirmed"]]
     428              :                               :users.telegram_bot_access_updated_at
     429              :                               :else
     430              :                               :excluded.telegram_bot_access_updated_at])))
     431           28 :            query         {:insert-into   :users
     432           16 :                           :values        [(user->row user)]
     433            8 :                           :on-conflict   [:uuid]
     434            4 :                           :do-update-set update-set
     435            8 :                           :returning     [:*]}
     436            4 :            result        (->>
     437           20 :                            (sql/format (audit/stamp query))
     438           12 :                            (jdbc/execute! ds)
     439            4 :                            first)]
     440           20 :        (either/right (row->user result)))
     441              :      (catch Exception e
     442            2 :        (either/left
     443            3 :         (utils.errors/build-error
     444              :          :postgres
     445            4 :          {:message (.getMessage e)
     446            6 :           :context {:table :users
     447              :                     :op    :upsert
     448            3 :                     :uuid  (:uuid user)}}))))))
     449              : 
     450              : 
     451            4 : (defn make-repository
     452              :  "Creates a PostgresUserRepository from a ds."
     453              :  [ds]
     454           12 :  (->PostgresUserRepository ds))
        

Generated by: LCOV version 2.0-1