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..9bfa85708 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -9,18 +9,15 @@ migrate = Migrate() load_dotenv() - def create_app(test_config=None): app = Flask(__name__) app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False if test_config is None: - app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( - "SQLALCHEMY_DATABASE_URI") + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_DATABASE_URI") else: app.config["TESTING"] = True - app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get( - "SQLALCHEMY_TEST_DATABASE_URI") + app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("SQLALCHEMY_TEST_DATABASE_URI") # Import models here for Alembic setup from app.models.task import Task @@ -30,5 +27,11 @@ 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) + + from app.models.task import Task + from app.models.goal import Goal return app diff --git a/app/models/goal.py b/app/models/goal.py index 8cad278f8..1c4ac8bbc 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -4,3 +4,5 @@ class Goal(db.Model): goal_id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + tasks = db.relationship("Task", back_populates="goal") \ No newline at end of file diff --git a/app/models/task.py b/app/models/task.py index 39c89cd16..58666d309 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -4,3 +4,8 @@ class Task(db.Model): task_id = db.Column(db.Integer, primary_key=True) + title = db.Column(db.String) + description = db.Column(db.String) + completed_at = db.Column(db.DateTime, nullable=True) + goal_id = db.Column(db.Integer, db.ForeignKey('goal.goal_id'), nullable=True) + goal = db.relationship("Goal", back_populates="tasks") diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..50ba9771f 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,292 @@ -from flask import Blueprint +from flask.wrappers import Response +from app import db +from app.models.task import Task +from app.models.goal import Goal +from flask import Blueprint, jsonify, make_response, request +from datetime import datetime, timezone +import os +from slack_sdk import WebClient +from slack_sdk.errors import SlackApiError +#create the blueprint for the endpoints +tasks_bp = Blueprint("tasks", __name__, url_prefix="/tasks") +goals_bp = Blueprint("goals", __name__, url_prefix="/goals") + +#Create a Task: Valid Task With null completed_at +@tasks_bp.route("", methods=["POST"]) +def create_task(): + request_body = request.get_json() + + if "title" not in request_body or "description" not in request_body or "completed_at" not in request_body: + return make_response({"details": "Invalid data"}, 400) + + new_task = set_task(request_body) + db.session.add(new_task) + db.session.commit() + + response = {} + response['task'] = format_task_dictionary(new_task) + return make_response(response, 201) + +################### +#Helper functions for tasks +def set_task(request_body): + new_task = Task(title=request_body["title"], + description=request_body["description"]) + + if request_body["completed_at"] is not None: + new_task.completed_at=request_body["completed_at"] + else: + new_task.completed_at = None + + return new_task + +def format_task_dictionary(new_task): + task = {} + task['id'] = new_task.task_id + task['title'] = new_task.title #request_body["title"] + task['description'] = new_task.description #request_body["description"] + if new_task.completed_at is not None: + task['is_complete'] = True + else: + task['is_complete'] = False + + if new_task.goal_id is not None: + task['goal_id'] = new_task.goal_id + + return task +#################### + +#Get Tasks: Getting Saved Tasks +@tasks_bp.route("", methods=["GET"]) +def get_tasks(): + + #this can go in a helper function + sort_query = request.args.get("sort") + if(sort_query == "asc"): + tasks = Task.query.order_by(Task.title).all() + elif(sort_query == "desc"): + tasks = Task.query.order_by(Task.title.desc()).all() + else: + tasks = Task.query.all() + + response = [] + for task in tasks: + task_dict = format_task_dictionary(task) + response.append(task_dict) + + return jsonify(response) + +#Get a Task +@tasks_bp.route("/", methods=["GET"]) +def get_task(task_id): + task = Task.query.get(task_id) + + if task is None: + return make_response("Not Found", 404) + + response = {} + response['task'] = format_task_dictionary(task) + return response + +#Update One Task +@tasks_bp.route("/", methods=["PUT"]) +def update_task(task_id): + task = Task.query.get(task_id) + + if task is None: + return make_response(f"Task {task_id} not found", 404) + + form_data = request.get_json() + task.title = form_data["title"] + task.description = form_data["description"] + + db.session.commit() + + response = {} + response['task'] = format_task_dictionary(task) + return make_response(response, 200) + + +# Delete One Task +@tasks_bp.route("/", methods=["DELETE"]) +def delete_task(task_id): + task = Task.query.get(task_id) + if task is None: + return make_response(f"Task {task_id} not found", 404) + response = {"details": f'Task {task.task_id} "{task.title}" successfully deleted' } + db.session.delete(task) + db.session.commit() + return make_response(response, 200) + + +#Mark Complete +@tasks_bp.route("//mark_complete", methods=["PATCH"]) +def mark_complete(task_id): + + #set up the token and client + slack_token = os.environ["SLACK_API_TOKEN"] + client = WebClient(token=slack_token) + + task = Task.query.get(task_id) + if task is None: + return make_response("Not Found", 404) + + response_json = {} + + task.completed_at = datetime.now(timezone.utc) + db.session.commit() + + response_json["task"]= format_task_dictionary(task) + + try: + response = client.chat_postMessage( + channel="task-notifications", + text=f"Someone just completed the task {task.title} :tada:") + + except SlackApiError as e: + # You will get a SlackApiError if "ok" is False + assert e.response["error"] # str like 'invalid_auth', 'channel_not_found' + # + return make_response(response_json, 200) + +#Mark Incomplete +@tasks_bp.route("//mark_incomplete", methods=["PATCH"]) +def mark_incomplete(task_id): + task = Task.query.get(task_id) + if task is None: + return make_response("Not Found", 404) + + response = {} + task_dict = {} + + task.completed_at = None + response["task"] = format_task_dictionary(task) + return make_response(response, 200) + +############--------------------------------------------------------- + +#Create a Goal +@goals_bp.route("", methods=["POST"]) +def create_goal(): + request_body = request.get_json() + + if "title" not in request_body: + return make_response({"details": "Invalid data"}, 400) + + new_goal = Goal(title=request_body["title"]) + db.session.add(new_goal) + db.session.commit() + + response = {} + response["goal"] = format_goal_dictionary(new_goal) + + return make_response(response, 201) + +############ +def format_goal_dictionary(new_goal): + goal = {} + goal['id'] = new_goal.goal_id + goal['title'] = new_goal.title + + return goal +############ + +#Get Goals +@goals_bp.route("", methods=["GET"]) +def get_goals(): + + sort_query = request.args.get("sort") + if(sort_query == "asc"): + goals = Goal.query.order_by(Goal.title).all() + elif(sort_query == "desc"): + goals = Goal.query.order_by(Goal.title.desc()).all() + else: + goals = Goal.query.all() + + response = [] + + for goal in goals: + goal_dict = format_goal_dictionary(goal) + response.append(goal_dict) + + return jsonify(response) + +#Get a Goal +@goals_bp.route("/", methods=["GET"]) +def get_goal(goal_id): + goal = Goal.query.get(goal_id) + + if goal is None: + return make_response("Not Found", 404) + + response = {} + response["goal"] = format_goal_dictionary(goal) + return jsonify(response) + +#Update One Goal +@goals_bp.route("/", methods=["PUT"]) +def update_goal(goal_id): + goal = Goal.query.get(goal_id) + + if goal is None: + return make_response(f"Goal {goal_id} not found", 404) + + form_data = request.get_json() + goal.title = form_data["title"] + db.session.commit() + + response = {} + response["goal"] = format_goal_dictionary(goal) + return make_response(response, 200) + + +# Delete One Goal +@goals_bp.route("/", methods=["DELETE"]) +def delete_goal(goal_id): + goal = Goal.query.get(goal_id) + if goal is None: + return make_response(f"Goal {goal_id} not found", 404) + response = {"details": f'Goal {goal.goal_id} "{goal.title}" successfully deleted' } + db.session.delete(goal) + db.session.commit() + return make_response(response, 200) + +@goals_bp.route("//tasks", methods=["POST"]) +def post_task_ids_to_goal(goal_id): + goal = Goal.query.get(goal_id) #we grabbed the goal for the provided id + + if goal is None: #error checking + return make_response("", 404) + + request_body = request.get_json() #grab form data + task_ids = request_body["task_ids"] #storing the list in a cleaner variable reference + + for task in range(len(task_ids)): #for each index in this list + this_task = Task.query.get(task_ids[task]) #get one task at a time + this_task.goal_id = goal.goal_id #set its goal id to the id of this goal + db.session.commit() + + response = {"id": goal.goal_id, "task_ids": task_ids} + return make_response(response, 200) + + +@goals_bp.route("//tasks", methods=["GET"]) +def get_tasks_for_specific_goals(goal_id): + + #get the goal cuz we need its details + #get tasks that have that goal id + #if no tasks have that goal id, return a specific response + + goal = Goal.query.get(goal_id) #grab the specific goal + if goal is None: + return make_response("", 404) + + tasks = Task.query.filter(Task.goal_id==goal_id).all() + response = {"id": goal.goal_id, "title": goal.title, "tasks": []} + + for task in tasks: + task_dict = format_task_dictionary(task) + response["tasks"].append(task_dict) + + return make_response(response, 200) 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/594600e086f8_.py b/migrations/versions/594600e086f8_.py new file mode 100644 index 000000000..7f00af782 --- /dev/null +++ b/migrations/versions/594600e086f8_.py @@ -0,0 +1,32 @@ +"""empty message + +Revision ID: 594600e086f8 +Revises: bbaf9faf71fd +Create Date: 2021-10-29 18:43:10.341092 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision = '594600e086f8' +down_revision = 'bbaf9faf71fd' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('task', 'completed_at', + existing_type=postgresql.TIMESTAMP(), + nullable=True) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.alter_column('task', 'completed_at', + existing_type=postgresql.TIMESTAMP(), + nullable=False) + # ### end Alembic commands ### diff --git a/migrations/versions/a4aa041dcbb4_.py b/migrations/versions/a4aa041dcbb4_.py new file mode 100644 index 000000000..97242ae37 --- /dev/null +++ b/migrations/versions/a4aa041dcbb4_.py @@ -0,0 +1,28 @@ +"""empty message + +Revision ID: a4aa041dcbb4 +Revises: 594600e086f8 +Create Date: 2021-11-01 19:56:53.524328 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'a4aa041dcbb4' +down_revision = '594600e086f8' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('goal', sa.Column('title', sa.String(), nullable=True)) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_column('goal', 'title') + # ### end Alembic commands ### diff --git a/migrations/versions/bbaf9faf71fd_.py b/migrations/versions/bbaf9faf71fd_.py new file mode 100644 index 000000000..abae66b32 --- /dev/null +++ b/migrations/versions/bbaf9faf71fd_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: bbaf9faf71fd +Revises: +Create Date: 2021-10-29 18:30:27.732665 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'bbaf9faf71fd' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('goal', + sa.Column('goal_id', sa.Integer(), nullable=False), + sa.PrimaryKeyConstraint('goal_id') + ) + op.create_table('task', + sa.Column('task_id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.Column('completed_at', sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint('task_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/migrations/versions/fc237ba8ea5a_.py b/migrations/versions/fc237ba8ea5a_.py new file mode 100644 index 000000000..462d47ae0 --- /dev/null +++ b/migrations/versions/fc237ba8ea5a_.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: fc237ba8ea5a +Revises: a4aa041dcbb4 +Create Date: 2021-11-02 11:17:24.610765 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'fc237ba8ea5a' +down_revision = 'a4aa041dcbb4' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('goal_id', sa.Integer(), nullable=True)) + op.create_foreign_key(None, 'task', 'goal', ['goal_id'], ['goal_id']) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_constraint(None, 'task', type_='foreignkey') + op.drop_column('task', 'goal_id') + # ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt index cfdf74050..ca4fe5324 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,12 +1,17 @@ +aiohttp==3.8.0 +aiosignal==1.2.0 alembic==1.5.4 +async-timeout==4.0.0a3 attrs==20.3.0 autopep8==1.5.5 certifi==2020.12.5 chardet==4.0.0 +charset-normalizer==2.0.7 click==7.1.2 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 +frozenlist==1.2.0 gunicorn==20.1.0 idna==2.10 iniconfig==1.1.1 @@ -14,6 +19,7 @@ itsdangerous==1.1.0 Jinja2==2.11.3 Mako==1.1.4 MarkupSafe==1.1.1 +multidict==5.2.0 packaging==20.9 pluggy==0.13.1 psycopg2-binary==2.8.6 @@ -26,7 +32,13 @@ python-dotenv==0.15.0 python-editor==1.0.4 requests==2.25.1 six==1.15.0 +slack==0.0.2 +slack-sdk==3.11.2 +slackclient==2.9.3 SQLAlchemy==1.3.23 toml==0.10.2 +typing-extensions==3.10.0.2 urllib3==1.26.4 +websocket-client==0.54.0 Werkzeug==1.0.1 +yarl==1.7.0 diff --git a/tests/test_wave_05.py b/tests/test_wave_05.py index 6ba60c6fa..03c167c8c 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 @@ -41,18 +42,14 @@ def test_get_goal(client, one_goal): } } -@pytest.mark.skip(reason="test to be completed by student") def test_get_goal_not_found(client): - pass # Act response = client.get("/goals/1") 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 @@ -70,31 +67,49 @@ def test_create_goal(client): "title": "My New Goal" } } - -@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": "Update 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": "Update Goal Title" + } + } + goal = Goal.query.get(1) + assert goal.title == "Update Goal Title" + + +# def test_update_task_not_found(client): +# # Act +# response = client.put("/tasks/1", json={ +# "title": "Updated Task Title", +# "description": "Updated Test Description", +# }) +# response_body = response.get_json() + +# # Assert +# assert response.status_code == 404 +# assert response_body == None + -@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("/goals/1", json={ + "title": "Updated Goal Title" + }) + 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 +128,15 @@ 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") def test_delete_goal_not_found(client): - pass - # Act - # ---- Complete Act Here ---- + response = client.delete("/goals/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):