def _scan_disk(self, cr, uid, context=None):
        """Scan the file system and register the result in database"""
        found_fonts = []
        for font_path in customfonts.list_all_sysfonts():
            try:
                font = ttfonts.TTFontFile(font_path)
                _logger.debug("Found font %s at %s", font.name, font_path)
                found_fonts.append((font.familyName, font.name, font_path, font.styleName))
            except ttfonts.TTFError:
                _logger.warning("Could not register Font %s", font_path)

        for family, name, path, mode in found_fonts:
            if not self.search(cr, uid, [('family', '=', family), ('name', '=', name)], context=context):
                self.create(cr, uid, {
                    'family': family, 'name': name,
                    'path': path, 'mode': mode,
                }, context=context)

        # remove fonts not present on the disk anymore
        existing_font_names = [name for (family, name, path, mode) in found_fonts]
        inexistant_fonts = self.search(cr, uid, [('name', 'not in', existing_font_names), ('path', '!=', '/dev/null')], context=context)
        if inexistant_fonts:
            self.unlink(cr, uid, inexistant_fonts, context=context)

        RegistryManager.signal_caches_change(cr.dbname)
        self._sync(cr, uid, context=context)
        return True
    def session(self):
        """ Context Manager: start a new session and ensure that the
        session's cursor is:

        * rollbacked on errors
        * commited at the end of the ``with`` context when no error occured
        * always closed at the end of the ``with`` context
        * it handles the registry signaling
        """
        with openerp.api.Environment.manage():
            db = openerp.sql_db.db_connect(self.db_name)
            session = ConnectorSession(db.cursor(),
                                       self.uid,
                                       context=self.context)

            try:
                with session.env.clear_upon_failure():
                    RegistryManager.check_registry_signaling(self.db_name)
                    yield session
                    RegistryManager.signal_caches_change(self.db_name)
            except:
                session.rollback()
                raise
            else:
                session.commit()
            finally:
                session.close()
示例#3
0
    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 ""
示例#4
0
 def create(self, vals):
     vals['state'] = 'done'
     rule = super(AuditRule, self).create(vals)
     rule.update_rule()
     if self._register_hook(rule.id):
         RegistryManager.signal_registry_change(self.env.cr.dbname)
     return rule
示例#5
0
 def clear_cache(self, cr):
     """clear cache and update models. Notify other workers to restart their registry."""
     self.precision_get.clear_cache(self)
     for obj in self.pool.obj_list():
         for colname, col in self.pool.get(obj)._columns.items():
             if hasattr(col, 'digits_change'):
                 col.digits_change(cr)
     RegistryManager.signal_caches_change(cr.dbname)
示例#6
0
 def _update_registry(self, cr, uid, context=None):
     """ Update the registry after a modification on action rules. """
     if self.pool.ready:
         # for the sake of simplicity, simply force the registry to reload
         cr.commit()
         openerp.api.Environment.reset()
         RegistryManager.new(cr.dbname)
         RegistryManager.signal_registry_change(cr.dbname)
示例#7
0
 def clear_cache(self, cr):
     """clear cache and update models. Notify other workers to restart their registry."""
     self.precision_get.clear_cache(self)
     env = openerp.api.Environment(cr, SUPERUSER_ID, {})
     for model in self.pool.values():
         for field in model._fields.values():
             if field.type == 'float':
                 field._setup_digits(env)
     RegistryManager.signal_caches_change(cr.dbname)
示例#8
0
    def test_02_uninstall(self):
        """ Check a few things showing the module is uninstalled. """
        with environment() as env:
            module = env['ir.module.module'].search([('name', '=', MODULE)])
            assert len(module) == 1
            module.button_uninstall()
        RegistryManager.new(common.get_db_name(), update_module=True)

        with environment() as env:
            self.assertNotIn('test_uninstall.model', env.registry)
            self.assertFalse(env['ir.model.data'].search([('module', '=', MODULE)]))
            self.assertFalse(env['ir.model.fields'].search([('model', '=', MODEL)]))
示例#9
0
文件: outbound.py 项目: dhl/frePPLe
    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"
示例#10
0
    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
示例#11
0
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
示例#12
0
 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)
示例#13
0
 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, {})
示例#14
0
文件: outbound.py 项目: DwBu/frePPLe
    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'
示例#15
0
    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)
示例#16
0
文件: web.py 项目: odoocn/odoo-dev
    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)
示例#17
0
    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'
示例#18
0
 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
示例#19
0
文件: web.py 项目: vnsofthe/odoo-dev
    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)
示例#20
0
    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+"&timestamp="+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 __enter__(self):
     """
     Context enter function.
     Temporarily add odoo 8 server path to system path and pop afterwards.
     Import odoo 8 server from path as library.
     Init logger, registry and environment.
     Add addons path to config.
     :returns Odoo8Context: This instance
     """
     sys.path.append(self.server_path)
     from openerp import netsvc, api
     from openerp.modules.registry import RegistryManager
     from openerp.tools import trans_export, config, trans_load_data
     self.trans_export = trans_export
     self.trans_load_data = trans_load_data
     sys.path.pop()
     netsvc.init_logger()
     config['addons_path'] = (
         config.get('addons_path') + ',' + self.addons_path
     )
     registry = RegistryManager.new(self.dbname)
     self.environment_manage = api.Environment.manage()
     self.environment_manage.__enter__()
     self.cr = registry.cursor()
     return self
示例#22
0
文件: web.py 项目: vnsofthe/odoo-dev
    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"
示例#23
0
文件: web.py 项目: odoocn/odoo-dev
    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)
示例#24
0
    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
示例#25
0
文件: web.py 项目: vnsofthe/odoo-dev
    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)
示例#26
0
文件: web.py 项目: odoocn/odoo-dev
    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)
示例#27
0
文件: web.py 项目: odoocn/odoo-dev
    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)
示例#28
0
 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
示例#29
0
 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"
示例#30
0
文件: web.py 项目: odoocn/odoo-dev
 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 change_password(self, cr, uid, old_passwd, new_passwd, context=None):
        """Change current user password. Old password must be provided explicitly
        to prevent hijacking an existing user session, or for cases where the cleartext
        password is not used to authenticate requests.

        :return: True
        :raise: openerp.exceptions.AccessDenied when old password is wrong
        :raise: except_osv when new password is not set or empty
        """
        cr.execute(
            'SELECT ldap_user FROM res_users WHERE id=%s AND active=TRUE',
            (int(uid), ))
        res = cr.fetchone()
        if not res[0]:
            cr.execute(
                'SELECT login FROM res_users WHERE id=%s AND active=TRUE',
                (int(uid), ))
            login = cr.fetchone()
            user_id = super(users, self)._login(cr.dbname, login[0],
                                                old_passwd)
            if user_id:
                return self.write(cr, SUPERUSER_ID, uid,
                                  {'password': new_passwd})
            else:
                raise openerp.exceptions.AccessDenied
        else:
            try:
                super(users, self).check(cr.dbname, uid, old_passwd)
            except openerp.exceptions.AccessDenied:
                raise

            cr.execute(
                'SELECT login FROM res_users WHERE id=%s AND active=TRUE',
                (int(uid), ))
            res = cr.fetchone()
            if not res:
                raise openerp.exceptions.AccessDenied()

            login = res[0]
            registry = RegistryManager.get(cr.dbname)
            with registry.cursor() as cr:
                ldap_obj = registry.get('res.company.ldap')
                for conf in ldap_obj.get_ldap_dicts(cr):
                    entry = ldap_obj.authenticate(conf, login, old_passwd)
                    if entry:
                        # todo
                        # modify password
                        try:
                            ldap_obj.change_password(conf, login, new_passwd)
                            return res
                        except:
                            raise
示例#32
0
    def __init__(self, cursor, uid, name, context):
        super(PartnersLedgerWebkit, self).__init__(cursor,
                                                   uid,
                                                   name,
                                                   context=context)
        self.pool = RegistryManager.get(self.cr.dbname)
        self.cursor = self.cr

        company = self.pool.get('res.users').browse(self.cr,
                                                    uid,
                                                    uid,
                                                    context=context).company_id
        header_report_name = ' - '.join(
            (_('PARTNER LEDGER'), company.name, company.currency_id.name))

        footer_date_time = self.formatLang(str(datetime.today()),
                                           date_time=True)

        self.localcontext.update({
            'cr':
            cursor,
            'uid':
            uid,
            'report_name':
            _('Partner Ledger'),
            'display_account_raw':
            self._get_display_account_raw,
            'filter_form':
            self._get_filter,
            'target_move':
            self._get_target_move,
            'initial_balance':
            self._get_initial_balance,
            'amount_currency':
            self._get_amount_currency,
            'display_partner_account':
            self._get_display_partner_account,
            'display_target_move':
            self._get_display_target_move,
            'additional_args': [
                ('--header-font-name', 'Helvetica'),
                ('--footer-font-name', 'Helvetica'),
                ('--header-font-size', '10'),
                ('--footer-font-size', '6'),
                ('--header-left', header_report_name),
                ('--header-spacing', '2'),
                ('--footer-left', footer_date_time),
                ('--footer-right', ' '.join(
                    (_('Page'), '[page]', _('of'), '[topage]'))),
                ('--footer-line', ),
            ],
        })
示例#33
0
文件: web.py 项目: cash2one/odoo-dev
 def get_mas(self,**kw):
     #{'cardType': u'0002',
     # 'RRN': u'001093037866',
     # 'amt': u'1.00',
     # 'authCode': u'',
     # 'issuerId': u'03080000',
     # 'responseMessage': u'\ufffd\ufffd\ufffd\u05f3\u0279\ufffd',
     # 'terminalId': u'35076467',
     # 'externalTraceNo': u'',
     # 'terminalOperId': u'001',
     # 'issuerIdView': u'\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd',
     # 'txnTime': u'20150615 101913',
     # 'shortPAN': u'6225887199',
     # 'orgTxnType': u'',
     # 'orgExternalTraceNo': u'',
     # 'responseCode': u'00',
     # 'signature': u'GVyliBwvRk2LPmtN/XwuuQopHeWXywRlsdl93YHRdx/uIO2RfE1zRKD66s1rdV8dlUBQqoHNjc1Rqtyd0K5EZXsEjR/NQoDnzJEmDn+4IA0TpbYvQnrKBTsvudfAB7CJxJ3OXIR38RyaoyNf+A/MW5CdUdFV+ElmflAaFp8ddgY=',
     # 'merchantId': u'812430080710001',
     # 'processFlag': u'0',
     # 'txnType': u'RFD'}
     _logger.warn(kw)
     registry = RegistryManager.get(request.session.db)
     for i in range(0,len(kw.get("issuerIdView"))):
         _logger.warn(ord(kw.get("issuerIdView")[i]))
     with registry.cursor() as cr:
         obj = registry.get("rhwl.99bill.mas")
         val={
             "card_type":kw.get("cardType"),
             "rrn":kw.get("RRN"),
             "issuer_id":kw.get("issuerId"),
             "issuer_id_view":bank_name.get(kw.get("issuerId").encode('utf-8')),
             "response_code":kw.get("responseCode"),
             "response_message":u"交易正常完成",
             "terminal_id":kw.get("terminalId"),
             "terminal_oper_id":kw.get("terminalOperId"),
             "txn_time":kw.get("txnTime",""),
             "txntime":datetime.datetime.strptime(kw.get("txnTime","").encode('utf-8'),'%Y%m%d %H%M%S')+datetime.timedelta(hours=-8),
             "short_pan":kw.get("shortPAN"),
             "org_txn_type":kw.get("orgTxnType"),
             "org_external_trace_no":kw.get("orgExternalTraceNo"),
             "external_trace_no":kw.get("externalTraceNo",""),
             "amt":kw.get("amt",0),
             "process_flag":kw.get("processFlag",False),
             "merchant_id":kw.get("merchantId"),
             "process_flag":True if kw.get("processFlag")==u"0" else False,
             "txn_type":kw.get("txnType"),
             "signature":kw.get("signature"),
         }
         if val.get("response_code")==u"00":
             obj.create(cr,SUPERUSER_ID,val)
             cr.commit()
     return "0"
示例#34
0
 def button_reload(self, cr, uid, ids, context=None):
     for module_record in self.browse(cr, uid, ids, context=context):
         #Remove any report parsers registered for this module.
         module_path = 'addons/' + module_record.name
         for service_name, service in Service._services.items():
             template = getattr(service, 'tmpl', '')
             if type(template) == type(''):
                 if template.startswith(module_path):
                     Service.remove(service_name)
         
         #Remove any model classes registered for this module
         MetaModel.module_to_models[module_record.name] = []                    
         
         #Reload all Python modules from the OpenERP module's directory.
         modulename = 'openerp.addons.' + module_record.name
         root = __import__(modulename)
         module = getattr(root.addons, module_record.name)
         
         reimport(module)
     RegistryManager.delete(cr.dbname)
     RegistryManager.new(cr.dbname)
     return {}
示例#35
0
 def reset_password(self, dbname, login):
     """ retrieve user, and perform reset password """
     registry = RegistryManager.get(dbname)
     with registry.cursor() as cr:
         try:
             res_users = registry.get('res.users')
             res_users.reset_password(cr, openerp.SUPERUSER_ID, login)
             cr.commit()
         except Exception as e:
             # signup error
             _logger.exception('error when resetting password')
             raise (e)
     return True
示例#36
0
    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("rhwl.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("rhwl.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("rhwl.weixin.base")
                orig.action_unsubscribe(cr, toUser, fromUser, AgentID)
            return self.replyWeiXin(fromUser, toUser, u"祝您生活愉快!", encrypt,
                                    AgentID, kw)
        else:
            return ""
 def _init_test_model(self, all_cls):
     pool = RegistryManager.get(common.DB)
     all_inst = []
     for cls in all_cls:
         inst = cls._build_model(pool, self.cr)
         inst._prepare_setup(self.cr, SUPERUSER_ID)
         inst._setup_base(self.cr, SUPERUSER_ID, partial=False)
         all_inst.append(inst)
     for inst in all_inst:
         inst._setup_fields(self.cr, SUPERUSER_ID)
         inst._setup_complete(self.cr, SUPERUSER_ID)
     for inst in all_inst:
         inst._auto_init(self.cr, {'module': __name__})
示例#38
0
 def login(self, db, login, password):
     result = super(res_users, self).login(db, login, password)
     if result:
         return result
     else:
         with RegistryManager.get(db).cursor() as cr:
             cr.execute("""UPDATE res_users
                             SET login_date=now() AT TIME ZONE 'UTC'
                             WHERE login=%s AND openid_key=%s AND active=%s RETURNING id""",
                        (tools.ustr(login), tools.ustr(password), True))
             res = cr.fetchone()
             cr.commit()
             return res[0] if res else False
示例#39
0
    def _post_detail(self, **kw):
        if not request.uid:
            return "权限不足"
        registry = RegistryManager.get(request.session.db)
        with registry.cursor() as cr:
            user = registry.get("res.users")
            user_obj = user.browse(cr, SUPERUSER_ID, request.uid)
            if not user.has_group(cr, request.uid, "mongo.rhwl_mongo_manager"):
                return "权限不足"

        db = self._get_cursor()
        contents = db.products.find_one({"_id":
                                         kw.get("id").encode("utf-8")})  #取套餐数据
        no = contents.get(kw.get("lang")).get("sets").get(
            kw.get("tc")).get("list").get(kw.get("no"))

        pd = db.prodata.find_one({"_id": no})

        for k, v in kw.items():
            if (k in ["lang", "id", "tc", "no"]): continue
            key = k.split("_")
            if (len(key) == 1):
                if (key[0] == "pic"):
                    mimetype = kw.get("pic").mimetype
                    fs = base64.encodestring(kw.get("pic").stream.read())
                    if not (mimetype and fs): continue
                    if not pd[kw.get("lang")].has_key(key[0]):
                        pd[kw.get("lang")][key[0]] = {
                            "base64": "",
                            "mimetype": ""
                        }
                    if not isinstance(pd[kw.get("lang")][key[0]], (dict, )):
                        pd[kw.get("lang")][key[0]] = {
                            "base64": "",
                            "mimetype": ""
                        }
                    pd[kw.get("lang")][key[0]]["base64"] = fs
                    pd[kw.get("lang")][key[0]]["mimetype"] = mimetype
                elif (key[0] == "sex"):
                    pd["sex"] = kw.get("sex")
                else:
                    pd[kw.get("lang")][key[0]] = v
            elif (len(key) == 2):
                if not pd[kw.get("lang")].has_key(key[0]):
                    pd[kw.get("lang")][key[0]] = {}
                pd[kw.get("lang")][key[0]][key[1]] = v
        db.prodata.update({"_id": no}, pd)

        response = request.make_response(
            "数据提交成功,<a href=\"javascript:history.back(-2);\">后退</a>")
        return response.make_conditional(request.httprequest)
示例#40
0
文件: web.py 项目: cash2one/odoo-dev
    def app_result(self,**kw):
        res = self.check_userinfo(kw)
        data = {}
        check_state={
            'get': u'已接收',
            'library': u'已进实验室',
            'pc': u'已上机',
            'reuse': u'需重采血',
            'ok': u'检验结果正常',
             'except': 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')
                    if res.get("params").get("name"):
                        reuseid = sampleone.search(cr,uid,['|',('yfxm','ilike',res.get("params").get("name")),('name','ilike',res.get("params").get("name"))])
                        data=[]
                        for i in sampleone.browse(cr,uid,reuseid,context=self.CONTEXT):
                            data.append({
                                "time":i.cx_date,
                                "name":i.yfxm,
                                "code":i.name,
                                "status":rhwl_sale.rhwl_sale_state_select.get(i.check_state)
                            })
                    else:
                        reuseid = sampleone.search(cr,uid,[('cx_date','<=',datetime.date.today()),('cx_date','>',datetime.timedelta(-17) + datetime.date.today())],order="cx_date desc,id desc",context={'tz': "Asia/Shanghai"})
                        temp = {}
                        except_count=0
                        for i in sampleone.browse(cr,uid,reuseid,context=self.CONTEXT):
                            if not temp.has_key(i.cx_date):
                                temp[i.cx_date]=[]
                            if i.check_state in ['reuse','except']:
                                except_count +=1
                            temp[i.cx_date].append({
                                "name":i.yfxm,
                                "code":i.name,
                                "status":rhwl_sale.rhwl_sale_state_select.get(i.check_state)
                            })
                        data = [{"exception":str(except_count)+u"个"},]

                        for v in [(k,temp[k]) for k in sorted(temp.keys(),reverse=True)] :
                            data.append({"time":v[0],"datas":v[1]})
                    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)
示例#41
0
    def create(self, cr, uid, ids, data, context=None):
        pool = RegistryManager.get(cr.dbname)
        ir_obj = pool.get('ir.actions.report.xml')
        report_xml_ids = ir_obj.search(cr,
                                       uid,
                                       [('report_name', '=', self.name[7:])],
                                       context=context)
        if report_xml_ids:
            report_xml = ir_obj.browse(cr,
                                       uid,
                                       report_xml_ids[0],
                                       context=context)
        else:
            title = ''
            rml = tools.file_open(self.tmpl, subdir=None).read()
            report_type = data.get('report_type', 'pdf')

            class a(object):
                def __init__(self, *args, **argv):
                    for key, arg in argv.items():
                        setattr(self, key, arg)

            report_xml = a(title=title,
                           report_type=report_type,
                           report_rml_content=rml,
                           name=title,
                           attachment=False,
                           header=self.header)

        report_type = report_xml.report_type
        if report_type in ['sxw', 'odt']:
            fnct = self.create_source_odt
        elif report_type in ['pdf', 'raw', 'txt', 'html']:
            fnct = self.create_source_pdf
        elif report_type == 'html2html':
            fnct = self.create_source_html2html
        elif report_type == 'mako2html':
            fnct = self.create_source_mako2html
        elif report_type == 'aeroo':
            if report_xml.out_format.code in ['oo-pdf']:
                fnct = self.create_source_pdf
            elif report_xml.out_format.code in [
                    'oo-odt', 'oo-ods', 'oo-doc', 'oo-xls', 'genshi-raw'
            ]:
                fnct = self.create_source_odt
            else:
                return super(Aeroo_report,
                             self).create(cr, uid, ids, data, context)
        else:
            raise Exception('Unknown Report Type')
        return fnct(cr, uid, ids, data, report_xml, context)
示例#42
0
    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
示例#43
0
    def create(self, vals):
        if self._context and self._context.get('bve'):
            vals['state'] = 'base'
        res = super(IrModel, self).create(vals)

        # this sql update is necessary since a write method here would
        # be not working (an orm constraint is restricting the modification
        # of the state field while updating ir.model)
        q = ("""UPDATE ir_model SET state = 'manual'
               WHERE id = """ + str(res.id))
        self.env.cr.execute(q)

        # update registry
        if self._context.get('bve'):

            # add model in registry
            self.instanciate(vals['model'])
            self.pool.setup_models(self.env.cr, partial=(not self.pool.ready))

            # signal that registry has changed
            RegistryManager.signal_registry_change(self.env.cr.dbname)

        return res
    def session(self, db_name):
        """ Context Manager: start a new session and ensure that the
        session's cursor is:

        * rollbacked on errors
        * commited at the end of the ``with`` context when no error occured
        * always closed at the end of the ``with`` context
        * it handles the registry signaling
        """
        db = openerp.sql_db.db_connect(db_name)
        cr = db.cursor()

        try:
            RegistryManager.check_registry_signaling(db_name)
            yield cr
            RegistryManager.signal_caches_change(db_name)
        except:
            cr.rollback()
            raise
        else:
            cr.commit()
        finally:
            cr.close()
示例#45
0
 def _check_accounting_configured(self):
     #minimal setUp() similar to the one of TransactionCase, although we can't use the regular setUp()
     #because we want to assume the accounting is already configured when making the setUp of tests.
     self.registry = RegistryManager.get(DB)
     self.cr = self.cursor()
     self.uid = SUPERUSER_ID
     self.env = api.Environment(self.cr, self.uid, {})
     #having at least one account created means the accounting is ready to be tested
     res = bool(self.env['account.account'].search([
         ('company_id', '=', self.env.ref('base.main_company').id)
     ]))
     #close the cursor, eventually rolleback and reset the environment
     self.tearDown()
     return res
示例#46
0
    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, {})

        @self.addCleanup
        def reset():
            # rollback and close the cursor, and reset the environments
            self.env.reset()
            self.cr.rollback()
            self.cr.close()
示例#47
0
文件: web.py 项目: cash2one/odoo-dev
 def app_woman(self,**kw):
     res = self.check_userinfo(kw)
     data = {}
     if res.get('statu')==200:
         id = res.get("params").get("pregnantWomanID") #样品编码
         uid = res.get("userid")
         if id:
             registry = RegistryManager.get(request.session.db)
             with registry.cursor() as cr:
                 sampleone = registry.get('sale.sampleone')
                 ids = sampleone.search(cr,uid,[('name','=',id)])
                 obj = sampleone.browse(cr,uid,ids)
                 data = {
                     "pregnantWomanID":obj.name,
                     "pregnantWomanName":obj.yfxm,
                     "gestationalWeeks":str(obj.yfyzweek)+u"周+"+str(obj.yfyzday)+u"天",
                     "takeBloodTime":obj.cx_date,
                     "state":rhwl_sale.rhwl_sale_state_select.get(obj.check_state),
                     "phoneNumber":obj.yftelno and obj.yftelno or "",
                     "emergencyCall":obj.yfjjlltel and obj.yfjjlltel or "",
                     "reTakeBloodID":"",
                     "report":"",
                     "btn":"None"
                 }
                 if obj.check_state == "reuse":
                     #需重采血
                     reused_obj =registry.get('sale.sampleone.reuse')
                     reuseid = reused_obj.search(cr,uid,[('name.name','=',id)])
                     if reuseid:
                         reused = reused_obj.browse(cr,uid,reuseid,context=self.CONTEXT)
                         data['reTakeBloodID'] = reused.newname.name
                         if reused.state=="draft":
                             data['btn'] = "1"
                         elif reused.state=="done":
                             data["btn"] = "0"
                 elif obj.check_state=="except":
                     #阳性
                     reused_obj =registry.get('sale.sampleone.exception')
                     reuseid = reused_obj.search(cr,uid,[('name.name','=',id)])
                     if reuseid:
                         reused = reused_obj.browse(cr,uid,reuseid,context=self.CONTEXT)
                         if reused.state=="draft":
                             data['btn'] = "1"
                         elif reused.state=="notice":
                             data["btn"] = "0"
                 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)
示例#48
0
 def list_providers(self, req, dbname):
     try:
         registry = RegistryManager.get(dbname)
         with registry.cursor() as cr:
             providers = registry.get('auth.oauth.provider')
             l = providers.read(
                 cr, SUPERUSER_ID,
                 providers.search(cr, SUPERUSER_ID,
                                  [('enabled', '=', True),
                                   ('auth_endpoint', '!=', False),
                                   ('validation_endpoint', '!=', False)]))
     except Exception:
         l = []
     return l
def migrate(cr, version):
    pool = RegistryManager.get(cr.dbname)

    openupgrade.map_values(cr,
                           openupgrade.get_legacy_name('priority'),
                           'priority', [('5', '0'), ('4', '0'), ('3', '1'),
                                        ('2', '2'), ('1', '2')],
                           table='project_issue',
                           write='sql')

    openupgrade_80.set_message_last_post(cr, uid, pool, ['project.issue'])

    openupgrade.load_data(cr, 'project_issue',
                          'migrations/8.0.1.0/noupdate_changes.xml')
示例#50
0
文件: main.py 项目: tedi3231/openerp
 def get_config(self, req, dbname):
     """ retrieve the module config (which features are enabled) for the login page """
     registry = RegistryManager.get(dbname)
     with registry.cursor() as cr:
         icp = registry.get('ir.config_parameter')
         config = {
             'signup':
             icp.get_param(cr, openerp.SUPERUSER_ID,
                           'auth_signup.allow_uninvited') == 'True',
             'reset_password':
             icp.get_param(cr, openerp.SUPERUSER_ID,
                           'auth_signup.reset_password') == 'True',
         }
     return config
示例#51
0
 def login(self, db, login, password):
     user_id = super(users, self).login(db, login, password)
     if user_id:
         return user_id
     registry = RegistryManager.get(db)
     with registry.cursor() as cr:
         ldap_obj = registry.get('res.company.ldap')
         for conf in ldap_obj.get_ldap_dicts(cr):
             entry = ldap_obj.authenticate(conf, login, password)
             if entry:
                 user_id = ldap_obj.get_or_create_user(
                     cr, SUPERUSER_ID, conf, login, entry)
                 if user_id:
                     break
         return user_id
示例#52
0
    def wechat_unbinding(self, mobile):
        db = RegistryManager.get(request.db)
        user = openerp.registry(request.db)['res.users']

        with closing(db.cursor()) as cr:
            users = user.search(cr, 1, [('oauth_access_token', '=', mobile)])
            user.write(cr, 1, users[0], {'oauth_access_token': False})

            cr.commit()

        return request.make_response(
            simplejson.dumps({
                'state': 'done',
                'message': u'解除绑定成功'
            }))
示例#53
0
 def check(self, db, uid, passwd):
     try:
         return super(res_users, self).check(db, uid, passwd)
     except openerp.exceptions.AccessDenied:
         if not passwd:
             raise
         with RegistryManager.get(db).cursor() as cr:
             cr.execute('''SELECT COUNT(1)
                             FROM res_users
                            WHERE id=%s
                              AND active=%s''',
                         (int(uid), True))
             if not cr.fetchone()[0]:
                 raise
             self._uid_cache.setdefault(db, {})[uid] = passwd
示例#54
0
文件: web.py 项目: cash2one/odoo-dev
    def hospital(self):
        request.session.db = self.get_dbname()
        registry = RegistryManager.get(request.session.db)
        with registry.cursor() as cr:
            try:
                u = registry.get('res.partner')
                data = u.get_hospital(cr, SUPERUSER_ID, context=None)
                cr.commit()
            except:
                return "Get Hospital Error "

        #request.session.authenticate(request.session.db,"admin","123")
        #data = request.session.model("res.partner").get_hospital()
        response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')])
        return response.make_conditional(request.httprequest)
示例#55
0
文件: web.py 项目: cash2one/odoo-dev
 def address_list(self,**kw):
     res = self.check_userinfo(kw)
     data = []
     if res.get('statu')==200:
         uid = res.get("userid")
         registry = RegistryManager.get(request.session.db)
         with registry.cursor() as cr:
             obj = registry.get("hr.employee")
             ids = obj.search(cr,uid,[("department_id","!=",False)],context=self.CONTEXT)
             for i in obj.browse(cr,uid,ids,context=self.CONTEXT):
                 data.append((i.department_id.id,i.department_id.name,i.name,i.user_id.mobile and i.user_id.mobile or i.mobile_phone))
     else:
         data = res
     response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')])
     return response.make_conditional(request.httprequest)
示例#56
0
文件: web.py 项目: cash2one/odoo-dev
 def _rhwl_partner_get(self,**kw):
     res = self.check_userinfo(kw)
     data = []
     if res.get('statu')==200:
         uid = res.get("userid")
         registry = RegistryManager.get(request.session.db)
         with registry.cursor() as cr:
             obj = registry.get("res.partner")
             ids = obj.search(cr,uid,['|','|','|',("sjjysj","!=",False),("yg_sjjysj","!=",False),("ys_sjjysj","!=",False),("el_sjjysj","!=",False)],context=self.CONTEXT)
             for i in obj.browse(cr,uid,ids,context=self.CONTEXT):
                 data.append((i.id,i.name))
     else:
         data = res
     response = request.make_response(json.dumps(data,ensure_ascii=False), [('Content-Type', 'application/json')])
     return response.make_conditional(request.httprequest)
示例#57
0
文件: web.py 项目: cash2one/odoo-dev
    def rhwl_sampleone_imagepost(self,**kw):
        registry = RegistryManager.get(request.session.db)
        obj = registry.get("sale.sampleone")
        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)
            img = img.transpose(Image.ROTATE_270)
            val={"img":base64.encodestring(img.tostring("jpeg",img.mode))}

            obj._post_images(cr,request.uid,id,val["img"],context={'lang': "zh_CN",'tz': "Asia/Shanghai","name":kw.get("no")})

            return "OK"
示例#58
0
def get_tree_top2low(objname,cr,uid,parent_id,context=None):
    """
自顶向下的寻找,不包含自己
"""
    print "objname is %s,cr.dbname is %s,uid is %s,parent_id is %s" % (objname,cr.dbname,uid,parent_id)
    if not objname:
        return None
    registry = RegistryManager.get(cr.dbname)
    rep = registry.get(objname)
    template = rep.read(cr,uid,parent_id,["parent_left","parent_right","id"],context=context)
    if not template:
        return None
    res = rep.search(cr,uid,[("parent_left",">",template["parent_left"]),("parent_right","<",template["parent_right"])],context=context)
    print "get_tree_low2top result is %s" % res
    return res
示例#59
0
文件: main.py 项目: tedi3231/openerp
 def reset_password(self, req, dbname, login):
     """ retrieve user, and perform reset password """
     registry = RegistryManager.get(dbname)
     with registry.cursor() as cr:
         try:
             res_users = registry.get('res.users')
             res_users.reset_password(cr, openerp.SUPERUSER_ID, login)
             cr.commit()
             message = 'An email has been sent with credentials to reset your password'
         except Exception as e:
             # signup error
             _logger.exception('error when resetting password')
             message = e.message
     params = [('action', 'login'), ('error_message', message)]
     return werkzeug.utils.redirect("/#" + urllib.urlencode(params))
示例#60
0
    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