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..1d599fe7f 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,9 +1,8 @@ from flask import Flask -from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate -import os +from flask_sqlalchemy import SQLAlchemy from dotenv import load_dotenv - +import os db = SQLAlchemy() migrate = Migrate() @@ -30,5 +29,9 @@ def create_app(test_config=None): migrate.init_app(app, db) # Register Blueprints here + from .routes import tasks_bp + app.register_blueprint(tasks_bp) + from .routes import goals_bp + app.register_blueprint(goals_bp) return app diff --git a/app/models/goal.py b/app/models/goal.py index 8cad278f8..4da39ab54 100644 --- a/app/models/goal.py +++ b/app/models/goal.py @@ -3,4 +3,13 @@ class Goal(db.Model): - goal_id = db.Column(db.Integer, primary_key=True) + goal_id = db.Column(db.Integer, primary_key=True, autoincrement=True) + title = db.Column(db.String) + # 'Task' looks at class in python and loads multiple of those (this is like a pseudo column) + tasks = db.relationship('Task', backref='goal', lazy=True) + + def to_dict(self): + return { + "id": self.goal_id, + "title": self.title, + } diff --git a/app/models/task.py b/app/models/task.py index 39c89cd16..b928b7b15 100644 --- a/app/models/task.py +++ b/app/models/task.py @@ -1,6 +1,37 @@ -from flask import current_app from app import db +from flask import current_app +from sqlalchemy import DateTime class Task(db.Model): - task_id = db.Column(db.Integer, primary_key=True) + task_id = db.Column(db.Integer, primary_key=True, autoincrement=True) + title = db.Column(db.String) + description = db.Column(db.String) + completed_at = db.Column(db.DateTime, nullable=True) + + # lowercase 'goal.id' looks at a table in your db + goal_id = db.Column(db.Integer, db.ForeignKey( + 'goal.goal_id'), nullable=True) + + def is_complete(self): + if self.completed_at: + return True + else: + return False + + def to_json(self): + return { + "id": self.task_id, + "title": self.title, + "description": self.description, + "is_complete": self.is_complete() + } + + def with_goal(self): + return { + "id": self.task_id, + "title": self.title, + "description": self.description, + "is_complete": self.is_complete(), + "goal_id": self.goal_id + } diff --git a/app/routes.py b/app/routes.py index 8e9dfe684..7e0ee3604 100644 --- a/app/routes.py +++ b/app/routes.py @@ -1,2 +1,217 @@ -from flask import Blueprint +from app import db +from app.models.task import Task +from datetime import datetime +from flask import request, Blueprint, make_response, jsonify +import requests +import os +# from slack_sdk import WebClient +# from slack_sdk.errors import SlackApiError +from app.models.goal import Goal + +goals_bp = Blueprint( + "goals", __name__, url_prefix="/goals") +tasks_bp = Blueprint( + "tasks", __name__, url_prefix="/tasks") + + +# ------------------------- +# WAVE 1 - TASK ENDPOINTS +# ------------------------- +@tasks_bp.route("", methods=["POST"], strict_slashes=False) +def create_task(): + request_body = request.get_json() + if "title" in request_body and "description" in request_body and "completed_at" in request_body: + new_task = Task( + title=request_body["title"], + description=request_body["description"], + completed_at=request_body["completed_at"] + ) + db.session.add(new_task) + db.session.commit() + return jsonify({"task": new_task.to_json()}), 201 + else: + return make_response({"details": "Invalid data"}, 400) + + +# WAVE 2 +@tasks_bp.route("", methods=["GET"], strict_slashes=False) +def task_index(): + sort_query = request.args.get("sort") + if sort_query == "asc": + tasks = Task.query.order_by(Task.title) + elif sort_query == "desc": + tasks = Task.query.order_by(Task.title.desc()) + else: + tasks = Task.query.all() + tasks_response = [(task.to_json()) for task in tasks] + return make_response(jsonify(tasks_response), 200) + + +# WAVE 1 +@tasks_bp.route("/", methods=["GET"], strict_slashes=False) +def get_one_task(task_id): + task = Task.query.get(task_id) + if task is None: + return make_response("", 404) +# thank you audrey! + elif task.goal_id is None: + return jsonify({"task": task.to_json()}), 200 + else: + return jsonify({"task": task.with_goal()}), 200 + + +@tasks_bp.route("/", methods=["PUT"], strict_slashes=False) +def update_task(task_id): + task = Task.query.get(task_id) + if task is None: + return make_response("", 404) + else: + form_data = request.get_json() + task.title = form_data["title"] + task.description = form_data["description"] + task.completed_at = form_data["completed_at"] + db.session.commit() + return jsonify({"task": task.to_json()}), 200 + + +@tasks_bp.route("/", methods=["DELETE"], strict_slashes=False) +def delete_task(task_id): + task = Task.query.get(task_id) + if task is None: + return make_response("", 404) + else: + db.session.delete(task) + db.session.commit() + task_response = { + "details": f'Task {task.task_id} "{task.title}" successfully deleted'} + return make_response(task_response), 200 + + +# WAVE 3 +@tasks_bp.route("//mark_incomplete", methods=["PATCH"], strict_slashes=False) +def handle_incomplete(task_id): + task = Task.query.get(task_id) + if task is None: + return make_response("", 404) + else: + task.completed_at = None + db.session.commit() + return jsonify({"task": task.to_json()}), 200 + + +@tasks_bp.route("//mark_complete", methods=["PATCH"], strict_slashes=False) +def handle_complete(task_id): + task = Task.query.get(task_id) + if task is None: + return make_response("", 404) + else: + task.completed_at = datetime.now() + db.session.commit() + call_slack_api(task) + return jsonify({"task": task.to_json()}), 200 + + +# WAVE 4 +def call_slack_api(task): + SLACK_TOKEN = os.environ.get("SLACK_BOT_TOKEN") + url = "https://slack.com/api/chat.postMessage" + payload = { + "channel": "task-notifications", + "text": f"Someone just completed the task {task.title}"} + headers = { + "Authorization": f"Bearer {SLACK_TOKEN}", + } + return requests.request("POST", url, headers=headers, data=payload) + +# IGNORE - WORKS BUT USES SLACK BOLT/PYTHON SDK (from slack API docs) instead of requests.package +# def call_slack_api(task): +# client = WebClient(token=os.environ.get("SLACK_BOT_TOKEN")) +# channel_id = "task-notifications" +# # try: +# result = client.chat_postMessage( +# channel=channel_id, +# text=f"Someone just completed the task {task.title}") +# return result + + +# ------------------------- +# WAVE 5 - GOAL ENDPOINTS +# ------------------------- +@goals_bp.route("", methods=["POST"], strict_slashes=False) +def create_goal(): + request_body = request.get_json() + if "title" in request_body: + new_goal = Goal( + title=request_body["title"]) + db.session.add(new_goal) + db.session.commit() + return jsonify({"goal": new_goal.to_dict()}), 201 + return make_response({"details": "Invalid data"}, 400) + + +@goals_bp.route("", methods=["GET"], strict_slashes=False) +def goal_index(): + goals = Goal.query.all() + goals_response = [(goal.to_dict()) for goal in goals] + return make_response(jsonify(goals_response), 200) + + +@goals_bp.route("/", methods=["GET"], strict_slashes=False) +def get_one_goal(goal_id): + goal = Goal.query.get(goal_id) + if goal is None: + return make_response("", 404) + return jsonify({"goal": goal.to_dict()}), 200 + + +@goals_bp.route("/", methods=["PUT"], strict_slashes=False) +def update_goal(goal_id): + goal = Goal.query.get(goal_id) + if goal is None: + return make_response("", 404) + else: + form_data = request.get_json() + goal.title = form_data["title"] + db.session.commit() + return jsonify({"goal": goal.to_dict()}), 200 + + +@goals_bp.route("/", methods=["DELETE"], strict_slashes=False) +def delete_goal(goal_id): + goal = Goal.query.get(goal_id) + if goal is None: + return make_response("", 404) + else: + db.session.delete(goal) + db.session.commit() + goal_response = { + "details": f'Goal {goal.goal_id} "{goal.title}" successfully deleted'} + return make_response(goal_response), 200 + + +# WAVE 6 +@goals_bp.route("//tasks", methods=["POST"], strict_slashes=False) +def sending_list_tasks_to_goal(goal_id): + request_body = request.get_json() + tasks = request_body["task_ids"] + # (db) + goal = Goal.query.get(goal_id) + for task_id in tasks: + task_db_object = Task.query.get(task_id) + goal.tasks.append(task_db_object) + # task_db_object.goal_id = int(goal_id) + db.session.commit() + return {"id": goal.goal_id, + "task_ids": tasks}, 200 + + +@goals_bp.route("//tasks", methods=["GET"], strict_slashes=False) +def getting_tasks_of_one_goal(goal_id): + goal = Goal.query.get(goal_id) + if goal is None: + return make_response("", 404) + tasks = Task.query.join(Goal).filter(Task.goal_id == goal_id).all() + # tasks_response = [] + tasks_response = [(task.with_goal()) for task in tasks] + return{"id": goal.goal_id, "title": goal.title, "tasks": tasks_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/1bb62149cec1_.py b/migrations/versions/1bb62149cec1_.py new file mode 100644 index 000000000..521baf4e9 --- /dev/null +++ b/migrations/versions/1bb62149cec1_.py @@ -0,0 +1,39 @@ +"""empty message + +Revision ID: 1bb62149cec1 +Revises: +Create Date: 2021-05-07 14:05:50.281429 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '1bb62149cec1' +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('task_title', sa.String(), nullable=True), + sa.Column('task_description', sa.String(), nullable=True), + sa.Column('task_completed_at', sa.DateTime(), nullable=True), + 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/214d1c57aeb2_.py b/migrations/versions/214d1c57aeb2_.py new file mode 100644 index 000000000..385332b5c --- /dev/null +++ b/migrations/versions/214d1c57aeb2_.py @@ -0,0 +1,30 @@ +"""empty message + +Revision ID: 214d1c57aeb2 +Revises: 9bb4509ff1ea +Create Date: 2021-05-12 18:31:31.628572 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '214d1c57aeb2' +down_revision = '9bb4509ff1ea' +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/migrations/versions/5b323b3e516c_.py b/migrations/versions/5b323b3e516c_.py new file mode 100644 index 000000000..69749c475 --- /dev/null +++ b/migrations/versions/5b323b3e516c_.py @@ -0,0 +1,38 @@ +"""empty message + +Revision ID: 5b323b3e516c +Revises: 1bb62149cec1 +Create Date: 2021-05-09 00:29:50.225257 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision = '5b323b3e516c' +down_revision = '1bb62149cec1' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('completed_at', sa.DateTime(), nullable=True)) + op.add_column('task', sa.Column('description', sa.String(), nullable=True)) + op.add_column('task', sa.Column('title', sa.String(), nullable=True)) + op.drop_column('task', 'task_completed_at') + op.drop_column('task', 'task_description') + op.drop_column('task', 'task_title') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.add_column('task', sa.Column('task_title', sa.VARCHAR(), autoincrement=False, nullable=True)) + op.add_column('task', sa.Column('task_description', sa.VARCHAR(), autoincrement=False, nullable=True)) + op.add_column('task', sa.Column('task_completed_at', postgresql.TIMESTAMP(), autoincrement=False, nullable=True)) + op.drop_column('task', 'title') + op.drop_column('task', 'description') + op.drop_column('task', 'completed_at') + # ### end Alembic commands ### diff --git a/migrations/versions/9bb4509ff1ea_.py b/migrations/versions/9bb4509ff1ea_.py new file mode 100644 index 000000000..2b9ab7999 --- /dev/null +++ b/migrations/versions/9bb4509ff1ea_.py @@ -0,0 +1,28 @@ +"""empty message + +Revision ID: 9bb4509ff1ea +Revises: 5b323b3e516c +Create Date: 2021-05-11 22:36:48.384281 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '9bb4509ff1ea' +down_revision = '5b323b3e516c' +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/requirements.txt b/requirements.txt index cfdf74050..6a684c4be 100644 --- a/requirements.txt +++ b/requirements.txt @@ -26,6 +26,7 @@ python-dotenv==0.15.0 python-editor==1.0.4 requests==2.25.1 six==1.15.0 +slack-sdk==3.5.1 SQLAlchemy==1.3.23 toml==0.10.2 urllib3==1.26.4