Exemplo n.º 1
0
    def _sale_get_invoice_price(self, order):
        """ Based on the current move line, compute the price to reinvoice the analytic line that is going to be created (so the
            price of the sale line).
        """
        self.ensure_one()

        unit_amount = self.quantity
        amount = (self.credit or 0.0) - (self.debit or 0.0)

        if self.product_id.expense_policy == 'sales_price':
            return self.product_id.with_context(
                partner=order.partner_id.id,
                date_order=order.date_order,
                pricelist=order.pricelist_id.id,
                uom=self.product_uom_id.id).price

        uom_precision_digits = self.env['decimal.precision'].precision_get(
            'Product Unit of Measure')
        if float_is_zero(unit_amount, precision_digits=uom_precision_digits):
            return 0.0

        # Prevent unnecessary currency conversion that could be impacted by exchange rate
        # fluctuations
        if self.company_id.currency_id and amount and self.company_id.currency_id == order.currency_id:
            return abs(amount / unit_amount)

        price_unit = abs(amount / unit_amount)
        currency_id = self.company_id.currency_id
        if currency_id and currency_id != order.currency_id:
            price_unit = currency_id._convert(
                price_unit, order.currency_id, order.company_id,
                order.date_order or fields.Date.today())
        return price_unit
Exemplo n.º 2
0
 def _search_difference_qty(self, operator, value):
     if operator == '=':
         result = True
     elif operator == '!=':
         result = False
     else:
         raise NotImplementedError()
     lines = self.search([('inventory_id', '=', self.env.context.get('default_inventory_id'))])
     line_ids = lines.filtered(lambda line: float_is_zero(line.difference_qty, line.product_id.uom_id.rounding) == result).ids
     return [('id', 'in', line_ids)]
Exemplo n.º 3
0
    def test_rounding_invalid(self):
        """ verify that invalid parameters are forbidden """
        with self.assertRaises(AssertionError):
            float_is_zero(0.01, precision_digits=3, precision_rounding=0.01)

        with self.assertRaises(AssertionError):
            float_is_zero(0.0, precision_rounding=0.0)

        with self.assertRaises(AssertionError):
            float_is_zero(0.0, precision_rounding=-0.1)

        with self.assertRaises(AssertionError):
            float_compare(0.01,
                          0.02,
                          precision_digits=3,
                          precision_rounding=0.01)

        with self.assertRaises(AssertionError):
            float_compare(1.0, 1.0, precision_rounding=0.0)

        with self.assertRaises(AssertionError):
            float_compare(1.0, 1.0, precision_rounding=-0.1)

        with self.assertRaises(AssertionError):
            float_round(0.01, precision_digits=3, precision_rounding=0.01)

        with self.assertRaises(AssertionError):
            float_round(1.25, precision_rounding=0.0)

        with self.assertRaises(AssertionError):
            float_round(1.25, precision_rounding=-0.1)
Exemplo n.º 4
0
 def _generate_moves(self):
     vals_list = []
     for line in self:
         virtual_location = line._get_virtual_location()
         rounding = line.product_id.uom_id.rounding
         if float_is_zero(line.difference_qty, precision_rounding=rounding):
             continue
         if line.difference_qty > 0:  # found more than expected
             vals = line._get_move_values(line.difference_qty, virtual_location.id, line.location_id.id, False)
         else:
             vals = line._get_move_values(abs(line.difference_qty), line.location_id.id, virtual_location.id, True)
         vals_list.append(vals)
     return self.env['stock.move'].create(vals_list)
Exemplo n.º 5
0
    def is_zero(self, amount):
        """Returns true if ``amount`` is small enough to be treated as
           zero according to current currency's rounding rules.
           Warning: ``is_zero(amount1-amount2)`` is not always equivalent to
           ``compare_amounts(amount1,amount2) == 0``, as the former will round after
           computing the difference, while the latter will round before, giving
           different results for e.g. 0.006 and 0.002 at 2 digits precision.

           :param float amount: amount to compare with currency's zero

           With the new API, call it like: ``currency.is_zero(amount)``.
        """
        self.ensure_one()
        return tools.float_is_zero(amount, precision_rounding=self.rounding)
Exemplo n.º 6
0
 def _costs_generate(self):
     """ Calculates total costs at the end of the production.
     """
     self.ensure_one()
     AccountAnalyticLine = self.env['account.analytic.line'].sudo()
     for wc_line in self.workorder_ids.filtered(
             'workcenter_id.costs_hour_account_id'):
         vals = self._prepare_wc_analytic_line(wc_line)
         precision_rounding = wc_line.workcenter_id.costs_hour_account_id.currency_id.rounding
         if not float_is_zero(vals.get('amount', 0.0),
                              precision_rounding=precision_rounding):
             # we use SUPERUSER_ID as we do not guarantee an mrp user
             # has access to account analytic lines but still should be
             # able to produce orders
             AccountAnalyticLine.create(vals)
Exemplo n.º 7
0
 def _onchange_qty_done(self):
     """ When the user is encoding a produce line for a tracked product, we apply some logic to
     help him. This onchange will warn him if he set `qty_done` to a non-supported value.
     """
     res = {}
     if self.product_id.tracking == 'serial' and not float_is_zero(
             self.qty_done, self.product_uom_id.rounding):
         if float_compare(
                 self.qty_done,
                 1.0,
                 precision_rounding=self.product_uom_id.rounding) != 0:
             message = _(
                 'You can only process 1.0 %s of products with unique serial number.'
             ) % self.product_id.uom_id.name
             res['warning'] = {'title': _('Warning'), 'message': message}
     return res
Exemplo n.º 8
0
 def summary(self):
     res = super(EventRegistration, self).summary()
     if self.event_ticket_id.product_id.image_128:
         res['image'] = '/web/image/product.product/%s/image_128' % self.event_ticket_id.product_id.id
     information = res.setdefault('information', {})
     information.append((_('Name'), self.name))
     information.append((_('Ticket'), self.event_ticket_id.name
                         or _('None')))
     order = self.sale_order_id.sudo()
     order_line = self.sale_order_line_id.sudo()
     if not order or float_is_zero(
             order_line.price_total,
             precision_digits=order.currency_id.rounding):
         payment_status = _('Free')
     elif not order.invoice_ids or any(invoice.state != 'paid'
                                       for invoice in order.invoice_ids):
         payment_status = _('To pay')
         res['alert'] = _('The registration must be paid')
     else:
         payment_status = _('Paid')
     information.append((_('Payment'), payment_status))
     return res
Exemplo n.º 9
0
    def _get_invoiced_lot_values(self):
        """ Get and prepare data to show a table of invoiced lot on the invoice's report. """
        self.ensure_one()

        if self.state == 'draft':
            return []

        sale_orders = self.mapped('invoice_line_ids.sale_line_ids.order_id')
        stock_move_lines = sale_orders.mapped(
            'picking_ids.move_lines.move_line_ids')

        # Get the other customer invoices and refunds.
        ordered_invoice_ids = sale_orders.mapped('invoice_ids')\
            .filtered(lambda i: i.state not in ['draft', 'cancel'])\
            .sorted(lambda i: (i.invoice_date, i.id))

        # Get the position of self in other customer invoices and refunds.
        self_index = None
        i = 0
        for invoice in ordered_invoice_ids:
            if invoice.id == self.id:
                self_index = i
                break
            i += 1

        # Get the previous invoice if any.
        previous_invoices = ordered_invoice_ids[:self_index]
        last_invoice = previous_invoices[-1] if len(
            previous_invoices) else None

        # Get the incoming and outgoing sml between self.invoice_date and the previous invoice (if any).
        self_datetime = max(self.invoice_line_ids.mapped(
            'write_date')) if self.invoice_line_ids else None
        last_invoice_datetime = max(
            last_invoice.invoice_line_ids.mapped(
                'write_date')) if last_invoice else None

        def _filter_incoming_sml(ml):
            if ml.state == 'done' and ml.location_id.usage == 'customer' and ml.lot_id:
                if last_invoice_datetime:
                    return last_invoice_datetime <= ml.date <= self_datetime
                else:
                    return ml.date <= self_datetime
            return False

        def _filter_outgoing_sml(ml):
            if ml.state == 'done' and ml.location_dest_id.usage == 'customer' and ml.lot_id:
                if last_invoice_datetime:
                    return last_invoice_datetime <= ml.date <= self_datetime
                else:
                    return ml.date <= self_datetime
            return False

        incoming_sml = stock_move_lines.filtered(_filter_incoming_sml)
        outgoing_sml = stock_move_lines.filtered(_filter_outgoing_sml)

        # Prepare and return lot_values
        qties_per_lot = defaultdict(lambda: 0)
        if self.type == 'out_refund':
            for ml in outgoing_sml:
                qties_per_lot[
                    ml.lot_id] -= ml.product_uom_id._compute_quantity(
                        ml.qty_done, ml.product_id.uom_id)
            for ml in incoming_sml:
                qties_per_lot[
                    ml.lot_id] += ml.product_uom_id._compute_quantity(
                        ml.qty_done, ml.product_id.uom_id)
        else:
            for ml in outgoing_sml:
                qties_per_lot[
                    ml.lot_id] += ml.product_uom_id._compute_quantity(
                        ml.qty_done, ml.product_id.uom_id)
            for ml in incoming_sml:
                qties_per_lot[
                    ml.lot_id] -= ml.product_uom_id._compute_quantity(
                        ml.qty_done, ml.product_id.uom_id)
        lot_values = []
        for lot_id, qty in qties_per_lot.items():
            if float_is_zero(
                    qty, precision_rounding=lot_id.product_id.uom_id.rounding):
                continue
            lot_values.append({
                'product_name': lot_id.product_id.name,
                'quantity': qty,
                'uom_name': lot_id.product_uom_id.name,
                'lot_name': lot_id.name,
            })
        return lot_values
Exemplo n.º 10
0
    def test_invoice(self):
        """ Test create and invoice from the SO, and check qty invoice/to invoice, and the related amounts """
        # lines are in draft
        for line in self.sale_order.order_line:
            self.assertTrue(
                float_is_zero(line.untaxed_amount_to_invoice,
                              precision_digits=2),
                "The amount to invoice should be zero, as the line is in draf state"
            )
            self.assertTrue(
                float_is_zero(line.untaxed_amount_invoiced,
                              precision_digits=2),
                "The invoiced amount should be zero, as the line is in draft state"
            )

        # Confirm the SO
        self.sale_order.action_confirm()

        # Check ordered quantity, quantity to invoice and invoiced quantity of SO lines
        for line in self.sale_order.order_line:
            if line.product_id.invoice_policy == 'delivery':
                self.assertEquals(
                    line.qty_to_invoice, 0.0,
                    'Quantity to invoice should be same as ordered quantity')
                self.assertEquals(
                    line.qty_invoiced, 0.0,
                    'Invoiced quantity should be zero as no any invoice created for SO'
                )
                self.assertEquals(
                    line.untaxed_amount_to_invoice, 0.0,
                    "The amount to invoice should be zero, as the line based on delivered quantity"
                )
                self.assertEquals(
                    line.untaxed_amount_invoiced, 0.0,
                    "The invoiced amount should be zero, as the line based on delivered quantity"
                )
            else:
                self.assertEquals(
                    line.qty_to_invoice, line.product_uom_qty,
                    'Quantity to invoice should be same as ordered quantity')
                self.assertEquals(
                    line.qty_invoiced, 0.0,
                    'Invoiced quantity should be zero as no any invoice created for SO'
                )
                self.assertEquals(
                    line.untaxed_amount_to_invoice,
                    line.product_uom_qty * line.price_unit,
                    "The amount to invoice should the total of the line, as the line is confirmed"
                )
                self.assertEquals(
                    line.untaxed_amount_invoiced, 0.0,
                    "The invoiced amount should be zero, as the line is confirmed"
                )

        # Let's do an invoice with invoiceable lines
        payment = self.env['sale.advance.payment.inv'].with_context(
            self.context).create({'advance_payment_method': 'delivered'})
        payment.create_invoices()

        invoice = self.sale_order.invoice_ids[0]

        # Update quantity of an invoice lines
        move_form = Form(invoice)
        with move_form.invoice_line_ids.edit(0) as line_form:
            line_form.quantity = 3.0
        with move_form.invoice_line_ids.edit(1) as line_form:
            line_form.quantity = 2.0
        invoice = move_form.save()

        # amount to invoice / invoiced should not have changed (amounts take only confirmed invoice into account)
        for line in self.sale_order.order_line:
            if line.product_id.invoice_policy == 'delivery':
                self.assertEquals(line.qty_to_invoice, 0.0,
                                  "Quantity to invoice should be zero")
                self.assertEquals(
                    line.qty_invoiced, 0.0,
                    "Invoiced quantity should be zero as delivered lines are not delivered yet"
                )
                self.assertEquals(
                    line.untaxed_amount_to_invoice, 0.0,
                    "The amount to invoice should be zero, as the line based on delivered quantity (no confirmed invoice)"
                )
                self.assertEquals(
                    line.untaxed_amount_invoiced, 0.0,
                    "The invoiced amount should be zero, as no invoice are validated for now"
                )
            else:
                if line == self.sol_prod_order:
                    self.assertEquals(
                        self.sol_prod_order.qty_to_invoice, 2.0,
                        "Changing the quantity on draft invoice update the qty to invoice on SO lines"
                    )
                    self.assertEquals(
                        self.sol_prod_order.qty_invoiced, 3.0,
                        "Changing the quantity on draft invoice update the invoiced qty on SO lines"
                    )
                else:
                    self.assertEquals(
                        self.sol_serv_order.qty_to_invoice, 1.0,
                        "Changing the quantity on draft invoice update the qty to invoice on SO lines"
                    )
                    self.assertEquals(
                        self.sol_serv_order.qty_invoiced, 2.0,
                        "Changing the quantity on draft invoice update the invoiced qty on SO lines"
                    )
                self.assertEquals(
                    line.untaxed_amount_to_invoice,
                    line.product_uom_qty * line.price_unit,
                    "The amount to invoice should the total of the line, as the line is confirmed (no confirmed invoice)"
                )
                self.assertEquals(
                    line.untaxed_amount_invoiced, 0.0,
                    "The invoiced amount should be zero, as no invoice are validated for now"
                )

        invoice.post()

        # Check quantity to invoice on SO lines
        for line in self.sale_order.order_line:
            if line.product_id.invoice_policy == 'delivery':
                self.assertEquals(
                    line.qty_to_invoice, 0.0,
                    "Quantity to invoice should be same as ordered quantity")
                self.assertEquals(
                    line.qty_invoiced, 0.0,
                    "Invoiced quantity should be zero as no any invoice created for SO"
                )
                self.assertEquals(
                    line.untaxed_amount_to_invoice, 0.0,
                    "The amount to invoice should be zero, as the line based on delivered quantity"
                )
                self.assertEquals(
                    line.untaxed_amount_invoiced, 0.0,
                    "The invoiced amount should be zero, as the line based on delivered quantity"
                )
            else:
                if line == self.sol_prod_order:
                    self.assertEquals(
                        line.qty_to_invoice, 2.0,
                        "The ordered sale line are totally invoiced (qty to invoice is zero)"
                    )
                    self.assertEquals(
                        line.qty_invoiced, 3.0,
                        "The ordered (prod) sale line are totally invoiced (qty invoiced come from the invoice lines)"
                    )
                else:
                    self.assertEquals(
                        line.qty_to_invoice, 1.0,
                        "The ordered sale line are totally invoiced (qty to invoice is zero)"
                    )
                    self.assertEquals(
                        line.qty_invoiced, 2.0,
                        "The ordered (serv) sale line are totally invoiced (qty invoiced = the invoice lines)"
                    )
                self.assertEquals(
                    line.untaxed_amount_to_invoice,
                    line.price_unit * line.qty_to_invoice,
                    "Amount to invoice is now set as qty to invoice * unit price since no price change on invoice, for ordered products"
                )
                self.assertEquals(
                    line.untaxed_amount_invoiced,
                    line.price_unit * line.qty_invoiced,
                    "Amount invoiced is now set as qty invoiced * unit price since no price change on invoice, for ordered products"
                )
Exemplo n.º 11
0
    def test_invoice_with_discount(self):
        """ Test invoice with a discount and check discount applied on both SO lines and an invoice lines """
        # Update discount and delivered quantity on SO lines
        self.sol_prod_order.write({'discount': 20.0})
        self.sol_serv_deliver.write({'discount': 20.0, 'qty_delivered': 4.0})
        self.sol_serv_order.write({'discount': -10.0})
        self.sol_prod_deliver.write({'qty_delivered': 2.0})

        for line in self.sale_order.order_line.filtered(lambda l: l.discount):
            product_price = line.price_unit * line.product_uom_qty
            self.assertEquals(line.discount,
                              (product_price - line.price_subtotal) /
                              product_price * 100,
                              'Discount should be applied on order line')

        # lines are in draft
        for line in self.sale_order.order_line:
            self.assertTrue(
                float_is_zero(line.untaxed_amount_to_invoice,
                              precision_digits=2),
                "The amount to invoice should be zero, as the line is in draf state"
            )
            self.assertTrue(
                float_is_zero(line.untaxed_amount_invoiced,
                              precision_digits=2),
                "The invoiced amount should be zero, as the line is in draft state"
            )

        self.sale_order.action_confirm()

        for line in self.sale_order.order_line:
            self.assertTrue(
                float_is_zero(line.untaxed_amount_invoiced,
                              precision_digits=2),
                "The invoiced amount should be zero, as the line is in draft state"
            )

        self.assertEquals(self.sol_serv_order.untaxed_amount_to_invoice, 297,
                          "The untaxed amount to invoice is wrong")
        self.assertEquals(
            self.sol_serv_deliver.untaxed_amount_to_invoice,
            self.sol_serv_deliver.qty_delivered *
            self.sol_serv_deliver.price_reduce,
            "The untaxed amount to invoice should be qty deli * price reduce, so 4 * (180 - 36)"
        )
        self.assertEquals(
            self.sol_prod_deliver.untaxed_amount_to_invoice, 140,
            "The untaxed amount to invoice should be qty deli * price reduce, so 4 * (180 - 36)"
        )

        # Let's do an invoice with invoiceable lines
        payment = self.env['sale.advance.payment.inv'].with_context(
            self.context).create({'advance_payment_method': 'delivered'})
        payment.create_invoices()
        invoice = self.sale_order.invoice_ids[0]
        invoice.post()

        # Check discount appeared on both SO lines and invoice lines
        for line, inv_line in zip(self.sale_order.order_line,
                                  invoice.invoice_line_ids):
            self.assertEquals(
                line.discount, inv_line.discount,
                'Discount on lines of order and invoice should be same')
Exemplo n.º 12
0
    def change_prod_qty(self):
        precision = self.env['decimal.precision'].precision_get(
            'Product Unit of Measure')
        for wizard in self:
            production = wizard.mo_id
            produced = sum(
                production.move_finished_ids.filtered(
                    lambda m: m.product_id == production.product_id).mapped(
                        'quantity_done'))
            if wizard.product_qty < produced:
                format_qty = '%.{precision}f'.format(precision=precision)
                raise UserError(
                    _("You have already processed %s. Please input a quantity higher than %s "
                      ) % (format_qty % produced, format_qty % produced))
            old_production_qty = production.product_qty
            production.write({'product_qty': wizard.product_qty})
            done_moves = production.move_finished_ids.filtered(
                lambda x: x.state == 'done' and x.product_id == production.
                product_id)
            qty_produced = production.product_id.uom_id._compute_quantity(
                sum(done_moves.mapped('product_qty')),
                production.product_uom_id)
            factor = production.product_uom_id._compute_quantity(
                production.product_qty - qty_produced, production.bom_id.
                product_uom_id) / production.bom_id.product_qty
            boms, lines = production.bom_id.explode(
                production.product_id,
                factor,
                picking_type=production.bom_id.picking_type_id)
            documents = {}
            for line, line_data in lines:
                if line.child_bom_id and line.child_bom_id.type == 'phantom' or\
                        line.product_id.type not in ['product', 'consu']:
                    continue
                move = production.move_raw_ids.filtered(
                    lambda x: x.bom_line_id.id == line.id and x.state not in
                    ('done', 'cancel'))
                if move:
                    move = move[0]
                    old_qty = move.product_uom_qty
                else:
                    old_qty = 0
                iterate_key = production._get_document_iterate_key(move)
                if iterate_key:
                    document = self.env[
                        'stock.picking']._log_activity_get_documents(
                            {move: (line_data['qty'], old_qty)}, iterate_key,
                            'UP')
                    for key, value in document.items():
                        if documents.get(key):
                            documents[key] += [value]
                        else:
                            documents[key] = [value]

                production._update_raw_move(line, line_data)

            production._log_manufacture_exception(documents)
            operation_bom_qty = {}
            for bom, bom_data in boms:
                for operation in bom.routing_id.operation_ids:
                    operation_bom_qty[operation.id] = bom_data['qty']
            finished_moves_modification = self._update_finished_moves(
                production, production.product_qty - qty_produced,
                old_production_qty)
            production._log_downside_manufactured_quantity(
                finished_moves_modification)
            moves = production.move_raw_ids.filtered(lambda x: x.state not in
                                                     ('done', 'cancel'))
            moves._action_assign()
            for wo in production.workorder_ids:
                operation = wo.operation_id
                if operation_bom_qty.get(operation.id):
                    cycle_number = float_round(
                        operation_bom_qty[operation.id] /
                        operation.workcenter_id.capacity,
                        precision_digits=0,
                        rounding_method='UP')
                    wo.duration_expected = (
                        operation.workcenter_id.time_start +
                        operation.workcenter_id.time_stop +
                        cycle_number * operation.time_cycle * 100.0 /
                        operation.workcenter_id.time_efficiency)
                quantity = wo.qty_production - wo.qty_produced
                if production.product_id.tracking == 'serial':
                    quantity = 1.0 if not float_is_zero(
                        quantity, precision_digits=precision) else 0.0
                else:
                    quantity = quantity if (quantity > 0) else 0
                if float_is_zero(quantity, precision_digits=precision):
                    wo.finished_lot_id = False
                    wo._workorder_line_ids().unlink()
                wo.qty_producing = quantity
                if wo.qty_produced < wo.qty_production and wo.state == 'done':
                    wo.state = 'progress'
                if wo.qty_produced == wo.qty_production and wo.state == 'progress':
                    wo.state = 'done'
                # assign moves; last operation receive all unassigned moves
                # TODO: following could be put in a function as it is similar as code in _workorders_create
                # TODO: only needed when creating new moves
                moves_raw = production.move_raw_ids.filtered(
                    lambda move: move.operation_id == operation and move.state
                    not in ('done', 'cancel'))
                if wo == production.workorder_ids[-1]:
                    moves_raw |= production.move_raw_ids.filtered(
                        lambda move: not move.operation_id)
                moves_finished = production.move_finished_ids.filtered(
                    lambda move: move.operation_id == operation
                )  #TODO: code does nothing, unless maybe by_products?
                moves_raw.mapped('move_line_ids').write(
                    {'workorder_id': wo.id})
                (moves_finished + moves_raw).write({'workorder_id': wo.id})
                if wo.state not in ('done', 'cancel'):
                    line_values = wo._update_workorder_lines()
                    wo._workorder_line_ids().create(line_values['to_create'])
                    if line_values['to_delete']:
                        line_values['to_delete'].unlink()
                    for line, vals in line_values['to_update'].items():
                        line.write(vals)
        return {}
Exemplo n.º 13
0
    def test_timesheet_manual(self):
        """ Test timesheet invoicing with 'invoice on delivery' timetracked products
        """
        # create SO and confirm it
        sale_order = self.env['sale.order'].create({
            'partner_id':
            self.partner_customer_usd.id,
            'partner_invoice_id':
            self.partner_customer_usd.id,
            'partner_shipping_id':
            self.partner_customer_usd.id,
            'pricelist_id':
            self.pricelist_usd.id,
        })
        so_line_manual_global_project = self.env['sale.order.line'].create({
            'name':
            self.product_delivery_manual2.name,
            'product_id':
            self.product_delivery_manual2.id,
            'product_uom_qty':
            50,
            'product_uom':
            self.product_delivery_manual2.uom_id.id,
            'price_unit':
            self.product_delivery_manual2.list_price,
            'order_id':
            sale_order.id,
        })
        so_line_manual_only_project = self.env['sale.order.line'].create({
            'name':
            self.product_delivery_manual4.name,
            'product_id':
            self.product_delivery_manual4.id,
            'product_uom_qty':
            20,
            'product_uom':
            self.product_delivery_manual4.uom_id.id,
            'price_unit':
            self.product_delivery_manual4.list_price,
            'order_id':
            sale_order.id,
        })

        # confirm SO
        sale_order.action_confirm()
        self.assertTrue(sale_order.project_ids,
                        "Sales Order should have create a project")
        self.assertEqual(
            sale_order.invoice_status, 'no',
            'Sale Timesheet: manually product should not need to be invoiced on so confirmation'
        )

        project_serv2 = so_line_manual_only_project.project_id
        self.assertTrue(
            project_serv2,
            "A second project is created when selling 'project only' after SO confirmation."
        )
        self.assertEqual(
            sale_order.analytic_account_id, project_serv2.analytic_account_id,
            "The created project should be linked to the analytic account of the SO"
        )

        # let's log some timesheets (on task and project)
        timesheet1 = self.env['account.analytic.line'].create({
            'name':
            'Test Line',
            'project_id':
            self.project_global.id,  # global project
            'task_id':
            so_line_manual_global_project.task_id.id,
            'unit_amount':
            6,
            'employee_id':
            self.employee_manager.id,
        })

        timesheet2 = self.env['account.analytic.line'].create({
            'name':
            'Test Line',
            'project_id':
            self.project_global.id,  # global project
            'unit_amount':
            3,
            'employee_id':
            self.employee_manager.id,
        })

        self.assertEqual(
            len(sale_order.project_ids), 2,
            "One project should have been created by the SO, when confirmed + the one coming from SO line 1 'task in global project'."
        )
        self.assertEqual(
            so_line_manual_global_project.task_id.sale_line_id,
            so_line_manual_global_project,
            "Task from a milestone product should be linked to its SO line too"
        )
        self.assertEqual(
            timesheet1.timesheet_invoice_type, 'billable_fixed',
            "Milestone timesheet goes in billable fixed category")
        self.assertTrue(
            float_is_zero(so_line_manual_global_project.qty_delivered,
                          precision_digits=2),
            "Milestone Timesheeting should not incremented the delivered quantity on the SO line"
        )
        self.assertEqual(
            so_line_manual_global_project.qty_to_invoice, 0.0,
            "Manual service should not be affected by timesheet on their created task."
        )
        self.assertEqual(
            so_line_manual_only_project.qty_to_invoice, 0.0,
            "Manual service should not be affected by timesheet on their created project."
        )
        self.assertEqual(
            sale_order.invoice_status, 'no',
            'Sale Timesheet: "invoice on delivery" should not need to be invoiced on so confirmation'
        )

        self.assertEqual(
            timesheet1.timesheet_invoice_type, 'billable_fixed',
            "Timesheets linked to SO line with ordered product shoulbe be billable fixed since it is a milestone"
        )
        self.assertEqual(
            timesheet2.timesheet_invoice_type, 'non_billable_project',
            "Timesheets without task shoulbe be 'no project found'")
        self.assertFalse(timesheet1.timesheet_invoice_id,
                         "The timesheet1 should not be linked to the invoice")
        self.assertFalse(timesheet2.timesheet_invoice_id,
                         "The timesheet2 should not be linked to the invoice")

        # invoice SO
        sale_order.order_line.write({'qty_delivered': 5})
        invoice1 = sale_order._create_invoices()

        for invoice_line in invoice1.invoice_line_ids:
            self.assertEqual(
                invoice_line.quantity, 5,
                "The invoiced quantity should be 5, as manually set on SO lines"
            )

        self.assertFalse(
            timesheet1.timesheet_invoice_id,
            "The timesheet1 should not be linked to the invoice, since timesheets are used for time tracking in milestone"
        )
        self.assertFalse(
            timesheet2.timesheet_invoice_id,
            "The timesheet2 should not be linked to the invoice, since timesheets are used for time tracking in milestone"
        )

        # validate the invoice
        invoice1.post()

        self.assertFalse(
            timesheet1.timesheet_invoice_id,
            "The timesheet1 should not be linked to the invoice, even after invoice validation"
        )
        self.assertFalse(
            timesheet2.timesheet_invoice_id,
            "The timesheet2 should not be linked to the invoice, even after invoice validation"
        )
Exemplo n.º 14
0
    def test_timesheet_delivery(self):
        """ Test timesheet invoicing with 'invoice on delivery' timetracked products
                1. Create SO and confirm it
                2. log timesheet
                3. create invoice
                4. log other timesheet
                5. create a second invoice
                6. add new SO line (delivered service)
        """
        # create SO and confirm it
        sale_order = self.env['sale.order'].create({
            'partner_id':
            self.partner_customer_usd.id,
            'partner_invoice_id':
            self.partner_customer_usd.id,
            'partner_shipping_id':
            self.partner_customer_usd.id,
            'pricelist_id':
            self.pricelist_usd.id,
        })
        so_line_deliver_global_project = self.env['sale.order.line'].create({
            'name':
            self.product_delivery_timesheet2.name,
            'product_id':
            self.product_delivery_timesheet2.id,
            'product_uom_qty':
            50,
            'product_uom':
            self.product_delivery_timesheet2.uom_id.id,
            'price_unit':
            self.product_delivery_timesheet2.list_price,
            'order_id':
            sale_order.id,
        })
        so_line_deliver_task_project = self.env['sale.order.line'].create({
            'name':
            self.product_delivery_timesheet3.name,
            'product_id':
            self.product_delivery_timesheet3.id,
            'product_uom_qty':
            20,
            'product_uom':
            self.product_delivery_timesheet3.uom_id.id,
            'price_unit':
            self.product_delivery_timesheet3.list_price,
            'order_id':
            sale_order.id,
        })
        so_line_deliver_global_project.product_id_change()
        so_line_deliver_task_project.product_id_change()

        # confirm SO
        sale_order.action_confirm()
        task_serv1 = self.env['project.task'].search([
            ('sale_line_id', '=', so_line_deliver_global_project.id)
        ])
        task_serv2 = self.env['project.task'].search([
            ('sale_line_id', '=', so_line_deliver_task_project.id)
        ])
        project_serv2 = self.env['project.project'].search([
            ('sale_line_id', '=', so_line_deliver_task_project.id)
        ])

        self.assertEqual(
            task_serv1.project_id, self.project_global,
            "Sale Timesheet: task should be created in global project")
        self.assertTrue(
            task_serv1,
            "Sale Timesheet: on SO confirmation, a task should have been created in global project"
        )
        self.assertTrue(
            task_serv2,
            "Sale Timesheet: on SO confirmation, a task should have been created in a new project"
        )
        self.assertEqual(
            sale_order.invoice_status, 'no',
            'Sale Timesheet: "invoice on delivery" should not need to be invoiced on so confirmation'
        )
        self.assertEqual(sale_order.analytic_account_id,
                         task_serv2.project_id.analytic_account_id,
                         "SO should have create a project")
        self.assertEqual(
            sale_order.tasks_count, 2,
            "Two tasks (1 per SO line) should have been created on SO confirmation"
        )
        self.assertEqual(
            len(sale_order.project_ids), 2,
            "One project should have been created by the SO, when confirmed + the one from SO line 1 'task in global project'"
        )
        self.assertEqual(
            sale_order.analytic_account_id, project_serv2.analytic_account_id,
            "The created project should be linked to the analytic account of the SO"
        )

        # let's log some timesheets
        timesheet1 = self.env['account.analytic.line'].create({
            'name':
            'Test Line',
            'project_id':
            task_serv1.project_id.id,  # global project
            'task_id':
            task_serv1.id,
            'unit_amount':
            10.5,
            'employee_id':
            self.employee_manager.id,
        })
        self.assertEqual(
            so_line_deliver_global_project.invoice_status, 'to invoice',
            'Sale Timesheet: "invoice on delivery" timesheets should set the so line in "to invoice" status when logged'
        )
        self.assertEqual(
            so_line_deliver_task_project.invoice_status, 'no',
            'Sale Timesheet: so line invoice status should not change when no timesheet linked to the line'
        )
        self.assertEqual(
            sale_order.invoice_status, 'to invoice',
            'Sale Timesheet: "invoice on delivery" timesheets should set the so in "to invoice" status when logged'
        )
        self.assertEqual(
            timesheet1.timesheet_invoice_type, 'billable_time',
            "Timesheets linked to SO line with delivered product shoulbe be billable time"
        )
        self.assertFalse(
            timesheet1.timesheet_invoice_id,
            "The timesheet1 should not be linked to the invoice yet")

        # invoice SO
        invoice1 = sale_order._create_invoices()
        self.assertTrue(
            float_is_zero(invoice1.amount_total -
                          so_line_deliver_global_project.price_unit * 10.5,
                          precision_digits=2),
            'Sale: invoice generation on timesheets product is wrong')
        self.assertEqual(
            timesheet1.timesheet_invoice_id, invoice1,
            "The timesheet1 should not be linked to the invoice 1, as we are in delivered quantity (even if invoice is in draft"
        )
        with self.assertRaises(
                UserError
        ):  # We can not modify timesheet linked to invoice (even draft ones)
            timesheet1.write({'unit_amount': 42})

        # log some timesheets again
        timesheet2 = self.env['account.analytic.line'].create({
            'name':
            'Test Line',
            'project_id':
            task_serv1.project_id.id,  # global project
            'task_id':
            task_serv1.id,
            'unit_amount':
            39.5,
            'employee_id':
            self.employee_user.id,
        })
        self.assertEqual(
            so_line_deliver_global_project.invoice_status, 'to invoice',
            'Sale Timesheet: "invoice on delivery" timesheets should set the so line in "to invoice" status when logged'
        )
        self.assertEqual(
            so_line_deliver_task_project.invoice_status, 'no',
            'Sale Timesheet: so line invoice status should not change when no timesheet linked to the line'
        )
        self.assertEqual(
            sale_order.invoice_status, 'to invoice',
            'Sale Timesheet: "invoice on delivery" timesheets should not modify the invoice_status of the so'
        )
        self.assertEqual(
            timesheet2.timesheet_invoice_type, 'billable_time',
            "Timesheets linked to SO line with delivered product shoulbe be billable time"
        )
        self.assertFalse(
            timesheet2.timesheet_invoice_id,
            "The timesheet2 should not be linked to the invoice yet")

        # create a second invoice
        invoice2 = sale_order._create_invoices()[0]
        self.assertEqual(
            len(sale_order.invoice_ids), 2,
            "A second invoice should have been created from the SO")
        self.assertEqual(
            so_line_deliver_global_project.invoice_status, 'invoiced',
            'Sale Timesheet: "invoice on delivery" timesheets should set the so line in "to invoice" status when logged'
        )
        self.assertEqual(
            sale_order.invoice_status, 'no',
            'Sale Timesheet: "invoice on delivery" timesheets should be invoiced completely by now'
        )
        self.assertEqual(
            timesheet2.timesheet_invoice_id, invoice2,
            "The timesheet2 should not be linked to the invoice 2")
        with self.assertRaises(
                UserError
        ):  # We can not modify timesheet linked to invoice (even draft ones)
            timesheet2.write({'unit_amount': 42})

        # add a line on SO
        so_line_deliver_only_project = self.env['sale.order.line'].create({
            'name':
            self.product_delivery_timesheet4.name,
            'product_id':
            self.product_delivery_timesheet4.id,
            'product_uom_qty':
            5,
            'product_uom':
            self.product_delivery_timesheet4.uom_id.id,
            'price_unit':
            self.product_delivery_timesheet4.list_price,
            'order_id':
            sale_order.id,
        })
        self.assertEqual(
            len(sale_order.project_ids), 2,
            "No new project should have been created by the SO, when selling 'project only' product, since it reuse the one from 'new task in new project'."
        )

        # let's log some timesheets on the project
        timesheet3 = self.env['account.analytic.line'].create({
            'name':
            'Test Line',
            'project_id':
            project_serv2.id,
            'unit_amount':
            7,
            'employee_id':
            self.employee_user.id,
        })
        self.assertTrue(
            float_is_zero(so_line_deliver_only_project.qty_delivered,
                          precision_digits=2),
            "Timesheeting on project should not incremented the delivered quantity on the SO line"
        )
        self.assertEqual(
            sale_order.invoice_status, 'no',
            'Sale Timesheet: "invoice on delivery" timesheets should be invoiced completely by now'
        )
        self.assertEqual(
            timesheet3.timesheet_invoice_type, 'non_billable_project',
            "Timesheets without task shoulbe be 'no project found'")
        self.assertFalse(
            timesheet3.timesheet_invoice_id,
            "The timesheet3 should not be linked to the invoice yet")

        # let's log some timesheets on the task (new task/new project)
        timesheet4 = self.env['account.analytic.line'].create({
            'name':
            'Test Line 4',
            'project_id':
            task_serv2.project_id.id,
            'task_id':
            task_serv2.id,
            'unit_amount':
            7,
            'employee_id':
            self.employee_user.id,
        })
        self.assertFalse(
            timesheet4.timesheet_invoice_id,
            "The timesheet4 should not be linked to the invoice yet")

        # modify a non invoiced timesheet
        timesheet4.write({'unit_amount': 42})

        self.assertFalse(
            timesheet4.timesheet_invoice_id,
            "The timesheet4 should not still be linked to the invoice")

        # validate the second invoice
        invoice2.post()

        self.assertEqual(
            timesheet1.timesheet_invoice_id, invoice1,
            "The timesheet1 should not be linked to the invoice 1, even after validation"
        )
        self.assertEqual(
            timesheet2.timesheet_invoice_id, invoice2,
            "The timesheet2 should not be linked to the invoice 1, even after validation"
        )
        self.assertFalse(
            timesheet3.timesheet_invoice_id,
            "The timesheet3 should not be linked to the invoice, since we are in ordered quantity"
        )
        self.assertFalse(
            timesheet4.timesheet_invoice_id,
            "The timesheet4 should not be linked to the invoice, since we are in ordered quantity"
        )
Exemplo n.º 15
0
    def test_timesheet_order(self):
        """ Test timesheet invoicing with 'invoice on order' timetracked products
                1. create SO with 2 ordered product and confirm
                2. create invoice
                3. log timesheet
                4. add new SO line (ordered service)
                5. create new invoice
        """
        # create SO and confirm it
        sale_order = self.env['sale.order'].create({
            'partner_id':
            self.partner_customer_usd.id,
            'partner_invoice_id':
            self.partner_customer_usd.id,
            'partner_shipping_id':
            self.partner_customer_usd.id,
            'pricelist_id':
            self.pricelist_usd.id,
        })
        so_line_ordered_project_only = self.env['sale.order.line'].create({
            'name':
            self.product_order_timesheet4.name,
            'product_id':
            self.product_order_timesheet4.id,
            'product_uom_qty':
            10,
            'product_uom':
            self.product_order_timesheet4.uom_id.id,
            'price_unit':
            self.product_order_timesheet4.list_price,
            'order_id':
            sale_order.id,
        })
        so_line_ordered_global_project = self.env['sale.order.line'].create({
            'name':
            self.product_order_timesheet2.name,
            'product_id':
            self.product_order_timesheet2.id,
            'product_uom_qty':
            50,
            'product_uom':
            self.product_order_timesheet2.uom_id.id,
            'price_unit':
            self.product_order_timesheet2.list_price,
            'order_id':
            sale_order.id,
        })
        so_line_ordered_project_only.product_id_change()
        so_line_ordered_global_project.product_id_change()
        sale_order.action_confirm()
        task_serv2 = self.env['project.task'].search([
            ('sale_line_id', '=', so_line_ordered_global_project.id)
        ])
        project_serv1 = self.env['project.project'].search([
            ('sale_line_id', '=', so_line_ordered_project_only.id)
        ])

        self.assertEqual(
            sale_order.tasks_count, 1,
            "One task should have been created on SO confirmation")
        self.assertEqual(
            len(sale_order.project_ids), 2,
            "One project should have been created by the SO, when confirmed + the one from SO line 2 'task in global project'"
        )
        self.assertEqual(
            sale_order.analytic_account_id, project_serv1.analytic_account_id,
            "The created project should be linked to the analytic account of the SO"
        )

        # create invoice
        invoice1 = sale_order._create_invoices()[0]

        # let's log some timesheets (on the project created by so_line_ordered_project_only)
        timesheet1 = self.env['account.analytic.line'].create({
            'name':
            'Test Line',
            'project_id':
            task_serv2.project_id.id,
            'task_id':
            task_serv2.id,
            'unit_amount':
            10.5,
            'employee_id':
            self.employee_user.id,
        })
        self.assertEqual(
            so_line_ordered_global_project.qty_delivered, 10.5,
            'Timesheet directly on project does not increase delivered quantity on so line'
        )
        self.assertEqual(
            sale_order.invoice_status, 'invoiced',
            'Sale Timesheet: "invoice on order" timesheets should not modify the invoice_status of the so'
        )
        self.assertEqual(
            timesheet1.timesheet_invoice_type, 'billable_fixed',
            "Timesheets linked to SO line with ordered product shoulbe be billable fixed"
        )
        self.assertFalse(
            timesheet1.timesheet_invoice_id,
            "The timesheet1 should not be linked to the invoice, since we are in ordered quantity"
        )

        timesheet2 = self.env['account.analytic.line'].create({
            'name':
            'Test Line',
            'project_id':
            task_serv2.project_id.id,
            'task_id':
            task_serv2.id,
            'unit_amount':
            39.5,
            'employee_id':
            self.employee_user.id,
        })
        self.assertEqual(
            so_line_ordered_global_project.qty_delivered, 50,
            'Sale Timesheet: timesheet does not increase delivered quantity on so line'
        )
        self.assertEqual(
            sale_order.invoice_status, 'invoiced',
            'Sale Timesheet: "invoice on order" timesheets should not modify the invoice_status of the so'
        )
        self.assertEqual(
            timesheet2.timesheet_invoice_type, 'billable_fixed',
            "Timesheets linked to SO line with ordered product shoulbe be billable fixed"
        )
        self.assertFalse(
            timesheet2.timesheet_invoice_id,
            "The timesheet should not be linked to the invoice, since we are in ordered quantity"
        )

        timesheet3 = self.env['account.analytic.line'].create({
            'name':
            'Test Line',
            'project_id':
            task_serv2.project_id.id,
            'unit_amount':
            10,
            'employee_id':
            self.employee_user.id,
        })
        self.assertEqual(
            so_line_ordered_project_only.qty_delivered, 0.0,
            'Timesheet directly on project does not increase delivered quantity on so line'
        )
        self.assertEqual(
            timesheet3.timesheet_invoice_type, 'non_billable_project',
            "Timesheets without task shoulbe be 'no project found'")
        self.assertFalse(
            timesheet3.timesheet_invoice_id,
            "The timesheet should not be linked to the invoice, since we are in ordered quantity"
        )

        # log timesheet on task in global project (higher than the initial ordrered qty)
        timesheet4 = self.env['account.analytic.line'].create({
            'name':
            'Test Line',
            'project_id':
            task_serv2.project_id.id,
            'task_id':
            task_serv2.id,
            'unit_amount':
            5,
            'employee_id':
            self.employee_user.id,
        })
        self.assertEqual(
            sale_order.invoice_status, 'upselling',
            'Sale Timesheet: "invoice on order" timesheets should not modify the invoice_status of the so'
        )
        self.assertFalse(
            timesheet4.timesheet_invoice_id,
            "The timesheet should not be linked to the invoice, since we are in ordered quantity"
        )

        # add so line with produdct "create task in new project".
        so_line_ordered_task_in_project = self.env['sale.order.line'].create({
            'name':
            self.product_order_timesheet3.name,
            'product_id':
            self.product_order_timesheet3.id,
            'product_uom_qty':
            3,
            'product_uom':
            self.product_order_timesheet3.uom_id.id,
            'price_unit':
            self.product_order_timesheet3.list_price,
            'order_id':
            sale_order.id,
        })

        self.assertEqual(
            sale_order.invoice_status, 'to invoice',
            'Sale Timesheet: Adding a new service line (so line) should put the SO in "to invocie" state.'
        )
        self.assertEqual(
            sale_order.tasks_count, 2,
            "Two tasks (1 per SO line) should have been created on SO confirmation"
        )
        self.assertEqual(
            len(sale_order.project_ids), 2,
            "No new project should have been created by the SO, when selling 'new task in new project' product, since it reuse the one from 'project only'."
        )

        # get first invoice line of sale line linked to timesheet1
        invoice_line_1 = so_line_ordered_global_project.invoice_lines.filtered(
            lambda line: line.move_id == invoice1)

        self.assertEqual(
            so_line_ordered_global_project.product_uom_qty,
            invoice_line_1.quantity,
            "The invoice (ordered) quantity should not change when creating timesheet"
        )

        # timesheet can be modified
        timesheet1.write({'unit_amount': 12})

        self.assertEqual(
            so_line_ordered_global_project.product_uom_qty,
            invoice_line_1.quantity,
            "The invoice (ordered) quantity should not change when modifying timesheet"
        )

        # create second invoice
        invoice2 = sale_order._create_invoices()[0]

        self.assertEqual(
            len(sale_order.invoice_ids), 2,
            "A second invoice should have been created from the SO")
        self.assertTrue(
            float_is_zero(invoice2.amount_total -
                          so_line_ordered_task_in_project.price_unit * 3,
                          precision_digits=2),
            'Sale: invoice generation on timesheets product is wrong')

        self.assertFalse(
            timesheet1.timesheet_invoice_id,
            "The timesheet1 should not be linked to the invoice, since we are in ordered quantity"
        )
        self.assertFalse(
            timesheet2.timesheet_invoice_id,
            "The timesheet2 should not be linked to the invoice, since we are in ordered quantity"
        )
        self.assertFalse(
            timesheet3.timesheet_invoice_id,
            "The timesheet3 should not be linked to the invoice, since we are in ordered quantity"
        )
        self.assertFalse(
            timesheet4.timesheet_invoice_id,
            "The timesheet4 should not be linked to the invoice, since we are in ordered quantity"
        )

        # validate the first invoice
        invoice1.post()

        self.assertEqual(
            so_line_ordered_global_project.product_uom_qty,
            invoice_line_1.quantity,
            "The invoice (ordered) quantity should not change when modifying timesheet"
        )
        self.assertFalse(
            timesheet1.timesheet_invoice_id,
            "The timesheet1 should not be linked to the invoice, since we are in ordered quantity"
        )
        self.assertFalse(
            timesheet2.timesheet_invoice_id,
            "The timesheet2 should not be linked to the invoice, since we are in ordered quantity"
        )
        self.assertFalse(
            timesheet3.timesheet_invoice_id,
            "The timesheet3 should not be linked to the invoice, since we are in ordered quantity"
        )
        self.assertFalse(
            timesheet4.timesheet_invoice_id,
            "The timesheet4 should not be linked to the invoice, since we are in ordered quantity"
        )

        # timesheet can still be modified
        timesheet1.write({'unit_amount': 13})
Exemplo n.º 16
0
    def _get_partner_move_lines(self, account_type, date_from, target_move,
                                period_length):
        # This method can receive the context key 'include_nullified_amount' {Boolean}
        # Do an invoice and a payment and unreconcile. The amount will be nullified
        # By default, the partner wouldn't appear in this report.
        # The context key allow it to appear
        # In case of a period_length of 30 days as of 2019-02-08, we want the following periods:
        # Name       Stop         Start
        # 1 - 30   : 2019-02-07 - 2019-01-09
        # 31 - 60  : 2019-01-08 - 2018-12-10
        # 61 - 90  : 2018-12-09 - 2018-11-10
        # 91 - 120 : 2018-11-09 - 2018-10-11
        # +120     : 2018-10-10
        ctx = self._context
        periods = {}
        date_from = fields.Date.from_string(date_from)
        start = date_from
        for i in range(5)[::-1]:
            stop = start - relativedelta(days=period_length)
            period_name = str((5 - (i + 1)) * period_length + 1) + '-' + str(
                (5 - i) * period_length)
            period_stop = (start - relativedelta(days=1)).strftime('%Y-%m-%d')
            if i == 0:
                period_name = '+' + str(4 * period_length)
            periods[str(i)] = {
                'name': period_name,
                'stop': period_stop,
                'start': (i != 0 and stop.strftime('%Y-%m-%d') or False),
            }
            start = stop

        res = []
        total = []
        partner_clause = ''
        cr = self.env.cr
        user_company = self.env.company
        user_currency = user_company.currency_id
        company_ids = self._context.get('company_ids') or [user_company.id]
        move_state = ['draft', 'posted']
        if target_move == 'posted':
            move_state = ['posted']
        arg_list = (
            tuple(move_state),
            tuple(account_type),
            date_from,
            date_from,
        )
        if ctx.get('partner_ids'):
            partner_clause = 'AND (l.partner_id IN %s)'
            arg_list += (tuple(ctx['partner_ids'].ids), )
        if ctx.get('partner_categories'):
            partner_clause += 'AND (l.partner_id IN %s)'
            partner_ids = self.env['res.partner'].search([
                ('category_id', 'in', ctx['partner_categories'].ids)
            ]).ids
            arg_list += (tuple(partner_ids or [0]), )
        arg_list += (date_from, tuple(company_ids))

        query = '''
            SELECT DISTINCT l.partner_id, res_partner.name AS name, UPPER(res_partner.name) AS UPNAME, CASE WHEN prop.value_text IS NULL THEN 'normal' ELSE prop.value_text END AS trust
            FROM account_move_line AS l
              LEFT JOIN res_partner ON l.partner_id = res_partner.id
              LEFT JOIN ir_property prop ON (prop.res_id = 'res.partner,'||res_partner.id AND prop.name='trust' AND prop.company_id=%s),
              account_account, account_move am
            WHERE (l.account_id = account_account.id)
                AND (l.move_id = am.id)
                AND (am.state IN %s)
                AND (account_account.internal_type IN %s)
                AND (
                        l.reconciled IS FALSE
                        OR l.id IN(
                            SELECT credit_move_id FROM account_partial_reconcile where max_date > %s
                            UNION ALL
                            SELECT debit_move_id FROM account_partial_reconcile where max_date > %s
                        )
                    )
                    ''' + partner_clause + '''
                AND (l.date <= %s)
                AND l.company_id IN %s
            ORDER BY UPPER(res_partner.name)'''
        arg_list = (self.env.company.id, ) + arg_list
        cr.execute(query, arg_list)

        partners = cr.dictfetchall()
        # put a total of 0
        for i in range(7):
            total.append(0)

        # Build a string like (1,2,3) for easy use in SQL query
        partner_ids = [
            partner['partner_id'] for partner in partners
            if partner['partner_id']
        ]
        lines = dict(
            (partner['partner_id'] or False, []) for partner in partners)
        if not partner_ids:
            return [], [], {}

        # Use one query per period and store results in history (a list variable)
        # Each history will contain: history[1] = {'<partner_id>': <partner_debit-credit>}
        history = []
        for i in range(5):
            args_list = (
                tuple(move_state),
                tuple(account_type),
                tuple(partner_ids),
            )
            dates_query = '(COALESCE(l.date_maturity,l.date)'

            if periods[str(i)]['start'] and periods[str(i)]['stop']:
                dates_query += ' BETWEEN %s AND %s)'
                args_list += (periods[str(i)]['start'],
                              periods[str(i)]['stop'])
            elif periods[str(i)]['start']:
                dates_query += ' >= %s)'
                args_list += (periods[str(i)]['start'], )
            else:
                dates_query += ' <= %s)'
                args_list += (periods[str(i)]['stop'], )
            args_list += (date_from, tuple(company_ids))

            query = '''SELECT l.id
                    FROM account_move_line AS l, account_account, account_move am
                    WHERE (l.account_id = account_account.id) AND (l.move_id = am.id)
                        AND (am.state IN %s)
                        AND (account_account.internal_type IN %s)
                        AND ((l.partner_id IN %s) OR (l.partner_id IS NULL))
                        AND ''' + dates_query + '''
                    AND (l.date <= %s)
                    AND l.company_id IN %s
                    ORDER BY COALESCE(l.date_maturity, l.date)'''
            cr.execute(query, args_list)
            partners_amount = {}
            aml_ids = cr.fetchall()
            aml_ids = aml_ids and [x[0] for x in aml_ids] or []
            for line in self.env['account.move.line'].browse(
                    aml_ids).with_context(prefetch_fields=False):
                partner_id = line.partner_id.id or False
                if partner_id not in partners_amount:
                    partners_amount[partner_id] = 0.0
                line_amount = line.company_id.currency_id._convert(
                    line.balance, user_currency, user_company, date_from)
                if user_currency.is_zero(line_amount):
                    continue
                for partial_line in line.matched_debit_ids:
                    if partial_line.max_date <= date_from:
                        line_amount += partial_line.company_id.currency_id._convert(
                            partial_line.amount, user_currency, user_company,
                            date_from)
                for partial_line in line.matched_credit_ids:
                    if partial_line.max_date <= date_from:
                        line_amount -= partial_line.company_id.currency_id._convert(
                            partial_line.amount, user_currency, user_company,
                            date_from)

                if not self.env.company.currency_id.is_zero(line_amount):
                    partners_amount[partner_id] += line_amount
                    lines.setdefault(partner_id, [])
                    lines[partner_id].append({
                        'line': line,
                        'amount': line_amount,
                        'period': i + 1,
                    })
            history.append(partners_amount)

        # This dictionary will store the not due amount of all partners
        undue_amounts = {}
        query = '''SELECT l.id
                FROM account_move_line AS l, account_account, account_move am
                WHERE (l.account_id = account_account.id) AND (l.move_id = am.id)
                    AND (am.state IN %s)
                    AND (account_account.internal_type IN %s)
                    AND (COALESCE(l.date_maturity,l.date) >= %s)\
                    AND ((l.partner_id IN %s) OR (l.partner_id IS NULL))
                AND (l.date <= %s)
                AND l.company_id IN %s
                ORDER BY COALESCE(l.date_maturity, l.date)'''
        cr.execute(query, (tuple(move_state), tuple(account_type), date_from,
                           tuple(partner_ids), date_from, tuple(company_ids)))
        aml_ids = cr.fetchall()
        aml_ids = aml_ids and [x[0] for x in aml_ids] or []
        for line in self.env['account.move.line'].browse(aml_ids):
            partner_id = line.partner_id.id or False
            if partner_id not in undue_amounts:
                undue_amounts[partner_id] = 0.0
            line_amount = line.company_id.currency_id._convert(
                line.balance, user_currency, user_company, date_from)
            if user_currency.is_zero(line_amount):
                continue
            for partial_line in line.matched_debit_ids:
                if partial_line.max_date <= date_from:
                    line_amount += partial_line.company_id.currency_id._convert(
                        partial_line.amount, user_currency, user_company,
                        date_from)
            for partial_line in line.matched_credit_ids:
                if partial_line.max_date <= date_from:
                    line_amount -= partial_line.company_id.currency_id._convert(
                        partial_line.amount, user_currency, user_company,
                        date_from)
            if not self.env.company.currency_id.is_zero(line_amount):
                undue_amounts[partner_id] += line_amount
                lines.setdefault(partner_id, [])
                lines[partner_id].append({
                    'line': line,
                    'amount': line_amount,
                    'period': 6,
                })

        for partner in partners:
            if partner['partner_id'] is None:
                partner['partner_id'] = False
            at_least_one_amount = False
            values = {}
            undue_amt = 0.0
            if partner[
                    'partner_id'] in undue_amounts:  # Making sure this partner actually was found by the query
                undue_amt = undue_amounts[partner['partner_id']]

            total[6] = total[6] + undue_amt
            values['direction'] = undue_amt
            if not float_is_zero(
                    values['direction'],
                    precision_rounding=self.env.company.currency_id.rounding):
                at_least_one_amount = True

            for i in range(5):
                during = False
                if partner['partner_id'] in history[i]:
                    during = [history[i][partner['partner_id']]]
                # Adding counter
                total[(i)] = total[(i)] + (during and during[0] or 0)
                values[str(i)] = during and during[0] or 0.0
                if not float_is_zero(values[str(i)],
                                     precision_rounding=self.env.company.
                                     currency_id.rounding):
                    at_least_one_amount = True
            values['total'] = sum([values['direction']] +
                                  [values[str(i)] for i in range(5)])
            # Add for total
            total[(i + 1)] += values['total']
            values['partner_id'] = partner['partner_id']
            if partner['partner_id']:
                values['name'] = len(partner['name']) >= 45 and partner[
                    'name'][0:40] + '...' or partner['name']
                values['trust'] = partner['trust']
            else:
                values['name'] = _('Unknown Partner')
                values['trust'] = False

            if at_least_one_amount or (
                    self._context.get('include_nullified_amount')
                    and lines[partner['partner_id']]):
                res.append(values)
        return res, total, lines
Exemplo n.º 17
0
 def try_zero(amount, expected):
     self.assertEqual(float_is_zero(amount,
                                    precision_digits=3), expected,
                      "Rounding error: %s should be zero!" % amount)