summaryrefslogtreecommitdiff
path: root/indoteknik_api/controllers/api_v1/wati.py
blob: d60cd1602e7c8083ed4736b80f8836a1e3b9f08b (plain)
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
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