Пример #1
0
def register(request, *args, **kwargs):
    if (request.user.is_admin) | (request.user.is_staff):
        form = UserCreationForm(request.POST or None)
        if form.is_valid():
            form.save()
            obj = UserProfile.objects.latest('id')
            if (form.cleaned_data.get('is_doctor') == True):
                doct = doctor(user=obj)
                doct.save()
            if request.POST.get('is_staff'):
                l = Staff(user=obj)
                l.save(obj)

            elif request.POST.get('is_medical'):
                l = medical(user=obj)
                l.save(obj)
            elif request.POST.get('is_lab'):
                l = lab(user=obj)
                l.save(obj)
            elif request.POST.get('is_admin'):
                l = superadmin(user=obj)
                l.save(obj)
            # else:
            #     pass
            # print(who)
            # print(obj)

            print("user Creted0")
            messages.success(request, 'User Register successfully!')
            return redirect("login")
        return render(request, 'register.html', {'form': form})
    else:
        form = UserLoginForm(request.POST or None)
        context = {"form": form}
        return render(request, 'login.html', context)
Пример #2
0
 def wm_import_stuff(self):
   for staff in Staff.objects.all():
     staff.delete()
   wm_staff_list = WorkflowmaxStaff.objects.all()
   for wm_staff in wm_staff_list:
     staff = Staff()
     staff.wm_import(wm_staff)
Пример #3
0
def staff_register(request):

    if request.method == 'POST':
        username = request.POST.get('username', None)
        password = request.POST.get('password', None)
        repeatpassword = request.POST.get('repeatpassword', None)
        firstname = request.POST.get('firstname', None)
        lastname = request.POST.get('lastname', None)
        sex = request.POST.get('sex', None)
        phone = request.POST.get('phone', None)
        email = request.POST.get('email', None)
        if password == '' or repeatpassword == '':
            return HttpResponse('empty password')
        elif password != repeatpassword:
            return HttpResponse('repeat error')
        elif User.objects.filter(username=username):
            return HttpResponse('user exist')
        else:
            new_user = User.objects.create_user(username=username,
                                                password=password)
            new_user.save()
            new_staff = Staff(account=new_user,
                              firstname=firstname,
                              lastname=lastname,
                              sex=sex,
                              phone=phone,
                              email=email)
            new_staff.save()
            return HttpResponseRedirect('/staff/login')

    return render_to_response('staff/staffregister.html')
Пример #4
0
def add_staff(request):
    # 添加完成后跳到最后一页
    staff_num = Staff.objects.all().count()
    per_page = 5
    if staff_num % per_page == 0:
        max_page = math.ceil(staff_num / per_page) + 1
    else:
        max_page = math.ceil(staff_num / per_page)

    if request.method == "GET":
        # 点击返回回到之前所在页面
        page = request.GET.get('page', 1)
        context = {'page': page}
        return render(request, 'add_staff.html', context=context)
    else:
        name = request.POST.get('name')
        age = request.POST.get('age')
        gender = request.POST.get('gender')

        # 信息缺失 无法添加
        if (not name) or (not age) or (not gender):
            context = {'error': 0}
            return render(request, 'add_staff.html', context=context)
        if age.isdigit() and 1 <= int(age) <= 100:
            age = int(age)
        else:
            context = {'error': 1}
            return render(request, 'add_staff.html', context=context)

        staff = Staff(name=name, age=age, gender=gender)
        staff.save()

        return redirect(f'/staff/staffList?page={max_page}')
Пример #5
0
    def post(self, request, *args, **kwargs):
        action = request.query_params.get('action')
        if action == 'register':
            staff_name = request.data.get('staff_name')
            password = request.data.get('password')
            email = request.data.get('email')
            department = request.data.get('department')
            dp = Department.objects.get(pk=department)
            is_leader = request.data.get('is_leader')
            staff = Staff()
            staff.staff_name = staff_name
            staff.password = password
            staff.email = email
            staff.department = dp
            if is_leader:
                staff.is_leader = is_leader
            staff.save()

            data = {
                'status': 200,
                'msg': 'create staff success',
                'staff': {
                    'id': staff.id,
                    'staff_name': staff.staff_name,
                    'email': staff.email,
                    'department': staff.department.dp_name,
                    'is_leader': staff.is_leader,
                    'is_delete': staff.is_delete
                }
            }
            return Response(data)
        elif action == 'login':
            return self.login(request, *args, **kwargs)
        else:
            raise ValidationError(detail='请提供正确的请求动作')
Пример #6
0
def register_staff(request):
    context = {
        'page': 'register_staff',
    }
    if request.session.get('is_login', None):
        username = request.session.get('username')
        store = request.session.get('storeid')
        context['username'] = username
        if request.session.get('identity') != 'shopkeeper':
            context['errmsg'] = '请以店主账号登录'
            shopkeeper = False
            return render(request,
                          'staff/register_staff.html',
                          context=context)
        else:
            shopkeeper = True
    else:
        return login(request)

    if request.method == "POST" and shopkeeper:
        username = request.POST.get('username')
        name = request.POST.get('name')
        password = request.POST.get('password')
        phonenumber = request.POST.get("phonenumber")
        desc = request.POST.get("desc")
        user_model = Staff.objects.filter(username=username).filter(
            store_id=store)

        # 参数验证
        if not all([username, name, password, phonenumber, desc]):
            # 参数不完整
            context['errmsg'] = '数据不完整'
            return render(request,
                          'staff/register_staff.html',
                          context=context)

        if user_model:  #不为NULL
            context['errmsg'] = '用户名已存在'
            return render(request,
                          'staff/register_staff.html',
                          context=context)
        else:
            user = Staff()
            user.username = username
            user.name = name
            user.password = password
            user.phonenumber = phonenumber
            user.desc = desc
            user.store_id = store
            user.save()
            return redirect(reverse('staff:find_staff'))
    return render(request, 'staff/register_staff.html', context=context)
Пример #7
0
def import_staff(request):
  context_vars = dict()
  context_vars['header'] = capfirst(_('import staff from workflowmax'))
  context_vars['comment'] = capfirst(_('this will destroy all your local staff, please confirm your decision.'))
  if request.method == "POST":
    for staff in Staff.objects.all():
      staff.delete()
    wm_staff_list = WorkflowmaxStaff.objects.all()
    for wm_staff in wm_staff_list:
      staff = Staff()
      staff.wm_import(wm_staff)
    return HttpResponseRedirect(reverse('staff-list'))
  
  return direct_to_template(request, template='staff/import.html', extra_context=context_vars)
Пример #8
0
def institute_staff_create(request):
    if request.method == 'POST':
        user_form = StaffCreateForm(request.POST)

        current_institute = Institutions.objects.get(user__username = request.user)
        license_institute = License.objects.get(li_institute = current_institute)

        is_allowed =   int(license_institute.li_current_staff) < int(license_institute.li_max_staff)

        if is_allowed and user_form.is_valid():
            user = user_form.save()
            user.refresh_from_db()  # This will load the Profile created by the Signal
            assign_perm('staff.is_staff', user)
            profile_form = Staff()  # Reload the profile form with the profile instance

            profile_form.institute = request.user.institutions
            profile_form.staffuser = user
            profile_form.full_clean()  # Manually clean the form this time. It is implicitly called by "is_valid()" method

            license_institute.li_current_staff += 1
            license_institute.save()
            profile_form.save()  # Gracefully save the form
            messages.add_message(request, messages.SUCCESS, 'Staff Profile Added Successfully')
        else:
            messages.add_message(request, messages.INFO, str(user_form.errors.as_ul()))
    else:
        user_form = StaffCreateForm()
        # profile_form = StaffProfileForm()
    return render(request, 'institutions/staff_create.html', {
        'user_form': user_form

    })
Пример #9
0
def loadStaff(staff, employee):
#    cargo = createPosition(staff['cargo'])
#    unit = createWorkUnit(staff['unidad'])
    type_document = TypeDocument.objects.get(key='ci')
    try:
        s = Staff(photo=staff['avatar'], first_name=staff['first_name'], last_name=staff['last_name'],
            birth_date=staff['birth_date'], type_document=type_document, val_document=staff['ci'],
            locale_issue=staff['locale_issue'], date_joined=datetime.datetime.now(), is_active=True)
        s.save()
    except IntegrityError:
        print 'ERROR GARRAFAL EN USUARIO CON CI: ' + str(staff['ci']) + ' E ITEM: ' + str(employee['item'])

    try:
        e = Employee(staff=s, item=employee['item'])
        e.save()
    except IntegrityError:
        print 'ERROR AL CARGAR EL ITEM: ' + employee['item']
Пример #10
0
def create_staff(staff_info: dict):
    """

    :param staff_info: {
        "shop_id": 1,
        "user_id": 1,
        "roles": 255,
        "permissions": 63,
        "position": "",
        "entry_date": "2019-10-14",
        "remark": ""
    }
    :return:
    """
    staff = Staff(**staff_info)
    staff.save()
    return staff
Пример #11
0
 def test_link(self):
     staff = Staff(
         link=
         'https://stackoverflow.com/questions/56820/round-in-python-doesnt-seem-to-be-rounding-properly'
     )
     self.assertEqual(
         staff.link,
         'https://stackoverflow.com/questions/56820/round-in-python-doesnt-seem-to-be-rounding-properly'
     )
Пример #12
0
def create_super_admin_staff(shop: Shop, user: User):
    """
    创建一个超级管理员
    :param shop:
    :param super_amdin:
    :return:
    """
    # 计算所有权限,超级管理员拥有所有权限
    permissions = 0
    for k, v in vars(StaffPermission).items():
        if not k.startswith("__"):
            permissions |= v

    staff = Staff(shop=shop,
                  user=user,
                  roles=StaffRole.SHOP_SUPER_ADMIN,
                  permissions=permissions)
    staff.save()
    return staff
Пример #13
0
def add_staff(request, excel_file):
    COLUMN_LIMIT = 4
    sheet_name = "staff"
    staff = _get_data_from_sheet(request, excel_file, COLUMN_LIMIT, sheet_name)
    if not staff: return False

    # DATA HEAD FROM SHEET:
    # No	staff_id	name	sms_number

    # Add teacher to the database
    for row in staff:
        if (len(row) > 0):
            if (row[0] != "No"):
                # if there are empty colums
                if (len(row) < COLUMN_LIMIT):
                    i = len(row)
                    while (i < COLUMN_LIMIT):
                        # fill with ""
                        row.append("")
                        i += 1
                try:
                    # Check for the exitence of the staff id
                    t = Staff.objects.filter(staff_id=row[1])
                    if (t.count() == 0):
                        new_row = Staff(
                            staff_id=row[1],
                            name=row[2],
                            sms_number=row[3],
                        )
                        new_row.save()
                except ValueError as err:
                    request.session["error_message"] = str(err)
                    return False
                except IntegrityError as err:
                    request.session["error_message"] = str(err)
                    return False
                except FieldError as err:
                    request.session["error_message"] = str(err)
                    return False
                except Exception as err:
                    request.session["error_message"] = str(err)
                    return False
    return True
Пример #14
0
def new_staff(req):
	from staff.models import Staff

	if req.method == 'POST':
		posted = req.POST

		staff = Staff()

		staff.groupschedule = req.user.groupschedule
		staff.name = posted['name']

		staff.save()

		return redirect('/')

	temp = 'staff/new_staff.html'
	contxt = {}

	return render(req,temp,contxt)
Пример #15
0
    def form_valid(self, form):
        user_obj = form.save()
        assign_perm('institutions.is_institute', user_obj)
        user_obj.save()
        institution_obj = Institutions()

        institution_obj.user = user_obj
        institution_obj.institute_name = self.request.POST['institute_name']
        institution_obj.institute_address = self.request.POST[
            'institute_address']
        institution_obj.institute_city = self.request.POST['institute_city']
        institution_obj.institute_state = self.request.POST['institute_state']
        institution_obj.institute_country = self.request.POST[
            'institute_country']
        institution_obj.institute_contact_mobile = self.request.POST[
            'institute_contact_mobile']
        institution_obj.institute_contact_landline = self.request.POST[
            'institute_contact_landline']

        license_obj = License()
        institution_obj.save()

        license_obj.li_institute = institution_obj
        license_obj.li_key = ''.join(
            random.choices(string.ascii_uppercase + string.digits, k=16))
        license_obj.li_expiration_date = datetime.now() + timedelta(days=10 *
                                                                    365)
        license_obj.li_max_staff = 50
        license_obj.li_max_students = 500
        license_obj.li_max_assesments = 1000
        license_obj.li_current_status = 'acti'

        license_obj.save()

        #Register Institute as first user:

        user_obj.refresh_from_db(
        )  # This will load the Profile created by the Signal
        assign_perm('staff.is_staff', user_obj)
        profile_form = Staff(
        )  # Reload the profile form with the profile instance
        profile_form.institute = user_obj.institutions
        profile_form.staffuser = user_obj
        profile_form.full_clean(
        )  # Manually clean the form this time. It is implicitly called by "is_valid()" method
        license_obj.li_current_staff += 1
        license_obj.save()
        profile_form.save()  # Gracefully save the form

        messages.add_message(self.request, messages.SUCCESS,
                             'Your Account Registered Successfully')
        return HttpResponseRedirect(self.get_success_url())
Пример #16
0
    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            staff = Staff(
                user=User.objects.get(pk=request.POST["user_id"]),
                academic_degree=Academic_Degree.objects.get(
                    pk=request.POST["academic_degree_id"]),
                academic_rank=Academic_Rank.objects.get(
                    pk=request.POST["academic_rank_id"]),
                position=Positions.objects.get(pk=request.POST["position_id"]))
            staff.save()

            user = User.objects.get(pk=request.POST["user_id"])
            group = Group.objects.get(name='Staff')
            group.user_set.add(user)

            response_serializer = self.serializer_class(staff)
            return Response(response_serializer.data)
        else:
            return Response({"msg": serializer.errors},
                            status=status.HTTP_400_BAD_REQUEST)
Пример #17
0
 def post(self):
     data = request.json
     parser.parse_args(strict=True)
     for staff in json_data:
         if staff.get("passport_id") == data["passport_id"]:
             return "Staff already works"
     else:
         staff_data.append(Staff(
             data["name"],
             data["passport_id"],
             data["position"],
             data["salary"],
         ).to_dict())
         write_data(staff_data, json_file)
         return "Staff hired"
Пример #18
0
 def test_score(self):
     staff = Staff()
     Comment1 = Comment(score=3, staff=staff)
     Comment2 = Comment(score=4, staff=staff)
     staff.update_score()
     self.assertEqual(staff.score, 3.5)
Пример #19
0
 def test_name(self):
     staff = Staff(firstname='l', secondname='b')
     self.assertEqual(staff.firstname, 'l')
     self.assertEqual(staff.secondname, 'b')
     self.assertEqual(staff.name(), 'l b')
     self.assertEqual(str(staff), 'l b')
Пример #20
0
def staff_registration(request, *args, **kwargs):
    if request.method == "POST":
        form = StaffForm(request.POST or None)
        if form.is_valid():
            details = form.cleaned_data
            new_username = details['username']
            new_fName = details['firstName']
            new_mName = details['middleName']
            new_lName = details['lastName']
            new_passwd = details['passwd']
            new_email = details['email']
            new_dob = details['date']
            new_gender = details['gender']
            new_mobile = details['mobile']
            new_branch = details['branch']
            new_designation = details['designation']
            new_isAdmin = False
            new_isPending = True
            new_account_id = id_generator()

            #sets category of user
            new_category = ''
            if new_designation in ['Professor', 'Assistant Professor']:
                new_category = 'Faculty'
            elif new_designation == 'Head of Department':
                new_category = 'Head of Department'
            elif new_designation in ['Lab Instructor', 'Lab Assistant']:
                new_category = 'Staff'

            # find the number of users in staff
            staff_count = int(Staff.objects.count())

            # if there are no staff members, the first created user will be admin
            if staff_count < 1:
                new_isAdmin = True
                new_category = 'Admin'
                new_isPending = False

            try:
                validate_password(new_passwd, form)
            except ValidationError as e:
                form.add_error('passwd', e)
                return render(request, "common/staffregistration.html",
                              {'form': form})

            # try:
            #     user_credentials = [new_username, new_fName, new_lName, new_mName, new_mobile]
            #     for item in user_credentials:
            #         if item.lower() in new_passwd.lower():
            #             raise ValidationError('Password too similar to credentials.')
            # except ValidationError as e:
            #     form.add_error('passwd', e)
            #     return render(request, "common/staffregistration.html", {'form': form})

            newStaff = Staff(firstName=str(new_fName.capitalize()),
                             middleName=str(new_mName.capitalize()),
                             lastName=str(new_lName.capitalize()),
                             username=str(new_username),
                             passwd=str(new_passwd),
                             account_id=str(new_account_id),
                             date=str(new_dob),
                             mobile=str(new_mobile),
                             branch=str(new_branch),
                             email=str(new_email.lower()),
                             gender=str(new_gender),
                             designation=str(new_designation),
                             isAdmin=new_isAdmin,
                             isPending=new_isPending,
                             category=str(new_category))

            # newUser = AppUser(
            #             firstName=str(new_fName.capitalize()),
            #             lastName=str(new_lName.capitalize()),
            #             username=str(new_username),
            #             passwd=str(new_passwd),
            #             email=str(new_email.lower()),
            #             category=str(new_category),
            #             isAdmin=new_isAdmin,
            #             isPending=new_isPending
            # )

            newUser = User.objects.create_user(
                username=str(new_username),
                password=str(new_passwd),
                first_name=str(new_fName.capitalize()),
                last_name=str(new_lName.capitalize()),
                email=str(new_email.lower()),
            )

            # newDjangoUser.save()
            newStaff.save()
            newUser.save()

            if new_isPending:
                return redirect("../pending-account")
            else:
                return redirect("../account-created")
    else:
        form = StaffForm(request.POST or None)
        for field in form.errors:
            form[field].field.widget.attrs['class'] += 'error'

    return render(request, "common/staffregistration.html", {'form': form})
Пример #21
0
def add(request):
    if request.POST:
        area_id = int(request.POST.get('area_id'))
        realname = request.POST.get('realname')
        accountname = request.POST.get('accountname')
        is_available_list = request.POST.getlist('is_available')
        phone = request.POST.get('phone')
        weight = int(request.POST.get('weight'))
        email = request.POST.get('email')
        
        # 不允许重复添加
        staff_list = Staff.objects.filter(accountname=accountname, is_deleted=0)
        if staff_list:
            return HttpResponse(simplejson.dumps({"statusCode":400, "message":u'此IT员工已存在,不允许重复添加!'}), mimetype='application/json')
            
        staff = Staff()
        # 一类特殊情况,IT工程师删除以后又被重新加入
        staff_list = Staff.objects.filter(accountname=accountname, is_deleted=1)
        if staff_list:
            staff = staff_list[0]
        
        staff.area_id = area_id
        staff.realname = realname
        staff.accountname = accountname
        staff.phone = phone
        staff.weight = weight
        staff.is_deleted = 0
        staff.email = email
        
        if is_available_list:
            staff.is_available = 1
        else:
            staff.is_available = 0
            
        staff.save()
        
        return HttpResponse(simplejson.dumps({"statusCode":200,"url": "/staff/index", "message":u'添加成功'}), mimetype='application/json')
    else:
        # 区域
        area_list = Area.objects.all()
        return render_to_response('staff/add.html',{'area_list':area_list,'weight_dict':weight_dict}) 
Пример #22
0
    def create_or_update(**kwargs):
        # Creates or updates a Social instance. Also creates User if email does not exist
        user = kwargs.pop('user')
        request = kwargs.pop('request', None)
        first_name = kwargs.pop('first_name')
        last_name = kwargs.pop('last_name')
        social_id = kwargs.pop('social_id')
        name = f'{first_name} {last_name}'
        user_created = False
        social_created = False

        temp_email = False
        email = kwargs.pop('email')
        if not email or email is None:
            email = Social.unique_email()
            temp_email = True

        social = Social.objects.filter(social_id=social_id)
        if social.exists():
            user = social.first().profile.user
            # If the social email is not temporary and the user is not verified
            if not temp_email and not user.profile.is_verified:
                # update the user email and verify them
                user.email = email
                user.save()
                profile = user.profile
                profile.verified = True
                profile.save()

        else:
            try:
                if user is None:
                    user = User.objects.get(email=email)
            except User.DoesNotExist:

                # Only create users if registration is open
                if not Settings.registration_is_open():
                    if request is not None:
                        messages.add_message(request, messages.INFO,
                                             'Período de registro fechado!')
                    return None, user_created, social_created, request

                user = User(first_name=first_name,
                            last_name=last_name,
                            username=Social.unique_username(name),
                            email=email)
                user.save()
                user_created = True
                if not temp_email:
                    profile = user.profile
                    profile.verified = True
                    profile.save()

                # New user created
                if Settings.default_hacker():
                    from hacker.models import Hacker
                    Hacker(profile=user.profile).save()
                if Settings.default_staff():
                    from staff.models import Staff
                    Staff(profile=user.profile).save()

        profile = user.profile
        try:
            social, social_created = Social.objects.update_or_create(
                profile=profile,
                social_id=social_id,
                provider=kwargs['provider'],
                defaults=kwargs)
        except IntegrityError:
            messages.add_message(
                request, messages.ERROR,
                f"Parece que alguém já tentou se inscrever com esse perfil do {kwargs['provider']}"
            )
            return None, user_created, social_created, request
        return social, user_created, social_created, request
Пример #23
0
 def test_staff_goot(self):
     staff = Staff()
     staff1 = Staff()
     comment = Comment(staff=staff)
     self.assertEqual(comment.staff, staff)
     self.assertNotEqual(comment.staff, staff1)