More civicrm exports.
[wolnelektury.git] / src / club / civicrm.py
1 from datetime import datetime
2 import json
3 from celery import shared_task
4 from django.conf import settings
5 import requests
6 import yaml
7
8
9 class CiviCRM:
10     def __init__(self, base, key):
11         self.base = base
12         self.key = key
13         self.api_base = (base or '') + 'civicrm/ajax/api4/'
14         self.enabled = bool(self.base and self.key)
15
16     def request(self, resource, method, params):
17         if not self.enabled:
18             return
19
20         response = requests.post(
21             self.api_base + f'{resource}/{method}',
22             params={
23                 'params': json.dumps(params),
24                 'api_key': self.key
25             },
26         )
27         d = response.json()
28         return d
29
30     def create_or_update_contact(self, email, fields=None):
31         contact_id = self.get_contact_id(email)
32         if contact_id is None:
33             contact_id = self.create_contact(email, fields)
34         elif fields:
35             self.update_contact(contact_id, fields)
36         return contact_id
37
38     def get_contact_id(self, email):
39         result = self.request(
40             'Contact',
41             'get',
42             {
43                 "join": [["Email AS email", "LEFT"]],
44                 "where":[["email.email", "=", email]],
45                 "limit":1,
46                 "debug":True
47             }
48         )['values']
49         if result:
50             return result[0]['id']
51
52     def create_contact(self, email, fields):
53         data = {
54             'values': {},
55             'chain': {
56                 'email': [
57                     'Email',
58                     'create',
59                     {
60                         'values': {
61                             'email': email,
62                             'contact_id': '$id'
63                         }
64                     }
65                 ]
66             }
67         }
68         if fields:
69             data['values'].update(fields)
70         result = self.request('Contact', 'create', data)
71         return result['values'][0]['id']
72
73     def update_phone(self, contact_id, phone):
74         if self.request('Phone', 'get', {'where': [['phone', "=", phone], ['contact_id', "=",  contact_id]]})['count']:
75             return
76         self.request('Phone', 'create', {'values': {'phone': phone, 'contact_id': contact_id}})
77
78     def update_contact(self, contact_id, fields):
79         return self.request(
80             'Contact',
81             'update',
82             {
83                 'values': fields,
84                 'where': [
85                     ['id', '=', contact_id]
86                 ]
87             }
88         )
89                 
90
91     def report_activity(self, email, tpwl_key, key, name, datetime, details):
92         if not self.enabled:
93             return
94
95         fields = {'WL.TPWL_key': tpwl_key}
96         contact_id = self.create_or_update_contact(email, fields)
97
98         activity_id = self.get_activity_id(key)
99         if activity_id is None:
100             self.create_activity(
101                 contact_id,
102                 key,
103                 name,
104                 datetime,
105                 details
106             )
107         else:
108             self.update_activity(
109                 activity_id,
110                 contact_id,
111                 name,
112                 datetime,
113                 details
114             )
115
116     def get_activity_id(self, key):
117         result = self.request(
118             'Activity',
119             'get',
120             {
121                 'where': [
122                     ['subject', '=', key],
123                 ]
124             }
125         )['values']
126         if result:
127             return result[0]['id']
128     
129     def create_activity(self, contact_id, key, name, date_time, details):
130         detail_str = yaml.dump(details)
131         return self.request(
132             'Activity',
133             'create',
134             {
135                 'values': {
136                     'source_contact_id': contact_id,
137                     'activity_type_id:name': name,
138                     'status_id:name': 'Completed',
139                     'activity_date_time': date_time.isoformat() if date_time else '',
140                     'details' : detail_str,
141                     'subject': key,
142                 },
143                 'debug': True,
144             }
145         )
146
147     def update_activity(self, activity_id, contact_id, name, date_time, details):
148         detail_str = yaml.dump(details)
149
150         self.request(
151             'Activity',
152             'update',
153             {
154                 'values': {
155                     'source_contact_id': contact_id,
156                     'activity_type_id:name': name,
157                     'status_id:name': 'Completed',
158                     'activity_date_time': date_time.isoformat(),
159                     'details' : detail_str,
160                 },
161                 'where': [
162                     ['id', '=', activity_id]
163                 ]
164             }
165         )
166     
167     def add_email_to_group(self, email, group_id):
168         contact_id = self.create_or_update_contact(email)
169         self.add_contact_to_group(contact_id, group_id)
170
171     def add_contact_to_group(self, contact_id, group_id):
172         self.request(
173             'GroupContact',
174             'create',
175             {
176                 "values": {
177                     "group_id": group_id,
178                     "contact_id": contact_id,
179                 }
180             }
181         )
182
183
184 civicrm = CiviCRM(
185     settings.CIVICRM_BASE,
186     settings.CIVICRM_KEY,
187 )
188
189 @shared_task(ignore_result=True)
190 def report_activity(*args, **kwargs):
191     civicrm.report_activity(*args, **kwargs)
192
193