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.

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