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.

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