Beispiel #1
0
    def post(self):
        ''' Create a employee '''
        arguments = request.get_json(force=True)
        first_name = arguments.get('firstName').strip()
        last_name = arguments.get('lastName').strip()
        department = arguments.get('department').strip() or None
        tel_one = arguments.get('telOne').strip() or None
        tel_two = arguments.get('telTwo').strip() or None
        email = arguments.get('email').strip() or None
        role = arguments.get('role').strip() or None

        if not last_name:
            return abort(400, 'Name cannot be empty!')
        try:
            person = Person(first_name, last_name)
            contact = Contact(email=email, tel_one=tel_one, tel_two=tel_two)
            department = Department.query.filter_by(id=int(department)).first()

            if not person.save_person():
                person = Person.query.filter_by(full_name=(first_name + ' ' +
                                                           last_name)).first()
            if not contact.save_contact():
                contact = Contact.query.filter_by(email=email).first()
            contact_person = ContactPerson(person=person, contact=contact)
            if not contact_person.save_contact_person():
                contact_person = ContactPerson.query.filter_by(
                    person=person, contact=contact).first()

            employee = Employee(contact_person=contact_person,
                                department=department)
            if employee.save_employee():
                return {'message': 'Employee created successfully!'}, 201
            return abort(409, message='Employee already exists!')
        except Exception as e:
            abort(400, message='Failed to create new employee -> {}'.format(e))
    def patch(self, employee_id):
        """
        Update a single employee
        """

        # To do check if user is admin
        schema = EmployeeSchema(partial=True)

        update_data = request.get_json()

        validated_update_data, errors = schema.load(update_data)

        if errors:
            return dict(status="fail", message=errors), 400

        employee = Employee.get_by_id(employee_id)

        if not employee:
            return dict(
                status="fail",
                message=f"Employee with id {employee_id} not found"), 404

        updated_employee = Employee.update(employee, **validated_update_data)

        if not updated_employee:
            return dict(status='fail', message='Internal Server Error'), 500

        return dict(status="success",
                    message="Employee updated successfully"), 200
Beispiel #3
0
def insert_employee_data(times=20):
    for _ in range(times):
        name, gender = random_gender_name()
        department_id = random.choice([7, 8, 9])
        emp = Employee(name=name, gender=gender, department_id=department_id)
        try:
            with db.auto_commit():
                db.session.add(emp)
        except Exception:
            continue
Beispiel #4
0
def verify_password(username_or_token, password):
    # first try to authenticate by token
    employee = Employee.verify_auth_token(username_or_token)
    if not employee:
        # try to authenticate with email/password
        employee = Employee.query.filter_by(email=username_or_token).first()
        if not employee or not employee.verify_password(password):
            return False
    g.employee = employee
    return True
def create_employee():
    # now = datetime.now()
    # dt_string = now.strftime("%d/%m/%Y %H:%M:%S")
    roles = getAllRoles()
    data = json.loads(request.data)
    role = data.get("role", None)
    user_role = role if role else "Employee"
    e = Employee(teams=data.get("teams", None),
                 name=data.get("name", None),
                 email=data.get("email", None),
                 id=str(uuid.uuid4()),
                 created_at=datetime.utcnow(),
                 updated_at=datetime.utcnow())

    for role in roles:
        if role["role"] == user_role:
            e.role = role["id"]

    e.hash_password(request.json['password'])
    db.session.add(e)
    db.session.commit()

    return e.serialize, 200
    def post(self):
        """
        Creating an Employee ad
        """
        employee_schema = EmployeeSchema()

        employee_data = request.get_json()

        validated_employee_data, errors = employee_schema.load(employee_data)

        if errors:
            return dict(status='fail', message=errors), 400

        employee = Employee(**validated_employee_data)

        saved_employee = employee.save()

        if not saved_employee:
            return dict(status='fail', message='Internal Server Error'), 500

        new_employee_data, errors = employee_schema.dumps(employee)

        return dict(status='success',
                    data=dict(employee=json.loads(new_employee_data))), 201
    def get(self):
        """
        Getting All employees
        """

        employee_schema = EmployeeSchema(many=True)

        employees = Employee.find_all()

        employees_data, errors = employee_schema.dumps(employees)

        if errors:
            return dict(status="fail", message="Internal Server Error"), 500

        return dict(status="success",
                    data=dict(employees=json.loads(employees_data))), 200
Beispiel #8
0
async def find_by_field(
        filter_field: str = None,
        filter_value: Any = None
) -> List[Employee]:
    info("Method findByField called field: {}, value: {}".format(filter_field, filter_value))
    value = validate_filter(filter_field, filter_value)

    if value is None:
        error("Failed to validate filter value")
        raise HTTPException(status_code=400, detail="failed to validate value")

    result = []
    for e in Conn.find({filter_field: value}, {'_id': 0}):
        result.append(Employee(**e))

    return result
Beispiel #9
0
def employee_data_input():
    if request.method == 'POST':
        employee = Employee()
        employee.set_attrs(request.form)
        employee.company = current_user.company
        employee.updatetime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime((time.time())))  # 修改数据更新时间
        db.session.add(employee)
        db.session.commit()
        return render_template('employee/employeeInput.html')
    else:
        employee_id = "%04d" % (Employee.query.filter(and_(Employee.status == 1, Employee.company == current_user.company)).count() + 1)
        return render_template('employee/employeeInput.html', employee_id=employee_id)
    def delete(self, employee_id):
        """
        Delete a single employee
        """

        employee = Employee.get_by_id(employee_id)

        if not employee:
            return dict(
                status="fail",
                message=f"Employee with id {employee_id} not found"), 404

        deleted_employee = employee.delete()

        if not deleted_employee:
            return dict(status='fail', message='Internal Server Error'), 500

        return dict(status='success', message="Successfully deleted"), 200
    def get(self, employee_id):
        """
        Getting individual employee
        """
        schema = EmployeeSchema()

        employee = Employee.get_by_id(employee_id)

        if not employee:
            return dict(
                status="fail",
                message=f"Employee with id {employee_id} not found"), 404

        employee_data, errors = schema.dumps(employee)

        if errors:
            return dict(status="fail", message=errors), 500

        return dict(status='success',
                    data=dict(employee=json.loads(employee_data))), 200
Beispiel #12
0
async def find_by_range(
        filter_field: str = None,
        range_from: Any = None,
        range_to: Any = None
) -> List[Employee]:
    info("Method findByRange called field: {}, from: {}, to: {}".format(filter_field, range_from, range_to))

    ranges = validate_range(filter_field, range_from, range_to)
    if ranges is None:
        error("Failed to validate range parameters")
        raise HTTPException(status_code=400, detail="failed to validate range parameters")

    result = []

    cursor = Conn.find(
        filter={filter_field: {"$gte": ranges["from"], "$lte": ranges["to"]}},
        projection={"_id": 0})

    for e in cursor:
        result.append(Employee(**e))

    return result
Beispiel #13
0
def employee_view(request):
    """/app/employee/
    API RESTFUL for employee management

    GET - return a list of employees that match parameters
        /app/employee/                  - list all employees
        /app/employee/?id=00            - list employee for specified id
        /app/employee/[email protected]   - list employee with informed email
        /app/employee/?name=xxxx        - list all employees that matches the string sequence (SQL LIKE). It is insensitive case
        /app/employee/?department_id=00 - list all employees for department

    POST - create a new employee registry. it will be set as active by default
        request.body should be in JSON format:
        {
            "name": "", 
            "email": "",
            "department_id": ""
        }

        - name          - REQUIRED - String(200)
        - email         - REQUIRED - String(200) - UNIQUE
        - department_id - OPTIONAL - integer - foreign key to Department
    
    PUT - allows to edit name, email, department and if it is active. Inform only the field to be edited
        request.body should be in JSON format:
        {
            "id": "",
            "name": "", 
            "email": "",
            "department_id": "",
            "active": ""
        }

        - id            - REQUIRED - employee.id
        - name          - OPTIONAL
        - email         - OPTIONAL
        - department_id - OPTIONAL
        - active        - OPTIONAL

    """

    # if not request.body:
    #     return HttpResponseBadRequest()

    if request.method == 'GET':
        parameters = request.GET

        id = parameters.get('id')
        name = parameters.get('name')
        email = parameters.get('email')
        department_id = parameters.get('department_id')

        if id or email:
            try:
                employee = Employee.objects.get(
                    id=id) if id else Employee.objects.get(email=email)
            except Employee.DoesNotExist:
                return HttpResponseNotFound('Employee not found.')

            response = [{
                'id':
                employee.id,
                'name':
                employee.name,
                'email':
                employee.email,
                'department':
                employee.department.id if employee.department else None,
                'department__name':
                employee.department.name if employee.department else None,
                'active':
                employee.active
            }]

        elif name:
            query = Employee.objects.filter(name__icontains=name) \
                    .values(
                        'id',
                        'name',
                        'email',
                        'department',
                        'department__name' ,
                        'active'
                        )
            if query.count() == 0:
                return HttpResponseNotFound('Employee not found.')

            response = list(query)

        elif department_id:
            try:
                department = Department.objects.get(id=department_id)
            except Department.DoesNotExist:
                return HttpResponseNotFound('Department not found.')

            query = Employee.objects.filter(department=department) \
                    .values(
                        'id',
                        'name',
                        'email',
                        'department',
                        'department__name' ,
                        'active'
                        )
            response = list(query)

        else:
            query = Employee.objects.all() \
                    .values(
                        'id',
                        'name',
                        'email',
                        'department',
                        'department__name' ,
                        'active'
                        )
            response = list(query)

    elif request.method == 'POST':
        request_body = json.loads(request.body) if request.body else {}

        id = request_body.get('id')
        name = request_body.get('name')
        email = request_body.get('email')
        department_id = request_body.get('department_id')
        active = (request_body.get('active')
                  == 'True') if request_body.get('active') else None

        if not all([name, email]):
            return HttpResponseBadRequest('Data missing')

        if not re.match('[^@]+@[^@]+\.[^@]+', email):
            return HttpResponseBadRequest('Invalid email address.')

        try:
            department = Department.objects.get(
                id=department_id) if department_id else None
            employee = Employee(name=name,
                                email=email,
                                department=department,
                                active=True)
            employee.save()

        except Department.DoesNotExist:
            return HttpResponseNotFound('Department not found.')

        except IntegrityError as exc:
            if str(exc) == 'UNIQUE constraint failed: app_person.email':
                return HttpResponseBadRequest(
                    'Employee with email {} already exists.'.format(email))
            else:
                raise exc

        response = [{
            'id':
            employee.id,
            'name':
            employee.name,
            'email':
            employee.email,
            'department':
            employee.department.id if employee.department else None,
            'department__name':
            employee.department.name if employee.department else None,
            'active':
            employee.active
        }]

    elif request.method == 'PUT':
        request_body = json.loads(request.body) if request.body else {}
        id = request_body.get('id')
        name = request_body.get('name')
        email = request_body.get('email')
        department_id = request_body.get('department_id')
        active = request_body.get('active') if request_body.get(
            'active') else None

        if not id:
            return HttpResponseBadRequest('id is required.')

        try:
            employee = Employee.objects.get(id=id)
        except Employee.DoesNotExist:
            return HttpResponseNotFound('Employee not found.')

        try:
            department = Department.objects.get(
                id=department_id) if department_id else None
            employee.name = name or employee.name
            employee.email = email or employee.email
            employee.department = department or employee.department
            employee.active = (active == 'True') if active else employee.active

            employee.save()

        except Department.DoesNotExist:
            return HttpResponseNotFound('Department not found.')

        except IntegrityError as exc:
            if str(exc) == 'UNIQUE constraint failed: app_person.email':
                return HttpResponseBadRequest(
                    'Employee with email {} already exists.'.format(email))
            else:
                raise exc

        response = [{
            'id':
            employee.id,
            'name':
            employee.name,
            'email':
            employee.email,
            'department':
            employee.department.id if employee.department else None,
            'department__name':
            employee.department.name if employee.department else None,
            'active':
            employee.active
        }]

    else:
        return HttpResponseBadRequest()

    return JsonResponse(response,
                        json_dumps_params={'indent': 2},
                        safe=False,
                        status=(200 if request.method == 'GET' else 201))
Beispiel #14
0
from pprint import pprint

from pymongo import MongoClient
from datetime import datetime, timedelta

# connect with MongoEngine
connect('project')

# connect with PyMongo
client = MongoClient()
db = client["project"]


# MONGOENGINE queries

emps = Employee.objects(name="funcionario 0").first()
emps = Employee.objects(routine__in=["5x2", "12x36"])
emps = Employee.objects(
    admission__gte=datetime(2020, 1, 1),
    admission__lte=datetime(2021, 1, 1),
).limit(3)

pprint(emps)
print()

# mesmas queries com PyMongo

emps = next(db.employee.find({"name": "funcionario 0"}))
emps = db.employee.find({
    "routine": {"$in": ["5x2", "12x36"]},
})