avanzosc team mailing list archive
-
avanzosc team
-
Mailing list archive
-
Message #00727
Re: [Merge] lp:~oihanecruce/avanzosc/dos_contracts into lp:~avanzosc-security-team/avanzosc/72horas
Y unos ultimos comentarios
Diff comments:
> === modified file 'dos_contracts/__init__.py'
> --- dos_contracts/__init__.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/__init__.py 2014-07-03 14:26:17 +0000
> @@ -19,12 +19,6 @@
> #
> ##############################################################################
>
> -import contract
> -import sale
> -import stock
> -import invoice
> -import partner
> -import report
> -import wizard
> -
> -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> +from . import models
> +from . import report
> +from . import wizard
>
> === modified file 'dos_contracts/__openerp__.py'
> --- dos_contracts/__openerp__.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/__openerp__.py 2014-07-03 14:26:17 +0000
> @@ -21,27 +21,35 @@
>
>
> {
> - "name" : "DOS Contracts",
> - "version" : "1.0",
> - "author" : "DOS",
> - "category" : "Enterprise Specific Modules",
> - "website" : "www.dos-sl.es",
> - "description": "This module allows to manage contract and annexes with shipping management.",
> - "depends" : ["base", "sale", "stock", "account",
> - "dos_sale_commissioncalc", "dos_partner_additional_info",
> - "dos_product_additional_info", "dos_services_to_invoice", "dos_sale_group"],
> - "init_xml" : [],
> - "update_xml" : ['contract_view.xml',
> - 'contract_commission_report.xml',
> - 'wizard/contract_commission_wizard.xml',
> - 'wizard/sale_order_line_view.xml',
> - 'sale_view.xml',
> - 'invoice_view.xml',
> - 'partner_view.xml',
> - 'security/ir.model.access.csv'
> - ],
> + "name": "DOS Contracts",
> + "version": "1.0",
> + "author": "DOS",
> + "category": "Enterprise Specific Modules",
> + "website": "www.dos-sl.es",
> + "description": """
> + This module allows to manage contract and annexes with shipping management.
> + """,
> + "depends": [
> + "base",
> + "sale",
> + "stock",
> + "account",
> + "dos_sale_commissioncalc",
> + "dos_partner_additional_info",
> + "dos_product_additional_info",
> + "dos_services_to_invoice",
> + "dos_sale_group",
> + ],
> + "data": [
> + "views/contract_view.xml",
> + "views/contract_commission_report.xml",
> + "wizard/contract_commission_wizard.xml",
> + "wizard/sale_order_line_view.xml",
> + "views/sale_view.xml",
> + "views/invoice_view.xml",
> + "views/partner_view.xml",
> + "security/ir.model.access.csv",
> + ],
> "active": False,
> "installable": True
> }
> -
> -
>
> === added directory 'dos_contracts/models'
> === added file 'dos_contracts/models/__init__.py'
> --- dos_contracts/models/__init__.py 1970-01-01 00:00:00 +0000
> +++ dos_contracts/models/__init__.py 2014-07-03 14:26:17 +0000
> @@ -0,0 +1,26 @@
> +# -*- coding: utf-8 -*-
> +##############################################################################
> +#
> +# OpenERP, Open Source Management Solution
> +# Copyright (C) 2004-2010 DOS (<http://www.dos-sl.es>).
> +#
> +# This program is free software: you can redistribute it and/or modify
> +# it under the terms of the GNU Affero General Public License as
> +# published by the Free Software Foundation, either version 3 of the
> +# License, or (at your option) any later version.
> +#
> +# This program is distributed in the hope that it will be useful,
> +# but WITHOUT ANY WARRANTY; without even the implied warranty of
> +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
> +# GNU Affero General Public License for more details.
> +#
> +# You should have received a copy of the GNU Affero General Public License
> +# along with this program. If not, see <http://www.gnu.org/licenses/>.
> +#
> +##############################################################################
> +
> +from . import contract
> +from . import sale
> +from . import stock
> +from . import invoice
> +from . import partner
>
> === renamed file 'dos_contracts/contract.py' => 'dos_contracts/models/contract.py'
> --- dos_contracts/contract.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/models/contract.py 2014-07-03 14:26:17 +0000
> @@ -19,92 +19,144 @@
> #
> ##############################################################################
>
> -from osv import osv
> -from osv import fields
> +from osv import orm, fields
> from tools.translate import _
> import time
> from datetime import datetime
> from dateutil.relativedelta import relativedelta
>
> -class contract_type(osv.osv):
>
> +class ContractType(orm.Model):
> _name = 'contract.type'
> _description = "Contract Type"
>
> - _columns = {
> + _columns = {
> 'ref': fields.char('Reference', size=64, required=True),
> 'name': fields.char('Name', size=64, required=True, translate=True),
> - 'sale_type' : fields.selection([('venta', 'Venta'), ('alquiler', 'Alquiler')], 'Sale Type'),
> - 'fixed_price': fields.float('Fixed Price', digits=(2,2)),
> - 'differential_price': fields.float('Differential Price', digits=(2,2)),
> - 'extra_cabin_price': fields.float('Extra Cabin Price', digits=(2,2)),
> - 'fixed_link_price': fields.float('Fixed Link Price', digits=(2,2)),
> - 'differential_link_price': fields.float('Differential Link Price', digits=(2,2)),
> - 'fixed_commission': fields.float('Fixed Commission', digits=(2,2)),
> + 'sale_type': fields.selection([('venta', 'Venta'),
> + ('alquiler', 'Alquiler')],
> + 'Sale Type'),
> + 'fixed_price': fields.float('Fixed Price', digits=(2, 2)),
> + 'differential_price': fields.float('Differential Price',
> + digits=(2, 2)),
> + 'extra_cabin_price': fields.float('Extra Cabin Price', digits=(2, 2)),
> + 'fixed_link_price': fields.float('Fixed Link Price', digits=(2, 2)),
> + 'differential_link_price': fields.float('Differential Link Price',
> + digits=(2, 2)),
> + 'fixed_commission': fields.float('Fixed Commission', digits=(2, 2)),
> }
> -
> +
> _sql_constraints = [
> ('ref_uniq', 'unique(ref)', 'Reference must be unique !'),
> ]
> -
> -contract_type()
> -
> -class contract_contract(osv.osv):
> -
> +
> +
> +class ContractContract(orm.Model):
> _name = 'contract.contract'
> _description = "Contract"
>
> - _columns = {
> + _columns = {
> 'ref': fields.char('Reference', size=64, required=True),
> - 'transmitter_partner_id': fields.many2one('res.partner', 'Transmitter', select=True, required=True),
> - 'transmitter_address_id': fields.many2one('res.partner.address', 'Transmitter Address', required=True, help="Transmitter address for current contract."),
> - 'customer_id': fields.many2one('res.partner', 'Customer', select=True, required=True),
> - 'customer_address_id': fields.many2one('res.partner.address', 'Customer Address', help="Customer address for current contract.", required=True),
> - 'customer_bank_id': fields.many2one('res.partner.bank', 'Customer Bank Account', help="Customer Bank Account for current contract."),
> + 'transmitter_partner_id': fields.many2one('res.partner',
> + 'Transmitter', select=True,
> + required=True),
> + # 'transmitter_address_id':
> + # fields.many2one('res.partner.address',
> + # 'Transmitter Address',
> + # required=True,
> + # help="Transmitter address for current contract."),
> + 'customer_id': fields.many2one('res.partner', 'Customer', select=True,
> + required=True),
> + # 'customer_address_id': fields.many2one('res.partner.address',
> + # 'Customer Address',
> + # help="Customer address for current contract.",
> + # required=True),
> + 'customer_bank_id':
> + fields.many2one('res.partner.bank',
> + 'Customer Bank Account',
> + help="Customer Bank Account for current contract."),
> 'elevator_id': fields.many2one('res.partner', 'Elevator', select=True),
> - 'elevator_address_id': fields.many2one('res.partner.address', 'Elevator Address', help="Elevator address for current contract."),
> - 'middleman_id': fields.many2one('res.partner', 'Middleman', select=True),
> - 'user_id': fields.many2one('res.users', 'Salesman', help='The internal user that is in charge of communicating with this partner if any.'),
> - #'agent_id': fields.many2one('sale.agent','Sales Agent', select=True),
> - 'contract_type_id': fields.many2one('contract.type', 'Contract Type', select=True),
> - 'sale_type' : fields.selection([('venta', 'Venta'), ('alquiler', 'Alquiler')], 'Sale Type'),
> - 'contract_date' : fields.date('Contract Date', required=True),
> - 'closing_date' : fields.date('Closing Date'),
> - 'fixed_price': fields.float('Fixed Price', digits=(2,2)),
> - 'differential_price': fields.float('Differential Price', digits=(2,2)),
> - 'extra_cabin_price': fields.float('Extra Cabin Price', digits=(2,2)),
> - 'fixed_commission': fields.float('Fixed Commission', digits=(2,2)),
> - 'differential_commission': fields.float('Differential Commission', digits=(2,2)),
> - 'fixed_link_price': fields.float('Fixed Link Price', digits=(2,2)),
> - 'differential_link_price': fields.float('Differential Link Price', digits=(2,2)),
> - 'payment_type': fields.many2one('payment.type', 'Payment Type', select=True),
> + # 'elevator_address_id': fields.many2one('res.partner.address',
> + # 'Elevator Address',
> + # help="Elevator address for "
> + # "current contract."),
> + 'middleman_id': fields.many2one('res.partner', 'Middleman',
> + select=True),
> + 'user_id': fields.many2one('res.users', 'Salesman',
> + help='The internal user that is in charge '
> + 'of communicating with this partner if '
> + 'any'),
> + # 'agent_id': fields.many2one('sale.agent','Sales Agent', select=True),
> + 'contract_type_id': fields.many2one('contract.type', 'Contract Type',
> + select=True),
> + 'sale_type': fields.selection([('venta', 'Venta'),
> + ('alquiler', 'Alquiler')], 'Sale Type'),
> + 'contract_date': fields.date('Contract Date', required=True),
> + 'closing_date': fields.date('Closing Date'),
> + 'fixed_price': fields.float('Fixed Price', digits=(2, 2)),
> + 'differential_price': fields.float('Differential Price',
> + digits=(2, 2)),
> + 'extra_cabin_price': fields.float('Extra Cabin Price', digits=(2, 2)),
> + 'fixed_commission': fields.float('Fixed Commission', digits=(2, 2)),
> + 'differential_commission': fields.float('Differential Commission',
> + digits=(2, 2)),
> + 'fixed_link_price': fields.float('Fixed Link Price', digits=(2, 2)),
> + 'differential_link_price': fields.float('Differential Link Price',
> + digits=(2, 2)),
> + 'payment_type': fields.many2one('payment.type', 'Payment Type',
> + select=True),
> 'pre_paid': fields.boolean('Pre Paid'),
> - 'billing_cycle' : fields.integer('Billing Cycle'),
> - 'billing_cycle_type' : fields.selection([('mes', 'Mes'), ('anyo', 'Año')], 'Billing Cycle Type'),
> - 'sale_group_sim_id': fields.many2one('sale.group', 'SIM Sale Group', help="Group sales by default for SIM type products."),
> - 'sale_group_link_id': fields.many2one('sale.group', 'Link Sale Group', help="Group sales by default for Link type products."),
> - 'sale_group_pack_id': fields.many2one('sale.group', 'Pack Sale Group', help="Group sales by default for Pack type products."),
> + 'billing_cycle': fields.integer('Billing Cycle'),
> + 'billing_cycle_type': fields.selection([('mes', 'Mes'),
> + ('anyo', 'Año')],
> + 'Billing Cycle Type'),
> + 'sale_group_sim_id': fields.many2one('sale.group', 'SIM Sale Group',
> + help="Group sales by default for "
> + "SIM type products."),
> + 'sale_group_link_id': fields.many2one('sale.group', 'Link Sale Group',
> + help="Group sales by default for"
> + " Link type products."),
> + 'sale_group_pack_id': fields.many2one('sale.group', 'Pack Sale Group',
> + help="Group sales by default for"
> + " Pack type products."),
> 'comments': fields.text('Comments'),
> 'active_contract': fields.boolean('Active'),
> - 'contract_annexe_ids': fields.one2many('contract.annexe', 'contract_id', 'Annexes'),
> - 'contract_shipping_cost_ids': fields.one2many('contract.shipping.cost', 'contract_id', 'Shipping Costs'),
> - 'info_invoice_ids': fields.one2many('contract.info.invoice', 'contract_id', 'Invoice information'),
> - 'contract_price_rules_ids': fields.one2many('contract.price.rules', 'contract_id', 'Prices Rules'),
> - 'contract_price_ids': fields.one2many('contract.price', 'contract_id', 'Prices'),
> - 'contract_scaled_price_ids': fields.one2many('contract.scaled.price', 'contract_id', 'Scaled Prices'),
> - 'historical_ids': fields.one2many('contract.historical', 'contract_id', 'Historical'),
> - 'orders_ids': fields.one2many('sale.order', 'contract_id', 'Sale Orders'),
> - 'picking_ids': fields.one2many('stock.picking', 'contract_id', 'Pickings'),
> - 'invoice_ids': fields.one2many('account.invoice', 'contract_id', 'Invoices'),
> - #'link_type' : fields.char('Link Type', size=64),
> - #'operator' : fields.char('Operator', size=64),
> + 'contract_annexe_ids': fields.one2many('contract.annexe',
> + 'contract_id', 'Annexes'),
> + 'contract_shipping_cost_ids': fields.one2many('contract.shipping.cost',
> + 'contract_id',
> + 'Shipping Costs'),
> + 'info_invoice_ids': fields.one2many('contract.info.invoice',
> + 'contract_id',
> + 'Invoice information'),
> + 'contract_price_rules_ids': fields.one2many('contract.price.rules',
> + 'contract_id',
> + 'Prices Rules'),
> + 'contract_price_ids': fields.one2many('contract.price', 'contract_id',
> + 'Prices'),
> + 'contract_scaled_price_ids': fields.one2many('contract.scaled.price',
> + 'contract_id',
> + 'Scaled Prices'),
> + 'historical_ids': fields.one2many('contract.historical', 'contract_id',
> + 'Historical'),
> + 'orders_ids': fields.one2many('sale.order', 'contract_id',
> + 'Sale Orders'),
> + 'picking_ids': fields.one2many('stock.picking', 'contract_id',
> + 'Pickings'),
> + 'invoice_ids': fields.one2many('account.invoice', 'contract_id',
> + 'Invoices'),
> + # 'link_type' : fields.char('Link Type', size=64),
> + # 'operator' : fields.char('Operator', size=64),
> }
> -
> +
> _defaults = {
> - 'ref': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'contract.contract'),
> + 'ref': lambda obj, cr, uid,
> + context: obj.pool['ir.sequence'].get(cr, uid, 'contract.contract'),
> 'contract_date': lambda *a: time.strftime('%Y-%m-%d'),
> - 'transmitter_partner_id': lambda self, cr, uid, context: self.get_transmitter(cr, uid),
> - 'transmitter_address_id': lambda self, cr, uid, context: self.get_transmitter_address(cr, uid),
> + 'transmitter_partner_id': lambda self, cr, uid,
> + context: self.get_transmitter(cr, uid),
> + #'transmitter_address_id': lambda self, cr, uid,
> + # context: self.get_transmitter_address(cr, uid),
> 'active_contract': True,
> 'fixed_price': 0,
> 'differential_price': 0,
> @@ -113,337 +165,385 @@
> 'differential_commission': 0,
> 'fixed_link_price': 0,
> 'differential_link_price': 0,
> - 'contract_shipping_cost_ids': lambda *a: [{'min_units': 1, 'max_units': 5, 'price': 10}],
> + 'contract_shipping_cost_ids': lambda *a: [{'min_units': 1,
> + 'max_units': 5,
> + 'price': 10}],
> }
> -
> +
> _sql_constraints = [
> - ('ref_uniq', 'unique(ref)', 'Reference must be unique !'),
> + ('ref_uniq', 'unique(ref)', _('Reference must be unique !')),
> ]
> -
> +
> _order = 'contract_date desc'
> -
> -
> - def name_search(self, cr, user, name='', args=None, operator='ilike', context=None, limit=100):
> +
> + def name_search(self, cr, user, name='', args=None, operator='ilike',
> + context=None, limit=100):
> if not args:
> - args=[]
> + args = []
> if name:
> - ids = self.search(cr, user, [('ref',operator,name)] + args, limit=limit, context=context)
> + ids = self.search(cr, user, [('ref', operator, name)] + args,
> + limit=limit, context=context)
> else:
> ids = self.search(cr, user, args, limit=limit, context=context)
> -
> +
> return self.name_get(cr, user, ids, context=context)
> -
> -
> - def name_get(self, cr, uid, ids, context={}):
> +
> + def name_get(self, cr, uid, ids, context=None):
> result = []
> - for c in self.browse(cr,uid,ids,context):
> - name = '[' + c.ref + '] ' + c.customer_id.name
> - name += ' (' + (c.contract_type_id and c.contract_type_id.name or '') + ' - ' + str(c.fixed_price) + ')'
> - result.append((c.id,name))
> -
> + for c in self.browse(cr, uid, ids, context=context):
> + name = '[%s] %s' % (c.ref, c.customer_id.name)
> + name += ' (%s - %s)' % ((c.contract_type_id and
> + c.contract_type_id.name or ''),
> + str(c.fixed_price))
> + result.append((c.id, name))
> +
> return result
> -
> -
> - def get_transmitter(self, cr, uid):
> - user = self.pool.get('res.users').browse(cr, uid, uid)
> +
> + def get_transmitter(self, cr, uid, context=None):
> + user = self.pool['res.users'].browse(cr, uid, uid, context=context)
> company = user.company_id
> -
> +
> return company.partner_id and company.partner_id.id or False
> -
> - def get_transmitter_address(self, cr, uid):
> - user = self.pool.get('res.users').browse(cr, uid, uid)
> - company = user.company_id
> -
> - partner = company.partner_id and company.partner_id.id or False
> -
> - if partner:
> - addr = self.pool.get('res.partner').address_get(cr, uid, [partner], ['default', 'delivery', 'invoice', 'contact'])
> - return addr['invoice'] or addr['default']
> -
> - return False
> -
> - def get_sale_type(self, cr, uid, contract_type_id=False, customer_id=False, elevator_id=False):
> +
> +# def get_transmitter_address(self, cr, uid):
> +# user = self.pool.get('res.users').browse(cr, uid, uid)
> +# company = user.company_id
> +#
> +# partner = company.partner_id and company.partner_id.id or False
> +#
> +# if partner:
> +# addr = self.pool.get('res.partner').address_get(cr, uid,
> +# [partner],
> +# ['default',
> +# 'delivery',
> +# 'invoice',
> +# 'contact'])
> +# return addr['invoice'] or addr['default']
> +#
> +# return False
> +
> + def get_sale_type(self, cr, uid, contract_type_id=False, customer_id=False,
> + elevator_id=False, context=None):
> sale_type = False
> -
> + partner_obj = self.pool['res.partner']
> +
> if contract_type_id:
> - contract_type = self.pool.get('contract.type').browse(cr, uid, contract_type_id)
> + contract_type = self.pool[
> + 'contract.type'].browse(cr, uid, contract_type_id,
> + context=context)
> sale_type = contract_type.sale_type
> if customer_id and not sale_type:
> - customer = self.pool.get('res.partner').browse(cr, uid, customer_id)
> + customer = partner_obj.browse(cr, uid, customer_id,
> + context=context)
> sale_type = customer.sale_type
> if elevator_id and not sale_type:
> - elevator = self.pool.get('res.partner').browse(cr, uid, elevator_id)
> + elevator = partner_obj.browse(cr, uid, elevator_id,
> + context=context)
> sale_type = elevator.sale_type
> -
> +
> return sale_type
> -
> -
> - def get_fixed_price(self, cr, uid, contract_id, product_sim_id = None, product_link_id = None, add_annexes = 0):
> -
> - contract_price_rules_obj = self.pool.get('contract.price.rules')
> -
> - contract = self.browse(cr, uid, contract_id)
> -
> +
> + def get_fixed_price(self, cr, uid, contract_id, product_sim_id=None,
> + product_link_id=None, add_annexes=0, context=None):
> + rules_obj = self.pool['contract.price.rules']
> fixed_price = 0.0
> -
> +
> + contract = self.browse(cr, uid, contract_id, context=context)
> if contract:
> -
> fixed_price = contract.fixed_price
> -
> +
> # Reglas de Precio por producto
> if product_sim_id:
> -
> +
> # Buscamos regla de precio para la SIM
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id), ('product_id', '=', product_sim_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_id', '=', product_sim_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> fixed_price = rule.fixed_price or 0.0
> break
> -
> - # Si se nos pasa la SIM y Enlace buscamos posible regla de precio para pack
> +
> + # Si se nos pasa la SIM y Enlace buscamos posible regla de
> + # precio para pack
> if product_link_id:
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id),
> - ('product_id', '=', product_sim_id),
> - ('product_2_id', '=', product_link_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_id', '=', product_sim_id),
> + ('product_2_id', '=', product_link_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> fixed_price = rule.fixed_price or 0.0
> break
> -
> +
> # Precios escalados
> if contract.contract_scaled_price_ids:
> num_annexes = len(contract.contract_annexe_ids) + add_annexes
> -
> +
> for scaled_price in contract.contract_scaled_price_ids:
> if num_annexes >= scaled_price.items:
> fixed_price = scaled_price.fixed_price
> else:
> break
> -
> +
> # Precios por mensualidades
> if contract.contract_price_rules_ids and product_sim_id:
> current_date = time.strftime('%Y-%m-%d')
> -
> +
> for contract_price in contract.contract_price_ids:
> num_months = contract_price.months
> - date_aux = datetime.strptime(current_date, '%Y-%m-%d') + relativedelta(months=num_months)
> + date_aux = (datetime.strptime(current_date, '%Y-%m-%d') +
> + relativedelta(months=num_months))
> expiration_date = date_aux.strftime('%Y-%m-%d')
> -
> +
> if current_date >= expiration_date:
> fixed_price = contract_price.fixed_price
> else:
> break
> -
> +
> return fixed_price
> -
> - def get_extra_cabin_price(self, cr, uid, contract_id, product_sim_id = None, product_link_id = None):
> -
> - contract_price_rules_obj = self.pool.get('contract.price.rules')
> -
> - contract = self.browse(cr, uid, contract_id)
> -
> +
> + def get_extra_cabin_price(self, cr, uid, contract_id, product_sim_id=None,
> + product_link_id=None, context=None):
> + rules_obj = self.pool['contract.price.rules']
> extra_cabin_price = 0.0
> -
> +
> + contract = self.browse(cr, uid, contract_id, context=context)
> if contract:
> -
> extra_cabin_price = contract.extra_cabin_price
> -
> +
> # Reglas de Precio por producto
> if contract.contract_price_rules_ids and product_sim_id:
> - # Si se nos pasa la SIM y Enlace buscamos posible regla de precio para pack
> + # Si se nos pasa la SIM y Enlace buscamos posible regla de
> + # precio para pack
> if product_link_id:
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id),
> - ('product_id', '=', product_sim_id),
> - ('product_2_id', '=', product_link_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_id', '=', product_sim_id),
> + ('product_2_id', '=', product_link_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> extra_cabin_price = rule.extra_cabin_price or 0.0
>
> return extra_cabin_price
> -
> +
> # Buscamos regla de precio para la SIM
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id), ('product_id', '=', product_sim_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_id', '=', product_sim_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> extra_cabin_price = rule.extra_cabin_price or 0.0
> break
> -
> +
> return extra_cabin_price
> -
> - def get_differential_price(self, cr, uid, contract_id, product_sim_id = None, product_link_id = None):
> -
> - contract_price_rules_obj = self.pool.get('contract.price.rules')
> -
> - contract = self.browse(cr, uid, contract_id)
> -
> +
> + def get_differential_price(self, cr, uid, contract_id, product_sim_id=None,
> + product_link_id=None, context=None):
> + rules_obj = self.pool['contract.price.rules']
> differential_price = 0.0
> -
> +
> + contract = self.browse(cr, uid, contract_id, context=context)
> if contract:
> -
> differential_price = contract.differential_price
> -
> +
> # Reglas de Precio por producto
> if contract.contract_price_rules_ids and product_sim_id:
> - # Si se nos pasa la SIM y Enlace buscamos posible regla de precio para pack
> + # Si se nos pasa la SIM y Enlace buscamos posible regla de
> + # precio para pack
> if product_link_id:
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id),
> - ('product_id', '=', product_sim_id),
> - ('product_2_id', '=', product_link_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_id', '=', product_sim_id),
> + ('product_2_id', '=', product_link_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> differential_price = rule.differential_price or 0.0
> -
> +
> return differential_price
> -
> +
> # Buscamos regla de precio para la SIM
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id), ('product_id', '=', product_sim_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_id', '=', product_sim_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> differential_price = rule.differential_price or 0.0
> break
> -
> +
> return differential_price
>
> - def get_fixed_link_price(self, cr, uid, contract_id, product_sim_id = None, product_link_id = None):
> -
> - contract_price_rules_obj = self.pool.get('contract.price.rules')
> -
> - contract = self.browse(cr, uid, contract_id)
> -
> + def get_fixed_link_price(self, cr, uid, contract_id, product_sim_id=None,
> + product_link_id=None, context=None):
> + rules_obj = self.pool['contract.price.rules']
> fixed_link_price = 0.0
> -
> +
> + contract = self.browse(cr, uid, contract_id, context=context)
> if contract:
> -
> fixed_link_price = contract.fixed_link_price
> -
> +
> # Reglas de Precio por producto
> if contract.contract_price_rules_ids and product_link_id:
> - # Si se nos pasa la SIM y Enlace buscamos posible regla de precio para pack
> + # Si se nos pasa la SIM y Enlace buscamos posible regla de
> + # precio para pack
> if product_sim_id:
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id),
> - ('product_id', '=', product_sim_id),
> - ('product_2_id', '=', product_link_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_id', '=', product_sim_id),
> + ('product_2_id', '=', product_link_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> fixed_link_price = rule.fixed_link_price or 0.0
> -
> +
> return fixed_link_price
>
> # Buscamos regla de precio para el enlace
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id), ('product_2_id', '=', product_link_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_2_id', '=', product_link_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> fixed_link_price = rule.fixed_link_price or 0.0
> break
> -
> +
> return fixed_link_price
> -
> - def get_differential_link_price(self, cr, uid, contract_id, product_sim_id = None, product_link_id = None):
> -
> - contract_price_rules_obj = self.pool.get('contract.price.rules')
> -
> - contract = self.browse(cr, uid, contract_id)
> -
> - differential_link_price = 0.0
> -
> +
> + def get_differential_link_price(self, cr, uid, contract_id,
> + product_sim_id=None, product_link_id=None,
> + context=None):
> + rules_obj = self.pool['contract.price.rules']
> + diff_link_price = 0.0
> +
> + contract = self.browse(cr, uid, contract_id, context=context)
> if contract:
> -
> - differential_link_price = contract.differential_link_price
> -
> + diff_link_price = contract.differential_link_price
> +
> # Reglas de Precio por producto
> if contract.contract_price_rules_ids and product_link_id:
> - # Si se nos pasa la SIM y Enlace buscamos posible regla de precio para pack
> + # Si se nos pasa la SIM y Enlace buscamos posible regla de
> + # precio para pack
> if product_sim_id:
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id),
> - ('product_id', '=', product_sim_id),
> - ('product_2_id', '=', product_link_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> - differential_link_price = rule.differential_link_price or 0.0
> -
> - return differential_link_price
> -
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_id', '=', product_sim_id),
> + ('product_2_id', '=', product_link_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> + diff_link_price = rule.differential_link_price or 0.0
> +
> + return diff_link_price
> +
> # Buscamos regla de precio para el enlace
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id), ('product_2_id', '=', product_link_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> - differential_link_price = rule.differential_link_price or 0.0
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_2_id', '=', product_link_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> + diff_link_price = rule.differential_link_price or 0.0
> break
> -
> - return differential_link_price
> -
> - def get_fixed_commission(self, cr, uid, contract_id, product_sim_id = None, product_link_id = None):
> -
> - contract_price_rules_obj = self.pool.get('contract.price.rules')
> -
> - contract = self.browse(cr, uid, contract_id)
> -
> + return diff_link_price
> +
> + def get_fixed_commission(self, cr, uid, contract_id, product_sim_id=None,
> + product_link_id=None, context=None):
> + rules_obj = self.pool['contract.price.rules']
> fixed_commission = 0.0
> -
> +
> + contract = self.browse(cr, uid, contract_id, context=context)
> if contract:
> -
> fixed_commission = contract.fixed_commission
> -
> +
> # Reglas de Precio por producto
> if contract.contract_price_rules_ids and product_sim_id:
> if product_link_id:
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id),
> - ('product_id', '=', product_sim_id),
> - ('product_2_id', '=', product_link_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_id', '=', product_sim_id),
> + ('product_2_id', '=', product_link_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> fixed_commission = rule.fixed_commission or 0.0
> break
> else:
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id),
> - ('product_id', '=', product_sim_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_id', '=', product_sim_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> fixed_commission = rule.fixed_commission or 0.0
> break
> -
> +
> return fixed_commission
> -
> - def get_differential_commission(self, cr, uid, contract_id, product_sim_id = None, product_link_id = None):
> -
> - contract_price_rules_obj = self.pool.get('contract.price.rules')
> -
> - contract = self.browse(cr, uid, contract_id)
> -
> - differential_commission = 0.0
> -
> +
> + def get_differential_commission(self, cr, uid, contract_id,
> + product_sim_id=None, product_link_id=None,
> + context=None):
> + rules_obj = self.pool['contract.price.rules']
> + diff_commission = 0.0
> +
> + contract = self.browse(cr, uid, contract_id, context=context)
> if contract:
> -
> - differential_commission = contract.differential_commission
> -
> + diff_commission = contract.differential_commission
> +
> # Reglas de Precio por producto
> if contract.contract_price_rules_ids and product_sim_id:
> if product_link_id:
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id),
> - ('product_id', '=', product_sim_id),
> - ('product_2_id', '=', product_link_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> - differential_commission = rule.differential_commission or 0.0
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_id', '=', product_sim_id),
> + ('product_2_id', '=', product_link_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> + diff_commission = rule.differential_commission or 0.0
> break
> else:
> - rule_ids = contract_price_rules_obj.search(cr, uid, [('contract_id', '=', contract.id),
> - ('product_id', '=', product_sim_id)])
> -
> - for rule in contract_price_rules_obj.browse(cr, uid, rule_ids):
> - differential_commission = rule.differential_commission or 0.0
> + rule_ids = rules_obj.search(
> + cr, uid, [('contract_id', '=', contract.id),
> + ('product_id', '=', product_sim_id)],
> + context=context)
> +
> + for rule in rules_obj.browse(cr, uid, rule_ids,
> + context=context):
> + diff_commission = rule.differential_commission or 0.0
> break
> -
> - return differential_commission
> -
> - def onchange_contract_type(self, cr, uid, ids, contract_type_id, customer_id=False, elevator_id=False):
> +
> + return diff_commission
> +
> + def onchange_contract_type(self, cr, uid, ids, contract_type_id,
> + customer_id=False, elevator_id=False):
> if not contract_type_id:
> return {'value': {'sale_type': False}}
>
> - contract_type = self.pool.get('contract.type').browse(cr, uid, contract_type_id)
> + contract_type = self.pool['contract.type'].browse(cr, uid,
> + contract_type_id)
> + sale_type = self.get_sale_type(cr, uid, contract_type_id, customer_id,
> + elevator_id)
>
> - sale_type = self.get_sale_type(cr, uid, contract_type_id, customer_id, elevator_id)
> -
> val = {
> 'sale_type': sale_type,
> 'fixed_price': contract_type.fixed_price,
> @@ -455,60 +555,74 @@
> }
>
> return {'value': val}
> -
> - def onchange_fixed_price(self, cr, uid, ids, contract_type_id, fixed_price):
> +
> + def onchange_fixed_price(self, cr, uid, ids, contract_type_id,
> + fixed_price, context=None):
> if not contract_type_id:
> return {'value': {}}
>
> - contract_type = self.pool.get('contract.type').browse(cr, uid, contract_type_id)
> + contract_type = self.pool['contract.type'].browse(cr, uid,
> + contract_type_id,
> + context=context)
> + fixed_commission = ((fixed_price or 0) -
> + (contract_type.fixed_price or 0))
>
> - fixed_commission = (fixed_price or 0) - (contract_type.fixed_price or 0)
> -
> if fixed_commission < 0:
> fixed_commission = 0
> -
> +
> return {'value': {'fixed_commission': fixed_commission}}
> -
> -
> +
> def onchange_transmitter_id(self, cr, uid, ids, part):
> if not part:
> return {'value': {'transmitter_address_id': False}}
>
> - addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['default', 'delivery', 'invoice', 'contact'])
> + addr = self.pool['res.partner'].address_get(cr, uid, [part],
> + ['default', 'delivery',
> + 'invoice', 'contact'])
>
> val = {
> 'transmitter_address_id': addr['invoice'] or addr['default'],
> }
>
> return {'value': val}
> -
> -
> - def onchange_customer_id(self, cr, uid, ids, part, elev=False, contract_type=False):
> +
> + def onchange_customer_id(self, cr, uid, ids, part, elev=False,
> + contract_type=False):
> if not part:
> - return {'value': {'customer_address_id': False, 'customer_bank_id': False, 'payment_type': False, 'billing_cycle': False, 'billing_cycle_type': False, 'pre_paid': False}}
> + return {'value': {'customer_address_id': False,
> + 'customer_bank_id': False,
> + 'payment_type': False,
> + 'billing_cycle': False,
> + 'billing_cycle_type': False,
> + 'pre_paid': False}}
>
> - addr = self.pool.get('res.partner').address_get(cr, uid, [part], ['default', 'delivery', 'invoice', 'contact'])
> - part = self.pool.get('res.partner').browse(cr, uid, part)
> + partner_obj = self.pool['res.partner']
> + addr = partner_obj.address_get(cr, uid, [part],
> + ['default', 'delivery', 'invoice',
> + 'contact'])
> + part = partner_obj.browse(cr, uid, part)
> agent_id = part.agent_id and part.agent_id.id or False
> - payment_type = part.payment_type_customer and part.payment_type_customer.id or False
> + payment_type = (part.payment_type_customer and
> + part.payment_type_customer.id or False)
> billing_cycle = part.ciclo_cobro or False
> billing_cycle_type = part.tipo_ciclo_cobro or False
> pre_paid = part.pre_pago or False
> sale_type = self.get_sale_type(cr, uid, contract_type, part.id, elev)
> -
> +
> bank = False
> if part.bank_ids and len(part.bank_ids) > 0:
> bank = part.bank_ids[0].id
> -
> +
> for id in ids:
> contract = self.browse(cr, uid, id)
> for info in contract.info_invoice_ids:
> - self.pool.get('contract.info.invoice').unlink(cr, uid, [info.id])
> -
> + self.pool['contract.info.invoice'].unlink(cr, uid, [info.id])
> +
> info_invoice_ids = []
> for info in part.info_invoice_ids:
> - info_invoice_ids.append({'categ_id': info.categ_id.id, 'receiver': info.receiver})
> -
> + info_invoice_ids.append({'categ_id': info.categ_id.id,
> + 'receiver': info.receiver})
> +
> val = {
> 'customer_address_id': addr['invoice'] or addr['default'],
> 'customer_bank_id': bank,
> @@ -522,35 +636,43 @@
> }
>
> return {'value': val}
> -
> - def onchange_elevator_id(self, cr, uid, ids, elev, part=False, contract_type=False):
> +
> + def onchange_elevator_id(self, cr, uid, ids, elev, part=False,
> + contract_type=False, context=None):
> if not elev:
> return {'value': {'elevator_address_id': False}}
>
> - #Obtenemos direccion
> - addr = self.pool.get('res.partner').address_get(cr, uid, [elev], ['default', 'delivery', 'invoice', 'contact'])
> -
> - #Obtenemos tipo de venta
> + partner_obj = self.pool['res.partner']
> +
> + # Obtenemos direccion
> + addr = partner_obj.address_get(cr, uid, [elev],
> + ['default', 'delivery', 'invoice',
> + 'contact'],
> + context=context)
> +
> + # Obtenemos tipo de venta
> sale_type = self.get_sale_type(cr, uid, contract_type, part, elev)
> -
> - #Obtenemos informacion de facturacion
> +
> + # Obtenemos informacion de facturacion
> info_invoice_ids = []
> -
> +
> for id in ids:
> contract = self.browse(cr, uid, id)
> for info in contract.info_invoice_ids:
> info_invoice_ids.append(info.id)
>
> if not info_invoice_ids and part:
> - partner = self.pool.get('res.partner').browse(cr, uid, part)
> + partner = partner_obj.browse(cr, uid, part)
> for info in partner.info_invoice_ids:
> - info_invoice_ids.append({'categ_id': info.categ_id.id, 'receiver': info.receiver})
> -
> + info_invoice_ids.append({'categ_id': info.categ_id.id,
> + 'receiver': info.receiver})
> +
> if not info_invoice_ids and elev:
> - partner = self.pool.get('res.partner').browse(cr, uid, elev)
> + partner = partner_obj.browse(cr, uid, elev)
> for info in partner.info_invoice_ids:
> - info_invoice_ids.append({'categ_id': info.categ_id.id, 'receiver': info.receiver})
> -
> + info_invoice_ids.append({'categ_id': info.categ_id.id,
> + 'receiver': info.receiver})
> +
> val = {
> 'elevator_address_id': addr['invoice'] or addr['default'],
> 'sale_type': sale_type,
> @@ -558,618 +680,746 @@
> }
>
> return {'value': val}
> -
> -
> +
> def create(self, cr, user, vals, context=None):
> - new_id = super(contract_contract, self).create(cr, user, vals, context)
> -
> + new_id = super(ContractContract,
> + self).create(cr, user, vals, context=context)
> +
> #Creamos entrada de creación en histórico
> - self.pool.get('contract.historical').create(cr, user, {
> - 'middleman_id': ('middleman_id' in vals) and vals.get('middleman_id') or False,
> - 'elevator_id': ('elevator_id' in vals) and vals.get('elevator_id') or False,
> - 'fixed_price': ('fixed_price' in vals) and vals.get('fixed_price') or 0,
> - 'differential_price': ('differential_price' in vals) and vals.get('differential_price') or 0,
> - 'extra_cabin_price': ('extra_cabin_price' in vals) and vals.get('extra_cabin_price') or 0,
> - 'fixed_commission': ('fixed_commission' in vals) and vals.get('fixed_commission') or 0,
> - 'differential_commission': ('differential_commission' in vals) and vals.get('differential_commission') or 0,
> - 'fixed_link_price': ('fixed_link_price' in vals) and vals.get('fixed_link_price') or 0,
> - 'differential_link_price': ('differential_link_price' in vals) and vals.get('differential_link_price') or 0,
> - 'contract_id': new_id,
> - 'customer_id': ('customer_id' in vals) and vals.get('customer_id') or 0,
> - 'comments': _('Creación de contrato')
> - }, context)
> -
> + self.pool['contract.historical'].create(cr, user, {
> + 'middleman_id': (('middleman_id' in vals) and
> + vals['middleman_id'] or False),
> + 'elevator_id': (('elevator_id' in vals) and
> + vals['elevator_id'] or False),
> + 'fixed_price': (('fixed_price' in vals) and
> + vals['fixed_price'] or 0),
> + 'differential_price': (('differential_price' in vals) and
> + vals['differential_price'] or 0),
> + 'extra_cabin_price': (('extra_cabin_price' in vals) and
> + vals['extra_cabin_price'] or 0),
> + 'fixed_commission': (('fixed_commission' in vals) and
> + vals.get('fixed_commission') or 0),
> + 'differential_commission': (('differential_commission' in vals) and
> + vals['differential_commission'] or 0),
> + 'fixed_link_price': (('fixed_link_price' in vals) and
> + vals['fixed_link_price'] or 0),
> + 'differential_link_price': (('differential_link_price' in vals) and
> + vals['differential_link_price'] or 0),
> + 'contract_id': new_id,
> + 'customer_id': (('customer_id' in vals) and
> + vals['customer_id'] or 0),
> + 'comments': _('Creación de contrato')
> + }, context)
> +
> return new_id
> -
> -
> +
> def write(self, cr, uid, ids, vals, context=None):
> -
> historical = True
> -
> +
> if context and 'historical' in context:
> historical = context['historical']
> -
> -
> +
> if historical:
> for id in ids:
> contract = self.browse(cr, uid, id, context)
> comments = ""
> -
> - if 'middleman_id' in vals and vals.get('middleman_id', False) != contract.middleman_id.id:
> - middleman_id = vals.get('middleman_id', False)
> +
> + if ('middleman_id' in vals and
> + vals['middleman_id'] != contract.middleman_id.id):
> + middleman_id = vals['middleman_id']
> comments += _('Cambio de comisionista') + '\n'
> else:
> middleman_id = contract.middleman_id.id
> -
> - if 'elevator_id' in vals and vals.get('elevator_id', False) != contract.elevator_id.id:
> - elevator_id = vals.get('elevator_id', False)
> +
> + if ('elevator_id' in vals and
> + vals['elevator_id'] != contract.elevator_id.id):
> + elevator_id = vals['elevator_id']
> comments += _('Cambio de ascensorista') + '\n'
> else:
> elevator_id = contract.elevator_id.id
> -
> - if 'fixed_price' in vals and vals.get('fixed_price', False) != contract.fixed_price:
> - fixed_price = vals.get('fixed_price', False)
> +
> + if ('fixed_price' in vals and
> + vals['fixed_price'] != contract.fixed_price):
> + fixed_price = vals['fixed_price']
> comments += _('Cambio de precio fijo') + '\n'
> else:
> fixed_price = contract.fixed_price
> -
> - if 'differential_price' in vals and vals.get('differential_price', False) != contract.differential_price:
> - differential_price = vals.get('differential_price', False)
> +
> + if ('differential_price' in vals and
> + (vals['differential_price'] !=
> + contract.differential_price)):
> + differential_price = vals['differential_price']
> comments += _('Cambio de precio diferencial') + '\n'
> else:
> differential_price = contract.differential_price
> -
> - if 'extra_cabin_price' in vals and vals.get('extra_cabin_price', False) != contract.extra_cabin_price:
> - extra_cabin_price = vals.get('extra_cabin_price', False)
> +
> + if ('extra_cabin_price' in vals and
> + (vals['extra_cabin_price'] !=
> + contract.extra_cabin_price)):
> + extra_cabin_price = vals['extra_cabin_price']
> comments += _('Cambio de precio de cabina extra') + '\n'
> else:
> extra_cabin_price = contract.extra_cabin_price
> -
> - if 'fixed_link_price' in vals and vals.get('fixed_link_price', False) != contract.fixed_link_price:
> - fixed_link_price = vals.get('fixed_link_price', False)
> +
> + if ('fixed_link_price' in vals and
> + vals['fixed_link_price'] != contract.fixed_link_price):
> + fixed_link_price = vals['fixed_link_price']
> comments += _('Cambio de precio fijo enlace') + '\n'
> else:
> fixed_link_price = contract.fixed_link_price
> -
> - if 'differential_link_price' in vals and vals.get('differential_link_price', False) != contract.differential_link_price:
> - differential_link_price = vals.get('differential_link_price', False)
> +
> + if ('differential_link_price' in vals and
> + (vals['differential_link_price'] !=
> + contract.differential_link_price)):
> + differential_link_price = vals['differential_link_price']
> comments += _('Cambio de precio diferencial enlace') + '\n'
> else:
> differential_link_price = contract.differential_link_price
> -
> - if 'fixed_commission' in vals and vals.get('fixed_commission', False) != contract.fixed_commission:
> - fixed_commission = vals.get('fixed_commission', False)
> +
> + if ('fixed_commission' in vals and
> + vals['fixed_commission'] != contract.fixed_commission):
> + fixed_commission = vals['fixed_commission']
> comments += _('Cambio de comisión fija') + '\n'
> else:
> fixed_commission = contract.fixed_commission
> -
> - if 'differential_commission' in vals and vals.get('differential_commission', False) != contract.differential_commission:
> - differential_commission = vals.get('differential_commission', False)
> +
> + if ('differential_commission' in vals and
> + (vals['differential_commission'] !=
> + contract.differential_commission)):
> + differential_commission = vals['differential_commission']
> comments += _('Cambio de comisión diferencial') + '\n'
> else:
> differential_commission = contract.differential_commission
> -
> - if 'customer_id' in vals and vals.get('customer_id', False) != contract.customer_id.id:
> - customer_id = vals.get('customer_id', False)
> +
> + if ('customer_id' in vals and
> + vals['customer_id'] != contract.customer_id.id):
> + customer_id = vals['customer_id']
> comments += _('Cambio de cliente') + '\n'
> else:
> customer_id = contract.customer_id.id
> -
> +
> if comments != "":
> - #Creamos entrada de cambio en histórico
> - self.pool.get('contract.historical').create(cr, uid, {
> - 'middleman_id': middleman_id,
> - 'elevator_id': elevator_id,
> - 'fixed_price': fixed_price,
> - 'differential_price': differential_price,
> - 'extra_cabin_price': extra_cabin_price,
> - 'fixed_link_price': fixed_link_price,
> - 'differential_link_price': differential_link_price,
> - 'fixed_commission': fixed_commission,
> - 'differential_commission': differential_commission,
> - 'contract_id': id,
> - 'customer_id': customer_id,
> - 'comments': comments
> - }, context)
> -
> - return super(contract_contract, self).write(cr, uid, ids, vals, context=context)
> -
> -
> -contract_contract()
> -
> -
> -class contract_annexe(osv.osv):
> -
> + # Creamos entrada de cambio en histórico
> + self.pool['contract.historical'].create(cr, uid, {
> + 'middleman_id': middleman_id,
> + 'elevator_id': elevator_id,
> + 'fixed_price': fixed_price,
> + 'differential_price': differential_price,
> + 'extra_cabin_price': extra_cabin_price,
> + 'fixed_link_price': fixed_link_price,
> + 'differential_link_price': differential_link_price,
> + 'fixed_commission': fixed_commission,
> + 'differential_commission': differential_commission,
> + 'contract_id': id,
> + 'customer_id': customer_id,
> + 'comments': comments
> + }, context)
> +
> + return super(ContractContract,
> + self).write(cr, uid, ids, vals, context=context)
> +
> +
> +class ContractAnnexe(orm.Model):
> _name = 'contract.annexe'
> _description = "Contract Annexe"
>
> def _fixed_price_default(self, cr, uid, context=None):
> if context is None:
> context = {}
> -
> return 'fixed_price' in context and context['fixed_price'] or 0
>
> def _differential_price_default(self, cr, uid, context=None):
> if context is None:
> context = {}
> -
> - return 'differential_price' in context and context['differential_price'] or 0
> + return ('differential_price' in context and
> + context['differential_price'] or 0)
>
> def _extra_cabin_price_default(self, cr, uid, context=None):
> if context is None:
> context = {}
> - return 'extra_cabin_price' in context and context['extra_cabin_price'] or 0
> + return ('extra_cabin_price' in context and
> + context['extra_cabin_price'] or 0)
>
> def _fixed_commission_default(self, cr, uid, context=None):
> if context is None:
> context = {}
> + return ('fixed_commission' in context and
> + context['fixed_commission'] or 0)
>
> - return 'fixed_commission' in context and context['fixed_commission'] or 0
> -
> def _differential_commission_default(self, cr, uid, context=None):
> if context is None:
> context = {}
> + return ('differential_commission' in context and
> + context['differential_commission'] or 0)
>
> - return 'differential_commission' in context and context['differential_commission'] or 0
> -
> -
> def _annexe_price_default(self, cr, uid, context=None):
> if context is None:
> context = {}
>
> annexe_price_ids = []
> -
> +
> if 'contract_price_ids' in context:
> contract_price_ids = context['contract_price_ids']
> -
> +
> for price_list in contract_price_ids:
> price_list = price_list[2]
> -
> +
> if price_list:
> + fixed_price = ('fixed_price' in price_list and
> + price_list['fixed_price'] or 0)
>
> - fixed_price = 'fixed_price' in price_list and price_list['fixed_price'] or 0
> -
> expiration_date = None
> -
> +
> if 'months' in price_list:
> num_months = price_list['months']
> current_date = datetime.today()
> - date_aux = current_date + relativedelta(months=num_months)
> + date_aux = (current_date +
> + relativedelta(months=num_months))
> expiration_date = date_aux.strftime('%Y-%m-%d')
> -
> - annexe_price_ids.append({'fixed_price': fixed_price, 'expiration_date': expiration_date})
> -
> +
> + annexe_price_ids.append(
> + {'fixed_price': fixed_price,
> + 'expiration_date': expiration_date})
> +
> return annexe_price_ids
> -
> -
> - _columns = {
> +
> + _columns = {
> 'ref': fields.char('Reference', size=64, required=True),
> 'name': fields.char('Name', size=128),
> - 'contract_id': fields.many2one('contract.contract', 'Contract', select=True, required=True),
> + 'contract_id': fields.many2one('contract.contract', 'Contract',
> + select=True, required=True),
> 'num_annexe_ship': fields.integer('Num. Annexe Ship'),
> - 'annexe_date' : fields.date('Annexe Date', required=True),
> - 'closing_date' : fields.date('Closing Date'),
> - 'shipping_date' : fields.date('Shipping Date'),
> - 'start_billing_date' : fields.date('Start Billing Date'),
> - 'expiration_date' : fields.date('Expiration Date'),
> - 'product_id': fields.many2one('product.product', 'SIM Product', select=True),
> - 'production_lot_id': fields.many2one('stock.production.lot', 'ICC', select=True),
> - 'product_2_id': fields.many2one('product.product', 'Link Product', select=True),
> - 'production_lot_2_id': fields.many2one('stock.production.lot', 'IMEI', select=True),
> - 'pack_product_id': fields.many2one('product.product', 'Pack Product', select=True),
> - 'pack_production_lot_id': fields.many2one('stock.production.lot', 'Pack Lot', select=True),
> - #'icc' : fields.char('ICC', size=64),
> - #'imei' : fields.char('IMEI', size=15),
> - #'phone' : fields.char('Phone', size=12),
> - 'fixed_price': fields.float('Fixed Price', digits=(2,2)),
> - 'differential_price': fields.float('Differential Price', digits=(2,2)),
> - 'extra_cabin_price': fields.float('Extra Cabin Price', digits=(2,2)),
> - 'fixed_commission': fields.float('Fixed Commission', digits=(2,2)),
> - 'differential_commission': fields.float('Differential Commission', digits=(2,2)),
> + 'annexe_date': fields.date('Annexe Date', required=True),
> + 'closing_date': fields.date('Closing Date'),
> + 'shipping_date': fields.date('Shipping Date'),
> + 'start_billing_date': fields.date('Start Billing Date'),
> + 'expiration_date': fields.date('Expiration Date'),
> + 'product_id': fields.many2one('product.product', 'SIM Product',
> + select=True),
> + 'production_lot_id': fields.many2one('stock.production.lot', 'ICC',
> + select=True),
> + 'product_2_id': fields.many2one('product.product', 'Link Product',
> + select=True),
> + 'production_lot_2_id': fields.many2one('stock.production.lot', 'IMEI',
> + select=True),
> + 'pack_product_id': fields.many2one('product.product', 'Pack Product',
> + select=True),
> + 'pack_production_lot_id': fields.many2one('stock.production.lot',
> + 'Pack Lot', select=True),
> + #'icc': fields.char('ICC', size=64),
> + #'imei': fields.char('IMEI', size=15),
> + #'phone': fields.char('Phone', size=12),
> + 'fixed_price': fields.float('Fixed Price', digits=(2, 2)),
> + 'differential_price': fields.float('Differential Price',
> + digits=(2, 2)),
> + 'extra_cabin_price': fields.float('Extra Cabin Price', digits=(2, 2)),
> + 'fixed_commission': fields.float('Fixed Commission', digits=(2, 2)),
> + 'differential_commission': fields.float('Differential Commission',
> + digits=(2, 2)),
> 'active_annexe': fields.boolean('Active'),
> 'state': fields.boolean('State'),
> - 'num_cabins' : fields.integer('Num. Cabins'),
> + 'num_cabins': fields.integer('Num. Cabins'),
> 'customer_ref': fields.char('Customer Ref.', size=256),
> - 'user_id': fields.many2one('res.users', 'Salesman', help='The internal user that is in charge of communicating with this partner if any.'),
> + 'user_id': fields.many2one('res.users', 'Salesman',
> + help='The internal user that is in charge '
> + 'of communicating with this partner if '
> + 'any.'),
> #'agent_id': fields.many2one('sale.agent','Sales Agent', select=True),
> - 'sale_order_id': fields.many2one('sale.order', 'Sale Order', select=True),
> - 'stock_move_id': fields.many2one('stock.move', 'Stock Move', select=True),
> - 'invoice_line_id': fields.many2one('account.invoice.line', 'Account Invoice Line', select=True),
> + 'sale_order_id': fields.many2one('sale.order', 'Sale Order',
> + select=True),
> + 'stock_move_id': fields.many2one('stock.move', 'Stock Move',
> + select=True),
> + 'invoice_line_id': fields.many2one('account.invoice.line',
> + 'Account Invoice Line',
> + select=True),
> 'comments': fields.text('Comments'),
> - 'annexe_price_ids': fields.one2many('contract.annexe.price', 'contract_annexe_id', 'Prices'),
> - 'historical_ids': fields.one2many('contract.annexe.historical', 'contract_annexe_id', 'Historical'),
> + 'annexe_price_ids': fields.one2many('contract.annexe.price',
> + 'contract_annexe_id', 'Prices'),
> + 'historical_ids': fields.one2many('contract.annexe.historical',
> + 'contract_annexe_id', 'Historical'),
> }
> -
> +
> _defaults = {
> - 'ref': lambda obj, cr, uid, context: obj.pool.get('ir.sequence').get(cr, uid, 'contract.annexe'),
> + 'ref': lambda obj, cr, uid,
> + context: obj.pool['ir.sequence'].get(cr, uid, 'contract.annexe'),
> 'annexe_date': lambda *a: time.strftime('%Y-%m-%d'),
> 'active_annexe': True,
> 'fixed_price': _fixed_price_default,
> 'differential_price': _differential_price_default,
> - 'extra_cabin_price': _extra_cabin_price_default,
> + 'extra_cabin_price': _extra_cabin_price_default,
> 'fixed_commission': _fixed_commission_default,
> 'differential_commission': _differential_commission_default,
> 'annexe_price_ids': _annexe_price_default,
> }
> -
> +
> _sql_constraints = [
> ('ref_uniq', 'unique(ref)', 'Reference must be unique !'),
> ]
> -
> +
> _order = 'annexe_date asc'
> -
> -
> +
> def next_expiration_date(self, cr, uid, annexe_id):
> -
> annexe = self.browse(cr, uid, annexe_id)
> -
> +
> next_date = None
> -
> +
> if annexe:
> #Calculamos proxima fecha de vencimiento
> date = annexe.expiration_date
> cycle = annexe.contract_id.billing_cycle
> cycle_type = annexe.contract_id.billing_cycle_type
> -
> +
> if date and cycle and cycle_type:
> if cycle_type == 'anyo':
> - date_aux = datetime.strptime(date, '%Y-%m-%d') + relativedelta(years=+cycle)
> + date_aux = (datetime.strptime(date, '%Y-%m-%d') +
> + relativedelta(years=+cycle))
> else:
> - date_aux = datetime.strptime(date, '%Y-%m-%d') + relativedelta(months=+cycle)
> -
> + date_aux = (datetime.strptime(date, '%Y-%m-%d') +
> + relativedelta(months=+cycle))
> next_date = date_aux.strftime('%Y-%m-%d')
> -
> -
> +
> return next_date
> -
> -
> - def get_fixed_price(self, cr, uid, annexe_id):
> -
> - annexe = self.browse(cr, uid, annexe_id)
> -
> +
> + def get_fixed_price(self, cr, uid, annexe_id, context=None):
> + annexe = self.browse(cr, uid, annexe_id, context=context)
> +
> fixed_price = 0.0
> -
> +
> if annexe:
> -
> fixed_price = annexe.fixed_price
> -
> +
> # Precios escalados
> - if annexe.contract_id.contract_scaled_price_ids:
> - num_annexes = len(annexe.contract_id.contract_annexe_ids)
> -
> - for scaled_price in annexe.contract_id.contract_scaled_price_ids:
> + scaled_ids = annexe.contract_id.contract_scaled_price_ids
> +
> + if scaled_ids:
> + num_annexes = len(scaled_ids)
> +
> + for scaled_price in scaled_ids:
> if num_annexes >= scaled_price.items:
> fixed_price = scaled_price.fixed_price
> else:
> break
> -
> +
> # Precios por mensualidades
> if annexe.annexe_price_ids:
> current_date = time.strftime('%Y-%m-%d')
> -
> +
> for annexe_price in annexe.annexe_price_ids:
> if current_date >= annexe_price.expiration_date:
> fixed_price = annexe_price.fixed_price
> else:
> break
> -
> +
> return fixed_price
> -
> -
> +
> def create(self, cr, user, vals, context=None):
> - new_id = super(contract_annexe, self).create(cr, user, vals, context)
> -
> - #Creamos entrada de creación en histórico
> - self.pool.get('contract.annexe.historical').create(cr, user, {
> - 'num_cabins': ('num_cabins' in vals) and vals.get('num_cabins') or False,
> - #'phone': ('phone' in vals) and vals.get('phone') or False,
> - 'production_lot_id': ('production_lot_id' in vals) and vals.get('production_lot_id') or False,
> - 'production_lot_2_id': ('production_lot_2_id' in vals) and vals.get('production_lot_2_id') or False,
> - 'fixed_price': ('fixed_price' in vals) and vals.get('fixed_price') or False,
> - 'differential_price': ('differential_price' in vals) and vals.get('differential_price') or False,
> - 'extra_cabin_price': ('extra_cabin_price' in vals) and vals.get('extra_cabin_price') or False,
> - 'fixed_commission': ('fixed_commission' in vals) and vals.get('fixed_commission') or False,
> - 'differential_commission': ('differential_commission' in vals) and vals.get('differential_commission') or False,
> - 'contract_annexe_id': new_id,
> - 'contract_id': ('contract_id' in vals) and vals.get('contract_id') or 0,
> - 'comments': _('Creación de anexo')
> - }, context)
> -
> + new_id = super(ContractAnnexe, self).create(cr, user, vals,
> + context=context)
> +
> + # Creamos entrada de creación en histórico
> + self.pool['contract.annexe.historical'].create(cr, user, {
> + 'num_cabins': (('num_cabins' in vals) and
> + vals['num_cabins'] or False),
> + 'production_lot_id': (('production_lot_id' in vals) and
> + vals['production_lot_id'] or False),
> + 'production_lot_2_id': (('production_lot_2_id' in vals) and
> + vals['production_lot_2_id'] or False),
> + 'fixed_price': (('fixed_price' in vals) and
> + vals['fixed_price'] or False),
> + 'differential_price': (('differential_price' in vals) and
> + vals['differential_price'] or False),
> + 'extra_cabin_price': (('extra_cabin_price' in vals) and
> + vals['extra_cabin_price'] or False),
> + 'fixed_commission': (('fixed_commission' in vals) and
> + vals['fixed_commission'] or False),
> + 'differential_commission': (('differential_commission' in vals) and
> + vals['differential_commission'] or
> + False),
> + 'contract_annexe_id': new_id,
> + 'contract_id': (('contract_id' in vals) and
> + vals['contract_id'] or 0),
> + 'comments': _('Creación de anexo')
> + }, context)
> +
> return new_id
> -
> +
> def write(self, cr, uid, ids, vals, context=None):
> -
> historical = True
> -
> +
> if context and 'historical' in context:
> historical = context['historical']
> -
> +
> if historical:
> for id in ids:
> annexe = self.browse(cr, uid, id, context)
> comments = ""
> -
> - if 'num_cabins' in vals and vals.get('num_cabins', False) != annexe.num_cabins:
> - num_cabins = vals.get('num_cabins', False)
> +
> + if ('num_cabins' in vals and
> + vals['num_cabins'] != annexe.num_cabins):
> + num_cabins = vals['num_cabins']
> comments += _('Cambio de número de cabinas') + '\n'
> else:
> num_cabins = annexe.num_cabins
> -
> - if 'production_lot_id' in vals and vals.get('production_lot_id', False) != annexe.production_lot_id.id:
> - production_lot_id = vals.get('production_lot_id', False)
> +
> + if ('production_lot_id' in vals and
> + (vals['production_lot_id'] !=
> + annexe.production_lot_id.id)):
> + production_lot_id = vals['production_lot_id']
> comments += _('Cambio de ICC') + '\n'
> else:
> production_lot_id = annexe.production_lot_id.id
> -
> - if 'production_lot_2_id' in vals and vals.get('production_lot_2_id', False) != annexe.production_lot_2_id.id:
> - production_lot_2_id = vals.get('production_lot_2_id', False)
> +
> + if ('production_lot_2_id' in vals and
> + (vals['production_lot_2_id'] !=
> + annexe.production_lot_2_id.id)):
> + production_lot_2_id = vals['production_lot_2_id']
> comments += _('Cambio de IMEI') + '\n'
> else:
> production_lot_2_id = annexe.production_lot_2_id.id
> -
> - if 'fixed_price' in vals and vals.get('fixed_price', False) != annexe.fixed_price:
> - fixed_price = vals.get('fixed_price', False)
> +
> + if ('fixed_price' in vals and
> + vals.get('fixed_price', False) != annexe.fixed_price):
> + fixed_price = vals['fixed_price']
> comments += _('Cambio de precio fijo') + '\n'
> else:
> fixed_price = annexe.fixed_price
> -
> - if 'differential_price' in vals and vals.get('differential_price', False) != annexe.differential_price:
> - differential_price = vals.get('differential_price', False)
> +
> + if ('differential_price' in vals and
> + (vals['differential_price'] !=
> + annexe.differential_price)):
> + differential_price = vals['differential_price']
> comments += _('Cambio de precio diferencial') + '\n'
> else:
> differential_price = annexe.differential_price
>
> - if 'extra_cabin_price' in vals and vals.get('extra_cabin_price', False) != annexe.extra_cabin_price:
> - extra_cabin_price = vals.get('extra_cabin_price', False)
> + if ('extra_cabin_price' in vals and
> + vals['extra_cabin_price'] != annexe.extra_cabin_price):
> + extra_cabin_price = vals['extra_cabin_price']
> comments += _('Cambio de precio de cabina extra') + '\n'
> else:
> extra_cabin_price = annexe.extra_cabin_price
> -
> - if 'fixed_commission' in vals and vals.get('fixed_commission', False) != annexe.fixed_commission:
> - fixed_commission = vals.get('fixed_commission', False)
> +
> + if ('fixed_commission' in vals and
> + vals['fixed_commission'] != annexe.fixed_commission):
> + fixed_commission = vals['fixed_commission']
> comments += _('Cambio de comisión fija') + '\n'
> else:
> fixed_commission = annexe.fixed_commission
> -
> - if 'differential_commission' in vals and vals.get('differential_commission', False) != annexe.differential_commission:
> - differential_commission = vals.get('differential_commission', False)
> +
> + if ('differential_commission' in vals and
> + (vals['differential_commission'] !=
> + annexe.differential_commission)):
> + differential_commission = vals['differential_commission']
> comments += _('Cambio de comisión diferencial') + '\n'
> else:
> differential_commission = annexe.differential_commission
> -
> - if 'contract_id' in vals and vals.get('contract_id', False) != annexe.contract_id.id:
> - contract_id = vals.get('contract_id', False)
> +
> + if ('contract_id' in vals and
> + vals['contract_id'] != annexe.contract_id.id):
> + contract_id = vals['contract_id']
> comments += _('Cambio de contrato') + '\n'
> else:
> contract_id = annexe.contract_id.id
> -
> +
> if comments:
> - #Creamos entrada de cambio en histórico
> - self.pool.get('contract.annexe.historical').create(cr, uid, {
> - 'num_cabins': num_cabins,
> - 'production_lot_id': production_lot_id,
> - 'production_lot_2_id': production_lot_2_id,
> - 'fixed_price': fixed_price,
> - 'differential_price': differential_price,
> - 'extra_cabin_price': extra_cabin_price,
> - 'fixed_commission': fixed_commission,
> - 'differential_commission': differential_commission,
> - 'contract_id': contract_id,
> - 'contract_annexe_id': id,
> - 'comments': comments.strip(),
> - }, context)
> -
> - return super(contract_annexe, self).write(cr, uid, ids, vals, context=context)
> -
> -contract_annexe()
> -
> -
> -class contract_historical(osv.osv):
> -
> + # Creamos entrada de cambio en histórico
> + self.pool['contract.annexe.historical'].create(cr, uid, {
> + 'num_cabins': num_cabins,
> + 'production_lot_id': production_lot_id,
> + 'production_lot_2_id': production_lot_2_id,
> + 'fixed_price': fixed_price,
> + 'differential_price': differential_price,
> + 'extra_cabin_price': extra_cabin_price,
> + 'fixed_commission': fixed_commission,
> + 'differential_commission': differential_commission,
> + 'contract_id': contract_id,
> + 'contract_annexe_id': id,
> + 'comments': comments.strip(),
> + }, context)
> +
> + return super(ContractAnnexe, self).write(
> + cr, uid, ids, vals, context=context)
> +
> +
> +class ContractHistorical(orm.Model):
> _name = 'contract.historical'
> _description = "Contract Historical"
>
> - _columns = {
> - 'contract_id': fields.many2one('contract.contract', 'Contract', select=True, required=True),
> - 'date' : fields.datetime('Date', required=True),
> + _columns = {
> + 'contract_id': fields.many2one('contract.contract', 'Contract',
> + select=True, required=True),
> + 'date': fields.datetime('Date', required=True),
> 'elevator_id': fields.many2one('res.partner', 'Elevator', select=True),
> - 'middleman_id': fields.many2one('res.partner', 'Middleman', select=True),
> - 'fixed_price': fields.float('Fixed Price', digits=(2,2)),
> - 'differential_price': fields.float('Differential Price', digits=(2,2)),
> - 'extra_cabin_price': fields.float('Extra Cabin Price', digits=(2,2)),
> - 'fixed_commission': fields.float('Fixed Commission', digits=(2,2)),
> - 'differential_commission': fields.float('Differential Commission', digits=(2,2)),
> - 'fixed_link_price': fields.float('Fixed Link Price', digits=(2,2)),
> - 'differential_link_price': fields.float('Differential Link Price', digits=(2,2)),
> + 'middleman_id': fields.many2one('res.partner', 'Middleman',
> + select=True),
> + 'fixed_price': fields.float('Fixed Price', digits=(2, 2)),
> + 'differential_price': fields.float('Differential Price',
> + digits=(2, 2)),
> + 'extra_cabin_price': fields.float('Extra Cabin Price', digits=(2, 2)),
> + 'fixed_commission': fields.float('Fixed Commission', digits=(2, 2)),
> + 'differential_commission': fields.float('Differential Commission',
> + digits=(2, 2)),
> + 'fixed_link_price': fields.float('Fixed Link Price', digits=(2, 2)),
> + 'differential_link_price': fields.float('Differential Link Price',
> + digits=(2, 2)),
> 'comments': fields.text('Comments'),
> }
> -
> +
> _defaults = {
> 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
> }
> -
> +
> _order = 'date desc'
> -
> -contract_historical()
> -
> -
> -class contract_annexe_historical(osv.osv):
> -
> +
> +
> +class ContractAnnexeHistorical(orm.Model):
> _name = 'contract.annexe.historical'
> _description = "Contract Annexe Historical"
>
> - _columns = {
> - 'contract_annexe_id': fields.many2one('contract.annexe', 'Contract Annexe', select=True, required=True),
> - 'date' : fields.datetime('Date', required=True),
> - 'production_lot_id': fields.many2one('stock.production.lot', 'ICC', select=True),
> - 'production_lot_2_id': fields.many2one('stock.production.lot', 'IMEI', select=True),
> - 'num_cabins' : fields.integer('Num. Cabins'),
> - 'fixed_price': fields.float('Fixed Price', digits=(2,2)),
> - 'differential_price': fields.float('Differential Price', digits=(2,2)),
> - 'extra_cabin_price': fields.float('Extra Cabin Price', digits=(2,2)),
> - 'fixed_commission': fields.float('Fixed Commission', digits=(2,2)),
> - 'differential_commission': fields.float('Differential Commission', digits=(2,2)),
> + _columns = {
> + 'contract_annexe_id': fields.many2one('contract.annexe',
> + 'Contract Annexe',
> + select=True,
> + required=True),
> + 'date': fields.datetime('Date', required=True),
> + 'production_lot_id': fields.many2one('stock.production.lot',
> + 'ICC', select=True),
> + 'production_lot_2_id': fields.many2one('stock.production.lot',
> + 'IMEI', select=True),
> + 'num_cabins': fields.integer('Num. Cabins'),
> + 'fixed_price': fields.float('Fixed Price',
> + digits=(2, 2)),
> + 'differential_price': fields.float('Differential Price',
> + digits=(2, 2)),
> + 'extra_cabin_price': fields.float('Extra Cabin Price',
> + digits=(2, 2)),
> + 'fixed_commission': fields.float('Fixed Commission',
> + digits=(2, 2)),
> + 'differential_commission': fields.float('Differential Commission',
> + digits=(2, 2)),
> 'comments': fields.text('Comments'),
> }
> -
> +
> _defaults = {
> 'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
> }
> -
> +
> _order = 'date desc'
> -
> -contract_annexe_historical()
> -
> -
> -class contract_shipping_cost(osv.osv):
> -
> +
> +
> +class ContractShippingCost(orm.Model):
> _name = 'contract.shipping.cost'
> _description = "Contract Shipping Cost"
>
> - _columns = {
> - 'min_units' : fields.integer('From', help="Minimum number of units."),
> - 'max_units' : fields.integer('To', help="Maximum number of units."),
> - 'price': fields.float('Price', digits=(2,2)),
> - 'contract_id': fields.many2one('contract.contract', 'Contract', select=True, required=True),
> + _columns = {
> + 'min_units': fields.integer('From', help="Minimum number of units."),
> + 'max_units': fields.integer('To', help="Maximum number of units."),
> + 'price': fields.float('Price', digits=(2, 2)),
> + 'contract_id': fields.many2one('contract.contract', 'Contract',
> + select=True, required=True),
> }
> -
> +
> _order = 'min_units asc'
> -
> -
> +
> def create(self, cr, uid, vals, context=None):
> -
> - if 'min_units' in vals.keys() and vals['min_units'] <= 0:
> - raise osv.except_osv(_('Shipping Cost Error !'), _('The minimum units can not be less than or equal to zero !'))
> -
> - if 'max_units' in vals.keys() and vals['max_units'] <= 0:
> - raise osv.except_osv(_('Shipping Cost Error !'), _('The maximum units can not be less than or equal to zero !'))
> -
> + if 'min_units' in vals and vals['min_units'] <= 0:
> + raise orm.except_orm(
> + _('Shipping Cost Error !'),
> + _('The minimum units can not be less than or equal to zero !'))
> +
> + if 'max_units' in vals and vals['max_units'] <= 0:
> + raise orm.except_orm(
> + _('Shipping Cost Error !'),
> + _('The maximum units can not be less than or equal to zero !'))
> +
> if vals['min_units'] > vals['max_units']:
> - raise osv.except_osv(_('Shipping Cost Error !'), _('You must enter a correct range of units !'))
> -
> - if 'contract_id' in vals.keys() and vals['contract_id']:
> - shipping_cost_ids = self.search(cr, uid, [('contract_id', '=', vals['contract_id'])])
> - for shipping_cost in self.browse(cr, uid, shipping_cost_ids, context=context):
> - if (shipping_cost.min_units <= vals['min_units'] and vals['min_units'] <= shipping_cost.max_units) or (shipping_cost.min_units <= vals['max_units'] and vals['max_units'] <= shipping_cost.max_units):
> - raise osv.except_osv(_('Shipping Cost Error !'), _('It is necessary that the shipping cost rules do not produce intersection between them !'))
> -
> - return super(contract_shipping_cost, self).create(cr, uid, vals, context=context)
> -
> -
> + raise orm.except_orm(
> + _('Shipping Cost Error !'),
> + _('You must enter a correct range of units !'))
> +
> + if 'contract_id' in vals and vals['contract_id']:
> + shipping_cost_ids = self.search(
> + cr, uid, [('contract_id', '=', vals['contract_id'])])
> + for shipping_cost in self.browse(
> + cr, uid, shipping_cost_ids, context=context):
> + if ((shipping_cost.min_units <= vals['min_units'] and
> + vals['min_units'] <= shipping_cost.max_units) or
> + (shipping_cost.min_units <= vals['max_units'] and
> + vals['max_units'] <= shipping_cost.max_units)):
> + raise orm.except_orm(
> + _('Shipping Cost Error !'),
> + _('It is necessary that the shipping cost rules do '
> + 'not produce intersection between them !'))
> +
> + return super(ContractShippingCost, self).create(
> + cr, uid, vals, context=context)
> +
> def write(self, cr, uid, ids, vals, context=None):
> -
> - if 'min_units' in vals.keys() and vals['min_units'] <= 0:
> - raise osv.except_osv(_('Shipping Cost Error !'), _('The minimum units can not be less than or equal to zero !'))
> -
> - if 'max_units' in vals.keys() and vals['max_units'] <= 0:
> - raise osv.except_osv(_('Shipping Cost Error !'), _('The maximum units can not be less than or equal to zero !'))
> -
> + if 'min_units' in vals and vals['min_units'] <= 0:
> + raise orm.except_orm(
> + _('Shipping Cost Error !'),
> + _('The minimum units can not be less than or equal to zero !'))
> +
> + if 'max_units' in vals and vals['max_units'] <= 0:
> + raise orm.except_orm(
> + _('Shipping Cost Error !'),
> + _('The maximum units can not be less than or equal to zero !'))
> +
> if vals['min_units'] > vals['max_units']:
> - raise osv.except_osv(_('Shipping Cost Error !'), _('You must enter a correct range of units !'))
> -
> + raise orm.except_orm(
> + _('Shipping Cost Error !'),
> + _('You must enter a correct range of units !'))
> +
> for shipping_cost in self.browse(cr, uid, ids, context=context):
> - shipping_cost_ids = self.search(cr, uid, [('contract_id', '=', shipping_cost.contract_id.id), ('id', '!=', shipping_cost.id)])
> - for shipping_cost_2 in self.browse(cr, uid, shipping_cost_ids, context=context):
> - if (shipping_cost_2.min_units <= vals['min_units'] and vals['min_units'] <= shipping_cost_2.max_units) or (shipping_cost_2.min_units <= vals['max_units'] and vals['max_units'] <= shipping_cost_2.max_units):
> - raise osv.except_osv(_('Shipping Cost Error !'), _('It is necessary that the shipping cost rules do not produce intersection between them !'))
> -
> - return super(contract_shipping_cost, self).write(cr, uid, ids, vals, context = context)
> -
> -
> -contract_shipping_cost()
> -
> -class contract_info_invoice(osv.osv):
> -
> + shipping_cost_ids = self.search(
> + cr, uid, [('contract_id', '=', shipping_cost.contract_id.id),
> + ('id', '!=', shipping_cost.id)],
> + context=context)
> + for shipping_cost_2 in self.browse(
> + cr, uid, shipping_cost_ids, context=context):
> + if ((shipping_cost_2.min_units <= vals['min_units'] and
> + vals['min_units'] <= shipping_cost_2.max_units) or
> + (shipping_cost_2.min_units <= vals['max_units'] and
> + vals['max_units'] <= shipping_cost_2.max_units)):
> + raise orm.except_orm(
> + _('Shipping Cost Error !'),
> + _('It is necessary that the shipping cost rules do '
> + 'not produce intersection between them !'))
> +
> + return super(ContractShippingCost,
> + self).write(cr, uid, ids, vals, context=context)
> +
> +
> +class ContractInfoInvoice(orm.Model):
> _name = 'contract.info.invoice'
> -
> +
> _columns = {
> - 'contract_id': fields.many2one('contract.contract', 'Contract', select=True, required=True),
> - 'categ_id' : fields.many2one('product.category', 'Product Category', select=True, required=True),
> - 'receiver' : fields.selection([('cliente', 'Cliente'), ('ascensorista', 'Ascensorista')], 'Receiver', select=True, required=True),
> + 'contract_id': fields.many2one('contract.contract',
> + 'Contract',
> + select=True,
> + required=True),
> + 'categ_id': fields.many2one('product.category',
> + 'Product Category',
> + select=True,
> + required=True),
> + 'receiver': fields.selection([('cliente', 'Cliente'),
> + ('ascensorista', 'Ascensorista')],
> + 'Receiver',
> + select=True,
> + required=True),
> }
> -
> +
> _sql_constraints = [
> - ('categ_uniq', 'unique(contract_id, categ_id)', 'Product Category must be unique !'),
> + ('categ_uniq',
> + 'unique(contract_id, categ_id)',
> + 'Product Category must be unique !'),
> ]
>
> -contract_info_invoice()
> -
> -
> -class contract_price_rules(osv.osv):
> -
> +
> +class ContractPriceRules(orm.Model):
> _name = 'contract.price.rules'
> -
> +
> _columns = {
> - 'contract_id': fields.many2one('contract.contract', 'Contract', select=True, required=True),
> - 'product_id': fields.many2one('product.product', 'SIM Product', select=True),
> - 'product_2_id': fields.many2one('product.product', 'Link Product', select=True),
> - 'fixed_price': fields.float('Fixed Price', digits=(2,2)),
> - 'differential_price': fields.float('Differential Price', digits=(2,2)),
> - 'extra_cabin_price': fields.float('Extra Cabin Price', digits=(2,2)),
> - 'fixed_link_price': fields.float('Fixed Link Price', digits=(2,2)),
> - 'differential_link_price': fields.float('Differential Link Price', digits=(2,2)),
> - 'fixed_commission': fields.float('Fixed Commission', digits=(2,2)),
> - 'differential_commission': fields.float('Differential Commission', digits=(2,2)),
> + 'contract_id': fields.many2one('contract.contract',
> + 'Contract',
> + select=True,
> + required=True),
> + 'product_id': fields.many2one('product.product',
> + 'SIM Product',
> + select=True),
> + 'product_2_id': fields.many2one('product.product',
> + 'Link Product',
> + select=True),
> + 'fixed_price': fields.float('Fixed Price',
> + digits=(2, 2)),
> + 'differential_price': fields.float('Differential Price',
> + digits=(2, 2)),
> + 'extra_cabin_price': fields.float('Extra Cabin Price',
> + digits=(2, 2)),
> + 'fixed_link_price': fields.float('Fixed Link Price',
> + digits=(2, 2)),
> + 'differential_link_price': fields.float('Differential Link Price',
> + digits=(2, 2)),
> + 'fixed_commission': fields.float('Fixed Commission',
> + digits=(2, 2)),
> + 'differential_commission': fields.float('Differential Commission',
> + digits=(2, 2)),
> }
> -
> +
> _sql_constraints = [
> - ('contract_price_rules_uniq', 'unique(contract_id, product_id, product_2_id)', 'Can not define price rules for the same SIM and/or link !'),
> + ('contract_price_rules_uniq',
> + 'unique(contract_id, product_id, product_2_id)',
> + 'Can not define price rules for the same SIM and/or link !'),
> ]
>
> -contract_price_rules()
> -
> -class contract_price(osv.osv):
> -
> +
> +class ContractPrice(orm.Model):
> _name = 'contract.price'
> -
> +
> _columns = {
> - 'contract_id': fields.many2one('contract.contract', 'Contract', select=True, required=True),
> - 'fixed_price': fields.float('Fixed Price', digits=(2,2), required=True),
> - 'months' : fields.integer('Num. Monthly', required=True),
> + 'contract_id': fields.many2one('contract.contract',
> + 'Contract',
> + select=True,
> + required=True),
> + 'fixed_price': fields.float('Fixed Price',
> + digits=(2, 2),
> + required=True),
> + 'months': fields.integer('Num. Monthly',
> + required=True),
> }
> -
> +
> _order = 'months asc'
> -
> +
> _sql_constraints = [
> - ('months_uniq', 'unique(contract_id, months)', 'Number of Monthly must be unique !'),
> + ('months_uniq',
> + 'unique(contract_id, months)',
> + 'Number of Monthly must be unique !'),
> ]
>
> -contract_price()
> -
> -
> -class contract_scaled_price(osv.osv):
> -
> +
> +class ContractScaledPrice(orm.Model):
> _name = 'contract.scaled.price'
> -
> +
> _columns = {
> - 'contract_id': fields.many2one('contract.contract', 'Contract', select=True, required=True),
> - 'fixed_price': fields.float('Fixed Price', digits=(2,2), required=True),
> - 'items' : fields.integer('Num. Items', required=True),
> + 'contract_id': fields.many2one('contract.contract',
> + 'Contract',
> + select=True,
> + required=True),
> + 'fixed_price': fields.float('Fixed Price',
> + digits=(2, 2),
> + required=True),
> + 'items': fields.integer('Num. Items',
> + required=True),
> }
> -
> +
> _order = 'items asc'
> -
> +
> _sql_constraints = [
> - ('items_uniq', 'unique(contract_id, items)', 'Number of Items must be unique !'),
> + ('items_uniq',
> + 'unique(contract_id, items)',
> + 'Number of Items must be unique !'),
> ]
>
> -contract_scaled_price()
> -
> -
> -class contract_annexe_price(osv.osv):
> -
> +
> +class ContractAnnexePrice(orm.Model):
> _name = 'contract.annexe.price'
> -
> +
> _columns = {
> - 'contract_annexe_id': fields.many2one('contract.annexe', 'Contract Annexe', select=True, required=True),
> - 'fixed_price': fields.float('Fixed Price', digits=(2,2), required=True),
> - 'expiration_date' : fields.date('Expiration Date', required=True),
> + 'contract_annexe_id': fields.many2one('contract.annexe',
> + 'Contract Annexe',
> + select=True,
> + required=True),
> + 'fixed_price': fields.float('Fixed Price',
> + digits=(2, 2),
> + required=True),
> + 'expiration_date': fields.date('Expiration Date',
> + required=True),
> }
> -
> +
> _order = 'expiration_date asc'
> -
> +
> _sql_constraints = [
> - ('expiration_date_uniq', 'unique(contract_annexe_id, expiration_date)', 'Expiration Date must be unique !'),
> + ('expiration_date_uniq',
> + 'unique(contract_annexe_id, expiration_date)',
> + 'Expiration Date must be unique !'),
> ]
> -
> -contract_annexe_price()
>
> === renamed file 'dos_contracts/invoice.py' => 'dos_contracts/models/invoice.py'
> --- dos_contracts/invoice.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/models/invoice.py 2014-07-03 14:26:17 +0000
> @@ -19,129 +19,165 @@
> #
> ##############################################################################
>
> -
> -from osv import osv
> -from osv import fields
> -from tools.translate import _
> -
> -class account_invoice(osv.osv):
> -
> - _inherit ="account.invoice"
> -
> - _columns = {
> - 'contract_id': fields.many2one('contract.contract', 'Contract', readonly=True, states={'draft':[('readonly',False)]}, select=True),
> - 'contact_id': fields.many2one('res.partner.job', 'Contact', readonly=True, states={'draft': [('readonly', False)]}, help="The name and address of the contact who requested the invoice."),
> - }
> -
> - def _refund_cleanup_lines(self, cr, uid, lines):
> - for line in lines:
> - del line['id']
> - del line['invoice_id']
> - for field in ('company_id', 'partner_id', 'account_id', 'product_id',
> - 'uos_id', 'account_analytic_id', 'tax_code_id', 'base_code_id',
> - 'contract_id', 'contract_annexe_id', 'stock_move_id'):
> - line[field] = line.get(field, False) and line[field][0]
> - if 'invoice_line_tax_id' in line:
> - line['invoice_line_tax_id'] = [(6,0, line.get('invoice_line_tax_id', [])) ]
> - return map(lambda x: (0,0,x), lines)
> -
> - def refund(self, cr, uid, ids, date=None, period_id=None, description=None, journal_id=None):
> -
> - res = super(account_invoice, self).refund(cr, uid, ids, date, period_id, description, journal_id)
> -
> - i = 0
> - for id in ids:
> - invoice = self.browse(cr, uid, id)
> -
> - self.write(cr, uid, [res[i]], {
> - 'commission_settled': invoice and invoice.commission_settled or False,
> - 'commission_settled_date': invoice and invoice.commission_settled_date or None,
> - 'commission_total': invoice and invoice.commission_total or None,
> - 'decorator_discount': invoice and invoice.decorator_discount or None,
> - 'agent_id': invoice and invoice.agent_id and invoice.agent_id.id or None,
> - 'agent2_id': invoice and invoice.agent2_id and invoice.agent2_id.id or None,
> - 'agent2_percentage_distribution_commission': invoice and invoice.agent2_percentage_distribution_commission or None,
> - 'elevator_partner_id': invoice and invoice.elevator_partner_id and invoice.elevator_partner_id.id or None,
> - 'middleman_partner_id': invoice and invoice.middleman_partner_id and invoice.middleman_partner_id.id or None,
> - 'contract_id': invoice and invoice.contract_id and invoice.contract_id.id or None,
> - }, context=None)
> -
> - i += 1
> -
> - return res
> -
> -
> - def unlink(self, cr, uid, ids, context=None):
> -
> - # Al eliminar una factura, si se han facturado SIMs
> - # actualizamos fecha de vencimiento de los anexos para dejarla
> - # en el estado anterior de la factura
> - product_obj = self.pool.get('product.product')
> - annexe_obj = self.pool.get('contract.annexe')
> -
> - for id in ids:
> - invoice = self.browse(cr, uid, id, context)
> -
> - for line in invoice.invoice_line:
> - if product_obj._is_sim(line.product_id.categ_id) and line.contract_annexe_id and line.start_date:
> - expiration_date = line.start_date
> - annexe_id = line.contract_annexe_id.id
> -
> - annexe_obj.write(cr, uid, [annexe_id], {'expiration_date': expiration_date}, context={'historical':False})
> -
> - return super(account_invoice, self).unlink(cr, uid, ids, context=context)
> -
> -account_invoice()
> -
> -
> -class account_invoice_line(osv.osv):
> -
> - _inherit ="account.invoice.line"
> -
> - def _get_product_identifier(self, cr, uid, ids, field_name, arg, context=None):
> - """ Gets identifier of products
> - @return: Dictionary of values
> - """
> - product_obj = self.pool.get('product.product')
> -
> - if context is None:
> - context = {}
> -
> - if isinstance(ids, (int, long)):
> - ids = [ids]
> -
> - res = {}.fromkeys(ids, '')
> -
> - for line in self.browse(cr, uid, ids, context):
> - if line.contract_annexe_id and product_obj._is_sim(line.product_id.categ_id):
> - res[line.id] = line.contract_annexe_id.production_lot_id and line.contract_annexe_id.production_lot_id.telefono or ''
> - elif line.contract_annexe_id and product_obj._is_link(line.product_id.categ_id):
> - res[line.id] = line.contract_annexe_id.production_lot_2_id and line.contract_annexe_id.production_lot_2_id.imei or ''
> -
> - return res
> -
> -
> - _columns = {
> - 'num_cabins' : fields.integer('Num. Cabins'),
> - 'months': fields.float('Months', digits=(2,2)),
> - 'start_date' : fields.date('Start Date'),
> - 'end_date' : fields.date('End Date'),
> - 'customer_ref': fields.char('Customer Ref.', size=256),
> - 'product_identifier': fields.function(_get_product_identifier, method=True, type="string", string="Identifier", select=True),
> - }
> -
> - _defaults = {
> - 'num_cabins': 0,
> - }
> -
> -
> - def onchange_account_id(self, cr, uid, ids, fposition_id, account_id):
> -
> - taxes = account_id and self.pool.get('account.account').browse(cr, uid, account_id).tax_ids or False
> -
> - if not account_id or not taxes:
> - return {}
> -
> - return super(account_invoice_line, self).onchange_account_id(cr, uid, ids, fposition_id, account_id)
> -
> -account_invoice_line()
> +from openerp.osv import orm, fields
> +
> +
> +class AccountInvoice(orm.Model):
> +
> + _inherit = "account.invoice"
> +
> + _columns = {
> + 'contract_id': fields.many2one('contract.contract', 'Contract',
> + readonly=True,
> + states={'draft': [('readonly', False)]},
> + select=True),
> + 'contact_id': fields.many2one('res.partner.job', 'Contact',
> + readonly=True,
> + states={'draft': [('readonly', False)]},
> + help="The name and address of the "
> + "contact who requested the invoice."),
> + }
> +
> + def _refund_cleanup_lines(self, cr, uid, lines):
> + for line in lines:
> + del line['id']
> + del line['invoice_id']
> + for field in ('company_id', 'partner_id', 'account_id',
> + 'product_id', 'uos_id', 'account_analytic_id',
> + 'tax_code_id', 'base_code_id', 'contract_id',
> + 'contract_annexe_id', 'stock_move_id'):
> + line[field] = line.get(field, False) and line[field][0]
> + if 'invoice_line_tax_id' in line:
> + line['invoice_line_tax_id'] = [
> + (6, 0, line.get('invoice_line_tax_id', []))]
> + return map(lambda x: (0, 0, x), lines)
> +
> + def refund(self, cr, uid, ids, date=None, period_id=None, description=None,
> + journal_id=None):
> +
> + res = super(AccountInvoice,
> + self).refund(cr, uid, ids, date, period_id, description,
> + journal_id)
> +
> + i = 0
> + for id in ids:
> + invoice = self.browse(cr, uid, id)
> +
> + self.write(cr, uid, [res[i]], {
> + 'commission_settled':
> + (invoice and invoice.commission_settled or False),
> + 'commission_settled_date':
> + (invoice and invoice.commission_settled_date or None),
> + 'commission_total':
> + (invoice and invoice.commission_total or None),
> + 'decorator_discount':
> + (invoice and invoice.decorator_discount or None),
> + 'agent_id':
> + (invoice and invoice.agent_id and invoice.agent_id.id or None),
> + 'agent2_id':
> + (invoice and invoice.agent2_id and invoice.agent2_id.id or
> + None),
> + 'agent2_percentage_distribution_commission':
> + (invoice and
> + invoice.agent2_percentage_distribution_commission or None),
> + 'elevator_partner_id':
> + (invoice and invoice.elevator_partner_id and
> + invoice.elevator_partner_id.id or None),
> + 'middleman_partner_id':
> + (invoice and invoice.middleman_partner_id and
> + invoice.middleman_partner_id.id or None),
> + 'contract_id':
> + (invoice and invoice.contract_id and invoice.contract_id.id or
> + None),
> + }, context=None)
> +
> + i += 1
> +
> + return res
> +
> + def unlink(self, cr, uid, ids, context=None):
> +
> + # Al eliminar una factura, si se han facturado SIMs
> + # actualizamos fecha de vencimiento de los anexos para dejarla
> + # en el estado anterior de la factura
> + product_obj = self.pool['product.product']
> + annexe_obj = self.pool['contract.annexe']
> +
> + for id in ids:
> + invoice = self.browse(cr, uid, id, context=context)
> +
> + for line in invoice.invoice_line:
> + if (product_obj._is_sim(line.product_id.categ_id) and
> + line.contract_annexe_id and line.start_date):
> + expiration_date = line.start_date
> + annexe_id = line.contract_annexe_id.id
> +
> + annexe_obj.write(cr, uid, [annexe_id],
> + {'expiration_date': expiration_date},
> + context={'historical': False})
> +
> + return super(AccountInvoice,
> + self).unlink(cr, uid, ids, context=context)
> +
> +
> +class AccountInvoiceLine(orm.Model):
> + _inherit = "account.invoice.line"
> +
> + def _get_product_identifier(self, cr, uid, ids, field_name, arg,
> + context=None):
> + """ Gets identifier of products
> + @return: Dictionary of values
> + """
> + product_obj = self.pool['product.product']
> +
> + if context is None:
> + context = {}
> +
> + if isinstance(ids, (int, long)):
> + ids = [ids]
> +
> + res = {}.fromkeys(ids, '')
> +
> + for line in self.browse(cr, uid, ids, context):
> + if (line.contract_annexe_id and
> + product_obj._is_sim(line.product_id.categ_id)):
> + res[line.id] = (
> + line.contract_annexe_id.production_lot_id and
> + line.contract_annexe_id.production_lot_id.telefono or '')
> + elif (line.contract_annexe_id and
> + product_obj._is_link(line.product_id.categ_id)):
> + res[line.id] = (
> + line.contract_annexe_id.production_lot_2_id and
> + line.contract_annexe_id.production_lot_2_id.imei or '')
> +
> + return res
> +
> + _columns = {
> + 'num_cabins': fields.integer('Num. Cabins'),
> + 'months': fields.float('Months', digits=(2, 2)),
> + 'start_date': fields.date('Start Date'),
> + 'end_date': fields.date('End Date'),
> + 'customer_ref': fields.char('Customer Ref.', size=256),
> + 'product_identifier': fields.function(_get_product_identifier,
> + method=True, type="string",
> + string="Identifier",
> + select=True),
> + }
> +
> + _defaults = {
> + 'num_cabins': 0,
> + }
> +
> + def onchange_account_id(self, cr, uid, ids, fposition_id, account_id):
> +
> + account_obj = self.pool['account.account']
> + taxes = False
> + if account_id:
> + taxes = account_obj.browse(cr, uid, account_id).tax_ids
> +
> + if not account_id or not taxes:
> + return {}
> +
> + return super(AccountInvoiceLine,
> + self).onchange_account_id(cr, uid, ids,
> + fposition_id, account_id)
>
> === renamed file 'dos_contracts/partner.py' => 'dos_contracts/models/partner.py'
> --- dos_contracts/partner.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/models/partner.py 2014-07-03 14:26:17 +0000
> @@ -19,25 +19,16 @@
> #
> ##############################################################################
>
> -import math
> -from osv import fields,osv
> -import tools
> -import pooler
> -from tools.translate import _
> -
> -class res_partner(osv.osv):
> -
> - _name = 'res.partner'
> - _inherit = 'res.partner'
> -
> - _columns = {
> - 'contract_ids': fields.one2many('contract.contract', 'customer_id', 'Contracts'),
> - 'elevator_contract_ids': fields.one2many('contract.contract', 'elevator_id', 'Elevator Contracts'),
> - }
> -
> -res_partner()
> -
> -
> -
> -
> -
> +from openerp.osv import fields, orm
> +
> +
> +class ResPartner(orm.Model):
> + _inherit = 'res.partner'
> +
> + _columns = {
> + 'contract_ids': fields.one2many('contract.contract', 'customer_id',
> + 'Contracts'),
> + 'elevator_contract_ids': fields.one2many('contract.contract',
> + 'elevator_id',
> + 'Elevator Contracts'),
> + }
>
> === renamed file 'dos_contracts/sale.py' => 'dos_contracts/models/sale.py'
> --- dos_contracts/sale.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/models/sale.py 2014-07-03 14:26:17 +0000
> @@ -19,186 +19,221 @@
> #
> ##############################################################################
>
> -from osv import osv
> -from osv import fields
> -from tools.translate import _
> +from openerp.osv import orm, fields
> +from openerp.tools.translate import _
> import time
> from datetime import datetime
> from dateutil.relativedelta import relativedelta
>
>
> -class sale_order(osv.osv):
> +class SaleOrder(orm.Model):
> + _inherit = "sale.order"
>
> - _inherit ="sale.order"
> -
> _columns = {
> - 'contract_id': fields.many2one('contract.contract', 'Contract', readonly=True, states={'draft': [('readonly', False)]}, select=True),
> - 'contact_id': fields.many2one('res.partner.job', 'Contact', readonly=True, states={'draft': [('readonly', False)]}, help="The name and address of the contact who requested the order or quotation."),
> + 'contract_id': fields.many2one('contract.contract', 'Contract',
> + readonly=True, select=True,
> + states={'draft':
> + [('readonly', False)]}),
> + 'contact_id': fields.many2one('res.partner.job', 'Contact',
> + readonly=True,
> + states={'draft': [('readonly', False)]},
> + help="The name and address of the "
> + "contact who requested the order or "
> + "quotation."),
> }
> -
> - def _get_bom_product_lot(self, cr, uid, warehouse, prodlot_id, product_id):
> -
> - stock_move_obj = self.pool.get('stock.move')
> -
> - dest_move_ids = stock_move_obj.search(cr, uid, [("prodlot_id", "=", prodlot_id), ("location_dest_id", "=", warehouse.lot_stock_id.id)], order='create_date desc')
> -
> +
> + def _get_bom_product_lot(self, cr, uid, warehouse, prodlot_id, product_id,
> + context=None):
> + move_obj = self.pool['stock.move']
> +
> + dest_move_ids = move_obj.search(
> + cr, uid, [("prodlot_id", "=", prodlot_id),
> + ("location_dest_id", "=", warehouse.lot_stock_id.id)],
> + order='create_date desc', context=context)
> +
> dest_move_id = dest_move_ids and dest_move_ids[0] or False
> - for dest_move in stock_move_obj.browse(cr, uid, dest_move_ids):
> + for dest_move in move_obj.browse(cr, uid, dest_move_ids,
> + context=context):
> if dest_move.move_dest_id:
> dest_move_id = dest_move.id
> -
> - move_ids = stock_move_obj.search(cr, uid, [("move_dest_id", "=", dest_move_id), ("product_id", "=", product_id)])
> +
> + move_ids = move_obj.search(
> + cr, uid, [("move_dest_id", "=", dest_move_id),
> + ("product_id", "=", product_id)],
> + context=context)
> move_id = move_ids and move_ids[0] or False
> -
> - move = stock_move_obj.browse(cr, uid, move_id, context={})
> -
> +
> + move = move_obj.browse(cr, uid, move_id, context=context)
> +
> return move.prodlot_id and move.prodlot_id.id or False
> -
> -
> - def _get_bom_stock_location_dest(self, cr, uid, warehouse, prodlot_id, product_id):
> -
> - stock_move_obj = self.pool.get('stock.move')
> -
> - dest_move_ids = stock_move_obj.search(cr, uid, [("prodlot_id", "=", prodlot_id), ("location_dest_id", "=", warehouse.lot_stock_id.id)], order='create_date desc')
> -
> - #dest_move_id = dest_move_ids and dest_move_ids[0] or False
> +
> + def _get_bom_stock_location_dest(self, cr, uid, warehouse, prodlot_id,
> + product_id, context=None):
> + move_obj = self.pool['stock.move']
> +
> + dest_move_ids = move_obj.search(
> + cr, uid, [("prodlot_id", "=", prodlot_id),
> + ("location_dest_id", "=", warehouse.lot_stock_id.id)],
> + order='create_date desc', context=context)
> +
> dest_move_id = False
> - for dest_move in stock_move_obj.browse(cr, uid, dest_move_ids):
> + for dest_move in move_obj.browse(cr, uid, dest_move_ids):
> if dest_move.move_dest_id:
> dest_move_id = dest_move.id
> -
> - move_ids = stock_move_obj.search(cr, uid, [("move_dest_id", "=", dest_move_id), ("product_id", "=", product_id)])
> +
> + move_ids = move_obj.search(
> + cr, uid, [("move_dest_id", "=", dest_move_id),
> + ("product_id", "=", product_id)],
> + context=context)
> move_id = move_ids and move_ids[0] or False
> -
> - move = stock_move_obj.browse(cr, uid, move_id, context={})
> -
> +
> + move = move_obj.browse(cr, uid, move_id, context=context)
> +
> return move.location_dest_id and move.location_dest_id.id or False
> -
> -
> +
> def exist_duplicate_order_lines(self, order):
> - unique_lots= []
> + unique_lots = []
> lots = []
> -
> +
> for line in order.order_line:
> - lots.append(line.prodlot_id and line.prodlot_id.name or ('LOT' + str(line.id)))
> -
> + lots.append(line.prodlot_id and line.prodlot_id.name or
> + ('LOT' + str(line.id)))
> +
> for lot in lots:
> if lot not in unique_lots:
> - unique_lots.append(lot)
> -
> + unique_lots.append(lot)
> +
> return (len(lots) != len(unique_lots))
> -
> -
> - def action_ship_create(self, cr, uid, ids, *args):
> -
> - sale_line_obj = self.pool.get('sale.order.line')
> - stock_picking_obj = self.pool.get('stock.picking')
> - stock_move_obj = self.pool.get('stock.move')
> - bom_obj = self.pool.get('mrp.bom')
> - contract_obj = self.pool.get('contract.contract')
> - annexe_obj = self.pool.get('contract.annexe')
> - hist_annexe_obj = self.pool.get('contract.annexe.historical')
> - annexe_prices_obj = self.pool.get('contract.annexe.price')
> - product_obj = self.pool.get('product.product')
> -
> - #Comprobamos que todos los production tienen asignado un lote de produccion
> +
> + def action_ship_create(self, cr, uid, ids, context=None, *args):
> + sale_line_obj = self.pool['sale.order.line']
> + stock_picking_obj = self.pool['stock.picking']
> + move_obj = self.pool['stock.move']
> + bom_obj = self.pool['mrp.bom']
> + contract_obj = self.pool['contract.contract']
> + annexe_obj = self.pool['contract.annexe']
> + hist_annexe_obj = self.pool['contract.annexe.historical']
> + annexe_prices_obj = self.pool['contract.annexe.price']
> + product_obj = self.pool['product.product']
> +
> + # Comprobamos que todos los production tienen asignado un lote de
> + # produccion
> num_annexes = 0
> -
> - for order in self.browse(cr, uid, ids, context={}):
> -
> +
> + for order in self.browse(cr, uid, ids, context=context):
> +
> # Comprobamos si se han introducido lotes de produccion duplicados
> if self.exist_duplicate_order_lines(order):
> - raise osv.except_osv(_('Duplicate lots !'), _('There are production lots of products duplicates.'))
> -
> -
> + raise orm.except_orm(
> + _('Duplicate lots !'),
> + _('There are production lots of products duplicates.'))
> +
> for line in order.order_line:
> - if (not line.prodlot_id or line.product_uom_qty > 1) and line.product_id.type == 'product':
> - raise osv.except_osv(_('Product Lots not defined !'), _('Need to assign a lot of production for each product in the sales order.'))
> -
> - #Contamos anexos que se van a crear
> - if product_obj._is_sim(line.product_id.categ_id) or product_obj._is_pack(line.product_id.categ_id):
> + if ((not line.prodlot_id or line.product_uom_qty > 1) and
> + line.product_id.type == 'product'):
> + raise orm.except_orm(
> + _('Product Lots not defined !'),
> + _('Need to assign a lot of production for each product'
> + ' in the sales order.'))
> +
> + # Contamos anexos que se van a crear
> + if (product_obj._is_sim(line.product_id.categ_id) or
> + product_obj._is_pack(line.product_id.categ_id)):
> num_annexes += 1
> -
> - #Si el producto tiene como metodo suministro producir (Pack)
> - #Creamos lineas con los materiales que lo componen
> - if line.product_id and line.product_id.supply_method == 'produce':
> - bom_id = bom_obj._bom_find(cr, uid, line.product_id.id, line.product_id.uom_id and line.product_id.uom_id.id, [])
> +
> + # Si el producto tiene como metodo suministro producir (Pack)
> + # Creamos lineas con los materiales que lo componen
> + if (line.product_id and
> + line.product_id.supply_method == 'produce'):
> + bom_id = bom_obj._bom_find(cr, uid, line.product_id.id,
> + (line.product_id.uom_id and
> + line.product_id.uom_id.id), [])
> delete = False
> if bom_id:
> - bom_point = bom_obj.browse(cr, uid, bom_id, context={})
> -
> + bom_point = bom_obj.browse(cr, uid, bom_id, context=context)
> +
> if bom_point.bom_lines:
> - #Creamos albarán interno para traspasar los materiales
> - #de la ubicacion de produccion a la ubicacion de stock
> + # Creamos albarán interno para traspasar los
> + # materiales de la ubicacion de produccion a la
> + # ubicacion de stock
> vals = {
> - 'sale_id': order.id,
> - 'origin': order.name,
> - 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
> - 'move_type': 'direct',
> - 'invoice_state': 'none',
> - 'state': 'draft',
> - 'auto_picking': False,
> - 'type': 'internal',
> + 'sale_id': order.id,
> + 'origin': order.name,
> + 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
> + 'move_type': 'direct',
> + 'invoice_state': 'none',
> + 'state': 'draft',
> + 'auto_picking': False,
> + 'type': 'internal',
> }
> - stock_picking_id = stock_picking_obj.create(cr, uid, vals)
> -
> - #Obtenemos productos que componen el pack
> + stock_picking_id = stock_picking_obj.create(
> + cr, uid, vals, context=context)
> +
> + # Obtenemos productos que componen el pack
> product_sim_id = None
> product_link_id = None
> -
> +
> for bom_line in bom_point.bom_lines:
> - if product_obj._is_sim(bom_line.product_id.categ_id):
> + if product_obj._is_sim(
> + bom_line.product_id.categ_id):
> product_sim_id = bom_line.product_id.id
> - elif product_obj._is_link(bom_line.product_id.categ_id):
> + elif product_obj._is_link(
> + bom_line.product_id.categ_id):
> product_link_id = bom_line.product_id.id
> -
> - #Recorremos materiales
> +
> + # Recorremos materiales
> for bom_line in bom_point.bom_lines:
> - prodlot_id = self._get_bom_product_lot(cr, uid, order.shop_id.warehouse_id, line.prodlot_id.id, bom_line.product_id.id)
> -
> + prodlot_id = self._get_bom_product_lot(
> + cr, uid, order.shop_id.warehouse_id,
> + line.prodlot_id.id, bom_line.product_id.id)
> +
> price_unit = line.price_unit
> discount = line.discount
> num_cabins = line.num_cabins
> rented = line.rented
> -
> - #Si es SIM siempre se alquila, si no se coje valor de la linea
> - #Calculamos precio SIM
> +
> + # Si es SIM siempre se alquila, si no se coje
> + # valor de la línea. Calculamos precio SIM
> if product_obj._is_sim(bom_line.product_id.categ_id):
> rented = True
> -
> - #Obtenemos precio fijo contrato segun reglas definidas
> - fixed_price = contract_obj.get_fixed_price(cr, uid, order.contract_id.id, product_sim_id, product_link_id, num_annexes)
> -
> +
> + # Obtenemos precio fijo contrato segun
> + # reglas definidas
> + fixed_price = contract_obj.get_fixed_price(
> + cr, uid, order.contract_id.id,
> + product_sim_id, product_link_id,
> + num_annexes, context=context)
> +
> extra_cabin_price = contract_obj.get_extra_cabin_price(cr, uid, order.contract_id.id, product_sim_id, product_link_id)
> differential_price = contract_obj.get_differential_price(cr, uid, order.contract_id.id, product_sim_id, product_link_id)
> -
> - #Las sims siempre tienes al menos una cabina
> +
> + # Las sims siempre tienes al menos una cabina
> if not num_cabins or (num_cabins and num_cabins <= 0):
> num_cabins = 1
> -
> +
> price_cabins = num_cabins > 1 and ((num_cabins - 1) * extra_cabin_price) or 0
> price_unit = fixed_price + price_cabins
> discount = differential_price
> -
> - #Si es Enlace, calculamos precio
> +
> + # Si es Enlace, calculamos precio
> elif product_obj._is_link(bom_line.product_id.categ_id):
> fixed_link_price = contract_obj.get_fixed_link_price(cr, uid, order.contract_id.id, product_sim_id, product_link_id)
> - differential_link_price = contract_obj.get_differential_link_price(cr, uid, order.contract_id.id, product_sim_id, product_link_id)
> -
> - num_cabins = 0 #Los enlace no tienen cabinas
> + diff_link_price = contract_obj.get_differential_link_price(cr, uid, order.contract_id.id, product_sim_id, product_link_id)
> +
> + num_cabins = 0 # Los enlace no tienen cabinas
> price_unit = fixed_link_price or bom_line.product_id.list_price
> - discount = differential_link_price or 0
> + discount = diff_link_price or 0
>
> # Cualquier otro producto dentro del pack
> else:
> num_cabins = 0
> price_unit = bom_line.product_id.list_price
> discount = 0
> -
> - #Destinatario de venta del producto
> +
> + # Destinatario de venta del producto
> receiver = sale_line_obj.get_receiver(bom_line.product_id, order.contract_id, order.partner_id, line.receiver)
> -
> - #Creamos nueva linea de pedido
> +
> + # Creamos nueva linea de pedido
> default_val = {
> 'product_id': bom_line.product_id.id,
> 'name': '[' + (bom_line.product_id.default_code or '') + '] ' + (bom_line.product_id.name or ''),
> @@ -210,150 +245,145 @@
> 'discount': discount,
> 'pack_product_id': line.product_id.id,
> 'pack_prodlot_id': line.prodlot_id.id,
> - }
> -
> - line_id = sale_line_obj.copy(cr, uid, line.id, default_val, context={})
> -
> -
> - #Creamos nueva linea de albarán interno
> + }
> +
> + line_id = sale_line_obj.copy(cr, uid, line.id, default_val, context=context)
> +
> + # Creamos nueva linea de albarán interno
> location_id = self._get_bom_stock_location_dest(cr, uid, order.shop_id.warehouse_id, line.prodlot_id.id, bom_line.product_id.id)
> -
> +
> vals = {
> - 'picking_id': stock_picking_id,
> - 'product_id': bom_line.product_id.id,
> - 'name': '[' + (bom_line.product_id.default_code or '') + '] ' + (bom_line.product_id.name or ''),
> - 'prodlot_id': prodlot_id,
> - 'product_qty': 1,
> - 'product_uos_qty': 1,
> - 'product_uom': bom_line.product_id.uom_id and bom_line.product_id.uom_id.id or False,
> - 'location_id': location_id,
> - 'location_dest_id': order.shop_id.warehouse_id.lot_stock_id.id,
> - 'date_expected': time.strftime('%Y-%m-%d %H:%M:%S'),
> - 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
> - 'auto_validate': False,
> - 'priority': '1',
> - 'state': 'done',
> + 'picking_id': stock_picking_id,
> + 'product_id': bom_line.product_id.id,
> + 'name': '[' + (bom_line.product_id.default_code or '') + '] ' + (bom_line.product_id.name or ''),
> + 'prodlot_id': prodlot_id,
> + 'product_qty': 1,
> + 'product_uos_qty': 1,
> + 'product_uom': bom_line.product_id.uom_id and bom_line.product_id.uom_id.id or False,
> + 'location_id': location_id,
> + 'location_dest_id': order.shop_id.warehouse_id.lot_stock_id.id,
> + 'date_expected': time.strftime('%Y-%m-%d %H:%M:%S'),
> + 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
> + 'auto_validate': False,
> + 'priority': '1',
> + 'state': 'done',
> }
> -
> - stock_move_id = stock_move_obj.create(cr, uid, vals)
> -
> +
> + stock_move_id = move_obj.create(cr, uid, vals)
> +
> delete = True
> -
> +
> if delete:
> #Creamos linea de salida de pack en albarán interno
> vals = {
> - 'picking_id': stock_picking_id,
> - 'product_id': line.product_id.id,
> - 'name': '[' + (line.product_id.default_code or '') + '] ' + (line.product_id.name or ''),
> - 'prodlot_id': line.prodlot_id.id,
> - 'product_qty': 1,
> - 'product_uos_qty': 1,
> - 'product_uom': line.product_id.uom_id and line.product_id.uom_id.id or False,
> - 'location_id': order.shop_id.warehouse_id.lot_stock_id.id,
> - 'location_dest_id': order.shop_id.warehouse_id.lot_customer_out_id.id,
> - 'date_expected': time.strftime('%Y-%m-%d %H:%M:%S'),
> - 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
> - 'auto_validate': False,
> - 'priority': '1',
> - 'state': 'done',
> + 'picking_id': stock_picking_id,
> + 'product_id': line.product_id.id,
> + 'name': '[' + (line.product_id.default_code or '') + '] ' + (line.product_id.name or ''),
> + 'prodlot_id': line.prodlot_id.id,
> + 'product_qty': 1,
> + 'product_uos_qty': 1,
> + 'product_uom': line.product_id.uom_id and line.product_id.uom_id.id or False,
> + 'location_id': order.shop_id.warehouse_id.lot_stock_id.id,
> + 'location_dest_id': order.shop_id.warehouse_id.lot_customer_out_id.id,
> + 'date_expected': time.strftime('%Y-%m-%d %H:%M:%S'),
> + 'date': time.strftime('%Y-%m-%d %H:%M:%S'),
> + 'auto_validate': False,
> + 'priority': '1',
> + 'state': 'done',
> }
> -
> - stock_move_id = stock_move_obj.create(cr, uid, vals)
> -
> - #Borramos linea origen (Pack)
> - sale_line_obj.write(cr, uid, [line.id], {'state': 'draft'}, context={})
> - sale_line_obj.unlink(cr, uid, [line.id], context={})
> -
> +
> + stock_move_id = move_obj.create(cr, uid, vals)
> +
> + # Borramos linea origen (Pack)
> + sale_line_obj.write(cr, uid, [line.id], {'state': 'draft'}, context=context)
> + sale_line_obj.unlink(cr, uid, [line.id], context=context)
> +
> #Validamos albaran interno
> stock_picking_obj.write(cr, uid, [stock_picking_id], {'state': 'done'})
> -
> -
> - result = super(sale_order, self).action_ship_create(cr, uid, ids, *args)
> -
> -
> - for order in self.browse(cr, uid, ids, context={}):
> +
> + result = super(SaleOrder, self).action_ship_create(cr, uid, ids, *args)
> +
> + for order in self.browse(cr, uid, ids, context=context):
> if order.order_line:
> # Obtenemos secuencia siguiente para el número de envio
> # Todos los anexos creados de este pedido tendrán el mismo núm. de envio
> - num_annexe_ship = self.pool.get('ir.sequence').get(cr, uid, 'contract.annexe.ship')
> -
> + num_annexe_ship = self.pool['ir.sequence'].get(
> + cr, uid, 'contract.annexe.ship')
> +
> for line in order.order_line:
> - #No dejamos receptor en blanco nunca, obtenemos valor de los contratos o por defecto al cliente.
> + # No dejamos receptor en blanco nunca, obtenemos valor de los contratos o por defecto al cliente.
> receiver = line.receiver
> -
> +
> if not receiver:
> receiver = sale_line_obj.get_receiver(line.product_id, order.contract_id, order.partner_id)
> # Actualizamos valor de receptor en la linea si es necesario
> - sale_line_obj.write(cr, uid, [line.id], {'receiver': receiver}, context={})
> -
> - #Asignamos lotes de produccion de las lineas a los movimientos de stock creados
> - move_ids = stock_move_obj.search(cr, uid, [("sale_line_id", "=", line.id)])
> - stock_move_obj.write(cr, uid, move_ids, {'prodlot_id': line.prodlot_id.id,
> - 'contract_id': order.contract_id and order.contract_id.id or False,
> - 'num_cabins': line.num_cabins,
> - 'receiver': receiver }, context={})
> -
> - #Creamos un anexo por cada linea de pedido
> + sale_line_obj.write(cr, uid, [line.id], {'receiver': receiver}, context=context)
> +
> + # Asignamos lotes de produccion de las lineas a los movimientos de stock creados
> + move_ids = move_obj.search(cr, uid, [("sale_line_id", "=", line.id)])
> + move_obj.write(cr, uid, move_ids, {'prodlot_id': line.prodlot_id.id,
> + 'contract_id': order.contract_id and order.contract_id.id or False,
> + 'num_cabins': line.num_cabins,
> + 'receiver': receiver}, context=context)
> +
> + # Creamos un anexo por cada linea de pedido
> if order.contract_id:
> product_id = production_lot_id = product_2_id = production_lot_2_id = False
> - pack_product_id = pack_production_lot_id = False
> -
> + pack_product_id = pack_production_lot_id = False
> +
> if product_obj._is_sim(line.product_id.categ_id):
> product_id = line.product_id.id
> production_lot_id = line.prodlot_id.id
> elif product_obj._is_link(line.product_id.categ_id):
> product_2_id = line.product_id.id
> production_lot_2_id = line.prodlot_id.id
> -
> +
> if (product_id or product_2_id) and line.pack_product_id and line.pack_prodlot_id:
> pack_product_id = line.pack_product_id.id
> pack_production_lot_id = line.pack_prodlot_id.id
> -
> +
> #Comprobamos si existe anexo creado para pack
> - annexe_ids = annexe_obj.search(cr, uid, [("pack_product_id", "=", pack_product_id),
> + annexe_ids = annexe_obj.search(cr, uid, [("pack_product_id", "=", pack_product_id),
> ("pack_production_lot_id", "=", pack_production_lot_id),
> ("active_annexe", "=", True),
> ])
> annexe_id = annexe_ids and annexe_ids[0] or False
> -
> +
> if annexe_id:
> -
> - annexe = annexe_obj.browse(cr, uid, annexe_id , context={})
> -
> +
> + annexe = annexe_obj.browse(cr, uid, annexe_id, context=context)
> +
> hist_annexe_ids = hist_annexe_obj.search(cr, uid, [("contract_annexe_id", "=", annexe_id)])
> -
> +
> if product_id and production_lot_id:
> -
> product_2_id = annexe.product_2_id.id
> -
> +
> vals = {
> 'product_id': product_id,
> 'production_lot_id': production_lot_id,
> - 'phone': line.prodlot_id.telefono,
> - 'num_cabins': line.num_cabins,
> + 'phone': line.prodlot_id.telefono,
> + 'num_cabins': line.num_cabins,
> }
> -
> +
> vals_hist = {
> - 'production_lot_id': production_lot_id,
> + 'production_lot_id': production_lot_id,
> 'phone': line.prodlot_id.telefono,
> 'num_cabins': line.num_cabins,
> }
> -
> -
> +
> elif product_2_id and production_lot_2_id:
> -
> product_id = annexe.product_2_id.id
> -
> +
> vals = {
> 'product_2_id': product_2_id,
> - 'production_lot_2_id': production_lot_2_id,
> + 'production_lot_2_id': production_lot_2_id,
> }
> -
> +
> vals_hist = {
> - 'production_lot_2_id': production_lot_2_id
> + 'production_lot_2_id': production_lot_2_id
> }
> -
> - #Actualizamos precios
> +
> + # Actualizamos precios
> fixed_price = contract_obj.get_fixed_price(cr, uid, order.contract_id.id, product_id, product_2_id)
> differential_price = contract_obj.get_differential_price(cr, uid, order.contract_id.id, product_id, product_2_id)
> extra_cabin_price = contract_obj.get_extra_cabin_price(cr, uid, order.contract_id.id, product_id, product_2_id)
> @@ -361,130 +391,154 @@
> differential_commission = contract_obj.get_differential_commission(cr, uid, order.contract_id.id, product_id, product_2_id)
>
> vals_prices = {
> - 'fixed_price': fixed_price,
> - 'differential_price': differential_price,
> - 'extra_cabin_price': extra_cabin_price,
> - 'fixed_commission': fixed_commission,
> - 'differential_commission': differential_commission,
> + 'fixed_price': fixed_price,
> + 'differential_price': differential_price,
> + 'extra_cabin_price': extra_cabin_price,
> + 'fixed_commission': fixed_commission,
> + 'differential_commission': differential_commission,
> }
>
> vals_hist = dict(vals_hist.items() + vals_prices.items())
> vals = dict(vals.items() + vals_prices.items())
> -
> - #Actualizamos historico de anexo del pack con la informacion restante
> - hist_annexe_obj.write(cr, uid, hist_annexe_ids, vals_hist, context={})
> -
> - #Actualizamos anexo del pack
> - annexe_obj.write(cr, uid, [annexe_id], vals, {'historical':False})
> -
> - #Relacionamos movimiento con anexo
> - stock_move_obj.write(cr, uid, move_ids, {'contract_annexe_id': annexe_id }, context={})
> -
> +
> + # Actualizamos historico de anexo del pack con la informacion restante
> + hist_annexe_obj.write(cr, uid, hist_annexe_ids, vals_hist, context=context)
> +
> + # Actualizamos anexo del pack
> + annexe_obj.write(cr, uid, [annexe_id], vals, {'historical': False})
{'historical': False} no es el context?
> +
> + # Relacionamos movimiento con anexo
> + move_obj.write(cr, uid, move_ids, {'contract_annexe_id': annexe_id}, context=context)
> +
> continue
> -
> +
> # Creamos anexo si el producto de la linea es de tipo SIM o tipo Pack
> if (product_id and production_lot_id) or (product_2_id and production_lot_2_id and pack_product_id and pack_production_lot_id):
> -
> +
> current_date = time.strftime('%Y-%m-%d')
> -
> - #Fecha inicio cobro es igual a la fecha actual mas 4 dias
> - start_billing_date = datetime.strptime(current_date, '%Y-%m-%d') + relativedelta(days=+order.contract_id.start_billing_days)
> -
> - fixed_price = contract_obj.get_fixed_price(cr, uid, order.contract_id.id, product_id, product_2_id)
> +
> + # Fecha inicio cobro es igual a la fecha actual más 4 dias
> + start_billing_date = (datetime.strptime(current_date, '%Y-%m-%d') +
> + relativedelta(days=+order.contract_id.start_billing_days))
> +
> + fixed_price = contract_obj.get_fixed_price(
> + cr, uid, order.contract_id.id, product_id,
> + product_2_id)
> differential_price = contract_obj.get_differential_price(cr, uid, order.contract_id.id, product_id, product_2_id)
> extra_cabin_price = contract_obj.get_extra_cabin_price(cr, uid, order.contract_id.id, product_id, product_2_id)
> fixed_commission = contract_obj.get_fixed_commission(cr, uid, order.contract_id.id, product_id, product_2_id)
> differential_commission = contract_obj.get_differential_commission(cr, uid, order.contract_id.id, product_id, product_2_id)
> -
> +
> vals = {
> - 'name': '',
> - 'num_annexe_ship': num_annexe_ship,
> - 'contract_id': order.contract_id.id,
> - 'sale_order_id': order.id,
> - 'stock_move_id': move_ids and move_ids[0] or False,
> - 'invoice_line_id': False,
> - 'annexe_date': current_date,
> - 'shipping_date': current_date,
> - 'start_billing_date': start_billing_date.strftime('%Y-%m-%d'),
> - #'expiration_date': start_billing_date.strftime('%Y-%m-%d'),
> - 'expiration_date': False,
> - 'closing_date': False,
> - 'fixed_price': fixed_price,
> - 'differential_price': differential_price,
> - 'extra_cabin_price': extra_cabin_price,
> - 'fixed_commission': fixed_commission,
> - 'differential_commission': differential_commission,
> - 'product_id': product_id,
> - 'production_lot_id': production_lot_id,
> - 'phone': line.prodlot_id.telefono,
> - 'product_2_id': product_2_id,
> - 'production_lot_2_id': production_lot_2_id,
> - 'pack_product_id': pack_product_id,
> - 'pack_production_lot_id': pack_production_lot_id,
> - 'user_id': order.user_id and order.user_id.id or False,
> - 'num_cabins': line.num_cabins,
> - 'active_annexe': True,
> - 'state': True,
> - 'customer_ref': line.client_order_ref or order.client_order_ref,
> - 'comments': '',
> + 'name': '',
> + 'num_annexe_ship': num_annexe_ship,
> + 'contract_id': order.contract_id.id,
> + 'sale_order_id': order.id,
> + 'stock_move_id': move_ids and move_ids[0] or False,
> + 'invoice_line_id': False,
> + 'annexe_date': current_date,
> + 'shipping_date': current_date,
> + 'start_billing_date': start_billing_date.strftime('%Y-%m-%d'),
> + 'expiration_date': False,
> + 'closing_date': False,
> + 'fixed_price': fixed_price,
> + 'differential_price': differential_price,
> + 'extra_cabin_price': extra_cabin_price,
> + 'fixed_commission': fixed_commission,
> + 'differential_commission': differential_commission,
> + 'product_id': product_id,
> + 'production_lot_id': production_lot_id,
> + 'phone': line.prodlot_id.telefono,
> + 'product_2_id': product_2_id,
> + 'production_lot_2_id': production_lot_2_id,
> + 'pack_product_id': pack_product_id,
> + 'pack_production_lot_id': pack_production_lot_id,
> + 'user_id': (order.user_id and
> + order.user_id.id or False),
> + 'num_cabins': line.num_cabins,
> + 'active_annexe': True,
> + 'state': True,
> + 'customer_ref': (line.client_order_ref or
> + order.client_order_ref),
> + 'comments': '',
> }
> -
> +
> annexe_id = annexe_obj.create(cr, uid, vals)
> -
> - #Creamos precios por mensualidad heredados del contrato
> - for price_list in order.contract_id.contract_price_ids:
> +
> + # Creamos precios por mensualidad heredados del
> + # contrato
> + price_ids = order.contract_id.contract_price_ids
> + for price_list in price_ids:
> fixed_price = price_list.fixed_price
> num_months = price_list.months
> - date_aux = datetime.strptime(current_date, '%Y-%m-%d') + relativedelta(months=num_months)
> + date_aux = (datetime.strptime(current_date,
> + '%Y-%m-%d') +
> + relativedelta(months=num_months))
> expiration_date = date_aux.strftime('%Y-%m-%d')
> -
> - annexe_prices_obj.create(cr, uid, {'contract_annexe_id': annexe_id,
> - 'fixed_price': fixed_price,
> - 'expiration_date': expiration_date})
> -
> -
> - #Relacionamos movimiento con anexo
> - stock_move_obj.write(cr, uid, move_ids, {'contract_annexe_id': annexe_id }, context={})
> -
> +
> + annexe_prices_obj.create(
> + cr, uid, {'contract_annexe_id': annexe_id,
> + 'fixed_price': fixed_price,
> + 'expiration_date':
> + expiration_date},
> + context=context)
> +
> + # Relacionamos movimiento con anexo
> + move_obj.write(cr, uid, move_ids,
> + {'contract_annexe_id': annexe_id},
> + context=context)
> +
> return result
> -
> -
> - def action_invoice_create(self, cr, uid, ids, grouped=False, states=['confirmed', 'done', 'exception'], date_inv = False, context=None):
> - #Comprobamos que todos los production tienen asignado un lote de produccion
> - for order in self.browse(cr, uid, ids, context={}):
> +
> + def action_invoice_create(self, cr, uid, ids, grouped=False,
> + states=['confirmed', 'done', 'exception'],
> + date_inv=False, context=None):
> + # Comprobamos que todos los production tienen asignado un lote de
> + # produccion
> + for order in self.browse(cr, uid, ids, context=context):
> for line in order.order_line:
> - if (not line.prodlot_id or line.product_uom_qty > 1) and line.product_id.type == 'product':
> - raise osv.except_osv(_('Product Lots not defined !'), _('Need to assign a lot of production for each product in the sales order.'))
> -
> - invoice_id = super(sale_order, self).action_invoice_create(cr, uid, ids, grouped=grouped, states=states, date_inv = date_inv, context=context)
> - annexe_obj = self.pool.get('contract.annexe')
> - for order in self.browse(cr, uid, ids, context=context):
> - if order.contract_id:
> - #Creamos un anexo por cada pedido
> - print "crear anexo"
> + if ((not line.prodlot_id or line.product_uom_qty > 1) and
> + line.product_id.type == 'product'):
> + raise orm.except_orm(
> + _('Product Lots not defined !'),
> + _('Need to assign a lot of production for each product'
> + ' in the sales order.'))
> +
> + invoice_id = super(SaleOrder,
> + self).action_invoice_create(
> + cr, uid, ids, grouped=grouped, states=states, date_inv=date_inv,
> + context=context)
> +# annexe_obj = self.pool['contract.annexe']
> +# for order in self.browse(cr, uid, ids, context=context):
> +# if order.contract_id:
> +# # Creamos un anexo por cada pedido
> +# print "crear anexo"
> return invoice_id
> -
> -sale_order()
> -
> -
> -class sale_order_line(osv.osv):
> -
> - _name = 'sale.order.line'
> +
> +
> +class SaleOrderLine(orm.Model):
> _inherit = 'sale.order.line'
> -
> +
> _columns = {
> - 'num_cabins' : fields.integer('Num. Cabins'),
> - 'receiver' : fields.selection([('cliente', 'Cliente'), ('ascensorista', 'Ascensorista')], 'Receiver', select=True),
> - 'prodlot_id' : fields.many2one('stock.production.lot', 'Production Lot', readonly=True, states={'draft': [('readonly', False)]}, help="Production lot is used to put a serial number on the production", select=True),
> - 'pack_product_id': fields.many2one('product.product', 'Product', select=True),
> - 'pack_prodlot_id' : fields.many2one('stock.production.lot', 'Pack Production Lot', select=True),
> + 'num_cabins': fields.integer('Num. Cabins'),
> + 'receiver': fields.selection([('cliente', 'Cliente'),
> + ('ascensorista', 'Ascensorista')],
> + 'Receiver', select=True),
> + 'prodlot_id': fields.many2one('stock.production.lot', 'Production Lot',
> + readonly=True, select=True,
> + states={'draft': [('readonly', False)]},
> + help="Production lot is used to put a"
> + " serial number on the production"),
> + 'pack_product_id': fields.many2one('product.product', 'Product',
> + select=True),
> + 'pack_prodlot_id': fields.many2one('stock.production.lot',
> + 'Pack Production Lot', select=True),
> 'client_order_ref': fields.char('Customer Reference', size=64),
> }
> -
> +
> _defaults = {
> 'num_cabins': 1,
> }
> -
>
> def _find_receiver(self, category_prod, info):
> if not category_prod:
> @@ -494,254 +548,328 @@
> return info.receiver
> else:
> return self._find_receiver(category_prod.parent_id, info)
> -
> -
> +
> def _is_rented(self, product, contract):
> -
> - product_obj = self.pool.get('product.product')
> -
> + product_obj = self.pool['product.product']
> +
> if product_obj._is_sim(product.categ_id):
> return True
> -
> +
> return (contract.sale_type == "alquiler")
> -
> -
> +
> def get_receiver(self, product, contract, partner, receiver=False):
> -
> if contract and contract.info_invoice_ids:
> for info in contract.info_invoice_ids:
> receiver = self._find_receiver(product.categ_id, info)
> if receiver:
> break
> -
> +
> if not receiver and partner and partner.info_invoice_ids:
> for info in partner.info_invoice_ids:
> receiver = self._find_receiver(product.categ_id, info)
> if receiver:
> break
> -
> - if not receiver and contract and contract.elevator_id and contract.elevator_id.info_invoice_ids:
> +
> + if (not receiver and contract and contract.elevator_id and
> + contract.elevator_id.info_invoice_ids):
> for info in contract.elevator_id.info_invoice_ids:
> receiver = self._find_receiver(product.categ_id, info)
> if receiver:
> break
> -
> +
> if not receiver:
> receiver = 'cliente'
> -
> +
> return receiver
> -
> -
> - def get_product_price(self, cr, uid, product, contract, num_cabins=0, rented=False, price_unit=0, discount=0):
> -
> - product_obj = self.pool.get('product.product')
> - contract_obj = self.pool.get('contract.contract')
> -
> +
> + def get_product_price(self, cr, uid, product, contract, num_cabins=0,
> + rented=False, price_unit=0, discount=0):
> + product_obj = self.pool['product.product']
> + contract_obj = self.pool['contract.contract']
> +
> # Precio producto si es una sim
> if product_obj._is_sim(product.categ_id):
> - #Obtenemos precios segun reglas definidas
> - fixed_price = contract_obj.get_fixed_price(cr, uid, contract.id, product.id)
> - extra_cabin_price = contract_obj.get_extra_cabin_price(cr, uid, contract.id, product.id)
> - differential_price = contract_obj.get_differential_price(cr, uid, contract.id, product.id)
> -
> - price_cabins = num_cabins > 1 and ((num_cabins - 1) * extra_cabin_price) or 0
> + # Obtenemos precios segun reglas definidas
> + fixed_price = contract_obj.get_fixed_price(
> + cr, uid, contract.id, product.id)
> + extra_cabin_price = contract_obj.get_extra_cabin_price(
> + cr, uid, contract.id, product.id)
> + differential_price = contract_obj.get_differential_price(
> + cr, uid, contract.id, product.id)
> +
> + price_cabins = (num_cabins > 1 and
> + ((num_cabins - 1) * extra_cabin_price) or 0)
> price_unit = fixed_price + price_cabins
> discount = differential_price or 0
> -
> +
> # Precio producto si es un enlace
> elif product_obj._is_link(product.categ_id):
> - #Obtenemos precios segun reglas definidas
> - fixed_link_price = contract_obj.get_fixed_link_price(cr, uid, contract.id, None, product.id)
> - differential_link_price = contract_obj.get_differential_link_price(cr, uid, contract.id, None, product.id)
> -
> + # Obtenemos precios segun reglas definidas
> + fixed_link_price = contract_obj.get_fixed_link_price(
> + cr, uid, contract.id, None, product.id)
> + differential_link_price = contract_obj.get_differential_link_price(
> + cr, uid, contract.id, None, product.id)
> +
> price_unit = fixed_link_price or product.list_price
> -
> +
> # El tipo de venta no es un requisito para aplicar el descuento
> # discount = rented and differential_link_price or 0
> discount = differential_link_price or 0
> -
> +
> # Precio producto si es un pack
> elif product_obj._is_pack(product.categ_id):
> -
> - product_sim_id, product_link_id = product_obj.pack_components(product)
> -
> - #Obtenemos precios segun reglas definidas
> - fixed_price = contract_obj.get_fixed_price(cr, uid, contract.id, product_sim_id, product_link_id)
> - extra_cabin_price = contract_obj.get_extra_cabin_price(cr, uid, contract.id, product_sim_id, product_link_id)
> - differential_price = contract_obj.get_differential_price(cr, uid, contract.id, product_sim_id, product_link_id)
> - fixed_link_price = contract_obj.get_fixed_link_price(cr, uid, contract.id, product_sim_id, product_link_id)
> - differential_link_price = contract_obj.get_differential_link_price(cr, uid, contract.id, product_sim_id, product_link_id)
> -
> - price_cabins = num_cabins > 1 and ((num_cabins - 1) * extra_cabin_price) or 0
> + product_sim_id, product_link_id = product_obj.pack_components(
> + product)
> +
> + # Obtenemos precios segun reglas definidas
> + fixed_price = contract_obj.get_fixed_price(
> + cr, uid, contract.id, product_sim_id, product_link_id)
> + extra_cabin_price = contract_obj.get_extra_cabin_price(
> + cr, uid, contract.id, product_sim_id, product_link_id)
> + differential_price = contract_obj.get_differential_price(
> + cr, uid, contract.id, product_sim_id, product_link_id)
> + fixed_link_price = contract_obj.get_fixed_link_price(
> + cr, uid, contract.id, product_sim_id, product_link_id)
> + differential_link_price = contract_obj.get_differential_link_price(
> + cr, uid, contract.id, product_sim_id, product_link_id)
> +
> + price_cabins = (num_cabins > 1 and
> + ((num_cabins - 1) * extra_cabin_price) or 0)
> price_sim = fixed_price + price_cabins
> price_sim = price_sim - (price_sim * differential_price / 100)
> -
> +
> price_link = fixed_link_price or product.list_price
> -
> +
> # El tipo de venta no es un requisito para aplicar el descuento
> # if rented:
> - price_link = price_link - (price_link * differential_link_price / 100)
> -
> + price_link = (price_link -
> + (price_link * differential_link_price / 100))
> +
> price_unit = price_sim + price_link
> discount = 0
> -
> +
> return price_unit, discount
> -
> -
> - def sale_line_change(self, cr, uid, product_id, contract_id, prodlot_id=False, num_cabins=0, price_unit=0, receiver=False, rented=False, discount=False):
> -
> +
> + def sale_line_change(self, cr, uid, product_id, contract_id,
> + prodlot_id=False, num_cabins=0, price_unit=0,
> + receiver=False, rented=False, discount=False):
> +
> if contract_id and product_id:
> - product_obj = self.pool.get('product.product')
> - contract_obj = self.pool.get('contract.contract')
> - prodlot_obj = self.pool.get('stock.production.lot')
> -
> + product_obj = self.pool['product.product']
> + contract_obj = self.pool['contract.contract']
> + prodlot_obj = self.pool['stock.production.lot']
> +
> product = product_obj.browse(cr, uid, product_id)
> contract = contract_obj.browse(cr, uid, contract_id)
> -
> +
> rented = self._is_rented(product, contract)
> discount = rented and product.discount or False
> -
> - price_unit, discount = self.get_product_price(cr, uid, product, contract, num_cabins, rented, price_unit, discount)
> -
> - # Por defecto no asignamos ningún receptor,
> +
> + price_unit, discount = self.get_product_price(
> + cr, uid, product, contract, num_cabins, rented, price_unit,
> + discount)
> +
> + # Por defecto no asignamos ningún receptor,
> # que lo especifique el usuario
> # ó
> # lo obtenga de los valores definidos en contrato o cliente
> - receiver = False #self.get_receiver(product, contract, receiver)
> -
> - # Si el producto es distinto del producto del lote de producción, quitamos lote
> + receiver = False # self.get_receiver(product, contract, receiver)
> +
> + # Si el producto es distinto del producto del lote de producción,
> + # quitamos lote
> if prodlot_id:
> prodlot = prodlot_obj.browse(cr, uid, prodlot_id)
> -
> - if prodlot and prodlot.product_id and (prodlot.product_id.id != product_id):
> +
> + if (prodlot and prodlot.product_id and
> + (prodlot.product_id.id != product_id)):
> prodlot_id = False
> -
> +
> # Número de cabinas 0 si es un enlace
> if product_obj._is_link(product.categ_id):
> num_cabins = 0
> -
> +
> return prodlot_id, num_cabins, price_unit, receiver, rented, discount
>
> -
> - def product_uom_change_inherit(self, cursor, user, ids, pricelist, product, contract_id=False, prodlot_id=False, num_cabins=0, qty=0,
> - uom=False, qty_uos=0, uos=False, name='', partner_id=False,
> - lang=False, update_tax=True, date_order=False):
> -
> - res = self.product_id_change_inherit(cursor, user, ids, pricelist, product, contract_id=contract_id, prodlot_id=prodlot_id, num_cabins=num_cabins,
> - qty=qty, uom=uom, qty_uos=qty_uos, uos=uos, name=name,
> - partner_id=partner_id, lang=lang, update_tax=update_tax,
> - date_order=date_order)
> -
> + def product_uom_change_inherit(
> + self, cr, user, ids, pricelist, product, contract_id=False,
> + prodlot_id=False, num_cabins=0, qty=0, uom=False, qty_uos=0,
> + uos=False, name='', partner_id=False, lang=False, update_tax=True,
> + date_order=False):
> +
> + res = self.product_id_change_inherit(
> + cr, user, ids, pricelist, product, contract_id=contract_id,
> + prodlot_id=prodlot_id, num_cabins=num_cabins, qty=qty, uom=uom,
> + qty_uos=qty_uos, uos=uos, name=name, partner_id=partner_id,
> + lang=lang, update_tax=update_tax, date_order=date_order)
> +
> if 'product_uom' in res['value']:
> del res['value']['product_uom']
> -
> +
> if not uom:
> res['value']['price_unit'] = 0.0
> -
> +
> return res
> -
> -
> - def product_id_change_inherit(self, cr, uid, ids, pricelist, product, contract_id=False, prodlot_id=False, num_cabins=0, qty=0,
> - uom=False, qty_uos=0, uos=False, name='', partner_id=False,
> - lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False):
> -
> - res = super(sale_order_line, self).product_id_change(cr, uid, ids, pricelist, product, qty, uom, qty_uos, uos, name, partner_id, lang, update_tax, date_order, packaging, fiscal_position, flag)
> -
> - price_unit = res.has_key('value') and res['value'].has_key('price_unit') and res['value']['price_unit'] or False
> -
> - prodlot_id, num_cabins, price_unit, receiver, rented, discount = self.sale_line_change(cr, uid, product, contract_id, prodlot_id=prodlot_id, num_cabins=num_cabins, price_unit=price_unit, receiver=False, rented=False, discount=False)
> -
> - res['value']['num_cabins'] = num_cabins
> +
> + def product_id_change_inherit(
> + self, cr, uid, ids, pricelist, product, contract_id=False,
> + prodlot_id=False, num_cabins=0, qty=0, uom=False, qty_uos=0,
> + uos=False, name='', partner_id=False, lang=False, update_tax=True,
> + date_order=False, packaging=False, fiscal_position=False,
> + flag=False):
> +
> + res = super(SaleOrderLine,
> + self).product_id_change(cr, uid, ids, pricelist, product,
> + qty, uom, qty_uos, uos, name,
> + partner_id, lang, update_tax,
> + date_order, packaging,
> + fiscal_position, flag)
> +
> + price_unit = ('value' in res and 'price_unit' in res['value'] and
> + res['value']['price_unit'] or 0)
> +
> + (prodlot_id, num_cabins, price_unit, receiver, rented,
> + discount) = self.sale_line_change(
> + cr, uid, product, contract_id, prodlot_id=prodlot_id,
> + num_cabins=num_cabins, price_unit=price_unit, receiver=False,
> + rented=False, discount=False)
> +
> + res['value']['num_cabins'] = num_cabins
> res['value']['receiver'] = receiver
> res['value']['rented'] = rented
> res['value']['price_unit'] = price_unit
> res['value']['discount'] = discount
> res['value']['prodlot_id'] = prodlot_id
> -
> +
> # Definimos dominios
> if product:
> - res['domain']['prodlot_id'] = [('product_id','=',product), ('stock_available', '>', 0)]
> + res['domain']['prodlot_id'] = [('product_id', '=', product),
> + ('stock_available', '>', 0)]
> else:
> res['domain']['prodlot_id'] = [('stock_available', '>', 0)]
>
> -
> - return res
> -
> - def prodlot_id_change_inherit(self, cr, uid, ids, pricelist, prodlot_id, product=False, contract_id=False, num_cabins=0, qty=0,
> - uom=False, qty_uos=0, uos=False, name='', partner_id=False,
> - lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False):
> -
> + return res
> +
> + def prodlot_id_change_inherit(
> + self, cr, uid, ids, pricelist, prodlot_id, product=False,
> + contract_id=False, num_cabins=0, qty=0, uom=False, qty_uos=0,
> + uos=False, name='', partner_id=False, lang=False, update_tax=True,
> + date_order=False, packaging=False, fiscal_position=False,
> + flag=False):
> +
> res = []
> -
> +
> if prodlot_id and not product:
> -
> - prodlot_obj = self.pool.get('stock.production.lot')
> +
> + prodlot_obj = self.pool['stock.production.lot']
> prodlot = prodlot_obj.browse(cr, uid, prodlot_id)
> -
> +
> if prodlot and prodlot.product_id:
> -
> +
> product = prodlot.product_id.id
> -
> - res = super(sale_order_line, self).product_id_change(cr, uid, ids, pricelist, product, qty, uom, qty_uos, uos, name, partner_id, lang, update_tax, date_order, packaging, fiscal_position, flag)
> -
> - price_unit = res.has_key('value') and res['value'].has_key('price_unit') and res['value']['price_unit'] or False
> -
> - prodlot_id, num_cabins, price_unit, receiver, rented, discount = self.sale_line_change(cr, uid, product, contract_id, prodlot_id=prodlot_id, num_cabins=num_cabins, price_unit=price_unit, receiver=False, rented=False, discount=False)
> -
> - res['value']['product_id'] = product
> - res['value']['num_cabins'] = num_cabins
> +
> + res = super(SaleOrderLine,
> + self).product_id_change(cr, uid, ids, pricelist,
> + product, qty, uom, qty_uos,
> + uos, name, partner_id,
> + lang, update_tax,
> + date_order, packaging,
> + fiscal_position, flag)
> +
> + price_unit = ('value' in res and 'price_unit' in res['value']
> + and res['value']['price_unit'] or 0)
> +
> + (prodlot_id, num_cabins, price_unit, receiver, rented,
> + discount) = self.sale_line_change(
> + cr, uid, product, contract_id, prodlot_id=prodlot_id,
> + num_cabins=num_cabins, price_unit=price_unit,
> + receiver=False, rented=False, discount=False)
> +
> + res['value']['product_id'] = product
> + res['value']['num_cabins'] = num_cabins
> res['value']['receiver'] = receiver
> res['value']['rented'] = rented
> res['value']['price_unit'] = price_unit
> res['value']['discount'] = discount
> -
> +
> # Definimos dominios
> if product:
> - res['domain']['prodlot_id'] = [('product_id','=',product), ('stock_available', '>', 0)]
> + res['domain']['prodlot_id'] = [('product_id', '=',
> + product),
> + ('stock_available', '>', 0)]
> else:
> res['domain']['prodlot_id'] = [('stock_available', '>', 0)]
>
> - return res
> -
> - def sale_group_type_change(self, cr, uid, ids, sale_group_type, pricelist, product, contract_id=False, prodlot_id=False, num_cabins=0, qty=0,
> - uom=False, qty_uos=0, uos=False, name='', partner_id=False,
> - lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False):
> -
> - res = super(sale_order_line, self).sale_group_type_change(cr, uid, ids, sale_group_type, pricelist, product, contract_id, prodlot_id, num_cabins, qty, uom, qty_uos, uos, name, partner_id, lang, update_tax, date_order, packaging, fiscal_position, flag)
> -
> - price_unit = res.has_key('value') and res['value'].has_key('price_unit') and res['value']['price_unit'] or 0
> - product_id = res.has_key('value') and res['value'].has_key('product_id') and res['value']['product_id'] or product
> -
> - prodlot_id, num_cabins, price_unit, receiver, rented, discount = self.sale_line_change(cr, uid, product_id, contract_id, prodlot_id=prodlot_id, num_cabins=num_cabins, price_unit=price_unit, receiver=False, rented=False, discount=False)
> -
> - res['value']['num_cabins'] = num_cabins
> - res['value']['receiver'] = receiver
> - res['value']['rented'] = rented
> - res['value']['price_unit'] = price_unit
> - res['value']['discount'] = discount
> - res['value']['prodlot_id'] = prodlot_id
> -
> - return res
> -
> -
> - def sale_group_id_change(self, cr, uid, ids, sale_group_id, pricelist, product, contract_id=False, prodlot_id=False, num_cabins=0, qty=0,
> - uom=False, qty_uos=0, uos=False, name='', partner_id=False,
> - lang=False, update_tax=True, date_order=False, packaging=False, fiscal_position=False, flag=False):
> -
> - res = super(sale_order_line, self).sale_group_id_change(cr, uid, ids, sale_group_id, pricelist, product, contract_id, prodlot_id, num_cabins, qty, uom, qty_uos, uos, name, partner_id, lang, update_tax, date_order, packaging, fiscal_position, flag)
> -
> - price_unit = res.has_key('value') and res['value'].has_key('price_unit') and res['value']['price_unit'] or 0
> - product_id = res.has_key('value') and res['value'].has_key('product_id') and res['value']['product_id'] or product
> -
> - prodlot_id, num_cabins, price_unit, receiver, rented, discount = self.sale_line_change(cr, uid, product_id, contract_id, prodlot_id=prodlot_id, num_cabins=num_cabins, price_unit=price_unit, receiver=False, rented=False, discount=False)
> -
> - res['value']['num_cabins'] = num_cabins
> - res['value']['receiver'] = receiver
> - res['value']['rented'] = rented
> - res['value']['price_unit'] = price_unit
> - res['value']['discount'] = discount
> - res['value']['prodlot_id'] = prodlot_id
> -
> - return res
> -
> -sale_order_line()
> + return res
> +
> + def sale_group_type_change(
> + self, cr, uid, ids, sale_group_type, pricelist, product,
> + contract_id=False, prodlot_id=False, num_cabins=0, qty=0,
> + uom=False, qty_uos=0, uos=False, name='', partner_id=False,
> + lang=False, update_tax=True, date_order=False, packaging=False,
> + fiscal_position=False, flag=False):
> +
> + res = super(SaleOrderLine,
> + self).sale_group_type_change(cr, uid, ids, sale_group_type,
> + pricelist, product,
> + contract_id, prodlot_id,
> + num_cabins, qty, uom, qty_uos,
> + uos, name, partner_id, lang,
> + update_tax, date_order,
> + packaging, fiscal_position,
> + flag)
> +
> + price_unit = ('value' in res and 'price_unit' in res['value'] and
> + res['value']['price_unit'] or 0)
> + product_id = ('value' in res and 'product_id' in res['value'] and
> + res['value']['product_id'] or product)
> +
> + (prodlot_id, num_cabins, price_unit, receiver, rented,
> + discount) = self.sale_line_change(
> + cr, uid, product_id, contract_id, prodlot_id=prodlot_id,
> + num_cabins=num_cabins, price_unit=price_unit, receiver=False,
> + rented=False, discount=False)
> +
> + res['value']['num_cabins'] = num_cabins
> + res['value']['receiver'] = receiver
> + res['value']['rented'] = rented
> + res['value']['price_unit'] = price_unit
> + res['value']['discount'] = discount
> + res['value']['prodlot_id'] = prodlot_id
> +
> + return res
> +
> + def sale_group_id_change(
> + self, cr, uid, ids, sale_group_id, pricelist, product,
> + contract_id=False, prodlot_id=False, num_cabins=0, qty=0,
> + uom=False, qty_uos=0, uos=False, name='', partner_id=False,
> + lang=False, update_tax=True, date_order=False, packaging=False,
> + fiscal_position=False, flag=False):
> +
> + res = super(SaleOrderLine,
> + self).sale_group_id_change(cr, uid, ids, sale_group_id,
> + pricelist, product, contract_id,
> + prodlot_id, num_cabins, qty,
> + uom, qty_uos, uos, name,
> + partner_id, lang, update_tax,
> + date_order, packaging,
> + fiscal_position, flag)
> +
> + price_unit = ('value' in res and 'price_unit' in res['value'] and
> + res['value']['price_unit'] or 0)
> + product_id = ('value' in res and 'product_id' in res['value'] and
> + res['value']['product_id'] or product)
> +
> + (prodlot_id, num_cabins, price_unit, receiver, rented,
> + discount) = self.sale_line_change(
> + cr, uid, product_id, contract_id, prodlot_id=prodlot_id,
> + num_cabins=num_cabins, price_unit=price_unit, receiver=False,
> + rented=False, discount=False)
> +
> + res['value']['num_cabins'] = num_cabins
> + res['value']['receiver'] = receiver
> + res['value']['rented'] = rented
> + res['value']['price_unit'] = price_unit
> + res['value']['discount'] = discount
> + res['value']['prodlot_id'] = prodlot_id
> +
> + return res
>
> === renamed file 'dos_contracts/stock.py' => 'dos_contracts/models/stock.py'
> --- dos_contracts/stock.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/models/stock.py 2014-07-03 14:26:17 +0000
> @@ -19,318 +19,301 @@
> #
> ##############################################################################
>
> -
> -from osv import osv
> -from osv import fields
> -from tools.translate import _
> +from openerp.osv import orm, fields
> from datetime import datetime
> from dateutil.relativedelta import relativedelta
> import time
> import calendar
>
> -class stock_picking(osv.osv):
> -
> - _inherit ="stock.picking"
> -
> - _columns = {
> - 'contract_id': fields.many2one('contract.contract', 'Contract', readonly=True, states={'draft': [('readonly', False)]}, select=True),
> - 'contact_id': fields.many2one('res.partner.job', 'Contact', readonly=True, states={'draft': [('readonly', False)]}, help="The name and address of the contact who requested the picking."),
> - }
> -
> - def _max_annexe_expiration_date(self, cr, uid, partner_id):
> -
> - sql = " SELECT MAX(a.expiration_date) as expiration_date "
> - sql += "FROM contract_contract c "
> - sql += "INNER JOIN contract_annexe a ON c.id = a.contract_id "
> - sql += "WHERE c.customer_id = " + str(partner_id) + " "
> - sql += "AND c.active_contract=true AND a.active_annexe=true "
> -
> - cr.execute(sql)
> -
> - return cr.fetchone()[0]
> -
> -
> - def _get_start_billing_days(self, cr, uid, move_line):
> - return 4
> -
> -
> - def _invoice_line_hook(self, cr, uid, move_line, invoice_line_id):
> - '''Call after the creation of the invoice line'''
> - picking_obj = self.pool.get('stock.picking')
> - stock_move_obj = self.pool.get('stock.move')
> - invoice_line_obj = self.pool.get('account.invoice.line')
> - annexe_obj = self.pool.get('contract.annexe')
> - product_obj = self.pool.get('product.product')
> - mysql_obj = self.pool.get('mysql.connect')
> -
> - # Fecha albaran
> - str_picking_date = move_line.picking_id and move_line.picking_id.date and move_line.picking_id.date[0:10] or False
> -
> - # Número de dias desde la fecha de albaran para iniciar el cobro
> - start_billing_days = picking_obj._get_start_billing_days(cr, uid, move_line)
> -
> - # Fecha Inicio Cobro = A partir de 4 días de la fecha de albarán (Fecha Factura)
> - start_billing_date = datetime.strptime(str_picking_date, '%Y-%m-%d') + relativedelta(days=+start_billing_days)
> - str_start_billing_date = start_billing_date.strftime('%Y-%m-%d')
> -
> - # Cliente del albaran
> - partner = move_line.picking_id.contract_id and move_line.picking_id.contract_id.customer_id or move_line.picking_id.partner_id
> -
> - # Número de meses que se cobrarán
> - # Por defecto 2 meses si es cliente o administrador
> - # -1 (final de mes) si es ascensorista o la linea va dirigida a un ascensorista
> - billing_months = partner.num_months_first_invoice or 2
> -
> - if move_line and move_line.receiver == 'ascensorista' or (partner and partner.tipo_cliente in ('ascensorista',)):
> - billing_partner = move_line.picking_id.elevator_partner_id or partner
> - billing_months = billing_partner.num_months_first_invoice or -1
> -
> - # Obtenemos ultima factura
> - max_expiration_date = self._max_annexe_expiration_date(cr, uid, partner.id)
> -
> - # Si se le ha facturado ya y la fecha de expiración del ultimo anexo es mayor
> - # que la fecha de expedicion del paquete, se le cobra hasta la fecha de expiración del ultimo anexo.
> - if max_expiration_date:
> - if str_start_billing_date < max_expiration_date:
> - billing_months = None
> - str_expiration_date = max_expiration_date
> -
> - # Si es la primera vez que se factura a un ascensorista se factura 1 mes
> - else:
> - billing_months = 1
> -
> -
> - if billing_months:
> -
> - if billing_months < 0:
> - # Obtenemos número de meses desde la fecha de albarán hasta final de mes de X meses
> - # -1 : Final de mes de la fecha de albaran
> - # -2 : Final de mes del mes siguiente a la fecha albarán
> - # ...
> -
> - num_months = (billing_months * -1) - 1
> - date_aux = start_billing_date + relativedelta(months=+num_months)
> -
> - #Final de mes
> - month_days = calendar.monthrange(date_aux.year, date_aux.month)[1]
> -
> - #Fecha vencimiento
> - expiration_date = date_aux.replace(day=month_days)
> - str_expiration_date = expiration_date.strftime('%Y-%m-%d')
> -
> - #Numero de meses
> - billing_months = self.pool.get('invoice.generator').calculate_months(str_start_billing_date, expiration_date.strftime('%Y-%m-%d'))
> -
> - else:
> - # X meses menos un dia
> - expiration_date = start_billing_date + relativedelta(months=+billing_months, days=-1)
> - str_expiration_date = expiration_date.strftime('%Y-%m-%d')
> -
> - else:
> - #Numero de meses
> - aux_date = datetime.strptime(str_expiration_date, '%Y-%m-%d') + relativedelta(days=+1)
> - equal_days = ((start_billing_date.day == aux_date.day) and (start_billing_date != aux_date))
> -
> - billing_months = self.pool.get('invoice.generator').calculate_months(str_start_billing_date, (equal_days and aux_date.strftime('%Y-%m-%d') or str_expiration_date) )
> -
> - # ---------------------------------
> -
> - # Heredamos cabinas y comisiones
> - if move_line:
> - invoice_line_obj.write(cr, uid, [invoice_line_id], {
> - 'num_cabins': move_line.num_cabins,
> - }, context=None)
> -
> - res = super(stock_picking, self)._invoice_line_hook(cr, uid, move_line, invoice_line_id)
> -
> - # Si la línea de albaran va dirigida a un cliente y el cliente no es ascensorista, la marcamos como facturada
> - if move_line and move_line.receiver == 'cliente' and (partner and not partner.tipo_cliente in ('ascensorista',)):
> -
> - # Linea de albarán como facturada
> - stock_move_obj.write(cr, uid, [move_line.id], {'invoiced': True}, context=None)
> -
> - # Obtenemos referencia de cliente desde sistema externo
> - customer_ref = None
> -
> - if move_line.contract_annexe_id:
> - phone = move_line.contract_annexe_id.production_lot_id and move_line.contract_annexe_id.production_lot_id.telefono or move_line.contract_annexe_id.phone
> -
> - if phone:
> - try:
> - mysql_db = mysql_obj.open_connection(cr, uid)
> - customer_ref = mysql_obj.get_customer_ref(cr, uid, mysql_db, phone)
> - mysql_obj.close_connection(mysql_db)
> - except:
> - pass
> -
> - # Si no obtenemos referencia, la buscamos en la linea de pedido origen
> - if not customer_ref and move_line.sale_line_id and move_line.sale_line_id.client_order_ref:
> - customer_ref = move_line.sale_line_id.client_order_ref
> -
> - # Si no obtenemos referencia, la buscamos en el pedido origen
> - if not customer_ref and move_line.picking_id and move_line.picking_id.sale_id and move_line.picking_id.sale_id.client_order_ref:
> - customer_ref = move_line.picking_id.sale_id.client_order_ref
> -
> - #----------------------------------------------------------------
> -
> -
> - if move_line.contract_annexe_id:
> -
> - # Actualizamos fecha de envio, fecha inicio cobro y vencimiento del anexo
> - # Relacionamos anexo con linea de factura creada
> - vals = {
> - 'shipping_date': str_picking_date,
> - 'start_billing_date': str_start_billing_date,
> - 'expiration_date': str_expiration_date,
> - 'customer_ref': customer_ref,
> - 'invoice_line_id': invoice_line_id,
> - }
> -
> - annexe_obj.write(cr, uid, [move_line.contract_annexe_id.id], vals)
> -
> -
> - #Actualizamos precio de linea de factura si es una SIM (Se cobra X meses por adelantado)
> - invoice_line = invoice_line_obj.browse(cr, uid, invoice_line_id, context=None)
> -
> - if invoice_line and invoice_line.product_id and product_obj._is_sim(invoice_line.product_id.categ_id):
> -
> - vals = {
> - 'price_unit': invoice_line.price_unit * billing_months,
> - 'price_subtotal': invoice_line.price_subtotal * billing_months,
> - 'months': billing_months,
> - 'start_date': str_start_billing_date or None,
> - 'end_date': str_expiration_date or None,
> - 'customer_ref': customer_ref,
> - }
> -
> - invoice_line_obj.write(cr, uid, [invoice_line.id], vals)
> -
> -
> - # Si el movimiento va dirigido a un ascensorista o el cliente es ascensorista, borramos linea de factura y se facturará mas adelante
> - elif move_line and move_line.receiver == 'ascensorista' or (partner and partner.tipo_cliente in ('ascensorista',)):
> -
> - if move_line.picking_id.type == 'out':
> - invoice_line_obj.unlink(cr, uid, [invoice_line_id], context=None)
> -
> - if move_line.contract_annexe_id:
> -
> - # Actualizamos fecha de envio, fecha inicio cobro y vencimiento del anexo
> - vals = {
> - 'shipping_date': str_picking_date,
> - 'start_billing_date': str_start_billing_date,
> - 'expiration_date': str_expiration_date,
> - }
> - annexe_obj.write(cr, uid, [move_line.contract_annexe_id.id], vals)
> -
> - # Guardamos periodo pendiente de facturar por el generador
> - # en la propia linea de albaran en el caso que esté asociada a un anexo
> - stock_move_obj.write(cr, uid, [move_line.id], { 'months': billing_months,
> - 'start_billing_date': str_start_billing_date,
> - 'expiration_date': str_expiration_date,
> - }, context=None)
> -
> - return res
> -
> -
> - def action_invoice_create(self, cr, uid, ids, journal_id=False, group=False, type='out_invoice', context=None):
> -
> - invoice_obj = self.pool.get('account.invoice')
> -
> - res = super(stock_picking, self).action_invoice_create(cr, uid, ids, journal_id=journal_id, group=group, type=type, context=context)
> -
> - for picking_id, invoice_id in res.items():
> - picking = self.browse(cr, uid, picking_id, context=context)
> -
> - vals = {
> - 'elevator_partner_id': picking.elevator_partner_id and picking.elevator_partner_id.id or False,
> - 'middleman_partner_id': picking.middleman_partner_id and picking.middleman_partner_id.id or False,
> - 'contract_id': picking.contract_id and picking.contract_id.id or False,
> - }
> -
> - # Comprobamos si al menos una linea del albaran va dirigida al cliente
> - partner_invoice = False
> -
> - partner = picking.contract_id and picking.contract_id.customer_id or picking.partner_id
> -
> - for line in picking.move_lines:
> - if line.receiver == 'cliente' and (partner and not partner.tipo_cliente in ('ascensorista',)) :
> - partner_invoice = True
> - break
> -
> - # Si toda la factura va dirigida al ascensorista, la borramos
> - if not partner_invoice and picking.type == 'out':
> - invoice_obj.unlink(cr, uid, [invoice_id], context=context)
> -
> - # En caso contrario...
> - else:
> - # Asignamos cuenta contable y tipo de pago del cliente del contrato o del albarán
> - # (no de la dirección de envio)
> - inv_type = invoice_obj.read(cr, uid, invoice_id, ['type'], context)['type']
> -
> - payment_term_id = False
> -
> - if inv_type in ('out_invoice', 'out_refund'):
> - account_id = partner.property_account_receivable.id
> - payment_term_id = partner.property_payment_term and partner.property_payment_term.id or False
> - else:
> - account_id = partner.property_account_payable.id
> -
> - invoice_obj.write(cr, uid, [invoice_id], {'account_id': account_id, 'payment_term': payment_term_id}, context=context)
> -
> - return res
> -
> - def action_cancel(self, cr, uid, ids, context=None):
> -
> - """
> - Cancelamos albaran y todos los albaranes internos relacionados, asi como los anexos creados.
> - """
> - res = super(stock_picking, self).action_cancel(cr, uid, ids, context=context)
> -
> - for pick in self.browse(cr, uid, ids, context=context):
> -
> - if pick.sale_id:
> - int_pick_ids = self.search(cr, uid, [('type', '=', 'internal'),
> - ('sale_id', '=', pick.sale_id.id),
> - ('state', '=', 'done'), ], context=context)
> -
> - """ Cancelamos movimientos """
> - for int_pick in self.browse(cr, uid, int_pick_ids, context=context):
> - move_ids = [move.id for move in int_pick.move_lines]
> - self.pool.get('stock.move').action_cancel(cr, uid, move_ids, context)
> -
> - """ Cancelamos albaranes internos """
> - self.write(cr, uid, int_pick_ids, {'state': 'cancel', 'invoice_state': 'none'})
> - self.log_picking(cr, uid, int_pick_ids, context=context)
> -
> - """
> - Cancelamos anexos
> - """
> - for move in pick.move_lines:
> - if move.contract_annexe_id:
> - self.pool.get('contract.annexe').write(cr, uid, [move.contract_annexe_id.id], {'active_annexe': False, 'closing_date': time.strftime('%Y-%m-%d')}, context)
> -
> - return res
> -
> -stock_picking()
> -
> -
> -class stock_move(osv.osv):
> -
> - _inherit ="stock.move"
> -
> - _columns = {
> - 'num_cabins' : fields.integer('Num. Cabins'),
> - 'receiver' : fields.selection([('cliente', 'Cliente'), ('ascensorista', 'Ascensorista')], 'Receiver', select=True, required=True),
> - 'invoiced' : fields.boolean('Invoiced'),
> - 'months': fields.float('Months', digits=(2,2)),
> - 'start_billing_date' : fields.date('Start billing date'),
> - 'expiration_date' : fields.date('Expiration date')
> - }
> -
> - _defaults = {
> - 'num_cabins': 0,
> - 'receiver': 'cliente',
> - 'invoiced': False,
> - }
> -
> -stock_move()
> +
> +class StockPicking(orm.Model):
> + _inherit = "stock.picking"
> +
> + _columns = {
> + 'contract_id': fields.many2one('contract.contract', 'Contract',
> + readonly=True, select=True,
> + states={'draft': [('readonly', False)]}),
> + 'contact_id': fields.many2one('res.partner.job', 'Contact',
> + readonly=True,
> + states={'draft': [('readonly', False)]},
> + help="The name and address of the "
> + "contact who requested the picking."),
> + }
> +
> + def _max_annexe_expiration_date(self, cr, uid, partner_id):
> + sql = " SELECT MAX(a.expiration_date) as expiration_date "
> + sql += "FROM contract_contract c "
> + sql += "INNER JOIN contract_annexe a ON c.id = a.contract_id "
> + sql += "WHERE c.customer_id = " + str(partner_id) + " "
> + sql += "AND c.active_contract=true AND a.active_annexe=true "
> + cr.execute(sql)
> +
> + return cr.fetchone()[0]
> +
> + def _get_start_billing_days(self, cr, uid, move_line):
> + return 4
> +
> + def _invoice_line_hook(self, cr, uid, move_line, invoice_line_id):
> + '''Call after the creation of the invoice line'''
> + picking_obj = self.pool['stock.picking']
> + stock_move_obj = self.pool['stock.move']
> + invoice_line_obj = self.pool['account.invoice.line']
> + annexe_obj = self.pool['contract.annexe']
> + product_obj = self.pool['product.product']
> + mysql_obj = self.pool['mysql.connect']
> +
> + # Fecha albaran
> + str_picking_date = move_line.picking_id and move_line.picking_id.date and move_line.picking_id.date[0:10] or False
> +
> + # Número de dias desde la fecha de albaran para iniciar el cobro
> + start_billing_days = picking_obj._get_start_billing_days(cr, uid, move_line)
> +
> + # Fecha Inicio Cobro = A partir de 4 días de la fecha de albarán (Fecha Factura)
> + start_billing_date = datetime.strptime(str_picking_date, '%Y-%m-%d') + relativedelta(days=+start_billing_days)
> + str_start_billing_date = start_billing_date.strftime('%Y-%m-%d')
> +
> + # Cliente del albaran
> + partner = move_line.picking_id.contract_id and move_line.picking_id.contract_id.customer_id or move_line.picking_id.partner_id
> +
> + # Número de meses que se cobrarán
> + # Por defecto 2 meses si es cliente o administrador
> + # -1 (final de mes) si es ascensorista o la linea va dirigida a un ascensorista
> + billing_months = partner.num_months_first_invoice or 2
> +
> + if move_line and move_line.receiver == 'ascensorista' or (partner and partner.tipo_cliente in ('ascensorista',)):
> + billing_partner = move_line.picking_id.elevator_partner_id or partner
> + billing_months = billing_partner.num_months_first_invoice or -1
> +
> + # Obtenemos ultima factura
> + max_expiration_date = self._max_annexe_expiration_date(cr, uid, partner.id)
> +
> + # Si se le ha facturado ya y la fecha de expiración del ultimo anexo es mayor
> + # que la fecha de expedicion del paquete, se le cobra hasta la fecha de expiración del ultimo anexo.
> + if max_expiration_date:
> + if str_start_billing_date < max_expiration_date:
> + billing_months = None
> + str_expiration_date = max_expiration_date
> +
> + # Si es la primera vez que se factura a un ascensorista se factura 1 mes
> + else:
> + billing_months = 1
> +
> + if billing_months:
> +
> + if billing_months < 0:
> + # Obtenemos número de meses desde la fecha de albarán hasta final de mes de X meses
> + # -1 : Final de mes de la fecha de albaran
> + # -2 : Final de mes del mes siguiente a la fecha albarán
> + # ...
> +
> + num_months = (billing_months * -1) - 1
> + date_aux = start_billing_date + relativedelta(months=+num_months)
> +
> + # Final de mes
> + month_days = calendar.monthrange(date_aux.year, date_aux.month)[1]
> +
> + # Fecha vencimiento
> + expiration_date = date_aux.replace(day=month_days)
> + str_expiration_date = expiration_date.strftime('%Y-%m-%d')
> +
> + # Numero de meses
> + billing_months = self.pool['invoice.generator'].calculate_months(str_start_billing_date, expiration_date.strftime('%Y-%m-%d'))
> +
> + else:
> + # X meses menos un dia
> + expiration_date = start_billing_date + relativedelta(months=+billing_months, days=-1)
> + str_expiration_date = expiration_date.strftime('%Y-%m-%d')
> +
> + else:
> + #Numero de meses
> + aux_date = datetime.strptime(str_expiration_date, '%Y-%m-%d') + relativedelta(days=+1)
> + equal_days = ((start_billing_date.day == aux_date.day) and (start_billing_date != aux_date))
> +
> + billing_months = self.pool['invoice.generator'].calculate_months(str_start_billing_date, (equal_days and aux_date.strftime('%Y-%m-%d') or str_expiration_date))
> +
> + # ---------------------------------
> + # Heredamos cabinas y comisiones
> + if move_line:
> + invoice_line_obj.write(cr, uid, [invoice_line_id], {
> + 'num_cabins': move_line.num_cabins,
> + }, context=None)
> +
> + res = super(StockPicking, self)._invoice_line_hook(cr, uid, move_line, invoice_line_id)
> +
> + # Si la línea de albaran va dirigida a un cliente y el cliente no es ascensorista, la marcamos como facturada
> + if move_line and move_line.receiver == 'cliente' and (partner and not partner.tipo_cliente in ('ascensorista',)):
> +
> + # Linea de albarán como facturada
> + stock_move_obj.write(cr, uid, [move_line.id], {'invoiced': True}, context=None)
> +
> + # Obtenemos referencia de cliente desde sistema externo
> + customer_ref = None
> +
> + if move_line.contract_annexe_id:
> + phone = move_line.contract_annexe_id.production_lot_id and move_line.contract_annexe_id.production_lot_id.telefono or move_line.contract_annexe_id.phone
> +
> + if phone:
> + try:
> + mysql_db = mysql_obj.open_connection(cr, uid)
> + customer_ref = mysql_obj.get_customer_ref(cr, uid, mysql_db, phone)
> + mysql_obj.close_connection(mysql_db)
> + except:
> + pass
> +
> + # Si no obtenemos referencia, la buscamos en la linea de pedido origen
> + if not customer_ref and move_line.sale_line_id and move_line.sale_line_id.client_order_ref:
> + customer_ref = move_line.sale_line_id.client_order_ref
> +
> + # Si no obtenemos referencia, la buscamos en el pedido origen
> + if not customer_ref and move_line.picking_id and move_line.picking_id.sale_id and move_line.picking_id.sale_id.client_order_ref:
> + customer_ref = move_line.picking_id.sale_id.client_order_ref
> +
> + #----------------------------------------------------------------
> + if move_line.contract_annexe_id:
> + # Actualizamos fecha de envio, fecha inicio cobro y vencimiento del anexo
> + # Relacionamos anexo con linea de factura creada
> + vals = {
> + 'shipping_date': str_picking_date,
> + 'start_billing_date': str_start_billing_date,
> + 'expiration_date': str_expiration_date,
> + 'customer_ref': customer_ref,
> + 'invoice_line_id': invoice_line_id,
> + }
> + annexe_obj.write(cr, uid, [move_line.contract_annexe_id.id], vals)
> +
> + # Actualizamos precio de linea de factura si es una SIM (Se cobra X meses por adelantado)
> + invoice_line = invoice_line_obj.browse(cr, uid, invoice_line_id, context=None)
> +
> + if invoice_line and invoice_line.product_id and product_obj._is_sim(invoice_line.product_id.categ_id):
> + vals = {
> + 'price_unit': invoice_line.price_unit * billing_months,
> + 'price_subtotal': invoice_line.price_subtotal * billing_months,
> + 'months': billing_months,
> + 'start_date': str_start_billing_date or None,
> + 'end_date': str_expiration_date or None,
> + 'customer_ref': customer_ref,
> + }
> + invoice_line_obj.write(cr, uid, [invoice_line.id], vals)
> +
> + # Si el movimiento va dirigido a un ascensorista o el cliente es ascensorista, borramos linea de factura y se facturará mas adelante
> + elif move_line and move_line.receiver == 'ascensorista' or (partner and partner.tipo_cliente in ('ascensorista',)):
> +
> + if move_line.picking_id.type == 'out':
> + invoice_line_obj.unlink(cr, uid, [invoice_line_id], context=None)
> +
> + if move_line.contract_annexe_id:
> +
> + # Actualizamos fecha de envio, fecha inicio cobro y vencimiento del anexo
> + vals = {
> + 'shipping_date': str_picking_date,
> + 'start_billing_date': str_start_billing_date,
> + 'expiration_date': str_expiration_date,
> + }
> + annexe_obj.write(cr, uid, [move_line.contract_annexe_id.id], vals)
> +
> + # Guardamos periodo pendiente de facturar por el generador
> + # en la propia linea de albaran en el caso que esté asociada a un anexo
> + stock_move_obj.write(cr, uid, [move_line.id], {'months': billing_months,
> + 'start_billing_date': str_start_billing_date,
> + 'expiration_date': str_expiration_date,
> + }, context=None)
> +
> + return res
> +
> + def action_invoice_create(self, cr, uid, ids, journal_id=False, group=False, type='out_invoice', context=None):
> + invoice_obj = self.pool['account.invoice']
> +
> + res = super(StockPicking, self).action_invoice_create(cr, uid, ids, journal_id=journal_id, group=group, type=type, context=context)
> +
> + for picking_id, invoice_id in res.items():
> + picking = self.browse(cr, uid, picking_id, context=context)
> +
> + vals = {
> + 'elevator_partner_id': picking.elevator_partner_id and picking.elevator_partner_id.id or False,
> + 'middleman_partner_id': picking.middleman_partner_id and picking.middleman_partner_id.id or False,
> + 'contract_id': picking.contract_id and picking.contract_id.id or False,
> + }
> +
> + # Comprobamos si al menos una linea del albaran va dirigida al cliente
> + partner_invoice = False
> +
> + partner = picking.contract_id and picking.contract_id.customer_id or picking.partner_id
> +
> + for line in picking.move_lines:
> + if line.receiver == 'cliente' and (partner and not partner.tipo_cliente in ('ascensorista',)):
> + partner_invoice = True
> + break
> +
> + # Si toda la factura va dirigida al ascensorista, la borramos
> + if not partner_invoice and picking.type == 'out':
> + invoice_obj.unlink(cr, uid, [invoice_id], context=context)
> +
> + # En caso contrario...
> + else:
> + # Asignamos cuenta contable y tipo de pago del cliente del contrato o del albarán
> + # (no de la dirección de envio)
> + inv_type = invoice_obj.read(cr, uid, invoice_id, ['type'], context)['type']
> +
> + payment_term_id = False
> +
> + if inv_type in ('out_invoice', 'out_refund'):
> + account_id = partner.property_account_receivable.id
> + payment_term_id = partner.property_payment_term and partner.property_payment_term.id or False
> + else:
> + account_id = partner.property_account_payable.id
> +
> + invoice_obj.write(cr, uid, [invoice_id], {'account_id': account_id, 'payment_term': payment_term_id}, context=context)
> +
> + return res
> +
> + def action_cancel(self, cr, uid, ids, context=None):
> + """
> + Cancelamos albaran y todos los albaranes internos relacionados, asi como los anexos creados.
> + """
> + res = super(StockPicking, self).action_cancel(cr, uid, ids, context=context)
> +
> + for pick in self.browse(cr, uid, ids, context=context):
> +
> + if pick.sale_id:
> + int_pick_ids = self.search(cr, uid, [('type', '=', 'internal'),
> + ('sale_id', '=', pick.sale_id.id),
> + ('state', '=', 'done'), ], context=context)
> +
> + """ Cancelamos movimientos """
> + for int_pick in self.browse(cr, uid, int_pick_ids, context=context):
> + move_ids = [move.id for move in int_pick.move_lines]
> + self.pool['stock.move'].action_cancel(cr, uid, move_ids, context)
> +
> + """ Cancelamos albaranes internos """
> + self.write(cr, uid, int_pick_ids, {'state': 'cancel', 'invoice_state': 'none'})
> + self.log_picking(cr, uid, int_pick_ids, context=context)
> +
> + """
> + Cancelamos anexos
> + """
> + for move in pick.move_lines:
> + if move.contract_annexe_id:
> + self.pool['contract.annexe'].write(cr, uid, [move.contract_annexe_id.id], {'active_annexe': False, 'closing_date': time.strftime('%Y-%m-%d')}, context)
> +
> + return res
> +
> +
> +class StockMove(orm.Model):
> + _inherit = "stock.move"
> +
> + _columns = {
> + 'num_cabins': fields.integer('Num. Cabins'),
> + 'receiver': fields.selection([('cliente', 'Cliente'),
> + ('ascensorista', 'Ascensorista')],
> + 'Receiver', select=True, required=True),
> + 'invoiced': fields.boolean('Invoiced'),
> + 'months': fields.float('Months', digits=(2, 2)),
> + 'start_billing_date': fields.date('Start billing date'),
> + 'expiration_date': fields.date('Expiration date')
> + }
> +
> + _defaults = {
> + 'num_cabins': 0,
> + 'receiver': 'cliente',
> + 'invoiced': False,
> + }
>
> === modified file 'dos_contracts/report/__init__.py'
> --- dos_contracts/report/__init__.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/report/__init__.py 2014-07-03 14:26:17 +0000
> @@ -1,6 +1,6 @@
> # -*- coding: utf-8 -*-
> ##############################################################################
> -#
> +#
> # OpenERP, Open Source Management Solution
> # Copyright (C) 2004-2010 DOS (<http://www.dos-sl.es>).
> #
> @@ -15,11 +15,8 @@
> # GNU Affero General Public License for more details.
> #
> # You should have received a copy of the GNU Affero General Public License
> -# along with this program. If not, see <http://www.gnu.org/licenses/>.
> +# along with this program. If not, see <http://www.gnu.org/licenses/>.
> #
> ##############################################################################
>
> -import contract_commission_report
> -
> -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> -
> +from . import contract_commission_report
>
> === modified file 'dos_contracts/report/client_order_ref_label.py'
> --- dos_contracts/report/client_order_ref_label.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/report/client_order_ref_label.py 2014-07-03 14:26:17 +0000
> @@ -19,24 +19,23 @@
> #
> ##############################################################################
>
> -from report import report_sxw
> -from osv import osv
> -from tools.translate import _
> -import pooler
> -
> -class client_order_ref_label_report(report_sxw.rml_parse):
> - def __init__(self, cr, uid, name, context):
> - super(client_order_ref_label_report, self).__init__(cr, uid, name, context=context)
> - self.localcontext.update({
> - 'time': time,
> - 'get_client_order_ref': self.get_client_order_ref,
> - })
> - self.context = context
> -
> -
> - def get_client_order_ref (self, order_line):
> - return order_line.client_order_ref
> -
> -
> -report_sxw.report_sxw('report.client.order.ref.label.report', 'sale.order.line', 'addons/dos_contracts/report/client_order_ref_label.rml', parser=client_order_ref_label_report)
> -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> +from openerp.report import report_sxw
> +
> +
> +class ClientOrderRefLabelReport(report_sxw.rml_parse):
> + def __init__(self, cr, uid, name, context):
> + super(ClientOrderRefLabelReport, self).__init__(cr, uid, name,
> + context=context)
> + self.localcontext.update({
> + 'time': time,
> + 'get_client_order_ref': self.get_client_order_ref,
> + })
> + self.context = context
> +
> + def get_client_order_ref(self, order_line):
> + return order_line.client_order_ref
> +
> +report_sxw.report_sxw('report.client.order.ref.label.report',
> + 'sale.order.line',
> + 'addons/dos_contracts/report/client_order_ref_label.rml',
> + parser=ClientOrderRefLabelReport)
>
> === modified file 'dos_contracts/report/contract_commission_report.py'
> --- dos_contracts/report/contract_commission_report.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/report/contract_commission_report.py 2014-07-03 14:26:17 +0000
> @@ -21,15 +21,14 @@
>
> import time
> from datetime import datetime
> -from report import report_sxw
> -import pooler
> -import decimal_precision as dp
> -from dateutil.relativedelta import relativedelta
> -from tools.translate import _
> +from openerp.report import report_sxw
> +from openerp.tools.translate import _
> +
>
> class contract_commission_report(report_sxw.rml_parse):
> def __init__(self, cr, uid, name, context):
> - super(contract_commission_report, self).__init__(cr, uid, name, context=context)
> + super(contract_commission_report, self).__init__(cr, uid, name,
> + context=context)
> self.localcontext.update({
> 'time': time,
> 'get_left_text': self.get_left_text,
> @@ -45,15 +44,16 @@
> })
> self.context = context
> self.data_report = context['data_report']
> - self.data_report['annexe_ids'] = self.load_annexes_info(cr, uid, self.data_report)
> - user = self.pool.get('res.users').browse(cr, uid, uid)
> + self.data_report['annexe_ids'] = self.load_annexes_info(
> + cr, uid, self.data_report)
> + user = self.pool['res.users'].browse(cr, uid, uid, context=context)
> self.company = user.company_id
>
> -
> def get_total_commission(self, cr, uid, annexe_id, start_date, end_date):
> - sql = ("SELECT DISTINCT date, MAX(COALESCE(fixed_commission, 0)) AS fixed_commission "
> + sql = ("SELECT DISTINCT date, MAX(COALESCE(fixed_commission, 0)) "
> + "AS fixed_commission "
> "FROM contract_annexe_historical "
> - "WHERE date <= '" + end_date + "' "
> + "WHERE date <= '" + end_date + "' "
> "AND contract_annexe_id = " + str(annexe_id) + " "
> "GROUP BY date "
> "ORDER BY date ")
> @@ -64,16 +64,18 @@
> fixed_commission = None
> total = 0
>
> - # Calculamos comision por tramos, si es que ha ido cambiando en el periodo
> + # Calculamos comision por tramos, si es que ha ido cambiando en el
> + # periodo
> for h in results:
> # date -> h[0]
> # fixed_commision -> h[1]
>
> - if fixed_commission == None:
> + if fixed_commission is None:
> fixed_commission = h[1]
>
> if fixed_commission != h[1]:
> - months = self.pool.get('invoice.generator').calculate_months(start_date.split(" ")[0], h[0].split(" ")[0])
> + months = self.pool['invoice.generator'].calculate_months(
> + start_date.split(" ")[0], h[0].split(" ")[0])
> if months and months > 0:
> total += months * fixed_commission
> if start_date < h[0]:
> @@ -82,16 +84,15 @@
>
> # Calculamos comision hasta el final
> if start_date < end_date:
> - months = self.pool.get('invoice.generator').calculate_months(start_date.split(" ")[0], end_date.split(" ")[0])
> + months = self.pool['invoice.generator'].calculate_months(
> + start_date.split(" ")[0], end_date.split(" ")[0])
> total += (months or 0) * (fixed_commission or 0)
>
> return total
>
> -
> def load_annexes_info(self, cr, uid, data):
> - annexe_obj = self.pool.get('contract.annexe')
> - cur_obj = self.pool.get('res.currency')
> -
> + annexe_obj = self.pool['contract.annexe']
> +
> sql = ("SELECT a.id "
> "FROM contract_annexe a "
> "INNER JOIN contract_contract c ON a.contract_id = c.id "
> @@ -100,21 +101,23 @@
> "AND a.fixed_commission > 0 ")
>
> if data['date_start'] and data['date_end']:
> - sql += "AND ((a.start_billing_date >= '" + data['date_start'] + "' AND a.start_billing_date <= '" + data['date_end'] + "') "
> + sql += "AND ((a.start_billing_date >= '" + data['date_start']
> + sql += "' AND a.start_billing_date <= '" + data['date_end'] + "') "
> sql += "OR a.start_billing_date < '" + data['date_start'] + "') "
> - sql += "AND COALESCE(a.closing_date, '" + data['date_start'] + "') >= '" + data['date_start'] + "' "
> + sql += "AND COALESCE(a.closing_date, '" + data['date_start']
> + sql += "') >= '" + data['date_start'] + "' "
>
> if data['partner_ids']:
> - sql += "AND c.middleman_id IN (" + ",".join([str(p) for p in data['partner_ids']]) + ") "
> + sql += "AND c.middleman_id IN ("
> + sql += ",".join([str(p) for p in data['partner_ids']]) + ") "
>
> sql += "ORDER BY a.annexe_date"
> -
> -
> +
> cr.execute(sql)
> -
> +
> results = cr.fetchall()
> annexe_ids = [x[0] for x in results]
> -
> +
> res = {}
>
> for annexe in annexe_obj.browse(cr, uid, annexe_ids, context=None):
> @@ -124,13 +127,14 @@
> months = self.pool.get('invoice.generator').calculate_months(start_date, end_date)
> total = self.get_total_commission(cr, uid, annexe.id, start_date, end_date)
>
> - line = {'id': annexe.id,
> - 'phone': annexe.production_lot_id and annexe.production_lot_id.telefono or None,
> - 'start_date': start_date,
> - 'end_date': end_date,
> - 'months': months,
> - 'fixed_commission': annexe.fixed_commission,
> - 'total': total,
> + line = {
> + 'id': annexe.id,
> + 'phone': annexe.production_lot_id and annexe.production_lot_id.telefono or None,
> + 'start_date': start_date,
> + 'end_date': end_date,
> + 'months': months,
> + 'fixed_commission': annexe.fixed_commission,
> + 'total': total,
> }
>
> if not partner_id in res:
> @@ -140,44 +144,35 @@
>
> return res
>
> -
> def format_date(self, date):
> -
> if str(date) != '':
> date = datetime.strptime(date, '%Y-%m-%d')
> date = date.strftime('%d/%m/%Y')
> -
> +
> return date
> -
> +
> def get_date_start(self):
> -
> return self.format_date(self.data_report['date_start'])
> -
> -
> +
> def get_date_end(self):
> -
> return self.format_date(self.data_report['date_end'])
> -
> -
> +
> def get_tax_name(self):
> -
> - tax_obj = self.pool.get('account.tax')
> -
> + tax_obj = self.pool['account.tax']
> +
> # Nombre de impuesto a aplicar
> tax_id = self.data_report['tax_id']
> tax = tax_obj.browse(self.cr, self.uid, tax_id)
>
> return tax and tax.name or 'IVA'
> -
> -
> +
> def get_left_text(self, partner):
> -
> text = ""
> -
> +
> company = partner.company_id or self.company or None
> -
> +
> if company and company.partner_id:
> -
> +
> partner = company.partner_id
>
> # Nombre empresa
> @@ -193,25 +188,23 @@
> # Hoja
> text += partner.es_hoja and (" " + _("Hoja") + " " + partner.es_hoja) or ""
> # Inscripcion
> - text += partner.es_registro_mercantil and (" " + _("Inscripción") + " " + partner.es_registro_mercantil) or ""
> + text += partner.es_registro_mercantil and (" " + _("Inscripción") + " " + partner.es_registro_mercantil) or ""
> # Final
> - text += "."
> + text += "."
>
> return text
> -
> +
> def get_footer_text(self, partner):
> -
> text = ""
> -
> +
> company = partner.company_id or self.company or None
> -
> +
> if company and company.partner_id:
> -
> partner = company.partner_id
> addr_ids = self.pool.get('res.partner').address_get(self.cr, self.uid, [partner.id], ['default'])
> addr_id = addr_ids['default']
> addr = self.pool.get('res.partner.address').browse(self.cr, self.uid, addr_id)
> -
> +
> # Nombre empresa
> text += partner and partner.name or ""
> # Calle empresa
> @@ -226,44 +219,42 @@
> text += addr and addr.fax and (" - " + _("Fax.") + " " + addr.fax) or ""
> # Email
> text += addr and addr.email and (" - " + _("E-Mail") + " " + addr.email) or ""
> -
> +
> return text
> -
> - def get_company_address (self, partner):
> -
> +
> + def get_company_address(self, partner):
> res = []
> -
> +
> company = partner.company_id or self.company or None
> -
> +
> if company and company.partner_id:
> -
> +
> partner = company.partner_id
> - addr_ids = self.pool.get('res.partner').address_get(self.cr, self.uid, [partner.id], ['default'])
> + addr_ids = self.pool['res.partner'].address_get(self.cr, self.uid, [partner.id], ['default'])
> addr_id = addr_ids['default']
> addr = self.pool.get('res.partner.address').browse(self.cr, self.uid, addr_id)
> -
> +
> res.append(partner and partner.name or "")
> res.append((addr and addr.street) or '')
> res.append((addr and addr.zip or '') + " - " + (addr and addr.city or ''))
> res.append((addr and addr.state_id and addr.state_id.name or '') + " (" + (addr and addr.country_id and addr.country_id.name or '') + ")")
> res.append(partner and partner.vat or '')
> -
> +
> else:
> -
> - res.append(" ")
> - res.append(" ")
> - res.append(" ")
> - res.append(" ")
> - res.append(" ")
> -
> +
> + res.append(" ")
> + res.append(" ")
> + res.append(" ")
> + res.append(" ")
> + res.append(" ")
> +
> return res
> -
> - def get_partner_address (self, partner):
>
> + def get_partner_address(self, partner):
> res = []
> -
> +
> if partner:
> -
> +
> addr_ids = self.pool.get('res.partner').address_get(self.cr, self.uid, [partner.id], ['default'])
> addr_id = addr_ids['default']
> addr = self.pool.get('res.partner.address').browse(self.cr, self.uid, addr_id)
> @@ -273,9 +264,9 @@
> res.append((addr and addr.zip or '') + " - " + (addr and addr.city or ''))
> res.append((addr and addr.state_id and addr.state_id.name or '') + " (" + (addr and addr.country_id and addr.country_id.name or '') + ")")
> res.append(partner and partner.vat or '')
> -
> +
> else:
> -
> +
> res.append(" ")
> res.append(" ")
> res.append(" ")
> @@ -283,53 +274,52 @@
> res.append(" ")
>
> return res
> -
> - def get_total_annexe_lines (self, partner):
> -
> +
> + def get_total_annexe_lines(self, partner):
> tax_obj = self.pool.get('account.tax')
> -
> +
> res = []
> total_amount = 0.0
> -
> +
> # Impuesto a aplicar
> tax_id = self.data_report['tax_id']
> tax = tax_obj.browse(self.cr, self.uid, tax_id)
> tax_percentage = tax and tax.amount or 0
>
> annexe_lines = self.data_report['annexe_ids'][partner.id]
> -
> +
> for a in annexe_lines:
> # total_amount += (a['months'] or 0) * (a['fixed_commission'] or 0)
> total_amount += a['total'] or 0
> -
> +
> total_tax = total_amount * tax_percentage
> total = total_amount + total_tax
> -
> +
> res.append(total_amount)
> res.append(total_tax)
> res.append(total)
> -
> +
> return res
> -
> - def get_annexe_lines (self, partner):
>
> + def get_annexe_lines(self, partner):
> res = []
> -
> +
> annexe_lines = self.data_report['annexe_ids'][partner.id]
> -
> +
> for a in annexe_lines:
> annexe = {}
> -
> +
> annexe["phone"] = a['phone'] or ''
> annexe["fixed_commission"] = a['fixed_commission'] or 0
> - annexe["start_date"] = a['start_date'] or ''
> + annexe["start_date"] = a['start_date'] or ''
> annexe["end_date"] = a['end_date'] or ''
> annexe["total"] = a['total'] or ''
>
> res.append(annexe)
> -
> +
> return res
> -
> -report_sxw.report_sxw('report.contract_commission_report', 'res.partner', 'addons/dos_contracts/report/contract_commission_report.rml', parser=contract_commission_report)
> -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
>
> +report_sxw.report_sxw(
> + 'report.contract_commission_report', 'res.partner',
> + 'addons/dos_contracts/report/contract_commission_report.rml',
> + parser=contract_commission_report)
>
> === modified file 'dos_contracts/report/sale_order_line_ref_label.py'
> --- dos_contracts/report/sale_order_line_ref_label.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/report/sale_order_line_ref_label.py 2014-07-03 14:26:17 +0000
> @@ -19,26 +19,25 @@
> #
> ##############################################################################
>
> -from report import report_sxw
> -from osv import osv
> -from tools.translate import _
> -import pooler
> -
> -class sale_order_line_ref_label_report(report_sxw.rml_parse):
> - def __init__(self, cr, uid, name, context):
> - super(sale_order_line_ref_label_report, self).__init__(cr, uid, name, context=context)
> - self.localcontext.update({
> - 'get_client_order_ref': self.get_client_order_ref,
> - })
> - self.context = context
> - import logging
> - logger = logging.getLogger('sale.order.line')
> - logger.info(self.localcontext.get('prueba'))
> -
> -
> - def get_client_order_ref (self, order_line):
> - return order_line.client_order_ref
> -
> -
> -report_sxw.report_sxw('report.sale.order.line.ref.label.report', 'sale.order.line', 'addons/dos_contracts/report/sale_order_line_ref_label.rml', parser=sale_order_line_ref_label_report)
> -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> +from openerp.report import report_sxw
> +
> +
> +class SaleOrderLineRefLabelReport(report_sxw.rml_parse):
> + def __init__(self, cr, uid, name, context):
> + super(SaleOrderLineRefLabelReport,
> + self).__init__(cr, uid, name, context=context)
> + self.localcontext.update({
> + 'get_client_order_ref': self.get_client_order_ref,
> + })
> + self.context = context
> + import logging
> + logger = logging.getLogger('sale.order.line')
> + logger.info(self.localcontext.get('prueba'))
> +
> + def get_client_order_ref(self, order_line):
> + return order_line.client_order_ref
> +
> +report_sxw.report_sxw('report.sale.order.line.ref.label.report',
> + 'sale.order.line',
> + 'addons/dos_contracts/report/sale_order_line_ref_label.rml',
> + parser=SaleOrderLineRefLabelReport)
>
> === modified file 'dos_contracts/report/sale_order_ref_label.py'
> --- dos_contracts/report/sale_order_ref_label.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/report/sale_order_ref_label.py 2014-07-03 14:26:17 +0000
> @@ -20,22 +20,20 @@
> ##############################################################################
>
> from report import report_sxw
> -from osv import osv
> -from tools.translate import _
> -import pooler
> +
>
> class sale_order_ref_label_report(report_sxw.rml_parse):
> - def __init__(self, cr, uid, name, context):
> - super(sale_order_ref_label_report, self).__init__(cr, uid, name, context=context)
> - self.localcontext.update({
> - 'get_client_order_ref': self.get_client_order_ref,
> - })
> - self.context = context
> -
> -
> - def get_client_order_ref (self, order):
> - return self.context.get('client_order_ref', order.client_order_ref)
> -
> -
> -report_sxw.report_sxw('report.sale.order.ref.label.report', 'sale.order', 'addons/dos_contracts/report/sale_order_ref_label.rml', parser=sale_order_ref_label_report)
> -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> + def __init__(self, cr, uid, name, context):
> + super(sale_order_ref_label_report, self).__init__(cr, uid, name,
> + context=context)
> + self.localcontext.update({
> + 'get_client_order_ref': self.get_client_order_ref,
> + })
> + self.context = context
> +
> + def get_client_order_ref(self, order):
> + return self.context.get('client_order_ref', order.client_order_ref)
> +
> +report_sxw.report_sxw('report.sale.order.ref.label.report', 'sale.order',
> + 'addons/dos_contracts/report/sale_order_ref_label.rml',
> + parser=sale_order_ref_label_report)
>
> === added directory 'dos_contracts/views'
> === renamed file 'dos_contracts/contract_commission_report.xml' => 'dos_contracts/views/contract_commission_report.xml'
> === renamed file 'dos_contracts/contract_view.out.xml' => 'dos_contracts/views/contract_view.out.xml'
> === renamed file 'dos_contracts/contract_view.xml' => 'dos_contracts/views/contract_view.xml'
> === renamed file 'dos_contracts/invoice_view.xml' => 'dos_contracts/views/invoice_view.xml'
> === renamed file 'dos_contracts/partner_view.xml' => 'dos_contracts/views/partner_view.xml'
> === renamed file 'dos_contracts/sale_view.xml' => 'dos_contracts/views/sale_view.xml'
> --- dos_contracts/sale_view.xml 2014-06-11 10:23:47 +0000
> +++ dos_contracts/views/sale_view.xml 2014-07-03 14:26:17 +0000
> @@ -1,87 +1,98 @@
> <?xml version="1.0"?>
> <openerp>
> - <data>
> -
> - <!-- Sale Order Inherit Form View -->
> - <record model="ir.ui.view" id="view_order_cabins_form_inherit">
> - <field name="name">sale.order.cabins.form.inherit</field>
> - <field name="model">sale.order</field>
> - <field name="inherit_id" ref="sale_layout.view_order_form_inherit_1"/>
> - <field name="type">form</field>
> - <field name="priority">1</field>
> - <field name="arch" type="xml">
> -
> - <xpath expr="/form/notebook/page/field[@name='abstract_line_ids']/form/notebook/page/field[@name='product_id']" position="replace">
> - <field colspan="4"
> - context="partner_id=parent.partner_id,quantity=product_uom_qty,pricelist=parent.pricelist_id,shop=parent.shop_id,uom=product_uom"
> - name="product_id"
> - attrs="{'readonly':[('layout_type','!=','article')]}"
> - on_change="product_id_change_inherit(parent.pricelist_id,product_id,parent.contract_id,prodlot_id,num_cabins,product_uom_qty,product_uom,product_uos_qty,product_uos,name,parent.partner_id, 'lang' in context and context['lang'], True, parent.date_order, product_packaging, parent.fiscal_position)"
> - select="1"/>
> - </xpath>
> -
> - <xpath expr="/form/notebook/page/field[@name='abstract_line_ids']/form/notebook/page/field[@name='product_id']" position="after">
> - <field name="prodlot_id"
> - context="{'product_id':product_id,'search_default_available':1}"
> - domain="[('stock_available', '>', 0)]"
> - on_change="prodlot_id_change_inherit(parent.pricelist_id,prodlot_id,product_id,parent.contract_id,num_cabins,product_uom_qty,product_uom,product_uos_qty,product_uos,name,parent.partner_id, 'lang' in context and context['lang'], True, parent.date_order, product_packaging, parent.fiscal_position)"
> - colspan="4"/>
> - </xpath>
> -
> - <xpath expr="/form/notebook/page/field[@name='abstract_line_ids']/form/notebook/page/field[@name='product_uom_qty']" position="replace">
> - <field
> - context="partner_id=parent.partner_id,quantity=product_uom_qty,pricelist=parent.pricelist_id,shop=parent.shop_id,uom=product_uom"
> - name="product_uom_qty"
> - attrs="{'readonly':[('layout_type','!=','article')]}"
> - on_change="product_id_change_inherit(parent.pricelist_id,product_id,parent.contract_id,prodlot_id,num_cabins,product_uom_qty,product_uom,product_uos_qty,product_uos,name,parent.partner_id, 'lang' in context and context['lang'], True, parent.date_order, product_packaging, parent.fiscal_position)"
> - select="1"/>
> - </xpath>
> -
> - <xpath expr="/form/notebook/page/field[@name='abstract_line_ids']/form/notebook/page/field[@name='product_uom']" position="replace">
> - <field name="product_uom"
> - required="0"
> - attrs="{'readonly':[('layout_type','!=','article')], 'required':[('layout_type','not in',['title','text','subtotal','line','break'])]}"
> - on_change="product_uom_change_inherit(parent.pricelist_id,product_id,parent.contract_id,prodlot_id,num_cabins,product_uom_qty,product_uom,product_uos_qty,product_uos,name,parent.partner_id, 'lang' in context and context['lang'], False, parent.date_order)"/>
> - </xpath>
> -
> - <xpath expr="/form/notebook/page/field[@name='abstract_line_ids']/tree/field[@name='name']" position="after">
> - <field name="prodlot_id" />
> -
> - <button name="%(act_sale_order_split)d" string="Split in production lots" type="action"
> - icon="terp-stock_effects-object-colorize" attrs="{'invisible': [('prodlot_id','<>',False)]}"
> - groups="base.group_extended"
> - states="draft"
> - />
> - </xpath>
> -
> - <xpath expr="/form/notebook/page/field[@name='abstract_line_ids']/form/notebook/page/field[@name='product_packaging']" position="after">
> - <field name="num_cabins"
> - on_change="product_id_change_inherit(parent.pricelist_id,product_id,parent.contract_id,prodlot_id,num_cabins,product_uom_qty,product_uom,product_uos_qty,product_uos,name,parent.partner_id, 'lang' in context and context['lang'], True, parent.date_order, product_packaging, parent.fiscal_position)" />
> - <field name="receiver" />
> - <field name="client_order_ref" />
> - </xpath>
> -
> - <xpath expr="/form/notebook/page/field[@name='abstract_line_ids']/tree/field[@name='price_subtotal']" position="after">
> - <field name="num_cabins" />
> - </xpath>
> -
> - </field>
> - </record>
> -
> -
> - <!-- Sale Order Inherit Form View -->
> - <record model="ir.ui.view" id="view_order_contact_form_inherit">
> - <field name="name">sale.order.contact.form.inherit</field>
> - <field name="model">sale.order</field>
> - <field name="inherit_id" ref="sale.view_order_form"/>
> - <field name="type">form</field>
> - <field name="priority">1</field>
> - <field name="arch" type="xml">
> - <field name="partner_invoice_id" position="before">
> - <field domain="[('address_id','=',partner_shipping_id)]" name="contact_id" />
> - </field>
> - </field>
> - </record>
> -
> - </data>
> + <data>
> +
> + <!-- Sale Order Inherit Form View -->
> + <record model="ir.ui.view" id="view_order_cabins_form_inherit">
> + <field name="name">sale.order.cabins.form.inherit</field>
> + <field name="model">sale.order</field>
> + <field name="inherit_id" ref="sale_layout.view_order_form_inherit_1" />
> + <field name="priority">1</field>
> + <field name="arch" type="xml">
> + <xpath
> + expr="/form/notebook/page/field[@name='abstract_line_ids']/form/notebook/page/field[@name='product_id']"
> + position="replace">
> + <field colspan="4"
> + context="partner_id=parent.partner_id,quantity=product_uom_qty,pricelist=parent.pricelist_id,shop=parent.shop_id,uom=product_uom"
> + name="product_id"
> + attrs="{'readonly':[('layout_type','!=','article')]}"
> + on_change="product_id_change_inherit(parent.pricelist_id,product_id,parent.contract_id,prodlot_id,num_cabins,product_uom_qty,product_uom,product_uos_qty,product_uos,name,parent.partner_id, 'lang' in context and context['lang'], True, parent.date_order, product_packaging, parent.fiscal_position)"
> + select="1" />
> + </xpath>
> +
> + <xpath
> + expr="/form/notebook/page/field[@name='abstract_line_ids']/form/notebook/page/field[@name='product_id']"
> + position="after">
> + <field name="prodlot_id"
> + context="{'product_id':product_id,'search_default_available':1}"
> + domain="[('stock_available', '>', 0)]"
> + on_change="prodlot_id_change_inherit(parent.pricelist_id,prodlot_id,product_id,parent.contract_id,num_cabins,product_uom_qty,product_uom,product_uos_qty,product_uos,name,parent.partner_id, 'lang' in context and context['lang'], True, parent.date_order, product_packaging, parent.fiscal_position)"
> + colspan="4" />
> + </xpath>
> +
> + <xpath
> + expr="/form/notebook/page/field[@name='abstract_line_ids']/form/notebook/page/field[@name='product_uom_qty']"
> + position="replace">
> + <field
> + context="partner_id=parent.partner_id,quantity=product_uom_qty,pricelist=parent.pricelist_id,shop=parent.shop_id,uom=product_uom"
> + name="product_uom_qty"
> + attrs="{'readonly':[('layout_type','!=','article')]}"
> + on_change="product_id_change_inherit(parent.pricelist_id,product_id,parent.contract_id,prodlot_id,num_cabins,product_uom_qty,product_uom,product_uos_qty,product_uos,name,parent.partner_id, 'lang' in context and context['lang'], True, parent.date_order, product_packaging, parent.fiscal_position)"
> + select="1" />
> + </xpath>
> +
> + <xpath
> + expr="/form/notebook/page/field[@name='abstract_line_ids']/form/notebook/page/field[@name='product_uom']"
> + position="replace">
> + <field name="product_uom" required="0"
> + attrs="{'readonly':[('layout_type','!=','article')], 'required':[('layout_type','not in',['title','text','subtotal','line','break'])]}"
> + on_change="product_uom_change_inherit(parent.pricelist_id,product_id,parent.contract_id,prodlot_id,num_cabins,product_uom_qty,product_uom,product_uos_qty,product_uos,name,parent.partner_id, 'lang' in context and context['lang'], False, parent.date_order)" />
> + </xpath>
> +
> + <xpath
> + expr="/form/notebook/page/field[@name='abstract_line_ids']/tree/field[@name='name']"
> + position="after">
> + <field name="prodlot_id" />
> +
> + <button name="%(act_sale_order_split)d"
> + string="Split in production lots" type="action"
> + icon="terp-stock_effects-object-colorize"
> + attrs="{'invisible': [('prodlot_id','<>',False)]}"
> + groups="base.group_extended" states="draft" />
> + </xpath>
> +
> + <xpath
> + expr="/form/notebook/page/field[@name='abstract_line_ids']/form/notebook/page/field[@name='product_packaging']"
> + position="after">
> + <field name="num_cabins"
> + on_change="product_id_change_inherit(parent.pricelist_id,product_id,parent.contract_id,prodlot_id,num_cabins,product_uom_qty,product_uom,product_uos_qty,product_uos,name,parent.partner_id, 'lang' in context and context['lang'], True, parent.date_order, product_packaging, parent.fiscal_position)" />
> + <field name="receiver" />
> + <field name="client_order_ref" />
> + </xpath>
> +
> + <xpath
> + expr="/form/notebook/page/field[@name='abstract_line_ids']/tree/field[@name='price_subtotal']"
> + position="after">
> + <field name="num_cabins" />
> + </xpath>
> +
> + </field>
> + </record>
> +
> +
> + <!-- Sale Order Inherit Form View -->
> + <record model="ir.ui.view" id="view_order_contact_form_inherit">
> + <field name="name">sale.order.contact.form.inherit</field>
> + <field name="model">sale.order</field>
> + <field name="inherit_id" ref="sale.view_order_form" />
> + <field name="priority">1</field>
> + <field name="arch" type="xml">
> + <field name="partner_invoice_id" position="before">
> + <field domain="[('address_id','=',partner_shipping_id)]"
> + name="contact_id" />
> + </field>
> + </field>
> + </record>
> +
> + </data>
> </openerp>
>
> === modified file 'dos_contracts/wizard/__init__.py'
> --- dos_contracts/wizard/__init__.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/wizard/__init__.py 2014-07-03 14:26:17 +0000
> @@ -19,9 +19,5 @@
> #
> ##############################################################################
>
> -
> -import sale_order_line
> -import contract_commission_wizard
> -
> -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> -
> +from . import sale_order_line
> +from . import contract_commission_wizard
>
> === modified file 'dos_contracts/wizard/contract_commission_wizard.py'
> --- dos_contracts/wizard/contract_commission_wizard.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/wizard/contract_commission_wizard.py 2014-07-03 14:26:17 +0000
> @@ -20,97 +20,100 @@
> ##############################################################################
>
> import time
> -from osv import osv, fields
> +from openerp.osv import orm, fields
> from datetime import datetime
> from dateutil.relativedelta import relativedelta
> -from tools.translate import _
> -
> -class contract_commission_wizard(osv.osv_memory):
> +from openerp.tools.translate import _
> +
> +
> +class ContractCommissionWizard(orm.TransientModel):
> _name = 'contract.commission.wizard'
> _description = 'Contract Commissions Wizard'
> -
> +
> def _get_first_day_present_year(self, cr, uid, context=None):
> if context is None:
> context = {}
> date_ref = datetime.now().strftime('%Y-%m-%d')
> - first_date = (datetime.strptime(date_ref, '%Y-%m-%d') + relativedelta(day=1, month=1))
> + first_date = (datetime.strptime(date_ref, '%Y-%m-%d') +
> + relativedelta(day=1, month=1))
> return first_date.strftime('%Y-%m-%d')
> -
> +
> def _get_tax(self, cr, uid, context=None):
> if context is None:
> context = {}
> -
> - tax_obj = self.pool.get('account.tax')
> -
> - tax_ids = tax_obj.search(cr, uid, [("name", "=", "IVA 21%")])
> +
> + tax_obj = self.pool['account.tax']
> + tax_ids = tax_obj.search(cr, uid, [("name", "=", "IVA 21%")],
> + context=context)
> tax_id = tax_ids and tax_ids[0] or None
> -
> +
> if not tax_id:
> - tax_ids = tax_obj.search(cr, uid, [("id", "=", 36)])
> + tax_ids = tax_obj.search(cr, uid, [("id", "=", 36)],
> + context=context)
> tax_id = tax_ids and tax_ids[0] or None
> -
> +
> if not tax_id:
> - tax_ids = tax_obj.search(cr, uid, [])
> + tax_ids = tax_obj.search(cr, uid, [], context=context)
> tax_id = tax_ids and tax_ids[0] or None
> -
> +
> return tax_id
> -
> +
> _columns = {
> 'date_start': fields.date('Start date', required=True),
> 'date_end': fields.date('End date', required=True),
> 'partner_id': fields.many2one('res.partner', 'Middleman', select=True),
> - 'tax_id': fields.many2one('account.tax', 'Tax', required=True, select=True),
> + 'tax_id': fields.many2one('account.tax', 'Tax', required=True,
> + select=True),
> }
> -
> +
> _defaults = {
> 'date_start': _get_first_day_present_year,
> 'date_end': lambda *a: time.strftime('%Y-%m-%d'),
> 'tax_id': _get_tax,
> }
> -
> +
> def _get_total_commission(self, cr, uid, annexe_id, start_date, end_date):
> -
> - sql = "SELECT DISTINCT date, MAX(COALESCE(fixed_commission,0)) As fixed_commission "
> + sql = "SELECT DISTINCT date, MAX(COALESCE(fixed_commission,0))"
> + sql += "AS fixed_commission "
> sql += "FROM contract_annexe_historical "
> - sql += "WHERE date <= '" + end_date + "' "
> + sql += "WHERE date <= '" + end_date + "' "
> sql += "AND contract_annexe_id = " + str(annexe_id) + " "
> sql += "GROUP BY date "
> sql += "ORDER BY date "
> -
> +
> cr.execute(sql)
> results = cr.fetchall()
> -
> +
> fixed_commission = None
> total = 0
> -
> - # Calculamos comision por tramos, si es que ha ido cambiando en el periodo
> +
> + # Calculamos comision por tramos, si es que ha ido cambiando en el
> + # periodo
> for h in results:
> # date -> h[0]
> # fixed_commision -> h[1]
> -
> - if fixed_commission == None:
> +
> + if fixed_commission is None:
> fixed_commission = h[1]
> -
> +
> if fixed_commission != h[1]:
> fixed_commission = h[1]
> - months = self.pool.get('invoice.generator').calculate_months(start_date.split(" ")[0], h[0].split(" ")[0])
> + months = self.pool['invoice.generator'].calculate_months(
> + start_date.split(" ")[0], h[0].split(" ")[0])
> total += (months or 0) * (fixed_commission or 0)
> start_date = h[0]
> -
> +
> # Calculamos comision hasta el final
> if start_date < end_date:
> - months = self.pool.get('invoice.generator').calculate_months(start_date.split(" ")[0], end_date.split(" ")[0])
> + months = self.pool['invoice.generator'].calculate_months(
> + start_date.split(" ")[0], end_date.split(" ")[0])
> total += (months or 0) * (fixed_commission or 0)
> -
> +
> return total
> -
> +
> def __get_partner_ids(self, cr, uid, data, context=None):
> -
> - annexe_obj = self.pool.get('contract.annexe')
> - cur_obj = self.pool.get('res.currency')
> -
> - partner_ids = []
> -
> + annexe_obj = self.pool['contract.annexe']
> +
> sql = " SELECT a.id, c.middleman_id, p.name, a.start_billing_date, a.closing_date, a.fixed_commission "
> sql += "FROM contract_annexe a "
> sql += "INNER JOIN contract_contract c ON a.contract_id=c.id "
> @@ -121,90 +124,87 @@
> if data['date_start'] and data['date_end']:
> sql += "AND ((a.start_billing_date >= '" + data['date_start'] + "' AND a.start_billing_date <= '" + data['date_end'] + "') "
> sql += "OR a.start_billing_date < '" + data['date_start'] + "') "
> - sql += "AND COALESCE(a.closing_date, '" + data['date_start'] + "') >= '" + data['date_start'] + "' "
> -
> + sql += "AND COALESCE(a.closing_date, '" + data['date_start'] + "') >= '" + data['date_start'] + "' "
> +
> if data['partner_id']:
> sql += "AND c.middleman_id = " + str(data['partner_id'])
> -
> +
> sql += "ORDER BY p.name, a.annexe_date "
> -
> -
> +
> cr.execute(sql)
> -
> +
> results = cr.fetchall()
> annexe_ids = [x[0] for x in results]
> -
> +
> res = {}
> -
> +
> for annexe in annexe_obj.browse(cr, uid, annexe_ids, context=None):
> -
> partner_id = annexe.contract_id.middleman_id.id
> -
> +
> start_date = data['date_start'] > annexe.start_billing_date and data['date_start'] or annexe.start_billing_date
> end_date = annexe.closing_date and data['date_end'] > annexe.closing_date and annexe.closing_date or data['date_end']
> - months = self.pool.get('invoice.generator').calculate_months(start_date, end_date)
> - total = self._get_total_commission(cr, uid, annexe.id, start_date, end_date)
> -
> - line = {'id': annexe.id,
> - 'phone': annexe.production_lot_id and annexe.production_lot_id.telefono or None,
> - 'start_date': start_date,
> - 'end_date': end_date,
> - 'months': months,
> - 'fixed_commission': annexe.fixed_commission,
> - 'total': total,
> + months = self.pool['invoice.generator'].calculate_months(
> + start_date, end_date)
> + total = self._get_total_commission(cr, uid, annexe.id, start_date,
> + end_date)
> +
> + line = {
> + 'id': annexe.id,
> + 'phone': annexe.production_lot_id and annexe.production_lot_id.telefono or None,
> + 'start_date': start_date,
> + 'end_date': end_date,
> + 'months': months,
> + 'fixed_commission': annexe.fixed_commission,
> + 'total': total,
> }
> -
> +
> if not partner_id in res:
> res[partner_id] = [line]
> else:
> res[partner_id].append(line)
>
> data['annexe_ids'] = res
> -
> +
> return res.keys()
>
> -
> def _get_partner_ids(self, cr, uid, data, context=None):
> -
> sql = ("SELECT DISTINCT c.middleman_id "
> "FROM contract_annexe a "
> "INNER JOIN contract_contract c ON a.contract_id=c.id "
> "INNER JOIN res_partner p ON c.middleman_id=p.id "
> - "WHERE NOT c.middleman_id IS NULL AND NOT a.start_billing_date IS NULL "
> - "AND a.fixed_commission > 0 ")
> + "WHERE NOT c.middleman_id IS NULL AND NOT a.start_billing_date "
> + "IS NULL AND a.fixed_commission > 0 ")
>
> if data['date_start'] and data['date_end']:
> sql += "AND ((a.start_billing_date >= '" + data['date_start'] + "' AND a.start_billing_date <= '" + data['date_end'] + "') "
> sql += "OR a.start_billing_date < '" + data['date_start'] + "') "
> - sql += "AND COALESCE(a.closing_date, '" + data['date_start'] + "') >= '" + data['date_start'] + "' "
> -
> + sql += "AND COALESCE(a.closing_date, '" + data['date_start'] + "') >= '" + data['date_start'] + "' "
> +
> if data['partner_id']:
> sql += "AND c.middleman_id = " + str(data['partner_id'])
>
> cr.execute(sql)
> -
> +
> results = cr.fetchall()
> return [c[0] for c in results]
>
> -
> def check_report(self, cr, uid, ids, context=None):
> -
> if context is None:
> context = {}
> -
> +
> data = self.read(cr, uid, ids, [], context=context)[0]
> partner_ids = self._get_partner_ids(cr, uid, data, context=context)
> data['partner_ids'] = partner_ids
>
> context['data_report'] = data
> -
> +
> datas = {
> - 'ids': partner_ids,
> - 'model': 'res.partner',
> - 'form': data,
> - 'context': context
> + 'ids': partner_ids,
> + 'model': 'res.partner',
> + 'form': data,
> + 'context': context
> }
> -
> +
> if partner_ids and len(partner_ids) > 0:
> return {
> 'type': 'ir.actions.report.xml',
> @@ -213,9 +213,7 @@
> 'datas': datas,
> }
> else:
> - raise osv.except_osv(_('Warning !'), _('No attachments commissionable within the limits indicated.'))
> -
> -
> -contract_commission_wizard()
> -
> -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> + raise orm.except_orm(
> + _('Warning !'),
> + _('No attachments commissionable within the limits '
> + 'indicated.'))
>
> === modified file 'dos_contracts/wizard/contract_commission_wizard.xml'
> --- dos_contracts/wizard/contract_commission_wizard.xml 2014-06-11 10:23:47 +0000
> +++ dos_contracts/wizard/contract_commission_wizard.xml 2014-07-03 14:26:17 +0000
> @@ -1,53 +1,57 @@
> <?xml version="1.0" encoding="utf-8"?>
> <openerp>
> - <data>
> - <record id="contract_commission_wizard_view" model="ir.ui.view">
> - <field name="name">Calculation of commissions</field>
> - <field name="model">contract.commission.wizard</field>
> - <field name="type">form</field>
> - <field name="arch" type="xml">
> - <form string="Limites">
> - <separator string="Calculation of commissions" colspan="4"/>
> -
> - <group colspan="4" col="4">
> - <field name="date_start"/>
> - <field name="date_end"/>
> - </group>
> -
> - <separator string="Apply tax" colspan="4"/>
> -
> - <group colspan="4" col="4">
> - <field name="tax_id" colspan="4"/>
> - </group>
> -
> - <separator string="Filters" colspan="4"/>
> -
> - <group colspan="4" col="4">
> - <field name="partner_id" colspan="4"/>
> - </group>
> -
> - <separator colspan="4"/>
> -
> - <group colspan="4" col="4">
> - <button special="cancel" string="Cancel" icon="gtk-cancel"/>
> - <button name="check_report" string="Print" type="object" icon="gtk-print"/>
> - </group>
> - </form>
> - </field>
> - </record>
> -
> - <record id="action_contract_commission_wizard" model="ir.actions.act_window">
> - <field name="name">Calculation of commissions</field>
> - <field name="type">ir.actions.act_window</field>
> - <field name="res_model">contract.commission.wizard</field>
> - <field name="view_type">form</field>
> - <field name="view_mode">form</field>
> - <field name="view_id" ref="contract_commission_wizard_view"/>
> - <field name="target">new</field>
> - </record>
> -
> - <menuitem id="menu_group_contract_commissions" name="Commissions" parent="base.menu_contracts" sequence="10"/>
> - <menuitem name="Calculation of commissions" id="menu_contract_commission" parent="menu_group_contract_commissions" action="action_contract_commission_wizard"/>
> -
> - </data>
> + <data>
> + <record id="contract_commission_wizard_view" model="ir.ui.view">
> + <field name="name">Calculation of commissions</field>
> + <field name="model">contract.commission.wizard</field>
> + <field name="arch" type="xml">
> + <form string="Limites">
> + <separator string="Calculation of commissions"
> + colspan="4" />
> +
> + <group colspan="4" col="4">
> + <field name="date_start" />
> + <field name="date_end" />
> + </group>
> +
> + <separator string="Apply tax" colspan="4" />
> +
> + <group colspan="4" col="4">
> + <field name="tax_id" colspan="4" />
> + </group>
> +
> + <separator string="Filters" colspan="4" />
> +
> + <group colspan="4" col="4">
> + <field name="partner_id" colspan="4" />
> + </group>
> +
> + <separator colspan="4" />
> +
> + <group colspan="4" col="4">
> + <button special="cancel" string="Cancel"
> + icon="gtk-cancel" />
> + <button name="check_report" string="Print"
> + type="object" icon="gtk-print" />
> + </group>
> + </form>
> + </field>
> + </record>
> +
> + <record id="action_contract_commission_wizard" model="ir.actions.act_window">
> + <field name="name">Calculation of commissions</field>
> + <field name="type">ir.actions.act_window</field>
> + <field name="res_model">contract.commission.wizard</field>
> + <field name="view_type">form</field>
> + <field name="view_mode">form</field>
> + <field name="view_id" ref="contract_commission_wizard_view" />
> + <field name="target">new</field>
> + </record>
> +
> + <menuitem id="menu_group_contract_commissions" name="Commissions"
> + parent="base.menu_contracts" sequence="10" />
> + <menuitem name="Calculation of commissions" id="menu_contract_commission"
> + parent="menu_group_contract_commissions" action="action_contract_commission_wizard" />
> +
> + </data>
> </openerp>
>
> === modified file 'dos_contracts/wizard/sale_order_line.py'
> --- dos_contracts/wizard/sale_order_line.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/wizard/sale_order_line.py 2014-07-03 14:26:17 +0000
> @@ -19,11 +19,11 @@
> #
> ##############################################################################
>
> -from osv import fields, osv
> -
> -
> -class sale_order_split(osv.osv_memory):
> -
> +from osv import fields, orm
> +
> +
> +class SaleOrderSplit(orm.TransientModel):
> +
> _name = "sale.order.split"
> _description = "Split in Production lots"
>
> @@ -39,9 +39,11 @@
> if context is None:
> context = {}
>
> - res = super(sale_order_split, self).default_get(cr, uid, fields, context=context)
> + res = super(SaleOrderSplit, self).default_get(
> + cr, uid, fields, context=context)
> if context.get('active_id'):
> - line = self.pool.get('sale.order.line').browse(cr, uid, context['active_id'], context=context)
> + line = self.pool['sale.order.line'].browse(
> + cr, uid, context['active_id'], context=context)
> if 'product_id' in fields:
> res.update({'product_id': line.product_id.id})
> if 'product_uom' in fields:
> @@ -52,10 +54,12 @@
>
> _columns = {
> 'qty': fields.integer('Quantity'),
> - 'product_id': fields.many2one('product.product', 'Product', required=True, select=True),
> + 'product_id': fields.many2one('product.product', 'Product',
> + required=True, select=True),
> 'product_uom': fields.many2one('product.uom', 'UoM'),
> - 'line_exist_ids': fields.one2many('sale.order.split.lines.exist', 'lot_id', 'Production Lots'),
> - }
> + 'line_exist_ids': fields.one2many('sale.order.split.lines.exist',
> + 'lot_id', 'Production Lots'),
> + }
>
> def split_lot(self, cr, uid, ids, context=None):
> """ To split a lot
> @@ -88,7 +92,8 @@
> sale_line_obj = self.pool.get('sale.order.line')
> new_sale_line = []
> for data in self.browse(cr, uid, ids, context=context):
> - for sale_line in sale_line_obj.browse(cr, uid, sale_line_ids, context=context):
> + for sale_line in sale_line_obj.browse(
> + cr, uid, sale_line_ids, context=context):
> sale_line_qty = sale_line.product_uom_qty
> quantity_rest = sale_line.product_uom_qty
> uos_qty_rest = sale_line.product_uos_qty
> @@ -101,8 +106,10 @@
> if quantity <= 0 or sale_line_qty == 0:
> continue
> quantity_rest -= quantity
> - uos_qty = quantity / sale_line_qty * sale_line.product_uos_qty
> - uos_qty_rest = quantity_rest / sale_line_qty * sale_line.product_uos_qty
> + uos_qty = (quantity / sale_line_qty *
> + sale_line.product_uos_qty)
> + uos_qty_rest = (quantity_rest / sale_line_qty *
> + sale_line.product_uos_qty)
> if quantity_rest < 0:
> quantity_rest = quantity
> break
> @@ -112,44 +119,48 @@
> 'state': sale_line.state
> }
> if quantity_rest > 0:
> - current_sale_line = sale_line_obj.copy(cr, uid, sale_line.id, default_val, context=context)
> + current_sale_line = sale_line_obj.copy(
> + cr, uid, sale_line.id, default_val,
> + context=context)
> new_sale_line.append(current_sale_line)
>
> if quantity_rest == 0:
> current_sale_line = sale_line.id
> -
> - prodlot_id = line.prodlot_id and line.prodlot_id.id or False
> +
> + prodlot_id = (line.prodlot_id and
> + line.prodlot_id.id or False)
>
> if not prodlot_id:
> - prodlot_id = prodlot_obj.create(cr, uid, {
> - 'name': line.name,
> - 'product_id': sale_line.product_id.id},
> - context=context)
> + prodlot_id = prodlot_obj.create(
> + cr, uid, {'name': line.name,
> + 'product_id': sale_line.product_id.id},
> + context=context)
>
> - sale_line_obj.write(cr, uid, [current_sale_line], {'prodlot_id': prodlot_id, 'state':sale_line.state})
> + sale_line_obj.write(
> + cr, uid, [current_sale_line],
> + {'prodlot_id': prodlot_id, 'state': sale_line.state})
>
> update_val = {}
> if quantity_rest > 0:
> update_val['product_uom_qty'] = quantity_rest
> update_val['product_uos_qty'] = uos_qty_rest
> update_val['state'] = sale_line.state
> - sale_line_obj.write(cr, uid, [sale_line.id], update_val)
> + sale_line_obj.write(
> + cr, uid, [sale_line.id], update_val)
>
> return new_sale_line
>
> -sale_order_split()
>
> -class sale_order_split_lines_exist(osv.osv_memory):
> +class SaleOrderSplitLinesExist(orm.TransientModel):
> _name = "sale.order.split.lines.exist"
> _description = "Exist Split lines"
> _columns = {
> 'name': fields.char('Tracking serial', size=64),
> 'quantity': fields.integer('Quantity'),
> 'lot_id': fields.many2one('sale.order.split', 'Lot'),
> - 'prodlot_id': fields.many2one('stock.production.lot', 'Production Lot'),
> + 'prodlot_id': fields.many2one('stock.production.lot',
> + 'Production Lot'),
> }
> _defaults = {
> 'quantity': lambda *x: 1,
> }
> -
> -sale_order_split_lines_exist()
>
> === modified file 'dos_contracts/wizard/sale_order_line_view.xml'
> --- dos_contracts/wizard/sale_order_line_view.xml 2014-06-11 10:23:47 +0000
> +++ dos_contracts/wizard/sale_order_line_view.xml 2014-07-03 14:26:17 +0000
> @@ -3,55 +3,64 @@
> <data>
>
> <record id="view_sale_order_split" model="ir.ui.view">
> - <field name="name">Split in lots</field>
> - <field name="model">sale.order.split</field>
> - <field name="type">form</field>
> - <field name="arch" type="xml">
> - <form string="Split in lots">
> - <group width="660" height="275">
> - <field name="product_id" colspan="4" readonly="1"/>
> - <newline/>
> -
> - <group colspan="4" col="4">
> - <group colspan="1" col="2">
> - <field name="qty" readonly="1"/>
> - </group>
> - <group colspan="1" col="2">
> - <field name="product_uom" readonly="1"/>
> - </group>
> - </group>
> -
> - <group colspan="4">
> - <field name="line_exist_ids" colspan="4" nolabel="1">
> - <tree string="Production Lot Numbers" editable="bottom">
> - <field name="prodlot_id" string="Lot number" domain="[('product_id','=',parent.product_id)]"/>
> - <field name="quantity" />
> - </tree>
> - <form string="Production Lot Number">
> - <field name="prodlot_id" string="Lot number" domain="[('product_id','=',parent.product_id)]"/>
> - <field name="quantity" />
> - </form>
> - </field>
> - </group>
> -
> - <separator string="" colspan="4" />
> - <label string="" colspan="2" />
> - <button icon='gtk-cancel' special="cancel" string="Cancel" />
> - <button name="split_lot" string="Ok" type="object" icon="gtk-ok" />
> -
> - </group>
> - </form>
> - </field>
> - </record>
> -
> - <record id="act_sale_order_split" model="ir.actions.act_window">
> - <field name="name">Split in lots</field>
> - <field name="type">ir.actions.act_window</field>
> - <field name="res_model">sale.order.split</field>
> - <field name="view_type">form</field>
> - <field name="view_mode">form</field>
> - <field name="target">new</field>
> - </record>
> -
> - </data>
> + <field name="name">Split in lots</field>
> + <field name="model">sale.order.split</field>
> + <field name="arch" type="xml">
> + <form string="Split in lots">
> + <group width="660" height="275">
> + <field name="product_id" colspan="4"
> + readonly="1" />
> + <newline />
> +
> + <group colspan="4" col="4">
> + <group colspan="1" col="2">
> + <field name="qty" readonly="1" />
> + </group>
> + <group colspan="1" col="2">
> + <field name="product_uom"
> + readonly="1" />
> + </group>
> + </group>
> +
> + <group colspan="4">
> + <field name="line_exist_ids" colspan="4"
> + nolabel="1">
> + <tree string="Production Lot Numbers"
> + editable="bottom">
> + <field name="prodlot_id"
> + string="Lot number"
> + domain="[('product_id','=',parent.product_id)]" />
> + <field name="quantity" />
> + </tree>
> + <form string="Production Lot Number">
> + <field name="prodlot_id"
> + string="Lot number"
> + domain="[('product_id','=',parent.product_id)]" />
> + <field name="quantity" />
> + </form>
> + </field>
> + </group>
> +
> + <separator string="" colspan="4" />
> + <label string="" colspan="2" />
> + <button icon='gtk-cancel' special="cancel"
> + string="Cancel" />
> + <button name="split_lot" string="Ok"
> + type="object" icon="gtk-ok" />
> +
> + </group>
> + </form>
> + </field>
> + </record>
> +
> + <record id="act_sale_order_split" model="ir.actions.act_window">
> + <field name="name">Split in lots</field>
> + <field name="type">ir.actions.act_window</field>
> + <field name="res_model">sale.order.split</field>
> + <field name="view_type">form</field>
> + <field name="view_mode">form</field>
> + <field name="target">new</field>
> + </record>
> +
> + </data>
> </openerp>
>
> === modified file 'dos_contracts/wizard/sale_order_print_labels.py'
> --- dos_contracts/wizard/sale_order_print_labels.py 2014-06-11 10:23:47 +0000
> +++ dos_contracts/wizard/sale_order_print_labels.py 2014-07-03 14:26:17 +0000
> @@ -20,117 +20,127 @@
>
> import wizard
> import pooler
> -import tools
>
> from tools.translate import _
> -from osv import fields,osv
> -import time
> +from osv import osv
> import netsvc
> -from tools.misc import UpdateableStr, UpdateableDict
> import base64
>
> print_init_form = '''<?xml version="1.0" encoding="utf-8"?>
> <form string="Print Production Labels">
> - <separator string="The following production labels will be print:" colspan="4"/>
> - <field name="text_print" nolabel="1" colspan="4" width="600" height="250" />
> - <newline />
> + <separator string="The following production labels will be print:" colspan="4"/>
> + <field name="text_print" nolabel="1" colspan="4" width="600" height="250" />
> + <newline />
> </form>'''
>
> print_init_fields = {
> - 'text_print': {'string':'Message', 'type':'text', 'readonly':True},
> + 'text_print': {'string': 'Message', 'type': 'text', 'readonly': True},
> }
>
> print_done_form = '''<?xml version="1.0" encoding="utf-8"?>
> <form string="Print Production Labels">
> - <separator string="Production labels have been successfully sent to print" colspan="4"/>
> - <field name="qty_labels"/>
> + <separator string="Production labels have been successfully sent to print" colspan="4"/>
> + <field name="qty_labels"/>
> </form>'''
>
> print_done_fields = {
> - 'qty_labels': {'string':'Printed Labels', 'type':'integer', 'readonly': True},
> + 'qty_labels': {'string': 'Printed Labels',
> + 'type': 'integer',
> + 'readonly': True},
> }
>
>
> def _get_defaults(self, cr, uid, data, context):
> - p = pooler.get_pool(cr.dbname)
> - user = p.get('res.users').browse(cr, uid, uid, context)
> -
> - text_print = ''
> - i = 0
> -
> - orders = p.get(data['model']).browse(cr, uid, data['ids'], context)
> -
> - for order in orders:
> -
> - i += 1
> - name = order.name or ''
> - ref = order.client_order_ref or ''
> -
> - text_print += str(i) + '. ' + name + ' - ' + ref + '\n'
> -
> - return {'text_print': text_print}
> + p = pooler.get_pool(cr.dbname)
> +
> + text_print = ''
> + i = 0
> +
> + orders = p.get(data['model']).browse(cr, uid, data['ids'], context)
> +
> + for order in orders:
> +
> + i += 1
> + name = order.name or ''
> + ref = order.client_order_ref or ''
> +
> + text_print += str(i) + '. ' + name + ' - ' + ref + '\n'
> +
> + return {'text_print': text_print}
>
>
> def create_report(cr, uid, res_ids, report_name=False, context={}):
> - if not report_name or not res_ids:
> - raise osv.except_osv(_('Error !'),_('Report name and Resources ids are required !!!'))
> -
> - try:
> - service = netsvc.LocalService("report."+report_name);
> - result, format = service.create(cr, uid, res_ids, {}, context)
> -
> - except Exception,e:
> - print 'Exception in create report:',e
> - raise osv.except_osv(_('Error !'),_('Exception in create report.'))
> -
> - return result, format
> + if not report_name or not res_ids:
> + raise osv.except_osv(
> + _('Error !'),
> + _('Report name and Resources ids are required !!!'))
> +
> + try:
> + service = netsvc.LocalService("report." + report_name)
> + result, format = service.create(cr, uid, res_ids, {}, context)
> +
> + except Exception, e:
> + print 'Exception in create report:', e
> + raise osv.except_osv(_('Error !'), _('Exception in create report.'))
> +
> + return result, format
>
>
> def _print_labels(self, cr, uid, data, context):
> - import re
> - p = pooler.get_pool(cr.dbname)
> - user = p.get('res.users').browse(cr, uid, uid, context)
> -
> - report_obj = p.get('ir.actions.report.xml')
> - printer_obj = p.get('printing.printer')
> -
> - qty_labels = 0
> -
> - # Obtenemos la impresora Brother-QL-1060N-62x29
> - default_printer = printer_obj.search(cr, uid, [('system_name', '=', 'Brother-QL-1060N-62x29')])
> -
> - if default_printer:
> - default_printer = default_printer[0]
> - printer = printer_obj.browse(cr, uid, default_printer, context).system_name
> - else:
> - raise osv.except_osv(_('Error !'),_('Not found any default printer. Please set the default printer.'))
> -
> -
> - orders = p.get(data['model']).browse(cr, uid, data['ids'], context)
> -
> - for order in orders:
> -
> - # Creamos informe
> - result, format = create_report(cr, uid, [order.id], 'sale.order.ref.label.report', context={})
> -
> - # Imprimimos informe (dos etiquetas de sim)
> - report_obj.print_direct(cr, uid, base64.encodestring(result), format, printer)
> -
> - qty_labels += 1
> -
> - return {'qty_labels': qty_labels}
> -
> -
> -class print_labels(wizard.interface):
> - states = {
> - 'init': {
> - 'actions': [_get_defaults],
> - 'result': {'type': 'form', 'arch': print_init_form, 'fields': print_init_fields, 'state':[('end','Cancel'), ('done','Print')]}
> - },
> - 'done': {
> - 'actions': [_print_labels],
> - 'result': {'type': 'form', 'arch': print_done_form, 'fields': print_done_fields, 'state': [('end', 'Close')] }
> - }
> - }
> -
> -print_labels('sale.order.print_labels')
> + p = pooler.get_pool(cr.dbname)
> +
> + report_obj = p.get('ir.actions.report.xml')
> + printer_obj = p.get('printing.printer')
> +
> + qty_labels = 0
> +
> + # Obtenemos la impresora Brother-QL-1060N-62x29
> + default_printer = printer_obj.search(
> + cr, uid, [('system_name', '=', 'Brother-QL-1060N-62x29')])
> +
> + if default_printer:
> + default_printer = default_printer[0]
> + printer = printer_obj.browse(
> + cr, uid, default_printer, context).system_name
> + else:
> + raise osv.except_osv(
> + _('Error !'),
> + _('Not found any default printer. '
> + 'Please set the default printer.'))
> +
> + orders = p.get(data['model']).browse(cr, uid, data['ids'], context)
> +
> + for order in orders:
> + # Creamos informe
> + result, format = create_report(
> + cr, uid, [order.id], 'sale.order.ref.label.report', context={})
> +
> + # Imprimimos informe (dos etiquetas de sim)
> + report_obj.print_direct(
> + cr, uid, base64.encodestring(result), format, printer)
> +
> + qty_labels += 1
> +
> + return {'qty_labels': qty_labels}
> +
> +
> +# MIRAR MODULO dos_mrp_production_report MIGRADO POR DANI
> +class PrintLabels(wizard.interface):
> + states = {
> + 'init': {
> + 'actions': [_get_defaults],
> + 'result': {'type': 'form',
> + 'arch': print_init_form,
> + 'fields': print_init_fields,
> + 'state': [('end', 'Cancel'), ('done', 'Print')]}
> + },
> + 'done': {
> + 'actions': [_print_labels],
> + 'result': {'type': 'form',
> + 'arch': print_done_form,
> + 'fields': print_done_fields,
> + 'state': [('end', 'Close')]}
> + }
> + }
> +
> +PrintLabels('sale.order.print_labels')
>
--
https://code.launchpad.net/~oihanecruce/avanzosc/dos_contracts/+merge/224976
Your team Avanzosc_security is subscribed to branch lp:~avanzosc-security-team/avanzosc/72horas.