Line data Source code
1 4 : (ns matchscore.domain.user.command
2 : (:require
3 : [cats.core :as c]
4 : [cats.monad.either :as either]
5 : [clojure.string :as str]
6 : [malli.core :as m]
7 : [matchscore.domain.user.entity :as entity]
8 : [matchscore.domain.user.repository.postgres :as user-postgres-repo]
9 : [matchscore.domain.user.repository.redis :as redis-repo]
10 : [matchscore.jobs.scheduler :as scheduler]
11 : [matchscore.jobs.users :as users-jobs]
12 : [matchscore.utils.errors :as utils.errors]
13 : [matchscore.utils.nanoid :as nanoid]
14 : [matchscore.utils.transliteration :as transliteration]
15 : [matchscore.utils.uuid :as uuid-utils]
16 : [schemas.domain.user :as user-schemas])
17 : (:import
18 : (java.time OffsetDateTime)))
19 :
20 :
21 4 : (defn- check-id-not-taken
22 : [repo account-data]
23 21 : (if (user-postgres-repo/find-by-id repo (:uuid account-data))
24 2 : (either/left
25 3 : (utils.errors/build-error
26 : :check
27 6 : {:code :error.account/conflict-id
28 : :message "User with such id already exist"
29 3 : :context {:input-data account-data}}))
30 9 : (either/right account-data)))
31 :
32 :
33 4 : (defn normalize-username
34 : [u]
35 72 : (some->
36 3 : u
37 3 : str/trim
38 3 : str/lower-case
39 3 : not-empty))
40 :
41 :
42 4 : (defn- normalize-localized-names
43 : [localized]
44 6 : (reduce-kv
45 3 : (fn [result language value]
46 16 : (let [language (if (keyword? language) (name language) (str language))
47 16 : value (some->
48 2 : value
49 2 : str/trim)]
50 19 : (if (str/blank? value) result (assoc result language value))))
51 3 : {}
52 17 : (or localized {})))
53 :
54 :
55 4 : (defn- localized-name-present?
56 : [localized language]
57 22 : (or (contains? localized language) (contains? localized (keyword language))))
58 :
59 :
60 4 : (defn- normalize-created-name
61 : [account-data]
62 18 : (let [sanitized (transliteration/sanitize (:name account-data))
63 15 : localized (normalize-localized-names (:name-localized account-data))
64 9 : already-latin? (transliteration/latin-name? sanitized)
65 11 : canonical (cond already-latin? sanitized
66 16 : (not (str/blank? sanitized)) (transliteration/transliterate sanitized)
67 : :else "User")
68 15 : canonical (if (transliteration/latin-name? canonical) canonical "User")
69 3 : localized (if
70 20 : (and
71 9 : (not already-latin?)
72 6 : (transliteration/localized-name? sanitized)
73 10 : (not (localized-name-present? localized "uk")))
74 5 : (assoc localized "uk" sanitized)
75 3 : localized)]
76 15 : (assoc account-data
77 3 : :name canonical
78 3 : :name-localized localized)))
79 :
80 :
81 4 : (defn latin-name-backfill
82 : "For a user whose name was never confirmed and is not Latin, returns the user with a
83 : transliterated Latin name and the original kept as the \"uk\" localized name; else nil.
84 : name-confirmed-at stays nil so the user is still asked to check the result."
85 : [user]
86 19 : (when (and (nil? (:name-confirmed-at user)) (not (transliteration/latin-name? (:name user))))
87 3 : (normalize-created-name user)))
88 :
89 :
90 4 : (defn backfill-latin-names!
91 : "One-time, idempotent: converts every unconfirmed non-Latin name with
92 : latin-name-backfill. Returns the number of users updated."
93 : [{:keys [repos goose]}]
94 4 : (let [repo (:user-postgres-repo repos)
95 1 : updated (->>
96 3 : (user-postgres-repo/get-all repo)
97 3 : (keep latin-name-backfill)
98 9 : (filter #(either/right? (user-postgres-repo/save! repo %)))
99 : count)]
100 4 : (when (pos? updated)
101 5 : (redis-repo/invalidate-users! (:user-redis-repo repos))
102 2 : (when goose (scheduler/schedule-job goose `users-jobs/update-users-in-redis-job)))
103 1 : updated))
104 :
105 :
106 4 : (defn- invalidate-and-schedule-cache-update!
107 : [user-redis goose telegram-id]
108 9 : (redis-repo/invalidate-users! user-redis)
109 12 : (redis-repo/invalidate-tg-uuid! user-redis telegram-id)
110 : ;; goose may be absent (e.g. auto-provisioning from the auth middleware); the
111 : ;; users-list cache refresh is best-effort and self-heals, so skip it then.
112 6 : (when goose (scheduler/schedule-job goose `users-jobs/update-users-in-redis-job)))
113 :
114 :
115 4 : (defn- resolve-default-username
116 : "If username is provided but already taken, set it to nil instead of failing."
117 : [repo account-data]
118 12 : (let [username (:username account-data)]
119 34 : (if (and (some? username) (user-postgres-repo/find-by-username repo username))
120 10 : (assoc account-data :username nil)
121 3 : account-data)))
122 :
123 :
124 4 : (defn create-user!
125 : "Creates a new user. Checks for ID and username conflicts.
126 : If the default username is taken, falls back to nil.
127 : Returns Either<Error, User>."
128 : [{:keys [repos goose]} account-data]
129 12 : (let [repo (:user-postgres-repo repos)
130 9 : user-redis (:user-redis-repo repos)
131 6 : account-data (->
132 3 : account-data
133 3 : normalize-created-name
134 15 : (update :username normalize-username)
135 22 : (cond-> (:confirm-name account-data) (assoc :name-confirmed-at
136 2 : (OffsetDateTime/now)))
137 3 : (dissoc :confirm-name))
138 12 : account-data (resolve-default-username repo account-data)
139 33 : result (c/mlet [_ (check-id-not-taken repo account-data)]
140 12 : (user-postgres-repo/save! repo account-data))]
141 15 : (when (either/right? result)
142 21 : (invalidate-and-schedule-cache-update! user-redis goose (:telegram-id account-data)))
143 3 : result))
144 :
145 :
146 4 : (defn create-from-telegram!
147 : "Creates a minimal account from a Telegram profile map
148 : {:telegram-id :first-name :last-name :username :photo-url}, generating uuid,
149 : public-id and default settings. Returns Either<Error, User>."
150 : [ctx {:keys [telegram-id first-name last-name username photo-url]}]
151 5 : (let [name (or
152 13 : (not-empty (str/trim (str/join " " (remove str/blank? [first-name last-name]))))
153 0 : (str "Telegram user " telegram-id))]
154 2 : (create-user!
155 1 : ctx
156 10 : {:uuid (uuid-utils/generate-uuid7-str)
157 2 : :public-id (nanoid/generate)
158 1 : :name name
159 3 : :username (not-empty username)
160 1 : :photo-url photo-url
161 1 : :telegram-id telegram-id
162 11 : :settings {:ui {:theme "sky"
163 : :mode "auto"}
164 : :language "en"
165 : :telegram-match-notifications-enabled true}})))
166 :
167 :
168 4 : (defn- find-by-id-or-fail
169 : [repo user-id]
170 18 : (if-let [existing (user-postgres-repo/find-by-id repo user-id)]
171 6 : (either/right existing)
172 4 : (either/left
173 6 : (utils.errors/build-error
174 : :check
175 10 : {:code :error.account/not-found
176 : :message "User not found."}))))
177 :
178 :
179 4 : (defn- check-username-available
180 : [repo existing account-data]
181 14 : (if (nil? (:username account-data))
182 3 : (either/right account-data)
183 2 : (if
184 10 : (and
185 8 : (entity/username-changed? existing account-data)
186 12 : (let [user (user-postgres-repo/find-by-username repo (:username account-data))]
187 30 : (and (some? user) (not= (:uuid user) (:uuid account-data)))))
188 4 : (either/left
189 6 : (utils.errors/build-error
190 : :check
191 8 : {:code :error.account/conflict-username
192 14 : :message (str "Username " (:username account-data) " is already taken.")}))
193 6 : (either/right account-data))))
194 :
195 :
196 4 : (defn- validate-name-change
197 : [existing account-data]
198 18 : (let [new-name (some->
199 6 : (:name account-data)
200 2 : str/trim)]
201 2 : (if
202 10 : (and
203 16 : (not= (:name existing) (:name account-data))
204 8 : (not (transliteration/latin-name? new-name)))
205 2 : (either/left
206 3 : (utils.errors/build-error
207 : :check
208 5 : {:code :error.account/invalid-name
209 : :message "Name must use Latin letters"}))
210 14 : (either/right (assoc account-data :name new-name)))))
211 :
212 :
213 4 : (defn- localized-value
214 : [localized language]
215 15 : (some->
216 12 : (or (get localized language) (get localized (keyword language)))
217 1 : str/trim
218 1 : not-empty))
219 :
220 :
221 4 : (defn locked-name-changes
222 : "Languages in the user's name locks whose name `account-data` would change, sorted.
223 : \"en\" is the Latin `name`; other languages are `name-localized` entries. A localized
224 : language missing from the incoming map is left as is, so it is not a change."
225 : [existing account-data]
226 6 : (->>
227 6 : (:name-locks existing)
228 4 : (filter
229 2 : (fn [language]
230 4 : (if (= "en" language)
231 5 : (and
232 4 : (contains? account-data :name)
233 1 : (not=
234 8 : (some->
235 3 : (:name existing)
236 1 : str/trim)
237 8 : (some->
238 3 : (:name account-data)
239 1 : str/trim)))
240 4 : (let [incoming (:name-localized account-data)]
241 8 : (and
242 3 : (map? incoming)
243 14 : (or (contains? incoming language) (contains? incoming (keyword language)))
244 1 : (not=
245 6 : (localized-value (:name-localized existing) language)
246 4 : (localized-value incoming language)))))))
247 2 : distinct
248 2 : sort
249 2 : vec))
250 :
251 :
252 4 : (defn- check-name-locks
253 : [existing account-data]
254 20 : (if-let [languages (not-empty (locked-name-changes existing account-data))]
255 2 : (either/left
256 3 : (utils.errors/build-error
257 : :check
258 5 : {:code :error.account/name-locked
259 8 : :message (str "Name change is locked by an administrator (" (str/join ", " languages) ").")
260 3 : :context {:languages languages}}))
261 6 : (either/right account-data)))
262 :
263 :
264 4 : (defn- merge-and-validate-localized-names
265 : [existing account-data]
266 14 : (if-not (contains? account-data :name-localized)
267 6 : (either/right account-data)
268 3 : (let [localized (merge
269 5 : (normalize-localized-names (:name-localized existing))
270 5 : (normalize-localized-names (:name-localized account-data)))
271 1 : cleared (->>
272 3 : (:name-localized account-data)
273 2 : (keep
274 1 : (fn [[language value]]
275 5 : (when (str/blank? value)
276 7 : (if (keyword? language) (name language) (str language)))))
277 1 : set)
278 5 : localized (apply dissoc localized cleared)
279 2 : valid-keys? (every?
280 3 : (set user-schemas/localized-languages)
281 3 : (map
282 7 : #(if (keyword? %) (name %) (str %))
283 5 : (keys (:name-localized account-data))))]
284 9 : (if (and valid-keys? (m/validate user-schemas/NameLocalizedSchema localized))
285 7 : (either/right (assoc account-data :name-localized localized))
286 0 : (either/left
287 0 : (utils.errors/build-error
288 : :check
289 0 : {:code :error.account/invalid-name-localized
290 : :message "Localized names are invalid"}))))))
291 :
292 :
293 4 : (defn- apply-name-confirmation
294 : [existing account-data]
295 17 : (cond-> (dissoc account-data :confirm-name)
296 20 : (and (:confirm-name account-data) (nil? (:name-confirmed-at existing)))
297 3 : (assoc :name-confirmed-at (OffsetDateTime/now))))
298 :
299 :
300 4 : (defn- save-if-changed
301 : [repo existing account-data]
302 10 : (if (entity/has-changes? existing account-data)
303 6 : (c/fmap
304 12 : #(hash-map :code :success.account/ok :data %)
305 14 : (user-postgres-repo/save! repo (entity/merge-updates existing account-data)))
306 4 : (either/right
307 8 : {:code :success.account/no-changes
308 2 : :data existing})))
309 :
310 :
311 4 : (defn update-user!
312 : "Updates the user's profile. Names in the user's locked languages cannot change unless
313 : `enforce-name-locks?` is false (admin edits). Returns Either<Error, {:code :data}>."
314 : [{:keys [repos goose]}
315 : account-data
316 : &
317 : [{:keys [enforce-name-locks?]
318 : :or {enforce-name-locks? true}}]]
319 8 : (let [repo (:user-postgres-repo repos)
320 6 : user-redis (:user-redis-repo repos)
321 : ;; :username is optional on update; omitting it must keep the stored value.
322 13 : account-data (cond-> account-data
323 12 : (contains? account-data :username) (update :username normalize-username))
324 110 : result (c/mlet [existing (find-by-id-or-fail repo (:uuid account-data))
325 18 : account-data (validate-name-change existing account-data)
326 12 : account-data (if enforce-name-locks?
327 8 : (check-name-locks existing account-data)
328 3 : (c/return account-data))
329 14 : account-data (merge-and-validate-localized-names existing account-data)
330 16 : account-data (c/return (apply-name-confirmation existing account-data))
331 12 : _ (check-username-available repo existing account-data)
332 10 : result (save-if-changed repo existing account-data)]
333 6 : (c/return result))]
334 32 : (when (and (either/right? result) (= :success.account/ok (:code (c/extract result))))
335 14 : (invalidate-and-schedule-cache-update! user-redis goose (:telegram-id account-data)))
336 2 : result))
337 :
338 :
339 4 : (defn set-name-locks!
340 : "Replaces the user's name locks with `languages` (a subset of the supported languages).
341 : Returns Either<Error, User>."
342 : [{:keys [repos goose]} user-id languages]
343 8 : (let [languages (vec (sort (distinct languages)))
344 5 : result (if (m/validate user-schemas/NameLocksSchema languages)
345 2 : (user-postgres-repo/update-name-locks!
346 3 : (:user-postgres-repo repos)
347 1 : user-id
348 1 : languages)
349 2 : (either/left
350 3 : (utils.errors/build-error
351 : :check
352 6 : {:code :error.account/invalid-name-locks
353 : :message "Unsupported name lock language"
354 3 : :context {:languages languages}})))]
355 5 : (when (either/right? result)
356 2 : (invalidate-and-schedule-cache-update!
357 3 : (:user-redis-repo repos)
358 1 : goose
359 5 : (:telegram-id (c/extract result))))
360 1 : result))
|