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.

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