places.go 12 KB

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