LCOV - code coverage report
Current view: top level - matchscore/api - payment_methods.clj Coverage Total Hit
Test: lcov.info Lines: 93.7 % 205 192
Test Date: 2026-11-23 18:11:10 Functions: - 0 0

            Line data    Source code
       1            4 : (ns matchscore.api.payment-methods
       2              :   (:require
       3              :    [clojure.string :as str]
       4              :    [malli.core :as m]
       5              :    [malli.error :as me]
       6              :    [matchscore.banks :as banks]
       7              :    [matchscore.db.postgres.payment-methods :as payment-methods]
       8              :    [matchscore.domain.event.repository.postgres :as event-postgres-repo]
       9              :    [matchscore.domain.template.repository.postgres :as template-postgres-repo]
      10              :    [matchscore.jobs.scheduler :as scheduler]
      11              :    [matchscore.jobs.telegram-payment-reminder :as payment-reminder-jobs]
      12              :    [ring.util.http-status :as status]
      13              :    [schemas.api.core :as api-schemas]
      14              :    [schemas.api.payment-methods :as schemas]
      15              :    [schemas.registry :as registry]))
      16              : 
      17              : 
      18            4 : (def ^:private account-authz
      19           28 :   {:obj     :account
      20              :    :act     :update
      21              :    :create? true})
      22              : 
      23              : 
      24           10 : (defn- user-id [request] (get-in request [:auth-headers :user/uuid]))
      25              : 
      26              : 
      27            8 : (defn- public-method [method] (dissoc method :user-id))
      28              : 
      29              : 
      30            4 : (defn- trim-to-nil
      31              :   [value]
      32           17 :   (some->
      33            1 :     value
      34            1 :     str/trim
      35            1 :     not-empty))
      36              : 
      37              : 
      38            4 : (defn- normalized-attrs
      39              :   [attrs]
      40            4 :   (let [kind  (:kind attrs)
      41            2 :         attrs (->
      42            1 :                 attrs
      43            4 :                 (update :label str/trim)
      44            4 :                 (update :value trim-to-nil)
      45            4 :                 (update :note trim-to-nil)
      46            4 :                 (update :bank-id trim-to-nil)
      47            4 :                 (update :bank-name trim-to-nil)
      48            4 :                 (update :recipient-name trim-to-nil)
      49            4 :                 (update :tax-id trim-to-nil)
      50            2 :                 (update :purpose trim-to-nil))
      51            3 :         attrs (case kind
      52            3 :                 "card"  (->
      53            1 :                           attrs
      54            4 :                           (update
      55              :                            :value
      56           12 :                            #(some->
      57              :                               %
      58            1 :                               (str/replace #"[\s-]" "")))
      59            1 :                           (assoc :tax-id nil))
      60            5 :                 "iban"  (->
      61            1 :                           attrs
      62            4 :                           (update
      63              :                            :value
      64           16 :                            #(some->
      65              :                               %
      66            3 :                               (str/replace #"\s" "")
      67            1 :                               str/upper-case))
      68            4 :                           (cond-> (:value attrs) (assoc :bank-id
      69            4 :                                                   (or
      70            2 :                                                    (banks/bank-id-for-iban
      71            1 :                                                     (->
      72            3 :                                                       (:value attrs)
      73            4 :                                                       (str/replace #"\s" "")
      74            1 :                                                       str/upper-case))
      75            0 :                                                    (:bank-id attrs)))))
      76            7 :                 "link"  (assoc attrs
      77              :                          :recipient-name nil
      78              :                          :tax-id         nil)
      79           13 :                 "cash"  (assoc attrs
      80              :                          :value          nil
      81              :                          :bank-id        nil
      82              :                          :recipient-name nil
      83              :                          :tax-id         nil
      84              :                          :purpose        nil)
      85            7 :                 "other" (assoc attrs
      86              :                          :recipient-name nil
      87              :                          :tax-id         nil)
      88            1 :                 attrs)]
      89              :     ;; Only an "other" bank keeps a typed name; a registry bank (including one
      90              :     ;; detected from the IBAN) is named by the registry.
      91           15 :     (cond-> attrs (not= banks/other-bank-id (:bank-id attrs)) (assoc :bank-name nil))))
      92              : 
      93              : 
      94            4 : (defn- http-url?
      95              :   [value]
      96            1 :   (try
      97            3 :     (let [uri (java.net.URI. value)]
      98            4 :       (and
      99            2 :        (contains?
     100            3 :         #{"http" "https"}
     101            8 :         (some->
     102            1 :           (.getScheme uri)
     103            1 :           str/lower-case))
     104              :        (.getHost uri)))
     105              :     (catch Exception _ false)))
     106              : 
     107              : 
     108            4 : (defn- validation-message
     109              :   [{:keys [kind value bank-id bank-name recipient-name tax-id]}]
     110           23 :   (cond (and
     111            3 :          (= "card" kind)
     112           17 :          (not (and (re-matches #"\d{13,19}" (or value "")) (schemas/luhn-valid? value))))
     113              :         "Card number is not valid"
     114              : 
     115           16 :         (and (= "iban" kind) (not (schemas/iban-valid? (or value ""))))
     116              :         "IBAN must be a valid Ukrainian IBAN (UA + 27 digits)"
     117              : 
     118           10 :         (and (= "iban" kind) (str/blank? recipient-name)) "Recipient name is required for IBANs"
     119              : 
     120           17 :         (and (= "iban" kind) (not (re-matches #"(?:\d{8}|\d{10})" (or tax-id ""))))
     121              :         "Tax ID must be 8 (ЄДРПОУ) or 10 (РНОКПП) digits"
     122              : 
     123           14 :         (and (contains? #{"card" "iban" "link"} kind) (str/blank? bank-id))
     124              :         "Bank is required for cards, IBANs and payment links"
     125              : 
     126           10 :         (and (= banks/other-bank-id bank-id) (str/blank? bank-name))
     127              :         "Bank name is required when the bank is not in the list"
     128              : 
     129           19 :         (and bank-id (not= banks/other-bank-id bank-id) (nil? (banks/find-bank bank-id)))
     130              :         "Unknown bank"
     131              : 
     132           12 :         (and (= "link" kind) (not (http-url? value))) "Payment links must be valid HTTP(S) URLs"
     133              : 
     134           10 :         (and (= "other" kind) (str/blank? value)) "Value is required for other payment methods"))
     135              : 
     136              : 
     137            4 : (defn- validation-errors
     138              :   [attrs]
     139           10 :   (when-not (m/validate schemas/PaymentMethodRequestSchema attrs {:registry registry/registry})
     140            2 :     (me/humanize
     141            7 :      (m/explain schemas/PaymentMethodRequestSchema attrs {:registry registry/registry}))))
     142              : 
     143              : 
     144            4 : (defn- validation-error-response
     145              :   [errors & [message]]
     146            4 :   {:status status/bad-request
     147            9 :    :body   {:message (or message "Validation failed")
     148            1 :             :errors  errors}})
     149              : 
     150              : 
     151            4 : (defn payment-methods-list-handler
     152              :  {:malli/schema [:=> [:cat api-schemas/RingRequest] schemas/PaymentMethodListResponseSchema]
     153              :   :authz        account-authz
     154              :   :summary      "List payment methods"
     155              :   :description  "Lists the authenticated user's live payment methods in display order."}
     156              :  [{:keys [pg]
     157              :    :as   request}]
     158            4 :  {:status status/ok
     159            4 :   :body   {:message "Payment methods retrieved successfully."
     160            9 :            :data    (mapv public-method (payment-methods/list-by-user pg (user-id request)))}})
     161              : 
     162              : 
     163            4 : (defn payment-methods-create-handler
     164              :  {:malli/schema [:=>
     165              :                  [:cat api-schemas/RingRequest schemas/PaymentMethodRequestSchema]
     166              :                  schemas/PaymentMethodCreateResponseSchema]
     167              :   :authz        account-authz
     168              :   :summary      "Create payment method"
     169              :   :description  "Creates a payment method owned by the authenticated user."}
     170              :  [{:keys [pg]
     171              :    :as   request}
     172              :   attrs]
     173            4 :  (let [attrs (normalized-attrs attrs)]
     174            8 :    (if-let [message (validation-message attrs)]
     175            6 :      (validation-error-response {:payment-method message} message)
     176            8 :      (if-let [errors (validation-errors attrs)]
     177            3 :        (validation-error-response errors)
     178            4 :        {:status status/created
     179            4 :         :body   {:message "Payment method created successfully."
     180            9 :                  :data    (public-method (payment-methods/create! pg (user-id request) attrs))}}))))
     181              : 
     182              : 
     183            4 : (defn payment-methods-update-handler
     184              :  {:malli/schema     [:=>
     185              :                      [:cat api-schemas/RingRequest schemas/PaymentMethodRequestSchema]
     186              :                      schemas/PaymentMethodUpdateResponseSchema]
     187              :   :malli/parameters {:path schemas/PaymentMethodPathParamsSchema}
     188              :   :authz            account-authz
     189              :   :summary          "Update payment method"
     190              :   :description      "Updates a live payment method owned by the authenticated user."}
     191              :  [{:keys [pg route-params]
     192              :    :as   request}
     193              :   attrs]
     194            4 :  (let [attrs (normalized-attrs attrs)]
     195            6 :    (if-let [message (validation-message attrs)]
     196            0 :      (validation-error-response {:payment-method message} message)
     197            6 :      (if-let [errors (validation-errors attrs)]
     198            0 :        (validation-error-response errors)
     199            7 :        (if-let [method (payment-methods/update!
     200            1 :                         pg
     201            3 :                         (user-id request)
     202            3 :                         (:payment-method-uuid route-params)
     203            1 :                         attrs)]
     204            4 :          {:status status/ok
     205            4 :           :body   {:message "Payment method updated successfully."
     206            3 :                    :data    (public-method method)}}
     207            4 :          {:status status/not-found
     208            3 :           :body   {:message "Payment method not found."}})))))
     209              : 
     210              : 
     211            4 : (defn payment-methods-delete-handler
     212              :  {:malli/schema     [:=> [:cat api-schemas/RingRequest] schemas/PaymentMethodDeleteResponseSchema]
     213              :   :malli/parameters {:path schemas/PaymentMethodPathParamsSchema}
     214              :   :authz            account-authz
     215              :   :summary          "Delete payment method"
     216              :   :description      "Soft-deletes a live payment method owned by the authenticated user."}
     217              :  [{:keys [pg route-params]
     218              :    :as   request}]
     219            4 :  (let [uuid (:payment-method-uuid route-params)]
     220            8 :    (if (payment-methods/soft-delete! pg (user-id request) uuid)
     221            4 :      {:status status/ok
     222            4 :       :body   {:message "Payment method deleted successfully."
     223            3 :                :data    {:uuid uuid}}}
     224            4 :      {:status status/not-found
     225            3 :       :body   {:message "Payment method not found."}})))
     226              : 
     227              : 
     228            4 : (defn payment-method-order-handler
     229              :  {:malli/schema [:=>
     230              :                  [:cat api-schemas/RingRequest schemas/PaymentMethodOrderRequestSchema]
     231              :                  schemas/PaymentMethodOrderResponseSchema]
     232              :   :authz        account-authz
     233              :   :summary      "Reorder payment methods"
     234              :   :description  "Replaces the display order using exactly the authenticated user's live IDs."}
     235              :  [{:keys [pg]
     236              :    :as   request}
     237              :   {:keys [uuids]}]
     238           12 :  (if-let [methods (payment-methods/reorder! pg (user-id request) uuids)]
     239            4 :    {:status status/ok
     240            4 :     :body   {:message "Payment methods reordered successfully."
     241            4 :              :data    (mapv public-method methods)}}
     242            4 :    {:status status/bad-request
     243            3 :     :body   {:message "Payment method IDs must exactly match the user's live payment methods."}}))
     244              : 
     245              : 
     246            4 : (defn- setting
     247              :   [m k]
     248            3 :   (some
     249            3 :    #(get m %)
     250           21 :    [k (keyword (str/replace (name k) "-" "_")) (name k) (str/replace (name k) "-" "_")]))
     251              : 
     252              : 
     253            4 : (defn- reminder-ids
     254              :   [entity]
     255            2 :   (map
     256            1 :    str
     257            2 :    (->
     258            3 :      (:settings entity)
     259            3 :      (setting :payment-reminder)
     260            1 :      (setting :payment-method-ids))))
     261              : 
     262              : 
     263            4 : (defn- selected-summaries
     264              :   "Masked summaries of the live methods selected on the given entities, so
     265              :    co-admins can see (and drop) each other's choices without reading the
     266              :    card or account numbers."
     267              :   [pg viewer-id entities]
     268           10 :   (let [ids     (distinct (mapcat reminder-ids (remove nil? entities)))
     269            7 :         methods (payment-methods/grouped-by-owner ids (payment-methods/find-live-by-ids pg ids))
     270            7 :         names   (payment-methods/owner-names pg (map :user-id methods))]
     271            2 :     (mapv
     272            1 :      (fn [{:keys [uuid kind label bank-id bank-name value user-id]}]
     273           11 :       {:uuid       uuid
     274            1 :        :kind       kind
     275            1 :        :label      label
     276            1 :        :bank-id    bank-id
     277            1 :        :bank-name  bank-name
     278            2 :        :last4      (when
     279           20 :                      (and (contains? #{"card" "iban"} kind) (string? value) (<= 4 (count value)))
     280            7 :                      (subs value (- (count value) 4)))
     281            1 :        :owner-id   user-id
     282            3 :        :owner-name (get names user-id)
     283            5 :        :own        (= (str viewer-id) user-id)})
     284            1 :      methods)))
     285              : 
     286              : 
     287            4 : (defn event-payment-methods-handler
     288              :  {:malli/schema [:=> [:cat api-schemas/RingRequest] schemas/SelectedPaymentMethodListResponseSchema]
     289              :   :malli/parameters {:path api-schemas/EventPathParamsSchema}
     290              :   :authz {:obj :event
     291              :           :act :update
     292              :           :id  :route-params/event-uuid}
     293              :   :summary "Payment methods selected on an event"
     294              :   :description
     295              :   "Masked summaries of the payment methods selected in the event's payment reminder and in its template's reminder, with each method's owner. Event managers only."}
     296              :  [{:keys [pg repos route-params]
     297              :    :as   request}]
     298            3 :  (let [event    (event-postgres-repo/find-by-id
     299            3 :                  (:event-postgres-repo repos)
     300            3 :                  (:event-uuid route-params)
     301            1 :                  {})
     302            9 :        template (when-let [template-id (:template-id event)]
     303            2 :                   (template-postgres-repo/find-by-id
     304            3 :                    (:template-postgres-repo repos)
     305            1 :                    template-id
     306            1 :                    {}))]
     307            2 :    (if event
     308            4 :      {:status status/ok
     309            4 :       :body   {:message "Selected payment methods retrieved successfully."
     310            9 :                :data    (selected-summaries pg (user-id request) [event template])}}
     311            0 :      {:status status/not-found
     312            0 :       :body   {:message "Event not found."}})))
     313              : 
     314              : 
     315            4 : (defn template-payment-methods-handler
     316              :  {:malli/schema [:=> [:cat api-schemas/RingRequest] schemas/SelectedPaymentMethodListResponseSchema]
     317              :   :malli/parameters {:path api-schemas/TemplatePathParamsSchema}
     318              :   :authz {:obj :template
     319              :           :act :update
     320              :           :id  :route-params/template-uuid}
     321              :   :summary "Payment methods selected on a template"
     322              :   :description
     323              :   "Masked summaries of the payment methods selected in the template's payment reminder, with each method's owner. Template managers only."}
     324              :  [{:keys [pg repos route-params]
     325              :    :as   request}]
     326            7 :  (if-let [template (template-postgres-repo/find-by-id
     327            3 :                     (:template-postgres-repo repos)
     328            3 :                     (:template-uuid route-params)
     329            1 :                     {})]
     330            4 :    {:status status/ok
     331            4 :     :body   {:message "Selected payment methods retrieved successfully."
     332            8 :              :data    (selected-summaries pg (user-id request) [template])}}
     333            0 :    {:status status/not-found
     334            0 :     :body   {:message "Template not found."}}))
     335              : 
     336              : 
     337            4 : (defn- sendable-method-ids
     338              :   "IDs a manager may post: their own live methods, plus live methods another
     339              :    organizer selected for this event or its template."
     340              :   [pg viewer-id event template]
     341            9 :   (let [selected (set (mapcat reminder-ids [event template]))]
     342            2 :     (into
     343            9 :      (set (map :uuid (payment-methods/list-by-user pg viewer-id)))
     344            8 :      (comp (map :uuid) (filter selected))
     345            6 :      (payment-methods/find-live-by-ids pg (vec selected)))))
     346              : 
     347              : 
     348            4 : (defn event-send-payment-details-handler
     349              :  {:malli/schema [:=>
     350              :                  [:cat api-schemas/RingRequest schemas/SendPaymentDetailsRequestSchema]
     351              :                  schemas/SendPaymentDetailsResponseSchema]
     352              :   :malli/parameters {:path api-schemas/EventPathParamsSchema}
     353              :   :authz {:obj :event
     354              :           :act :update
     355              :           :id  :route-params/event-uuid}
     356              :   :summary "Post payment details to Telegram now"
     357              :   :description
     358              :   "Schedules an immediate Telegram post with the chosen payment methods and the event's fee to every chat linked to the event. Methods must be the caller's own or already selected on the event or its template."}
     359              :  [{:keys [pg repos goose route-params]
     360              :    :as   request}
     361              :   {:keys [payment-method-ids]}]
     362            4 :  (let [event-id (:event-uuid route-params)
     363            7 :        event    (event-postgres-repo/find-by-id (:event-postgres-repo repos) event-id {})
     364            6 :        template (when-let [template-id (:template-id event)]
     365            0 :                   (template-postgres-repo/find-by-id
     366            0 :                    (:template-postgres-repo repos)
     367            0 :                    template-id
     368            0 :                    {}))]
     369            6 :    (cond (not event)
     370            0 :          {:status status/not-found
     371            0 :           :body   {:message "Event not found."}}
     372              : 
     373            2 :          (not-every?
     374            8 :           (sendable-method-ids pg (user-id request) event template)
     375            4 :           (map str payment-method-ids))
     376            4 :          {:status status/bad-request
     377            3 :           :body   {:message
     378              :                    "Choose your own live payment methods or ones selected for this event."}}
     379              : 
     380              :          :else
     381            1 :          (do
     382            3 :            (scheduler/schedule-job
     383            1 :             goose
     384              :             `payment-reminder-jobs/send-payment-details-job
     385            8 :             {:args [event-id (mapv str payment-method-ids)]})
     386            4 :            {:status status/accepted
     387            4 :             :body   {:message "Payment details post scheduled."
     388            3 :                      :data    {:event-uuid event-id}}}))))
        

Generated by: LCOV version 2.0-1