Exemple #1
0
def calendar(year):
    company = g.user.company

    if request.method == 'GET':
        access_calendar = AccessCalendar.get_or_create(company.id, year)
    elif request.method == 'PUT':
        params = request.get_json() or request.form
        access_calendar = AccessCalendar.get_or_create(company.id, year)
        access_calendar.days = params['days']
        db.session.add(access_calendar)
        update_company_data_version(company)
    return success_result(access_calendar.get_json())
Exemple #2
0
def add_visitor():
    params = request.form or request.get_json()

    try:
        name = params['name']
        photo = request.files.get('photo')
        purpose = params.get('purpose')
        interviewee = params.get('interviewee')
        come_from = params.get('come_from')
        phone = params.get('phone')
        remark = params.get('remark')
        company_id = g.user.company_id
        start_time = int(params.get('start_time', 0))
        end_time = int(params.get('end_time', 0))
        vip = bool(int(params.get('vip', False)))
        subject_type = int(params.get('subject_type', 1))
        description = params.get('description')
    except:
        import traceback
        print traceback.format_exc()
        return error_result(ErrorCode.ERROR_INVALID_PARAM)

    if not start_time or not end_time:
        start_time = g.TIMESTAMP - 5 * 60
        end_time = g.TIMESTAMP + 2 * 3600

    if vip:
        subject_type = SubjectType.TYPE_VIP

    subject = Subject(company_id=company_id,
                      name=name,
                      subject_type=subject_type,
                      description=description,
                      remark=remark,
                      start_time=start_time,
                      end_time=end_time,
                      purpose=purpose,
                      interviewee=interviewee,
                      come_from=come_from,
                      phone=phone,
                      password='******')
    db.session.add(subject)
    db.session.commit()

    if photo:
        photo, error = create_user_photo(photo, company_id)
        if error:
            return error
        subject.photos.append(photo)
        update_company_data_version(g.user.company, subject.id)

    return success_result(subject.get_json())
Exemple #3
0
def user_info(subject_id):
    if subject_id is None:
        subject = g.subject
    else:
        subject = g.subject.visitors.filter_by(id=subject_id).first()
        if subject is None:
            return abort(404)

    if request.method == 'GET':
        attendance = subject.attendances.filter_by(date=date.today()).first()
        ret = subject.get_json(with_photos=True)
        ret['holiday'] = is_holiday(g.subject.company_id, date.today())
        ret['today'] = time.time()
        ret['clock_in'] = u'无'
        ret['clock_out'] = u'无'

        if attendance and attendance.earliest_record:
            ret['clock_in'] = timestamp_to_timestring(
                attendance.earliest_event.timestamp)
        if attendance and attendance.latest_record:
            ret['clock_out'] = timestamp_to_timestring(
                attendance.latest_event.timestamp)
        ret['boxes'] = [box.get_json() for box in subject.company.boxes]
        return success_result(ret)
    elif request.method == 'PUT':
        params = request.form or request.get_json()
        fields = ('description', 'avatar', 'start_time', 'end_time', 'title',
                  'gender', 'department', 'name', 'email', 'phone', 'purpose',
                  'interviewee', 'come_from', 'job_number', 'remark',
                  'visit_notify', 'subject_type')
        subject.update(fields, params)
        if params.get('birthday'):
            subject.birthday = date.fromtimestamp(int(params['birthday']))
        db.session.add(subject)
        db.session.commit()
        update_company_data_version(subject.company, subject.id)
        return success_result(subject.get_json())
    elif request.method == 'DELETE':
        subject = Subject.query.get(subject_id)
        if subject is None:
            return abort(404)
        if g.subject.visitors.filter_by(id=subject_id).first() is None:
            return error_result(ErrorCode.ERROR_NOT_ALLOWED)
        for photo in subject.photos:
            storage.remove(photo.url)
        company = subject.company
        db.session.delete(subject)
        db.session.commit()
        update_company_data_version(company, subject.id)
        return success_result()
Exemple #4
0
def subject_import_photo():
    try:
        photo = request.files['photo']
        name = photo.filename.rsplit('.', 1)[0]
    except:
        return error_result(ErrorCode.ERROR_INVALID_PARAM)
    photo, error = create_user_photo(photo, g.user.company_id)
    if error:
        return error
    subject = Subject(company_id=g.user.company_id, subject_type=SubjectType.TYPE_EMPLOYEE,
                      name=name, create_time=g.TIMESTAMP)
    subject.photos.append(photo)
    db.session.add(subject)
    db.session.commit()
    update_company_data_version(g.user.company, subject.id)
    return success_result(subject.get_json(with_photos=True))
Exemple #5
0
def login():
    params = request.form or request.get_json()

    try:
        username = params['username']
        password = params['password']
        pad_id = params['pad_id']
        device_type = int(params['device_type'])
        if device_type not in [ScreenType.DOOR_PAD, ScreenType.FRONT_PAD]:
            raise Exception()
    except:
        return error_result(ErrorCode.ERROR_INVALID_PARAM)

    user = User.query.filter_by(username=username).first()
    if user:
        if user.check_password(password):
            if not user.password_reseted:
                return error_result(ErrorCode.ERROR_PASSWORD_NEED_CHANGE)

            login_user(user)
            ret = user.get_json()
            if pad_id == 'importer':
                return success_result(ret)
            screen = Screen.query.filter_by(company_id=user.company_id,
                                            token=pad_id).first()
            if screen is None:
                screen = Screen(
                    company_id=user.company_id,
                    token=pad_id,
                    name='pad',
                    theme='center',
                    type=device_type,
                    camera_position=ScreenType.get_desc(device_type))
                db.session.add(screen)
                db.session.commit()
                update_company_data_version(user.company)

            ret['position'] = screen.camera_position
            ret['screen_token'] = screen.token
            ret['boxes'] = [box.get_json() for box in user.company.boxes]
            ret['company'] = user.company.get_json()
            return success_result(ret)
        else:
            return error_result(ErrorCode.ERROR_PASSWORD_ERROR)
    else:
        return error_result(ErrorCode.ERROR_USER_NOT_EXIST)
Exemple #6
0
def subject_photo_delete(photo_id):
    photo = Photo.query.get(photo_id)
    subject = Subject.query.get(photo.subject_id)

    if photo is None:
        return abort(404)

    if g.subject.visitors.filter_by(id=photo.subject_id).first() is None:
        return error_result(ErrorCode.ERROR_NOT_ALLOWED)

    storage.remove(photo.url)
    db.session.delete(photo)
    db.session.query(PhotoAlternative).filter(PhotoAlternative.subject_id == photo.subject_id).\
                                       filter(PhotoAlternative.url == photo.url).delete()
    db.session.commit()
    update_company_data_version(g.subject.company, subject.id)
    return success_result({})
Exemple #7
0
def attendance_setting():
    company = g.user.company

    if request.method == 'GET':
        ret = {
            'door_range': json.loads(company.door_range),
            'attendance_on': company.attendance_on,
            'attendance_range': json.loads(company.normal_time),
            'tolerance': json.loads(company.tolerance),
            'weekdays': json.loads(company.door_weekdays),
            'attendance_weekdays': json.loads(company.attendance_weekdays),
            'warning': company.warning
        }
        return success_result(ret)
    elif request.method == 'PUT':
        params = request.get_json()
        company.door_range = json.dumps(params['door_range'])
        company.normal_time = json.dumps(params['attendance_range'])
        company.tolerance = json.dumps(params['tolerance'])
        company.attendance_on = params['attendance_on']
        weekdays = json.dumps(params['weekdays'])
        attendance_weekdays = json.dumps(params.get('attendance_weekdays', []))
        # 更新门禁控制
        if company.door_weekdays != weekdays:
            access_calendar = AccessCalendar.get_or_create(
                company.id,
                datetime.date.today().year)
            access_calendar.set_weekdays(params['weekdays'])
            db.session.add(access_calendar)
            company.door_weekdays = weekdays
        # 更新考勤日期
        if company.attendance_weekdays != attendance_weekdays:
            attendance_calendar = AttendanceCalendar.get_or_create(
                company.id,
                datetime.date.today().year)
            attendance_calendar.set_weekdays(
                params.get('attendance_weekdays', []))
            db.session.add(attendance_calendar)
            company.attendance_weekdays = attendance_weekdays

        company.warning = params['warning']
        db.session.add(company)
        update_company_data_version(company)
    return success_result({})
Exemple #8
0
def subject_avatar_create():
    try:
        avatar = request.files['avatar']
        subject_id = int(request.form.get('subject_id', 0))
    except:
        return error_result(ErrorCode.ERROR_INVALID_PARAM)
    if not avatar:
        return error_result(ErrorCode.ERROR_INVALID_PARAM)

    image_uri = storage.save_image(avatar.stream, 'avatar', resize=(300, 300), sync=True)
    if not image_uri:
        return error_result(ErrorCode.ERROR_UNKNOWN)

    if subject_id:
        subject = Subject.query.get(subject_id)
        subject.avatar = image_uri
        db.session.add(subject)
        db.session.commit()
        update_company_data_version(g.user.company, subject.id)
    return success_result({'url': storage.get_url(image_uri)})
Exemple #9
0
def update_avatar(subject_id):
    if subject_id is None:
        subject = g.subject
    else:
        subject = g.subject.visitors.filter_by(id=subject_id).first()
        if subject is None:
            return abort(404)

    avatar_file = request.files.get('avatar')
    if avatar_file is None:
        return error_result(ErrorCode.ERROR_INVALID_PARAM)

    uri = storage.save_image(avatar_file.stream, 'avatar', resize=(300, 300))
    if not uri:
        return error_result(ErrorCode.ERROR_UNKNOWN)
    subject.avatar = uri
    db.session.add(subject)
    db.session.commit()
    update_company_data_version(subject.company, subject.id)
    return success_result(subject.get_json())
Exemple #10
0
def subject_photo_create():
    try:
        payload = request.files['photo']
        subject_id = int(request.form.get('subject_id', 0))
        old_photo_id = int(request.form.get('old_photo_id', 0))
    except:
        return error_result(ErrorCode.ERROR_INVALID_PARAM)

    if not payload:
        return error_result(ErrorCode.ERROR_INVALID_PARAM)

    if subject_id:
        subject = Subject.query.filter_by(id=subject_id).first()
        if subject is None:
            return error_result(ErrorCode.ERROR_INVALID_PARAM)
        subject_type = subject.subject_type
        if ((subject_type == SubjectType.TYPE_VISITOR and not g.user.has_permission(AccountPermission.ADD_VISITOR)) or
                (subject_type == SubjectType.TYPE_EMPLOYEE and not g.user.has_permission(
                        AccountPermission.ADD_EMPLOYEE))):
            return error_result(ErrorCode.ERROR_PERMISSION_DENIED)

    photo, error = create_user_photo(payload, g.user.company_id)
    if error:
        return error

    # delete old photo
    if subject_id and old_photo_id:
        old_photo = Photo.query.get(old_photo_id)
        if old_photo and old_photo.subject_id == subject_id:
            storage.remove(old_photo.url)
            db.session.delete(old_photo)
            db.session.query(PhotoAlternative).filter(PhotoAlternative.subject_id == old_photo.subject_id). \
                filter(PhotoAlternative.url == old_photo.url).delete()

    if subject_id:
        photo.subject_id = subject_id
    db.session.add(photo)
    db.session.commit()
    if subject_id:
        update_company_data_version(g.user.company, subject.id)
    return success_result(photo.get_json())
Exemple #11
0
def add_visitor():
    params = request.args or request.get_json() or request.form
    device, err = get_device_from_params(params)
    if err is not None:
        return error_result(err)

    name = params.get('name')
    vip = params.get('vip', False)
    photo = request.files.get('photo')
    company = device.company

    if not photo:
        error_result(ErrorCode.ERROR_INVALID_PARAM)
    if not name:
        name = generate_name() + u'(临时名)'

    user_photo, error = create_user_photo(photo, company.id)
    if error:
        return error

    subject_type = SubjectType.TYPE_VIP if vip else SubjectType.TYPE_VISITOR
    start_time = g.TIMESTAMP - 5 * 60
    end_time = g.TIMESTAMP + 2 * 3600
    subject = Subject(company_id=company.id,
                      name=name,
                      subject_type=subject_type,
                      start_time=start_time,
                      end_time=end_time)
    db.session.add(subject)
    db.session.commit()

    user_photo.subject_id = subject.id
    db.session.add(user_photo)
    db.session.commit()

    update_company_data_version(company, subject.id)
    return success_result(subject.get_data())
Exemple #12
0
def bind_box():
    params = request.form or request.get_json()
    try:
        email = params['email']
        password = params['password']
        box_token = params['box_token']
        is_binding = params['binding'] == 'true'
    except:
        return error_result(ErrorCode.ERROR_INVALID_PARAM)

    user = User.query.filter_by(username=email).first()
    if not user:
        return error_result(ErrorCode.ERROR_USER_NOT_EXIST)
    if not user.check_password(password):
        return error_result(ErrorCode.ERROR_PASSWORD_ERROR)

    box = Box.query.filter_by(box_token=box_token).first()
    if not box:
        return error_result(ErrorCode.ERROR_BOX_NOT_EXIST)
    if is_binding:
        if box.company_id is not None:
            return error_result(ErrorCode.ERROR_BOX_BINDED)
        box.company_id = user.company_id
        db.session.add(box)
        db.session.commit()
        update_company_data_version(box.company)
    else:
        if box.company_id is None:
            return error_result(ErrorCode.ERROR_BOX_NOT_BINDED)
        if box.company_id != user.company_id:
            return error_result(ErrorCode.ERROR_BOX_NOT_MATCH_USER)
        update_company_data_version(box.company)
        box.company_id = None
        db.session.add(box)
        db.session.commit()
    return success_result({})
Exemple #13
0
def subject_detail(sid):
    params = request.form or request.get_json() or request.args

    subject = g.user.company.subjects.filter_by(id=sid).first()
    if not subject:
        return error_result(ErrorCode.ERROR_SUBJECT_NOT_EXIST)

    if request.method == 'GET':
        return success_result(subject.get_json(with_photos=True))

    subject_type = subject.subject_type
    if ((subject_type == SubjectType.TYPE_VISITOR and not g.user.has_permission(AccountPermission.ADD_VISITOR)) or
            (subject_type == SubjectType.TYPE_EMPLOYEE and not g.user.has_permission(AccountPermission.ADD_EMPLOYEE))):
        return error_result(ErrorCode.ERROR_PERMISSION_DENIED)

    if request.method == 'PUT':
        email = params.get('email')
        avatar = params.get('avatar')
        if email and Subject.query.filter(Subject.id != sid, Subject.email == email).first():
            return error_result(ErrorCode.ERROR_EMAIL_EXISTED)

        if params.get('visitor_type') is not None:
            params['subject_type'] = params['visitor_type']
        fields = (
            'subject_type',
            'description',
            'title',
            'gender',
            'start_time',
            'end_time',
            'department',
            'name',
            'email',
            'phone',
            'purpose',
            'interviewee',
            'come_from',
            'job_number',
            'remark'
        )
        subject.update(fields, params)

        if avatar is None:
            pass
        elif avatar.startswith('http'):
            pass
        elif avatar == '':
            storage.remove(subject.avatar)
            subject.avatar = ''
        elif avatar.startswith('data:image'):
            avatar_url = storage.save_image_base64(avatar, 'avatar', sync=True)
            if avatar_url:
                storage.remove(subject.avatar)
                subject.avatar = avatar_url
            DisplayDevice.query.filter_by(company_id=subject.company.id).update({'user_info_timestamp': g.TIMESTAMP})

        if 'photo_ids' in params:
            _update_photos(subject, params['photo_ids'])
        if 'birthday' in params:
            subject.birthday = datetime.date.fromtimestamp(int(params['birthday'])) if params['birthday'] else None
        if 'entry_date' in params:
            subject.entry_date = datetime.date.fromtimestamp(int(params['entry_date'])) if params[
                'entry_date'] else None
        db.session.add(subject)
        db.session.commit()
        update_company_data_version(subject.company, subject.id)
    elif request.method == 'DELETE':
        for photo in subject.photos:
            storage.remove(photo.url)
        db.session.delete(subject)
        db.session.commit()
        update_company_data_version(subject.company, subject.id)
    return success_result(subject.get_json(with_photos=True))