summaryrefslogtreecommitdiff
path: root/fixco_custom/models/upload_ginee.py
blob: cfab74a92dc2c2acaf9e963f113b024e192c80c6 (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
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
from odoo import models, fields, api, _
from datetime import datetime
import base64
import xlrd
from odoo.exceptions import ValidationError, UserError
import requests
import json
import hmac
from hashlib import sha256

API_BASE_URL = "https://api.ginee.com"
BATCH_GET_URI = '/openapi/order/v1/batch-get'
LIST_ORDER_URI = '/openapi/order/v2/list-order'
ACCESS_KEY = '24bb6a1ec618ec6a'
SECRET_KEY = '32e4a78ad05ee230'

class UploadGinee(models.Model):
    _name = "upload.ginee"
    _description = "Upload Ginee"
    _order = "create_date desc"
    _rec_name = "number"

    ginee_lines = fields.One2many('upload.ginee.line', 'upload_ginee_id', 
                                  string='Lines', copy=False, auto_join=True)
    number = fields.Char('Number', copy=False)
    date_upload = fields.Datetime('Upload Date', copy=False)
    user_id = fields.Many2one('res.users', 'Created By', default=lambda self: self.env.user.id)
    excel_file = fields.Binary('Excel File', attachment=True)
    filename = fields.Char('File Name')

    @api.model
    def create(self, vals):
        vals['number'] = self.env['ir.sequence'].next_by_code('upload.ginee') or '/'
        return super().create(vals)

    def action_import_excel(self):
        self.ensure_one()
        if not self.excel_file:
            raise ValidationError(_("Please upload an Excel file first."))
        
        try:
            file_content = base64.b64decode(self.excel_file)
            workbook = xlrd.open_workbook(file_contents=file_content)
            sheet = workbook.sheet_by_index(0)
        except:
            raise ValidationError(_("Invalid Excel file format."))
        
        header = [str(sheet.cell(0, col).value).strip().lower() for col in range(sheet.ncols)]
        expected_headers = ['marketplace', 'shop', 'invoice']
        
        if not all(h in header for h in expected_headers):
            raise ValidationError(_("Invalid Excel format. Expected columns: Marketplace, Shop, Invoice"))
        
        marketplace_col = header.index('marketplace')
        shop_col = header.index('shop')
        invoice_col = header.index('invoice')
        
        line_vals_list = []
        for row in range(1, sheet.nrows):
            try:
                marketplace = str(sheet.cell(row, marketplace_col).value).strip()
                shop = str(sheet.cell(row, shop_col).value).strip()
                invoice_marketplace = str(sheet.cell(row, invoice_col).value).strip()
                
                line_vals = {
                    'marketplace': marketplace,
                    'shop': shop,
                    'invoice_marketplace': invoice_marketplace,
                    'upload_ginee_id': self.id,
                }
                line_vals_list.append((0, 0, line_vals))
            except Exception as e:
                continue
        
        self.ginee_lines.unlink()
        self.write({
            'ginee_lines': line_vals_list,
        })
        
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': _('Success'),
                'message': _('Imported %s lines from Excel.') % len(line_vals_list),
                'sticky': False,
                'next': {'type': 'ir.actions.act_window_close'},
            }
        }


    def _show_notification(self, message):
        return {
            'type': 'ir.actions.client',
            'tag': 'display_notification',
            'params': {
                'title': _('Success'),
                'message': message,
                'sticky': False,
            }
        }

    def action_get_order_id(self):
        self.date_upload = datetime.utcnow()
        self.ginee_lines.get_order_id()

    def action_create_detail_order(self):
        self.date_upload = datetime.utcnow()
        self.ginee_lines.create_so_and_detail_order()

    def action_get_order_id_and_create_detail_order(self):
        self.date_upload = datetime.utcnow()
        self.ginee_lines.get_order_id()
        self.ginee_lines.create_so_and_detail_order()
            
class UploadGineeLine(models.Model):
    _name = "upload.ginee.line"
    _description = "Upload Ginee Line"
    _inherit = ['mail.thread']

    upload_ginee_id = fields.Many2one('upload.ginee', string='Upload')
    marketplace = fields.Char('Marketplace')
    shop = fields.Char('Shop')
    invoice_marketplace = fields.Char('Invoice Marketplace')
    order_id = fields.Char('Order ID')
    message_error = fields.Text('Error Message')
    detail_order_id = fields.Many2one('detail.order', string='Detail Order')

    def _sign_request(self, uri):
        """Membuat tanda tangan sesuai format yang berhasil"""
        sign_data = f'POST${uri}$'
        signature = hmac.new(
            SECRET_KEY.encode('utf-8'),
            sign_data.encode('utf-8'),
            digestmod=sha256
        ).digest()
        return f"{ACCESS_KEY}:{base64.b64encode(signature).decode('ascii')}"

    def _call_api(self, uri, payload):
        """Memanggil API dengan autentikasi yang benar"""
        headers = {
            'Content-Type': 'application/json',
            'X-Advai-Country': 'ID',
            'Authorization': self._sign_request(uri)
        }
        
        response = requests.post(
            f"{API_BASE_URL}{uri}",
            headers=headers,
            data=json.dumps(payload)
        )
        
        if response.status_code != 200:
            error_msg = f"API Error ({response.status_code}): {response.text}"
            raise UserError(_(error_msg))
        
        return response.json()

    def create_so_and_detail_order(self):
        try:
            for rec in self:
                if not rec.order_id:
                    raise UserError(_('Order ID is empty!'))
                
                if self.env['detail.order'].search([('detail_order', 'ilike', rec.order_id)]):
                    raise UserError(_(
                        "Order ID %s already exists in Detail Orders") % rec.order_id)
                
                data = self._call_api(BATCH_GET_URI, {"orderIds": [rec.order_id]})
                detail_order = self.env['detail.order'].create({
                    'detail_order': json.dumps(data, indent=4),
                    'source': 'manual',
                })
                detail_order.execute_queue_detail()
                
                rec.update({
                    'message_error': 'Success',
                    'detail_order_id': detail_order.id
                })
        except Exception as e:
            self.message_error = str(e)

    def get_order_id(self):
        try:
            for rec in self:
                if self.search_count([
                    ('marketplace', '=', rec.marketplace),
                    ('invoice_marketplace', '=', rec.invoice_marketplace),
                    ('id', '!=', rec.id)
                ]):
                    raise UserError(_(
                        "Invoice %s already exists") % rec.invoice_marketplace)
                
                data = self._call_api(
                    LIST_ORDER_URI,
                    {
                        "channel": rec.marketplace,
                        "orderNumbers": [rec.invoice_marketplace]
                    }
                )
                
                orders = data.get('data', {}).get('content', [])
                if orders:
                    rec.order_id = orders[0].get('orderId')
                    rec.message_error = 'Success'
                else:
                    raise UserError(_("No orders found for invoice: %s") % self.invoice_marketplace)
        except Exception as e:
            self.message_error = str(e)