Esempio n. 1
0
def removeItem():
    if request.method == "GET":
        return render_template("items/markUnsold.html")
    elif request.method == "POST":
        item_to_delete = Item.query.filter_by(
            item_id=request.form['itemID']).first()
        if item_to_delete is None:
            return jsonify(False)

        item_to_delete.unsold = 1
        item_to_delete.removed_by = current_user.id

        if item_to_delete is None:
            return jsonify(False)

        removed_item = {
            "type": item_to_delete.getTypeName(),
            "category": item_to_delete.getCategoryName(),
            "subcategory": item_to_delete.getSubcategoryName()
        }
        print(removed_item)
        try:
            db_session.add(item_to_delete)
            db_session.commit()
        except:
            return jsonify(False)
        else:
            return jsonify(removed_item)
Esempio n. 2
0
def editAttribute(id=None):
    if request.method == "GET":
        error = request.args.get('error', default=None, type=str)
        success = request.args.get('success', default=None, type=str)
        oldAttr = itemAttribute.query.filter_by(id=id).first()
        return render_template("attributes/editAttribute.html",
                               oldAttr=oldAttr,
                               attr_values=json.loads(oldAttr.attr_values),
                               error=error,
                               success=success)
    elif request.method == "POST":
        name = request.form['attr_name']
        attr_values = request.form['attr_values']

        new_attr = itemAttribute(attr_name=name, attr_values=attr_values)

        try:
            db_session.add(new_attr)
            db_session.commit()
        except:
            return redirect(
                url_for("items",
                        error="There was an error adding that attribute"))
        else:
            return redirect(
                url_for("items",
                        success="The attribute %s was successfully added" %
                        (name)))
Esempio n. 3
0
def registerForProject():
    project_id = request.form['project_id']
    project_strengths = request.form['projectStrengths']

    proj = Project.query.filter_by(nice_url=project_id).first()

    if proj is None:
        return url_for("projects", error="That project doesn't exist.")

    if not current_user.is_part_of_project(
            proj.project_id) and len(proj.get_members()) < 12:
        stud_to_proj = StudentToProject(proj.project_id, current_user.id,
                                        project_strengths)

        try:
            db_session.add(stud_to_proj)
            db_session.commit()
        except:
            return url_for(
                "projects",
                error="There was an error adding your to that project.")
        else:
            return url_for("projects", success="You were successfully added.")
    else:
        if current_user.is_part_of_project(proj.project_id):
            return url_for("projects",
                           success="You are already part of this project.")
        else:
            return url_for("projects", error="That project is full.")
Esempio n. 4
0
def addCategory():
    if request.method == "GET":
        error = request.args.get('error', default=None, type=str)
        success = request.args.get('success', default=None, type=str)
        types = itemType.query.all()

        item_types = []
        for item_type in types:
            item_types.append([item_type.id, item_type.name])

        return render_template("categories/addCategory.html",
                               types=item_types,
                               error=error,
                               success=success)
    elif request.method == "POST":
        name = request.form['name']
        icon = request.form['icon']

        new_category = itemCategory(type_id=int(request.form['type']),
                                    name=name,
                                    icon=icon)

        try:
            db_session.add(new_category)
            db_session.commit()
        except:
            return redirect(
                url_for("items",
                        error="There was an error adding that Subcategory"))
        else:
            return redirect(
                url_for("items",
                        success="The Subcategory %s was successfully added" %
                        (name)))
Esempio n. 5
0
def editType(id=None):
    if request.method == "GET":
        oldType = itemType.query.filter_by(id=id).first()
        if oldType is None:
            return redirect(url_for('items', error="That type doesn't exist."))

        error = request.args.get('error', default=None, type=str)
        success = request.args.get('success', default=None, type=str)
        return render_template("types/editType.html",
                               type=oldType,
                               error=error,
                               success=success)
    elif request.method == "POST":
        oldType = itemType.query.filter_by(id=id).first()
        if oldType is None:
            return redirect('items', error="That type doesn't exist.")

        name = request.form['name']
        icon = request.form['icon']
        oldName = oldType.name
        oldType.name = name
        oldType.icon = icon

        try:
            db_session.add(oldType)
            db_session.commit()
        except:
            return redirect(
                url_for("items", error="There was an error adding that type"))
        else:
            return redirect(
                url_for("items",
                        success="The type %s was successfully updated" %
                        (oldName)))
Esempio n. 6
0
def create():
    if request.json is None:
        return jsonify({'error': 'Missing Request Body'}), 400

    task = request.json.get('task')
    if not task:
        return jsonify({'error': 'Missing Task'}), 400

    todo = Todo(task)
    db_session.add(todo)
    db_session.commit()

    return jsonify(todo.serialize)
Esempio n. 7
0
def joinGroup(group_id):
    group = Group.query.filter_by(id=group_id).first()

    project = group.get_project()

    if current_user.user_type == "student":
        current_group = StudentToGroup.query.filter_by(
            user_id=current_user.id, group_id=group_id).first()
        if current_group == None:
            student_group = StudentToGroup.query.filter_by(
                user_id=current_user.id,
                project_id=project.project_id).first()

            if student_group is None:
                student_to_group = StudentToGroup(group_id, current_user.id)
                try:
                    db_session.add(student_to_group)
                    db_session.commit()
                except:
                    db_session.rollback()
                    return redirect(
                        url_for(
                            "project",
                            project_id=project.project_id,
                            error=
                            "Something went wrong, try again a little later."))
                else:
                    return redirect(
                        url_for(
                            "project",
                            project_id=project.project_id,
                            success="You were successfully added to that group."
                        ))
            else:
                return redirect(
                    url_for(
                        "project",
                        project_id=project.project_id,
                        error="You are already registered for the group '" +
                        student_group.get_group().name + "'"))
        else:
            return redirect(
                url_for("project",
                        project_id=project.project_id,
                        error="You are already part of this group."))
    else:
        return redirect(
            url_for("project",
                    project_id=project.project_id,
                    error="Only Students can join groups."))
Esempio n. 8
0
def createGroup(project_id):
    group_name = request.form['group_name']
    desc = request.form['desc']

    group = Group(group_name=group_name,
                  project_id=project_id,
                  solution_desc=desc)

    try:
        db_session.add(group)
        db_session.commit()
    except:
        return url_for("project",
                       project_id=project_id,
                       error="Something went wrong, try again a little later.")
    else:
        return url_for("project",
                       project_id=project_id,
                       success="That group was successfully created.")
Esempio n. 9
0
def editCategory(id=None):
    oldCategory = itemCategory.query.filter_by(id=id).first()

    if oldCategory == None:
        return redirect(url_for('items', error="That category doesn't exist."))

    if request.method == "GET":
        error = request.args.get('error', default=None, type=str)
        success = request.args.get('success', default=None, type=str)
        types = itemType.query.all()

        item_types = []
        for item_type in types:
            item_types.append([item_type.id, item_type.name])

        return render_template("categories/editCategory.html",
                               category=oldCategory,
                               types=item_types,
                               error=error,
                               success=success)
    elif request.method == "POST":
        name = request.form['name']
        icon = request.form['icon']

        oldCategory.type_id = int(request.form['type'])
        oldCategory.name = name
        oldCategory.icon = icon

        try:
            db_session.add(oldCategory)
            db_session.commit()
        except:
            return redirect(
                url_for("items",
                        error="There was an error adding that category"))
        else:
            return redirect(
                url_for("items",
                        success="The category %s was successfully added" %
                        (name)))
Esempio n. 10
0
def addUser():
    if request.method == "GET":
        return render_template('users/addUser.html')
    elif request.method == "POST":
        username = request.form['employeeNumber']
        name = request.form['name']
        password = generate_password_hash(request.form['password'])
        id = request.form['employeeNumber']

        user = User(username=username,
                    password=password,
                    name=name,
                    id=id,
                    admin=int(request.form['admin']))

        try:
            db_session.add(user)
            db_session.commit()
        except:
            return jsonify(False)
        else:
            return redirect(url_for("home"))
Esempio n. 11
0
def editUser(id=None):
    oldUser = User.query.filter_by(id=id).first()
    if request.method == "GET":

        if oldUser is None:
            return redirect(url_for('users', error="That user doesn't exist."))

        error = request.args.get('error', default=None, type=str)
        success = request.args.get('success', default=None, type=str)
        return render_template("users/editUser.html",
                               user=oldUser,
                               error=error,
                               success=success)
    elif request.method == "POST":
        username = request.form['employeeNumber']
        name = request.form['name']
        if not request.form['password'] == "":
            password = generate_password_hash(request.form['password'])
            oldUser.password = password

        id = request.form['employeeNumber']

        oldUser.id = username
        oldUser.name = name
        oldUser.username = username

        try:
            db_session.add(oldUser)
            db_session.commit()
        except:
            return redirect(
                url_for("users",
                        error="There was a problem updating that user." %
                        (oldUser.name)))
        else:
            return redirect(
                url_for("users",
                        success="%s was successfully saved." % (oldUser.name)))
Esempio n. 12
0
def addType():
    if request.method == "GET":
        error = request.args.get('error', default=None, type=str)
        success = request.args.get('success', default=None, type=str)
        return render_template("types/addType.html",
                               error=error,
                               success=success)
    elif request.method == "POST":
        name = request.form['name']
        icon = request.form['icon']

        new_type = itemType(name=name, icon=icon)

        try:
            db_session.add(new_type)
            db_session.commit()
        except:
            return redirect(
                url_for("items", error="There was an error adding that type"))
        else:
            return redirect(
                url_for("items",
                        success="The type %s was successfully added" % (name)))
Esempio n. 13
0
def createProject():
    project_name = request.form['project_name']
    desc = request.form['desc']

    project = Project(project_name=project_name,
                      user_id=current_user.id,
                      description=desc)
    auto_assign_group = Group(
        "Auto-Assign Group", project.project_id,
        "This is a group that will auto assign you to the group with the best schedule"
    )
    project.autoAssign_group_id = auto_assign_group.id

    try:
        db_session.add(project)
        db_session.add(auto_assign_group)
        db_session.commit()

        if debug:
            all_students = User.query.filter_by(user_type="student").all()[:12]
            for student in all_students:
                stud_to_proj = StudentToProject(project.project_id, student.id,
                                                "")
                stud_to_aass = StudentToGroup(group_id=auto_assign_group.id,
                                              user_id=student.id)

                try:
                    db_session.add(stud_to_proj)
                    db_session.add(stud_to_aass)
                    db_session.commit()
                except:
                    continue
    except:
        return url_for("projects",
                       error="Something went wrong, try again a little later.")
    else:
        return url_for("project",
                       project_id=project.project_id,
                       success="That project was successfully created.")
Esempio n. 14
0
	def assign_autoassign(self):
		print("hello world")
		autoAssign_group = Group.query.filter_by(id=self.autoAssign_group_id).first()

		no_place = []

		members = autoAssign_group.get_members()

		numberOfMembers = len(members)

		left_overs = numberOfMembers % 3
		max_groups = 3

		if max_groups in [0, 1]:
			groups = [members]

		else:

			groups = []

			while len(groups) <= max_groups and numberOfMembers >= 1:
				print("GROUPS", len(groups) <= max_groups, len(groups), max_groups)
				print("MEMBERS", numberOfMembers > 1, numberOfMembers)

				#print(len(groups), max_groups)
				group = []
				found_group = False
				# Loop each member
				for x in range(numberOfMembers):
					# get the current member
					member = members[x]
					print("Found Member: ", member)
					group.append(member)

					schedule = json.loads(member.schedule)

					for y in range(numberOfMembers):

						member2 = members[y]
						schedule2 = json.loads(member2.schedule)

						if member == member2:
							continue
						
						print("TESTING MEMBER 2:", member2)

						compare = compareSchedules(schedule, schedule2)

						if not compare is False:
							print("Found Member: ", member2)

							if not len(compare[0]) > 2:
								continue

							group.append(member2)
							new_schedule = compare[0]

							for z in range(numberOfMembers):
								member3 = members[z]

								if member3 == member2 or member3 == member:
									continue

								print("TESTING MEMBER 3:", member3)
								final_schedule = compareSchedules(new_schedule, json.loads(member3.schedule))

								if not final_schedule is False:
									print("Found Member: ", member3)
									group.append(member3)
									groups.append(group)
									found_group = True

									if numberOfMembers == 3:
										numberOfMembers = 0

									break
								
								if left_overs == 2:
									groups.append(group)
									left_overs = 0
									found_group = True
									break


							if len(group) == 3 or found_group:
								break


					if found_group:
						break
					elif len(group) < 3:
						print("no group")
						no_place.append(member)
						print(no_place)
						members.remove(member)
						numberOfMembers = len(members)
						break

				if found_group:
					for student in group:
						members.remove(student)
					
					numberOfMembers = len(members)
					if numberOfMembers == 3:
						groups.append(members)
						members = []
						break

				if len(groups) == max_groups and 1 <= len(no_place) <= 4:
					groups.append(no_place)
					no_place = []
					print("no_place reset")
					break

			if not no_place == []:
				if len(no_place) == 1 and len(groups[-1]) < 4:
					groups[-1].append(no_place[0])
				elif len(groups[-1]) >= 4:
					groups.append([no_place[0]])
				else:
					for i in range(0, len(no_place), 3):
						print("no place %s " % i, no_place[i:i + 3])
						groups.append(no_place[i:i + 3])

		rows_to_add = []
		for i, group in enumerate(groups, start=1):
			groupObj = Group("Group #%s" % (i), self.project_id, "Describe your project here!")
			try:
				db_session.add(groupObj)
				db_session.commit()
			except:
				db_session.rollback()
				return False

			for user in group:
				stu_to_group = StudentToGroup(group_id=groupObj.id, user_id=user.id)
				rows_to_add.append(stu_to_group)


		db_session.delete(autoAssign_group)
		db_session.commit()
		db_session.add_all(rows_to_add)
		self.autoAssign_group_id = None
		db_session.commit()

		try:
			db_session.delete(autoAssign_group)
			db_session.add_all(rows_to_add)
			self.autoAssign_group_id = None
			db_session.commit()
		except:
			db_session.rollback()
			return False
		else:
			return True
Esempio n. 15
0
def register():
    username = request.form['username']
    email = request.form['email']
    password = generate_password_hash(request.form['password'])
    id = randomString(50) if not 'uid' in request.form else request.form['uid']
    user_type = request.form['user_type']
    activation_token = randomString(50)

    userObject = User.query.filter_by(email=email).first()
    username_exists = User.query.filter_by(username=username).count()

    if userObject is None:
        if username_exists:
            return redirect(
                url_for(
                    'login',
                    error=
                    "There's already someone with that username registered."))

        schedule = {}
        if user_type == "student":
            days = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"]

            for day in days:
                if not request.form['{}_start'.format(
                        day)] == "" and not request.form['{}_end'.format(
                            day)] == "":
                    start_time = datetime.datetime.strptime(
                        request.form['{}_start'.format(day)], "%I:%M %p")
                    end_time = datetime.datetime.strptime(
                        request.form['{}_end'.format(day)], "%I:%M %p")

                    if start_time.time() < end_time.time():
                        if (end_time -
                                start_time) > datetime.timedelta(hours=2):
                            schedule[day] = [
                                start_time.strftime("%H:%M"),
                                end_time.strftime("%H:%M")
                            ]
                        else:
                            return redirect(
                                url_for(
                                    'login',
                                    error=
                                    "Please ensure you choose a duration of at least 3 hours."
                                ))
                    else:
                        return redirect(
                            url_for(
                                'login',
                                error=
                                "There was an issue processing the schedule you provided. Please try again."
                            ))

            if len(schedule.keys()) < 3:
                return redirect(
                    url_for(
                        'login',
                        error=
                        "Please ensure you choose at least 3 days to meet."))

        user = User(username=username,
                    password=password,
                    email=email,
                    id=id,
                    user_type=user_type,
                    activation_token=activation_token,
                    schedule=schedule)
    else:
        return redirect(
            url_for(
                'login',
                error="There's already someone with that email registered."))
        # userObject.username = username
        # userObject.password = password
        # userObject.uid = id
        # userObject.activation_token = activation_token
        # userObject.
        # user = userObject
    try:
        db_session.add(user)
        db_session.commit()
        login_user(user)
    except Exception as e:
        print(e)
        return redirect(
            url_for('login', error="There was an issue signing you up"))

    return redirect(url_for("projects", macro_id=None))
Esempio n. 16
0
def addItem():
    if request.method == "GET":
        item_types = itemType.query.all()
        type_ids = [item_type.id for item_type in item_types]

        typeCategories = {}
        typeCategoryIDs = []
        for type_id in type_ids:
            typeCategories[type_id] = itemCategory.query.filter_by(
                type_id=type_id).order_by(itemCategory.sort_order.asc()).all()
            typeCategoryIDs += [
                category.id
                for category in itemCategory.query.filter_by(type_id=type_id).
                order_by(itemCategory.sort_order.asc()).all()
            ]

        print(typeCategoryIDs)
        typeSubcategories = {}
        for category_id in typeCategoryIDs:
            typeSubcategories[category_id] = itemSubcategory.query.filter_by(
                category_id=category_id).order_by(
                    itemSubcategory.sort_order.asc()).all()

        print(typeSubcategories)
        return render_template("items/addItem.html",
                               itemTypes=item_types,
                               typeCategories=typeCategories,
                               typeSubcategories=typeSubcategories)
    elif request.method == "POST":
        item_type = request.form['item_type']
        item_category = request.form['item_category']
        item_subcategory = request.form['item_subcategory']

        item_attributes = request.form['item_attributes']
        item_quantity = int(request.form['quantity'])
        items = []
        print(current_user.id)
        for i in range(0, item_quantity):
            item_id = randomString(10)
            new_item = Item(item_id,
                            item_type,
                            item_category,
                            item_subcategory,
                            entered_by=current_user.id,
                            item_attributes=item_attributes)

            item_title = "Category: " + new_item.getCategoryName(
            ) + "\nSubcategory: " + new_item.getSubcategoryName()
            size = ""
            try:
                attrs = json.loads(item_attributes)
            except json.decoder.JSONDecodeError:
                attrs = {}

            if not item_attributes == "":
                size = attrs['Size'] if "Size" in attrs else ""
                if "Size" in attrs:
                    del attrs['Size']
                else:
                    size = attrs[
                        'Mens_Pant_Sizes'] if "Mens_Pant_Sizes" in attrs else ""
                    if "Mens_Pant_Sizes" in attrs:
                        del attrs['Mens_Pant_Sizes']

                    size = attrs[
                        'Womens_Pant_Sizes'] if "Womens_Pant_Sizes" in attrs else ""
                    if "Womens_Pant_Sizes" in attrs:
                        del attrs['Womens_Pant_Sizes']

                for attr, value in attrs.items():
                    item_title += "\n%s: %s\n" % (attr.replace("_",
                                                               " "), value)

            color_to_use = ""
            colors = ['red', 'blue', 'green', 'orange', 'purple']
            current_color = GioOption.query.filter_by(
                option_key="color").first()
            color_to_use = current_color.option_value
            if datetime.datetime.utcnow(
            ) >= current_color.updated + datetime.timedelta(weeks=1):
                color_num = colors.index(current_color.option_value) + 1
                if color_num > len(colors) - 1:
                    color_num = 0
                new_color = colors[color_num]
                current_color.option_value = new_color

                color_to_use = new_color
                db_session.add(current_color)
                db_session.commit()

            new_item.tag_color = color_to_use
            create_ticket(item_id + ".png", item_title, item_id,
                          new_item.price, color_to_use, size)
            items.append(new_item)

        db_session.add_all(items)
        db_session.commit()

        try:
            db_session.add_all(items)
            db_session.commit()
        except:
            return jsonify(False)
        else:
            return jsonify([x.as_dict() for x in items])
Esempio n. 17
0
def editSubcategory(sub_id=None):
    oldSubcategory = itemSubcategory.query.filter_by(id=sub_id).first()

    if oldSubcategory == None:
        return redirect(url_for('items', error="That category doesn't exist."))

    if request.method == "GET":
        error = request.args.get('error', default=None, type=str)
        success = request.args.get('success', default=None, type=str)
        categories = itemCategory.query.all()
        attributes = itemAttribute.query.all()
        subcatAttrs = attr_to_subcategory.query.filter_by(
            subcategory_id=sub_id).all()

        attr_ids = [attr.attr_id for attr in subcatAttrs]
        item_categories = []
        for item_category in categories:
            item_categories.append([item_category.id, item_category.name])

        print()
        return render_template("subcategories/editSubcategory.html",
                               subcategory=oldSubcategory,
                               categories=item_categories,
                               attributes=attributes,
                               current_attrs=attr_ids,
                               error=error,
                               success=success)
    elif request.method == "POST":
        formDict = dict(request.form)
        print(formDict)
        name = request.form['name']
        button_color = request.form['button_color']
        sort_order = request.form['sort_order']
        del formDict['name']

        if 'icon' in request.files:
            icon = request.files['icon']

            if not icon.filename == '':
                oldSubcategory.icon = icon.filename
                icon.save(
                    os.path.join(application.config['UPLOAD_FOLDER'],
                                 icon.filename))

        oldSubcategory.category_id = int(request.form['category'])
        del formDict['category']
        oldSubcategory.name = name
        oldSubcategory.button_color = button_color
        oldSubcategory.sort_order = sort_order
        oldPrice = ItemPrice.query.filter_by(item_subcategory=sub_id).first()
        oldPrice.price = request.form['price']
        oldPrice.item_category = int(request.form['category'])
        del formDict['price']

        removedAttr = attr_to_subcategory.query.filter_by(
            subcategory_id=sub_id).delete()
        db_session.commit()

        new_attrs = []
        for attr, value in formDict.items():
            if value == "on":
                new_attrs.append(attr_to_subcategory(int(sub_id), attr))

        try:
            db_session.add_all(new_attrs)
            db_session.add(oldSubcategory)
            db_session.add(oldPrice)
            db_session.commit()
        except:
            return redirect(
                url_for("items",
                        error="There was an error editing that subcategory"))
        else:
            return redirect(
                url_for("items",
                        success="The subcategory %s was successfully added" %
                        (name)))
Esempio n. 18
0
def addSubcategory():
    if request.method == "GET":
        error = request.args.get('error', default=None, type=str)
        success = request.args.get('success', default=None, type=str)
        categories = itemCategory.query.all()
        attributes = itemAttribute.query.all()

        category_withTypes = []
        for category in categories:
            cat_type = itemType.query.filter_by(
                id=category.type_id).first().name
            category_withTypes.append(
                [category.id, cat_type + " - " + category.name])

        return render_template("subcategories/addSubcategory.html",
                               categories=category_withTypes,
                               attributes=attributes,
                               error=error,
                               success=success)
    elif request.method == "POST":
        formDict = dict(request.form)
        print(formDict)
        parent_category = itemCategory.query.filter_by(
            id=request.form['category']).first()
        name = request.form['name']
        price = request.form['price']
        sort_order = request.form[
            'sort_order'] if not request.form['sort_order'] == "" else 999999
        del formDict['name']
        del formDict['category']
        del formDict['price']
        del formDict['button_color']
        del formDict['sort_order']

        if request.files['icon'].filename == "":
            return redirect(
                url_for("addSubcategory",
                        error="You need to add an icon for the subcategory"))

        file = request.files['icon']
        file.save(
            os.path.join(application.config['UPLOAD_FOLDER'], file.filename))

        button_color = request.form['button_color']
        new_subcategory = itemSubcategory(category_id=parent_category.id,
                                          name=name,
                                          icon=file.filename,
                                          button_color=button_color,
                                          sort_order=sort_order)
        db_session.add(new_subcategory)
        db_session.commit()

        subcategory_price = ItemPrice(item_type=parent_category.type_id,
                                      category=parent_category.id,
                                      subcategory=new_subcategory.id,
                                      price=price)

        new_attrs = []
        for attr, value in formDict.items():
            if value == "on":
                new_attrs.append(
                    attr_to_subcategory(new_subcategory.id, int(attr)))

        db_session.add(subcategory_price)
        db_session.commit()
        try:
            db_session.add_all(new_attrs)
            db_session.add(new_subcategory)
            db_session.add(subcategory_price)
            db_session.commit()
        except:
            return redirect(
                url_for("items",
                        error="There was an error adding that Subcategory"))
        else:
            return redirect(
                url_for("items",
                        success="The Subcategory %s was successfully added" %
                        (name)))