Beispiel #1
0
def calcPriReport(request):
    if request.method == "POST":
        deptIDs = request.POST.get('DeptIDs', "")
        userIDs = request.POST.get('UserIDs', "")
        st = request.POST.get('ComeTime', '')
        et = request.POST.get('EndTime', '')
        isforce = request.POST.get('IsForce', '1')
        st = datetime.datetime.strptime(st, '%Y-%m-%d')
        et = datetime.datetime.strptime(et, '%Y-%m-%d')
        deptids = []
        userids = []
        if userIDs == "":
            deptids = deptIDs.split(',')
        else:
            userids = userIDs.split(',')

        if userids or deptids:
            t1 = datetime.datetime.now()
            re = PriReportCalc(userids, deptids, st, et, int(isforce))
            t2 = datetime.datetime.now() - t1
            if re == -3:
                r = getJSResponse("result=-3")
            elif re == -4:
                r = getJSResponse("result=0;message=%s" % (_(u"账户已经被锁定!")))
            else:
                r = getJSResponse("result=0;message=%s%s%d sec" %
                                  (_(u'计算成功'), _(u'总时间'), t2.seconds))
        else:
            r = getJSResponse("result=1")
        return r
Beispiel #2
0
def get_pos_device_redis(request):
    """
        获取IC消费设备redis存放的内容
    """
    from mysite.pos.pos_ic.ic_sync_model import Pos_Device
    from mysite.pos.pos_ic.ic_sync_model import PosDeviceDoesNotExist
    from mysite.pos.pos_ic.ic_sync_action import init_ic_pos_device
    device_sn = request.REQUEST.get("sn", "")
    try:
        r_device = Pos_Device(device_sn)
        try:
            pos_device = r_device.get()
        except PosDeviceDoesNotExist:
            from mysite.iclock.models import Device as D
            device = D.objects.get(sn=device_sn)
            init_ic_pos_device(device)
            pos_device = r_device.get()
            return pos_device
        pos_log_stamp_id = pos_device.pos_log_stamp_id
        full_log_stamp_id = pos_device.full_log_stamp_id
        allow_log_stamp_id = pos_device.allow_log_stamp_id
        pos_dev_data_status = pos_device.pos_dev_data_status
        return getJSResponse(
            smart_str(
                simplejson.dumps({
                    'ret': 1,
                    'pos_dev_data_status': pos_dev_data_status,
                    'pos_log_stamp_id': pos_log_stamp_id,
                    'full_log_stamp_id': full_log_stamp_id,
                    'allow_log_stamp_id': allow_log_stamp_id
                })))
    except:
        #        import traceback;traceback.print_exc();
        return getJSResponse(smart_str(simplejson.dumps({'ret': -1})))
Beispiel #3
0
def applySpecialday(request):
    if request.method == "POST":
        id = request.POST.get('id', '')
        st = request.POST.get('StartSpecDay', '')
        et = request.POST.get('EndSpecDay', '')
        at = request.POST.get('ApplyDate', '')
        reson = request.POST.get('YUANYING', '')
        dateid = request.POST.get('DateID', '')
        st = datetime.datetime.strptime(st, "%Y-%m-%d %H:%M:%S")
        et = datetime.datetime.strptime(et, "%Y-%m-%d %H:%M:%S")
        if id == '':
            return getJSResponse("result=1")
        try:
            if settings.DATABASE_ENGINE == 'oracle':
                sql = """insert into %s (UserID, StartSpecDay, EndSpecDay, YUANYING,"DATE",DateID,State) values('%s',  to_date('%s','YYYY-MM-DD HH24:MI:SS'), to_date('%s','YYYY-MM-DD HH24:MI:SS'), '%s', to_date('%s','YYYY-MM-DD HH24:MI:SS'),'%s','0')""" % (
                    USER_SPEDAY._meta.db_table, int(id), st, et, reson, at,
                    dateid)
#                                print 111,sql
            else:
                sql = """insert into %s (UserID, StartSpecDay, EndSpecDay, YUANYING,Date,DateID,State) values('%s', '%s', '%s', '%s','%s','%s','0')""" % (
                    USER_SPEDAY._meta.db_table, int(id), st, et, reson, at,
                    dateid)
            customSql(sql)


#                        deleteCalcLog(UserID=int(id))
#adminLog(time=datetime.datetime.now(),User=request.user, model=u"%s"%USER_SPEDAY._meta.verbose_name,action=_("Add"),object=request.META["REMOTE_ADDR"]).save()
        except:
            return getJSResponse("result=1")
        return getJSResponse("result=0")
Beispiel #4
0
def calcPriReport(request):
        if request.method=="POST":
                deptIDs=request.POST.get('DeptIDs',"")
                userIDs=request.POST.get('UserIDs',"")
                st=request.POST.get('ComeTime','')
                et=request.POST.get('EndTime','')
                isforce=request.POST.get('IsForce','1')
                st=datetime.datetime.strptime(st,'%Y-%m-%d')
                et=datetime.datetime.strptime(et,'%Y-%m-%d')
                deptids=[]
                userids=[]
                if userIDs == "":
                        deptids=deptIDs.split(',')
                else:
                        userids=userIDs.split(',')


                if userids or deptids:        
                        t1=datetime.datetime.now()
                        re=PriReportCalc(userids,deptids,st,et,int(isforce))
                        t2=datetime.datetime.now()-t1
                        if re==-3:
                                r=getJSResponse("result=-3")
                        elif re==-4:
                                r=getJSResponse("result=0;message=%s"%(_(u"账户已经被锁定!")))
                        else:
                                r=getJSResponse("result=0;message=%s%s%d sec"%(_(u'计算成功'),_(u'总时间'),t2.seconds))
                else:
                        r=getJSResponse("result=1")
                return r
Beispiel #5
0
def send_doors_data(request):
    fun_mode = request.GET.get("func", "")
    type = request.GET.get("type", "")
    door = request.GET.get("data", "")

    if type == 'part':
        doors = AccDoor.objects.filter(id__in=door.split(','))

    datas = []
    if fun_mode in ["cancelalarm", "cancelall"]:  #单个门对应控制器的取消报警
        devs = Device.objects.filter(accdoor__in=doors)  #sure to exist
        for dev in devs:
            ret = dev.cancel_alarm()  #>=0成功,否则失败  None??????????????//////
            datas.append({
                "device_name": dev.alias,
                "ret": ret == None and -1 or ret
            })
        return getJSResponse(smart_str(simplejson.dumps({'result': datas})))
    elif fun_mode in ["opendoor", "openpart"]:  #, "openall"]:
        interval = request.GET.get("open_interval", 0)  #1-254
        enable = request.GET.get("enable_no_tzs", False)
        #print '----------interval=',interval
        #print '------enable=',enable
        if enable == "true":  #仅启用常开时间段,不开门
            for door_obj in doors:
                ret = sync_control_no(door_obj, 1)  #重新启用常开时间段
                #ret = sync_set_output(door_obj, 1, int(interval))#ret为None代表固件没有返回值,成功还是失败?  door_obj.lock_delay
                datas.append({
                    "door_name": door_obj.door_name,
                    "ret": ret == None and -1 or ret
                })
        else:
            for door_obj in doors:
                ret = sync_set_output(door_obj, 1, int(
                    interval))  #ret为None代表固件没有返回值,成功还是失败?  door_obj.lock_delay
                datas.append({
                    "door_name": door_obj.door_name,
                    "ret": ret == None and -1 or ret
                })
        return getJSResponse(smart_str(simplejson.dumps({'result': datas})))
    elif fun_mode in ["closedoor", "closepart"]:  # "closeall",:
        disable = request.GET.get("disable_no_tzs", False)
        #print '----disable=',disable
        if disable == "true":
            for door_obj in doors:
                ret = sync_control_no(door_obj, 0)  #仅禁用门常开时间段
                #ret = sync_set_output(door_obj, 1, 0)
                datas.append({
                    "door_name": door_obj.door_name,
                    "ret": ret == None and -1 or ret
                })
        else:
            #print '---in'
            for door_obj in doors:
                ret = sync_set_output(door_obj, 1, 0)
                datas.append({
                    "door_name": door_obj.door_name,
                    "ret": ret == None and -1 or ret
                })
        return getJSResponse(smart_str(simplejson.dumps({'result': datas})))
Beispiel #6
0
def uploadFile(request, path): #上传文件
    if request.method=='GET':
        return render_to_response("uploadfile.html",{"title": "Only for upload file test"})
    if "EMP_PIN" not in request.REQUEST:
        return getJSResponse("result=-1; message='Not specified a target';")
    f=device_pin(request.REQUEST["EMP_PIN"])+".jpg"
    size=saveUploadImage(request, "fileUpload", fname=get_stored_file_name("photo", None, f))
    return getJSResponse("result=%s; message='%s';"%(size,get_stored_file_url("photo",None,f)))
Beispiel #7
0
def reCaluateAction(request):

    if request.method == "POST":
        deptIDs = request.POST.get('DeptIDs', "")
        userIDs = request.POST.get('UserIDs', "")
        st = request.POST.get('ComeTime', '')
        et = request.POST.get('EndTime', '')
        isforce = request.POST.get('isForce', '0')
        st = datetime.datetime.strptime(st, '%Y-%m-%d')
        et = datetime.datetime.strptime(et, '%Y-%m-%d')
        deptids = []
        userids = []
        if userIDs == "":
            deptids = deptIDs.split(',')
            userids = Employee.objects.filter(DeptID__in=deptIDs).values_list(
                'id', flat=True).order_by('id')
        else:
            userids = userIDs.split(',')

        if userids or deptids:
            #                        print "OK"
            t1 = datetime.datetime.now()
            #                        re=MainCalc(userids,deptids,st,et,int(isforce))# lehman 2010-06-01 屏蔽
            try:
                from mysite.iclock.attcalc import MainCalc_new
                re = MainCalc_new(userids, deptids, st, et,
                                  int(isforce))  # lehman 2010-06-01 加入
            except:
                import traceback
                traceback.print_exc()
            t2 = datetime.datetime.now() - t1
            if re == -3:
                r = getJSResponse("result=-3")
            elif re == -4:
                r = getJSResponse("result=0;message=%s" % (_(u"账户已经被锁定!")))
            else:
                r = getJSResponse("result=0;message=%s%s%d sec" %
                                  (_(u'计算成功'), _(u'总时间'), t2.seconds))
        else:
            r = getJSResponse("result=1")
        #if userIDs == "":
        #try:
        #deptIDs=deptIDs.split(',')
        #userlist = Employee.objects.filter(DeptID__in=deptIDs ).values_list('id', flat=True).order_by('id')
        #except:
        #pass
        #userIDs=",".join(["%s" % int(i) for i in userlist])
        #t1=datetime.datetime.now()
        #if len(userIDs)>0:
        #re=MainCalc(userIDs,st,et,1)
        #t2=datetime.datetime.now()-t1
        #if re==-3:
        #r=getJSResponse("result=-3")
        #else:
        #r=getJSResponse("result=0;message=%d sec"%(t2.seconds))
        #else:
        #r=getJSResponse("result=1")
        return r
Beispiel #8
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))
Beispiel #9
0
def auditedTrans(request):
        try:        
                id=int(request.POST['id'])
                rk=request.POST['remarks']
                sql="update %s set Reserved2='%s' where id=%s "%(Transaction._meta.db_table,rk,id)
                customSql(sql)
                return getJSResponse("result=0")
        except:
                return getJSResponse("result=1")
Beispiel #10
0
def reCaluateAction(request):
   
        if request.method=="POST":
                deptIDs=request.POST.get('DeptIDs',"")
                userIDs=request.POST.get('UserIDs',"")
                st=request.POST.get('ComeTime','')
                et=request.POST.get('EndTime','')
                isforce=request.POST.get('isForce','0')
                st=datetime.datetime.strptime(st,'%Y-%m-%d')
                et=datetime.datetime.strptime(et,'%Y-%m-%d')
                deptids=[]
                userids=[]
                if userIDs == "":
                        deptids=deptIDs.split(',')
                        userids=Employee.objects.filter(DeptID__in=deptIDs ).values_list('id', flat=True).order_by('id')
                else:
                        userids=userIDs.split(',')
                
                
                if userids or deptids:        
#                        print "OK"
                        t1=datetime.datetime.now()
#                        re=MainCalc(userids,deptids,st,et,int(isforce))# lehman 2010-06-01 屏蔽 
                        try:
                           from mysite.iclock.attcalc import MainCalc_new                            
                           re = MainCalc_new(userids,deptids,st,et,int(isforce)) # lehman 2010-06-01 加入
                        except:
                            import traceback;
                            traceback.print_exc()                            
                        t2=datetime.datetime.now()-t1
                        if re==-3:
                                r=getJSResponse("result=-3")
                        elif re==-4:
                                r=getJSResponse("result=0;message=%s"%(_(u"账户已经被锁定!")))
                        else:
                                r=getJSResponse("result=0;message=%s%s%d sec"%(_(u'计算成功'),_(u'总时间'),t2.seconds))
                else:
                        r=getJSResponse("result=1")
                #if userIDs == "":
                        #try:
                                #deptIDs=deptIDs.split(',')
                                #userlist = Employee.objects.filter(DeptID__in=deptIDs ).values_list('id', flat=True).order_by('id')
                        #except:
                                #pass
                        #userIDs=",".join(["%s" % int(i) for i in userlist])
                #t1=datetime.datetime.now()
                #if len(userIDs)>0:        
                        #re=MainCalc(userIDs,st,et,1)
                        #t2=datetime.datetime.now()-t1
                        #if re==-3:
                                #r=getJSResponse("result=-3")
                        #else:
                                #r=getJSResponse("result=0;message=%d sec"%(t2.seconds))
                #else:
                        #r=getJSResponse("result=1")
                return r
Beispiel #11
0
def auditedTrans(request):
    try:
        id = int(request.POST['id'])
        rk = request.POST['remarks']
        sql = "update %s set Reserved2='%s' where id=%s " % (
            Transaction._meta.db_table, rk, id)
        customSql(sql)
        return getJSResponse("result=0")
    except:
        return getJSResponse("result=1")
Beispiel #12
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!" }')
Beispiel #13
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!" }')
Beispiel #14
0
def outputattrate(request):
    '''
    出勤率数据库视图
    '''
    json_data = []
    try:
        from mysite.personnel.models.model_emp import Employee
        emCounts = Employee.objects.count()
        if emCounts == 0:
            return getJSResponse(json.dumps([]))
        from mysite.iclock.models.model_trans import Transaction
        from mysite.att.models.model_empspecday import EmpSpecDay
        curr_dt = datetime.datetime.now()
        d1 = datetime.datetime(curr_dt.year, curr_dt.month, curr_dt.day, 0, 0,
                               1)
        d2 = datetime.datetime(curr_dt.year, curr_dt.month, curr_dt.day, 23,
                               59, 59)
        d3 = datetime.datetime(curr_dt.year, curr_dt.month, curr_dt.day)
        qs_atts_emp = Transaction.objects.select_related().filter(
            TTime__range=(d1, d2), UserID__isatt=True).distinct().values(
                "UserID__PIN").values_list("UserID")
        #atts = Transaction.objects.select_related().filter(TTime__range=(d1,d2),UserID__isatt=True).distinct().values("UserID__PIN").count()
        atts = qs_atts_emp.count()
        specialDays = EmpSpecDay.objects.select_related() \
                     .filter(Q(end__gte=d3,start__lte=d3)
                             |Q(start__year=d3.year,start__month=d3.month,start__day=d3.day)
                             |Q(end__year=d3.year,end__month=d3.month,end__day=d3.day)
                         ) \
                     .exclude(emp__in=qs_atts_emp) \
                     .distinct().values("emp__PIN")  \
                     .count()
        absents = Employee.objects.count() - atts - specialDays
        json_data.append({
            "label": u"%s" % _(u'考勤 ') + str(atts),
            "data": [[20, atts]]
        })
        json_data.append({
            "label": u"%s" % _(u'缺勤 ') + str(absents),
            "data": [[20, absents]]
        })
        json_data.append({
            "label": u"%s" % _(u'请假 ') + str(specialDays),
            "data": [[20, specialDays]]
        })

        json_data.sort(lambda x1, x2: x1["data"][0][1] - x2["data"][0][1])
        return getJSResponse(json.dumps(json_data))
    except:
        import traceback
        traceback.print_exc()
    finally:
        pass
    return getJSResponse(json.dumps([]))
Beispiel #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))
Beispiel #16
0
def funSaveCardmanage(request):
    from mysite.personnel.models.model_issuecard import IssueCard, PRIVAGE_CARD, POS_CARD, CARD_LOST, CARD_STOP, CARD_OVERDUE, CARD_VALID
    from mysite.iclock.models.dev_comm_operate import update_pos_device_info
    from mysite.iclock.models.model_device import Device, DEVICE_POS_SERVER
    from mysite.pos.models.model_cardmanage import CardManage
    from mysite.iclock.models.model_dininghall import Dininghall
    from mysite.pos.pos_constant import TIMEOUT
    from django.core.cache import cache
    obj = request.POST
    request.session.save()
    card_privage = obj['card_privage']
    card = int(obj['cardno'])
    sys_card_no = obj['sys_card_no']
    pwd = obj['Password']
    dining_id = obj['dining']
    try:
        if IssueCard.objects.get(cardno=card):
            return getJSResponse("result=ISUSE")  #卡号已经使用
    except:
        pass
    try:
        if IssueCard.objects.get(sys_card_no=sys_card_no):
            return getJSResponse("result=SYS_ISUSE")  #卡账号重复
    except:
        pass
    try:
        CardManage(card_no=card,
                   pass_word=pwd,
                   dining_id=dining_id,
                   cardstatus=CARD_VALID,
                   sys_card_no=sys_card_no,
                   card_privage=card_privage).save()
        IssueCard(cardno=card,
                  sys_card_no=sys_card_no,
                  cardstatus=CARD_VALID,
                  card_privage=card_privage,
                  Password=pwd,
                  type=None).save()
        dev = Device.objects.filter(
            device_type=DEVICE_POS_SERVER,
            dining=Dininghall.objects.get(pk=dining_id))
        objcard = IssueCard.objects.get(sys_card_no=sys_card_no)
        update_pos_device_info(dev, [objcard], "USERINFO")
        return getJSResponse("result=OK")
    except:
        cache.delete("IC_Card_Count")
        import traceback
        traceback.print_exc()
        return getJSResponse("result=FAIL")
Beispiel #17
0
def blance_valid(type, newblance, user):
    try:
        from mysite.personnel.models.model_iccard import ICcard
        iccardobj = ICcard.objects.filter(pk=type)
        lessmoney = iccardobj[0].less_money  #卡类最小余额
        maxmoney = iccardobj[0].max_money  #卡类最大余额
        if lessmoney > newblance and lessmoney > 0:
            return getJSResponse("result=OUT_LESSMONEY")
        elif newblance > maxmoney and maxmoney > 0:
            return getJSResponse("result=OUT_MAXMONEY")
        else:
            return "OK"
    except:
        import traceback
        traceback.print_exc()
Beispiel #18
0
def outputattrate(request):
    '''
    出勤率数据库视图
    '''
    json_data=[]
    try:
       from mysite.personnel.models.model_emp import Employee
       emCounts = Employee.objects.count()
       if emCounts==0:
           return getJSResponse(json.dumps([]))
       from mysite.iclock.models.model_trans import Transaction
       from mysite.att.models.model_empspecday import EmpSpecDay
       curr_dt= datetime.datetime.now()
       d1= datetime.datetime(curr_dt.year,curr_dt.month,curr_dt.day,0,0,1)
       d2= datetime.datetime(curr_dt.year,curr_dt.month,curr_dt.day,23,59,59)
       d3 = datetime.datetime(curr_dt.year,curr_dt.month,curr_dt.day)
       qs_atts_emp=Transaction.objects.select_related().filter(TTime__range=(d1,d2),UserID__isatt=True).distinct().values("UserID__PIN").values_list("UserID")
       #atts = Transaction.objects.select_related().filter(TTime__range=(d1,d2),UserID__isatt=True).distinct().values("UserID__PIN").count()
       atts=qs_atts_emp.count()
       specialDays = EmpSpecDay.objects.select_related() \
                    .filter(Q(end__gte=d3,start__lte=d3)
                            |Q(start__year=d3.year,start__month=d3.month,start__day=d3.day)
                            |Q(end__year=d3.year,end__month=d3.month,end__day=d3.day)
                        ) \
                    .exclude(emp__in=qs_atts_emp) \
                    .distinct().values("emp__PIN")  \
                    .count()
       absents= Employee.objects.count() -atts - specialDays
       json_data.append({
            "label":u"%s"%_(u'考勤 ')+ str(atts),
            "data":[[20,atts]]
       })
       json_data.append({
            "label":u"%s"%_(u'缺勤 ')+str(absents),
            "data":[[20,absents]]
       })
       json_data.append({
            "label":u"%s"%_(u'请假 ') + str(specialDays),
            "data":[[20,specialDays]]
       })
    
       json_data.sort(lambda x1,x2:x1["data"][0][1]-x2["data"][0][1])
       return getJSResponse(json.dumps(json_data))
    except:
        import traceback; traceback.print_exc()
    finally:
        pass
    return getJSResponse(json.dumps([]))
Beispiel #19
0
def select_checkType(request):
    ATTSTATES = (
        (1, _(u"正常")),
        (2, _(u"缺席")),
        (3, _(u"请假")),
        (4, _(u"签退未签到")),
        (5, _(u"签到未签退")),
        (6, _(u"迟到")),
        (7, _(u"早退")),
        (8, _(u"迟到、早退")),
        #    (9,_(u"迟到、未签到")),
        (10, _(u"迟到、未签退")),
        #    (11,_(u"早退")),
        (12, _(u"早退、未签到")),
        #    (13,_(u"早退、未签退")),
    )
    from mysite.meeting.models.detailMeeting import DetailMeeting
    checkType = DetailMeeting.objects.all()
    #    checkType = ATTSTATES
    checkTypeDict = {}
    #    for i in ATTSTATES:
    #        checkTypeDict[i.pk] = None

    for m in ATTSTATES:
        s = u'%s' % m[1]
        checkTypeDict[m[0]] = s
    return getJSResponse(smart_str(simplejson.dumps(checkTypeDict)))
Beispiel #20
0
def GenerateEmpCardJsonData(request, data):
    temp="""{tmp_name:{% autoescape off %}"{{tmp_name}}"{% endautoescape %},heads:{% autoescape off %}{{heads}}{% endautoescape %},fields:{% autoescape off %}{{fields}}{% endautoescape %},page_count:{{page_count}},record_count:{{record_count}},page_number:{{page_number}},data:[{% for i in data %}\
             [""" +"\"{{i.0}}\"," + "\"{{i.1}}\"," +"\"{{i.2}}\","+"\"{{i.3}}\"]" \
             """{%if not forloop.last%},{%endif%}{% endfor %}]}"""
    cc = Context(data)
    d = Template(temp).render(RequestContext(request, cc))
    return getJSResponse(d)
Beispiel #21
0
def funGetAllExcept(request):
    from mysite.att.models import LeaveClass, LeaveClass1
    from mysite.att.models.model_leaveclass1 import LEAVE_UNITS
    ret = {}
    ret['data'] = []
    l = LeaveClass.objects.all()
    for i in l:
        tmp = []
        tmp.append(u"%s" % _(i.LeaveName))
        tmp.append(i.ReportSymbol)
        if i.Unit >= 4:
            tmp.append("")
        else:
            tmp.append(u"%s" % _(LEAVE_UNITS[i.Unit - 1][1]))
        ret['data'].append(tmp)
    l = LeaveClass1.objects.all()
    for i in l:
        tmp = []
        tmp.append(u"%s" % _(i.name))
        tmp.append(i.ReportSymbol)
        if i.Unit >= 4 or i.pk in [1009, 1008]:
            tmp.append("")
        else:
            tmp.append(u"%s" % _(LEAVE_UNITS[i.Unit - 1][1]))
        ret['data'].append(tmp)
    return getJSResponse(smart_str(dumps(ret)))
Beispiel #22
0
def dailycalcReport(request):
    deptIDs = request.POST.get('DeptIDs', "")
    userIDs = request.POST.get('UserIDs', "")
    st = request.POST.get('ComeTime', '')
    et = request.POST.get('EndTime', '')
    st = datetime.datetime.strptime(st, '%Y-%m-%d')
    et = datetime.datetime.strptime(et, '%Y-%m-%d')
    #修改  郭学文   2010-05-17
    #        et=et+datetime.timedelta(days=-1)
    #        print "-------------------",st,et,deptIDs,userIDs
    #        st=datetime.datetime(2008,5,1)
    #        et=datetime.datetime(2008,5,30)
    r = CalcReportItem(request, deptIDs, userIDs, st, et, 1)
    #        print "11111111111111111111111"
    loadall = request.REQUEST.get('pa', '')
    if not loadall:

        allr = CalcReportItem(request, deptIDs, userIDs, st, et, 1, True)
        objdata = {}
        objdata['data'] = allr['datas']
        objdata['fields'] = allr['fieldnames']
        heads = {}
        for i in range(len(allr['fieldnames'])):
            heads[allr['fieldnames'][i]] = allr['fieldcaptions'][i]
        objdata['heads'] = heads

        tmp_name = save_datalist(objdata)
        r['tmp_name'] = tmp_name


#            print "allr['fieldnames']:%s"%r['fieldnames']
    return getJSResponse(smart_str(dumps(r)))
Beispiel #23
0
def calcReport(request):
        '''
        考勤汇总表
        '''
        deptIDs=request.POST.get('DeptIDs',"")
        userIDs=request.POST.get('UserIDs',"")
        st=request.POST.get('ComeTime','')
        et=request.POST.get('EndTime','')
        st=datetime.datetime.strptime(st,'%Y-%m-%d')
        et=datetime.datetime.strptime(et,'%Y-%m-%d')
        r=CalcReportItem(request,deptIDs,userIDs,st,et)
        loadall=request.REQUEST.get('pa','')
        if not loadall:
            objdata={}
            allr=CalcReportItem(request,deptIDs,userIDs,st,et,0,True)
            objdata['data']=allr['datas']
            objdata['fields']=allr['fieldnames']
            heads={}
            for i  in  range(len(allr['fieldnames'])):
                heads[allr['fieldnames'][i]]=allr['fieldcaptions'][i]
            objdata['heads']=heads
    
            tmp_name=save_datalist(objdata)
            r['tmp_name']=tmp_name
        return getJSResponse(smart_str(dumps(r)))
Beispiel #24
0
def getValidRecords(request):
    from dbapp.datalist import save_datalist
    from headerStatistics import ConstructValidRecordFields

    validRecords = []
    result = {}

    deptIDs = request.POST.get('DeptIDs', "")
    userIDs = request.POST.get('UserIDs', "")
    st = request.POST.get('ComeTime', '')
    et = request.POST.get('EndTime', '')
    #    st=datetime.datetime.strptime(st,'%Y-%m-%d')
    #    et=datetime.datetime.strptime(et,'%Y-%m-%d')
    #    et=et+datetime.timedelta(days=-1)

    FieldNames = []
    FieldCaption = []
    r = []
    r, FieldNames, FieldCaption = ConstructValidRecordFields()

    result['fieldnames'] = FieldNames
    result['fieldcaptions'] = FieldCaption
    result['datas'] = r
    heads = {}
    vr = {}

    for i in range(len(FieldNames)):
        heads[FieldNames[i]] = FieldCaption[i]
    result['heads'] = heads

    result['fields'] = FieldNames
    validRecords = list(getValidRecord(request))
    for key in r.keys():
        vr[key] = ""
    re = []
    records = {}

    for validRecord in validRecords:
        pass
        #        emp = Employee.objects.get(pk=validRecord.UserID.pk)
        #        vr['badgenumber'] = emp.PIN
        #        vr['username'] = emp.EName
        #        vr['deptid'] = emp.DeptID.code
        #        vr['deptname'] = emp.DeptID.name
        #        vr['numberMeeting'] = validRecord.meetingID.numberMeeting
        #        vr['nameMeeting'] = validRecord.meetingID.nameMeeting
        #        vr['startTime'] = validRecord.meetingID.startTime
        #        vr['endTime'] = validRecord.meetingID.endTime
        #        vr['startCheckTime'] =
        #        vr['endCheckTime'] =
        #        vr['duration'] =
        #        vr['nameSN'] = validRecord.nameSN

        re.append(records)
    result['data'] = re
    #    result['tmp_name'] = r
    #    tmp_name=save_datalist(result)
    #    r['tmp_name']=tmp_name
    #    print 'tmp_name:%s' % tmp_name
    return getJSResponse(smart_str(dumps(result)))
Beispiel #25
0
def deleteEmpFromDevice(request):
        userids=request.POST.get("userids","")
        deptIDs=request.POST.get("deptIDs","")
        sns=request.POST.getlist("K")
        flag=int(request.POST.get("flag"))        #flag=1为从所有设备删除人员
        if userids=='':
                deptidlist=[int(i) for i in deptIDs.split(',')]
                deptids=[]
                for d in deptidlist:#支持选择多部门
                        deptids+=getAllAuthChildDept(d,request)
                userids=Employee.objects.filter(DeptID__in=deptids)  
        else:
                emplist=userids.split(',')
                userids=Employee.objects.filter(id__in=emplist)  
        len(userids)
        if flag==1:
                o_devs=iclock.objects.all()
        else:
                o_devs=iclock.objects.filter(SN__in=sns)
        for dev in o_devs:
                d=getDevice(dev.SN)
                for userPin in userids:
                        append_dev_cmd(d, "DATA DEL_USER PIN=%s"%userPin.PIN)
                sendRecCMD(d)
        return getJSResponse("result=0")
Beispiel #26
0
def GenerateEmpPunchCardJsonData(request,data):
     temp="""{tmp_name:{% autoescape off %}"{{tmp_name}}"{% endautoescape %},heads:{% autoescape off %}{{heads}}{% endautoescape %},fields:{% autoescape off %}{{fields}}{% endautoescape %},page_count:{{page_count}},record_count:{{record_count}},page_number:{{page_number}},data:[{% for i in data %}\
             [""" +"\"{{i.0}}\"," + "\"{{i.1}}\"," +"\"{{i.2}}\","+"\"{{i.3}}\"]" \
             """{%if not forloop.last%},{%endif%}{% endfor %}]}"""
     cc = Context(data)
     d = Template(temp).render(RequestContext(request,cc))
     return getJSResponse(d)
Beispiel #27
0
def funGetAllExcept(request):
    from mysite.att.models import LeaveClass,LeaveClass1
    from mysite.att.models.model_leaveclass1    import LEAVE_UNITS
    ret={}
    ret['data']=[]
    l=LeaveClass.objects.all()
    for i in l:
        tmp=[]
        tmp.append(u"%s"%_(i.LeaveName))
        tmp.append(i.ReportSymbol)
        if i.Unit>=4 :
            tmp.append("")
        else:
            tmp.append(u"%s"%_(LEAVE_UNITS[i.Unit-1][1]))
        ret['data'].append(tmp)
    l=LeaveClass1.objects.all()
    for i in l:
        tmp=[]
        tmp.append(u"%s"%_(i.name))
        tmp.append(i.ReportSymbol)
        if i.Unit>=4 or i.pk in [1009,1008]:
            tmp.append("")
        else:        
            tmp.append(u"%s"%_(LEAVE_UNITS[i.Unit-1][1]))
        ret['data'].append(tmp)
    return getJSResponse(smart_str(dumps(ret)))
Beispiel #28
0
def newDevLog(request): #考勤记录实时监控
    device=get_device(request.REQUEST.get('SN', ""))
    result={}
    lasttid=int(request.REQUEST.get("lasttid","-1"));
    lastdid=int(request.REQUEST.get("lastdid","-1"));
    if lasttid==-1:
        return render_to_response("dlogcheck.html",{},RequestContext(request, {}))
#        if lasttid==0:
#                logs=Transaction.objects.filter(id__gt=lasttid).order_by("-id")[:1]
#        else:
    logs=Transaction.objects.filter(id__gt=lasttid).order_by("-id")
    if device: logs.filter(SN=device)
    logs=logs[:MAX_REALTIME_COUNT]
    if len(logs)>0: lasttid=logs[0].id
#        if lasttid==0:
#                logs=[]
    lines=[]
    for l in logs:
        line={}
        line['id']=l.id
        line['PIN']="%s"%l.employee()
        line['TTime']=l.TTime.strftime(settings.SHORT_DATETIME_FMT)
        line['State']=l.get_State_display()
        line['Verify']=l.get_Verify_display()
        line['SC']=l.State
        line['VC']=l.Verify
        line['Device']=smart_str(l.Device())
        line['WorkCode']=l.WorkCode=="0" and " " or l.WorkCode or ""
        line['Reserved']=l.Reserved=="0" and " " or l.Reserved or ""
        line['T']=1
        line['time']=l.TTime
        lines.append(line.copy())

    logs=oplog.objects.filter(id__gt=lastdid).order_by("-id")
    if device: logs.filter(SN=device)
    if len(logs)>0: lastdid=logs[0].id
    logs=logs[:MAX_REALTIME_COUNT]
    for l in logs:
        line={}
        line['id']=l.id
        line['PIN']=l.admin or ""
        line['TTime']=l.OPTime.strftime(settings.SHORT_DATETIME_FMT)
        line['State']=u"%s"%l.ObjName() or ""
        line['Verify']=u"%s"%l.OpName()
        line['SC']=u"%s"%l.Object
        line['VC']=u"%s"%l.OP
        line['Device']=smart_str(l.Device())
        line['WorkCode']=l.Param1 or ""
        line['Reserved']=l.Param2 or ""
        line['time']=l.OPTime
        lines.append(line.copy())
    lines.sort(lambda x,y: x['time']<y['time'] and 1 or -1)
    for i in lines: i.pop("time")
    lines=lines[:MAX_REALTIME_COUNT]
    result['msg']='OK'
    result['data']=lines
    result['lasttId']=lasttid
    result['lastDId']=lastdid
    result['ret']=len(lines)
    return getJSResponse(smart_str(simplejson.dumps(result)))
Beispiel #29
0
def le_reprot(request):
    '''
    汇总最早与最晚计算报表
    '''
    deptids=request.POST.get('DeptIDs','')
    userids=request.POST.get('UserIDs','')
    st=request.POST.get('ComeTime','')
    et=request.POST.get('EndTime','')
    st=datetime.datetime.strptime(st,'%Y-%m-%d')
    et=datetime.datetime.strptime(et,'%Y-%m-%d')
    r=le_reprot_calculate(request,deptids,userids,st,et)
    loadall=request.REQUEST.get('pa','')
    if not loadall:
       objdata={}
       allr=le_reprot_calculate(request,deptids,userids,st,et,True)
    
       objdata['data']=allr['datas']
       objdata['fields']=allr['fieldnames']
       heads={}
       for i  in  range(len(allr['fieldnames'])):
           heads[allr['fieldnames'][i]]=allr['fieldcaptions'][i]
       objdata['heads']=heads
       tmp_name=save_datalist(objdata)
       r['tmp_name']=tmp_name#用于导出  没有这个字段导出报错。
       
    return getJSResponse(smart_str(dumps(r)))
    
    
    
    '''
Beispiel #30
0
def le_reprot(request):
    '''
    汇总最早与最晚计算报表
    '''
    deptids = request.POST.get('DeptIDs', '')
    userids = request.POST.get('UserIDs', '')
    st = request.POST.get('ComeTime', '')
    et = request.POST.get('EndTime', '')
    st = datetime.datetime.strptime(st, '%Y-%m-%d')
    et = datetime.datetime.strptime(et, '%Y-%m-%d')
    r = le_reprot_calculate(request, deptids, userids, st, et)
    loadall = request.REQUEST.get('pa', '')
    if not loadall:
        objdata = {}
        allr = le_reprot_calculate(request, deptids, userids, st, et, True)

        objdata['data'] = allr['datas']
        objdata['fields'] = allr['fieldnames']
        heads = {}
        for i in range(len(allr['fieldnames'])):
            heads[allr['fieldnames'][i]] = allr['fieldcaptions'][i]
        objdata['heads'] = heads
        tmp_name = save_datalist(objdata)
        r['tmp_name'] = tmp_name  #用于导出  没有这个字段导出报错。

    return getJSResponse(smart_str(dumps(r)))
    '''
Beispiel #31
0
def funGetModelData(request,app_lable,model_name):
        from mysite.personnel.models.model_emp  import format_pin
        model=GetModel(app_lable,model_name)
        fields=request.REQUEST.get("fields","")
        userid=request.REQUEST.get("userid","")
        orgdept=request.REQUEST.get("orgdept","")
        para=dict(request.REQUEST)
        where={}
        for p in para:
                
                if p.find("__")>0:
                    t=p.split("__")
                    
                        
                    if p.find("__range")>0:
                        where[str(p)]=eval(para[p])
                    elif p.find("__in")>0:
                        where[str(p)]=para[p].split(",")
                    else:
                        where[str(p)]=para[p].decode("utf-8")                
                    
        #print where
        #print model
        if fields:
                fields=fields.split(",")
        if model:
                if userid:
                        data=model.objects.filter(id__in=userid)
                else:
                        data=model.objects.all()
                if where:
                        data=model.objects.filter(Q(**where))
                #print data
                if fields:
                        data=data.values_list(*fields)
                #print data
                xdata=[]
                i=0 
                while i<len(data):
                        tmpdata=data[i]
                        j=0
                        ndata=[]
                        while j<len(tmpdata):
                                #print type(tmpdata[j])
                                if type(tmpdata[j])==datetime.time:
                                        #print "1"
                                        ndata.append(tmpdata[j].strftime("%H:%M:%S"))
                                elif type(tmpdata[j])==datetime.date:
                                        ndata.append(tmpdata[j].strftime("%Y-%m-%d"))
                                else:
                                        ndata.append(tmpdata[j])
                                j+=1
                        xdata.append(ndata)
                        i+=1
                #print xdata
                if orgdept:
                    xdata=processdept(xdata)
                return getJSResponse(smart_str(dumps(xdata)))
        else:
                return NoFound404Response(request)
Beispiel #32
0
def deleteEmpFromDevice(request):
    userids = request.POST.get("userids", "")
    deptIDs = request.POST.get("deptIDs", "")
    sns = request.POST.getlist("K")
    flag = int(request.POST.get("flag"))  #flag=1为从所有设备删除人员
    if userids == '':
        deptidlist = [int(i) for i in deptIDs.split(',')]
        deptids = []
        for d in deptidlist:  #支持选择多部门
            deptids += getAllAuthChildDept(d, request)
        userids = Employee.objects.filter(DeptID__in=deptids)
    else:
        emplist = userids.split(',')
        userids = Employee.objects.filter(id__in=emplist)
    len(userids)
    if flag == 1:
        o_devs = iclock.objects.all()
    else:
        o_devs = iclock.objects.filter(SN__in=sns)
    for dev in o_devs:
        d = getDevice(dev.SN)
        for userPin in userids:
            append_dev_cmd(d, "DATA DEL_USER PIN=%s" % userPin.PIN)
        sendRecCMD(d)
    return getJSResponse("result=0")
Beispiel #33
0
def newTransLog(request): #考勤记录实时监控
    from devview import del_len
    from redis.server import queqe_server
    result={}
    lastid=int(request.REQUEST.get("lastid","-1"));
    if lastid==-1:
        return render_to_response("logcheck.html",{},RequestContext(request, {}))
    q=queqe_server()
    l=q.llen(REALTIME_EVENT)
    if lastid>l and lastid>=MAX_TRANS_IN_QUEQE/2:
        ll=lastid		
        while lastid>l:
           if lastid>=MAX_TRANS_IN_QUEQE/2:
               lastid-=MAX_TRANS_IN_QUEQE/2
           else:
               break
        print "Queqe Len: ", l, ", lastid: %s->%s"%(ll, lastid)
    if l>lastid:
        event_list=q.lrange(REALTIME_EVENT, 0, -lastid)
        lastid+=len(event_list)
        event_list=event_list[:MAX_REALTIME_COUNT]  #id=%s\tPIN=%s\tEName=%s\tTTime=%s\tState=%s\tVerify=%s\tDevice=%s
    else:
        event_list=[]

    result['msg']='OK'
    result['data']=[dict([item.split("=") for item in line.split("\t")]) for line in event_list]
    result['lastId']=lastid
    result['ret']=len(event_list)
    return getJSResponse(smart_str(simplejson.dumps(result)))
Beispiel #34
0
def select_city(request, app_label, model_name):
    from dbapp.datautils import QueryData
    from dbapp.modelutils import GetModel
    from dbapp.utils import getJSResponse
    import json
    from django.http import HttpResponseRedirect, HttpResponse
    from mysite.personnel.models.model_city import City
    from mysite.personnel.models.model_emp import format_pin

    ModelCls = GetModel(app_label, model_name)

    ret = []
    keys = [
        "state",
    ]
    filter_dict = {}
    qs = []
    for e in keys:
        value = request.REQUEST.get(e, None)
        if value:
            filter_dict[e] = value

    if filter_dict:
        qs = ModelCls.all_objects.filter(**filter_dict)
        for elem in qs:
            ret.append([elem.id, elem.city_code, elem.city_name])
    return getJSResponse(json.dumps(ret))
Beispiel #35
0
def calcReport(request):
    '''
        考勤汇总表
        '''
    deptIDs = request.POST.get('DeptIDs', "")
    userIDs = request.POST.get('UserIDs', "")
    st = request.POST.get('ComeTime', '')
    et = request.POST.get('EndTime', '')
    st = datetime.datetime.strptime(st, '%Y-%m-%d')
    et = datetime.datetime.strptime(et, '%Y-%m-%d')
    r = CalcReportItem(request, deptIDs, userIDs, st, et)
    loadall = request.REQUEST.get('pa', '')
    if not loadall:
        objdata = {}
        allr = CalcReportItem(request, deptIDs, userIDs, st, et, 0, True)
        objdata['data'] = allr['datas']
        objdata['fields'] = allr['fieldnames']
        heads = {}
        for i in range(len(allr['fieldnames'])):
            heads[allr['fieldnames'][i]] = allr['fieldcaptions'][i]
        objdata['heads'] = heads

        tmp_name = save_datalist(objdata)
        r['tmp_name'] = tmp_name
    return getJSResponse(smart_str(dumps(r)))
Beispiel #36
0
def dailycalcReport(request):
        deptIDs=request.POST.get('DeptIDs',"")
        userIDs=request.POST.get('UserIDs',"")
        st=request.POST.get('ComeTime','')
        et=request.POST.get('EndTime','')
        st=datetime.datetime.strptime(st,'%Y-%m-%d')
        et=datetime.datetime.strptime(et,'%Y-%m-%d')
        #修改  郭学文   2010-05-17
#        et=et+datetime.timedelta(days=-1)
#        print "-------------------",st,et,deptIDs,userIDs
#        st=datetime.datetime(2008,5,1)
#        et=datetime.datetime(2008,5,30)
        r=CalcReportItem(request,deptIDs,userIDs,st,et,1)
#        print "11111111111111111111111"
        loadall=request.REQUEST.get('pa','')
        if not loadall:
            
            allr=CalcReportItem(request,deptIDs,userIDs,st,et,1,True)
            objdata={}
            objdata['data']=allr['datas']
            objdata['fields']=allr['fieldnames']
            heads={}
            for i  in  range(len(allr['fieldnames'])):
                heads[allr['fieldnames'][i]]=allr['fieldcaptions'][i]
            objdata['heads']=heads
            
            tmp_name=save_datalist(objdata)
            r['tmp_name']=tmp_name
#            print "allr['fieldnames']:%s"%r['fieldnames']
        return getJSResponse(smart_str(dumps(r)))
Beispiel #37
0
def funGetAllExcept_fast(request):
    from mysite.att.models import LeaveClass
    from mysite.att.models.model_leaveclass1 import LEAVE_UNITS
    from mysite.att.att_param import LoadAttRule
    qs = LoadAttRule()
    ret = {}
    ret['data'] = []
    l = LeaveClass.objects.all()
    for i in l:
        tmp = []
        tmp.append(u"%s" % _(i.LeaveName))
        tmp.append(i.ReportSymbol)
        if i.Unit >= 4:
            tmp.append("")
        else:
            tmp.append(u"%s" % _(LEAVE_UNITS[i.Unit - 1][1]))
        ret['data'].append(tmp)
    l = qs['LeaveClass']
    for i in l:
        tmp = []
        tmp.append(u"%s" % _(i['LeaveName']))
        tmp.append(i['ReportSymbol'])
        if i['Unit'] >= 4 or i['LeaveId'] in [1009, 1008]:
            tmp.append("")
        else:
            tmp.append(u"%s" % _(LEAVE_UNITS[i['Unit'] - 1][1]))
        ret['data'].append(tmp)
    return getJSResponse(smart_str(dumps(ret)))
Beispiel #38
0
def funGetModelData(request, app_lable, model_name):
    from mysite.personnel.models.model_emp import format_pin
    model = GetModel(app_lable, model_name)
    fields = request.REQUEST.get("fields", "")
    userid = request.REQUEST.get("userid", "")
    orgdept = request.REQUEST.get("orgdept", "")
    para = dict(request.REQUEST)
    where = {}
    for p in para:

        if p.find("__") > 0:
            t = p.split("__")

            if p.find("__range") > 0:
                where[str(p)] = eval(para[p])
            elif p.find("__in") > 0:
                where[str(p)] = para[p].split(",")
            else:
                where[str(p)] = para[p].decode("utf-8")

    #print where
    #print model
    if fields:
        fields = fields.split(",")
    if model:
        if userid:
            data = model.objects.filter(id__in=userid)
        else:
            data = model.objects.all()
        if where:
            data = model.objects.filter(Q(**where))
        #print data
        if fields:
            data = data.values_list(*fields)
        #print data
        xdata = []
        i = 0
        while i < len(data):
            tmpdata = data[i]
            j = 0
            ndata = []
            while j < len(tmpdata):
                #print type(tmpdata[j])
                if type(tmpdata[j]) == datetime.time:
                    #print "1"
                    ndata.append(tmpdata[j].strftime("%H:%M:%S"))
                elif type(tmpdata[j]) == datetime.date:
                    ndata.append(tmpdata[j].strftime("%Y-%m-%d"))
                else:
                    ndata.append(tmpdata[j])
                j += 1
            xdata.append(ndata)
            i += 1
        #print xdata
        if orgdept:
            xdata = processdept(xdata)
        return getJSResponse(smart_str(dumps(xdata)))
    else:
        return NoFound404Response(request)
Beispiel #39
0
def submitLeaveClass(request):
        if request.method=="POST":
                s=request.POST['LeaveClass']
                l=loads(s)
                SaveLeaveClass(l,1)  #保存假类表
                InitData()
                #adminLog(time=datetime.datetime.now(),User=request.user, model='LeaveClass').save()
                return getJSResponse("result=0")
Beispiel #40
0
def funAttParamSetting_o(request):
    InitData()
    la = LoadAttRule(True)  # 0607  考勤参数 界面刷新 显示问题
    lc = LoadCalcItems()
    qs = la.copy()
    qs['LeaveClass'] = lc
    #print lc
    return getJSResponse(smart_str(dumps(qs)))
Beispiel #41
0
def submitAttParam(request):
    '''
    保存考勤参数视图
    '''
    SaveAttRule(request.POST)
    from mysite.att.calculate.global_cache import C_ATT_RULE
    C_ATT_RULE.refresh()
    return getJSResponse("result=0")
Beispiel #42
0
def submitLeaveClass(request):
    if request.method == "POST":
        s = request.POST['LeaveClass']
        l = loads(s)
        SaveLeaveClass(l, 1)  #保存假类表
        InitData()
        #adminLog(time=datetime.datetime.now(),User=request.user, model='LeaveClass').save()
        return getJSResponse("result=0")
Beispiel #43
0
def funValidRecord(request):
    mids = []
    userIDs = request.POST.get('UserIDs', None)
    meetingIDs = request.REQUEST.get("meetingIDS", None)
    mids = meetingIDs.split(',')
    getAndSaveMeetingOriginalRecord(mids)
    getMeetingValidRecord(mids)
    return getJSResponse(None)
Beispiel #44
0
def funValidCard(request):
    from mysite.personnel.models.model_issuecard import IssueCard, PRIVAGE_CARD, CARD_LOST, CARD_STOP, CARD_OVERDUE, CARD_VALID, POS_CARD
    from base.cached_model import STATUS_OK, STATUS_INVALID, STATUS_LEAVE
    obj = request.POST
    operate_type = obj['operate_type']
    if operate_type == '12':  #换卡
        sys_card_no = obj['old_sys_card_no']
    elif operate_type in ['8', '1']:  #修改卡资料
        sys_card_no = obj['sys_card_no']
    try:
        objcard = IssueCard.objects.get(sys_card_no=sys_card_no)
    except:
        return getJSResponse("result=Not_REGISTER_CARD")
    if objcard:
        if objcard.card_privage == PRIVAGE_CARD:
            return getJSResponse("result=PRIVAGE_CARD")
        elif operate_type == '12' and objcard.cardstatus in [
                CARD_OVERDUE, CARD_VALID
        ]:
            return getJSResponse("result=CARD_OVERDUE_VALID")
        elif objcard.UserID.status == STATUS_LEAVE:
            return getJSResponse("result=STATUS_LEAVE")
        elif objcard.cardstatus == CARD_STOP:
            return getJSResponse("result=CARD_STOP")
        elif operate_type <> '12' and objcard.cardstatus == CARD_LOST:
            return getJSResponse("result=CARD_LOST")
        else:
            return getJSResponse("result=OK")
Beispiel #45
0
def saveFingerprint(request):    #保存指纹采集器登记的指纹模板
        userid=int(request.POST['UserIDs'])
        fid=request.POST.get('fingerid',0)
        tmp=request.POST.get('templates','')
        tmps=tmp.split(',')
        fids=fid.split(',')
        for i in range(len(fids)):
                try:
                        
                        f=fptemp.objects.filter(UserID=userid, FingerID=int(fids[i])-1)
                        if f.count():
                                sql="update template set template = '%s', utime='%s' where userid='%s' and fingerid=%s" % (tmps[i], str(datetime.datetime.now())[:19], userid, int(fids[i])-1)
                        else:
                                sql="insert into template(template, userid, fingerid,  utime, valid, DelTag) values('%s', '%s', %s, '%s', 1, '0')" % (tmps[i], userid, int(fids[i])-1, str(datetime.datetime.now())[:19])
                        customSql(sql)
                except:
                        return getJSResponse("result=1")
        return getJSResponse("result=0")
Beispiel #46
0
def calcAttShiftsReport(request):
        deptIDs=request.POST.get('DeptIDs',"")
        userIDs=request.POST.get('UserIDs',"")
        st=request.POST.get('ComeTime','')
        et=request.POST.get('EndTime','')
        st=datetime.datetime.strptime(st,'%Y-%m-%d')
        et=datetime.datetime.strptime(et,'%Y-%m-%d')
        r=CalcAttShiftsReportItem(request,deptIDs,userIDs,st,et)
        return getJSResponse(smart_str(dumps(r)))
Beispiel #47
0
def send_doors_data(request):
    fun_mode = request.GET.get("func", "")
    type = request.GET.get("type", "")
    door = request.GET.get("data", "")
    
    if type == 'part':
        doors = AccDoor.objects.filter(id__in=door.split(','))
            
    datas = []
    if fun_mode in ["cancelalarm", "cancelall"]:#单个门对应控制器的取消报警
        devs = Device.objects.filter(accdoor__in=doors)#sure to exist
        for dev in devs:
            ret = dev.cancel_alarm()#>=0成功,否则失败  None??????????????//////
            datas.append({ "device_name": dev.alias, "ret": ret == None and -1 or ret })
        return getJSResponse(smart_str(simplejson.dumps({'result': datas})))
    elif fun_mode in ["opendoor", "openpart"]:#, "openall"]:
        interval = request.GET.get("open_interval", 0)#1-254
        enable = request.GET.get("enable_no_tzs", False)
        #print '----------interval=',interval
        #print '------enable=',enable
        if enable == "true":#仅启用常开时间段,不开门
            for door_obj in doors:
                ret = sync_control_no(door_obj, 1)#重新启用常开时间段
                #ret = sync_set_output(door_obj, 1, int(interval))#ret为None代表固件没有返回值,成功还是失败?  door_obj.lock_delay
                datas.append({ "door_name": door_obj.door_name, "ret": ret == None and -1 or ret })
        else:
            for door_obj in doors:
                ret = sync_set_output(door_obj, 1, int(interval))#ret为None代表固件没有返回值,成功还是失败?  door_obj.lock_delay
                datas.append({ "door_name": door_obj.door_name, "ret": ret == None and -1 or ret })
        return getJSResponse(smart_str(simplejson.dumps({'result': datas})))
    elif fun_mode in ["closedoor", "closepart"]:# "closeall",:
        disable = request.GET.get("disable_no_tzs", False)
        #print '----disable=',disable
        if disable == "true":
            for door_obj in doors:  
                ret = sync_control_no(door_obj, 0)#仅禁用门常开时间段              
                #ret = sync_set_output(door_obj, 1, 0)
                datas.append({ "door_name": door_obj.door_name, "ret": ret == None and -1 or ret}) 
        else:
            #print '---in'
            for door_obj in doors:  
                ret = sync_set_output(door_obj, 1, 0)
                datas.append({ "door_name": door_obj.door_name, "ret": ret == None and -1 or ret})        
        return getJSResponse(smart_str(simplejson.dumps({'result': datas})))
Beispiel #48
0
def shift_detail(request):
    '''
    班次明细
    '''
    from datetime import datetime
    if request.method=="POST":
            id=int(request.POST.get("Shift_id","0"))    #---班次ID
            unit=int(request.POST.get("unit","1"))  #---单位
            weekStart=int(request.POST.get("weekStartDay","0"))
            N=NUM_RUN.objects.filter(pk=id).values_list('pk','Name','StartDate','EndDate','Cycle','Units')  #---班次
            p=[]
            for f in N:
                if type(f)==datetime.date:
                    p.append(f.strftime("%Y-%m-%d"))
                else:
                    p.append(f)
            
            objNRD=NUM_RUN_DEIL.objects.filter(Num_runID=id).order_by('Num_runID', 'Sdays', 'StartTime')#---班次详细
            l=[]
            dic={}
            li=[]
            n=0
            d={}
            if objNRD.count()==0:
                    d['StartTime']=0
                    d['EndTime']=0
                    d['Color']=16715535
                    d['SchName']=''
                    l.append(d.copy())
                    qs=l
            else:
                    sch=GetSchClasses()
                    for t in objNRD:
                        try:
                            j=FindSchClassByID(t.SchclassID_id)
                            x=sch[j]['TimeZone']

                            st=(float(x['StartTime'].hour)+float(x['StartTime'].minute)/60)/24
                            et=(float(x['EndTime'].hour)+float(x['EndTime'].minute)/60)/24
                            sd=t.Sdays
                            ed=t.Edays
                            
                            clr=sch[j]['Color']
                            d['StartTime']=st+sd
                            d['EndTime']=et+ed
                            if clr==None:
                                    d['Color']=16715535
                            else:
                                    d['Color']=clr
                            d['SchName']=t.SchclassID.SchName
                            l.append(d.copy())
                        except:
                            import traceback;traceback.print_exc()
            j={'data':l,'N':p}
                    
    return getJSResponse(smart_str(dumps(j)))
Beispiel #49
0
def get_data(request):
    fun_mode = request.REQUEST.get("func", "")

    if fun_mode == "video":
        type = request.GET.get("type", "") 
        u = request.user
        aa = u.areaadmin_set.all()
        a_limit = aa and [int(a.area_id) for a in aa] or [int(area.pk) for area in Area.objects.all()]#非超级管理员且没有配置有效区域(默认全部)的有效区域id列表(即用户手动配置过用户区域的)
        print "a_limit=", a_limit
        if type == 'all_device':
            devices = Device.objects.filter(area__pk__in=a_limit).filter(device_type=2).order_by('id').values_list('id', 'alias')
            videos = Device.objects.filter(area__pk__in=a_limit).filter(device_type=4).order_by('id').values_list('id', 'alias')
            doors = AccDoor.objects.filter(device__area__pk__in=a_limit).order_by('id').values_list('id', 'door_name')
            return getJSResponse(smart_str(simplejson.dumps({ 'type': 'all', 'videos': [device for device in videos], 'devices': [device for device in devices], 'doors': [door for door in doors]})))
        if type == 'device':    #通过设备查找相绑定的视频服务器
            device_id = request.GET.get("device_id", 0)
            doors = AccDoor.objects.filter(device__area__pk__in=a_limit).filter(device__id=device_id).order_by('id').values_list('id', 'door_name')
            door = [door[0] for door in doors]
            linkages = AccLinkageIO.objects.filter(device__pk__in = [device_id]).filter(in_address_hide__in = door)
            videos=[link.video_linkageio.id for link in linkages]
            devices = Device.objects.filter(area__pk__in=a_limit).filter(id__in=videos).filter(device_type=4).order_by('id').values_list('id', 'alias', 'ipaddress', 'ip_port', 'video_login', 'comm_pwd')
            return getJSResponse(smart_str(simplejson.dumps({ 'type': 'device', 'videos': [device for device in devices], 'devices': '', 'doors': [door for door in doors]})))
        if type == 'door':
            door_id = request.GET.get("door_id", 0)
            print "door_id=", door_id
            doors = AccDoor.objects.filter(device__area__pk__in=a_limit).filter(id=door_id)
            print "doors=", doors, "=", doors[0].device
            videos=[]
            if doors:
                linkages = AccLinkageIO.objects.filter(device = doors[0].device).filter(in_address_hide = doors[0].door_no)
                videos=[link.video_linkageio.id for link in linkages]
            devices = Device.objects.filter(area__pk__in=a_limit).filter(id__in=videos).filter(device_type=4).order_by('id').values_list('id', 'alias', 'ipaddress', 'ip_port', 'video_login', 'comm_pwd')
            print "devices=", devices
            return getJSResponse(smart_str(simplejson.dumps({ 'type': 'door', 'videos': [device for device in devices], 'devices': '', 'doors': ""})))
        if type == 'all_video':
            devices = Device.objects.filter(area__pk__in=a_limit).filter(device_type=4).order_by('id').values_list('id', 'alias', 'ipaddress', 'ip_port', 'video_login', 'comm_pwd')
            return getJSResponse(smart_str(simplejson.dumps({ 'type': 'allvideo', 'videos': [device for device in devices], 'devices': ''})))            
        if type == 'videoserver':
            device_id = request.GET.get("server_id", 0)
            devices = Device.objects.filter(area__pk__in=a_limit).filter(device_type=4, id=device_id).order_by('id').values_list('id', 'alias', 'ipaddress', 'ip_port', 'video_login', 'comm_pwd')
            #devices[0][5] = devices[0][5] and decrypt(devices[0][5]) or ""
            device=[devices[0][0], devices[0][1], devices[0][2], devices[0][3], devices[0][4], devices[0][5] and decrypt(devices[0][5]) or ""];
            return getJSResponse(smart_str(simplejson.dumps({ 'type': 'video', 'videos': '', 'devices': device})))
Beispiel #50
0
def getchange(request):
    from mysite.personnel.models import Employee    
    id=request.GET.get("k")
    u=Employee.objects.get(pk=id)
    data={}
    if u:
        data['dept']=int(u.DeptID_id)
        data['title']=u.Title and str(u.Title) or 0
        data['hiretype']=u.emptype and str(u.emptype) or 1
        data['attarea']=[int(i.pk) for i in u.attarea.all()]
    return getJSResponse(smart_str(data))
Beispiel #51
0
def funGetShifts(request):
        nrun = NUM_RUN.objects.all().order_by('Num_runID')
        len(nrun)
        re = []
        ss = {}
        for t in nrun:
                ss['shift_id'] = t.Num_runID
                ss['shift_name'] = t.Name
                t = ss.copy()
                re.append(t)
        return getJSResponse(smart_str(dumps(re)))
Beispiel #52
0
def funAttParamSetting(request):
        '''
        获取考勤参数数据
        '''
        InitData()
        la = LoadAttRule()
        lc = LoadCalcItems()
        qs = la.copy()
        qs['LeaveClass'] = lc
        #print lc
        return getJSResponse(smart_str(dumps(qs)))
Beispiel #53
0
def cancel_alarm(request):
    data =request.GET.get("data", "")#前端已做了不能为空的判断,故正常情况下data!=''
    datas = []
    if data:
        #doors = set(data.split(','))#去掉重复的门id
        doors_ids = [int(d) for d in data.split(',')]
        devs = Device.objects.filter(accdoor__pk__in=door_ids)
        for dev in devs:
            ret = dev.cancel_alarm()
            datas.append({ "dev_name": dev.alias, "ret": ret == None and -1 or ret})
    return getJSResponse(smart_str(simplejson.dumps({'result': datas})))
Beispiel #54
0
def assignedShifts(request):
        if request.method=="POST":
                id=request.POST.get("emp","")
                deptids=request.POST.get("deptIDs","")
                if id=="":
                        deptIDs=deptids.split(',')
                        UserIDs = Employee.objects.filter(DeptID__in=deptIDs ).values_list('id', flat=True).order_by('id')
                        len(UserIDs)
                        id=UserIDs[0]
                schPlan=LoadSchPlan(int(id),True,True,True)
                return getJSResponse(smart_str(dumps(schPlan)))
Beispiel #55
0
def saveFields(request):
        u=request.user
        f=request.POST.get('Fields','')
        tblName=request.POST.get('tblName','')
        item=ItemDefine(Author=u,ItemName=tblName,ItemType='report_fields_define')
        if f!="":
                #item=ItemDefine(Author=u,ItemName=tblName,ItemType='report_fields_define',ItemValue=f)
                item.ItemValue=f
                item.save()
        else:
                item.delete()
        return getJSResponse("result=0")
Beispiel #56
0
def  searchComposite(request):
        deptIDs=request.POST.get('deptIDs',"")
        userIDs=request.POST.get('UserIDs',"")
        st=request.POST.get('startDate','')
        et=request.POST.get('endDate','')
        st=datetime.datetime.strptime(st,'%Y-%m-%d')
        et=datetime.datetime.strptime(et,'%Y-%m-%d')
        if len(userIDs)>0 and userIDs!='null':
                ids=userIDs.split(',')
        elif len(deptIDs)>0:
                deptids=deptIDs.split(',')
#                deptids=[]
#                for d in deptidS:#支持选择多部门
#                        deptids+=getAllAuthChildDept(d,request)
                ot=['DeptID','PIN']
                ids=Employee.objects.filter(DeptID__in=deptids,OffDuty__lt=1).values_list('id', flat=True).order_by(*ot)
        try:
                offset = int(request.GET.get('p', 1))
        except:
                offset=1
                
        Fields,Capt=ConstructScheduleFields()
        re=[]
        Result={}
        Result['fieldnames']=Fields
        Result['fieldcaptions']=Capt
        Result['datas']=re

        for id in ids:
                userplan=LoadSchPlanEx(id,True,True)
                l=GetUserScheduler(int(id), st, et, userplan['HasHoliday'])
                d={}
                for t in l:
                        d['userid']=id
                        d['deptid']=userplan['DeptName']
                        d['badgenumber']=userplan['BadgeNumber']
                        d['username']=userplan['UserName']
                        d['starttime']=t['TimeZone']['StartTime']
                        d['endtime']=t['TimeZone']['EndTime']
                        d['schname']=t['SchName']
                        re.append(d.copy())
        limit= int(request.GET.get('l', 500))
        page_count =len(re)/limit+1
        if offset>page_count:offet=page_count
        item_count =len(re)
        res=re[(offset-1)*limit:offset*limit]
        Result['item_count']=item_count
        Result['page']=offset
        Result['limit']=limit
        Result['from']=(offset-1)*limit+1
        Result['page_count']=page_count
        Result['datas']=res
        return getJSResponse(smart_str(dumps(Result)))
Beispiel #57
0
def get_dept_tree_data(request):
    selected=request.REQUEST.getlist("K")
    selected=[int(item) for item in selected]
    level=request.REQUEST.get("LEVEL","1")
    root=request.REQUEST.get("root","1")
    try:
        root=int(root)
    except:
        root=None
        if level=='1': level=2
    from models import depttree
    html=depttree.DeptTree(Department.objects.all()).html_jtree(selected,root_id=root, next_level=int(level))
    return getJSResponse(html)