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.

384 lines
16 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. return values
  146. def get_products_share(self, is_company):
  147. product_obj = request.env['product.template']
  148. products = product_obj.sudo().get_web_share_products(is_company)
  149. return products
  150. def get_countries(self):
  151. countries = request.env['res.country'].sudo().search([])
  152. return countries
  153. def get_langs(self):
  154. langs = request.env['res.lang'].sudo().search([])
  155. return langs
  156. def get_selected_share(self, kwargs):
  157. prod_obj = request.env['product.template']
  158. product_id = kwargs.get("share_product_id")
  159. return prod_obj.sudo().browse(int(product_id)).product_variant_ids[0]
  160. def validation(self, kwargs, logged, values, post_file):
  161. user_obj = request.env['res.users']
  162. sub_req_obj = request.env['subscription.request']
  163. redirect = "easy_my_coop.becomecooperator"
  164. email = kwargs.get('email')
  165. is_company = kwargs.get("is_company") == 'on'
  166. if is_company:
  167. is_company = True
  168. redirect = "easy_my_coop.becomecompanycooperator"
  169. email = kwargs.get('company_email')
  170. if ('g-recaptcha-response' not in kwargs
  171. or not request.website.is_captcha_valid(
  172. kwargs['g-recaptcha-response'])):
  173. values = self.fill_values(values, is_company, logged)
  174. values["error_msg"] = _("the captcha has not been validated,"
  175. " please fill in the captcha")
  176. return request.website.render(redirect, values)
  177. # Check that required field from model subscription_request exists
  178. required_fields = sub_req_obj.sudo().get_required_field()
  179. error = set(field for field in required_fields if not values.get(field)) #noqa
  180. if error:
  181. values = self.fill_values(values, is_company, logged)
  182. values["error_msg"] = _("Some mandatory fields have not "
  183. "been filled")
  184. values = dict(values, error=error, kwargs=kwargs.items())
  185. return request.website.render(redirect, values)
  186. if not logged and email:
  187. user = user_obj.sudo().search([('login', '=', email)])
  188. if user:
  189. values = self.fill_values(values, is_company, logged)
  190. values.update(kwargs)
  191. values["error_msg"] = _("There is an existing account for this"
  192. " mail address. Please login before "
  193. "fill in the form")
  194. return request.website.render(redirect, values)
  195. company = request.website.company_id
  196. if company.allow_id_card_upload:
  197. if not post_file:
  198. values = self.fill_values(values, is_company, logged)
  199. values.update(kwargs)
  200. values["error_msg"] = _("You need to upload a"
  201. " scan of your id card")
  202. return request.website.render(redirect, values)
  203. iban = kwargs.get("iban")
  204. valid = sub_req_obj.check_iban(iban)
  205. if not valid:
  206. values = self.fill_values(values, is_company, logged)
  207. values["error_msg"] = _("You iban account number"
  208. "is not valid")
  209. return request.website.render(redirect, values)
  210. if not is_company and 'no_registre' in required_fields:
  211. no_registre = re.sub('[^0-9a-zA-Z]+', '',
  212. kwargs.get("no_registre"))
  213. valid = sub_req_obj.check_belgian_identification_id(no_registre)
  214. if not valid:
  215. values = self.fill_values(values, is_company, logged)
  216. values["error_msg"] = _("You national register number "
  217. "is not valid")
  218. return request.website.render(redirect, values)
  219. values["no_registre"] = no_registre
  220. # check the subscription's amount
  221. max_amount = company.subscription_maximum_amount
  222. if logged:
  223. partner = request.env.user.partner_id
  224. if partner.member:
  225. max_amount = max_amount - partner.total_value
  226. if company.unmix_share_type:
  227. share = self.get_selected_share(kwargs)
  228. if int(partner.cooperator_type) != share.id:
  229. values = self.fill_values(values, is_company, logged)
  230. values["error_msg"] = (_("You can't subscribe two "
  231. "different types of share"))
  232. return request.website.render(redirect, values)
  233. total_amount = float(kwargs.get('total_parts'))
  234. if max_amount > 0 and total_amount > max_amount:
  235. values = self.fill_values(values, is_company, logged)
  236. values["error_msg"] = (_("You can't subscribe for an amount that "
  237. "exceed ")
  238. + str(max_amount)
  239. + company.currency_id.symbol)
  240. return request.website.render(redirect, values)
  241. return True
  242. @http.route(['/subscription/get_share_product'],
  243. type='json',
  244. auth="public",
  245. methods=['POST'], website=True)
  246. def get_share_product(self, share_product_id, **kw):
  247. product_template = request.env['product.template']
  248. product = product_template.sudo().browse(int(share_product_id))
  249. return {
  250. product.id: {
  251. 'list_price': product.list_price,
  252. 'min_qty': product.minimum_quantity,
  253. 'force_min_qty': product.force_min_qty
  254. }
  255. }
  256. @http.route(['/subscription/subscribe_share'],
  257. type='http',
  258. auth="public", website=True)
  259. def share_subscription(self, **kwargs):
  260. sub_req_obj = request.env['subscription.request']
  261. attach_obj = request.env['ir.attachment']
  262. required_fields = sub_req_obj.sudo().get_required_field()
  263. # List of file to add to ir_attachment once we have the ID
  264. post_file = []
  265. # Info to add after the message
  266. post_description = []
  267. values = {}
  268. for field_name, field_value in kwargs.items():
  269. if hasattr(field_value, 'filename'):
  270. post_file.append(field_value)
  271. elif (field_name in sub_req_obj._fields
  272. and field_name not in _BLACKLIST):
  273. values[field_name] = field_value
  274. # allow to add some free fields or blacklisted field like ID
  275. elif field_name not in _TECHNICAL:
  276. post_description.append("%s: %s" % (field_name, field_value))
  277. logged = kwargs.get("logged") == 'on'
  278. is_company = kwargs.get("is_company") == 'on'
  279. response = self.validation(kwargs, logged, values, post_file)
  280. if response is not True:
  281. return response
  282. already_coop = False
  283. if logged:
  284. partner = request.env.user.partner_id
  285. values['partner_id'] = partner.id
  286. already_coop = partner.member
  287. elif kwargs.get("already_cooperator") == 'on':
  288. already_coop = True
  289. values["already_cooperator"] = already_coop
  290. values["is_company"] = is_company
  291. if kwargs.get('data_policy_approved', 'off') == 'on':
  292. values['data_policy_approved'] = True
  293. lastname = kwargs.get("lastname").upper()
  294. firstname = kwargs.get("firstname").title()
  295. values["name"] = firstname + " " + lastname
  296. values["lastname"] = lastname
  297. values["firstname"] = firstname
  298. values["birthdate"] = datetime.strptime(kwargs.get("birthdate"),
  299. "%d/%m/%Y").date()
  300. values["source"] = "website"
  301. values["share_product_id"] = self.get_selected_share(kwargs).id
  302. if is_company:
  303. if kwargs.get("company_register_number", is_company):
  304. values["company_register_number"] = re.sub('[^0-9a-zA-Z]+',
  305. '',
  306. kwargs.get("company_register_number"))
  307. subscription_id = sub_req_obj.sudo().create_comp_sub_req(values)
  308. else:
  309. if 'no_registre' in required_fields:
  310. no_registre = re.sub('[^0-9a-zA-Z]+', '',
  311. kwargs.get("no_registre"))
  312. values["no_registre"] = no_registre
  313. subscription_id = sub_req_obj.sudo().create(values)
  314. if subscription_id:
  315. for field_value in post_file:
  316. attachment_value = {
  317. 'name': field_value.filename,
  318. 'res_name': field_value.filename,
  319. 'res_model': 'subscription.request',
  320. 'res_id': subscription_id,
  321. 'datas': base64.encodestring(field_value.read()),
  322. 'datas_fname': field_value.filename,
  323. }
  324. attach_obj.sudo().create(attachment_value)
  325. return self.get_subscription_response(values, kwargs)