You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
2.3 KiB

  1. # © 2016 Pedro M. Baeza <pedro.baeza@tecnativa.com>
  2. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  3. from odoo import _, api, fields, models, exceptions
  4. from odoo.tools.safe_eval import safe_eval
  5. class AccountAnalyticAccount(models.Model):
  6. _inherit = "account.analytic.account"
  7. @api.model
  8. def _prepare_invoice_line(self, line, invoice_id):
  9. vals = super(AccountAnalyticAccount, self)._prepare_invoice_line(
  10. line, invoice_id)
  11. if line.qty_type == 'variable':
  12. eval_context = {
  13. 'env': self.env,
  14. 'context': self.env.context,
  15. 'user': self.env.user,
  16. 'line': line,
  17. 'contract': line.analytic_account_id,
  18. 'invoice': self.env['account.invoice'].browse(invoice_id),
  19. }
  20. safe_eval(line.qty_formula_id.code.strip(), eval_context,
  21. mode="exec", nocopy=True) # nocopy for returning result
  22. vals['quantity'] = eval_context.get('result', 0)
  23. return vals
  24. class AccountAnalyticInvoiceLine(models.Model):
  25. _inherit = 'account.analytic.invoice.line'
  26. qty_type = fields.Selection(
  27. selection=[
  28. ('fixed', 'Fixed quantity'),
  29. ('variable', 'Variable quantity'),
  30. ], required=True, default='fixed', string="Qty. type")
  31. qty_formula_id = fields.Many2one(
  32. comodel_name="contract.line.qty.formula", string="Qty. formula")
  33. class ContractLineFormula(models.Model):
  34. _name = 'contract.line.qty.formula'
  35. name = fields.Char(required=True)
  36. code = fields.Text(required=True, default="result = 0")
  37. @api.constrains('code')
  38. def _check_code(self):
  39. eval_context = {
  40. 'env': self.env,
  41. 'context': self.env.context,
  42. 'user': self.env.user,
  43. 'line': self.env['account.analytic.invoice.line'],
  44. 'contract': self.env['account.analytic.account'],
  45. 'invoice': self.env['account.invoice'],
  46. }
  47. try:
  48. safe_eval(
  49. self.code.strip(), eval_context, mode="exec", nocopy=True)
  50. except Exception as e:
  51. raise exceptions.ValidationError(
  52. _('Error evaluating code.\nDetails: %s') % e)
  53. if 'result' not in eval_context:
  54. raise exceptions.ValidationError(_('No valid result returned.'))