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.

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