places.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. // Package repository
  2. package repository
  3. import (
  4. "context"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/jackc/pgx/v5"
  8. "github.com/jackc/pgx/v5/pgxpool"
  9. "gogs.fxtmmsk.ru/foxtime/photoplaces/backend/internal/models"
  10. )
  11. type PlaceRepo struct {
  12. pool *pgxpool.Pool
  13. }
  14. func NewPlaceRepo(pool *pgxpool.Pool) *PlaceRepo {
  15. return &PlaceRepo{pool: pool}
  16. }
  17. func (r *PlaceRepo) Create(ctx context.Context, p *models.Place) error {
  18. err := r.pool.QueryRow(ctx,
  19. `INSERT INTO places (type, owner_id, title, description, address, coordinates,
  20. cover_image, access_info, status, hourly_rate, currency, min_hours, booking_url)
  21. VALUES ($1, $2, $3, $4, $5, ST_SetSRID(ST_MakePoint($6, $7), 4326),
  22. $8, $9, $10, $11, $12, $13, $14)
  23. RETURNING id, created_at, updated_at`,
  24. p.Type, p.OwnerID, p.Title, p.Description, p.Address,
  25. p.Lng, p.Lat,
  26. p.CoverImage, p.AccessInfo, p.Status,
  27. p.HourlyRate, p.Currency, p.MinHours, p.BookingURL,
  28. ).Scan(&p.ID, &p.CreatedAt, &p.UpdatedAt)
  29. if err != nil {
  30. return fmt.Errorf("create place: %w", err)
  31. }
  32. if len(p.Tags) > 0 {
  33. if err := r.SetTags(ctx, p.ID, p.Tags); err != nil {
  34. return err
  35. }
  36. }
  37. if len(p.Features) > 0 {
  38. if err := r.SetFeatures(ctx, p.ID, p.Features); err != nil {
  39. return err
  40. }
  41. }
  42. return nil
  43. }
  44. func (r *PlaceRepo) GetByID(ctx context.Context, id string) (*models.Place, error) {
  45. row := r.pool.QueryRow(ctx,
  46. `SELECT id, type, owner_id, title, description, address,
  47. ST_Y(coordinates::geometry), ST_X(coordinates::geometry),
  48. cover_image, access_info, status, moderation_comment,
  49. rating, reviews_count, hourly_rate, currency, min_hours, booking_url,
  50. created_at, updated_at, published_at, deleted_at
  51. FROM places WHERE id = $1 AND deleted_at IS NULL`, id)
  52. return scanPlace(row)
  53. }
  54. func (r *PlaceRepo) GetByIDWithDetails(ctx context.Context, id string) (*models.Place, error) {
  55. query := `
  56. SELECT p.id, p.type, p.owner_id, p.title, p.description, p.address,
  57. ST_Y(p.coordinates::geometry), ST_X(p.coordinates::geometry),
  58. p.cover_image, p.access_info, p.status, p.moderation_comment,
  59. p.rating, p.reviews_count, p.hourly_rate, p.currency, p.min_hours, p.booking_url,
  60. p.created_at, p.updated_at, p.published_at, p.deleted_at,
  61. COALESCE(json_agg(DISTINCT jsonb_build_object('id', t.id, 'name', t.name, 'category', t.category))
  62. FILTER (WHERE t.id IS NOT NULL), '[]'::json) as tags,
  63. COALESCE(json_agg(DISTINCT jsonb_build_object('id', f.id, 'name', f.name, 'category', f.category, 'icon', f.icon))
  64. FILTER (WHERE f.id IS NOT NULL), '[]'::json) as features
  65. FROM places p
  66. LEFT JOIN place_tags pt ON pt.place_id = p.id
  67. LEFT JOIN tags t ON t.id = pt.tag_id
  68. LEFT JOIN place_features pf ON pf.place_id = p.id
  69. LEFT JOIN features f ON f.id = pf.feature_id
  70. WHERE p.id = $1 AND p.deleted_at IS NULL
  71. GROUP BY p.id`
  72. row := r.pool.QueryRow(ctx, query, id)
  73. var p models.Place
  74. var tagsJSON, featuresJSON []byte
  75. err := row.Scan(
  76. &p.ID, &p.Type, &p.OwnerID, &p.Title, &p.Description, &p.Address,
  77. &p.Lat, &p.Lng,
  78. &p.CoverImage, &p.AccessInfo, &p.Status, &p.ModerationComment,
  79. &p.Rating, &p.ReviewsCount, &p.HourlyRate, &p.Currency, &p.MinHours, &p.BookingURL,
  80. &p.CreatedAt, &p.UpdatedAt, &p.PublishedAt, &p.DeletedAt,
  81. &tagsJSON, &featuresJSON,
  82. )
  83. if err != nil {
  84. if err == pgx.ErrNoRows {
  85. return nil, nil
  86. }
  87. return nil, fmt.Errorf("get place with details: %w", err)
  88. }
  89. if err := json.Unmarshal(tagsJSON, &p.Tags); err != nil {
  90. return nil, fmt.Errorf("unmarshal tags: %w", err)
  91. }
  92. if err := json.Unmarshal(featuresJSON, &p.Features); err != nil {
  93. return nil, fmt.Errorf("unmarshal features: %w", err)
  94. }
  95. return &p, nil
  96. }
  97. func (r *PlaceRepo) List(ctx context.Context, filter models.PlaceFilter) ([]*models.Place, error) {
  98. q := `SELECT p.id, p.type, p.owner_id, p.title, p.description, p.address,
  99. ST_Y(p.coordinates::geometry), ST_X(p.coordinates::geometry),
  100. p.cover_image, p.access_info, p.status, p.moderation_comment,
  101. p.rating, p.reviews_count, p.hourly_rate, p.currency, p.min_hours, p.booking_url,
  102. p.created_at, p.updated_at, p.published_at, p.deleted_at
  103. FROM places p`
  104. args := pgx.NamedArgs{}
  105. joins := ""
  106. if len(filter.TagIDs) > 0 {
  107. joins += ` JOIN place_tags pt ON pt.place_id = p.id`
  108. }
  109. if len(filter.FeatureIDs) > 0 {
  110. joins += ` JOIN place_features pf ON pf.place_id = p.id`
  111. }
  112. // Если есть JOIN-ы, добавляем DISTINCT, чтобы избежать дубликатов мест при нескольких совпадениях
  113. if joins != "" {
  114. q = "SELECT DISTINCT" + q[6:] // заменяем "SELECT" на "SELECT DISTINCT"
  115. }
  116. if filter.Status != "deleted" {
  117. q += ` WHERE p.deleted_at IS NULL`
  118. } else {
  119. q += ` WHERE p.deleted_at IS NOT NULL`
  120. }
  121. if filter.Status != "" { q += ` AND p.status = @status`; args["status"] = filter.Status }
  122. if filter.Type != "" { q += ` AND p.type = @type`; args["type"] = filter.Type }
  123. if filter.OwnerID != "" { q += ` AND p.owner_id = @owner_id`; args["owner_id"] = filter.OwnerID }
  124. if filter.MinRating > 0 { q += ` AND p.rating >= @min_rating`; args["min_rating"] = filter.MinRating }
  125. if filter.PriceMin != nil { q += ` AND p.hourly_rate >= @price_min`; args["price_min"] = *filter.PriceMin }
  126. if filter.PriceMax != nil { q += ` AND p.hourly_rate <= @price_max`; args["price_max"] = *filter.PriceMax }
  127. if filter.Bounds != nil {
  128. q += ` AND ST_Intersects(p.coordinates, ST_MakeEnvelope(@sw_lng, @sw_lat, @ne_lng, @ne_lat, 4326))`
  129. args["sw_lng"] = filter.Bounds.SWLng; args["sw_lat"] = filter.Bounds.SWLat
  130. args["ne_lng"] = filter.Bounds.NELng; args["ne_lat"] = filter.Bounds.NELat
  131. }
  132. if len(filter.TagIDs) > 0 { q += ` AND pt.tag_id = ANY(@tag_ids)`; args["tag_ids"] = filter.TagIDs }
  133. if len(filter.FeatureIDs) > 0 { q += ` AND pf.feature_id = ANY(@feature_ids)`; args["feature_ids"] = filter.FeatureIDs }
  134. // Cursor-based pagination
  135. if filter.Cursor != "" && filter.CursorCreatedAt != nil {
  136. if filter.Sort == "rating" && filter.CursorRating != nil {
  137. q += ` AND (p.rating, p.created_at, p.id) < (@cursor_rating, @cursor_created_at, @cursor_id)`
  138. args["cursor_rating"] = *filter.CursorRating
  139. args["cursor_created_at"] = *filter.CursorCreatedAt
  140. args["cursor_id"] = filter.Cursor
  141. } else {
  142. q += ` AND (p.created_at, p.id) < (@cursor_created_at, @cursor_id)`
  143. args["cursor_created_at"] = *filter.CursorCreatedAt
  144. args["cursor_id"] = filter.Cursor
  145. }
  146. }
  147. if filter.Sort == "rating" {
  148. q += ` ORDER BY p.rating DESC, p.created_at DESC, p.id`
  149. } else if filter.Sort == "distance" && filter.UserLat != nil && filter.UserLng != nil {
  150. q += ` ORDER BY p.coordinates <-> ST_SetSRID(ST_MakePoint(@user_lng, @user_lat), 4326), p.created_at DESC, p.id`
  151. args["user_lng"] = *filter.UserLng; args["user_lat"] = *filter.UserLat
  152. } else {
  153. q += ` ORDER BY p.created_at DESC, p.id`
  154. }
  155. q += ` LIMIT @lim`
  156. args["lim"] = filter.Limit() + 1 // fetch one extra to detect hasMore
  157. rows, err := r.pool.Query(ctx, q, args)
  158. if err != nil {
  159. return nil, fmt.Errorf("list places: %w", err)
  160. }
  161. defer rows.Close()
  162. var places []*models.Place
  163. for rows.Next() {
  164. p, err := scanPlace(rows)
  165. if err != nil {
  166. return nil, err
  167. }
  168. places = append(places, p)
  169. }
  170. return places, nil
  171. }
  172. func (r *PlaceRepo) Update(ctx context.Context, p *models.Place) error {
  173. _, err := r.pool.Exec(ctx,
  174. `UPDATE places SET title=$1, description=$2, address=$3,
  175. coordinates=ST_SetSRID(ST_MakePoint($4, $5), 4326),
  176. cover_image=$6, access_info=$7, status=$8, hourly_rate=$9, currency=$10, min_hours=$11,
  177. booking_url=$12, updated_at=now()
  178. WHERE id=$13 AND deleted_at IS NULL`,
  179. p.Title, p.Description, p.Address,
  180. p.Lng, p.Lat,
  181. p.CoverImage, p.AccessInfo, p.Status,
  182. p.HourlyRate, p.Currency, p.MinHours, p.BookingURL,
  183. p.ID)
  184. return err
  185. }
  186. func (r *PlaceRepo) UpdateStatus(ctx context.Context, id, status, comment string) error {
  187. _, err := r.pool.Exec(ctx,
  188. `UPDATE places SET status=$1, moderation_comment=$2, updated_at=now(),
  189. published_at = CASE WHEN $3 THEN now() ELSE published_at END
  190. WHERE id=$4 AND deleted_at IS NULL`,
  191. status, comment, status == "published", id)
  192. return err
  193. }
  194. func (r *PlaceRepo) SoftDelete(ctx context.Context, id string) error {
  195. _, err := r.pool.Exec(ctx,
  196. `UPDATE places SET status='deleted', deleted_at=now() WHERE id=$1 AND deleted_at IS NULL`, id)
  197. return err
  198. }
  199. func (r *PlaceRepo) HardDelete(ctx context.Context, id string) error {
  200. _, err := r.pool.Exec(ctx, `DELETE FROM places WHERE id=$1`, id)
  201. return err
  202. }
  203. func (r *PlaceRepo) Restore(ctx context.Context, id string) error {
  204. _, err := r.pool.Exec(ctx,
  205. `UPDATE places SET status='published', deleted_at=NULL, published_at=now(), updated_at=now()
  206. WHERE id=$1 AND deleted_at IS NOT NULL`, id)
  207. return err
  208. }
  209. func (r *PlaceRepo) GetByIDRaw(ctx context.Context, id string) (*models.Place, error) {
  210. row := r.pool.QueryRow(ctx,
  211. `SELECT id, type, owner_id, title, description, address,
  212. ST_Y(coordinates::geometry), ST_X(coordinates::geometry),
  213. cover_image, access_info, status, moderation_comment,
  214. rating, reviews_count, hourly_rate, currency, min_hours, booking_url,
  215. created_at, updated_at, published_at, deleted_at
  216. FROM places WHERE id = $1`, id)
  217. return scanPlace(row)
  218. }
  219. func (r *PlaceRepo) GetPlaceImages(ctx context.Context, placeID string) ([]models.PlaceImage, error) {
  220. rows, err := r.pool.Query(ctx,
  221. `SELECT id, place_id, url, alt, sort_order, is_cover FROM place_images WHERE place_id = $1`,
  222. placeID)
  223. if err != nil {
  224. return nil, err
  225. }
  226. defer rows.Close()
  227. var images []models.PlaceImage
  228. for rows.Next() {
  229. var img models.PlaceImage
  230. if err := rows.Scan(&img.ID, &img.PlaceID, &img.URL, &img.Alt, &img.SortOrder, &img.IsCover); err != nil {
  231. return nil, err
  232. }
  233. images = append(images, img)
  234. }
  235. return images, nil
  236. }
  237. func (r *PlaceRepo) SetTags(ctx context.Context, placeID string, tags []models.Tag) error {
  238. tx, err := r.pool.Begin(ctx)
  239. if err != nil {
  240. return err
  241. }
  242. defer tx.Rollback(ctx)
  243. _, err = tx.Exec(ctx, `DELETE FROM place_tags WHERE place_id = $1`, placeID)
  244. if err != nil {
  245. return err
  246. }
  247. for _, tag := range tags {
  248. _, err = tx.Exec(ctx,
  249. `INSERT INTO place_tags (place_id, tag_id) VALUES ($1, $2)`,
  250. placeID, tag.ID)
  251. if err != nil {
  252. return err
  253. }
  254. }
  255. return tx.Commit(ctx)
  256. }
  257. func (r *PlaceRepo) SetFeatures(ctx context.Context, placeID string, features []models.Feature) error {
  258. tx, err := r.pool.Begin(ctx)
  259. if err != nil {
  260. return err
  261. }
  262. defer tx.Rollback(ctx)
  263. _, err = tx.Exec(ctx, `DELETE FROM place_features WHERE place_id = $1`, placeID)
  264. if err != nil {
  265. return err
  266. }
  267. for _, f := range features {
  268. _, err = tx.Exec(ctx,
  269. `INSERT INTO place_features (place_id, feature_id) VALUES ($1, $2)`,
  270. placeID, f.ID)
  271. if err != nil {
  272. return err
  273. }
  274. }
  275. return tx.Commit(ctx)
  276. }
  277. func (r *PlaceRepo) GetTags(ctx context.Context, placeID string) ([]models.Tag, error) {
  278. rows, err := r.pool.Query(ctx,
  279. `SELECT t.id, t.name, t.category FROM tags t
  280. JOIN place_tags pt ON pt.tag_id = t.id
  281. WHERE pt.place_id = $1`, placeID)
  282. if err != nil {
  283. return nil, err
  284. }
  285. defer rows.Close()
  286. var tags []models.Tag
  287. for rows.Next() {
  288. var t models.Tag
  289. if err := rows.Scan(&t.ID, &t.Name, &t.Category); err != nil {
  290. return nil, err
  291. }
  292. tags = append(tags, t)
  293. }
  294. return tags, nil
  295. }
  296. func (r *PlaceRepo) GetFeatures(ctx context.Context, placeID string) ([]models.Feature, error) {
  297. rows, err := r.pool.Query(ctx,
  298. `SELECT f.id, f.name, f.category, f.icon FROM features f
  299. JOIN place_features pf ON pf.feature_id = f.id
  300. WHERE pf.place_id = $1`, placeID)
  301. if err != nil {
  302. return nil, err
  303. }
  304. defer rows.Close()
  305. var features []models.Feature
  306. for rows.Next() {
  307. var f models.Feature
  308. if err := rows.Scan(&f.ID, &f.Name, &f.Category, &f.Icon); err != nil {
  309. return nil, err
  310. }
  311. features = append(features, f)
  312. }
  313. return features, nil
  314. }
  315. func (r *PlaceRepo) GetTagsBatch(ctx context.Context, placeIDs []string) (map[string][]models.Tag, error) {
  316. if len(placeIDs) == 0 {
  317. return map[string][]models.Tag{}, nil
  318. }
  319. rows, err := r.pool.Query(ctx,
  320. `SELECT pt.place_id, t.id, t.name, t.category FROM tags t
  321. JOIN place_tags pt ON pt.tag_id = t.id
  322. WHERE pt.place_id = ANY($1)`, placeIDs)
  323. if err != nil {
  324. return nil, err
  325. }
  326. defer rows.Close()
  327. result := make(map[string][]models.Tag)
  328. for rows.Next() {
  329. var placeID string
  330. var t models.Tag
  331. if err := rows.Scan(&placeID, &t.ID, &t.Name, &t.Category); err != nil {
  332. return nil, err
  333. }
  334. result[placeID] = append(result[placeID], t)
  335. }
  336. return result, nil
  337. }
  338. func (r *PlaceRepo) GetFeaturesBatch(ctx context.Context, placeIDs []string) (map[string][]models.Feature, error) {
  339. if len(placeIDs) == 0 {
  340. return map[string][]models.Feature{}, nil
  341. }
  342. rows, err := r.pool.Query(ctx,
  343. `SELECT pf.place_id, f.id, f.name, f.category, f.icon FROM features f
  344. JOIN place_features pf ON pf.feature_id = f.id
  345. WHERE pf.place_id = ANY($1)`, placeIDs)
  346. if err != nil {
  347. return nil, err
  348. }
  349. defer rows.Close()
  350. result := make(map[string][]models.Feature)
  351. for rows.Next() {
  352. var placeID string
  353. var f models.Feature
  354. if err := rows.Scan(&placeID, &f.ID, &f.Name, &f.Category, &f.Icon); err != nil {
  355. return nil, err
  356. }
  357. result[placeID] = append(result[placeID], f)
  358. }
  359. return result, nil
  360. }
  361. func scanPlace(row interface{ Scan(dest ...any) error }) (*models.Place, error) {
  362. var p models.Place
  363. err := row.Scan(
  364. &p.ID, &p.Type, &p.OwnerID, &p.Title, &p.Description, &p.Address,
  365. &p.Lat, &p.Lng,
  366. &p.CoverImage, &p.AccessInfo, &p.Status, &p.ModerationComment,
  367. &p.Rating, &p.ReviewsCount, &p.HourlyRate, &p.Currency, &p.MinHours, &p.BookingURL,
  368. &p.CreatedAt, &p.UpdatedAt, &p.PublishedAt, &p.DeletedAt,
  369. )
  370. if err != nil {
  371. if err == pgx.ErrNoRows {
  372. return nil, nil
  373. }
  374. return nil, err
  375. }
  376. return &p, nil
  377. }