def oauth2callback(self, **kw): """ This route/function is called by Google when user Accept/Refuse the consent of Google """ state = json.loads(kw['state']) dbname = state.get('d') service = state.get('s') url_return = state.get('f') with registry(dbname).cursor() as cr: if kw.get('code'): request.env(cr, request.session.uid)['google.%s' % service].set_all_tokens(kw['code']) return redirect(url_return) elif kw.get('error'): return redirect("%s%s%s" % (url_return, "?error=", kw['error'])) else: return redirect("%s%s" % (url_return, "?error=Unknown_error"))
def get_entity_logo(self, entity_id=None, entity_code=None): try: entity_id = int(entity_id) except: entity_id = -1 entity_model = request.env['s2u.crm.entity'] if entity_id > 0: entity = entity_model.sudo().search([('id', '=', entity_id), ('entity_code', '=', entity_code)]) if not entity: entity_id = -1 status, headers, content = binary_content( model='s2u.crm.entity', id=entity_id, field='image', default_mimetype='image/jpeg', env=request.env(user=SUPERUSER_ID)) if not content: return request.render("website.404") if status == 304: return werkzeug.wrappers.Response(status=304) image_base64 = base64.b64decode(content) headers.append(('Content-Length', len(image_base64))) response = request.make_response(image_base64, headers) response.status = str(status) return response
def add(self, sub_domain, **kwargs): try: token = kwargs.get('token', None) res, wechat_user, entry = self._check_user(sub_domain, token) if res:return res new_address = request.env(user=1)['res.partner'].create({ 'parent_id': wechat_user.partner_id.id, 'name': kwargs['linkMan'], 'mobile': kwargs['mobile'], 'province_id': int(kwargs['provinceId']), 'city_id': int(kwargs['cityId']), 'district_id': int(kwargs['districtId']) if kwargs.get('districtId') else False, 'street': kwargs['address'], 'zip': kwargs['code'], 'type': 'delivery', 'is_default': json.loads(kwargs['isDefault']) }) address_ids = wechat_user.address_ids.filtered(lambda r: r.id != new_address.id) if address_ids: address_ids.write({'is_default': False}) return self.res_ok() except Exception as e: _logger.exception(e) return self.res_err(-1, e.name)
def get_create_context(namespace, model, canned_context): """Get the requested preconfigured context of the model specification. The canned context is used to preconfigure default values or context flags. That are used in a repetitive way in namespace for specific model. As this should, for performance reasons, not repeatedly result in calls to the persistence layer, this method is cached in memory. :param str namespace: The namespace to also validate against. :param str model: The model, for which we retrieve the configuration. :param str canned_context: The preconfigured context, which we request. :returns: A dictionary containing the requested context. :rtype: dict :raise: werkzeug.exceptions.HTTPException TODO: add description in which case """ cr, uid = request.cr, request.session.uid # Singleton by construction (_sql_constraints) openapi_access = request.env(cr, uid)['openapi.access'].search( [('model_id', '=', model), ('namespace_id.name', '=', namespace)]) assert len(openapi_access) == 1, "'openapi_access' is not a singleton, bad construction." # Singleton by construction (_sql_constraints) context = openapi_access.create_context_ids.filtered(lambda r: r['name'] == canned_context) assert len(context) == 1, "'context' is not a singleton, bad construction." if not context: raise werkzeug.exceptions.HTTPException(response=error_response(*CODE__canned_ctx_not_found)) return context
def index(self): req = request.httprequest event = req.headers['X-Github-Event'] c = EVENTS.get(event) if not c: _logger.warning('Unknown event %s', event) return 'Unknown event {}'.format(event) repo = request.jsonrequest['repository']['full_name'] env = request.env(user=1) secret = env['runbot_merge.repository'].search([ ('name', '=', repo), ]).project_id.secret if secret: signature = 'sha1=' + hmac.new(secret.encode('ascii'), req.get_data(), hashlib.sha1).hexdigest() if not hmac.compare_digest(signature, req.headers.get('X-Hub-Signature', '')): _logger.warning("Ignored hook with incorrect signature %s", req.headers.get('X-Hub-Signature')) return werkzeug.exceptions.Forbidden() return c(env, request.jsonrequest)
def update(self, sub_domain, **kwargs): try: token = kwargs.get('token', None) res, wechat_user, entry = self._check_user(sub_domain, token) if res:return res address = request.env(user=1)['res.partner'].browse(int(kwargs['id'])) if not address: return self.res_err(404) address.write({ 'name': kwargs['linkMan'] if kwargs.get('linkMan') else address.name, 'mobile': kwargs['mobile'] if kwargs.get('mobile') else address.mobile, 'province_id': int(kwargs['provinceId']) if kwargs.get('provinceId') else address.province_id.id, 'city_id': int(kwargs['cityId']) if kwargs.get('cityId') else address.city_id.id, 'district_id': int(kwargs['districtId']) if kwargs.get('districtId') else address.district_id.id, 'street': kwargs['address'] if kwargs.get('address') else address.street, 'zip': kwargs['code'] if kwargs.get('code') else address.zip, 'is_default': json.loads(kwargs['isDefault']) }) address_ids = wechat_user.address_ids.filtered(lambda r: r.id != address.id) if address_ids: address_ids.write({'is_default': False}) return self.res_ok() except Exception as e: _logger.exception(e) return self.res_err(-1, e.name)
def bind_mobile(self, sub_domain, token=None, encryptedData=None, iv=None, **kwargs): try: res, wechat_user, entry = self._check_user(sub_domain, token) if res:return res config = request.env['wxapp.config'].sudo() encrypted_data = encryptedData if not token or not encrypted_data or not iv: return self.res_err(300) app_id = config.get_config('app_id', sub_domain) secret = config.get_config('secret', sub_domain) if not app_id or not secret: return self.res_err(404) access_token = request.env(user=1)['wxapp.access_token'].search([ ('token', '=', token), ]) if not access_token: return self.res_err(901) session_key = access_token[0].session_key _logger.info('>>> decrypt: %s %s %s %s', app_id, session_key, encrypted_data, iv) user_info = get_decrypt_info(app_id, session_key, encrypted_data, iv) _logger.info('>>> bind_mobile: %s', user_info) wechat_user.write({'phone': user_info.get('phoneNumber')}) wechat_user.partner_id.write({'mobile': user_info.get('phoneNumber')}) return self.res_ok() except Exception as e: _logger.exception(e) return self.res_err(-1, str(e))
def render_student_tc_form_responce(self, **post): """ this method is use for getting responce from parent for conformation of tc form. :param post: :return: """ if post and 'TCCODE' in post and post.get('TCCODE'): env = request.env(user=SUPERUSER_ID) tc_object = env['trensfer.certificate'] tc_stud_record = tc_object.sudo().search( [('id', '=', post.get('TCCODE'))], limit=1) if tc_stud_record.id: tc_type = '' if 'select_type_tc' in post and post.get('select_type_tc'): tc_type = post.get('select_type_tc') tc_stud_record.sudo().write({ 'tc_form_filled': True, 'new_school_name': post.get('new_school_name'), 'reason_for_leaving': post.get('reason_leaving'), 'tc_type': tc_type }) if tc_stud_record.tc_form_filled == True: tc_stud_record.sudo().come_to_fee_balance_review() return http.request.render( "edsys_transfer_certificate.tc_request_success", {}) else: return http.request.render( "edsys_transfer_certificate.tc_request_fail", {})
def __init__(self): param = request.env()['ir.config_parameter'] self.wx_appid = param.get_param('wx_appid') or '' self.wx_AppSecret = param.get_param('wx_AppSecret') or '' from ..rpc import oa_client oa_client.init_oa_client(self.wx_appid, self.wx_AppSecret)
def binary_content(xmlid=None, model='ir.attachment', id=None, field='datas', unique=False, filename=None, filename_field='datas_fname', download=False, mimetype=None, default_mimetype='application/octet-stream', access_token=None, env=None): env = env if id: attachement_id = request.env['ir.attachment'].sudo().browse(id) if request.env.user.partner_id.id in attachement_id.partner_ids.ids: env = request.env(user=SUPERUSER_ID) return request.registry['ir.http'].binary_content( xmlid=xmlid, model=model, id=id, field=field, unique=unique, filename=filename, filename_field=filename_field, download=download, mimetype=mimetype, default_mimetype=default_mimetype, access_token=access_token, env=env)
def wxPay(self, sub_domain, **kwargs): try: ret, entry = self._check_domain(sub_domain) if ret: return ret token = kwargs.pop('token', None) total_fee = int(float(kwargs.pop('money')) * 100) nextAction = kwargs.pop('nextAction', None) actionJson = json.loads(nextAction) orderId = actionJson['id'] body = str(orderId) out_trade_no = get_order_code(orderId) access_token = request.env(user=1)['wxapp.access_token'].search([ ('token', '=', token), ]) if not access_token: return self.res_err(901) openid = access_token.open_id # return self.res_ok([entry.app_id, entry.wechat_pay_id, entry.wechat_pay_secret, openid]) wxPay = WXAppPay(entry.app_id, entry.wechat_pay_id, partner_key=entry.wechat_pay_secret, notify_url='http://erp.yunfc.net/yunfc/notify') # return self.res_ok([body, out_trade_no, total_fee, openid, wxPay.mch_id]) res = wxPay.unifiedorder(body=body, out_trade_no=out_trade_no, total_fee=total_fee, openid=openid) res.update({'orderId': orderId}) return self.res_ok(res) except Exception as e: _logger.exception(e) return self.res_err(-1, str(e))
def register(self, sub_domain, code=None, encryptedData=None, iv=None, **kwargs): ''' 用户注册 ''' try: ret, entry = self._check_domain(sub_domain) if ret:return ret encrypted_data = encryptedData if not code or not encrypted_data or not iv: return self.res_err(300) app_id = entry.get_config('app_id') secret = entry.get_config('secret') if not app_id or not secret: return self.res_err(404) session_key, user_info = get_wx_user_info(app_id, secret, code, encrypted_data, iv) if kwargs.get('userInfo'): user_info.update(json.loads(kwargs.get('userInfo'))) user_id = None if hasattr(request, 'user_id'): user_id = request.user_id vals = { 'name': user_info['nickName'], 'nickname': user_info['nickName'], 'open_id': user_info['openId'], 'gender': user_info['gender'], 'language': user_info['language'], 'country': user_info['country'], 'province': user_info['province'], 'city': user_info['city'], 'avatar_url': user_info['avatarUrl'], 'register_ip': request.httprequest.remote_addr, 'user_id': user_id, 'partner_id': user_id and request.env['res.users'].sudo().browse(user_id).partner_id.id or None, 'category_id': [(4, request.env.ref('oejia_weshop.res_partner_category_data_1').sudo().id)], } if user_id: vals['user_id'] = user_id vals['partner_id'] = request.env['res.users'].sudo().browse(user_id).partner_id.id vals.pop('name') try: wechat_user = request.env(user=1)['wxapp.user'].create(vals) except: import traceback;traceback.print_exc() return self.res_err(-99, u'账号状态异常') request.wechat_user = wechat_user request.entry = entry return self.res_ok() except AttributeError: return self.res_err(404) except Exception as e: _logger.exception(e) return self.res_err(-1, str(e))
def check_token(self, sub_domain, token=None, **kwargs): try: ret, entry = self._check_domain(sub_domain) if ret: return ret if not token: return self.res_err(300) if request.uid != request.env.ref('base.public_user').id: if str(request.uid) == token: _logger.info('>>> check_token user %s', request.env.user) return self.res_ok() access_token = request.env(user=1)['wxapp.access_token'].search([ ('token', '=', token), ]) if not access_token: return self.res_err(901) return self.res_ok() except Exception as e: _logger.exception(e) return self.res_err(-1, str(e))
def _serve_attachment(cls): env = request.env(user=SUPERUSER_ID) attach = env['ir.attachment'].get_serve_attachment( request.httprequest.path, extra_fields=['name', 'checksum']) if attach: wdate = attach[0]['__last_update'] datas = attach[0]['datas'] or b'' name = attach[0]['name'] checksum = attach[0]['checksum'] or hashlib.sha512( datas).hexdigest()[:64] # sha512/256 if (not datas and name != request.httprequest.path and name.startswith(('http://', 'https://', '/'))): return request.redirect(name, 301, local=False) response = werkzeug.wrappers.Response() response.last_modified = wdate response.set_etag(checksum) response.make_conditional(request.httprequest) if response.status_code == 304: return response response.mimetype = attach[0][ 'mimetype'] or 'application/octet-stream' response.data = base64.b64decode(datas) return response
def get_orignal_amount(self, amount): """ this method use to convert orignal amount --------------------------------------------- :param amount: get amount from payfort link :return: return orignal amount of payment. """ env = request.env(user=SUPERUSER_ID) active_payforts_rec = env['payfort.config'].sudo().search([ ('active', '=', 'True') ]) amount = float(amount) if len(active_payforts_rec) == 1: if active_payforts_rec.transaction_charg_amount > 0: transaction_charg_amount = active_payforts_rec.transaction_charg_amount else: transaction_charg_amount = 0.00 amount -= transaction_charg_amount # removed payfort charge amount if active_payforts_rec.charge > 0: dummy_amount = 100.00 + active_payforts_rec.charge act_amount = round(((amount / dummy_amount) * 100.00), 2) else: dummy_amount = 100.00 + 0.00 act_amount = round(((amount / dummy_amount) * 100.00), 2) return act_amount else: amount -= 0.00 dummy_amount = 100.00 + 0.00 act_amount = round(((amount / dummy_amount) * 100.00), 2) return act_amount
def bind_mobile(self, sub_domain, token=None, encryptedData=None, iv=None, **kwargs): ''' 绑定手机号码 ''' try: res, wechat_user, entry = self._check_user(sub_domain, token) if res: return res access_token = request.env(user=1)['wxapp.access_token'].search([ ('token', '=', token), ]) config = request.env['wxapp.config'].sudo() encrypted_data = encryptedData if not encrypted_data or not iv: return self.res_err(300) app_id = config.get_config('app_id', sub_domain) secret = config.get_config('secret', sub_domain) if not app_id or not secret: return self.res_err(404) crypt = WXBizDataCrypt(app_id, access_token.session_key) user_info = crypt.decrypt(encrypted_data, iv) wechat_user.write({'mobile': user_info['phoneNumber']}) return self.res_ok() except Exception as e: _logger.exception(e) return self.res_err(-1, e.name)
def reputation(self, sub_domain, **kwargs): try: postJsonString = kwargs.get('postJsonString') # orderId = kwargs.get('orderId', '') reputationsDict = json.loads(postJsonString) reputationsArr = reputationsDict.get('reputations') orderId = reputationsDict.get('orderId') # 判断有无评价 if not reputationsArr: return self.res_err(901) # 获取单条评价 reputations = reputationsArr[0] saleOrder = request.env(user=1)['sale.order'].search([('id', '=', orderId)]) if not saleOrder: return self.res_err(901) saleOrder.write({ 'customer_status': 'completed', 'reputation': 1, 'reputation_content': '非常愉快的一次购物!' }) return self.res_ok('success') except Exception as e: _logger.exception(e) return self.res_err(-1, str(e))
def delete(self, sub_domain, token=None, id=None, **kwargs): address_id = id try: res, wechat_user, entry = self._check_user(sub_domain, token) if res: return res if not address_id: return self.res_err(300) address = request.env(user=1)['res.partner'].browse( int(address_id)) if not address: return self.res_err(404) address.unlink() if wechat_user.address_ids: wechat_user.address_ids[0].write({'is_default': True}) return self.res_ok() except Exception as e: _logger.exception(e) return self.res_err(-1, str(e))
def get_model_for_read(model): """Fetch a model object from the environment optimized for read. Postgres serialization levels are changed to allow parallel read queries. To increase the overall efficiency, as it is unlikely this API will be used as a mass transactional interface. Rather we assume sequential and structured integration workflows. :param str model: The model to retrieve from the environment. :returns: the framework model if exist, otherwise raises. :rtype: odoo.models.Model :raise: werkzeug.exceptions.HTTPException if the model not found in env. """ cr, uid = request.cr, request.session.uid test_mode = request.registry.test_cr if not test_mode: # Permit parallel query execution on read # Contrary to ISOLATION_LEVEL_SERIALIZABLE as per Odoo Standard cr._cnx.set_isolation_level(ISOLATION_LEVEL_READ_COMMITTED) try: return request.env(cr, uid)[model] except KeyError: err = list(CODE__obj_not_found) err[2] = 'The "%s" model is not available on this instance.' % model raise werkzeug.exceptions.HTTPException(response=error_response(*err))
def avatar(self, res_model, res_id, partner_id): headers = [("Content-Type", "image/png")] status = 200 content = "R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" # default image is one white pixel if res_model in request.env: try: # if the current user has access to the document, get the partner avatar as sudo() request.env[res_model].browse(res_id).check_access_rule("read") if ( partner_id in request.env[res_model].browse(res_id).sudo().exists().message_ids.mapped("author_id").ids ): status, headers, _content = binary_content( model="res.partner", id=partner_id, field="image_medium", default_mimetype="image/png", env=request.env(user=SUPERUSER_ID), ) # binary content return an empty string and not a placeholder if obj[field] is False if _content != "": content = _content if status == 304: return werkzeug.wrappers.Response(status=304) except AccessError: pass image_base64 = base64.b64decode(content) headers.append(("Content-Length", len(image_base64))) response = request.make_response(image_base64, headers) response.status = str(status) return response
def avatar(self, res_model, res_id, partner_id): headers = [('Content-Type', 'image/png')] status = 200 content = 'R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' # default image is one white pixel if res_model in request.env: try: # if the current user has access to the document, get the partner avatar as sudo() request.env[res_model].browse(res_id).check_access_rule('read') if partner_id in request.env[res_model].browse(res_id).sudo( ).exists().message_ids.mapped('author_id').ids: status, headers, _content = binary_content( model='res.partner', id=partner_id, field='image_medium', default_mimetype='image/png', env=request.env(user=SUPERUSER_ID)) # binary content return an empty string and not a placeholder if obj[field] is False if _content != '': content = _content if status == 304: return werkzeug.wrappers.Response(status=304) except AccessError: pass image_base64 = base64.b64decode(content) headers.append(('Content-Length', len(image_base64))) response = request.make_response(image_base64, headers) response.status = str(status) return response
def jobs_apply(self, job, **kwargs): """A Method for the users to be able to apply for job. Args: job: The first parameter to fetch the job position. kwargs: The second parameter to get the details of the job applicant. Returns: It renders the template & creates a record for job application. """ error = {} default = {} env = request.env(context=dict(request.env.context, show_address=True, no_tag_br=True)) applicant_1 = request.env['hr.applicant'] \ .search([('partner_id', '=', request.env.user.partner_id.id)], limit=1, order='create_date desc') countries = env['res.country'].sudo().search([]) states = env['res.country.state'].sudo().search([]) if 'website_hr_recruitment_error' in request.session: error = request.session.pop('website_hr_recruitment_error') default = request.session.pop('website_hr_recruitment_default') return request.render("website_hr_recruitment.apply", { 'applicant': applicant_1, 'job': job, 'error': error, 'default': default, 'countries': countries, 'states': states, 'partner': request.env['res.users'].sudo().browse( request.uid).partner_id, })
def register(self, sub_domain, code=None, encryptedData=None, iv=None, **kwargs): ''' 用户注册 ''' try: ret, entry = self._check_domain(sub_domain) if ret:return ret config = request.env['wxapp.config'].sudo() encrypted_data = encryptedData if not code or not encrypted_data or not iv: return self.res_err(300) app_id = config.get_config('app_id', sub_domain) secret = config.get_config('secret', sub_domain) if not app_id or not secret: return self.res_err(404) session_key, user_info = get_wx_user_info(app_id, secret, code, encrypted_data, iv) user_id = None if hasattr(request, 'user_id'): user_id = request.user_id request.env(user=1)['wxapp.user'].create({ 'name': user_info['nickName'], 'open_id': user_info['openId'], 'gender': user_info['gender'], 'language': user_info['language'], 'country': user_info['country'], 'province': user_info['province'], 'city': user_info['city'], 'avatar_url': user_info['avatarUrl'], 'register_ip': request.httprequest.remote_addr, 'user_id': user_id, 'partner_id': user_id and request.env['res.users'].sudo().browse(user_id).partner_id.id or None, }) return self.res_ok() except AttributeError: return self.res_err(404) except Exception as e: _logger.exception(e) return self.res_err(-1, e.name)
def render_enquiry(self, **kwargs): """ this method is used to call webpage, also we pass the data we required in web form. ------------------------------------------ @param self : object pointer @param type : http @param auth : public @param website : True @return : call templet also pass dictonary for required data """ env = request.env(context=dict(request.env.context, show_address=True, no_tag_br=True)) country_obj = env['res.country'] state_obj = env['res.country.state'] academic_Year_obj = env['batch'] course_obj = env['course'] language_obj = env['res.lang'] religion_obj = env['religion'] # nationality_obj = env['nationality'] religion = [] course = [] batch = [] country = [] state = [] language = [] nationality=[] eff_date = '' min_max = '' for country_rec in country_obj.sudo().search([]): country.append(country_rec) for state_rec in state_obj.sudo().search([]): state.append(state_rec) for each in country_obj.sudo().search([]): nationality.append(each) for batch_rec in academic_Year_obj.sudo().search([]): eff_date += str(batch_rec.id) + ',' + str(batch_rec.effective_date) + ',' current_year = int(date.today().year) if int(str(batch_rec.start_date).split("-")[0]) >= current_year or int(str(batch_rec.end_date).split("-")[0]) == current_year: batch.append(batch_rec) for course_rec in course_obj.sudo().search([]): min_max += str(course_rec.id) + ',' + str(course_rec.min_age) + '|' + str(course_rec.max_age) + ',' course.append(course_rec) for lang in language_obj.sudo().search([]): language.append(lang) for reg in religion_obj.sudo().search([]): religion.append(reg) return http.request.render("website_student_enquiry.index", { 'country_id' : country, 'state_rec' : state, 'batch_rec' : batch, 'course_rec' : course, 'language_rec' : language, 'regligion_rec' : religion, 'nationality_id':nationality, 'eff_date': eff_date, 'min_max_age' : min_max, })
def list_providers(self): providers = super(AuthSignupHome, self).list_providers() weodoo_provider = request.env(user=1).ref('weodoo.provider_third') for provider in providers: if provider['id'] == weodoo_provider.id: provider['auth_link'] = self._get_auth_link_wo(provider) break return providers
def get(self, sub_domain, token=None, address_id=None, **kwargs): try: user = request.env['res.users'].sudo().search([('sub_domain', '=', sub_domain)]) if not user: return request.make_response(json.dumps({'code': 404, 'msg': error_code[404]})) if not token: return request.make_response(json.dumps({'code': 300, 'msg': error_code[300].format('token')})) if not address_id: return request.make_response(json.dumps({'code': 300, 'msg': error_code[300].format('address_id')})) access_token = request.env(user=user.id)['wechat_mall.access_token'].search([ ('token', '=', token), ('create_uid', '=', user.id) ]) if not access_token: return request.make_response(json.dumps({'code': 901, 'msg': error_code[901]})) if not access_token: return request.make_response(json.dumps({'code': 901, 'msg': error_code[901]})) wechat_user = request.env(user=user.id)['wechat_mall.user'].search([ ('open_id', '=', access_token.open_id), ('create_uid', '=', user.id) ]) if not wechat_user: return request.make_response(json.dumps({'code': 10000, 'msg': error_code[10000]})) address = request.env(user=user.id)['wechat_mall.address'].browse(int(address_id)) if not address: return request.make_response(json.dumps({'code': 404, 'msg': error_code[404]})) address.unlink() if wechat_user.address_ids: wechat_user.address_ids[0].write({'is_default': True}) return request.make_response(json.dumps({'code': 0, 'msg': 'success'})) except Exception as e: _logger.exception(e) return request.make_response(json.dumps({'code': -1, 'msg': error_code[-1], 'data': e.message}))
def check_userid(self, token, userid): if token and userid: _logger.info('>>> check_userid: %s %s', userid, token) access_token = request.env(user=1)['wxapp.access_token'].search([ ('token', '=', token), ]) if not access_token: return wechat_user = request.env(user=1)['wxapp.user'].search([ ('open_id', '=', access_token.open_id), ]) if not wechat_user: return if hasattr(wechat_user, 'user_id') and str( wechat_user.user_id.id) == str(userid): request.wechat_user = wechat_user
def get_task_url(self, key): env = request.env() Task = env['project.task'] tasks = Task.search([('key', '=ilike', key)]) url = "/my/task/%s" return url % (tasks and tasks.id or -1)
def list(self, sub_domain, default_banner=True, **kwargs): try: ret, entry = self._check_domain(sub_domain) if ret:return ret banner_list = request.env['wxxcx.banner'].sudo().search([ ('status', '=', True) ]) data = [] if banner_list: data = [ { "businessId": each_banner.business_id.id, "dateAdd": each_banner.create_date, "dateUpdate": each_banner.write_date, "id": each_banner.id, "linkUrl": each_banner.link_url or '', "paixu": each_banner.sort or 0, "picUrl": each_banner.get_main_image(), "remark": each_banner.remark or '', "status": 0 if each_banner.status else 1, "statusStr": '显示' if each_banner.status else '不显示', "title": each_banner.title, "type": each_banner.type_mark, "userId": each_banner.create_uid.id } for each_banner in banner_list ] recommend_goods = request.env(user=1)['course.template'].search([ ('recommend_status', '=', True), ('wxxcx_published', '=', True) ], limit=5) data += [ { "goods": True, "businessId": course.id, "dateAdd": course.create_date, "dateUpdate": course.write_date, "id": course.id, "linkUrl": '', "paixu": course.sequence or 0, "picUrl": course.get_main_image(), "remark": '', "status": 0 if course.wxxcx_published else 1, "statusStr": '', "title": course.name, "type": 0, "userId": course.create_uid.id } for course in recommend_goods ] return self.res_ok(data) except Exception as e: _logger.exception(e) return self.res_err(-1, e.message)
def oauth2callback(self, **kw): """ This route/function is called by Google when user Accept/Refuse the consent of Google """ state = json.loads(kw['state']) dbname = state.get('d') service = state.get('s') url_return = state.get('f') with registry(dbname).cursor() as cr: if kw.get('code'): request.env(cr, request.session.uid)['google.%s' % service].set_all_tokens( kw['code']) return redirect(url_return) elif kw.get('error'): return redirect("%s%s%s" % (url_return, "?error=", kw['error'])) else: return redirect("%s%s" % (url_return, "?error=Unknown_error"))
def sycn_position_survey(self, sub_domain,apply_id): applicant = request.env(user =1 )['hr.applicant'].browse([apply_id]) my_applicant = API.ApiPrd() sync_data = my_applicant.post_applicant(applicant) _logger.info("################%s######################" % sync_data) res = my_applicant.post_data(sync_data) _logger.info("################同步:%s######################" % res) if applicant and res == '1': applicant.write({"is_synced":True})
def render_page4(self, **post): """ this method store data from current(4) page, and redirect to page next page(5) ------------------------------------------ @param self : object pointer @param type : http @param auth : public @param website : True @return : """ env = request.env(context=dict(request.env.context, show_address=True, no_tag_br=True)) student_obj = env['res.partner'] student_rec = student_obj.sudo().browse(int(post.get('student_id'))) if not student_rec.id: return request.redirect("/student/verification/expired") else: student_data = { 'hobbies_interests': post.get('Hobbies_Interests') or '', 'has_play_any_musical_instrument': post.get('Has_Play_any_Musical_Instrument') or '', 'musical_instrument_details': post.get('Musical_Instrument_Details') or '', 'has_formal_training_in_music': post.get('Has_Formal_Training_in_Music') or '', 'training_in_music_details': post.get('Training_in_Music_Details') or '', 'sport_child_play': post.get('Sport_Child_Play') or '', 'has_training_or_interest_art': post.get('Has_Training_or_Interest_Art') or '', 'has_training_or_interest_art_details': post.get('Training_or_Interest_Art_Details') or '', 'inter_school_competitions': post.get('Inter_School_Competitions') or '', 'inter_school_competitions_details': post.get('Inter_School_Competitions_Details') or '', 'special_activity_interested': post.get('Special_Activity_Interested') or '', 'adjusts_new_situations_with_ease': self.get_check_box_value( post.get('Adjusts_New_Situations_with_Ease')) or '', 'has_small_group_of_friends': self.get_check_box_value( post.get('Has_Small_Group_of_Friends')) or '', 'has_never_adjust_new_situation': self.get_check_box_value( post.get('Has_Never_Adjust_New_Situation')) or '', 'has_many_friends': self.get_check_box_value( post.get('Has_Many_Friends')) or '', 'likes_be_active_in_school': self.get_check_box_value( post.get('Likes_be_Active_in_School')) or '', 'expressions_describe_your_child': post.get('Expressions_Describe_your_Child') or '', 'social_emotional_behavioural_difficulties': post.get('Social_Emotional_Behavioural_Difficulties') or '', 'social_emotional_behavioural_difficulties_details': post.get( 'Social_Emotional_Behavioural_Difficulties_Details') or '', 'useful_information_for_educating': post.get('Useful_Information_for_Educating') or '', 'person_to_call' : post.get('Person_to_Call') or '', 'emergency_relationship' : post.get('Emergency_Relationship') or '', 'emergency_contact' : post.get('Emergency_Tel_No') or '', 'has_use_bus_facility' : post.get('Has_Use_Bus_Facility') or '', 'pick_up' : post.get('Pick_Up') or '', } student_rec.sudo().write(student_data) reg_obj = env['registration'] reg_rec = reg_obj.sudo().search([('enquiry_no','=',student_rec.reg_no)],limit=1) reg_rec.sudo().write(student_data) e_page_code = base64.b64encode('5') e_student_id = base64.b64encode(str(post.get('student_id'))) return request.redirect("/student/verification/pagecode?page_code=%s&student_id=%s" % (e_page_code,e_student_id))
def jobs(self, country=None, department=None, office_id=None, **kwargs): env = request.env(context=dict(request.env.context, show_address=True, no_tag_br=True)) Country = env['res.country'] Jobs = env['hr.job'] # List jobs available to current UID job_ids = Jobs.search([], order="website_published desc,no_of_recruitment desc").ids # Browse jobs as superuser, because address is restricted jobs = Jobs.sudo().browse(job_ids) # Default search by user country if not (country or department or office_id or kwargs.get('all_countries')): country_code = request.session['geoip'].get('country_code') if country_code: countries_ = Country.search([('code', '=', country_code)]) country = countries_[0] if countries_ else None if not any(j for j in jobs if j.address_id and j.address_id.country_id == country): country = False # Filter job / office for country if country and not kwargs.get('all_countries'): jobs = [j for j in jobs if j.address_id is None or j.address_id.country_id and j.address_id.country_id.id == country.id] offices = set(j.address_id for j in jobs if j.address_id is None or j.address_id.country_id and j.address_id.country_id.id == country.id) else: offices = set(j.address_id for j in jobs if j.address_id) # Deduce departments and countries offices of those jobs departments = set(j.department_id for j in jobs if j.department_id) countries = set(o.country_id for o in offices if o.country_id) if department: jobs = (j for j in jobs if j.department_id and j.department_id.id == department.id) if office_id and office_id in map(lambda x: x.id, offices): jobs = (j for j in jobs if j.address_id and j.address_id.id == office_id) else: office_id = False # Render page return request.render("website_hr_recruitment.index", { 'jobs': jobs, 'countries': countries, 'departments': departments, 'offices': offices, 'country_id': country, 'department_id': department, 'office_id': office_id, })
def user_avatar(self, user_id=0, **post): status, headers, content = binary_content( model="res.users", id=user_id, field="image_medium", default_mimetype="image/png", env=request.env(user=SUPERUSER_ID), ) if not content: img_path = modules.get_module_resource("web", "static/src/img", "placeholder.png") with open(img_path, "rb") as f: image = f.read() content = image.encode("base64") if status == 304: return werkzeug.wrappers.Response(status=304) image_base64 = base64.b64decode(content) headers.append(("Content-Length", len(image_base64))) response = request.make_response(image_base64, headers) response.status = str(status) return response
def user_avatar(self, user_id=0, **post): status, headers, content = binary_content(model='res.users', id=user_id, field='image_medium', default_mimetype='image/png', env=request.env(user=SUPERUSER_ID)) if not content: img_path = modules.get_module_resource('web', 'static/src/img', 'placeholder.png') with open(img_path, 'rb') as f: image = f.read() content = base64.b64encode(image) if status == 304: return werkzeug.wrappers.Response(status=304) image_base64 = base64.b64decode(content) headers.append(('Content-Length', len(image_base64))) response = request.make_response(image_base64, headers) response.status = str(status) return response
def avatar(self, res_model, res_id, partner_id): headers = [('Content-Type', 'image/png')] status = 200 content = 'R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==' # default image is one white pixel if res_model in request.env: try: # if the current user has access to the document, get the partner avatar as sudo() request.env[res_model].browse(res_id).check_access_rule('read') if partner_id in request.env[res_model].browse(res_id).sudo().exists().message_ids.mapped('author_id').ids: status, headers, _content = binary_content(model='res.partner', id=partner_id, field='image_medium', default_mimetype='image/png', env=request.env(user=SUPERUSER_ID)) # binary content return an empty string and not a placeholder if obj[field] is False if _content != '': content = _content if status == 304: return werkzeug.wrappers.Response(status=304) except AccessError: pass if status == 301 and is_url(content): r = requests.get(content) image_base64 = r.content else: image_base64 = base64.b64decode(content) headers.append(('Content-Length', len(image_base64))) response = request.make_response(image_base64, headers) response.status = str(status) return response
def bundle(self): env = request.env(user=SUPERUSER_ID) bundle = env.ref('test_assetsbundle.bundle1') views = env['ir.ui.view'].search([('inherit_id', '=', bundle.id)]) return views.with_context(check_view_ids=views.ids).render_template('test_assetsbundle.template1')