bookings.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. // Package repository
  2. package repository
  3. import (
  4. "context"
  5. "errors"
  6. "fmt"
  7. "math"
  8. "github.com/jackc/pgx/v5"
  9. "github.com/jackc/pgx/v5/pgxpool"
  10. "gogs.fxtmmsk.ru/foxtime/photoplaces/backend/internal/models"
  11. )
  12. var ErrPlaceNotFound = errors.New("place not found")
  13. type BookingRepo struct {
  14. pool *pgxpool.Pool
  15. }
  16. func NewBookingRepo(pool *pgxpool.Pool) *BookingRepo {
  17. return &BookingRepo{pool: pool}
  18. }
  19. func (r *BookingRepo) Create(ctx context.Context, b *models.Booking) error {
  20. tx, err := r.pool.Begin(ctx)
  21. if err != nil {
  22. return fmt.Errorf("begin tx: %w", err)
  23. }
  24. defer tx.Rollback(ctx)
  25. var hourlyRate *int
  26. var placeStatus string
  27. err = tx.QueryRow(ctx,
  28. `SELECT hourly_rate, currency, status FROM places WHERE id = $1 AND deleted_at IS NULL FOR UPDATE`,
  29. b.PlaceID).Scan(&hourlyRate, &b.Currency, &placeStatus)
  30. if err != nil {
  31. if errors.Is(err, pgx.ErrNoRows) {
  32. return ErrPlaceNotFound
  33. }
  34. return fmt.Errorf("lock place: %w", err)
  35. }
  36. if placeStatus != "published" {
  37. return fmt.Errorf("place is not available for booking")
  38. }
  39. if hourlyRate != nil {
  40. hours := math.Ceil(b.EndTime.Sub(b.StartTime).Hours())
  41. if hours < 1 {
  42. hours = 1
  43. }
  44. total := *hourlyRate * int(hours)
  45. b.TotalPrice = &total
  46. }
  47. err = tx.QueryRow(ctx,
  48. `INSERT INTO bookings (place_id, user_id, start_time, end_time, status, total_price, currency, comment)
  49. VALUES ($1, $2, $3, $4, 'pending', $5, $6, $7)
  50. RETURNING id, created_at, updated_at`,
  51. b.PlaceID, b.UserID, b.StartTime, b.EndTime, b.TotalPrice, b.Currency, b.Comment,
  52. ).Scan(&b.ID, &b.CreatedAt, &b.UpdatedAt)
  53. if err != nil {
  54. return fmt.Errorf("insert booking: %w", err)
  55. }
  56. return tx.Commit(ctx)
  57. }
  58. func (r *BookingRepo) GetByID(ctx context.Context, id string) (*models.Booking, error) {
  59. row := r.pool.QueryRow(ctx,
  60. `SELECT id, place_id, user_id, start_time, end_time, status, total_price, currency, comment,
  61. created_at, updated_at
  62. FROM bookings WHERE id = $1`, id)
  63. var b models.Booking
  64. err := row.Scan(&b.ID, &b.PlaceID, &b.UserID, &b.StartTime, &b.EndTime,
  65. &b.Status, &b.TotalPrice, &b.Currency, &b.Comment, &b.CreatedAt, &b.UpdatedAt)
  66. if err != nil {
  67. if err == pgx.ErrNoRows {
  68. return nil, nil
  69. }
  70. return nil, err
  71. }
  72. return &b, nil
  73. }
  74. func (r *BookingRepo) ListByUser(ctx context.Context, userID string) ([]*models.Booking, error) {
  75. rows, err := r.pool.Query(ctx,
  76. `SELECT id, place_id, user_id, start_time, end_time, status, total_price, currency, comment,
  77. created_at, updated_at
  78. FROM bookings WHERE user_id = $1 ORDER BY start_time DESC`, userID)
  79. if err != nil {
  80. return nil, err
  81. }
  82. defer rows.Close()
  83. return scanBookings(rows)
  84. }
  85. func (r *BookingRepo) ListByPlace(ctx context.Context, placeID string) ([]*models.Booking, error) {
  86. rows, err := r.pool.Query(ctx,
  87. `SELECT id, place_id, user_id, start_time, end_time, status, total_price, currency, comment,
  88. created_at, updated_at
  89. FROM bookings WHERE place_id = $1 ORDER BY start_time DESC`, placeID)
  90. if err != nil {
  91. return nil, err
  92. }
  93. defer rows.Close()
  94. return scanBookings(rows)
  95. }
  96. func (r *BookingRepo) UpdateStatusIfPending(ctx context.Context, id, status string) (bool, error) {
  97. tag, err := r.pool.Exec(ctx,
  98. `UPDATE bookings SET status=$1, updated_at=now() WHERE id=$2 AND status='pending'`, status, id)
  99. if err != nil {
  100. return false, fmt.Errorf("update status if pending: %w", err)
  101. }
  102. return tag.RowsAffected() > 0, nil
  103. }
  104. func (r *BookingRepo) GetPlaceMinHours(ctx context.Context, placeID string) (int, error) {
  105. var minHours int
  106. err := r.pool.QueryRow(ctx,
  107. `SELECT min_hours FROM places WHERE id = $1 AND deleted_at IS NULL`, placeID).Scan(&minHours)
  108. if err != nil {
  109. if errors.Is(err, pgx.ErrNoRows) {
  110. return 0, ErrPlaceNotFound
  111. }
  112. return 0, fmt.Errorf("get place min_hours: %w", err)
  113. }
  114. return minHours, nil
  115. }
  116. func scanBookings(rows pgx.Rows) ([]*models.Booking, error) {
  117. var bookings []*models.Booking
  118. for rows.Next() {
  119. var b models.Booking
  120. if err := rows.Scan(&b.ID, &b.PlaceID, &b.UserID, &b.StartTime, &b.EndTime,
  121. &b.Status, &b.TotalPrice, &b.Currency, &b.Comment, &b.CreatedAt, &b.UpdatedAt); err != nil {
  122. return nil, err
  123. }
  124. bookings = append(bookings, &b)
  125. }
  126. return bookings, nil
  127. }