summaryrefslogtreecommitdiff
path: root/fixco_custom/models/shipment_group.py
blob: 117de0b8dcc32cc3225dcb6a69b015fbbbdd8b04 (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
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
from odoo import fields, models, api, _
from odoo.exceptions import AccessError, UserError, ValidationError
from odoo.tools.float_utils import float_is_zero
from collections import defaultdict
from datetime import timedelta, datetime
from datetime import timedelta, datetime as waktu
from itertools import groupby
import pytz, requests, json, requests
from dateutil import parser
import datetime
import hmac
import hashlib
import base64
import requests
import time
import logging
import re
from hashlib import sha256

_logger = logging.getLogger(__name__)


Request_URI = '/openapi/order/v2/list-order'
ACCESS_KEY = '24bb6a1ec618ec6a'
SECRET_KEY = '32e4a78ad05ee230'

class ShipmentGroup(models.Model):
    _name = "shipment.group"
    _description = "Shipment Group"
    _inherit = ['mail.thread']
    _rec_name = 'number'

    number = fields.Char(string='Document No', index=True, copy=False, readonly=True, tracking=True)
    shipment_line = fields.One2many('shipment.group.line', 'shipment_id', string='Shipment Group Lines', auto_join=True)
    picking_lines = fields.One2many('picking.line', 'shipment_id', string='Picking Lines', auto_join=True)
    related_count = fields.Integer(compute='_compute_related_count', string='Related Count')
    receipt = fields.Char(string='Receipt', related='picking_lines.scan_receipt')
    total_line = fields.Integer(string='Total Line', compute='_compute_total_line')

    @api.depends('picking_lines')
    def _compute_total_line(self):
        for rec in self:
            rec.total_line = len(rec.picking_lines)

    def sync_product_to_picking_line(self):
        for shipment in self:
            cancelled_picking = shipment.picking_lines.filtered(
                lambda picking: picking.status == 'CANCELLED'
            )
            if cancelled_picking:
                cancelled_names = "\n - " + "\n - ".join(cancelled_picking.mapped("name"))
                raise UserError(f"Pickings berikut telah dibatalkan:{cancelled_names}")

            for picking_line in shipment.picking_lines:
                shipment_lines = self.env['shipment.group.line'].search([
                    ('shipment_id', '=', shipment.id),
                    ('invoice_marketplace', '=', picking_line.invoice_marketplace),
                    ('picking_id', '=', picking_line.picking_id.id)
                ])

                picking_line.product_shipment_lines.unlink()

                for sl in shipment_lines:
                    self.env['product.shipment.line'].create({
                        'picking_line_id': picking_line.id,
                        'product_id': sl.product_id.id,
                        'carrier': sl.carrier or picking_line.carrier,
                        'invoice_marketplace': sl.invoice_marketplace,
                        'picking_id': sl.picking_id.id,
                        'order_reference': sl.order_reference,
                    })

    def _compute_related_count(self):
        for record in self:
            record.related_count = len(record.picking_lines)

    def action_view_related_line(self):
        self.ensure_one()

        pickingLines = self.env['picking.line']

        base_bu = pickingLines.search([
            ('shipment_id', '=', self.id)
        ])

        all_bu = base_bu

        return {
            'name': 'Related',
            'type': 'ir.actions.act_window',
            'res_model': 'picking.line',
            'view_mode': 'tree,form',
            'target': 'current',
            'domain': [('id', 'in', list(all_bu.ids))],
        }

    @api.constrains('picking_lines')
    def _check_picking_lines(self):
        for record in self:

            for picking_line in record.picking_lines:
                if not picking_line.picking_id:
                    continue

                for move in picking_line.picking_id.move_line_ids_without_package:
                    existing_line = record.shipment_line.filtered(
                        lambda l: l.product_id == move.product_id and
                        l.picking_id.tracking_number == picking_line.scan_receipt and
                        l.carrier == picking_line.carrier
                    )

                    if not existing_line:
                        self.env['shipment.group.line'].create({
                            'shipment_id': record.id,
                            'product_id': move.product_id.id,
                            'carrier': picking_line.picking_id.carrier,
                            'invoice_marketplace': picking_line.picking_id.invoice_mp,
                            'order_reference': picking_line.order_reference,
                            'picking_id': picking_line.picking_id.id
                        })

    def get_status(self):
        """
        Batch realtime check status order Ginee
        - 1 request untuk banyak order
        - Anti 429
        - Siap dipanggil sebelum validate picking
        """
        # 1️⃣ Kumpulin invoice marketplace
        order_map = {}
        for line in self.picking_lines:
            if line.invoice_marketplace:
                order_map[line.invoice_marketplace] = line

        if not order_map:
            return

        # 2️⃣ Prepare request
        authorization = self.sign_request()
        headers = {
            'Content-Type': 'application/json',
            'X-Advai-Country': 'ID',
            'Authorization': authorization
        }

        payload = {
            "orderNumbers": list(order_map.keys())
        }

        url = "https://api.ginee.com/openapi/order/v2/list-order"

        response = requests.post(
            url,
            headers=headers,
            data=json.dumps(payload),
            timeout=30
        )

        if response.status_code != 200:
            raise UserError(_("API request failed with status code: %s") % response.status_code)

        data = response.json()
        if data.get('code') != 'SUCCESS':
            raise UserError(_("API Error: %s - %s") % (
                data.get('code', 'UNKNOWN'),
                data.get('message', 'No error message')
            ))

        # 3️⃣ Mapping response ke picking line
        contents = data.get('data', {}).get('content', [])
        if not contents:
            return

        for item in contents:
            order_no = item.get('orderNumber')
            order_status = item.get('orderStatus')

            picking_line = order_map.get(order_no)
            if not picking_line:
                continue

            # Simpan status
            picking_line.status = order_status if order_status == 'CANCELLED' else ''


    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


    @api.model
    def create(self, vals):
        vals['number'] = self.env['ir.sequence'].next_by_code('shipment.group') or '0'
        result = super(ShipmentGroup, self).create(vals)
        return result

class ShipmentGroupLine(models.Model):
    _name = 'shipment.group.line'
    _description = 'Shipment Group Line'
    _order = 'shipment_id, id'

    shipment_id = fields.Many2one('shipment.group', string='Shipment Ref', required=True, ondelete='cascade')
    product_id = fields.Many2one('product.product', string='Product')
    carrier = fields.Char(string='Shipping Method')
    invoice_marketplace = fields.Char(string='Invoice Marketplace')
    picking_id = fields.Many2one('stock.picking', string='Picking')
    order_reference = fields.Char(string='Order Reference')


class PickingLine(models.Model):
    _name = 'picking.line'
    _description = 'Picking Line'
    _order = 'shipment_id, id'

    shipment_id = fields.Many2one('shipment.group', string='Shipment Ref', required=True, ondelete='cascade')
    product_shipment_lines = fields.One2many('product.shipment.line', 'picking_line_id', string='Product Shipment Lines', auto_join=True)
    picking_id = fields.Many2one('stock.picking', string='Picking')
    scan_receipt = fields.Char(string="Scan Receipt")
    invoice_marketplace = fields.Char(string='Invoice Marketplace')
    carrier = fields.Char(string='Ekspedisi')
    order_reference = fields.Char(string='Order Reference')
    status = fields.Char(string='Status')

    @api.onchange('scan_receipt')
    def _check_duplicate_scan(self):
        for line in self:
            if not line.scan_receipt:
                continue

            # Cari duplikat selain dirinya
            dup = self.search([
                ('scan_receipt', '=', line.scan_receipt),
                # ('id', '!=', line.id)
            ], limit=1)

            if not dup:
                continue

            # 1. Dup di shipment yang sama (lagi create / edit)
            # if dup.shipment_id.id == line.shipment_id.id:
            #     raise ValidationError(
            #         "Receipt '%s' sudah ada di Shipment ini." %
            #         line.scan_receipt
            #     )

            # 2. Dup di shipment lain (data lama)
            raise ValidationError(
                "Receipt '%s' sudah digunakan di Shipment %s." %
                (line.scan_receipt, dup.shipment_id.number or '-')
            )


    @api.onchange('scan_receipt')
    def _onchange_scan_receipt(self):
        for line in self:
            if not line.scan_receipt:
                continue

            picking = self.env['stock.picking'].search([
                ('tracking_number', '=', line.scan_receipt)
            ], limit=1)

            if not picking:
                picking = self.env['stock.picking'].search([
                    ('invoice_mp', '=', line.scan_receipt)
                ], limit=1)

            if not picking:
                raise UserError(
                    "Receipt '%s' not found or hasn't been done." % line.scan_receipt
                )

            # isi field
            line.picking_id = picking
            line.carrier = picking.carrier
            line.order_reference = picking.order_reference
            line.invoice_marketplace = picking.invoice_mp



class ProductShipmentLine(models.Model):
    _name = 'product.shipment.line'
    _description = 'Product Shipment Line'
    _order = 'picking_line_id, id'

    picking_line_id = fields.Many2one('picking.line', string='Picking Line', required=True, ondelete='cascade')
    product_id = fields.Many2one('product.product', string='Product')
    carrier = fields.Char(string='Shipping Method')
    invoice_marketplace = fields.Char(string='Invoice Marketplace')
    picking_id = fields.Many2one('stock.picking', string='Picking')
    order_reference = fields.Char(string='Order Reference')