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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
|
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
import logging
_logger = logging.getLogger(__name__)
Request_URI = '/openapi/order/v1/batch-get'
ACCESS_KEY = '24bb6a1ec618ec6a'
SECRET_KEY = '32e4a78ad05ee230'
class DetailOrder(models.Model):
_name = "detail.order"
_inherit = ['mail.thread']
json_ginee = fields.Text('JSON Ginee')
detail_order = fields.Text()
execute_status = fields.Selection([
('from_webhook', 'From Webhook'),
('detail_order', 'Detail Order'),
('so_confirm', 'SO Confirm'),
('so_draft', 'SO Draft'),
('done', 'Done'),
('failed', 'Failed'),
('already_so', 'SO Already Created'),
('processing_get_so', 'Processing Get SO'),
('cancelled_so', 'Cancelled SO'),
('cancelled_so_picking', 'Cancelled Picking'),
], 'Execute Status')
source = fields.Selection([
('webhook', 'From Webhook'),
('manual', 'Manual'),
], 'source')
sale_id = fields.Many2one('sale.order', 'Sale Order')
picking_id = fields.Many2one('stock.picking', 'Picking')
invoice_id = fields.Many2one('account.move', 'Invoice')
message_error = fields.Text('Message Error')
is_grouped_order = fields.Boolean('Is Grouped Order', default=False)
original_order_ids = fields.Char('Original Order IDs')
# get detail order section
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):
domain = [('execute_status', '=', False)]
records = self.search(domain, order='create_date asc', limit=limit)
for rec in records:
rec.execute_queue()
def execute_queue(self):
try:
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()
self.detail_order = json.dumps(data, indent=4, sort_keys=True)
self.execute_status = 'detail_order'
else:
self.write({
'message_error': json.dumps({
'error': f"Request failed with status code {response.status_code}",
'response': response.text
})
})
except Exception as e:
self.write({
'message_error': json.dumps({
'error': str(e)
})
})
# detail order to so section
def get_order_id_detail(self):
try:
if self.detail_order:
json_data = json.loads(self.detail_order)
order_id = json_data.get('data', {})[0].get('orderId')
order_status = json_data.get('data', {})[0].get('orderStatus')
print_info = json_data.get('data', {})[0].get('printInfo', {}).get('labelPrintStatus')
if not order_id:
raise UserError(_("Order ID not found in JSON data"))
return order_id, order_status, print_info
raise UserError(_("No JSON data available"))
except json.JSONDecodeError:
raise UserError(_("Invalid JSON format in detail_order field"))
except Exception as e:
raise UserError(_("Error extracting order ID: %s") % str(e))
def process_queue_item_detail(self, limit=100):
domain = [
('execute_status', '=', 'detail_order'),
'|',
('detail_order', 'not like', '"orderStatus": "PENDING_PAYMENT"'),
('json_ginee', 'not like', '"orderStatus": "PENDING_PAYMENT"'),
'|',
('detail_order', 'not like', '"channel":"BLIBLI_ID"'),
('json_ginee', 'not like', '"channel":"BLIBLI_ID"'),
]
records = self.search(domain, order='create_date desc', limit=limit)
for i, rec in enumerate(records, 1):
try:
rec.execute_queue_detail()
if i % 10 == 0:
self.env.cr.commit()
except Exception as e:
_logger.error("Failed to process record %s: %s", rec.id, str(e))
self.env.cr.rollback()
self.env.cr.commit()
def get_partner(self, shop_id):
partner = self.env['res.partner'].search([('ginee_shop_id', '=', shop_id)], limit=1)
if not partner:
raise UserError(_("Partner not found for Shop ID: %s") % shop_id)
return partner.id
def prepare_data_so(self, json_data):
data = {
'partner_id': self.get_partner(json_data.get('data', {})[0].get('shopId')),
'client_order_ref': json_data.get('data', {})[0].get('orderId'),
'warehouse_id': 4,
'picking_policy': 'direct',
'carrier': json_data.get('data', {})[0].get('logisticsInfos')[0].get('logisticsProviderName'),
'invoice_mp': json_data.get('data', {})[0].get('externalOrderId'),
}
return data
def _combine_order_items(self, items):
"""Combine quantities of the same products from multiple orders"""
product_quantities = {}
for item in items:
key = item.get('masterSku')
if key in product_quantities:
product_quantities[key]['quantity'] += item.get('quantity', 0)
product_quantities[key]['actualPrice'] += item.get('actualPrice', 0)
else:
product_quantities[key] = {
'quantity': item.get('quantity', 0),
'actualPrice': item.get('actualPrice', 0),
'productName': item.get('productName'),
'masterSkuType': item.get('masterSkuType'),
'item_data': item # Keep original item data
}
return product_quantities
def prepare_data_so_line(self, json_data):
order_lines = []
product_not_found = False
# Get all items (already combined if grouped)
items = json_data.get('data', [{}])[0].get('items', [])
# Combine quantities of the same products
product_quantities = self._combine_order_items(items)
# Process the combined items
for sku, combined_item in product_quantities.items():
item = combined_item['item_data']
product = self.env['product.product'].search(
[('default_code', '=', sku)],
limit=1
)
if product and item.get('masterSkuType') == 'BUNDLE':
order_lines.append((0, 0, {
'display_type': 'line_note',
'name': f"Bundle: {item.get('productName')}, Qty: {combined_item['quantity']}, Master SKU: {sku}",
'product_uom_qty': 0,
'price_unit': 0,
}))
bundling_lines = self.env['bundling.line'].search([('product_id', '=', product.id)])
bundling_variant_ids = bundling_lines.mapped('variant_id').ids
sale_pricelist = self.env['product.pricelist.item'].search([
('product_id', 'in', bundling_variant_ids),
('pricelist_id', '=', 17)
])
price_bundling_bottom = sum(item.fixed_price for item in sale_pricelist)
for bline in bundling_lines:
bottom_price = self.env['product.pricelist.item'].search([
('product_id', '=', bline.variant_id.id),
('pricelist_id', '=', 17)
], limit=1)
price = bottom_price.fixed_price
price_unit = self.prorate_price_bundling(
bline.variant_id,
price_bundling_bottom,
price,
actual_price=combined_item['actualPrice']
)
order_lines.append((0, 0, {
'product_id': bline.variant_id.id if bline.variant_id else product.id,
'product_uom_qty': bline.product_uom_qty * combined_item['quantity'],
'price_unit': price_unit,
'name': f"{bline.variant_id.display_name} (Bundle Component)" if bline.variant_id.display_name else product.name,
}))
order_lines.append((0, 0, {
'display_type': 'line_note',
'name': f"End Of Bundling Product",
'product_uom_qty': 0,
'price_unit': 0,
}))
continue
# Regular product line
line_data = {
'product_id': product.id if product else 5792,
'product_uom_qty': combined_item['quantity'],
'price_unit': combined_item['actualPrice'],
}
if not product:
line_data['name'] = f"{sku} ({combined_item['productName']})"
product_not_found = True
order_lines.append((0, 0, line_data))
return order_lines, product_not_found
def execute_queue_detail(self):
try:
json_data = json.loads(self.detail_order)
data = self.prepare_data_so(json_data)
order_lines, product_not_found = self.prepare_data_so_line(json_data)
order_id, order_status, print_info = self.get_order_id_detail()
# First check if a sale order with this reference already exists
existing_order = self.env['sale.order'].search([('order_reference', '=', order_id)], limit=1)
if existing_order:
# If order already exists, just update the references
self.sale_id = existing_order.id
self.execute_status = 'already_so'
return # Exit early since we don't need to create anything
# Handle cancelled orders
if order_status == 'CANCELLED':
external_order_id = json_data.get('data', [{}])[0].get('externalOrderId')
order_id = json_data.get('data', [{}])[0].get('orderId')
# Try to find existing SO
existing_order = self.env['sale.order'].search([
'|',
('invoice_mp', '=', external_order_id),
('client_order_ref', '=', order_id)
], limit=1)
if existing_order:
if existing_order.state == 'sale':
# Cancel all pickings linked to this order
for picking in existing_order.picking_ids:
if picking.state not in ['cancel', 'done']:
picking.action_cancel()
self.sale_id = existing_order.id
self.execute_status = 'cancelled_so_picking'
else:
existing_order.action_cancel()
self.sale_id = existing_order.id
self.execute_status = 'cancelled_so'
else:
# If no existing SO, create one, then cancel
data = self.prepare_data_so(json_data)
order_lines, product_not_found = self.prepare_data_so_line(json_data)
data['order_line'] = order_lines
sale_order = self.env['sale.order'].create(data)
self.sale_id = sale_order.id
sale_order.order_reference = order_id
sale_order.address = json_data.get('data', [{}])[0].get('shippingAddressInfo', []).get('fullAddress', [])
sale_order.note_by_buyer = json_data.get('data', [{}])[0].get('extraInfo', []).get('noteByBuyer', [])
sale_order.action_cancel()
self.execute_status = 'cancelled_so_created'
if order_status != 'PENDING_PAYMENT':
if order_status in ('PARTIALLY_PAID', 'PAID'):
data['order_line'] = order_lines
sale_order = self.env['sale.order'].create(data)
self.sale_id = sale_order.id
sale_order.order_reference = order_id
sale_order.address = json_data.get('data', [{}])[0].get('shippingAddressInfo', []).get('fullAddress', [])
sale_order.note_by_buyer = json_data.get('data', [{}])[0].get('extraInfo', []).get('noteByBuyer', [])
if not product_not_found:
sale_order.action_confirm()
# self.picking_id = sale_order.picking_ids[0].id
# self.picking_id.order_reference = order_id
# self.picking_id.invoice_mp = sale_order.invoice_mp
# self.picking_id.carrier = sale_order.carrier
# self.picking_id.address = json_data.get('data', [{}])[0].get('shippingAddressInfo', []).get('fullAddress', [])
# self.picking_id.note_by_buyer = json_data.get('data', [{}])[0].get('extraInfo', []).get('noteByBuyer', [])
self.execute_status = 'so_confirm'
else:
self.execute_status = 'so_draft'
else:
# For other statuses, create new order only if it doesn't exist
data['order_line'] = order_lines
sale_order = self.env['sale.order'].create(data)
self.sale_id = sale_order.id
sale_order.order_reference = order_id
sale_order.address = json_data.get('data', [{}])[0].get('shippingAddressInfo', []).get('fullAddress', [])
sale_order.note_by_buyer = json_data.get('data', [{}])[0].get('extraInfo', []).get('noteByBuyer', [])
if not product_not_found:
sale_order.action_confirm()
# self.picking_id = sale_order.picking_ids[0].id
# self.picking_id.order_reference = order_id
# self.picking_id.invoice_mp = sale_order.invoice_mp
# self.picking_id.carrier = sale_order.carrier
# self.picking_id.address = json_data.get('data', [{}])[0].get('shippingAddressInfo', []).get('fullAddress', [])
# self.picking_id.note_by_buyer = json_data.get('data', [{}])[0].get('extraInfo', []).get('noteByBuyer', [])
self.execute_status = 'so_confirm'
else:
self.execute_status = 'so_draft'
except Exception as e:
self.write({
'message_error': 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
def prorate_price_bundling(self, product, sum_bottom, price_bottom,actual_price):
percent = price_bottom / sum_bottom
real_price = percent * actual_price
return real_price
|