You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

194 lines
10 KiB

  1. # -*- coding: utf-8 -*-
  2. from datetime import datetime
  3. from openerp import api, fields, models, _
  4. from openerp.addons.base_iban import base_iban
  5. from openerp.exceptions import UserError, ValidationError
  6. class operation_request(models.Model):
  7. _name = 'operation.request'
  8. def get_date_now(self):
  9. return datetime.strftime(datetime.now(), '%Y-%m-%d')
  10. @api.multi
  11. @api.depends('share_product_id', 'share_product_id.list_price','quantity')
  12. def _compute_subscription_amount(self):
  13. for operation_request in self:
  14. operation_request.subscription_amount = operation_request.share_product_id.list_price * operation_request.quantity
  15. request_date = fields.Date(string='Request date', default=lambda self: self.get_date_now())
  16. partner_id = fields.Many2one('res.partner', string='Cooperator', domain=[('member','=',True)],required=True)
  17. partner_id_to = fields.Many2one('res.partner',string='Transfered to', domain=[('cooperator','=',True)])
  18. operation_type = fields.Selection([('subscription','Subscription'),
  19. ('transfer','Transfer'),
  20. ('sell_back','Sell Back'),
  21. ('convert','Conversion')],string='Operation Type', required=True)
  22. share_product_id = fields.Many2one('product.product', string='Share type', domain=[('is_share','=',True)], required=True)
  23. share_product_id_to = fields.Many2one('product.product', string='Concert to this share type', domain=[('is_share','=',True)])
  24. share_short_name = fields.Char(related='share_product_id.short_name', string='Share type name')
  25. share_unit_price = fields.Float(related='share_product_id.list_price', string='Share price')
  26. subscription_amount = fields.Float(compute='_compute_subscription_amount', string='Subscription amount')
  27. quantity = fields.Integer(string='Number of share', required=True)
  28. state = fields.Selection([('draft','Draft'),
  29. ('waiting','Waiting'),
  30. ('approved','Approved'),
  31. ('done','Done'),
  32. ('cancelled','Cancelled'),
  33. ('refused','Refused')], string='State',required=True, default='draft')
  34. user_id = fields.Many2one('res.users', string='Responsible', readonly=True, default=lambda self: self.env.user)
  35. subscription_request = fields.One2many('subscription.request','operation_request_id',
  36. string="Share Receiver Info",
  37. help="In case on a transfer of share. "
  38. "If the share receiver isn't a effective member "
  39. "then a subscription form should be filled.")
  40. receiver_not_member = fields.Boolean(string='Receiver is not a member')
  41. company_id = fields.Many2one('res.company', string='Company', required=True,
  42. change_default=True, readonly=True,
  43. default=lambda self: self.env['res.company']._company_default_get())
  44. invoice = fields.Many2one('account.invoice', string="Invoice")
  45. @api.one
  46. def approve_operation(self):
  47. self.write({'state':'approved'})
  48. @api.one
  49. def refuse_operation(self):
  50. self.write({'state':'refused'})
  51. @api.one
  52. def submit_operation(self):
  53. self.write({'state':'waiting'})
  54. @api.one
  55. def cancel_operation(self):
  56. self.write({'state':'cancelled'})
  57. @api.one
  58. def reset_to_draft(self):
  59. self.write({'state':'draft'})
  60. def get_total_share_dic(self, partner):
  61. total_share_dic = {}
  62. share_products = self.env['product.template'].search([('is_share','=',True)])
  63. for share_product in share_products:
  64. total_share_dic[share_product.id] = 0
  65. for line in partner.share_ids:
  66. total_share_dic[line.share_product_id.id] += line.share_number
  67. return total_share_dic
  68. # This function doesn't handle the case of a cooperator can own
  69. # different kinds of share type
  70. def hand_share_over(self, partner, share_product_id, quantity):
  71. if not partner.member:
  72. raise ValidationError(_("This operation can't be executed if the cooperator is not an effective member"))
  73. share_ind = len(partner.share_ids)
  74. i = 1
  75. while quantity > 0:
  76. line = self.partner_id.share_ids[share_ind-i]
  77. if line.share_product_id.id == share_product_id.id:
  78. if quantity > line.share_number:
  79. quantity -= line.share_number
  80. line.unlink()
  81. else:
  82. share_left = line.share_number - quantity
  83. quantity = 0
  84. line.write({'share_number': share_left})
  85. i += 1
  86. # if the cooperator sold all his shares he's no more an effective member
  87. remaning_share_dict = 0
  88. for share_quant in self.get_total_share_dic(partner).values():
  89. remaning_share_dict += share_quant
  90. if remaning_share_dict == 0:
  91. self.partner_id.write({'member': False,'old_member':True})
  92. def has_share_type(self):
  93. for line in self.partner_id.share_ids:
  94. if line.share_product_id.id == self.share_product_id.id:
  95. return True
  96. return False
  97. @api.one
  98. def execute_operation(self):
  99. effective_date = self.get_date_now()
  100. if not self.has_share_type():
  101. raise ValidationError(_("The cooperator doesn't own this share type. Please choose the appropriate share type."))
  102. if self.state != 'approved':
  103. raise ValidationError(_("This operation must be approved before to be executed"))
  104. if self.operation_type in ['sell_back','convert','transfer']:
  105. total_share_dic = self.get_total_share_dic(self.partner_id)
  106. if self.quantity > total_share_dic[self.share_product_id.id]:
  107. raise ValidationError(_("The cooperator can't hand over more shares that he/she owns."))
  108. if self.operation_type == 'sell_back':
  109. self.hand_share_over(self.partner_id, self.share_product_id, self.quantity)
  110. elif self.operation_type == 'convert':
  111. print "convert"
  112. amount_to_convert = self.share_unit_price * self.quantity
  113. share_to_quant = int(amount_to_convert / self.share_product_id_to.list_price)
  114. remainder = amount_to_convert % self.share_product_id_to.list_price
  115. print self.share_product_id_to.list_price
  116. print amount_to_convert
  117. print share_to_quant
  118. print remainder
  119. #self.hand_share_over(self.partner_id, self.share_product_id, self.quantity)
  120. elif self.operation_type == 'transfer':
  121. if self.receiver_not_member:
  122. partner = self.subscription_request.create_coop_partner()
  123. #get cooperator number
  124. sequence_id = self.env['ir.sequence'].search([('name','=','Subscription Register')])[0]
  125. sub_reg_num = sequence_id.next_by_id()
  126. partner_vals = self.env['subscription.request'].get_eater_vals(partner, self.share_product_id)
  127. partner_vals['member'] = True
  128. partner_vals['cooperator_register_number'] = int(sub_reg_num)
  129. partner.write(partner_vals)
  130. self.partner_id_to = partner
  131. else:
  132. if self.company_id.unmix_share_type and (self.partner_id_to.cooperator_type and self.partner_id.cooperator_type != self.partner_id_to.cooperator_type):
  133. raise ValidationError(_("This share type could not be transfered "
  134. "to " + self.partner_id_to.name))
  135. if not self.partner_id_to.member:
  136. partner_vals = self.env['subscription.request'].get_eater_vals(self.partner_id_to, self.share_product_id)
  137. partner_vals['member'] = True
  138. partner_vals['old_member'] = False
  139. self.partner_id_to.write(partner_vals)
  140. #remove the parts to the giver
  141. self.hand_share_over(self.partner_id, self.share_product_id, self.quantity)
  142. #give the share to the receiver
  143. self.env['share.line'].create({'share_number':self.quantity,
  144. 'partner_id':self.partner_id_to.id,
  145. 'share_product_id':self.share_product_id.id,
  146. 'share_unit_price':self.share_unit_price,
  147. 'effective_date':effective_date})
  148. else:
  149. raise ValidationError(_("This operation is not yet implemented."))
  150. sequence_operation = self.env['ir.sequence'].search([('name','=','Register Operation')])[0]
  151. sub_reg_operation = sequence_operation.next_by_id()
  152. values = {'name':sub_reg_operation,'register_number_operation':int(sub_reg_operation),
  153. 'partner_id':self.partner_id.id, 'quantity':self.quantity,
  154. 'share_product_id':self.share_product_id.id, 'type':self.operation_type,
  155. 'share_unit_price': self.share_unit_price, 'date':effective_date,
  156. }
  157. self.write({'state':'done'})
  158. email_template_obj = self.env['mail.template']
  159. if self.operation_type == 'transfer':
  160. values['partner_id_to'] = self.partner_id_to.id
  161. certificat_email_template = email_template_obj.search([('name', '=', "Share transfer - Send By Email")])[0]
  162. certificat_email_template.send_mail(self.partner_id_to.id, False)
  163. self.env['subscription.register'].create(values)
  164. certificat_email_template = email_template_obj.search([('name', '=', "Share update - Send By Email")])[0]
  165. certificat_email_template.send_mail(self.partner_id.id, False)