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.

397 lines
17 KiB

6 years ago
  1. # -*- coding: utf-8 -*-
  2. import base64
  3. from datetime import datetime
  4. import re
  5. from openerp import http
  6. from openerp.http import request
  7. from openerp.tools.translate import _
  8. # Only use for behavior, don't stock it
  9. _TECHNICAL = ['view_from', 'view_callback']
  10. # Allow in description
  11. _BLACKLIST = ['id', 'create_uid', 'create_date', 'write_uid', 'write_date',
  12. 'user_id', 'active']
  13. _COOP_FORM_FIELD = ['email', 'firstname', 'lastname', 'birthdate', 'iban',
  14. 'share_product_id', 'no_registre', 'address', 'city',
  15. 'zip_code', 'country_id', 'phone', 'lang', 'nb_parts',
  16. 'total_parts', 'error_msg']
  17. _COMPANY_FORM_FIELD = ['is_company', 'company_register_number', 'company_name',
  18. 'company_email', 'company_type', 'email', 'firstname',
  19. 'lastname', 'birthdate', 'iban', 'share_product_id',
  20. 'no_registre', 'address', 'city', 'zip_code',
  21. 'country_id', 'phone', 'lang', 'nb_parts',
  22. 'total_parts', 'error_msg']
  23. class WebsiteSubscription(http.Controller):
  24. @http.route(['/page/become_cooperator',
  25. '/become_cooperator'],
  26. type='http', auth="public", website=True)
  27. def display_become_cooperator_page(self, **kwargs):
  28. values = {}
  29. logged = False
  30. if request.env.user.login != 'public':
  31. logged = True
  32. partner = request.env.user.partner_id
  33. if partner.is_company:
  34. return request.website.render("easy_my_coop.becomecompanycooperator", values)
  35. values = self.fill_values(values, False, logged, True)
  36. for field in _COOP_FORM_FIELD:
  37. if kwargs.get(field):
  38. values[field] = kwargs.pop(field)
  39. values.update(kwargs=kwargs.items())
  40. return request.website.render("easy_my_coop.becomecooperator", values)
  41. @http.route(['/page/become_company_cooperator',
  42. '/become_company_cooperator'],
  43. type='http', auth="public", website=True)
  44. def display_become_company_cooperator_page(self, **kwargs):
  45. values = {}
  46. logged = False
  47. if request.env.user.login != 'public':
  48. logged = True
  49. values = self.fill_values(values, True, logged, True)
  50. for field in _COMPANY_FORM_FIELD:
  51. if kwargs.get(field):
  52. values[field] = kwargs.pop(field)
  53. values.update(kwargs=kwargs.items())
  54. return request.website.render("easy_my_coop.becomecompanycooperator", values)
  55. def preRenderThanks(self, values, kwargs):
  56. """ Allow to be overrided """
  57. return {
  58. '_values': values,
  59. '_kwargs': kwargs,
  60. }
  61. def get_subscription_response(self, values, kwargs):
  62. values = self.preRenderThanks(values, kwargs)
  63. return request.website.render("easy_my_coop.cooperator_thanks", values)
  64. def get_date_string(self, birthdate):
  65. if birthdate:
  66. birthdate = datetime.strptime(birthdate, "%Y-%m-%d")
  67. return datetime.strftime(birthdate, "%d/%m/%Y")
  68. return False
  69. def get_values_from_user(self, values, is_company):
  70. # the subscriber is connected
  71. if request.env.user.login != 'public':
  72. values['logged'] = 'on'
  73. partner = request.env.user.partner_id
  74. if partner.member or partner.old_member:
  75. values['already_cooperator'] = 'on'
  76. if partner.bank_ids:
  77. values['iban'] = partner.bank_ids[0].acc_number
  78. values['address'] = partner.street
  79. values['zip_code'] = partner.zip
  80. values['city'] = partner.city
  81. values['country_id'] = partner.country_id.id
  82. if is_company:
  83. # company values
  84. values['company_register_number'] = partner.company_register_number
  85. values['company_name'] = partner.name
  86. values['company_email'] = partner.email
  87. # contact person values
  88. representative = partner.get_representative()
  89. values['firstname'] = representative.firstname
  90. values['lastname'] = representative.lastname
  91. values['gender'] = representative.gender
  92. values['email'] = representative.email
  93. values['contact_person_function'] = representative.function
  94. values['no_registre'] = representative.national_register_number
  95. values['birthdate'] = self.get_date_string(representative.birthdate)
  96. values['lang'] = representative.lang
  97. values['phone'] = representative.phone
  98. else:
  99. values['firstname'] = partner.firstname
  100. values['lastname'] = partner.lastname
  101. values['email'] = partner.email
  102. values['gender'] = partner.gender
  103. values['no_registre'] = partner.national_register_number
  104. values['birthdate'] = self.get_date_string(partner.birthdate)
  105. values['lang'] = partner.lang
  106. values['phone'] = partner.phone
  107. return values
  108. def fill_values(self, values, is_company, logged, load_from_user=False):
  109. sub_req_obj = request.env['subscription.request']
  110. company = request.website.company_id
  111. products = self.get_products_share(is_company)
  112. if load_from_user:
  113. values = self.get_values_from_user(values, is_company)
  114. if is_company:
  115. values['is_company'] = 'on'
  116. if logged:
  117. values['logged'] = 'on'
  118. values['countries'] = self.get_countries()
  119. values['langs'] = self.get_langs()
  120. values['products'] = products
  121. fields_desc = sub_req_obj.sudo().fields_get(['company_type', 'gender'])
  122. values['company_types'] = fields_desc['company_type']['selection']
  123. values['genders'] = fields_desc['gender']['selection']
  124. values['company'] = company
  125. if not values.get('share_product_id'):
  126. for product in products:
  127. if product.default_share_product is True:
  128. values['share_product_id'] = product.id
  129. break
  130. if not values.get('share_product_id', False) and products:
  131. values['share_product_id'] = products[0].id
  132. if not values.get('country_id'):
  133. if company.default_country_id:
  134. values['country_id'] = company.default_country_id.id
  135. else:
  136. values['country_id'] = '21'
  137. if not values.get('activities_country_id'):
  138. if company.default_country_id:
  139. values['activities_country_id'] = company.default_country_id.id
  140. else:
  141. values['activities_country_id'] = '21'
  142. if not values.get('lang'):
  143. if company.default_lang_id:
  144. values['lang'] = company.default_lang_id.code
  145. comp = request.env['res.company']._company_default_get()
  146. values.update({
  147. 'display_data_policy': comp.display_data_policy_approval,
  148. 'data_policy_required': comp.data_policy_approval_required,
  149. 'data_policy_text': comp.data_policy_approval_text,
  150. 'display_internal_rules': comp.display_internal_rules_approval,
  151. 'internal_rules_required': comp.internal_rules_approval_required,
  152. 'internal_rules_text': comp.internal_rules_approval_text,
  153. })
  154. return values
  155. def get_products_share(self, is_company):
  156. product_obj = request.env['product.template']
  157. products = product_obj.sudo().get_web_share_products(is_company)
  158. return products
  159. def get_countries(self):
  160. countries = request.env['res.country'].sudo().search([])
  161. return countries
  162. def get_langs(self):
  163. langs = request.env['res.lang'].sudo().search([])
  164. return langs
  165. def get_selected_share(self, kwargs):
  166. prod_obj = request.env['product.template']
  167. product_id = kwargs.get("share_product_id")
  168. return prod_obj.sudo().browse(int(product_id)).product_variant_ids[0]
  169. def validation(self, kwargs, logged, values, post_file):
  170. user_obj = request.env['res.users']
  171. sub_req_obj = request.env['subscription.request']
  172. redirect = "easy_my_coop.becomecooperator"
  173. email = kwargs.get('email')
  174. is_company = kwargs.get("is_company") == 'on'
  175. if is_company:
  176. is_company = True
  177. redirect = "easy_my_coop.becomecompanycooperator"
  178. email = kwargs.get('company_email')
  179. if ('g-recaptcha-response' not in kwargs
  180. or not request.website.is_captcha_valid(
  181. kwargs['g-recaptcha-response'])):
  182. values = self.fill_values(values, is_company, logged)
  183. values["error_msg"] = _("the captcha has not been validated,"
  184. " please fill in the captcha")
  185. return request.website.render(redirect, values)
  186. # Check that required field from model subscription_request exists
  187. required_fields = sub_req_obj.sudo().get_required_field()
  188. error = set(field for field in required_fields if not values.get(field)) #noqa
  189. if error:
  190. values = self.fill_values(values, is_company, logged)
  191. values["error_msg"] = _("Some mandatory fields have not "
  192. "been filled")
  193. values = dict(values, error=error, kwargs=kwargs.items())
  194. return request.website.render(redirect, values)
  195. if not logged and email:
  196. user = user_obj.sudo().search([('login', '=', email)])
  197. if user:
  198. values = self.fill_values(values, is_company, logged)
  199. values.update(kwargs)
  200. values["error_msg"] = _("There is an existing account for this"
  201. " mail address. Please login before "
  202. "fill in the form")
  203. return request.website.render(redirect, values)
  204. company = request.website.company_id
  205. if company.allow_id_card_upload:
  206. if not post_file:
  207. values = self.fill_values(values, is_company, logged)
  208. values.update(kwargs)
  209. values["error_msg"] = _("You need to upload a"
  210. " scan of your id card")
  211. return request.website.render(redirect, values)
  212. iban = kwargs.get("iban")
  213. valid = sub_req_obj.check_iban(iban)
  214. if not valid:
  215. values = self.fill_values(values, is_company, logged)
  216. values["error_msg"] = _("You iban account number"
  217. "is not valid")
  218. return request.website.render(redirect, values)
  219. if not is_company and 'no_registre' in required_fields:
  220. no_registre = re.sub('[^0-9a-zA-Z]+', '',
  221. kwargs.get("no_registre"))
  222. valid = sub_req_obj.check_belgian_identification_id(no_registre)
  223. if not valid:
  224. values = self.fill_values(values, is_company, logged)
  225. values["error_msg"] = _("You national register number "
  226. "is not valid")
  227. return request.website.render(redirect, values)
  228. values["no_registre"] = no_registre
  229. # check the subscription's amount
  230. max_amount = company.subscription_maximum_amount
  231. if logged:
  232. partner = request.env.user.partner_id
  233. if partner.member:
  234. max_amount = max_amount - partner.total_value
  235. if company.unmix_share_type:
  236. share = self.get_selected_share(kwargs)
  237. if partner.cooperator_type != share.short_name:
  238. values = self.fill_values(values, is_company, logged)
  239. values["error_msg"] = (_("You can't subscribe two "
  240. "different types of share"))
  241. return request.website.render(redirect, values)
  242. total_amount = float(kwargs.get('total_parts'))
  243. if max_amount > 0 and total_amount > max_amount:
  244. values = self.fill_values(values, is_company, logged)
  245. values["error_msg"] = (_("You can't subscribe for an amount that "
  246. "exceed ")
  247. + str(max_amount)
  248. + company.currency_id.symbol)
  249. return request.website.render(redirect, values)
  250. return True
  251. @http.route(['/subscription/get_share_product'],
  252. type='json',
  253. auth="public",
  254. methods=['POST'], website=True)
  255. def get_share_product(self, share_product_id, **kw):
  256. product_template = request.env['product.template']
  257. product = product_template.sudo().browse(int(share_product_id))
  258. return {
  259. product.id: {
  260. 'list_price': product.list_price,
  261. 'min_qty': product.minimum_quantity,
  262. 'force_min_qty': product.force_min_qty
  263. }
  264. }
  265. @http.route(['/subscription/subscribe_share'],
  266. type='http',
  267. auth="public", website=True)
  268. def share_subscription(self, **kwargs):
  269. sub_req_obj = request.env['subscription.request']
  270. attach_obj = request.env['ir.attachment']
  271. required_fields = sub_req_obj.sudo().get_required_field()
  272. # List of file to add to ir_attachment once we have the ID
  273. post_file = []
  274. # Info to add after the message
  275. post_description = []
  276. values = {}
  277. for field_name, field_value in kwargs.items():
  278. if hasattr(field_value, 'filename'):
  279. post_file.append(field_value)
  280. elif (field_name in sub_req_obj._fields
  281. and field_name not in _BLACKLIST):
  282. values[field_name] = field_value
  283. # allow to add some free fields or blacklisted field like ID
  284. elif field_name not in _TECHNICAL:
  285. post_description.append("%s: %s" % (field_name, field_value))
  286. logged = kwargs.get("logged") == 'on'
  287. is_company = kwargs.get("is_company") == 'on'
  288. response = self.validation(kwargs, logged, values, post_file)
  289. if response is not True:
  290. return response
  291. already_coop = False
  292. if logged:
  293. partner = request.env.user.partner_id
  294. values['partner_id'] = partner.id
  295. already_coop = partner.member
  296. elif kwargs.get("already_cooperator") == 'on':
  297. already_coop = True
  298. values["already_cooperator"] = already_coop
  299. values["is_company"] = is_company
  300. if kwargs.get('data_policy_approved', 'off') == 'on':
  301. values['data_policy_approved'] = True
  302. if kwargs.get('internal_rules_approved', 'off') == 'on':
  303. values['internal_rules_approved'] = True
  304. lastname = kwargs.get("lastname").upper()
  305. firstname = kwargs.get("firstname").title()
  306. values["name"] = firstname + " " + lastname
  307. values["lastname"] = lastname
  308. values["firstname"] = firstname
  309. values["birthdate"] = datetime.strptime(kwargs.get("birthdate"),
  310. "%d/%m/%Y").date()
  311. values["source"] = "website"
  312. values["share_product_id"] = self.get_selected_share(kwargs).id
  313. if is_company:
  314. if kwargs.get("company_register_number", is_company):
  315. values["company_register_number"] = re.sub('[^0-9a-zA-Z]+',
  316. '',
  317. kwargs.get("company_register_number"))
  318. subscription_id = sub_req_obj.sudo().create_comp_sub_req(values)
  319. else:
  320. if 'no_registre' in required_fields:
  321. no_registre = re.sub('[^0-9a-zA-Z]+', '',
  322. kwargs.get("no_registre"))
  323. values["no_registre"] = no_registre
  324. subscription_id = sub_req_obj.sudo().create(values)
  325. if subscription_id:
  326. for field_value in post_file:
  327. attachment_value = {
  328. 'name': field_value.filename,
  329. 'res_name': field_value.filename,
  330. 'res_model': 'subscription.request',
  331. 'res_id': subscription_id,
  332. 'datas': base64.encodestring(field_value.read()),
  333. 'datas_fname': field_value.filename,
  334. }
  335. attach_obj.sudo().create(attachment_value)
  336. return self.get_subscription_response(values, kwargs)