project_service_task.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. self.stage_id = 4
  50. @api.depends('activity_ids.work_cost', 'materials_used.price')
  51. def get_amount_total(self):
  52. for records in self:
  53. for hour in records:
  54. amount_totall = 0.0
  55. for line in hour.activity_ids:
  56. amount_totall += line.work_cost
  57. if self.include_materials==True:
  58. for line2 in hour.materials_used:
  59. amount_totall += line2.price
  60. records.amount_total = amount_totall
  61. @api.depends('activity_ids.time_spent')
  62. def hours_spent(self):
  63. for hour in self:
  64. effective_hour = 0.0
  65. for line in hour.works_done:
  66. effective_hour += line.time_spent
  67. self.effective_hour = effective_hour
  68. @api.one
  69. @api.depends('invoice_ids','state')
  70. def _get_invoice_count(self):
  71. self.invoice_count = len(self.invoice_ids)
  72. @api.multi
  73. def button_draft(self):
  74. if self.invoice_count > 0:
  75. raise Warning('Esta tarea tiene una factura asociada')
  76. if self.invoice_count == 0:
  77. self.stage_id = 1
  78. for work in self:
  79. work.write({'state': 'Preparado'})
  80. return True
  81. @api.multi
  82. def unlink(self):
  83. for task in self:
  84. if task.state in ('Facturado'):
  85. raise Warning(('No puedes borrar una tarea ya facturada'))
  86. if len(task.activity_ids)>0:
  87. raise Warning(('No puedes borrar una tarea que tiene actividades'))
  88. return super(ProjectServiceTask, self).unlink()
  89. @api.multi
  90. def Facturado(self):
  91. activity = self.activity_ids
  92. # print('****************************',activity,'**********************************')
  93. if not activity:
  94. raise osv.except_osv(_('UserError!'), _('No puedes facturas una tarea sin actividades.'))
  95. self.state = 'Facturado'
  96. inv_obj = self.env['account.invoice']
  97. inv_line_obj = self.env['account.invoice.line']
  98. customer = self.partner_id
  99. if not customer.name:
  100. raise osv.except_osv(_('UserError!'), _('Please select a Customer.'))
  101. company_id = self.env['res.users'].browse(1).company_id
  102. self.ensure_one()
  103. ir_values = self.env['ir.values']
  104. inv_data = {
  105. 'name': customer.name,
  106. 'reference': customer.name,
  107. 'account_id': customer.property_account_receivable.id,
  108. 'partner_id': customer.id,
  109. 'origin': self.name,
  110. 'task_invoice_id': self.id,
  111. }
  112. inv_id = inv_obj.create(inv_data)
  113. for records in self.activity_ids:
  114. if records.product_id.id:
  115. income_account = records.product_id.categ_id.property_account_income_categ.id
  116. if not income_account:
  117. raise osv.except_osv(_('UserError!'), _('There is no income account defined '
  118. 'for this product: "%s".') % (records.product_id.name,))
  119. if records.completed == False:
  120. raise osv.except_osv(_('UserError!'), _('Esta actividad aun no ha sido concluida '
  121. '"%s".') % (records.product_id.name,))
  122. inv_line_data = {
  123. 'name': records.product_id.name,
  124. 'account_id': income_account,
  125. 'price_unit': records.work_cost,
  126. 'quantity': 1,
  127. 'product_id': records.product_id.id,
  128. 'invoice_id': inv_id.id,
  129. 'invoice_line_tax_id': [(6, 0, [x.id for x in records.product_id.taxes_id])],
  130. }
  131. inv_line_obj.create(inv_line_data)
  132. for records in self.materials_used:
  133. if records.product_id.id:
  134. income_account = records.product_id.categ_id.property_account_income_categ.id
  135. if not income_account:
  136. raise osv.except_osv(_('UserError!'), _('There is no income account defined '
  137. 'for this product: "%s".') % (records.product_id.name,))
  138. if self.include_materials==True:
  139. inv_line_data = {
  140. 'name': records.product_id.name,
  141. 'account_id': income_account,
  142. 'price_unit': records.price,
  143. 'quantity': records.amount,
  144. 'product_id': records.product_id.id,
  145. 'invoice_id': inv_id.id,
  146. 'invoice_line_tax_id': [(6, 0, [x.id for x in records.product_id.taxes_id])],
  147. }
  148. inv_line_obj.create(inv_line_data)
  149. imd = self.env['ir.model.data']
  150. action = imd.xmlid_to_object('account.action_invoice_tree1')
  151. list_view_id = imd.xmlid_to_res_id('account.invoice_tree')
  152. form_view_id = imd.xmlid_to_res_id('account.invoice_form')
  153. result = {
  154. 'name': action.name,
  155. 'help': action.help,
  156. 'type': 'ir.actions.act_window',
  157. 'views': [[list_view_id, 'tree'], [form_view_id, 'form'], [False, 'graph'], [False, 'kanban'],
  158. [False, 'calendar'], [False, 'pivot']],
  159. 'target': action.target,
  160. 'context': action.context,
  161. 'res_model': 'account.invoice',
  162. }
  163. if len(inv_id) > 1:
  164. result['domain'] = "[('id','in',%s)]" % inv_id.ids
  165. elif len(inv_id) == 1:
  166. result['views'] = [(form_view_id, 'form')]
  167. result['res_id'] = inv_id.ids[0]
  168. else:
  169. result = {'type': 'ir.actions.act_window_close'}
  170. invoiced_records = self.env['project.service.task']
  171. total = 0
  172. self.stage_id = 3
  173. for rows in invoiced_records:
  174. invoiced_date = rows.date
  175. invoiced_date = invoiced_date[0:10]
  176. if invoiced_date == str(date.today()):
  177. total = total + rows.price_subtotal
  178. inv_id.signal_workflow('invoice_open')
  179. return result