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.

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