summaryrefslogtreecommitdiff
path: root/indoteknik_custom/models/solr/product_template.py
blob: 062f14559ddbd8f6edb8de9e9d3f80f3e4934e8c (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
from datetime import datetime

from odoo import api, fields, models


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

    unpublished = fields.Boolean(string='Unpublished')
    last_update_solr = fields.Datetime(string='Last Update Solr')
    desc_update_solr = fields.Char(string='Desc Update Solr')

    def change_solr_data(self, desc):
        self.desc_update_solr = desc
        self.last_update_solr = datetime.utcnow()

    def solr(self):
        return self.env['apache.solr'].connect('product')

    def _create_solr_queue(self, function_name):
        for rec in self:
            self.env['apache.solr.queue'].create_unique({
                'res_model': self._name,
                'res_id': rec.id,
                'function_name': function_name
            }) 

    @api.constrains('name', 'default_code', 'weight', 'x_manufacture', 'public_categ_ids', 'search_rank', 'search_rank_weekly', 'image_1920', 'unpublished')
    def _create_solr_queue_sync_product_template(self):
        self._create_solr_queue('_sync_product_template_to_solr')

    @api.constrains('active')
    def _constrains_active(self):
        for rec in self:
            if not rec.active:
                rec.unpublished = True

    def action_sync_to_solr(self):
        template_ids = self.env.context.get('active_ids', [])
        templates = self.search([('id', 'in', template_ids)])
        templates._create_solr_queue('_sync_product_template_to_solr')
    
    def solr_flag_to_solr(self, limit=500):
        template_products = self.search([('solr_flag', '=', 2), ('active', 'in', [True, False])], limit=limit)
        for product in template_products:
            product._create_solr_queue('_sync_product_template_to_solr')
            product._create_solr_queue('_sync_price_to_solr')
            product.solr_flag = 1

    def _sync_product_stock_to_solr(self):
        self._sync_product_template_to_solr()

    def _sync_product_template_to_solr(self):
        solr_model = self.env['apache.solr']

        for template in self:
            variant_names = ', '.join([x.display_name or '' for x in template.product_variant_ids])
            variant_codes = ', '.join([x.default_code or '' for x in template.product_variant_ids])

            category_id = 0
            category_name = ''
            for category in template.public_categ_ids:
                category_id, category_name = category.id, category.name
                break
            
            document = solr_model.get_doc('product', template.id)
            document.update({
                "id": template.id,
                "display_name_s": template.display_name,
                "name_s": template.name,
                "default_code_s": template.default_code or '',
                "product_rating_f": template.virtual_rating,
                "product_id_i": template.id,
                "image_s": self.env['ir.attachment'].api_image('product.template', 'image_256', template.id),
                "variant_total_i": template.product_variant_count,
                "stock_total_f": template.qty_stock_vendor,
                "weight_f": template.weight,
                "manufacture_id_i": template.x_manufacture.id or 0,
                "manufacture_name_s": template.x_manufacture.x_name or '',
                "manufacture_name": template.x_manufacture.x_name or '',
                "image_promotion_1_s": self.env['ir.attachment'].api_image('x_manufactures', 'image_promotion_1', template.x_manufacture.id),
                "image_promotion_2_s": self.env['ir.attachment'].api_image('x_manufactures', 'image_promotion_2', template.x_manufacture.id),
                "variants_name_t": variant_names,
                "variants_code_t": variant_codes,
                "search_rank_i": template.search_rank,
                "search_rank_weekly_i": template.search_rank_weekly,
                "category_id_i": category_id,
                "category_name_s": category_name,
                "category_name": category_name,
                "description_t": template.website_description or '',
                'has_product_info_b': True,
                'publish_b': not template.unpublished,
                "qty_sold_f": template.qty_sold
            })

            self.solr().add(docs=[document], softCommit=True)
            products = self.env['product.product'].search([
                ('product_tmpl_id', '=', template.id),
                ('active', 'in', [True, False])
            ])
            products._sync_variants_to_solr()
            self.change_solr_data('Perubahan pada data product')

            if not document.get('has_price_info_b'):
                template._sync_price_to_solr()

    def _sync_price_to_solr(self):
        solr_model = self.env['apache.solr']
        TIER_NUMBERS = ['1_v2', '2_v2', '3_v2', '4_v2', '5_v2']

        for template in self:
            cheapest_flashsale = {}

            for variant in template.product_variant_ids:
                variant_flashsale = variant.with_context(price_for="web")._get_flashsale_price()
                variant_flashsale_price = variant_flashsale.get('flashsale_price', 0)
                cheapest_flashsale_price = cheapest_flashsale.get('flashsale_price', 0)

                if cheapest_flashsale_price == 0 or (variant_flashsale_price != 0 and variant_flashsale_price < cheapest_flashsale_price):
                    cheapest_flashsale = variant_flashsale

            flashsale_doc = {
                "flashsale_id_i": cheapest_flashsale.get('flashsale_id', 0),
                "flashsale_tag_s": cheapest_flashsale.get('flashsale_tag', ''),
                "flashsale_name_s": cheapest_flashsale.get('flashsale_name', ''),
                "flashsale_start_date_s": cheapest_flashsale.get('flashsale_start_date', ''),
                "flashsale_end_date_s": cheapest_flashsale.get('flashsale_end_date', ''),
                "flashsale_base_price_f": cheapest_flashsale.get('flashsale_base_price', 0),
                "flashsale_discount_f": cheapest_flashsale.get('flashsale_discount', 0),
                "flashsale_price_f": cheapest_flashsale.get('flashsale_price', 0)
            }
            
            price_doc = {}
            
            # Loop tier to get each variant price
            for tier_number in TIER_NUMBERS:
                for variant in template.product_variant_ids:
                    tier = variant._get_pricelist_tier(tier_number)
                    discount_tier_key = f'discount_tier{tier_number}'
                    price_tier_key = f'price_tier{tier_number}'
                    
                    variant_discount = tier.get(discount_tier_key, 0)
                    variant_price = tier.get(price_tier_key, 0)
                    
                    price_tier = price_doc.get(f"{price_tier_key}_f", 0)
                    # When price tier is 0 or variant_price less than price tier then use variant price
                    if price_tier == 0 or (variant_price < price_tier and variant_price > 0):
                        price_doc[f"{discount_tier_key}_f"] = variant_discount
                        price_doc[f"{price_tier_key}_f"] = variant_price
            
            document = solr_model.get_doc('product', template.id)
            document['id'] = template.id
            document.update(flashsale_doc)
            document.update(price_doc)
            document.update({"has_price_info_b": True})

            self.solr().add(docs=[document], softCommit=True)
            template.product_variant_ids._sync_price_to_solr()
            template.change_solr_data('Ada perubahan pada harga product')

            if not document.get('has_product_info_b'):
                template._sync_product_template_to_solr()
   
    def solr_results(self, detail=False):
        solr_model = self.env['apache.solr']
        pricelist = self.env.context.get('user_pricelist')
        price_tier = pricelist.get_tier_name()

        results = []
        for template in self:
            doc = solr_model.get_doc('product', template.id)
            if len(doc) == 0: continue

            discount_key = 'discount_f'
            price_discount_key = 'price_discount_f'
            if price_tier:
                discount_key = f'discount_{price_tier}_f'
                price_discount_key = f'price_{price_tier}_f'

            flashsale = template._get_active_flash_sale()
            if flashsale:
                discount_key = 'flashsale_discount_f'
                price_discount_key = 'flashsale_price_f'
            
            result = {
                'id': doc.get('id'),
                'image': doc.get('image_s'),
                'code': doc.get('default_code_s'),
                'display_name': doc.get('display_name_s'),
                'name': doc.get('name_s'),
                'variant_total': doc.get('variant_total_i'),
                'weight': doc.get('weight_f'),
                'manufacture': None,
                'categories': [],
                'flash_sale': {
                    'remaining_time': flashsale._remaining_time_in_second() or 0,
                    'tag': doc.get('flashsale_tag_s')
                },
                'lowest_price': {
                    'price': doc.get('price_f'),
                    'discount_percentage': doc.get(discount_key),
                    'price_discount': doc.get(price_discount_key)
                }
            }

            manufacture_id = doc.get('manufacture_id_i')
            if manufacture_id:
                result['manufacture'] = {
                    'id': manufacture_id,
                    'name': doc.get('manufacture_name_s'),
                    'image_promotion_1': doc.get('image_promotion_1_s'),
                    'image_promotion_2': doc.get('image_promotion_2_s'),
                }
            
            category_id = doc.get('category_id_i')
            if category_id:
                result['categories'] = [{
                    'id': category_id,
                    'name': doc.get('category_name_s'),
                }]
            
            if detail == True:
                result['variants'] = template.product_variant_ids.solr_results()
                result['description'] = template.website_description or ''
            
            results.append(result)
        
        return results

    @api.constrains('active')
    def constrains_active(self):
        for rec in self:
            rec._create_solr_queue_sync_product_template()