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.

319 lines
15 KiB

  1. # -*- coding: utf-8 -*-
  2. from datetime import datetime
  3. from openerp import api, fields, models, _
  4. from openerp.exceptions import ValidationError
  5. class operation_request(models.Model):
  6. _name = 'operation.request'
  7. def get_date_now(self):
  8. return datetime.strftime(datetime.now(), '%Y-%m-%d')
  9. @api.multi
  10. @api.depends('share_product_id', 'share_product_id.list_price', 'quantity')
  11. def _compute_subscription_amount(self):
  12. for operation_request in self:
  13. operation_request.subscription_amount = (operation_request.
  14. share_product_id.
  15. list_price *
  16. operation_request.
  17. quantity)
  18. request_date = fields.Date(string='Request date',
  19. default=lambda self: self.get_date_now())
  20. partner_id = fields.Many2one('res.partner',
  21. string='Cooperator',
  22. domain=[('member', '=', True)],
  23. required=True)
  24. partner_id_to = fields.Many2one('res.partner',
  25. string='Transfered to',
  26. domain=[('cooperator', '=', True)])
  27. operation_type = fields.Selection([('subscription', 'Subscription'),
  28. ('transfer', 'Transfer'),
  29. ('sell_back', 'Sell Back'),
  30. ('convert', 'Conversion')],
  31. string='Operation Type',
  32. required=True)
  33. share_product_id = fields.Many2one('product.product',
  34. string='Share type',
  35. domain=[('is_share', '=', True)],
  36. required=True)
  37. share_to_product_id = fields.Many2one('product.product',
  38. string='Convert to this share type',
  39. domain=[('is_share', '=', True)])
  40. share_short_name = fields.Char(related='share_product_id.short_name',
  41. string='Share type name')
  42. share_to_short_name = fields.Char(related='share_to_product_id.short_name',
  43. string='Share to type name')
  44. share_unit_price = fields.Float(related='share_product_id.list_price',
  45. string='Share price')
  46. share_to_unit_price = fields.Float(related='share_to_product_id.list_price',
  47. string='Share to price')
  48. subscription_amount = fields.Float(compute='_compute_subscription_amount',
  49. string='Operation amount')
  50. quantity = fields.Integer(string='Number of share',
  51. required=True)
  52. state = fields.Selection([('draft', 'Draft'),
  53. ('waiting', 'Waiting'),
  54. ('approved', 'Approved'),
  55. ('done', 'Done'),
  56. ('cancelled', 'Cancelled'),
  57. ('refused', 'Refused')],
  58. string='State',
  59. required=True,
  60. default='draft')
  61. user_id = fields.Many2one('res.users',
  62. string='Responsible',
  63. readonly=True,
  64. default=lambda self: self.env.user)
  65. subscription_request = fields.One2many('subscription.request',
  66. 'operation_request_id',
  67. string="Share Receiver Info",
  68. help="In case on a transfer of"
  69. " share. If the share receiver"
  70. " isn't a effective member then a"
  71. " subscription form should"
  72. " be filled.")
  73. receiver_not_member = fields.Boolean(string='Receiver is not a member')
  74. company_id = fields.Many2one('res.company',
  75. string='Company',
  76. required=True,
  77. change_default=True,
  78. readonly=True,
  79. default=lambda self: self.env['res.company']._company_default_get())
  80. invoice = fields.Many2one('account.invoice',
  81. string="Invoice")
  82. @api.multi
  83. def approve_operation(self):
  84. for rec in self:
  85. rec.write({'state': 'approved'})
  86. @api.multi
  87. def refuse_operation(self):
  88. for rec in self:
  89. rec.write({'state': 'refused'})
  90. @api.multi
  91. def submit_operation(self):
  92. for rec in self:
  93. rec.validate()
  94. rec.write({'state': 'waiting'})
  95. @api.multi
  96. def cancel_operation(self):
  97. for rec in self:
  98. rec.write({'state': 'cancelled'})
  99. @api.multi
  100. def reset_to_draft(self):
  101. for rec in self:
  102. rec.write({'state': 'draft'})
  103. def get_total_share_dic(self, partner):
  104. total_share_dic = {}
  105. prod_template_obj = self.env['product.product']
  106. share_products = prod_template_obj.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. amount_to_convert = self.share_unit_price * self.quantity
  156. share_price = self.share_to_product_id.list_price
  157. remainder = amount_to_convert % share_price
  158. if remainder != 0:
  159. raise ValidationError(_("The conversion must give a whole"
  160. " number for quantity"))
  161. if self.company_id.unmix_share_type:
  162. if self.share_product_id.code == self.share_to_product_id.code:
  163. raise ValidationError(_("You can't convert the share to"
  164. " the same share type."))
  165. if self.subscription_amount != self.partner_id.total_value:
  166. raise ValidationError(_("You must convert all the shares"
  167. " to the selected type."))
  168. else:
  169. if self.subscription_amount != self.partner_id.total_value:
  170. raise ValidationError(_("Converting just part of the"
  171. " shares is not yet implemented"))
  172. elif self.operation_type == 'transfer':
  173. if not self.receiver_not_member and self.company_id.unmix_share_type \
  174. and (self.partner_id_to.cooperator_type
  175. and self.partner_id.cooperator_type != self.partner_id_to.cooperator_type):
  176. raise ValidationError(_("This share type could not be"
  177. " transfered to " +
  178. self.partner_id_to.name))
  179. if self.partner_id_to.is_company \
  180. and not self.share_product_id.by_company:
  181. raise ValidationError(_("This share can not be"
  182. " subscribed by a company"))
  183. if not self.partner_id_to.is_company \
  184. and not self.share_product_id.by_individual:
  185. raise ValidationError(_("This share can not be"
  186. " subscribed an individual"))
  187. if self.receiver_not_member and self.subscription_request \
  188. and not self.subscription_request.validated:
  189. raise ValidationError(_("The information of the receiver"
  190. " are not correct. Please correct"
  191. " the information before"
  192. " submitting"))
  193. @api.multi
  194. def execute_operation(self):
  195. self.ensure_one()
  196. effective_date = self.get_date_now()
  197. sub_request = self.env['subscription.request']
  198. for rec in self:
  199. rec.validate()
  200. if rec.state != 'approved':
  201. raise ValidationError(_("This operation must be approved"
  202. " before to be executed"))
  203. values = {
  204. 'partner_id': rec.partner_id.id, 'quantity': rec.quantity,
  205. 'share_product_id': rec.share_product_id.id,
  206. 'type': rec.operation_type,
  207. 'share_unit_price': rec.share_unit_price,
  208. 'date': effective_date,
  209. }
  210. if rec.operation_type == 'sell_back':
  211. self.hand_share_over(rec.partner_id, rec.share_product_id,
  212. rec.quantity)
  213. elif rec.operation_type == 'convert':
  214. amount_to_convert = rec.share_unit_price * rec.quantity
  215. convert_quant = int(amount_to_convert / rec.share_to_product_id.list_price)
  216. remainder = amount_to_convert % rec.share_to_product_id.list_price
  217. if convert_quant > 0 and remainder == 0:
  218. share_ids = rec.partner_id.share_ids
  219. line = share_ids[0]
  220. if len(share_ids) > 1:
  221. share_ids[1:len(share_ids)].unlink()
  222. line.write({
  223. 'share_number': convert_quant,
  224. 'share_product_id': rec.share_to_product_id.id,
  225. 'share_unit_price': rec.share_to_unit_price,
  226. 'share_short_name': rec.share_to_short_name
  227. })
  228. values['share_to_product_id'] = rec.share_to_product_id.id
  229. values['quantity_to'] = convert_quant
  230. else:
  231. raise ValidationError(_("Converting just part of the"
  232. " shares is not yet implemented"))
  233. elif rec.operation_type == 'transfer':
  234. sequence_id = self.env.ref('easy_my_coop.sequence_subscription', False)
  235. if rec.receiver_not_member:
  236. partner = rec.subscription_request.create_coop_partner()
  237. # get cooperator number
  238. sub_reg_num = int(sequence_id.next_by_id())
  239. partner_vals = sub_request.get_eater_vals(partner, rec.share_product_id)
  240. partner_vals['member'] = True
  241. partner_vals['cooperator_register_number'] = sub_reg_num
  242. partner.write(partner_vals)
  243. rec.partner_id_to = partner
  244. else:
  245. # means an old member or cooperator candidate
  246. if not rec.partner_id_to.member:
  247. if rec.partner_id_to.cooperator_register_number == 0:
  248. sub_reg_num = int(sequence_id.next_by_id())
  249. partner_vals['cooperator_register_number'] = sub_reg_num
  250. partner_vals = sub_request.get_eater_vals(
  251. rec.partner_id_to,
  252. rec.share_product_id)
  253. partner_vals['member'] = True
  254. partner_vals['old_member'] = False
  255. rec.partner_id_to.write(partner_vals)
  256. # remove the parts to the giver
  257. self.hand_share_over(rec.partner_id,
  258. rec.share_product_id,
  259. rec.quantity)
  260. # give the share to the receiver
  261. self.env['share.line'].create({
  262. 'share_number': rec.quantity,
  263. 'partner_id': rec.partner_id_to.id,
  264. 'share_product_id': rec.share_product_id.id,
  265. 'share_unit_price': rec.share_unit_price,
  266. 'effective_date': effective_date})
  267. values['partner_id_to'] = rec.partner_id_to.id
  268. else:
  269. raise ValidationError(_("This operation is not yet"
  270. " implemented."))
  271. sequence_operation = self.env.ref('easy_my_coop.sequence_register_operation', False)
  272. sub_reg_operation = sequence_operation.next_by_id()
  273. values['name'] = sub_reg_operation
  274. values['register_number_operation'] = int(sub_reg_operation)
  275. rec.write({'state': 'done'})
  276. # send mail to the receiver
  277. if rec.operation_type == 'transfer':
  278. certificat_email_template = self.env.ref('easy_my_coop.email_template_share_transfer', False)
  279. certificat_email_template.send_mail(rec.partner_id_to.id, False)
  280. self.env['subscription.register'].create(values)
  281. certificat_email_template = self.env.ref('easy_my_coop.email_template_share_update', False)
  282. certificat_email_template.send_mail(rec.partner_id.id, False)