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.

211 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_short_name = fields.Char(related='share_product_id.short_name', string='Share type name')
  24. share_unit_price = fields.Float(related='share_product_id.list_price', string='Share price')
  25. subscription_amount = fields.Float(compute='_compute_subscription_amount', string='Subscription amount')
  26. quantity = fields.Integer(string='Number of share', required=True)
  27. state = fields.Selection([('draft','Draft'),
  28. ('waiting','Waiting'),
  29. ('approved','Approved'),
  30. ('done','Done'),
  31. ('cancelled','Cancelled'),
  32. ('refused','Refused')], string='State',required=True, default='draft')
  33. user_id = fields.Many2one('res.users', string='Responsible', readonly=True, default=lambda self: self.env.user)
  34. subscription_request = fields.One2many('subscription.request','operation_request_id',
  35. string="Share Receiver Info",
  36. help="In case on a transfer of share. "
  37. "If the share receiver isn't a effective member "
  38. "then a subscription form should be filled.")
  39. receiver_not_member = fields.Boolean(string='Receiver is not a member')
  40. company_id = fields.Many2one('res.company', string='Company', required=True,
  41. change_default=True, readonly=True,
  42. default=lambda self: self.env['res.company']._company_default_get())
  43. # def create_credit_note(self):
  44. # # getting info in order to fill in the invoice
  45. # product_obj = self.env['product.product']
  46. # product = product_obj.search([('default_code','=','share_250')])[0]
  47. # #product = product_obj.browse(cr, uid, product_id, context)
  48. # journal = self.env['account.journal'].search([('code','=','SUBJ')])[0]
  49. # # TODO check that this account in the right one and do the same on the product
  50. # account = self.env['account.account'].search([('code','=','416000')])[0]
  51. # capital_account_id = self.pool.get('account.account').search(cr, uid, [('code','=','416000')])[0]
  52. # # creating invoice and invoice lines
  53. # account_obj = self.env['account.invoice']
  54. # account_invoice_id = account_obj.create({'partner_id':vals['partner_id'],
  55. # 'journal_id':journal.id,'account_id':account.id,
  56. # 'type': 'out_refund', 'release_capital_request':True})
  57. # result = self.pool.get('account.invoice.line').product_id_change(cr, uid, False, product.id, False, vals['quantity'], '', 'out_invoice', vals['partner_id'])
  58. # self.pool.get('account.invoice.line').create({'invoice_id':account_invoice_id,
  59. # 'product_id':product.id,'quantity':vals['quantity'],
  60. # 'price_unit':result['value']['price_unit'],
  61. # 'uos_id':result['value']['uos_id'],'account_id':result['value']['account_id'],
  62. # 'name':product.name})
  63. # # run the validation on the invoice
  64. # wf_service = netsvc.LocalService("workflow")
  65. # wf_service.trg_validate(uid, 'account.invoice', account_invoice_id, 'invoice_open', cr)
  66. # #we get the print service for the invoice and send directly the invoice by mail
  67. # email_template_obj = self.pool.get('email.template')
  68. # invoice_email_template_id = email_template_obj.search(cr, uid, [('name', '=', 'Request to Release Capital - Send by Email')])[0]
  69. # # we send the email with the invoice in attachment
  70. # email_template_obj.send_mail(cr, uid, invoice_email_template_id, account_invoice_id, True, context)
  71. # account_obj.write(cr, uid, account_invoice_id,{'sent':True},context)
  72. # return True
  73. @api.one
  74. def approve_operation(self):
  75. self.write({'state':'approved'})
  76. @api.one
  77. def refuse_operation(self):
  78. self.write({'state':'refused'})
  79. @api.one
  80. def submit_operation(self):
  81. self.write({'state':'waiting'})
  82. @api.one
  83. def cancel_operation(self):
  84. self.write({'state':'cancelled'})
  85. @api.one
  86. def reset_to_draft(self):
  87. self.write({'state':'draft'})
  88. def get_total_share_dic(self, partner):
  89. total_share_dic = {}
  90. share_products = self.env['product.template'].search([('is_share','=',True)])
  91. for share_product in share_products:
  92. total_share_dic[share_product.id] = 0
  93. for line in partner.share_ids:
  94. total_share_dic[line.share_product_id.id] += line.share_number
  95. return total_share_dic
  96. # This function doesn't handle the case of a cooperator can own
  97. # different kinds of share type
  98. def hand_share_over(self, partner, share_product_id, quantity):
  99. if not partner.member:
  100. raise ValidationError(_("This operation can't be executed if the cooperator is not an effective member"))
  101. total_share_dic = self.get_total_share_dic(partner)
  102. if quantity > total_share_dic[share_product_id.id]:
  103. raise ValidationError(_("The cooperator can't hand over more shares that he/she owns."))
  104. share_ind = len(partner.share_ids)
  105. i = 1
  106. while quantity > 0:
  107. line = self.partner_id.share_ids[share_ind-i]
  108. if line.share_product_id.id == share_product_id.id:
  109. if quantity > line.share_number:
  110. quantity -= line.share_number
  111. line.unlink()
  112. else:
  113. share_left = line.share_number - quantity
  114. quantity = 0
  115. line.write({'share_number': share_left})
  116. i += 1
  117. # if the cooperator sold all his shares he's no more a effective member
  118. remaning_share_dict = 0
  119. for share_quant in self.get_total_share_dic(partner).values():
  120. remaning_share_dict += share_quant
  121. if remaning_share_dict == 0:
  122. self.partner_id.write({'member': False,'old_member':True})
  123. def has_share_type(self):
  124. for line in self.partner_id.share_ids:
  125. if line.share_product_id.id == self.share_product_id.id:
  126. return True
  127. return False
  128. @api.one
  129. def execute_operation(self):
  130. effective_date = self.get_date_now()
  131. if not self.has_share_type():
  132. raise ValidationError(_("The cooperator doesn't own this share type. Please choose the appropriate share type."))
  133. if self.state != 'approved':
  134. raise ValidationError(_("This operation must be approved before to be executed"))
  135. if self.operation_type == 'sell_back':
  136. self.hand_share_over(self.partner_id, self.share_product_id, self.quantity)
  137. elif self.operation_type == 'transfer':
  138. if self.receiver_not_member:
  139. partner = self.subscription_request.create_coop_partner()
  140. #get cooperator number
  141. sequence_id = self.env['ir.sequence'].search([('name','=','Subscription Register')])[0]
  142. sub_reg_num = sequence_id.next_by_id()
  143. partner_vals = self.env['subscription.request'].get_eater_vals(partner, self.share_product_id)
  144. partner_vals['member'] = True
  145. partner_vals['cooperator_register_number'] = int(sub_reg_num)
  146. partner.write(partner_vals)
  147. self.partner_id_to = partner
  148. else:
  149. if self.company_id.unmix_share_type and (self.partner_id_to.cooperator_type and self.partner_id.cooperator_type != self.partner_id_to.cooperator_type):
  150. raise ValidationError(_("This share type could not be transfered "
  151. "to " + self.partner_id_to.name))
  152. if not self.partner_id_to.member:
  153. partner_vals = self.env['subscription.request'].get_eater_vals(self.partner_id_to, self.share_product_id)
  154. partner_vals['member'] = True
  155. partner_vals['old_member'] = False
  156. self.partner_id_to.write(partner_vals)
  157. #remove the parts to the giver
  158. self.hand_share_over(self.partner_id, self.share_product_id, self.quantity)
  159. #give the share to the receiver
  160. self.env['share.line'].create({'share_number':self.quantity,
  161. 'partner_id':self.partner_id_to.id,
  162. 'share_product_id':self.share_product_id.id,
  163. 'share_unit_price':self.share_unit_price,
  164. 'effective_date':effective_date})
  165. else:
  166. raise ValidationError(_("This operation is not yet implemented."))
  167. sequence_operation = self.env['ir.sequence'].search([('name','=','Register Operation')])[0]
  168. sub_reg_operation = sequence_operation.next_by_id()
  169. values = {'name':sub_reg_operation,'register_number_operation':int(sub_reg_operation),
  170. 'partner_id':self.partner_id.id, 'quantity':self.quantity,
  171. 'share_product_id':self.share_product_id.id, 'type':self.operation_type,
  172. 'share_unit_price': self.share_unit_price, 'date':effective_date,
  173. }
  174. self.write({'state':'done'})
  175. email_template_obj = self.env['mail.template']
  176. if self.operation_type == 'transfer':
  177. values['partner_id_to'] = self.partner_id_to.id
  178. certificat_email_template = email_template_obj.search([('name', '=', "Share transfer - Send By Email")])[0]
  179. certificat_email_template.send_mail(self.partner_id_to.id, False)
  180. self.env['subscription.register'].create(values)
  181. certificat_email_template = email_template_obj.search([('name', '=', "Share update - Send By Email")])[0]
  182. certificat_email_template.send_mail(self.partner_id.id, False)