from odoo import fields, models, api from datetime import datetime, timedelta from odoo.exceptions import AccessError, UserError, ValidationError import logging import requests import json _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') # 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.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): templates_without_variant = self.env['product.template'].search([ ('default_code', '=', False), ('type', '=', 'product'), ('active', '=', True), ('product_variant_ids', '=', False), ]) for template_without_variant in templates_without_variant: template_without_variant.default_code = 'IT.'+str(template_without_variant.id) _logger.info('Updated Template %s' % template_without_variant.name) templates_with_variant = self.env['product.template'].search([ ('default_code', '=', False), ('type', '=', 'product'), ('active', '=', True), ('product_variant_ids', '!=', False), ]) 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: # product = self.env['product.product'].search([('product_tmpl_id', '=', template.id)], limit=1) product_pricelist_item = self.env['product.pricelist.item'].search([ ('pricelist_id', '=', 1), ('product_id', '=', template.product_variant_id.id)], limit=1) price = product_pricelist_item.fixed_price template.web_price = 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 @api.model def _calculate_rating_product(self): #["&","&",["type","=","product"],["active","=",True],"|",["last_calculate_rating","=",False],["last_calculate_rating","<","2023-01-01 00:00:00"]] current_time = datetime.now() delta_time = current_time - timedelta(days=30) current_time = current_time.strftime('%Y-%m-%d %H:%M:%S') delta_time = delta_time.strftime('%Y-%m-%d %H:%M:%S') products = self.env['product.template'].search([ '&','&', ('type', '=', 'product'), ('active', '=', True), '|', ('last_calculate_rating', '=', False), ('last_calculate_rating', '<', delta_time), # ('id', '=', 22798), ], limit=500) for product in products: # print("Calculate Rating Product ", product) _logger.info("Calculate Rating Product %s" % product.id) # product_variant = self.env['product.product'].search([('product_tmpl_id', '=', product.id)], limit=1) rate = 0 if product.web_price: rate += 1 if product.have_promotion_program: #have discount from pricelist rate += 1 if product.image_128: rate += 5 if product.website_description: rate += 1 if product.product_variant_id.qty_stock_vendor > 0: rate += 1 product.product_rating = rate product.last_calculate_rating = current_time 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 = int(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 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='Qty Incoming Bandengan', compute='_get_qty_onhand_bandengan') qty_incoming_bandengan = fields.Float(string='Qty Incoming Bandengan', compute='_get_qty_incoming_bandengan') sla_version = fields.Integer(string="SLA Version", default=0) 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_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 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: product_pricelist_item = self.env['product.pricelist.item'].search( [('pricelist_id', '=', 1), ('product_id', '=', product.id)], 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')