| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275 | # -*- coding: utf-8 -*-# License, author and contributors information in:# __openerp__.py file at the root folder of this module.from openerp import api, models, fieldsfrom openerp.exceptions import ValidationError, except_orm, Warning, RedirectWarningimport logging_log = logging.getLogger(__name__)class WorkOrder(models.Model):    _name = 'repair.workorderimproved'    _description = 'Work order improved'    _inherit = ['mail.thread', 'ir.needaction_mixin']    def _get_user(self):        return self.env.uid    def _get_number(self):        return self.env['ir.sequence'].get('repair.workorderimproved') or '*'    name = fields.Char(        string=u'Code',        readonly=True,        default=_get_number    )    user_id = fields.Many2one(        comodel_name='res.users',        string='Engineer',        default=_get_user    )    partner_id = fields.Many2one(        comodel_name='res.partner',        string='Partner'    )    line_ids = fields.One2many(        comodel_name='repair.workorderimproved.line',        inverse_name='workorder_id',        string='Products delivered'    )    consumed_ids = fields.One2many(        comodel_name='repair.workorderimproved.consumed',        inverse_name='workorder_id',        string='Product & Services consumed'    )    order_date = fields.Datetime(        string='Order date',        default=fields.Datetime.now    )    planned_start_date = fields.Datetime(        string='Planned start date'    )    planned_end_date = fields.Datetime(        string='Planned end date'    )    name_obra = fields.Char(        string='Obra'    )    contacto_obra = fields.Char(        string='Contacto de la Obra'    )    emergente = fields.Text(        string='Pedidos adicionales y emergentes'    )    diagnostic = fields.Text(        string='Diagnostic'    )    causes = fields.Text(        string='Causes'    )    actions = fields.Text(        string='Acciones'    )    recommendations = fields.Text(        string="recommendations"    )    state = fields.Selection([        ('draft', 'Pending'),        ('in_progress', 'In progress'),        ('done', 'Done'),        ('canceled', 'Canceled'),        ('invoiced', 'Invoiced')],        string='State',        default='draft'    )    invoice_ids = fields.One2many('account.invoice', 'work_invoice_id')    invoice_count = fields.Integer(        string='Facturas',        compute='_get_invoice_count',    )    @api.multi    def button_draft(self):        if self.invoice_count > 0:            raise Warning('Este trabajo tiene una factura asociada')        if self.invoice_count == 0:            for work in self:                work.write({'state': 'draft'})            return True    @api.one    @api.depends('invoice_ids')    def _get_invoice_count(self):        self.invoice_count = len(self.invoice_ids)    @api.one    def onchange_partner_id(self, partner_id):        _log.info('-'*100)        _log.info(partner_id)    @api.one    def button_in_progress(self):        self.state = 'in_progress'    @api.one    def button_in_progress_back(self):        self.state = 'draft'    @api.one    def button_done(self):        product = self.line_ids        works = self.consumed_ids        if not product or not works:            raise Warning('El trabajo debe tener productos y trabajos asociados')        else:            self.state = 'done'    @api.one    def button_done_back(self):        self.state = 'in_progress'    @api.one    def button_cancel(self):        self.state = 'canceled'    @api.multi    def Facturado(self):        inv_obj = self.env['account.invoice']        inv_line_obj = self.env['account.invoice.line']        customer = self.partner_id        if not customer.name:            raise osv.except_osv(_('UserError!'), _('Please select a Customer.'))        company_id = self.env['res.users'].browse(1).company_id        self.ensure_one()        ir_values = self.env['ir.values']        inv_data = {            'name': customer.name,            'reference': customer.name,            'account_id': customer.property_account_receivable.id,            'partner_id': customer.id,            'origin': self.name,            'work_invoice_id': self.id        }        inv_id = inv_obj.create(inv_data)        for records in self.consumed_ids:            if records.product_id.id:                income_account = records.product_id.categ_id.property_account_income_categ.id            if not income_account:                raise osv.except_osv(_('UserError!'), _('There is no income account defined '                                                        'for this product: "%s".') % (records.product_id.name,))            inv_line_data = {                'name': records.product_id.name,                'account_id': income_account,                'price_unit': records.price_unit,                'quantity': records.quantity,                'product_id': records.product_id.id,                'invoice_id': inv_id.id,                'invoice_line_tax_id': [(6, 0, [x.id for x in records.product_id.taxes_id])],            }            inv_line_obj.create(inv_line_data)        self.state = 'invoiced'        imd = self.env['ir.model.data']        action = imd.xmlid_to_object('account.action_invoice_tree1')        list_view_id = imd.xmlid_to_res_id('account.invoice_tree')        form_view_id = imd.xmlid_to_res_id('account.invoice_form')        result = {            'name': action.name,            'help': action.help,            'type': 'ir.actions.act_window',            'views': [[list_view_id, 'tree'], [form_view_id, 'form'], [False, 'graph'], [False, 'kanban'],                      [False, 'calendar'], [False, 'pivot']],            'target': action.target,            'context': action.context,            'res_model': 'account.invoice',        }        if len(inv_id) > 1:            result['domain'] = "[('id','in',%s)]" % inv_id.ids        elif len(inv_id) == 1:            result['views'] = [(form_view_id, 'form')]            result['res_id'] = inv_id.ids[0]        else:            result = {'type': 'ir.actions.act_window_close'}        invoiced_records = self.env['repair.workorderimproved']        total = 0        self.stage_id = 3        for rows in invoiced_records:            invoiced_date = rows.date            invoiced_date = invoiced_date[0:10]            if invoiced_date == str(date.today()):                total = total + rows.price_subtotal        inv_id.signal_workflow('invoice_open')        return resultclass WorkOrderLine(models.Model):    _name = 'repair.workorderimproved.line'    _description = 'Product to repair'    _inherit = ['mail.thread', 'ir.needaction_mixin']    workorder_id = fields.Many2one(        comodel_name='repair.workorderimproved',        string='Work order improved')    description = fields.Char(string='Description')    quantity = fields.Float(string='Quantity', default=1.0)    brand = fields.Char(string='Marca')    number = fields.Char(string="Numero de serie")class WorkOrderConsumed(models.Model):    _name = 'repair.workorderimproved.consumed'    _description = 'Services for repair'    _inherit = ['mail.thread', 'ir.needaction_mixin']    workorder_id = fields.Many2one(        comodel_name='repair.workorderimproved',        string='Work order'    )    product_id = fields.Many2one(        comodel_name='product.product',        string='Product'    )    type = fields.Selection([        ('service', 'Service'),        ('product', 'Product')],        string='Type',        required=True,        default='service'    )    description = fields.Char(        string='Description',        required=True    )    quantity = fields.Float(        string='Quantity',        default=1    )    price_unit = fields.Float(        string='Price unit'    )    subtotal = fields.Float(        string='Subtotal',        compute='compute_subtotal'    )    @api.one    @api.depends('quantity', 'price_unit')    def compute_subtotal(self):        self.subtotal = self.quantity * self.price_unit    @api.onchange('product_id')    def onchange_product_id(self):        if self.product_id:            self.description = self.product_id.name            self.type = 'service' if self.product_id.type == 'service' \                else 'product'            # @ TODO impuestos??            # Obtener el precio del producto a partir de la tarifa del cliente            self.price_unit = self.product_id.list_priceclass AccountInvoice(models.Model):    _inherit = 'account.invoice'    work_invoice_id = fields.Many2one('repair.workorderimproved')
 |