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.

411 lines
17 KiB

5 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', 'confirm_email', 'firstname', 'lastname',
  14. 'birthdate', 'iban', 'share_product_id', '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. '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 self.display_become_company_cooperator_page()
  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",
  55. values)
  56. def preRenderThanks(self, values, kwargs):
  57. """ Allow to be overrided """
  58. return {
  59. '_values': values,
  60. '_kwargs': kwargs,
  61. }
  62. def get_subscription_response(self, values, kwargs):
  63. values = self.preRenderThanks(values, kwargs)
  64. return request.website.render("easy_my_coop.cooperator_thanks", values)
  65. def get_date_string(self, birthdate):
  66. if birthdate:
  67. birthdate = datetime.strptime(birthdate, "%Y-%m-%d")
  68. return datetime.strftime(birthdate, "%d/%m/%Y")
  69. return False
  70. def get_values_from_user(self, values, is_company):
  71. # the subscriber is connected
  72. if request.env.user.login != 'public':
  73. values['logged'] = 'on'
  74. partner = request.env.user.partner_id
  75. if partner.member or partner.old_member:
  76. values['already_cooperator'] = 'on'
  77. if partner.bank_ids:
  78. values['iban'] = partner.bank_ids[0].acc_number
  79. values['address'] = partner.street
  80. values['zip_code'] = partner.zip
  81. values['city'] = partner.city
  82. values['country_id'] = partner.country_id.id
  83. if is_company:
  84. # company values
  85. values['company_register_number'] = partner.company_register_number
  86. values['company_name'] = partner.name
  87. values['company_email'] = partner.email
  88. values['company_type'] = partner.legal_form
  89. # contact person values
  90. representative = partner.get_representative()
  91. values['firstname'] = representative.firstname
  92. values['lastname'] = representative.lastname
  93. values['gender'] = representative.gender
  94. values['email'] = representative.email
  95. values['contact_person_function'] = representative.function
  96. values['birthdate'] = self.get_date_string(representative.birthdate)
  97. values['lang'] = representative.lang
  98. values['phone'] = representative.phone
  99. else:
  100. values['firstname'] = partner.firstname
  101. values['lastname'] = partner.lastname
  102. values['email'] = partner.email
  103. values['gender'] = partner.gender
  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_internal_rules': comp.display_internal_rules_approval,
  148. 'internal_rules_required': comp.internal_rules_approval_required,
  149. 'internal_rules_text': comp.internal_rules_approval_text,
  150. 'display_data_policy': comp.display_data_policy_approval,
  151. 'data_policy_required': comp.data_policy_approval_required,
  152. 'data_policy_text': comp.data_policy_approval_text,
  153. 'display_financial_risk': comp.display_financial_risk_approval,
  154. 'financial_risk_required': comp.financial_risk_approval_required,
  155. 'financial_risk_text': comp.financial_risk_approval_text,
  156. })
  157. return values
  158. def get_products_share(self, is_company):
  159. product_obj = request.env['product.template']
  160. products = product_obj.sudo().get_web_share_products(is_company)
  161. return products
  162. def get_countries(self):
  163. countries = request.env['res.country'].sudo().search([])
  164. return countries
  165. def get_langs(self):
  166. langs = request.env['res.lang'].sudo().search([])
  167. return langs
  168. def get_selected_share(self, kwargs):
  169. prod_obj = request.env['product.template']
  170. product_id = kwargs.get("share_product_id")
  171. return prod_obj.sudo().browse(int(product_id)).product_variant_ids[0]
  172. def remove_field_from_list(self, required_fields, field):
  173. if required_fields.count(field) > 0:
  174. required_fields.remove(field)
  175. return required_fields
  176. def validation(self, kwargs, logged, values, post_file):
  177. user_obj = request.env['res.users']
  178. sub_req_obj = request.env['subscription.request']
  179. redirect = "easy_my_coop.becomecooperator"
  180. email = kwargs.get('email')
  181. is_company = kwargs.get("is_company") == 'on'
  182. if is_company:
  183. is_company = True
  184. redirect = "easy_my_coop.becomecompanycooperator"
  185. email = kwargs.get('company_email')
  186. if ('g-recaptcha-response' not in kwargs
  187. or not request.website.is_captcha_valid(
  188. kwargs['g-recaptcha-response'])):
  189. values = self.fill_values(values, is_company, logged)
  190. values["error_msg"] = _("the captcha has not been validated,"
  191. " please fill in the captcha")
  192. return request.website.render(redirect, values)
  193. # Check that required field from model subscription_request exists
  194. required_fields = sub_req_obj.sudo().get_required_field()
  195. if logged:
  196. # these fields are readonly when logged
  197. # we want to ease the process if user was a subscriber
  198. self.remove_field_from_list(required_fields, 'iban')
  199. self.remove_field_from_list(required_fields, 'birthdate')
  200. error = set(field for field in required_fields if not values.get(field)) #noqa
  201. if error:
  202. values = self.fill_values(values, is_company, logged)
  203. values["error_msg"] = _("Some mandatory fields have not "
  204. "been filled")
  205. values = dict(values, error=error, kwargs=kwargs.items())
  206. return request.website.render(redirect, values)
  207. if not logged and email:
  208. user = user_obj.sudo().search([('login', '=', email)])
  209. if user:
  210. values = self.fill_values(values, is_company, logged)
  211. values.update(kwargs)
  212. values["error_msg"] = _("There is an existing account for this"
  213. " mail address. Please login before "
  214. "fill in the form")
  215. return request.website.render(redirect, values)
  216. else:
  217. confirm_email = kwargs.get('confirm_email')
  218. if email != confirm_email:
  219. values = self.fill_values(values, is_company, logged)
  220. values.update(kwargs)
  221. values["error_msg"] = _("The email and the confirmation "
  222. "email doesn't match.Please check "
  223. "the given mail addresses")
  224. return request.website.render(redirect, values)
  225. company = request.website.company_id
  226. if company.allow_id_card_upload:
  227. if not post_file:
  228. values = self.fill_values(values, is_company, logged)
  229. values.update(kwargs)
  230. values["error_msg"] = _("You need to upload a"
  231. " scan of your id card")
  232. return request.website.render(redirect, values)
  233. iban = kwargs.get("iban")
  234. if iban:
  235. valid = sub_req_obj.check_iban(iban)
  236. if not valid:
  237. values = self.fill_values(values, is_company, logged)
  238. values["error_msg"] = _("You iban account number "
  239. "is not valid")
  240. return request.website.render(redirect, values)
  241. # check the subscription's amount
  242. max_amount = company.subscription_maximum_amount
  243. if logged:
  244. partner = request.env.user.partner_id
  245. if partner.member:
  246. max_amount = max_amount - partner.total_value
  247. if company.unmix_share_type:
  248. share = self.get_selected_share(kwargs)
  249. if partner.cooperator_type != share.default_code:
  250. values = self.fill_values(values, is_company, logged)
  251. values["error_msg"] = (_("You can't subscribe two "
  252. "different types of share"))
  253. return request.website.render(redirect, values)
  254. total_amount = float(kwargs.get('total_parts'))
  255. if max_amount > 0 and total_amount > max_amount:
  256. values = self.fill_values(values, is_company, logged)
  257. values["error_msg"] = (_("You can't subscribe for an amount that "
  258. "exceed ")
  259. + str(max_amount)
  260. + company.currency_id.symbol)
  261. return request.website.render(redirect, values)
  262. return True
  263. @http.route(['/subscription/get_share_product'],
  264. type='json',
  265. auth="public",
  266. methods=['POST'], website=True)
  267. def get_share_product(self, share_product_id, **kw):
  268. product_template = request.env['product.template']
  269. product = product_template.sudo().browse(int(share_product_id))
  270. return {
  271. product.id: {
  272. 'list_price': product.list_price,
  273. 'min_qty': product.minimum_quantity,
  274. 'force_min_qty': product.force_min_qty
  275. }
  276. }
  277. @http.route(['/subscription/subscribe_share'],
  278. type='http',
  279. auth="public", website=True)
  280. def share_subscription(self, **kwargs):
  281. sub_req_obj = request.env['subscription.request']
  282. attach_obj = request.env['ir.attachment']
  283. # List of file to add to ir_attachment once we have the ID
  284. post_file = []
  285. # Info to add after the message
  286. post_description = []
  287. values = {}
  288. for field_name, field_value in kwargs.items():
  289. if hasattr(field_value, 'filename'):
  290. post_file.append(field_value)
  291. elif (field_name in sub_req_obj._fields
  292. and field_name not in _BLACKLIST):
  293. values[field_name] = field_value
  294. # allow to add some free fields or blacklisted field like ID
  295. elif field_name not in _TECHNICAL:
  296. post_description.append("%s: %s" % (field_name, field_value))
  297. logged = kwargs.get("logged") == 'on'
  298. is_company = kwargs.get("is_company") == 'on'
  299. response = self.validation(kwargs, logged, values, post_file)
  300. if response is not True:
  301. return response
  302. already_coop = False
  303. if logged:
  304. partner = request.env.user.partner_id
  305. values['partner_id'] = partner.id
  306. already_coop = partner.member
  307. elif kwargs.get("already_cooperator") == 'on':
  308. already_coop = True
  309. values["already_cooperator"] = already_coop
  310. values["is_company"] = is_company
  311. if kwargs.get('internal_rules_approved', 'off') == 'on':
  312. values['internal_rules_approved'] = True
  313. if kwargs.get('data_policy_approved', 'off') == 'on':
  314. values['data_policy_approved'] = True
  315. if kwargs.get('financial_risk_approved', 'off') == 'on':
  316. values['financial_risk_approved'] = True
  317. lastname = kwargs.get("lastname").upper()
  318. firstname = kwargs.get("firstname").title()
  319. values["name"] = firstname + " " + lastname
  320. values["lastname"] = lastname
  321. values["firstname"] = firstname
  322. birthdate = kwargs.get("birthdate")
  323. if birthdate:
  324. values["birthdate"] = datetime.strptime(birthdate,
  325. ("%d/%m/%Y")).date()
  326. else:
  327. values["birthdate"] = False
  328. values["source"] = "website"
  329. values["share_product_id"] = self.get_selected_share(kwargs).id
  330. if is_company:
  331. values['company_type'] = kwargs.get("company_type")
  332. if kwargs.get("company_register_number", False):
  333. values["company_register_number"] = re.sub('[^0-9a-zA-Z]+', '',
  334. kwargs.get("company_register_number"))
  335. subscription_id = sub_req_obj.sudo().create_comp_sub_req(values)
  336. else:
  337. subscription_id = sub_req_obj.sudo().create(values)
  338. if subscription_id:
  339. for field_value in post_file:
  340. attachment_value = {
  341. 'name': field_value.filename,
  342. 'res_name': field_value.filename,
  343. 'res_model': 'subscription.request',
  344. 'res_id': subscription_id,
  345. 'datas': base64.encodestring(field_value.read()),
  346. 'datas_fname': field_value.filename,
  347. }
  348. attach_obj.sudo().create(attachment_value)
  349. return self.get_subscription_response(values, kwargs)