Example #1
0
def dept_treeview():
    from mysite.iclock.models import Department
    vdata = filterdata_by_user(Department.objects.all(),threadlocals.get_current_user())
    for ii in vdata:
        if ii.parent_id is not None:
            l=[e for e in vdata if  e.id==ii.parent_id]
            if not l:ii.parent_id=None 
    return DeptTree(vdata).html_ul_li()
Example #2
0
 def limit_door_group_to(self, queryset):
     #需要过滤掉用户权限不能控制的门(需要按照id排序)
     u = threadlocals.get_current_user()
     aa = u.areaadmin_set.all()
     if not u.is_superuser and aa:#非超级用户如果a不为空则默认全部区域
         areas = [a.area for a in aa]
         from mysite.iclock.models import Device
         queryset = queryset.filter(device__area__in=areas).order_by('id')
     return queryset.order_by('id')
Example #3
0
def get_view_byname_js( model,view_name):        
        op=threadlocals.get_current_user()
        obj=ViewModel.objects.filter(model__exact=ContentType.objects.get_for_model(model),name__exact=view_name,create_operator__exact=op.username)
        ret=""
        if len(obj)>0:                
                ret=eval(obj[0].info)
                ret["viewtype"]=obj[0].viewtype
                ret={view_name:ret}
        return ret
Example #4
0
def get_view(request, app_label, model_name,view_name):
        model=GetModel(app_label, model_name)
        op=threadlocals.get_current_user()

        obj=ViewModel.objects.filter(model__exact=ContentType.objects.get_for_model(model),name__exact=view_name,create_operator__exact=op.username)
        ret=""
        if len(obj)>0:                
                ret=eval(obj[0].info)
                ret["viewtype"]=obj[0].viewtype
                ret=simplejson.dumps(ret)
        return getJSResponse(ret)
Example #5
0
def get_all_viewJson(model):
        op=threadlocals.get_current_user()
        
        vn=ViewModel.objects.filter(model__exact=ContentType.objects.get_for_model(model),create_operator__exact=op.username)        
        ret={}
        for i in vn:
                t=eval(i.info)
                t["viewtype"]=i.viewtype
                ret[i.name]=t
        
        return ret
Example #6
0
def user_perms(app_label_model_name):
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.auth.models import Permission
    from base.model_utils import GetModel
    from base.middleware import threadlocals
    user=threadlocals.get_current_user()
    split=app_label_model_name.split(".")
    m=GetModel(split[0],split[1])
    ct=ContentType.objects.get_for_model(m)
    perms=[p.codename for p in Permission.objects.filter(content_type=ct) if user.has_perm(split[0]+"."+p.codename)]
    perms=sorted(perms)
    return ".".join(perms)
Example #7
0
def set_msg_read(request,datakey):
    u=threadlocals.get_current_user()
    try:
        um=UsrMsg()
        um.user=u
        um.msg=InstantMsg.objects.filter(pk=datakey)[0]
        um.readtype="1"
        um.save()
        return getJSResponse('{ Info:"OK" }')
    except:
        import traceback; traceback.print_exc()
        return getJSResponse('{ Info:"exception!" }')
Example #8
0
def delete_view(request, app_label, model_name,view_name):
        try:
                        
                model=GetModel(app_label, model_name)
                op=threadlocals.get_current_user()
                
                ret=ViewModel.objects.filter(model__exact=ContentType.objects.get_for_model(model),name__exact=view_name,create_operator__exact=op.username)
                if len(ret)<=0:
                        return HttpResponse("View not found or You are not the view's creator !")
                ret.delete()
        except:
                return HttpResponse("delete fail !")
        return HttpResponse("delete Ok !")
Example #9
0
def set_msg_read(request, datakey):
    u = threadlocals.get_current_user()
    try:
        um = UsrMsg()
        um.user = u
        um.msg = InstantMsg.objects.filter(pk=datakey)[0]
        um.readtype = "1"
        um.save()
        return getJSResponse('{ Info:"OK" }')
    except:
        import traceback
        traceback.print_exc()
        return getJSResponse('{ Info:"exception!" }')
Example #10
0
 def limit_device_to(self, queryset):
     #需要过滤掉已经配置过的,当前自身(编辑时)以及单门控制器
     if self.device:
         v = AccInterLock.objects.exclude(
             device=self.device).values("device")
     else:
         v = AccInterLock.objects.values("device")
     q = queryset.filter(device_type=DEVICE_ACCESS_CONTROL_PANEL).filter(
         is_elevator=ACPANEL_AS_USUAL_ACPANEL).exclude(
             acpanel_type=ACPANEL_1_DOOR)  #门禁控制器
     return filterdata_by_user(
         q.exclude(pk__in=[item["device"] for item in v]),
         threadlocals.get_current_user())
Example #11
0
def get_all_viewJson(model):
    op = threadlocals.get_current_user()

    vn = ViewModel.objects.filter(
        model__exact=ContentType.objects.get_for_model(model),
        create_operator__exact=op.username)
    ret = {}
    for i in vn:
        t = eval(i.info)
        t["viewtype"] = i.viewtype
        ret[i.name] = t

    return ret
Example #12
0
    def render(self, name, data, attrs=None):
        #from mysite.personnel.views import get_dept_tree_data
        from django.core.urlresolvers import reverse

        #print "ZDeptChoiceWidget_render data", data

        if data is not None:
            try:
                data = int(data)
            except:
                pass
            if type(data) in (int, long):
                data = self.choices.queryset.model.objects.get(pk=data)
        if attrs: self.attrs.update(attrs)
        if 'id' not in self.attrs: self.attrs['id'] = 'id_' + name
        self.attrs['class'] = self.attrs['class'] + ' filetree r'
        self.attrs = self.build_attrs(self.attrs, name=name)
        required = ""
        if hasattr(self.choices.field,
                   "required") and self.choices.field.required:
            required = "class='wZBaseCharField required input_showDeptTree'"
        try:
            vdata = filterdata_by_user(
                self.choices.queryset.all().filter(isvalid=1),
                threadlocals.get_current_user())
            #            for ii in vdata:
            #                if ii.parent_id is not None:
            #                    l=[e for e in vdata if  e.id==ii.parent_id]
            #                    if not l:ii.parent_id=None
            html = u"<div id='999' class='title' style='margin-left: 0px;'>"\
                    "<p style='margin-right: 110px;'>%s&nbsp; %s &nbsp; &nbsp; %s</p></div>" % (_(u'开始时间'), _(u'结束时间'), _(u'金额'))
            html += DeptTree(vdata).html_ul_li(data and [data.pk] or [])
            html_el = {
                "disp": data or "",
                "name": name,
                "value": data and data.pk or "",
                "attr": flatatt(self.attrs),
                "required": required,
                "id": self.attrs['id'],
                "uid": "%s" % id(self),
                "none": _(u"撤销选择").capitalize(),
                "items": html,
                "ok": _(u"确定")
            }
            if self.flat == False:  #平铺
                return ('<input %(required)s class="wZBaseCharField input_showDeptTree" type="text" readonly="readonly" value="%(disp)s"><input type=hidden name="%(name)s" value="%(value)s">' + \
                                u'<span class="btn_showDeptTree"><img onclick="render_dept_dropdown(this, false)" src="/media/img/sug_down_on.gif" id="id_drop_dept"><div  id="show_deptment" style="display: none;"><div class="title"><span class="span_selectNone Link_blue1" onclick="clear_none(this)"><a href="javascript: void(0)">%(none)s</a>&nbsp;&nbsp;</span><span onclick="javascript:$(this).parent().parent().hide();" class="close btn">%(ok)s</span></div><div id="id_dept"><ul %(attr)s>%(items)s</ul></div></div></span>') % html_el
            else:
                return u'<input type=hidden><input value="%(disp)s" type=hidden>%(value)s<div id="show_deptment"><div id=%(uid)s><ul %(attr)s>%(items)s</ul></div><script>render_dept_($("#%(uid)s"),false,true)</script></div>' % html_el
        except:
            print_exc()
Example #13
0
 def limit_parent_to(self, queryset):
     #根部门不存在上级部门.
     if self.pk == 1:
         return Department.objects.none()
     valid_depts = filterdata_by_user(queryset, threadlocals.get_current_user())
     if self.pk:
         invalid_pks = [self.pk]#限制不能设置一个部门的上级部门为其自身
         
         for dept in valid_depts:
             if self in get_dept_parents(valid_depts,dept):#限制不能设置一个部门的上级部门为子部门
                 invalid_pks.append(dept.pk)
         return valid_depts.exclude(pk__in=invalid_pks)
     else:
         return valid_depts
Example #14
0
def get_view(request, app_label, model_name, view_name):
    model = GetModel(app_label, model_name)
    op = threadlocals.get_current_user()

    obj = ViewModel.objects.filter(
        model__exact=ContentType.objects.get_for_model(model),
        name__exact=view_name,
        create_operator__exact=op.username)
    ret = ""
    if len(obj) > 0:
        ret = eval(obj[0].info)
        ret["viewtype"] = obj[0].viewtype
        ret = simplejson.dumps(ret)
    return getJSResponse(ret)
Example #15
0
def get_instant_msg(request):
    '''
    即时信息数据视图
    '''
    from dbapp.data_viewdb import model_data_list
    from django.contrib.auth.models import User,Group
    from django.template.defaultfilters import escapejs
    from django.db.models import Q
    import json
    u=threadlocals.get_current_user()
    if u and u.is_anonymous():
        return getJSResponse(u"[]")
    d={}
    qs=None
    [SYSMSG,ATTMSG,IACCESSMSG,PERSONNELMSG]=[1,2,3,4 ]
    exclude_msgtype=[]
    if "mysite.att" not in settings.INSTALLED_APPS:
        exclude_msgtype.append(ATTMSG)
    if "mysite.iaccess" not in settings.INSTALLED_APPS:
        exclude_msgtype.append(IACCESSMSG)

    msgtypes=MsgType.objects.exclude(pk__in=exclude_msgtype)
    dt=datetime.datetime.now()
    dt=datetime.datetime(year=dt.year,month=dt.month,day=dt.day)

    #持续时间过滤条件
    querys=[]
    for elem in msgtypes:
        begin_date=dt-datetime.timedelta(days=elem.msg_keep_time)
        querys.append((Q(change_time__gte=begin_date)&Q(msgtype=elem)))
    combine_query=querys[0]
    for i in querys[1:]:
        combine_query|=i

    #不是超级管理员过滤条件
    if not u.is_superuser:
        ms=GroupMsg.objects.filter(group__user=u).values_list("msgtype")
        d["msgtype__in"]=ms

    #是否已读过滤条件
    has_read=UsrMsg.objects.filter(user=u).values_list("msg")

    qs=InstantMsg.objects.filter(**d).exclude(id__in=has_read)
    qs=qs.filter(combine_query).order_by("-pk")

    json_data={"fields":["id","msgtype","content","change_time"],"data":[]}
    for ee in qs:
        json_data["data"].append([ee.id,u"%s"%ee.msgtype,ee.content,ee.change_time.strftime("%Y-%m-%d")])

    return getJSResponse(json.dumps(json_data))
Example #16
0
 def limit_parent_to(self, queryset):
     #根部门不存在上级部门.
     if self.pk == 1:
         from django.db.models.query import QuerySet
         return Department.objects.none()
     valid_depts = filterdata_by_user(queryset, threadlocals.get_current_user())
     if self.pk:
         invalid_pks = [self.pk]#限制不能设置一个部门的上级部门为其自身
         
         for dept in Department.objects.all():
             if self in dept.parents():#限制不能设置一个部门的上级部门为子部门
                 invalid_pks.append(dept.pk)
         return valid_depts.exclude(pk__in=invalid_pks)
     else:
         return valid_depts
Example #17
0
def user_perms(app_label_model_name):
    from django.contrib.contenttypes.models import ContentType
    from django.contrib.auth.models import Permission
    from dbapp.modelutils import GetModel
    from base.middleware import threadlocals
    user = threadlocals.get_current_user()
    split = app_label_model_name.split(".")
    m = GetModel(split[0], split[1])
    ct = ContentType.objects.get_for_model(m)
    perms = [
        p.codename for p in Permission.objects.filter(content_type=ct)
        if user.has_perm(split[0] + "." + p.codename)
    ]
    perms = sorted(perms)
    return ".".join(perms)
Example #18
0
 def limit_parent_to(self, queryset):
     #根区域不存在上级区域.
     if self.pk == 1:
         from django.db.models.query import QuerySet
         return Area.objects.none()
     valid_areas = filterdata_by_user(queryset, threadlocals.get_current_user())
     if self.pk:
         invalid_pks = [self.pk]#限制不能设置一个区域的上级区域为其自身
         
         for a in Area.objects.all():
             if self in a.parents():#限制不能设置一个区域的上级区域为子区域
                 invalid_pks.append(a.pk)
         return valid_areas.exclude(pk__in=invalid_pks)
     else:
         return valid_areas
Example #19
0
 def save(self, *args, **kwargs):
     try:
         if get_option("POS_ID"):
             if self.serialnum and self.sn_name:
                 iskey = "CarCashSZ_%s%s" % (self.serialnum, self.sn_name)
                 cache.set(iskey, self, TIMEOUT)
             op = threadlocals.get_current_user()
             self.create_operator = op.username
             serino = get_cardserial_from_cache(self.card)
             self.cardserial = serino
             models.Model.save(self, args)
         else:
             super(CarCashSZ, self).save()
     except:
         import traceback
         traceback.print_exc()
Example #20
0
    def limit_parent_to(self, queryset):
        #根区域不存在上级区域.
        if self.pk == 1:
            from django.db.models.query import QuerySet
            return Area.objects.none()
        valid_areas = filterdata_by_user(queryset,
                                         threadlocals.get_current_user())
        if self.pk:
            invalid_pks = [self.pk]  #限制不能设置一个区域的上级区域为其自身

            for a in Area.objects.all():
                if self in a.parents():  #限制不能设置一个区域的上级区域为子区域
                    invalid_pks.append(a.pk)
            return valid_areas.exclude(pk__in=invalid_pks)
        else:
            return valid_areas
Example #21
0
def get_instant_msg(request):
    from dbapp.dataviewdb import model_data_list
    from django.contrib.auth.models import User,Group
    from django.template.defaultfilters import escapejs
    from django.db.models import Q
    import json
    u=threadlocals.get_current_user()
    if u and u.is_anonymous():
        return getJSResponse(u"[]")
    d={}
    qs=None
    [SYSMSG,ATTMSG,IACCESSMSG,PERSONNELMSG]=[1,2,3,4 ]
    exclude_msgtype=[]
    if "mysite.att" not in settings.INSTALLED_APPS:
        exclude_msgtype.append(ATTMSG)
    if "mysite.iaccess" not in settings.INSTALLED_APPS:
        exclude_msgtype.append(IACCESSMSG)

    msgtypes=MsgType.objects.exclude(pk__in=exclude_msgtype)
    dt=datetime.datetime.now()
    dt=datetime.datetime(year=dt.year,month=dt.month,day=dt.day)

    #持续时间过滤条件
    querys=[]
    for elem in msgtypes:
        begin_date=dt-datetime.timedelta(days=elem.msg_keep_time)
        querys.append((Q(change_time__gte=begin_date)&Q(msgtype=elem)))
    combine_query=querys[0]
    for i in querys[1:]:
        combine_query|=i

    #不是超级管理员过滤条件
    if not u.is_superuser:
        ms=GroupMsg.objects.filter(group__user=u).values_list("msgtype")
        d["msgtype__in"]=ms

    #是否已读过滤条件
    has_read=UsrMsg.objects.filter(user=u).values_list("msg")

    qs=InstantMsg.objects.filter(**d).exclude(id__in=has_read)
    qs=qs.filter(combine_query).order_by("-pk")

    json_data={"fields":["id","msgtype","content","change_time"],"data":[]}
    for ee in qs:
        json_data["data"].append([ee.id,u"%s"%ee.msgtype,ee.content,ee.change_time.strftime("%Y-%m-%d")])

    return getJSResponse(json.dumps(json_data))
Example #22
0
    def render(self, name, data, attrs=None):
        from mysite.personnel.views import get_dept_tree_data
        from django.core.urlresolvers import reverse
        
        #print "ZDeptChoiceWidget_render data", data
       
        if data is not None:
            try:
                data=int(data)
            except:
                pass            
            if type(data) in (int, long):
                data=self.choices.queryset.model.objects.get(pk=data)
        if attrs: self.attrs.update(attrs)
        if 'id' not in self.attrs: self.attrs['id']='id_'+name
        self.attrs['class']=self.attrs['class']+' filetree r'
        self.attrs = self.build_attrs(self.attrs, name=name)
        required=""
        if hasattr(self.choices.field,"required") and self.choices.field.required:
            required="class='wZBaseCharField required input_showDeptTree'"
        try:
            vdata =filterdata_by_user(self.choices.queryset.all(),threadlocals.get_current_user())
            for ii in vdata:
                if ii.parent_id is not None:
                    l=[e for e in vdata if  e.id==ii.parent_id]
                    if not l:ii.parent_id=None 

            html=DeptTree(vdata).html_ul_li(data and [data.pk] or [])
            html_el={"disp": data or "",
                "name": name, 
                "value": data and data.pk or "", 
                "attr": flatatt(self.attrs),
                "required":required, 
                "id": self.attrs['id'], 
                "uid":"%s"%id(self),
                "none": _(u"撤销选择").capitalize(),
                "items": html,
                "ok":_(u"确定")}
            if self.flat==False:#平铺
                return ('<input %(required)s class="wZBaseCharField input_showDeptTree" type="text" readonly="readonly" value="%(disp)s"><input type=hidden name="%(name)s" value="%(value)s">'+\
                                u'<span class="btn_showDeptTree"><img onclick="render_dept_dropdown(this, false)" src="/media/img/sug_down_on.gif" id="id_drop_dept"><div  id="show_deptment" style="display: none;"><div class="title"><span class="span_selectNone Link_blue1" onclick="dept_tree_none(this)"><a href="javascript: void(0)">%(none)s</a>&nbsp;&nbsp;</span><span onclick="javascript:$(this).parent().parent().hide();" class="close btn">%(ok)s</span></div><div id="id_dept"><ul %(attr)s>%(items)s</ul></div></div></span>')%html_el            
            else:
                return u'<input type=hidden><input value="%(disp)s" type=hidden>%(value)s<div id="show_deptment"><div id=%(uid)s><ul %(attr)s>%(items)s</ul></div><script>render_dept_($("#%(uid)s"),false,true)</script></div>'%html_el
        except:
            print_exc()
Example #23
0
 def process_row(self, row_data, calculate_dict):
     from mysite.personnel.models import Employee
     from mysite.personnel.models.model_emp import format_pin
     from base.middleware import threadlocals
     op = threadlocals.get_current_user()
     key = u"%s" % _(u"人员编号")
     emp_pin = u"%s" % calculate_dict[key]
     emp_pin = format_pin(emp_pin)
     try:
         obj_emp = Employee.objects.get(PIN=emp_pin)
         row_data["user_id"] = obj_emp.pk  #初始化人员
     except:
         row_data["user_id"] = '0000'
     row_data["batch"] = datetime.datetime.now().strftime("%Y%m")[2:]
     row_data["date"] = datetime.datetime.now()
     row_data["is_pass"] = 1
     row_data["pass_name"] = op.username
     row_data["user_pin"] = emp_pin
     return row_data
Example #24
0
 def limit_door_group_to(self, queryset, limitleveltype=0):
     #需要过滤掉用户权限不能控制的门(需要按照id排序)
     if limitleveltype:  #先过滤控制器类型
         acptype = []
         if limitleveltype == 1:
             is_elevator = 0  #非电梯控制器
         else:
             if limitleveltype == 2:
                 is_elevator = 1  #电梯控制器
         from mysite.iclock.models import Device
         queryset = queryset.filter(
             device__is_elevator__exact=is_elevator).order_by('id')
     u = threadlocals.get_current_user()
     aa = u.areaadmin_set.all()
     if not u.is_superuser and aa:  #非超级用户如果a不为空则默认全部区域
         areas = [a.area for a in aa]
         from mysite.iclock.models import Device
         queryset = queryset.filter(device__area__in=areas).order_by('id')
     return queryset.order_by('id')
Example #25
0
    def render(self, name, data, attrs=None, choices=()):
        import time
        if data is not None:
            model=self.choices.queryset.model
            try:
                datapk = data
                data=[model.objects.get(pk=int(d)) for d in datapk]
            except:
                print_exc()
        if attrs: self.attrs.update(attrs)
        if 'id' not in self.attrs: self.attrs['id']='id_'+name
        self.attrs['class']=self.attrs['class']+' filetree'
        self.attrs = self.build_attrs(self.attrs, name=name)
        try:
            
            vdata =filterdata_by_user(self.choices.queryset.all().filter(isvalid=1),threadlocals.get_current_user())
#            for ii in vdata:
#                if ii.parent_id is not None:
#                    l=[e for e in vdata if  e.id==ii.parent_id]
#                    if not l:ii.parent_id=None
            html = u"<div id='999' class='div_box1' style='padding-left: 30px;'>"\
                    "<p style='margin-right: 40px;'>%s&nbsp; %s &nbsp; &nbsp;</p></div>" % (_(u'开始时间'), _(u'结束时间'))
            html+=TimeSliceTree(vdata).html_ul_li(data=data and datapk or [])
            html_el={\
                "disp": data and ",".join([u"%s"%d for d in data]) or "", 
                "name": name, 
                "value": data and "".join(['<input type=hidden name="%s" value="%s">'%(name, d.pk) for d in data]) or "",
                "attr": flatatt(self.attrs),
                "id": self.attrs['id'],
                'uid': "%s"%id(self),
                "items": html,
                "ok":_(u"确定"),
                "selectchildren":_(u"包含下级")}
            if self.flat: #平铺型
                return u'<input value="%(disp)s" type=hidspan_selectchildrenspan_selectchildrenden>%(value)s<div id="show_deptment"><div id="id_dept"><span id=%(uid)s></span><ul %(attr)s>%(items)s</ul></div><script>render_dept_tree("%(uid)s")</script></div>'%html_el
            else: #下拉框型
                return ('<input  id="dropTime" type="text" class="wZBaseCharField input_showDeptTree" readonly="readonly" value="%(disp)s">%(value)s'+\
                u'<span class="btn_showDeptTree" style="width:200px;"><img onclick="render_dept_dropdown(this, true)"  src="/media/img/sug_down_on.gif" id="id_drop_dept"><div id="show_deptment" style="display: none;""><div class="title"><span class="span_selectchildren displayN"></span><span onclick="javascript:$(this).parent().parent().hide();" class="close btn">%(ok)s</span></div><div id="id_dept"><ul %(attr)s>%(items)s</ul></div></div></span>')%html_el
        except:
            print_exc()
Example #26
0
 def render(self, name, data, attrs=None, choices=()):
     import time
     if data is not None:
         model=self.choices.queryset.model
         try:
             datapk = data
             data=[model.objects.get(pk=int(d)) for d in datapk]
         except:
             print_exc()
     if attrs: self.attrs.update(attrs)
     if 'id' not in self.attrs: self.attrs['id']='id_'+name
     self.attrs['class']=self.attrs['class']+' filetree'
     self.attrs = self.build_attrs(self.attrs, name=name)
     try:
         
         vdata =filterdata_by_user(self.choices.queryset.all(),threadlocals.get_current_user())
         for ii in vdata:
             if ii.parent_id is not None:
                 l=[e for e in vdata if  e.id==ii.parent_id]
                 if not l:ii.parent_id=None
         html=DeptTree(vdata).html_ul_li(data=data and datapk or [])
         html_el={\
             "disp": data and ",".join([u"%s"%d for d in data]) or "", 
             "name": name, 
             "value": data and "".join(['<input type=hidden name="%s" value="%s">'%(name, d.pk) for d in data]) or "",
             "attr": flatatt(self.attrs),
             "id": self.attrs['id'],
             'uid': "%s"%id(self),
             "items": html,
             "ok":_(u"确定"),
             "selectchildren":_(u"包含下级")}
         if self.flat: #平铺型
             return u'<input value="%(disp)s" type=hidden>%(value)s<div id="show_deptment"><div id="id_dept"><span id=%(uid)s></span><ul %(attr)s>%(items)s</ul></div><script>render_dept_tree("%(uid)s")</script></div>'%html_el
         else: #下拉框型
             return ('<input type="text" class="wZBaseCharField input_showDeptTree" readonly="readonly" value="%(disp)s">%(value)s'+\
             u'<span class="btn_showDeptTree"><img onclick="render_dept_dropdown(this, true)"  src="/media/img/sug_down_on.gif" id="id_drop_dept"><div id="show_deptment" style="display: none;"><div class="title"><span class="span_selectchildren"><span><input type="checkbox" id="id_selectchildren" checked="checked" ></input></span><span class="title_selectchildren">%(selectchildren)s &nbsp;&nbsp;</span></span><span onclick="javascript:$(this).parent().parent().hide();" class="close btn">%(ok)s</span></div><div id="id_dept"><ul %(attr)s>%(items)s</ul></div></div></span>')%html_el
     except:
         print_exc()
Example #27
0
    def save(self):
        from mysite.personnel.models.model_areaadmin import AreaAdmin
        tmp = Area.objects.filter(areaid__exact=self.areaid)
        if self.areaid and len(tmp) > 0 and tmp[0].id != self.id:
            raise Exception(_(u'区域编号已经存在!'))
        is_new = True
        if self.id:
            is_new = False

        if self.id == 1: self.parent = None
        super(Area, self).save()
        if is_new:
            login_user = threadlocals.get_current_user()
            if login_user and not login_user.is_superuser and AreaAdmin.objects.filter(
                    user__exact=login_user).count() > 0:
                obj_ua = AreaAdmin()
                obj_ua.area = self
                obj_ua.user = login_user
                try:
                    obj_ua.save()
                except:
                    import traceback
                    traceback.print_exc()
Example #28
0
def simple_get_importPara(request):
    try:
        #获取导入参数
        data=dict(request.POST)
        #print data
        filetype=str(data["filetype"][0])
        #获取文件
        file_obj = request.FILES.get('file', None)
    except:
        import traceback; traceback.print_exc()
        return HttpResponse(u"%s"%_(u"取文件参数错误"))
    if filetype == 'xls': 
        if file_obj:        
            op=threadlocals.get_current_user()        
            dtstr=""
            dt=datetime.now()        
            dtstr=str(dt.year)+str(dt.month)+str(dt.day)+str(dt.hour)+str(dt.minute)+str(dt.second)        
            filename=op.username+dtstr+"."+filetype
        try:
            print "Process xls file.........."
            stw=file_obj.file
            
            filedata=[]
            wr=file(uploadpath+filename,"w+b",)
            linedata=stw.read()
            wr.write(linedata)
            wr.close()
            
            ret={}
            ret['filename']=filename
            ret=simplejson.dumps(ret)              
            return HttpResponse(u"%s"%ret)
        except:
            import traceback; traceback.print_exc()
            return HttpResponse(u"%s"%_(u"处理XLS文件错误!"))
    else:
        return HttpResponse(u"%s"%_(u"上传文件类型未知!"))
    def render(self, name, data, attrs=None):
        from django.core.urlresolvers import reverse
        from dbapp.urls import surl
        if data is not None:
            try:
                data = int(data)
            except:
                pass
            if type(data) in (int, long):
                data = self.choices.queryset.model.objects.get(pk=data)
        if attrs: self.attrs.update(attrs)
        if 'id' not in self.attrs: self.attrs['id'] = 'id_' + name
        self.attrs['class'] = self.attrs['class'] + ' filetree r'
        self.attrs = self.build_attrs(self.attrs, name=name)
        required = ""
        #        if hasattr(self.choices.field, "required") and self.choices.field.required:
        #            required = "class='wZBaseCharField required input_showDeptTree'"
        try:
            vdata = filterdata_by_user(
                self.choices.queryset.all().filter(device_type=5),
                threadlocals.get_current_user())
            need_async_nodes = []
            btn_cancel = ""
            if not required:
                btn_cancel = '''<span class="span_selectNone Link_blue1" onclick="clear_none(this)">
                               <a href="javascript: void(0)">%(none)s</a>&nbsp;&nbsp;
                            </span>
                           ''' % {
                    "none": (u"%s" % _(u"撤销选择")).capitalize()
                }

            html = DeviceTree(vdata).html_ul_li(data and [data.pk] or [])
            html_el = {
                "disp": data or "",
                "name": name,
                "value": data and data.pk or "",
                "attr": flatatt(self.attrs),
                "required": required,
                "id": self.attrs['id'],
                "uid": "%s" % id(self),
                "none": btn_cancel,
                "items": html,
                "ok": _(u"确定"),
                "need_async_nodes": ",".join(need_async_nodes),
                "surl": surl,
            }

            if self.flat == False:  #平铺
                return u'''<input %(required)s  id="dropDevice" class="wZBaseCharField input_showDeptTree" type="text" readonly="readonly" value="%(disp)s"/><input type=hidden name="%(name)s" value="%(value)s"/>
                           <span class="btn_showDeptTree">
                               <img onclick="javascript:$(this).parent().find('#show_deptment').show();" src="/media/img/sug_down_on.gif" id="id_drop_dept"/>
                               <div  id="show_deptment" style="display: none;">
                                   <div class="title">
                                       %(none)s
                                       <span onclick="javascript:$(this).parent().parent().hide();" class="close btn">%(ok)s</span>
                                   </div>
                                   <div id="id_dept">
                                       <ul id="%(uid)s" %(attr)s>%(items)s</ul>
                                       <script>
                                           render_dropdown($("#%(uid)s").parents("#show_deptment"), false,'%(need_async_nodes)s');
                                       </script>
                                   </div>
                               </div>
                           </span>
                       ''' % html_el


#              return u'''<input %(required)s id="dropDevice" class="wZBaseCharField input_showDeptTree" type="text" readonly="readonly" value="%(disp)s"><input type=hidden name="%(name)s" value="%(value)s"/>'
#                                <span class="btn_showDeptTree">
#                                <img onclick="render_dept_dropdown(this, false)" src="/media/img/sug_down_on.gif" id="id_drop_dept">
#                                <div  id="show_deptment" style="display: none;">
#                                <div class="title">
#                                    %(none)s
#
#                                    <span onclick="javascript:$(this).parent().parent().hide();" class="close btn">%(ok)s</span>
#                                </div>
#                                <div id="id_dept">
#                                    <ul id="%(uid)s" %(attr)s>%(items)s</ul>
#                                    <script>
#                                        render_dept_dropdown($("#%(uid)s").parents("#show_deptment"), false,'%(need_async_nodes)s');
#                                        ajax_render_dept_($("#%(uid)s").parent().parent("#show_deptment"),$("#%(uid)s"),"%(need_async_nodes)s",false,"%(surl)s");
#                                    </script>
#                                </div>
#
#                                </div>
#                                </span>''' % html_el
            else:
                return u'<input type=hidden><input value="%(disp)s" type=hidden>%(value)s<div id="show_deptment"><div id=%(uid)s><ul %(attr)s>%(items)s</ul></div><script>render_dept_($("#%(uid)s"),false,true)</script></div>' % html_el
        except:
            print_exc()
Example #30
0
 def limit_video_linkageio_to(self, queryset):
     print '-----------------------', filterdata_by_user(queryset.filter(device_type = DEVICE_VIDEO_SERVER), threadlocals.get_current_user()) #只要门禁控制器
     return filterdata_by_user(queryset.filter(device_type = DEVICE_VIDEO_SERVER), threadlocals.get_current_user()) #只要门禁控制器
Example #31
0
def get_importPara(request):  # 分析文件,并返回到前端
    tablename = ""  # 导入表名
    filetype = ""  # 文件类型   txt   xls   csv
    sparator = 0  # 分隔号    0智能查找    1 制表符    2   按分隔符
    sparatorvalue = ""  # 分隔符
    headerflg = 1  # 文件内容是否含有标题
    headerln = 1  # 标题在文件中的行号
    recordln = 2  # 记录从第几行起
    filename = ""  # 保存上传文件的文件名
    tablename = ""  # 表名
    autosplit = [",", ";", ":", "\t", " "]  # 智能查找分隔符
    unicode_ = ""  # 字符编号
    file_obj = ""
    fields = []
    fieldsdesc = []
    try:
        # 获取导入参数
        data = dict(request.POST)
        # print data
        filetype = str(data["filetype"][0])
        sparator = int(data["sparator"][0])
        sparatorvalue = data["sparatorvalue"][0]
        headerflg = int(data["header"][0])
        headerln = int(data["headerln"][0])
        recordln = int(data["recordln"][0])
        unicode_ = str(data["selectunicode"][0])

        tablename = str("".join(data["tablename"][0].split()))

        # print data

        # 表字段及描述文字
        model, flds, rlfield = findAllFieldsAndModel(tablename)
        for f, v in flds.items():
            fields.append(f)
            fieldsdesc.append(v)
        # 获取文件
        file_obj = request.FILES.get("file", None)
    except:
        import traceback

        traceback.print_exc()
        return HttpResponse(u"%s" % _(u"取文件参数错误"))

    if file_obj:

        op = threadlocals.get_current_user()

        dtstr = ""
        dt = datetime.now()

        dtstr = str(dt.year) + str(dt.month) + str(dt.day) + str(dt.hour) + str(dt.minute) + str(dt.second)

        filename = op.username + dtstr + "." + filetype
        if filetype == "txt" or filetype == "csv":  # txt csv文件处理
            try:

                print "Process txt or csv file......."

                stw = file_obj.file
                filedata = []
                wr = file(uploadpath + filename, "w")

                linedata = stw.readline()

                while linedata != "":
                    if linedata[:3] == codecs.BOM_UTF8:
                        linedata = linedata[3:]

                    filedata.append(str(linedata).decode(unicode_))
                    wr.write(linedata)
                    linedata = stw.readline()

                wr.close()
                hdata = ""
                ddata = ""

                if len(filedata) == 0:
                    return HttpResponse(u"%s" % _(u"文件内容为空!"))
                if headerflg and headerln:
                    hdata = filedata[int(headerln) - 1]

                ddata = filedata[int(recordln) - 1]
                # 智能查找分隔符

                colCount = 0
                if int(sparator) == 0:
                    for sp in autosplit:

                        if len(ddata.split(sp)) > colCount:
                            sparatorvalue = sp
                            colCount = len(ddata.split(sp))

                # 分隔标题头和第一条记录
                if sparatorvalue != "":
                    ddata = ddata.split(sparatorvalue)
                    if headerflg and headerln:
                        hdata = hdata.split(sparatorvalue)

                # print hdata
                ret = {}
                ret["tablename"] = tablename
                ret["headdata"] = hdata
                ret["recorddata"] = ddata
                ret["fields"] = fields
                ret["fieldsdesc"] = fieldsdesc
                ret["filetype"] = filetype
                ret["filename"] = filename
                ret["sparatorvalue"] = sparatorvalue
                ret["headln"] = headerln
                ret["recordln"] = recordln
                ret["unicode"] = unicode_

                ret = simplejson.dumps(ret)

                return HttpResponse(u"%s" % ret)
            except:
                import traceback

                traceback.print_exc()
                return HttpResponse(u"%s" % _(u"处理txt文件出错!"))

        elif filetype == "xls":  # xls文件处理
            try:
                print "Process xls file.........."
                stw = file_obj.file

                filedata = []
                wr = file(uploadpath + filename, "w+b")
                linedata = stw.read()
                wr.write(linedata)
                wr.close()

                ds = ParseXlsUxlrd(uploadpath + filename)  # 读XLS文件

                datash = []

                for sh in range(len(ds)):  # 智能查找SHEET数据
                    if len(ds[sh][1]) >= 0:
                        datash = ds[sh][1]

                        break

                hdata = []
                ddata = []
                if datash:
                    if headerflg and headerln:

                        for v in datash[headerln - 1]:
                            hdata.append(v[1])
                        # print hdata
                    if len(datash[1]) > recordln:

                        for v in datash[recordln - 1]:

                            ddata.append(v[1])
                        # print ddata

                ret = {}
                ret["tablename"] = tablename
                ret["headdata"] = hdata
                ret["recorddata"] = ddata
                ret["fields"] = fields
                ret["fieldsdesc"] = fieldsdesc
                ret["filetype"] = filetype
                ret["filename"] = filename
                ret["sparatorvalue"] = sparatorvalue
                ret["headln"] = headerln
                ret["recordln"] = recordln
                ret["unicode"] = unicode_
                ret = simplejson.dumps(ret)

                return HttpResponse(u"%s" % ret)

            except:
                import traceback

                traceback.print_exc()
                return HttpResponse(u"%s" % _(u"处理XLS文件错误!"))

        else:
            return HttpResponse(u"%s" % _(u"上传文件类型未知!"))
Example #32
0
def file_export(request, app_label, model_name):

    exportpath = settings.ADDITION_FILE_ROOT + "/"
    # print exportpath
    filename = ""
    filetype = ""
    model = ""
    templatename = ""
    filecode = ""
    viewname = ""

    data = dict(request.POST)
    filetype = str(data["filetype"][0])
    model = str(data["model"][0])
    templatename = data["templatename"][0].decode("utf-8")
    filecode = str(data["filecode"][0])
    viewname = str(data["txtviewname"][0])
    op = threadlocals.get_current_user()

    dtstr = ""
    dt = datetime.now()

    dtstr = str(dt.year) + str(dt.month) + str(dt.day) + str(dt.hour) + str(dt.minute) + str(dt.second)

    Displayfileds = ""  # 导出字段列表,可从视图中提取,或定制
    data = []
    tblname = ""
    model = GetModel(app_label, model_name)
    if viewname:
        from viewmodels import get_view_byname_js

        Displayfileds = get_view_byname_js[viewname]["fields"]

    if filetype == "txt":
        try:
            if templatename == "stdemployee":
                tblname = "emp"
                Displayfileds = ["id", "EName", "Gender", "DeptID"]
                data = Employee.objects.all().values_list(*Displayfileds).order_by("id")

            elif templatename == "smpemployee":
                Displayfileds = ["id", "EName", "Gender", "DeptID"]
                data = Employee.objects.all().values_list(*Displayfileds).order_by("id")
                tblname = "emp"
            elif templatename == "stddepartment":
                Displayfileds = ["DeptID", "DeptCode", "DeptName", "parent"]
                data = Department.objects.all().values_list(*Displayfileds).order_by("DeptID")
                tblname = "dep"
            else:
                Displayfileds = [fl.name for fl in model._meta.fields]
                data = model.objects.all().values_list(*Displayfileds).order_by("id")
                tblname = model.__name__
            # print "%s"%data
            filename = op.username + dtstr + tblname + "." + filetype

            ret = render_to_string(templatename + ".txt", {"fields": Displayfileds, "tdata": data})
            f = file(exportpath + filename, "w")
            f.write(ret.encode(filecode))
            f.close()
            # print ret
            response = HttpResponse(ret, mimetype="application/octet-stream")
            response["Content-Disposition"] = "attachment; filename=%s" % filename
            return response

        #           return HttpResponseRedirect("/data/file/%s"%filename)

        #            response = HttpResponse(mimetype='text/csv')
        #            response['Content-Disposition'] = 'attachment; filename=%s' % filename
        #
        #            t = loader.get_template(templatename+".txt")
        #            c = Context({
        #                'tdata': data,
        #                'fields': Displayfileds,
        #            })
        #            response.write(t.render(c))
        #            return response

        except:
            import traceback

            traceback.print_exc()
    elif filetype == "xls":
        pass
    elif filetype == "pdf":
        pass
    else:
        pass

    return HttpResponse(u"%s" % _(u"文件导入操作完成!"))
Example #33
0
 def limit_device_to(self, queryset):
     print '--------------------------queryset=', queryset
     return filterdata_by_user(
         queryset.filter(device_type=DEVICE_ACCESS_CONTROL_PANEL),
         threadlocals.get_current_user())  #只要门禁控制器
Example #34
0
    def render(self, name, data, attrs=None, choices=()):
        import time
        from dbapp.urls import surl
        if data is not None:
            model = self.choices.queryset.model
            try:
                datapk = data
                data = [model.objects.get(pk=int(d)) for d in datapk]
            except:
                print_exc()
        if attrs: self.attrs.update(attrs)
        if 'id' not in self.attrs: self.attrs['id'] = 'id_' + name
        self.attrs['class'] = self.attrs['class'] + ' filetree'
        self.attrs = self.build_attrs(self.attrs, name=name)
        try:
            if not required:
                btn_cancel = '''<span class="span_selectNone Link_blue1" onclick="clear_none(this)">
                               <a href="javascript: void(0)">%(none)s</a>&nbsp;&nbsp;
                            </span>
                           ''' % {
                    "none": (u"%s" % _(u"撤销选择")).capitalize()
                }

            vdata = filterdata_by_user(
                self.choices.queryset.all().filter(isvalid=1),
                threadlocals.get_current_user())
            html = u"<div id='999' class='title' style='margin-left: 0px;'>"\
                  "<p style='margin-right: 110px;'>%s&nbsp; %s &nbsp; &nbsp; %s</p></div>" % (_(u'开始时间'), _(u'结束时间'), _(u'金额'))
            html += DeptTree(vdata).html_ul_li(data=data and datapk or [])
            need_async_nodes = []
            html_el = {
                "disp":
                data and ",".join([u"%s" % d for d in data]) or "",
                "name":
                name,
                "value":
                data and "".join([
                    '<input type=hidden name="%s" value="%s">' % (name, d.pk)
                    for d in data
                ]) or "",
                "attr":
                flatatt(self.attrs),
                "id":
                self.attrs['id'],
                'uid':
                "%s" % id(self),
                "items":
                html,
                "none":
                btn_cancel,
                "ok":
                _(u"确定"),
                "selectchildren":
                u"%s" % _(u"包含下级"),
                "need_async_nodes":
                ",".join(need_async_nodes),
                "surl":
                surl,
            }
            if self.flat:  #平铺型
                return u'<input value="%(disp)s" type=hidden>%(value)s<div id="show_deptment"><div id="id_dept"><span id=%(uid)s></span><ul %(attr)s>%(items)s</ul></div><script>render_dept_tree("%(uid)s")</script></div>' % html_el
            else:  #下拉框型
                return '''<input type="text" id="splitTime_val"  class="wZBaseCharField input_showDeptTree" readonly="readonly" value="%(disp)s"/>%(value)s<span class="btn_showDeptTree">
                                                 <img onclick="javascript:$(this).parent().find('#show_deptment').show();"  src="/media/img/sug_down_on.gif" id="id_drop_dept"/>
                                                 <div id="show_deptment" style="display: none;">
                                                     <div class="title">
                                                         <span class="span_selectchildren">
                                                             <span>
                                                                 <input type="checkbox" id="id_selectchildren" checked="checked" ></input>
                                                             </span>
                                                             <span class="title_selectchildren">%(selectchildren)s &nbsp;&nbsp;</span>
                                                         </span>
                                                         <span onclick="javascript:$(this).parent().parent().hide();" class="close btn">%(ok)s</span>
                                                     </div>
                                                     <div id="id_dept">
                                                         <ul id="%(uid)s" %(attr)s>%(items)s</ul>
                                                         <script>
                                                             render_dropdown($("#%(uid)s").parent().parent(), true,'%(need_async_nodes)s');
                                                         </script>
                                                     </div>
                                                 </div>
                                                 
                                             </span>
                                     ''' % html_el


#                return ('<input type="text" id="splitTime_val" class="wZBaseCharField input_showDeptTree" readonly="readonly" value="%(disp)s">%(value)s'+\
#                u'<span class="btn_showDeptTree"><img onclick="render_dropdown(this, true)"  src="/media/img/sug_down_on.gif" id="id_drop_dept"><div id="show_deptment" style="display: none;"><div class="title"><span class="span_selectchildren" displayN></span><span onclick="javascript:$(this).parent().parent().hide();" class="close btn">%(ok)s</span></div><div id="id_dept"><ul %(attr)s>%(items)s</ul></div></div></span>')%html_el
        except:
            print_exc()
Example #35
0
 def save(self, *args, **kwargs):
     op = threadlocals.get_current_user()
     self.create_operator = op.username
     models.Model.save(self, args)
Example #36
0
 def limit_device_to(self, queryset):
     print '--------------------------queryset=',queryset
     return filterdata_by_user(queryset.filter(device_type = DEVICE_ACCESS_CONTROL_PANEL), threadlocals.get_current_user()) #只要门禁控制器
Example #37
0
def get_all_view(model):
        op=threadlocals.get_current_user()
        
        vn=ViewModel.objects.filter(model__exact=ContentType.objects.get_for_model(model),create_operator__exact=op.username)        
        
        return [i.name for i in vn]
Example #38
0
    def render(self, name, data, attrs=None, choices=()):
        import time
        from dbapp.urls import surl
        from mysite.iclock.iutils import get_max_in
        if data is not None:
            model = self.choices.queryset.model
            try:
                #data=list(model.objects.filter(pk__in=datapk))
                data = get_max_in(model.objects.all(), data)
            except:
                print_exc()

        MCls = self.choices.queryset.model
        value = []
        checked_ids = []
        if data:
            for d in data:
                checked_ids.append(d.pk)
                value.append(u"%s" % d.pk)

        value = u",".join(value)

        if attrs: self.attrs.update(attrs)
        checkable = True
        if self.attrs.has_key("checkable"):
            checkable = self.attrs["checkable"]

        if 'id' not in self.attrs:
            self.attrs['id'] = (u"id_%(n)s_%(t)s" % {
                "n": name,
                "t": time.time()
            }).replace(".", "")
        self.attrs['class'] = self.attrs['class'] + ' filetree'
        self.attrs = self.build_attrs(self.attrs, name=name)

        dict_rows = []  #第一级的数据
        required = False
        if hasattr(self.choices.field,
                   "required") and self.choices.field.required:
            required = True
        from django.db import connection as conn
        from django import db

        m_id = "id"
        m_p = "parent_id"
        m_n = "name"
        s_id = "dept_id"
        r_m = "deptadmin"
        TreeModel = MCls
        sup_id = "supdeptid"
        if TreeModel.__name__ == "Department":
            m_id = "id"
            m_p = "parent_id"
            m_n = "name"
            s_id = "dept_id"
            r_m = "deptadmin"
            sup_id = "supdeptid"
        elif TreeModel.__name__ == "Area":
            m_id = "id"
            m_p = "parent_id"
            m_n = "areaname"
            s_id = "area_id"
            r_m = "areaadmin"
            sup_id = "parent_id"
        try:
            #新增的时候不需要限制
            uobj = threadlocals.get_current_user()
            vdata = self.choices.queryset.all()

            vdata = filterdata_by_user(vdata, uobj)
            async_fields = [m_id, m_p, m_n]
            if not uobj.is_superuser:  #不是超级管理员
                select = "select  distinct %s from %s where user_id=%s and %s.%s=%s" % (
                    s_id, r_m, uobj.pk, TreeModel._meta.db_table, sup_id, s_id)
                vdata = vdata.extra(select={m_p: select})
            vdata = list(vdata.values(*async_fields))
            for e in vdata:
                tmp_vdata = {}
                if e[m_p] is None:
                    if e[m_id] in checked_ids:
                        checked = True
                    else:
                        checked = False

                    tmp_vdata = {
                        "id": e[m_id],
                        "pId": 0,
                        "name": e[m_n],
                        "isParent": False,
                        "checked": checked
                    }
                    for ee in vdata:
                        if ee[m_p] == e[m_id]:
                            tmp_vdata["isParent"] = True
                            break
                if tmp_vdata:
                    dict_rows.append(tmp_vdata)

            dict_attrs = {
                "disp": data and ",".join([u"%s" % d for d in data]) or "",
                "flat": self.flat,
                "multiple": self.multiple,
                "name": name,
                "value": value,
                "attr": self.attrs,
                "id": self.attrs['id'],
                "dict_rows": dict_rows,
                "surl": surl,
                "required": required,
                "checkable": checkable,
            }

            #只是把属性传送到前端,由前端去处理
            return u'''
                    <ul class="tree" id = "%(id)s">
                    </ul>
                    <div>
                         <script>
                            render_tree(%(attrs)s);
                        </script>
                    </div>
            ''' % {
                "id": self.attrs['id'],
                "attrs": json.dumps(dict_attrs)
            }
        except:
            print_exc()
Example #39
0
def save_view(request, app_label, model_name):        
        try:
                ret={}
                op=threadlocals.get_current_user()
                #print op
                obj=GetModel(app_label, model_name)
                para=dict(request.POST)        
                view_name=para['viewname'][0]
                defaultview=""
                
                
                vi=ViewModel.objects.filter(model__exact=ContentType.objects.get_for_model(obj),name__exact=view_name,create_operator__exact=op.username)
                if vi:
                        newview=vi[0]
                else:
                        newview=ViewModel()                
                newview.name=para['viewname'][0]
                newview.viewtype=para['viewtype'][0]
                col_set=[]
                fun_set={}
                filter_set={}
                other_set={}
                sort={}
                fieldswidth={}
                sort["firstsort"]=[para['firstsort'][0],para['sort1'][0]]
                sort["secondsort"]=[para['secondsort'][0],para['sort2'][0]]
                field_prefix="%s."%obj.__name__
                flen=len(field_prefix)
                #print field_prefix, flen
                view_property={}
                col=[]
                for name,value in para.items():
                        if name not in ['viewname','firstsort','secondsort','sort1','sort2','viewtype']:
                                if name.startswith("_fun_"):                                        
                                        
                                        fun_set[name[5:]]=value[0]                                        
                                        
                                elif name.startswith("_col_"):
                                        name=name[5:]
                                        
                                        if name.find(field_prefix)==0:
                                                col.append([value[0],str(name[flen:])])
                                        elif name.find('.')>0:
                                                col.append([value[0],"__".join(name.split('.'))])
                                
                                elif name.startswith("_filter_"):
                                                filter_set[name[8:]]=value[0]
                                        
                                elif name.startswith("_other_"):
                                        other_set[name[7:]]=value[0]
                                elif name.startswith("_txt_"):
                                        fieldswidth[name[5:]]=value[0]
                                else:
                                        view_property[name]=value[0]
                #print pset
                col.sort()
                for i in col:
                        col_set.append(i[1])
                defaultview=""
                if para.has_key('defaultview'):
                        defaultview='true'
                        view_property['defaultview']='true'
                if defaultview=='true':
                        #print 'find'
                        allvi=ViewModel.objects.filter(model__exact=ContentType.objects.get_for_model(obj),create_operator__exact=op.username)
                        for v in allvi:
                                info=eval(v.info)
                                #print info
                                info["defaultview"]='false'
                                v.info=simplejson.dumps(info)
                                v.save()
                
                view_property['fields']=col_set
                view_property['action']=fun_set
                view_property['filter']=filter_set
                view_property['other']=other_set
                view_property['sort']=sort                
                
                view_property['fieldswidth']=fieldswidth                
                pset=simplejson.dumps(view_property)
                newview.info=pset
                newview.model=ContentType.objects.get_for_model(obj)
                newview.save()
                vj=get_all_viewJson(obj)
                
        except:
                import traceback; traceback.print_exc()
                
                ret["flag"]="false"
                ret["msg"]="save fail"
                ret["options"]=""
                return getJSResponse(smart_str(simplejson.dumps(ret)))
        ret["flag"]="true"
        ret["msg"]="save success!"
        ret["options"]=vj
        
        return getJSResponse(smart_str(simplejson.dumps(ret)))
Example #40
0
def api_for_model(request, model, data_key=None, query_set=None):
    from dbapp.modelutils import default_fields
    try:
        fields = request.GET.get("fields", "")
        if fields:
            fields = fields.split(",")
        if len(fields) == 0:
            fields = None
            if hasattr(model, 'Admin'):
                if model.Admin:

                    if hasattr(model.Admin, 'api_fields'):
                        fields = model.Admin.api_fields
                    elif hasattr(model.Admin, "list_display"):
                        fields = model.Admin.list_display
            if not fields:
                #fields=[isinstance(f, models.ForeignKey) and f.name+"_id" or f.name for f in model._meta.fields]
                fields = [
                    isinstance(f, models.ForeignKey) and f.name + "_id"
                    or f.name for f in model._meta.fields
                    if f.name not in default_fields
                ]
        else:
            of = fields
            if hasattr(model.Admin, 'api_fields'):
                of = model.Admin.api_fields
            f = [i for i in fields if i.split("|")[0] in of]
            fields = f


#        print "export fields:%s"%fields
#fields=[f.replace(".","__") for f in fields]

        dict_data = {
            'model': model,
            'fields': fields,
            'qs': query_set,
        }

        try:
            dict_export = get_eport_dict()
            sql_key = model._meta.app_label + "." + model.__name__
            if dict_export.has_key(sql_key):
                dict_data["fields"] = dict_export[sql_key]["db_fields"]
                request.special_head = dict_export[sql_key]["head"]
        except:
            pass

        handler = type(
            str("_%s_%s_APIHandler" % (id(model.Admin), model.__name__)),
            (APIHandler, ), dict_data)
        #print "----",str("_%s_%s_APIHandler"%(id(model.Admin), model.__name__))
        #导出日志
        try:

            op = threadlocals.get_current_user()
            LogEntry.objects.log_action(
                user_id=op and op.pk or None,
                content_type_id=ContentType.objects.get_for_model(model).pk,
                object_id="",
                object_repr="",
                action_flag=EXPORT)
        except:
            pass  #解决在非管理员不能导出报表。重复插入日志报错
        return Resource(handler=handler,
                        authentication=get_auth(request))(request, data_key)
    except UnicodeError:
        from django.http import HttpResponse
        import traceback
        traceback.print_exc()
        return HttpResponse(u"%s" % _(u'导出的内容与选择的编码不符'))
    def render(self, name, data, attrs=None, choices=()):
        import time
        from dbapp.urls import surl
        if data is not None:
            model = self.choices.queryset.model
            try:
                datapk = data
                data = [model.objects.get(pk=int(d)) for d in datapk]
            except:
                print_exc()
        if attrs: self.attrs.update(attrs)
        if 'id' not in self.attrs: self.attrs['id'] = 'id_' + name
        self.attrs['class'] = self.attrs['class'] + ' filetree'
        self.attrs = self.build_attrs(self.attrs, name=name)
        try:
            vdata = filterdata_by_user(
                self.choices.queryset.all().filter(device_type=5),
                threadlocals.get_current_user())
            html = DeviceTree(vdata).html_ul_li(data=data and datapk or [])
            need_async_nodes = []
            html_el = {
                "disp":
                data and ",".join([u"%s" % d for d in data]) or "",
                "name":
                name,
                "value":
                data and "".join([
                    '<input type=hidden name="%s" value="%s">' % (name, d.pk)
                    for d in data
                ]) or "",
                "attr":
                flatatt(self.attrs),
                "id":
                self.attrs['id'],
                'uid':
                "%s" % id(self),
                "items":
                html,
                "ok":
                _(u"确定"),
                "selectchildren":
                u"%s" % _(u"全选/取消全选"),
                "need_async_nodes":
                ",".join(need_async_nodes),
                "surl":
                surl
            }
            if self.flat:  #平铺型
                return u'<input value="%(disp)s" type=hidden>%(value)s<div id="show_deptment"><div id="id_dept"><span id=%(uid)s></span><ul %(attr)s>%(items)s</ul></div><script>render_dept_tree("%(uid)s")</script></div>' % html_el
            else:  #下拉框型
                return '''<input type="text" id="dropDevice"  class="wZBaseCharField input_showDeptTree" readonly="readonly" value="%(disp)s"/>%(value)s<span class="btn_showDeptTree">
                              <img onclick="javascript:$(this).parent().find('#show_deptment').show();"  src="/media/img/sug_down_on.gif" id="id_drop_dept"/>
                              <div id="show_deptment" style="display: none;">
                                  <div class="title">
                                      <span class="span_selectchildren">
                                          <span>
                                              <input type="checkbox" id="id_select_all" onclick='check_all($("#%(uid)s").parent().parent());' ></input>
                                          </span> 
                                          
                                          <span class="title_selectchildren" id="ck_title">%(selectchildren)s &nbsp;&nbsp;</span>
                                      </span>
                                      <span onclick="javascript:$(this).parent().parent().hide();" class="close btn">%(ok)s</span>
                                  </div>
                                  <div id="id_dept">
                                      <ul id="%(uid)s" %(attr)s>%(items)s</ul>
                                      <script>
                                          render_dropdown($("#%(uid)s").parent().parent(), true,'%(need_async_nodes)s');
                                      </script>
                                  </div>
                              </div>
                          </span>
                    ''' % html_el


#                return ('<input id="dropDevice" type="text" class="wZBaseCharField input_showDeptTree" readonly="readonly" value="%(disp)s">%(value)s'+\
#                u'<span class="btn_showDeptTree" style="width:200px;"><img onclick="render_dept_dropdown(this, true)"  src="/media/img/sug_down_on.gif" id="id_drop_dept"><div id="show_deptment" style="display: none;"><div class="title"><span class="span_selectchildren displayN"></span><span onclick="javascript:$(this).parent().parent().hide();" class="close btn">%(ok)s</span></div><div id="id_dept"><ul %(attr)s>%(items)s</ul></div></div></span>')%html_el
        except:
            print_exc()
Example #42
0
def append_rtlog_status_push(devobj, rtlog, d_server):#append_rtlog_push(d_server, devobj, rtlog):#push ----cccc20110726
    from mysite.iaccess.models import AccRTMonitor
    from base.middleware import threadlocals
    from mysite.iaccess.models.accdoor import AccDoor
    try:
        rtlogs = rtlog.split("\t")
        operator = threadlocals.get_current_user()
        cursor = connection.cursor()
        dev_door_list = AccDoor.objects.filter(device=devobj)  #读设备门列表到缓存
        for rtlog in rtlogs:#修改支持一次获取多条事件记录
            #print '---rtlog=',rtlog
#            if not rtlog:#非记录
#                continue
#            str = rtlog.split("\t")#pull为','
            str = rtlog.split(",")  #----cccc
            doorstr=""
            if len(str) < 7:      #不合规范数据
                return 0
            d_server.set_to_dict(devobj.get_doorstate_cache_key(), "%s,%s,1"%(str[7],str[8]))
            print 'door_state---status====',d_server.get_from_dict(devobj.get_doorstate_cache_key())
#            if strtoint(str[4]) == DOOR_STATE_ID:#0时间+1门开关状态+2报警或门开超时+3没用+4(255标明该事件为门状态,否则为事件)+5 没用+6验证方式(200其他)
#                d_server.set_to_dict(devobj.get_doorstate_cache_key(), "%s,%s,1"%(str[1],str[2]))
#                write_log("rtlog ---- %s %s"%(str[1],str[2]))
#                return
##            print '---str=',str
#            if strtoint(str[4]) == EVENT_DOORSENSOROPEN:
#                doorstate = d_server.get_from_dict(devobj.get_doorstate_cache_key())#dict中读取
#    #            print "doorstate=",doorstate
#                if doorstate is None:
#                    doorstate = "0,0,0"
#                doorstr = doorstate.split(",", 3)
#                try:
#                    val = set_doorstr(int(doorstr[0]), 0x02, int(str[3]))
#                except:
#                    val = 0
#                d_server.set_to_dict(devobj.get_doorstate_cache_key(), "%d,%s,1"%(val,doorstr[1]))
#
#            if strtoint(str[4]) == EVENT_DOORSENSORCLOSE:
#                doorstate = d_server.get_from_dict(devobj.get_doorstate_cache_key())
#                #print "doorstate=",doorstate
#                if doorstate is None:
#                    doorstate = "0,0,0"
#                doorstr = doorstate.split(",", 3)
#                try:
#                    val = set_doorstr(int(doorstr[0]), 0x01, int(str[3]))
#                except:
#                    val = 0
#                d_server.set_to_dict(devobj.get_doorstate_cache_key(), "%d,%s,1"%(val,doorstr[1]))
#
#            if (strtoint(str[4]) >= ALAEM_ID_START) and (strtoint(str[4]) < ALAEM_ID_END):
#                doorstate = d_server.get_from_dict(devobj.get_doorstate_cache_key())
#                #print "doorstate=",doorstate
#                if doorstate is None:
#                    doorstate = "0,0,0"
#                doorstr = doorstate.split(",", 3)
#                try:
#                    val = set_doorstr(int(doorstr[1]), int(str[4]), int(str[3]))
#                except:
#                    val = 0
#                d_server.set_to_dict(devobj.get_doorstate_cache_key(), "%s,%d,1"%(doorstr[0], val))

            doorobj = None
            try:
                for obj in dev_door_list:
                    if obj.door_no == int(str[3]): #查找相应的门对像,避免重复查询数据库
                        doorobj = obj
                        break
                doorobj = obtain_doorobj_from_log(str, doorobj)
                if doorobj is not None:
                    str[3] = doorobj and doorobj.id or 0
#                     str[3] = str[3] or 0  #----cccc20110726
                    area_id = doorobj.device.area.id
            except:
                print_exc()
            #print '--!!!!!!!--str=',str
             #if d_server.llen("MONITOR_RT")<MAX_RTLOG:
            #暂不考虑,设备人员不在数据库中的情况。固件已判断,只有验证通过的人才会上来41事件。darcy20110803锦湖轮胎
            try:
                #新记录格式:0:时间, 1:PIN号 , 2:卡号, 3:门编号, 4:事件类型, 5:出入状态, 6:验证方式  ----cccc
                #time, Pin, cardno, doorID, even_type, reserved, verified
                #push方式给设备发命令 ----chenwj20110726

                if int(str[4]) == EVENT_GAPB_SUCCEED or int(str[4]) == EVENT_GAPB_RESET: #反潜验证开门成功或者初始化反潜规则---222
                    #d_server.set_to_dict("APB_STATE_EMP_"+str[1], str[5])
                    if doorobj:
                        if doorobj.global_apb:
                            d_server.set_to_dict("GLOBAL_APB_AREA_%s_EMP_%s"%(area_id, str[1]), str[5])

                #由于devview中已经做了设备所属区域内是否都在线的判断,所以程序执行至此时,说明区域内所有设备都在线
                if int(str[4]) == EVENT_ANTIPASSBACK: #反潜验证41
                    if doorobj:
                        global_apb_cmd = ""#返回空,表示后台验证失败--darcy20110803锦湖轮胎
                        #查看区域反潜范围内的设备的当前状态(不需要检查当前设备)-darcy20110803锦湖轮胎
                        if not check_apb_device_state(devobj, d_server):
                        #if area_apb_offline:#如果区域反潜上一个状态是离线的,那么整个区域内的所有设备上来的之后的第一条记录都按照固件权限组逻辑判断。
                            #d_server.delete_dict("GLOBAL_APB_AREA_"+area_id)#清空
                            global_apb_cmd = "NA"
                            print '------NA'
                            keys = d_server.get_keys_from_dict()#效率不高。。。
                            #print '-@@@@@@--keys=',keys
                            for key in keys:
                                if key.startswith("GLOBAL_APB_AREA_%s"%area_id):
                                    #print '--------delete the emp key=',key
                                    d_server.delete_dict(key)
                                    #print '--get key=',key,'---',d_server.get_from_dict(key)
                        else:
                            lock_delay = doorobj.lock_delay#获取锁驱动时长
                            print '----GLOBAL_APB_AREA=',"GLOBAL_APB_AREA_%s_EMP_%s"%(area_id, str[1])
                            apb_state = d_server.get_from_dict("GLOBAL_APB_AREA_%s_EMP_%s"%(area_id, str[1]))
                            #print '---apb_state=',apb_state
                            #DEVICE SET %d %d %d %d   #1继电器,门id,1继电器类型为门,时长
                            if apb_state:#缓存中存在此人员
                                if apb_state != str[5]:#出入状态匹配成功,可以开门--darcy20110803锦湖轮胎
                                    #print '-----can open the door'
                                    global_apb_cmd = "DEVICE SET 1 %d 1 %s"%(int(str[3]), lock_delay)
                            elif apb_state is None:#第一次,里面还没有内容,即初始化反潜规则,要求固件发送224事件-darcy20110803
                                #print '--apb_state is None---can open the door'
                                global_apb_cmd = "RESET_GAPB DEVICE SET 1 %d 1 %s"%(int(str[3]), lock_delay)
                            else:
                                pass
                                #print '------cannot open the door'
                        d_server.set_to_dict("GLOBAL_APB_CMD_%s"%devobj.sn, global_apb_cmd + '\n' + rtlog.strip())#生成开门命令

                #else:#其它情况,如:卡未注册
                if doorobj is not None:
                    str[3] = doorobj and doorobj.id or 0
                log = "%s,%s,%s,%s,%s,%s,%s,%d"%(FmtTTime(str[0]).strftime('%Y-%m-%d %H:%M:%S'),str[1],str[3],str[4],str[5], str[6].strip(), str[2], devobj and devobj.id or 0)
                write_log("---log=%s"%log)
                save_event_log(str, cursor, operator, doorobj, devobj)#写入报表
                d_server.rpush_to_dict("MONITOR_RT", log)#{"MONITOR_RT':['log1','log2']}#push实时监控

                if (strtoint(str[4]) >= ALAEM_ID_START) and (strtoint(str[4]) < ALAEM_ID_END):
                    d_server.rpush_to_dict("ALARM_RT", log)

            except Exception, e:
                print '--e2=',e
                print_exc()

        connection.close()
Example #43
0
 def limit_device_to(self, queryset):
     if self.device:
         v = AccAntiBack.objects.exclude(device=self.device).values("device")
     else:    
         v = AccAntiBack.objects.values("device")
     q = queryset.filter(device_type = DEVICE_ACCESS_CONTROL_PANEL)
     return filterdata_by_user(q.exclude(pk__in=[item["device"] for item in v]), threadlocals.get_current_user()) 
Example #44
0
def Get_Author():
    auth = get_current_user()
    if auth and auth.is_anonymous(): auth = None
    return auth
Example #45
0
 def limit_video_linkageio_to(self, queryset):
     #print '-----------------------', filterdata_by_user(queryset.filter(device_type = DEVICE_VIDEO_SERVER), threadlocals.get_current_user()) #只要门禁控制器
     return filterdata_by_user(
         queryset.filter(
             device_type__in=[DEVICE_VIDEO_SERVER, DEVICE_CAMERA_SERVER]),
         threadlocals.get_current_user())  #只要门禁控制器
Example #46
0
def save_view(request, app_label, model_name):
    try:
        ret = {}
        op = threadlocals.get_current_user()
        #print op
        obj = GetModel(app_label, model_name)
        para = dict(request.POST)
        view_name = para['viewname'][0]
        defaultview = ""

        vi = ViewModel.objects.filter(
            model__exact=ContentType.objects.get_for_model(obj),
            name__exact=view_name,
            create_operator__exact=op.username)
        if vi:
            newview = vi[0]
        else:
            newview = ViewModel()
        newview.name = para['viewname'][0]
        newview.viewtype = para['viewtype'][0]
        col_set = []
        fun_set = {}
        filter_set = {}
        other_set = {}
        sort = {}
        fieldswidth = {}
        sort["firstsort"] = [para['firstsort'][0], para['sort1'][0]]
        sort["secondsort"] = [para['secondsort'][0], para['sort2'][0]]
        field_prefix = "%s." % obj.__name__
        flen = len(field_prefix)
        #print field_prefix, flen
        view_property = {}
        col = []
        for name, value in para.items():
            if name not in [
                    'viewname', 'firstsort', 'secondsort', 'sort1', 'sort2',
                    'viewtype'
            ]:
                if name.startswith("_fun_"):

                    fun_set[name[5:]] = value[0]

                elif name.startswith("_col_"):
                    name = name[5:]

                    if name.find(field_prefix) == 0:
                        col.append([value[0], str(name[flen:])])
                    elif name.find('.') > 0:
                        col.append([value[0], "__".join(name.split('.'))])

                elif name.startswith("_filter_"):
                    filter_set[name[8:]] = value[0]

                elif name.startswith("_other_"):
                    other_set[name[7:]] = value[0]
                elif name.startswith("_txt_"):
                    fieldswidth[name[5:]] = value[0]
                else:
                    view_property[name] = value[0]
        #print pset
        col.sort()
        for i in col:
            col_set.append(i[1])
        defaultview = ""
        if para.has_key('defaultview'):
            defaultview = 'true'
            view_property['defaultview'] = 'true'
        if defaultview == 'true':
            #print 'find'
            allvi = ViewModel.objects.filter(
                model__exact=ContentType.objects.get_for_model(obj),
                create_operator__exact=op.username)
            for v in allvi:
                info = eval(v.info)
                #print info
                info["defaultview"] = 'false'
                v.info = simplejson.dumps(info)
                v.save()

        view_property['fields'] = col_set
        view_property['action'] = fun_set
        view_property['filter'] = filter_set
        view_property['other'] = other_set
        view_property['sort'] = sort

        view_property['fieldswidth'] = fieldswidth
        pset = simplejson.dumps(view_property)
        newview.info = pset
        newview.model = ContentType.objects.get_for_model(obj)
        newview.save()
        vj = get_all_viewJson(obj)

    except:
        import traceback
        traceback.print_exc()

        ret["flag"] = "false"
        ret["msg"] = "save fail"
        ret["options"] = ""
        return getJSResponse(smart_str(simplejson.dumps(ret)))
    ret["flag"] = "true"
    ret["msg"] = "save success!"
    ret["options"] = vj

    return getJSResponse(smart_str(simplejson.dumps(ret)))
Example #47
0
 def limit_device_to(self, queryset):
     #需要过滤掉已经配置过的,当前自身(编辑时)以及单门控制器
     if self.device:
         v = AccInterLock.objects.exclude(device = self.device).values("device")
     else:    
         v = AccInterLock.objects.values("device")
     q = queryset.filter(device_type = DEVICE_ACCESS_CONTROL_PANEL).exclude(acpanel_type = ACPANEL_1_DOOR)#门禁控制器
     return filterdata_by_user(q.exclude(pk__in = [item["device"] for item in v]), threadlocals.get_current_user()) 
Example #48
0
def Get_Author():
    auth=get_current_user()
    if auth and auth.is_anonymous(): auth=None
    return auth
Example #49
0
def getUsrCreateFrameOptions(dataModel,request):
    '''
    return options , actions
    '''
    from urls import get_model_data_url
    import base
    lng=get_language()
    
    model_name=dataModel.__name__
    
    #**********options cache********
    cache_key=u"%s_%s_%s"%(lng,model_name,'options')
    options=cache.get(cache_key)
    if not options:
        options={
                #"canEdit": (not hasattr(dataModel.Admin, 'read_only')) or not dataModel.Admin.read_only,
                "key_field":dataModel._meta.pk.name,
                "title":u"%s"%dataModel._meta.verbose_name,
                "addition_fields":[], 
                "addition_columns":[],
                "exception_fields":[],
                "model": model_name,
                #"model_url":get_model_data_url(dataModel),
                "app_label": dataModel._meta.app_label,
                "children_models": {},
                "detail_model":hasattr(dataModel.Admin, "detail_model") and [ m for m in dataModel.Admin.detail_model] or [],
                "parent_models":dict([(f.rel.to.__name__,f.name) for f in dataModel._meta.fields if isinstance(f,models.fields.related.ForeignKey)]),
                
        }
        
        if options["detail_model"]:
            all_related_objects = dataModel._meta.get_all_related_objects()
            for r in all_related_objects:
                child_fk_field = hasattr(r.model.Admin, 'child_fk_field') and r.model.Admin.child_fk_field or ''#只需要从表中存在多个对于主表的外键时配置。不配置取默认
                if child_fk_field and r.field.name != child_fk_field:#去掉不合要求的多余的对象(如video_linkageio__id)
                    all_related_objects.remove(r)
                
            options["children_models"] = dict([(r.name, [r.model._meta.app_label, r.model.__name__,\
                                                         u"%s"%r.model._meta.verbose_name, r.field.name\
                                                         ]) for r in all_related_objects\
                                              ])
        
        
        hide_fields=hasattr(dataModel.Admin, 'hide_fields') and list(dataModel.Admin.hide_fields) or[]
        if hide_fields:
            options["disable_cols"]=hide_fields
        
        if hasattr(dataModel.Admin,"sort_fields"):
            options["sort_fields"]=dataModel.Admin.sort_fields
        if hasattr(dataModel.Admin,"photo_path"):
            options["photo_path"]=dataModel.Admin.photo_path
        if hasattr(dataModel.Admin,"photo_path_tran"):
            options["photo_path_tran"]=dataModel.Admin.photo_path_tran
            
        if hasattr(dataModel.Admin,"layout_types"):
            options["layout_types"]=dataModel.Admin.layout_types
        cache.set(cache_key,options,60*60*24*7)
        
        
    #*******actions cache*******
    usr = threadlocals.get_current_user()
    cache_key = u"%s_%s_%s_%s"%(lng,usr.username,model_name,"actions")
    actions = cache.get(cache_key)
    if not actions:
        if hasattr(dataModel,"get_all_operation_js"):
                actions=dataModel.get_all_operation_js(request.user)
        elif hasattr(dataModel.Admin, "read_only") and not dataModel.Admin.read_only:
                from dbapp.data_utils import hasPerm
                actions={}
                if hasPerm(request.user,dataModel,"add"):
                    actions["_add"]={
                                "verbose_name":u"%(name)s"%{"name":_(u"新增")},
                                "help_text":u"%(name)s"%{"name":_(u"新增记录")},
                                "confirm":"",
                                "params":0,
                                "for_model":True,
                                "only_one":False,
                                }
                if ( hasPerm(request.user,dataModel,"delete") and model_name=="User" ) \
                    or ( hasPerm(request.user,dataModel,"groupdel") and model_name=="Group"):
                    actions["_delete"]={
                                "verbose_name":u"%(name)s"%{"name":_(u"删除")},
                                "help_text":u"%(name)s"%{"name":_(u"删除选定记录")},
                                "confirm":"are you sure?",
                                "params":0,
                                "for_model":False,
                                "only_one":False,
                                "for_select":True
                                }
                                
                if hasPerm(request.user,dataModel,"change"):
                    actions["_change"]={
                                "verbose_name":u"%(name)s"%{"name":_(u"修改")},
                                "help_text": u"%(name)s"%{"name":_(u"修改选定记录")},
                                "params":0,
                                "for_model":False,
                                "only_one":True,
                                "for_select":True
                                }
                actions =smart_str(simplejson.dumps(actions))
        cache.set(cache_key,actions,60*60*24*7)
    return (simplejson.dumps(options),actions or '{"op":"null"}')