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.

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