from .. import controller from odoo import http from odoo.http import request import json import logging _logger = logging.getLogger(__name__) # class Wati(controller.Controller): # prefix = '/api/v1/' # # @http.route(prefix + 'wati/notification', auth='none', type='json', csrf=False, cors='*', methods=['POST', 'OPTIONS']) # def notification(self, **kw): # json_raw = json.loads(request.httprequest.data) # json_dump = json.dumps(json_raw, indent=4, sort_keys=True) # # request.env['wati.notification'].create([{ # 'json_raw': json_dump, # 'is_lead': False # }]) # # return # REPLACE webhook controller yang sudah ada dengan ini: class Wati(http.Controller): prefix = '/api/v1/' @http.route(prefix + 'wati/notification', auth='none', type='json', csrf=False, cors='*', methods=['POST', 'OPTIONS']) def notification(self, **kw): json_raw = json.loads(request.httprequest.data) json_dump = json.dumps(json_raw, indent=4, sort_keys=True) # Create notification record (existing) notification = request.env['wati.notification'].create([{ 'json_raw': json_dump, 'is_lead': False }]) # NEW: Immediate tags check phone = json_raw.get('waId') or json_raw.get('from') if phone: lead_id = self._check_tags_immediate(phone, notification[0]) if lead_id: notification.write({'is_lead': True, 'lead_id': lead_id}) _logger.info('🚀 Lead created immediately via webhook: %s' % lead_id) return {'status': 'success'} def _check_tags_immediate(self, phone, notification): """Check tags untuk specific phone - immediate""" try: _logger.info('📱 Immediate tags check for: %s' % phone) # Get contact dari WATI untuk phone ini wati_api = request.env['wati.api'] params = { 'pageSize': 1, 'pageNumber': 1, 'attribute': json.dumps([ {'name': "phone", 'operator': "contain", 'value': phone} ]), } result = wati_api.http_get('/api/v1/getContacts', params) if isinstance(result, dict) and result.get('result') == 'success': contact_list = result.get('contact_list', []) if contact_list: contact = contact_list[0] # Check if has tags=leads if self._contact_has_tags_leads(contact): # Check existing lead existing_lead = request.env['crm.lead'].search([('phone', '=', phone)], limit=1) if existing_lead: _logger.info('✅ Lead already exists for %s' % phone) return existing_lead.id # Create new lead lead_id = self._create_lead_from_webhook(contact) if lead_id: _logger.info('🎯 Created new lead %s from webhook tags' % lead_id) return lead_id return None except Exception as e: _logger.error('❌ Error in immediate tags check: %s' % str(e)) return None def _contact_has_tags_leads(self, contact): """Check if contact has tags=leads""" custom_params = contact.get('customParams', []) for param in custom_params: if (param.get('name', '').lower() == 'tags' and param.get('value', '').lower() == 'leads'): return True return False def _create_lead_from_webhook(self, contact): """Create lead dari webhook data""" try: phone = contact.get('phone', '') # Extract data dari customParams custom_params = contact.get('customParams', []) contact_data = {} for param in custom_params: param_name = param.get('name', '').lower() param_value = param.get('value', '').strip() if param_name == 'perusahaan': contact_data['perusahaan'] = param_value elif param_name == 'name': contact_data['name'] = param_value elif param_name == 'email': contact_data['email'] = param_value elif param_name == 'sales': contact_data['sales'] = param_value elif param_name == 'notes': contact_data['notes'] = param_value # Generate lead name company_name = contact_data.get('perusahaan', '') contact_name = contact_data.get('name', '') or contact.get('name', '') if company_name: lead_name = 'WATI Lead (Webhook) - %s' % company_name elif contact_name: lead_name = 'WATI Lead (Webhook) - %s' % contact_name else: lead_name = 'WATI Lead (Webhook) - %s' % phone # Get salesperson sales_name = contact_data.get('sales', '') user_id = 2 # Default if sales_name: user = request.env['res.users'].search([('name', 'ilike', sales_name)], limit=1) if user: user_id = user.id # Create lead lead_vals = { 'name': lead_name, 'phone': phone, 'contact_name': contact_name, 'partner_name': company_name, 'email_from': contact_data.get('email', ''), 'description': contact_data.get('notes', 'Lead created from WATI webhook (real-time)'), 'type': 'lead', 'user_id': user_id, } new_lead = request.env['crm.lead'].create(lead_vals) # Create activity untuk follow up request.env['mail.activity'].create({ 'activity_type_id': request.env.ref('mail.mail_activity_data_todo').id, 'summary': '🚨 URGENT: New WATI Lead (Real-time)', 'note': 'Lead created instantly from WATI webhook when tags=leads was added. Immediate follow up required!', 'res_id': new_lead.id, 'res_model_id': request.env.ref('crm.model_crm_lead').id, 'user_id': user_id, 'date_deadline': fields.Date.today(), }) return new_lead.id except Exception as e: _logger.error('❌ Error creating lead from webhook: %s' % str(e)) return None