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.

424 lines
18 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. company_email = kwargs.get('company_email')
  194. if email == company_email:
  195. values["error_msg"] = _("Cooperator and company emails"
  196. " should be different.")
  197. return request.website.render(redirect, values)
  198. email = company_email
  199. if ('g-recaptcha-response' not in kwargs
  200. or not request.website.is_captcha_valid(
  201. kwargs['g-recaptcha-response'])):
  202. values = self.fill_values(values, is_company, logged)
  203. values["error_msg"] = _("the captcha has not been validated,"
  204. " please fill in the captcha")
  205. return request.website.render(redirect, values)
  206. # Check that required field from model subscription_request exists
  207. required_fields = sub_req_obj.sudo().get_required_field()
  208. if logged:
  209. # these fields are readonly when logged
  210. # we want to ease the process if user was a subscriber
  211. self.remove_field_from_list(required_fields, 'iban')
  212. self.remove_field_from_list(required_fields, 'birthdate')
  213. error = set(
  214. field for field in required_fields if not values.get(field)
  215. )
  216. if error:
  217. values = self.fill_values(values, is_company, logged)
  218. values["error_msg"] = _("Some mandatory fields have not "
  219. "been filled")
  220. values = dict(values, error=error, kwargs=kwargs.items())
  221. return request.website.render(redirect, values)
  222. if not logged and email:
  223. user = user_obj.sudo().search([('login', '=', email)])
  224. if user:
  225. values = self.fill_values(values, is_company, logged)
  226. values.update(kwargs)
  227. values["error_msg"] = _("There is an existing account for this"
  228. " mail address. Please login before "
  229. "fill in the form")
  230. return request.website.render(redirect, values)
  231. else:
  232. confirm_email = kwargs.get('confirm_email')
  233. if email != confirm_email:
  234. values = self.fill_values(values, is_company, logged)
  235. values.update(kwargs)
  236. values["error_msg"] = _("The email and the confirmation "
  237. "email doesn't match.Please check "
  238. "the given mail addresses")
  239. return request.website.render(redirect, values)
  240. company = request.website.company_id
  241. if company.allow_id_card_upload:
  242. if not post_file:
  243. values = self.fill_values(values, is_company, logged)
  244. values.update(kwargs)
  245. values["error_msg"] = _("You need to upload a"
  246. " scan of your id card")
  247. return request.website.render(redirect, values)
  248. iban = kwargs.get("iban")
  249. if iban:
  250. valid = sub_req_obj.check_iban(iban)
  251. if not valid:
  252. values = self.fill_values(values, is_company, logged)
  253. values["error_msg"] = _("You iban account number "
  254. "is not valid")
  255. return request.website.render(redirect, values)
  256. # check the subscription's amount
  257. max_amount = company.subscription_maximum_amount
  258. if logged:
  259. partner = request.env.user.partner_id
  260. if partner.member:
  261. max_amount = max_amount - partner.total_value
  262. if company.unmix_share_type:
  263. share = self.get_selected_share(kwargs)
  264. if partner.cooperator_type != share.default_code:
  265. values = self.fill_values(values, is_company, logged)
  266. values["error_msg"] = (_("You can't subscribe two "
  267. "different types of share"))
  268. return request.website.render(redirect, values)
  269. total_amount = float(kwargs.get('total_parts'))
  270. if max_amount > 0 and total_amount > max_amount:
  271. values = self.fill_values(values, is_company, logged)
  272. values["error_msg"] = (_("You can't subscribe for an amount that "
  273. "exceed ")
  274. + str(max_amount)
  275. + company.currency_id.symbol)
  276. return request.website.render(redirect, values)
  277. return True
  278. @http.route(['/subscription/get_share_product'],
  279. type='json',
  280. auth="public",
  281. methods=['POST'], website=True)
  282. def get_share_product(self, share_product_id, **kw):
  283. product_template = request.env['product.template']
  284. product = product_template.sudo().browse(int(share_product_id))
  285. return {
  286. product.id: {
  287. 'list_price': product.list_price,
  288. 'min_qty': product.minimum_quantity,
  289. 'force_min_qty': product.force_min_qty
  290. }
  291. }
  292. def share_subscription(self, **kwargs):
  293. sub_req_obj = request.env['subscription.request']
  294. attach_obj = request.env['ir.attachment']
  295. # List of file to add to ir_attachment once we have the ID
  296. post_file = []
  297. # Info to add after the message
  298. post_description = []
  299. values = {}
  300. for field_name, field_value in kwargs.items():
  301. if hasattr(field_value, 'filename'):
  302. post_file.append(field_value)
  303. elif (field_name in sub_req_obj._fields
  304. and field_name not in _BLACKLIST):
  305. values[field_name] = field_value
  306. # allow to add some free fields or blacklisted field like ID
  307. elif field_name not in _TECHNICAL:
  308. post_description.append("%s: %s" % (field_name, field_value))
  309. logged = kwargs.get("logged") == 'on'
  310. is_company = kwargs.get("is_company") == 'on'
  311. response = self.validation(kwargs, logged, values, post_file)
  312. if response is not True:
  313. return response
  314. already_coop = False
  315. if logged:
  316. partner = request.env.user.partner_id
  317. values['partner_id'] = partner.id
  318. already_coop = partner.member
  319. elif kwargs.get("already_cooperator") == 'on':
  320. already_coop = True
  321. values["already_cooperator"] = already_coop
  322. values["is_company"] = is_company
  323. if kwargs.get('internal_rules_approved', 'off') == 'on':
  324. values['internal_rules_approved'] = True
  325. if kwargs.get('data_policy_approved', 'off') == 'on':
  326. values['data_policy_approved'] = True
  327. if kwargs.get('financial_risk_approved', 'off') == 'on':
  328. values['financial_risk_approved'] = True
  329. lastname = kwargs.get("lastname").upper()
  330. firstname = kwargs.get("firstname").title()
  331. values["name"] = firstname + " " + lastname
  332. values["lastname"] = lastname
  333. values["firstname"] = firstname
  334. birthdate = kwargs.get("birthdate")
  335. if birthdate:
  336. values["birthdate"] = datetime.strptime(birthdate,
  337. ("%d/%m/%Y")).date()
  338. else:
  339. values["birthdate"] = False
  340. values["source"] = "website"
  341. values["share_product_id"] = self.get_selected_share(kwargs).id
  342. if is_company:
  343. values['company_type'] = kwargs.get("company_type")
  344. if kwargs.get("company_register_number", False):
  345. values["company_register_number"] = re.sub(
  346. '[^0-9a-zA-Z]+', '', kwargs.get("company_register_number")
  347. )
  348. subscription_id = sub_req_obj.sudo().create_comp_sub_req(values)
  349. else:
  350. subscription_id = sub_req_obj.sudo().create(values)
  351. if subscription_id:
  352. for field_value in post_file:
  353. attachment_value = {
  354. 'name': field_value.filename,
  355. 'res_name': field_value.filename,
  356. 'res_model': 'subscription.request',
  357. 'res_id': subscription_id,
  358. 'datas': base64.encodestring(field_value.read()),
  359. 'datas_fname': field_value.filename,
  360. }
  361. attach_obj.sudo().create(attachment_value)
  362. return self.get_subscription_response(values, kwargs)