Skip to content

Commit

Permalink
bugfixes
Browse files Browse the repository at this point in the history
  • Loading branch information
posthogseb committed Aug 14, 2024
1 parent d507752 commit 3dd0b4a
Show file tree
Hide file tree
Showing 22 changed files with 233 additions and 193 deletions.
Binary file modified .DS_Store
Binary file not shown.
1 change: 1 addition & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ RUN pip3 install -r requirements.txt
COPY . .

RUN python pop_db.py
RUN python dummy_data.py

CMD [ "flask", "run", "--host=0.0.0.0"]
55 changes: 30 additions & 25 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def logout():
return redirect(url_for('index'))

@app.route('/search', methods=['POST'])
@csrf.exempt # Disable CSRF for this route
@csrf.exempt # Disable CSRF for this route for debugging.
def search():
query = request.form.get('query')
posthog.capture('search', 'search_performed', {'query': query})
Expand All @@ -118,26 +118,39 @@ def search_results():
@app.route('/profile', methods=['GET', 'POST'])
@login_required
def profile():
form = ChangePlanForm()
form = ChangePlanForm()

if form.validate_on_submit():
new_plan = form.plan.data
if new_plan:
if request.method == 'POST':
new_plan = request.form.get('plan')
app.logger.debug(f"Plan to update: {new_plan}")
if new_plan in ['Free', 'Premium', 'Max-imal']:
current_user.plan = new_plan
db.session.commit()
posthog.capture(current_user.email, 'plan_changed', {'new_plan': new_plan})
flash('Your subscription plan has been updated!')
try:
db.session.commit()
app.logger.debug(f"User plan updated to: {new_plan}")
flash('Your subscription plan has been updated!')
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify({'success': True})
except Exception as e:
db.session.rollback()
app.logger.error(f"Error updating plan: {e}")
flash('An error occurred while updating your plan. Please try again.', 'danger')
if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify({'success': False})
else:
flash('Please select a valid plan.', 'danger')
return redirect(url_for('profile'))

if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return jsonify({'success': False})

if not request.headers.get('X-Requested-With') == 'XMLHttpRequest':
return redirect(url_for('profile'))

# Load the user's movie stats for the profile page
stats_week = [stat.to_dict() for stat in MovieStats.query.filter_by(user_id=current_user.id, time_frame='week').all()]
stats_month = [stat.to_dict() for stat in MovieStats.query.filter_by(user_id=current_user.id, time_frame='month').all()]
stats_year = [stat.to_dict() for stat in MovieStats.query.filter_by(user_id=current_user.id, time_frame='year').all()]

return render_template('profile.html', user=current_user, form=form, stats_week=stats_week, stats_month=stats_month, stats_year=stats_year)


return render_template('profile.html', user=current_user, form=form, stats_week=stats_week, stats_month=stats_month, stats_year=stats_year)
@app.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():
Expand Down Expand Up @@ -166,18 +179,10 @@ def create_post():
return redirect(url_for('blog'))
return render_template('create_post.html', form=form)

@app.route('/change_plan', methods=['POST'])
@login_required
def change_plan():
new_plan = request.form.get('plan')
if new_plan:
current_user.plan = new_plan
db.session.commit()
posthog.capture(current_user.email, 'plan_changed', {'new_plan': new_plan})
flash('Your subscription plan has been updated!')
else:
flash('Please select a valid plan.', 'danger')
return redirect(url_for('profile'))

@app.route('/toc')
def toc():
return render_template('toc.html')

if __name__ == '__main__':
app.run(debug=True)
2 changes: 2 additions & 0 deletions dummy_data.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
# used to create some dummy data to show historical view count of movies in the profile etc.

from app import app, db
from models import User, MovieStats
from datetime import datetime, timedelta
Expand Down
3 changes: 2 additions & 1 deletion forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,10 @@ class LoginForm(FlaskForm):
submit = SubmitField('Login')

class ChangePlanForm(FlaskForm):
plan = HiddenField('Plan', validators=[DataRequired()])
plan = HiddenField('Plan') # Remove DataRequired for debugging
submit = SubmitField('Change Plan')


class BlogPostForm(FlaskForm):
title = StringField('Title', validators=[DataRequired()])
content = TextAreaField('Content', validators=[DataRequired()])
Expand Down
Binary file added instance/hogflix.sqlite
Binary file not shown.
Binary file removed login_error_user1.png
Binary file not shown.
Empty file modified migrations/README
100755 → 100644
Empty file.
Empty file modified migrations/alembic.ini
100755 → 100644
Empty file.
Empty file modified migrations/env.py
100755 → 100644
Empty file.
Empty file modified migrations/script.py.mako
100755 → 100644
Empty file.
37 changes: 0 additions & 37 deletions migrations/versions/53d232ec31a1_remove_rich.py

This file was deleted.

16 changes: 12 additions & 4 deletions migrations/versions/eadedf58f27f_init.py → migrations/versions/6611fec06885_init_seb.py
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,23 +1,30 @@
"""init
"""init seb
Revision ID: eadedf58f27f
Revision ID: 6611fec06885
Revises:
Create Date: 2024-08-14 13:55:38.775753
Create Date: 2024-08-14 15:08:10.643635
"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'eadedf58f27f'
revision = '6611fec06885'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('blog_post',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=150), nullable=False),
sa.Column('content', sa.Text(), nullable=False),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id')
)
op.create_table('movie',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('title', sa.String(length=100), nullable=False),
Expand Down Expand Up @@ -54,4 +61,5 @@ def downgrade():
op.drop_table('movie_stats')
op.drop_table('user')
op.drop_table('movie')
op.drop_table('blog_post')
# ### end Alembic commands ###
34 changes: 0 additions & 34 deletions migrations/versions/92f1848cd462_blog_pst.py

This file was deleted.

34 changes: 0 additions & 34 deletions migrations/versions/ab410ccb30fc_blog.py

This file was deleted.

Binary file removed search_error.png
Binary file not shown.
Binary file modified static/.DS_Store
Binary file not shown.
21 changes: 21 additions & 0 deletions static/css/profile.css
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,24 @@
background-color: #b30000;
border-color: #b30000;
}

.dark-modal {
background-color: #333;
color: white;
}

.dark-modal .modal-header {
border-bottom: 1px solid #555;
}

.dark-modal .modal-footer {
border-top: 1px solid #555;
}

.dark-modal .close {
color: white;
}

.dark-modal .btn-outline-light:hover {
color: #333;
}
97 changes: 82 additions & 15 deletions static/js/profile.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,76 @@
function selectPlan(plan) {
document.querySelectorAll('.plan-card').forEach(card => {
card.classList.remove('border-danger');
card.querySelector('.overlay').style.opacity = '0.6';
});
const selectedCard = document.querySelector(`.plan-card[data-plan="${plan}"]`);
if (selectedCard) {
selectedCard.classList.add('border-danger');
selectedCard.querySelector('.overlay').style.opacity = '0';
}

console.log("Plan selected: " + plan);

showConfirmationModal(plan);
}

function showConfirmationModal(plan) {
const modal = $('#confirmationModal');
const modalBody = $('#modalBody');
modalBody.text(`Are you sure you want to change your plan to ${plan}?`);

$('#confirmButton').off('click').on('click', function() {
updatePlan(plan);
modal.modal('hide');
});

modal.modal('show');
}

function updatePlan(plan) {
const formData = new FormData();
formData.append('plan', plan);
formData.append('csrf_token', csrfToken);

fetch('/profile', {
method: 'POST',
body: formData,
headers: {
'X-Requested-With': 'XMLHttpRequest',
'X-CSRFToken': csrfToken
}
})
.then(response => response.json())
.then(data => {
if (data.success) {
showSuccessModal(plan);
document.getElementById('currentPlan').textContent = plan;
} else {
showErrorModal();
}
})
.catch(error => {
console.error('Error:', error);
showErrorModal();
});
}

function showSuccessModal(plan) {
const modal = $('#confirmationModal');
const modalBody = $('#modalBody');
modalBody.text(`Your plan has been successfully updated to ${plan}!`);
$('#confirmButton').hide();
modal.modal('show');
}

function showErrorModal() {
const modal = $('#confirmationModal');
const modalBody = $('#modalBody');
modalBody.text('Failed to update plan. Please try again.');
$('#confirmButton').hide();
modal.modal('show');
}

document.addEventListener('DOMContentLoaded', function () {
const weekStats = JSON.parse(document.getElementById('weekStats').textContent);
const monthStats = JSON.parse(document.getElementById('monthStats').textContent);
Expand Down Expand Up @@ -65,18 +138,12 @@ document.addEventListener('DOMContentLoaded', function () {
updateChart(timeFrame);
});

// Automatically highlight the user's current plan
const currentPlan = document.getElementById('currentPlan').textContent;
selectPlan(currentPlan);
});

function selectPlan(plan) {
document.getElementById('plan_input').value = plan;
document.querySelectorAll('.plan-card').forEach(card => {
card.classList.remove('border-danger');
card.querySelector('.overlay').style.opacity = '0.6';
});
const selectedCard = document.getElementById('card_' + plan.toLowerCase().replace('-', '_'));
selectedCard.classList.add('border-danger');
selectedCard.querySelector('.overlay').style.opacity = '0';
}
const currentPlan = document.getElementById('currentPlan').textContent.trim();
if (currentPlan) {
const currentPlanCard = document.querySelector(`.plan-card[data-plan="${currentPlan}"]`);
if (currentPlanCard) {
currentPlanCard.classList.add('border-danger');
currentPlanCard.querySelector('.overlay').style.opacity = '0';
}
}
});
Loading

0 comments on commit 3dd0b4a

Please sign in to comment.