1 from datetime import datetime
3 from celery import shared_task
4 from django.conf import settings
10 def __init__(self, base, key):
13 self.api_base = (base or '') + 'civicrm/ajax/api4/'
14 self.enabled = bool(self.base and self.key)
16 def request(self, resource, method, params):
20 response = requests.post(
21 self.api_base + f'{resource}/{method}',
23 'params': json.dumps(params),
30 def create_or_update_contact(self, email, key=None):
31 contact_id = self.get_contact_id(email)
32 if contact_id is None:
33 contact_id = self.create_contact(email, key)
35 self.update_contact(contact_id, key)
38 def get_contact_id(self, email):
39 result = self.request(
43 "join": [["Email AS email", "LEFT"]],
44 "where":[["email.email", "=", email]],
50 return result[0]['id']
52 def create_contact(self, email, key=None):
69 data['values']['WL.TPWL_key'] = key
70 result = self.request('Contact', 'create', data)
71 return result['values'][0]['id']
73 def update_contact(self, contact_id, key):
82 ['id', '=', contact_id]
88 def report_activity(self, email, tpwl_key, key, name, datetime, details):
92 contact_id = self.create_or_update_contact(email, tpwl_key)
94 activity_id = self.get_activity_id(key)
95 if activity_id is None:
104 self.update_activity(
112 def get_activity_id(self, key):
113 result = self.request(
118 ['subject', '=', key],
123 return result[0]['id']
125 def create_activity(self, contact_id, key, name, date_time, details):
126 detail_str = yaml.dump(details)
132 'source_contact_id': contact_id,
133 'activity_type_id:name': name,
134 'status_id:name': 'Completed',
135 'activity_date_time': date_time.isoformat() if date_time else '',
136 'details' : detail_str,
143 def update_activity(self, activity_id, contact_id, name, date_time, details):
144 detail_str = yaml.dump(details)
151 'source_contact_id': contact_id,
152 'activity_type_id:name': name,
153 'status_id:name': 'Completed',
154 'activity_date_time': date_time.isoformat(),
155 'details' : detail_str,
158 ['id', '=', activity_id]
163 def add_email_to_group(self, email, group_id):
164 contact_id = self.create_or_update_contact(email)
165 self.add_contact_to_group(contact_id, group_id)
167 def add_contact_to_group(self, contact_id, group_id):
173 "group_id": group_id,
174 "contact_id": contact_id,
181 settings.CIVICRM_BASE,
182 settings.CIVICRM_KEY,
185 @shared_task(ignore_result=True)
186 def report_activity(*args, **kwargs):
187 civicrm.report_activity(*args, **kwargs)