places.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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.OwnerID != "" { q += ` AND p.owner_id = @owner_id`; args["owner_id"] = filter.OwnerID }
  76. if filter.MinRating > 0 { q += ` AND p.rating >= @min_rating`; args["min_rating"] = filter.MinRating }
  77. if filter.PriceMin != nil { q += ` AND p.hourly_rate >= @price_min`; args["price_min"] = *filter.PriceMin }
  78. if filter.PriceMax != nil { q += ` AND p.hourly_rate <= @price_max`; args["price_max"] = *filter.PriceMax }
  79. if filter.Bounds != nil {
  80. q += ` AND ST_Intersects(p.coordinates, ST_MakeEnvelope(@sw_lng, @sw_lat, @ne_lng, @ne_lat, 4326))`
  81. args["sw_lng"] = filter.Bounds.SWLng; args["sw_lat"] = filter.Bounds.SWLat
  82. args["ne_lng"] = filter.Bounds.NELng; args["ne_lat"] = filter.Bounds.NELat
  83. }
  84. if len(filter.TagIDs) > 0 { q += ` AND pt.tag_id = ANY(@tag_ids)`; args["tag_ids"] = filter.TagIDs }
  85. if len(filter.FeatureIDs) > 0 { q += ` AND pf.feature_id = ANY(@feature_ids)`; args["feature_ids"] = filter.FeatureIDs }
  86. // Cursor-based pagination
  87. if filter.Cursor != "" && filter.CursorCreatedAt != nil {
  88. if filter.Sort == "rating" && filter.CursorRating != nil {
  89. q += ` AND (p.rating, p.created_at, p.id) < (@cursor_rating, @cursor_created_at, @cursor_id)`
  90. args["cursor_rating"] = *filter.CursorRating
  91. args["cursor_created_at"] = *filter.CursorCreatedAt
  92. args["cursor_id"] = filter.Cursor
  93. } else {
  94. q += ` AND (p.created_at, p.id) < (@cursor_created_at, @cursor_id)`
  95. args["cursor_created_at"] = *filter.CursorCreatedAt
  96. args["cursor_id"] = filter.Cursor
  97. }
  98. }
  99. if filter.Sort == "rating" {
  100. q += ` ORDER BY p.rating DESC, p.created_at DESC, p.id`
  101. } else if filter.Sort == "distance" && filter.UserLat != nil && filter.UserLng != nil {
  102. q += ` ORDER BY p.coordinates <-> ST_SetSRID(ST_MakePoint(@user_lng, @user_lat), 4326), p.created_at DESC, p.id`
  103. args["user_lng"] = *filter.UserLng; args["user_lat"] = *filter.UserLat
  104. } else {
  105. q += ` ORDER BY p.created_at DESC, p.id`
  106. }
  107. q += ` LIMIT @lim`
  108. args["lim"] = filter.Limit() + 1 // fetch one extra to detect hasMore
  109. rows, err := r.pool.Query(ctx, q, args)
  110. if err != nil {
  111. return nil, fmt.Errorf("list places: %w", err)
  112. }
  113. defer rows.Close()
  114. var places []*models.Place
  115. for rows.Next() {
  116. p, err := scanPlace(rows)
  117. if err != nil {
  118. return nil, err
  119. }
  120. places = append(places, p)
  121. }
  122. return places, nil
  123. }
  124. func (r *PlaceRepo) Update(ctx context.Context, p *models.Place) error {
  125. _, err := r.pool.Exec(ctx,
  126. `UPDATE places SET title=$1, description=$2, address=$3,
  127. coordinates=ST_SetSRID(ST_MakePoint($4, $5), 4326),
  128. cover_image=$6, access_info=$7, status=$8, hourly_rate=$9, currency=$10, min_hours=$11,
  129. booking_url=$12, updated_at=now()
  130. WHERE id=$13 AND deleted_at IS NULL`,
  131. p.Title, p.Description, p.Address,
  132. p.Lng, p.Lat,
  133. p.CoverImage, p.AccessInfo, p.Status,
  134. p.HourlyRate, p.Currency, p.MinHours, p.BookingURL,
  135. p.ID)
  136. return err
  137. }
  138. func (r *PlaceRepo) UpdateStatus(ctx context.Context, id, status, comment string) error {
  139. _, err := r.pool.Exec(ctx,
  140. `UPDATE places SET status=$1, moderation_comment=$2, updated_at=now(),
  141. published_at = CASE WHEN $1 = 'published' THEN now() ELSE published_at END
  142. WHERE id=$3 AND deleted_at IS NULL`,
  143. status, comment, id)
  144. return err
  145. }
  146. func (r *PlaceRepo) SoftDelete(ctx context.Context, id string) error {
  147. _, err := r.pool.Exec(ctx,
  148. `UPDATE places SET deleted_at=now() WHERE id=$1`, id)
  149. return err
  150. }
  151. func (r *PlaceRepo) SetTags(ctx context.Context, placeID string, tags []models.Tag) error {
  152. tx, err := r.pool.Begin(ctx)
  153. if err != nil {
  154. return err
  155. }
  156. defer tx.Rollback(ctx)
  157. _, err = tx.Exec(ctx, `DELETE FROM place_tags WHERE place_id = $1`, placeID)
  158. if err != nil {
  159. return err
  160. }
  161. for _, tag := range tags {
  162. _, err = tx.Exec(ctx,
  163. `INSERT INTO place_tags (place_id, tag_id) VALUES ($1, $2)`,
  164. placeID, tag.ID)
  165. if err != nil {
  166. return err
  167. }
  168. }
  169. return tx.Commit(ctx)
  170. }
  171. func (r *PlaceRepo) SetFeatures(ctx context.Context, placeID string, features []models.Feature) error {
  172. tx, err := r.pool.Begin(ctx)
  173. if err != nil {
  174. return err
  175. }
  176. defer tx.Rollback(ctx)
  177. _, err = tx.Exec(ctx, `DELETE FROM place_features WHERE place_id = $1`, placeID)
  178. if err != nil {
  179. return err
  180. }
  181. for _, f := range features {
  182. _, err = tx.Exec(ctx,
  183. `INSERT INTO place_features (place_id, feature_id) VALUES ($1, $2)`,
  184. placeID, f.ID)
  185. if err != nil {
  186. return err
  187. }
  188. }
  189. return tx.Commit(ctx)
  190. }
  191. func (r *PlaceRepo) GetTags(ctx context.Context, placeID string) ([]models.Tag, error) {
  192. rows, err := r.pool.Query(ctx,
  193. `SELECT t.id, t.name, t.category FROM tags t
  194. JOIN place_tags pt ON pt.tag_id = t.id
  195. WHERE pt.place_id = $1`, placeID)
  196. if err != nil {
  197. return nil, err
  198. }
  199. defer rows.Close()
  200. var tags []models.Tag
  201. for rows.Next() {
  202. var t models.Tag
  203. if err := rows.Scan(&t.ID, &t.Name, &t.Category); err != nil {
  204. return nil, err
  205. }
  206. tags = append(tags, t)
  207. }
  208. return tags, nil
  209. }
  210. func (r *PlaceRepo) GetFeatures(ctx context.Context, placeID string) ([]models.Feature, error) {
  211. rows, err := r.pool.Query(ctx,
  212. `SELECT f.id, f.name, f.category, f.icon FROM features f
  213. JOIN place_features pf ON pf.feature_id = f.id
  214. WHERE pf.place_id = $1`, placeID)
  215. if err != nil {
  216. return nil, err
  217. }
  218. defer rows.Close()
  219. var features []models.Feature
  220. for rows.Next() {
  221. var f models.Feature
  222. if err := rows.Scan(&f.ID, &f.Name, &f.Category, &f.Icon); err != nil {
  223. return nil, err
  224. }
  225. features = append(features, f)
  226. }
  227. return features, nil
  228. }
  229. func (r *PlaceRepo) GetTagsBatch(ctx context.Context, placeIDs []string) (map[string][]models.Tag, error) {
  230. if len(placeIDs) == 0 {
  231. return map[string][]models.Tag{}, nil
  232. }
  233. rows, err := r.pool.Query(ctx,
  234. `SELECT pt.place_id, t.id, t.name, t.category FROM tags t
  235. JOIN place_tags pt ON pt.tag_id = t.id
  236. WHERE pt.place_id = ANY($1)`, placeIDs)
  237. if err != nil {
  238. return nil, err
  239. }
  240. defer rows.Close()
  241. result := make(map[string][]models.Tag)
  242. for rows.Next() {
  243. var placeID string
  244. var t models.Tag
  245. if err := rows.Scan(&placeID, &t.ID, &t.Name, &t.Category); err != nil {
  246. return nil, err
  247. }
  248. result[placeID] = append(result[placeID], t)
  249. }
  250. return result, nil
  251. }
  252. func (r *PlaceRepo) GetFeaturesBatch(ctx context.Context, placeIDs []string) (map[string][]models.Feature, error) {
  253. if len(placeIDs) == 0 {
  254. return map[string][]models.Feature{}, nil
  255. }
  256. rows, err := r.pool.Query(ctx,
  257. `SELECT pf.place_id, f.id, f.name, f.category, f.icon FROM features f
  258. JOIN place_features pf ON pf.feature_id = f.id
  259. WHERE pf.place_id = ANY($1)`, placeIDs)
  260. if err != nil {
  261. return nil, err
  262. }
  263. defer rows.Close()
  264. result := make(map[string][]models.Feature)
  265. for rows.Next() {
  266. var placeID string
  267. var f models.Feature
  268. if err := rows.Scan(&placeID, &f.ID, &f.Name, &f.Category, &f.Icon); err != nil {
  269. return nil, err
  270. }
  271. result[placeID] = append(result[placeID], f)
  272. }
  273. return result, nil
  274. }
  275. func scanPlace(row interface{ Scan(dest ...any) error }) (*models.Place, error) {
  276. var p models.Place
  277. err := row.Scan(
  278. &p.ID, &p.Type, &p.OwnerID, &p.Title, &p.Description, &p.Address,
  279. &p.Lat, &p.Lng,
  280. &p.CoverImage, &p.AccessInfo, &p.Status, &p.ModerationComment,
  281. &p.Rating, &p.ReviewsCount, &p.HourlyRate, &p.Currency, &p.MinHours, &p.BookingURL,
  282. &p.CreatedAt, &p.UpdatedAt, &p.PublishedAt, &p.DeletedAt,
  283. )
  284. if err != nil {
  285. if err == pgx.ErrNoRows {
  286. return nil, nil
  287. }
  288. return nil, err
  289. }
  290. return &p, nil
  291. }