summaryrefslogtreecommitdiff
path: root/indoteknik_custom/models/product_template.py
blob: 4bab2cad9a230b17c92e31d8e69ae4e5497419aa (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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
from odoo import fields, models, api
from datetime import datetime, timedelta, date
from odoo.exceptions import UserError
import logging
import requests
import json
import re

_logger = logging.getLogger(__name__)


class ProductTemplate(models.Model):
    _inherit = "product.template"

    x_studio_field_tGhJR = fields.Many2many('x_product_tags', string="Product Tags")
    x_manufacture = fields.Many2one(
        comodel_name="x_manufactures",
        string="Manufactures"
    )
    x_model_product = fields.Char(string="Model Produk")
    x_product_manufacture = fields.Many2one(
        comodel_name="x_manufactures",
        string="Manufacture"
    )
    x_lazada = fields.Text(string="Lazada")
    x_tokopedia = fields.Text(string="Tokopedia")
    web_tax_id = fields.Many2one('account.tax', string='Website Tax')
    web_price = fields.Float(
        'Web Price', compute='_compute_web_price',
        digits='Product Price', inverse='_set_product_lst_price',
        help="Web Price with pricelist_id = 1")
    qty_stock_vendor = fields.Float('QTY Stock Vendor', compute='_compute_qty_stock_vendor')
    have_promotion_program = fields.Boolean('Have Promotion Program', compute='_have_promotion_program', help="Punya promotion program gak?")
    product_rating = fields.Float('Product Rating', help="Digunakan untuk sorting product di website", default=0.0)
    virtual_rating = fields.Float('Virtual Rating', compute='_compute_virtual_rating', help="Column Virtual untuk product rating, digunakan oleh Solr", default=0.0)
    last_calculate_rating = fields.Datetime("Last Calculate Rating")
    web_price_sorting = fields.Float('Web Price Sorting', help='Hanya digunakan untuk sorting di web, harga tidak berlaku', default=0.0)
    virtual_qty = fields.Float(string='Virtual Qty', default=0)
    solr_flag = fields.Integer(string='Solr Flag', default=0)
    search_rank = fields.Integer(string='Search Rank', default=0)
    search_rank_weekly = fields.Integer(string='Search Rank Weekly', default=0)
    supplier_url = fields.Char(string='Vendor URL')
    # custom field for support Trusco products
    maker_code = fields.Char(string='Maker Code')
    maker_name = fields.Char(string='Maker Name')
    origin = fields.Char(string='Origin')
    features = fields.Char(string='Features')
    usage = fields.Char(string='Usage')
    specification = fields.Char(string='Specification')
    material = fields.Char(string='Material')
    is_new_product = fields.Boolean(string='Produk Baru',
                                    help='Centang jika ingin ditammpilkan di website sebagai segment Produk Baru')
    seq_new_product = fields.Integer(string='Seq New Product', help='Urutan Sequence New Product')
    is_edited = fields.Boolean(string='Is Edited')
    qty_sold = fields.Float(string='Sold Quantity', compute='_get_qty_sold')
    kind_of = fields.Selection([
        ('sp', 'Spare Part'),
        ('acc', 'Accessories')
    ], string='Kind of', copy=False)
    
    def _get_qty_sold(self):
        for rec in self:
            rec.qty_sold = sum(x.qty_sold for x in rec.product_variant_ids)

    def day_product_to_edit(self):
        day_products = []
        
        for product in self:
            day_product = (product.write_date - product.create_date).days
            day_products.append(day_product)

        return day_products

    @api.constrains('name', 'default_code')
    def _check_duplicate_product(self):
        for product in self:
            variants = product.product_variant_ids
            names = [x.name for x in variants] if variants else [product.name]
            default_codes = [x.default_code for x in variants] if variants else [product.default_code]
            
            domain = [
                ('default_code', '!=', False), 
                ('id', '!=', product.id),
                '|', 
                ('name', 'in', names), 
                ('default_code', 'in', default_codes)
            ]
            
            product_exist = self.search(domain, limit=1)
            if len(product_exist) > 0:
                raise UserError('Name atau Internal Reference sudah digunakan pada produk lain')
            
            if self.env.user.is_purchasing_manager or self.env.user.is_editor_product or self.env.user.id in [1, 25]:
                continue
            
            if sum(product.day_product_to_edit()) > 0:
                raise UserError('Produk ini tidak dapat diubah')
    
    @api.constrains('name')
    def _validate_name(self):
        rule_regex = self.env['ir.config_parameter'].sudo().get_param('product.product.rule_name_regex') or ''
        pattern = rf'^{rule_regex}$'
        if not re.match(pattern, self.name):
            pattern_suggest = rf"{rule_regex}"
            suggest = ''.join(re.findall(pattern_suggest, self.name))
            raise UserError(f'Contoh yang benar adalah {suggest}')
    
    # def write(self, vals):
    #     if 'solr_flag' not in vals and self.solr_flag == 1:
    #         vals['solr_flag'] = 2
    #     return super().write(vals)

    def _compute_virtual_rating(self):
        for product in self:
            rate = 0
            if product.web_price:
                rate += 4
            if product.qty_sold > 0:
                rate += 3
            if product.have_promotion_program: #have discount from pricelist
                rate += 5
            if product.image_128:
                rate += 3
            if product.website_description:
                rate += 1
            if product.product_variant_id.qty_stock_vendor > 0:
                rate += 2
            product.virtual_rating = rate

    def unlink(self):
        if self._name == 'product.template':
            raise UserError('Maaf anda tidak bisa delete product')
    
    def update_new_product(self):
        current_time = datetime.now()
        delta_time = current_time - timedelta(days=30)

        delta_time = delta_time.strftime('%Y-%m-%d %H:%M:%S')

        products = self.env['product.template'].search([
            ('type', '=', 'product'),
            ('active', '=', True),
            ('product_rating', '>', 3),
            ('create_date', '>=', delta_time),
        ], limit=100)

        seq = 0
        for product in products:
            seq += 1
            product.is_new_product = True
            product.seq_new_product = seq
            _logger.info('Updated New Product %s' % product.name)

    def update_internal_reference(self, limit=100):
        templates = self.env['product.template'].search([
            ('default_code', '=', False),
            ('product_variant_ids.default_code', '=', False),
            ('type', '=', 'product'),
            ('active', '=', True)
        ], limit=limit, order='write_date desc')
        for template in templates:
            if not template.default_code:
                template.default_code = 'IT.'+str(template.id)
                
            for variant in template.product_variant_ids:
                if not variant.default_code:
                    variant.default_code = 'ITV.%s' % str(variant.id)

            _logger.info('Updated Template %s' % template.name)

        # templates_with_variant = self.env['product.product'].search([
        #     ('default_code', '=', False),
        #     ('type', '=', 'product'),
        #     ('active', '=', True),
        #     ('product_tmpl_id', '!=', False),
        # ], limit=limit, order='write_date desc')
        # for template_with_variant in templates_with_variant:
        #     for product in template_with_variant.product_variant_ids:
        #         if product.default_code:
        #             continue
        #         product.default_code = 'ITV.'+str(product.id)
        #         _logger.info('Updated Variant %s' % product.name)

    @api.onchange('name','default_code','x_manufacture','product_rating','website_description','image_1920','weight','public_categ_ids')
    def update_solr_flag(self):
        for tmpl in self:
            if tmpl.solr_flag == 1:
                tmpl.solr_flag = 2

    def _compute_qty_stock_vendor(self):
        for product_template in self:
            product_template.qty_stock_vendor = 0
            for product_variant in product_template.product_variant_ids:
                product_template.qty_stock_vendor += int(product_variant.qty_stock_vendor)

    def _compute_web_price(self):
        for template in self:
            template.web_price = template.product_variant_id.web_price

    def _have_promotion_program(self):
        for template in self:
            # product = self.env['product.product'].search([('product_tmpl_id', '=', template.id)], limit=1)

            product_pricelist_item = self.env['product.pricelist.item'].search([
                ('pricelist_id', '=', 4),
                ('product_id', '=', template.product_variant_id.id)], limit=1)
            discount = product_pricelist_item.price_discount
            if discount:
                template.have_promotion_program = True
            else:
                template.have_promotion_program = False

    def _get_active_flash_sale(self):
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        variant_ids = [x.id for x in self.product_variant_ids]
        pricelist = self.env['product.pricelist'].search([
            ('is_flash_sale', '=', True),
            ('item_ids.product_id', 'in', variant_ids),
            ('start_date', '<=', current_time),
            ('end_date', '>=', current_time)
        ], limit=1)
        return pricelist

    @api.model
    def _calculate_rating_product(self, limit=1000, expiry_days=30, ids=False):
        current_time = datetime.now()
        current_time_str = current_time.strftime('%Y-%m-%d %H:%M:%S')

        delta_time = current_time - timedelta(days=expiry_days)
        delta_time_str = delta_time.strftime('%Y-%m-%d %H:%M:%S')

        query = [
            '&','&',
            ('type', '=', 'product'),
            ('active', '=', True)
        ]
        if not ids:
            query += [
                '|',
                ('last_calculate_rating', '=', False),
                ('last_calculate_rating', '<', delta_time_str)
            ]
        else:
            query += [('id', 'in', ids)]

        products = self.env['product.template'].search(query, limit=limit)

        for product in products:
            _logger.info("Calculate Rating Product %s" % product.id)
            product.product_rating = product.virtual_rating
            product.last_calculate_rating = current_time_str

    def _get_stock_website(self):
        qty = self._get_stock_altama()
        print(qty)
    
    def get_stock_altama(self, item_code):
        current_time = datetime.now()
        current_time = current_time.strftime('%Y-%m-%d %H:%M:%S')
        query = [('source', '=', 'altama'), ('expired_date', '>', current_time)]
        token_data = self.env['token.storage'].search(query, order='expired_date desc',limit=1)
        if not token_data:
            token_data = self._get_new_token_altama()
            token = token_data['access_token']
        else:
            token = token_data.access_token
        
        url = "https://erpapi.altama.co.id/erp/api/stock/buffer/btob"
        auth = "Bearer "+token
        headers = {
            'Content-Type': 'application/json',
            'Authorization': auth,
        }
        json_data = {
            'type_search': 'Item_code',
            'search_key':[item_code],
        }
        response = requests.post(url, headers=headers, json=json_data)
        datas = json.loads(response.text)['data']
        qty = 0
        for data in datas:
            availability = float(data['availability'])  # Mengonversi ke tipe data int
            qty += availability  # Mengakumulasi qty dari setiap data

        return qty

    def _get_new_token_altama(self):
        url = "https://kc.altama.co.id/realms/altama/protocol/openid-connect/token"
        auth = 'Basic SW5kb3Rla25pa19DbGllbnQ6Vm1iZExER1ZUS3RuVlRQdkU1MXRvRzdiTW51TE1WRVI='
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': auth,
        }
        data = {
            'grant_type': 'client_credentials',
        }
        
        response = requests.post(url, headers=headers, data=data).json()
        lookup_json = json.dumps(response, indent=4, sort_keys=True)
        token = json.loads(lookup_json)['access_token']
        expires_in = json.loads(lookup_json)['expires_in']
        
        current_time = datetime.now()
        delta_time = current_time + timedelta(seconds=int(expires_in))

        current_time = current_time.strftime('%Y-%m-%d %H:%M:%S')
        delta_time = delta_time.strftime('%Y-%m-%d %H:%M:%S')

        values = {
            'source': 'altama',
            'access_token': token,
            'expires_in': expires_in,
            'expired_date': delta_time,
        }
        self.env['token.storage'].create([values])
        return values

    def write(self, vals):
        for rec in self:
            if rec.id == 224484:
                raise UserError('Tidak dapat mengubah produk sementara')
        
        return super(ProductTemplate, self).write(vals)
        
class ProductProduct(models.Model):
    _inherit = "product.product"
    web_price = fields.Float(
        'Web Price', compute='_compute_web_price',
        digits='Product Price', inverse='_set_product_lst_price',
        help="Web Price with pricelist_id = 1")
    qty_stock_vendor = fields.Float(
        'Qty Stock Vendor', compute='_compute_stock_vendor',
        help="Stock Vendor")
    solr_flag = fields.Integer(string='Solr Flag', default=0)
    # custom field for support Trusco products
    maker_code = fields.Char(string='Maker Code')
    maker_name = fields.Char(string='Maker Name')
    origin = fields.Char(string='Origin')
    features = fields.Char(string='Features')
    usage = fields.Char(string='Usage')
    specification = fields.Char(string='Specification')
    material = fields.Char(string='Material')
    qty_onhand_bandengan = fields.Float(string='Onhand BU', compute='_get_qty_onhand_bandengan')
    qty_incoming_bandengan = fields.Float(string='Incoming BU', compute='_get_qty_incoming_bandengan')
    qty_outgoing_bandengan = fields.Float(string='Outgoing BU', compute='_get_qty_outgoing_bandengan')
    qty_available_bandengan = fields.Float(string='Available BU', compute='_get_qty_available_bandengan')
    qty_free_bandengan = fields.Float(string='Free BU', compute='_get_qty_free_bandengan')
    qty_upcoming = fields.Float(string='Qty Upcoming', compute='_get_qty_upcoming')
    sla_version = fields.Integer(string="SLA Version", default=0)
    is_edited = fields.Boolean(string='Is Edited')
    qty_sold = fields.Float(string='Sold Quantity', compute='_get_qty_sold')

    def _get_po_suggest(self, qty_purchase):
        if self.qty_available_bandengan < qty_purchase:
            return 'harus beli'
        return 'masih cukup'
    
    def _get_qty_upcoming(self):
        for product in self:
            product.qty_upcoming = product.incoming_qty + product.qty_available
    
    def _get_qty_sold(self):
        for product in self:
            order_line = self.env['sale.order.line'].search([
                ('order_id.state', 'in', ['done', 'sale']),
                ('product_id', '=', product.id)
            ])
            product.qty_sold = sum(x.product_uom_qty for x in order_line)

    def day_product_to_edit(self):
        day_products = []
        
        for product in self:
            day_product = (product.write_date - product.create_date).days
            day_products.append(day_product)

        return day_products
    
    @api.constrains('name')
    def _validate_name(self):
        rule_regex = self.env['ir.config_parameter'].sudo().get_param('product.product.rule_name_regex') or ''
        pattern = rf'^{rule_regex}$'
        if not re.match(pattern, self.name):
            pattern_suggest = rf"{rule_regex}"
            suggest = ''.join(re.findall(pattern_suggest, self.name))
            raise UserError(f'Contoh yang benar adalah {suggest}')
    
    def _get_qty_incoming_bandengan(self):
        for product in self:
            qty_incoming = self.env['stock.move'].search([
                            ('product_id', '=', product.id),
                            ('location_dest_id', '=', 57),
                            ('state', 'not in', ['done', 'cancel'])
                        ])
            qty = sum(qty_incoming.mapped('product_uom_qty'))
            product.qty_incoming_bandengan = qty

    def _get_qty_outgoing_bandengan(self):
        for product in self:
            qty_incoming = self.env['stock.move'].search([
                            ('product_id', '=', product.id),
                            ('location_dest_id', '=', 5),
                            ('location_id', '=', 57),
                            ('state', 'not in', ['done', 'cancel'])
                        ])
            qty = sum(qty_incoming.mapped('product_uom_qty'))
            product.qty_outgoing_bandengan = qty

    def _get_qty_onhand_bandengan(self):
        for product in self:
            qty_onhand = self.env['stock.quant'].search([
                        ('product_id', '=', product.id),
                        ('location_id', '=', 57)
                    ])
            qty = sum(qty_onhand.mapped('quantity'))
            product.qty_onhand_bandengan = qty

    def _get_qty_available_bandengan(self):
        for product in self:
            qty_available = product.qty_incoming_bandengan + product.qty_onhand_bandengan - product.qty_outgoing_bandengan
            product.qty_available_bandengan = qty_available

    def _get_qty_free_bandengan(self):
        for product in self:
            qty_free = product.qty_onhand_bandengan - product.qty_outgoing_bandengan
            product.qty_free_bandengan = qty_free
            
    # def write(self, vals):
    #     if 'solr_flag' not in vals:
    #         for variant in self:
    #             if variant.solr_flag == 1:
    #                 variant.product_tmpl_id.solr_flag = 2
    #         vals['solr_flag'] = 2
    #     return super().write(vals)

    def _compute_web_price(self):
        for product in self:
            pricelist_id = self.env['ir.config_parameter'].sudo().get_param('product.pricelist.default_price_id_v2')

            domain = [('pricelist_id.id', '=', pricelist_id or 17022), ('product_id.id', '=', product.id)]
            product_pricelist_item = self.env['product.pricelist.item'].search(domain, limit=1)

            if product_pricelist_item.base_pricelist_id:
                base_pricelist_id = product_pricelist_item.base_pricelist_id.id
                domain = [('pricelist_id', '=', base_pricelist_id), ('product_id', '=', product.id)]
                product_pricelist_item = self.env['product.pricelist.item'].search(domain, limit=1)

            product.web_price = product_pricelist_item.fixed_price

    def _compute_stock_vendor(self):
        for product in self:
            stock_vendor = self.env['stock.vendor'].search([('product_variant_id', '=', product.id)], limit=1)
            product.qty_stock_vendor = stock_vendor.quantity + product.qty_available
    
    def unlink(self):
        if self._name == 'product.product':
            raise UserError('Maaf anda tidak bisa delete product')
        
    def _get_active_flash_sale(self):
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        pricelist = self.env['product.pricelist'].search([
            ('is_flash_sale', '=', True),
            ('item_ids.product_id', '=', self.id),
            ('start_date', '<=', current_time),
            ('end_date', '>=', current_time)
        ], limit=1)
        return pricelist