places.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. package repository
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/jackc/pgx/v5"
  6. "github.com/jackc/pgx/v5/pgxpool"
  7. "github.com/photoplaces/backend/internal/models"
  8. )
  9. type PlaceRepo struct {
  10. pool *pgxpool.Pool
  11. }
  12. func NewPlaceRepo(pool *pgxpool.Pool) *PlaceRepo {
  13. return &PlaceRepo{pool: pool}
  14. }
  15. func (r *PlaceRepo) Create(ctx context.Context, p *models.Place) error {
  16. err := r.pool.QueryRow(ctx,
  17. `INSERT INTO places (type, owner_id, title, description, address, coordinates,
  18. cover_image, access_info, status, hourly_rate, currency, min_hours, booking_url)
  19. VALUES ($1, $2, $3, $4, $5, ST_SetSRID(ST_MakePoint($6, $7), 4326),
  20. $8, $9, $10, $11, $12, $13, $14)
  21. RETURNING id, created_at, updated_at`,
  22. p.Type, p.OwnerID, p.Title, p.Description, p.Address,
  23. p.Lng, p.Lat,
  24. p.CoverImage, p.AccessInfo, p.Status,
  25. p.HourlyRate, p.Currency, p.MinHours, p.BookingURL,
  26. ).Scan(&p.ID, &p.CreatedAt, &p.UpdatedAt)
  27. if err != nil {
  28. return fmt.Errorf("create place: %w", err)
  29. }
  30. if len(p.Tags) > 0 {
  31. if err := r.SetTags(ctx, p.ID, p.Tags); err != nil {
  32. return err
  33. }
  34. }
  35. if len(p.Features) > 0 {
  36. if err := r.SetFeatures(ctx, p.ID, p.Features); err != nil {
  37. return err
  38. }
  39. }
  40. return nil
  41. }
  42. func (r *PlaceRepo) GetByID(ctx context.Context, id string) (*models.Place, error) {
  43. row := r.pool.QueryRow(ctx,
  44. `SELECT id, type, owner_id, title, description, address,
  45. ST_Y(coordinates::geometry), ST_X(coordinates::geometry),
  46. cover_image, access_info, status, moderation_comment,
  47. rating, reviews_count, hourly_rate, currency, min_hours, booking_url,
  48. created_at, updated_at, published_at, deleted_at
  49. FROM places WHERE id = $1 AND deleted_at IS NULL`, id)
  50. return scanPlace(row)
  51. }
  52. func (r *PlaceRepo) List(ctx context.Context, filter models.PlaceFilter) ([]*models.Place, error) {
  53. q := `SELECT p.id, p.type, p.owner_id, p.title, p.description, p.address,
  54. ST_Y(p.coordinates::geometry), ST_X(p.coordinates::geometry),
  55. p.cover_image, p.access_info, p.status, p.moderation_comment,
  56. p.rating, p.reviews_count, p.hourly_rate, p.currency, p.min_hours, p.booking_url,
  57. p.created_at, p.updated_at, p.published_at, p.deleted_at
  58. FROM places p`
  59. args := pgx.NamedArgs{}
  60. joins := ""
  61. if len(filter.TagIDs) > 0 {
  62. joins += ` JOIN place_tags pt ON pt.place_id = p.id`
  63. }
  64. if len(filter.FeatureIDs) > 0 {
  65. joins += ` JOIN place_features pf ON pf.place_id = p.id`
  66. }
  67. q += joins + ` WHERE p.deleted_at IS NULL`
  68. if filter.Status != "" { q += ` AND p.status = @status`; args["status"] = filter.Status }
  69. if filter.Type != "" { q += ` AND p.type = @type`; args["type"] = filter.Type }
  70. if filter.MinRating > 0 { q += ` AND p.rating >= @min_rating`; args["min_rating"] = filter.MinRating }
  71. if filter.PriceMin != nil { q += ` AND p.hourly_rate >= @price_min`; args["price_min"] = *filter.PriceMin }
  72. if filter.PriceMax != nil { q += ` AND p.hourly_rate <= @price_max`; args["price_max"] = *filter.PriceMax }
  73. if filter.Bounds != nil {
  74. q += ` AND ST_Intersects(p.coordinates, ST_MakeEnvelope(@sw_lng, @sw_lat, @ne_lng, @ne_lat, 4326))`
  75. args["sw_lng"] = filter.Bounds.SWLng; args["sw_lat"] = filter.Bounds.SWLat
  76. args["ne_lng"] = filter.Bounds.NELng; args["ne_lat"] = filter.Bounds.NELat
  77. }
  78. if len(filter.TagIDs) > 0 { q += ` AND pt.tag_id = ANY(@tag_ids)`; args["tag_ids"] = filter.TagIDs }
  79. if len(filter.FeatureIDs) > 0 { q += ` AND pf.feature_id = ANY(@feature_ids)`; args["feature_ids"] = filter.FeatureIDs }
  80. if filter.Sort == "rating" {
  81. q += ` ORDER BY p.rating DESC`
  82. } else if filter.Sort == "distance" && filter.UserLat != nil && filter.UserLng != nil {
  83. q += ` ORDER BY p.coordinates <-> ST_SetSRID(ST_MakePoint(@user_lng, @user_lat), 4326)`
  84. args["user_lng"] = *filter.UserLng; args["user_lat"] = *filter.UserLat
  85. } else {
  86. q += ` ORDER BY p.created_at DESC`
  87. }
  88. q += ` LIMIT @lim`
  89. args["lim"] = filter.Limit()
  90. rows, err := r.pool.Query(ctx, q, args)
  91. if err != nil {
  92. return nil, fmt.Errorf("list places: %w", err)
  93. }
  94. defer rows.Close()
  95. var places []*models.Place
  96. for rows.Next() {
  97. p, err := scanPlace(rows)
  98. if err != nil {
  99. return nil, err
  100. }
  101. places = append(places, p)
  102. }
  103. return places, nil
  104. }
  105. func (r *PlaceRepo) Update(ctx context.Context, p *models.Place) error {
  106. _, err := r.pool.Exec(ctx,
  107. `UPDATE places SET title=$1, description=$2, address=$3,
  108. coordinates=ST_SetSRID(ST_MakePoint($4, $5), 4326),
  109. cover_image=$6, access_info=$7, status=$8, hourly_rate=$9, currency=$10, min_hours=$11,
  110. booking_url=$12, updated_at=now()
  111. WHERE id=$13 AND deleted_at IS NULL`,
  112. p.Title, p.Description, p.Address,
  113. p.Lng, p.Lat,
  114. p.CoverImage, p.AccessInfo, p.Status,
  115. p.HourlyRate, p.Currency, p.MinHours, p.BookingURL,
  116. p.ID)
  117. return err
  118. }
  119. func (r *PlaceRepo) UpdateStatus(ctx context.Context, id, status, comment string) error {
  120. _, err := r.pool.Exec(ctx,
  121. `UPDATE places SET status=$1, moderation_comment=$2, updated_at=now(),
  122. published_at = CASE WHEN $1 = 'published' THEN now() ELSE published_at END
  123. WHERE id=$3 AND deleted_at IS NULL`,
  124. status, comment, id)
  125. return err
  126. }
  127. func (r *PlaceRepo) SoftDelete(ctx context.Context, id string) error {
  128. _, err := r.pool.Exec(ctx,
  129. `UPDATE places SET deleted_at=now() WHERE id=$1`, id)
  130. return err
  131. }
  132. func (r *PlaceRepo) SetTags(ctx context.Context, placeID string, tags []models.Tag) error {
  133. tx, err := r.pool.Begin(ctx)
  134. if err != nil {
  135. return err
  136. }
  137. defer tx.Rollback(ctx)
  138. _, err = tx.Exec(ctx, `DELETE FROM place_tags WHERE place_id = $1`, placeID)
  139. if err != nil {
  140. return err
  141. }
  142. for _, tag := range tags {
  143. _, err = tx.Exec(ctx,
  144. `INSERT INTO place_tags (place_id, tag_id) VALUES ($1, $2)`,
  145. placeID, tag.ID)
  146. if err != nil {
  147. return err
  148. }
  149. }
  150. return tx.Commit(ctx)
  151. }
  152. func (r *PlaceRepo) SetFeatures(ctx context.Context, placeID string, features []models.Feature) error {
  153. tx, err := r.pool.Begin(ctx)
  154. if err != nil {
  155. return err
  156. }
  157. defer tx.Rollback(ctx)
  158. _, err = tx.Exec(ctx, `DELETE FROM place_features WHERE place_id = $1`, placeID)
  159. if err != nil {
  160. return err
  161. }
  162. for _, f := range features {
  163. _, err = tx.Exec(ctx,
  164. `INSERT INTO place_features (place_id, feature_id) VALUES ($1, $2)`,
  165. placeID, f.ID)
  166. if err != nil {
  167. return err
  168. }
  169. }
  170. return tx.Commit(ctx)
  171. }
  172. func (r *PlaceRepo) GetTags(ctx context.Context, placeID string) ([]models.Tag, error) {
  173. rows, err := r.pool.Query(ctx,
  174. `SELECT t.id, t.name, t.category FROM tags t
  175. JOIN place_tags pt ON pt.tag_id = t.id
  176. WHERE pt.place_id = $1`, placeID)
  177. if err != nil {
  178. return nil, err
  179. }
  180. defer rows.Close()
  181. var tags []models.Tag
  182. for rows.Next() {
  183. var t models.Tag
  184. if err := rows.Scan(&t.ID, &t.Name, &t.Category); err != nil {
  185. return nil, err
  186. }
  187. tags = append(tags, t)
  188. }
  189. return tags, nil
  190. }
  191. func (r *PlaceRepo) GetFeatures(ctx context.Context, placeID string) ([]models.Feature, error) {
  192. rows, err := r.pool.Query(ctx,
  193. `SELECT f.id, f.name, f.category, f.icon FROM features f
  194. JOIN place_features pf ON pf.feature_id = f.id
  195. WHERE pf.place_id = $1`, placeID)
  196. if err != nil {
  197. return nil, err
  198. }
  199. defer rows.Close()
  200. var features []models.Feature
  201. for rows.Next() {
  202. var f models.Feature
  203. if err := rows.Scan(&f.ID, &f.Name, &f.Category, &f.Icon); err != nil {
  204. return nil, err
  205. }
  206. features = append(features, f)
  207. }
  208. return features, nil
  209. }
  210. func scanPlace(row interface{ Scan(dest ...any) error }) (*models.Place, error) {
  211. var p models.Place
  212. err := row.Scan(
  213. &p.ID, &p.Type, &p.OwnerID, &p.Title, &p.Description, &p.Address,
  214. &p.Lat, &p.Lng,
  215. &p.CoverImage, &p.AccessInfo, &p.Status, &p.ModerationComment,
  216. &p.Rating, &p.ReviewsCount, &p.HourlyRate, &p.Currency, &p.MinHours, &p.BookingURL,
  217. &p.CreatedAt, &p.UpdatedAt, &p.PublishedAt, &p.DeletedAt,
  218. )
  219. if err != nil {
  220. if err == pgx.ErrNoRows {
  221. return nil, nil
  222. }
  223. return nil, err
  224. }
  225. return &p, nil
  226. }