-
Notifications
You must be signed in to change notification settings - Fork 4
/
res_partner_address.py
330 lines (289 loc) · 12.7 KB
/
res_partner_address.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
# -*- coding: utf-8 -*-
from osv import osv
from tools.translate import _
import logging
from hashlib import md5
import mailchimp_marketing as MailchimpMarketing
from mailchimp_marketing.api_client import ApiClientError
from oorq.decorators import job
from tools import config
FIELDS_NO_MEMBERS = {
"zip_code": "MMERGE10",
"province": "MMERGE7",
"region": "MMERGE8",
"name": "MMERGE9",
"comarca": "MMERGE6",
"municipality": "MMERGE5",
"member_num": "MMERGE4",
"lang": "MMERGE3",
"surname": "LNAME",
"firstname": "FNAME",
"email": "EMAIL",
}
FIELDS_SOCIS = {
"Cognoms, nom": "MMERGE5",
"NumSoci": "MMERGE4",
"E-mail": "EMAIL",
"Categoria": "MMERGE2",
"Ciutat": "MMERGE3",
"Provincia": "MMERGE6",
"CodiPostal": "MMERGE7",
"Idioma": "MMERGE8",
"Empresa": "MMERGE9",
"Telefon": "MMERGE10", # (###)###-####
"Comarca": "MMERGE11",
"NIF": "MMERGE1",
"comunitat_autonoma": "MMERGE13",
"Enllac": "MMERGE12",
"Generation": "MMERGE14",
"No rebre condicions generals": "MMERGE15",
"Assamblea Virtual": "MMERGE16",
"Nom empresa": "MMERGE17",
"Proj. Transicio Energet": "MMERGE18",
"Compra Coletiva": "MMERGE19",
}
class ResPartnerAddress(osv.osv):
"""Class to manage Mailchimp lists subscriptions"""
_name = "res.partner.address"
_inherit = "res.partner.address"
def write(self, cursor, uid, ids, vals, context=None):
if context is None:
context = {}
if not isinstance(ids, (list, tuple)):
ids = [ids]
MAILCHIMP_CLIENT = MailchimpMarketing.Client(
dict(
api_key=config.options.get("mailchimp_apikey"),
server=config.options.get("mailchimp_server_prefix"),
)
)
if "email" in vals:
for _id in ids:
old_email = self.read(cursor, uid, _id, ["email"])["email"]
email = vals["email"]
if not old_email or old_email == email:
continue
if not email:
self.unsubscribe_client_email_in_all_lists_async(
cursor, uid, _id, old_email, MAILCHIMP_CLIENT
)
else:
self.update_client_email_in_all_lists_async(
cursor, uid, _id, old_email, email, MAILCHIMP_CLIENT
)
return super(ResPartnerAddress, self).write(cursor, uid, ids, vals, context=context)
@staticmethod
def get_mailchimp_list_id(list_name, mailchip_conn):
all_lists = mailchip_conn.lists.get_all_lists(fields=["lists.id,lists.name"], count=100)[
"lists"
]
for lis in all_lists:
if lis["name"] == list_name:
return lis["id"]
raise osv.except_osv(_("Error"), _("List: <{}> not found".format(list_name)))
@job(queue="mailchimp_tasks")
def archieve_mail_in_list(self, cursor, uid, ids, list_id, mailchimp_conn, context=None):
self.archieve_mail_in_list_sync(cursor, uid, ids, list_id, mailchimp_conn, context=None)
def archieve_mail_in_list_sync(self, cursor, uid, ids, list_id, mailchimp_conn, context=None):
if not isinstance(ids, (list, tuple)):
ids = [ids]
logger = logging.getLogger("openerp.{0}.archieve_mail_in_list".format(__name__))
email_addresses = self.read(cursor, uid, ids, ["email"])
for email in email_addresses:
subscriber_hash = md5(email["email"].lower()).hexdigest()
try:
mailchimp_conn.lists.delete_list_member(
list_id=list_id, subscriber_hash=subscriber_hash
)
except ApiClientError as error:
if error.status_code == 404:
logger.warning(
"L'API no ha permès arxivar l'email {}. "
"Error comú quan el mail no es troba a la llista: "
"Error de l'API: {}".format(email, error.text)
)
elif error.status_code == 405:
logger.warning(
"L'API no ha permès arxivar l'email {}. "
"Error comú quan el mail ja ha estat arxivat de la llista: "
"Error de l'API: {}".format(email, error.text)
)
else:
raise osv.except_osv(
_("Error"), _("Error archieving email {}:\n{}".format(email, error.text))
)
else:
logger.info("Email arxivat: {}".format(email))
def fill_merge_fields_clients(self, cursor, uid, id, context=None):
partner_obj = self.pool.get("res.partner")
municipi_obj = self.pool.get("res.municipi")
self.pool.get("res.comunitat.autonoma")
partner_data = self.read(cursor, uid, id, ["partner_id", "email", "zip", "id_municipi"])
partner_fields = partner_obj.read(
cursor, uid, partner_data["partner_id"][0], ["name", "lang"]
)
mailchimp_member = {
"email_address": partner_data["email"],
"status": "subscribed",
"merge_fields": {
FIELDS_NO_MEMBERS["name"]: partner_fields["name"],
FIELDS_NO_MEMBERS["lang"]: partner_fields["lang"],
FIELDS_NO_MEMBERS["surname"]: partner_fields["name"].split(",")[0],
FIELDS_NO_MEMBERS["firstname"]: partner_fields["name"].split(",")[-1],
FIELDS_NO_MEMBERS["email"]: partner_data["email"],
FIELDS_NO_MEMBERS["zip_code"]: partner_data["zip"],
},
}
if partner_data["id_municipi"]:
municipi_data = municipi_obj.browse(cursor, uid, partner_data["id_municipi"][0])
comarca_name = ""
if municipi_data.comarca:
comarca_name = municipi_data.comarca.name
provincia_name = municipi_data.state.name
ccaa_name = municipi_data.state.comunitat_autonoma.name
mailchimp_member["merge_fields"].update(
{
FIELDS_NO_MEMBERS["province"]: provincia_name,
FIELDS_NO_MEMBERS["region"]: ccaa_name,
FIELDS_NO_MEMBERS["comarca"]: comarca_name,
FIELDS_NO_MEMBERS["municipality"]: municipi_data.name,
}
)
return mailchimp_member
def fill_merge_fields_soci(self, cursor, uid, id, context=None):
partner_obj = self.pool.get("res.partner")
municipi_obj = self.pool.get("res.municipi")
self.pool.get("res.comunitat.autonoma")
partner_data = self.read(
cursor, uid, id, ["partner_id", "email", "zip", "id_municipi", "mobile", "phone"]
)
partner_fields = partner_obj.read(
cursor, uid, partner_data["partner_id"][0], ["name", "lang", "vat", "ref"]
)
mailchimp_member = {
"email_address": partner_data["email"],
"status": "subscribed",
"merge_fields": {
FIELDS_SOCIS["Cognoms, nom"]: partner_fields["name"],
FIELDS_SOCIS["Idioma"]: partner_fields["lang"],
FIELDS_SOCIS["E-mail"]: partner_data["email"],
FIELDS_SOCIS["CodiPostal"]: partner_data["zip"],
FIELDS_SOCIS["NIF"]: partner_fields["vat"],
FIELDS_SOCIS["NumSoci"]: partner_fields["ref"],
FIELDS_SOCIS["Telefon"]: partner_data["phone"]
if partner_data["phone"]
else partner_data["mobile"],
},
}
if partner_data["id_municipi"]:
municipi_data = municipi_obj.browse(cursor, uid, partner_data["id_municipi"][0])
comarca_name = ""
if municipi_data.comarca:
comarca_name = municipi_data.comarca.name
provincia_name = municipi_data.state.name
ccaa_name = municipi_data.state.comunitat_autonoma.name
mailchimp_member["merge_fields"].update(
{
FIELDS_SOCIS["Provincia"]: provincia_name,
FIELDS_SOCIS["comunitat_autonoma"]: ccaa_name,
FIELDS_SOCIS["Comarca"]: comarca_name,
FIELDS_SOCIS["Ciutat"]: municipi_data.name,
}
)
return mailchimp_member
@job(queue="mailchimp_tasks")
def subscribe_mail_in_list(
self, cursor, uid, clients_data, list_id, mailchimp_conn, context=None
):
logger = logging.getLogger("openerp.{0}.subscribe_mail_in_list".format(__name__))
for client_data in clients_data:
try:
mailchimp_conn.lists.add_list_member(list_id, client_data)
except ApiClientError as e:
if e.status_code == 400 and e.text.title == "Member Exists":
logger.warning(
"El correu {} que intentem subscriure ja esta subscrit."
"Error de l'API: {}".format(client_data["email_address"], e.text)
)
else:
raise osv.except_osv(
_("Error"),
_(
"Error en subscriure l'email {}:\n{}".format(
client_data["email_address"], e.text
)
),
)
@job(queue="mailchimp_tasks")
def update_client_email_in_all_lists_async(
self, cursor, uid, ids, old_email, email, mailchimp_conn, context=None
):
self.update_client_email_in_all_lists(
cursor, uid, ids, old_email, email, mailchimp_conn, context=None
)
def update_client_email_in_all_lists(
self, cursor, uid, ids, old_email, email, mailchimp_conn, context=None
):
if not isinstance(ids, (list, tuple)):
ids = [ids]
logger = logging.getLogger("openerp.{0}.update_client_email_in_all_lists".format(__name__))
all_lists = mailchimp_conn.lists.get_all_lists(
fields=["lists.id,lists.name"], count=100, email=old_email
)["lists"]
for _id in ids:
for mchimp_list in all_lists:
list_id = mchimp_list["id"]
subscriber_hash = md5(old_email.lower()).hexdigest()
new_subscriber_hash = md5(email.lower()).hexdigest()
try:
mailchimp_conn.lists.get_list_member(list_id, subscriber_hash)
except Exception:
continue
client_data = {}
client_data["email_address"] = email
client_data["merge_fields"] = {FIELDS_NO_MEMBERS["email"]: email}
try:
mailchimp_conn.lists.update_list_member(list_id, subscriber_hash, client_data)
except ApiClientError as e:
logger.warning(
"Error en update l'email {} en la llista {}:\n{}".format(
client_data["email_address"], mchimp_list["name"], e.text
)
)
else:
mailchimp_conn.lists.create_list_member_note(
list_id,
new_subscriber_hash,
{
"note": "S'ha actualitzat l'e-mail {} per {} vía ERP".format(
old_email, email
)
},
)
logger.info(
"L'email {} s'ha actualitzat en la llista {}".format(
client_data["email_address"], mchimp_list["name"]
)
)
@job(queue="mailchimp_tasks")
def unsubscribe_client_email_in_all_lists_async(
self, cursor, uid, ids, old_email, mailchimp_conn, context=None
):
self.unsubscribe_client_email_in_all_lists(
cursor, uid, ids, old_email, mailchimp_conn, context=None
)
def unsubscribe_client_email_in_all_lists(
self, cursor, uid, ids, old_email, mailchimp_conn, context=None
):
if not isinstance(ids, (list, tuple)):
ids = [ids]
logging.getLogger(
"openerp.{0}.unsubscribe_client_email_in_all_lists".format(__name__)
)
all_lists = mailchimp_conn.lists.get_all_lists(
fields=["lists.id,lists.name"], count=100, email=old_email
)["lists"]
for mchimp_list in all_lists:
list_id = mchimp_list["id"]
self.archieve_mail_in_list_sync(cursor, uid, ids, list_id, mailchimp_conn)
ResPartnerAddress()