Skip to content

Madeline/backup branch #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
from flask import Flask
from flask import Flask, request, jsonify
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
from .db import db, migrate
from .models import task, goal
from .routes.task_routes import tasks_bp
from .routes.slack_routes import slack_bp
from .routes.goal_routes import goals_bp
import os

def create_app(config=None):
Expand All @@ -18,5 +23,34 @@ def create_app(config=None):
migrate.init_app(app, db)

# Register Blueprints here
app.register_blueprint(tasks_bp)
app.register_blueprint(slack_bp)
app.register_blueprint(goals_bp)

return app

# from flask import Flask
# from .db import db, migrate
# from .models import task, goal
# from .routes.task_routes import tasks_bp
# import os

# def create_app(config=None):
# app = Flask(__name__)

# app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('SQLALCHEMY_DATABASE_URI')

# if config:
# # Merge `config` into the app's configuration
# # to override the app's default settings for testing
# app.config.update(config)

# db.init_app(app)
# migrate.init_app(app, db)

# # Register Blueprints here
# app.register_blueprint(tasks_bp)

# return app

41 changes: 40 additions & 1 deletion app/models/goal.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,44 @@
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.orm import Mapped, mapped_column, relationship
from datetime import datetime
from app.routes.utilities_routes import create_model, validate_model, check_for_completion
from typing import Optional
from sqlalchemy import ForeignKey
# from app.models.task import Task
from ..db import db

class Goal(db.Model):
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
title: Mapped[str]
tasks: Mapped[list["Task"]] = relationship("Task",back_populates="goal", lazy=True)
# description=Mapped[str]
# completed_at: Mapped[Optional[datetime]]=mapped_column(nullable = True)


def to_dict(self):
goal_as_dict = {}
goal_as_dict["id"] = self.id
goal_as_dict["title"] = self.title
if self.tasks:
task_ids=[]
task_dictionaries = [task.to_dict() for task in self.tasks]
for task in task_dictionaries:
task_id = task.get("id")
task_ids.append(task_id)
goal_as_dict["task_ids"] = task_ids
else:
goal_as_dict["task_ids"] = []
# task_as_dict["description"] = self.description
# task_as_dict["is_complete"] = check_for_completion(Goal,self)

return goal_as_dict



@classmethod
def from_dict(cls, goal_data):
new_goal = cls(
title=goal_data["title"],
# description=goal_data["description"],
# completed_at=goal_data["completed_at"]
)
return new_goal
34 changes: 33 additions & 1 deletion app/models/task.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,37 @@
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.orm import Mapped, mapped_column, relationship
from ..db import db
from datetime import datetime
from app.routes.utilities_routes import create_model, validate_model, check_for_completion
from typing import Optional
from sqlalchemy import ForeignKey

class Task(db.Model):
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
title: Mapped[str]
description: Mapped[str]
completed_at: Mapped[Optional[datetime]]= mapped_column(nullable = True)
goal_id: Mapped[Optional[int]] = mapped_column(ForeignKey("goal.id"), nullable=True)
goal: Mapped["Goal"] = relationship("Goal", back_populates="tasks")

def to_dict(self):
task_as_dict = {}
task_as_dict["id"] = self.id
task_as_dict["title"] = self.title
task_as_dict["description"] = self.description
task_as_dict["is_complete"] = check_for_completion(Task,self)
if self.goal_id:
task_as_dict["goal_id"] = self.goal_id

return task_as_dict


@classmethod
def from_dict(cls, task_data):
goal_id = task_data.get("goal_id")

new_task = cls(
title=task_data["title"],
description=task_data["description"],
goal_id = goal_id
)
return new_task
96 changes: 95 additions & 1 deletion app/routes/goal_routes.py
Original file line number Diff line number Diff line change
@@ -1 +1,95 @@
from flask import Blueprint
from flask import Blueprint, abort, make_response, request, Response

from app.models.goal import Goal
from app.models.task import Task
from ..db import db
from datetime import datetime
from app.routes.utilities_routes import create_model, validate_model, get_models_with_filters, check_for_completion, delete_model

import requests

goals_bp = Blueprint("goals_bp",__name__, url_prefix= "/goals")


####################################################################
######################### Create FUNCTIONS #########################
####################################################################
@goals_bp.post("")
def create_goal():
request_body = request.get_json()
return create_model(Goal,request_body)

@goals_bp.post("/<goal_id>/tasks")
def post_task_ids_to_goal(goal_id):
request_body = request.get_json()
goal = validate_model(Goal, goal_id)

task_ids = request_body.get("task_ids", [])
for task_id in task_ids:
task = validate_model(Task, task_id)
if task:
goal.tasks.append(task)

db.session.commit()
goal = goal.to_dict()
response_body = {
"id": goal.get("id"),
"task_ids": goal.get("task_ids")
}

return response_body, 200


####################################################################
######################### READ FUNCTIONS #########################
####################################################################
@goals_bp.get("")
def get_goals():
request_arguements = request.args
return get_models_with_filters(Goal, request_arguements)

@goals_bp.get("/<goal_id>")
def get_one_goal(goal_id):
goal = validate_model(Goal, goal_id)
response = {"goal": goal.to_dict()}
return make_response(response, 200)

@goals_bp.get("/<goal_id>/tasks")
def get_tasks_for_specific_goal(goal_id):
goal = validate_model(Goal, goal_id)
goal_as_dict = goal.to_dict()
tasks = [task.to_dict() for task in goal.tasks]

response_body = {
"id": goal_as_dict.get("id"),
"title": goal_as_dict.get('title'),
"tasks": tasks
}
for key, value in goal_as_dict.items():
print("Key is : ", key),
print("Value is :", value)

return response_body, 200

####################################################################
######################### UPDATE FUNCTIONS #########################
####################################################################
@goals_bp.put("/<goal_id>")
def update_goal(goal_id):
goal = validate_model(Goal, goal_id)
request_body = request.get_json()

goal_title = request_body["title"]
db.session.commit()

response_body = {"message": f"Goal #{goal_id} succesfully updated"}
return make_response(response_body, 200)


####################################################################
######################### DELETE FUNCTIONS #########################
####################################################################
@goals_bp.delete("/<goal_id>")
def delete_goal(goal_id):
goal = validate_model(Goal, goal_id)
return delete_model(Goal, goal)
33 changes: 33 additions & 0 deletions app/routes/slack_routes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
from flask import Blueprint, request, jsonify
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
import os

# Initialize the Blueprint
slack_bp = Blueprint('slack_bp', __name__)

# Slack Bot Token from environment variable
SLACK_BOT_TOKEN ="n/a"
client = WebClient(token=SLACK_BOT_TOKEN)

@slack_bp.post('/send_message')
def send_message():
data = request.get_json()
channel = data.get("channel")
message = data.get("message")

if not channel or not message:
return jsonify({"error": "Channel and message are required"}), 400

try:
# Make the chat.postMessage API call
response = client.chat_postMessage(channel=channel, text=message)
return jsonify({"ok": response["ok"], "message": "Message sent successfully!"}), 200
except SlackApiError as e:
# Handle Slack API error and print more details for debugging
error_message = e.response["error"]
print(f"Slack API Error: {error_message}")
return jsonify({"ok": False, "error": error_message}), 400
app.run(debug=True)


Loading