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.

389 lines
20 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  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. import openerp.addons.decimal_precision as dp
  7. _REQUIRED = ['email','firstname','lastname','birthdate','address','share_product_id','ordered_parts','zip_code','city','iban','no_registre','gender'] # Could be improved including required from model
  8. @api.model
  9. def _lang_get(self):
  10. languages = self.env['res.lang'].search([])
  11. return [(language.code, language.name) for language in languages]
  12. class subscription_request(models.Model):
  13. _name = 'subscription.request'
  14. _description = 'Subscription Request'
  15. def get_required_field(self):
  16. return _REQUIRED
  17. @api.model
  18. def create(self,vals):
  19. if not vals.get('partner_id'):
  20. cooperator = False
  21. if vals.get('no_registre'):
  22. cooperator = self.env['res.partner'].get_cooperator_from_nin(vals.get('no_registre'))
  23. if cooperator:
  24. # TODO remove the following line of code once it has
  25. # been founded a way to avoid dubble entry
  26. cooperator = cooperator[0]
  27. if cooperator.member:
  28. vals['type'] = 'increase'
  29. vals['already_cooperator'] = True
  30. else:
  31. vals['type'] = 'subscription'
  32. vals['partner_id'] = cooperator.id
  33. if not cooperator.cooperator:
  34. cooperator.write({'cooperator':True})
  35. subscr_request = super(subscription_request, self).create(vals)
  36. mail_template_obj = self.env['mail.template']
  37. confirmation_mail_template = mail_template_obj.search([('name', '=', 'Confirmation Email')])[0]
  38. confirmation_mail_template.send_mail(subscr_request.id)
  39. return subscr_request
  40. @api.model
  41. def create_comp_sub_req(self, vals):
  42. if not vals.get('partner_id'):
  43. cooperator = self.env['res.partner'].get_cooperator_from_crn(vals.get('company_register_number'))
  44. if cooperator:
  45. vals['partner_id'] = cooperator.id
  46. vals['type'] = 'increase'
  47. vals['already_cooperator'] = True
  48. subscr_request = super(subscription_request, self).create(vals)
  49. mail_template_obj = self.env['mail.template']
  50. confirmation_mail_template = mail_template_obj.search([('name', '=', 'Company Confirmation Email')])[0]
  51. confirmation_mail_template.send_mail(subscr_request.id, True)
  52. return subscr_request
  53. def check_belgian_identification_id(self, nat_register_num):
  54. if not self.check_empty_string(nat_register_num):
  55. return False
  56. if len(nat_register_num) != 11:
  57. return False
  58. if not nat_register_num.isdigit():
  59. return False
  60. birthday_number = nat_register_num[0:9]
  61. controle = nat_register_num[9:11]
  62. check_controle = 97 - (int(birthday_number) % 97)
  63. if int(check_controle) != int(controle):
  64. check_controle = 97 - ((2000000000 + int(birthday_number)) % 97)
  65. if int(check_controle) != int(controle):
  66. return False
  67. return True
  68. def check_empty_string(self, value):
  69. if value == None or value == False or value == '':
  70. return False
  71. return True
  72. @api.multi
  73. @api.depends('iban', 'no_registre','skip_control_ng')
  74. def _validated_lines(self):
  75. for sub_request in self:
  76. try:
  77. base_iban.validate_iban(sub_request.iban)
  78. sub_request.validated = True
  79. except ValidationError:
  80. sub_request.validated = False
  81. if not sub_request.is_company and (sub_request.skip_control_ng or self.check_belgian_identification_id(sub_request.no_registre)):
  82. sub_request.validated = True
  83. @api.multi
  84. @api.depends('share_product_id', 'share_product_id.list_price','ordered_parts')
  85. def _compute_subscription_amount(self):
  86. for sub_request in self:
  87. sub_request.subscription_amount = sub_request.share_product_id.list_price * sub_request.ordered_parts
  88. already_cooperator = fields.Boolean(string="I'm already cooperator")
  89. name = fields.Char(string='Name', required=True)
  90. firstname = fields.Char(string='Firstname')
  91. lastname = fields.Char(string='Lastname')
  92. birthdate = fields.Date(string="Birthdate")
  93. gender = fields.Selection([('male', _('Male')),
  94. ('female', _('Female')),
  95. ('other', _('Other'))], string='Gender')
  96. type = fields.Selection([('new','New Cooperator'),
  97. ('subscription','Subscription'),
  98. ('increase','Increase number of share')],
  99. string='Type', default="new")
  100. state = fields.Selection([('draft','Draft'),
  101. ('block','Blocked'),
  102. ('done','Done'),
  103. ('cancelled','Cancelled'),
  104. ('paid','paid')],
  105. string='State',required=True, default="draft")
  106. email = fields.Char(string='Email')
  107. iban = fields.Char(string='Account Number')
  108. partner_id = fields.Many2one('res.partner',string='Cooperator')
  109. share_product_id = fields.Many2one('product.product', string='Share type', domain=[('is_share','=',True)])
  110. share_short_name = fields.Char(related='share_product_id.short_name', string='Share type name')
  111. share_unit_price = fields.Float(related='share_product_id.list_price', string='Share price')
  112. subscription_amount = fields.Float(compute='_compute_subscription_amount', string='Subscription amount')
  113. ordered_parts = fields.Integer(string='Number of Share')
  114. address = fields.Char(string='Address')
  115. city = fields.Char(string='City')
  116. zip_code = fields.Char(string='Zip Code')
  117. country_id = fields.Many2one('res.country', string='Country', ondelete='restrict')
  118. phone = fields.Char(string='Phone')
  119. no_registre = fields.Char(string='National Register Number')
  120. user_id = fields.Many2one('res.users', string='Responsible', readonly=True)
  121. validated = fields.Boolean(compute='_validated_lines', string='Valid Line?', readonly=True)
  122. skip_control_ng = fields.Boolean(string="Skip control",
  123. help="if this field is checked then no control will be done on the national register number and on the iban bank account. To be done in case of the id card is from abroad or in case of a passport")
  124. lang = fields.Selection(_lang_get, 'Language', default='fr_BE',
  125. help="If the selected language is loaded in the system, all documents related to this contact will be printed in this language. If not, it will be English.")
  126. date = fields.Date(string='Subscription date request', default=lambda self: datetime.strftime(datetime.now(), '%Y-%m-%d'))
  127. company_id = fields.Many2one('res.company', string='Company', required=True,
  128. change_default=True, readonly=True,
  129. default=lambda self: self.env['res.company']._company_default_get())
  130. is_company = fields.Boolean(string='Is a company')
  131. is_operation = fields.Boolean(string='Is an operation')
  132. company_name = fields.Char(string="Company name")
  133. company_email = fields.Char(string="Company email")
  134. company_register_number = fields.Char(string='Company register number')
  135. company_type = fields.Selection([('scrl','SCRL'),
  136. ('asbl','ASBL'),
  137. ('sprl','SPRL'),
  138. ('sa','SA'),
  139. ('other','Other')])
  140. same_address = fields.Boolean(string='Same address')
  141. activities_address = fields.Char(string='Activities address')
  142. activities_city = fields.Char(string='Activities city')
  143. activities_zip_code = fields.Char(string='Activities zip Code')
  144. activities_country_id = fields.Many2one('res.country', string='Activities country', ondelete='restrict')
  145. contact_person_function = fields.Char(string='Function')
  146. operation_request_id = fields.Many2one('operation.request', string="Operation Request")
  147. is_operation = fields.Boolean(string="Is Operation request")
  148. capital_release_request = fields.One2many('account.invoice','subscription_request', string='Subscription request')
  149. capital_release_request_date = fields.Date(string="Force the capital release request date",
  150. help="Keep empty to use the current date", copy=False)
  151. source = fields.Selection([('website','Website'),
  152. ('crm','CRM'),
  153. ('manual','Manual')], string="Source", default="website")
  154. _order = "id desc"
  155. def _prepare_invoice_line(self, product, partner, qty):
  156. self.ensure_one()
  157. res = {}
  158. account = product.property_account_income_id or product.categ_id.property_account_income_categ_id
  159. if not account:
  160. raise UserError(_('Please define income account for this product: "%s" (id:%d) - or for its category: "%s".') % \
  161. (product.name, product.id, product.categ_id.name))
  162. fpos = partner.property_account_position_id
  163. if fpos:
  164. account = fpos.map_account(account)
  165. res = {
  166. 'name': product.name,
  167. 'account_id': account.id,
  168. 'price_unit': product.lst_price,
  169. 'quantity': qty,
  170. 'uom_id': product.uom_id.id,
  171. 'product_id': product.id or False,
  172. }
  173. return res
  174. def send_capital_release_request(self, invoice):
  175. invoice_email_template = self.env['mail.template'].search([('name', '=', 'Request to Release Capital - Send by Email')])[0]
  176. # we send the email with the capital release request in attachment
  177. invoice_email_template.send_mail(invoice.id, True)
  178. invoice.sent = True
  179. def create_invoice(self, partner):
  180. # get subscription journal
  181. journal = self.env['account.journal'].search([('code','=','SUBJ')])[0]
  182. # get the account for associate
  183. # TODO this should be defined in configuration
  184. if self.company_id.property_cooperator_account:
  185. account = self.company_id.property_cooperator_account
  186. else:
  187. account = self.env['account.account'].search([('code','=','416000')])[0]
  188. # creating invoice and invoice lines
  189. invoice_vals = {'partner_id':partner.id,
  190. 'journal_id':journal.id,'account_id':account.id,
  191. 'type': 'out_invoice', 'release_capital_request':True,
  192. 'subscription_request':self.id}
  193. if self.capital_release_request_date:
  194. invoice_vals['date_invoice'] = self.capital_release_request_date
  195. invoice = self.env['account.invoice'].create(invoice_vals)
  196. vals = self._prepare_invoice_line(self.share_product_id, partner, self.ordered_parts)
  197. vals['invoice_id'] = invoice.id
  198. line = self.env['account.invoice.line'].create(vals)
  199. # validate the capital release request
  200. invoice.signal_workflow('invoice_open')
  201. self.send_capital_release_request(invoice)
  202. return invoice
  203. def get_partner_company_vals(self):
  204. # this should go to the many2many tag field
  205. #'title':'company',
  206. #self.env['res.partner.title'].search([('shortcut','=',self.company_type)])
  207. partner_vals = {'name':self.company_name, 'is_company': self.is_company,
  208. 'company_register_number':self.company_register_number, 'customer':False,
  209. 'cooperator':True, 'street':self.address, 'zip':self.zip_code,
  210. 'city': self.city,'email':self.email, 'out_inv_comm_type':'bba','customer': share_product_id.customer,
  211. 'out_inv_comm_algorithm':'random', 'country_id': self.country_id.id, 'lang':self.lang}
  212. return partner_vals
  213. def get_partner_vals(self):
  214. partner_vals = {'name':self.name, 'first_name':self.firstname, 'last_name': self.lastname,
  215. 'customer':False, 'gender':self.gender,'cooperator':True, 'street':self.address,'zip':self.zip_code,
  216. 'city': self.city, 'phone': self.phone, 'email':self.email,
  217. 'national_register_number':self.no_registre, 'out_inv_comm_type':'bba',
  218. 'out_inv_comm_algorithm':'random', 'country_id': self.country_id.id,
  219. 'lang':self.lang, 'birthdate':self.birthdate, 'customer': share_product_id.customer}
  220. return partner_vals
  221. def create_coop_partner(self):
  222. partner_obj = self.env['res.partner']
  223. if self.is_company:
  224. partner_vals = self.get_partner_company_vals()
  225. else:
  226. partner_vals = self.get_partner_vals()
  227. partner = partner_obj.create(partner_vals)
  228. if self.iban :
  229. self.env['res.partner.bank'].create({'partner_id':partner.id,'acc_number':self.iban})
  230. return partner
  231. def create_user(self, partner):
  232. user_obj = self.env['res.users']
  233. email = self.email
  234. if self.is_company:
  235. email = self.company_email
  236. user = user_obj.search([('login','=',email)])
  237. if not user:
  238. user_values = {'partner_id': partner.id,'login':email}
  239. user_id = user_obj.sudo()._signup_create_user(user_values)
  240. user = user_obj.browse(user_id)
  241. user.sudo().with_context({'create_user': True}).action_reset_password()
  242. return True
  243. @api.one
  244. def validate_subscription_request(self):
  245. partner_obj = self.env['res.partner']
  246. if self.partner_id:
  247. if not self.partner_id.cooperator:
  248. self.partner_id.cooperator = True
  249. partner = self.partner_id
  250. else:
  251. if self.already_cooperator:
  252. raise UserError(_('The checkbox already cooperator is checked please select a cooperator.'))
  253. elif self.is_company:
  254. partner = partner_obj.search([('company_register_number','=',self.company_register_number)])
  255. elif self.no_registre:
  256. partner = partner_obj.search([('national_register_number','=',self.no_registre)])
  257. else:
  258. partner = None
  259. if not partner:
  260. partner = self.create_coop_partner()
  261. else:
  262. partner = partner[0]
  263. if self.is_company and not partner.has_representative():
  264. contact = partner_obj.search([('national_register_number','=',self.no_registre)])
  265. if not contact:
  266. contact_vals = {'name':self.name, 'first_name':self.firstname, 'last_name': self.lastname,
  267. 'customer':False, 'is_company':False, 'cooperator':True,
  268. 'street':self.address,'zip':self.zip_code,'gender':self.gender,
  269. 'city': self.city, 'phone': self.phone, 'email':self.email,
  270. 'national_register_number':self.no_registre, 'out_inv_comm_type':'bba',
  271. 'out_inv_comm_algorithm':'random', 'country_id': self.country_id.id,
  272. 'lang':self.lang, 'birthdate_date':self.birthdate, 'parent_id': partner.id,
  273. 'function':self.contact_person_function,'representative':True}
  274. contact = partner_obj.create(contact_vals)
  275. else:
  276. if len(contact) > 1:
  277. raise UserError(_('There is two different persons with the same national register number. Please proceed to a merge before to continue'))
  278. if contact.parent_id and contact.parent_id.id != partner.id:
  279. raise UserError(_('This contact person is already defined for another company. Please select another contact'))
  280. else:
  281. contact.parent_id = partner.id
  282. invoice = self.create_invoice(partner)
  283. self.write({'partner_id':partner.id, 'state':'done'})
  284. self.create_user(partner)
  285. return invoice
  286. @api.one
  287. def block_subscription_request(self):
  288. self.write({'state':'block'})
  289. @api.one
  290. def unblock_subscription_request(self):
  291. self.write({'state':'draft'})
  292. @api.one
  293. def cancel_subscription_request(self):
  294. self.write({'state':'cancelled'})
  295. class share_line(models.Model):
  296. _name='share.line'
  297. @api.multi
  298. def _compute_total_line(self):
  299. res = {}
  300. for line in self:
  301. line.total_amount_line = line.share_unit_price * line.share_number
  302. return res
  303. share_product_id = fields.Many2one('product.product', string='Share type', required=True, readonly=True)
  304. share_number = fields.Integer(string='Number of Share', required=True, readonly=True)
  305. share_short_name = fields.Char(related='share_product_id.short_name', string='Share type name')
  306. share_unit_price = fields.Float(string='Share price', readonly=True)
  307. effective_date = fields.Date(string='Effective Date', readonly=True)
  308. partner_id = fields.Many2one('res.partner',string='Cooperator', required=True, ondelete='cascade', readonly=True)
  309. total_amount_line = fields.Float(compute='_compute_total_line', string='Total amount line')
  310. class subscription_register(models.Model):
  311. _name= 'subscription.register'
  312. @api.multi
  313. def _compute_total_line(self):
  314. res = {}
  315. for register_line in self:
  316. register_line.total_amount_line = register_line.share_unit_price * register_line.quantity
  317. name = fields.Char(string='Register Number Operation', required=True, readonly=True)
  318. register_number_operation = fields.Integer(string='Register Number Operation', required=True, readonly=True)
  319. partner_id = fields.Many2one('res.partner',string='Cooperator', required=True, readonly=True)
  320. partner_id_to = fields.Many2one('res.partner',string='Transfered to', readonly=True)
  321. date = fields.Date(string='Subscription Date', required= True, readonly=True)
  322. quantity = fields.Integer(string='Number of share', readonly=True)
  323. share_unit_price = fields.Float(string='Share price', readonly=True)
  324. total_amount_line = fields.Float(compute='_compute_total_line', string='Total amount line')
  325. share_product_id = fields.Many2one('product.product', string='Share type', required=True, readonly=True, domain=[('is_share','=',True)])
  326. share_short_name = fields.Char(related='share_product_id.short_name', string='Share type name', readonly=True)
  327. type = fields.Selection([('subscription','Subscription'),
  328. ('transfer','Transfer'),
  329. ('sell_back','Sell Back'),
  330. ('convert','Conversion')],
  331. string='Operation Type', readonly=True)
  332. company_id = fields.Many2one('res.company', string='Company', required=True,
  333. change_default=True, readonly=True,
  334. default=lambda self: self.env['res.company']._company_default_get())
  335. user_id = fields.Many2one('res.users', string='Responsible', readonly=True, default=lambda self: self.env.user)
  336. _order = "register_number_operation asc"