def read_group(
     self,
     domain,
     fields,
     groupby,
     offset=0,
     limit=None,
     orderby=False,
     lazy=True,
 ):
     if "share_unit_price" in fields:
         fields.remove("share_unit_price")
     if "register_number_operation" in fields:
         fields.remove("register_number_operation")
     res = super(SubscriptionRegister, self).read_group(
         domain,
         fields,
         groupby,
         offset=offset,
         limit=limit,
         orderby=orderby,
         lazy=lazy,
     )
     if "total_amount_line" in fields:
         for line in res:
             if "__domain" in line:
                 lines = self.search(line["__domain"])
                 inv_value = 0.0
                 for line2 in lines:
                     inv_value += line2.total_amount_line
                 line["total_amount_line"] = inv_value
     return res
Exemple #2
0
    def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
        if all('on_time_rate' not in field for field in fields):
            res = super().read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
            return res

        for field in fields:
            if 'on_time_rate' not in field:
                continue

            fields.remove(field)

            agg = field.split(':')[1:]
            if agg and agg[0] != 'sum':
                raise NotImplementedError('Aggregate functions other than \':sum\' are not allowed.')

            qty_total = field.replace('on_time_rate', 'qty_total')
            if qty_total not in fields:
                fields.append(qty_total)
            qty_on_time = field.replace('on_time_rate', 'qty_on_time')
            if qty_on_time not in fields:
                fields.append(qty_on_time)
            break

        res = super().read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)

        for group in res:
            if group['qty_total'] == 0:
                on_time_rate = 100
            else:
                on_time_rate = group['qty_on_time'] / group['qty_total'] * 100
            group.update({'on_time_rate': on_time_rate})

        return res
Exemple #3
0
 def _onchange_country_id(self):
     """Sensible values and domains for related fields."""
     fields = ['state_id', 'nuts1_id', 'nuts2_id', 'nuts3_id', 'nuts4_id']
     country_domain = ([('country_id', '=',
                         self.country_id.id)] if self.country_id else [])
     domain = dict()
     for field in fields:
         if self.country_id and self[field].country_id != self.country_id:
             self[field] = False
         domain[field] = list(country_domain)  # Using list() to copy
     fields.remove('state_id')
     for field in fields:
         level = int(field[4])
         domain[field].append(('level', '=', level))
     if self.country_id:
         nuts1 = self.env['res.partner.nuts'].search([
             ('level', '=', 1),
             ('country_id', '=', self.country_id.id),
         ],
                                                     limit=1)
         if self.nuts1_id.id != nuts1.id:
             self.nuts1_id = nuts1.id
     return {
         'domain': domain,
     }
Exemple #4
0
 def _generate_dict_fields(self):
     fields = super(ConnectorDirectory, self)._generate_dict_fields()
     if 'thumbnail' in fields:
         fields.remove('thumbnail')
     if 'custom_thumbnail' in fields:
         fields.remove('custom_thumbnail')
     return fields
 def read_group(self,
                domain,
                fields,
                groupby,
                offset=0,
                limit=None,
                orderby=False,
                lazy=True):
     if 'share_unit_price' in fields:
         fields.remove('share_unit_price')
     if 'register_number_operation' in fields:
         fields.remove('register_number_operation')
     res = super(SubscriptionRegister, self).read_group(domain,
                                                        fields,
                                                        groupby,
                                                        offset=offset,
                                                        limit=limit,
                                                        orderby=orderby,
                                                        lazy=lazy)
     if 'total_amount_line' in fields:
         for line in res:
             if '__domain' in line:
                 lines = self.search(line['__domain'])
                 inv_value = 0.0
                 for line2 in lines:
                     inv_value += line2.total_amount_line
                 line['total_amount_line'] = inv_value
     return res
 def read_group(self,
                domain,
                fields,
                groupby,
                offset=0,
                limit=None,
                orderby=False,
                lazy=True):
     groups = {
         "location_id",
         "company_id",
         "preset_reason_id",
         "category_id",
         "in_date",
     }
     if (groups & set(groupby)) or len(groupby) == 0:
         if "unit_value" in fields:
             fields.remove("unit_value")
         if "difference_qty" in fields:
             fields.remove("difference_qty")
     return super().read_group(domain,
                               fields,
                               groupby,
                               offset,
                               limit=limit,
                               orderby=orderby,
                               lazy=lazy)
 def read_group(self,
                domain,
                fields,
                groupby,
                offset=0,
                limit=None,
                orderby=False,
                lazy=True):
     fields_to_compute = []
     for field in ('line_rate', 'branch_rate'):
         if field in fields:
             fields.remove(field)
             fields_to_compute.append(field)
     res = super(Coverage, self).read_group(domain, fields, groupby, offset,
                                            limit, orderby, lazy)
     if fields_to_compute:
         fields_to_read = [
             'line_count', 'branch_count', 'branch_rate', 'line_rate'
         ]
         for group in res:
             if group.get('__domain'):
                 line_infos = self.search_read(group['__domain'],
                                               fields_to_read)
                 line_counts = sum([l['line_count'] for l in line_infos])
                 branch_counts = sum(
                     [l['branch_count'] for l in line_infos])
                 group['line_rate'] = line_counts and \
                     sum([l['line_rate'] * l['line_count']
                          for l in line_infos]) / line_counts or 0
                 group['branch_rate'] = branch_counts and \
                     sum([l['branch_rate'] * l['branch_count']
                          for l in line_infos]) / branch_counts or 0
     return res
Exemple #8
0
    def _generate_order_by(self, order_spec, query):
        '''
        replace sort field, if sort by key.
        replace on sort by prefix, number
        '''
        new_order_spec = order_spec
        if order_spec:
            fields = []
            for order_part in order_spec.split(','):
                order_split = order_part.strip().split(' ')
                order_field = order_split[0].strip()
                order_direction = order_split[1].strip().upper() if len(order_split) == 2 else ''
                fields.append((order_field, order_direction))

            key_field = [x for x in fields if x[0] == 'key']
            if key_field:
                direction = key_field[0][1]
                fields.remove(key_field[0])
                fields.extend([('prefix', direction), ('number', direction)])

            fields = map(lambda x: ' '.join(x), fields)
            new_order_spec = ','.join(fields)

        order_by = super(Task, self)._generate_order_by(new_order_spec, query)
        return order_by
Exemple #9
0
    def _update_fields_values(self, fields):
        #print '_update_fields_values'
        if 'property_account_position_id' in fields:
            #print 'se encontro'
            fields.remove('property_account_position_id')
            #print 'fields: ',fields

        return super(res_partner, self)._update_fields_values(fields)
Exemple #10
0
 def _get_eshop_fields(self):
     fields = super()._get_eshop_fields()
     for field in fields:
         if "image" in field:
             fields.remove(field)
     fields.append("image_write_date")
     fields.append("image_write_date_hash")
     return fields
Exemple #11
0
 def read(self, fields=None, load='_classic_read'):
     if not fields:
         return super(OperationResult, self).read(fields, load=load)
     if 'display_name' in fields:
         fields.remove('display_name')
     if '__last_update' in fields:
         fields.remove('__last_update')
     return super(OperationResult, self).read(fields, load=load)
	def read(self, fields=None, load='_classic_read'):
		lang = self._context.get('lang')  or False
		if lang and lang == 'es_CO':		
			if 'l10n_ar_afip_responsibility_type_id' in fields:
				fields.remove('l10n_ar_afip_responsibility_type_id')
			if 'l10n_latam_identification_type_id' in fields:
				fields.remove('l10n_latam_identification_type_id')
		
		return super(ResPartner, self).read(fields, load=load)
				
Exemple #13
0
 def _onchange_country_id_base_location_nuts(self):
     """Sensible values and domains for related fields."""
     fields = ["state_id", "nuts1_id", "nuts2_id", "nuts3_id", "nuts4_id"]
     for field in fields:
         if self.country_id and self[field].country_id != self.country_id:
             self[field] = False
     fields.remove("state_id")
     if self.country_id:
         nuts1 = self.env["res.partner.nuts"].search(
             [("level", "=", 1), ("country_id", "=", self.country_id.id)],
             limit=1)
         if self.nuts1_id.id != nuts1.id:
             self.nuts1_id = nuts1.id
Exemple #14
0
 def read_group(self,
                domain,
                fields,
                groupby,
                offset=0,
                limit=None,
                orderby=False,
                lazy=True):
     if 'co2' in fields:
         fields.remove('co2')
     return super(FleetVehicle,
                  self).read_group(domain, fields, groupby, offset, limit,
                                   orderby, lazy)
Exemple #15
0
 def on_record_write(self, record, fields=None):
     """ Called when a record is written """
     for field in self.EXCLUDE_FIELDS:
         if field in fields:
             fields.remove(field)
     if 'active' in fields and not record.active:
         self.prestashop_product_combination_unlink(record)
         return
     if fields:
         priority = 20
         if 'default_on' in fields and record.active:
             # PS has to uncheck actual default combination first
             priority = 99
         for binding in record.prestashop_combinations_bind_ids:
             binding.with_delay(priority=priority).export_record(
                 fields=fields)
 def read(self, fields=None, load='_classic_read'):
     special = False
     if fields:
         for field in ('fields_to_fill', 'fields_filled'):
             if field in fields:
                 fields.remove(field)
                 special = True
                 break
     res = super(ChecklistTaskInstance, self).read(fields, load)
     if special:
         for info in res:
             task_inst = self.browse(info['id'])
             info['fields_to_fill'] = task_inst.field_ids_to_fill.mapped(
                 'name')
             info['fields_filled'] = task_inst.field_ids_filled.mapped(
                 'name')
     return res
Exemple #17
0
 def read_group(self, domain, fields, groupby, offset=0, limit=None,
                orderby=False, lazy=True):
     fields_to_compute = []
     for field in self._fields_to_compute:
         if field in fields:
             fields.remove(field)
             fields_to_compute.append(field)
     res = super(BudgetLine, self).read_group(
         domain, fields, groupby, offset, limit, orderby, lazy)
     if fields_to_compute:
         for group in res:
             if group.get('__domain'):
                 line_infos = self.search_read(group['__domain'],
                                               fields_to_compute)
                 for field in fields_to_compute:
                     group[field] = sum([l[field] for l in line_infos])
     return res
Exemple #18
0
 def read_group(self,
                domain,
                fields,
                groupby,
                offset=0,
                limit=None,
                orderby=False,
                lazy=True):
     if ("categ_id" in groupby
             or "location_id" not in groupby) and "cost" in fields:
         fields.remove("cost")
     return super().read_group(domain,
                               fields,
                               groupby,
                               offset,
                               limit=limit,
                               orderby=orderby,
                               lazy=lazy)
Exemple #19
0
 def _generate_dict_fields(self):
     fields = super(ConnectorFile, self)._generate_dict_fields()
     if 'content' in fields:
         fields.remove('content')
     if 'index_content' in fields:
         fields.remove('index_content')
     if 'thumbnail' in fields:
         fields.remove('thumbnail')
     if 'custom_thumbnail' in fields:
         fields.remove('custom_thumbnail')
     return fields
Exemple #20
0
 def read_group(self,
                domain,
                fields,
                groupby,
                offset=0,
                limit=None,
                context=None,
                orderby=False,
                lazy=True):
     if 'stop_time' in fields:
         fields.remove('stop_time')
     if 'start_time' in fields:
         fields.remove('start_time')
     return super(AccountAnalyticLine, self).read_group(domain,
                                                        fields,
                                                        groupby,
                                                        offset,
                                                        limit=limit,
                                                        orderby=orderby,
                                                        lazy=lazy)
Exemple #21
0
 def read_group(self,
                domain,
                fields,
                groupby,
                offset=0,
                limit=None,
                context=None,
                orderby=False,
                lazy=True):
     if 'rate_per_hour' in fields:
         fields.remove('rate_per_hour')
     if 'min_bill' in fields:
         fields.remove('min_bill')
     return super(TimesheetInvoice, self).read_group(domain,
                                                     fields,
                                                     groupby,
                                                     offset,
                                                     limit=limit,
                                                     orderby=orderby,
                                                     lazy=lazy)
Exemple #22
0
    def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
        """ This is a hack to allow us to correctly calculate the average of PO specific date values since
            the normal report query result will duplicate PO values across its PO lines during joins and
            lead to incorrect aggregation values.

            Only the AVG operator is supported for avg_days_to_purchase.
        """
        avg_days_to_purchase = next((field for field in fields if re.search(r'\bavg_days_to_purchase\b', field)), False)

        if avg_days_to_purchase:
            fields.remove(avg_days_to_purchase)
            if any(field.split(':')[1].split('(')[0] != 'avg' for field in [avg_days_to_purchase] if field):
                raise UserError("Value: 'avg_days_to_purchase' should only be used to show an average. If you are seeing this message then it is being accessed incorrectly.")

        res = []
        if fields:
            res = super(PurchaseReport, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)

        if not res and avg_days_to_purchase:
            res = [{}]

        if avg_days_to_purchase:
            self.check_access_rights('read')
            query = """ SELECT AVG(days_to_purchase.po_days_to_purchase)::decimal(16,2) AS avg_days_to_purchase
                          FROM (
                              SELECT extract(epoch from age(po.date_approve,po.create_date))/(24*60*60) AS po_days_to_purchase
                              FROM purchase_order po
                              WHERE po.id IN (
                                  SELECT "purchase_report"."order_id" FROM %s WHERE %s)
                              ) AS days_to_purchase
                    """

            subdomain = AND([domain, [('company_id', '=', self.env.company.id), ('date_approve', '!=', False)]])
            subtables, subwhere, subparams = expression(subdomain, self).query.get_sql()

            self.env.cr.execute(query % (subtables, subwhere), subparams)
            res[0].update({
                '__count': 1,
                avg_days_to_purchase.split(':')[0]: self.env.cr.fetchall()[0][0],
            })
        return res
Exemple #23
0
 def read_group(self,
                domain,
                fields,
                groupby,
                offset=0,
                limit=None,
                orderby=False,
                lazy=True):
     """ Override to handle the "inventory mode" and set the `inventory_quantity`
     in view list grouped.
     """
     if 'purity' in fields:
         fields.remove('purity')
     result = super(StockValuationLayer, self).read_group(domain,
                                                          fields,
                                                          groupby,
                                                          offset=offset,
                                                          limit=limit,
                                                          orderby=orderby,
                                                          lazy=lazy)
     return result
Exemple #24
0
 def _onchange_country_id_base_location_nuts(self):
     """Sensible values and domains for related fields."""
     fields = ["state_id", "nuts1_id", "nuts2_id", "nuts3_id", "nuts4_id"]
     country_domain = ([("country_id", "=",
                         self.country_id.id)] if self.country_id else [])
     domain = dict()
     for field in fields:
         if self.country_id and self[field].country_id != self.country_id:
             self[field] = False
         domain[field] = list(country_domain)  # Using list() to copy
     fields.remove("state_id")
     for field in fields:
         level = int(field[4])
         domain[field].append(("level", "=", level))
     if self.country_id:
         nuts1 = self.env["res.partner.nuts"].search(
             [("level", "=", 1), ("country_id", "=", self.country_id.id)],
             limit=1)
         if self.nuts1_id.id != nuts1.id:
             self.nuts1_id = nuts1.id
     return {"domain": domain}
    def read_group(self,
                   domain,
                   fields,
                   groupby,
                   offset=0,
                   limit=None,
                   orderby=False,
                   lazy=True):
        if 'on_time_rate' not in fields:
            res = super().read_group(domain,
                                     fields,
                                     groupby,
                                     offset=offset,
                                     limit=limit,
                                     orderby=orderby,
                                     lazy=lazy)
            return res

        fields.remove('on_time_rate')
        if 'qty_total' not in fields:
            fields.append('qty_total')
        if 'qty_on_time' not in fields:
            fields.append('qty_on_time')
        res = super().read_group(domain,
                                 fields,
                                 groupby,
                                 offset=offset,
                                 limit=limit,
                                 orderby=orderby,
                                 lazy=lazy)
        for group in res:
            if group['qty_total'] == 0:
                on_time_rate = 100
            else:
                on_time_rate = group['qty_on_time'] / group['qty_total'] * 100
            group.update({'on_time_rate': on_time_rate})

        return res
Exemple #26
0
 def read(self, fields=None, load='_classic_read'):
     # ugly hack to avoid report being read when we enter a view with report added on print menu
     if not fields:
         fields = list(self._fields)
         fields.remove('report_data')
         if 'background_image' in fields:
             fields.remove('background_image')
         if 'logo' in fields:
             fields.remove('logo')
     return super().read(fields, load=load)
Exemple #27
0
    def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
        """
            This is a hack made in order to improve performance as adding
            inventory valuation on the report itself would be too costly.

            Basically when asked to return the valuation, it will run a smaller
            SQL query that will calculate the inventory valuation on the given
            domain.

            Only the SUM operator is supported for valuation.

            We can also get the stock_value of the inventory at a specific date
            (default is today).

            The same applies to this stock_value field, it only supports the sum operator
            and does not support the group by.

            NB: This should probably be implemented in a read instead of read_group since
                we don't support grouping

            NB: We might be able to avoid doing this hack by optimizing the query used to
                generate the report (= TODO: see nse)
        """
        stock_value = next((field for field in fields if re.search(r'\bstock_value\b', field)), False)
        valuation = next((field for field in fields if re.search(r'\bvaluation\b', field)), False)

        if stock_value:
            fields.remove(stock_value)

        if valuation:
            fields.remove(valuation)

        if stock_value or valuation:
            if groupby:
                raise UserError("valuation and stock_value don't support grouping")

            if any(field.split(':')[1].split('(')[0] != 'sum' for field in [stock_value, valuation] if field):
                raise UserError("read_group only support operator sum for valuation and stock_value")

        res = []
        if fields:
            res = super(StockReport, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)

        if not res and (stock_value or valuation):
            res = [{}]

        if stock_value:
            products = self.env['product.product']
            # Split the recordset for faster computing.
            value = sum(
                product.value_svl
                for products_split in self.env.cr.split_for_in_conditions(
                    products.search([("product_tmpl_id.type", "=", "product")]).ids
                )
                for product in products.browse(products_split)
            )

            res[0].update({
                '__count': 1,
                stock_value.split(':')[0]: value,
            })

        if valuation:
            query = """
                SELECT
                    SUM(move_valuation.valuation) as valuation
                FROM (
                    SELECT
                        sum(svl.value) AS valuation
                    FROM
                        stock_move move
                        INNER JOIN stock_valuation_layer AS svl ON svl.stock_move_id = move.id
                    WHERE
                        move.id IN (
                            SELECT id
                            FROM stock_report
                            WHERE %s )
                 GROUP BY
                        move.id
                ) as move_valuation
            """

            where, args = expression(domain + [('company_id', '=', self.env.company.id)], self).to_sql()
            self.env.cr.execute(query % where, args)
            res[0].update({
                '__count': 1,
                valuation.split(':')[0]: self.env.cr.fetchall()[0][0],
            })

        return res
Exemple #28
0
    def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
        """
            This is a hack made in order to improve performance as adding
            inventory valuation on the report itself would be too costly.

            Basically when asked to return the valuation, it will run a smaller
            SQL query that will calculate the inventory valuation on the given
            domain.

            Only the SUM operator is supported for valuation.

            We can also get the stock_value of the inventory at a specific date
            (default is today).

            The same applies to this stock_value field, it only supports the sum operator
            and does not support the group by.

            NB: This should probably be implemented in a read instead of read_group since
                we don't support grouping

            NB: We might be able to avoid doing this hack by optimizing the query used to
                generate the report (= TODO: see nse)
        """
        stock_value = next((field for field in fields if re.search(r'\bstock_value\b', field)), False)
        valuation = next((field for field in fields if re.search(r'\bvaluation\b', field)), False)

        if stock_value:
            fields.remove(stock_value)

        if valuation:
            fields.remove(valuation)

        if stock_value or valuation:
            if groupby:
                raise UserError("valuation and stock_value don't support grouping")

            if any(field.split(':')[1].split('(')[0] != 'sum' for field in [stock_value, valuation] if field):
                raise UserError("read_group only support operator sum for valuation and stock_value")

        res = []
        if fields:
            res = super(StockReport, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)

        if not res and (stock_value or valuation):
            res = [{}]

        if stock_value:
            date = Date.to_string(Date.from_string(next((d[2] for d in domain if d[0] == 'date_done'), Date.today())))

            products = self.env['product.product'].with_context(to_date=date).search([('product_tmpl_id.type', '=', 'product')])
            value = sum(product.stock_value for product in products)

            res[0].update({
                '__count': 1,
                stock_value.split(':')[0]: value,
            })

        if valuation:
            query = """
                SELECT
                    SUM(move_valuation.valuation) as valuation
                FROM (
                    SELECT
                        CASE property.value_text -- cost method
                            WHEN 'fifo' THEN move.value
                            WHEN 'average' THEN move.value
                            ELSE move.product_qty * product_property.value_float -- standard price
                        END as valuation
                    FROM
                        stock_move move
                        INNER JOIN product_product product ON move.product_id = product.id
                        INNER JOIN product_template ON product.product_tmpl_id = product_template.id
                        INNER JOIN product_category category ON product_template.categ_id = category.id
                        LEFT JOIN ir_property property ON property.res_id = CONCAT('product.category,', category.id)
                        INNER JOIN ir_property product_property ON product_property.res_id = CONCAT('product.product,', product.id)
                    WHERE
                        move.id IN (
                            SELECT id
                            FROM stock_report
                            WHERE %s )
                        AND (property.company_id is null or property.company_id = move.company_id)
                        AND product_property.company_id = move.company_id
                ) as move_valuation
            """

            where, args = expression(domain + [('company_id', '=', self.env.user.company_id.id)], self).to_sql()
            self.env.cr.execute(query % where, args)
            res[0].update({
                '__count': 1,
                valuation.split(':')[0]: self.env.cr.fetchall()[0][0],
            })

        return res
Exemple #29
0
    def read_group(self,
                   domain,
                   fields,
                   groupby,
                   offset=0,
                   limit=None,
                   orderby=False,
                   lazy=True):
        """ This is a hack to allow us to correctly calculate the average of PO specific date values since
            the normal report query result will duplicate PO values across its PO lines during joins and
            lead to incorrect aggregation values.

            Only the AVG operator is supported for avg_receipt_delay.
        """
        avg_receipt_delay = next(
            (field for field in fields
             if re.search(r'\bavg_receipt_delay\b', field)), False)

        if avg_receipt_delay:
            fields.remove(avg_receipt_delay)
            if any(
                    field.split(':')[1].split('(')[0] != 'avg'
                    for field in [avg_receipt_delay] if field):
                raise UserError(
                    "Value: 'avg_receipt_delay' should only be used to show an average. If you are seeing this message then it is being accessed incorrectly."
                )

        res = []
        if fields:
            res = super(PurchaseReport, self).read_group(domain,
                                                         fields,
                                                         groupby,
                                                         offset=offset,
                                                         limit=limit,
                                                         orderby=orderby,
                                                         lazy=lazy)

        if not res and avg_receipt_delay:
            res = [{}]

        if avg_receipt_delay:
            query = """ SELECT AVG(receipt_delay.po_receipt_delay)::decimal(16,2) AS avg_receipt_delay
                          FROM (
                              SELECT extract(epoch from age(po.effective_date,COALESCE(po.date_planned, po.expected_date)))/(24*60*60) AS po_receipt_delay
                              FROM purchase_order po
                              WHERE po.id IN (
                                  SELECT order_id
                                  FROM purchase_report
                                  WHERE effective_date IS NOT NULL
                                    AND %s )
                              ) AS receipt_delay
                    """

            where, args = expression(
                domain + [('company_id', '=', self.env.company.id)],
                self).to_sql()
            self.env.cr.execute(query % where, args)
            res[0].update({
                '__count':
                1,
                avg_receipt_delay.split(':')[0]:
                self.env.cr.fetchall()[0][0],
            })
        return res
Exemple #30
0
 def _generate_dict_fields(self):
     fields = self._fields.keys()
     fields.remove('id')
     fields.append('.id')
     return fields