def eventProcess(self,xmlstr,encrypt=False,kw=None): xml_data = self.xml2dict(xmlstr) msgType=xml_data.get("MsgType") fromUser=xml_data.get("FromUserName") toUser=xml_data.get("ToUserName") Event=xml_data.get("Event")#获得用户所输入的内容 AgentID=xml_data.get("AgentID",None) if Event=='subscribe':#关注 registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: orig = registry.get("gbsoft.weixin.base") welcome = orig.action_subscribe(cr,toUser,fromUser,AgentID) return self.replyWeiXin(fromUser,toUser,welcome,encrypt,AgentID,kw) #return self.replyWeiXin(fromUser,toUser,u"欢迎关注【人和未来生物科技(北京)有限公司】,您可以通过输入送检编号查询检测进度和结果。\n祝您生活愉快!") elif Event=="CLICK" or Event=="click": key = xml_data.get("EventKey") registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: orig = registry.get("gbsoft.weixin.base") res=orig.action_event_clicked(cr,key,toUser,fromUser,AgentID) if isinstance(res,(list,tuple)): return self.send_photo_text(fromUser,toUser,res[0],res[1],encrypt,AgentID,kw) else: return self.replyWeiXin(fromUser,toUser,res,encrypt,AgentID,kw) elif Event=="unsubscribe": registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: orig = registry.get("gbsoft.weixin.base") orig.action_unsubscribe(cr,toUser,fromUser,AgentID) return self.replyWeiXin(fromUser,toUser,u"祝您生活愉快!",encrypt,AgentID,kw) else: return ""
def connectdb(dbname=None, uid=1, context=None): openerp.tools.config.parse_config([]) r = RegistryManager.get(dbname or config["db_name"]) cr = r.cursor() Environment.reset() env = Environment(cr, uid, context or {}) return env
def get_detail(self, **kw): registry = RegistryManager.get(request.session.db) obj = registry.get("rhwl.genes.ys") sexdict = {'M': u'男', 'F': u'女'} with registry.cursor() as cr: id = obj.search(cr, request.uid, [("name", "=", kw.get("no"))]) if not id: data = {} else: res = obj.browse(cr, request.uid, id, context={ 'lang': "zh_CN", 'tz': "Asia/Shanghai" }) data = { "name": res.name, "hospital": res.hospital.name, "doctor": res.doctor.name or "", "date": res.date, "cust_name": res.cust_name, "identity": res.identity, "tel": res.tel } response = request.make_response(json.dumps( data, ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def charts_sale(self,**kw): res =self.check_userinfo(kw) if res.get("statu")!=200: return self.json_return(res) uid=res.get("userid") registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: obj = registry.get("res.partner") partner_ids = obj.search(cr,uid,[("sjjysj","!=",False)]) _logger.info(partner_ids) cr.execute(""" with t as ( select b.id,b.name,a.cx_date,count(*) as c from sale_sampleone a left join res_partner b on a.cxyy=b.id where a.is_reused='0' and b.id in %s group by b.id,b.name,a.cx_date) select id ,name ,sum(c) ,(select COALESCE(sum(c),0) from t where date_trunc('month',cx_date)::date = date_trunc('month',now())::date and t.id=tt.id) ,(select COALESCE(sum(c),0) from t where date_trunc('month',cx_date)::date = date_trunc('month',(now() - interval '1 month'))::date and t.id=tt.id) ,(select COALESCE(sum(c),0) from t where cx_date >= (now() - interval '3 month')::date and t.id=tt.id) ,(select COALESCE(sum(c),0) from t where cx_date >= (now() - interval '6 month')::date and t.id=tt.id) ,(select COALESCE(sum(c),0) from t where cx_date >= (now() - interval '12 month')::date and t.id=tt.id) from t tt group by id,name""" % (str(partner_ids).replace('[','(').replace(']',')'),)) return self.json_return(cr.fetchall())
def migrate(cr, version): recompute_date_fields(cr) import_crm_meeting(cr) # now we filled new fields, recalculate some stored fields pool = RegistryManager.get(cr.dbname) calendar_event = pool['calendar.event'] for field in ['start', 'stop', 'display_start']: calendar_event._update_store(cr, calendar_event._columns[field], field) migrate_attendees(cr) migrate_alarms(cr) # map renamed and deprecated reminder actions to 'notification' cr.execute('''update calendar_alarm set type='notification' where type in ('audio', 'display', 'procedure')''') # map renamed event states cr.execute('''update calendar_event set state='draft' where state in ('cancelled', 'tentative')''') cr.execute('''update calendar_event set state='open' where state in ('confirmed')''') # map renamed attendee states cr.execute('''update calendar_attendee set state='needsAction' where state in ('needs-action')''') # load modified noupdate data openupgrade.load_data(cr, 'calendar', 'migrations/8.0.1.0/data.xml') openupgrade_80.set_message_last_post(cr, SUPERUSER_ID, pool, ['calendar.event'])
def migrate_alarms(cr): '''now alarms are only defined in relation to the events they are attached to''' pool = RegistryManager.get(cr.dbname) calendar_event_model_id = pool['ir.model.data'].xmlid_to_res_id( cr, SUPERUSER_ID, 'calendar.model_calendar_event', raise_if_not_found=True) cr.execute( '''insert into calendar_alarm_calendar_event_rel (calendar_event_id, calendar_alarm_id) select %s, calendar_alarm.id from calendar_alarm where %s=%s ''' % (openupgrade.get_legacy_name('res_id'), openupgrade.get_legacy_name('model_id'), calendar_event_model_id)) crm_meeting_model_id = pool['ir.model.data'].xmlid_to_res_id( cr, SUPERUSER_ID, 'calendar.model_crm_meeting', raise_if_not_found=True) cr.execute('''insert into calendar_alarm_calendar_event_rel (calendar_event_id, calendar_alarm_id) select calendar_event.id, calendar_alarm.id from calendar_alarm join calendar_event on %s=%s where %s=%s ''' % (openupgrade.get_legacy_name('res_id'), openupgrade.get_legacy_name('crm_meeting_id'), openupgrade.get_legacy_name('model_id'), crm_meeting_model_id))
def migrate(cr, version): print 'Migrating product_uom_prices' if not version: return # no lo podemos auto instalar porque nos da une error hasta que no se # termine de actualziar todo # install_module(cr, 'product_template_tree_prices') registry = RegistryManager.get(cr.dbname) cr.execute( "SELECT currency_id FROM product_price_type WHERE field = 'list_price'" ) currency_id = cr.fetchall()[0][0] print 'currency_id', currency_id model = 'product.template' table = 'product_template' field = "list_price_type" value = "other_currency" condition = "WHERE other_currency_id != %s" % currency_id set_value( cr, registry[model], table, field, value, condition, )
def migrate_to_alias(self, cr, child_model_name, child_table_name, child_model_auto_init_fct, alias_model_name, alias_id_column, alias_key, alias_prefix='', alias_force_key='', alias_defaults={}, alias_generate_name=False, context=None): """ Installation hook to create aliases for all users and avoid constraint errors. :param child_model_name: model name of the child class (i.e. res.users) :param child_table_name: table name of the child class (i.e. res_users) :param child_model_auto_init_fct: pointer to the _auto_init function (i.e. super(res_users,self)._auto_init(cr, context=context)) :param alias_model_name: name of the aliased model :param alias_id_column: alias_id column (i.e. self._columns['alias_id']) :param alias_key: name of the column used for the unique name (i.e. 'login') :param alias_prefix: prefix for the unique name (i.e. 'jobs' + ...) :param alias_force_key': name of the column for force_thread_id; if empty string, not taken into account :param alias_defaults: dict, keys = mail.alias columns, values = child model column name used for default values (i.e. {'job_id': 'id'}) :param alias_generate_name: automatically generate alias name using prefix / alias key; default alias_name value is False because since 8.0 it is not required anymore """ if context is None: context = {} # disable the unique alias_id not null constraint, to avoid spurious warning during # super.auto_init. We'll reinstall it afterwards. alias_id_column.required = False # call _auto_init res = child_model_auto_init_fct(cr, context=context) registry = RegistryManager.get(cr.dbname) mail_alias = registry.get('mail.alias') child_class_model = registry[child_model_name] no_alias_ids = child_class_model.search(cr, SUPERUSER_ID, [('alias_id', '=', False)], context={'active_test': False}) # Use read() not browse(), to avoid prefetching uninitialized inherited fields for obj_data in child_class_model.read(cr, SUPERUSER_ID, no_alias_ids, [alias_key]): alias_vals = {'alias_name': False} if alias_generate_name: alias_vals['alias_name'] = '%s%s' % (alias_prefix, obj_data[alias_key]) if alias_force_key: alias_vals['alias_force_thread_id'] = obj_data[alias_force_key] alias_vals['alias_defaults'] = dict((k, obj_data[v]) for k, v in alias_defaults.iteritems()) alias_vals['alias_parent_thread_id'] = obj_data['id'] alias_create_ctx = dict(context, alias_model_name=alias_model_name, alias_parent_model_name=child_model_name) alias_id = mail_alias.create(cr, SUPERUSER_ID, alias_vals, context=alias_create_ctx) child_class_model.write(cr, SUPERUSER_ID, obj_data['id'], {'alias_id': alias_id}, context={'mail_notrack': True}) _logger.info('Mail alias created for %s %s (id %s)', child_model_name, obj_data[alias_key], obj_data['id']) # Finally attempt to reinstate the missing constraint try: cr.execute('ALTER TABLE %s ALTER COLUMN alias_id SET NOT NULL' % (child_table_name)) except Exception: _logger.warning("Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\ "If you want to have it, you should update the records and execute manually:\n"\ "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL", child_table_name, 'alias_id', child_table_name, 'alias_id') # set back the unique alias_id constraint alias_id_column.required = True return res
def run_test(self, cr, uid, module_path): registry = RegistryManager.get(cr.dbname) module_name = module_path.split('/')[-1] obj_list = self.get_objects(cr, uid, module_name) # remove osv_memory class becaz it does not have demo data if obj_list: cr.execute( "select w.res_model from ir_actions_todo as t left join " "ir_act_window as w on t.action_id=w.id where w.res_model" " IN %s", (tuple(obj_list),)) res = cr.fetchall() for remove_obj in res: if remove_obj and (remove_obj[0] in obj_list): obj_list.remove(remove_obj[0]) if not obj_list: self.error = True self.result += _( "Given module has no objects.Speed test can work only when " "new objects are created in the module along with demo data") return None obj_counter = 0 score = 0.0 try: obj_ids = self.get_ids(cr, uid, obj_list) except Exception, e: self.log.warning("Cannot get ids:", exc_info=True) obj_ids = {} self.result_details += e.message
def list_holidays(self, **kw): res = wb.WebClient().check_userinfo(kw) registry = RegistryManager.get(request.session.db) if res["statu"] == 200: uid = res["userid"] res["data"] = [] with registry.cursor() as cr: try: hr_holidays = registry.get("hr.holidays") emp_obj = registry.get("hr.employee") emp_id = emp_obj.search(cr, SUPERUSER_ID, [("user_id", "=", uid)]) if not emp_id: res["statu"] = 500 res["errtext"] = u"当前用户没有关联员工信息。" else: ids = hr_holidays.search( cr, uid, [("employee_id", "in", emp_id), ("type", "=", "remove")], order="id desc" ) sel_state = hr_holidays.get_select_state(cr, uid, self.CONTEXT) for i in hr_holidays.browse(cr, uid, ids, context=self.CONTEXT): df = self.dateTimeTZ(i.date_from, 8) dt = self.dateTimeTZ(i.date_to, 8) res["data"].append((i.id, df, dt, i.holiday_status_id.name, i.name, sel_state.get(i.state))) except: res["statu"] = 500 response = request.make_response(json.dumps(res, ensure_ascii=False), [("Content-Type", "application/json")]) return response.make_conditional(request.httprequest)
def get_new_models_of_module(self, cr, uid, module_name): """ Only get models created in this module """ registry = RegistryManager.get(cr.dbname) ir_model_obj = registry['ir.model'] sql = """ SELECT imd1.res_id FROM ir_model_data imd1 WHERE model='ir.model' and exists (select 1 from ir_model_data imd2 where imd1.name=imd2.name and module='%s') GROUP BY imd1.res_id HAVING count(*)=1 """ sql = sql % (module_name) cr.execute(sql) module_new_modules_ids = [] if cr.rowcount: module_new_modules_ids = [x[0] for x in cr.fetchall()] obj_list = [] model_recs = ir_model_obj.browse(cr, uid, module_new_modules_ids) for model_rec in model_recs: obj_list.append(model_rec.model) return obj_list
def init(self, cr): # Installation hook to create aliases for all users, right after _auto_init registry = RegistryManager.get(cr.dbname) mail_alias = registry.get('mail.alias') res_users = registry.get('res.users') users_no_alias = res_users.search(cr, SUPERUSER_ID, [('alias_id', '=', False)]) # Use read() not browse(), to avoid prefetching uninitialized inherited fields for user_data in res_users.read(cr, SUPERUSER_ID, users_no_alias, ['login']): alias_id = mail_alias.create_unique_alias( cr, SUPERUSER_ID, { 'alias_name': user_data['login'], 'alias_force_id': user_data['id'] }, model_name=self._name) res_users.write(cr, SUPERUSER_ID, user_data['id'], {'alias_id': alias_id}) _logger.info('Mail alias created for user %s (uid %s)', user_data['login'], user_data['id']) # Finally attempt to reinstate the missing constraint try: cr.execute( 'ALTER TABLE res_users ALTER COLUMN alias_id SET NOT NULL') except Exception: pass
def migrate(cr, installed_version): registry = RegistryManager.get(cr.dbname) module_obj = registry['ir.module.module'] module_ids = module_obj.search( cr, SUPERUSER_ID, [('name', '=', 'l10n_fr_fec_custom'), ('state', '=', 'uninstalled')]) module_obj.button_install(cr, SUPERUSER_ID, module_ids, {})
def get_config(self, dbname): """ Retrieves the module config for the CAS authentication. """ registry = RegistryManager.get(dbname) with registry.cursor() as cr: icp = registry.get('ir.config_parameter') config = { 'login_cas': icp.get_param(cr, openerp.SUPERUSER_ID, 'cas_auth.cas_activated'), 'host': icp.get_param(cr, openerp.SUPERUSER_ID, 'cas_auth.cas_server'), 'port': icp.get_param(cr, openerp.SUPERUSER_ID, 'cas_auth.cas_server_port'), 'cas_service': icp.get_param(cr, openerp.SUPERUSER_ID, 'cas_auth.cas_service'), 'base_url': icp.get_param(cr, openerp.SUPERUSER_ID, 'web.base.url'), 'auto_create': icp.get_param(cr, openerp.SUPERUSER_ID, 'cas_auth.cas_create_user'), } return config
def export_onhand(self): ''' Extracting all on hand inventories to frePPLe. We're bypassing the ORM for performance reasons. Mapping: stock.report.prodlots.product_id.name @ stock.report.prodlots.location_id.name -> buffer.name stock.report.prodlots.product_id.name -> buffer.item stock.report.prodlots.location_id.name -> buffer.location sum(stock.report.prodlots.qty) -> buffer.onhand ''' yield '<!-- inventory -->\n' yield '<buffers>\n' cr = RegistryManager.get(self.database).cursor() try: cr.execute('SELECT product_id, location_id, sum(qty) ' 'FROM stock_quant ' 'WHERE qty > 0 ' 'GROUP BY product_id, location_id') for i in cr.fetchall(): item = self.product_product.get(i[0], None) location = self.map_locations.get(i[1], None) if location and item: yield '<buffer name=%s onhand="%f"><item name=%s/><location name=%s/></buffer>\n' % ( quoteattr(u'%s @ %s' % (item['name'], location)), i[2], quoteattr(item['name']), quoteattr(location) ) finally: cr.close() yield '</buffers>\n'
def export_onhand(self): ''' Extracting all on hand inventories to frePPLe. We're bypassing the ORM for performance reasons. Mapping: stock.report.prodlots.product_id.name @ stock.report.prodlots.location_id.name -> buffer.name stock.report.prodlots.product_id.name -> buffer.item stock.report.prodlots.location_id.name -> buffer.location sum(stock.report.prodlots.qty) -> buffer.onhand ''' yield '<!-- inventory -->\n' yield '<buffers>\n' cr = RegistryManager.get(self.database).cursor() try: cr.execute('SELECT product_id, location_id, sum(qty) ' 'FROM stock_quant ' 'WHERE qty > 0 ' 'GROUP BY product_id, location_id') for i in cr.fetchall(): item = self.product_product.get(i[0], None) location = self.map_locations.get(i[1], None) if location and item: yield '<buffer name=%s onhand="%f"><item name=%s/><location name=%s/></buffer>\n' % ( quoteattr(u'%s @ %s' % (item['name'], location)), i[2], quoteattr(item['name']), quoteattr(location) ) finally: cr.close() yield '</buffers>\n'
def retrieve(self, req, dbname, token): """ retrieve the user info (name, login or email) corresponding to a signup token """ registry = RegistryManager.get(dbname) with registry.cursor() as cr: res_partner = registry.get('res.partner') user_info = res_partner.signup_retrieve_info(cr, openerp.SUPERUSER_ID, token) return user_info
def oea(self, **kw): """login user via Odoo Account provider""" dbname = kw.pop('db', None) if not dbname: dbname = db_monodb() if not dbname: return BadRequest() if not http.db_filter([dbname]): return BadRequest() registry = RegistryManager.get(dbname) with registry.cursor() as cr: IMD = registry['ir.model.data'] try: model, provider_id = IMD.get_object_reference( cr, SUPERUSER_ID, 'auth_oauth', 'provider_openerp') except ValueError: return set_cookie_and_redirect('/web?db=%s' % dbname) assert model == 'auth.oauth.provider' state = { 'd': dbname, 'p': provider_id, 'c': { 'no_user_creation': True }, } kw['state'] = json.dumps(state) return self.signin(**kw)
def _get_cursor(self, dbname): cr = self._dbname_to_cr.get(dbname) if not cr or (cr and cr.closed): db = RegistryManager.get(dbname).db cr = db.cursor() self._dbname_to_cr[dbname] = cr return cr
def _signup_with_values(self, req, dbname, token, values): registry = RegistryManager.get(dbname) with registry.cursor() as cr: res_users = registry.get('res.users') print "res user" print res_users res_users.signup(cr, openerp.SUPERUSER_ID, values, token)
def list_providers(self, req, dbname): l = [] try: registry = RegistryManager.get(dbname) with registry.cursor() as cr: providers = registry.get('auth.saml.provider') if providers: l = providers.read( cr, SUPERUSER_ID, providers.search( cr, SUPERUSER_ID, [('enabled', '=', True)] ), [ "id", "name", "enabled", "css_class", "body", "sequence", ], ) else: l = [] except Exception, e: _logger.exception("SAML2: %s" % str(e))
def __init__(self, dbname, model_name, res_id, uid=0): assert isinstance(uid, (int, long)), 'uid should be an integer' self._logger = logging.getLogger('smile_log') db = RegistryManager.get(dbname).db pid = 0 try: cr = db.cursor() cr.execute( "select relname from pg_class where relname='smile_log_seq'") if not cr.rowcount: cr.execute("create sequence smile_log_seq") cr.execute("select nextval('smile_log_seq')") res = cr.fetchone() pid = res and res[0] or 0 finally: cr.close() self._logger_start = datetime.datetime.now() self._logger_args = { 'dbname': dbname, 'model_name': model_name, 'res_id': res_id, 'uid': uid, 'pid': pid }
def rhwl_weixin_jsapi(self, **kw): para = {} if request.httprequest.data: para = eval(request.httprequest.data) if kw: para.update(kw) url = para.get("url", "").encode('utf-8') code = para.get("code", "").encode('utf-8') s = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' noncestr = ''.join( [s[random.randrange(0, s.__len__() - 1)] for i in range(1, 21)]) timestamp = time.time().__trunc__().__str__() registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: b = registry.get('rhwl.weixin.base') ids = b.search(cr, SUPERUSER_ID, [("code", "=", code)], limit=1) appid = b.browse(cr, SUPERUSER_ID, ids).original_id jsapi_ticket = b._get_ticket(cr, SUPERUSER_ID, code, context=self.CONTEXT) str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "×tamp=" + timestamp + "&url=" + url sha = hashlib.sha1(str) s = sha.hexdigest() data = { "noncestr": noncestr, "timestamp": timestamp, "signature": s, "appid": appid } response = request.make_response(json.dumps( data, ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def utc_timestamp(cr, uid, timestamp, context=None): """Returns the given timestamp converted to the client's timezone. This method is *not* meant for use as a _defaults initializer, because datetime fields are automatically converted upon display on client side. For _defaults you :meth:`fields.datetime.now` should be used instead. :param datetime timestamp: naive datetime value (expressed in LOCAL) to be converted to the client timezone :param dict context: the 'tz' key in the context should give the name of the User/Client timezone (otherwise UTC is used) :rtype: datetime :return: timestamp converted to timezone-aware datetime in UTC """ assert isinstance(timestamp, datetime), 'Datetime instance expected' if context and context.get('tz'): tz_name = context['tz'] else: registry = RegistryManager.get(cr.dbname) tz_name = registry.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz'] if tz_name: try: utc = pytz.timezone('UTC') context_tz = pytz.timezone(tz_name) context_timestamp = context_tz.localize( timestamp, is_dst=False) # UTC = no DST return context_timestamp.astimezone(utc) except Exception: _logger.debug( "failed to compute context/client-specific timestamp, " "using the UTC value", exc_info=True) return timestamp
def _signup_with_values(self, req, dbname, token, values): registry = RegistryManager.get(dbname) with registry.cursor() as cr: res_users = registry.get('res.users') print "res user" print res_users res_users.signup(cr, openerp.SUPERUSER_ID, values, token)
def setUp(self): self.registry = RegistryManager.get(get_db_name()) #: current transaction's cursor self.cr = self.cursor() self.uid = openerp.SUPERUSER_ID #: :class:`~openerp.api.Environment` for the current test case self.env = api.Environment(self.cr, self.uid, {})
def atuo_log_in(self, msg): db = RegistryManager.get(request.db) user = openerp.registry(request.db)['res.users'] session = openerp.registry(request.db)['weixin.session'] mobile = self._get_user_mobile(msg.source) if not mobile: return u'错误,用户手机号不存在' with closing(db.cursor()) as cr: users = user.search(cr, 1, [('oauth_access_token', '=', mobile)]) if not users: return u'错误,当前用户还没有在ERP端绑定' users = user.browse(cr, 1, users[0]) uid = request.session.authenticate(request.session.db, users.login, users.oauth_access_token) if uid: self.login_user = uid session_id = session.search( cr, 1, [('temp_password', '=', msg.content)]) session_old_id = session.search(cr, 1, [('mobile', '=', mobile)]) if session_old_id: session.unlink(cr, uid, session_old_id) cr.commit() if session_id: session.write(cr, 1, session_id, {'mobile': mobile}) session_row = session.browse(cr, 1, session_id) cr.commit() self.login_session = session_row.session_id return u'成功' return "登录成功!"
def wechat_binding(self, user_id, mobile, login, password, **args): db = RegistryManager.get(request.db) user = openerp.registry(request.db)['res.users'] with closing(db.cursor()) as cr: users = user.search(cr, 1, [('login', '=', login)]) if not users: return request.make_response( simplejson.dumps({ 'message': u'账户不存在', 'state': 'error', })) try: user.check_credentials(cr, users[0], password) except: return request.make_response( simplejson.dumps({ 'message': u'密码错误', 'state': 'error', })) user.write(cr, 1, users[0], { 'oauth_access_token': mobile, 'weixin_id': user_id, }) cr.commit() return request.make_response( simplejson.dumps({ 'state': 'done', 'message': u'绑定成功,请使用手机微信扫码登录' }))
def migrate(cr, version): """ It can be the case that procurement was not installed in the 7.0 database, as in 7.0 stock was a dependency of procurement and not the other way around like it is in 8.0. So we need to check if we are migrating a database in which procurement related stuff needs to be migrated. """ registry = RegistryManager.get(cr.dbname) create_stock_move_fields(cr, registry) have_procurement = openupgrade.column_exists( cr, 'product_template', openupgrade.get_legacy_name('procure_method')) migrate_stock_warehouse(cr, registry) migrate_stock_picking(cr, registry) migrate_stock_location(cr, registry) if have_procurement: migrate_stock_warehouse_orderpoint(cr) migrate_product_supply_method(cr, registry) migrate_procurement_order(cr, registry) migrate_stock_qty(cr, registry) migrate_stock_production_lot(cr, registry) # Initiate defaults before filling. openupgrade.set_defaults(cr, registry, default_spec, force=False) migrate_product(cr, registry) openupgrade.delete_model_workflow(cr, 'stock.picking') openupgrade_80.set_message_last_post( cr, uid, registry, ['stock.production.lot', 'stock.picking']) migrate_move_inventory(cr, registry) reset_warehouse_data_ids(cr, registry)
def get_detail(self,**kw): registry = RegistryManager.get(request.session.db) obj = registry.get("rhwl.easy.genes.new") sexdict={'M':u'男','F':u'女'} with registry.cursor() as cr: id = obj.search(cr,request.uid,[("name","=",kw.get("no"))]) if not id: data={} else: res = obj.browse(cr,request.uid,id,context={'lang': "zh_CN",'tz': "Asia/Shanghai"}) data={ "batch_no":res.batch_no, "name":res.name, "date":res.date, "cust_name":res.cust_name, "sex": sexdict.get(res.sex,""), "identity":res.identity and res.identity or "", "mobile":res.mobile and res.mobile or "", "birthday":res.birthday and res.birthday or "", "hospital":res.hospital.name, "package":res.package_id.name, "gene_id":res.id, } response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def oea(self, req, **kw): """login user via PengERP Account provider""" dbname = kw.pop('db', None) if not dbname: dbname = db_monodb(req) if not dbname: return BadRequest() registry = RegistryManager.get(dbname) with registry.cursor() as cr: IMD = registry['ir.model.data'] model, provider_id = IMD.get_object_reference( cr, SUPERUSER_ID, 'auth_oauth', 'provider_openerp') assert model == 'auth.oauth.provider' state = { 'd': dbname, 'p': provider_id, 'c': { 'no_user_creation': True }, } kw['state'] = simplejson.dumps(state) return self.signin(req, **kw)
def imagepost(self,**kw): registry = RegistryManager.get(request.session.db) obj = registry.get("rhwl.easy.genes.new") with registry.cursor() as cr: id = obj.search(cr,request.uid,[("name","=",kw.get("no"))]) if not id: return "NO_DATA_FOUND" file_like = cStringIO.StringIO(kw.get("img1").split(";")[-1].split(",")[-1].decode('base64','strict')) img = Image.open(file_like) #判断是单张还是两张拍照,如果是单张,则旋转后保存,如果是两张,则截取后合并保存 if not kw.has_key("img2"): img = img.transpose(Image.ROTATE_270) else: width,height = img.size file_like2 = cStringIO.StringIO(kw.get("img2").split(";")[-1].split(",")[-1].decode('base64','strict')) img2 = Image.open(file_like2) region = img2.crop((0,0,width/2,height)) img.paste(region, (width/2, 0,width,height)) val={"img":base64.encodestring(img.tostring("jpeg",img.mode))} if kw.get("etx",""): val["except_note"]=kw.get("etx") val["except_type"]=kw.get("etx_type") obj.write(cr,request.uid,id,{"except_note":kw.get("etx"),"state":"except"},context={'lang': "zh_CN",'tz': "Asia/Shanghai","name":kw.get("no")}) obj._post_images(cr,request.uid,id,val["img"],context={'lang': "zh_CN",'tz': "Asia/Shanghai","name":kw.get("no")}) #obj.write(cr,request.uid,id,val,context={'lang': "zh_CN",'tz': "Asia/Shanghai","name":kw.get("no")}) if (not val.has_key("except_note")) and kw.get("is_confirm")=="true": o=obj.browse(cr,request.uid,id,context={'lang': "zh_CN",'tz': "Asia/Shanghai"}) if o.state=="draft": obj.action_state_confirm(cr,request.uid,id,context={'lang': "zh_CN",'tz': "Asia/Shanghai"}) return "OK"
def remove_share_module(cr): pool = RegistryManager.get(cr.dbname) ir_module_module = pool['ir.module.module'] domain = [('name', '=', 'share'), ('state', 'in', ('installed', 'to install', 'to upgrade'))] ids = ir_module_module.search(cr, SUPERUSER_ID, domain) ir_module_module.module_uninstall(cr, SUPERUSER_ID, ids)
def send_sms(queue_id): """ 发送短信 max_retries: 最多重发10次 """ _logger.info("queue_id: %s" % queue_id) _logger.info("retry_test id:%s" % send_sms.request.id) _logger.info("retries:%s" % send_sms.request.retries) # 当前重发次数 从0开始 send_sms.request.called_directly = False # 强制制定False 否则无法重发 registry = RegistryManager.get(config['db_name']) with registry.cursor() as cr: queue_obj = registry.get('sms.gateway.queue') queue = queue_obj.browse(cr, 1, queue_id, context=None) result = queue.send() _logger.info("result: %s" % result) # result在with外判断是为了防止重发机制导致事物无法提交的情况 if result == 'success': return True elif result == 'nosend': return False else: args = send_sms.request.args kwargs = send_sms.request.kwargs # 重发必须放在cr外 否则会导致无法提交 send_sms.retry(args=args, kwargs=kwargs, exc=Exception(result), countdown=2)
def retrieve(self, req, dbname, token): """ retrieve the user info (name, login or email) corresponding to a signup token """ registry = RegistryManager.get(dbname) with registry.cursor() as cr: res_partner = registry.get('res.partner') user_info = res_partner.signup_retrieve_info(cr, openerp.SUPERUSER_ID, token) return user_info
def export_onhand(self): ''' Extracting all on hand inventories to frePPLe. We're bypassing the ORM for performance reasons. Mapping: stock.report.prodlots.product_id.name @ stock.report.prodlots.location_id.name -> buffer.name stock.report.prodlots.product_id.name -> buffer.item stock.report.prodlots.location_id.name -> buffer.location sum(stock.report.prodlots.qty) -> buffer.onhand ''' yield '<!-- inventory -->\n' yield '<buffers>\n' cr = RegistryManager.get(self.database).cursor() try: cr.execute('SELECT product_id, location_id, sum(qty) ' 'FROM stock_quant ' 'WHERE qty > 0 ' 'GROUP BY product_id, location_id ' 'ORDER BY location_id ASC') inventory = {} for i in cr.fetchall(): item = self.product_product.get(i[0], None) location = self.map_locations.get(i[1], None) if item and location: inventory[ (item['name'], location) ] = i[2] + inventory.get( (item['name'], location), 0) for key, val in inventory.items(): buf = "%s @ %s" % (key[0], key[1]) yield '<buffer name=%s onhand="%f"><item name=%s/><location name=%s/></buffer>\n' % ( quoteattr(buf), val, quoteattr(key[0]), quoteattr(key[1]) ) finally: cr.close() yield '</buffers>\n'
def _rhwl_web_material_detail(self,**kw): res = self.check_userinfo(kw) data = [] if res.get('statu')==200: uid = res.get("userid") id = int(res.get("params").get("id")) registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: material = registry.get("rhwl.web.material") for i in material.browse(cr,uid,id,context=self.CONTEXT): data = [i.wh_level, i.hospital.id if i.hospital else 0, i.address_id.id if i.address_id else 0, i.state, i.receiver_user, i.receiver_address, i.receiver_tel ] detail=[] for d in i.line: detail.append([d.product_id.id,d.product_id.name,d.product_id.uom_id.name,round(d.qty,2)]) data.append(detail) else: data = res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def log(self, cr, uid, message, model_name=False, object_id=None, level='info'): # If no object we create a new cursor db_name = threading.current_thread().dbname new_cr = RegistryManager.get(db_name).cursor() if level == 'info': logger.info(message) elif level == 'debug': logger.debug(message) elif level == 'warning': logger.warn(message) elif level == 'error': logger.error(message) else: logger.fatal(message) try: values = { 'message': message, 'level': level, 'object_id': object_id or False, 'uid': uid, 'model_name': model_name } log_id = self.create(new_cr, uid, values) new_cr.commit() finally: new_cr.close() return log_id
def _get_cursor(self, dbname): cr = self._dbname_to_cr.get(dbname) if not cr or (cr and cr.closed): db = RegistryManager.get(dbname)._db cr = db.cursor() self._dbname_to_cr[dbname] = cr return cr
def export_onhand(self): ''' Extracting all on hand inventories to frePPLe. We're bypassing the ORM for performance reasons. Mapping: stock.report.prodlots.product_id.name @ stock.report.prodlots.location_id.name -> buffer.name stock.report.prodlots.product_id.name -> buffer.item stock.report.prodlots.location_id.name -> buffer.location sum(stock.report.prodlots.qty) -> buffer.onhand ''' yield '<!-- inventory -->\n' yield '<buffers>\n' cr = RegistryManager.get(self.database).cursor() try: cr.execute('SELECT product_id, location_id, sum(qty) ' 'FROM stock_quant ' 'WHERE qty > 0 ' 'GROUP BY product_id, location_id ' 'ORDER BY location_id ASC') inventory = {} for i in cr.fetchall(): item = self.product_product.get(i[0], None) location = self.map_locations.get(i[1], None) if item and location: inventory[ (item['name'], location) ] = i[2] + inventory.get( (item['name'], location), 0) for key, val in inventory.items(): buf = "%s @ %s" % (key[0], key[1]) yield '<buffer name=%s onhand="%f"><item name=%s/><location name=%s/></buffer>\n' % ( quoteattr(buf), val, quoteattr(key[0]), quoteattr(key[1]) ) finally: cr.close() yield '</buffers>\n'
def rhwl_weixin_jsapi(self,**kw): para={} if request.httprequest.data: para = eval(request.httprequest.data) if kw: para.update(kw) url=para.get("url","").encode('utf-8') code=para.get("code","").encode('utf-8') s='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' noncestr=''.join([s[random.randrange(0,s.__len__()-1)] for i in range(1,21)]) timestamp=time.time().__trunc__().__str__() registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: b = registry.get('gbsoft.weixin.base') ids =b.search(cr,SUPERUSER_ID,[("code","=",code)],limit=1) appid = b.browse(cr,SUPERUSER_ID,ids).original_id jsapi_ticket= b._get_ticket(cr,SUPERUSER_ID,code,context=self.CONTEXT) str = "jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"×tamp="+timestamp+"&url="+url sha = hashlib.sha1(str) s = sha.hexdigest() data={ "noncestr":noncestr, "timestamp":timestamp, "signature":s, "appid":appid } response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def app_receive(self,**kw): res = self.check_userinfo(kw) data = {} if res.get('statu')==200: id = res.get("params").get("goodsId") uid = res.get("userid") if id: registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: express = registry.get('stock.picking.express') ids = express.search(cr,uid,[('num_express','=',id),('state','not in',['done','cancel'])],context=self.CONTEXT) data = { "receiv_real_qty":res.get("params").get("actualNumber"), "receiv_real_user": uid, "receiv_real_date": datetime.datetime.now(), } express.write(cr,uid,ids,data,context=self.CONTEXT) express.action_ok(cr,uid,ids,context=self.CONTEXT) data={} data['statu'] = 200 cr.commit() else: data = res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def weixin_name_email(self, **kw): qcontext = request.params.copy() if kw.get('email') and kw.get('name'): import re def validateEmail(email): if email: if len(email) > 7: if re.match("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$", email) != None: return 1 return 0 if not validateEmail(kw['email']) or kw['name'] == '': qcontext['error'] = _('name or email error') if 'error' not in qcontext and kw.get('state') and kw.get('access_token') and kw.get('name') and kw.get('email'): dbname = kw['state'] registry = RegistryManager.get(dbname) u = registry.get('res.users') with registry.cursor() as cr: try: credentials = u.weixin_auth_signup(cr, SUPERUSER_ID, kw) url='/web' cr.commit() return login_and_redirect(*credentials, redirect_url=url) except Exception, e: _logger.exception("OAuth2: %s" % str(e)) url = "/weixin/login?oauth_error=2" return set_cookie_and_redirect(url)
def app_notice(self,**kw): res = self.check_userinfo(kw) data = {} if res.get('statu')==200: id = res.get("params").get("id") #样品编码 btn = res.get("params").get("btn") uid = res.get("userid") if id: registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: reuse_obj = registry.get('sale.sampleone.reuse') reuseid = reuse_obj.search(cr,uid,[('name.name','=',id)]) if reuseid: if btn=="1": vals = {'notice_user':uid,'notice_date':datetime.datetime.now(),'state':'done'} else: vals = {'state':'draft'} reuse_obj.write(cr,SUPERUSER_ID,reuseid,vals,context=self.CONTEXT) else: except_obj = registry.get('sale.sampleone.exception') expid = except_obj.search(cr,uid,[('name.name','=',id)]) if btn=="1": vals = {'notice_user':uid,'notice_date':datetime.datetime.now(),'state':'notice',"is_notice":True} else: vals = {'state':'draft',"is_notice":False} if expid: except_obj.write(cr,SUPERUSER_ID,expid,vals,context=self.CONTEXT) data['statu'] = 200 cr.commit() else: data = res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def migrate_to_alias(self, cr, child_model_name, child_table_name, child_model_auto_init_fct, alias_model_name, alias_id_column, alias_key, alias_prefix='', alias_force_key='', alias_defaults={}, alias_generate_name=False, context=None): """ Installation hook to create aliases for all users and avoid constraint errors. :param child_model_name: model name of the child class (i.e. res.users) :param child_table_name: table name of the child class (i.e. res_users) :param child_model_auto_init_fct: pointer to the _auto_init function (i.e. super(res_users,self)._auto_init(cr, context=context)) :param alias_model_name: name of the aliased model :param alias_id_column: alias_id column (i.e. self._columns['alias_id']) :param alias_key: name of the column used for the unique name (i.e. 'login') :param alias_prefix: prefix for the unique name (i.e. 'jobs' + ...) :param alias_force_key': name of the column for force_thread_id; if empty string, not taken into account :param alias_defaults: dict, keys = mail.alias columns, values = child model column name used for default values (i.e. {'job_id': 'id'}) :param alias_generate_name: automatically generate alias name using prefix / alias key; default alias_name value is False because since 8.0 it is not required anymore """ if context is None: context = {} # disable the unique alias_id not null constraint, to avoid spurious warning during # super.auto_init. We'll reinstall it afterwards. alias_id_column.required = False # call _auto_init res = child_model_auto_init_fct(cr, context=context) registry = RegistryManager.get(cr.dbname) mail_alias = registry.get('mail.alias') child_class_model = registry[child_model_name] no_alias_ids = child_class_model.search(cr, SUPERUSER_ID, [('alias_id', '=', False)], context={'active_test': False}) # Use read() not browse(), to avoid prefetching uninitialized inherited fields for obj_data in child_class_model.read(cr, SUPERUSER_ID, no_alias_ids, [alias_key]): alias_vals = {'alias_name': False} if alias_generate_name: alias_vals['alias_name'] = '%s%s' % (alias_prefix, obj_data[alias_key]) if alias_force_key: alias_vals['alias_force_thread_id'] = obj_data[alias_force_key] alias_vals['alias_defaults'] = dict((k, obj_data[v]) for k, v in alias_defaults.iteritems()) alias_vals['alias_parent_thread_id'] = obj_data['id'] alias_create_ctx = dict(context, alias_model_name=alias_model_name, alias_parent_model_name=child_model_name) alias_id = mail_alias.create(cr, SUPERUSER_ID, alias_vals, context=alias_create_ctx) child_class_model.write(cr, SUPERUSER_ID, obj_data['id'], {'alias_id': alias_id}) _logger.info('Mail alias created for %s %s (id %s)', child_model_name, obj_data[alias_key], obj_data['id']) # Finally attempt to reinstate the missing constraint try: cr.execute('ALTER TABLE %s ALTER COLUMN alias_id SET NOT NULL' % (child_table_name)) except Exception: _logger.warning("Table '%s': unable to set a NOT NULL constraint on column '%s' !\n"\ "If you want to have it, you should update the records and execute manually:\n"\ "ALTER TABLE %s ALTER COLUMN %s SET NOT NULL", child_table_name, 'alias_id', child_table_name, 'alias_id') # set back the unique alias_id constraint alias_id_column.required = True return res
def utc_timestamp(cr, uid, timestamp, context=None): """Returns the given timestamp converted to the client's timezone. This method is *not* meant for use as a _defaults initializer, because datetime fields are automatically converted upon display on client side. For _defaults you :meth:`fields.datetime.now` should be used instead. :param datetime timestamp: naive datetime value (expressed in LOCAL) to be converted to the client timezone :param dict context: the 'tz' key in the context should give the name of the User/Client timezone (otherwise UTC is used) :rtype: datetime :return: timestamp converted to timezone-aware datetime in UTC """ assert isinstance(timestamp, datetime), 'Datetime instance expected' if context and context.get('tz'): tz_name = context['tz'] else: registry = RegistryManager.get(cr.dbname) tz_name = registry.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz'] if tz_name: try: utc = pytz.timezone('UTC') context_tz = pytz.timezone(tz_name) context_timestamp = context_tz.localize(timestamp, is_dst=False) # UTC = no DST return context_timestamp.astimezone(utc) except Exception: _logger.debug("failed to compute context/client-specific timestamp, " "using the UTC value", exc_info=True) return timestamp
def oea(self, **kw): """login user via OpenERP Account provider""" dbname = kw.pop('db', None) if not dbname: dbname = db_monodb() if not dbname: return BadRequest() registry = RegistryManager.get(dbname) with registry.cursor() as cr: IMD = registry['ir.model.data'] try: model, provider_id = IMD.get_object_reference(cr, SUPERUSER_ID, 'auth_oauth', 'provider_openerp') except ValueError: return set_cookie_and_redirect('/web?db=%s' % dbname) assert model == 'auth.oauth.provider' state = { 'd': dbname, 'p': provider_id, 'c': {'no_user_creation': True}, } kw['state'] = simplejson.dumps(state) return self.signin(**kw)
def export_onhand(self): """ Extracting all on hand inventories to frePPLe. We're bypassing the ORM for performance reasons. Mapping: stock.report.prodlots.product_id.name @ stock.report.prodlots.location_id.name -> buffer.name stock.report.prodlots.product_id.name -> buffer.item stock.report.prodlots.location_id.name -> buffer.location sum(stock.report.prodlots.qty) -> buffer.onhand """ yield "<!-- inventory -->\n" yield "<buffers>\n" cr = RegistryManager.get(self.database).db.cursor() try: cr.execute( "SELECT product_id, location_id, sum(qty) " "FROM stock_report_prodlots " "WHERE qty > 0 " "GROUP BY product_id, location_id" ) for i in cr.fetchall(): item = self.product_product.get(i[0], None) location = self.map_locations.get(i[1], None) if location and item: yield '<buffer name=%s onhand="%f"><item name=%s/><location name=%s/></buffer>\n' % ( quoteattr(u"%s @ %s" % (item["name"], location)), i[2], quoteattr(item["name"]), quoteattr(location), ) finally: cr.close() yield "</buffers>\n"
def _get_rhwl_api_report_img(self,**kw): res = self.check_userinfo(kw) data = [] if res.get('statu')==200: registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: sample = registry.get("rhwl.easy.genes") id = sample.search(cr,SUPERUSER_ID,[("name","=",res.get("params").get("id"))]) if id: obj=sample.browse(cr,SUPERUSER_ID,id) png_path = os.path.join("/data/odoo/file/report",obj.name) if not os.path.exists(png_path): os.mkdir(png_path) ps=int(res.get("params").get("ps")) pe=int(res.get("params").get("pe")) for i in range(ps,pe+1): if not os.path.exists(os.path.join(png_path,"pg_"+str(i).zfill(4)+".pdf")): shutil.copy(os.path.join("/data/odoo/file/report",obj.name+".pdf"),os.path.join(png_path,obj.name+".pdf")) os.system("cd "+png_path+";pdftk "+obj.name+".pdf burst") if not os.path.exists(os.path.join(png_path,"pg_"+str(i).zfill(4)+".png")): os.system("cd "+png_path+";convert -density 100 pg_"+str(i).zfill(4)+".pdf pg_"+str(i).zfill(4)+".png") data.append("/rhwl_gene/static/local/report/"+obj.name.encode("utf-8")+"/pg_"+str(i).zfill(4)+".png") else: data=res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def signin(self, **kw): state = simplejson.loads(kw['state']) dbname = state['d'] provider = state['p'] context = state.get('c', {}) registry = RegistryManager.get(dbname) with registry.cursor() as cr: try: u = registry.get('res.users') credentials = u.auth_oauth(cr, SUPERUSER_ID, provider, kw, context=context) cr.commit() action = state.get('a') menu = state.get('m') url = '/web' if action: url = '/web#action=%s' % action elif menu: url = '/web#menu_id=%s' % menu return login_and_redirect(*credentials, redirect_url=url) except AttributeError: # auth_signup is not installed _logger.error("auth_signup not installed on database %s: oauth sign up cancelled." % (dbname,)) url = "/web/login?oauth_error=1" except openerp.exceptions.AccessDenied: # oauth credentials not valid, user could be on a temporary session _logger.info('OAuth2: access denied, redirect to main page in case a valid session exists, without setting cookies') url = "/web/login?oauth_error=3" redirect = werkzeug.utils.redirect(url, 303) redirect.autocorrect_location_header = False return redirect except Exception, e: # signup error _logger.exception("OAuth2: %s" % str(e)) url = "/web/login?oauth_error=2"
def app_today_deliver(self,**kw): res = self.check_userinfo(kw) data = {} if res.get('statu')==200: id = res.get("params").get("parentID") detail = eval(res.get("params").get("datas")) #[{ "code":"X140545" , "preCode":"X145655" },{ "code":"4X32871" , "preCode":"" },{ "code":"4Y45474" , "preCode":"" } ]}'; uid = res.get("userid") if id: registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: obj = registry.get('sale.sampleone.days') dobj =registry.get("sale.sampleone.days.line") vals={ "partner_id":id, "user_id":uid } mid = obj.create(cr,uid,vals,context=self.CONTEXT) did=[] for j in detail: did.append( dobj.create(cr,uid,{"parent_id":mid,"sample_no":j.get("code"),"name":j.get("name")},context=self.CONTEXT)) obj.write(cr,uid,mid,{'detail_ids':[[6, False, did]]}) data['statu'] = 200 cr.commit() else: data = res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def imagepost(self,**kw): registry = RegistryManager.get(request.session.db) obj = registry.get("rhwl.easy.genes") with registry.cursor() as cr: if kw.get("id",0) and int(kw.get("id",0))>0: id = [int(kw.get("id",0))] else: id = obj.search(cr,request.uid,[("name","=",kw.get("no"))]) if not id: return "NO_DATA_FOUND" file_like = cStringIO.StringIO(kw.get("img1").split(";")[-1].split(",")[-1].decode('base64','strict')) img = Image.open(file_like) width,height = img.size file_like2 = cStringIO.StringIO(kw.get("img2").split(";")[-1].split(",")[-1].decode('base64','strict')) img2 = Image.open(file_like2) region = img2.crop((0,0,width/2,height)) img.paste(region, (width/2, 0,width,height)) val={"img":base64.encodestring(img.tostring("jpeg",img.mode))} if kw.get("etx",""): val["except_note"]=kw.get("etx") obj.write(cr,request.uid,id,val,context={'lang': "zh_CN",'tz': "Asia/Shanghai","name":kw.get("no")}) if val.has_key("except_note") or kw.get("is_confirm")=="true": o=obj.browse(cr,request.uid,id,context={'lang': "zh_CN",'tz': "Asia/Shanghai"}) if o.state=="draft": if val.has_key("except_note"): obj.action_state_except(cr,request.uid,id,context={'lang': "zh_CN",'tz': "Asia/Shanghai"}) elif kw.get("is_confirm")=="true": obj.action_state_confirm(cr,request.uid,id,context={'lang': "zh_CN",'tz': "Asia/Shanghai"}) return "OK"
def signin(self, req, **kw): state = simplejson.loads(kw['state']) dbname = state['d'] provider = state['p'] context = state.get('c', {}) registry = RegistryManager.get(dbname) with registry.cursor() as cr: try: u = registry.get('res.users') credentials = u.auth_oauth(cr, SUPERUSER_ID, provider, kw, context=context) cr.commit() action = state.get('a') menu = state.get('m') url = '/' if action: url = '/#action=%s' % action elif menu: url = '/#menu_id=%s' % menu return login_and_redirect(req, *credentials, redirect_url=url) except AttributeError: # auth_signup is not installed _logger.error("auth_signup not installed on database %s: oauth sign up cancelled." % (dbname,)) url = "/#action=login&oauth_error=1" except openerp.exceptions.AccessDenied: # oauth credentials not valid, user could be on a temporary session _logger.info('OAuth2: access denied, redirect to main page in case a valid session exists, without setting cookies') url = "/#action=login&oauth_error=3" redirect = werkzeug.utils.redirect(url, 303) redirect.autocorrect_location_header = False return redirect except Exception, e: # signup error _logger.exception("OAuth2: %s" % str(e)) url = "/#action=login&oauth_error=2"
def setUp(self): self.registry = RegistryManager.get(DB) #: current transaction's cursor self.cr = self.cursor() self.uid = openerp.SUPERUSER_ID #: :class:`~openerp.api.Environment` for the current test case self.env = api.Environment(self.cr, self.uid, {})
def app_express(self,**kw): res = self.check_userinfo(kw) data = {} if res.get('statu')==200: startTime = res.get("params").get("startTime") endTime = res.get("params").get("endTime") uid = res.get("userid") if not startTime:startTime=(datetime.datetime.today() - datetime.timedelta(100)).strftime("%Y-%m-%d") if not endTime:endTime=(datetime.datetime.today() + datetime.timedelta(1)).strftime("%Y-%m-%d") if startTime and endTime: registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: express = registry.get('stock.picking.express') ids = express.search(cr,uid,[('date','>=',startTime),('date','<=',endTime)],order="date desc",context=self.CONTEXT) data=[] for i in express.browse(cr,uid,ids,self.CONTEXT): data.append({ "time":i.date[0:10], "logIdCompany": [i.num_express,i.deliver_id.name], "state": STATE.get(i.state), "is_deliver":i.is_deliver, "is_receiv":i.is_receiv }) cr.commit() else: data = res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def app_reuse(self,**kw): res = self.check_userinfo(kw) data = {} state={ "draft": u"未通知", "done": u"已通知", "cancel": u"孕妇放弃", "reuse": u"已重采血" } if res.get('statu')==200: uid = res.get("userid") if id: registry = RegistryManager.get(request.session.db) with registry.cursor() as cr: sampleone = registry.get('sale.sampleone.reuse') reuseid = sampleone.search(cr,uid,[('state','not in',['cancel','reuse'])],order="id desc") data=[] for i in sampleone.browse(cr,uid,reuseid,context=self.CONTEXT): data.append({ "time":i.cx_date, "name":i.yfxm, "numbers":i.name.yftelno, "id":i.name.name, "status":state.get(i.state) }) cr.commit() else: data = res response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')]) return response.make_conditional(request.httprequest)
def authenticate(self, req, db, login, password, totp_pin, base_location=None): wsgienv = req.httprequest.environ env = dict( base_location=base_location, HTTP_HOST=wsgienv['HTTP_HOST'], REMOTE_ADDR=wsgienv['REMOTE_ADDR'], ) # first do the standard authenticate and save the returned uid uid = req.session.authenticate(db, login, password, env) if uid: registry = RegistryManager.get(db) need_totp = 'not_defined' ids = [] with registry.cursor() as cr: # find the user who attempts a login user_obj = registry.get('res.users') user_rec = user_obj.browse(cr, uid, uid) user_sec = user_rec.totp_login_secret or False user_totp = totp_pin or '' user_totp = user_totp.replace(' ', '') remote_ip = ipaddr.IPAddress(wsgienv['REMOTE_ADDR']) # elaborate the ip rule definitions totp_ip_def = registry.get('totp.config_ip') ip_def_ids = totp_ip_def.search(cr, uid, []) for ip_def in totp_ip_def.browse(cr, uid, ip_def_ids): if ip_def.ip_type == 'host': if (ip_def.ip_value == '*') or (remote_ip == ipaddr.IPAddress( ip_def.ip_value)): need_totp = ip_def.login_mode break elif ip_def.ip_type == 'network': if (ip_def.ip_value == '*') or (remote_ip in ipaddr.IPNetwork( ip_def.ip_value)): need_totp = ip_def.login_mode break _logger.debug( "******** TOTP authentication rule %s matches for IP %s - procedure '%s' applies.", str(ip_def.sequence), str(remote_ip), ip_def.login_mode) if need_totp == 'usetotp': if user_sec and totp_pin and valid_totp( user_totp, user_sec): return self.session_info(req) else: _logger.debug( "******** TOTP authentication failed because of invalid TOTP!" ) return False return self.session_info(req)
def cas_authenticate(self, req, dbname, cur_url, cas_host, auto_create, ticket): """ Checks if the user attempts to authenticate is authorized to do it and, if it is, authenticate him. """ # cas_server = cas_host + ':' + cas_port cas_server = cas_host service_url = urllib.quote(cur_url, safe='') # The login function, from pycas, check if the ticket given by # CAS is a real ticket. The login of the user # connected by CAS is returned. status, idUser, cookie = login(cas_server, service_url, ticket) result = False if idUser and status == 0: cr = pooler.get_db(dbname).cursor() registry = RegistryManager.get(dbname) users = registry.get('res.users') ids = users.search(cr, SUPERUSER_ID, [('login', '=', idUser)]) assert len(ids) < 2 # We check if the user authenticated have an OpenERP account or if # the auto_create field is True if ids or auto_create == 'True': if ids: user_id = ids[0] # If the user have no account, we create one else: user_id = users.create(cr, SUPERUSER_ID, { 'name': idUser.capitalize(), 'login': idUser }) # A random key is generated in order to verify if the # login request come from here or if the user # try to authenticate by any other way cas_key = randomString(16, '0123456789abcdefghijklmnopqrstuvwxyz') users.write(cr, SUPERUSER_ID, [user_id], {'cas_key': cas_key}) cr.commit() login_and_redirect(dbname, idUser, cas_key) result = {'status': status, 'session_id': req.session_id} else: result = { 'status': status, 'fail': True, 'session_id': req.session_id } cr.close() if not result: result = {'status': status} return result
def signin(self, req, **kw): """JS client obtained a saml token and passed it back to us... we need to validate it """ saml_response = kw.get('SAMLResponse', None) if not kw.get('RelayState', None): # here we are in front of a client that went through # some routes that "lost" its relaystate... this can happen # if the client visited his IDP and successfully logged in # then the IDP gave him a portal with his available applications # but the provided link does not include the necessary relaystate url = "/?type=signup" redirect = werkzeug.utils.redirect(url, 303) redirect.autocorrect_location_header = True return redirect state = simplejson.loads(kw['RelayState']) dbname = state['d'] provider = state['p'] context = state.get('c', {}) registry = RegistryManager.get(dbname) with registry.cursor() as cr: try: u = registry.get('res.users') credentials = u.auth_saml(cr, SUPERUSER_ID, provider, saml_response, context=context) cr.commit() action = state.get('a') menu = state.get('m') url = '/' if action: url = '/#action=%s' % action elif menu: url = '/#menu_id=%s' % menu return login_and_redirect(req, *credentials, redirect_url=url) except AttributeError, e: print e # auth_signup is not installed _logger.error("auth_signup not installed on database " "%s: saml sign up cancelled." % (dbname, )) url = "/#action=login&saml_error=1" except openerp.exceptions.AccessDenied: # saml credentials not valid, # user could be on a temporary session _logger.info('SAML2: access denied, redirect to main page ' 'in case a valid session exists, ' 'without setting cookies') url = "/#action=login&saml_error=3" redirect = werkzeug.utils.redirect(url, 303) redirect.autocorrect_location_header = False return redirect