diff --git a/app/__init__.py b/app/__init__.py index 4ab3975b8..25d0c9e96 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -32,5 +32,10 @@ def create_app(test_config=None): migrate.init_app(app, db) #Register Blueprints Here - + from .routes import customers_bp, videos_bp, rentals_bp + + app.register_blueprint(customers_bp) + app.register_blueprint(videos_bp) + app.register_blueprint(rentals_bp) + return app \ No newline at end of file diff --git a/app/models/customer.py b/app/models/customer.py index e3aece97b..4afb2a6b9 100644 --- a/app/models/customer.py +++ b/app/models/customer.py @@ -1,4 +1,10 @@ from app import db class Customer(db.Model): - id = db.Column(db.Integer, primary_key=True) \ No newline at end of file + + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + name = db.Column(db.String) + postal_code = db.Column(db.String) + phone = db.Column(db.String) + registered_at = db.Column(db.DateTime()) + videos = db.relationship("Video", secondary="rental", backref="customers") \ No newline at end of file diff --git a/app/models/rental.py b/app/models/rental.py index 11009e593..d3d814756 100644 --- a/app/models/rental.py +++ b/app/models/rental.py @@ -1,4 +1,10 @@ from app import db +# join table class Rental(db.Model): - id = db.Column(db.Integer, primary_key=True) \ No newline at end of file + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + customer_id = db.Column(db.Integer, db.ForeignKey('customer.id')) + video_id = db.Column(db.Integer, db.ForeignKey('video.id')) + due_date = db.Column(db.DateTime()) + video = db.relationship('Video', backref='rentals') + customer = db.relationship('Customer', backref='rentals') diff --git a/app/models/video.py b/app/models/video.py index 9893a6ef9..5d0a35c92 100644 --- a/app/models/video.py +++ b/app/models/video.py @@ -1,4 +1,20 @@ from app import db class Video(db.Model): - id = db.Column(db.Integer, primary_key=True) \ No newline at end of file + + id = db.Column(db.Integer, primary_key=True, autoincrement=True) + title = db.Column(db.String) + release_date = db.Column(db.DateTime()) + total_inventory = db.Column(db.Integer) + + def to_dict(self): + return { + "id": self.id, + "title" : self.title, + "release_date" : self.release_date, + "total_inventory" : self.total_inventory + } + + @classmethod + def from_dict(cls, values): + return cls(**values) \ No newline at end of file diff --git a/app/routes.py b/app/routes.py index e69de29bb..34118c474 100644 --- a/app/routes.py +++ b/app/routes.py @@ -0,0 +1,413 @@ +from app import db +from app.models.customer import Customer +from app.models.video import Video +from app.models.rental import Rental +from flask import Blueprint, jsonify, request +import datetime +from datetime import timedelta + + +# Establishing due date +NOW = datetime.datetime.now() +DUE_DATE = NOW + timedelta(days=7) + +# Blueprints +customers_bp = Blueprint("customers", __name__, url_prefix="/customers") +videos_bp = Blueprint("videos", __name__, url_prefix="/videos") +rentals_bp = Blueprint("rentals", __name__, url_prefix="/rentals") + +# Customer model helper functions +def display_customer_info(customer): + return { + "id": customer.id, + "name": customer.name, + "postal_code": customer.postal_code, + "phone": customer.phone + } + +def customer_not_found(customer_id): + return {"message" : f"Customer {customer_id} was not found"} + +# Video model helper function +def video_not_found(video_id): + return {"message" : f"Video {video_id} was not found"} + + + +# ******************************** +# *** customers endpoint CRUD *** +# ******************************** +@customers_bp.route("", methods=["GET"]) +def get_all_customers(): + """Lists all existing customers + and details about each customer + """ + + customers = Customer.query.all() + if customers is None: + return jsonify("Not Found"), 404 + + customer_response = [] + for customer in customers: + customer_response.append(display_customer_info(customer)) + + return jsonify(customer_response), 200 + + +@customers_bp.route("/", methods=["GET"]) +def get_one_customer(customer_id): + """Returns details about a specific customer""" + + if not customer_id.isnumeric(): + return jsonify(None), 400 + + customer = Customer.query.get(customer_id) + if customer == None: + return customer_not_found(customer_id), 404 + + response_body = display_customer_info(customer) + + return jsonify(response_body), 200 + + +@customers_bp.route("", methods=["POST"]) +def create_customer(): + """Creates a new customer based on given params""" + + request_body = request.get_json() + if "name" not in request_body: + return {"details": "Request body must include name."}, 400 + if "postal_code" not in request_body: + return {"details": "Request body must include postal_code."}, 400 + if "phone" not in request_body: + return {"details": "Request body must include phone."}, 400 + + new_customer = Customer( + name=request_body["name"], + postal_code=request_body["postal_code"], + phone=request_body["phone"] + ) + + db.session.add(new_customer) + db.session.commit() + + return display_customer_info(new_customer), 201 + + +@customers_bp.route("/", methods=["PUT"]) +def update_existing_customer(customer_id): + """Updates and returns details + about a specific customer + """ + + customer = Customer.query.get(customer_id) + if not customer: + return customer_not_found(customer_id), 404 + + request_body = request.get_json() + if "name" not in request_body or "phone" not in request_body\ + or "postal_code" not in request_body: + return jsonify("Bad Request"), 400 + + customer.name = request_body.get("name") + customer.postal_code = request_body.get("postal_code") + customer.phone = request_body.get("phone") + customer.registered_at = NOW + + db.session.commit() + response_body = ({ + "name": f"{customer.name}", + "postal_code": f"{customer.postal_code}", + "phone": f"{customer.phone}"}) + + return response_body, 200 + + +@customers_bp.route("/", methods=["DELETE"]) +def delete_existing_customer(customer_id): + """Deletes a specific customer""" + + customer = Customer.query.get(customer_id) + if not customer: + return customer_not_found(customer_id), 404 + + if customer.videos: + for rental_record in customer.rentals: + db.session.delete(rental_record) + db.session.delete(customer) + db.session.commit() + response_body = {"message" : f"{customer.name} and all their rental records have been deleted"} + return jsonify(response_body), 200 + + db.session.delete(customer) + db.session.commit() + + return {"id": customer.id}, 200 + + +# ***************************** +# *** videos endpoint CRUD *** +# ***************************** +@videos_bp.route("", methods = ["GET"]) +def get_videos(): + """Lists all existing videos + and details about each video + """ + videos = Video.query.all() + response_body = [video.to_dict() for video in videos] + + return jsonify(response_body), 200 + + +@videos_bp.route("/", methods = ["GET"]) +def get_video(video_id): + """Returns details about + a specific video in the store's inventory + """ + + # check that is valid input (ie an id number) + if not video_id.isnumeric(): + return jsonify(None), 400 + + video = Video.query.get(video_id) + if video == None: + return video_not_found(video_id), 404 + + response_body = video.to_dict() + + return jsonify(response_body), 200 + + +@videos_bp.route("", methods = ["POST"]) +def post_video(): + """Creates a new video based on given params""" + + request_body = request.get_json() + if "title" not in request_body: + return {"details": "Request body must include title."}, 400 + + if "release_date" not in request_body: + return {"details": "Request body must include release_date."}, 400 + + if "total_inventory" not in request_body: + return {"details": "Request body must include total_inventory."}, 400 + + new_video = Video.from_dict(request_body) + + db.session.add(new_video) + db.session.commit() + + response_body = new_video.to_dict() + + return jsonify(response_body), 201 + +@videos_bp.route("", methods = ["PUT"]) +def update_video(video_id): + """Returns details about + a specific video in the store's inventory + """ + + video = Video.query.get(video_id) + if video is None: + return video_not_found(video_id), 404 + + form_data = request.get_json() + + if "title" not in form_data or "total_inventory" not in form_data or "release_date" not in form_data: + return jsonify(None), 400 + + video.title = form_data["title"] + video.total_inventory = form_data["total_inventory"] + video.release_date = form_data["release_date"] + + db.session.commit() + + response_body = video.to_dict() + + return jsonify(response_body), 200 + + +@videos_bp.route("/", methods = ["DELETE"]) +def delete_video(video_id): + """Deletes a specific video.""" + + video = Video.query.get(video_id) + if video is None: + return video_not_found(video_id), 404 + + if video.customers: + for rental_record in video.rentals: + db.session.delete(rental_record) + db.session.delete(video) + db.session.commit() + response_body = {"message" : f"{video.title} and all rental records for that film have been deleted", + } + return jsonify(response_body), 200 + + response_body = {"id" : video.id} + + db.session.delete(video) + db.session.commit() + + return jsonify(response_body), 200 + + +# ******************************** +# *** rentals custom endpoints *** +# ******************************** +@rentals_bp.route("/check-out", methods = ["POST"]) +def post_rentals_check_out(): + """Checks out a video + to a customer and updates the database + """ + + request_body = request.get_json() + if "customer_id" not in request_body: + return {"details": "Request body must include customer_id."}, 400 + + if "video_id" not in request_body: + return {"details": "Request body must include video_id."}, 400 + + # this is the customer id of the customer who has this rental + customer_id = request_body["customer_id"] + video_id = request_body["video_id"] + + # check if customer exists + customer = Customer.query.get(customer_id) + if not customer: + return customer_not_found(customer_id), 404 + + # check if video exists + video = Video.query.get(video_id) + if not video: + return video_not_found(video_id), 404 + + # check if video is in stock + if video.total_inventory - len(video.rentals) < 1: + return {"message": "Could not perform checkout"}, 400 + + # create a new rental instance + new_rental = Rental( + due_date=DUE_DATE, + customer_id=customer.id, + video_id=video.id + ) + + # add new_rental instance to the database + db.session.add(new_rental) + db.session.commit() + + # create a response body + response_body = { + "customer_id": new_rental.customer_id, + "video_id": new_rental.video_id, + "due_date": new_rental.due_date, + "videos_checked_out_count": len(customer.videos), + "available_inventory": video.total_inventory - len(video.rentals) + } + + return jsonify(response_body), 200 + + +@rentals_bp.route("/check-in", methods = ["POST"]) +def post_rentals_check_in(): + """Checks in a video from a customer + and updates the database + """ + + request_body = request.get_json() + # check for valid input + if "customer_id" not in request_body: + return {"details": "Request body must include customer_id."}, 400 + + if "video_id" not in request_body: + return {"details": "Request body must include video_id."}, 400 + + # this is the customer id of the customer who has this rental + customer_id = request_body["customer_id"] + video_id = request_body["video_id"] + + # check if customer exists + customer = Customer.query.get(customer_id) + if not customer: + return customer_not_found(customer_id), 404 + + # check if video exists + video = Video.query.get(video_id) + if not video: + return video_not_found(video_id), 404 + + # logic for counting number of check-ins + checked_in_count = len(video.rentals) - 1 + + rentals = customer.rentals + if not rentals: + return {"message": "No outstanding rentals for customer 1 and video 1"}, 400 + + for rental in rentals: + response_body = { + "customer_id": rental.customer_id, + "video_id" : rental.video_id, + "videos_checked_out_count" : (len(customer.videos) - 1), + "available_inventory" : (video.total_inventory - checked_in_count) + } + + # delete the rental record + db.session.delete(rental) + db.session.commit() + + return jsonify(response_body), 200 + + +# ********************************** +# *** customers custom endpoints *** +# ********************************** +@customers_bp.route("//rentals", methods=["GET"]) +def get_checked_out_videos(customer_id): + """Lists the videos a customer + currently has checked out + """ + + #check if the customer exists + customer = Customer.query.get(customer_id) + if customer is None: + return customer_not_found(customer_id), 404 + + checked_out_videos = [] + rentals = customer.rentals + videos = customer.videos + for rental in rentals: + for video in videos: + checked_out_videos.append({ + "release_date": video.release_date, + "title": video.title, + "due_date": rental.due_date + }) + + return jsonify(checked_out_videos), 200 + + +# ********************************** +# *** videos custom endpoints *** +# ********************************** +@videos_bp.route("//rentals", methods=["GET"]) +def get_customers_by_video(video_id): + """Lists the customers who currently + have the video checked out + """ + + video = Video.query.get(video_id) + if video is None: + return video_not_found(video_id), 404 + + customers_with_video = [] + rentals = video.rentals + for rental in rentals: + customers_with_video.append({ + "name": rental.customer.name, + "phone": rental.customer.phone, + "postal_code": rental.customer.postal_code, + "due_date": rental.due_date + }) + + return jsonify(customers_with_video), 200 \ No newline at end of file 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/c5f908b46d67_.py b/migrations/versions/c5f908b46d67_.py new file mode 100644 index 000000000..3f2ee99f8 --- /dev/null +++ b/migrations/versions/c5f908b46d67_.py @@ -0,0 +1,53 @@ +"""empty message + +Revision ID: c5f908b46d67 +Revises: +Create Date: 2021-11-15 15:52:07.156915 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'c5f908b46d67' +down_revision = None +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('customer', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('name', sa.String(), nullable=True), + sa.Column('postal_code', sa.String(), nullable=True), + sa.Column('phone', sa.String(), nullable=True), + sa.Column('registered_at', sa.DateTime(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('video', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('release_date', sa.DateTime(), nullable=True), + sa.Column('total_inventory', sa.Integer(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_table('rental', + sa.Column('id', sa.Integer(), autoincrement=True, nullable=False), + sa.Column('customer_id', sa.Integer(), nullable=True), + sa.Column('video_id', sa.Integer(), nullable=True), + sa.Column('due_date', sa.DateTime(), nullable=True), + sa.ForeignKeyConstraint(['customer_id'], ['customer.id'], ), + sa.ForeignKeyConstraint(['video_id'], ['video.id'], ), + sa.PrimaryKeyConstraint('id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('rental') + op.drop_table('video') + op.drop_table('customer') + # ### end Alembic commands ### diff --git a/requirements.txt b/requirements.txt index 71f94035e..7897bdf91 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,6 +5,7 @@ blinker==1.4 certifi==2020.12.5 chardet==4.0.0 click==7.1.2 +DateTime==4.3 Flask==1.1.2 Flask-Migrate==2.6.0 Flask-SQLAlchemy==2.4.4 @@ -24,9 +25,11 @@ pytest==6.2.5 python-dateutil==2.8.1 python-dotenv==0.15.0 python-editor==1.0.4 +pytz==2021.3 requests==2.25.1 six==1.15.0 SQLAlchemy==1.3.23 toml==0.10.2 urllib3==1.26.5 Werkzeug==1.0.1 +zope.interface==5.4.0 diff --git a/tests/test_wave_01.py b/tests/test_wave_01.py index 8d32038f2..7c90b62b5 100644 --- a/tests/test_wave_01.py +++ b/tests/test_wave_01.py @@ -66,7 +66,6 @@ def test_get_invalid_video_id(client, one_video): # Assert assert response.status_code == 400 - # CREATE def test_create_video(client): # Act diff --git a/tests/test_wave_02.py b/tests/test_wave_02.py index b9f65b208..28e665811 100644 --- a/tests/test_wave_02.py +++ b/tests/test_wave_02.py @@ -159,9 +159,9 @@ def test_rentals_by_customer(client, one_checked_out_video): response_body = response.get_json() - response.status_code == 200 - len(response_body) == 1 - response_body[0]["title"] == VIDEO_TITLE + assert response.status_code == 200 + assert len(response_body) == 1 + assert response_body[0]["title"] == VIDEO_TITLE def test_rentals_by_customer_not_found(client): response = client.get("/customers/1/rentals")