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.

267 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. values['company'] = company
  99. if is_company:
  100. values['is_company'] = 'on'
  101. if not values.get('share_product_id'):
  102. products = request.env['product.template'].sudo().get_web_share_products(is_company)
  103. for product in products:
  104. if product.default_share_product == True:
  105. values['share_product_id'] = product.id
  106. break
  107. if not values.get('country_id'):
  108. if company.default_country_id:
  109. values['country_id'] = company.default_country_id.id
  110. else:
  111. values['country_id'] = '21'
  112. if not values.get('activities_country_id'):
  113. if company.default_country_id:
  114. values['activities_country_id'] = company.default_country_id.id
  115. else:
  116. values['activities_country_id'] = '21'
  117. if not values.get('lang'):
  118. if company.default_lang_id:
  119. values['lang'] = company.default_lang_id.code
  120. return values
  121. def get_products_share(self, is_company):
  122. products = request.env['product.template'].sudo().get_web_share_products(is_company)
  123. return products
  124. def get_countries(self):
  125. countries = request.env['res.country'].sudo().search([])
  126. return countries
  127. def get_langs(self):
  128. langs = request.env['res.lang'].sudo().search([])
  129. return langs
  130. @http.route(['/subscription/get_share_product'], type='json', auth="public", methods=['POST'], website=True)
  131. def get_share_product(self, share_product_id, **kw):
  132. product = request.env['product.template'].sudo().browse(int(share_product_id))
  133. return {product.id: {'list_price':product.list_price,'min_qty':product.minimum_quantity,'force_min_qty':product.force_min_qty}}
  134. @http.route(['/subscription/subscribe_share'], type='http', auth="public", website=True)
  135. def share_subscription(self, **kwargs):
  136. user_obj = request.env['res.users']
  137. post_file = [] # List of file to add to ir_attachment once we have the ID
  138. post_description = [] # Info to add after the message
  139. values = {}
  140. for field_name, field_value in kwargs.items():
  141. if hasattr(field_value, 'filename'):
  142. post_file.append(field_value)
  143. elif field_name in request.registry['subscription.request']._fields and field_name not in _BLACKLIST:
  144. values[field_name] = field_value
  145. elif field_name not in _TECHNICAL: # allow to add some free fields or blacklisted field like ID
  146. post_description.append("%s: %s" % (field_name, field_value))
  147. logged = kwargs.get("logged")=='on'
  148. if logged:
  149. partner = request.env.user.partner_id
  150. values['partner_id'] = partner.id
  151. values['already_cooperator'] = partner.member
  152. redirect = "easy_my_coop.becomecooperator"
  153. email = kwargs.get('email')
  154. is_company = kwargs.get("is_company") == 'on'
  155. if is_company:
  156. is_company = True
  157. redirect = "easy_my_coop.becomecompanycooperator"
  158. email = kwargs.get('company_email')
  159. values["is_company"] = is_company
  160. if not kwargs.has_key('g-recaptcha-response') or not request.website.is_captcha_valid(kwargs['g-recaptcha-response']):
  161. values = self.fill_values(values,is_company)
  162. values["error_msg"] = _("the captcha has not been validated, please fill in the captcha")
  163. return request.website.render(redirect, values)
  164. if not logged and email:
  165. user = user_obj.sudo().search([('login','=',email)])
  166. if user:
  167. values = self.fill_values(values,is_company)
  168. values.update(kwargs)
  169. values["error_msg"] = _("There is an existing account for this mail address. Please login before fill in the form")
  170. return request.website.render(redirect, values)
  171. # fields validation : Check that required field from model subscription_request exists
  172. required_fields = request.env['subscription.request'].sudo().get_required_field()
  173. error = set(field for field in required_fields if not values.get(field))
  174. if error:
  175. values = self.fill_values(values, is_company)
  176. values["error_msg"] = _("Some mandatory fields have not been filled")
  177. values = dict(values, error=error, kwargs=kwargs.items())
  178. return request.website.render(kwargs.get("view_from", redirect), values)
  179. if kwargs.get("already_cooperator") == 'on':
  180. already_cooperator = True
  181. lastname = kwargs.get("lastname").upper()
  182. firstname = kwargs.get("firstname").title()
  183. values["name"] = firstname + " " + lastname
  184. values["lastname"] = lastname
  185. values["firstname"] = firstname
  186. values["birthdate"] = datetime.strptime(kwargs.get("birthdate"), "%d/%m/%Y").date()
  187. values["source"] = "website"
  188. if kwargs.get("share_product_id"):
  189. product_id = kwargs.get("share_product_id")
  190. product = request.env['product.template'].sudo().browse(int(product_id)).product_variant_ids[0]
  191. values["share_product_id"] = product.id
  192. #check the subscription's amount
  193. company = request.website.company_id
  194. max_amount = company.subscription_maximum_amount
  195. total_amount = float(kwargs.get('total_parts'))
  196. if max_amount > 0 and total_amount > max_amount:
  197. values = self.fill_values(values,is_company)
  198. values["error_msg"] = _("You can't subscribe for an amount that exceed ") + str(max_amount) + company.currency_id.symbol
  199. return request.website.render("easy_my_coop.becomecooperator", values)
  200. if is_company:
  201. if kwargs.get("company_register_number", is_company):
  202. values["company_register_number"] = re.sub('[^0-9a-zA-Z]+', '', kwargs.get("company_register_number"))
  203. subscription_id = request.env['subscription.request'].sudo().create_comp_sub_req(values)
  204. else:
  205. if kwargs.get("no_registre"):
  206. values["no_registre"] = re.sub('[^0-9a-zA-Z]+', '', kwargs.get("no_registre"))
  207. subscription_id = request.env['subscription.request'].sudo().create(values)
  208. values.update(subscription_id = subscription_id)
  209. if subscription_id:
  210. for field_value in post_file:
  211. attachment_value = {
  212. 'name': field_value.filename,
  213. 'res_name': field_value.filename,
  214. 'res_model': 'subscription.request',
  215. 'res_id': subscription_id,
  216. 'datas': base64.encodestring(field_value.read()),
  217. 'datas_fname': field_value.filename,
  218. }
  219. request.registry['ir.attachment'].create(request.cr, SUPERUSER_ID, attachment_value, context=request.context)
  220. return self.get_subscription_response(values, kwargs)