def input_handle(message, session): content = message.content.lower() serviceid = message.target openid = message.source rs = request.env()['wx.autoreply'].sudo().search([]) for rc in rs: if rc.type == 1: if content == rc.key: return rc.action.get_wx_reply() elif rc.type == 2: if rc.key in content: return rc.action.get_wx_reply() elif rc.type == 3: try: flag = re.compile(rc.key).match(content) except: flag = False if flag: return rc.action.get_wx_reply() #客服对话 uuid = session.get("uuid", None) ret_msg = '' cr, uid, context, db = request.cr, request.uid or openerp.SUPERUSER_ID, request.context, request.db if not client.UUID_OPENID.has_key(db): client.UUID_OPENID[db] = {} if not uuid: Param = request.env()['ir.config_parameter'] channel_id = Param.get_param('wx_channel') or 0 channel_id = int(channel_id) info = client.wxclient.get_user_info(openid) anonymous_name = info.get('nickname', '微信网友') reg = openerp.modules.registry.RegistryManager.get(db) session_info = reg.get('im_livechat.channel').get_channel_session( cr, uid, channel_id, anonymous_name, context=context) if session_info: uuid = session_info['uuid'] session["uuid"] = uuid ret_msg = '请稍后,正在分配客服为您解答' if uuid: client.UUID_OPENID[db][uuid] = openid message_type = "message" message_content = content registry, cr, uid, context = request.registry, request.cr, request.session.uid, request.context message_id = registry["im_chat.message"].post(cr, openerp.SUPERUSER_ID, uid, uuid, message_type, message_content, context=context) return ret_msg
def website_info(self): admin_group_id = request.env().ref('base.group_erp_manager') is_admin_group = request.env()['res.groups'].search([ ('id', '=', admin_group_id.id), ('users', 'in', request.session._uid) ]) if not is_admin_group: return request.registry['ir.http']._handle_exception( 'Not found', 404) try: request.website.get_template('website.info').name except Exception, e: return request.registry['ir.http']._handle_exception(e, 404)
def input_handle(message, session): content = message.content.lower() serviceid = message.target openid = message.source rs = request.env()['wx.autoreply'].sudo().search([]) for rc in rs: if rc.type==1: if content==rc.key: return rc.action.get_wx_reply() elif rc.type==2: if rc.key in content: return rc.action.get_wx_reply() elif rc.type==3: try: flag = re.compile(rc.key).match(content) except:flag=False if flag: return rc.action.get_wx_reply() #客服对话 uuid = session.get("uuid", None) ret_msg = '' cr, uid, context, db = request.cr, request.uid or openerp.SUPERUSER_ID, request.context, request.db if not client.UUID_OPENID.has_key(db): client.UUID_OPENID[db] = {} if not uuid: Param = request.env()['ir.config_parameter'] channel_id = Param.get_param('wx_channel') or 0 channel_id = int(channel_id) info = client.wxclient.get_user_info(openid) anonymous_name = info.get('nickname','微信网友') reg = openerp.modules.registry.RegistryManager.get(db) session_info = reg.get('im_livechat.channel').get_channel_session(cr, uid, channel_id, anonymous_name, context=context) if session_info: uuid = session_info['uuid'] session["uuid"] = uuid ret_msg = '请稍后,正在分配客服为您解答' if uuid: client.UUID_OPENID[db][uuid] = openid message_type = "message" message_content = content registry, cr, uid, context = request.registry, request.cr, request.session.uid, request.context message_id = registry["im_chat.message"].post(cr,openerp.SUPERUSER_ID,uid, uuid, message_type, message_content, context=context) return ret_msg
def input_handle(message, session): from .. import client entry = client.wxenv(request.env) client = entry content = message.content.lower() serviceid = message.target openid = message.source _logger.info('>>> wx text msg: %s'%content) rs = request.env()['wx.autoreply'].sudo().search([]) for rc in rs: if rc.type==1: if content==rc.key: return rc.action.get_wx_reply() elif rc.type==2: if rc.key in content: return rc.action.get_wx_reply() elif rc.type==3: try: flag = re.compile(rc.key).match(content) except:flag=False if flag: return rc.action.get_wx_reply() #客服对话 uuid = client.OPENID_UUID.get(openid, None) ret_msg = '' cr, uid, context, db = request.cr, request.uid or openerp.SUPERUSER_ID, request.context, request.db if not uuid: rs = request.env['wx.user'].sudo().search( [('openid', '=', openid)] ) if not rs.exists(): info = client.wxclient.get_user_info(openid) info['group_id'] = '' wx_user = request.env['wx.user'].sudo().create(info) else: wx_user = rs[0] anonymous_name = wx_user.nickname channel = request.env.ref('oejia_wx.channel_wx') channel_id = channel.id session_info, ret_msg = request.env["im_livechat.channel"].create_mail_channel(channel_id, anonymous_name, content) if session_info: uuid = session_info['uuid'] client.OPENID_UUID[openid] = uuid client.UUID_OPENID[uuid] = openid wx_user.write({'last_uuid': uuid}) request.env['wx.user.uuid'].sudo().create({'openid': openid, 'uuid': uuid}) if uuid: message_type = "message" message_content = message.content request_uid = request.session.uid or openerp.SUPERUSER_ID author_id = False # message_post accept 'False' author_id, but not 'None' if request.session.uid: author_id = request.env['res.users'].sudo().browse(request.session.uid).partner_id.id mail_channel = request.env["mail.channel"].sudo(request_uid).search([('uuid', '=', uuid)], limit=1) message = mail_channel.sudo(request_uid).with_context(mail_create_nosubscribe=True).message_post(author_id=author_id, email_from=False, body=message_content, message_type='comment', subtype='mail.mt_comment', content_subtype='plaintext') return ret_msg
def avatar(self, res_model, res_id, partner_id): headers = [[('Content-Type', 'image/png')]] 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=openerp.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 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: openerp.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 Openerp 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 jobs_thankyou(self, **post): error = {} for field_name in ["partner_name", "phone", "email_from"]: if not post.get(field_name): error[field_name] = 'missing' if error: request.session['website_hr_recruitment_error'] = error ufile = post.pop('ufile') if ufile: error['ufile'] = 'reset' request.session['website_hr_recruitment_default'] = post return request.redirect('/jobs/apply/%s' % post.get("job_id")) # public user can't create applicants (duh) env = request.env(user=SUPERUSER_ID) value = { 'name': '%s\'s Application' % post.get('partner_name'), } for f in ['email_from', 'partner_name', 'description']: value[f] = post.get(f) for f in ['department_id', 'job_id']: value[f] = int(post.get(f) or 0) # Retro-compatibility for saas-3. "phone" field should be replace by "partner_phone" in the template in trunk. value['partner_phone'] = post.pop('phone', False) applicant = env['hr.applicant'].create(value) if post['ufile']: name = applicant.partner_name if applicant.partner_name else applicant.name applicant.message_post( body = _("%s's Application \n From: %s \n\n %s \n") % (name, applicant.email_from or "", applicant.description or ""), attachments = [(post['ufile'].filename, post['ufile'].read())], content_subtype = 'plaintext', subtype = "hr_recruitment.mt_applicant_hired") return request.render("website_hr_recruitment.thankyou", {})
class Website(openerp.addons.web.controllers.main.Home): @http.route('/website/info', type='http', auth="user", website=True) def website_info(self): admin_group_id = request.env().ref('base.group_erp_manager') is_admin_group = request.env()['res.groups'].search([ ('id', '=', admin_group_id.id), ('users', 'in', request.session._uid) ]) if not is_admin_group: return request.registry['ir.http']._handle_exception( 'Not found', 404) try: request.website.get_template('website.info').name except Exception, e: return request.registry['ir.http']._handle_exception(e, 404) irm = request.env()['ir.module.module'].sudo() apps = irm.search([('state', '=', 'installed'), ('application', '=', True)]) modules = irm.search([('state', '=', 'installed'), ('application', '=', False)]) values = { 'apps': apps, 'modules': modules, 'version': openerp.service.common.exp_version() } return request.render('website.info', values)
def _on_messages(self, uuid, session, from_uid, message_id, message_content, notifications): if hasattr(session, 'channel_id'): Param = request.env()['ir.config_parameter'] wx_channel_id = Param.get_param('wx_channel') or 0 wx_channel_id = int(wx_channel_id) if session.channel_id.id==wx_channel_id and from_uid: client.chat_send(request.db,uuid, message_content)
def offers(self, type=None, **kwargs): env = request.env(context=dict( request.env.context, show_address=True, no_tag_br=True)) offer_orm = env['project.offer'] # List Offers available to current UID offer_ids = offer_orm.search( [('state', '=', 'open')], order="website_published desc, date_open desc").ids # Browse Offers as superuser, because address is restricted offers = offer_orm.sudo().browse(offer_ids) # Deduce types and offices of those Offers types = set(j.type for j in offers if j.type) # Filter the matching one if type: offers = (j for j in offers if j.type and j.type.id == type.id) # Render page return request.website.render("website_project_submission.index", { 'offers': offers, 'types': types, 'type': type, })
def create(self, vals): if vals.get('name', '/') == '/': vals['name'] = self.env['ir.sequence'].get('sale.order') or '/' res = super(sale_order, self).create(vals) if not res.to_affcode_id: affcode_cookie = request.httprequest.cookies.get(AFFCODE_PARAM_NAME) if affcode_cookie: env = request.env(user=SUPERUSER_ID) affcode = env['to.affiliate.code'].search([('name', '=', affcode_cookie)], limit=1) if affcode: res.to_affcode_id = affcode.id if res.to_affcode_id: salesperson = res.to_affcode_id.saleperson_id if salesperson: res.user_id = salesperson.id company = res.to_affcode_id.company_id if company: res.company_id = company.id return res
def jobs_thankyou(self, **post): error = {} for field_name in ["name", "personal_email"]: if not post.get(field_name): error[field_name] = 'missing' env = request.env(user=SUPERUSER_ID) value = {} for f in [ 'personal_email', 'name', 'dob', 'age', 'gender', 'father_name', 'passport_no', 'place_of_birth', 'martial', 'mobile', 'nationality', 'mobile' ]: value[f] = post.get(f) for f in ['join_id']: join_id = int(post.get(f) or False) emp_join_form_rec = env['od.beta.joining.form'].browse(join_id) # Retro-compatibility for saas-3. "phone" field should be replace by "partner_phone" in the template in trunk. # value['partner_phone'] = post.pop('phone', False) emp_join_id = emp_join_form_rec.write(value) if post['ufile']: attachment_value = { 'name': post['ufile'].filename, 'res_name': value['name'], 'res_model': 'hr.applicant', 'res_id': join_id, 'datas': base64.encodestring(post['ufile'].read()), 'datas_fname': post['ufile'].filename, } env['ir.attachment'].create(attachment_value) return request.render("beta_customisation.beta_thankyou", {})
def home(self, **kw): env = request.env(context=dict( request.env.context, show_address=True, no_tag_br=True)) units_model = env['product.product'] units = units_model.search([('sale_ok', '=', True)]) shop_menu = env['website.menu'].search([('name', '=', 'Shop')]) contact_us = env['website.menu'].search([('name', '=', 'Contact us')]) shop_menu.unlink() contact_us.unlink() units_no = len(units) items_no = units_no / 4.00 items = int(math.ceil(items_no)) if items > 1: more_than_one = True return request.website.render( "website.homepage", { 'units': units, 'items': items, 'units_no': units_no, 'more_than_one': more_than_one, }) else: items = 1 return request.website.render("website.homepage", { 'units': units, 'items': items, 'units_no': units_no, })
def avatar(self, res_model, res_id, partner_id): headers = [[("Content-Type", "image/png")]] 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=openerp.SUPERUSER_ID), ) 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): content = None 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=openerp.SUPERUSER_ID)) if status == 304: return werkzeug.wrappers.Response(status=304) except AccessError: pass if content: image_base64 = base64.b64decode(content) else: binary = Binary() image_base64 = binary.placeholder( image='placeholder.png' ) # could return (contenttype, content) in master headers = binary.force_contenttype(headers, contenttype='image/png') headers.append(('Content-Length', len(image_base64))) response = request.make_response(image_base64, headers) response.status = str(status) return response
def onclick(message, session): _name, action_id = message.key.split(',') action_id = int(action_id) if _name: action = request.env()[_name].sudo().browse(action_id) ret = action.get_wx_reply() if is_string(ret): return create_reply(ret, message=message) elif isinstance(ret, list): return create_reply(ret, message=message) elif type(ret)==dict: media = ret media_type = media['media_type'] media_id = media['media_id'] from werobot.replies import ImageReply, VoiceReply, VideoReply, ArticlesReply if media_type=='image': return ImageReply(message=message, media_id=media_id).render() elif media_type=='voice': return VoiceReply(message=message, media_id=media_id).render() elif media_type=='video': return VideoReply(message=message, media_id=media_id).render() elif media_type=='news': from .. import client entry = client.wxenv(request.env) entry.wxclient.send_news_message(message.source, media_id)
def __init__(self): import client Param = request.env()["ir.config_parameter"] robot.config["TOKEN"] = Param.get_param("wx_token") or "K5Dtswpte" client.wxclient.appid = Param.get_param("wx_appid") or "" client.wxclient.appsecret = Param.get_param("wx_AppSecret") or ""
def school_class(self, class_id): class_1 = request.env()['school.standard'].sudo().search([('id', '=', class_id)]) print class_1 return env.get_template("class.html").render({ # 'databases': dbs, # 'debug': request.debug, 'sclass': class_1 })
def jobs(self, country=None, department=None, office_id=None, tag=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'] #Tags = env['x_job.tag'] # List jobs available to current UID job_ids = Jobs.search([], order="create_date desc").ids # Browse jobs as superuser, because address is restricted jobs = Jobs.sudo().browse(job_ids) # Deduce departments and offices of those jobs departments = set(j.department_id for j in jobs if j.department_id) offices = set(j.address_id for j in jobs if j.address_id) countries = set(o.country_id for o in offices if o.country_id) #tags = set(j.x_tag_ids for j in jobs if j.x_tag_ids) tags = {} for j in jobs: for t in j.x_tag_ids: if t in tags: tags[t] += 1 else: tags[t] = 1 # 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 the matching one 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) if department: jobs = (j for j in jobs if j.department_id and j.department_id.id == department.id) if office_id: jobs = (j for j in jobs if j.address_id and j.address_id.id == office_id) if tag: jobs = (j for j in jobs if j.x_tag_ids and tag in j.x_tag_ids) # Render page return request.website.render("website_hr_recruitment.index", { 'jobs': jobs, 'countries': countries, 'departments': departments, 'offices': offices, 'tag_ids': sorted(tags.items(), key=lambda x: x[1], reverse=True), 'country_id': country, 'department_id': department, 'office_id': office_id, 'tag': tag, })
def __init__(self): Param = request.env()['ir.config_parameter'] self.TOKEN = Param.get_param('wx_token') or 'K5Dtswpte' self.EncodingAESKey = Param.get_param('EncodingAESKey') or '' self.CorpId = Param.get_param('CorpId') or '' # 企业号 global crypto crypto = WeChatCrypto(self.TOKEN, self.EncodingAESKey, self.CorpId)
def newsletter_thankyou(self, **post): env = request.env() email = post.get('email') search_email = env['office.newsletter'].search([('email', '=', email)]) if not search_email: value = {'email': email} newsletter_id = env['office.newsletter'].create(value).id return request.redirect('/')
def jobs_thankyou(self, **post): error = {} for field_name in ["partner_name", "phone", "email_from"]: if not post.get(field_name): error[field_name] = 'missing' if error: request.session['website_hr_recruitment_error'] = error ufile = post.pop('ufile') if ufile: error['ufile'] = 'reset' request.session['website_hr_recruitment_default'] = post return request.redirect('/jobs/apply/%s' % post.get("job_id")) # public user can't create applicants (duh) env = request.env(user=SUPERUSER_ID) value = { 'name': '%s\'s Application' % post.get('partner_name'), } for f in ['email_from', 'partner_name', 'description']: value[f] = post.get(f) for f in ['department_id', 'job_id']: value[f] = int(post.get(f) or 0) # Retro-compatibility for saas-3. "phone" field should be replace by "partner_phone" in the template in trunk. value['partner_phone'] = post.pop('phone', False) # If the email is already known in our database, match it to the existing partner, else create a new one Partner = env['res.partner'] existing_partner = Partner.name_search( name=post.get('email_from').strip(), args=[('is_company', '=', False)], limit=1) if not existing_partner: value_partner = { 'name': post['partner_name'], 'email': post['email_from'], 'phone': value['partner_phone'], } partner = Partner.create(value_partner) value['partner_id'] = partner.id else: value['partner_id'] = existing_partner[0][0] # Create applicant applicant = env['hr.applicant'].create(value) if post['ufile']: name = applicant.partner_name if applicant.partner_name else applicant.name applicant.message_post( body=_("%s's Application \n From: %s \n\n %s \n") % (name, applicant.email_from or "", applicant.description or ""), attachments=[(post['ufile'].filename, post['ufile'].read())], content_subtype='plaintext', subtype="hr_recruitment.mt_applicant_hired") return request.render("website_hr_recruitment.thankyou", {})
def get_logo(self, company_id): env = request.env(user=request.uid) image_data = env['res.company'].sudo().browse(int(company_id)).logo # image_data = openerp.tools.image_resize_image(base64_source=image_data, size=(240, 80), encoding='base64', filetype='PNG') image_data = base64.b64decode(image_data) return request.make_response(image_data, [ ('Content-Type', 'image/png'), ('Content-Length', len(image_data)), ])
def _get_applicant_skils(self,skill_list): skill_ids=[] if (skill_list): env = request.env(user=SUPERUSER_ID) aplicant_skill=env['hr.applicant.skills'] skills = aplicant_skill.search([('name','in',skill_list)]) for sk in skills: skill_ids.append(sk[0]['id']) return skill_ids
def web_settings_dashboard_data(self, **kw): has_access_to_apps = request.registry['res.users'].has_group( request.cr, request.uid, 'access_apps.group_show_modules_menu') # issue: due to unknown reason has_group is always invoked with superuser as uid param in new API # has_access_to_apps = request.env.user.has_group('access_apps.group_show_modules_menu') request.env = request.env(user=SUPERUSER_ID) res = super(WebSettingsDashboardCustom, self).web_settings_dashboard_data(**kw) res['has_access_to_apps'] = has_access_to_apps return res
def unsubscribe(message): serviceid = message.target openid = message.source env = request.env() rs = env['wx.user'].sudo().search( [('openid', '=', openid)] ) if rs.exists(): rs.unlink() return "欢迎下次光临!"
def _on_messages(self, uuid, session, from_uid, message_id, message_content, notifications): if hasattr(session, 'channel_id'): Param = request.env()['ir.config_parameter'] wx_channel_id = Param.get_param('wx_channel') or 0 wx_channel_id = int(wx_channel_id) Corp_Channel_id = Param.get_param('Corp_Channel') or 0 Corp_Channel_id = int(Corp_Channel_id) Corp_Agent = Param.get_param('Corp_Agent') or 0 Corp_Agent = int(Corp_Agent) if from_uid: session_channel_id = session.channel_id.id if session_channel_id and session_channel_id==wx_channel_id: from ..controllers import client client.chat_send(request.db, uuid, message_content) elif session_channel_id and session_channel_id==Corp_Channel_id: from ..rpc import corp_client corp_client.chat_send(request.db, uuid, message_content) else: session_users = session.user_ids from_user = [e for e in session_users if e.id==from_uid][0] for user in session.user_ids: if user.id==from_uid: continue _partner = user.partner_id if _partner.wxcorp_user_id: from ..rpc import corp_client _key = '%s-%s'%(request.db, user.id) new_flag = False if _key in corp_client.UID_UUID: _data = corp_client.UID_UUID[_key] _now = datetime.datetime.now() if _now - _data['last_time']<= datetime.timedelta(seconds=10*60): if _data['from'] == from_uid: message_content = u'%s:%s'%(from_user.name, message_content) new_flag = True else: message_content = u'%s:%s'%(from_user.name, message_content) else: message_content = u'%s:%s\n (10分钟内可直接回复)'%(from_user.name, message_content) new_flag = True else: message_content = u'%s:%s\n (10分钟内可直接回复)'%(from_user.name, message_content) new_flag = True # 全新 if new_flag: if _key not in corp_client.UID_UUID: corp_client.UID_UUID[_key] = {} corp_client.UID_UUID[_key]['from'] = from_uid corp_client.UID_UUID[_key]['last_time'] = datetime.datetime.now() corp_client.UID_UUID[_key]['uuid'] = uuid try: corp_client.client.message.send_text(Corp_Agent, _partner.wxcorp_user_id.userid, message_content) except: pass
def property(self, **post): env = request.env(context=dict( request.env.context, show_address=True, no_tag_br=True)) form_fields = [ 'name', 'property_type', 'min_beds', 'max_beds', 'min_price', 'max_price' ] search_fields = {} for field in form_fields: if post.get(field): search_fields[field] = post.get(field) if not search_fields: properties = env['product.product'].search([('sale_ok', '=', True) ]) else: fields = [] for key, value in search_fields.iteritems(): if key == 'min_price': fields.append(('list_price', '>=', value)) elif key == 'max_price': fields.append(('list_price', '<=', value)) elif key == 'min_beds': fields.append(('bed_rooms', '>=', value)) elif key == 'max_beds': fields.append(('bed_rooms', '<=', value)) elif key == 'name': fields.append((key, 'like', '%' + value + '%')) else: fields.append((key, "=", value)) print fields properties = env['product.product'].search(fields) properties_no = len(properties) items_no = properties_no / 9.00 items = int(math.ceil(items_no)) list_items_no = properties_no / 4.00 list_items = int(math.ceil(list_items_no)) more_than_one = False more_than_one_list = False if items > 1: more_than_one = True else: items = 1 if list_items > 1: more_than_one_list = True else: items = 1 return request.website.render( "website.property", { 'properties': properties, 'properties_no': properties_no, 'items': items, 'more_than_one': more_than_one, 'list_items': list_items, 'more_than_one_list': more_than_one_list, })
def unsubscribe(message): serviceid = message.target openid = message.source env = request.env() rs = env['wx.user'].sudo().search([('openid', '=', openid)]) if rs.exists(): # rn:计划修改为发往用户订阅状态,而不是删除 rs.write({'subscribe': False}) # rs.unlink() return "欢迎下次光临!"
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( [('website_published', '=', True)], order="website_published desc,no_of_recruitment desc").ids # Browse jobs as superuser, because address is restricted jobs = Jobs.sudo().browse(job_ids) # Deduce departments and offices of those jobs departments = set(j.department_id for j in jobs if j.department_id) offices = set(j.address_id for j in jobs if j.address_id) countries = set(o.country_id for o in offices if o.country_id) # 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 the matching one 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) if department: jobs = (j for j in jobs if j.department_id and j.department_id.id == department.id) if office_id: jobs = (j for j in jobs if j.address_id and j.address_id.id == office_id) # Render page return request.website.render( "website_hr_recruitment.index", { 'jobs': jobs, 'countries': countries, 'departments': departments, 'offices': offices, 'country_id': country, 'department_id': department, 'office_id': office_id, })
def __init__(self): Param = request.env()['ir.config_parameter'] self.TOKEN = Param.get_param('Corp_Token') or 'NN07w58BUvhuHya' self.EncodingAESKey = Param.get_param('Corp_AESKey') or 'esGH2pMM98SwPMMQpXPG5Y5QawuL67E2aBvNP10V8Gl' self.CorpId = Param.get_param('Corp_Id') or '' # 企业号 self.Secret = Param.get_param('Corp_Secret') or '' global crypto crypto = WeChatCrypto(self.TOKEN, self.EncodingAESKey, self.CorpId) from ..rpc import corp_client corp_client.init_client(self.CorpId, self.Secret)
def subscribe(message): serviceid = message.target openid = message.source info = client.wxclient.get_user_info(openid) info['group_id'] = str(info['groupid']) env = request.env() rs = env['wx.user'].sudo().search( [('openid', '=', openid)] ) if not rs.exists(): env['wx.user'].sudo().create(info) return "您终于来了!欢迎关注"
def subscribe(message): serviceid = message.target openid = message.source info = client.wxclient.get_user_info(openid) info['group_id'] = str(info['groupid']) env = request.env() rs = env['wx.user'].sudo().search([('openid', '=', openid)]) if not rs.exists(): env['wx.user'].sudo().create(info) return "您终于来了!欢迎关注"
def __init__(self): Param = request.env()['ir.config_parameter'] self.TOKEN = Param.get_param('Corp_Token') or 'NN07w58BUvhuHya' self.EncodingAESKey = Param.get_param( 'Corp_AESKey') or 'esGH2pMM98SwPMMQpXPG5Y5QawuL67E2aBvNP10V8Gl' self.CorpId = Param.get_param('Corp_Id') or '' # 企业号 self.Secret = Param.get_param('Corp_Secret') or '' global crypto crypto = WeChatCrypto(self.TOKEN, self.EncodingAESKey, self.CorpId) from ..rpc import corp_client corp_client.init_client(self.CorpId, self.Secret)
def get_authorization_code(self, **kwargs): """ Allow to catch the authorization code form Microsoft. """ state = json.loads(kwargs['state']) dbname = state.get('d') # service = state.get('s') # url_return = state.get('f') with registry(dbname).cursor() as cr: if kwargs.get('code'): request.env(cr, request.session.uid )['knowledge.config.settings'].get_refresh_token( kwargs['code']) # return redirect(url_return) elif kwargs.get('error'): # return redirect("%s%s%s" % (url_return, "?error=", kwargs['error'])) return redirect("%s%s" % ("?error=", kwargs['error'])) else: # return redirect("%s%s" % (url_return, "?error=Unknown_error")) return redirect("%s" % ("?error=Unknown_error"))
def checkout_parse(self, address_type, data, remove_prefix=False): values = super(website_sale, self).checkout_parse(address_type, data, remove_prefix=remove_prefix) affcode_cookie = request.httprequest.cookies.get(AFFCODE_PARAM_NAME) if affcode_cookie: env = request.env(user=SUPERUSER_ID) affcode = env['to.affiliate.code'].search( [('name', '=', affcode_cookie)], limit=1) if affcode: values.update({'to_affcode_id': affcode.id}) return values
def jobs_thankyou(self, **post): error = {} for field_name in ["partner_name", "phone", "email_from"]: if not post.get(field_name): error[field_name] = 'missing' if error: request.session['website_hr_recruitment_error'] = error ufile = post.pop('ufile') if ufile: error['ufile'] = 'reset' request.session['website_hr_recruitment_default'] = post return request.redirect('/jobs/apply/%s' % post.get("job_id")) # public user can't create applicants (duh) env = request.env(user=SUPERUSER_ID) value = { 'name': '%s\'s Application' % post.get('partner_name'), } for f in ['email_from', 'partner_name', 'description']: value[f] = post.get(f) for f in ['department_id', 'job_id']: value[f] = int(post.get(f) or 0) # Retro-compatibility for saas-3. "phone" field should be replace by "partner_phone" in the template in trunk. value['partner_phone'] = post.pop('phone', False) # If the email is already known in our database, match it to the existing partner, else create a new one Partner = env['res.partner'] existing_partner = Partner.name_search(name=post.get('email_from').strip(), args=[('is_company', '=', False)], limit=1) if not existing_partner: value_partner = { 'name': post['partner_name'], 'email': post['email_from'], 'phone': value['partner_phone'], } partner = Partner.create(value_partner) value['partner_id'] = partner.id else: value['partner_id'] = existing_partner[0][0] # Create applicant applicant = env['hr.applicant'].create(value) if post['ufile']: name = applicant.partner_name if applicant.partner_name else applicant.name applicant.message_post( body = _("%s's Application \n From: %s \n\n %s \n") % (name, applicant.email_from or "", applicant.description or ""), attachments = [(post['ufile'].filename, post['ufile'].read())], content_subtype = 'plaintext', subtype = "hr_recruitment.mt_applicant_hired") return request.render("website_hr_recruitment.thankyou", {})
def town(self,town_id): # cr, uid, session = request.cr, request.uid, request.session # if not session.uid: # return login_redirect(MODULE_BASE_PATH) # partners = request.registry.get("res.partner") # ids = partners.search(cr, uid, [('id', '=', id)]) # obj = partners.browse(cr, uid, ids) town=request.env()['res.country.county.town'].sudo().search([('id','=',town_id)]) return env.get_template("town.html").render({ # 'databases': dbs, # 'debug': request.debug, 'town': town })
def affiliate_register(self, user=None, **kwargs): env = request.env(user=SUPERUSER_ID) res_company = env['res.company'].search([]) values = {} aff_code = False if user and user.partner_id.to_is_affiliate: aff_code = env['to.affiliate.code'].search( [('partner_id', '=', user.partner_id.id)], limit=1) values.update(kwargs={ 'to_res_company': res_company, 'user': user, 'aff_code': aff_code }) return request.website.render("to_affiliate_manager.to_affiliate", values)
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 freshers(self, **kwargs): env = request.env(context=dict(request.env.context, no_tag_br=True)) Freshers = env['hr.applicant'] # List jobs available to current UID fresher_ids = Freshers.search([]).ids # Browse jobs as superuser, because address is restricted freshers = Freshers.sudo().browse(fresher_ids) # Deduce departments and offices of those jobs name = set(n.name for n in freshers if n.name) # Render page return request.website.render("website_freshers.index", { 'freshers': freshers, 'name':name, })
def sms_authentication_new_code(self, code_id, **kwargs): if not code_id: return request.website.render('website.404') env = request.env(context=dict(request.context)) values = dict(kwargs) error = {} code_obj = env['sms.authentication'] code = code_obj.sudo().search([('id', '=', code_id)], limit=1) if not code: return request.website.render('website.404') code = code.send_new_code() values.update({ 'code': code, 'error': error, }) return request.website.\ render('website_sms_authentication.sms_authentication', values)
def jobs_thankyou(self, **post): error = {} for field_name in ["partner_name", "phone", "email_from", "port_register_no", "seaman_book_no", "passport_validity_date", "police_validity_date", "health_validity_date", 'seaman_validity_date', 'security_date']: if not post.get(field_name): error[field_name] = 'missing' if error: request.session['website_hr_recruitment_error'] = error ufile = post.pop('ufile') if ufile: error['ufile'] = 'reset' request.session['website_hr_recruitment_default'] = post return request.redirect('/jobs/apply/%s' % post.get("job_id")) # public user can't create applicants (duh) env = request.env(user=SUPERUSER_ID) value = { 'source_id': env.ref('hr_recruitment.source_website_company').id, 'name': '%s\'s ' % post.get('partner_name'), } for f in ['email_from', 'partner_name', 'port_register_no', 'description', 'seaman_book_no', 'passport_validity_date', 'seaman_validity_date', 'police_validity_date', 'health_validity_date', 'security_date', 'base_stcw_date', 'shift_date', 'life_saving_date', 'guv_zbt_date', 'mk_zbt_date']: value[f] = post.get(f) for f in ['department_id', 'job_id', 'stcw_id']: value[f] = int(post.get(f) or 0) # Retro-compatibility for saas-3. "phone" field should be replace by # "partner_phone" in the template in trunk. value['partner_phone'] = post.pop('phone', False) applicant_id = env['hr.applicant'].create(value).id if post['ufile']: attachment_value = { 'name': post['ufile'].filename, 'res_name': value['partner_name'], 'res_model': 'hr.applicant', 'res_id': applicant_id, 'datas': base64.encodestring(post['ufile'].read()), 'datas_fname': post['ufile'].filename, } env['ir.attachment'].create(attachment_value) return request.render("website_hr_recruitment.thankyou", {})
def company_save(self, **post): error = {} for field_name in ["name"]: if not post.get(field_name): error[field_name] = 'missing' if error: request.session['website_freshers_error'] = error request.session['website_freshers_default'] = post return request.redirect('/freshers/create_company/%s' % post.get("fresher_id")) # public user can't create applicants (duh) env = request.env(user=SUPERUSER_ID) value = { 'name': '%s\'s Application' % post.get('partner_name'), } contact_value = { 'type':'contact', 'use_parent_address':True, 'name': post.pop('contact_name'), 'email': post.pop('contact_email'), 'mobile': post.pop('contact_mobile'), } username=post.pop('name', False) value['name'] = username value['street'] = post.pop('street', False) value['city'] = post.pop('city', False) value['phone'] = post.pop('phone', False) value['email'] = post.pop('email', False) value['district_id'] = post.pop('district_id', False) value['state_id'] = post.pop('state_id', False) value['country_id'] = post.pop('country_id', False) value['is_company'] = True value['child_ids'] = [(0,0,contact_value)] partner_id=env['res.partner'].create(value).id if partner_id: value={} value['name']= username value['active']= True value['login'] = post.pop('login', False) value['password']= post.pop('password', False) value['partner_id']=partner_id env['res.users'].create(value).id return request.render("website_freshers.index", {})
def theme_customize(self, enable, disable, get_bundle=False): """ enable or Disable lists of ``xml_id`` of the inherit templates """ cr, uid, context, pool = request.cr, request.uid, request.context, request.registry view = pool["ir.ui.view"] context = dict(request.context or {}, active_test=True) def set_active(ids, active): if ids: view.write(cr, uid, self.get_view_ids(ids), {'active': active}, context=context) set_active(disable, False) set_active(enable, True) if get_bundle: bundle = AssetsBundle('web.assets_frontend', env=request.env(context={})) return bundle.to_html() return True
def freshers_thankyou(self, **post): error = {} for field_name in ["name"]: if not post.get(field_name): error[field_name] = 'missing' if error: request.session['website_freshers_error'] = error request.session['website_freshers_default'] = post return request.redirect('/freshers/create/%s' % post.get("fresher_id")) # public user can't create applicants (duh) env = request.env(user=SUPERUSER_ID) value = { 'name': '%s\'s Application' % post.get('partner_name'), } username=post.pop('name', False) value['name'] = username value['partner_name']= post.pop('partner_name', False) value['email_from']=post.pop('email_from', False) value['partner_phone']= post.pop('partner_phone', False) # file=post['ufile'] env['hr.applicant'].create(value).id # if file and partner_id: # attachment_value = { # 'name': post['ufile'].filename, # 'res_name': value['partner_name'], # 'res_model': 'hr.applicant', # 'res_id': partner_id, # 'datas': base64.encodestring(post['ufile'].read()), # 'datas_fname': post['ufile'].filename, # } # env['ir.attachment'].create(attachment_value) value={} value['name']= username value['active']= True value['login'] = post.pop('login', False) value['password']= post.pop('password', False) value['partner_id']='' env['res.users'].create(value).id return request.render("website_freshers.index", {})
def confirm_order(self, **post): """add to confirm_order the attachment.""" cr, uid, context = request.cr, request.uid, request.context order = request.website.sale_get_order(context=context) if not order: return request.redirect("/shop") redirection = self.checkout_redirection(order) if redirection: return redirection values = self.checkout_values(post) values["error"] = self.checkout_form_validate(values["checkout"]) if values["error"]: return request.website.render("website_sale.checkout", values) self.checkout_form_save(values["checkout"]) request.session['sale_last_order_id'] = order.id request.website.sale_get_order(update_pricelist=True, context=context) error = {} if error: request.session['bp_checkout_file_upload_error'] = error ufile = post.pop('ufile') if ufile: error['ufile'] = 'reset' request.session['bp_checkout_file_upload_default'] = post return request.redirect('/shop/checkout') env = request.env(user=SUPERUSER_ID) if post['ufile']: attachment_value = { 'name': post['ufile'].filename, 'res_name': post['name'], 'res_model': 'sale.order', 'res_id': order.id, 'datas': base64.encodestring(post['ufile'].read()), 'datas_fname': post['ufile'].filename, } env['ir.attachment'].create(attachment_value) return request.redirect("/shop/payment")
def jobs_thankyou(self, **post): error = {} for field_name in ["partner_name", "phone", "email_from"]: if not post.get(field_name): error[field_name] = 'missing' if error: request.session['website_hr_recruitment_error'] = error ufile = post.pop('ufile') if ufile: error['ufile'] = 'reset' request.session['website_hr_recruitment_default'] = post return request.redirect('/jobs/apply/%s' % post.get("job_id")) # public user can't create applicants (duh) env = request.env(user=SUPERUSER_ID) value = { 'source_id' : env.ref('hr_recruitment.source_website_company').id, 'name': '%s\'s Application' % post.get('partner_name'), } for f in self._get_applicant_char_fields(): value[f] = post.get(f) for f in self._get_applicant_relational_fields(): value[f] = int(post.get(f) or 0) for f in self._get_applicant_one2many_fields(): value[f] = post.get(f) # Retro-compatibility for saas-3. "phone" field should be replace by "partner_phone" in the template in trunk. value['partner_phone'] = post.pop('phone', False) applicant_id = env['hr.applicant'].create(value).id if post['ufile']: attachment_value = { 'name': post['ufile'].filename, 'res_name': value['partner_name'], 'res_model': 'hr.applicant', 'res_id': applicant_id, 'datas': base64.encodestring(post['ufile'].read()), 'datas_fname': post['ufile'].filename, } env['ir.attachment'].create(attachment_value) return request.render("website_hr_recruitment.thankyou", {})
def college_save(self, **post): error = {} for field_name in ["name"]: if not post.get(field_name): error[field_name] = 'missing' if error: request.session['website_freshers_error'] = error request.session['website_freshers_default'] = post return request.redirect('/freshers/create_college/%s' % post.get("fresher_id")) # public user can't create applicants (duh) env = request.env(user=SUPERUSER_ID) value = { 'name': '%s\'s Application' % post.get('partner_name'), } username=post.pop('name', False) value['name'] = username value['email']= post.pop('email', False) value['mobile']= post.pop('mobile', False) value['country_id']= post.pop('country_id', False) value['state_id']= post.pop('state_id', False) value['street']= post.pop('street', False) value['city']= post.pop('city', False) value['accreditation']= post.pop('accreditation', False) value['year_of_establishemnt']= post.pop('year_of_establishemnt', False) value['avail_courses']= post.pop('avail_courses', False) value['college_dec']= post.pop('college_dec', False) value['about_management']= post.pop('about_management', False) value['is_college']=True partner_id=env['res.partner'].create(value).id if partner_id: value={} value['name']= username value['active']= True value['login'] = post.pop('login', False) value['password']= post.pop('password', False) value['partner_id']=partner_id env['res.users'].create(value).id return request.render("website_freshers.index", {})
def sms_authentication(self, code_id, **kwargs): if not code_id: return request.website.render('website.404') env = request.env(context=dict(request.context)) values = dict(kwargs) error = {} code_obj = env['sms.authentication'] code = code_obj.sudo().search([('id', '=', code_id)], limit=1) if not code: return request.website.render('website.404') if code.validity <= fields.Datetime.now() or code.state == 'cancel': error['expired'] = True values.update({ 'code': code, 'error': error, }) return request.website.\ render('website_sms_authentication.sms_authentication', values) for field in ['code']: if kwargs.get(field): values[field] = kwargs.pop(field) written_code = 'code' in values and values['code'] and \ values.pop('code') or False if not written_code: pass elif not code.verify_code(written_code): error['wrong_code'] = True else: values = self.preRenderThanks(code, values, kwargs) return self.callback_sms(code, values, kwargs) values.update({ 'code': code, 'error': error, }) return request.website.\ render('website_sms_authentication.sms_authentication', values)
def create_lead(self, request, values, kwargs): # Create a new Lead with correct Sales Team # FIXME: request.registry is depricated - should use request.env instead values['section_id'] = request.env.ref('website.salesteam_website_sales').id newlead = request.registry['crm.lead'].create(request.cr, SUPERUSER_ID, values, request.context) # Get a Recordset from crm.lead - in this case a singleton for the new lead # Create an additional environment with user superuser env = request.env(user=SUPERUSER_ID) leadrecord = env['crm.lead'].browse(newlead) # Search if a res.partner with the same E-Mail or with an similar name exists and add this to the # lead. If more then one partner is found assign none for safety (assign it manually later) partners = request.env['res.partner'].search([('email', '=', values['email_from'])]) if len(partners.ids) == 1: leadrecord.partner_id = partners.id if len(partners.ids) == 0: partners = request.env['res.partner'].search([('name', 'ilike', values['contact_name'])]) if len(partners.ids) == 1: leadrecord.partner_id = partners.id # Post a New Message to this record # Todo use a Mail-Template (so translation would be working too!) recordtext = 'Neue Webanfrage: \n\nVon: %s\nE-Mail: %s\nPhone: %s\nFirma: %s\n\nBetreff: %s\nNachricht: %s' % ( values['contact_name'], values['email_from'], values['phone'], values['partner_name'], values['name'], values['description'], ) leadrecord.message_post(body=recordtext, subject=values['name'], type='notification', subtype='mail.mt_comment', content_subtype='plaintext') return newlead
def avatar(self, res_model, res_id, partner_id): headers = [[('Content-Type', 'image/png')]] 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=openerp.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
# Sitemaps must be split in several smaller files with a sitemap index content = iuv.render(cr, uid, 'website.sitemap_index_xml', dict( pages=range(1, pages + 1), url_root=request.httprequest.url_root, ), context=context) create_sitemap('/sitemap.xml', content) return request.make_response(content, [('Content-Type', mimetype)]) @http.route('/website/info', type='http', auth="public", website=True) def website_info(self): try: request.website.get_template('website.info').name except Exception, e: return request.registry['ir.http']._handle_exception(e, 404) irm = request.env()['ir.module.module'].sudo() apps = irm.search([('state','=','installed'),('application','=',True)]) modules = irm.search([('state','=','installed'),('application','=',False)]) values = { 'apps': apps, 'modules': modules, 'version': openerp.service.common.exp_version() } return request.render('website.info', values) #------------------------------------------------------ # Edit #------------------------------------------------------ @http.route('/website/add/<path:path>', type='http', auth="user", website=True) def pagenew(self, path, noredirect=False, add_menu=None): xml_id = request.registry['website'].new_page(request.cr, request.uid, path, context=request.context)
def __init__(self): import client Param = request.env()['ir.config_parameter'] robot.config["TOKEN"] = Param.get_param('wx_token') or 'K5Dtswpte' client.wxclient.appid = Param.get_param('wx_appid') or '' client.wxclient.appsecret = Param.get_param('wx_AppSecret') or ''
def __init__(self): Param = request.env()['ir.config_parameter'] self.TOKEN = Param.get_param('wx_token') or 'K5Dtswpte' self.AES_KEY = Param.get_param('AES_KEY') or '' self.APPID = Param.get_param('APPID') or '' # 公众号
def jobs_thankyou(self, **post): error = {} for field_name in ["salutation", "first_name", "last_name", "partner_address", "place", "partner_phone", "email_from", "cover_letter", "curriculum_vitae"]: if not post.get(field_name): error[field_name] = 'missing' if error: request.session['website_hr_recruitment_error'] = error cover_letter = post.pop('cover_letter') curriculum_vitae = post.pop('curriculum_vitae') diploma_certificates = post.pop('diploma_certificates') if cover_letter: error['cover_letter'] = 'reset' if curriculum_vitae: error['curriculum_vitae'] = 'reset' if diploma_certificates: error['diploma_certificates'] = 'reset' request.session['website_hr_recruitment_default'] = post return request.redirect('/jobs/apply/%s' % post.get("job_id")) # public user can't create applicants (duh) env = request.env(user=SUPERUSER_ID) value = { 'source_id' : env.ref('hr_recruitment.source_website_company').id, 'name': '%s\'s Application' % post.get('first_name'), } for f in ['salutation', 'first_name', 'last_name', 'partner_address', 'place', 'partner_phone', 'email_from', 'possible_join_date', 'description']: value[f] = post.get(f) for f in ['department_id', 'job_id']: value[f] = int(post.get(f) or 0) # Retro-compatibility for saas-3. "phone" field should be replace by "partner_phone" in the template in trunk. value['partner_name'] = post.pop('first_name', False) + ' ' + post.pop('last_name', False) applicant_id = env['hr.applicant'].create(value).id if post['cover_letter']: attachment_value = { 'name': post['cover_letter'].filename, 'res_name': value['first_name'], 'res_model': 'hr.applicant', 'res_id': applicant_id, 'datas': base64.encodestring(post['cover_letter'].read()), 'datas_fname': post['cover_letter'].filename, } env['ir.attachment'].create(attachment_value) if post['curriculum_vitae']: attachment_value = { 'name': post['curriculum_vitae'].filename, 'res_name': value['first_name'], 'res_model': 'hr.applicant', 'res_id': applicant_id, 'datas': base64.encodestring(post['curriculum_vitae'].read()), 'datas_fname': post['curriculum_vitae'].filename, } env['ir.attachment'].create(attachment_value) if post['diploma_certificates']: attachment_value = { 'name': post['diploma_certificates'].filename, 'res_name': value['first_name'], 'res_model': 'hr.applicant', 'res_id': applicant_id, 'datas': base64.encodestring(post['diploma_certificates'].read()), 'datas_fname': post['diploma_certificates'].filename, } env['ir.attachment'].create(attachment_value) return request.render("website_hr_recruitment.thankyou", {})