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.

389 lines
16 KiB

5 years ago
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', '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_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. else:
  205. confirm_email = kwargs.get('confirm_email')
  206. if email != confirm_email:
  207. values = self.fill_values(values, is_company, logged)
  208. values.update(kwargs)
  209. values["error_msg"] = _("The email and the confirmation "
  210. "email doesn't match.Please check "
  211. "the given mail addresses")
  212. return request.website.render(redirect, values)
  213. company = request.website.company_id
  214. if company.allow_id_card_upload:
  215. if not post_file:
  216. values = self.fill_values(values, is_company, logged)
  217. values.update(kwargs)
  218. values["error_msg"] = _("You need to upload a"
  219. " scan of your id card")
  220. return request.website.render(redirect, values)
  221. iban = kwargs.get("iban")
  222. valid = sub_req_obj.check_iban(iban)
  223. if not valid:
  224. values = self.fill_values(values, is_company, logged)
  225. values["error_msg"] = _("You iban account number"
  226. "is not valid")
  227. return request.website.render(redirect, values)
  228. # check the subscription's amount
  229. max_amount = company.subscription_maximum_amount
  230. if logged:
  231. partner = request.env.user.partner_id
  232. if partner.member:
  233. max_amount = max_amount - partner.total_value
  234. if company.unmix_share_type:
  235. share = self.get_selected_share(kwargs)
  236. if partner.cooperator_type != share.default_code:
  237. values = self.fill_values(values, is_company, logged)
  238. values["error_msg"] = (_("You can't subscribe two "
  239. "different types of share"))
  240. return request.website.render(redirect, values)
  241. total_amount = float(kwargs.get('total_parts'))
  242. if max_amount > 0 and total_amount > max_amount:
  243. values = self.fill_values(values, is_company, logged)
  244. values["error_msg"] = (_("You can't subscribe for an amount that "
  245. "exceed ")
  246. + str(max_amount)
  247. + company.currency_id.symbol)
  248. return request.website.render(redirect, values)
  249. return True
  250. @http.route(['/subscription/get_share_product'],
  251. type='json',
  252. auth="public",
  253. methods=['POST'], website=True)
  254. def get_share_product(self, share_product_id, **kw):
  255. product_template = request.env['product.template']
  256. product = product_template.sudo().browse(int(share_product_id))
  257. return {
  258. product.id: {
  259. 'list_price': product.list_price,
  260. 'min_qty': product.minimum_quantity,
  261. 'force_min_qty': product.force_min_qty
  262. }
  263. }
  264. @http.route(['/subscription/subscribe_share'],
  265. type='http',
  266. auth="public", website=True)
  267. def share_subscription(self, **kwargs):
  268. sub_req_obj = request.env['subscription.request']
  269. attach_obj = request.env['ir.attachment']
  270. # List of file to add to ir_attachment once we have the ID
  271. post_file = []
  272. # Info to add after the message
  273. post_description = []
  274. values = {}
  275. for field_name, field_value in kwargs.items():
  276. if hasattr(field_value, 'filename'):
  277. post_file.append(field_value)
  278. elif (field_name in sub_req_obj._fields
  279. and field_name not in _BLACKLIST):
  280. values[field_name] = field_value
  281. # allow to add some free fields or blacklisted field like ID
  282. elif field_name not in _TECHNICAL:
  283. post_description.append("%s: %s" % (field_name, field_value))
  284. logged = kwargs.get("logged") == 'on'
  285. is_company = kwargs.get("is_company") == 'on'
  286. response = self.validation(kwargs, logged, values, post_file)
  287. if response is not True:
  288. return response
  289. already_coop = False
  290. if logged:
  291. partner = request.env.user.partner_id
  292. values['partner_id'] = partner.id
  293. already_coop = partner.member
  294. elif kwargs.get("already_cooperator") == 'on':
  295. already_coop = True
  296. values["already_cooperator"] = already_coop
  297. values["is_company"] = is_company
  298. if kwargs.get('data_policy_approved', 'off') == 'on':
  299. values['data_policy_approved'] = True
  300. if kwargs.get('internal_rules_approved', 'off') == 'on':
  301. values['internal_rules_approved'] = True
  302. lastname = kwargs.get("lastname").upper()
  303. firstname = kwargs.get("firstname").title()
  304. values["name"] = firstname + " " + lastname
  305. values["lastname"] = lastname
  306. values["firstname"] = firstname
  307. values["birthdate"] = datetime.strptime(kwargs.get("birthdate"),
  308. "%d/%m/%Y").date()
  309. values["source"] = "website"
  310. values["share_product_id"] = self.get_selected_share(kwargs).id
  311. if is_company:
  312. values['company_type'] = kwargs.get("company_type")
  313. if kwargs.get("company_register_number", False):
  314. values["company_register_number"] = re.sub('[^0-9a-zA-Z]+', '',
  315. kwargs.get("company_register_number"))
  316. subscription_id = sub_req_obj.sudo().create_comp_sub_req(values)
  317. else:
  318. subscription_id = sub_req_obj.sudo().create(values)
  319. if subscription_id:
  320. for field_value in post_file:
  321. attachment_value = {
  322. 'name': field_value.filename,
  323. 'res_name': field_value.filename,
  324. 'res_model': 'subscription.request',
  325. 'res_id': subscription_id,
  326. 'datas': base64.encodestring(field_value.read()),
  327. 'datas_fname': field_value.filename,
  328. }
  329. attach_obj.sudo().create(attachment_value)
  330. return self.get_subscription_response(values, kwargs)