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.

311 lines
15 KiB

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