places.go 7.8 KB

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