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.

400 lines
20 KiB

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