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.

430 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. certificat_email_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. certificat_email_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. ('transfer','Transfer'),
  115. ('cancelled','Cancelled'),
  116. ('paid','paid')],
  117. string='State',required=True, default="draft")
  118. email = fields.Char(string='Email')
  119. iban = fields.Char(string='Account Number')
  120. partner_id = fields.Many2one('res.partner',string='Cooperator')
  121. share_product_id = fields.Many2one('product.product', string='Share type', domain=[('is_share','=',True)])
  122. share_short_name = fields.Char(related='share_product_id.short_name', string='Share type name')
  123. share_unit_price = fields.Float(related='share_product_id.list_price', string='Share price')
  124. subscription_amount = fields.Float(compute='_compute_subscription_amount', string='Subscription amount')
  125. ordered_parts = fields.Integer(string='Number of Share')
  126. address = fields.Char(string='Address')
  127. city = fields.Char(string='City')
  128. zip_code = fields.Char(string='Zip Code')
  129. country_id = fields.Many2one('res.country', string='Country', ondelete='restrict')
  130. phone = fields.Char(string='Phone')
  131. no_registre = fields.Char(string='National Register Number')
  132. user_id = fields.Many2one('res.users', string='Responsible', readonly=True)
  133. validated = fields.Boolean(compute='_validated_lines', string='Valid Line?', readonly=True)
  134. skip_control_ng = fields.Boolean(string="Skip control",
  135. 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")
  136. lang = fields.Selection(_lang_get, 'Language', default=lambda self: self.env['res.company']._company_default_get().default_lang_id.code,
  137. 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.")
  138. date = fields.Date(string='Subscription date request', default=lambda self: datetime.strftime(datetime.now(), '%Y-%m-%d'))
  139. company_id = fields.Many2one('res.company', string='Company', required=True,
  140. change_default=True, readonly=True,
  141. default=lambda self: self.env['res.company']._company_default_get())
  142. is_company = fields.Boolean(string='Is a company')
  143. is_operation = fields.Boolean(string='Is an operation')
  144. company_name = fields.Char(string="Company name")
  145. company_email = fields.Char(string="Company email")
  146. company_register_number = fields.Char(string='Company register number')
  147. company_type = fields.Selection([('scrl','SCRL'),
  148. ('asbl','ASBL'),
  149. ('sprl','SPRL'),
  150. ('sa','SA'),
  151. ('other','Other')])
  152. same_address = fields.Boolean(string='Same address')
  153. activities_address = fields.Char(string='Activities address')
  154. activities_city = fields.Char(string='Activities city')
  155. activities_zip_code = fields.Char(string='Activities zip Code')
  156. activities_country_id = fields.Many2one('res.country', string='Activities country', ondelete='restrict')
  157. contact_person_function = fields.Char(string='Function')
  158. operation_request_id = fields.Many2one('operation.request', string="Operation Request")
  159. is_operation = fields.Boolean(string="Is Operation request")
  160. capital_release_request = fields.One2many('account.invoice','subscription_request', string='Subscription request')
  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. class share_line(models.Model):
  318. _name='share.line'
  319. @api.multi
  320. def _compute_total_line(self):
  321. res = {}
  322. for line in self:
  323. line.total_amount_line = line.share_unit_price * line.share_number
  324. return res
  325. share_product_id = fields.Many2one('product.product', string='Share type', required=True, readonly=True)
  326. share_number = fields.Integer(string='Number of Share', required=True, readonly=True)
  327. share_short_name = fields.Char(related='share_product_id.short_name', string='Share type name')
  328. share_unit_price = fields.Float(string='Share price', readonly=True)
  329. effective_date = fields.Date(string='Effective Date', readonly=True)
  330. partner_id = fields.Many2one('res.partner',string='Cooperator', required=True, ondelete='cascade', readonly=True)
  331. total_amount_line = fields.Float(compute='_compute_total_line', string='Total amount line')
  332. class subscription_register(models.Model):
  333. _name= 'subscription.register'
  334. @api.multi
  335. def _compute_total_line(self):
  336. res = {}
  337. for register_line in self:
  338. register_line.total_amount_line = register_line.share_unit_price * register_line.quantity
  339. name = fields.Char(string='Register Number Operation', required=True, readonly=True)
  340. register_number_operation = fields.Integer(string='Register Number Operation', required=True, readonly=True)
  341. partner_id = fields.Many2one('res.partner',string='Cooperator', required=True, readonly=True)
  342. partner_id_to = fields.Many2one('res.partner',string='Transfered to', readonly=True)
  343. date = fields.Date(string='Subscription Date', required= True, readonly=True)
  344. quantity = fields.Integer(string='Number of share', readonly=True)
  345. share_unit_price = fields.Float(string='Share price', readonly=True)
  346. total_amount_line = fields.Float(compute='_compute_total_line', string='Total amount line')
  347. share_product_id = fields.Many2one('product.product', string='Share type', required=True, readonly=True, domain=[('is_share','=',True)])
  348. share_short_name = fields.Char(related='share_product_id.short_name', string='Share type name', readonly=True)
  349. share_to_product_id = fields.Many2one('product.product', string='Share to type', readonly=True, domain=[('is_share','=',True)])
  350. share_to_short_name = fields.Char(related='share_to_product_id.short_name', string='Share to type name', readonly=True)
  351. quantity_to = fields.Integer(string='Number of share to', readonly=True)
  352. share_to_unit_price = fields.Float(string='Share to price', readonly=True)
  353. type = fields.Selection([('subscription','Subscription'),
  354. ('transfer','Transfer'),
  355. ('sell_back','Sell Back'),
  356. ('convert','Conversion')],
  357. string='Operation Type', readonly=True)
  358. company_id = fields.Many2one('res.company', string='Company', required=True,
  359. change_default=True, readonly=True,
  360. default=lambda self: self.env['res.company']._company_default_get())
  361. user_id = fields.Many2one('res.users', string='Responsible', readonly=True, default=lambda self: self.env.user)
  362. _order = "register_number_operation asc"
  363. @api.model
  364. def read_group(self, domain, fields, groupby, offset=0, limit=None, orderby=False, lazy=True):
  365. if 'share_unit_price' in fields:
  366. fields.remove('share_unit_price')
  367. if 'register_number_operation' in fields:
  368. fields.remove('register_number_operation')
  369. res = super(subscription_register, self).read_group(domain, fields, groupby, offset=offset, limit=limit, orderby=orderby, lazy=lazy)
  370. if 'total_amount_line' in fields:
  371. for line in res:
  372. if '__domain' in line:
  373. lines = self.search(line['__domain'])
  374. inv_value = 0.0
  375. for line2 in lines:
  376. inv_value += line2.total_amount_line
  377. line['total_amount_line'] = inv_value
  378. return res