def add_to_mentor_service(track_info, acc_id): """get the user id from ajax request and add user as mentor user if the user mentor status is false Arguments: track_info {DICT} -- dictionary contains of user id and ip to update status_of_user acc_id {INT} -- the id of user Returns: DICT -- returns back the user id """ data = { 'add_id': acc_id, } person = get_user_service(id=acc_id) # person = get_object_or_404(models.User, id=acc_id) if person.add_to_mentors == False: person.add_to_mentors = True person.save() try: status = f"{person.first_name} {person.last_name} را به صفحه منتور ها اضافه کرد" status_of_user(track_info, status, 'add-user-mentors') except: pass else: person.add_to_mentors = False person.save() status = f"{person.first_name} {person.last_name} را از صفحه منتور ها حذف کرد" try: status = f"{person.first_name} {person.last_name} را به صفحه منتور ها اضافه کرد" status_of_user(track_info, status, 'delete-user-mentors') except: pass return data
def register_user_condition_service(session, phone_form, form): """checks if user can register - if the number assigned to a user that has role cannot create startup - user only can request for verification code every 2 minutes - Arguments: session {SESSION} -- to store generated code/ registered time phone_form {POST Method} -- get the number that user has entered form {FORM} -- to validate number that has been entered Returns: STRING -- if try to spam returns expired if is karmand return karmand return error if not valid """ try: the_time = parser.parse(session['register_timer']) except: the_time = timezone.now() if the_time <= timezone.now(): try: del session['register_timer'] except: pass try: del session['sms_validate'] except: pass if 'register_timer' in session and the_time >= timezone.now(): return 'expired' else: register_t = timezone.now() + timezone.timedelta(minutes=2) try: th_user = get_user_service(phone=phone_form.get('phone')) if th_user.user_type == 'karmand': return 'karmand' session['phone'] = phone_form.get('phone') sms_validate = str(randint(int('1' * 6), int('9' * 6))) sms.sms(sms_validate, session['phone'], 'register') session['sms_validate'] = sms_validate session['register_timer'] = str(register_t) return 'success' except: if form.is_valid(): session['phone'] = form.cleaned_data['phone'] sms_validate = str(randint(int('1' * 6), int('9' * 6))) sms.sms(sms_validate, session['phone'], 'register') session['sms_validate'] = sms_validate session['register_timer'] = str(register_t) return 'success' else: print(str(form.errors)) return 'error'
def change_username_service(form, track_info, user): """if the username is not taken it will save the mentioned username for requested user Arguments: form {GET method} -- get the mentioned username from requested user track_info {DICT} -- dictionary contains of user id and ip to update status_of_user user {OBJECT} -- requested user Returns: BOOLEAN -- returns True if the username successfully changed eles reutrns False """ try: get_user_service(username=form['user_name']) # models.User.objects.get(username=form['user_name']) return False except: user.username = form['user_name'] user.save() status = f"نام کاربری خود را تغییر داد" status_of_user(track_info, status, 'chenge-username') return True
def edit_offerto_leader_get_create(form, the_event, track_info): """update or create the LeaderModel and CreateEvent records Arguments: form {POST Method} -- to get new entered values the_event {OBJECT} -- TheEvent objecte that got by id track_info {DICT} -- dictionary contains of user id and ip to update status_of_user Returns: BOOLEAN -- returns True if everything goes well """ if form.getlist('leader[]'): create_event_id = (c_e for c_e in form.getlist('c_e_id')) for person_id in form.getlist('leader[]'): if not re.search(r'\d', person_id, re.I): continue leader_id = (c_e for c_e in form.getlist(f'lead_pk-{person_id}')) user_leader = get_user_service(pk=int(person_id)) try: event = get_create_event_service( pk=int(create_event_id.__next__())) event.content_object = user_leader event.save() except: event = models.CreateEvent.objects.create_by_model( instance=user_leader) finally: the_event.c_event.add(event) the_event.save() for st in form.getlist(f'startup-{person_id}'): if not re.search(r'\d', st, re.I): continue start = get_startup_service(pk=int(st)) try: leader = models.LeaderModel.objects.get( pk=int(leader_id.__next__())) leader.startup = start leader.save() except: models.LeaderModel.objects.create( event=event, startup=start, ) status = f"ملاقات {the_event.pk} با راهبر {user_leader.first_name} {user_leader.last_name} به استارتاپ {get_startup_service(pk=int(st)).title} تغییر کرد" status_of_user(track_info, status, 'edit-offerto-leader') create_notification(user_leader, 'edit-offerto-leader', start) create_notification(start.owner, 'edit-offerto-leader', user_leader) return True
def support_service(user, file_value, form, session, track_info, current_site, protocol): """get the phone number from session if exists else if user is authenticated will get phone from database else we don't pass any phone assgin user informaion to the SupportModel Arguments: user {OBJECT} -- requested user form {POST Method} -- get screen-shot(base-64) session {SESSION} -- to get phone number from session track_info {DICT} -- dictionary contains of user id and ip to update status_of_user Returns: BOOLEAN/STRING -- returns True if form is valid else returns forms errors """ if user.is_authenticated: the_phone = user.phone the_user = user elif session.get('phone'): the_phone = session.get('phone') the_user = get_user_service(phone=the_phone) else: the_phone = None the_user = None try: support_form = SupportForm(form) if support_form.is_valid(): support_form.instance.user = the_user support_form.instance.phone = the_phone support_form.instance.image = file_value.get('screenshot') support_form.save() the_message = support_form.instance.content try: the_messages2 = f'کاربر با نام {support_form.instance.user.first_name} {support_form.instance.user.last_name} و شماره تماس {support_form.instance.user.phone} :' except: the_messages2 = f'کاربر با شماره تماس {the_phone} :' sub = 'گزارش پشتیبانی در روند ثبت نام' template = 'email/startup-email.html' to = '*****@*****.**' to2 = '*****@*****.**' image_url = ''.join([str(protocol), '://', str(current_site), str(support_form.instance.image.url)]) Thread(target=send_email, args=(track_info,), kwargs={ "to": [to, to2], 'template': template, 'sub': sub, 'the_messages': the_message, 'the_messages2': the_messages2, 'image': image_url }).start() return True else: logger.error(str(support_form.errors)) return support_form.errors except Exception as e: logger.error(str(e))
def edit_user_get_service(track_info, pk): """get Karmand form for selected user Arguments: track_info {DICT} -- dictionary contains of user id and ip to update status_of_user Returns: TUPLE -- returns an instance of Karmand form for selected user """ user = get_user_service(pk=pk) user_form = KarmandForm(instance=user) roles = models.Role.objects.all() categories = Categories.objects.all() status = f"مشخصات {user_form.instance.first_name} {user_form.instance.last_name} را تغییر داد" status_of_user(track_info, status, 'import-edit-user') return user, user_form, roles, categories
def delete_user_service(user_id, track_info): """get user_id from ajax and delete the user Arguments: user_id {STRING} -- get the str of user id and do a queryset in User model track_info {DICT} -- dictionary contains of user id and ip to update status_of_user Returns: DICT -- returns dictionary that contains user_id """ data = { 'delete_id': user_id } the_user = get_user_service(id=int(user_id)) # the_user = models.User.objects.get(id=int(user_id)) the_user.delete() status = f"کاربر {the_user.first_name} {the_user.first_name} {the_user.phone} را حذف کرد" status_of_user(track_info, status, 'delete-user') return data
def __call__(self, request): if '/admin/' not in request.path and not 'iam_ghosting' in request.session: match = resolve(str(request.path)) model = None id = None instance = None if '_id' in str(match.kwargs): for key, val in match.kwargs.items(): model = str(str(key).split('_')[0]) id = val model_qs = ContentType.objects.get(model=model) Model = model_qs.model_class() instance = Model.objects.get(id=id) # ----------------------------------------------------- protocol = urlsplit(request.build_absolute_uri(None)).scheme current_site = get_current_site(request) current_path = request.path url = ''.join( [str(protocol), '://', str(current_site), str(current_path)]) # ----------------------------------------------------- if request.user.is_authenticated: UserTracker.objects.create_by_model( user=request.user, url=url, instance=instance, user_agent=str(get_user_agent(request)), user_ip=get_client_ip(request)) else: try: th_user = get_user_service(phone=request.session['phone']) except: th_user = None UserTracker.objects.create_by_model( user=th_user, url=url, instance=instance, user_agent=str(get_user_agent(request)), user_ip=get_client_ip(request)) response = self.get_response(request) return response
def send_message_chat_instances_service(pk, track_info, context): """get message by primary key if it's exists and if the messages is not readed is_readed of the message objects become True Arguments: pk {PRIMARY KEY/INT} -- a unique field to select the message we want track_info {DICT} -- dictionary contains of user id and ip to update status_of_user Returns: OBJECT -- returns receiver object for the form """ receiver = get_user_service(pk=pk) send_m_receiver = models.SendMessage.objects.filter(receiver=receiver) all_messages = models.AllMessages.objects.prefetch_related('send_message').filter( send_message__in=send_m_receiver) message_form = SendMessageForm() status = f"پیام {receiver.first_name} {receiver.last_name} را خوانده" status_of_user(track_info, status, 'seeing-message') context.update({'form': message_form, 'receiver': receiver, 'all_messages': all_messages}) return receiver
def verify_user_service(session, form): """check the verification code if time is not expire / if user exists will login or create user then login Arguments: session {SESSION} -- to check verification code and time form {POST method} -- with one field to get code Returns: STRING -- returns loggedin and user if goes successfully/expire if time remain to send again / false if code is wrong """ the_time = parser.parse(session['register_timer']) if the_time >= timezone.now(): if str(form['verify']) == str(session['sms_validate']): try: user = get_user_service(phone=session['phone']) except: username_random, password = create_passwd() user = models.User.objects.create_startup_user( phone=session['phone'], password=password, username=username_random) UserProfile.objects.create(user=user) session['the_startup_user_password'] = str(password) return ('loggedin', user) else: return 'false' else: try: del session['sms_validate'] except: pass if not 'sms_validate' in session: return 'expired'
def offerto_leader_service(owner, form, track_info): """create an event with the type of leader - get the list of leaders ids and assgin CreateEvent by their model and id (GenericForeignKey) and then assgin them to TheEvent object - get the list of startups ids and create LeaderModel object with user model assgin to it(the choosen leader) Arguments: owner {OBJECT} -- requested user (the maker of this event) form {POST Method} -- to get ids from the maker Returns: BOOLEAN -- returns True if everything goes well """ the_event = models.TheEvent.objects.create(owner=owner, th_type='leader') if form.getlist('leader[]'): for person_id in form.getlist('leader[]'): if not re.search(r'\d', person_id, re.I): continue user_leader = get_user_service(pk=int(person_id)) event = models.CreateEvent.objects.create_by_model( instance=user_leader, ) the_event.c_event.add(event) the_event.save() for st in form.getlist(f'startup-{person_id}'): if not re.search(r'\d', st, re.I): continue startup = get_startup_service(pk=int(st)) models.LeaderModel.objects.create( event=event, startup=startup, ) status = f"استارتاپ {startup.title} به راهبر {user_leader} پیشنهاد داده شد" status_of_user(track_info, status, 'assigne-startup-to-leader') create_notification(startup.owner, 'assigne-startup-to-leader', user_leader) create_notification(user_leader, 'assigne-startup-to-leader', startup) return True
def login_verify_phone_service(the_code, expire_time, session, track_info): now = timezone.now() if expire_time >= now: if the_code == session.get('the_code'): # user = models.User.objects.get( # phone=session.get('phone')) user = get_user_service(phone=session.get('phone')) del session['timer'] del session['the_code'] status = f"کاربر {user.first_name} {user.last_name} با شماره تلفن وارد شد" status_of_user(track_info, status, 'phone-login-dashboard') return (True, user,) else: return (False,) else: try: del session['the_code'] except: pass try: del session['timer'] except: pass return ('expired',)
def assign_accelerator_or_leader(user, form, form_start): """allow user to choose a leader o accelerator or create custom leader(mentor) Arguments: user {OBJECT} -- requested user form {POST Method} -- to get values from user form_start {FORM} -- to assign selected options (leader, accelerator) to the current startup Returns: BOOLEAN -- returns False if user use his/her phone number to create a mentor/ True if everythig goes well """ if user.phone in form.getlist('mentor_number'): return False else: try: # user create a custome leader and it will add to startup rahbar user_mentor = get_user_service( first_name=form['mentor_fname'], last_name=form['mentor_lname'], phone=form['mentor_number'], ) form_start.instance.rahbar = user_mentor form_start.save() except: if form.getlist('mentor_fname') and form.getlist( 'mentor_lname') and form.getlist('mentor_number'): username_random, password = create_passwd() try: user_mentor = get_user_service(phone=form['mentor_number']) form_start.instance.rahbar = user_mentor form_start.save() except: user_mentor = models.User.objects.create( first_name=form['mentor_fname'], last_name=form['mentor_lname'], phone=form['mentor_number'], is_active=False, username=username_random, mentor_user=True, ) user_mentor.set_password(password) form_start.instance.rahbar = user_mentor role = get_role_service(name='leader') user_mentor.role.add(role) form_start.save() if form_start.instance.shetab_dahande: form_start.instance.shetab_dahande = None form_start.instance.shetab_shude = False form_start.save() if form.getlist( 'companion1' ): # get shetabdahande and add namayande as rahbar_asli for startup for person_id in form.getlist('companion1'): if not re.search(r'\d', person_id, re.I): continue shetab_dahande = ShetabDahande.objects.get(pk=int(person_id)) form_start.instance.shetab_dahande = shetab_dahande form_start.instance.rahbar_asli = shetab_dahande.name_namayande form_start.instance.rahbar = None form_start.instance.shetab_shude = True form_start.save() if form.getlist( 'mentor_name' ): # user choose a leader and it will add to startup rahbar for person_id in form.getlist('mentor_name'): if not person_id: continue user_rahbar = get_user_service(pk=int(person_id)) form_start.instance.rahbar = user_rahbar form_start.save() if form_start.instance.shetab_dahande: form_start.instance.shetab_dahande = None form_start.instance.shetab_shude = False form_start.save() return True
def edit_meeting_get_create_service(form, the_event, track_info): """get the event and coach id to update if there is instances else create new Arguments: form {POST Method} -- to get entered values the_event {OBJECT} -- TheEvent object that got by id track_info {DICT} -- dictionary contains of user id and ip to update status_of_user Returns: BOOLEAN -- returns True if everything goes well """ if form.getlist('coach[]'): create_event_id = (c_e for c_e in form.getlist('c_e_id')) for person_id in form.getlist('coach[]'): if not person_id: continue coach_id = (c_e for c_e in form.getlist(f'coach_pk-{person_id}')) startuptime_id = (sut for sut in form.getlist('startuptime')) from_time = (ft for ft in form.getlist('meeting_time_s')) to_time = (tt for tt in form.getlist('meeting_time_e')) from_date = form.get('date_meeting_s') to_date = form.get('date_meeting_e') user_coach = get_user_service(pk=int(person_id)) try: event = get_create_event_service( pk=int(create_event_id.__next__())) event.content_object = user_coach event.save() except: event = models.CreateEvent.objects.create_by_model( instance=user_coach) finally: the_event.c_event.add(event) the_event.save() for th in form.getlist(f'meeting-{person_id}'): if not re.search(r'\d', th, re.I): continue try: times = models.StartupTime.objects.get( pk=startuptime_id.__next__()) times.the_date = datetime.fromtimestamp( float(from_date) / 1000) times.to_date = datetime.fromtimestamp( float(to_date) / 1000) times.from_time = datetime.fromtimestamp( float(from_time.__next__()) / 1000) times.to_time = datetime.fromtimestamp( float(to_time.__next__()) / 1000) times.save() except: times = models.StartupTime.objects.create( the_event=the_event, the_date=datetime.fromtimestamp( float(from_date) / 1000), to_date=datetime.fromtimestamp(float(to_date) / 1000), from_time=datetime.fromtimestamp( float(from_time.__next__()) / 1000), to_time=datetime.fromtimestamp( float(to_time.__next__()) / 1000), ) finally: try: start_events = models.CoachEvent.objects.get( pk=int(coach_id.__next__())) start_events.th_time = th start_events.schedule = times start_events.save() except: start_events = models.CoachEvent.objects.create( event=event, schedule=times, th_time=int(th)) status = f"منتورینگ {the_event.id} با مربی {user_coach.first_name} {user_coach.last_name} به وضعیت {'آزاد' if start_events.th_time == 1 else 'پر'} و تاریخ {JalaliDate.to_jalali(times.the_date.year, times.the_date.month, times.the_date.day)} تا {JalaliDate.to_jalali(times.to_date.year, times.to_date.month, times.to_date.day)} و زمان {times.from_time} تا {times.to_time} تغییر کرد" status_of_user(track_info, status, 'edit-meetingto-coach') create_notification(user_coach, 'edit-meetingto-coach', start_events) return True
def list_user_service(search, track_info): """searchable list of users Arguments: search {DICT} -- a dictionary of input boxes name and page number track_info {DICT} -- dictionary contains of user id and ip to update status_of_user Returns: DICT -- returns dictionary of contexts """ try: status = "لیست کاربران را دید" status_of_user(track_info, status, 'import-list-user') except: pass th_roles = models.Role.objects.all() th_manager = get_user_service(user_type='manager') # th_manager = models.User.objects.get(user_type='manager') Users = models.User.objects.filter( is_admin=False).exclude(pk=th_manager.pk).order_by('-pk') the_users = Users if search.get('role_input'): try: db_role = get_role_service(name=search.get('role_input')) except models.Role.DoesNotExist: db_role = None if search.get('role_input') == 'startup': Users = models.User.objects.filter(user_type='startup') the_users = Users try: status = f"کاربر {Users.first().first_name} {Users.first().last_name} را جستجو کرد" status_of_user(track_info, status, 'search-list-user') except: pass else: Users = Users.filter(role=db_role) the_users = Users try: status = f"کاربر {Users.first().first_name} {Users.first().last_name} را جستجو کرد" status_of_user(track_info, status, 'search-list-user') except: pass if search.get('fname'): Users = Users.filter(first_name__icontains=search.get('fname')) the_users = Users try: status = f"کاربر {Users.first().first_name} {Users.first().last_name} را جستجو کرد" status_of_user(track_info, status, 'search-list-user') except: pass if search.get('lname'): Users = Users.filter(last_name__icontains=search.get('lname')) the_users = Users try: status = f"کاربر {Users.first().first_name} {Users.first().last_name} را جستجو کرد" status_of_user(track_info, status, 'search-list-user') except: pass if search.get('email'): Users = Users.filter(email__icontains=search.get('email')) the_users = Users try: status = f"کاربر {Users.first().first_name} {Users.first().last_name} را جستجو کرد" status_of_user(track_info, status, 'search-list-user') except: pass if search.get('the_phone'): Users = Users.filter(phone__icontains=search.get('the_phone')) the_users = Users try: status = f"کاربر {Users.first().first_name} {Users.first().last_name} را جستجو کرد" status_of_user(track_info, status, 'search-list-user') except: pass paginator = Paginator(Users, 30) page = search.get('offset') try: Users = paginator.page(page) except PageNotAnInteger: Users = paginator.page(1) except EmptyPage: Users = paginator.page(paginator.num_pages) return { 'Users': Users, 'fname': search.get('fname'), 'lname': search.get('lname'), 'email': search.get('email'), 'role_input': search.get('role_input'), 'the_users': the_users, 'th_roles': th_roles, 'the_phone': search.get('the_phone'), }