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.

235 lines
12 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_to_product_id = fields.Many2one('product.product', string='Convert 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_to_short_name = fields.Char(related='share_to_product_id.short_name', string='Share to type name')
  26. share_unit_price = fields.Float(related='share_product_id.list_price', string='Share price')
  27. share_to_unit_price = fields.Float(related='share_to_product_id.list_price', string='Share to price')
  28. subscription_amount = fields.Float(compute='_compute_subscription_amount', string='Operation amount')
  29. quantity = fields.Integer(string='Number of share', required=True)
  30. state = fields.Selection([('draft','Draft'),
  31. ('waiting','Waiting'),
  32. ('approved','Approved'),
  33. ('done','Done'),
  34. ('cancelled','Cancelled'),
  35. ('refused','Refused')], string='State',required=True, default='draft')
  36. user_id = fields.Many2one('res.users', string='Responsible', readonly=True, default=lambda self: self.env.user)
  37. subscription_request = fields.One2many('subscription.request','operation_request_id',
  38. string="Share Receiver Info",
  39. help="In case on a transfer of share. "
  40. "If the share receiver isn't a effective member "
  41. "then a subscription form should be filled.")
  42. receiver_not_member = fields.Boolean(string='Receiver is not a member')
  43. company_id = fields.Many2one('res.company', string='Company', required=True,
  44. change_default=True, readonly=True,
  45. default=lambda self: self.env['res.company']._company_default_get())
  46. invoice = fields.Many2one('account.invoice', string="Invoice")
  47. @api.multi
  48. def approve_operation(self):
  49. for rec in self:
  50. rec.write({'state':'approved'})
  51. @api.multi
  52. def refuse_operation(self):
  53. for rec in self:
  54. rec.write({'state':'refused'})
  55. @api.multi
  56. def submit_operation(self):
  57. for rec in self:
  58. rec.validate()
  59. rec.write({'state':'waiting'})
  60. @api.multi
  61. def cancel_operation(self):
  62. for rec in self:
  63. rec.write({'state':'cancelled'})
  64. @api.multi
  65. def reset_to_draft(self):
  66. for rec in self:
  67. rec.write({'state':'draft'})
  68. def get_total_share_dic(self, partner):
  69. total_share_dic = {}
  70. share_products = self.env['product.template'].search([('is_share','=',True)])
  71. for share_product in share_products:
  72. total_share_dic[share_product.id] = 0
  73. for line in partner.share_ids:
  74. total_share_dic[line.share_product_id.id] += line.share_number
  75. return total_share_dic
  76. # This function doesn't handle the case of a cooperator can own
  77. # different kinds of share type
  78. def hand_share_over(self, partner, share_product_id, quantity):
  79. if not partner.member:
  80. raise ValidationError(_("This operation can't be executed if the cooperator is not an effective member"))
  81. share_ind = len(partner.share_ids)
  82. i = 1
  83. while quantity > 0:
  84. line = self.partner_id.share_ids[share_ind-i]
  85. if line.share_product_id.id == share_product_id.id:
  86. if quantity > line.share_number:
  87. quantity -= line.share_number
  88. line.unlink()
  89. else:
  90. share_left = line.share_number - quantity
  91. quantity = 0
  92. line.write({'share_number': share_left})
  93. i += 1
  94. # if the cooperator sold all his shares he's no more an effective member
  95. remaning_share_dict = 0
  96. for share_quant in self.get_total_share_dic(partner).values():
  97. remaning_share_dict += share_quant
  98. if remaning_share_dict == 0:
  99. self.partner_id.write({'member': False,'old_member':True})
  100. def has_share_type(self):
  101. for line in self.partner_id.share_ids:
  102. if line.share_product_id.id == self.share_product_id.id:
  103. return True
  104. return False
  105. def validate(self):
  106. if not self.has_share_type() and self.operation_type in ['sell_back', 'transfer']:
  107. raise ValidationError(_("The cooperator doesn't own this share type. Please choose the appropriate share type."))
  108. if self.operation_type in ['sell_back','convert','transfer']:
  109. total_share_dic = self.get_total_share_dic(self.partner_id)
  110. if self.quantity > total_share_dic[self.share_product_id.id]:
  111. raise ValidationError(_("The cooperator can't hand over more shares that he/she owns."))
  112. if self.operation_type == 'convert' and self.company_id.unmix_share_type:
  113. if self.share_product_id.code == self.share_to_product_id.code:
  114. raise ValidationError(_("You can't convert the share to the same share type."))
  115. if self.subscription_amount != self.partner_id.total_value :
  116. raise ValidationError(_("You must convert all the shares to the selected type."))
  117. elif self.operation_type == 'transfer':
  118. if not self.receiver_not_member and self.company_id.unmix_share_type \
  119. and (self.partner_id_to.cooperator_type \
  120. and self.partner_id.cooperator_type != self.partner_id_to.cooperator_type):
  121. raise ValidationError(_("This share type could not be transfered "
  122. "to " + self.partner_id_to.name))
  123. @api.multi
  124. def execute_operation(self):
  125. effective_date = self.get_date_now()
  126. ir_sequence = self.env['ir.sequence']
  127. sub_request = self.env['subscription.request']
  128. email_template_obj = self.env['mail.template']
  129. for rec in self:
  130. rec.validate()
  131. if rec.state != 'approved':
  132. raise ValidationError(_("This operation must be approved before to be executed"))
  133. values = {
  134. 'partner_id':rec.partner_id.id, 'quantity':rec.quantity,
  135. 'share_product_id':rec.share_product_id.id, 'type':rec.operation_type,
  136. 'share_unit_price': rec.share_unit_price, 'date':effective_date,
  137. }
  138. if rec.operation_type == 'sell_back':
  139. self.hand_share_over(rec.partner_id, rec.share_product_id, rec.quantity)
  140. elif rec.operation_type == 'convert':
  141. amount_to_convert = rec.share_unit_price * rec.quantity
  142. convert_quant = int(amount_to_convert / rec.share_to_product_id.list_price)
  143. remainder = amount_to_convert % rec.share_to_product_id.list_price
  144. if rec.company_id.unmix_share_type:
  145. if convert_quant > 0 and remainder == 0:
  146. share_ids = rec.partner_id.share_ids
  147. line = share_ids[0]
  148. if len(share_ids) > 1:
  149. share_ids[1:len(share_ids)].unlink()
  150. line.write({
  151. 'share_number':convert_quant,
  152. 'share_product_id':rec.share_to_product_id.id,
  153. 'share_unit_price': rec.share_to_unit_price,
  154. 'share_short_name': rec.share_to_short_name
  155. })
  156. values['share_to_product_id'] = rec.share_to_product_id.id
  157. values['quantity_to'] = convert_quant
  158. else:
  159. raise ValidationError(_("Converting just part of the shares is not yet implemented"))
  160. elif rec.operation_type == 'transfer':
  161. if rec.receiver_not_member:
  162. partner = rec.subscription_request.create_coop_partner()
  163. #get cooperator number
  164. sequence_id = self.env.ref('easy_my_coop.sequence_subscription', False)
  165. sub_reg_num = sequence_id.next_by_id()
  166. partner_vals = sub_request.get_eater_vals(partner, rec.share_product_id)
  167. partner_vals['member'] = True
  168. partner_vals['cooperator_register_number'] = int(sub_reg_num)
  169. partner.write(partner_vals)
  170. rec.partner_id_to = partner
  171. else:
  172. if not rec.partner_id_to.member:
  173. partner_vals = sub_request.get_eater_vals(rec.partner_id_to, rec.share_product_id)
  174. partner_vals['member'] = True
  175. partner_vals['old_member'] = False
  176. rec.partner_id_to.write(partner_vals)
  177. #remove the parts to the giver
  178. self.hand_share_over(rec.partner_id, rec.share_product_id, rec.quantity)
  179. #give the share to the receiver
  180. self.env['share.line'].create({'share_number':rec.quantity,
  181. 'partner_id':rec.partner_id_to.id,
  182. 'share_product_id':rec.share_product_id.id,
  183. 'share_unit_price':rec.share_unit_price,
  184. 'effective_date':effective_date})
  185. values['partner_id_to'] = rec.partner_id_to.id
  186. else:
  187. raise ValidationError(_("This operation is not yet implemented."))
  188. #sequence_operation = ir_sequence.search([('name','=','Register Operation')])[0]
  189. sequence_operation = self.env.ref('easy_my_coop.sequence_register_operation', False)
  190. sub_reg_operation = sequence_operation.next_by_id()
  191. values['name'] = sub_reg_operation
  192. values['register_number_operation'] = int(sub_reg_operation)
  193. rec.write({'state':'done'})
  194. # send mail and to the receiver
  195. if rec.operation_type == 'transfer':
  196. certificat_email_template = self.env.ref('easy_my_coop.email_template_share_transfer', False)
  197. certificat_email_template.send_mail(rec.partner_id_to.id, False)
  198. self.env['subscription.register'].create(values)
  199. certificat_email_template = self.env.ref('easy_my_coop.email_template_share_update', False)
  200. certificat_email_template.send_mail(rec.partner_id.id, False)