summaryrefslogtreecommitdiff
path: root/fixco_custom/models/webhook_ginee.py
blob: 1ee814fa882eced642bdd2d7d432805f1bbfceef (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
from odoo import api, fields, models, _
from odoo.exceptions import UserError
import time
import requests
import json
import hmac
import base64
from hashlib import sha256

Request_URI = '/openapi/order/v1/batch-get'
ACCESS_KEY = '24bb6a1ec618ec6a'
SECRET_KEY = '32e4a78ad05ee230'

class WebhookGinee(models.Model):
    _name = "webhook.ginee"
    _inherit = ['mail.thread']

    json_ginee = fields.Text()
    execute_status = fields.Selection([
        ('success', 'Success'),
        ('failed', 'Failed'),
        ('done', 'Done'),
        ('not_found', 'Record not found')
    ], 'Execute Status')

    def get_order_id(self):
        try:
            if self.json_ginee: 
                json_data = json.loads(self.json_ginee)
                order_id = json_data.get('payload', {}).get('orderId')
                if not order_id:
                    raise UserError(_("Order ID not found in JSON data"))
                return order_id 
            raise UserError(_("No JSON data available"))
        except json.JSONDecodeError:
            raise UserError(_("Invalid JSON format in json_ginee field"))
        except Exception as e:
            raise UserError(_("Error extracting order ID: %s") % str(e))

    def process_queue_item(self, limit=100, max_exec_time=30):
        domain = [('execute_status', '=', False)]
        records = self.search(domain, order='create_date asc', limit=limit)
        start_time = time.time()
        for rec in records:
            end_time = time.time()
            elapsed_time = end_time - start_time
            if elapsed_time > max_exec_time:
                break
            rec.execute_queue()

    def execute_queue(self):
        try:
            # Get order ID from json_ginee
            order_id = self.get_order_id()
            
            authorization = self.sign_request()
            headers = {
                'Content-Type': 'application/json',
                'X-Advai-Country': 'ID',
                'Authorization': authorization
            }
            
            payload = {
                "orderIds": [order_id]
            }
            
            # URL endpoint Ginee
            url = "https://api.ginee.com/openapi/order/v1/batch-get"
            
            # Melakukan POST request
            response = requests.post(
                url,
                headers=headers,
                data=json.dumps(payload)
            )
            
            # Cek status response
            if response.status_code == 200:
                data = response.json()
                detail_order = self.env['detail.order'].create({
                    'detail_order': json.dumps(data),
                    'execute_status': 'success'
                })
                self.execute_status = 'done'
            else:
                self.write({
                    'execute_status': 'failed',
                    'json_ginee': json.dumps({
                        'error': f"Request failed with status code {response.status_code}",
                        'response': response.text
                    })
                })
                
        except Exception as e:
            self.write({
                'execute_status': 'failed',
                'json_ginee': json.dumps({
                    'error': str(e)
                })
            })

    def sign_request(self):
        signData = '$'.join(['POST', Request_URI]) + '$'
        authorization = ACCESS_KEY + ':' + base64.b64encode(
            hmac.new(SECRET_KEY.encode('utf-8'), signData.encode('utf-8'), digestmod=sha256).digest()
        ).decode('ascii')
        return authorization