project_service_task.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. # -*- coding: utf-8 -*-
  2. from datetime import date
  3. from dateutil.relativedelta import relativedelta
  4. from openerp import models, api, fields, tools, _
  5. from openerp.exceptions import ValidationError, except_orm, Warning, RedirectWarning
  6. from openerp.osv import osv
  7. class ProjectServiceTask(models.Model):
  8. _name = 'project.service.task'
  9. name = fields.Char(string='Title', required=True)
  10. project_id = fields.Many2one('project.service', string='Vehicle', required=True, track_visibility='onchange')
  11. user_id = fields.Many2one('res.users', string='Assigned to', select=True)
  12. description = fields.Html('Description')
  13. priority = fields.Selection([('0', 'Normal'), ('1', 'High')], string='Priority', select=True)
  14. partner_id = fields.Many2one('res.partner', string='Customer')
  15. date_assign = fields.Datetime(string='Assigning Date', select=True, copy=False, readonly=True)
  16. date_deadline = fields.Datetime(string='Deadline', select=True, copy=False)
  17. color = fields.Integer(string='Color Index')
  18. stage_id = fields.Many2one('project.service.stage', string='Stage', track_visibility='onchange', copy=False)
  19. effective_hour = fields.Float(string='Hours Spent', compute="hours_spent",readonly=True)
  20. activity_ids = fields.One2many('project.service.activity', 'task_id', string='Planned/Ordered Works')
  21. materials_used = fields.One2many('project.service.material', 'task_id', string='Materials Used')
  22. amount_total = fields.Float(string='Total Amount', compute="get_amount_total", readonly=True)
  23. include_materials = fields.Boolean('Incluir')
  24. state = fields.Selection([
  25. ('Preparado', 'Preparado'),
  26. ('Facturado', 'Facturado'),
  27. ('Cancelado', 'Cancelado'),
  28. ], string='Status', readonly=True, default='Preparado', track_visibility='onchange', select=True)
  29. sequence = fields.Integer(string='Sequence', select=True, help="Gives the sequence order when displaying a list of tasks.")
  30. invoice_ids = fields.One2many('account.invoice', 'task_invoice_id')
  31. invoice_count = fields.Integer(
  32. string='Facturas',
  33. compute='_get_invoice_count',
  34. )
  35. works_done = fields.One2many('project.service.activity', 'task_id', string='Work Done', domain=[('completed', '=', True)])
  36. _defaults = {
  37. 'stage_id': 1,
  38. 'state': 'Preparado',
  39. 'user_id': lambda obj, cr, uid, ctx=None: uid,
  40. 'date_start': fields.datetime.now(),
  41. }
  42. @api.one
  43. @api.onchange('project_id')
  44. def onchange_name(self):
  45. self.partner_id = self.project_id.partner_id.id
  46. @api.multi
  47. def cancel(self):
  48. self.state = 'Cancelado'
  49. @api.depends('activity_ids.work_cost', 'materials_used.price')
  50. def get_amount_total(self):
  51. for records in self:
  52. for hour in records:
  53. amount_totall = 0.0
  54. for line in hour.activity_ids:
  55. amount_totall += line.work_cost
  56. if self.include_materials==True:
  57. for line2 in hour.materials_used:
  58. amount_totall += line2.price
  59. records.amount_total = amount_totall
  60. @api.depends('activity_ids.time_spent')
  61. def hours_spent(self):
  62. for hour in self:
  63. effective_hour = 0.0
  64. for line in hour.works_done:
  65. effective_hour += line.time_spent
  66. self.effective_hour = effective_hour
  67. @api.one
  68. @api.depends('invoice_ids','state')
  69. def _get_invoice_count(self):
  70. self.invoice_count = len(self.invoice_ids)
  71. @api.multi
  72. def button_draft(self):
  73. if self.invoice_count > 0:
  74. raise Warning('Esta tarea tiene una factura asociada')
  75. if self.invoice_count == 0:
  76. for work in self:
  77. work.write({'state': 'Preparado'})
  78. return True
  79. @api.multi
  80. def unlink(self):
  81. for task in self:
  82. if task.state in ('Facturado'):
  83. raise Warning(('No puedes borrar una tarea ya facturada'))
  84. if len(task.activity_ids)>0:
  85. raise Warning(('No puedes borrar una tarea que tiene actividades'))
  86. return super(ProjectServiceTask, self).unlink()
  87. @api.multi
  88. def Facturado(self):
  89. activity = self.activity_ids
  90. if not activity:
  91. raise osv.except_osv(_('UserError!'), _('No puedes facturas una tarea sin actividades.'))
  92. self.state = 'Facturado'
  93. inv_obj = self.env['account.invoice']
  94. inv_line_obj = self.env['account.invoice.line']
  95. customer = self.partner_id
  96. if not customer.name:
  97. raise osv.except_osv(_('UserError!'), _('Please select a Customer.'))
  98. company_id = self.env['res.users'].browse(1).company_id
  99. self.ensure_one()
  100. ir_values = self.env['ir.values']
  101. inv_data = {
  102. 'name': customer.name,
  103. 'reference': customer.name,
  104. 'account_id': customer.property_account_receivable.id,
  105. 'partner_id': customer.id,
  106. 'origin': self.name,
  107. 'task_invoice_id': self.id
  108. }
  109. inv_id = inv_obj.create(inv_data)
  110. for records in self.activity_ids:
  111. if records.product_id.id:
  112. income_account = records.product_id.categ_id.property_account_income_categ.id
  113. if not income_account:
  114. raise osv.except_osv(_('UserError!'), _('There is no income account defined '
  115. 'for this product: "%s".') % (records.product_id.name,))
  116. if records.completed == False:
  117. raise osv.except_osv(_('UserError!'), _('Esta actividad aun no ha sido concluida '
  118. '"%s".') % (records.product_id.name,))
  119. inv_line_data = {
  120. 'name': records.product_id.name,
  121. 'account_id': income_account,
  122. 'price_unit': records.work_cost,
  123. 'quantity': 1,
  124. 'product_id': records.product_id.id,
  125. 'invoice_id': inv_id.id,
  126. }
  127. inv_line_obj.create(inv_line_data)
  128. for records in self.materials_used:
  129. if records.product_id.id:
  130. income_account = records.product_id.categ_id.property_account_income_categ.id
  131. if not income_account:
  132. raise osv.except_osv(_('UserError!'), _('There is no income account defined '
  133. 'for this product: "%s".') % (records.product_id.name,))
  134. if self.include_materials==True:
  135. inv_line_data = {
  136. 'name': records.product_id.name,
  137. 'account_id': income_account,
  138. 'price_unit': records.price,
  139. 'quantity': records.amount,
  140. 'product_id': records.product_id.id,
  141. 'invoice_id': inv_id.id,
  142. }
  143. inv_line_obj.create(inv_line_data)
  144. imd = self.env['ir.model.data']
  145. action = imd.xmlid_to_object('account.action_invoice_tree1')
  146. list_view_id = imd.xmlid_to_res_id('account.invoice_tree')
  147. form_view_id = imd.xmlid_to_res_id('account.invoice_form')
  148. result = {
  149. 'name': action.name,
  150. 'help': action.help,
  151. 'type': 'ir.actions.act_window',
  152. 'views': [[list_view_id, 'tree'], [form_view_id, 'form'], [False, 'graph'], [False, 'kanban'],
  153. [False, 'calendar'], [False, 'pivot']],
  154. 'target': action.target,
  155. 'context': action.context,
  156. 'res_model': 'account.invoice',
  157. }
  158. if len(inv_id) > 1:
  159. result['domain'] = "[('id','in',%s)]" % inv_id.ids
  160. elif len(inv_id) == 1:
  161. result['views'] = [(form_view_id, 'form')]
  162. result['res_id'] = inv_id.ids[0]
  163. else:
  164. result = {'type': 'ir.actions.act_window_close'}
  165. invoiced_records = self.env['project.service.task']
  166. total = 0
  167. for rows in invoiced_records:
  168. invoiced_date = rows.date
  169. invoiced_date = invoiced_date[0:10]
  170. if invoiced_date == str(date.today()):
  171. total = total + rows.price_subtotal
  172. return result