places.go 8.1 KB

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