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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
|
from odoo import fields, models, api
from datetime import datetime, timedelta
import logging
import json
import requests
_logger = logging.getLogger(__name__)
class WatiNotification(models.Model):
_name = 'wati.notification'
lead_id = fields.Many2one('crm.lead', string='Lead Id')
ticket_id = fields.Char(string='Ticked Id')
mobile = fields.Char(string='Mobile')
sender_name = fields.Char(string='Sender Name')
text = fields.Char(string='Text Message')
text_time = fields.Datetime(string='Text Time')
text_type = fields.Char(string='Text Type')
json_raw = fields.Char(string='JSON Raw Text')
is_parsed = fields.Boolean(string='Is Parsed', default=False)
is_lead = fields.Boolean(string='To Leads', help='apakah sudah ter-convert jadi leads')
def _cleanup(self):
current_time = datetime.now()
delta_time = current_time - timedelta(days=15)
delta_time = delta_time.strftime('%Y-%m-%d %H:%M:%S')
self.env['wati.notification'].search([
('create_date', '<', delta_time),
('is_lead', '=', True),
]).unlink()
_logger.info('Success Cleanup WATI Notification')
def _parse_notification(self, limit=0):
domain = [('is_parsed', '=', False)]
notifications = self.search(domain, order='id', limit=limit)
notification_not_parsed_count = self.search_count(domain)
i = 0
for notification in notifications:
i += 1
_logger.info('[Parse Notification][%s] Process: %s/%s | Not Parsed: %s' %
(notification.id, i, str(limit), str(notification_not_parsed_count)))
notification_json = json.loads(notification.json_raw)
sender_name = 'Indoteknik'
if 'senderName' in notification_json:
sender_name = notification_json['senderName']
ticket_id = notification_json.get('ticketId')
timestamp = notification_json.get('timestamp')
if not timestamp:
_logger.warning('[Parse Notification][%s] Missing timestamp in notification JSON: %s' %
(notification.id, notification.json_raw))
continue # Skip this notification
try:
date_wati = datetime.fromtimestamp(float(timestamp))
except ValueError as e:
_logger.error('[Parse Notification][%s] Invalid timestamp format: %s. Error: %s' %
(notification.id, timestamp, str(e)))
continue
wati_history = self.env['wati.history'].search([('ticket_id', '=', ticket_id)], limit=1)
if wati_history:
self._create_wati_history_line(wati_history, ticket_id, sender_name, notification_json, date_wati)
else:
new_header = self._create_wati_history_header(ticket_id, sender_name, notification_json, date_wati)
self._create_wati_history_line(new_header, ticket_id, sender_name, notification_json, date_wati)
notification.is_parsed = True
return
def _create_wati_history_header(self, ticket_id, sender_name, notification_json, date_wati):
# Helper function to remove NUL characters
def remove_null_characters(value):
if isinstance(value, str):
return value.replace('\0', '')
return value
# Sanitize the input data
param_header = {
'ticket_id': ticket_id,
'conversation_id': remove_null_characters(notification_json.get('conversationId', '')),
'sender_name': remove_null_characters(sender_name),
'wa_id': remove_null_characters(notification_json.get('waId', '')),
'text': remove_null_characters(notification_json.get('text', '')),
'date_wati': remove_null_characters(date_wati or ''),
}
# Create the record
new_header = self.env['wati.history'].create([param_header])
return new_header
def _create_wati_history_line(self, new_header, ticket_id, sender_name, notification_json, date_wati):
# Helper function to remove NUL characters
def remove_null_characters(value):
if isinstance(value, str):
return value.replace('\0', '')
return value
# Sanitize the input data
param_line = {
"wati_history_id": new_header.id,
"conversation_id": remove_null_characters(notification_json.get('conversationId', '')),
"data": remove_null_characters(notification_json.get('data', '')),
"event_type": remove_null_characters(notification_json.get('eventType', '')),
"operator_email": remove_null_characters(notification_json.get('operatorEmail', '')),
"operator_name": remove_null_characters(notification_json.get('operatorName', '')),
"sender_name": remove_null_characters(sender_name or ''),
"status_string": remove_null_characters(notification_json.get('statusString', '')),
"text": remove_null_characters(notification_json.get('text', '')),
"ticket_id": ticket_id,
"type": remove_null_characters(notification_json.get('type', '')),
"wa_id": remove_null_characters(notification_json.get('waId', '')),
"date_wati": remove_null_characters(date_wati or ''),
}
# Create the record safely without NUL characters
self.env['wati.history.line'].create([param_line])
self._update_header_after_create_line(new_header, sender_name, date_wati, param_line['text'])
return
def _update_header_after_create_line(self, new_header, sender_name, date_wati, text_body):
new_header.last_reply_by = sender_name
new_header.last_reply_date = date_wati
new_header.last_reply_text = text_body
if sender_name == 'Indoteknik':
current_time = date_wati
delta_time = current_time + timedelta(days=1)
new_header.expired_date = delta_time
# this commented code not run smoothly, need more time
# change to scheduler
# if not new_header.perusahaan or not new_header.email:
# self._get_attribute_wati(new_header)
return
def _convert_to_leads(self):
query = [
('is_lead', '=', False)
]
watis = self.env['wati.notification'].search(query, order='id')
for wati in watis:
_logger.info('Convert to Lead WATI Notification ID %s' % wati.id)
ticket_id = json.loads(wati.json_raw)['ticketId']
text = json.loads(wati.json_raw)['text']
current_lead = self.env['crm.lead'].search([('ticket_id', '=', ticket_id)], limit=1)
operator_email = json.loads(wati.json_raw)['operatorEmail']
operator_name = json.loads(wati.json_raw)['operatorName']
event_type = json.loads(wati.json_raw)['eventType']
if event_type == 'sessionMessageSent':
if 'Saya *Eko*' in str(text):
sales = 11
elif 'Saya *Nabila*' in str(text):
sales = 20
elif 'Saya *Novita*' in str(text):
sales = 377
elif 'Saya *Putri*' in str(text):
sales = 10
elif 'Saya *Heriyanto*' in str(text):
sales = 375
elif 'Saya *Ade*' in str(text):
sales = 9
elif 'Saya *Adela*' in str(text):
sales = 8
elif 'Saya *Jananto*' in str(text):
sales = 376
elif 'Saya *Dwi*' in str(text):
sales = 24
else:
sales = 25 #System
current_lead.description = str(current_lead.description)+ "| i:" + str(text)
current_lead.operator_email = operator_email
current_lead.operator_name = operator_name
current_lead.user_id = sales
elif current_lead:
# must append internal notes as a reply here
current_lead.description = str(current_lead.description) + " | c:" +str(text)
current_lead.operator_email = operator_email
current_lead.operator_name = operator_name
else:
# create new leads
contact_name = json.loads(wati.json_raw)['senderName']
phone = json.loads(wati.json_raw)['waId']
name = 'Ada pesan dari WATI '+str(phone)+' '+str(contact_name)
current_lead = self.env['crm.lead'].create([{
'name': name,
'ticket_id': ticket_id,
'operator_email': operator_email,
'operator_name': operator_name,
'contact_name': contact_name,
'phone': phone,
'description': "c:" +str(text)
}])
wati.is_lead = True
wati.lead_id = current_lead.id
# FINAL CODE - Sesuai dengan mapping table Anda
def check_wati_tags_leads(self):
"""Check tags 'leads' di WATI dan create leads di Odoo - Final Version"""
_logger.info('=== Starting WATI Tags Check (Final) ===')
wati_api = self.env['wati.api']
total_leads_created = 0
try:
# Get WATI contacts
wati_contacts = wati_api.http_get('/api/v1/getContacts', {'pageSize': 100, 'pageNumber': 1})
if isinstance(wati_contacts, dict) and wati_contacts.get('result') == 'success':
contact_list = wati_contacts.get('contact_list', [])
for contact in contact_list:
if self._create_lead_if_tagged(contact):
total_leads_created += 1
_logger.info('WATI check completed: %s leads created' % total_leads_created)
return {'leads_created': total_leads_created}
except Exception as e:
_logger.error('Error in WATI tags check: %s' % str(e))
return {'leads_created': 0, 'error': str(e)}
def _create_lead_if_tagged(self, contact):
"""Create lead jika contact punya tags=leads - Sesuai Mapping Table"""
try:
# Check tags leads
if not self._has_tags_leads(contact):
return False
phone = contact.get('phone', '')
if not phone:
return False
# Check existing lead by phone
existing_lead = self.env['crm.lead'].search([('phone', '=', phone)], limit=1)
if existing_lead:
_logger.info('Lead already exists for phone %s' % phone)
return False
# Extract data dari customParams sesuai mapping table
custom_params = contact.get('customParams', [])
contact_data = self._extract_contact_data(custom_params)
# Create lead dengan field mapping yang sesuai
lead_vals = {
'name': self._generate_lead_name(contact_data, contact),
'phone': phone, # Phone Number → Mobile
'contact_name': contact_data.get('name', ''), # Name → Contact Name
'partner_name': contact_data.get('perusahaan', ''), # Perusahaan → Company Name
'email_from': contact_data.get('email', ''), # Email → Email
'description': contact_data.get('notes', ''), # Notes → Internal Notes
'type': 'lead',
'user_id': self._get_salesperson_id(contact_data.get('sales', '')), # Sales → Salesperson
}
new_lead = self.env['crm.lead'].create(lead_vals)
_logger.info('Created WATI lead %s for %s (%s)' % (new_lead.id, contact_data.get('name', 'Unknown'), phone))
return True
except Exception as e:
_logger.error('Error creating lead: %s' % str(e))
return False
def _extract_contact_data(self, custom_params):
"""Extract data dari customParams sesuai mapping table"""
contact_data = {}
for param in custom_params:
param_name = param.get('name', '').lower()
param_value = param.get('value', '').strip()
# Mapping sesuai table:
if param_name == 'perusahaan': # Perusahaan → Company Name
contact_data['perusahaan'] = param_value
elif param_name == 'name': # Name → Contact Name
contact_data['name'] = param_value
elif param_name == 'email': # Email → Email
contact_data['email'] = param_value
elif param_name == 'sales': # Sales → Salesperson
contact_data['sales'] = param_value
elif param_name == 'notes': # Notes → Internal Notes
contact_data['notes'] = param_value
# Phone Number sudah diambil dari contact.phone
return contact_data
def _generate_lead_name(self, contact_data, contact):
"""Generate lead name sesuai mapping: Judul Leads berdasarkan company/contact"""
company_name = contact_data.get('perusahaan', '')
contact_name = contact_data.get('name', '') or contact.get('name', '')
if company_name:
return 'WATI Lead - %s' % company_name
elif contact_name:
return 'WATI Lead - %s' % contact_name
else:
return 'WATI Lead - %s' % contact.get('phone', 'Unknown')
def _get_salesperson_id(self, sales_name):
"""Get salesperson ID dari nama - Sales → Salesperson"""
if not sales_name:
return 2 # Default Sales (ID 2)
# Try find user by name
user = self.env['res.users'].search([
('name', 'ilike', sales_name)
], limit=1)
if user:
return user.id
else:
# Fallback ke default Sales
return 2
def _has_tags_leads(self, contact):
"""Check apakah ada tags untuk tajik ke odoo => Leads"""
custom_params = contact.get('customParams', [])
for param in custom_params:
param_name = param.get('name', '').lower()
param_value = param.get('value', '').lower()
# Check: "Judul Tags untuk tajik ke odoo => Leads"
if param_name == 'tags' and param_value == 'leads':
return True
return False
def manual_check_tags(self):
"""Manual trigger untuk testing"""
result = self.check_wati_tags_leads()
message = 'WATI Tags Check Completed!\n\n'
message += 'Leads Created: %s\n\n' % result.get('leads_created', 0)
message += 'Field Mapping:\n'
message += '• Perusahaan → Company Name\n'
message += '• Name → Contact Name\n'
message += '• Email → Email\n'
message += '• Sales → Salesperson\n'
message += '• Phone Number → Mobile\n'
message += '• Notes → Internal Notes\n'
message += '• Tags=leads → Trigger Lead Creation'
if result.get('error'):
message += '\n\nError: %s' % result['error']
message_type = 'warning'
else:
message_type = 'success'
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
'params': {
'title': 'WATI Tags Check',
'message': message,
'type': message_type,
'sticky': True,
}
}
class WatiHistory(models.Model):
_name = 'wati.history'
_order = 'id desc'
ticket_id = fields.Char(string='Ticket ID')
conversation_id = fields.Char(string='Conversation ID')
sender_name = fields.Char(string='Sender Name')
wa_id = fields.Char(string='WA ID')
text = fields.Char(string='Text')
date_wati = fields.Datetime(string='Date WATI')
wati_lines = fields.One2many('wati.history.line', 'wati_history_id', string='Lines', auto_join=True)
last_reply_by = fields.Char(string='Last Reply by')
last_reply_text = fields.Char(string='Last Reply Text')
last_reply_date = fields.Datetime(string='Last Reply Date')
expired_date = fields.Datetime(string='Expired Date')
email = fields.Char(string='Email')
perusahaan = fields.Char(string='Perusahaan')
is_get_attribute = fields.Boolean(string='Get Attribute', default=False)
def _get_attribute_wati(self):
domain = [
'&',
('is_get_attribute', '=', False),
'|',
('perusahaan', '=', False),
('email', '=', False),
]
limit = 50
wati_histories = self.env['wati.history'].search(domain, limit=limit)
count = 0
for wati_history in wati_histories:
count += 1
_logger.info('[Parse Notification] Processing: %s/%s', count, limit)
wati_api = self.env['wati.api']
# Perbaikan pada parameter JSON
params = {
'pageSize': 1,
'pageNumber': 1,
'attribute': json.dumps([
{'name': "phone", 'operator': "contain", 'value': wati_history.wa_id}
]),
}
try:
wati_contacts = wati_api.http_get('/api/v1/getContacts', params)
except Exception as e:
_logger.error('Error while calling WATI API: %s', str(e))
continue
# Validasi respons dari API
if not isinstance(wati_contacts, dict):
_logger.error('Invalid response format from WATI API: %s', wati_contacts)
continue
if wati_contacts.get('result') != 'success':
_logger.warning('WATI API request failed with result: %s', wati_contacts.get('result'))
continue
contact_list = wati_contacts.get('contact_list', [])
if not contact_list:
_logger.info('No contacts found for WA ID: %s', wati_history.wa_id)
continue
perusahaan = email = ''
for data in contact_list:
custom_params = data.get('customParams', [])
for custom_param in custom_params:
name = custom_param.get('name')
value = custom_param.get('value')
if name == 'perusahaan':
perusahaan = value
elif name == 'email':
email = value
# Update wati_history fields
wati_history.write({
'perusahaan': perusahaan,
'email': email,
'is_get_attribute': True,
})
_logger.info('Wati history updated: %s', wati_history.id)
# @api.onchange('last_reply_date')
# def _compute_expired_date(self):
# if self.last_reply_by == 'Indoteknik':
# return
# else:
# print(1)
# current_time = self.last_reply_date
# # current_time_str = current_time.strftime('%Y-%m-%d %H:%M:%S')
# delta_time = current_time + timedelta(days=1)
# # delta_time_str = delta_time.strftime('%Y-%m-%d %H:%M:%S')
# self.expired_date = delta_time
# return
class WatiHistoryLine(models.Model):
_name = 'wati.history.line'
#sender
wati_history_id = fields.Many2one('ref', required=True, ondelete='cascade', index=True, copy=False)
conversation_id = fields.Char(string='Conversation ID')
data = fields.Char(string='data')
event_type = fields.Char(string='Event Type')
list_reply = fields.Char(string='List Reply')
message_contact = fields.Char(string='Message Contact')
operator_email = fields.Char(string='Operator Email')
operator_name = fields.Char(string='Operator Name')
sender_name = fields.Char(string='Sender Name')
source_url = fields.Char(string='Source URL')
status_string = fields.Char(string='Status String')
text = fields.Char(string='Text')
ticket_id = fields.Char(string='Ticket ID')
type = fields.Char(string='Type')
wa_id = fields.Char(string='WA ID')
date_wati = fields.Datetime(string='Date WATI')
|