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