guesty-client 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +59 -1
  3. data/README.md +2 -3
  4. data/lib/guesty/access_tokens/upsert.rb +8 -34
  5. data/lib/guesty/api_error.rb +8 -16
  6. data/lib/guesty/client.rb +6 -12
  7. data/lib/guesty/config.rb +1 -16
  8. data/lib/guesty/conversations/attachments/index.rb +2 -6
  9. data/lib/guesty/conversations/index.rb +14 -32
  10. data/lib/guesty/conversations/messages/reply.rb +2 -24
  11. data/lib/guesty/conversations/posts/index.rb +5 -22
  12. data/lib/guesty/conversations/posts/since.rb +0 -1
  13. data/lib/guesty/conversations/search.rb +2 -5
  14. data/lib/guesty/conversations/show.rb +1 -10
  15. data/lib/guesty/conversations.rb +5 -1
  16. data/lib/guesty/error.rb +0 -4
  17. data/lib/guesty/guest_folio/invoice_items/index.rb +2 -6
  18. data/lib/guesty/guests/profiles/create.rb +1 -5
  19. data/lib/guesty/guests/profiles/show.rb +1 -8
  20. data/lib/guesty/guests/profiles/update.rb +2 -7
  21. data/lib/guesty/homes/calendars/show.rb +29 -68
  22. data/lib/guesty/homes/search.rb +4 -23
  23. data/lib/guesty/memory_rate_limiter.rb +0 -3
  24. data/lib/guesty/memory_token_store.rb +0 -8
  25. data/lib/guesty/operation.rb +5 -3
  26. data/lib/guesty/payments/index.rb +14 -0
  27. data/lib/guesty/payments/record.rb +59 -0
  28. data/lib/guesty/rate_limiter_middleware.rb +2 -15
  29. data/lib/guesty/reservations/accommodation_fare/update.rb +4 -5
  30. data/lib/guesty/reservations/approve.rb +2 -8
  31. data/lib/guesty/reservations/booking_date/update.rb +19 -0
  32. data/lib/guesty/reservations/confirmation_code/update.rb +22 -0
  33. data/lib/guesty/reservations/create.rb +1 -8
  34. data/lib/guesty/reservations/custom_fields/update.rb +2 -11
  35. data/lib/guesty/reservations/dates/update.rb +2 -8
  36. data/lib/guesty/reservations/decline.rb +1 -11
  37. data/lib/guesty/reservations/guests/update.rb +43 -0
  38. data/lib/guesty/reservations/index.rb +18 -0
  39. data/lib/guesty/reservations/pre_approve.rb +2 -8
  40. data/lib/guesty/reservations/recover.rb +3 -11
  41. data/lib/guesty/reservations/relocate.rb +18 -0
  42. data/lib/guesty/reservations/reviews/extractors/airbnb.rb +0 -1
  43. data/lib/guesty/reservations/reviews/index.rb +17 -42
  44. data/lib/guesty/reservations/search.rb +58 -35
  45. data/lib/guesty/reservations/show.rb +7 -16
  46. data/lib/guesty/reservations/source/update.rb +19 -0
  47. data/lib/guesty/reservations/status/update.rb +1 -3
  48. data/lib/guesty/reviews/respond.rb +1 -3
  49. data/lib/guesty/version.rb +1 -1
  50. data/lib/guesty/views/create.rb +1 -5
  51. data/lib/guesty/views/update.rb +1 -19
  52. data/lib/guesty/webhooks/create.rb +1 -7
  53. data/lib/guesty/webhooks/index.rb +1 -7
  54. data/lib/guesty/webhooks/signatures/verify.rb +3 -6
  55. data/lib/guesty/webhooks/sync.rb +0 -3
  56. data/lib/guesty/webhooks/update.rb +1 -7
  57. data/lib/guesty.rb +8 -4
  58. data/sig/guesty.rbs +52 -30
  59. metadata +9 -5
  60. data/lib/guesty/reservations/flags/update.rb +0 -33
  61. data/lib/guesty/reservations/payments/create.rb +0 -72
  62. data/lib/guesty/reservations/stays/update.rb +0 -42
  63. data/lib/guesty/reservations/update.rb +0 -19
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 83257fa001c6c49e93fc8e82a589f7021c5924e79aa37c4aba1ac39016190b91
4
- data.tar.gz: 47f958e92a9567eaea516c9e65e1842fbf801e0f2bf298156f043e90ace89abc
3
+ metadata.gz: abb486d40a4bf8d831a35d7096142a0abb0203bc7ebf330d7c5be0f28d720c56
4
+ data.tar.gz: b6c5ceeda67b8a09f4da6785e0ba16a6903860337705cd1412aa8af7258d16f5
5
5
  SHA512:
6
- metadata.gz: b7d52343654868afa7b48544b81f088214c7201c89f408ea24104ad8c9fb7642466b53aab13be87e4d56cba4dada62578871c322dddc778255df010023b0b79b
7
- data.tar.gz: faec56e53c7a5477e98a7db05c5d4156ed0e096764793a5a23ccd68ba93d50a0da102ad9cb7ce16c699e2cb30b9ae272a53c7960582d47474d7e9a453192fdaf
6
+ metadata.gz: 4f16f55de71dc90340172b65eb1cabd589387e67cdd5b459ffea7cb9a43a3f6624de1bcf5663c707d81e1fc4b32247ed8a10e0ed7551d3d99e765a809d9f1315
7
+ data.tar.gz: 9ad6eb5ddac5b0f54183a8d4a7a5de6aa4708729d8070f2e8d3194ec271e2ece0d2e8da09698432c2b63543e012c172c6350242eea825396cb32e10d8e1e01c1
data/CHANGELOG.md CHANGED
@@ -2,6 +2,63 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.2.0] - 2026-11-10
6
+
7
+ Migrates the reservation surface off the legacy `/reservations` resources, which Guesty retires on
8
+ 2027-03-01 (<https://open-api-docs.guesty.com/docs/reservation-migration>), and moves the pieces that spoke
9
+ Guestit's own vocabulary back into the host.
10
+
11
+ ### Breaking
12
+
13
+ - `Reservations::Search` now reads `GET /reservations-v3/search`: the `fields:` keyword is gone (the payload
14
+ is fixed and lean, keyed by `reservationId`; guest, money and conversationId are not embedded) and the
15
+ result is `{ results:, pagination: }` with `pagination.hasMore` instead of `count`. Filters are
16
+ `status`, `confirmation_code`, `listing_id`, `source` (one value or an Array) and `check_in`, `check_out`,
17
+ `created_at` (a Ruby Range); `ids`, `updated_at` and `conversation_id` have no v3 equivalent.
18
+ - `Reservations::Show` now reads `GET /reservations-v3`: the `fields:` keyword is gone, and an unknown id
19
+ fails with a fatal `Guesty::Error` instead of a 404 `Guesty::ApiError`. The v3 reservation embeds no
20
+ `money`: read `hostPayout`, `totalPaid` and `currency` from `Payments::Index`.
21
+ - `Reservations::Update` and `Reservations::Stays::Update` are removed. The broad `PUT /reservations/{id}`
22
+ is replaced by one endpoint per operation: `Status::Update`/`Status::Cancel`, `Dates::Update`,
23
+ `CustomFields::Update` (all unchanged) plus the new `Guests::Update`, `ConfirmationCode::Update`,
24
+ `Source::Update`, `BookingDate::Update` and `Relocate`.
25
+ - `Reservations::AccommodationFare::Update` reads the current fare from `GuestFolio::InvoiceItems::Index`
26
+ instead of the legacy reservation's `money.invoiceItems`.
27
+ - Host vocabulary moves out of the gem, into the host:
28
+ - `Reservations::Payments::Create` is removed. It was Guestit's idempotent record of a Stripe payment;
29
+ compose `Payments::Index` and `Payments::Record` instead.
30
+ - `Reservations::Flags::Update` and `config.custom_fields` are removed. Pass the account's field ids to
31
+ `Reservations::CustomFields::Update`.
32
+ - `config.sync_guest_and_reservation_changes` and `Guesty.sync_guest_and_reservation_changes?` are
33
+ removed. The gem never read the flag.
34
+ - `Conversations::Messages::Reply::BOOKING_MODULE_TYPES` and `.module_type_for` are removed. They mapped
35
+ the host's channel names to Guesty module types.
36
+ - `Guesty::MemoryTokenStore#clear` is removed.
37
+
38
+ ### Changed
39
+
40
+ - Every operation reads its response through one private `Operation#request`, which returns the parsed body
41
+ and raises the `ApiError` that `#call` turns into the `Failure`. The failures are the same, with one
42
+ exception: `Conversations::Index` now fails with the `Guesty::ApiError` itself instead of re-wrapping its
43
+ message in a plain `Guesty::Error`.
44
+ - `Reservations::Show` reads through `Reservations::Index`.
45
+ - `Conversations.summary(conversation)` builds the `{ id:, reservations: }` hash that `Conversations::Index`,
46
+ `Search` and `Show` return.
47
+
48
+ ### Added
49
+
50
+ - `Reservations::Index`: up to 10 reservations by id from `GET /reservations-v3`.
51
+ - `Reservations::Guests::Update`: `PUT /reservations-v3/{id}/guests` (guestsCount + numberOfGuests).
52
+ - `Reservations::ConfirmationCode::Update`: `PUT /reservations-v3/{id}/confirmation-code`.
53
+ - `Reservations::Source::Update`: `PUT /reservations-v3/{id}/source`.
54
+ - `Reservations::BookingDate::Update`: `PUT /reservations-v3/{id}/booking-date` (the real-world booking
55
+ date; `createdAt` stays canonical for Guesty).
56
+ - `Reservations::Relocate`: `PUT /reservations-v3/{id}/relocate` (change the listing).
57
+ - `Payments::Index`: `GET /payments` — a reservation's payments with `totalPaid`, `balanceDue` and
58
+ `isFullyPaid`.
59
+ - `Payments::Record`: `POST /payments/record` — record an offline payment (`shouldBePaidAt`, method
60
+ `RECORDED_CASH` unless given).
61
+
5
62
  ## [0.1.0] - 2026-11-08
6
63
 
7
64
  First release as `guesty-client`, extracted from the Guesty integration Guestit runs in production. The specs are
@@ -30,5 +87,6 @@ that integration's provider specs, ported with their recorded VCR cassettes.
30
87
  - Webhooks: `Index`, `Create`, `Update`, `Sync`, `Signatures::Verify` for Svix signatures.
31
88
  - Views: `Create`, `Update`.
32
89
 
33
- [Unreleased]: https://github.com/guestitab/guesty-client/compare/v0.1.0...staging
90
+ [Unreleased]: https://github.com/guestitab/guesty-client/compare/v0.2.0...staging
91
+ [0.2.0]: https://github.com/guestitab/guesty-client/compare/v0.1.0...v0.2.0
34
92
  [0.1.0]: https://github.com/guestitab/guesty-client/releases/tag/v0.1.0
data/README.md CHANGED
@@ -42,7 +42,6 @@ end
42
42
  | `token_store` | `Guesty::MemoryTokenStore` | Holds one access token per credential slot. |
43
43
  | `rate_limiter` | `Guesty::MemoryRateLimiter` | Counts requests per slot and window. |
44
44
  | `slot_picker` | first slot | `->(slots, priority) { slot }`, called when a lane has several credentials. |
45
- | `custom_fields` | `{}` | Account custom field ids by flag name, read by `Reservations::Flags::Update`. |
46
45
  | `default_currency` | `nil` | When set, `Homes::Calendars::Show` refuses a calendar priced in another currency. |
47
46
  | `base_url` | `https://open-api.guesty.com/v1/` | API root. |
48
47
 
@@ -94,10 +93,10 @@ A lane with several credentials gets one slot per credential. Each slot has its
94
93
  Operations live under `Guesty::<Resource>::<Action>`. Build a fresh instance for every call:
95
94
 
96
95
  ```ruby
97
- result = Guesty::Reservations::Show.new.call(reservation_id: '67ebc9c7c5904c0010502f89', fields: %w[status money])
96
+ result = Guesty::Reservations::Show.new.call(reservation_id: '67ebc9c7c5904c0010502f89')
98
97
 
99
98
  if result.success?
100
- result.value! # => { _id: '67ebc9c7c5904c0010502f89', status: 'confirmed', money: { ... } }
99
+ result.value! # => { _id: '67ebc9c7c5904c0010502f89', status: 'confirmed', stay: [...], ... }
101
100
  else
102
101
  result.failure # => a Guesty::Error or a Faraday::Error
103
102
  end
@@ -1,9 +1,5 @@
1
1
  module Guesty
2
2
  module AccessTokens
3
- # Ensures a live access token for the current credential slot: reuse the
4
- # stored one, else mint one. Persistence, caching and expiry policy live in
5
- # the injected token store (Guesty.config.token_store).
6
- #
7
3
  # Guesty mints only 5 access tokens per client id within 24 hours and
8
4
  # answers 429 to everything after, so a token must never be discarded.
9
5
  class Upsert
@@ -13,14 +9,9 @@ module Guesty
13
9
 
14
10
  # @rbs () -> Dry::Monads::Result[untyped]
15
11
  def call
16
- if (token = store.read(Guesty.current_slot[:key]))
17
- return Success(token)
18
- end
19
-
20
- response = request_access_token
21
- raise ApiError, response unless Guesty.successful_response?(response)
12
+ slot = Guesty.current_slot
22
13
 
23
- Success(save_token(response))
14
+ Success(store.read(slot[:key]) || mint(slot))
24
15
  end
25
16
 
26
17
  private
@@ -29,32 +20,15 @@ module Guesty
29
20
  Guesty.config.token_store
30
21
  end
31
22
 
32
- def client_id
33
- Guesty.current_slot[:client_id]
34
- end
35
-
36
- def client_secret
37
- Guesty.current_slot[:secret]
38
- end
39
-
40
- def request_access_token
41
- Guesty.connection(url: OAUTH_ENDPOINT, skip_auth: true).post do |req|
23
+ # @rbs (Guesty::slot slot) -> untyped
24
+ def mint(slot)
25
+ response = Guesty.connection(url: OAUTH_ENDPOINT, skip_auth: true).post do |req|
42
26
  req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
43
- req.body = {
44
- grant_type: 'client_credentials',
45
- scope: 'open-api',
46
- client_secret:,
47
- client_id:
48
- }
27
+ req.body = { grant_type: 'client_credentials', scope: 'open-api', client_secret: slot[:secret], client_id: slot[:client_id] }
49
28
  end
50
- end
29
+ raise ApiError, response unless Guesty.successful_response?(response)
51
30
 
52
- def save_token(response)
53
- store.save(
54
- slot_key: Guesty.current_slot[:key],
55
- access_token: response.body[:access_token],
56
- expires_at: response.body[:expires_in].seconds.from_now
57
- )
31
+ store.save(slot_key: slot[:key], access_token: response.body[:access_token], expires_at: response.body[:expires_in].seconds.from_now)
58
32
  end
59
33
  end
60
34
  end
@@ -1,19 +1,17 @@
1
1
  module Guesty
2
- # A rejected Guesty response. Carries the response and its parsed body, and
3
- # classifies transience so callers can tell a retryable glitch from a write
4
- # that never landed (see Guesty.unapplied? and Guesty.delivery_unknown?).
5
2
  class ApiError < Error
6
- GLITCH_MESSAGES = [
3
+ GLITCH_MESSAGES = Regexp.union(
7
4
  /An invalid response was received from the upstream server/,
8
5
  /Forbidden err/,
9
6
  /Reservation Meta not found/,
10
7
  /Write conflict during plan execution/,
11
8
  /You don't have permission to access, please contact Guesty support/
12
- ].freeze
9
+ ) #: ::Regexp
13
10
 
14
11
  RETRYABLE_NON_DELIVERY_STATUSES = [401, 403, 429].freeze #: ::Array[::Integer]
15
12
  PERMANENT_REJECTION_STATUSES = [400, 404, 405, 409, 410, 415, 422].freeze #: ::Array[::Integer]
16
13
  UPSTREAM_STATUS = /\ARequest failed with status code (\d{3})\z/ #: ::Regexp
14
+ ERROR_PATHS = [%i[error data], %i[error message], [:message], [:data], [:error], [:code]].freeze #: ::Array[::Array[::Symbol]]
17
15
 
18
16
  attr_reader :raw_body, :response
19
17
 
@@ -25,18 +23,18 @@ module Guesty
25
23
  super(error_message.to_s.presence || response.status.to_s)
26
24
  end
27
25
 
26
+ # Guesty tunnels errors through HTTP 200 bodies and relays upstream ones in the message.
28
27
  # @rbs () -> Integer
29
28
  def status
30
29
  body_status = @raw_body[:status] if @raw_body.is_a?(Hash)
31
- parsed_status = Integer(body_status, exception: false) || Integer(error_message.to_s[UPSTREAM_STATUS, 1], exception: false)
30
+ parsed_status = Integer(body_status, exception: false) || Integer(message[UPSTREAM_STATUS, 1], exception: false)
32
31
 
33
32
  parsed_status && parsed_status >= 300 ? parsed_status : @response.status
34
33
  end
35
34
 
35
+ # @rbs () -> bool
36
36
  def guesty_glitch?
37
- GLITCH_MESSAGES.any? do |message|
38
- error_message.to_s =~ message
39
- end
37
+ GLITCH_MESSAGES.match?(message)
40
38
  end
41
39
 
42
40
  # @rbs () -> bool
@@ -60,13 +58,7 @@ module Guesty
60
58
  def error_message
61
59
  return @raw_body unless @raw_body.respond_to?(:dig)
62
60
 
63
- error_paths = [%i[error data], %i[error message], :message, :data, :error, :code]
64
-
65
- error_message = error_paths.find do |path|
66
- value = path.is_a?(Array) ? @raw_body.dig(*path) : @raw_body[path]
67
- break value if value.present?
68
- end
69
-
61
+ error_message = ERROR_PATHS.lazy.map { |path| @raw_body.dig(*path) }.find(&:present?)
70
62
  error_message.is_a?(Array) ? error_message.join(', ') : error_message || @raw_body
71
63
  end
72
64
  end
data/lib/guesty/client.rb CHANGED
@@ -37,15 +37,14 @@ module Guesty
37
37
  Fiber[:guesty__slot] = pick_slot(current_priority)
38
38
 
39
39
  http = connection(timeout:)
40
- response = params.present? ? http.send(request_method, path, params) : http.send(request_method, path)
41
- result = successful_response?(response) ? Success(response) : Failure(ApiError.new(response))
40
+ response = params.present? ? http.public_send(request_method, path, params) : http.public_send(request_method, path)
41
+ return Success(response) if successful_response?(response)
42
42
 
43
- if retries.positive? && result.failure? && result.failure.guesty_glitch?
44
- sleep(1.0)
45
- result = do_request(request_method, path, params, retries: (retries - 1), timeout:)
46
- end
43
+ error = ApiError.new(response)
44
+ return Failure(error) unless retries.positive? && error.guesty_glitch?
47
45
 
48
- result
46
+ sleep(1.0)
47
+ do_request(request_method, path, params, retries: retries - 1, timeout:)
49
48
  end
50
49
 
51
50
  # @rbs (::Symbol priority) { (?) -> untyped } -> untyped
@@ -92,11 +91,6 @@ module Guesty
92
91
  config.credentials[:webhook_key]
93
92
  end
94
93
 
95
- # @rbs () -> bool
96
- def self.sync_guest_and_reservation_changes?
97
- !!config.sync_guest_and_reservation_changes
98
- end
99
-
100
94
  # @rbs (::Symbol priority) -> slot
101
95
  def self.pick_slot(priority)
102
96
  slots = token_slots(priority)
data/lib/guesty/config.rb CHANGED
@@ -1,29 +1,14 @@
1
1
  module Guesty
2
- # Injected by the host app (see the Guesty.configure initializer): the API
3
- # credentials per priority lane, the webhook signing key, a token store, a
4
- # rate limiter and a slot picker. Keeping these out of the gem is what makes
5
- # it host-agnostic.
6
- #
7
- # credentials maps each priority to its client credentials, plus webhook_key:
8
- #
9
- # {
10
- # default: [{ client_id: '...', secret: '...' }, ...],
11
- # high: [{ client_id: '...', secret: '...' }],
12
- # webhook_key: 'whsec_...'
13
- # }
14
2
  class Config
15
- attr_accessor :credentials, :token_store, :rate_limiter, :slot_picker, :base_url, :sync_guest_and_reservation_changes, :custom_fields,
16
- :default_currency
3
+ attr_accessor :credentials, :token_store, :rate_limiter, :slot_picker, :base_url, :default_currency
17
4
 
18
5
  def initialize
19
6
  @base_url = BASE_URL
20
7
  @credentials = {}
21
- @custom_fields = {}
22
8
  @default_currency = nil
23
9
  @token_store = MemoryTokenStore.new
24
10
  @rate_limiter = MemoryRateLimiter.new
25
11
  @slot_picker = ->(slots, _priority) { slots.first }
26
- @sync_guest_and_reservation_changes = false
27
12
  end
28
13
  end
29
14
  end
@@ -1,8 +1,7 @@
1
1
  module Guesty
2
2
  module Conversations
3
3
  module Attachments
4
- # Trades attachment storage keys for signed URLs (they expire after about
5
- # an hour). Keys that are already links pass through unchanged.
4
+ # Signed URLs expire after about an hour.
6
5
  class Index
7
6
  include Guesty::Operation
8
7
 
@@ -18,10 +17,7 @@ module Guesty
18
17
  urls = links.index_with(&:itself)
19
18
 
20
19
  storage_keys.each_slice(BATCH_SIZE) do |batch|
21
- response = Guesty.do_request :get, 'communication/conversations/get-attachments', { keys: batch }
22
- return response unless response.success?
23
-
24
- urls.merge!(normalize_response(batch, response.value!.body))
20
+ urls.merge!(normalize_response(batch, request(:get, 'communication/conversations/get-attachments', { keys: batch })))
25
21
  end
26
22
 
27
23
  Success(urls)
@@ -9,49 +9,31 @@ module Guesty
9
9
 
10
10
  # @rbs (since: ::Time) -> Dry::Monads::Result[::Array[::Hash[::Symbol, untyped]]]
11
11
  def call(since:)
12
- results = collect_updated(since)
13
-
14
- Success(results)
15
- end
16
-
17
- private
18
-
19
- def collect_updated(since)
20
- results = [] #: ::Array[untyped]
21
- cursor_after = nil
12
+ conversations = [] #: ::Array[untyped]
13
+ cursor = nil
22
14
 
23
15
  MAX_PAGES.times do
24
- data = fetch_page(cursor_after)
25
- page = data[:conversations].map { |conversation| normalize(conversation) }
26
- results.concat(page.select { |conversation| conversation[:updated_at] >= since })
16
+ data = request(:get, 'communication/conversations', query(cursor))[:data]
17
+ page = data[:conversations]
18
+ conversations.concat(page.select { |conversation| updated_at(conversation) >= since })
27
19
 
28
- cursor_after = data.dig(:cursor, :after)
29
- return without_timestamps(results) if page.empty? || cursor_after.blank? || page.last[:updated_at] < since
20
+ cursor = data.dig(:cursor, :after)
21
+ return Success(conversations.map { Conversations.summary(it) }) if page.empty? || cursor.blank? || updated_at(page.last) < since
30
22
  end
31
23
 
32
24
  error! "Guesty conversations pagination exceeded #{MAX_PAGES} pages since #{since.iso8601}"
33
25
  end
34
26
 
35
- def without_timestamps(conversations)
36
- conversations.map { |conversation| conversation.except(:updated_at) }
37
- end
38
-
39
- def fetch_page(cursor_after)
40
- params = { fields: FIELDS, sort: '-updatedAt', limit: LIMIT }
41
- params[:cursorAfter] = cursor_after if cursor_after.present?
42
-
43
- response = Guesty.do_request(:get, 'communication/conversations', params)
44
- error! response.failure.message unless response.success?
27
+ private
45
28
 
46
- response.value!.body[:data]
29
+ # @rbs (::String? cursor) -> ::Hash[::Symbol, untyped]
30
+ def query(cursor)
31
+ { fields: FIELDS, sort: '-updatedAt', limit: LIMIT, cursorAfter: cursor.presence }.compact
47
32
  end
48
33
 
49
- def normalize(conversation)
50
- {
51
- id: conversation.fetch(:_id),
52
- updated_at: Time.iso8601(conversation.fetch(:updatedAt)),
53
- reservations: Guesty::Reservations.from_conversation(conversation)
54
- }
34
+ # @rbs (untyped conversation) -> ::Time
35
+ def updated_at(conversation)
36
+ Time.iso8601(conversation.fetch(:updatedAt))
55
37
  end
56
38
  end
57
39
  end
@@ -4,22 +4,6 @@ module Guesty
4
4
  class Reply
5
5
  include Guesty::Operation
6
6
 
7
- # Guesty module type per booking channel; direct channels go by email.
8
- BOOKING_MODULE_TYPES = {
9
- 'airbnb' => 'airbnb2',
10
- 'booking_com' => 'bookingCom',
11
- 'guestit' => 'email',
12
- 'core_manual' => 'email',
13
- 'core_group_manual' => 'email',
14
- 'ago' => 'email',
15
- 'owner_stay' => 'email'
16
- }.freeze #: ::Hash[::String, ::String]
17
-
18
- # @rbs (::String? channel_name) -> ::String?
19
- def self.module_type_for(channel_name)
20
- BOOKING_MODULE_TYPES[channel_name]
21
- end
22
-
23
7
  # @rbs (conversation_id: String, body: String, ?module_type: String?) -> Dry::Monads::Result[Hash[Symbol, untyped]]
24
8
  def call(conversation_id:, body:, module_type: nil)
25
9
  argument! conversation_id: :required, fatal: true if conversation_id.blank?
@@ -27,15 +11,9 @@ module Guesty
27
11
  argument! module_type: :invalid, fatal: true if !module_type.nil? && module_type.blank?
28
12
 
29
13
  # On `platform` Guesty picks the booking channel, or email, and echoes the channel it used.
30
- response = Guesty.do_request(
31
- :post,
32
- "communication/conversations/#{conversation_id}/send-message",
33
- { module: { type: module_type || 'platform' }, body: },
34
- retries: 0
35
- )
36
- return response unless response.success?
14
+ post = request(:post, "communication/conversations/#{conversation_id}/send-message", { module: { type: module_type || 'platform' }, body: }, retries: 0)
37
15
 
38
- Success(normalize(response.value!.body.fetch(:data)))
16
+ Success(normalize(post.fetch(:data)))
39
17
  end
40
18
 
41
19
  private
@@ -14,14 +14,7 @@ module Guesty
14
14
  def call(conversation_id:, cursor: nil)
15
15
  argument! conversation_id: :required if conversation_id.blank?
16
16
 
17
- response = Guesty.do_request(
18
- :get,
19
- "communication/conversations/#{conversation_id}/posts",
20
- query(cursor)
21
- )
22
- return response unless response.success?
23
-
24
- Success(normalize_response(response.value!.body[:data]))
17
+ Success(normalize_response(request(:get, "communication/conversations/#{conversation_id}/posts", query(cursor))[:data]))
25
18
  end
26
19
 
27
20
  private
@@ -35,25 +28,21 @@ module Guesty
35
28
  { results: posts, cursor_after: data.dig(:cursor, :after).presence, oldest_created_at: oldest_created_at(raw_posts) }
36
29
  end
37
30
 
38
- # Taken before the filter. A page of only skipped post types must still tell the caller
39
- # how far back it reached.
31
+ # Taken before the filter, so a page of skipped posts still tells how far back it reached.
40
32
  # @rbs (::Array[untyped] raw_posts) -> ::Time?
41
33
  def oldest_created_at(raw_posts)
42
34
  raw_posts.filter_map { |post| Time.iso8601(post[:createdAt]) if post[:createdAt].present? }.min
43
35
  end
44
36
 
45
37
  def query(cursor)
46
- params = { limit: LIMIT, sort: '-createdAt' }
47
- params[:cursorAfter] = cursor if cursor.present?
48
- params
38
+ { limit: LIMIT, sort: '-createdAt', cursorAfter: cursor.presence }.compact
49
39
  end
50
40
 
51
41
  def normalize_attachments(attachments)
52
42
  attachments.map { |attachment| attachment_media_type(attachment[:type]) }
53
43
  end
54
44
 
55
- # Parallel to #normalize_attachments. Index N names the same attachment in both arrays,
56
- # so a missing attachmentUrl keeps its slot as an empty string.
45
+ # Index-aligned with #normalize_attachments, so a missing attachmentUrl keeps its slot.
57
46
  def normalize_attachment_keys(attachments)
58
47
  attachments.map { |attachment| attachment[:attachmentUrl].to_s }
59
48
  end
@@ -65,9 +54,7 @@ module Guesty
65
54
  MiniMime.lookup_by_extension(type)&.content_type || 'application/octet-stream'
66
55
  end
67
56
 
68
- # Guesty allows a post that is only an attachment. A post with neither text nor a file
69
- # carries nothing. Provider-side automation posts stay visible so the host does not answer a
70
- # turn that was already answered.
57
+ # Automation posts stay so the host does not answer a turn twice.
71
58
  def importable?(post, attachments)
72
59
  return false if post[:_id].blank? || post[:createdAt].blank?
73
60
  return false if SYSTEM_MODULE_TYPES.include?(post.dig(:module, :type))
@@ -75,7 +62,6 @@ module Guesty
75
62
  SENDERS.include?(post[:sentBy]) && (post[:body].present? || attachments.any?)
76
63
  end
77
64
 
78
- # provider_reservation_id routes the post to its stay and author_name lands on the sync row; neither is a message column.
79
65
  # @rbs (untyped post) -> untyped
80
66
  def normalize_post(post)
81
67
  raw_attachments = post.fetch(:attachments, [])
@@ -95,8 +81,6 @@ module Guesty
95
81
  }
96
82
  end
97
83
 
98
- # Guesty's own scheduled posts and reservation logs are system posts. Everything else keeps the sender
99
- # Guesty names.
100
84
  # @rbs (untyped post) -> String
101
85
  def sender_kind(post)
102
86
  post[:isAutomatic] || post[:sentBy] == LOG_SENDER ? 'system' : post[:sentBy]
@@ -107,7 +91,6 @@ module Guesty
107
91
  post.dig(:module, :type) unless post[:sentBy] == LOG_SENDER
108
92
  end
109
93
 
110
- # Only a person answering from Guesty has a name worth keeping.
111
94
  # @rbs (untyped post) -> String?
112
95
  def author_name(post)
113
96
  return if post[:isAutomatic] || post[:sentBy] != 'host'
@@ -1,7 +1,6 @@
1
1
  module Guesty
2
2
  module Conversations
3
3
  module Posts
4
- # Walks a thread newest-first until the page that reaches `since`, or to the end without one.
5
4
  class Since
6
5
  include Guesty::Operation
7
6
 
@@ -9,12 +9,9 @@ module Guesty
9
9
  def call(external_id:)
10
10
  argument! external_id: :required if external_id.blank?
11
11
 
12
- response = Guesty.do_request(:get, 'communication/conversations', query(external_id))
13
- return response unless response.success?
12
+ conversation = request(:get, 'communication/conversations', query(external_id))[:data][:conversations].first
14
13
 
15
- conversation = response.value!.body[:data][:conversations].first
16
-
17
- Success(conversation && { id: conversation.fetch(:_id), reservations: Guesty::Reservations.from_conversation(conversation) })
14
+ Success(conversation && Conversations.summary(conversation))
18
15
  end
19
16
 
20
17
  private
@@ -9,16 +9,7 @@ module Guesty
9
9
  def call(conversation_id:)
10
10
  argument! conversation_id: :required if conversation_id.blank?
11
11
 
12
- response = Guesty.do_request(
13
- :get,
14
- "communication/conversations/#{conversation_id}",
15
- { fields: FIELDS }
16
- )
17
- return response unless response.success?
18
-
19
- conversation = response.value!.body[:data]
20
-
21
- Success({ id: conversation.fetch(:_id), reservations: Guesty::Reservations.from_conversation(conversation) })
12
+ Success(Conversations.summary(request(:get, "communication/conversations/#{conversation_id}", { fields: FIELDS })[:data]))
22
13
  end
23
14
  end
24
15
  end
@@ -1,6 +1,5 @@
1
1
  module Guesty
2
2
  module Conversations
3
- # Neutral channel names for Guesty's versioned module types.
4
3
  CHANNELS = {
5
4
  'airbnb2' => 'airbnb',
6
5
  'bookingCom' => 'booking_com'
@@ -11,5 +10,10 @@ module Guesty
11
10
  def self.channel(module_type)
12
11
  CHANNELS.fetch(module_type) { module_type.sub(VERSION_SUFFIX, '') }
13
12
  end
13
+
14
+ # @rbs (untyped conversation) -> ::Hash[::Symbol, untyped]
15
+ def self.summary(conversation)
16
+ { id: conversation.fetch(:_id), reservations: Reservations.from_conversation(conversation) }
17
+ end
14
18
  end
15
19
  end
data/lib/guesty/error.rb CHANGED
@@ -10,12 +10,8 @@ module Guesty
10
10
  end
11
11
  end
12
12
 
13
- # Raised by operations before any network call when the arguments are unusable.
14
- # fatal: true marks a refusal no retry can fix; the host decides what to do with it.
15
13
  class ArgumentError < Error; end
16
14
 
17
- # Raised by the rate limiter middleware when the injected limiter refuses the
18
- # request: the call never left the process, so no write landed upstream.
19
15
  class ThrottledError < Error
20
16
  attr_reader :key, :threshold, :interval, :retry_after
21
17
 
@@ -1,8 +1,7 @@
1
1
  module Guesty
2
2
  module GuestFolio
3
3
  module InvoiceItems
4
- # Closed Airbnb Resolution Center items: negative amounts are refunds and
5
- # positive amounts are guest charges.
4
+ # Negative amounts are refunds, positive amounts guest charges.
6
5
  class Index
7
6
  include Guesty::Operation
8
7
 
@@ -13,10 +12,7 @@ module Guesty
13
12
  def call(reservation_id:)
14
13
  argument! reservation_id: :required if reservation_id.blank?
15
14
 
16
- response = Guesty.do_request(:get, 'guest-folio/invoice-items', query(reservation_id))
17
- return response unless response.success?
18
-
19
- Success(normalize_response(response.value!.body, reservation_id))
15
+ Success(normalize_response(request(:get, 'guest-folio/invoice-items', query(reservation_id)), reservation_id))
20
16
  end
21
17
 
22
18
  private
@@ -13,11 +13,7 @@ module Guesty
13
13
  missing = REQUIRED_ATTRIBUTES.find { |attribute| attributes[attribute].blank? }
14
14
  argument! missing => :required if missing
15
15
 
16
- response = Guesty.do_request :post, 'guests-crud', attributes, retries: 0
17
-
18
- raise response.failure unless response.success?
19
-
20
- Success(response.value!.body)
16
+ Success(request(:post, 'guests-crud', attributes, retries: 0))
21
17
  end
22
18
  end
23
19
  end
@@ -8,14 +8,7 @@ module Guesty
8
8
  def call(guest_id:, fields: nil)
9
9
  argument! guest_id: :required if guest_id.blank?
10
10
 
11
- attributes = {} #: ::Hash[::Symbol, ::String]
12
- attributes[:fields] = fields.join(' ') if fields.present?
13
-
14
- response = Guesty.do_request :get, "guests-crud/#{guest_id}", attributes
15
-
16
- raise response.failure unless response.success?
17
-
18
- Success(response.value!.body)
11
+ Success(request(:get, "guests-crud/#{guest_id}", { fields: fields&.join(' ') }.compact_blank))
19
12
  end
20
13
  end
21
14
  end