-
Notifications
You must be signed in to change notification settings - Fork 2
/
portal_property_syncer.py
331 lines (274 loc) · 10.8 KB
/
portal_property_syncer.py
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
"""
HubSpot Portal property syncer.
"""
# Copyright 2017-2021 (c) Mayple. All rights reserved.
# Copying and/or distribution of this file is prohibited.
import dataclasses
from typing import Dict
from typing import List
from typing import Optional
import requests
from hubspot import HubSpot
from hubspot.crm.properties import ModelProperty
from hubspot.crm.properties import PropertyGroup
# For more info about the HubSpot API etc: https://developers.hubspot.com/docs/api/crm/properties
# And about the Python SDK: https://github.com/HubSpot/hubspot-api-python
# =======================================================================================================================
# Public Members
# =======================================================================================================================
@dataclasses.dataclass
class Portal:
portalId: int
name: str
apiKey: str
apiClient: Optional[HubSpot] = None
class ResultMessages:
def __init__(self, objectType: str, sourcePortal: Portal, targetPortal: Portal):
self._messages = []
self._objectType = objectType
self._sourcePortal = sourcePortal
self._targetPortal = targetPortal
def addMessage(self, message: str) -> None:
formattedMessage = f'{self._sourcePortal.name}->{self._targetPortal.name} ({self._objectType}): {message}'
self._messages.append(formattedMessage)
def getMessages(self) -> List[str]:
return self._messages
def preparePortal(portal: Portal) -> None:
if not portal.apiKey:
raise ValueError(
f'Missing API key for portal {portal.name}',
)
response = requests.get(
url=f'https://api.hubapi.com/integrations/v1/me?hapikey={portal.apiKey}',
)
readPortalId = response.json()['portalId']
assert readPortalId == portal.portalId
apiClient = HubSpot(api_key=portal.apiKey)
portal.apiClient = apiClient
def syncProperties(
objectType: str,
sourcePortal: Portal,
targetPortal: Portal,
) -> ResultMessages:
print(f"Syncing {objectType} properties and groups from source={sourcePortal.name} to target={targetPortal.name}")
resultMessages = ResultMessages(
objectType=objectType,
sourcePortal=sourcePortal,
targetPortal=targetPortal,
)
sourceContactPropertyGroups = sourcePortal.apiClient.crm.properties.groups_api.get_all(object_type=objectType)
sourceContactPropertyGroupsByName: Dict[str, PropertyGroup] = {
currentProperty.name: currentProperty
for currentProperty in sourceContactPropertyGroups.results
}
sourceContactProperties = sourcePortal.apiClient.crm.properties.core_api.get_all(object_type=objectType)
sourcePropertiesByName: Dict[str, ModelProperty] = {
currentProperty.name: currentProperty
for currentProperty in sourceContactProperties.results
}
targetContactPropertyGroups = targetPortal.apiClient.crm.properties.groups_api.get_all(object_type=objectType)
targetContactPropertyGroupsByName: Dict[str, PropertyGroup] = {
currentProperty.name: currentProperty
for currentProperty in targetContactPropertyGroups.results
}
targetContactProperties = targetPortal.apiClient.crm.properties.core_api.get_all(object_type=objectType)
targetPropertiesByName: Dict[str, ModelProperty] = {
currentProperty.name: currentProperty
for currentProperty in targetContactProperties.results
}
# PropertyGroups
# --------------
# Create missing:
for name, propertyGroup in sourceContactPropertyGroupsByName.items():
# Skip HS-owned
if name.startswith("hs_"):
print(
f'Skipped HubSpot-owned property group {name} in source',
)
continue
if not name in targetContactPropertyGroupsByName:
createPropertyGroupBasedOnOtherPropertyGroup(
resultMessages=resultMessages,
targetPortal=targetPortal,
objectType=objectType,
otherPropertyGroup=propertyGroup,
)
else:
# TODO: compare and sync
print(
f"Skipped source existing property group {name}: sync it manually, not yet implemented"
)
print("-------------")
# Report extra
for name, propertyGroup in targetContactPropertyGroupsByName.items():
# Skip HS-owned
if name.startswith("hs_"):
print(
f'Skipped HubSpot-owned property group {name} in target',
)
continue
if not name in sourceContactPropertyGroupsByName:
resultMessages.addMessage(
f"property group {name} is only in target - delete it "
f"manually or sync other way",
)
else:
# TODO: compare and sync
print(
f"Skipped target existing property group {name}: sync it manually, not yet implemented"
)
print("-------------")
# Properties
# ----------
# Create missing
for name, currentProperty in sourcePropertiesByName.items():
# Skip HS-owned
if name.startswith("hs_"):
print(
f'Skipped HubSpot-owned property {name} in source',
)
continue
if not name in targetPropertiesByName:
createPropertyBasedOnOtherProperty(
resultMessages=resultMessages,
targetPortal=targetPortal,
objectType=objectType,
otherProperty=currentProperty,
)
else:
# TODO: compare and sync
print(
f"Skipped source existing property {name}: sync it manually, not yet implemented"
)
print("-------------")
# Report extra
for name, currentProperty in targetPropertiesByName.items():
# Skip HS-owned
if name.startswith("hs_"):
print(
f'Skipped HubSpot-owned property group {name} in target',
)
continue
if not name in sourcePropertiesByName:
resultMessages.addMessage(
f"property {name} is only in target - delete it "
f"manually or sync other way",
)
else:
# TODO: compare and sync
print(
f"Skipped target existing property {name}: sync it manually, not yet implemented"
)
print("-------------")
return resultMessages
def createPropertyGroupBasedOnOtherPropertyGroup(
resultMessages: ResultMessages,
targetPortal: Portal,
objectType: str,
otherPropertyGroup: PropertyGroup,
) -> None:
try:
print(f"Creating new property group {otherPropertyGroup.name}")
targetPortal.apiClient.crm.properties.groups_api.create(
objectType,
property_group_create={
'name': otherPropertyGroup.name,
'label': otherPropertyGroup.label,
'displayOrder': otherPropertyGroup.display_order,
'archived': otherPropertyGroup.archived,
},
)
except Exception as e:
resultMessages.addMessage(
f'Failed creating new property group {otherPropertyGroup.name}: {e}',
)
def createPropertyBasedOnOtherProperty(
resultMessages: ResultMessages,
targetPortal: Portal,
objectType: str,
otherProperty: ModelProperty,
) -> None:
if otherProperty.calculated:
resultMessages.addMessage(
f'Skipped property {otherProperty.name}: it is a calculated property, create it manually.',
)
return
try:
print(f"Creating new property {otherProperty.name}")
targetPortal.apiClient.crm.properties.core_api.create(
objectType,
property_create={
'name': otherProperty.name,
'label': otherProperty.label,
'type': otherProperty.type,
'fieldType': otherProperty.field_type,
'groupName': otherProperty.group_name,
'description': otherProperty.description,
'options': otherProperty.options,
'displayOrder': otherProperty.display_order,
'hasUniqueValue': otherProperty.has_unique_value,
'hidden': otherProperty.hidden,
'formField': otherProperty.form_field,
'calculated': otherProperty.calculated,
'externalOptions': otherProperty.external_options,
'hubspotDefined': otherProperty.hubspot_defined,
'referencedObjectType': otherProperty.referenced_object_type,
'showCurrencySymbol': otherProperty.show_currency_symbol,
},
)
except Exception as e:
resultMessages.addMessage(
f'Failed creating new property {otherProperty.name}: {e}',
)
# =======================================================================================================================
# Private Members
# =======================================================================================================================
# =======================================================================================================================
# Main
# =======================================================================================================================
if __name__ == "__main__":
portal1Portal = Portal(
portalId=111111,
name="portal1",
apiKey="",
)
preparePortal(portal1Portal)
portal2Portal = Portal(
portalId=222222,
name="portal2",
apiKey="",
)
preparePortal(portal2Portal)
portal3Portal = Portal(
portalId=3333333,
name="portal3",
apiKey=""
)
preparePortal(portal3Portal)
portal4Portal = Portal(
portalId=444444,
name="portal4",
apiKey="",
)
preparePortal(portal4Portal)
portalPairs = [
(portal1Portal, portal2Portal),
(portal2Portal, portal3Portal),
(portal3Portal, portal4Portal),
]
allMessages = []
for currentSourcePortal, currentTargetPortal, in portalPairs:
for currentObjectType in [
"contact",
"company",
"deal",
"ticket",
]:
currentResultMessages = syncProperties(
objectType=currentObjectType,
sourcePortal=currentSourcePortal,
targetPortal=currentTargetPortal,
)
allMessages.extend(currentResultMessages.getMessages())
print("Requires manual attention:")
print('\n'.join(allMessages))