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

            Line data    Source code
       1            4 : (ns matchscore.domain.template.repository.postgres
       2              :   (:require
       3              :    [cats.monad.either :as either]
       4              :    [cheshire.core :as json]
       5              :    [clojure.string :as str]
       6              :    [honey.sql :as sql]
       7              :    [matchscore.domain.club.entity :as club-entity]
       8              :    [matchscore.domain.telegram-chat-member.repository.postgres :as telegram-chat-member-repo]
       9              :    [matchscore.domain.template.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.nanoid :as nanoid]
      14              :    [matchscore.utils.pagination :as qh]
      15              :    [next.jdbc :as jdbc]))
      16              : 
      17              : 
      18            4 : (defprotocol
      19              :   TemplatePostgresRepository
      20              :   (find-by-id
      21              :    [this id ctx]
      22              :    "Find event template by UUID string. Returns EventTemplate map or nil.")
      23              :   (find-by-ids
      24              :    [this ids]
      25              :    "Find event templates by UUID strings. Returns a vector of EventTemplate maps.")
      26              :   (find-by-public-id
      27              :    [this public-id]
      28              :    [this public-id ctx]
      29              :    "Find template by 12-char public_id. Returns EventTemplate map or nil.")
      30              :   (find-by-creator-id
      31              :    [this id ctx]
      32              :    "Find event template by UUID string. Returns EventTemplate map or nil.")
      33              :   (search
      34              :    [this filters pagination]
      35              :    "Search event templates by filters and pagination.
      36              :       filters: {:name {:eq \"...\"} :state {:eq \"...\"} :clubId {:eq \"uuid\"}
      37              :                 :sportCode {:eq \"...\"} :activityTypeCode {:eq \"...\"}
      38              :                 :createdBy {:eq \"uuid\"}}
      39              :       pagination: {:limit 20 :cursor \"base64...\" :sort-by :created-datetime :sort-dir :desc}
      40              :       Returns {:items [...] :has-next-page bool :end-cursor \"base64-or-nil\" :total-count N}")
      41              :   (save!
      42              :    [this template]
      43              :    "Persists an event template (insert or update). Returns Either<Error, EventTemplate>.")
      44              :   (delete!
      45              :    [this id]
      46              :    "Deletes an event template by UUID. Returns Either<Error, nil>."))
      47              : 
      48              : 
      49           12 : (declare -extract-club -parse-clubs-json)
      50              : 
      51              : 
      52            4 : (def ^:private clubs-agg-sql
      53              :   "Correlated subquery: JSON array of clubs for each template row (kebab-case keys)."
      54           76 :   (str
      55              :    "COALESCE("
      56              :    "(SELECT json_agg(json_build_object(" "'uuid',c.uuid::text,"
      57              :    "'public-id',c.public_id," "'sl-uuid',c.sl_uuid::text,"
      58              :    "'name',c.name," "'network',c.network,"
      59              :    "'country',c.country," "'city',c.city,"
      60              :    "'phone-number',c.phone_number," "'location',c.location,"
      61              :    "'working-hours',c.working_hours," "'images',c.images,"
      62              :    "'is-active',c.is_active" ")) FROM template_clubs tc JOIN clubs c ON c.uuid=tc.club_id"
      63              :    " WHERE tc.template_id=et.uuid AND c.is_active)," "'[]'::json)"))
      64              : 
      65              : 
      66            4 : (defn- -parse-clubs-json
      67              :   "Parses the clubs-json aggregate column into a vector of ClubRecord maps."
      68              :   [v]
      69           20 :   (when (sequential? v)
      70            4 :     (->>
      71            4 :       v
      72           12 :       (filter identity)
      73            4 :       (mapv
      74            4 :        (fn [club-map]
      75            4 :         (club-entity/make-club
      76           12 :          (assoc club-map
      77           14 :           :location      (or (:location club-map) {})
      78           14 :           :working-hours (or (:working-hours club-map) [])
      79           14 :           :images        (or (:images club-map) []))))))))
      80              : 
      81              : 
      82            4 : (defn- row->template
      83              :   "Converts a database row to a domain EventTemplate map."
      84              :   [row]
      85           12 :   (when row
      86           16 :     (let [from-qualified? (:templates/uuid row)
      87           12 :           unq             (utils.db/unqualify-keys row)
      88           20 :           clubs           (-parse-clubs-json (:clubs-json unq))
      89           44 :           club            (when (or (:clubs/uuid row) (:c/uuid row))
      90           10 :                             (club-entity/make-club (-extract-club row)))
      91            8 :           template        (->
      92            4 :                             (if
      93            4 :                               from-qualified?
      94           16 :                               (entity/make-template row true)
      95            0 :                               (entity/make-template unq))
      96           16 :                             (assoc :clubs clubs)
      97           28 :                             (assoc :club-ids (mapv :uuid clubs))
      98           34 :                             (assoc :club (or (first clubs) club)))]
      99            4 :       template)))
     100              : 
     101              : 
     102            4 : (defn- -decode-json-if-needed
     103              :   [value]
     104            8 :   (if (string? value)
     105            0 :     (try
     106            0 :       (json/parse-string value)
     107            0 :       (catch Exception _ value))
     108            2 :     value))
     109              : 
     110              : 
     111            4 : (defn- -extract-club
     112              :   [row]
     113            6 :   (let [club-data (reduce-kv
     114            2 :                    (fn [acc k v]
     115           30 :                     (if (and (keyword? k) (contains? #{"clubs" "c"} (namespace k)))
     116           16 :                       (let [key-name (str/replace (name k) #"_" "-")
     117            6 :                             key      (keyword key-name)
     118           14 :                             shape?   (contains? #{"location" "working-hours" "images"} key-name)
     119           12 :                             value    (if shape? (-decode-json-if-needed v) v)]
     120           30 :                         (if (and shape? (nil? value)) acc (assoc acc key value)))
     121            2 :                       acc))
     122            2 :                    {}
     123            2 :                    row)]
     124           10 :     (when (seq club-data)
     125            4 :       (merge
     126           10 :        {:location      {}
     127            2 :         :working-hours []
     128            2 :         :images        []}
     129            2 :        club-data))))
     130              : 
     131              : 
     132            4 : (defn- template->row
     133              :   "Converts a domain EventTemplate map to a database row for upsert."
     134              :   [template]
     135            4 :   (let [{:keys [uuid
     136              :                 public-id
     137              :                 sport-code
     138              :                 activity-type-code
     139              :                 name
     140              :                 description
     141              :                 state
     142              :                 visibility
     143              :                 fee
     144              :                 fee-type
     145              :                 currency
     146              :                 timezone
     147              :                 language
     148              :                 duration
     149              :                 score-entry-mode
     150              :                 score-entry-default
     151              :                 automatic-event-creation
     152              :                 automatic-event-creation-delay-minutes
     153              :                 source
     154              :                 created-by
     155              :                 rrule
     156              :                 rrule-json
     157              :                 ruleset-id
     158              :                 settings]}
     159            4 :         template]
     160          120 :     {:uuid                [:cast uuid :uuid]
     161           24 :      :public_id           (or public-id (nanoid/generate))
     162            4 :      :name                name
     163            4 :      :sport_code          sport-code
     164            4 :      :activity_type_code  activity-type-code
     165            4 :      :description         description
     166            4 :      :state               state
     167           24 :      :visibility          (or visibility "public")
     168           32 :      :club_id             [:cast (first (:club-ids template)) :uuid]
     169            4 :      :fee                 fee
     170            4 :      :fee_type            fee-type
     171            4 :      :currency            currency
     172            4 :      :timezone            timezone
     173           23 :      :language            (or language "en")
     174            4 :      :duration            duration
     175           23 :      :score_entry_mode    (or score-entry-mode "either")
     176           23 :      :score_entry_default (or score-entry-default "game")
     177            8 :      :automatic_event_creation (boolean automatic-event-creation)
     178           23 :      :automatic_event_creation_delay_minutes (or automatic-event-creation-delay-minutes 5)
     179           24 :      :source              (or source "matchscore")
     180           16 :      :created_by          [:cast created-by :uuid]
     181            4 :      :rrule               rrule
     182           43 :      :rrule_json          [:cast (json/generate-string (or rrule-json {})) :jsonb]
     183           16 :      :ruleset_id          [:cast ruleset-id :uuid]
     184           44 :      :settings            [:cast (json/generate-string (or settings {})) :jsonb]}))
     185              : 
     186              : 
     187            4 : (def ^:private participant-role-clauses
     188           24 :   {:player [:raw "etp.roles @> '[\"player\"]'::jsonb"]
     189           12 :    :admin  [:raw "etp.roles @> '[\"admin\"]'::jsonb"]})
     190              : 
     191              : 
     192            4 : (defn- participating-user-clause
     193              :   "Matches templates where user-id participates; role (:player or :admin) narrows it to
     194              :   participants holding that role, nil matches any role."
     195              :   [user-id role]
     196           18 :   [:exists {:select [1]
     197            8 :             :from   [[:template_participants :etp]]
     198           16 :             :join   [[:participants :p] [:= :etp.participant-id :p.uuid]]
     199           10 :             :where  (cond->
     200           26 :                       [:and [:= :etp.template-id :et.uuid] [:= :p.user-id [:cast user-id :uuid]]]
     201           10 :                       role (conj (participant-role-clauses role)))}])
     202              : 
     203              : 
     204            4 : (defn- managing-user-clause
     205              :   "Matches templates user-id created or holds the admin participant role in."
     206              :   [user-id]
     207           26 :   [:or [:= :et.created-by [:cast user-id :uuid]] (participating-user-clause user-id :admin)])
     208              : 
     209              : 
     210            4 : (defn- profile-visible-to-user-clause
     211              :   [user-id]
     212            4 :   [:or
     213            8 :    [:= :et.visibility "public"]
     214           14 :    [:= :et.created-by [:cast user-id :uuid]]
     215            8 :    (participating-user-clause user-id nil)
     216           16 :    [:exists {:select [1]
     217            8 :              :from   [[:users :profile-viewer]]
     218            4 :              :where  [:and
     219           14 :                       [:= :profile-viewer.uuid [:cast user-id :uuid]]
     220            6 :                       [:raw "profile_viewer.roles @> '[\"root\"]'::jsonb"]]}]
     221           18 :    [:exists {:select [1]
     222            8 :              :from   [[:telegram-chat-members :tcm]]
     223           16 :              :join   [[:telegram-template-links :ttl] [:= :ttl.chat-id :tcm.chat-id]]
     224            4 :              :where  [:and
     225            8 :                       [:= :ttl.template-id :et.uuid]
     226           14 :                       [:= :tcm.user-id [:cast user-id :uuid]]
     227            6 :                       (telegram-chat-member-repo/fresh-membership-clause :tcm.checked-at)]}]])
     228              : 
     229              : 
     230            4 : (defn- filters->specs
     231              :   [{:keys [name state visibility sportCode activityTypeCode createdBy]}]
     232            6 :   (qh/typed-filters->specs
     233           24 :    {:name       name
     234            3 :     :state      state
     235            3 :     :visibility visibility
     236            3 :     :sport-code sportCode
     237            3 :     :activity-type-code activityTypeCode
     238            9 :     :created-by (utils.db/cast-uuid-filter createdBy)}))
     239              : 
     240              : 
     241           20 : (def ^:private valid-sort-fields #{:name :created-datetime :updated-datetime})
     242              : 
     243              : 
     244            8 : (def ^:private default-sort :created-datetime)
     245              : 
     246              : 
     247            4 : (def ^:private base-query
     248           40 :   {:select [:* [[:raw clubs-agg-sql] :clubs-json]]
     249           16 :    :from   [[:templates :et]]})
     250              : 
     251              : 
     252           52 : (def ^:private available-joins {:club [:left-join [[:clubs :c] [:= :et.club-id :c.uuid]]]})
     253              : 
     254              : 
     255            4 : (defrecord
     256              :   PostgresTemplateRepository
     257              :   [ds]
     258              :   TemplatePostgresRepository
     259              : 
     260              :   (find-by-id
     261              :    [_ id {:keys [joins]}]
     262           20 :    (let [joins-to-apply (select-keys available-joins joins)
     263           16 :          query          (->
     264            4 :                           base-query
     265           40 :                           (assoc :where [:= :et.uuid [:cast id :uuid]])
     266           20 :                           (cond-> (seq joins-to-apply) (into (vals joins-to-apply))))
     267            4 :          result         (->>
     268           12 :                           (sql/format query)
     269           12 :                           (jdbc/execute! ds)
     270            4 :                           first)]
     271           12 :      (row->template result)))
     272              : 
     273              :   (find-by-ids
     274              :    [_ ids]
     275            4 :    (if (empty? ids)
     276            0 :      []
     277           17 :      (let [query (assoc base-query :where [:in :et.uuid (mapv #(vector :cast % :uuid) ids)])]
     278            1 :        (->>
     279            3 :          (sql/format query)
     280            3 :          (jdbc/execute! ds)
     281            2 :          (mapv row->template)))))
     282              : 
     283           20 :   (find-by-public-id [this public-id] (find-by-public-id this public-id nil))
     284              :   (find-by-public-id
     285              :    [_ public-id {:keys [joins]}]
     286           39 :    (let [joins-to-apply (select-keys available-joins (or joins []))
     287           14 :          query          (->
     288           32 :                           (assoc base-query :where [:= :et.public-id public-id])
     289           16 :                           (cond-> (seq joins-to-apply) (into (vals joins-to-apply))))
     290            4 :          result         (->>
     291           12 :                           (sql/format query)
     292           12 :                           (jdbc/execute! ds)
     293            4 :                           first)]
     294           12 :      (row->template result)))
     295              : 
     296              :   (find-by-creator-id
     297              :    [_ creator-id {:keys [joins]}]
     298            5 :    (let [joins-to-apply (select-keys available-joins joins)
     299            5 :          query (->
     300            1 :                  base-query
     301           10 :                  (assoc :where [:= :et.created-by [:cast creator-id :uuid]])
     302            7 :                  (cond-> (seq joins-to-apply) (into (vals joins-to-apply))))]
     303            1 :      (->>
     304            3 :        (sql/format query)
     305            3 :        (jdbc/execute! ds)
     306            2 :        (mapv row->template))))
     307              : 
     308              :   (search
     309              :    [_ filters pagination]
     310           12 :    (let [participating-user-id (:participating-user-id filters)
     311            7 :          participating    (when participating-user-id
     312            2 :                             (participating-user-clause
     313            1 :                              participating-user-id
     314            6 :                              (when (:participating-player-only? filters) :player)))
     315            9 :          managing-user-id (:managing-user-id filters)
     316           14 :          managing         (when managing-user-id (managing-user-clause managing-user-id))
     317            9 :          hosted-user-id   (:hosted-user-id filters)
     318            7 :          hosted           (when hosted-user-id
     319            2 :                             [:or
     320            7 :                              [:= :et.host-user-id [:cast hosted-user-id :uuid]]
     321            2 :                              [:and
     322            4 :                               [:= :et.host-user-id nil]
     323            3 :                               (managing-user-clause hosted-user-id)]])
     324            9 :          profile-viewer-id (:profile-visible-to-user-id filters)
     325            8 :          profile-visible  (when profile-viewer-id
     326            6 :                             (profile-visible-to-user-clause profile-viewer-id))
     327            6 :          club-conds       (reduce
     328            3 :                            (fn [acc f]
     329           13 :                             (cond-> acc
     330           30 :                               (:eq f)       (conj [:= :tc.club-id [:cast (:eq f) :uuid]])
     331           11 :                               (seq (:in f)) (conj
     332            3 :                                              [:in
     333              :                                               :tc.club-id
     334           11 :                                               (mapv #(vector :cast % :uuid) (:in f))])))
     335            3 :                            []
     336           30 :                            (remove nil? [(:clubId filters) (:clubIds filters)]))
     337           14 :          club-exists      (when (seq club-conds)
     338            4 :                             [:exists
     339           12 :                              {:select [1]
     340            8 :                               :from   [[:template-clubs :tc]]
     341           18 :                               :where  (into [:and [:= :tc.template-id :et.uuid]] club-conds)}])
     342           40 :          base             (cond-> base-query
     343            7 :                             participating   (qh/add-where-clause participating)
     344           11 :                             managing        (qh/add-where-clause managing)
     345            7 :                             hosted          (qh/add-where-clause hosted)
     346           11 :                             profile-visible (qh/add-where-clause profile-visible)
     347            7 :                             club-exists     (qh/add-where-clause club-exists))
     348            9 :          specs            (filters->specs filters)
     349            6 :          query            (qh/build-search-query
     350            3 :                            base
     351            3 :                            specs
     352            3 :                            valid-sort-fields
     353            3 :                            default-sort
     354            3 :                            pagination
     355           21 :                            {:sort-field-casts {:created-datetime :timestamptz
     356              :                                                :updated-datetime :timestamptz}})
     357            3 :          rows             (->>
     358            9 :                             (sql/format query)
     359            9 :                             (jdbc/execute! ds)
     360            6 :                             (mapv row->template))
     361           16 :          opts             (when-not (:cursor pagination)
     362           15 :                             (let [cnt-query (qh/build-count-query base specs)
     363            9 :                                   total     (->>
     364            9 :                                               (sql/format cnt-query)
     365            9 :                                               (jdbc/execute-one! ds)
     366            3 :                                               utils.db/unqualify-keys
     367              :                                               :total)]
     368            9 :                               {:total-count total}))]
     369           21 :      (qh/paginate-results rows valid-sort-fields default-sort pagination opts)))
     370              : 
     371              :   (save!
     372              :    [_ template]
     373            4 :    (try
     374           24 :      (let [club-ids (seq (:club-ids template))
     375           12 :            template-uuid (:uuid template)
     376              :            result
     377           16 :            (jdbc/with-transaction
     378            4 :             [tx ds]
     379           32 :             (let [query {:insert-into   :templates
     380           16 :                          :values        [(template->row template)]
     381            8 :                          :on-conflict   [:uuid]
     382          108 :                          :do-update-set {:fields [:name
     383              :                                                   :sport_code
     384              :                                                   :activity_type_code
     385              :                                                   :description
     386              :                                                   :state
     387              :                                                   :visibility
     388              :                                                   :club_id
     389              :                                                   :fee
     390              :                                                   :fee_type
     391              :                                                   :currency
     392              :                                                   :timezone
     393              :                                                   :language
     394              :                                                   :duration
     395              :                                                   :score_entry_mode
     396              :                                                   :score_entry_default
     397              :                                                   :automatic_event_creation
     398              :                                                   :automatic_event_creation_delay_minutes
     399              :                                                   :updated_datetime
     400              :                                                   :source
     401              :                                                   :created_by
     402              :                                                   :rrule
     403              :                                                   :rrule_json
     404              :                                                   :ruleset_id
     405              :                                                   :settings]}
     406            8 :                          :returning     [:*]}
     407            4 :                   row   (->>
     408           20 :                           (sql/format (audit/stamp query))
     409           12 :                           (jdbc/execute! tx)
     410            4 :                           first)]
     411           12 :               (when template-uuid
     412            8 :                 (jdbc/execute!
     413            4 :                  tx
     414            8 :                  (sql/format
     415           16 :                   {:delete-from :template-clubs
     416           28 :                    :where       [:= :template-id [:cast template-uuid :uuid]]}))
     417           10 :                 (when club-ids
     418            4 :                   (jdbc/execute!
     419            2 :                    tx
     420            4 :                    (sql/format
     421            8 :                     {:insert-into :template-clubs
     422            6 :                      :values      (mapv
     423            8 :                                    #(hash-map
     424            8 :                                      :template-id [:cast template-uuid :uuid]
     425            8 :                                      :club-id     [:cast % :uuid])
     426            2 :                                    club-ids)}))))
     427            4 :               row))]
     428            8 :        (if result
     429           32 :          (let [saved-uuid (str (:uuid (utils.db/unqualify-keys result)))
     430            4 :                full-row   (->>
     431            8 :                             (sql/format
     432           44 :                              (assoc base-query :where [:= :et.uuid [:cast saved-uuid :uuid]]))
     433           12 :                             (jdbc/execute! ds)
     434            4 :                             first)]
     435           20 :            (either/right (row->template full-row)))
     436            0 :          (either/left
     437            0 :           (utils.errors/build-error
     438              :            :postgres
     439            0 :            {:message "No row returned"
     440            0 :             :context {:table :templates
     441              :                       :op    :upsert
     442            0 :                       :uuid  template-uuid}}))))
     443              :      (catch Exception e
     444            4 :        (either/left
     445            6 :         (utils.errors/build-error
     446              :          :postgres
     447            8 :          {:message (.getMessage e)
     448           12 :           :context {:table :templates
     449              :                     :op    :upsert
     450            6 :                     :uuid  (:uuid template)}})))))
     451              : 
     452              :   (delete!
     453              :    [_ id]
     454            2 :    (try
     455            4 :      (jdbc/execute!
     456            2 :       ds
     457            4 :       (sql/format
     458            8 :        {:delete-from :templates
     459           14 :         :where       [:= :uuid [:cast id :uuid]]}))
     460            6 :      (either/right nil)
     461              :      (catch Exception e
     462            0 :        (either/left
     463            0 :         (utils.errors/build-error
     464              :          :postgres
     465            0 :          {:message (.getMessage e)
     466            0 :           :context {:table :templates
     467              :                     :op    :delete
     468            0 :                     :uuid  id}}))))))
     469              : 
     470              : 
     471            4 : (defn make-repository
     472              :  "Creates a PostgresTemplateRepository from a ds."
     473              :  [ds]
     474           12 :  (->PostgresTemplateRepository ds))
        

Generated by: LCOV version 2.0-1