fix chats: one chat per ad, ordering, delivery after commit, errors

A chat was unique per user pair, so contacting the same author about a
second ad returned the old chat with the old post_id, and the chat list
showed the other ad's title and image.

- chats are unique per (user_one_id, user_two_id, post_id); migration 015
  drops the old pair constraint whatever its name and adds the new one
- getOrCreateChat looks the chat up by users and post, and checks that the
  other user exists and the post belongs to one of the participants
- chat list is sorted by last message time (chat creation as fallback)
- WebSocket message and unread events are sent only after commit
- chat errors are ApiException: 404 not found, 403 not a participant,
  400 validation; messages are limited to 4000 characters
- Post.images ordered by id so the cover image is stable everywhere

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
SlimusMinus
2026-10-13 01:20:09 +03:00
parent 008852c781
commit 45c4273ea8
7 changed files with 116 additions and 16 deletions

View File

@@ -0,0 +1,39 @@
databaseChangeLog:
- changeSet:
id: 015-chats-unique-per-post
author: krylov
comment: >
Чат теперь уникален для пары пользователей И объявления. Раньше уникальной была
только пара, и при обращении к тому же автору по другому объявлению возвращался
старый чат со старым post_id (не та картинка во вкладке чатов).
Имя старого ограничения может отличаться (таблицу раньше создавал Hibernate),
поэтому удаляем любое unique-ограничение ровно по (user_one_id, user_two_id).
preConditions:
onFail: MARK_RAN
tableExists:
tableName: chats
changes:
- sql:
splitStatements: false
sql: |
DO $$
DECLARE r record;
BEGIN
FOR r IN
SELECT con.conname
FROM pg_constraint con
JOIN pg_class t ON t.oid = con.conrelid
WHERE t.relname = 'chats'
AND con.contype = 'u'
AND (SELECT array_agg(a.attname::text ORDER BY a.attname::text)
FROM pg_attribute a
WHERE a.attrelid = t.oid AND a.attnum = ANY (con.conkey))
= ARRAY['user_one_id', 'user_two_id']
LOOP
EXECUTE format('ALTER TABLE chats DROP CONSTRAINT %I', r.conname);
END LOOP;
END $$;
- addUniqueConstraint:
tableName: chats
columnNames: user_one_id, user_two_id, post_id
constraintName: uq_chat_users_post

View File

@@ -29,3 +29,4 @@ databaseChangeLog:
- include: { file: db/changelog/create/006-create-chats.yaml }
- include: { file: db/changelog/add/017-messages-chat-id.yaml }
- include: { file: db/changelog/alter/014-posts-rules-accepted-type.yaml }
- include: { file: db/changelog/alter/015-chats-unique-per-post.yaml }