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.

304 lines
15 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
  1. # -*- coding: utf-8 -*-
  2. from datetime import datetime
  3. from odoo import api, fields, models, _
  4. from odoo.exceptions import ValidationError
  5. class operation_request(models.Model):
  6. _name = 'operation.request'
  7. _description = "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.
  15. share_product_id.
  16. list_price *
  17. operation_request.
  18. quantity)
  19. request_date = fields.Date(string='Request date',
  20. default=lambda self: self.get_date_now())
  21. partner_id = fields.Many2one('res.partner',
  22. string='Cooperator',
  23. domain=[('member', '=', True)],
  24. required=True)
  25. partner_id_to = fields.Many2one('res.partner',
  26. string='Transfered to',
  27. domain=[('cooperator', '=', True)])
  28. operation_type = fields.Selection([('subscription', 'Subscription'),
  29. ('transfer', 'Transfer'),
  30. ('sell_back', 'Sell Back'),
  31. ('convert', 'Conversion')],
  32. string='Operation Type',
  33. required=True)
  34. share_product_id = fields.Many2one('product.product',
  35. string='Share type',
  36. domain=[('is_share', '=', True)],
  37. required=True)
  38. share_to_product_id = fields.Many2one('product.product',
  39. string='Convert to this share type',
  40. domain=[('is_share', '=', True)])
  41. share_short_name = fields.Char(related='share_product_id.short_name',
  42. string='Share type name')
  43. share_to_short_name = fields.Char(related='share_to_product_id.short_name',
  44. string='Share to type name')
  45. share_unit_price = fields.Float(related='share_product_id.list_price',
  46. string='Share price')
  47. share_to_unit_price = fields.Float(related='share_to_product_id.list_price',
  48. string='Share to price')
  49. subscription_amount = fields.Float(compute='_compute_subscription_amount',
  50. string='Operation amount')
  51. quantity = fields.Integer(string='Number of share',
  52. required=True)
  53. state = fields.Selection([('draft', 'Draft'),
  54. ('waiting', 'Waiting'),
  55. ('approved', 'Approved'),
  56. ('done', 'Done'),
  57. ('cancelled', 'Cancelled'),
  58. ('refused', 'Refused')],
  59. string='State',
  60. required=True,
  61. default='draft')
  62. user_id = fields.Many2one('res.users',
  63. string='Responsible',
  64. readonly=True,
  65. default=lambda self: self.env.user)
  66. subscription_request = fields.One2many('subscription.request',
  67. 'operation_request_id',
  68. string="Share Receiver Info",
  69. help="In case on a transfer of"
  70. " share. If the share receiver"
  71. " isn't a effective member then a"
  72. " subscription form should"
  73. " be filled.")
  74. receiver_not_member = fields.Boolean(string='Receiver is not a member')
  75. company_id = fields.Many2one('res.company',
  76. string='Company',
  77. required=True,
  78. change_default=True,
  79. readonly=True,
  80. default=lambda self: self.env['res.company']._company_default_get())
  81. invoice = fields.Many2one('account.invoice',
  82. string="Invoice")
  83. @api.multi
  84. def approve_operation(self):
  85. for rec in self:
  86. rec.write({'state': 'approved'})
  87. @api.multi
  88. def refuse_operation(self):
  89. for rec in self:
  90. rec.write({'state': 'refused'})
  91. @api.multi
  92. def submit_operation(self):
  93. for rec in self:
  94. rec.validate()
  95. rec.write({'state': 'waiting'})
  96. @api.multi
  97. def cancel_operation(self):
  98. for rec in self:
  99. rec.write({'state': 'cancelled'})
  100. @api.multi
  101. def reset_to_draft(self):
  102. for rec in self:
  103. rec.write({'state': 'draft'})
  104. def get_total_share_dic(self, partner):
  105. total_share_dic = {}
  106. share_products = self.env['product.template'].search([('is_share', '=', True)])
  107. for share_product in share_products:
  108. total_share_dic[share_product.id] = 0
  109. for line in partner.share_ids:
  110. total_share_dic[line.share_product_id.id] += line.share_number
  111. return total_share_dic
  112. # This function doesn't handle the case of a cooperator can own
  113. # different kinds of share type
  114. def hand_share_over(self, partner, share_product_id, quantity):
  115. if not partner.member:
  116. raise ValidationError(_("This operation can't be executed if the"
  117. " cooperator is not an effective member"))
  118. share_ind = len(partner.share_ids)
  119. i = 1
  120. while quantity > 0:
  121. line = self.partner_id.share_ids[share_ind-i]
  122. if line.share_product_id.id == share_product_id.id:
  123. if quantity > line.share_number:
  124. quantity -= line.share_number
  125. line.unlink()
  126. else:
  127. share_left = line.share_number - quantity
  128. quantity = 0
  129. line.write({'share_number': share_left})
  130. i += 1
  131. # if the cooperator sold all his shares he's no more
  132. # an effective member
  133. remaning_share_dict = 0
  134. for share_quant in self.get_total_share_dic(partner).values():
  135. remaning_share_dict += share_quant
  136. if remaning_share_dict == 0:
  137. self.partner_id.write({'member': False, 'old_member': True})
  138. def has_share_type(self):
  139. for line in self.partner_id.share_ids:
  140. if line.share_product_id.id == self.share_product_id.id:
  141. return True
  142. return False
  143. def validate(self):
  144. if not self.has_share_type() and \
  145. self.operation_type in ['sell_back', 'transfer']:
  146. raise ValidationError(_("The cooperator doesn't own this share"
  147. " type. Please choose the appropriate"
  148. " share type."))
  149. if self.operation_type in ['sell_back', 'convert', 'transfer']:
  150. total_share_dic = self.get_total_share_dic(self.partner_id)
  151. if self.quantity > total_share_dic[self.share_product_id.id]:
  152. raise ValidationError(_("The cooperator can't hand over more"
  153. " shares that he/she owns."))
  154. if self.operation_type == 'convert':
  155. if self.company_id.unmix_share_type:
  156. if self.share_product_id.code == self.share_to_product_id.code:
  157. raise ValidationError(_("You can't convert the share to"
  158. " the same share type."))
  159. if self.subscription_amount != self.partner_id.total_value:
  160. raise ValidationError(_("You must convert all the shares"
  161. " to the selected type."))
  162. else:
  163. if self.subscription_amount != self.partner_id.total_value:
  164. raise ValidationError(_("Converting just part of the"
  165. " shares is not yet implemented"))
  166. elif self.operation_type == 'transfer':
  167. if not self.receiver_not_member and self.company_id.unmix_share_type \
  168. and (self.partner_id_to.cooperator_type
  169. and self.partner_id.cooperator_type != self.partner_id_to.cooperator_type):
  170. raise ValidationError(_("This share type could not be"
  171. " transfered to " +
  172. self.partner_id_to.name))
  173. if self.receiver_not_member and self.subscription_request \
  174. and not self.subscription_request.validated:
  175. raise ValidationError(_("The information of the receiver"
  176. " are not correct. Please correct"
  177. " the information before"
  178. " submitting"))
  179. @api.multi
  180. def execute_operation(self):
  181. self.ensure_one()
  182. effective_date = self.get_date_now()
  183. sub_request = self.env['subscription.request']
  184. for rec in self:
  185. rec.validate()
  186. if rec.state != 'approved':
  187. raise ValidationError(_("This operation must be approved"
  188. " before to be executed"))
  189. values = {
  190. 'partner_id': rec.partner_id.id, 'quantity': rec.quantity,
  191. 'share_product_id': rec.share_product_id.id,
  192. 'type': rec.operation_type,
  193. 'share_unit_price': rec.share_unit_price,
  194. 'date': effective_date,
  195. }
  196. if rec.operation_type == 'sell_back':
  197. self.hand_share_over(rec.partner_id, rec.share_product_id,
  198. rec.quantity)
  199. elif rec.operation_type == 'convert':
  200. amount_to_convert = rec.share_unit_price * rec.quantity
  201. convert_quant = int(amount_to_convert / rec.share_to_product_id.list_price)
  202. remainder = amount_to_convert % rec.share_to_product_id.list_price
  203. if convert_quant > 0 and remainder == 0:
  204. share_ids = rec.partner_id.share_ids
  205. line = share_ids[0]
  206. if len(share_ids) > 1:
  207. share_ids[1:len(share_ids)].unlink()
  208. line.write({
  209. 'share_number': convert_quant,
  210. 'share_product_id': rec.share_to_product_id.id,
  211. 'share_unit_price': rec.share_to_unit_price,
  212. 'share_short_name': rec.share_to_short_name
  213. })
  214. values['share_to_product_id'] = rec.share_to_product_id.id
  215. values['quantity_to'] = convert_quant
  216. else:
  217. raise ValidationError(_("Converting just part of the"
  218. " shares is not yet implemented"))
  219. elif rec.operation_type == 'transfer':
  220. sequence_id = self.env.ref('easy_my_coop.sequence_subscription', False)
  221. if rec.receiver_not_member:
  222. partner = rec.subscription_request.create_coop_partner()
  223. # get cooperator number
  224. sub_reg_num = int(sequence_id.next_by_id())
  225. partner_vals = sub_request.get_eater_vals(partner, rec.share_product_id)
  226. partner_vals['member'] = True
  227. partner_vals['cooperator_register_number'] = sub_reg_num
  228. partner.write(partner_vals)
  229. rec.partner_id_to = partner
  230. else:
  231. # means an old member or cooperator candidate
  232. if not rec.partner_id_to.member:
  233. if rec.partner_id_to.cooperator_register_number == 0:
  234. sub_reg_num = int(sequence_id.next_by_id())
  235. partner_vals['cooperator_register_number'] = sub_reg_num
  236. partner_vals = sub_request.get_eater_vals(
  237. rec.partner_id_to,
  238. rec.share_product_id)
  239. partner_vals['member'] = True
  240. partner_vals['old_member'] = False
  241. rec.partner_id_to.write(partner_vals)
  242. # remove the parts to the giver
  243. self.hand_share_over(rec.partner_id,
  244. rec.share_product_id,
  245. rec.quantity)
  246. # give the share to the receiver
  247. self.env['share.line'].create({
  248. 'share_number': rec.quantity,
  249. 'partner_id': rec.partner_id_to.id,
  250. 'share_product_id': rec.share_product_id.id,
  251. 'share_unit_price': rec.share_unit_price,
  252. 'effective_date': effective_date})
  253. values['partner_id_to'] = rec.partner_id_to.id
  254. else:
  255. raise ValidationError(_("This operation is not yet"
  256. " implemented."))
  257. sequence_operation = self.env.ref('easy_my_coop.sequence_register_operation', False)
  258. sub_reg_operation = sequence_operation.next_by_id()
  259. values['name'] = sub_reg_operation
  260. values['register_number_operation'] = int(sub_reg_operation)
  261. rec.write({'state': 'done'})
  262. # send mail to the receiver
  263. if rec.operation_type == 'transfer':
  264. certificat_email_template = self.env.ref('easy_my_coop.email_template_share_transfer', False)
  265. certificat_email_template.send_mail(rec.partner_id_to.id, False)
  266. self.env['subscription.register'].create(values)
  267. certificat_email_template = self.env.ref('easy_my_coop.email_template_share_update', False)
  268. certificat_email_template.send_mail(rec.partner_id.id, False)