-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcontact.go
More file actions
430 lines (398 loc) · 17.4 KB
/
Copy pathcontact.go
File metadata and controls
430 lines (398 loc) · 17.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
package sentdm
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"time"
"github.com/sentdm/sent-dm-go/internal/apijson"
"github.com/sentdm/sent-dm-go/internal/apiquery"
shimjson "github.com/sentdm/sent-dm-go/internal/encoding/json"
"github.com/sentdm/sent-dm-go/internal/requestconfig"
"github.com/sentdm/sent-dm-go/option"
"github.com/sentdm/sent-dm-go/packages/pagination"
"github.com/sentdm/sent-dm-go/packages/param"
"github.com/sentdm/sent-dm-go/packages/respjson"
)
// The people you message, and their channel identities.
//
// A contact holds one identity per channel — a phone number, a WhatsApp number —
// so routing can choose between them for the same person. Opt-out is recorded
// against the contact and honoured on every send, whichever channel it came
// through.
//
// `GET /v3/contacts/{id}/message-summary` is the per-contact view of what you have
// sent and what happened to it.
//
// ContactService contains methods and other services that help with interacting
// with the Sent API.
//
// Note, unlike clients, this service does not read variables from the environment
// automatically. You should not instantiate this service directly, and instead use
// the [NewContactService] method instead.
type ContactService struct {
Options []option.RequestOption
}
// NewContactService generates a new service that applies the given options to each
// request. These options are applied after the parent client's options (if there
// is one), and before any request-specific options.
func NewContactService(opts ...option.RequestOption) (r ContactService) {
r = ContactService{}
r.Options = opts
return
}
// Creates a new contact by phone number and associates it with the authenticated
// customer.
func (r *ContactService) New(ctx context.Context, params ContactNewParams, opts ...option.RequestOption) (res *APIResponseOfContact, err error) {
if !param.IsOmitted(params.IdempotencyKey) {
opts = append(opts, option.WithHeader("Idempotency-Key", fmt.Sprintf("%v", params.IdempotencyKey.Value)))
}
if !param.IsOmitted(params.XProfileID) {
opts = append(opts, option.WithHeader("x-profile-id", fmt.Sprintf("%v", params.XProfileID.Value)))
}
opts = slices.Concat(r.Options, opts)
path := "v3/contacts"
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPost, path, params, &res, opts...)
return res, err
}
// Retrieves a specific contact by their unique identifier. Returns detailed
// contact information including phone formats, available channels, and opt-out
// status.
func (r *ContactService) Get(ctx context.Context, id string, query ContactGetParams, opts ...option.RequestOption) (res *APIResponseOfContact, err error) {
if !param.IsOmitted(query.XProfileID) {
opts = append(opts, option.WithHeader("x-profile-id", fmt.Sprintf("%v", query.XProfileID.Value)))
}
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("v3/contacts/%s", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
return res, err
}
// Updates a contact's default channel and/or opt-out status.
func (r *ContactService) Update(ctx context.Context, id string, params ContactUpdateParams, opts ...option.RequestOption) (res *APIResponseOfContact, err error) {
if !param.IsOmitted(params.IdempotencyKey) {
opts = append(opts, option.WithHeader("Idempotency-Key", fmt.Sprintf("%v", params.IdempotencyKey.Value)))
}
if !param.IsOmitted(params.XProfileID) {
opts = append(opts, option.WithHeader("x-profile-id", fmt.Sprintf("%v", params.XProfileID.Value)))
}
opts = slices.Concat(r.Options, opts)
if id == "" {
err = errors.New("missing required id parameter")
return nil, err
}
path := fmt.Sprintf("v3/contacts/%s", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodPatch, path, params, &res, opts...)
return res, err
}
// Retrieves a paginated list of contacts for the authenticated customer. Supports
// filtering by search term, channel, or phone number.
func (r *ContactService) List(ctx context.Context, params ContactListParams, opts ...option.RequestOption) (res *pagination.ContactsPage[ContactResponse], err error) {
var raw *http.Response
if !param.IsOmitted(params.XProfileID) {
opts = append(opts, option.WithHeader("x-profile-id", fmt.Sprintf("%v", params.XProfileID.Value)))
}
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithResponseInto(&raw)}, opts...)
path := "v3/contacts"
cfg, err := requestconfig.NewRequestConfig(ctx, http.MethodGet, path, params, &res, opts...)
if err != nil {
return nil, err
}
err = cfg.Execute()
if err != nil {
return nil, err
}
res.SetPageConfig(cfg, raw)
return res, nil
}
// Retrieves a paginated list of contacts for the authenticated customer. Supports
// filtering by search term, channel, or phone number.
func (r *ContactService) ListAutoPaging(ctx context.Context, params ContactListParams, opts ...option.RequestOption) *pagination.ContactsPageAutoPager[ContactResponse] {
return pagination.NewContactsPageAutoPager(r.List(ctx, params, opts...))
}
// **Deprecated.** Use `PATCH /v3/contacts/{id}` with `{"opt_out": true}` instead,
// and expect this to be removed in a future release. It still behaves exactly as
// before, so nothing needs to change today.
//
// Opting a contact out stops every send to them, which is what deleting one was
// mostly used for — and it keeps the record of who they were and that they asked.
// A delete discards the consent history along with the contact, which is the part
// you need if anyone ever asks why you stopped, or why you started again.
//
// Dissociates a contact from the authenticated customer.
//
// Deprecated: deprecated
func (r *ContactService) Delete(ctx context.Context, id string, params ContactDeleteParams, opts ...option.RequestOption) (err error) {
if !param.IsOmitted(params.XProfileID) {
opts = append(opts, option.WithHeader("x-profile-id", fmt.Sprintf("%v", params.XProfileID.Value)))
}
opts = slices.Concat(r.Options, opts)
opts = append([]option.RequestOption{option.WithHeader("Accept", "*/*")}, opts...)
if id == "" {
err = errors.New("missing required id parameter")
return err
}
path := fmt.Sprintf("v3/contacts/%s", id)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodDelete, path, params, nil, opts...)
return err
}
// Returns aggregate message counts, time bounds, channels used, and per-channel
// success/fail scores (each as a percentage 0-100 of messages on that channel) for
// one of your contacts. Successful terminal states: SENT/DELIVERED/READ for
// outbound, RECEIVED for inbound. Fail: FAILED.
func (r *ContactService) GetMessageSummary(ctx context.Context, contactID string, query ContactGetMessageSummaryParams, opts ...option.RequestOption) (res *APIResponseOfContactMessageSummary, err error) {
if !param.IsOmitted(query.XProfileID) {
opts = append(opts, option.WithHeader("x-profile-id", fmt.Sprintf("%v", query.XProfileID.Value)))
}
opts = slices.Concat(r.Options, opts)
if contactID == "" {
err = errors.New("missing required contactId parameter")
return nil, err
}
path := fmt.Sprintf("v3/contacts/%s/message-summary", contactID)
err = requestconfig.ExecuteNewRequest(ctx, http.MethodGet, path, nil, &res, opts...)
return res, err
}
// Standard API response envelope for all v3 endpoints
type APIResponseOfContact struct {
// Contact response for v3 API Uses snake_case for JSON property names
Data ContactResponse `json:"data" api:"nullable"`
// Error information
Error ErrorDetail `json:"error" api:"nullable"`
// Request and response metadata
Meta APIMeta `json:"meta"`
// Indicates whether the request was successful
Success bool `json:"success"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Data respjson.Field
Error respjson.Field
Meta respjson.Field
Success respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r APIResponseOfContact) RawJSON() string { return r.JSON.raw }
func (r *APIResponseOfContact) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Standard API response envelope for all v3 endpoints
type APIResponseOfContactMessageSummary struct {
// The response data (null if error)
Data ContactMessageSummary `json:"data" api:"nullable"`
// Error information
Error ErrorDetail `json:"error" api:"nullable"`
// Request and response metadata
Meta APIMeta `json:"meta"`
// Indicates whether the request was successful
Success bool `json:"success"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Data respjson.Field
Error respjson.Field
Meta respjson.Field
Success respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r APIResponseOfContactMessageSummary) RawJSON() string { return r.JSON.raw }
func (r *APIResponseOfContactMessageSummary) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type ContactMessageSummary struct {
ChannelScores []ContactMessageSummaryChannelScore `json:"channel_scores"`
ChannelsUsed []string `json:"channels_used"`
ContactID string `json:"contact_id" format:"uuid"`
FirstMessageAt time.Time `json:"first_message_at" api:"nullable" format:"date-time"`
LastMessageAt time.Time `json:"last_message_at" api:"nullable" format:"date-time"`
MessageCount int64 `json:"message_count"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ChannelScores respjson.Field
ChannelsUsed respjson.Field
ContactID respjson.Field
FirstMessageAt respjson.Field
LastMessageAt respjson.Field
MessageCount respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r ContactMessageSummary) RawJSON() string { return r.JSON.raw }
func (r *ContactMessageSummary) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type ContactMessageSummaryChannelScore struct {
Channel string `json:"channel"`
// Percentage (0-100) of messages on this channel that ended in FAILED.
FailScore int64 `json:"fail_score"`
// Percentage (0-100) of messages on this channel that reached a successful
// terminal state: SENT/DELIVERED/READ for outbound, RECEIVED for inbound.
SuccessScore int64 `json:"success_score"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
Channel respjson.Field
FailScore respjson.Field
SuccessScore respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r ContactMessageSummaryChannelScore) RawJSON() string { return r.JSON.raw }
func (r *ContactMessageSummaryChannelScore) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
// Contact response for v3 API Uses snake_case for JSON property names
type ContactResponse struct {
// Unique identifier for the contact
ID string `json:"id" format:"uuid"`
// Comma-separated list of available messaging channels (e.g., "sms,whatsapp")
AvailableChannels string `json:"available_channels"`
// Country calling code (e.g., 1 for US/Canada)
CountryCode string `json:"country_code"`
// When the contact was created
CreatedAt time.Time `json:"created_at" format:"date-time"`
// Which customer owns this — the key's own, or the profile named in x-profile-id.
// Says whose resource this is, which the resource's own id does not.
CustomerID string `json:"customer_id" format:"uuid"`
// Default messaging channel to use (e.g., "sms" or "whatsapp")
DefaultChannel string `json:"default_channel"`
// Phone number in E.164 format (e.g., +1234567890)
FormatE164 string `json:"format_e164"`
// Phone number in international format (e.g., +1 234-567-890)
FormatInternational string `json:"format_international"`
// Phone number in national format (e.g., (234) 567-890)
FormatNational string `json:"format_national"`
// Phone number in RFC 3966 format (e.g., tel:+1-234-567-890)
FormatRfc string `json:"format_rfc"`
// Always false. Contacts are no longer shared or inherited between sender profiles
// — a profile sees only the contacts it owns. Retained so existing v3 clients
// reading is_inherited keep deserializing; it carries no information.
//
// Deprecated: deprecated
IsInherited bool `json:"is_inherited"`
// Whether the contact has opted out of messaging. Single source of truth — opt-out
// is per-contact, not per-channel.
OptOut bool `json:"opt_out"`
// Phone number in original format
PhoneNumber string `json:"phone_number"`
// ISO 3166-1 alpha-2 country code (e.g., US, CA, GB)
RegionCode string `json:"region_code"`
// When the contact was last updated
UpdatedAt time.Time `json:"updated_at" api:"nullable" format:"date-time"`
// JSON contains metadata for fields, check presence with [respjson.Field.Valid].
JSON struct {
ID respjson.Field
AvailableChannels respjson.Field
CountryCode respjson.Field
CreatedAt respjson.Field
CustomerID respjson.Field
DefaultChannel respjson.Field
FormatE164 respjson.Field
FormatInternational respjson.Field
FormatNational respjson.Field
FormatRfc respjson.Field
IsInherited respjson.Field
OptOut respjson.Field
PhoneNumber respjson.Field
RegionCode respjson.Field
UpdatedAt respjson.Field
ExtraFields map[string]respjson.Field
raw string
} `json:"-"`
}
// Returns the unmodified JSON received from the API
func (r ContactResponse) RawJSON() string { return r.JSON.raw }
func (r *ContactResponse) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type ContactNewParams struct {
// Phone number of the contact to create
PhoneNumber string `json:"phone_number" api:"required"`
// Sandbox flag - when true, the operation is simulated without side effects Useful
// for testing integrations without actual execution
Sandbox param.Opt[bool] `json:"sandbox,omitzero"`
IdempotencyKey param.Opt[string] `header:"Idempotency-Key,omitzero" json:"-"`
XProfileID param.Opt[string] `header:"x-profile-id,omitzero" format:"uuid" json:"-"`
paramObj
}
func (r ContactNewParams) MarshalJSON() (data []byte, err error) {
type shadow ContactNewParams
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *ContactNewParams) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type ContactGetParams struct {
XProfileID param.Opt[string] `header:"x-profile-id,omitzero" format:"uuid" json:"-"`
paramObj
}
type ContactUpdateParams struct {
// Default messaging channel: "sms" or "whatsapp"
DefaultChannel param.Opt[string] `json:"default_channel,omitzero"`
// Whether the contact has opted out of messaging. Single source of truth — opt-out
// is per-contact, not per-channel.
OptOut param.Opt[bool] `json:"opt_out,omitzero"`
// Sandbox flag - when true, the operation is simulated without side effects Useful
// for testing integrations without actual execution
Sandbox param.Opt[bool] `json:"sandbox,omitzero"`
IdempotencyKey param.Opt[string] `header:"Idempotency-Key,omitzero" json:"-"`
XProfileID param.Opt[string] `header:"x-profile-id,omitzero" format:"uuid" json:"-"`
paramObj
}
func (r ContactUpdateParams) MarshalJSON() (data []byte, err error) {
type shadow ContactUpdateParams
return param.MarshalObject(r, (*shadow)(&r))
}
func (r *ContactUpdateParams) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type ContactListParams struct {
// Optional channel filter (sms, whatsapp)
Channel param.Opt[string] `query:"channel,omitzero" json:"-"`
// Optional phone number filter (alternative to list view)
Phone param.Opt[string] `query:"phone,omitzero" json:"-"`
// Optional search term for filtering contacts
Search param.Opt[string] `query:"search,omitzero" json:"-"`
// Page number (1-indexed)
Page param.Opt[int64] `query:"page,omitzero" json:"-"`
// Number of items per page
PageSize param.Opt[int64] `query:"page_size,omitzero" json:"-"`
XProfileID param.Opt[string] `header:"x-profile-id,omitzero" format:"uuid" json:"-"`
paramObj
}
// URLQuery serializes [ContactListParams]'s query parameters as `url.Values`.
func (r ContactListParams) URLQuery() (v url.Values, err error) {
return apiquery.MarshalWithSettings(r, apiquery.QuerySettings{
ArrayFormat: apiquery.ArrayQueryFormatComma,
NestedFormat: apiquery.NestedQueryFormatBrackets,
})
}
type ContactDeleteParams struct {
MutationRequest MutationRequestParam
XProfileID param.Opt[string] `header:"x-profile-id,omitzero" format:"uuid" json:"-"`
paramObj
}
func (r ContactDeleteParams) MarshalJSON() (data []byte, err error) {
return shimjson.Marshal(r.MutationRequest)
}
func (r *ContactDeleteParams) UnmarshalJSON(data []byte) error {
return apijson.UnmarshalRoot(data, r)
}
type ContactGetMessageSummaryParams struct {
XProfileID param.Opt[string] `header:"x-profile-id,omitzero" format:"uuid" json:"-"`
paramObj
}