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.

317 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. # 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. def get_share_trans_mail_template(self):
  184. return self.env.ref('easy_my_coop.email_template_share_transfer',
  185. False)
  186. def get_share_update_mail_template(self):
  187. return self.env.ref('easy_my_coop.email_template_share_update',
  188. False)
  189. @api.multi
  190. def execute_operation(self):
  191. self.ensure_one()
  192. effective_date = self.get_date_now()
  193. sub_request = self.env['subscription.request']
  194. for rec in self:
  195. rec.validate()
  196. if rec.state != 'approved':
  197. raise ValidationError(_("This operation must be approved"
  198. " before to be executed"))
  199. values = {
  200. 'partner_id': rec.partner_id.id, 'quantity': rec.quantity,
  201. 'share_product_id': rec.share_product_id.id,
  202. 'type': rec.operation_type,
  203. 'share_unit_price': rec.share_unit_price,
  204. 'date': effective_date,
  205. }
  206. if rec.operation_type == 'sell_back':
  207. self.hand_share_over(rec.partner_id, rec.share_product_id,
  208. rec.quantity)
  209. elif rec.operation_type == 'convert':
  210. amount_to_convert = rec.share_unit_price * rec.quantity
  211. convert_quant = int(amount_to_convert / rec.share_to_product_id.list_price)
  212. remainder = amount_to_convert % rec.share_to_product_id.list_price
  213. if convert_quant > 0 and remainder == 0:
  214. share_ids = rec.partner_id.share_ids
  215. line = share_ids[0]
  216. if len(share_ids) > 1:
  217. share_ids[1:len(share_ids)].unlink()
  218. line.write({
  219. 'share_number': convert_quant,
  220. 'share_product_id': rec.share_to_product_id.id,
  221. 'share_unit_price': rec.share_to_unit_price,
  222. 'share_short_name': rec.share_to_short_name
  223. })
  224. values['share_to_product_id'] = rec.share_to_product_id.id
  225. values['quantity_to'] = convert_quant
  226. else:
  227. raise ValidationError(_("Converting just part of the"
  228. " shares is not yet implemented"))
  229. elif rec.operation_type == 'transfer':
  230. sequence_id = self.env.ref('easy_my_coop.sequence_subscription', False)
  231. partner_vals = {'member': True}
  232. if rec.receiver_not_member:
  233. partner = rec.subscription_request.create_coop_partner()
  234. # get cooperator number
  235. sub_reg_num = int(sequence_id.next_by_id())
  236. partner_vals = sub_request.get_eater_vals(partner, rec.share_product_id)
  237. partner_vals['cooperator_register_number'] = sub_reg_num
  238. partner.write(partner_vals)
  239. rec.partner_id_to = partner
  240. else:
  241. # means an old member or cooperator candidate
  242. if not rec.partner_id_to.member:
  243. if rec.partner_id_to.cooperator_register_number == 0:
  244. sub_reg_num = int(sequence_id.next_by_id())
  245. partner_vals['cooperator_register_number'] = sub_reg_num
  246. partner_vals = sub_request.get_eater_vals(
  247. rec.partner_id_to,
  248. rec.share_product_id)
  249. partner_vals['old_member'] = False
  250. rec.partner_id_to.write(partner_vals)
  251. # remove the parts to the giver
  252. self.hand_share_over(rec.partner_id,
  253. rec.share_product_id,
  254. rec.quantity)
  255. # give the share to the receiver
  256. self.env['share.line'].create({
  257. 'share_number': rec.quantity,
  258. 'partner_id': rec.partner_id_to.id,
  259. 'share_product_id': rec.share_product_id.id,
  260. 'share_unit_price': rec.share_unit_price,
  261. 'effective_date': effective_date})
  262. values['partner_id_to'] = rec.partner_id_to.id
  263. else:
  264. raise ValidationError(_("This operation is not yet"
  265. " implemented."))
  266. sequence_operation = self.env.ref('easy_my_coop.sequence_register_operation', False) #noqa
  267. sub_reg_operation = sequence_operation.next_by_id()
  268. values['name'] = sub_reg_operation
  269. values['register_number_operation'] = int(sub_reg_operation)
  270. rec.write({'state': 'done'})
  271. # send mail to the receiver
  272. if rec.operation_type == 'transfer':
  273. cert_email_template = self.get_share_trans_mail_template()
  274. cert_email_template.send_mail(rec.partner_id_to.id, False)
  275. self.env['subscription.register'].create(values)
  276. cert_email_template = self.get_share_update_mail_template()
  277. cert_email_template.send_mail(rec.partner_id.id, False)