python-amcards 1.5.0__tar.gz → 1.6.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: python-amcards
3
- Version: 1.5.0
3
+ Version: 1.6.0
4
4
  Summary: A wrapper for the AMcards API.
5
5
  Home-page: https://github.com/simonesestili/python-amcards
6
6
  Author: Simone Sestili
@@ -14,6 +14,15 @@ Classifier: Programming Language :: Python :: 3.10
14
14
  Description-Content-Type: text/x-rst
15
15
  License-File: LICENSE
16
16
  Requires-Dist: requests>=2
17
+ Dynamic: author
18
+ Dynamic: author-email
19
+ Dynamic: classifier
20
+ Dynamic: description
21
+ Dynamic: description-content-type
22
+ Dynamic: home-page
23
+ Dynamic: license-file
24
+ Dynamic: requires-dist
25
+ Dynamic: summary
17
26
 
18
27
  Getting Started | See the full docs at `Read the Docs <https://python-amcards.readthedocs.io/en/latest/>`_
19
28
  ==========================================================================================================
@@ -11,6 +11,26 @@ REQUIRED_SHIPPING_ADDRESS_FIELDS = {
11
11
  'postal_code',
12
12
  }
13
13
 
14
+ REQUIRED_CONTACT_FIELDS = {
15
+ 'first_name',
16
+ 'last_name',
17
+ 'address_line_1',
18
+ 'city',
19
+ 'state',
20
+ 'postal_code',
21
+ }
22
+
23
+ OPTIONAL_CONTACT_FIELDS = {
24
+ 'country',
25
+ 'organization',
26
+ 'phone_number',
27
+ 'birth_date',
28
+ 'anniversary_date',
29
+ 'third_party_contact_id',
30
+ 'address_line_2',
31
+ 'extra_data',
32
+ }
33
+
14
34
  CARD_OPTIONAL_SHIPPING_ADDRESS_FIELDS = {
15
35
  'country',
16
36
  'organization',
@@ -122,6 +142,13 @@ def sanitize_shipping_address_for_campaign_send(shipping_address: dict) -> dict:
122
142
  sanitized_shipping_address[optional] = shipping_address[optional]
123
143
  return sanitized_shipping_address
124
144
 
145
+ def sanitize_contact_for_campaign_multi_send(contact: dict) -> dict:
146
+ sanitized_contact = {field: contact[field] for field in REQUIRED_CONTACT_FIELDS}
147
+ for optional in OPTIONAL_CONTACT_FIELDS:
148
+ if not contact.get(optional): continue
149
+ sanitized_contact[optional] = contact[optional]
150
+ return sanitized_contact
151
+
125
152
  def sanitize_return_address(return_address: dict) -> dict:
126
153
  sanitized_return_address = {}
127
154
  for optional in OPTIONAL_RETURN_ADDRESS_FIELDS:
@@ -2,7 +2,7 @@ import requests
2
2
  from typing import List, Optional, Callable, Any
3
3
 
4
4
 
5
- from .models import User, Template, Gift, Campaign, CardResponse, CardsResponse, CampaignResponse, Card, Contact, Mailing, CreditTransaction
5
+ from .models import User, Template, Gift, Campaign, CardResponse, CardsResponse, CampaignResponse, CampaignMultiResponse, Card, Contact, Mailing, CreditTransaction
6
6
  from . import exceptions
7
7
  from . import __helpers as helpers
8
8
 
@@ -1059,6 +1059,136 @@ class AMcardsClient:
1059
1059
  'shipping_address': shipping_address,
1060
1060
  })
1061
1061
 
1062
+ def send_campaign_multi(
1063
+ self,
1064
+ campaign_id: str | int,
1065
+ initiator: str,
1066
+ contacts: List[dict],
1067
+ ) -> CampaignMultiResponse:
1068
+ """Attempt to send a drip campaign to multiple contacts.
1069
+
1070
+ .. code-block::
1071
+
1072
+ >>> from amcards import AMcardsClient
1073
+ >>> client = AMcardsClient('youraccesstoken')
1074
+ >>> res = client.send_campaign_multi(
1075
+ ... campaign_id='123',
1076
+ ... initiator='myintegration123',
1077
+ ... contacts=[
1078
+ ... {
1079
+ ... 'first_name': 'Ralph',
1080
+ ... 'last_name': 'Mullins',
1081
+ ... 'address_line_1': '2285 Reppert Road',
1082
+ ... 'city': 'Southfield',
1083
+ ... 'state': 'MI',
1084
+ ... 'postal_code': '48075',
1085
+ ... 'country': 'US'
1086
+ ... },
1087
+ ... {
1088
+ ... 'first_name': 'Keith',
1089
+ ... 'last_name': 'May',
1090
+ ... 'address_line_1': '364 Spruce Drive',
1091
+ ... 'city': 'Philadelphia',
1092
+ ... 'state': 'PA',
1093
+ ... 'postal_code': '19107',
1094
+ ... 'country': 'US'
1095
+ ... }
1096
+ ... ]
1097
+ ... )
1098
+ >>> res.mailing_id
1099
+ 29695
1100
+ >>> res.contacts_scheduled_count
1101
+ 2
1102
+ >>> res.duplicate_contacts_count
1103
+ 0
1104
+ >>> res.message
1105
+ 'Cards scheduled successfully. Debited $8.84 credits. This may take a few minutes to complete.'
1106
+
1107
+ :param str or int campaign_id: Unique id for the :py:class:`drip campaign <amcards.models.Campaign>` you are sending.
1108
+ :param str initiator: Unique identifier of client's user so if multiple users use a single AMcards.com account, a drip campaign can be identified per person.
1109
+ :param List[dict] contacts: List of contact details. Here's an example how the list might look, make sure you include all of the `required` keys for each dict in the list:
1110
+
1111
+ .. code-block::
1112
+
1113
+ [
1114
+ {
1115
+ 'first_name': 'Ralph',
1116
+ 'last_name': 'Mullins',
1117
+ 'address_line_1': '2285 Reppert Road',
1118
+ 'city': 'Southfield',
1119
+ 'state': 'MI',
1120
+ 'postal_code': '48075',
1121
+ 'country': 'US',
1122
+ 'organization': 'Google', # OPTIONAL
1123
+ 'phone_number': '15556667777', # OPTIONAL
1124
+ 'birth_date': '2003-12-25', # OPTIONAL
1125
+ 'anniversary_date': '2022-10-31', # OPTIONAL
1126
+ 'third_party_contact_id': 'crmid1453131', # OPTIONAL
1127
+ 'address_line_2': 'Apt 2' # OPTIONAL
1128
+ 'extra_data': { # OPTIONAL
1129
+ 'carMake': 'Honda', # OPTIONAL
1130
+ } # OPTIONAL
1131
+ },
1132
+ ]
1133
+
1134
+ :return: AMcards' :py:class:`response <amcards.models.CampaignMultiResponse>` for sending a drip campaign to multiple contacts.
1135
+ :rtype: :py:class:`CampaignMultiResponse <amcards.models.CampaignMultiResponse>`
1136
+
1137
+ :raises CampaignMultiSendError: When something goes wrong when attempting to send a drip campaign.
1138
+ :raises AuthenticationError: When the client's ``access_token`` is invalid.
1139
+ :raises ShippingAddressError: When ``contacts`` is missing some `required` keys.
1140
+ :raises DateFormatError: When one of the dates provided is not in ``"YYYY-MM-DD"`` format.
1141
+ :raises PhoneFormatError: When the ``phone_number`` is not a digit string of length 10.
1142
+ :raises InsufficientCreditsError: When the client's user has insufficient credits in their balance.
1143
+
1144
+ """
1145
+ # Validate contacts
1146
+ for idx, contact in enumerate(contacts):
1147
+ missings = helpers.get_missing_required_shipping_address_fields(contact)
1148
+ if missings:
1149
+ error_message = f'Missing the following required shipping address fields at contacts[{idx}]: ' + ', '.join(missings)
1150
+ raise exceptions.ShippingAddressError(error_message)
1151
+
1152
+ # Sanitize contacts
1153
+ contacts = [helpers.sanitize_contact_for_campaign_multi_send(contact) for contact in contacts]
1154
+
1155
+ for idx, contact in enumerate(contacts):
1156
+ # Validate birth_date
1157
+ if 'birth_date' in contact and not helpers.is_valid_birthdate(contact['birth_date']):
1158
+ error_message = f'Invalid birth_date format of "{contact["birth_date"]}" for contact at contacts[{idx}], please specify date as "YYYY-MM-DD", or omit it'
1159
+ raise exceptions.DateFormatError(error_message)
1160
+ # Validate anniversary_date
1161
+ if 'anniversary_date' in contact and not helpers.is_valid_date(contact['anniversary_date']):
1162
+ error_message = f'Invalid anniversary_date format of "{contact["anniversary_date"]}" for contact at contacts[{idx}], please specify date as "YYYY-MM-DD", or omit it'
1163
+ raise exceptions.DateFormatError(error_message)
1164
+ # Validate phone_number
1165
+ if 'phone_number' in contact and not helpers.is_valid_phone(contact['phone_number']):
1166
+ error_message = f'Invalid phone_number format of "{contact["phone_number"]}" for contact at contacts[{idx}], please specify phone as a 10 number string with no special formatting (ex. 15556667777), or omit it'
1167
+ raise exceptions.PhoneFormatError(error_message)
1168
+ if 'extra_data' in contact:
1169
+ contact['extra_data'] = helpers.sanitize_extra_data(contact['extra_data'])
1170
+
1171
+ # Build request json payload
1172
+ body = {
1173
+ 'campaign_id': campaign_id,
1174
+ 'initiator': initiator,
1175
+ 'contacts': contacts,
1176
+ }
1177
+
1178
+ res = requests.post(f'{DOMAIN}/campaigns/open-campaign-multi-form/', json=body, headers=self._HEADERS)
1179
+
1180
+ # Check for errors
1181
+ match res.status_code:
1182
+ case 400:
1183
+ raise exceptions.CampaignMultiSendError('Something went wrong when attempting to send a drip campaign')
1184
+ case 401:
1185
+ raise exceptions.AuthenticationError('Access token provided to client is unauthorized')
1186
+ case 402:
1187
+ raise exceptions.InsufficientCreditsError('Clients\' user has insufficient credits, no cards were scheduled')
1188
+
1189
+ res_json = res.json()
1190
+ return CampaignMultiResponse._from_json(res_json)
1191
+
1062
1192
  def send_cards(
1063
1193
  self,
1064
1194
  template_id: str | int,
@@ -51,5 +51,8 @@ class CardsSendError(AMcardsException):
51
51
  class CampaignSendError(AMcardsException):
52
52
  """Something went wrong when attempting to send a drip campaign"""
53
53
 
54
+ class CampaignMultiSendError(AMcardsException):
55
+ """Something went wrong when attempting to send a drip campaign to multiple contacts"""
56
+
54
57
  class OAuthTokenRefreshError(AMcardsException):
55
58
  """Something went wrong when attempting to refresh AMcards access_token"""
@@ -19,6 +19,7 @@ class User:
19
19
  phone: str,
20
20
  date_joined: datetime,
21
21
  address_line_1: str,
22
+ address_line_2: str,
22
23
  city: str,
23
24
  state: str,
24
25
  postal_code: str,
@@ -36,6 +37,7 @@ class User:
36
37
  self._phone = phone
37
38
  self._date_joined = date_joined
38
39
  self._address_line_1 = address_line_1
40
+ self._address_line_2 = address_line_2
39
41
  self._city = city
40
42
  self._state = state
41
43
  self._postal_code = postal_code
@@ -88,9 +90,14 @@ class User:
88
90
  """Primary address line of user."""
89
91
  return self._address_line_1
90
92
 
93
+ @property
94
+ def address_line_2(self) -> str:
95
+ """Secondary address line of user."""
96
+ return self._address_line_2
97
+
91
98
  @property
92
99
  def city(self) -> str:
93
- """User's state."""
100
+ """User's city."""
94
101
  return self._city
95
102
 
96
103
  @property
@@ -142,6 +149,7 @@ class User:
142
149
  phone=json['phone'],
143
150
  date_joined=helpers.to_datetime(json['date_joined']),
144
151
  address_line_1=json['address_line_1'],
152
+ address_line_2=json.get('address_line_2', ''),
145
153
  city=json['city'],
146
154
  state=json['state'],
147
155
  postal_code=json['postal'],
@@ -860,6 +868,56 @@ class CampaignResponse:
860
868
  shipping_address=json['shipping_address'],
861
869
  )
862
870
 
871
+ class CampaignMultiResponse:
872
+ """Represents AMcards' response for sending a drip campaign to multiple contacts."""
873
+ def __init__(
874
+ self,
875
+ mailing_id: int,
876
+ contacts_scheduled_count: int,
877
+ duplicate_contacts_count: int,
878
+ message: str,
879
+ ) -> None:
880
+ self._mailing_id = mailing_id
881
+ self._contacts_scheduled_count = contacts_scheduled_count
882
+ self._duplicate_contacts_count = duplicate_contacts_count
883
+ self._message = message
884
+
885
+ __repr__ = helpers.repr
886
+
887
+ @property
888
+ def mailing_id(self) -> int:
889
+ """Unique id for the :py:class:`mailing <amcards.models.Mailing>` created."""
890
+ return self._mailing_id
891
+
892
+ @property
893
+ def mailing_link(self) -> str:
894
+ """This is the link to the mailing list inside of AMcards.com."""
895
+ return f'https://amcards.com/cards/history/?mailing={self._mailing_id}'
896
+
897
+ @property
898
+ def contacts_scheduled_count(self) -> int:
899
+ """Number of contacts scheduled for the drip campaign."""
900
+ return self._contacts_scheduled_count
901
+
902
+ @property
903
+ def duplicate_contacts_count(self) -> int:
904
+ """Number of contacts that were duplicates and not scheduled."""
905
+ return self._duplicate_contacts_count
906
+
907
+ @property
908
+ def message(self) -> str:
909
+ """Represents AMcards' response message for sending a drip campaign to multiple contacts."""
910
+ return self._message
911
+
912
+ @classmethod
913
+ def _from_json(cls, json: dict):
914
+ return cls(
915
+ mailing_id=json['mailing_id'],
916
+ contacts_scheduled_count=json['contacts_scheduled_count'],
917
+ duplicate_contacts_count=json['duplicate_contacts_count'],
918
+ message=json['message'],
919
+ )
920
+
863
921
  class CardsResponse:
864
922
  """Represents AMcards' response for sending multiple cards."""
865
923
  def __init__(
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.4
2
2
  Name: python-amcards
3
- Version: 1.5.0
3
+ Version: 1.6.0
4
4
  Summary: A wrapper for the AMcards API.
5
5
  Home-page: https://github.com/simonesestili/python-amcards
6
6
  Author: Simone Sestili
@@ -14,6 +14,15 @@ Classifier: Programming Language :: Python :: 3.10
14
14
  Description-Content-Type: text/x-rst
15
15
  License-File: LICENSE
16
16
  Requires-Dist: requests>=2
17
+ Dynamic: author
18
+ Dynamic: author-email
19
+ Dynamic: classifier
20
+ Dynamic: description
21
+ Dynamic: description-content-type
22
+ Dynamic: home-page
23
+ Dynamic: license-file
24
+ Dynamic: requires-dist
25
+ Dynamic: summary
17
26
 
18
27
  Getting Started | See the full docs at `Read the Docs <https://python-amcards.readthedocs.io/en/latest/>`_
19
28
  ==========================================================================================================
@@ -7,7 +7,7 @@ def README():
7
7
 
8
8
  setup(
9
9
  name='python-amcards',
10
- version='1.5.0',
10
+ version='1.6.0',
11
11
  description='A wrapper for the AMcards API.',
12
12
  long_description=README(),
13
13
  long_description_content_type='text/x-rst',
File without changes
File without changes