avanzosc team mailing list archive
-
avanzosc team
-
Mailing list archive
-
Message #00628
Re: [Merge] lp:~oihanecruce/avanzosc/nayar_invoice_generator into lp:~avanzosc-security-team/avanzosc/72horas
Review: Needs Fixing code review
Comentarios inline.
Un saludo.
Diff comments:
> === modified file 'nayar_invoice_generator/__init__.py'
> --- nayar_invoice_generator/__init__.py 2014-06-11 10:23:47 +0000
> +++ nayar_invoice_generator/__init__.py 2014-07-04 09:27:08 +0000
> @@ -19,7 +19,5 @@
> #
> ##############################################################################
>
> -import invoice_generator
> -import wizard
> -
> -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> +from . import models
> +from . import wizard
>
> === modified file 'nayar_invoice_generator/__openerp__.py'
> --- nayar_invoice_generator/__openerp__.py 2014-06-11 10:23:47 +0000
> +++ nayar_invoice_generator/__openerp__.py 2014-07-04 09:27:08 +0000
> @@ -24,18 +24,24 @@
> "version": "1.0",
> "author": "Nayar Systems",
> "category": "Invoice",
> - "description": "This module takes care of the monthly billing of contracted services for each client.",
> - "depends" : ["sale", "stock", "account", "dos_contracts", "dos_mysql_connect"],
> - "init_xml": [],
> - "update_xml": [
> + "description": """
> + This module takes care of the monthly billing of contracted services
> + for each client.
> + """,
> + "depends": [
> + "sale",
> + "stock",
> + "account",
> + "dos_contracts",
> + "dos_mysql_connect",
> + ],
> + "data": [
> "wizard/wizard_invoice_generator_run_view.xml",
> - "invoice_generator_view.xml",
> + "views/invoice_generator_view.xml",
> "security/invoice_generator_security.xml",
> "security/ir.model.access.csv",
> - ],
> + ],
> "website": 'http://www.72horas.net/',
> "active": False,
> "installable": True
> }
> -
> -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
>
> === added directory 'nayar_invoice_generator/models'
> === added file 'nayar_invoice_generator/models/__init__.py'
> --- nayar_invoice_generator/models/__init__.py 1970-01-01 00:00:00 +0000
> +++ nayar_invoice_generator/models/__init__.py 2014-07-04 09:27:08 +0000
> @@ -0,0 +1,22 @@
> +# -*- coding: utf-8 -*-
> +##############################################################################
> +#
> +# OpenERP, Open Source Management Solution
> +# Copyright (C) 2013 Nayar Systems (<http://www.72horas.net/>)
> +#
> +# 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 invoice_generator
>
> === renamed file 'nayar_invoice_generator/invoice_generator.py' => 'nayar_invoice_generator/models/invoice_generator.py'
> --- nayar_invoice_generator/invoice_generator.py 2014-06-11 10:23:47 +0000
> +++ nayar_invoice_generator/models/invoice_generator.py 2014-07-04 09:27:08 +0000
> @@ -23,33 +23,35 @@
> from datetime import datetime
> from dateutil.relativedelta import relativedelta
> import logging
> -from osv import osv, fields
> +from openerp.osv import orm, fields
> import platform
> import sql_db
> import threading
> -from tools import config
> -from tools import tb
> -from tools.translate import _
> -import netsvc
> +from openerp.tools import config, tb
> +from openerp.tools.translate import _
> +from openerp import netsvc
>
> _RESULT_STATES = (
> ('running', 'Running'),
> ('done', 'Done'),
> ('exception', 'Exception'),
> - )
> -
> -class invoice_generator(osv.osv):
> +)
> +
> +
> +class InvoiceGenerator(orm.Model):
> _name = 'invoice.generator'
> _description = 'Invoice Generator'
>
> def _get_last_result(self, cr, uid, ids, field_name, arg, context=None):
> res = {}
> - result_obj = self.pool.get('invoice.generator.result')
> - states = dict(_RESULT_STATES)
> + result_obj = self.pool['invoice.generator.result']
> for i in ids:
> - result_ids = result_obj.search(cr, uid, [('generator_id', '=', i)], order='date desc')
> + result_ids = result_obj.search(cr, uid, [('generator_id', '=', i)],
> + order='date desc',
> + context=context)
> if result_ids:
> - res[i] = result_obj.read(cr, uid, result_ids[0], ['state'])['state']
> + res[i] = result_obj.read(cr, uid, result_ids[0],
> + ['state'])['state']
> else:
> res[i] = False
> return res
> @@ -58,57 +60,96 @@
> 'name': fields.char('Name', size=64, required=True),
> 'contract_annexes': fields.boolean('Annexes'),
> 'stock_pickings': fields.boolean('Pickings'),
> - 'partners': fields.many2many('res.partner', 'invoice_generator_partner', 'invoice_generator_id', 'partner_id', 'Partners'),
> - 'partners_action': fields.selection((('invoice', 'Invoice partners'), ('exclude', 'Exclude partners from invoicing')), 'Action', required=True),
> - 'contracts': fields.many2many('contract.contract', 'invoice_generator_contract', 'invoice_generator_id', 'contract_id', 'Contracts'),
> - 'contracts_action': fields.selection((('invoice', 'Invoice contracts'), ('exclude', 'Exclude contracts from invoicing')), 'Action', required=True),
> - 'pickings': fields.many2many('stock.picking', 'invoice_generator_picking', 'invoice_generator_id', 'picking_id', 'Pickings'),
> - 'pickings_action': fields.selection((('invoice', 'Invoice pickings'), ('exclude', 'Exclude pickings from invoicing')), 'Action', required=True),
> + 'partners': fields.many2many('res.partner',
> + 'invoice_generator_partner',
> + 'invoice_generator_id', 'partner_id',
> + 'Partners'),
> + 'partners_action': fields.selection(
> + (('invoice', 'Invoice partners'),
> + ('exclude', 'Exclude partners from invoicing')), 'Action',
> + required=True),
> + 'contracts': fields.many2many('contract.contract',
> + 'invoice_generator_contract',
> + 'invoice_generator_id', 'contract_id',
> + 'Contracts'),
> + 'contracts_action': fields.selection(
> + (('invoice', 'Invoice contracts'),
> + ('exclude', 'Exclude contracts from invoicing')), 'Action',
> + required=True),
> + 'pickings': fields.many2many('stock.picking',
> + 'invoice_generator_picking',
> + 'invoice_generator_id', 'picking_id',
> + 'Pickings'),
> + 'pickings_action': fields.selection(
> + (('invoice', 'Invoice pickings'),
> + ('exclude', 'Exclude pickings from invoicing')), 'Action',
> + required=True),
> 'active': fields.boolean('Active'),
> - 'result_ids': fields.one2many('invoice.generator.result', 'generator_id', 'Results', readonly=True),
> + 'result_ids': fields.one2many('invoice.generator.result',
> + 'generator_id', 'Results',
> + readonly=True),
> 'next_invoice_date': fields.date('Next Invoice Date'),
> 'next_generation_date': fields.date('Next Generation Date'),
> 'validate_invoices': fields.boolean('Validate invoices'),
> - 'last_result': fields.function(_get_last_result, method=True, type='selection', selection=_RESULT_STATES, string='Last Result'),
> - }
> + 'last_result': fields.function(_get_last_result, method=True,
> + type='selection',
> + selection=_RESULT_STATES,
> + string='Last Result'),
> + }
>
> _defaults = {
> 'contract_annexes': True,
> 'stock_pickings': True,
> - 'partners_action': lambda *a: 'invoice',
> - 'contracts_action': lambda *a: 'invoice',
> - 'pickings_action': lambda *a: 'invoice',
> + 'partners_action': 'invoice',
> + 'contracts_action': 'invoice',
> + 'pickings_action': 'invoice',
> 'active': True,
> 'validate_invoices': True,
> - }
> -
> -
> - def run_planned_generators(self, cr, uid, date=None, check_node=True, context=None):
> + }
> +
> + def run_planned_generators(self, cr, uid, date=None, check_node=True,
> + context=None):
> """ Lanza las facturaciones programadas """
>
> - if check_node and (platform.node() != config.get('prod_host') or cr.dbname != config.get('prod_db')):
> + if (check_node and (platform.node() != config.get('prod_host') or
> + cr.dbname != config.get('prod_db'))):
> return True
>
> if date is None:
> date = datetime.today().strftime("%Y-%m-%d")
>
> - generator_ids = self.search(cr, uid, [('next_invoice_date', '<=', date), ('active', '=', True)])
> + generator_ids = self.search(
> + cr, uid, [('next_invoice_date', '<=', date),
> + ('active', '=', True)], context=context)
> generators = self.browse(cr, uid, generator_ids)
> for generator in generators:
> # Lanzamos proceso de facturación
> - self.generate_invoices(cr, uid, generator.id, generator.next_invoice_date, generator.next_generation_date, runtype='planned')
> + self.generate_invoices(cr, uid, generator.id,
> + generator.next_invoice_date,
> + generator.next_generation_date,
> + runtype='planned')
> # Preparamos fechas para facturar el próximo mes
> - next_invoice_date = datetime.strptime(generator.next_invoice_date, "%Y-%m-%d") + relativedelta(months=1)
> - next_generation_date = datetime.strptime(generator.next_generation_date, "%Y-%m-%d") + relativedelta(months=1)
> - next_generation_date = next_generation_date.replace(day=calendar.monthrange(next_generation_date.year, next_generation_date.month)[1])
> - self.write(cr, uid, generator.id, {'next_invoice_date': next_invoice_date, 'next_generation_date': next_generation_date})
> + next_invoice_date = (datetime.strptime(
> + generator.next_invoice_date, "%Y-%m-%d") +
> + relativedelta(months=1))
> + next_generation_date = (datetime.strptime(
> + generator.next_generation_date, "%Y-%m-%d") +
> + relativedelta(months=1))
> + next_generation_date = next_generation_date.replace(
> + day=calendar.monthrange(next_generation_date.year,
> + next_generation_date.month)[1])
> + self.write(cr, uid, generator.id,
> + {'next_invoice_date': next_invoice_date,
> + 'next_generation_date': next_generation_date},
> + context=context)
>
> return True
>
> -
> - def generate_invoices(self, cr, uid, ids, invoice_date, generation_date, end_date=False, thread=False, runtype='manual', context=None):
> + def generate_invoices(self, cr, uid, ids, invoice_date, generation_date,
> + end_date=False, thread=False, runtype='manual',
> + context=None):
> # Creamos un contenedor de resultados
> - result_obj = self.pool.get('invoice.generator.result')
> + result_obj = self.pool['invoice.generator.result']
> new = {
> 'generator_id': ids,
> 'invoice_date': invoice_date,
> @@ -116,18 +157,20 @@
> 'end_date': end_date,
> 'runtype': runtype,
> 'state': 'running',
> - }
> + }
> result_id = result_obj.create(cr, uid, new)
> cr.commit()
>
> # Ejecutamos la generación de facturas
> if thread:
> - process_thread = threading.Thread(target=self._run_generate_invoices, args=(cr.dbname, uid, ids, result_id, context))
> + process_thread = threading.Thread(
> + target=self._run_generate_invoices,
> + args=(cr.dbname, uid, ids, result_id, context))
> process_thread.start()
> return (process_thread, result_id)
> else:
> - return self._run_generate_invoices(cr.dbname, uid, ids, result_id, context)
> -
> + return self._run_generate_invoices(cr.dbname, uid, ids, result_id,
> + context)
>
> def get_next_expiration_date(self, annexe):
> "Devuelve la próxima fecha 'pagado hasta' del anexo"
> @@ -146,86 +189,101 @@
> if not delta:
> return False
>
> - new_expiration_date = datetime.strptime(annexe.expiration_date, "%Y-%m-%d") + delta
> - new_expiration_date = new_expiration_date.replace(day=calendar.monthrange(new_expiration_date.year, new_expiration_date.month)[1])
> + new_expiration_date = (datetime.strptime(
> + annexe.expiration_date, "%Y-%m-%d") + delta)
> + new_expiration_date = (new_expiration_date.replace(
> + day=calendar.monthrange(new_expiration_date.year,
> + new_expiration_date.month)[1]))
> return new_expiration_date
>
> -
> def calculate_months(self, start_date, end_date):
> start_date = datetime.strptime(start_date, '%Y-%m-%d')
> end_date = datetime.strptime(end_date, '%Y-%m-%d')
>
> # Comprobamos que las dos fechas sean final de mes
> # o el numero de dia sea igual
> - equal_days = ((start_date.day == end_date.day) and (start_date != end_date))
> + equal_days = ((start_date.day == end_date.day) and
> + (start_date != end_date))
> start_month_1 = start_date.day == 1
> - end_month_1 = start_date.day == calendar.monthrange(start_date.year, start_date.month)[1]
> - end_month_2 = end_date.day == calendar.monthrange(end_date.year, end_date.month)[1]
> -
> + end_month_1 = (start_date.day ==
> + calendar.monthrange(start_date.year,
> + start_date.month)[1])
> + end_month_2 = (end_date.day ==
> + calendar.monthrange(end_date.year, end_date.month)[1])
> +
> if (end_month_1 and end_month_2) or equal_days:
> - months = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month)
> -
> + months = ((end_date.year - start_date.year) * 12 +
> + (end_date.month - start_date.month))
> +
> # Si el dia de la fecha inicial es primero de mes y
> # el dia de la fecha de fin es final de mes
> elif start_month_1 and end_month_2:
> - months = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month + 1)
> + months = ((end_date.year - start_date.year) * 12 +
> + (end_date.month - start_date.month + 1))
>
> # Si no son final de mes, obtenemos media mensual
> else:
> - month_days = calendar.monthrange(start_date.year, start_date.month)[1] * 1.00
> -
> + month_days = calendar.monthrange(start_date.year,
> + start_date.month)[1] * 1.00
> +
> if start_date.month == end_date.month:
> - delta = end_date - start_date
> + delta = end_date - start_date
> days = delta.days
> months = days / month_days
> else:
> - days = calendar.monthrange(start_date.year, start_date.month)[1]
> - end_date_aux = datetime(start_date.year, start_date.month, days, 0, 0, 0)
> - start_date_aux = end_date_aux + relativedelta(days=+1)
> - months = self.calculate_months(start_date.strftime('%Y-%m-%d'), end_date_aux.strftime('%Y-%m-%d')) + self.calculate_months(start_date_aux.strftime('%Y-%m-%d'), end_date.strftime('%Y-%m-%d'))
> -
> + days = calendar.monthrange(start_date.year,
> + start_date.month)[1]
> + end_date_aux = datetime(start_date.year,
> + start_date.month, days, 0, 0, 0)
> + start_date_aux = end_date_aux + relativedelta(days=+1)
> + months = self.calculate_months(
> + start_date.strftime('%Y-%m-%d'),
> + (end_date_aux.strftime('%Y-%m-%d')) +
> + self.calculate_months(start_date_aux.strftime('%Y-%m-%d')),
> + end_date.strftime('%Y-%m-%d'))
> +
> return months
> -
> -
> +
> def get_total_invoice(self, cr, uid, contract, generation_date):
> """
> - Total de facturación de un contrato desde la fecha de vencimiento de sus anexos
> - hasta la fecha de generación
> + Total de facturación de un contrato desde la fecha de vencimiento de
> + sus anexos hasta la fecha de generación
> """
> total = 0.0
> -
> +
> if contract and generation_date:
> for annexe in contract.contract_annexe_ids:
> if annexe.expiration_date < generation_date:
> num_cabins = annexe.num_cabins
> - price_cabins = num_cabins > 1 and ((num_cabins - 1) * (annexe.extra_cabin_price or 0)) or 0
> + price_cabins = (num_cabins > 1 and
> + ((num_cabins - 1) *
> + (annexe.extra_cabin_price or 0)) or 0)
> price_unit = (annexe.fixed_price or 0) + price_cabins
> - months = self.calculate_months(annexe.expiration_date, generation_date)
> + months = self.calculate_months(annexe.expiration_date,
> + generation_date)
> price_unit = price_unit * months
> #discount = annexe.differential_price or 0
> -
> +
> total += price_unit
> -
> +
> return total
>
> -
> def is_minimum_amount(self, cr, uid, contract, generation_date):
> """
> - - Si el total de la factura no alcanza el precio fijo definido en el contrato devolvemos False
> + - Si el total de la factura no alcanza el precio fijo definido en el
> + contrato devolvemos False
> - Si por el contrario si lo alcanza o lo iguala devolvemos True
> """
> -
> +
> if contract and generation_date:
> fixed_price = contract.fixed_price
> total = self.get_total_invoice(cr, uid, contract, generation_date)
> -
> +
> return (fixed_price <= total)
> -
> return False
>
> -
> def _get_customer_refs(self, cr, uid):
> - mysql_obj = self.pool.get('mysql.connect')
> + mysql_obj = self.pool['mysql.connect']
> mysql_obj.open_connection(cr, uid)
> refs = mysql_obj.query("SELECT n_telefono, ref_cliente FROM telefonos")
> mysql_obj.close_connection()
> @@ -240,27 +298,27 @@
>
> return customer_refs
>
> -
> - def _run_generate_invoices(self, db_name, uid, ids, result_id, context=None):
> + def _run_generate_invoices(self, db_name, uid, ids, result_id,
> + context=None):
> logger = logging.getLogger("Invoicing")
> - result_obj = self.pool.get('invoice.generator.result')
> + result_obj = self.pool['invoice.generator.result']
> conn = sql_db.db_connect(db_name)
> cr = conn.cursor()
> - th = None
>
> if context is None:
> context = {}
> -
> +
> logger.info("#### Invoice generation started ####")
> process_output = _("\n#### Invoice generation started ####\n")
> - result_obj.write(cr, uid, result_id, {'result': process_output}, context=context)
> + result_obj.write(cr, uid, result_id, {'result': process_output},
> + context=context)
>
> try:
> data = result_obj.browse(cr, uid, result_id)
> invoice_date = data.invoice_date
> generation_date = data.generation_date
> end_invoice_date = data.end_date
> -
> +
> data = self.browse(cr, uid, ids)
> partners = data.partners
> partners_action = data.partners_action
> @@ -276,59 +334,76 @@
>
> if generation_date:
>
> - annexe_obj = self.pool.get('contract.annexe')
> - invoice_obj = self.pool.get('account.invoice')
> - invoice_line_obj = self.pool.get('account.invoice.line')
> - stock_picking_obj = self.pool.get('stock.picking')
> - stock_move_obj = self.pool.get('stock.move')
> - journal_obj = self.pool.get('account.journal')
> - product_obj = self.pool.get('product.product')
> - partner_obj = self.pool.get('res.partner')
> - address_obj = self.pool.get('res.partner.address')
> - bank_obj = self.pool.get('res.partner.bank')
> + annexe_obj = self.pool['contract.annexe']
> + invoice_obj = self.pool['account.invoice']
> + invoice_line_obj = self.pool['account.invoice.line']
> + picking_obj = self.pool['stock.picking']
> + stock_move_obj = self.pool['stock.move']
> + journal_obj = self.pool['account.journal']
> + product_obj = self.pool['product.product']
> + partner_obj = self.pool['res.partner']
> + bank_obj = self.pool['res.partner.bank']
>
> - user = self.pool.get('res.users').browse(cr, uid, uid)
> + user = self.pool['res.users'].browse(cr, uid, uid,
> + context=context)
> company_id = user.company_id
>
> # Obtenemos referencias de clientes desde 72horas
> customer_refs = self._get_customer_refs(cr, uid)
>
> - journal_ids = journal_obj.search(cr, uid, [('type', '=', 'sale'), ('company_id', '=', company_id.id)], limit=1)
> + journal_ids = journal_obj.search(
> + cr, uid, [('type', '=', 'sale'),
> + ('company_id', '=', company_id.id)], limit=1)
propagar context
> if not journal_ids:
> - raise osv.except_osv(_('Error !'),
> - _('There is no sales journal defined for this company: "%s" (id:%d)') % (company_id.name, company_id.id))
> + raise orm.except_orm(
> + _('Error !'),
> + _('There is no sales journal defined for this company:'
> + ' "%s" (id:%d)') % (company_id.name, company_id.id))
>
> - # Fecha de generacion de facturas, inicio de mes de la fecha de generacion
> - inv_generation_date = datetime.strptime(generation_date, '%Y-%m-%d')
> + # Fecha de generacion de facturas, inicio de mes de la
> + # fecha de generacion
> + inv_generation_date = datetime.strptime(generation_date,
> + '%Y-%m-%d')
> inv_generation_date = inv_generation_date.strftime('%Y-%m-01')
>
> partner_invoices = {}
>
> # Obtenemos facuras de clientes con servicios a generar
> - # -------------------------------------------------------------------------------------------
> + # -------------------------------------------------------------
> if contract_annexes:
> logger.info("## Annexe invoice generation ##")
> process_output += _("\n## Annexe invoice generation ##\n")
> - result_obj.write(cr, uid, result_id, {'result': process_output}, context=context)
> + result_obj.write(cr, uid, result_id,
> + {'result': process_output},
> + context=context)
>
> sql = " SELECT a.id FROM contract_annexe a "
> - sql += "INNER JOIN contract_contract c ON a.contract_id=c.id "
> + sql += "INNER JOIN contract_contract c"
> + sql += " ON a.contract_id=c.id "
> sql += "WHERE a.active_annexe=true "
> - sql += "AND COALESCE(a.expiration_date, '" + inv_generation_date + "') < '" + inv_generation_date + "' "
> - sql += "AND COALESCE(c.closing_date, '" + inv_generation_date + "') >= '" + inv_generation_date + "' "
> - sql += "AND COALESCE(a.closing_date, '" + inv_generation_date + "') >= '" + inv_generation_date + "' "
> + sql += "AND COALESCE(a.expiration_date, '"
> + sql += inv_generation_date + "') < '"
> + sql += inv_generation_date + "' "
> + sql += "AND COALESCE(c.closing_date, '"
> + sql += inv_generation_date + "') >= '"
> + sql += inv_generation_date + "' "
> + sql += "AND COALESCE(a.closing_date, '"
> + sql += inv_generation_date + "') >= '"
> + sql += inv_generation_date + "' "
>
> if partners:
> sql += "AND c.customer_id "
> if partners_action == "exclude":
> sql += "NOT "
> - sql += "IN (" + ", ".join([str(p.id) for p in partners]) + ") "
> + sql += "IN ("
> + sql += ", ".join([str(p.id) for p in partners]) + ") "
>
> if contracts:
> sql += "AND c.id "
> if contracts_action == "exclude":
> sql += "NOT "
> - sql += "IN (" + ", ".join([str(c.id) for c in contracts]) + ") "
> + sql += "IN ("
> + sql += ", ".join([str(c.id) for c in contracts]) + ") "
>
> sql += "ORDER BY c.customer_id, c.id"
>
> @@ -340,37 +415,58 @@
> current_partner_id = None
> current_contract_id = None
>
> - for annexe in annexe_obj.browse(cr, uid, annexe_ids, context=None):
> -
> + for annexe in annexe_obj.browse(cr, uid, annexe_ids,
> + context=None):
> if annexe.product_id or annexe.product_2_id:
> -
> - new_invoice = current_partner_id != annexe.contract_id.customer_id.id
> -
> + new_invoice = (current_partner_id !=
> + annexe.contract_id.customer_id.id)
> if new_invoice:
> -
> partner = annexe.contract_id.customer_id
>
> current_partner_id = partner.id
> current_contract_id = annexe.contract_id.id
>
> - logger.info("[%s] %s" % (partner.ref, partner.name))
> - process_output += "[%s] %s\n" % (partner.ref, partner.name)
> - result_obj.write(cr, uid, result_id, {'result': process_output}, context=context)
> + logger.info("[%s] %s" %
> + (partner.ref, partner.name))
> + process_output += ("[%s] %s\n" %
> + (partner.ref, partner.name))
> + result_obj.write(cr, uid, result_id,
> + {'result': process_output},
> + context=context)
>
> #Creamos factura
> - account = partner.property_account_receivable.id or False
> - address = partner_obj.address_get(cr, uid, [current_partner_id], ['invoice', 'contact'])
> - currency_id = partner.property_product_pricelist and partner.property_product_pricelist.id or False
> - payment_term = partner.property_payment_term and partner.property_payment_term.id or False
> - payment_type = partner.payment_type_customer and partner.payment_type_customer.id or False
> + account = (
> + partner.property_account_receivable.id or
> + False)
> + address = partner_obj.address_get(
> + cr, uid, [current_partner_id], ['invoice',
> + 'contact'])
> + currency_id = (
> + partner.property_product_pricelist and
> + partner.property_product_pricelist.id or
> + False)
> + payment_term = (
> + partner.property_payment_term and
> + partner.property_payment_term.id or False)
> + payment_type = (
> + partner.payment_type_customer and
> + partner.payment_type_customer.id or False)
> fiscal_position = partner.property_account_position
> contact_id = False
>
> - if address['contact']:
> - addr = self.pool.get('res.partner.address').read(cr, uid, address['contact'], ['job_ids'], context=None)
> - contact_id = addr and addr['job_ids'] and addr['job_ids'][0] or False
> +# if address['contact']:
> +# addr_obj = self.pool['res.partner.address']
> +# addr = addr_obj.read(cr, uid,
> +# address['contact'],
> +# ['job_ids'],
> +# context=None)
> +# contact_id = (addr and addr['job_ids'] and
> +# addr['job_ids'][0] or False)
Esto se pondría simplemente como:
contact_id = address['contact']
Pero es necesario, ya que el contact_id está presente.
>
> - bank_ids = bank_obj.search(cr, uid, [('partner_id', '=', current_partner_id)], order="default_bank desc", context=context)
> + bank_ids = bank_obj.search(
> + cr, uid, [('partner_id', '=',
> + current_partner_id)],
> + order="default_bank desc", context=context)
>
> invoice = {
> 'origin': origin,
> @@ -378,9 +474,16 @@
> 'reference': False,
> 'account_id': account,
> 'partner_id': current_partner_id,
> - 'partner_bank_id': bank_ids and bank_ids[0] or False,
> - 'elevator_partner_id': annexe.contract_id.elevator_id and annexe.contract_id.elevator_id.id or False,
> - 'middleman_partner_id': annexe.contract_id.middleman_id and annexe.contract_id.middleman_id.id or False,
> + 'partner_bank_id': (bank_ids and
> + bank_ids[0] or False),
> + 'elevator_partner_id': (
> + annexe.contract_id.elevator_id and
> + annexe.contract_id.elevator_id.id or
> + False),
> + 'middleman_partner_id': (
> + annexe.contract_id.middleman_id and
> + annexe.contract_id.middleman_id.id or
> + False),
> 'journal_id': journal_ids[0],
> 'address_invoice_id': address['invoice'],
> 'address_contact_id': address['contact'],
> @@ -389,57 +492,81 @@
> 'comment': False,
> 'payment_term': payment_term,
> 'payment_type': payment_type,
> - 'fiscal_position': fiscal_position and fiscal_position.id or False,
> + 'fiscal_position': (fiscal_position and
Poniendo sólo 'fiscal_position': fiscal_position.id valdría, ya que devuelve False en caso de fiscal_position sea browse_record_null.
> + fiscal_position.id or
> + False),
> 'invoice_date': invoice_date,
> 'contract_id': annexe.contract_id.id,
> 'company_id': company_id.id,
> 'user_id': False
> }
>
> - inv_id = invoice_obj.create(cr, uid, invoice, context=context)
> -
> - # Añadimos factura al diccionario de facturas por cliente.
> - # De esta manera sabremos que factura se ha creado para un cliente
> - partner_invoices[current_partner_id] = (inv_id, [])
> -
> - #Obtenemos referencia de cliente desde sistema externo
> + inv_id = invoice_obj.create(cr, uid, invoice,
> + context=context)
> +
> + # Añadimos factura al diccionario de facturas
> + # por cliente. De esta manera sabremos que
> + # factura se ha creado para un cliente
> + partner_invoices[current_partner_id] = (inv_id,
> + [])
> +
> + # Obtenemos referencia de cliente desde sistema
> + # externo
> customer_ref = None
> - phone = annexe.production_lot_id and annexe.production_lot_id.telefono
> + phone = (annexe.production_lot_id and
> + annexe.production_lot_id.telefono)
>
> if phone:
> customer_ref = customer_refs.get(phone)
>
> - #Creamos lineas de factura
> - service = annexe.product_id or (annexe.product_2_id or False)
> + # Creamos lineas de factura
> + service = annexe.product_id or (annexe.product_2_id
> + or False)
>
> a = service.product_tmpl_id.property_account_income.id
> if not a:
> a = service.categ_id.property_account_income_categ.id
>
> - name = (service.default_code and '[' + service.default_code + '] ' or '') + service.name
> -
> - #Obtenemos precio fijo anexo segun reglas definidas
> - fixed_price = annexe_obj.get_fixed_price(cr, uid, annexe.id)
> -
> - #Obtenemos fecha desde de generacion
> - start_generation_date = datetime.strptime(annexe.expiration_date, '%Y-%m-%d')
> - start_generation_date = start_generation_date + relativedelta(days=+1)
> -
> - start_date = start_generation_date.strftime('%Y-%m-%d')
> + name = (service.default_code and
> + '[' + service.default_code + '] ' or
> + '') + service.name
> +
> + # Obtenemos precio fijo anexo segun reglas definidas
> + fixed_price = annexe_obj.get_fixed_price(
> + cr, uid, annexe.id)
> +
> + # Obtenemos fecha desde de generacion
> + start_generation_date = datetime.strptime(
> + annexe.expiration_date, '%Y-%m-%d')
> + start_generation_date = (start_generation_date +
> + relativedelta(days=+1))
> +
> + start_date = start_generation_date.strftime(
> + '%Y-%m-%d')
> if end_invoice_date:
> end_date = end_invoice_date
> else:
> - end_date = self.get_next_expiration_date(annexe).strftime('%Y-%m-%d')
> + end_date = self.get_next_expiration_date(
> + annexe).strftime('%Y-%m-%d')
> num_cabins = annexe.num_cabins
> - price_cabins = num_cabins > 1 and ((num_cabins -1) * (annexe.extra_cabin_price or 0)) or 0
> + price_cabins = (num_cabins > 1 and
> + ((num_cabins - 1) *
> + (annexe.extra_cabin_price or 0))
> + or 0)
> price_unit = fixed_price + price_cabins
> discount = annexe.differential_price or 0
> - months = round(self.calculate_months(annexe.expiration_date, end_date), 2)
> + months = round(
> + self.calculate_months(annexe.expiration_date,
> + end_date), 2)
>
> price_unit = round(price_unit * months, 2)
>
> - account = self.pool.get('account.fiscal.position').map_account(cr, uid, fiscal_position, a)
> - taxes_id = self.pool.get('account.fiscal.position').map_tax(cr, uid, fiscal_position, service.taxes_id)
> + pos_obj = self.pool['account.fiscal.position']
> + account = pos_obj.map_account(cr, uid,
> + fiscal_position, a)
> + taxes_id = pos_obj.map_tax(cr, uid,
> + fiscal_position,
> + service.taxes_id)
>
> line = {
> 'name': name,
> @@ -448,7 +575,9 @@
> 'price_unit': price_unit,
> 'quantity': 1,
> 'discount': discount,
> - 'uos_id': service.uos_id.id or service.uom_id.id or False,
> + 'uos_id':
Pon mejor:
'uos_id': service.uos_id.id
> + (service.uos_id.id or service.uom_id.id or
> + False),
> 'product_id': service.id or False,
> 'invoice_line_tax_id': [(6, 0, taxes_id)],
> 'note': False,
> @@ -459,35 +588,45 @@
> 'end_date': end_date,
> 'contract_id': annexe.contract_id.id,
> 'contract_annexe_id': annexe.id,
> - 'customer_ref': customer_ref,
> + 'customer_ref': customer_ref,
> }
>
> - line_id = invoice_line_obj.create(cr, uid, line)
> - partner_invoices[current_partner_id][1].append(line_id)
> -
> - #Actualizamos fecha vencimiento del anexo, referencias de cliente y ultima linea de factura
> - result = annexe_obj.write(cr, uid, [annexe.id], {'expiration_date': end_date,
> - 'customer_ref': customer_ref,
> - 'invoice_line_id': line_id,
> - })
> -
> -
> - #Obtenemos líneas de albarán pendientes de facturar
> - #-------------------------------------------------------------------------------------------
> + line_id = invoice_line_obj.create(cr, uid, line,
> + context=context)
> + partner_invoices[current_partner_id][1].append(
> + line_id)
> +
> + # Actualizamos fecha vencimiento del anexo,
> + # referencias de cliente y ultima linea de factura
> + annexe_obj.write(
> + cr, uid, [annexe.id],
> + {'expiration_date': end_date,
> + 'customer_ref': customer_ref,
> + 'invoice_line_id': line_id},
> + context=context)
> +
> + # Obtenemos líneas de albarán pendientes de facturar
> + #--------------------------------------------------------------
> if stock_pickings:
> logger.info("## Stock picking invoice generation ##")
> - process_output += _("\n## Stock picking invoice generation ##\n")
> - result_obj.write(cr, uid, result_id, {'result': process_output}, context=context)
> + process_output += _("\n## Stock picking invoice "
> + "generation ##\n")
> + result_obj.write(
> + cr, uid, result_id, {'result': process_output},
> + context=context)
>
> # Para clientes con facturación normal
> - #---------------------------------------------------------------------------------------
> + #----------------------------------------------------------
> sql = "SELECT id "
> sql += "FROM ( "
> - sql += " SELECT p.partner_id, p.date, p.id As picking_id, m.id FROM stock_move m "
> + sql += " SELECT p.partner_id, p.date, p.id "
> + sql += " AS picking_id, m.id FROM stock_move m "
> sql += " INNER JOIN stock_picking p ON m.picking_id=p.id "
> sql += " INNER JOIN res_partner c ON p.partner_id=c.id "
> - sql += " LEFT JOIN stock_move_history_ids h ON m.id = h.child_id "
> - sql += " WHERE m.invoiced=false AND p.date < '" + invoice_date + "' "
> + sql += " LEFT JOIN stock_move_history_ids h"
> + sql += " ON m.id = h.child_id "
> + sql += " WHERE m.invoiced=false AND p.date < '"
> + sql += invoice_date + "' "
> sql += " AND p.type='out' and p.invoice_state='invoiced' "
> sql += " AND h.parent_id IS NULL "
>
> @@ -495,25 +634,33 @@
> sql += "AND p.partner_id "
> if partners_action == "exclude":
> sql += "NOT "
> - sql += "IN (" + ", ".join([str(p.id) for p in partners]) + ") "
> + sql += "IN (" + ", ".join(
> + [str(p.id) for p in partners]) + ") "
>
> if pickings:
> sql += "AND p.id "
> if pickings_action == "exclude":
> sql += "NOT "
> - sql += "IN (" + ", ".join([str(p.id) for p in pickings]) + ") "
> + sql += "IN (" + ", ".join(
> + [str(p.id) for p in pickings]) + ") "
>
> - sql += " AND p.company_id=" + str(company_id.id) + " "
> - sql += " AND m.receiver='cliente' "
> - sql += " AND c.special_invoicing != True "
> + sql += " AND p.company_id=" + str(company_id.id) + " "
> + sql += " AND m.receiver='cliente' "
> + sql += " AND c.special_invoicing != True "
>
> sql += " UNION "
>
> - sql += " SELECT p.elevator_partner_id As partner_id, p.date, p.id As picking_id, m.id FROM stock_move m "
> - sql += " INNER JOIN stock_picking p ON m.picking_id=p.id "
> - sql += " INNER JOIN res_partner c ON p.elevator_partner_id=c.id "
> - sql += " LEFT JOIN stock_move_history_ids h ON m.id = h.child_id "
> - sql += " WHERE m.invoiced=false AND p.date < '" + invoice_date + "' "
> + sql += " SELECT p.elevator_partner_id As partner_id, "
> + sql += " p.date, p.id As picking_id, m.id "
> + sql += " FROM stock_move m "
> + sql += " INNER JOIN stock_picking p "
> + sql += " ON m.picking_id=p.id "
> + sql += " INNER JOIN res_partner c "
> + sql += " ON p.elevator_partner_id=c.id "
> + sql += " LEFT JOIN stock_move_history_ids h "
> + sql += " ON m.id = h.child_id "
> + sql += " WHERE m.invoiced=false AND p.date < '"
> + sql += invoice_date + "' "
> sql += " AND p.type='out' and p.invoice_state='invoiced' "
> sql += " AND h.parent_id IS NULL "
>
> @@ -521,17 +668,19 @@
> sql += "AND p.elevator_partner_id "
> if partners_action == "exclude":
> sql += "NOT "
> - sql += "IN (" + ", ".join([str(p.id) for p in partners]) + ") "
> + sql += "IN (" + ", ".join(
> + [str(p.id) for p in partners]) + ") "
>
> if pickings:
> sql += "AND p.id "
> if pickings_action == "exclude":
> sql += "NOT "
> - sql += "IN (" + ", ".join([str(p.id) for p in pickings]) + ") "
> + sql += "IN (" + ", ".join(
> + [str(p.id) for p in pickings]) + ") "
>
> - sql += " AND p.company_id=" + str(company_id.id) + " "
> - sql += " AND m.receiver='ascensorista' "
> - sql += " AND c.special_invoicing != True "
> + sql += " AND p.company_id=" + str(company_id.id) + " "
> + sql += " AND m.receiver='ascensorista' "
> + sql += " AND c.special_invoicing != True "
>
> sql += ") t "
> sql += "ORDER BY partner_id, date, picking_id "
> @@ -543,32 +692,56 @@
>
> current_partner_id = None
>
> - for move in stock_move_obj.browse(cr, uid, move_ids, context=None):
> -
> - partner = move.picking_id.elevator_partner_id or move.picking_id.partner_id
> -
> + for move in stock_move_obj.browse(cr, uid, move_ids,
> + context=context):
> + partner = (move.picking_id.elevator_partner_id or
> + move.picking_id.partner_id)
>
> # Creamos factura para cliente, si es necesario
> if current_partner_id != partner.id:
>
> current_partner_id = partner.id
>
> - logger.info("[%s] %s" % (partner.ref, partner.name))
> - process_output += "[%s] %s\n" % (partner.ref, partner.name)
> - result_obj.write(cr, uid, result_id, {'result': process_output}, context=context)
> + logger.info("[%s] %s" % (partner.ref,
> + partner.name))
> + process_output += "[%s] %s\n" % (partner.ref,
> + partner.name)
> + result_obj.write(cr, uid, result_id,
> + {'result': process_output},
> + context=context)
>
> if not current_partner_id in partner_invoices:
> #Creamos factura
> - account = partner.property_account_receivable.id or False
> - address_invoice_id = move.picking_id.elevator_invoice_id and move.picking_id.elevator_invoice_id.id or False
> - address = self.pool.get('res.partner').address_get(cr, uid, [current_partner_id], ['invoice', 'contact'])
> - currency_id = partner.property_product_pricelist and partner.property_product_pricelist.id or False
> - payment_term = partner.property_payment_term and partner.property_payment_term.id or False
> - payment_type = partner.payment_type_customer and partner.payment_type_customer.id or False
> + account = (
Todos estos se pueden poner directamente el dato, y devolverá False directamente.
> + partner.property_account_receivable.id or
> + False)
> + address_invoice_id = (
> + move.picking_id.elevator_invoice_id and
> + move.picking_id.elevator_invoice_id.id or
> + False)
> + partner_obj = self.pool['res.partner']
> + address = partner_obj.address_get(
> + cr, uid, [current_partner_id], ['invoice',
> + 'contact'])
> + currency_id = (
> + partner.property_product_pricelist and
> + partner.property_product_pricelist.id or
> + False)
> + payment_term = (
> + partner.property_payment_term and
> + partner.property_payment_term.id or False)
> + payment_type = (
> + partner.payment_type_customer and
> + partner.payment_type_customer.id or False)
> fiscal_position = partner.property_account_position
> - contact_id = move.picking_id.contact_id and move.picking_id.contact_id.id or False
> + contact_id = (move.picking_id.contact_id and
> + move.picking_id.contact_id.id or
> + False)
>
> - bank_ids = bank_obj.search(cr, uid, [('partner_id', '=', current_partner_id)], order="default_bank desc", context=context)
> + bank_ids = bank_obj.search(
> + cr, uid, [('partner_id', '=',
> + current_partner_id)],
> + order="default_bank desc", context=context)
>
> invoice = {
> 'origin': origin,
> @@ -576,31 +749,43 @@
> 'reference': False,
> 'account_id': account,
> 'partner_id': current_partner_id,
> - 'partner_bank_id': bank_ids and bank_ids[0] or False,
> + 'partner_bank_id': (bank_ids and
> + bank_ids[0] or False),
> 'elevator_partner_id': False,
> 'middleman_partner_id': False,
> 'journal_id': journal_ids[0],
> - 'address_invoice_id': address_invoice_id or address['invoice'],
> + 'address_invoice_id': (
> + address_invoice_id or
> + address['invoice']),
> 'address_contact_id': address['contact'],
> 'contact_id': contact_id,
> 'currency_id': currency_id,
> 'comment': False,
> 'payment_term': payment_term,
> 'payment_type': payment_type,
> - 'fiscal_position': fiscal_position and fiscal_position.id or False,
> + 'fiscal_position': (fiscal_position and
> + fiscal_position.id or
> + False),
> 'invoice_date': invoice_date,
> - 'contract_id': move.contract_annexe_id and move.contract_annexe_id.contract_id and move.contract_annexe_id.contract_id.id or False,
> + 'contract_id': (
> + move.contract_annexe_id and
> + move.contract_annexe_id.contract_id and
> + move.contract_annexe_id.contract_id.id
> + or False),
> 'company_id': company_id.id,
> 'user_id': False
> }
>
> - inv_id = invoice_obj.create(cr, uid, invoice, context=None)
> -
> - # Añadimos factura al diccionario de facturas por cliente.
> - # De esta manera sabremos que factura se ha creado para un cliente
> - partner_invoices[current_partner_id] = (inv_id, [])
> -
> - #Creamos lineas de factura
> + inv_id = invoice_obj.create(cr, uid, invoice,
> + context=context)
> +
> + # Añadimos factura al diccionario de facturas
> + # por cliente. De esta manera sabremos que
> + # factura se ha creado para un cliente
> + partner_invoices[current_partner_id] = (inv_id,
> + [])
> +
> + # Creamos lineas de factura
> product = move.product_id or False
>
> a = product.product_tmpl_id.property_account_income.id
> @@ -608,49 +793,66 @@
> a = product.categ_id.property_account_income_categ.id
>
> inv_type = 'out_invoice'
> - name = (product.default_code and '[' + product.default_code + '] ' or '') + product.name
> - taxes_id = stock_picking_obj._get_taxes_invoice(cr, uid, move, inv_type)
> - account_analytic_id = stock_picking_obj._get_account_analytic_invoice(cr, uid, move.picking_id, move)
> - account = self.pool.get('account.fiscal.position').map_account(cr, uid, fiscal_position, a)
> + name = (product.default_code and
> + '[' + product.default_code + '] '
> + or '') + product.name
> + taxes_id = picking_obj._get_taxes_invoice(
> + cr, uid, move, inv_type)
> + account_analytic_id = picking_obj._get_account_analytic_invoice(
> + cr, uid, move.picking_id, move)
> + pos_obj = self.pool['account.fiscal.position']
> + account = pos_obj.map_account(cr, uid,
> + fiscal_position, a)
>
> uos_id = move.product_uos and move.product_uos.id or False
> - if not uos_id and inv_type in ('out_invoice', 'out_refund'):
> + if (not uos_id and
> + inv_type in ('out_invoice', 'out_refund')):
> uos_id = move.product_uom.id
>
> -
> - #Obtenemos referencia de cliente desde sistema externo
> - #----------------------------------------------------------------
> + # Obtenemos referencia de cliente desde sistema externo
> + #------------------------------------------------------
> customer_ref = None
>
> if move.contract_id and move.contract_annexe_id:
> - phone = move.contract_annexe_id.production_lot_id and move.contract_annexe_id.production_lot_id.telefono or move.contract_annexe_id.phone
> + phone = (move.contract_annexe_id.production_lot_id
> + and move.contract_annexe_id.production_lot_id.telefono
> + or move.contract_annexe_id.phone)
>
> if phone:
> customer_ref = customer_refs.get(phone)
>
> - #Si no obtenemos referencia, la buscamos en la linea de pedido origen
> - if not customer_ref and move.sale_line_id and move.sale_line_id.client_order_ref:
> + # Si no obtenemos referencia, la buscamos en la linea
> + # de pedido origen
> + if (not customer_ref and move.sale_line_id and
> + move.sale_line_id.client_order_ref):
> customer_ref = move.sale_line_id.client_order_ref
>
> - #Si no obtenemos referencia, la buscamos en el pedido origen
> - if not customer_ref and move.picking_id and move.picking_id.sale_id and move.picking_id.sale_id.client_order_ref:
> + # Si no obtenemos referencia, la buscamos en el pedido
> + # origen
> + if (not customer_ref and move.picking_id and
> + move.picking_id.sale_id and
> + move.picking_id.sale_id.client_order_ref):
> customer_ref = move.picking_id.sale_id.client_order_ref
>
> - #----------------------------------------------------------------
> + #------------------------------------------------------
>
> - price_unit = stock_picking_obj._get_price_unit_invoice(cr, uid, move, inv_type)
> - discount = stock_picking_obj._get_discount_invoice(cr, uid, move)
> + price_unit = picking_obj._get_price_unit_invoice(
> + cr, uid, move, inv_type)
> + discount = picking_obj._get_discount_invoice(cr, uid,
> + move)
> months = False
> start_date = False
> end_date = False
> num_cabins = 0
>
> # Calculamos precio producto si es una sim
> - if product_obj._is_sim(product.categ_id) and move.contract_id and move.contract_annexe_id:
> + if (product_obj._is_sim(product.categ_id) and
> + move.contract_id and move.contract_annexe_id):
> num_cabins = move.num_cabins
> months = round(move.months, 2)
> price_unit = round(price_unit * months, 2)
> - discount = move.contract_annexe_id.differential_price or 0
> + discount = (
> + move.contract_annexe_id.differential_price or 0)
> start_date = move.start_billing_date
> end_date = move.expiration_date
>
> @@ -659,7 +861,8 @@
> 'origin': origin,
> 'account_id': account,
> 'price_unit': price_unit,
> - 'quantity': move.product_uos_qty or move.product_qty,
> + 'quantity': (move.product_uos_qty or
> + move.product_qty),
> 'discount': discount,
> 'uos_id': uos_id,
> 'product_id': product.id or False,
> @@ -670,86 +873,104 @@
> 'num_cabins': num_cabins,
> 'start_date': start_date,
> 'end_date': end_date,
> - 'contract_id': move.contract_annexe_id and move.contract_annexe_id.contract_id and move.contract_annexe_id.contract_id.id or False,
> - 'contract_annexe_id': move.contract_annexe_id and move.contract_annexe_id.id or False,
> + 'contract_id': (
> + move.contract_annexe_id and
> + move.contract_annexe_id.contract_id and
> + move.contract_annexe_id.contract_id.id or
> + False),
> + 'contract_annexe_id': (
> + move.contract_annexe_id and
Poner directamente move.contract_annexe_id.id
> + move.contract_annexe_id.id or False),
> 'customer_ref': customer_ref,
> 'stock_move_id': move.id,
> }
>
> - line_id = invoice_line_obj.create(cr, uid, line, context=None)
> + line_id = invoice_line_obj.create(cr, uid, line,
> + context=context)
> partner_invoices[current_partner_id][1].append(line_id)
>
> - #Actualizamos movimiento a facturado
> - result = stock_move_obj.write(cr, uid, [move.id], {'state': 'done',
> - 'invoiced': True
> - })
> + # Actualizamos movimiento a facturado
> + stock_move_obj.write(
> + cr, uid, [move.id], {'state': 'done',
> + 'invoiced': True
> + },
> + context=context)
>
> - #Actualizamos fecha vencimiento del anexo, referencias de cliente y ultima linea de factura
> + # Actualizamos fecha vencimiento del anexo, referencias
> + # de cliente y ultima linea de factura
> if move.contract_id and move.contract_annexe_id:
> annexe_id = move.contract_annexe_id.id
> - result = annexe_obj.write(cr, uid, [annexe_id], {
> - 'customer_ref': customer_ref,
> - 'invoice_line_id': line_id,
> - })
> -
> + annexe_obj.write(
> + cr, uid, [annexe_id],
> + {'customer_ref': customer_ref,
> + 'invoice_line_id': line_id,
> + })
>
> # Para clientes con facturación especial
> - #---------------------------------------------------------------------------------------
> + #----------------------------------------------------------
> logger.info("## Special invoice generation ##")
> process_output += _("\n## Special invoice generation ##\n")
> - result_obj.write(cr, uid, result_id, {'result': process_output}, context=context)
> + result_obj.write(cr, uid, result_id,
> + {'result': process_output},
> + context=context)
>
> sql = "SELECT id "
> sql += "FROM ( "
> - sql += " SELECT p.partner_id, p.date, p.id As picking_id, m.id FROM stock_move m "
> + sql += " SELECT p.partner_id, p.date, p.id "
> + sql += " AS picking_id, m.id FROM stock_move m "
> sql += " INNER JOIN stock_picking p ON m.picking_id=p.id "
> sql += " INNER JOIN res_partner c ON p.partner_id=c.id "
> - sql += " WHERE m.invoiced=false AND p.date < '" + invoice_date + "' "
> + sql += " WHERE m.invoiced=false AND p.date < '"
> + sql += invoice_date + "' "
> sql += " AND p.type='out' and p.invoice_state='invoiced' "
>
> if partners:
> sql += "AND p.partner_id "
> if partners_action == "exclude":
> sql += "NOT "
> - sql += "IN (" + ", ".join([str(p.id) for p in partners]) + ") "
> + sql += "IN (" + ", ".join(
> + [str(p.id) for p in partners]) + ") "
>
> if pickings:
> sql += "AND p.id "
> if pickings_action == "exclude":
> sql += "NOT "
> - sql += "IN (" + ", ".join([str(p.id) for p in pickings]) + ") "
> -
> - sql += " AND p.company_id=" + str(company_id.id) + " "
> - sql += " AND m.receiver='cliente' "
> - sql += " AND c.special_invoicing = True "
> -
> + sql += "IN (" + ", ".join(
> + [str(p.id) for p in pickings]) + ") "
> + sql += " AND p.company_id=" + str(company_id.id) + " "
> + sql += " AND m.receiver='cliente' "
> + sql += " AND c.special_invoicing = True "
> sql += " UNION "
> -
> - sql += " SELECT p.elevator_partner_id As partner_id, p.date, p.id As picking_id, m.id FROM stock_move m "
> - sql += " INNER JOIN stock_picking p ON m.picking_id=p.id "
> - sql += " INNER JOIN res_partner c ON p.elevator_partner_id=c.id "
> - sql += " WHERE m.invoiced=false AND p.date < '" + invoice_date + "' "
> + sql += " SELECT p.elevator_partner_id AS partner_id, "
> + sql += " p.date, p.id AS picking_id, m.id "
> + sql += " FROM stock_move m "
> + sql += " INNER JOIN stock_picking p "
> + sql += " ON m.picking_id=p.id "
> + sql += " INNER JOIN res_partner c "
> + sql += " ON p.elevator_partner_id=c.id "
> + sql += " WHERE m.invoiced=false AND p.date < '"
> + sql += invoice_date + "' "
> sql += " AND p.type='out' and p.invoice_state='invoiced' "
>
> if partners:
> sql += "AND p.elevator_partner_id "
> if partners_action == "exclude":
> sql += "NOT "
> - sql += "IN (" + ", ".join([str(p.id) for p in partners]) + ") "
> + sql += "IN (" + ", ".join(
> + [str(p.id) for p in partners]) + ") "
>
> if pickings:
> sql += "AND p.id "
> if pickings_action == "exclude":
> sql += "NOT "
> - sql += "IN (" + ", ".join([str(p.id) for p in pickings]) + ") "
> -
> - sql += " AND p.company_id=" + str(company_id.id) + " "
> - sql += " AND m.receiver='ascensorista' "
> - sql += " AND c.special_invoicing = True "
> -
> + sql += "IN (" + ", ".join(
> + [str(p.id) for p in pickings]) + ") "
> +
> + sql += " AND p.company_id=" + str(company_id.id) + " "
> + sql += " AND m.receiver='ascensorista' "
> + sql += " AND c.special_invoicing = True "
> sql += ") t "
> sql += "ORDER BY partner_id, date, picking_id "
> -
> cr.execute(sql)
>
> results = cr.fetchall()
> @@ -757,43 +978,70 @@
>
> current_partner_id = None
> current_picking_id = None
> - rest_inv_id= None
> + rest_inv_id = None
> ship_move_id = proportional_cost = remaining_cost = None
>
> - for move in stock_move_obj.browse(cr, uid, move_ids, context=None):
> + for move in stock_move_obj.browse(cr, uid, move_ids,
> + context=context):
>
> - # Obtenemos proporcion de gastos de envio a pagar por enlace dentro del albarán.
> + # Obtenemos proporcion de gastos de envio a pagar por
> + # enlace dentro del albarán.
> if current_picking_id != move.picking_id.id:
> -
> - ship_move_id, proportional_cost, remaining_cost = self._found_ship_costs_picking(cr, uid, move.picking_id)
> -
> + (ship_move_id, proportional_cost,
> + remaining_cost) = self._found_ship_costs_picking(
> + cr, uid, move.picking_id)
> current_picking_id = move.picking_id.id
>
> -
> - partner = move.picking_id.elevator_partner_id or move.picking_id.partner_id
> -
> - # Creamos factura agrupada por cliente con todos los productos tipo SIM de los albaranes.
> - if move.product_id and product_obj._is_sim(move.product_id.categ_id):
> + partner = (move.picking_id.elevator_partner_id or
> + move.picking_id.partner_id)
> +
> + # Creamos factura agrupada por cliente con todos los
> + # productos tipo SIM de los albaranes.
> + if (move.product_id and
> + product_obj._is_sim(move.product_id.categ_id)):
>
> if current_partner_id != partner.id:
> -
> current_partner_id = partner.id
>
> - logger.info("[%s] %s" % (partner.ref, partner.name))
> - process_output += "[%s] %s\n" % (partner.ref, partner.name)
> - result_obj.write(cr, uid, result_id, {'result': process_output}, context=context)
> + logger.info("[%s] %s" % (partner.ref,
> + partner.name))
> + process_output += "[%s] %s\n" % (partner.ref,
> + partner.name)
> + result_obj.write(cr, uid, result_id,
> + {'result': process_output},
> + context=context)
>
> - #Creamos factura
> - account = partner.property_account_receivable.id or False
> - address_invoice_id = move.picking_id.elevator_invoice_id and move.picking_id.elevator_invoice_id.id or False
> - address = self.pool.get('res.partner').address_get(cr, uid, [current_partner_id], ['invoice', 'contact'])
> - currency_id = partner.property_product_pricelist and partner.property_product_pricelist.id or False
> - payment_term = partner.property_payment_term and partner.property_payment_term.id or False
> - payment_type = partner.payment_type_customer and partner.payment_type_customer.id or False
> + # Creamos factura
> + account = (
> + partner.property_account_receivable.id or
Poner partner.property_account_receivable.id directamente y lo mismo para los demás valores.
> + False)
> + address_invoice_id = (
> + move.picking_id.elevator_invoice_id and
> + move.picking_id.elevator_invoice_id.id or
> + False)
> + partner_obj = self.pool['res.partner']
> + address = partner_obj.address_get(
> + cr, uid, [current_partner_id], ['invoice',
> + 'contact'])
> + currency_id = (
> + partner.property_product_pricelist and
> + partner.property_product_pricelist.id or
> + False)
> + payment_term = (
> + partner.property_payment_term and
> + partner.property_payment_term.id or False)
> + payment_type = (
> + partner.payment_type_customer and
> + partner.payment_type_customer.id or False)
> fiscal_position = partner.property_account_position
> - contact_id = move.picking_id.contact_id and move.picking_id.contact_id.id or False
> + contact_id = (move.picking_id.contact_id and
> + move.picking_id.contact_id.id or
> + False)
>
> - bank_ids = bank_obj.search(cr, uid, [('partner_id', '=', current_partner_id)], order="default_bank desc", context=context)
> + bank_ids = bank_obj.search(
> + cr, uid, [('partner_id', '=',
> + current_partner_id)],
> + order="default_bank desc", context=context)
>
> invoice = {
> 'origin': origin,
> @@ -801,25 +1049,35 @@
> 'reference': False,
> 'account_id': account,
> 'partner_id': current_partner_id,
> - 'partner_bank_id': bank_ids and bank_ids[0] or False,
> + 'partner_bank_id': (bank_ids and
> + bank_ids[0] or False),
> 'elevator_partner_id': False,
> 'middleman_partner_id': False,
> 'journal_id': journal_ids[0],
> - 'address_invoice_id': address_invoice_id or address['invoice'],
> + 'address_invoice_id': (
> + address_invoice_id or
> + address['invoice']),
> 'address_contact_id': address['contact'],
> 'contact_id': contact_id,
> 'currency_id': currency_id,
> 'comment': False,
> 'payment_term': payment_term,
> 'payment_type': payment_type,
> - 'fiscal_position': fiscal_position and fiscal_position.id or False,
> + 'fiscal_position': (fiscal_position and
Poner directamente fiscal_position.id
> + fiscal_position.id or
> + False),
> 'invoice_date': invoice_date,
> - 'contract_id': move.contract_annexe_id and move.contract_annexe_id.contract_id and move.contract_annexe_id.contract_id.id or False,
> + 'contract_id': (
> + move.contract_annexe_id and
> + move.contract_annexe_id.contract_id and
> + move.contract_annexe_id.contract_id.id
> + or False),
> 'company_id': company_id.id,
> 'user_id': False
> }
>
> - rest_inv_id = invoice_obj.create(cr, uid, invoice, context=None)
> + rest_inv_id = invoice_obj.create(
> + cr, uid, invoice, context=context)
>
> #Creamos linea de factura de enlace
> product = move.product_id or False
> @@ -829,38 +1087,56 @@
> a = product.categ_id.property_account_income_categ.id
>
> inv_type = 'out_invoice'
> - name = (product.default_code and '[' + product.default_code + '] ' or '') + product.name
> - taxes_id = stock_picking_obj._get_taxes_invoice(cr, uid, move, inv_type)
> - account_analytic_id = stock_picking_obj._get_account_analytic_invoice(cr, uid, move.picking_id, move)
> - account = self.pool.get('account.fiscal.position').map_account(cr, uid, fiscal_position, a)
> + name = (product.default_code and
> + '[' + product.default_code + '] '
> + or '') + product.name
> + taxes_id = picking_obj._get_taxes_invoice(
> + cr, uid, move, inv_type)
> + account_analytic_id = picking_obj._get_account_analytic_invoice(
> + cr, uid, move.picking_id, move)
> + pos_obj = self.pool['account.fiscal.position']
> + account = pos_obj.map_account(cr, uid,
> + fiscal_position, a)
>
> - uos_id = move.product_uos and move.product_uos.id or False
> - if not uos_id and inv_type in ('out_invoice', 'out_refund'):
> + uos_id = (move.product_uos and move.product_uos.id
> + or False)
> + if (not uos_id and
> + inv_type in ('out_invoice', 'out_refund')):
> uos_id = move.product_uom.id
>
> -
> - #Obtenemos referencia de cliente desde sistema externo
> - #----------------------------------------------------------------
> + # Obtenemos referencia de cliente desde sistema
> + # externo
> + #--------------------------------------------------
> customer_ref = None
>
> if move.contract_id and move.contract_annexe_id:
> - phone = move.contract_annexe_id.production_lot_id and move.contract_annexe_id.production_lot_id.telefono or move.contract_annexe_id.phone
> + phone = (
> + move.contract_annexe_id.production_lot_id
> + and move.contract_annexe_id.production_lot_id.telefono
> + or move.contract_annexe_id.phone)
>
> if phone:
> customer_ref = customer_refs.get(phone)
>
> - #Si no obtenemos referencia, la buscamos en la linea de pedido origen
> - if not customer_ref and move.sale_line_id and move.sale_line_id.client_order_ref:
> + # Si no obtenemos referencia, la buscamos en la
> + # linea de pedido origen
> + if (not customer_ref and move.sale_line_id and
> + move.sale_line_id.client_order_ref):
> customer_ref = move.sale_line_id.client_order_ref
>
> - #Si no obtenemos referencia, la buscamos en el pedido origen
> - if not customer_ref and move.picking_id and move.picking_id.sale_id and move.picking_id.sale_id.client_order_ref:
> + # Si no obtenemos referencia, la buscamos en el
> + # pedido origen
> + if (not customer_ref and move.picking_id and
> + move.picking_id.sale_id and
> + move.picking_id.sale_id.client_order_ref):
> customer_ref = move.picking_id.sale_id.client_order_ref
>
> - #----------------------------------------------------------------
> + #--------------------------------------------------
>
> - price_unit = stock_picking_obj._get_price_unit_invoice(cr, uid, move, inv_type)
> - discount = stock_picking_obj._get_discount_invoice(cr, uid, move)
> + price_unit = picking_obj._get_price_unit_invoice(
> + cr, uid, move, inv_type)
> + discount = picking_obj._get_discount_invoice(
> + cr, uid, move)
> months = False
> start_date = False
> end_date = False
> @@ -871,7 +1147,9 @@
> num_cabins = move.num_cabins
> months = round(move.months, 2)
> price_unit = round(price_unit * months, 2)
> - discount = move.contract_annexe_id.differential_price or 0
> + discount = (
> + move.contract_annexe_id.differential_price
> + or 0)
> start_date = move.start_billing_date
> end_date = move.expiration_date
>
> @@ -881,7 +1159,8 @@
> 'invoice_id': rest_inv_id,
> 'account_id': account,
> 'price_unit': price_unit,
> - 'quantity': move.product_uos_qty or move.product_qty,
> + 'quantity': (move.product_uos_qty or
> + move.product_qty),
> 'discount': discount,
> 'uos_id': uos_id,
> 'product_id': product.id or False,
> @@ -892,38 +1171,63 @@
> 'num_cabins': num_cabins,
> 'start_date': start_date,
> 'end_date': end_date,
> - 'contract_id': move.contract_annexe_id and move.contract_annexe_id.contract_id and move.contract_annexe_id.contract_id.id or False,
> - 'contract_annexe_id': move.contract_annexe_id and move.contract_annexe_id.id or False,
> + 'contract_id': (
> + move.contract_annexe_id and
> + move.contract_annexe_id.contract_id and
> + move.contract_annexe_id.contract_id.id or
> + False),
> + 'contract_annexe_id': (
> + move.contract_annexe_id and
> + move.contract_annexe_id.id or False),
> 'customer_ref': customer_ref,
> - 'stock_move_id': move.id,
> + 'stock_move_id': move.id,
> }
>
> - line_id = invoice_line_obj.create(cr, uid, line, context=None)
> + line_id = invoice_line_obj.create(cr, uid, line,
> + context=context)
>
> - #Actualizamos fecha vencimiento del anexo, referencias de cliente y ultima linea de factura
> + # Actualizamos fecha vencimiento del anexo,
> + # referencias de cliente y ultima linea de factura
> if move.contract_id and move.contract_annexe_id:
> annexe_id = move.contract_annexe_id.id
> - result = annexe_obj.write(cr, uid, [annexe_id], {
> - 'customer_ref': customer_ref,
> - 'invoice_line_id': line_id,
> - })
> -
> -
> - # Creamos factura por cada enlace, repartiendo los gastos de envio
> - # entre todos los enlaces de un mismo albaran
> - elif move.product_id and product_obj._is_link(move.product_id.categ_id):
> -
> - #Creamos factura
> - account = partner.property_account_receivable.id or False
> - address_invoice_id = move.picking_id.elevator_invoice_id and move.picking_id.elevator_invoice_id.id or False
> - address = self.pool.get('res.partner').address_get(cr, uid, [partner.id], ['invoice', 'contact'])
> - currency_id = partner.property_product_pricelist and partner.property_product_pricelist.id or False
> - payment_term = partner.property_payment_term and partner.property_payment_term.id or False
> - payment_type = partner.payment_type_customer and partner.payment_type_customer.id or False
> + annexe_obj.write(
> + cr, uid, [annexe_id],
> + {'customer_ref': customer_ref,
> + 'invoice_line_id': line_id,
> + }, context=context)
> +
> + # Creamos factura por cada enlace, repartiendo los
> + # gastos de envio entre todos los enlaces de un mismo
> + # albaran
> + elif (move.product_id and
> + product_obj._is_link(move.product_id.categ_id)):
> + # Creamos factura
> + account = (partner.property_account_receivable.id
Poner directamente:
account = partner.property_account_receivable.id
> + or False)
> + address_invoice_id = (
address_invoice_id = move.picking_id.elevator_invoice_id
> + move.picking_id.elevator_invoice_id and
> + move.picking_id.elevator_invoice_id.id or
> + False)
> + partner_obj = self.pool['res.partner']
> + address = partner_obj.address_get(
> + cr, uid, [partner.id], ['invoice', 'contact'])
> + currency_id = (partner.property_product_pricelist
En todos estos hacer lo mismo para reducir la expresión, ya que no hace falta comprobar todo eso.
> + and partner.property_product_pricelist.id
> + or False)
> + payment_term = (partner.property_payment_term and
> + partner.property_payment_term.id or
> + False)
> + payment_type = (partner.payment_type_customer and
> + partner.payment_type_customer.id or
> + False)
> fiscal_position = partner.property_account_position
> - contact_id = move.picking_id.contact_id and move.picking_id.contact_id.id or False
> + contact_id = (move.picking_id.contact_id and
> + move.picking_id.contact_id.id or
> + False)
>
> - bank_ids = bank_obj.search(cr, uid, [('partner_id', '=', partner.id)], order="default_bank desc", context=context)
> + bank_ids = bank_obj.search(
> + cr, uid, [('partner_id', '=', partner.id)],
> + order="default_bank desc", context=context)
>
> invoice = {
> 'origin': origin,
> @@ -931,25 +1235,33 @@
> 'reference': False,
> 'account_id': account,
> 'partner_id': partner.id,
> - 'partner_bank_id': bank_ids and bank_ids[0] or False,
> + 'partner_bank_id': (bank_ids and bank_ids[0] or
> + False),
> 'elevator_partner_id': False,
> 'middleman_partner_id': False,
> 'journal_id': journal_ids[0],
> - 'address_invoice_id': address_invoice_id or address['invoice'],
> + 'address_invoice_id': (address_invoice_id or
> + address['invoice']),
> 'address_contact_id': address['contact'],
> 'contact_id': contact_id,
> 'currency_id': currency_id,
> 'comment': False,
> 'payment_term': payment_term,
> 'payment_type': payment_type,
> - 'fiscal_position': fiscal_position and fiscal_position.id or False,
> + 'fiscal_position': (fiscal_position and
'fiscal_position': fiscal_position.id,
> + fiscal_position.id or
> + False),
> 'invoice_date': invoice_date,
> - 'contract_id': move.contract_annexe_id and move.contract_annexe_id.contract_id and move.contract_annexe_id.contract_id.id or False,
> + 'contract_id': (move.contract_annexe_id and
> + move.contract_annexe_id.contract_id
> + and move.contract_annexe_id.contract_id.id
> + or False),
> 'company_id': company_id.id,
> 'user_id': False
> }
>
> - inv_id = invoice_obj.create(cr, uid, invoice, context=None)
> + inv_id = invoice_obj.create(cr, uid, invoice,
> + context=context)
>
> #Creamos linea de factura de enlace
> product = move.product_id or False
> @@ -959,50 +1271,75 @@
> a = product.categ_id.property_account_income_categ.id
>
> inv_type = 'out_invoice'
> - name = (product.default_code and '[' + product.default_code + '] ' or '') + product.name
> - taxes_id = stock_picking_obj._get_taxes_invoice(cr, uid, move, inv_type)
> - account_analytic_id = stock_picking_obj._get_account_analytic_invoice(cr, uid, move.picking_id, move)
> - account = self.pool.get('account.fiscal.position').map_account(cr, uid, fiscal_position, a)
> + name = ((product.default_code and
> + '[' + product.default_code + '] ' or '') +
> + product.name)
> + taxes_id = picking_obj._get_taxes_invoice(
> + cr, uid, move, inv_type)
> + account_analytic_id = picking_obj._get_account_analytic_invoice(
> + cr, uid, move.picking_id, move)
> + pos_obj = self.pool['account.fiscal.position']
> + account = pos_obj.map_account(cr, uid,
> + fiscal_position, a)
>
> uos_id = move.product_uos and move.product_uos.id or False
> if not uos_id and inv_type in ('out_invoice', 'out_refund'):
> uos_id = move.product_uom.id
>
> -
> - #Obtenemos referencia de cliente desde sistema externo
> - #----------------------------------------------------------------
> + # Obtenemos referencia de cliente desde sistema
> + # externo
> + #--------------------------------------------------
> customer_ref = None
> + annexe_id = move.contract_annexe_id
>
> - if move.contract_id and move.contract_annexe_id:
> - phone = move.contract_annexe_id.production_lot_id and move.contract_annexe_id.production_lot_id.telefono or move.contract_annexe_id.phone
> + if move.contract_id and annexe_id:
> + phone = (annexe_id.production_lot_id and
> + annexe_id.production_lot_id.telefono
> + or annexe_id.phone)
>
> if phone:
> customer_ref = customer_refs.get(phone)
>
> - #Si no obtenemos referencia, la buscamos en la linea de pedido origen
> - if not customer_ref and move.sale_line_id and move.sale_line_id.client_order_ref:
> - customer_ref = move.sale_line_id.client_order_ref
> -
> - #Si no obtenemos referencia, la buscamos en el pedido origen
> - if not customer_ref and move.picking_id and move.picking_id.sale_id and move.picking_id.sale_id.client_order_ref:
> - customer_ref = move.picking_id.sale_id.client_order_ref
> -
> - #----------------------------------------------------------------
> -
> - price_unit = stock_picking_obj._get_price_unit_invoice(cr, uid, move, inv_type)
> - discount = stock_picking_obj._get_discount_invoice(cr, uid, move)
> + # Si no obtenemos referencia, la buscamos en la
> + # linea de pedido origen
> + if (not customer_ref and move.sale_line_id and
> + move.sale_line_id.client_order_ref):
> + line_id = move.sale_line_id
> + customer_ref = line_id.client_order_ref
> +
> + # Si no obtenemos referencia, la buscamos en el
> + # pedido origen
> + picking_id = move.picking_id
> + if (not customer_ref and picking_id and
> + picking_id.sale_id and
> + picking_id.sale_id.client_order_ref):
> + sale_id = picking_id.sale_id
> + customer_ref = sale_id.client_order_ref
> +
> + #--------------------------------------------------
> +
> + price_unit = picking_obj._get_price_unit_invoice(
> + cr, uid, move, inv_type)
> + discount = picking_obj._get_discount_invoice(
> + cr, uid, move)
> months = False
> start_date = False
> end_date = False
> num_cabins = 0
>
> + contract_id = (annexe_id and
contract_id = annexe_id and annexe_id.contract_id.id
> + annexe_id.contract_id and
> + annexe_id.contract_id.id or
> + False)
> +
> line = {
> 'name': name,
> 'origin': origin,
> 'invoice_id': inv_id,
> 'account_id': account,
> 'price_unit': price_unit,
> - 'quantity': move.product_uos_qty or move.product_qty,
> + 'quantity': (move.product_uos_qty or
> + move.product_qty),
> 'discount': discount,
> 'uos_id': uos_id,
> 'product_id': product.id or False,
> @@ -1013,18 +1350,21 @@
> 'num_cabins': num_cabins,
> 'start_date': start_date,
> 'end_date': end_date,
> - 'contract_id': move.contract_annexe_id and move.contract_annexe_id.contract_id and move.contract_annexe_id.contract_id.id or False,
> - 'contract_annexe_id': move.contract_annexe_id and move.contract_annexe_id.id or False,
> - 'customer_ref': customer_ref,
> - 'stock_move_id': move.id,
> + 'contract_id': contract_id,
> + 'contract_annexe_id': (annexe_id and
'contract_annexe_id': annexe_id.id,
> + annexe_id.id or
> + False),
> + 'customer_ref': customer_ref,
> + 'stock_move_id': move.id,
> }
>
> - line_id = invoice_line_obj.create(cr, uid, line, context=None)
> + line_id = invoice_line_obj.create(cr, uid, line,
> + context=None)
>
> - #Creamos linea de factura de gastos de envio proporcionales,
> - #si el albaran incluye gastos de envio.
> + # Creamos linea de factura de gastos de envio
> + # proporcionales, si el albaran incluye gastos de
> + # envio.
> if ship_move_id:
> -
> product = ship_move_id.product_id or False
>
> a = product.product_tmpl_id.property_account_income.id
> @@ -1032,21 +1372,33 @@
> a = product.categ_id.property_account_income_categ.id
>
> inv_type = 'out_invoice'
> - name = (product.default_code and '[' + product.default_code + '] ' or '') + product.name
> - taxes_id = stock_picking_obj._get_taxes_invoice(cr, uid, ship_move_id, inv_type)
> - account_analytic_id = stock_picking_obj._get_account_analytic_invoice(cr, uid, ship_move_id.picking_id, ship_move_id)
> - account = self.pool.get('account.fiscal.position').map_account(cr, uid, fiscal_position, a)
> + name = (product.default_code and
> + '[' + product.default_code + '] ' or
> + '') + product.name
> + taxes_id = picking_obj._get_taxes_invoice(
> + cr, uid, ship_move_id, inv_type)
> + account_analytic_id = picking_obj._get_account_analytic_invoice(
> + cr, uid, ship_move_id.picking_id,
> + ship_move_id)
> + pos_obj = self.pool['account.fiscal.position']
> + account = pos_obj.map_account(
> + cr, uid, fiscal_position, a)
>
> - uos_id = ship_move_id.product_uos and ship_move_id.product_uos.id or False
> - if not uos_id and inv_type in ('out_invoice', 'out_refund'):
> + uos_id = (ship_move_id.product_uos and
> + ship_move_id.product_uos.id or False)
> + if not uos_id and (inv_type in
> + ('out_invoice',
> + 'out_refund')):
> uos_id = ship_move_id.product_uom.id
>
> + contract = ship_move_id.contract_annexe_id
> line = {
> 'name': name,
> 'origin': origin,
> 'invoice_id': inv_id,
> 'account_id': account,
> - 'price_unit': proportional_cost + remaining_cost,
> + 'price_unit': (proportional_cost +
> + remaining_cost),
> 'quantity': 1,
> 'discount': 0,
> 'uos_id': uos_id,
> @@ -1054,100 +1406,124 @@
> 'invoice_line_tax_id': [(6, 0, taxes_id)],
> 'note': False,
> 'account_analytic_id': account_analytic_id,
> - 'contract_id': ship_move_id.contract_annexe_id and ship_move_id.contract_annexe_id.contract_id and ship_move_id.contract_annexe_id.contract_id.id or False,
> - 'contract_annexe_id': ship_move_id.contract_annexe_id and ship_move_id.contract_annexe_id.id or False,
> + 'contract_id':
'contract_id': contract and contract.contract_id.id,
> + (contract and contract.contract_id and
> + contract.contract_id.id or False),
> + 'contract_annexe_id':
'contract_annexe_id': contract.id,
> + contract and contract.id or False,
> }
>
> - ship_line_id = invoice_line_obj.create(cr, uid, line, context=None)
> + invoice_line_obj.create(
> + cr, uid, line, context=None)
>
> - # Aplicamos posible resto de la division solo la primera vez por albaran
> + # Aplicamos posible resto de la division solo
> + # la primera vez por albaran
> remaining_cost = 0
>
> - #Actualizamos fecha vencimiento del anexo, referencias de cliente y ultima linea de factura
> + # Actualizamos fecha vencimiento del anexo,
> + # referencias de cliente y ultima linea de factura
> if move.contract_id and move.contract_annexe_id:
> annexe_id = move.contract_annexe_id.id
> - result = annexe_obj.write(cr, uid, [annexe_id], {
> - 'customer_ref': customer_ref,
> - 'invoice_line_id': line_id,
> - })
> -
> + annexe_obj.write(
> + cr, uid, [annexe_id],
> + {'customer_ref': customer_ref,
> + 'invoice_line_id': line_id},
> + context=context)
>
> #Actualizamos movimiento a facturado
> - result = stock_move_obj.write(cr, uid, [move.id], {'state': 'done',
> - 'invoiced': True
> - })
> -
> + stock_move_obj.write(cr, uid, [move.id],
> + {'state': 'done',
> + 'invoiced': True},
> + context=context)
>
> # Cerramos las facturas creadas, asociando las líneas
> logger.info("## Closing invoices ##")
> process_output += _("\n## Closing invoices ##\n")
> - result_obj.write(cr, uid, result_id, {'result': process_output}, context=context)
> + result_obj.write(cr, uid, result_id,
> + {'result': process_output}, context=context)
>
> for invoice_id, line_ids in partner_invoices.values():
> - invoice_line_obj.write(cr, uid, line_ids, {'invoice_id': invoice_id}, context=context)
> + invoice_line_obj.write(cr, uid, line_ids,
> + {'invoice_id': invoice_id},
> + context=context)
>
> - # Agrupamos lineas de facturas en todas las facturas creadas por annexo y producto.
> + # Agrupamos lineas de facturas en todas las facturas
> + # creadas por annexo y producto.
> if partner_invoices:
> invoice_ids = [i[0] for i in partner_invoices.values()]
> self._merge_invoices(cr, uid, invoice_ids, context=context)
>
> # Validación de facturas
> if validate_invoices:
> - invoice_ids = invoice_obj.search(cr, uid, [('origin', '=', origin)])
> + invoice_ids = invoice_obj.search(cr, uid,
> + [('origin', '=', origin)],
> + context=context)
> if invoice_ids:
> logger.info("## Invoice validation ##")
> process_output += _("\n## Invoice validation ##\n")
> - result_obj.write(cr, uid, result_id, {'result': process_output}, context=context)
> + result_obj.write(cr, uid, result_id,
> + {'result': process_output},
> + context=context)
> wf_service = netsvc.LocalService('workflow')
> for invoice_id in invoice_ids:
> - wf_service.trg_validate(uid, 'account.invoice', invoice_id, 'invoice_open', cr)
> + wf_service.trg_validate(uid, 'account.invoice',
> + invoice_id, 'invoice_open',
> + cr)
>
> logger.info("#### Invoice generation succesfully completed ####")
> - process_output += _("\n#### Invoice generation succesfully completed ####\n")
> - result_obj.write(cr, uid, result_id, {'result': process_output, 'state': 'done'}, context=context)
> + process_output += _("\n#### Invoice generation succesfully "
> + "completed ####\n")
> + result_obj.write(cr, uid, result_id,
> + {'result': process_output, 'state': 'done'},
> + context=context)
>
> except Exception, ex:
> cr.rollback()
> logger.error(tb.get_traceback())
> - if type(ex) is osv.except_osv:
> + if type(ex) is orm.except_orm:
> process_output += "\n" + ex.name + " " + ex.value
> else:
> process_output += "\nError: " + ex.message.decode("utf-8")
> - result_obj.write(cr, uid, result_id, {'result': process_output, 'state': 'exception'}, context=context)
> + result_obj.write(cr, uid, result_id,
> + {'result': process_output, 'state': 'exception'},
> + context=context)
>
> finally:
> cr.commit()
> cr.close()
> -
> +
> return True
> -
> -
> +
> def _merge_invoices(self, cr, uid, inv_ids, context=None):
> for inv_id in inv_ids:
> sql = " UPDATE account_invoice_line "
> - sql += "SET start_date=t.start_date, end_date =t.end_date, months = t.months, "
> - sql += "price_unit = t.price_unit, price_subtotal = t.price_subtotal "
> + sql += "SET start_date=t.start_date, end_date =t.end_date, "
> + sql += " months = t.months, price_unit = t.price_unit,"
> + sql += " price_subtotal = t.price_subtotal "
> sql += "FROM "
> sql += " ( "
> - sql += " SELECT max(id) As id, product_id, contract_annexe_id, "
> - sql += " min(start_date) As start_date, max(end_date) As end_date, sum(months) As months, "
> - sql += " sum(price_unit) As price_unit, sum(price_subtotal) As price_subtotal "
> + sql += " SELECT max(id) As id, product_id, contract_annexe_id,"
> + sql += " min(start_date) As start_date, "
> + sql += " max(end_date) As end_date, sum(months) As months, "
> + sql += " sum(price_unit) As price_unit,"
> + sql += " sum(price_subtotal) As price_subtotal "
> sql += " FROM account_invoice_line "
> - sql += " WHERE invoice_id = " + str(inv_id) + " AND NOT contract_annexe_id is null "
> + sql += " WHERE invoice_id = " + str(inv_id)
> + sql += " AND NOT contract_annexe_id is null "
> sql += " GROUP BY product_id, contract_annexe_id "
> sql += " HAVING count(*) > 1 "
> sql += " ) As t "
> sql += "WHERE account_invoice_line.id = t.id "
> + cr.execute(sql)
>
> - cr.execute(sql)
> -
> sql = " DELETE "
> sql += "FROM account_invoice_line l "
> sql += "USING "
> sql += "( "
> sql += " SELECT max(id) As id, product_id, contract_annexe_id "
> sql += " FROM account_invoice_line "
> - sql += " WHERE invoice_id = " + str(inv_id) + " AND NOT contract_annexe_id is null "
> + sql += " WHERE invoice_id = " + str(inv_id)
> + sql += " AND NOT contract_annexe_id is null "
> sql += " GROUP BY product_id, contract_annexe_id "
> sql += " HAVING count(*) > 1 "
> sql += ") As t "
> @@ -1155,68 +1531,68 @@
> sql += " AND l.product_id = t.product_id "
> sql += " AND l.contract_annexe_id = t.contract_annexe_id "
> sql += " AND l.invoice_id = " + str(inv_id) + " "
> -
> cr.execute(sql)
> -
> +
> return True
> -
> -
> +
> def _found_ship_costs_picking(self, cr, uid, picking, context=None):
> -
> - product_obj = self.pool.get('product.product')
> - stock_picking_obj = self.pool.get('stock.picking')
> -
> + product_obj = self.pool['product.product']
> + picking_obj = self.pool['stock.picking']
> +
> num_links = 0
> shipping_cost = 0
> proportional_cost = 0
> remaining_cost = 0
> ship_move_id = False
> -
> +
> for move in picking.move_lines:
> - if move.product_id and product_obj._is_link(move.product_id.categ_id):
> + if (move.product_id and
> + product_obj._is_link(move.product_id.categ_id)):
> num_links += 1
> -
> - elif move.product_id and product_obj._is_shipping_cost(move.product_id.categ_id):
> +
> + elif (move.product_id and
> + product_obj._is_shipping_cost(move.product_id.categ_id)):
> ship_move_id = move
> - price_unit = stock_picking_obj._get_price_unit_invoice(cr, uid, move, 'out_invoice')
> + price_unit = picking_obj._get_price_unit_invoice(
> + cr, uid, move, 'out_invoice')
> shipping_cost += price_unit
> -
> +
> if shipping_cost and num_links:
> proportional_cost = round(shipping_cost / num_links, 2)
> remaining_cost = shipping_cost - (proportional_cost * num_links)
> -
> -
> +
> return ship_move_id, proportional_cost, remaining_cost
>
> -invoice_generator()
> -
> -
> -class invoice_generator_result(osv.osv):
> +
> +class InvoiceGeneratorResult(orm.Model):
> _name = 'invoice.generator.result'
> _descripcion = 'Invoice Generator Result'
> _order = "date DESC"
>
> _columns = {
> - 'generator_id': fields.many2one('invoice.generator', 'Invoice Generator', select=True),
> + 'generator_id': fields.many2one('invoice.generator',
> + 'Invoice Generator', select=True),
> 'date': fields.datetime('Date', required=True),
> 'invoice_date': fields.date('Invoice Date', required=True),
> 'generation_date': fields.date('Generation Date', required=True),
> - 'runtype': fields.selection((('manual', 'Manual'), ('planned', 'Planned')), 'Type', required=True),
> + 'runtype': fields.selection((('manual', 'Manual'),
> + ('planned', 'Planned')), 'Type',
> + required=True),
> 'state': fields.selection(_RESULT_STATES, 'State', required=True),
> 'result': fields.text('Process Result', readonly=True),
> 'end_date': fields.date('End Date'),
> - }
> + }
>
> _defaults = {
> - 'date': lambda *a: datetime.strftime(datetime.today(), '%Y-%m-%d %H:%M:%S'),
> - }
> + 'date': lambda *a: datetime.strftime(datetime.today(),
Se podría poner directamente:
'date': lambda *a: datetime.today().strftime('%Y-%m-%d %H:%M:%S'),
> + '%Y-%m-%d %H:%M:%S'),
> + }
>
> def write(self, cr, uid, ids, data, context=None):
> conn = sql_db.db_connect(cr.dbname)
> cr2 = conn.cursor()
> - res = super(invoice_generator_result, self).write(cr2, uid, ids, data, context=context)
> + res = super(InvoiceGeneratorResult, self).write(cr2, uid, ids, data,
> + context=context)
> cr2.commit()
> cr2.close()
> return res
> -
> -invoice_generator_result()
>
> === added directory 'nayar_invoice_generator/views'
> === renamed file 'nayar_invoice_generator/invoice_generator_view.xml' => 'nayar_invoice_generator/views/invoice_generator_view.xml'
> --- nayar_invoice_generator/invoice_generator_view.xml 2014-06-11 10:23:47 +0000
> +++ nayar_invoice_generator/views/invoice_generator_view.xml 2014-07-04 09:27:08 +0000
> @@ -1,123 +1,130 @@
> <?xml version="1.0" encoding="utf-8"?>
> <openerp>
> - <data>
> - <record id="view_invoice_generator_search" model="ir.ui.view">
> - <field name="name">view.invoice.generator.search</field>
> - <field name="model">invoice.generator</field>
> - <field name="type">search</field>
> - <field name="arch" type="xml">
> - <search string="Search Invoice Generators">
> - <field name="name" select="1" />
> - </search>
> - </field>
> - </record>
> -
> - <record id="view_invoice_generator_tree" model="ir.ui.view">
> - <field name="name">view.invoice.generator.tree</field>
> - <field name="model">invoice.generator</field>
> - <field name="type">tree</field>
> - <field name="arch" type="xml">
> - <tree string="Invoice Generators">
> - <field name="name" />
> - <field name="contract_annexes" />
> - <field name="stock_pickings" />
> - <field name="next_invoice_date"/>
> - <field name="last_result"/>
> - </tree>
> - </field>
> - </record>
> -
> - <record id="view_invoice_generator_form" model="ir.ui.view">
> - <field name="name">view.invoice.generator.form</field>
> - <field name="model">invoice.generator</field>
> - <field name="type">form</field>
> - <field name="arch" type="xml">
> - <form string="Invoice Generator">
> - <group col="5" colspan="4">
> - <field name="name" />
> - <field name="active" />
> - <button name="%(action_invoice_generator_run_wizard)d" string="Run Invoice Generation" type="action" icon="gtk-execute" />
> - <notebook colspan="5">
> - <page string="Configuration">
> - <group colspan="2" col="2">
> - <separator string="Invoice Elements"/>
> - <field name="contract_annexes"/>
> - <field name="stock_pickings"/>
> - </group>
> - <group colspan="2" col="2">
> - <separator string="Invoices"/>
> - <field name="validate_invoices"/>
> - </group>
> - <separator string="Planning" colspan="4" col="4" />
> - <field name="next_invoice_date" />
> - <newline />
> - <field name="next_generation_date" />
> - </page>
> - <page string="Partners">
> - <field name="partners" nolabel="1" colspan="4" />
> - <field name="partners_action" colspan="4" />
> - </page>
> - <page string="Contracts">
> - <field name="contracts" nolabel="1" colspan="4" />
> - <field name="contracts_action" colspan="4" />
> - </page>
> - <page string="Pickings">
> - <field name="pickings" nolabel="1" colspan="4" />
> - <field name="pickings_action" colspan="4" />
> - </page>
> - <page string="Results">
> - <field name="result_ids" nolabel="1" colspan="4" />
> - </page>
> - </notebook>
> - </group>
> - </form>
> - </field>
> - </record>
> -
> - <record id="view_invoice_generator_result_tree" model="ir.ui.view">
> - <field name="name">view.invoice.generator.result.tree</field>
> - <field name="model">invoice.generator.result</field>
> - <field name="type">tree</field>
> - <field name="arch" type="xml">
> - <tree string="Invoice Generator Results">
> - <field name="date" />
> - <field name="invoice_date" />
> - <field name="generation_date" />
> - <field name="end_date"/>
> - <field name="runtype" />
> - <field name="state" />
> - </tree>
> - </field>
> - </record>
> -
> - <record id="view_invoice_generator_result_form" model="ir.ui.view">
> - <field name="name">view.invoice.generator.result.form</field>
> - <field name="model">invoice.generator.result</field>
> - <field name="type">form</field>
> - <field name="arch" type="xml">
> - <form string="Invoice Generator Results">
> - <group col="6" colspan="4">
> - <field name="date" />
> - <field name="invoice_date" />
> - <field name="generation_date" />
> - <field name="runtype" />
> - <field name="state" />
> - <field name="result" colspan="6" />
> - </group>
> - </form>
> - </field>
> - </record>
> -
> - <record id="action_invoice_generator" model="ir.actions.act_window">
> - <field name="name">Invoice Generators</field>
> - <field name="type">ir.actions.act_window</field>
> - <field name="res_model">invoice.generator</field>
> - <field name="view_type">form</field>
> - <field name="view_id" ref="view_invoice_generator_tree" />
> - <field name="search_view_id" ref="view_invoice_generator_search" />
> - </record>
> -
> - <menuitem action="action_invoice_generator" id="menu_invoice_generator" parent="account.menu_finance_receivables" sequence="110" />
> -
> - </data>
> + <data>
> + <record id="view_invoice_generator_search" model="ir.ui.view">
> + <field name="name">view.invoice.generator.search</field>
> + <field name="model">invoice.generator</field>
> + <field name="arch" type="xml">
> + <search string="Search Invoice Generators">
> + <field name="name" select="1" />
> + </search>
> + </field>
> + </record>
> +
> + <record id="view_invoice_generator_tree" model="ir.ui.view">
> + <field name="name">view.invoice.generator.tree</field>
> + <field name="model">invoice.generator</field>
> + <field name="arch" type="xml">
> + <tree string="Invoice Generators">
> + <field name="name" />
> + <field name="contract_annexes" />
> + <field name="stock_pickings" />
> + <field name="next_invoice_date" />
> + <field name="last_result" />
> + </tree>
> + </field>
> + </record>
> +
> + <record id="view_invoice_generator_form" model="ir.ui.view">
> + <field name="name">view.invoice.generator.form</field>
> + <field name="model">invoice.generator</field>
> + <field name="arch" type="xml">
> + <form string="Invoice Generator">
> + <group col="5" colspan="4">
> + <field name="name" />
> + <field name="active" />
> + <button
> + name="%(action_invoice_generator_run_wizard)d"
> + string="Run Invoice Generation" type="action"
> + icon="gtk-execute" />
> + <notebook colspan="5">
> + <page string="Configuration">
> + <group colspan="2" col="2">
> + <separator string="Invoice Elements" />
> + <field name="contract_annexes" />
> + <field name="stock_pickings" />
> + </group>
> + <group colspan="2" col="2">
> + <separator string="Invoices" />
> + <field name="validate_invoices" />
> + </group>
> + <separator string="Planning"
> + colspan="4" col="4" />
> + <field name="next_invoice_date" />
> + <newline />
> + <field name="next_generation_date" />
> + </page>
> + <page string="Partners">
> + <field name="partners" nolabel="1"
> + colspan="4" />
> + <field name="partners_action"
> + colspan="4" />
> + </page>
> + <page string="Contracts">
> + <field name="contracts" nolabel="1"
> + colspan="4" />
> + <field name="contracts_action"
> + colspan="4" />
> + </page>
> + <page string="Pickings">
> + <field name="pickings" nolabel="1"
> + colspan="4" />
> + <field name="pickings_action"
> + colspan="4" />
> + </page>
> + <page string="Results">
> + <field name="result_ids" nolabel="1"
> + colspan="4" />
> + </page>
> + </notebook>
> + </group>
> + </form>
> + </field>
> + </record>
> +
> + <record id="view_invoice_generator_result_tree" model="ir.ui.view">
> + <field name="name">view.invoice.generator.result.tree</field>
> + <field name="model">invoice.generator.result</field>
> + <field name="arch" type="xml">
> + <tree string="Invoice Generator Results">
> + <field name="date" />
> + <field name="invoice_date" />
> + <field name="generation_date" />
> + <field name="end_date" />
> + <field name="runtype" />
> + <field name="state" />
> + </tree>
> + </field>
> + </record>
> +
> + <record id="view_invoice_generator_result_form" model="ir.ui.view">
> + <field name="name">view.invoice.generator.result.form</field>
> + <field name="model">invoice.generator.result</field>
> + <field name="arch" type="xml">
> + <form string="Invoice Generator Results">
> + <group col="6" colspan="4">
> + <field name="date" />
> + <field name="invoice_date" />
> + <field name="generation_date" />
> + <field name="runtype" />
> + <field name="state" />
> + <field name="result" colspan="6" />
> + </group>
> + </form>
> + </field>
> + </record>
> +
> + <record id="action_invoice_generator" model="ir.actions.act_window">
> + <field name="name">Invoice Generators</field>
> + <field name="type">ir.actions.act_window</field>
> + <field name="res_model">invoice.generator</field>
> + <field name="view_type">form</field>
> + <field name="view_id" ref="view_invoice_generator_tree" />
> + <field name="search_view_id" ref="view_invoice_generator_search" />
> + </record>
> +
> + <menuitem action="action_invoice_generator" id="menu_invoice_generator"
> + parent="account.menu_finance_receivables" sequence="110" />
> +
> + </data>
> </openerp>
>
> === modified file 'nayar_invoice_generator/wizard/__init__.py'
> --- nayar_invoice_generator/wizard/__init__.py 2014-06-11 10:23:47 +0000
> +++ nayar_invoice_generator/wizard/__init__.py 2014-07-04 09:27:08 +0000
> @@ -19,6 +19,4 @@
> #
> ##############################################################################
>
> -import wizard_invoice_generator_run
> -
> -# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
> +from . import wizard_invoice_generator_run
>
> === modified file 'nayar_invoice_generator/wizard/wizard_invoice_generator_run.py'
> --- nayar_invoice_generator/wizard/wizard_invoice_generator_run.py 2014-06-11 10:23:47 +0000
> +++ nayar_invoice_generator/wizard/wizard_invoice_generator_run.py 2014-07-04 09:27:08 +0000
> @@ -21,10 +21,11 @@
>
> import calendar
> from datetime import datetime
> -from osv import osv, fields
> +from openerp.osv import orm, fields
> import time
>
> -class invoice_generator_run_wizard(osv.osv_memory):
> +
> +class InvoiceGeneratorRunWizard(orm.TransientModel):
> _name = 'invoice.generator.run.wizard'
> _description = 'Run Invoice Generator'
>
> @@ -40,7 +41,8 @@
> context = {}
>
> current_date = datetime.today()
> - month_days = calendar.monthrange(current_date.year, current_date.month)[1]
> + month_days = calendar.monthrange(current_date.year,
> + current_date.month)[1]
> current_date = current_date.replace(day=month_days)
>
> return current_date and current_date.strftime('%Y-%m-%d') or None
> @@ -49,17 +51,24 @@
> if context is None:
> return ""
> else:
> - return self.get_summary(cr, uid, context['active_id'], self._invoice_date_default(cr, uid), self._generation_date_default(cr, uid))
> + return self.get_summary(cr, uid, context['active_id'],
> + self._invoice_date_default(cr, uid),
> + self._generation_date_default(cr, uid),
> + context=context)
>
> _columns = {
> 'invoice_date': fields.date('Invoice Date', required=True),
> 'generation_date': fields.date('Generation Date', required=True),
> 'summary': fields.text('Summary', readonly=True),
> 'process_output': fields.text('Process Output', readonly=True),
> - 'state': fields.selection((('draft', 'draft'), ('running', 'running'), ('done', 'done'), ('exception', 'exception'))),
> - 'generator_id': fields.many2one('invoice.generator', 'Invoice Generator'),
> + 'state': fields.selection((('draft', 'draft'),
> + ('running', 'running'),
> + ('done', 'done'),
> + ('exception', 'exception'))),
> + 'generator_id': fields.many2one('invoice.generator',
> + 'Invoice Generator'),
> 'end_date': fields.date('End Date'),
> - }
> + }
>
> _defaults = {
> 'invoice_date': _invoice_date_default,
> @@ -67,7 +76,7 @@
> 'summary': _summary_default,
> 'state': lambda *a: 'draft',
Quitar lambda
> 'generator_id': lambda self, cr, uid, context: context['active_id'],
> - }
> + }
>
> def invoice_date_change(self, cr, uid, ids, invoice_date):
> value = {}
> @@ -77,16 +86,20 @@
> if invoice_date:
> # Obtenemos fecha de generación. Último dia del mes seleccionado
> current_date = datetime.strptime(invoice_date, '%Y-%m-%d')
> - month_days = calendar.monthrange(current_date.year, current_date.month)[1]
> + month_days = calendar.monthrange(current_date.year,
> + current_date.month)[1]
> current_date = current_date.replace(day=month_days)
> - generation_date = current_date and current_date.strftime('%Y-%m-%d') or None
> + generation_date = (current_date and
> + current_date.strftime('%Y-%m-%d') or None)
> value["generation_date"] = generation_date
>
> return {'value': value, 'domain': domain, 'warning': warning}
>
> def refresh_summary(self, cr, uid, ids, context=None):
> data = self.browse(cr, uid, ids[0])
> - summary = self.get_summary(cr, uid, data.generator_id.id, data.invoice_date, data.generation_date)
> + summary = self.get_summary(cr, uid, data.generator_id.id,
> + data.invoice_date, data.generation_date,
> + context=context)
> self.write(cr, uid, ids, {'summary': summary})
> return {'res_model': 'invoice.generator.run.wizard',
> 'type': 'ir.actions.act_window',
> @@ -95,7 +108,8 @@
> 'target': 'new',
> 'res_id': ids and ids[0] or False}
>
> - def get_summary(self, cr, uid, generator_id, invoice_date, generation_date):
> + def get_summary(self, cr, uid, generator_id, invoice_date,
> + generation_date, context=None):
> data = self.pool.get('invoice.generator').browse(cr, uid, generator_id)
> partners = data.partners
> partners_action = data.partners_action
> @@ -106,17 +120,19 @@
> contract_annexes = data.contract_annexes
> stock_pickings = data.stock_pickings
>
> - user = self.pool.get('res.users').browse(cr, uid, uid)
> + user = self.pool['res.users'].browse(cr, uid, uid, context=context)
> company_id = user.company_id.id
>
> output = ""
> i = 0
>
> # Obtenemos facuras de clientes con servicios a generar
> - # -------------------------------------------------------------------------------------------
> + # ---------------------------------------------------------------------
> if contract_annexes:
> - # Fecha de generacion de facturas, inicio de mes de la fecha de generacion
> - inv_generation_date = datetime.strptime(generation_date, '%Y-%m-%d')
> + # Fecha de generacion de facturas,
> + # inicio de mes de la fecha de generacion
> + inv_generation_date = datetime.strptime(generation_date,
> + '%Y-%m-%d')
> inv_generation_date = inv_generation_date.strftime('%Y-%m-01')
>
> sql = " SELECT p.name "
> @@ -124,9 +140,12 @@
> sql += "INNER JOIN contract_contract c ON (a.contract_id = c.id) "
> sql += "INNER JOIN res_partner p ON (c.customer_id = p.id) "
> sql += "WHERE a.active_annexe = true "
> - sql += "AND COALESCE(a.expiration_date, '" + inv_generation_date + "') < '" + inv_generation_date + "' "
> - sql += "AND COALESCE(c.closing_date, '" + inv_generation_date + "') >= '" + inv_generation_date + "' "
> - sql += "AND COALESCE(a.closing_date, '" + inv_generation_date + "') >= '" + inv_generation_date + "' "
> + sql += "AND COALESCE(a.expiration_date, '"
> + sql += inv_generation_date + "') < '" + inv_generation_date + "' "
> + sql += "AND COALESCE(c.closing_date, '"
> + sql += inv_generation_date + "') >= '" + inv_generation_date + "' "
> + sql += "AND COALESCE(a.closing_date, '"
> + sql += inv_generation_date + "') >= '" + inv_generation_date + "' "
>
> if partners:
> sql += "AND c.customer_id "
> @@ -138,7 +157,8 @@
> sql += "AND c.id "
> if contracts_action == "exclude":
> sql += "NOT "
> - sql += "IN (" + ", ".join([str(c.id) for c in contracts]) + ") "
> + sql += "IN (" + ", ".join([str(c.id) for c in contracts])
> + sql += ") "
>
> sql += "GROUP BY c.customer_id, p.name "
> sql += "ORDER BY c.customer_id"
> @@ -150,17 +170,24 @@
> output += '\n' + 'Factura ' + str(i) + ' - ' + res[0]
>
> # Obtenemos líneas de albarán pendientes de facturar
> - # -------------------------------------------------------------------------------------------
> + # ---------------------------------------------------------------------
> if stock_pickings:
> - sql = "SELECT partner_id, partner_name, product_name, default_code, picking_number "
> + sql = "SELECT partner_id, partner_name, product_name,"
> + sql += "default_code, picking_number "
> sql += "FROM ( "
> - sql += " SELECT m.id, p.partner_id, p.date, p.id AS picking_id, c.name AS partner_name, prod.name_template AS product_name, prod.default_code, p.name AS picking_number "
> + sql += " SELECT m.id, p.partner_id, p.date, p.id AS picking_id,"
> + sql += " c.name AS partner_name,"
> + sql += " prod.name_template AS product_name,"
> + sql += " prod.default_code, p.name AS picking_number "
> sql += " FROM stock_move m "
> sql += " INNER JOIN stock_picking p ON (m.picking_id = p.id) "
> sql += " INNER JOIN res_partner c ON (p.partner_id = c.id) "
> - sql += " INNER JOIN product_product prod ON (m.product_id = prod.id) "
> - sql += " LEFT JOIN stock_move_history_ids h ON (m.id = h.child_id) "
> - sql += " WHERE m.invoiced = false AND p.date < '" + invoice_date + "' "
> + sql += " INNER JOIN product_product prod ON "
> + sql += " (m.product_id = prod.id) "
> + sql += " LEFT JOIN stock_move_history_ids h ON"
> + sql += " (m.id = h.child_id) "
> + sql += " WHERE m.invoiced = false AND p.date < '"
> + sql += invoice_date + "' "
> sql += " AND p.type = 'out' and p.invoice_state = 'invoiced' "
> sql += " AND h.parent_id IS NULL "
>
> @@ -181,13 +208,21 @@
>
> sql += " UNION "
>
> - sql += " SELECT m.id, p.elevator_partner_id AS partner_id, p.date, p.id AS picking_id, c.name AS partner_name, prod.name_template AS product_name, prod.default_code, p.name AS picking_number "
> + sql += " SELECT m.id, p.elevator_partner_id AS partner_id, "
> + sql += " p.date, p.id AS picking_id,"
> + sql += " c.name AS partner_name,"
> + sql += " prod.name_template AS product_name,"
> + sql += " prod.default_code, p.name AS picking_number "
> sql += " FROM stock_move m "
> sql += " INNER JOIN stock_picking p ON (m.picking_id = p.id) "
> - sql += " INNER JOIN res_partner c ON (p.elevator_partner_id = c.id) "
> - sql += " INNER JOIN product_product prod ON (m.product_id = prod.id) "
> - sql += " LEFT JOIN stock_move_history_ids h ON (m.id = h.child_id) "
> - sql += " WHERE m.invoiced = false AND p.date < '" + invoice_date + "' "
> + sql += " INNER JOIN res_partner c ON"
> + sql += " (p.elevator_partner_id = c.id) "
> + sql += " INNER JOIN product_product prod ON"
> + sql += " (m.product_id = prod.id) "
> + sql += " LEFT JOIN stock_move_history_ids h ON"
> + sql += " (m.id = h.child_id) "
> + sql += " WHERE m.invoiced = false AND p.date < '"
> + sql += invoice_date + "' "
> sql += " AND p.type = 'out' and p.invoice_state = 'invoiced' "
> sql += " AND h.parent_id IS NULL "
>
> @@ -212,41 +247,49 @@
> cr.execute(sql)
> results = cr.fetchall()
> current_partner_id = None
> - for partner_id, partner_name, product_name, default_code, picking_number in results:
> + for (partner_id, partner_name, product_name, default_code,
> + picking_number) in results:
> str_invoice = ' '
> if current_partner_id != partner_id:
> current_partner_id = partner_id
> i += 1
> - str_invoice = 'Factura ' + str(i) + ' - ' + partner_name + '\n' + str_invoice
> - product = (default_code and '[' + default_code + '] ' or '') + product_name
> - output += '\n' + str_invoice + ' - Albaran ' + picking_number + ' - ' + product
> + str_invoice = ('Factura ' + str(i) + ' - ' + partner_name +
Se podría utilizar sustitución de cadenas para ser más legible, pero tampoco es súper necesario.
> + '\n' + str_invoice)
> + product = (default_code and '[' + default_code + '] ' or
> + '') + product_name
> + output += '\n' + str_invoice + ' - Albaran ' + picking_number
> + output += ' - ' + product
>
> if output == "":
> - output = "No hay facturas pendientes de generar para la fecha seleccionada."
> + output = "No hay facturas pendientes de generar para la fecha "
> + "seleccionada."
>
> return output.strip()
>
> -
> def generate_invoices(self, cr, uid, ids, context=None):
> if not self.process_thread or not self.process_thread.is_alive():
> - generator_obj = self.pool.get('invoice.generator')
> - data = self.browse(cr, uid, ids[0])
> - (self.process_thread, self.result_id) = generator_obj.generate_invoices(cr, uid, data.generator_id.id, data.invoice_date, data.generation_date, end_date=data.end_date, thread=True, context=context)
> + gen_obj = self.pool['invoice.generator']
> + data = self.browse(cr, uid, ids[0], context=context)
> + (self.process_thread, self.result_id) = gen_obj.generate_invoices(
> + cr, uid, data.generator_id.id, data.invoice_date,
> + data.generation_date, end_date=data.end_date, thread=True,
> + context=context)
> self.write(cr, uid, ids, {'state': 'running'}, context=context)
>
> return self.wait(cr, uid, ids, context=context)
>
> -
> def wait(self, cr, uid, ids, context=None):
> - result_obj = self.pool.get('invoice.generator.result')
> - data = result_obj.browse(cr, uid, self.result_id)
> + result_obj = self.pool['invoice.generator.result']
> + data = result_obj.browse(cr, uid, self.result_id, context=context)
> time_left = 10
> while data.state == 'running' and time_left > 0:
> time_left -= 1
> time.sleep(1)
> - data = result_obj.browse(cr, uid, self.result_id)
> + data = result_obj.browse(cr, uid, self.result_id, context=context)
>
> - self.write(cr, uid, ids, {'process_output': data.result, 'state': data.state})
> + self.write(cr, uid, ids, {'process_output': data.result,
> + 'state': data.state},
> + context=context)
>
> return {'res_model': 'invoice.generator.run.wizard',
> 'type': 'ir.actions.act_window',
> @@ -255,9 +298,5 @@
> 'target': 'new',
> 'res_id': ids and ids[0] or False}
>
> -
> def go_back(self, cr, uid, ids, context=None):
> - return self.write(cr, uid, ids, {'state':'draft'}, context=context)
> -
> -
> -invoice_generator_run_wizard()
> + return self.write(cr, uid, ids, {'state': 'draft'}, context=context)
>
> === modified file 'nayar_invoice_generator/wizard/wizard_invoice_generator_run_view.xml'
> --- nayar_invoice_generator/wizard/wizard_invoice_generator_run_view.xml 2014-06-11 10:23:47 +0000
> +++ nayar_invoice_generator/wizard/wizard_invoice_generator_run_view.xml 2014-07-04 09:27:08 +0000
> @@ -1,93 +1,112 @@
> <?xml version="1.0" encoding="utf-8"?>
> <openerp>
> - <data>
> - <record id="invoice_generator_run_wizard_view" model="ir.ui.view">
> - <field name="name">Run Invoice Generator</field>
> - <field name="model">invoice.generator.run.wizard</field>
> - <field name="type">form</field>
> - <field name="arch" type="xml">
> - <form string="Run Invoice Generator">
> - <newline/>
> - <group colspan="4" col="4" states="draft">
> - <separator colspan="4" string="Process of generating monthly invoices for contracted services for each client:"/>
> - <field name="invoice_date" on_change="invoice_date_change(invoice_date)"/>
> - <field name="generation_date" />
> - <field name="end_date"/>
> - <field name="summary" colspan="4" />
> - <button name="refresh_summary" string="Recalculate" type="object" colspan="4" />
> - <field invisible="1" name="state" />
> - <separator colspan="4"/>
> - </group>
> -
> - <group colspan="4" col="4" states="running">
> - <separator colspan="4" string="Running invoice generation" />
> - </group>
> -
> - <group colspan="4" col="4" states="done">
> - <separator colspan="4" string="Successfully completed generation" />
> - </group>
> -
> - <group colspan="4" col="4" states="exception">
> - <separator colspan="4" string="Error when generating invoices" />
> - </group>
> -
> - <group colspan="4" col="4" states="running,done,exception">
> - <field name="process_output" nolabel="1" colspan="4" height="100" default_focus="1" />
> - </group>
> -
> - <group colspan="4" col="4" states="running">
> - <label colspan="4" />
> - <label colspan="4" string="It seems that the process will take some time." />
> - <label colspan="4" />
> - <label colspan="4" string="You can wait or close (process will continue in background)."/>
> - <label colspan="4" />
> - <separator colspan="4"/>
> - </group>
> -
> - <group colspan="4" col="4" states="done">
> - <label colspan="4" />
> - <label colspan="4" string="If you want to generate more invoice, push Go Back button."/>
> - <label colspan="4" />
> - <label colspan="4" string="If you finish, push Close button."/>
> - <label colspan="4" />
> - <separator colspan="4"/>
> - </group>
> -
> - <group colspan="4" col="4" states="exception">
> - <label colspan="4" />
> - <label colspan="4" string="If you want to try one more time, push Go Back button."/>
> - <label colspan="4" />
> - <label colspan="4" string="If you finish, push Close button."/>
> - <label colspan="4" />
> - <separator colspan="4"/>
> - </group>
> -
> - <group colspan="4" col="4" states="draft">
> - <button special="cancel" string="Cancel" icon="gtk-cancel"/>
> - <button name="generate_invoices" string="Generate Invoices" type="object" icon="gtk-ok"/>
> - </group>
> -
> - <group colspan="4" col="4" states="running">
> - <button special="cancel" string="Close (background)" icon="gtk-cancel"/>
> - <button name="wait" string="Wait" type="object" icon="gtk-ok"/>
> - </group>
> -
> - <group colspan="4" col="4" states="done,exception">
> - <button special="cancel" string="Close" icon="gtk-cancel"/>
> - <button name="go_back" string="Go back" type="object" icon="" />
> - </group>
> - </form>
> - </field>
> - </record>
> -
> - <record id="action_invoice_generator_run_wizard" model="ir.actions.act_window">
> - <field name="name">Run Invoice Generator</field>
> - <field name="type">ir.actions.act_window</field>
> - <field name="res_model">invoice.generator.run.wizard</field>
> - <field name="view_type">form</field>
> - <field name="view_mode">form</field>
> - <field name="view_id" ref="invoice_generator_run_wizard_view" />
> - <field name="target">new</field>
> - </record>
> - </data>
> + <data>
> + <record id="invoice_generator_run_wizard_view" model="ir.ui.view">
> + <field name="name">Run Invoice Generator</field>
> + <field name="model">invoice.generator.run.wizard</field>
> + <field name="arch" type="xml">
> + <form string="Run Invoice Generator">
Poner version="7.0" como atributo
> + <newline />
> + <group colspan="4" col="4" states="draft">
> + <separator colspan="4"
> + string="Process of generating monthly invoices for contracted services for each client:" />
> + <field name="invoice_date"
> + on_change="invoice_date_change(invoice_date)" />
> + <field name="generation_date" />
> + <field name="end_date" />
> + <field name="summary" colspan="4" />
> + <button name="refresh_summary" string="Recalculate"
> + type="object" colspan="4" />
> + <field invisible="1" name="state" />
> + <separator colspan="4" />
> + </group>
> +
> + <group colspan="4" col="4" states="running">
> + <separator colspan="4"
> + string="Running invoice generation" />
> + </group>
> +
> + <group colspan="4" col="4" states="done">
> + <separator colspan="4"
> + string="Successfully completed generation" />
> + </group>
> +
> + <group colspan="4" col="4" states="exception">
> + <separator colspan="4"
> + string="Error when generating invoices" />
> + </group>
> +
> + <group colspan="4" col="4"
> + states="running,done,exception">
> + <field name="process_output" nolabel="1"
> + colspan="4" height="100" default_focus="1" />
> + </group>
> +
> + <group colspan="4" col="4" states="running">
> + <label colspan="4" />
> + <label colspan="4"
> + string="It seems that the process will take some time." />
> + <label colspan="4" />
> + <label colspan="4"
> + string="You can wait or close (process will continue in background)." />
> + <label colspan="4" />
> + <separator colspan="4" />
> + </group>
> +
> + <group colspan="4" col="4" states="done">
> + <label colspan="4" />
> + <label colspan="4"
> + string="If you want to generate more invoice, push Go Back button." />
> + <label colspan="4" />
> + <label colspan="4"
> + string="If you finish, push Close button." />
> + <label colspan="4" />
> + <separator colspan="4" />
> + </group>
> +
> + <group colspan="4" col="4" states="exception">
> + <label colspan="4" />
> + <label colspan="4"
> + string="If you want to try one more time, push Go Back button." />
> + <label colspan="4" />
> + <label colspan="4"
> + string="If you finish, push Close button." />
> + <label colspan="4" />
> + <separator colspan="4" />
> + </group>
> +
> + <footer colspan="4" col="4" states="draft">
> + <button name="generate_invoices" string="Generate Invoices"
> + type="object" icon="gtk-ok" />
> + <button class="oe-link" special="cancel"
> + string="Cancel" icon="gtk-cancel" />
> + </footer>
> +
> + <footer colspan="4" col="4" states="running">
> + <button name="wait" string="Wait" type="object"
> + icon="gtk-ok" />
> + <button class="oe-link" special="cancel"
> + string="Close (background)" icon="gtk-cancel" />
> + </footer>
> +
> + <footer colspan="4" col="4" states="done,exception">
> + <button name="go_back" string="Go back"
> + type="object" icon="" />
> + <button class="oe-link" special="cancel"
> + string="Close" icon="gtk-cancel" />
> + </footer>
> + </form>
> + </field>
> + </record>
> +
> + <record id="action_invoice_generator_run_wizard" model="ir.actions.act_window">
> + <field name="name">Run Invoice Generator</field>
> + <field name="type">ir.actions.act_window</field>
> + <field name="res_model">invoice.generator.run.wizard</field>
> + <field name="view_type">form</field>
> + <field name="view_mode">form</field>
> + <field name="view_id" ref="invoice_generator_run_wizard_view" />
> + <field name="target">new</field>
> + </record>
> + </data>
> </openerp>
>
--
https://code.launchpad.net/~oihanecruce/avanzosc/nayar_invoice_generator/+merge/225050
Your team Avanzosc_security is subscribed to branch lp:~avanzosc-security-team/avanzosc/72horas.