from itertools import product from odoo import fields, models, api, tools, _ import logging import re import pysolr from odoo.exceptions import UserError import base64 import xlrd, xlwt import io from bs4 import BeautifulSoup _logger = logging.getLogger(__name__) # solr = pysolr.Solr('http://10.148.0.5:8983/solr/searchkey/', always_commit=True, timeout=30) solr = pysolr.Solr('http://127.0.0.1:8983/solr/searchkey/', always_commit=True, timeout=30) class Keywords(models.Model): _name = 'keywords' _order= 'id desc' category_id = fields.Many2one('product.public.category', string='Category', required=True) keywords = fields.Char('Keywords', required=True) product_ids = fields.Many2many( 'product.product', 'keywords_product_rel', 'keyword_id', 'product_id', string='Products' ) name = fields.Char('Name', compute="_compute_name") skip = fields.Boolean('Skip Generate Product', default=False) url = fields.Char('Website URL', compute="_compute_url") sum = fields.Integer('Total Product', compute="_compute_total_product", readonly=True) @api.depends('product_ids') def _compute_total_product(self): for record in self: record.sum = len(record.product_ids) @api.depends('keywords') def _compute_url(self): prefix = "https://indoteknik.com/searchkey/" for record in self: if record.keywords: slug = re.sub(r'[^a-zA-Z0-9]+', '-', record.keywords.strip().lower()) slug = slug.strip('-') record.url = prefix + slug else: record.url = False def _compute_name(self): for record in self: if not record.name: record.name = record.keywords # @api.constrains('keywords') # def check_already_exist(self): # model = self.env['keywords'] # for record in self: # match = model.search([ # ('name', 'ilike', record.name) # ]) # if match: # raise UserError("Tidak bisa create/write/duplicate karena keywords sudah dipakai") def generate_products(self): for record in self: if not record.keywords: continue keyword = "%" + record.keywords.strip() + "%" # Query dasar sql = """ SELECT pp.id FROM product_product pp JOIN product_template pt ON pt.id = pp.product_tmpl_id LEFT JOIN product_public_category_product_template_rel rel ON rel.product_template_id = pt.id WHERE ( pt.name ILIKE %s OR pt.website_description ILIKE %s AND pt.unpublished = False AND pt.product_rating >= 8 ) """ params = [keyword, keyword] # Filter kategori ke child if record.category_id: child_categs = self.env['product.public.category'].search([ ('id', 'child_of', record.category_id.id) ]) sql += " AND rel.product_public_category_id = ANY(%s)" params.append(child_categs.ids) # Exec SQL self.env.cr.execute(sql, params) rows = self.env.cr.fetchall() product_ids = [r[0] for r in rows] if not product_ids: raise UserError("Tidak berhasil menemukan barang") record.with_context(skip_generate=True).write({ 'product_ids': [(6, 0, product_ids)] }) _logger.info( "Product Found: Found %s products for keyword '%s'", len(product_ids), record.keywords ) def sync_solr(self): # solr_model = self.env['apache.solr'] documents = [] data = {} for keyword in self.search([]): searchkey = (keyword.keywords or '').strip().lower().replace(' ', '-') try: doc = { 'id': keyword.id, 'category_id_i': keyword.category_id.id, 'keywords_s': searchkey, # 'searchkey_t': searchkey, 'url_s': keyword.url, 'product_ids_is': [p.product_tmpl_id.id for p in keyword.product_ids] } documents.append(doc) data = doc except Exception as e: _logger.error('failed %s', e) _logger.error('doc data: %s', data) solr.add(documents) return True @api.model def create(self, vals): record = super().create(vals) record.generate_products() return record def write(self, vals): result = super().write(vals) # if not self.env.context.get("skip_generate") and not self.skip: # self.generate_products() return result