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.

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