diff --git a/Procfile b/Procfile new file mode 100644 index 000000000..62e430aca --- /dev/null +++ b/Procfile @@ -0,0 +1 @@ +web: gunicorn 'app:create_app()' \ No newline at end of file diff --git a/app/__init__.py b/app/__init__.py index 2764c4cc8..d88bb54c4 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -30,5 +30,8 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here + from .routes import tasks_bp, goals_bp + app.register_blueprint(tasks_bp) + app.register_blueprint(goals_bp) return app diff --git a/app/models/goal.py b/app/models/goal.py index 8cad278f8..c6d5a3fb7 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -3,4 +3,27 @@ class Goal(db.Model): - goal_id = db.Column(db.Integer, primary_key=True) + id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + tasks = db.relationship("Task", back_populates="goal", lazy=True) + + def to_dict(self): + return { + "id": self.id, + "title": self.title + } + + def tasks_to_dict(self): + tasks = [task.goals_to_dict() for task in self.tasks] + return { + "id": self.id, + "title": self.title, + "tasks": tasks + } + + def update_from_dict(self, data): + # Loops through attributes provided by users + for key, value in data.items(): + # Restricts to attributes that are columns + if key in Goal.__table__.columns.keys(): + setattr(self, key, value) \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index 39c89cd16..80355392b 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -3,4 +3,38 @@ class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + title = db.Column(db.String, nullable=False) + description = db.Column(db.String) + completed_at = db.Column(db.DateTime) + goal_id = db.Column(db.Integer, db.ForeignKey('goal.id'), nullable=True) + goal = db.relationship("Goal", back_populates="tasks") + + def check_if_completed(self): + if self.completed_at: + return True + return False + + def to_dict(self): + return { + "id": self.id, + "title": self.title, + "description": self.description, + "is_complete": self.check_if_completed() + } + + def goals_to_dict(self): + return { + "id": self.id, + "goal_id": self.goal_id, + "title": self.title, + "description": self.description, + "is_complete": self.check_if_completed() + } + + def update_from_dict(self, data): + # Loops through attributes provided by user + for key, value in data.items(): + # Restricts to attributes that are table columns + if key in Task.__table__.columns.keys(): + setattr(self, key, value) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..2a202dbf4 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,193 @@ -from flask import Blueprint +from app import db +from flask import Blueprint, request, abort, jsonify, make_response +from datetime import datetime +from dotenv import load_dotenv +import os +import requests +from app.models.task import Task +from app.models.goal import Goal +from app.utils.route_wrappers import require_instance_or_404 +tasks_bp = Blueprint("tasks", __name__, url_prefix="/tasks") +goals_bp = Blueprint("goals", __name__, url_prefix="/goals") + +@tasks_bp.route("", methods=["GET"]) +def get_tasks(): + """ + Retrieve all tasks. Allows for use of query parameters. + Returns JSON list of task dictionaries. """ + query = Task.query # Base query + + # Query params, adding to query where indicated + sort = request.args.get("sort") + if sort == "asc": + query = query.order_by(Task.title) + elif sort == "desc": + query = query.order_by(Task.title.desc()) + + query = query.all() # Final query + + # Returns jsonified list of task dicionaries + return jsonify([task.to_dict() for task in query]), 200 + +@tasks_bp.route("/", methods=["GET"]) +@require_instance_or_404 +def get_task(task): + """Retrieve one stored task by id.""" + if task.goal_id: + return jsonify({"task": task.goals_to_dict()}), 200 + else: + return jsonify({"task": task.to_dict()}), 200 + +@tasks_bp.route("", methods=["POST"]) +def post_task(): + """Create a new task from JSON data.""" + form_data = request.get_json() + + # All fields must be provided + mandatory_fields = ["title", "description", "completed_at"] + for field in mandatory_fields: + if field not in form_data: + return jsonify({"details": "Invalid data"}), 400 + + new_task = Task( + title=form_data["title"], + description=form_data["description"], + completed_at=form_data["completed_at"] + ) + + db.session.add(new_task) + db.session.commit() + return {"task": new_task.to_dict()}, 201 + +@tasks_bp.route("/", methods=["PUT"]) +@require_instance_or_404 +def put_task(task): + """Updates task by id.""" + form_data = request.get_json() + + # Updates object from form data + task.update_from_dict(form_data) + db.session.commit() + + return {"task": task.to_dict()}, 200 + +@tasks_bp.route("//mark_complete", methods=["PATCH"]) +@require_instance_or_404 +def update_task_to_complete(task): + """Updates task at particular id to completed using PATCH.""" + # Make call to Slack API if task newly completed + if not task.check_if_completed(): + slack_api_url = "https://slack.com/api/chat.postMessage" + headers = {"Authorization": "Bearer " + os.environ.get("SLACK_API_KEY")} + param_payload = { + "channel": "task-notifications", + "text": f"Someone has just completed the task {task.title}" + } + + try: + requests.post(slack_api_url, headers=headers, params=param_payload) + + except Exception as e: + return f"Error posting message to Slack: {e}" + + # Change task to completed in db + task.completed_at = datetime.now() + db.session.commit() + + return {"task": task.to_dict()}, 200 + +@tasks_bp.route("/mark_incomplete", methods=["PATCH"]) +@require_instance_or_404 +def update_task_to_incomplete(task): + """Updates task at particular id to incomplete using PATCH.""" + task.completed_at = None + db.session.commit() + return {"task": task.to_dict()}, 200 + +@tasks_bp.route("/", methods=["DELETE"]) +@require_instance_or_404 +def delete_task(task): + """Deletes task by id.""" + db.session.delete(task) + db.session.commit() + + return { + "details": f"Task {task.id} \"{task.title}\" successfully deleted" + }, 200 + +@goals_bp.route("", methods=["GET"]) +def get_goals(): + """Retrieve all stored goals.""" + goals = Goal.query.all() + + return jsonify([goal.to_dict() for goal in goals]), 200 + +@goals_bp.route("/", methods=["GET"]) +@require_instance_or_404 +def get_goal(goal): + """Retrieve one stored goal by id.""" + return jsonify({"goal": goal.to_dict()}), 200 + +@goals_bp.route("", methods=["POST"]) +def create_goal(): + """Create a new goal from JSON data.""" + form_data = request.get_json() + + if "title" not in form_data: + return jsonify({"details": "Invalid data"}), 400 + + new_goal = Goal( + title=form_data["title"] + ) + db.session.add(new_goal) + db.session.commit() + + return jsonify({"goal": new_goal.to_dict()}), 201 + +@goals_bp.route("/", methods=["PUT"]) +@require_instance_or_404 +def update_goal(goal): + """Updates goal by id.""" + form_data = request.get_json() + + goal.update_from_dict(form_data) + db.session.commit() + + return jsonify({"goal": goal.to_dict()}), 200 + +@goals_bp.route("/", methods=["DELETE"]) +@require_instance_or_404 +def delete_goal(goal): + """Deletes goal by id.""" + db.session.delete(goal) + db.session.commit() + + return { + "details": f"Goal {goal.id} \"{goal.title}\" successfully deleted" + }, 200 + +@goals_bp.route("//tasks", methods=["POST"]) +@require_instance_or_404 +def post_tasks_related_to_goal(goal): + """Adds tasks to goal wiht id.""" + form_data = request.get_json() + + for task_id in form_data["task_ids"]: + query = Task.query.get(task_id) + if not query: + continue + goal.tasks.append(query) + + db.session.commit() + + return jsonify({ + "id": goal.id, + "task_ids": [task.id for task in goal.tasks] + }), 200 + +@goals_bp.route("//tasks", methods=["GET"]) +@require_instance_or_404 +def get_tasks_related_to_goal(goal): + """Retrieves all tasks associated with goal id.""" + return jsonify(goal.tasks_to_dict()), 200 \ No newline at end of file diff --git a/app/utils/__init__.py b/app/utils/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/app/utils/route_wrappers.py b/app/utils/route_wrappers.py new file mode 100644 index 000000000..a8dcb0a2c --- /dev/null +++ b/app/utils/route_wrappers.py @@ -0,0 +1,32 @@ +from functools import wraps +from flask import jsonify +from app.models.task import Task +from app.models.goal import Goal + +def require_instance_or_404(endpoint): + """ + Decorator to validate that a requested id of input data exists. + Returns JSON and 404 if not found.""" + @wraps(endpoint) # Makes fn look like func to return + def fn(*args, **kwargs): + if "task_id" in kwargs: + task_id = kwargs.get("task_id", None) + task = Task.query.get(task_id) + + if not task: + return jsonify(None), 404 # null + + kwargs.pop("task_id") + return endpoint(*args, task=task, **kwargs) + + elif "goal_id" in kwargs: + goal_id = kwargs.get("goal_id", None) + goal = Goal.query.get(goal_id) + + if not goal: + return jsonify(None), 404 + + kwargs.pop("goal_id") + return endpoint(*args, goal=goal, **kwargs) + + return fn diff --git a/migrations/README b/migrations/README new file mode 100644 index 000000000..98e4f9c44 --- /dev/null +++ b/migrations/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/migrations/alembic.ini b/migrations/alembic.ini new file mode 100644 index 000000000..f8ed4801f --- /dev/null +++ b/migrations/alembic.ini @@ -0,0 +1,45 @@ +# A generic, single database configuration. + +[alembic] +# template used to generate migration files +# file_template = %%(rev)s_%%(slug)s + +# set to 'true' to run the environment during +# the 'revision' command, regardless of autogenerate +# revision_environment = false + + +# Logging configuration +[loggers] +keys = root,sqlalchemy,alembic + +[handlers] +keys = console + +[formatters] +keys = generic + +[logger_root] +level = WARN +handlers = console +qualname = + +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine + +[logger_alembic] +level = INFO +handlers = +qualname = alembic + +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic + +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/migrations/env.py b/migrations/env.py new file mode 100644 index 000000000..8b3fb3353 --- /dev/null +++ b/migrations/env.py @@ -0,0 +1,96 @@ +from __future__ import with_statement + +import logging +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool +from flask import current_app + +from alembic import context + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config + +# Interpret the config file for Python logging. +# This line sets up loggers basically. +fileConfig(config.config_file_name) +logger = logging.getLogger('alembic.env') + +# add your model's MetaData object here +# for 'autogenerate' support +# from myapp import mymodel +# target_metadata = mymodel.Base.metadata +config.set_main_option( + 'sqlalchemy.url', + str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%')) +target_metadata = current_app.extensions['migrate'].db.metadata + +# other values from the config, defined by the needs of env.py, +# can be acquired: +# my_important_option = config.get_main_option("my_important_option") +# ... etc. + + +def run_migrations_offline(): + """Run migrations in 'offline' mode. + + This configures the context with just a URL + and not an Engine, though an Engine is acceptable + here as well. By skipping the Engine creation + we don't even need a DBAPI to be available. + + Calls to context.execute() here emit the given string to the + script output. + + """ + url = config.get_main_option("sqlalchemy.url") + context.configure( + url=url, target_metadata=target_metadata, literal_binds=True + ) + + with context.begin_transaction(): + context.run_migrations() + + +def run_migrations_online(): + """Run migrations in 'online' mode. + + In this scenario we need to create an Engine + and associate a connection with the context. + + """ + + # this callback is used to prevent an auto-migration from being generated + # when there are no changes to the schema + # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html + def process_revision_directives(context, revision, directives): + if getattr(config.cmd_opts, 'autogenerate', False): + script = directives[0] + if script.upgrade_ops.is_empty(): + directives[:] = [] + logger.info('No changes in schema detected.') + + connectable = engine_from_config( + config.get_section(config.config_ini_section), + prefix='sqlalchemy.', + poolclass=pool.NullPool, + ) + + with connectable.connect() as connection: + context.configure( + connection=connection, + target_metadata=target_metadata, + process_revision_directives=process_revision_directives, + **current_app.extensions['migrate'].configure_args + ) + + with context.begin_transaction(): + context.run_migrations() + + +if context.is_offline_mode(): + run_migrations_offline() +else: + run_migrations_online() diff --git a/migrations/script.py.mako b/migrations/script.py.mako new file mode 100644 index 000000000..2c0156303 --- /dev/null +++ b/migrations/script.py.mako @@ -0,0 +1,24 @@ +"""${message} + +Revision ID: ${up_revision} +Revises: ${down_revision | comma,n} +Create Date: ${create_date} + +""" +from alembic import op +import sqlalchemy as sa +${imports if imports else ""} + +# revision identifiers, used by Alembic. +revision = ${repr(up_revision)} +down_revision = ${repr(down_revision)} +branch_labels = ${repr(branch_labels)} +depends_on = ${repr(depends_on)} + + +def upgrade(): + ${upgrades if upgrades else "pass"} + + +def downgrade(): + ${downgrades if downgrades else "pass"} diff --git a/migrations/versions/b73adc7c9cf5_.py b/migrations/versions/b73adc7c9cf5_.py new file mode 100644 index 000000000..2a357b3e2 --- /dev/null +++ b/migrations/versions/b73adc7c9cf5_.py @@ -0,0 +1,42 @@ +"""empty message + +Revision ID: b73adc7c9cf5 +Revises: +Create Date: 2021-11-04 20:49:26.638587 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'b73adc7c9cf5' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goal', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('task', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=False), + sa.Column('description', sa.String(), nullable=True), + sa.Column('completed_at', sa.DateTime(), nullable=True), + sa.Column('goal_id', sa.Integer(), nullable=True), + sa.ForeignKeyConstraint(['goal_id'], ['goal.id'], ), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('task') + op.drop_table('goal') + # ### end Alembic commands ### diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 6ba60c6fa..0aa8e9a70 100644 --- a/tests/test_wave_05.py +++ b/tests/test_wave_05.py @@ -1,4 +1,5 @@ import pytest +from app.models.goal import Goal def test_get_goals_no_saved_goals(client): # Act @@ -25,7 +26,6 @@ def test_get_goals_one_saved_goal(client, one_goal): } ] - def test_get_goal(client, one_goal): # Act response = client.get("/goals/1") @@ -41,7 +41,7 @@ def test_get_goal(client, one_goal): } } -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): pass # Act @@ -49,10 +49,8 @@ def test_get_goal_not_found(client): response_body = response.get_json() # Assert - # ---- Complete Test ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Test ---- + assert response.status_code == 404 + assert response_body == None def test_create_goal(client): # Act @@ -71,30 +69,40 @@ def test_create_goal(client): } } -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal(client, one_goal): - pass # Act - # ---- Complete Act Here ---- + response = client.put("/goals/1", json={ + "title": "Updated Goal Title" + }) + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # assertion 3 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 200 + assert "goal" in response_body + assert response_body == { + "goal": { + "id": 1, + "title": "Updated Goal Title" + } + } + goal = Goal.query.get(1) + assert goal.title == "Updated Goal Title" -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_update_goal_not_found(client): pass # Act - # ---- Complete Act Here ---- + response = client.put("/tasks/1", json={ + "title": "Updated Task Title", + "description": "Updated Test Description", + }) + + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + assert response_body == None def test_delete_goal(client, one_goal): @@ -113,18 +121,16 @@ def test_delete_goal(client, one_goal): response = client.get("/goals/1") assert response.status_code == 404 -@pytest.mark.skip(reason="test to be completed by student") +# @pytest.mark.skip(reason="test to be completed by student") def test_delete_goal_not_found(client): - pass - # Act - # ---- Complete Act Here ---- + response = client.delete("/tasks/1") + response_body = response.get_json() # Assert - # ---- Complete Assertions Here ---- - # assertion 1 goes here - # assertion 2 goes here - # ---- Complete Assertions Here ---- + assert response.status_code == 404 + assert response_body == None + assert Goal.query.all() == [] def test_create_goal_missing_title(client):