Esempio n. 1
0
def stats(request, visit_id):
	v = get_object_or_404(SchoolVisit, pk=visit_id)
	if v.school.chapter != request.user.chapter:
		raise Http404
	if not request.user.is_staff:
		raise Http404
	if request.method == 'POST':
		form = SchoolVisitStatsForm(request.POST, visit = v)
		if form.is_valid():
			data = form.cleaned_data
			stats = SchoolVisitStats()
			stats.visit = v
			stats.visit_type = data['visit_type']
			stats.primary_girls_first = data['primary_girls_first']
			stats.primary_girls_repeat = data['primary_girls_repeat']
			stats.primary_boys_first = data['primary_boys_first']
			stats.primary_boys_repeat = data['primary_boys_repeat']
			stats.high_girls_first = data['high_girls_first']
			stats.high_girls_repeat = data['high_girls_repeat']
			stats.high_boys_first = data['high_boys_first']
			stats.high_boys_repeat = data['high_boys_repeat']
			stats.other_girls_first = data['other_girls_first']
			stats.other_girls_repeat = data['other_girls_repeat']
			stats.other_boys_first = data['other_boys_first']
			stats.other_boys_repeat = data['other_boys_repeat']
			stats.notes = data['notes']
			stats.save()
			for attendee in data['attended']:
				list = EventAttendee.objects.filter(event__id=v.id).values_list('user_id', flat=True)
				if attendee.id not in list:
					newinvite = EventAttendee()
					newinvite.event = v
					newinvite.user = attendee
					newinvite.actual_status = 1
					newinvite.rsvp_status = 0
					newinvite.save()
			
			for person in EventAttendee.objects.filter(event__id=v.id):
				if person.user in data['attended']:
					person.actual_status = 1
					person.save()
				else:
					person.actual_status = 2
					person.save()
						
			v.status = 1
			v.save()
			request.user.message_set.create(message=unicode(_("Stats saved successfully, visit closed.")))
			return HttpResponseRedirect('/teaching/')
	else:
		form = SchoolVisitStatsForm(None, visit = v)
	return render_to_response('visit_stats.html', {'form':form, 'visit_id':visit_id}, context_instance=RequestContext(request))
Esempio n. 2
0
def dorsvp(request, event_id, user_id, rsvp_status):
	event = get_object_or_404(Event, pk=event_id)
	user = get_object_or_404(User, pk=user_id)
	if event.status != 0:
		raise Http404
	if request.user.is_staff:
		EventAttendee.objects.filter(user=user, event=event).delete()
		ea = EventAttendee(user=user, event=event, rsvp_status=rsvp_status)
		ea.save()
	elif event.chapter == user.chapter and user == request.user:
		if event.allow_rsvp == 0:  # Allow anyone to RSVP
			EventAttendee.objects.filter(user=user, event=event).delete()
			ea = EventAttendee(user=user, event=event, rsvp_status=rsvp_status)
			ea.save()
		elif event.allow_rsvp == 1:  # Only allow invitees to RSVP
			if EventAttendee.objects.filter(user=user, event=event).count() > 0:
				EventAttendee.objects.filter(user=user, event=event).delete()
				ea = EventAttendee(user=user, event=event, rsvp_status=rsvp_status)
				ea.save()
	return HttpResponseRedirect('/teaching/' + str(event.pk) + '/')
Esempio n. 3
0
def instantvisit(request):
    chapter = request.user.chapter

    # Check if the user has exec rights
    if not request.user.is_staff and not request.user.is_superuser:
        raise Http404

    if not request.session.get('hoursPerPersonStage', False):
        request.session['hoursPerPersonStage'] = 1

    # Sometimes request.session['hoursPerPersonStage'] may equal 1 from editing stats from a closed workshop
    if request.method == 'POST' and request.session['hoursPerPersonStage'] != 2:
        if request.user.is_superuser:
            formpart1 = SchoolVisitFormInstant(request.POST, chapter=None)
            formpart2 = SchoolVisitStatsFormInstant(request.POST, chapter=None)
        else:
            formpart1 = SchoolVisitFormInstant(request.POST, chapter=chapter)
            formpart2 = SchoolVisitStatsFormInstant(request.POST,
                                                    chapter=chapter)

        form_school = SchoolFormPartOne(request.POST,
                                        chapter=chapter,
                                        school_id=0)

        # Validate form
        if formpart1.is_valid() and formpart2.is_valid():
            data = formpart1.cleaned_data
            data_stats = formpart2.cleaned_data

            selected_school = data['school']
            school_visit = SchoolVisit()
            new_school = School()

            school_visit.created_method = 1

            # Check if new school was selected, New school equals to 0
            if selected_school == u'0':
                if form_school.is_valid():
                    new_school_form = form_school.cleaned_data

                    # Check if school exists
                    exist = School.objects.filter(
                        name__iexact=new_school_form['name'], chapter=chapter)
                    if exist:
                        messages.error(
                            request,
                            "School seems to already exist, please recheck list."
                        )
                        return render_to_response(
                            'instant_workshop.html', {
                                'form1': formpart1,
                                'form2': formpart2,
                                'schoolform': form_school
                            },
                            context_instance=RequestContext(request))

                    # Create new school after checking it doesn't exist
                    new_school.name = new_school_form['name']
                    new_school.chapter = chapter
                    new_school.address_street = new_school_form[
                        'address_street']
                    new_school.address_city = new_school_form['address_city']
                    new_school.address_state = new_school_form['address_state']
                    new_school.address_country = new_school_form[
                        'address_country']
                    new_school.save()
                    school_visit.school = new_school
                else:
                    # School form invalid
                    return render_to_response(
                        'instant_workshop.html', {
                            'form1': formpart1,
                            'form2': formpart2,
                            'schoolform': form_school
                        },
                        context_instance=RequestContext(request))
            else:
                try:
                    previously_visited_school = School.objects.get(
                        name=selected_school)
                except ObjectDoesNotExist:
                    messages.error(
                        request,
                        message=unicode(
                            "Please select a school from the list or create a new one."
                        ))
                    return render_to_response(
                        'instant_workshop.html', {
                            'form1': formpart1,
                            'form2': formpart2,
                            'schoolform': form_school
                        },
                        context_instance=RequestContext(request))
                school_visit.school = previously_visited_school

            school_visit.chapter = chapter
            school_visit.creator = request.user
            school_visit.location = data['location']
            school_visit.visit_start = make_aware(datetime.datetime.combine(
                data['date'], data['start_time']),
                                                  timezone=chapter.tz_obj())
            school_visit.visit_end = make_aware(datetime.datetime.combine(
                data['date'], data['end_time']),
                                                timezone=chapter.tz_obj())
            school_visit.save()

            # Add the new stats just entered
            stats = SchoolVisitStats()
            stats.visit = school_visit
            stats.visit_type = data_stats['visit_type']
            stats.primary_girls_first = data_stats['primary_girls_first']
            stats.primary_girls_repeat = data_stats['primary_girls_repeat']
            stats.primary_boys_first = data_stats['primary_boys_first']
            stats.primary_boys_repeat = data_stats['primary_boys_repeat']
            stats.high_girls_first = data_stats['high_girls_first']
            stats.high_girls_repeat = data_stats['high_girls_repeat']
            stats.high_boys_first = data_stats['high_boys_first']
            stats.high_boys_repeat = data_stats['high_boys_repeat']
            stats.other_girls_first = data_stats['other_girls_first']
            stats.other_girls_repeat = data_stats['other_girls_repeat']
            stats.other_boys_first = data_stats['other_boys_first']
            stats.other_boys_repeat = data_stats['other_boys_repeat']
            stats.notes = data_stats['notes']
            stats.save()

            # Save attendance in database
            for attendee in data_stats['attended']:
                newinvite = EventAttendee()
                newinvite.event = school_visit
                newinvite.user = attendee
                newinvite.actual_status = 1
                newinvite.rsvp_status = 0
                newinvite.save()

            # Render page 2: enter user-specific volunteering hours
            default_hours = int(
                math.ceil((school_visit.visit_end -
                           school_visit.visit_start).total_seconds() / 3600.0))

            request.session['hoursPerPersonStage'] = 2

            return render_to_response('visit_hoursPerPerson.html', {
                'attended': data_stats['attended'],
                'visit_id': school_visit.id,
                'defaultHours': range(default_hours)
            },
                                      context_instance=RequestContext(request))

        # Form is invalid
        else:
            return render_to_response('instant_workshop.html', {
                'form1': formpart1,
                'form2': formpart2,
                'schoolform': form_school
            },
                                      context_instance=RequestContext(request))

    # Happens when someone presses back - refer them to the workshop list page to refill stats there
    elif request.method == 'POST' and request.session[
            'hoursPerPersonStage'] == 2:
        del request.session['hoursPerPersonStage']
        messages.info(
            request,
            message=
            'An error occurred, find your newly created workshop here and refill in your stats.'
        )
        return redirect('/teaching/list/')

    # Prepare form
    if request.user.is_superuser:
        formpart1 = SchoolVisitFormInstant(chapter=None)
        formpart2 = SchoolVisitStatsFormInstant(chapter=None)
    else:
        formpart1 = SchoolVisitFormInstant(chapter=chapter)
        formpart2 = SchoolVisitStatsFormInstant(chapter=chapter)

    form_school = SchoolFormPartOne(chapter=chapter, school_id=0)

    # Render clean form
    return render_to_response('instant_workshop.html', {
        'form1': formpart1,
        'form2': formpart2,
        'schoolform': form_school
    },
                              context_instance=RequestContext(request))
Esempio n. 4
0
def stats(request, visit_id):
	v = get_object_or_404(SchoolVisit, pk=visit_id)
	if v.school.chapter != request.user.chapter:
		raise Http404
	if not request.user.is_staff:
		raise Http404
	if not request.session.get('hoursPerPersonStage', False):
		request.session['hoursPerPersonStage'] = 1
		form = SchoolVisitStatsForm(None, visit = v)
		return render_to_response('visit_stats.html', {'form':form, 'visit_id':visit_id}, context_instance=RequestContext(request))
	if request.method == 'POST' and request.session['hoursPerPersonStage'] == 1:
		request.session['hoursPerPersonStage'] = 2
		form = SchoolVisitStatsForm(request.POST, visit = v)
		if form.is_valid():
			data = form.cleaned_data
			stats = SchoolVisitStats()
			stats.visit = v
			stats.visit_type = data['visit_type']
			stats.primary_girls_first = data['primary_girls_first']
			stats.primary_girls_repeat = data['primary_girls_repeat']
			stats.primary_boys_first = data['primary_boys_first']
			stats.primary_boys_repeat = data['primary_boys_repeat']
			stats.high_girls_first = data['high_girls_first']
			stats.high_girls_repeat = data['high_girls_repeat']
			stats.high_boys_first = data['high_boys_first']
			stats.high_boys_repeat = data['high_boys_repeat']
			stats.other_girls_first = data['other_girls_first']
			stats.other_girls_repeat = data['other_girls_repeat']
			stats.other_boys_first = data['other_boys_first']
			stats.other_boys_repeat = data['other_boys_repeat']
			stats.notes = data['notes']
			stats.save()
			for attendee in data['attended']:
				list = EventAttendee.objects.filter(event__id=v.id).values_list('user_id', flat=True)
				if attendee.id not in list:
					newinvite = EventAttendee()
					newinvite.event = v
					newinvite.user = attendee
					newinvite.actual_status = 1
					newinvite.rsvp_status = 0
					newinvite.save()
			
			for person in EventAttendee.objects.filter(event__id=v.id):
				if person.user in data['attended']:
					person.actual_status = 1
					person.save()
				else:
					person.actual_status = 2
					person.save()
						
			defaultHours =  v.visit_end.hour - v.visit_start.hour
			if v.visit_end.minute > v.visit_start.minute:
				defaultHours += 1
			return render_to_response('visit_hoursPerPerson.html', {'attended': data['attended'], 'visit_id': visit_id, 'defaultHours': range(defaultHours)}, context_instance=RequestContext(request))
		else:
			request.session['hoursPerPersonStage'] = 1
			return render_to_response('visit_stats.html', {'form':form, 'visit_id':visit_id}, context_instance=RequestContext(request))
	elif request.method == 'POST' and request.session['hoursPerPersonStage'] == 2:
		raise Http404
	else:
		request.session['hoursPerPersonStage'] = 1
		form = SchoolVisitStatsForm(None, visit = v)
		return render_to_response('visit_stats.html', {'form':form, 'visit_id':visit_id}, context_instance=RequestContext(request))
Esempio n. 5
0
def invitetovisit(request, visit_id):
	chapter = request.user.chapter
	v = get_object_or_404(SchoolVisit, pk=visit_id)
	error = ''
	if (v.chapter != chapter):
		raise Http404
	if request.method == 'POST':
		inviteform = InviteForm(request.POST, user=request.user, visit=v)
		if inviteform.is_valid():
			data = inviteform.cleaned_data
			try:
				if data['action'] == '1':
					message = EmailMessage()
					message.subject = data['subject']
					try:
						message.body = data['body'].format(
							visit=v,
							user=request.user
						)
					except Exception:
						raise Exception(_('Email body contains invalid fields'))
					message.from_address = request.user.email
					message.reply_address = request.user.email
					message.sender = request.user
					message.html = True
					message.from_name = chapter.name
					
					# Don't send it yet until the recipient list is done
					message.status = -1
					# Save to database so we get a value for the primary key,
					# which we need for entering the recipient entries
					message.save()
	
				if request.POST['type'] == '1':
					users = User.objects.filter(chapter=chapter, is_active=True, email_reminder_optin=True)
				elif request.POST['type'] == '2':
					users = User.objects.filter(chapter=chapter, is_active=True, is_staff=True)
				elif request.POST['type'] == '4':
					users = User.objects.filter(chapter=chapter, is_active=True, email_reminder_optin=True, trained=True)
				elif request.POST['type'] == '5':
					ul = data['list']
					users = ul.users.all()
				else:
					users = data['memberselect']
	
				for one_user in users:
					if data['action'] == '1':
						recipient = EmailRecipient()
						recipient.message = message
						recipient.user = one_user
						recipient.to_name = one_user.get_full_name()
						recipient.to_address = one_user.email
						recipient.save()
					EventAttendee.objects.filter(user=one_user, event=v).delete()
					ea = EventAttendee()
					ea.event=v
					ea.user=one_user
					if data['action'] == '1':
						ea.rsvp_status=1
					if data['action'] == '2':
						ea.rsvp_status=2
					ea.actual_status=0
					ea.save()
				
				if data['action'] == '1':
					# Now mark it as OK to send. The email and all recipients are now in MySQL.
					# A background script on the server will process the queue.
					message.status = 0
					message.save()
				
				if data['action'] == '1':
					request.user.message_set.create(message=unicode(_("Invitations have been sent to the selected volunteers")))
				if data['action'] == '2':
					request.user.message_set.create(message=unicode(_("Selected volunteers have been added as attending")))
				return HttpResponseRedirect('/teaching/' + str(v.pk) + '/')
			except Exception as e:
				error = e.args[0]
	else:
		inviteform = InviteForm(None, user=request.user, visit=v)
	return render_to_response('visit_invite.html', {'inviteform': inviteform, 'visit_id': visit_id, 'error': error}, context_instance=RequestContext(request))
Esempio n. 6
0
def instantvisit(request):
    chapter = request.user.chapter

    # Check if the user has exec rights
    if not request.user.is_staff and not request.user.is_superuser:
        raise Http404

    if not request.session.get('hoursPerPersonStage', False):
        request.session['hoursPerPersonStage'] = 1

    # Sometimes request.session['hoursPerPersonStage'] may equal 1 from editing stats from a closed workshop
    if request.method == 'POST' and request.session['hoursPerPersonStage'] != 2:
        if request.user.is_superuser:
            formpart1 = SchoolVisitFormInstant(request.POST, chapter=None)
            formpart2 = SchoolVisitStatsFormInstant(request.POST, chapter=None)
        else:
            formpart1 = SchoolVisitFormInstant(request.POST, chapter=chapter)
            formpart2 = SchoolVisitStatsFormInstant(request.POST, chapter=chapter)

        form_school = SchoolFormPartOne(request.POST, chapter=chapter, school_id=0)

        # Validate form
        if formpart1.is_valid() and formpart2.is_valid():
            data = formpart1.cleaned_data
            data_stats = formpart2.cleaned_data

            selected_school = data['school']
            school_visit = SchoolVisit()
            new_school = School()

            school_visit.created_method = 1

            # Check if new school was selected, New school equals to 0
            if selected_school == u'0':
                if form_school.is_valid():
                    new_school_form = form_school.cleaned_data

                    # Check if school exists
                    exist = School.objects.filter(name__iexact=new_school_form['name'], chapter=chapter)
                    if exist:
                        messages.error(request, "School seems to already exist, please recheck list.")
                        return render_to_response('instant_workshop.html',
                                                  {'form1': formpart1, 'form2': formpart2, 'schoolform': form_school},
                                                  context_instance=RequestContext(request))

                    # Create new school after checking it doesn't exist
                    new_school.name = new_school_form['name']
                    new_school.chapter = chapter
                    new_school.address_street = new_school_form['address_street']
                    new_school.address_city = new_school_form['address_city']
                    new_school.address_state = new_school_form['address_state']
                    new_school.address_country = new_school_form['address_country']
                    new_school.save()
                    school_visit.school = new_school
                else:
                    # School form invalid
                    return render_to_response('instant_workshop.html',
                                              {'form1': formpart1, 'form2': formpart2, 'schoolform': form_school},
                                              context_instance=RequestContext(request))
            else:
                try:
                    previously_visited_school = School.objects.get(name=selected_school, chapter=chapter)
                except ObjectDoesNotExist:
                    messages.error(request,
                                   message=unicode("Please select a school from the list or create a new one."))
                    return render_to_response('instant_workshop.html',
                                              {'form1': formpart1, 'form2': formpart2, 'schoolform': form_school},
                                              context_instance=RequestContext(request))
                school_visit.school = previously_visited_school

            school_visit.chapter = chapter
            school_visit.creator = request.user
            school_visit.location = data['location']
            school_visit.visit_start = make_aware(datetime.datetime.combine(data['date'], data['start_time']),
                                                  timezone=chapter.tz_obj())
            school_visit.visit_end = make_aware(datetime.datetime.combine(data['date'], data['end_time']),
                                                timezone=chapter.tz_obj())
            school_visit.save()

            # Add the new stats just entered
            stats = SchoolVisitStats()
            stats.visit = school_visit
            stats.visit_type = data_stats['visit_type']
            stats.primary_girls_first = data_stats['primary_girls_first']
            stats.primary_girls_repeat = data_stats['primary_girls_repeat']
            stats.primary_boys_first = data_stats['primary_boys_first']
            stats.primary_boys_repeat = data_stats['primary_boys_repeat']
            stats.high_girls_first = data_stats['high_girls_first']
            stats.high_girls_repeat = data_stats['high_girls_repeat']
            stats.high_boys_first = data_stats['high_boys_first']
            stats.high_boys_repeat = data_stats['high_boys_repeat']
            stats.other_girls_first = data_stats['other_girls_first']
            stats.other_girls_repeat = data_stats['other_girls_repeat']
            stats.other_boys_first = data_stats['other_boys_first']
            stats.other_boys_repeat = data_stats['other_boys_repeat']
            stats.notes = data_stats['notes']
            stats.save()

            # Save attendance in database
            for attendee in data_stats['attended']:
                newinvite = EventAttendee()
                newinvite.event = school_visit
                newinvite.user = attendee
                newinvite.actual_status = 1
                newinvite.rsvp_status = 0
                newinvite.save()

            # Render page 2: enter user-specific volunteering hours
            default_hours = int(math.ceil((school_visit.visit_end - school_visit.visit_start).total_seconds() / 3600.0))

            request.session['hoursPerPersonStage'] = 2

            return render_to_response('visit_hoursPerPerson.html',
                                      {'attended': data_stats['attended'], 'visit_id': school_visit.id,
                                       'defaultHours': range(default_hours)},
                                      context_instance=RequestContext(request))

        # Form is invalid
        else:
            return render_to_response('instant_workshop.html',
                                      {'form1': formpart1, 'form2': formpart2, 'schoolform': form_school},
                                      context_instance=RequestContext(request))

    # Happens when someone presses back - refer them to the workshop list page to refill stats there
    elif request.method == 'POST' and request.session['hoursPerPersonStage'] == 2:
        del request.session['hoursPerPersonStage']
        messages.info(request,
                      message='An error occurred, find your newly created workshop here and refill in your stats.')
        return redirect('/teaching/list/')

    # Prepare form
    if request.user.is_superuser:
        formpart1 = SchoolVisitFormInstant(chapter=None)
        formpart2 = SchoolVisitStatsFormInstant(chapter=None)
    else:
        formpart1 = SchoolVisitFormInstant(chapter=chapter)
        formpart2 = SchoolVisitStatsFormInstant(chapter=chapter)

    form_school = SchoolFormPartOne(chapter=chapter, school_id=0)

    # Render clean form
    return render_to_response('instant_workshop.html',
                              {'form1': formpart1, 'form2': formpart2, 'schoolform': form_school},
                              context_instance=RequestContext(request))
Esempio n. 7
0
    def import_workshop_csv(request, filerows, save):
        columns = None
        workshops_imported = 0
        workshop_list = []
        err_msg = {}
        row_idx = 0

        # Find the indices of fields
        for row in filerows:
            if any(row):
                row_idx += 1
                if columns is None:
                    columns = row

                    # Check to see there are an appropriate number of columns in the header
                    if len(columns) < 20:
                        err_msg.update({str(row_idx): 'You are missing columns in your .csv table. Please correct the error and try again.'})
                        workshops_imported = None
                        return workshop_list, workshops_imported, err_msg

                    continue

                school_visit = SchoolVisit()
                stats = SchoolVisitStats()

                school_visit.chapter = request.user.chapter
                school_visit.creator = request.user
                school_visit.created_method = 2

                i = 0
                date = ''
                attendees_list = []
                attendee_errors = {}
                data_filled_correctly = False

                for col in row:
                    colname = columns[i]
                    i += 1

                    if i > 19: i = 19

                    if 'Attendees' in colname:
                        if i != 19:
                            err_msg.update({str(row_idx): 'There was an incorrect number of items in this row, please check your columns from template again'})
                            break

                        # ASSUMPTION: The remaining columns in a row are all volunteer usernames
                        data_filled_correctly = True
                        attendee = EventAttendee()

                        try:
                            # Empty attendee field
                            if not col:
                                continue

                            # Try to find in the user exists
                            u = User.objects.get(username__exact=col)
                        except ObjectDoesNotExist:
                            try:
                                attendee_errors[str(row_idx)] += '<br>Could not find %s and has not been added to the workshop' % col
                            except KeyError:
                                attendee_errors.update({str(row_idx): 'Could not find %s and has not been added to the workshop' % col})

                            continue

                        attendee.user = u
                        attendee.actual_status = 1
                        attendee.rsvp_status = 0
                        attendees_list.append(attendee)
                    else:
                        if colname == 'School ID':
                            try:
                                school_visit.school = School.objects.get(pk=sint(col), chapter=request.user.chapter)
                            except ObjectDoesNotExist:
                                err_msg.update({str(row_idx): "That school ID does not exist in your schools database, please check again from your schools list. If they don't exist, add them in the Schools tab and try again"})
                                break

                        elif colname == 'Visit Date':
                            # Check for correct format
                            try:
                                date = datetime.strptime(col, '%d/%m/%Y')
                            except ValueError:
                                err_msg.update({str(row_idx): 'The date format specified (%s) is not in the correct format' % col})
                                break

                            # Check if user enters an event that's set in the future
                            if make_aware(date, timezone=request.user.chapter.tz_obj()) > datetime.now(tz=request.user.chapter.tz_obj()):
                                err_msg.update({str(row_idx): 'This event has not occurred yet and therefore cannot be entered in'})
                                break
                        elif colname == 'Start Time':
                            # Check for correct format
                            try:
                                t = datetime.strptime(col, '%H:%M:%S').time()
                            except ValueError:
                                try:
                                    # Try another format cause excel -_-
                                    t = datetime.strptime(col, '%H:%M').time()
                                except ValueError:
                                    err_msg.update({str(row_idx): 'The start time specified (%s) is not in the correct format' % col})
                                    break

                            school_visit.visit_start = make_aware(datetime.combine(date, t), timezone=request.user.chapter.tz_obj())
                        elif colname == 'End Time':
                            # Check for correct format
                            try:
                                t = datetime.strptime(col, '%H:%M:%S').time()
                            except ValueError:
                                try:
                                    # Try another format cause excel -_-
                                    t = datetime.strptime(col, '%H:%M').time()
                                except ValueError:
                                    err_msg.update({str(row_idx): 'The end time specified (%s) is not in the correct format' % col})
                                    break

                            school_visit.visit_end = make_aware(datetime.combine(date, t), timezone=request.user.chapter.tz_obj())

                            if school_visit.visit_end < school_visit.visit_start:
                                err_msg.update({str(row_idx): 'The end time is earlier than start time'})
                                break

                        elif colname == 'Location':
                            if col == '':
                                err_msg.update({str(row_idx): 'You must specify a location for this visit'})
                                break

                            school_visit.location = col
                        elif colname == 'Visit Type ID':
                            if sint(col) < 0 or sint(col) > 7:
                                stats.visit_type = 0
                            else:
                                stats.visit_type = sint(col)
                        elif colname == 'Primary Girls First':
                            stats.primary_girls_first = sint(col)
                        elif colname == 'Primary Girls Repeat':
                            stats.primary_girls_repeat = sint(col)
                        elif colname == 'Primary Boys First':
                            stats.primary_boys_first = sint(col)
                        elif colname == 'Primary Boys Repeat':
                            stats.primary_boys_repeat = sint(col)
                        elif colname == 'High Girls First':
                            stats.high_girls_first = sint(col)
                        elif colname == 'High Girls Repeat':
                            stats.high_girls_repeat = sint(col)
                        elif colname == 'High Boys First':
                            stats.high_boys_first = sint(col)
                        elif colname == 'High Boys Repeat':
                            stats.high_boys_repeat = sint(col)
                        elif colname == 'Other Girls First':
                            stats.other_girls_first = sint(col)
                        elif colname == 'Other Girls Repeat':
                            stats.other_girls_repeat = sint(col)
                        elif colname == 'Other Boys First':
                            stats.other_boys_first = sint(col)
                        elif colname == 'Other Boys Repeat':
                            stats.other_boys_repeat = sint(col)
                        elif colname == 'Notes':
                            stats.notes = col
                        else:
                            err_msg.update({str(row_idx): "Column not recognised, use the column names provided in the template and reupload your file."})
                            return workshop_list, workshops_imported, err_msg

                # Only check for existence and save when data is filled correctly
                if data_filled_correctly:
                    # Perform saves to database
                    d_start = datetime.replace(school_visit.visit_start, microsecond=0, tzinfo=None).__format__('%d/%m/%y %H:%M')
                    d_end = datetime.replace(school_visit.visit_end, microsecond=0, tzinfo=None).time().__format__('%H:%M')

                    try:
                        s = SchoolVisit.objects.get(
                            visit_start=school_visit.visit_start,
                            visit_end=school_visit.visit_end,
                            school=school_visit.school
                        )

                        err_msg.update({str(row_idx): ' Visit to %s on %s-%s already exists in the database' % (school_visit.school.name, d_start, d_end)})
                        continue
                    except ObjectDoesNotExist:
                        w = {'text': {str(row_idx): 'Adding visit to %s on %s-%s' % (school_visit.school.name, d_start, d_end)}, 'attendees': attendees_list}
                        workshop_list.append(w)

                        if save:
                            school_visit.status = 1
                            school_visit.save()
                            stats.visit = school_visit
                            stats.save()

                            # Save the stats of all attendees
                            for attendee in attendees_list:
                                attendee.event = school_visit
                                attendee.save()

                        err_msg.update(attendee_errors)
                        workshops_imported += 1

        return workshop_list, workshops_imported, err_msg
Esempio n. 8
0
    def import_workshop_csv(request, filerows, save):
        columns = None
        workshops_imported = 0
        workshop_list = []
        err_msg = {}
        row_idx = 0

        # Find the indices of fields
        for row in filerows:
            if any(row):
                row_idx += 1
                if columns is None:
                    columns = row

                    # Check to see there are an appropriate number of columns in the header
                    if len(columns) < 20:
                        err_msg.update({
                            str(row_idx):
                            'You are missing columns in your .csv table. Please correct the error and try again.'
                        })
                        workshops_imported = None
                        return workshop_list, workshops_imported, err_msg

                    continue

                school_visit = SchoolVisit()
                stats = SchoolVisitStats()

                school_visit.chapter = request.user.chapter
                school_visit.creator = request.user
                school_visit.created_method = 2

                i = 0
                date = ''
                attendees_list = []
                attendee_errors = {}
                data_filled_correctly = False

                for col in row:
                    colname = columns[i]
                    i += 1

                    if i > 19: i = 19

                    if 'Attendees' in colname:
                        if i != 19:
                            err_msg.update({
                                str(row_idx):
                                'There was an incorrect number of items in this row, please check your columns from template again'
                            })
                            break

                        # ASSUMPTION: The remaining columns in a row are all volunteer usernames
                        data_filled_correctly = True
                        attendee = EventAttendee()

                        try:
                            # Empty attendee field
                            if not col:
                                continue

                            # Try to find in the user exists
                            u = User.objects.get(username__exact=col)
                        except ObjectDoesNotExist:
                            try:
                                attendee_errors[str(
                                    row_idx
                                )] += '<br>Could not find %s and has not been added to the workshop' % col
                            except KeyError:
                                attendee_errors.update({
                                    str(row_idx):
                                    'Could not find %s and has not been added to the workshop'
                                    % col
                                })

                            continue

                        attendee.user = u
                        attendee.actual_status = 1
                        attendee.rsvp_status = 0
                        attendees_list.append(attendee)
                    else:
                        if colname == 'School ID':
                            try:
                                school_visit.school = School.objects.get(
                                    pk=sint(col), chapter=request.user.chapter)
                            except ObjectDoesNotExist:
                                err_msg.update({
                                    str(row_idx):
                                    "That school ID does not exist in your schools database, please check again from your schools list. If they don't exist, add them in the Schools tab and try again"
                                })
                                break

                        elif colname == 'Visit Date':
                            # Check for correct format
                            try:
                                date = datetime.strptime(col, '%d/%m/%Y')
                            except ValueError:
                                err_msg.update({
                                    str(row_idx):
                                    'The date format specified (%s) is not in the correct format'
                                    % col
                                })
                                break

                            # Check if user enters an event that's set in the future
                            if make_aware(
                                    date,
                                    timezone=request.user.chapter.tz_obj()
                            ) > datetime.now(tz=request.user.chapter.tz_obj()):
                                err_msg.update({
                                    str(row_idx):
                                    'This event has not occurred yet and therefore cannot be entered in'
                                })
                                break
                        elif colname == 'Start Time':
                            # Check for correct format
                            try:
                                t = datetime.strptime(col, '%H:%M:%S').time()
                            except ValueError:
                                try:
                                    # Try another format cause excel -_-
                                    t = datetime.strptime(col, '%H:%M').time()
                                except ValueError:
                                    err_msg.update({
                                        str(row_idx):
                                        'The start time specified (%s) is not in the correct format'
                                        % col
                                    })
                                    break

                            school_visit.visit_start = make_aware(
                                datetime.combine(date, t),
                                timezone=request.user.chapter.tz_obj())
                        elif colname == 'End Time':
                            # Check for correct format
                            try:
                                t = datetime.strptime(col, '%H:%M:%S').time()
                            except ValueError:
                                try:
                                    # Try another format cause excel -_-
                                    t = datetime.strptime(col, '%H:%M').time()
                                except ValueError:
                                    err_msg.update({
                                        str(row_idx):
                                        'The end time specified (%s) is not in the correct format'
                                        % col
                                    })
                                    break

                            school_visit.visit_end = make_aware(
                                datetime.combine(date, t),
                                timezone=request.user.chapter.tz_obj())

                            if school_visit.visit_end < school_visit.visit_start:
                                err_msg.update({
                                    str(row_idx):
                                    'The end time is earlier than start time'
                                })
                                break

                        elif colname == 'Location':
                            if col == '':
                                err_msg.update({
                                    str(row_idx):
                                    'You must specify a location for this visit'
                                })
                                break

                            school_visit.location = col
                        elif colname == 'Visit Type ID':
                            if sint(col) < 0 or sint(col) > 7:
                                stats.visit_type = 0
                            else:
                                stats.visit_type = sint(col)
                        elif colname == 'Primary Girls First':
                            stats.primary_girls_first = sint(col)
                        elif colname == 'Primary Girls Repeat':
                            stats.primary_girls_repeat = sint(col)
                        elif colname == 'Primary Boys First':
                            stats.primary_boys_first = sint(col)
                        elif colname == 'Primary Boys Repeat':
                            stats.primary_boys_repeat = sint(col)
                        elif colname == 'High Girls First':
                            stats.high_girls_first = sint(col)
                        elif colname == 'High Girls Repeat':
                            stats.high_girls_repeat = sint(col)
                        elif colname == 'High Boys First':
                            stats.high_boys_first = sint(col)
                        elif colname == 'High Boys Repeat':
                            stats.high_boys_repeat = sint(col)
                        elif colname == 'Other Girls First':
                            stats.other_girls_first = sint(col)
                        elif colname == 'Other Girls Repeat':
                            stats.other_girls_repeat = sint(col)
                        elif colname == 'Other Boys First':
                            stats.other_boys_first = sint(col)
                        elif colname == 'Other Boys Repeat':
                            stats.other_boys_repeat = sint(col)
                        elif colname == 'Notes':
                            stats.notes = col
                        else:
                            err_msg.update({
                                str(row_idx):
                                "Column not recognised, use the column names provided in the template and reupload your file."
                            })
                            return workshop_list, workshops_imported, err_msg

                # Only check for existence and save when data is filled correctly
                if data_filled_correctly:
                    # Perform saves to database
                    d_start = datetime.replace(
                        school_visit.visit_start, microsecond=0,
                        tzinfo=None).__format__('%d/%m/%y %H:%M')
                    d_end = datetime.replace(
                        school_visit.visit_end, microsecond=0,
                        tzinfo=None).time().__format__('%H:%M')

                    try:
                        s = SchoolVisit.objects.get(
                            visit_start=school_visit.visit_start,
                            visit_end=school_visit.visit_end,
                            school=school_visit.school)

                        err_msg.update({
                            str(row_idx):
                            ' Visit to %s on %s-%s already exists in the database'
                            % (school_visit.school.name, d_start, d_end)
                        })
                        continue
                    except ObjectDoesNotExist:
                        w = {
                            'text': {
                                str(row_idx):
                                'Adding visit to %s on %s-%s' %
                                (school_visit.school.name, d_start, d_end)
                            },
                            'attendees': attendees_list
                        }
                        workshop_list.append(w)

                        if save:
                            school_visit.status = 1
                            school_visit.save()
                            stats.visit = school_visit
                            stats.save()

                            # Save the stats of all attendees
                            for attendee in attendees_list:
                                attendee.event = school_visit
                                attendee.save()

                        err_msg.update(attendee_errors)
                        workshops_imported += 1

        return workshop_list, workshops_imported, err_msg