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.

191 lines
9.0 KiB

  1. # -*- coding: utf-8 -*-
  2. import base64
  3. import datetime
  4. import re
  5. import werkzeug
  6. import werkzeug.urls
  7. from openerp import http, SUPERUSER_ID
  8. from openerp.http import request
  9. from openerp.tools.translate import _
  10. _TECHNICAL = ['view_from', 'view_callback'] # Only use for behavior, don't stock it
  11. _BLACKLIST = ['id', 'create_uid', 'create_date', 'write_uid', 'write_date', 'user_id', 'active'] # Allow in description
  12. class WebsiteSubscription(http.Controller):
  13. @http.route(['/page/become_cooperator','/become_cooperator'], type='http', auth="public", website=True)
  14. def display_become_cooperator_page(self, **kwargs):
  15. values = {}
  16. values = self.fill_values(values,is_company=False)
  17. for field in ['email','firstname','lastname','birthdate','iban','share_product_id','no_registre','address','city','zip_code','country_id','phone','lang','nb_parts','total_parts','error_msg']:
  18. if kwargs.get(field):
  19. values[field] = kwargs.pop(field)
  20. values.update(kwargs=kwargs.items())
  21. return request.website.render("easy_my_coop.becomecooperator", values)
  22. @http.route(['/page/become_company_cooperator','/become_company_cooperator'], type='http', auth="public", website=True)
  23. def display_become_company_cooperator_page(self, **kwargs):
  24. values = {}
  25. values = self.fill_values(values,is_company=True)
  26. for field in ['is_company','company_register_number','company_name','company_email','company_type','email','firstname','lastname','birthdate','iban','share_product_id','no_registre','address','city','zip_code','country_id','phone','lang','nb_parts','total_parts','error_msg']:
  27. if kwargs.get(field):
  28. values[field] = kwargs.pop(field)
  29. values.update(kwargs=kwargs.items())
  30. return request.website.render("easy_my_coop.becomecompanycooperator", values)
  31. def preRenderThanks(self, values, kwargs):
  32. """ Allow to be overrided """
  33. return {
  34. '_values': values,
  35. '_kwargs': kwargs,
  36. }
  37. def get_subscription_response(self, values, kwargs):
  38. values = self.preRenderThanks(values, kwargs)
  39. return request.website.render(kwargs.get("view_callback", "easy_my_coop.cooperator_thanks"), values)
  40. def fill_values(self, values, is_company):
  41. company = request.website.company_id
  42. values['countries'] = self.get_countries()
  43. values['langs'] = self.get_langs()
  44. values['products'] = self.get_products_share(is_company)
  45. fields_desc = request.env['subscription.request'].sudo().fields_get(['company_type','gender'])
  46. values['company_types'] = fields_desc['company_type']['selection']
  47. values['genders'] = fields_desc['gender']['selection']
  48. if not values.get('share_product_id'):
  49. products = request.env['product.template'].sudo().get_web_share_products(is_company)
  50. for product in products:
  51. if product.default_share_product == True:
  52. values['share_product_id'] = product.id
  53. break
  54. if not values.get('country_id'):
  55. if company.default_country_id:
  56. values['country_id'] = company.default_country_id.id
  57. else:
  58. values['country_id'] = '21'
  59. if not values.get('activities_country_id'):
  60. if company.default_country_id:
  61. values['activities_country_id'] = company.default_country_id.id
  62. else:
  63. values['activities_country_id'] = '21'
  64. if not values.get('lang'):
  65. if company.default_lang_id:
  66. values['lang'] = company.default_lang_id.code
  67. return values
  68. def get_products_share(self, is_company):
  69. products = request.env['product.template'].sudo().get_web_share_products(is_company)
  70. return products
  71. def get_countries(self):
  72. countries = request.env['res.country'].sudo().search([])
  73. return countries
  74. def get_langs(self):
  75. langs = request.env['res.lang'].sudo().search([])
  76. return langs
  77. @http.route(['/subscription/get_share_product'], type='json', auth="public", methods=['POST'], website=True)
  78. def get_share_product(self, share_product_id, **kw):
  79. product = request.env['product.template'].sudo().browse(int(share_product_id))
  80. return {product.id: {'list_price':product.list_price,'min_qty':product.minimum_quantity,'force_min_qty':product.force_min_qty}}
  81. @http.route(['/subscription/subscribe_share'], type='http', auth="public", website=True)
  82. def share_subscription(self, **kwargs):
  83. post_file = [] # List of file to add to ir_attachment once we have the ID
  84. post_description = [] # Info to add after the message
  85. values = {}
  86. for field_name, field_value in kwargs.items():
  87. if hasattr(field_value, 'filename'):
  88. post_file.append(field_value)
  89. elif field_name in request.registry['subscription.request']._fields and field_name not in _BLACKLIST:
  90. values[field_name] = field_value
  91. elif field_name not in _TECHNICAL: # allow to add some free fields or blacklisted field like ID
  92. post_description.append("%s: %s" % (field_name, field_value))
  93. is_company = False
  94. if kwargs.get("is_company") == 'on':
  95. is_company = True
  96. values["is_company"] = is_company
  97. redirect = "easy_my_coop.becomecooperator"
  98. if is_company:
  99. redirect = "easy_my_coop.becomecompanycooperator"
  100. if not kwargs.has_key('g-recaptcha-response') or not request.website.is_captcha_valid(kwargs['g-recaptcha-response']):
  101. values = self.fill_values(values,is_company)
  102. values["error_msg"] = "the captcha has not been validated, please fill in the captcha"
  103. return request.website.render(kwargs.get("view_from", redirect), values)
  104. # fields validation : Check that required field from model subscription_request exists
  105. required_fields = request.env['subscription.request'].sudo().get_required_field()
  106. error = set(field for field in required_fields if not values.get(field))
  107. if error:
  108. values = self.fill_values(values, is_company)
  109. values["error_msg"] = "Some mandatory fields have not been filled"
  110. values = dict(values, error=error, kwargs=kwargs.items())
  111. return request.website.render(kwargs.get("view_from", redirect), values)
  112. if kwargs.get("already_cooperator") == 'on':
  113. already_cooperator = True
  114. lastname = kwargs.get("lastname").upper()
  115. firstname = kwargs.get("firstname").title()
  116. values["name"] = firstname + " " + lastname
  117. values["lastname"] = lastname
  118. values["firstname"] = firstname
  119. values["birthdate"] = datetime.datetime.strptime(kwargs.get("birthdate"), "%d/%m/%Y").date()
  120. values["source"] = "website"
  121. if kwargs.get("share_product_id"):
  122. product_id = kwargs.get("share_product_id")
  123. product = request.env['product.template'].sudo().browse(int(product_id)).product_variant_ids[0]
  124. values["share_product_id"] = product.id
  125. #check the subscription's amount
  126. company = request.website.company_id
  127. max_amount = company.subscription_maximum_amount
  128. total_amount = float(kwargs.get('total_parts'))
  129. if max_amount > 0 and total_amount > max_amount:
  130. values = self.fill_values(values)
  131. values["error_msg"] = "You can't suscribe for an amount that exceed " + str(max_amount) + company.currency_id.symbol
  132. return request.website.render("easy_my_coop.becomecooperator", values)
  133. if values["is_company"] == True:
  134. if kwargs.get("company_register_number"):
  135. values["company_register_number"] = re.sub('[^0-9a-zA-Z]+', '', kwargs.get("company_register_number"))
  136. subscription_id = request.env['subscription.request'].sudo().create_comp_sub_req(values)
  137. else:
  138. if kwargs.get("no_registre"):
  139. values["no_registre"] = re.sub('[^0-9a-zA-Z]+', '', kwargs.get("no_registre"))
  140. subscription_id = request.env['subscription.request'].sudo().create(values)
  141. values.update(subscription_id = subscription_id)
  142. if subscription_id:
  143. for field_value in post_file:
  144. attachment_value = {
  145. 'name': field_value.filename,
  146. 'res_name': field_value.filename,
  147. 'res_model': 'subscription.request',
  148. 'res_id': subscription_id,
  149. 'datas': base64.encodestring(field_value.read()),
  150. 'datas_fname': field_value.filename,
  151. }
  152. request.registry['ir.attachment'].create(request.cr, SUPERUSER_ID, attachment_value, context=request.context)
  153. return self.get_subscription_response(values, kwargs)