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.

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