python-amcards 1.5.1__tar.gz → 1.6.1__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
1
  Metadata-Version: 2.4
2
2
  Name: python-amcards
3
- Version: 1.5.1
3
+ Version: 1.6.1
4
4
  Summary: A wrapper for the AMcards API.
5
5
  Home-page: https://github.com/simonesestili/python-amcards
6
6
  Author: Simone Sestili
@@ -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"""
@@ -279,6 +279,7 @@ class Campaign:
279
279
  send_if_duplicate: bool,
280
280
  has_anniversary_drip: bool = False,
281
281
  has_birthday_drip: bool = False,
282
+ total_cost: int = 0,
282
283
  ) -> None:
283
284
  self._id = id
284
285
  self._name = name
@@ -286,6 +287,7 @@ class Campaign:
286
287
  self._send_if_duplicate = send_if_duplicate
287
288
  self._has_anniversary_drip = has_anniversary_drip
288
289
  self._has_birthday_drip = has_birthday_drip
290
+ self._total_cost = total_cost
289
291
 
290
292
  __repr__ = helpers.repr
291
293
 
@@ -319,6 +321,11 @@ class Campaign:
319
321
  """True if one of more drips in this campaign are birthday drips. False otherwise."""
320
322
  return self._has_birthday_drip
321
323
 
324
+ @property
325
+ def total_cost(self) -> int:
326
+ """Drip campaign's total cost in `cents`."""
327
+ return self._total_cost
328
+
322
329
  @classmethod
323
330
  def _from_json(cls, json: dict):
324
331
  return cls(
@@ -328,6 +335,7 @@ class Campaign:
328
335
  send_if_duplicate=json['send_even_if_duplicate'],
329
336
  has_anniversary_drip=json['has_anniversary_drip'],
330
337
  has_birthday_drip=json['has_birthday_drip'],
338
+ total_cost=json['campaign_cost'],
331
339
  )
332
340
 
333
341
  class CardStatus(Enum):
@@ -868,6 +876,56 @@ class CampaignResponse:
868
876
  shipping_address=json['shipping_address'],
869
877
  )
870
878
 
879
+ class CampaignMultiResponse:
880
+ """Represents AMcards' response for sending a drip campaign to multiple contacts."""
881
+ def __init__(
882
+ self,
883
+ mailing_id: int,
884
+ contacts_scheduled_count: int,
885
+ duplicate_contacts_count: int,
886
+ message: str,
887
+ ) -> None:
888
+ self._mailing_id = mailing_id
889
+ self._contacts_scheduled_count = contacts_scheduled_count
890
+ self._duplicate_contacts_count = duplicate_contacts_count
891
+ self._message = message
892
+
893
+ __repr__ = helpers.repr
894
+
895
+ @property
896
+ def mailing_id(self) -> int:
897
+ """Unique id for the :py:class:`mailing <amcards.models.Mailing>` created."""
898
+ return self._mailing_id
899
+
900
+ @property
901
+ def mailing_link(self) -> str:
902
+ """This is the link to the mailing list inside of AMcards.com."""
903
+ return f'https://amcards.com/cards/history/?mailing={self._mailing_id}'
904
+
905
+ @property
906
+ def contacts_scheduled_count(self) -> int:
907
+ """Number of contacts scheduled for the drip campaign."""
908
+ return self._contacts_scheduled_count
909
+
910
+ @property
911
+ def duplicate_contacts_count(self) -> int:
912
+ """Number of contacts that were duplicates and not scheduled."""
913
+ return self._duplicate_contacts_count
914
+
915
+ @property
916
+ def message(self) -> str:
917
+ """Represents AMcards' response message for sending a drip campaign to multiple contacts."""
918
+ return self._message
919
+
920
+ @classmethod
921
+ def _from_json(cls, json: dict):
922
+ return cls(
923
+ mailing_id=json['mailing_id'],
924
+ contacts_scheduled_count=json['contacts_scheduled_count'],
925
+ duplicate_contacts_count=json['duplicate_contacts_count'],
926
+ message=json['message'],
927
+ )
928
+
871
929
  class CardsResponse:
872
930
  """Represents AMcards' response for sending multiple cards."""
873
931
  def __init__(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: python-amcards
3
- Version: 1.5.1
3
+ Version: 1.6.1
4
4
  Summary: A wrapper for the AMcards API.
5
5
  Home-page: https://github.com/simonesestili/python-amcards
6
6
  Author: Simone Sestili
@@ -7,7 +7,7 @@ def README():
7
7
 
8
8
  setup(
9
9
  name='python-amcards',
10
- version='1.5.1',
10
+ version='1.6.1',
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