-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpachca.go
2529 lines (2016 loc) · 56.9 KB
/
pachca.go
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package pachca
// ////////////////////////////////////////////////////////////////////////////////// //
// //
// Copyright (c) 2024 ESSENTIAL KAOS //
// Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0> //
// //
// ////////////////////////////////////////////////////////////////////////////////// //
import (
"bytes"
"fmt"
"io"
"mime/multipart"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/essentialkaos/ek/v13/errors"
"github.com/essentialkaos/ek/v13/mathutil"
"github.com/essentialkaos/ek/v13/path"
"github.com/essentialkaos/ek/v13/req"
"github.com/essentialkaos/ek/v13/strutil"
)
// ////////////////////////////////////////////////////////////////////////////////// //
// API_URL is URL of Pachca API
const API_URL = "https://api.pachca.com/api/shared/v1"
// APP_URL is application URL used to generate links
const APP_URL = "https://app.pachca.com"
// ////////////////////////////////////////////////////////////////////////////////// //
const (
PROP_TYPE_DATE PropertyType = "date"
PROP_TYPE_LINK PropertyType = "link"
PROP_TYPE_NUMBER PropertyType = "number"
PROP_TYPE_TEXT PropertyType = "text"
)
const (
INVITE_SENT InviteStatus = "sent"
INVITE_CONFIRMED InviteStatus = "confirmed"
)
const (
ROLE_ADMIN UserRole = "admin"
ROLE_REGULAR UserRole = "user"
ROLE_MULTI_GUEST UserRole = "multi_guest"
ROLE_GUEST UserRole = "guest"
)
const (
CHAT_ROLE_ADMIN ChatRole = "admin"
CHAT_ROLE_EDITOR ChatRole = "editor"
CHAT_ROLE_MEMBER ChatRole = "member"
)
const (
FILE_TYPE_FILE FileType = "file"
FILE_TYPE_IMAGE FileType = "image"
)
const (
ENTITY_TYPE_DISCUSSION EntityType = "discussion"
ENTITY_TYPE_THREAD EntityType = "thread"
ENTITY_TYPE_USER EntityType = "user"
)
const (
WEBHOOK_EVENT_NEW WebhookEvent = "new"
WEBHOOK_EVENT_UPDATE WebhookEvent = "update"
WEBHOOK_EVENT_DELETE WebhookEvent = "delete"
)
const (
WEBHOOK_TYPE_MESSAGE WebhookType = "message"
WEBHOOK_TYPE_REACTION WebhookType = "reaction"
WEBHOOK_TYPE_BUTTON WebhookType = "button"
)
// ////////////////////////////////////////////////////////////////////////////////// //
// Date is JSON date
type Date struct {
time.Time
}
// ////////////////////////////////////////////////////////////////////////////////// //
// EntityType is type of entity type
type EntityType string
// PropertyType is type for property type
type PropertyType string
// UserRole is type of user role
type UserRole string
// ChatRole is type of user in chat
type ChatRole string
// InviteStatus is type of invite status
type InviteStatus string
// FileType is type for file type
type FileType string
// WebhookEvent is type for webhook events
type WebhookEvent string
// WebhookType is type for webhook types
type WebhookType string
// ////////////////////////////////////////////////////////////////////////////////// //
// Chats is slice of chats
type Chats []*Chat
// Chat contains info about channel
type Chat struct {
Members []uint `json:"member_ids"`
GroupTags []uint `json:"group_tag_ids"`
ID uint `json:"id"`
OwnerID uint `json:"owner_id"`
Name string `json:"name"`
MeetRoomURL string `json:"meet_room_url"`
CreatedAt Date `json:"created_at"`
LastMessageAt Date `json:"last_message_at"`
IsPublic bool `json:"public"`
IsChannel bool `json:"channel"`
}
// Users is a slice of users
type Users []*User
// User contains info about user
type User struct {
ID uint `json:"id"`
CreatedAt Date `json:"created_at"`
ImageURL string `json:"image_url"`
Email string `json:"email"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Nickname string `json:"nickname"`
Role UserRole `json:"role"`
PhoneNumber string `json:"phone_number"`
TimeZone string `json:"time_zone"`
Title string `json:"title"`
InviteStatus InviteStatus `json:"invite_status"`
Department string `json:"department"`
Properties Properties `json:"custom_properties"`
Tags []string `json:"list_tags"`
Status *Status `json:"user_status"`
IsBot bool `json:"bot"`
IsSuspended bool `json:"suspended"`
}
// Status is user status
type Status struct {
Emoji string `json:"emoji"`
Title string `json:"title"`
ExpiresAt Date `json:"expires_at"`
}
// Properties is a slice of properties
type Properties []*Property
// Property is custom property
type Property struct {
ID uint `json:"id"`
Type PropertyType `json:"data_type"`
Name string `json:"name"`
Value string `json:"value"`
}
// Tag contains info about tag
type Tag struct {
ID uint `json:"id"`
Name string `json:"name"`
UsersCount int `json:"users_count"`
}
// Tags is a slice of tags
type Tags []*Tag
// Reaction contains reaction info
type Reaction struct {
UserID uint `json:"user_id"`
CreatedAt Date `json:"created_at"`
Emoji string `json:"code"`
}
// Reactions is a slice of reactions
type Reactions []*Reaction
// Thread contains info about thread
type Thread struct {
ID uint `json:"id"`
ChatID uint `json:"chat_id"`
MessageID uint `json:"message_id"`
MessageChatID uint `json:"message_chat_id"`
UpdatedAt Date `json:"updated_at"`
}
// Message contains info about message
type Message struct {
ID uint `json:"id"`
EntityID uint `json:"entity_id"`
ChatID uint `json:"chat_id"`
ParentMessageID uint `json:"parent_message_id"`
UsedID uint `json:"user_id"`
EntityType EntityType `json:"entity_type"`
Content string `json:"content"`
CreatedAt Date `json:"created_at"`
Thread *Thread `json:"thread"`
Files Files `json:"files"`
Buttons Buttons `json:"buttons"`
Forwarding *Forwarding `json:"forwarding"`
}
// Forwarding contains info about message forwarding
type Forwarding struct {
OriginalMessageID uint `json:"original_message_id"`
OriginalChatID uint `json:"original_chat_id"`
AuthorID uint `json:"author_id"`
OriginalThreadID uint `json:"original_thread_id"`
OriginalThreadMessageID uint `json:"original_thread_message_id"`
OriginalThreadParentChatID uint `json:"original_thread_parent_chat_id"`
OriginalCreatedAt Date `json:"original_created_at"`
}
// File contains info about message attachment
type File struct {
ID uint `json:"id,omitempty"`
Key string `json:"key"`
Name string `json:"name"`
Type FileType `json:"file_type,omitempty"`
URL string `json:"url,omitempty"`
Size uint `json:"size,omitempty"`
}
// Files is a slice of attachments
type Files []*File
// Button contains info about message button
type Button struct {
Text string `json:"text"`
URL string `json:"url"`
Data string `json:"data"`
}
// Buttons is a slice of buttons
type Buttons []*Button
// Upload contains upload info used for uploading files
type Upload struct {
ContentDisposition string `json:"Content-Disposition"`
ACL string `json:"acl"`
Policy string `json:"policy"`
Credential string `json:"x-amz-credential"`
Algorithm string `json:"x-amz-algorithm"`
Date string `json:"x-amz-date"`
Signature string `json:"x-amz-signature"`
Key string `json:"key"`
DirectURL string `json:"direct_url"`
}
// ////////////////////////////////////////////////////////////////////////////////// //
// APIError contains API error info
type APIError struct {
Key string `json:"key"`
Value string `json:"value"`
Message string `json:"message"`
Code string `json:"code"`
StatusCode int
}
// ////////////////////////////////////////////////////////////////////////////////// //
// WebhookMessage is message webhook payload
type Webhook struct {
Type WebhookType `json:"type"`
ID uint `json:"id"` // message
Event WebhookEvent `json:"event"` // message, reaction
EntityType EntityType `json:"entity_type"` // message
EntityID uint `json:"entity_id"` // message
Content string `json:"content"` // message
Emoji string `json:"code"` // reaction
Data string `json:"data"` // button
UserID uint `json:"user_id"` // message, reaction
CreatedAt Date `json:"created_at"` // message, reaction, button
ChatID uint `json:"chat_id"` // message
MessageID uint `json:"message_id"` // reaction, button
ParentMessageID uint `json:"parent_message_id"` // message
Thread *Thread `json:"thread"` // message
}
// WebhookThread contains info about message thread
type WebhookThread struct {
MessageID uint `json:"message_id"`
MessageChatID uint `json:"message_chat_id"`
}
// WebhookLink contains payload for link unfurl
type WebhookLink struct {
ChatID uint `json:"chat_id"`
MessageID uint `json:"message_id"`
Links []*UnfurlLink `json:"links"`
}
// UnfurlLink contains info about link in message to unfurl
type UnfurlLink struct {
URL string `json:"url"`
Domain string `json:"domain"`
}
// ////////////////////////////////////////////////////////////////////////////////// //
// uploadInfo contains info about uploaded file
type uploadInfo struct {
Key string // Uploading key
Name string // File name
Size uint // File size
ContentType string // Content type
Buffer *bytes.Buffer // Buffer with data
}
// ////////////////////////////////////////////////////////////////////////////////// //
// ChatFilter is configuration for filtering chats
type ChatFilter struct {
LastMessageAfter time.Time
LastMessageBefore time.Time
Public bool
}
// UserRequest is a struct with information needed to create or modify a user
type UserRequest struct {
Email string `json:"email,omitempty"`
FirstName string `json:"first_name,omitempty"`
LastName string `json:"last_name,omitempty"`
Nickname string `json:"nickname,omitempty"`
Role UserRole `json:"role,omitempty"`
PhoneNumber string `json:"phone_number,omitempty"`
Title string `json:"title,omitempty"`
Department string `json:"department,omitempty"`
Properties PropertyRequests `json:"custom_properties,omitempty"`
Tags []string `json:"list_tags,omitempty"`
IsSuspended bool `json:"suspended,omitempty"`
SkipEmailNotify bool `json:"skip_email_notify,omitempty"`
}
// PropertyRequest is a struct with property info
type PropertyRequest struct {
ID uint `json:"id"`
Value string `json:"value"`
}
// PropertyRequests is a slice with properties requests
type PropertyRequests []*PropertyRequest
// ChatRequest is a struct with information needed to create or modify a chat
type ChatRequest struct {
Name string `json:"name,omitempty"`
Members []uint `json:"member_ids,omitempty"`
Groups []uint `json:"group_tag_ids,omitempty"`
IsChannel bool `json:"channel,omitempty"`
IsPublic bool `json:"public,omitempty"`
}
// MessageRequest is a struct with information needed to create or modify a message
type MessageRequest struct {
EntityType EntityType `json:"entity_type,omitempty"`
EntityID uint `json:"entity_id,omitempty"`
Content string `json:"content,omitempty"`
Files Files `json:"files,omitempty"`
Buttons Buttons `json:"buttons,omitempty"`
ParentMessageID Buttons `json:"parent_message_id,omitempty"`
SkipInviteMentions bool `json:"skip_invite_mentions,omitempty"`
}
// LinkPreview contains link preview data
type LinkPreview struct {
Title string `json:"title"`
Description string `json:"description"`
ImageURL string `json:"image_url,omitempty"`
Image *File `json:"image,omitempty"`
}
// LinkPreviews is map (url → preview data) with link previews
type LinkPreviews map[string]*LinkPreview
// ////////////////////////////////////////////////////////////////////////////////// //
// UnmarshalJSON parses JSON date
func (d *Date) UnmarshalJSON(b []byte) error {
data := string(b)
if data == "null" {
d.Time = time.Time{}
return nil
}
date, err := time.Parse(`"2006-01-02T15:04:05.999Z"`, data)
if err != nil {
return err
}
d.Time = date
return nil
}
// Error returns error text
func (e APIError) Error() string {
return fmt.Sprintf(
"(%s) %s [%s:%s]",
e.Code, e.Message, e.Key, strutil.Q(e.Value, "-"),
)
}
// ////////////////////////////////////////////////////////////////////////////////// //
// tokenValidationRegex is regex pattern for token validation
var tokenValidationRegex = regexp.MustCompile(`^[a-zA-Z0-9\-_]{43}$`)
// s3ErrorExtractRegex is regex pattern for extracting text from S3 error message
var s3ErrorExtractRegex = regexp.MustCompile(`\<Message\>(.*)\<\/Message\>`)
var (
ErrNilClient = errors.New("Client is nil")
ErrNilUserRequest = errors.New("User requests is nil")
ErrNilChatRequest = errors.New("Chat requests is nil")
ErrNilMessageRequest = errors.New("Message requests is nil")
ErrNilProperty = errors.New("Property requests is nil")
ErrEmptyToken = errors.New("Token is empty")
ErrEmptyTag = errors.New("Group tag is empty")
ErrEmptyMessage = errors.New("Message text is empty")
ErrEmptyUserEmail = errors.New("User email is required for creating user account")
ErrEmptyChatName = errors.New("Name is required for creating new chat")
ErrEmptyUsersIDS = errors.New("Users IDs are empty")
ErrEmptyTagsIDS = errors.New("Tags IDs are empty")
ErrEmptyFilePath = errors.New("Path to file is empty")
ErrInvalidToken = errors.New("Token has wrong format")
ErrInvalidMessageID = errors.New("Message ID must be greater than 0")
ErrInvalidChatID = errors.New("Chat ID must be greater than 0")
ErrInvalidUserID = errors.New("User ID must be greater than 0")
ErrInvalidThreadID = errors.New("Thread ID must be greater than 0")
ErrInvalidTagID = errors.New("Group tag ID must be greater than 0")
ErrInvalidEntityID = errors.New("Entity ID must be greater than 0")
ErrBlankEmoji = errors.New("Non-blank emoji is required")
ErrEmptyPreviews = errors.New("Previews map has no data")
)
// ////////////////////////////////////////////////////////////////////////////////// //
// Client is Pachca API client
type Client struct {
BatchSize int // BatchSize is a number of items for paginated requests
MaxFileSize int64 // Maximum file size to upload
engine *req.Engine
token string
}
// ////////////////////////////////////////////////////////////////////////////////// //
// NewClient creates new client with given token
func NewClient(token string) (*Client, error) {
err := ValidateToken(token)
if err != nil {
return nil, err
}
return &Client{
BatchSize: 50,
MaxFileSize: 10 * 1024 * 1024, // 10 MB
token: token,
engine: &req.Engine{},
}, nil
}
// NewPropertyRequest creates new custom property
func NewPropertyRequest(id uint, value any) *PropertyRequest {
var v string
switch t := value.(type) {
case time.Time:
v = formatDate(t.UTC())
case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
v = fmt.Sprintf("%d", value)
case float32:
v = fmt.Sprintf("%d", int64(t))
case float64:
v = fmt.Sprintf("%d", int64(t))
default:
v = fmt.Sprintf("%v", value)
}
return &PropertyRequest{ID: id, Value: v}
}
// ValidateToken validates API access token
func ValidateToken(token string) error {
switch {
case token == "":
return ErrEmptyToken
case !tokenValidationRegex.MatchString(token):
return ErrInvalidToken
}
return nil
}
// ////////////////////////////////////////////////////////////////////////////////// //
// SetUserAgent sets user-agent info
func (c *Client) SetUserAgent(app, ver string) {
if c == nil || c.engine == nil {
return
}
c.engine.SetUserAgent(app, ver, "EK-Pachca.go/1")
}
// Engine returns pointer to request engine used for all HTTP requests to API
func (c *Client) Engine() *req.Engine {
if c == nil || c.engine == nil {
return nil
}
return c.engine
}
// CUSTOM PROPERTIES //////////////////////////////////////////////////////////////// //
// GetProperties returns custom properties
//
// https://crm.pachca.com/dev/common/fields/
func (c *Client) GetProperties() (Properties, error) {
if c == nil || c.engine == nil {
return nil, ErrNilClient
}
query := req.Query{"entity_type": "User"}
resp := &struct {
Data Properties `json:"data"`
}{}
err := c.sendRequest(
req.GET, getURL("/custom_properties"),
query, nil, resp,
)
if err != nil {
return nil, fmt.Errorf("Can't fetch custom properties: %w", err)
}
return resp.Data, nil
}
// REACTIONS //////////////////////////////////////////////////////////////////////// //
// GetReactions returns slice with reactions added to given message
//
// https://crm.pachca.com/dev/reactions/list/
func (c *Client) GetReactions(messageID uint) (Reactions, error) {
switch {
case c == nil || c.engine == nil:
return nil, ErrNilClient
case messageID == 0:
return nil, ErrInvalidMessageID
}
var result Reactions
query := req.Query{"per": c.getBatchSize()}
for i := 1; i < 100; i++ {
query["page"] = i
resp := &struct {
Data Reactions `json:"data"`
}{}
err := c.sendRequest(
req.GET, getURL("/messages/%d/reactions", messageID),
query, nil, resp,
)
if err != nil {
return nil, fmt.Errorf("Can't fetch reactions for message %d: %w", messageID, err)
}
result = append(result, resp.Data...)
if len(resp.Data) != c.getBatchSize() {
break
}
}
return result, nil
}
// AddReaction adds given emoji reaction to the message
//
// https://crm.pachca.com/dev/reactions/new/
func (c *Client) AddReaction(messageID uint, emoji string) error {
switch {
case c == nil || c.engine == nil:
return ErrNilClient
case messageID == 0:
return ErrInvalidMessageID
case emoji == "":
return ErrBlankEmoji
}
err := c.sendRequest(
req.POST, getURL("/messages/%d/reactions", messageID),
req.Query{"code": emoji}, nil, nil,
)
if err != nil {
return fmt.Errorf("Can't add reaction %q to message %d: %w", emoji, messageID, err)
}
return nil
}
// DeleteReaction removes given emoji reaction from the message
//
// https://crm.pachca.com/dev/reactions/delete/
func (c *Client) DeleteReaction(messageID uint, emoji string) error {
switch {
case c == nil:
return ErrNilClient
case messageID == 0:
return ErrInvalidMessageID
case emoji == "":
return ErrBlankEmoji
}
err := c.sendRequest(
req.DELETE, getURL("/messages/%d/reactions", messageID),
req.Query{"code": emoji}, nil, nil,
)
if err != nil {
return fmt.Errorf("Can't remove reaction %q from message %d: %w", emoji, messageID, err)
}
return nil
}
// USERS //////////////////////////////////////////////////////////////////////////// //
// GetUser returns info about user
//
// https://crm.pachca.com/dev/users/get/
func (c *Client) GetUser(userID uint) (*User, error) {
switch {
case c == nil || c.engine == nil:
return nil, ErrNilClient
case userID == 0:
return nil, ErrInvalidUserID
}
resp := &struct {
Data *User `json:"data"`
}{}
err := c.sendRequest(
req.GET, getURL("/users/%d", userID),
nil, nil, resp,
)
if err != nil {
return nil, fmt.Errorf("Can't fetch user info: %w", err)
}
return resp.Data, nil
}
// GetUsers returns info about all users
//
// https://crm.pachca.com/dev/users/list/
func (c *Client) GetUsers(searchQuery ...string) (Users, error) {
if c == nil || c.engine == nil {
return nil, ErrNilClient
}
var result Users
query := req.Query{"per": c.getBatchSize()}
if len(searchQuery) != 0 {
query["query"] = searchQuery[0]
}
for i := 1; i < 100; i++ {
query["page"] = i
resp := &struct {
Data Users `json:"data"`
}{}
err := c.sendRequest(req.GET, getURL("/users"), query, nil, resp)
if err != nil {
return nil, fmt.Errorf("Can't fetch users: %w", err)
}
result = append(result, resp.Data...)
if len(resp.Data) != c.getBatchSize() {
break
}
}
return result, nil
}
// AddUser creates a new user
//
// https://crm.pachca.com/dev/users/new/
func (c *Client) AddUser(user *UserRequest) (*User, error) {
switch {
case c == nil || c.engine == nil:
return nil, ErrNilClient
case user == nil:
return nil, ErrNilUserRequest
case user.Email == "":
return nil, ErrEmptyUserEmail
}
payload := &struct {
User *UserRequest `json:"user"`
}{
User: user,
}
resp := &struct {
Data *User `json:"data"`
}{}
err := c.sendRequest(req.POST, getURL("/users"), nil, payload, resp)
if err != nil {
return nil, fmt.Errorf("Can't create a new user: %w", err)
}
return resp.Data, nil
}
// EditUser modifies an existing user
//
// https://crm.pachca.com/dev/users/update/
func (c *Client) EditUser(userID uint, user *UserRequest) (*User, error) {
switch {
case c == nil || c.engine == nil:
return nil, ErrNilClient
case userID == 0:
return nil, ErrInvalidUserID
case user == nil:
return nil, ErrNilUserRequest
}
payload := &struct {
User *UserRequest `json:"user"`
}{
User: user,
}
resp := &struct {
Data *User `json:"data"`
}{}
err := c.sendRequest(req.PUT, getURL("/users/%d", userID), nil, payload, resp)
if err != nil {
return nil, fmt.Errorf("Can't edit user %d: %w", userID, err)
}
return resp.Data, nil
}
// DeleteUser deletes an existing user
//
// https://crm.pachca.com/dev/users/delete/
func (c *Client) DeleteUser(userID uint) error {
switch {
case c == nil || c.engine == nil:
return ErrNilClient
case userID == 0:
return ErrInvalidUserID
}
err := c.sendRequest(req.DELETE, getURL("/users/%d", userID), nil, nil, nil)
if err != nil {
return fmt.Errorf("Can't delete user %d: %w", userID, err)
}
return nil
}
// GROUP TAGS /////////////////////////////////////////////////////////////////////// //
// GetTags returns all group tags
//
// https://crm.pachca.com/dev/group_tags/list/
func (c *Client) GetTags() (Tags, error) {
if c == nil || c.engine == nil {
return nil, ErrNilClient
}
var result Tags
query := req.Query{"per": c.getBatchSize()}
for i := 1; i < 100; i++ {
query["page"] = i
resp := &struct {
Data Tags `json:"data"`
}{}
err := c.sendRequest(req.GET, getURL("/group_tags"), query, nil, resp)
if err != nil {
return nil, fmt.Errorf("Can't fetch group tags: %w", err)
}
result = append(result, resp.Data...)
if len(resp.Data) != c.getBatchSize() {
break
}
}
return result, nil
}
// GetTag returns info about group tag with given ID
//
// https://crm.pachca.com/dev/group_tags/get/
func (c *Client) GetTag(groupTagID uint) (*Tag, error) {
switch {
case c == nil || c.engine == nil:
return nil, ErrNilClient
case groupTagID == 0:
return nil, ErrInvalidTagID
}
resp := &struct {
Data *Tag `json:"data"`
}{}
err := c.sendRequest(
req.GET, getURL("/group_tags/%d", groupTagID),
nil, nil, resp,
)
if err != nil {
return nil, fmt.Errorf("Can't fetch group tag: %w", err)
}
return resp.Data, nil
}
// GetTagUsers returns slice with users with given tag
//
// https://crm.pachca.com/dev/group_tags/users/
func (c *Client) GetTagUsers(groupTagID uint) (Users, error) {
switch {
case c == nil || c.engine == nil:
return nil, ErrNilClient
case groupTagID == 0:
return nil, ErrInvalidTagID
}
var result Users
query := req.Query{"per": c.getBatchSize()}
for i := 1; i < 100; i++ {
query["page"] = i
resp := &struct {
Data Users `json:"data"`
}{}
err := c.sendRequest(
req.GET, getURL("/group_tags/%d/users", groupTagID),
query, nil, resp,
)
if err != nil {
return nil, fmt.Errorf("Can't fetch group tag users: %w", err)
}
result = append(result, resp.Data...)
if len(resp.Data) != c.getBatchSize() {
break
}
}
return result, nil
}
// AddTag creates new group tag
//
// https://crm.pachca.com/dev/group_tags/new/
func (c *Client) AddTag(groupTagName string) (*Tag, error) {
switch {
case c == nil || c.engine == nil:
return nil, ErrNilClient
case groupTagName == "":
return nil, ErrEmptyTag
}
payload := &struct {
Name string `json:"name"`
}{
Name: groupTagName,
}
resp := &struct {
Data *Tag `json:"data"`
}{}
err := c.sendRequest(req.POST, getURL("/group_tags"), nil, payload, resp)
if err != nil {
return nil, fmt.Errorf("Can't create new group tag %q: %w", groupTagName, err)
}
return resp.Data, nil
}
// EditTag changes name of given group tag
//
// https://crm.pachca.com/dev/group_tags/update/
func (c *Client) EditTag(groupTagID uint, groupTagName string) (*Tag, error) {
switch {
case c == nil || c.engine == nil:
return nil, ErrNilClient
case groupTagID == 0:
return nil, ErrInvalidTagID
case groupTagName == "":
return nil, ErrEmptyTag
}
payload := &struct {
Name string `json:"name"`
}{
Name: groupTagName,
}
resp := &struct {
Data *Tag `json:"data"`
}{}
err := c.sendRequest(
req.PUT, getURL("/group_tags/%d", groupTagID),
nil, payload, resp,
)
if err != nil {
return nil, fmt.Errorf("Can't edit group tag %d: %w", groupTagID, err)
}
return resp.Data, nil
}
// DeleteTag removes group tag
//
// https://crm.pachca.com/dev/group_tags/delete/
func (c *Client) DeleteTag(groupTagID uint) error {
switch {
case c == nil || c.engine == nil:
return ErrNilClient
case groupTagID == 0:
return ErrInvalidTagID
}