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.

383 lines
16 KiB

6 years ago
  1. import base64
  2. from datetime import datetime
  3. import re
  4. from openerp import http
  5. from openerp.http import request
  6. from openerp.tools.translate import _
  7. # Only use for behavior, don't stock it
  8. _TECHNICAL = ['view_from', 'view_callback']
  9. # Allow in description
  10. _BLACKLIST = ['id', 'create_uid', 'create_date', 'write_uid', 'write_date',
  11. 'user_id', 'active']
  12. _COOP_FORM_FIELD = ['email', 'firstname', 'lastname', 'birthdate', 'iban',
  13. 'share_product_id', 'no_registre', 'address', 'city',
  14. 'zip_code', 'country_id', 'phone', 'lang', 'nb_parts',
  15. 'total_parts', 'error_msg']
  16. _COMPANY_FORM_FIELD = ['is_company', 'company_register_number', 'company_name',
  17. 'company_email', 'company_type', 'email', 'firstname',
  18. 'lastname', 'birthdate', 'iban', 'share_product_id',
  19. 'no_registre', 'address', 'city', 'zip_code',
  20. 'country_id', 'phone', 'lang', 'nb_parts',
  21. 'total_parts', 'error_msg']
  22. class WebsiteSubscription(http.Controller):
  23. @http.route(['/page/become_cooperator',
  24. '/become_cooperator'],
  25. type='http', auth="public", website=True)
  26. def display_become_cooperator_page(self, **kwargs):
  27. values = {}
  28. logged = False
  29. if request.env.user.login != 'public':
  30. logged = True
  31. partner = request.env.user.partner_id
  32. if partner.is_company:
  33. return request.website.render("easy_my_coop.becomecompanycooperator", values)
  34. values = self.fill_values(values, False, logged, True)
  35. for field in _COOP_FORM_FIELD:
  36. if kwargs.get(field):
  37. values[field] = kwargs.pop(field)
  38. values.update(kwargs=kwargs.items())
  39. return request.website.render("easy_my_coop.becomecooperator", values)
  40. @http.route(['/page/become_company_cooperator',
  41. '/become_company_cooperator'],
  42. type='http', auth="public", website=True)
  43. def display_become_company_cooperator_page(self, **kwargs):
  44. values = {}
  45. logged = False
  46. if request.env.user.login != 'public':
  47. logged = True
  48. values = self.fill_values(values, True, logged, True)
  49. for field in _COMPANY_FORM_FIELD:
  50. if kwargs.get(field):
  51. values[field] = kwargs.pop(field)
  52. values.update(kwargs=kwargs.items())
  53. return request.website.render("easy_my_coop.becomecompanycooperator", values)
  54. def preRenderThanks(self, values, kwargs):
  55. """ Allow to be overrided """
  56. return {
  57. '_values': values,
  58. '_kwargs': kwargs,
  59. }
  60. def get_subscription_response(self, values, kwargs):
  61. values = self.preRenderThanks(values, kwargs)
  62. return request.website.render("easy_my_coop.cooperator_thanks", values)
  63. def get_date_string(self, birthdate):
  64. if birthdate:
  65. birthdate = datetime.strptime(birthdate, "%Y-%m-%d")
  66. return datetime.strftime(birthdate, "%d/%m/%Y")
  67. return False
  68. def get_values_from_user(self, values, is_company):
  69. # the subscriber is connected
  70. if request.env.user.login != 'public':
  71. values['logged'] = 'on'
  72. partner = request.env.user.partner_id
  73. if partner.member or partner.old_member:
  74. values['already_cooperator'] = 'on'
  75. if partner.bank_ids:
  76. values['iban'] = partner.bank_ids[0].acc_number
  77. values['address'] = partner.street
  78. values['zip_code'] = partner.zip
  79. values['city'] = partner.city
  80. values['country_id'] = partner.country_id.id
  81. if is_company:
  82. # company values
  83. values['company_register_number'] = partner.company_register_number
  84. values['company_name'] = partner.name
  85. values['company_email'] = partner.email
  86. # contact person values
  87. representative = partner.get_representative()
  88. values['firstname'] = representative.firstname
  89. values['lastname'] = representative.lastname
  90. values['gender'] = representative.gender
  91. values['email'] = representative.email
  92. values['contact_person_function'] = representative.function
  93. values['no_registre'] = representative.national_register_number
  94. values['birthdate'] = self.get_date_string(representative.birthdate)
  95. values['lang'] = representative.lang
  96. values['phone'] = representative.phone
  97. else:
  98. values['firstname'] = partner.firstname
  99. values['lastname'] = partner.lastname
  100. values['email'] = partner.email
  101. values['gender'] = partner.gender
  102. values['no_registre'] = partner.national_register_number
  103. values['birthdate'] = self.get_date_string(partner.birthdate)
  104. values['lang'] = partner.lang
  105. values['phone'] = partner.phone
  106. return values
  107. def fill_values(self, values, is_company, logged, load_from_user=False):
  108. sub_req_obj = request.env['subscription.request']
  109. company = request.website.company_id
  110. products = self.get_products_share(is_company)
  111. if load_from_user:
  112. values = self.get_values_from_user(values, is_company)
  113. if is_company:
  114. values['is_company'] = 'on'
  115. if logged:
  116. values['logged'] = 'on'
  117. values['countries'] = self.get_countries()
  118. values['langs'] = self.get_langs()
  119. values['products'] = products
  120. fields_desc = sub_req_obj.sudo().fields_get(['company_type', 'gender'])
  121. values['company_types'] = fields_desc['company_type']['selection']
  122. values['genders'] = fields_desc['gender']['selection']
  123. values['company'] = company
  124. if not values.get('share_product_id'):
  125. for product in products:
  126. if product.default_share_product is True:
  127. values['share_product_id'] = product.id
  128. break
  129. if not values.get('share_product_id', False) and products:
  130. values['share_product_id'] = products[0].id
  131. if not values.get('country_id'):
  132. if company.default_country_id:
  133. values['country_id'] = company.default_country_id.id
  134. else:
  135. values['country_id'] = '21'
  136. if not values.get('activities_country_id'):
  137. if company.default_country_id:
  138. values['activities_country_id'] = company.default_country_id.id
  139. else:
  140. values['activities_country_id'] = '21'
  141. if not values.get('lang'):
  142. if company.default_lang_id:
  143. values['lang'] = company.default_lang_id.code
  144. return values
  145. def get_products_share(self, is_company):
  146. product_obj = request.env['product.template']
  147. products = product_obj.sudo().get_web_share_products(is_company)
  148. return products
  149. def get_countries(self):
  150. countries = request.env['res.country'].sudo().search([])
  151. return countries
  152. def get_langs(self):
  153. langs = request.env['res.lang'].sudo().search([])
  154. return langs
  155. def get_selected_share(self, kwargs):
  156. prod_obj = request.env['product.template']
  157. product_id = kwargs.get("share_product_id")
  158. return prod_obj.sudo().browse(int(product_id)).product_variant_ids[0]
  159. def validation(self, kwargs, logged, values, post_file):
  160. user_obj = request.env['res.users']
  161. sub_req_obj = request.env['subscription.request']
  162. redirect = "easy_my_coop.becomecooperator"
  163. email = kwargs.get('email')
  164. is_company = kwargs.get("is_company") == 'on'
  165. if is_company:
  166. is_company = True
  167. redirect = "easy_my_coop.becomecompanycooperator"
  168. email = kwargs.get('company_email')
  169. if ('g-recaptcha-response' not in kwargs
  170. or not request.website.is_captcha_valid(
  171. kwargs['g-recaptcha-response'])):
  172. values = self.fill_values(values, is_company, logged)
  173. values["error_msg"] = _("the captcha has not been validated,"
  174. " please fill in the captcha")
  175. return request.website.render(redirect, values)
  176. # Check that required field from model subscription_request exists
  177. required_fields = sub_req_obj.sudo().get_required_field()
  178. error = set(field for field in required_fields if not values.get(field)) #noqa
  179. if error:
  180. values = self.fill_values(values, is_company, logged)
  181. values["error_msg"] = _("Some mandatory fields have not "
  182. "been filled")
  183. values = dict(values, error=error, kwargs=kwargs.items())
  184. return request.website.render(redirect, values)
  185. if not logged and email:
  186. user = user_obj.sudo().search([('login', '=', email)])
  187. if user:
  188. values = self.fill_values(values, is_company, logged)
  189. values.update(kwargs)
  190. values["error_msg"] = _("There is an existing account for this"
  191. " mail address. Please login before "
  192. "fill in the form")
  193. return request.website.render(redirect, values)
  194. company = request.website.company_id
  195. if company.allow_id_card_upload:
  196. if not post_file:
  197. values = self.fill_values(values, is_company, logged)
  198. values.update(kwargs)
  199. values["error_msg"] = _("You need to upload a"
  200. " scan of your id card")
  201. return request.website.render(redirect, values)
  202. iban = kwargs.get("iban")
  203. valid = sub_req_obj.check_iban(iban)
  204. if not valid:
  205. values = self.fill_values(values, is_company, logged)
  206. values["error_msg"] = _("You iban account number"
  207. "is not valid")
  208. return request.website.render(redirect, values)
  209. if not is_company and 'no_registre' in required_fields:
  210. no_registre = re.sub('[^0-9a-zA-Z]+', '',
  211. kwargs.get("no_registre"))
  212. valid = sub_req_obj.check_belgian_identification_id(no_registre)
  213. if not valid:
  214. values = self.fill_values(values, is_company, logged)
  215. values["error_msg"] = _("You national register number "
  216. "is not valid")
  217. return request.website.render(redirect, values)
  218. values["no_registre"] = no_registre
  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 int(partner.cooperator_type) != share.id:
  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. required_fields = sub_req_obj.sudo().get_required_field()
  262. # List of file to add to ir_attachment once we have the ID
  263. post_file = []
  264. # Info to add after the message
  265. post_description = []
  266. values = {}
  267. for field_name, field_value in kwargs.items():
  268. if hasattr(field_value, 'filename'):
  269. post_file.append(field_value)
  270. elif (field_name in sub_req_obj._fields
  271. and field_name not in _BLACKLIST):
  272. values[field_name] = field_value
  273. # allow to add some free fields or blacklisted field like ID
  274. elif field_name not in _TECHNICAL:
  275. post_description.append("%s: %s" % (field_name, field_value))
  276. logged = kwargs.get("logged") == 'on'
  277. is_company = kwargs.get("is_company") == 'on'
  278. response = self.validation(kwargs, logged, values, post_file)
  279. if response is not True:
  280. return response
  281. already_coop = False
  282. if logged:
  283. partner = request.env.user.partner_id
  284. values['partner_id'] = partner.id
  285. already_coop = partner.member
  286. elif kwargs.get("already_cooperator") == 'on':
  287. already_coop = True
  288. values["already_cooperator"] = already_coop
  289. values["is_company"] = is_company
  290. lastname = kwargs.get("lastname").upper()
  291. firstname = kwargs.get("firstname").title()
  292. values["name"] = firstname + " " + lastname
  293. values["lastname"] = lastname
  294. values["firstname"] = firstname
  295. values["birthdate"] = datetime.strptime(kwargs.get("birthdate"),
  296. "%d/%m/%Y").date()
  297. values["source"] = "website"
  298. values["share_product_id"] = self.get_selected_share(kwargs).id
  299. if is_company:
  300. if kwargs.get("company_register_number", is_company):
  301. values["company_register_number"] = re.sub('[^0-9a-zA-Z]+',
  302. '',
  303. kwargs.get("company_register_number"))
  304. subscription_id = sub_req_obj.sudo().create_comp_sub_req(values)
  305. else:
  306. no_registre = re.sub('[^0-9a-zA-Z]+', '',
  307. kwargs.get("no_registre"))
  308. values["no_registre"] = no_registre
  309. if 'no_registre' in required_fields:
  310. no_registre = re.sub('[^0-9a-zA-Z]+', '',
  311. kwargs.get("no_registre"))
  312. values["no_registre"] = no_registre
  313. subscription_id = sub_req_obj.sudo().create(values)
  314. if subscription_id:
  315. for field_value in post_file:
  316. attachment_value = {
  317. 'name': field_value.filename,
  318. 'res_name': field_value.filename,
  319. 'res_model': 'subscription.request',
  320. 'res_id': subscription_id,
  321. 'datas': base64.encodestring(field_value.read()),
  322. 'datas_fname': field_value.filename,
  323. }
  324. attach_obj.sudo().create(attachment_value)
  325. return self.get_subscription_response(values, kwargs)