project_service_task.py 9.0 KB

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