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.

232 lines
11 KiB

  1. # -*- coding: utf-8 -*-
  2. import base64
  3. from datetime 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,False,True)
  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,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 get_values_from_user(self, values, is_company):
  41. # the subscriber is connected
  42. if request.env.user.login != 'public':
  43. if is_company:
  44. print ''
  45. else:
  46. values['logged'] = 'on'
  47. partner = request.env.user.partner_id
  48. values['firstname'] = partner.firstname
  49. values['lastname'] = partner.lastname
  50. values['email'] = partner.email
  51. values['address'] = partner.street
  52. values['zip_code'] = partner.zip
  53. values['city'] = partner.city
  54. values['country_id'] = partner.country_id.id
  55. values['gender'] = partner.gender
  56. values['no_registre'] = partner.national_register_number
  57. birthdate = datetime.strptime(partner.birthdate,"%Y-%m-%d")
  58. values['birthdate'] = datetime.strftime(birthdate,"%d/%m/%Y")
  59. if partner.bank_ids:
  60. values['iban'] = partner.bank_ids[0].acc_number
  61. values['lang'] = partner.lang
  62. values['phone'] = partner.phone
  63. return values
  64. def fill_values(self, values, is_company, load_from_user=False):
  65. company = request.website.company_id
  66. if load_from_user:
  67. values = self.get_values_from_user(values,is_company)
  68. values['countries'] = self.get_countries()
  69. values['langs'] = self.get_langs()
  70. values['products'] = self.get_products_share(is_company)
  71. fields_desc = request.env['subscription.request'].sudo().fields_get(['company_type','gender'])
  72. values['company_types'] = fields_desc['company_type']['selection']
  73. values['genders'] = fields_desc['gender']['selection']
  74. if not values.get('share_product_id'):
  75. products = request.env['product.template'].sudo().get_web_share_products(is_company)
  76. for product in products:
  77. if product.default_share_product == True:
  78. values['share_product_id'] = product.id
  79. break
  80. if not values.get('country_id'):
  81. if company.default_country_id:
  82. values['country_id'] = company.default_country_id.id
  83. else:
  84. values['country_id'] = '21'
  85. if not values.get('activities_country_id'):
  86. if company.default_country_id:
  87. values['activities_country_id'] = company.default_country_id.id
  88. else:
  89. values['activities_country_id'] = '21'
  90. if not values.get('lang'):
  91. if company.default_lang_id:
  92. values['lang'] = company.default_lang_id.code
  93. return values
  94. def get_products_share(self, is_company):
  95. products = request.env['product.template'].sudo().get_web_share_products(is_company)
  96. return products
  97. def get_countries(self):
  98. countries = request.env['res.country'].sudo().search([])
  99. return countries
  100. def get_langs(self):
  101. langs = request.env['res.lang'].sudo().search([])
  102. return langs
  103. @http.route(['/subscription/get_share_product'], type='json', auth="public", methods=['POST'], website=True)
  104. def get_share_product(self, share_product_id, **kw):
  105. product = request.env['product.template'].sudo().browse(int(share_product_id))
  106. return {product.id: {'list_price':product.list_price,'min_qty':product.minimum_quantity,'force_min_qty':product.force_min_qty}}
  107. @http.route(['/subscription/subscribe_share'], type='http', auth="public", website=True)
  108. def share_subscription(self, **kwargs):
  109. user_obj = request.env['res.users']
  110. post_file = [] # List of file to add to ir_attachment once we have the ID
  111. post_description = [] # Info to add after the message
  112. values = {}
  113. for field_name, field_value in kwargs.items():
  114. if hasattr(field_value, 'filename'):
  115. post_file.append(field_value)
  116. elif field_name in request.registry['subscription.request']._fields and field_name not in _BLACKLIST:
  117. values[field_name] = field_value
  118. elif field_name not in _TECHNICAL: # allow to add some free fields or blacklisted field like ID
  119. post_description.append("%s: %s" % (field_name, field_value))
  120. logged = kwargs.get("logged")=='on'
  121. is_company = False
  122. if kwargs.get("is_company") == 'on':
  123. is_company = True
  124. values["is_company"] = is_company
  125. redirect = "easy_my_coop.becomecooperator"
  126. if is_company:
  127. redirect = "easy_my_coop.becomecompanycooperator"
  128. if not kwargs.has_key('g-recaptcha-response') or not request.website.is_captcha_valid(kwargs['g-recaptcha-response']):
  129. values = self.fill_values(values,is_company)
  130. values["error_msg"] = "the captcha has not been validated, please fill in the captcha"
  131. return request.website.render(kwargs.get("view_from", redirect), values)
  132. if not logged and kwargs.has_key('email'):
  133. user = user_obj.sudo().search([('login','=',kwargs.get("email"))])
  134. if user:
  135. values = self.fill_values(values,is_company)
  136. values.update(kwargs)
  137. values["error_msg"] = "There is an existing account for this mail address. Please login before fill in the form"
  138. return request.website.render(redirect, values)
  139. # fields validation : Check that required field from model subscription_request exists
  140. required_fields = request.env['subscription.request'].sudo().get_required_field()
  141. error = set(field for field in required_fields if not values.get(field))
  142. if error:
  143. values = self.fill_values(values, is_company)
  144. values["error_msg"] = "Some mandatory fields have not been filled"
  145. values = dict(values, error=error, kwargs=kwargs.items())
  146. return request.website.render(kwargs.get("view_from", redirect), values)
  147. if kwargs.get("already_cooperator") == 'on':
  148. already_cooperator = True
  149. lastname = kwargs.get("lastname").upper()
  150. firstname = kwargs.get("firstname").title()
  151. values["name"] = firstname + " " + lastname
  152. values["lastname"] = lastname
  153. values["firstname"] = firstname
  154. values["birthdate"] = datetime.strptime(kwargs.get("birthdate"), "%d/%m/%Y").date()
  155. values["source"] = "website"
  156. if kwargs.get("share_product_id"):
  157. product_id = kwargs.get("share_product_id")
  158. product = request.env['product.template'].sudo().browse(int(product_id)).product_variant_ids[0]
  159. values["share_product_id"] = product.id
  160. #check the subscription's amount
  161. company = request.website.company_id
  162. max_amount = company.subscription_maximum_amount
  163. total_amount = float(kwargs.get('total_parts'))
  164. if max_amount > 0 and total_amount > max_amount:
  165. values = self.fill_values(values,is_company)
  166. values["error_msg"] = "You can't suscribe for an amount that exceed " + str(max_amount) + company.currency_id.symbol
  167. return request.website.render("easy_my_coop.becomecooperator", values)
  168. if is_company:
  169. if kwargs.get("company_register_number", is_company):
  170. values["company_register_number"] = re.sub('[^0-9a-zA-Z]+', '', kwargs.get("company_register_number"))
  171. subscription_id = request.env['subscription.request'].sudo().create_comp_sub_req(values)
  172. else:
  173. if kwargs.get("no_registre"):
  174. values["no_registre"] = re.sub('[^0-9a-zA-Z]+', '', kwargs.get("no_registre"))
  175. subscription_id = request.env['subscription.request'].sudo().create(values)
  176. values.update(subscription_id = subscription_id)
  177. if subscription_id:
  178. for field_value in post_file:
  179. attachment_value = {
  180. 'name': field_value.filename,
  181. 'res_name': field_value.filename,
  182. 'res_model': 'subscription.request',
  183. 'res_id': subscription_id,
  184. 'datas': base64.encodestring(field_value.read()),
  185. 'datas_fname': field_value.filename,
  186. }
  187. request.registry['ir.attachment'].create(request.cr, SUPERUSER_ID, attachment_value, context=request.context)
  188. return self.get_subscription_response(values, kwargs)