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.

302 lines
13 KiB

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