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.

380 lines
16 KiB

5 years ago
6 years ago
  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', '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. '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. logged = False
  30. if request.env.user.login != 'public':
  31. logged = True
  32. partner = request.env.user.partner_id
  33. if partner.is_company:
  34. return request.website.render("easy_my_coop.becomecompanycooperator", values)
  35. values = self.fill_values(values, False, logged, True)
  36. for field in _COOP_FORM_FIELD:
  37. if kwargs.get(field):
  38. values[field] = kwargs.pop(field)
  39. values.update(kwargs=kwargs.items())
  40. return request.website.render("easy_my_coop.becomecooperator", values)
  41. @http.route(['/page/become_company_cooperator',
  42. '/become_company_cooperator'],
  43. type='http', auth="public", website=True)
  44. def display_become_company_cooperator_page(self, **kwargs):
  45. values = {}
  46. logged = False
  47. if request.env.user.login != 'public':
  48. logged = True
  49. values = self.fill_values(values, True, logged, True)
  50. for field in _COMPANY_FORM_FIELD:
  51. if kwargs.get(field):
  52. values[field] = kwargs.pop(field)
  53. values.update(kwargs=kwargs.items())
  54. return request.website.render("easy_my_coop.becomecompanycooperator",
  55. values)
  56. def preRenderThanks(self, values, kwargs):
  57. """ Allow to be overrided """
  58. return {
  59. '_values': values,
  60. '_kwargs': kwargs,
  61. }
  62. def get_subscription_response(self, values, kwargs):
  63. values = self.preRenderThanks(values, kwargs)
  64. return request.website.render("easy_my_coop.cooperator_thanks", values)
  65. def get_date_string(self, birthdate):
  66. if birthdate:
  67. birthdate = datetime.strptime(birthdate, "%Y-%m-%d")
  68. return datetime.strftime(birthdate, "%d/%m/%Y")
  69. return False
  70. def get_values_from_user(self, values, is_company):
  71. # the subscriber is connected
  72. if request.env.user.login != 'public':
  73. values['logged'] = 'on'
  74. partner = request.env.user.partner_id
  75. if partner.member or partner.old_member:
  76. values['already_cooperator'] = 'on'
  77. if partner.bank_ids:
  78. values['iban'] = partner.bank_ids[0].acc_number
  79. values['address'] = partner.street
  80. values['zip_code'] = partner.zip
  81. values['city'] = partner.city
  82. values['country_id'] = partner.country_id.id
  83. if is_company:
  84. # company values
  85. values['company_register_number'] = partner.company_register_number
  86. values['company_name'] = partner.name
  87. values['company_email'] = partner.email
  88. # contact person values
  89. representative = partner.get_representative()
  90. values['firstname'] = representative.firstname
  91. values['lastname'] = representative.lastname
  92. values['gender'] = representative.gender
  93. values['email'] = representative.email
  94. values['contact_person_function'] = representative.function
  95. values['birthdate'] = self.get_date_string(representative.birthdate)
  96. values['lang'] = representative.lang
  97. values['phone'] = representative.phone
  98. else:
  99. values['firstname'] = partner.firstname
  100. values['lastname'] = partner.lastname
  101. values['email'] = partner.email
  102. values['gender'] = partner.gender
  103. values['function'] = partner.function
  104. values['birthdate'] = self.get_date_string(partner.birthdate)
  105. values['lang'] = partner.lang
  106. values['phone'] = partner.phone
  107. return values
  108. def fill_values(self, values, is_company, logged, load_from_user=False):
  109. sub_req_obj = request.env['subscription.request']
  110. company = request.website.company_id
  111. products = self.get_products_share(is_company)
  112. if load_from_user:
  113. values = self.get_values_from_user(values, is_company)
  114. if is_company:
  115. values['is_company'] = 'on'
  116. if logged:
  117. values['logged'] = 'on'
  118. values['countries'] = self.get_countries()
  119. values['langs'] = self.get_langs()
  120. values['products'] = products
  121. fields_desc = sub_req_obj.sudo().fields_get(['company_type', 'gender'])
  122. values['company_types'] = fields_desc['company_type']['selection']
  123. values['genders'] = fields_desc['gender']['selection']
  124. values['company'] = company
  125. if not values.get('share_product_id'):
  126. for product in products:
  127. if product.default_share_product is True:
  128. values['share_product_id'] = product.id
  129. break
  130. if not values.get('share_product_id', False) and products:
  131. values['share_product_id'] = products[0].id
  132. if not values.get('country_id'):
  133. if company.default_country_id:
  134. values['country_id'] = company.default_country_id.id
  135. else:
  136. values['country_id'] = '21'
  137. if not values.get('activities_country_id'):
  138. if company.default_country_id:
  139. values['activities_country_id'] = company.default_country_id.id
  140. else:
  141. values['activities_country_id'] = '21'
  142. if not values.get('lang'):
  143. if company.default_lang_id:
  144. values['lang'] = company.default_lang_id.code
  145. comp = request.env['res.company']._company_default_get()
  146. values.update({
  147. 'display_data_policy': comp.display_data_policy_approval,
  148. 'data_policy_required': comp.data_policy_approval_required,
  149. 'data_policy_text': comp.data_policy_approval_text,
  150. 'display_internal_rules': comp.display_internal_rules_approval,
  151. 'internal_rules_required': comp.internal_rules_approval_required,
  152. 'internal_rules_text': comp.internal_rules_approval_text,
  153. })
  154. return values
  155. def get_products_share(self, is_company):
  156. product_obj = request.env['product.template']
  157. products = product_obj.sudo().get_web_share_products(is_company)
  158. return products
  159. def get_countries(self):
  160. countries = request.env['res.country'].sudo().search([])
  161. return countries
  162. def get_langs(self):
  163. langs = request.env['res.lang'].sudo().search([])
  164. return langs
  165. def get_selected_share(self, kwargs):
  166. prod_obj = request.env['product.template']
  167. product_id = kwargs.get("share_product_id")
  168. return prod_obj.sudo().browse(int(product_id)).product_variant_ids[0]
  169. def validation(self, kwargs, logged, values, post_file):
  170. user_obj = request.env['res.users']
  171. sub_req_obj = request.env['subscription.request']
  172. redirect = "easy_my_coop.becomecooperator"
  173. email = kwargs.get('email')
  174. is_company = kwargs.get("is_company") == 'on'
  175. if is_company:
  176. is_company = True
  177. redirect = "easy_my_coop.becomecompanycooperator"
  178. email = kwargs.get('company_email')
  179. if ('g-recaptcha-response' not in kwargs
  180. or not request.website.is_captcha_valid(
  181. kwargs['g-recaptcha-response'])):
  182. values = self.fill_values(values, is_company, logged)
  183. values["error_msg"] = _("the captcha has not been validated,"
  184. " please fill in the captcha")
  185. return request.website.render(redirect, values)
  186. # Check that required field from model subscription_request exists
  187. required_fields = sub_req_obj.sudo().get_required_field()
  188. error = set(field for field in required_fields if not values.get(field)) #noqa
  189. if error:
  190. values = self.fill_values(values, is_company, logged)
  191. values["error_msg"] = _("Some mandatory fields have not "
  192. "been filled")
  193. values = dict(values, error=error, kwargs=kwargs.items())
  194. return request.website.render(redirect, values)
  195. if not logged and email:
  196. user = user_obj.sudo().search([('login', '=', email)])
  197. if user:
  198. values = self.fill_values(values, is_company, logged)
  199. values.update(kwargs)
  200. values["error_msg"] = _("There is an existing account for this"
  201. " mail address. Please login before "
  202. "fill in the form")
  203. return request.website.render(redirect, values)
  204. company = request.website.company_id
  205. if company.allow_id_card_upload:
  206. if not post_file:
  207. values = self.fill_values(values, is_company, logged)
  208. values.update(kwargs)
  209. values["error_msg"] = _("You need to upload a"
  210. " scan of your id card")
  211. return request.website.render(redirect, values)
  212. iban = kwargs.get("iban")
  213. valid = sub_req_obj.check_iban(iban)
  214. if not valid:
  215. values = self.fill_values(values, is_company, logged)
  216. values["error_msg"] = _("You iban account number"
  217. "is not valid")
  218. return request.website.render(redirect, values)
  219. # check the subscription's amount
  220. max_amount = company.subscription_maximum_amount
  221. if logged:
  222. partner = request.env.user.partner_id
  223. if partner.member:
  224. max_amount = max_amount - partner.total_value
  225. if company.unmix_share_type:
  226. share = self.get_selected_share(kwargs)
  227. if partner.cooperator_type != share.short_name:
  228. values = self.fill_values(values, is_company, logged)
  229. values["error_msg"] = (_("You can't subscribe two "
  230. "different types of share"))
  231. return request.website.render(redirect, values)
  232. total_amount = float(kwargs.get('total_parts'))
  233. if max_amount > 0 and total_amount > max_amount:
  234. values = self.fill_values(values, is_company, logged)
  235. values["error_msg"] = (_("You can't subscribe for an amount that "
  236. "exceed ")
  237. + str(max_amount)
  238. + company.currency_id.symbol)
  239. return request.website.render(redirect, values)
  240. return True
  241. @http.route(['/subscription/get_share_product'],
  242. type='json',
  243. auth="public",
  244. methods=['POST'], website=True)
  245. def get_share_product(self, share_product_id, **kw):
  246. product_template = request.env['product.template']
  247. product = product_template.sudo().browse(int(share_product_id))
  248. return {
  249. product.id: {
  250. 'list_price': product.list_price,
  251. 'min_qty': product.minimum_quantity,
  252. 'force_min_qty': product.force_min_qty
  253. }
  254. }
  255. @http.route(['/subscription/subscribe_share'],
  256. type='http',
  257. auth="public", website=True)
  258. def share_subscription(self, **kwargs):
  259. sub_req_obj = request.env['subscription.request']
  260. attach_obj = request.env['ir.attachment']
  261. # List of file to add to ir_attachment once we have the ID
  262. post_file = []
  263. # Info to add after the message
  264. post_description = []
  265. values = {}
  266. for field_name, field_value in kwargs.items():
  267. if hasattr(field_value, 'filename'):
  268. post_file.append(field_value)
  269. elif (field_name in sub_req_obj._fields
  270. and field_name not in _BLACKLIST):
  271. values[field_name] = field_value
  272. # allow to add some free fields or blacklisted field like ID
  273. elif field_name not in _TECHNICAL:
  274. post_description.append("%s: %s" % (field_name, field_value))
  275. logged = kwargs.get("logged") == 'on'
  276. is_company = kwargs.get("is_company") == 'on'
  277. response = self.validation(kwargs, logged, values, post_file)
  278. if response is not True:
  279. return response
  280. already_coop = False
  281. if logged:
  282. partner = request.env.user.partner_id
  283. values['partner_id'] = partner.id
  284. already_coop = partner.member
  285. elif kwargs.get("already_cooperator") == 'on':
  286. already_coop = True
  287. values["already_cooperator"] = already_coop
  288. values["is_company"] = is_company
  289. if kwargs.get('data_policy_approved', 'off') == 'on':
  290. values['data_policy_approved'] = True
  291. if kwargs.get('internal_rules_approved', 'off') == 'on':
  292. values['internal_rules_approved'] = True
  293. lastname = kwargs.get("lastname").upper()
  294. firstname = kwargs.get("firstname").title()
  295. values["name"] = firstname + " " + lastname
  296. values["lastname"] = lastname
  297. values["firstname"] = firstname
  298. values["birthdate"] = datetime.strptime(kwargs.get("birthdate"),
  299. "%d/%m/%Y").date()
  300. values["source"] = "website"
  301. values["share_product_id"] = self.get_selected_share(kwargs).id
  302. if is_company:
  303. if kwargs.get("company_register_number", False):
  304. values["company_register_number"] = re.sub('[^0-9a-zA-Z]+',
  305. '',
  306. kwargs.get("company_register_number"))
  307. subscription_id = sub_req_obj.sudo().create_comp_sub_req(values)
  308. else:
  309. subscription_id = sub_req_obj.sudo().create(values)
  310. if subscription_id:
  311. for field_value in post_file:
  312. attachment_value = {
  313. 'name': field_value.filename,
  314. 'res_name': field_value.filename,
  315. 'res_model': 'subscription.request',
  316. 'res_id': subscription_id,
  317. 'datas': base64.encodestring(field_value.read()),
  318. 'datas_fname': field_value.filename,
  319. }
  320. attach_obj.sudo().create(attachment_value)
  321. return self.get_subscription_response(values, kwargs)