summaryrefslogtreecommitdiff
path: root/indoteknik_custom/models/wati_contact.py
blob: bdef0e048306c4965f60252269513d3c26e8edf0 (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
from odoo import models
import logging
import math

_logger = logging.getLogger('[Update Attribute Wati Contact]')


class WatiContact(models.Model):
    _name = 'wati.contact'

    def update_attribute_wati_contact(self):
        wati_api = self.env['wati.api']
        res_partner = self.env['res.partner']
        total_synced = 0

        has_next = True
        page_number = 0
        while has_next:
            page_number += 1
            wati_contacts = wati_api.http_get('/api/v1/getContacts', {
                'pageSize': 1,
                'pageNumber': page_number
            })
            if wati_contacts['result'] != 'success':
                continue
            page_size = wati_contacts['link']['pageSize']
            total = wati_contacts['link']['total']
            page_total = math.ceil(total / page_size)
            offset = (page_number - 1) * page_size
            current = 0
            _logger.info('=== Page: %s | Page Total: %s' % (str(page_number), str(page_total)))
            for contact in wati_contacts['contact_list']:
                current += 1
                _logger.info('= Process: %s/%s' % (str(offset + current), str(total)))
                params = [('mobile', '=', contact['phone'])]
                partner = res_partner.search(params, limit=1)
                if not partner:
                    continue

                company = partner.parent_id or partner
                attributes = [{'name': 'perusahaan', 'value': company.name}]
                email = partner.email or company.email
                if email:
                    attributes.append({'name': 'email', 'value': email})
                sales = partner.user_id or company.user_id
                if sales:
                    attributes.append({'name': 'sales', 'value': sales.name})
                attributes.append({'name': 'sync', 'value': 'true'})

                endpoint = '/api/v1/updateContactAttributes/%s' % contact['phone']
                wati_api.http_post(endpoint, {'customParams': attributes})
                total_synced += 1
            has_next = wati_contacts['link']['nextPage'] is not None
        _logger.info('=== Total Synced: %s ===' % str(total_synced))
        return