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.

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