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.

262 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. if logged:
  146. partner = request.env.user.partner_id
  147. values['partner_id'] = partner.id
  148. values['already_cooperator'] = partner.member
  149. is_company = False
  150. if kwargs.get("is_company") == 'on':
  151. is_company = True
  152. values["is_company"] = is_company
  153. redirect = "easy_my_coop.becomecooperator"
  154. if is_company:
  155. redirect = "easy_my_coop.becomecompanycooperator"
  156. if not kwargs.has_key('g-recaptcha-response') or not request.website.is_captcha_valid(kwargs['g-recaptcha-response']):
  157. values = self.fill_values(values,is_company)
  158. values["error_msg"] = "the captcha has not been validated, please fill in the captcha"
  159. return request.website.render(kwargs.get("view_from", redirect), values)
  160. if not logged and kwargs.has_key('email'):
  161. user = user_obj.sudo().search([('login','=',kwargs.get("email"))])
  162. if user:
  163. values = self.fill_values(values,is_company)
  164. values.update(kwargs)
  165. values["error_msg"] = "There is an existing account for this mail address. Please login before fill in the form"
  166. return request.website.render(redirect, values)
  167. # fields validation : Check that required field from model subscription_request exists
  168. required_fields = request.env['subscription.request'].sudo().get_required_field()
  169. error = set(field for field in required_fields if not values.get(field))
  170. if error:
  171. values = self.fill_values(values, is_company)
  172. values["error_msg"] = "Some mandatory fields have not been filled"
  173. values = dict(values, error=error, kwargs=kwargs.items())
  174. return request.website.render(kwargs.get("view_from", redirect), values)
  175. if kwargs.get("already_cooperator") == 'on':
  176. already_cooperator = True
  177. lastname = kwargs.get("lastname").upper()
  178. firstname = kwargs.get("firstname").title()
  179. values["name"] = firstname + " " + lastname
  180. values["lastname"] = lastname
  181. values["firstname"] = firstname
  182. values["birthdate"] = datetime.strptime(kwargs.get("birthdate"), "%d/%m/%Y").date()
  183. values["source"] = "website"
  184. if kwargs.get("share_product_id"):
  185. product_id = kwargs.get("share_product_id")
  186. product = request.env['product.template'].sudo().browse(int(product_id)).product_variant_ids[0]
  187. values["share_product_id"] = product.id
  188. #check the subscription's amount
  189. company = request.website.company_id
  190. max_amount = company.subscription_maximum_amount
  191. total_amount = float(kwargs.get('total_parts'))
  192. if max_amount > 0 and total_amount > max_amount:
  193. values = self.fill_values(values,is_company)
  194. values["error_msg"] = "You can't subscribe for an amount that exceed " + str(max_amount) + company.currency_id.symbol
  195. return request.website.render("easy_my_coop.becomecooperator", values)
  196. if is_company:
  197. if kwargs.get("company_register_number", is_company):
  198. values["company_register_number"] = re.sub('[^0-9a-zA-Z]+', '', kwargs.get("company_register_number"))
  199. subscription_id = request.env['subscription.request'].sudo().create_comp_sub_req(values)
  200. else:
  201. if kwargs.get("no_registre"):
  202. values["no_registre"] = re.sub('[^0-9a-zA-Z]+', '', kwargs.get("no_registre"))
  203. subscription_id = request.env['subscription.request'].sudo().create(values)
  204. values.update(subscription_id = subscription_id)
  205. if subscription_id:
  206. for field_value in post_file:
  207. attachment_value = {
  208. 'name': field_value.filename,
  209. 'res_name': field_value.filename,
  210. 'res_model': 'subscription.request',
  211. 'res_id': subscription_id,
  212. 'datas': base64.encodestring(field_value.read()),
  213. 'datas_fname': field_value.filename,
  214. }
  215. request.registry['ir.attachment'].create(request.cr, SUPERUSER_ID, attachment_value, context=request.context)
  216. return self.get_subscription_response(values, kwargs)