places.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. // Package repository
  2. package repository
  3. import (
  4. "context"
  5. "fmt"
  6. "github.com/jackc/pgx/v5"
  7. "github.com/jackc/pgx/v5/pgxpool"
  8. "gogs.fxtmmsk.ru/foxtime/photoplaces/backend/internal/models"
  9. )
  10. type PlaceRepo struct {
  11. pool *pgxpool.Pool
  12. }
  13. func NewPlaceRepo(pool *pgxpool.Pool) *PlaceRepo {
  14. return &PlaceRepo{pool: pool}
  15. }
  16. func (r *PlaceRepo) Create(ctx context.Context, p *models.Place) error {
  17. err := r.pool.QueryRow(ctx,
  18. `INSERT INTO places (type, owner_id, title, description, address, coordinates,
  19. cover_image, access_info, status, hourly_rate, currency, min_hours, booking_url)
  20. VALUES ($1, $2, $3, $4, $5, ST_SetSRID(ST_MakePoint($6, $7), 4326),
  21. $8, $9, $10, $11, $12, $13, $14)
  22. RETURNING id, created_at, updated_at`,
  23. p.Type, p.OwnerID, p.Title, p.Description, p.Address,
  24. p.Lng, p.Lat,
  25. p.CoverImage, p.AccessInfo, p.Status,
  26. p.HourlyRate, p.Currency, p.MinHours, p.BookingURL,
  27. ).Scan(&p.ID, &p.CreatedAt, &p.UpdatedAt)
  28. if err != nil {
  29. return fmt.Errorf("create place: %w", err)
  30. }
  31. if len(p.Tags) > 0 {
  32. if err := r.SetTags(ctx, p.ID, p.Tags); err != nil {
  33. return err
  34. }
  35. }
  36. if len(p.Features) > 0 {
  37. if err := r.SetFeatures(ctx, p.ID, p.Features); err != nil {
  38. return err
  39. }
  40. }
  41. return nil
  42. }
  43. func (r *PlaceRepo) GetByID(ctx context.Context, id string) (*models.Place, error) {
  44. row := r.pool.QueryRow(ctx,
  45. `SELECT id, type, owner_id, title, description, address,
  46. ST_Y(coordinates::geometry), ST_X(coordinates::geometry),
  47. cover_image, access_info, status, moderation_comment,
  48. rating, reviews_count, hourly_rate, currency, min_hours, booking_url,
  49. created_at, updated_at, published_at, deleted_at
  50. FROM places WHERE id = $1 AND deleted_at IS NULL`, id)
  51. return scanPlace(row)
  52. }
  53. func (r *PlaceRepo) List(ctx context.Context, filter models.PlaceFilter) ([]*models.Place, error) {
  54. q := `SELECT p.id, p.type, p.owner_id, p.title, p.description, p.address,
  55. ST_Y(p.coordinates::geometry), ST_X(p.coordinates::geometry),
  56. p.cover_image, p.access_info, p.status, p.moderation_comment,
  57. p.rating, p.reviews_count, p.hourly_rate, p.currency, p.min_hours, p.booking_url,
  58. p.created_at, p.updated_at, p.published_at, p.deleted_at
  59. FROM places p`
  60. args := pgx.NamedArgs{}
  61. joins := ""
  62. if len(filter.TagIDs) > 0 {
  63. joins += ` JOIN place_tags pt ON pt.place_id = p.id`
  64. }
  65. if len(filter.FeatureIDs) > 0 {
  66. joins += ` JOIN place_features pf ON pf.place_id = p.id`
  67. }
  68. // Если есть JOIN-ы, добавляем DISTINCT, чтобы избежать дубликатов мест при нескольких совпадениях
  69. if joins != "" {
  70. q = "SELECT DISTINCT" + q[6:] // заменяем "SELECT" на "SELECT DISTINCT"
  71. }
  72. q += joins + ` WHERE p.deleted_at IS NULL`
  73. if filter.Status != "" { q += ` AND p.status = @status`; args["status"] = filter.Status }
  74. if filter.Type != "" { q += ` AND p.type = @type`; args["type"] = filter.Type }
  75. if filter.MinRating > 0 { q += ` AND p.rating >= @min_rating`; args["min_rating"] = filter.MinRating }
  76. if filter.PriceMin != nil { q += ` AND p.hourly_rate >= @price_min`; args["price_min"] = *filter.PriceMin }
  77. if filter.PriceMax != nil { q += ` AND p.hourly_rate <= @price_max`; args["price_max"] = *filter.PriceMax }
  78. if filter.Bounds != nil {
  79. q += ` AND ST_Intersects(p.coordinates, ST_MakeEnvelope(@sw_lng, @sw_lat, @ne_lng, @ne_lat, 4326))`
  80. args["sw_lng"] = filter.Bounds.SWLng; args["sw_lat"] = filter.Bounds.SWLat
  81. args["ne_lng"] = filter.Bounds.NELng; args["ne_lat"] = filter.Bounds.NELat
  82. }
  83. if len(filter.TagIDs) > 0 { q += ` AND pt.tag_id = ANY(@tag_ids)`; args["tag_ids"] = filter.TagIDs }
  84. if len(filter.FeatureIDs) > 0 { q += ` AND pf.feature_id = ANY(@feature_ids)`; args["feature_ids"] = filter.FeatureIDs }
  85. // Cursor-based pagination
  86. if filter.Cursor != "" && filter.CursorCreatedAt != nil {
  87. if filter.Sort == "rating" && filter.CursorRating != nil {
  88. q += ` AND (p.rating, p.created_at, p.id) < (@cursor_rating, @cursor_created_at, @cursor_id)`
  89. args["cursor_rating"] = *filter.CursorRating
  90. args["cursor_created_at"] = *filter.CursorCreatedAt
  91. args["cursor_id"] = filter.Cursor
  92. } else {
  93. q += ` AND (p.created_at, p.id) < (@cursor_created_at, @cursor_id)`
  94. args["cursor_created_at"] = *filter.CursorCreatedAt
  95. args["cursor_id"] = filter.Cursor
  96. }
  97. }
  98. if filter.Sort == "rating" {
  99. q += ` ORDER BY p.rating DESC, p.created_at DESC, p.id`
  100. } else if filter.Sort == "distance" && filter.UserLat != nil && filter.UserLng != nil {
  101. q += ` ORDER BY p.coordinates <-> ST_SetSRID(ST_MakePoint(@user_lng, @user_lat), 4326), p.created_at DESC, p.id`
  102. args["user_lng"] = *filter.UserLng; args["user_lat"] = *filter.UserLat
  103. } else {
  104. q += ` ORDER BY p.created_at DESC, p.id`
  105. }
  106. q += ` LIMIT @lim`
  107. args["lim"] = filter.Limit() + 1 // fetch one extra to detect hasMore
  108. rows, err := r.pool.Query(ctx, q, args)
  109. if err != nil {
  110. return nil, fmt.Errorf("list places: %w", err)
  111. }
  112. defer rows.Close()
  113. var places []*models.Place
  114. for rows.Next() {
  115. p, err := scanPlace(rows)
  116. if err != nil {
  117. return nil, err
  118. }
  119. places = append(places, p)
  120. }
  121. return places, nil
  122. }
  123. func (r *PlaceRepo) Update(ctx context.Context, p *models.Place) error {
  124. _, err := r.pool.Exec(ctx,
  125. `UPDATE places SET title=$1, description=$2, address=$3,
  126. coordinates=ST_SetSRID(ST_MakePoint($4, $5), 4326),
  127. cover_image=$6, access_info=$7, status=$8, hourly_rate=$9, currency=$10, min_hours=$11,
  128. booking_url=$12, updated_at=now()
  129. WHERE id=$13 AND deleted_at IS NULL`,
  130. p.Title, p.Description, p.Address,
  131. p.Lng, p.Lat,
  132. p.CoverImage, p.AccessInfo, p.Status,
  133. p.HourlyRate, p.Currency, p.MinHours, p.BookingURL,
  134. p.ID)
  135. return err
  136. }
  137. func (r *PlaceRepo) UpdateStatus(ctx context.Context, id, status, comment string) error {
  138. _, err := r.pool.Exec(ctx,
  139. `UPDATE places SET status=$1, moderation_comment=$2, updated_at=now(),
  140. published_at = CASE WHEN $1 = 'published' THEN now() ELSE published_at END
  141. WHERE id=$3 AND deleted_at IS NULL`,
  142. status, comment, id)
  143. return err
  144. }
  145. func (r *PlaceRepo) SoftDelete(ctx context.Context, id string) error {
  146. _, err := r.pool.Exec(ctx,
  147. `UPDATE places SET deleted_at=now() WHERE id=$1`, id)
  148. return err
  149. }
  150. func (r *PlaceRepo) SetTags(ctx context.Context, placeID string, tags []models.Tag) error {
  151. tx, err := r.pool.Begin(ctx)
  152. if err != nil {
  153. return err
  154. }
  155. defer tx.Rollback(ctx)
  156. _, err = tx.Exec(ctx, `DELETE FROM place_tags WHERE place_id = $1`, placeID)
  157. if err != nil {
  158. return err
  159. }
  160. for _, tag := range tags {
  161. _, err = tx.Exec(ctx,
  162. `INSERT INTO place_tags (place_id, tag_id) VALUES ($1, $2)`,
  163. placeID, tag.ID)
  164. if err != nil {
  165. return err
  166. }
  167. }
  168. return tx.Commit(ctx)
  169. }
  170. func (r *PlaceRepo) SetFeatures(ctx context.Context, placeID string, features []models.Feature) error {
  171. tx, err := r.pool.Begin(ctx)
  172. if err != nil {
  173. return err
  174. }
  175. defer tx.Rollback(ctx)
  176. _, err = tx.Exec(ctx, `DELETE FROM place_features WHERE place_id = $1`, placeID)
  177. if err != nil {
  178. return err
  179. }
  180. for _, f := range features {
  181. _, err = tx.Exec(ctx,
  182. `INSERT INTO place_features (place_id, feature_id) VALUES ($1, $2)`,
  183. placeID, f.ID)
  184. if err != nil {
  185. return err
  186. }
  187. }
  188. return tx.Commit(ctx)
  189. }
  190. func (r *PlaceRepo) GetTags(ctx context.Context, placeID string) ([]models.Tag, error) {
  191. rows, err := r.pool.Query(ctx,
  192. `SELECT t.id, t.name, t.category FROM tags t
  193. JOIN place_tags pt ON pt.tag_id = t.id
  194. WHERE pt.place_id = $1`, placeID)
  195. if err != nil {
  196. return nil, err
  197. }
  198. defer rows.Close()
  199. var tags []models.Tag
  200. for rows.Next() {
  201. var t models.Tag
  202. if err := rows.Scan(&t.ID, &t.Name, &t.Category); err != nil {
  203. return nil, err
  204. }
  205. tags = append(tags, t)
  206. }
  207. return tags, nil
  208. }
  209. func (r *PlaceRepo) GetFeatures(ctx context.Context, placeID string) ([]models.Feature, error) {
  210. rows, err := r.pool.Query(ctx,
  211. `SELECT f.id, f.name, f.category, f.icon FROM features f
  212. JOIN place_features pf ON pf.feature_id = f.id
  213. WHERE pf.place_id = $1`, placeID)
  214. if err != nil {
  215. return nil, err
  216. }
  217. defer rows.Close()
  218. var features []models.Feature
  219. for rows.Next() {
  220. var f models.Feature
  221. if err := rows.Scan(&f.ID, &f.Name, &f.Category, &f.Icon); err != nil {
  222. return nil, err
  223. }
  224. features = append(features, f)
  225. }
  226. return features, nil
  227. }
  228. func (r *PlaceRepo) GetTagsBatch(ctx context.Context, placeIDs []string) (map[string][]models.Tag, error) {
  229. if len(placeIDs) == 0 {
  230. return map[string][]models.Tag{}, nil
  231. }
  232. rows, err := r.pool.Query(ctx,
  233. `SELECT pt.place_id, t.id, t.name, t.category FROM tags t
  234. JOIN place_tags pt ON pt.tag_id = t.id
  235. WHERE pt.place_id = ANY($1)`, placeIDs)
  236. if err != nil {
  237. return nil, err
  238. }
  239. defer rows.Close()
  240. result := make(map[string][]models.Tag)
  241. for rows.Next() {
  242. var placeID string
  243. var t models.Tag
  244. if err := rows.Scan(&placeID, &t.ID, &t.Name, &t.Category); err != nil {
  245. return nil, err
  246. }
  247. result[placeID] = append(result[placeID], t)
  248. }
  249. return result, nil
  250. }
  251. func (r *PlaceRepo) GetFeaturesBatch(ctx context.Context, placeIDs []string) (map[string][]models.Feature, error) {
  252. if len(placeIDs) == 0 {
  253. return map[string][]models.Feature{}, nil
  254. }
  255. rows, err := r.pool.Query(ctx,
  256. `SELECT pf.place_id, f.id, f.name, f.category, f.icon FROM features f
  257. JOIN place_features pf ON pf.feature_id = f.id
  258. WHERE pf.place_id = ANY($1)`, placeIDs)
  259. if err != nil {
  260. return nil, err
  261. }
  262. defer rows.Close()
  263. result := make(map[string][]models.Feature)
  264. for rows.Next() {
  265. var placeID string
  266. var f models.Feature
  267. if err := rows.Scan(&placeID, &f.ID, &f.Name, &f.Category, &f.Icon); err != nil {
  268. return nil, err
  269. }
  270. result[placeID] = append(result[placeID], f)
  271. }
  272. return result, nil
  273. }
  274. func scanPlace(row interface{ Scan(dest ...any) error }) (*models.Place, error) {
  275. var p models.Place
  276. err := row.Scan(
  277. &p.ID, &p.Type, &p.OwnerID, &p.Title, &p.Description, &p.Address,
  278. &p.Lat, &p.Lng,
  279. &p.CoverImage, &p.AccessInfo, &p.Status, &p.ModerationComment,
  280. &p.Rating, &p.ReviewsCount, &p.HourlyRate, &p.Currency, &p.MinHours, &p.BookingURL,
  281. &p.CreatedAt, &p.UpdatedAt, &p.PublishedAt, &p.DeletedAt,
  282. )
  283. if err != nil {
  284. if err == pgx.ErrNoRows {
  285. return nil, nil
  286. }
  287. return nil, err
  288. }
  289. return &p, nil
  290. }