Merge branch 'develop' into kostia/fix/user_profile_ui

This commit is contained in:
Kostiantyn Stoliarskyi 2023-05-12 12:17:15 +03:00
commit 564229c5df
18 changed files with 383 additions and 30 deletions

View File

@ -24,6 +24,7 @@ def create_app(environment="development"):
home_blueprint,
section_blueprint,
vote_blueprint,
approve_blueprint,
)
from app.models import (
User,
@ -53,6 +54,7 @@ def create_app(environment="development"):
app.register_blueprint(home_blueprint)
app.register_blueprint(section_blueprint)
app.register_blueprint(vote_blueprint)
app.register_blueprint(approve_blueprint)
# Set up flask login.
@login_manager.user_loader

View File

@ -1,16 +1,14 @@
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, BooleanField
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired, Length
class BaseCommentForm(FlaskForm):
text = StringField("Text", [DataRequired(), Length(3, 256)])
marked = BooleanField("Marked")
included_with_interpretation = BooleanField("Included")
parent_id = StringField("Text")
class CreateCommentForm(BaseCommentForm):
parent_id = StringField("Text")
submit = SubmitField("Create")
@ -19,7 +17,6 @@ class DeleteCommentForm(FlaskForm):
submit = SubmitField("Delete")
class EditCommentForm(FlaskForm):
class EditCommentForm(BaseCommentForm):
comment_id = StringField("Text")
text = StringField("Text", [DataRequired(), Length(3, 256)])
submit = SubmitField("Edit")

View File

@ -10,9 +10,9 @@ class Comment(BaseModel):
# need to redeclare id to use it in the parent relationship
id = db.Column(db.Integer, primary_key=True)
text = db.Column(db.Text, unique=False, nullable=False)
approved = db.Column(db.Boolean, default=False)
marked = db.Column(db.Boolean, default=False)
edited = db.Column(db.Boolean, default=False)
included_with_interpretation = db.Column(db.Boolean, default=False)
# Foreign keys
user_id = db.Column(db.ForeignKey("users.id"))

View File

@ -2,7 +2,7 @@ from datetime import datetime
from flask_login import current_user
from app import db
from app import db, models as m
from app.models.utils import BaseModel
@ -11,6 +11,7 @@ class Interpretation(BaseModel):
label = db.Column(db.String(256), unique=False, nullable=False)
text = db.Column(db.Text, unique=False, nullable=False)
approved = db.Column(db.Boolean, default=False)
marked = db.Column(db.Boolean, default=False)
created_at = db.Column(db.DateTime, default=datetime.now)
@ -21,7 +22,7 @@ class Interpretation(BaseModel):
# Relationships
user = db.relationship("User")
section = db.relationship("Section")
comments = db.relationship("Comment", viewonly=True)
comments = db.relationship("Comment", viewonly=True, order_by="desc(Comment.id)")
votes = db.relationship("InterpretationVote", viewonly=True)
tags = db.relationship(
"Tag",
@ -52,5 +53,9 @@ class Interpretation(BaseModel):
def active_comments(self):
return [comment for comment in self.comments if not comment.is_deleted]
@property
def book(self) -> m.Book:
return self.section.version.book
def __repr__(self):
return f"<{self.id}: {self.label}>"

View File

@ -19,7 +19,9 @@ class Section(BaseModel):
collection = db.relationship("Collection", viewonly=True)
user = db.relationship("User", viewonly=True)
version = db.relationship("BookVersion", viewonly=True)
interpretations = db.relationship("Interpretation", viewonly=True)
interpretations = db.relationship(
"Interpretation", viewonly=True, order_by="desc(Interpretation.id)"
)
@property
def path(self):

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -109,8 +109,8 @@
{% for interpretation in section.active_interpretations %}
<!-- prettier-ignore -->
<dl class="bg-white dark:bg-gray-900 max-w-full p-3 text-gray-900 divide-y divide-gray-200 dark:text-white dark:divide-gray-700 m-3 border-2 border-gray-200 border-solid rounded-lg dark:border-gray-700">
<div class="flex flex-row pb-3 p-3 w-2/3 md:w-10/12">
<div class="vote-block flex flex-col m-5 justify-center items-center">
<div class="flex flex-row pb-3 p-3 w-2/3 md:w-full">
<div class="vote-block flex flex-col m-5 mr-8 justify-center items-center">
{% if interpretation.user_id != current_user.id %}
<div class="vote-button cursor-pointer" data-vote-for="interpretation" data-entity-id="{{ interpretation.id }}" data-positive="true">
<svg class="w-6 h-6 select-none
@ -142,9 +142,24 @@
" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 13.5L12 21m0 0l-7.5-7.5M12 21V3" /> </svg>
</div>
{% endif %}
<!-- TODO check permissions -->
{% if interpretation.book.owner == current_user %}
<div class="approve-button select-none approve-btn mt-3 cursor-pointer" data-approve="interpretation" data-entity-id="{{ interpretation.id }}">
<!-- outline -->
<svg class="not-approved-icon w-6 h-6 {% if interpretation.approved %} hidden {% endif %}" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<!-- solid -->
<svg class="approved-icon w-6 h-6 {% if not interpretation.approved %} hidden {% endif %}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
<path fill-rule="evenodd" d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm13.36-1.814a.75.75 0 10-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 00-1.06 1.06l2.25 2.25a.75.75 0 001.14-.094l3.75-5.25z" clip-rule="evenodd" />
</svg>
</div>
{% endif %}
</div>
<!-- prettier-ignore -->
<dt class="flex w-full mb-1 text-gray-500 md:text-lg dark:text-gray-400 flex-col">
<dt class="flex justify-center w-full mb-1 text-gray-500 md:text-lg dark:text-gray-400 flex-col">
<div class="ql-snow truncate md:max-w-xl">
<a
class="flex space-x-2"
@ -163,7 +178,7 @@
<p>{{ interpretation.text|safe }}</p>
</div>
</div>
<div class="flex mt-auto align-center justify-between md:w-full">
<div class="flex border-t-2 pt-3 mt-6 align-center justify-between md:w-full">
<div>
<span class="hidden md:inline-block">Interpretation by</span>
{{interpretation.user.username}} on {{interpretation.created_at.strftime('%B %d, %Y')}}
@ -174,7 +189,7 @@
</span>
<div class="space-x-0.5 flex items-center">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6"> <path stroke-linecap="round" stroke-linejoin="round" d="M20.25 8.511c.884.284 1.5 1.128 1.5 2.097v4.286c0 1.136-.847 2.1-1.98 2.193-.34.027-.68.052-1.02.072v3.091l-3-3c-1.354 0-2.694-.055-4.02-.163a2.115 2.115 0 01-.825-.242m9.345-8.334a2.126 2.126 0 00-.476-.095 48.64 48.64 0 00-8.048 0c-1.131.094-1.976 1.057-1.976 2.192v4.286c0 .837.46 1.58 1.155 1.951m9.345-8.334V6.637c0-1.621-1.152-3.026-2.76-3.235A48.455 48.455 0 0011.25 3c-2.115 0-4.198.137-6.24.402-1.608.209-2.76 1.614-2.76 3.235v6.226c0 1.621 1.152 3.026 2.76 3.235.577.075 1.157.14 1.74.194V21l4.155-4.155" /> </svg>
<p>{{interpretation.active_comments | length}}</p>
<p class="select-none">{{interpretation.active_comments | length}}</p>
</div>
</div>
</div>

View File

@ -49,12 +49,12 @@
<!-- prettier-ignore -->
<dl class="w-md md:w-full text-gray-900 divide-y divide-gray-200 dark:text-white dark:divide-gray-700">
<!-- prettier-ignore -->
<div class="quill-editor text-sm dark:text-white p-3">Comments:</div>
<div class="text-sm dark:text-white p-3">Comments:</div>
{% for comment in interpretation.comments if not comment.is_deleted %}
<!-- prettier-ignore -->
<dl class="bg-white dark:bg-gray-900 max-w-full p-3 text-gray-900 divide-y divide-gray-200 dark:text-white dark:divide-gray-700 m-3 border-2 border-gray-200 border-solid rounded-lg dark:border-gray-700">
<div class="flex flex-row pb-3 p-3 w-2/3 md:w-full">
<div class="vote-block flex flex-col m-5 justify-center items-center">
<div class="vote-block flex flex-col m-5 mr-8 justify-center items-center">
{% if comment.user_id != current_user.id %}
<div class="vote-button cursor-pointer" data-vote-for="comment" data-entity-id="{{ comment.id }}" data-positive="true">
<svg
@ -88,15 +88,30 @@
" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"> <path stroke-linecap="round" stroke-linejoin="round" d="M19.5 13.5L12 21m0 0l-7.5-7.5M12 21V3" /> </svg>
</div>
{% endif %}
<!-- TODO check permissions -->
{% if interpretation.book.owner == current_user %}
<div class="approve-button select-none approve-btn mt-3 cursor-pointer" data-approve="comment" data-entity-id="{{ comment.id }}">
<!-- outline -->
<svg class="not-approved-icon w-6 h-6 {% if comment.approved %} hidden {% endif %}" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" d="M9 12.75L11.25 15 15 9.75M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
<!-- solid -->
<svg class="approved-icon w-6 h-6 {% if not comment.approved %} hidden {% endif %}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
<path fill-rule="evenodd" d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm13.36-1.814a.75.75 0 10-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 00-1.06 1.06l2.25 2.25a.75.75 0 001.14-.094l3.75-5.25z" clip-rule="evenodd" />
</svg>
</div>
{% endif %}
</div>
<!-- prettier-ignore -->
<dt class="flex w-full mb-1 text-gray-500 md:text-lg dark:text-gray-400 flex-col md:max-w-xl">
<div class="ql-snow">
<div class="dark:text-white h-30 ql-editor">
<dt class="flex justify-center w-full mb-1 text-gray-500 md:text-lg dark:text-gray-400 flex-col">
<div>
<div class="dark:text-white h-30">
<p>{{ comment.text }}</p>
</div>
</div>
<div id="accordion-collapse" data-accordion="collapse" class="flex mt-auto align-center justify-between space-x-3">
<div id="accordion-collapse" data-accordion="collapse" class="flex border-t-2 pt-3 mt-6 align-center justify-between space-x-3">
<div>Commented by <span class="text-blue-500">{{comment.user.username}}</span> on {{comment.created_at.strftime('%B %d, %Y')}}{% if comment.edited %}<i class="text-green-200"> edited</i>{% endif %}</div>
{% if comment.user_id == current_user.id %}
<div class="flex ml-auto justify-between w-24">

View File

@ -6,3 +6,4 @@ from .book import bp as book_blueprint
from .home import bp as home_blueprint
from .section import bp as section_blueprint
from .vote import bp as vote_blueprint
from .approve import bp as approve_blueprint

80
app/views/approve.py Normal file
View File

@ -0,0 +1,80 @@
from flask import (
Blueprint,
jsonify,
)
from flask_login import login_required, current_user
from app import models as m, db
from app.logger import log
bp = Blueprint("approve", __name__, url_prefix="/approve")
@bp.route(
"/interpretation/<int:interpretation_id>",
methods=["POST"],
)
@login_required
def approve_interpretation(interpretation_id: int):
interpretation: m.Interpretation = db.session.get(
m.Interpretation, interpretation_id
)
if not interpretation:
log(log.WARNING, "Interpretation with id [%s] not found", interpretation_id)
return jsonify({"message": "Interpretation not found"}), 404
# TODO check permission
if interpretation.book.owner != current_user:
log(
log.WARNING,
"User [%s] dont have permission to approve [%s]",
current_user,
interpretation,
)
return jsonify({"message": "You dont have permission"}), 404
interpretation.approved = not interpretation.approved
log(
log.INFO,
"User [%s]. [%s] interpretation: [%s]",
current_user,
"Approve" if interpretation.approved else "Cancel approve",
interpretation,
)
interpretation.save()
return jsonify({"message": "success", "approve": interpretation.approved})
@bp.route(
"/comment/<int:interpretation_id>",
methods=["POST"],
)
@login_required
def approve_comment(interpretation_id: int):
comment: m.Comment = db.session.get(m.Comment, interpretation_id)
if not comment:
log(log.WARNING, "Comment with id [%s] not found", interpretation_id)
return jsonify({"message": "Comment not found"}), 404
# TODO check permission
if comment.interpretation.book.owner != current_user:
log(
log.WARNING,
"User [%s] dont have permission to approve [%s]",
current_user,
comment,
)
return jsonify({"message": "You dont have permission"}), 404
comment.approved = not comment.approved
log(
log.INFO,
"User [%s]. [%s] comment: [%s]",
current_user,
"Approve" if comment.approved else "Cancel approve",
comment,
)
comment.save()
return jsonify({"message": "success", "approve": comment.approved})

View File

@ -0,0 +1,40 @@
"""approved fields
Revision ID: 5df1fabbee7d
Revises: 1dfa1f2c208f
Create Date: 2023-05-11 15:06:42.883725
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '5df1fabbee7d'
down_revision = '1dfa1f2c208f'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('comments', schema=None) as batch_op:
batch_op.add_column(sa.Column('approved', sa.Boolean(), nullable=True))
batch_op.drop_column('included_with_interpretation')
with op.batch_alter_table('interpretations', schema=None) as batch_op:
batch_op.add_column(sa.Column('approved', sa.Boolean(), nullable=True))
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('interpretations', schema=None) as batch_op:
batch_op.drop_column('approved')
with op.batch_alter_table('comments', schema=None) as batch_op:
batch_op.add_column(sa.Column('included_with_interpretation', sa.BOOLEAN(), autoincrement=False, nullable=True))
batch_op.drop_column('approved')
# ### end Alembic commands ###

47
src/approve.ts Normal file
View File

@ -0,0 +1,47 @@
const REQUEST_URLS: {[key: string]: string} = {
interpretation: '/approve/interpretation/',
comment: '/approve/comment/',
};
const approveClickEventListener = async (btn: Element) => {
const approve = btn.getAttribute('data-approve');
if (!(approve in REQUEST_URLS)) {
console.error('Unknown data-approve attribute');
return;
}
const entityId = btn.getAttribute('data-entity-id');
const requestUrl = REQUEST_URLS[approve] + entityId;
const response = await fetch(requestUrl, {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json',
},
});
const json = await response.json();
const approved = json.approve;
const approvedIconSvg = btn.querySelector('.approved-icon');
const notApprovedIconSvg = btn.querySelector('.not-approved-icon');
approvedIconSvg.classList.remove('hidden');
notApprovedIconSvg.classList.remove('hidden');
if (approved) {
notApprovedIconSvg.classList.add('hidden');
} else {
approvedIconSvg.classList.add('hidden');
}
};
export function initApprove() {
const approveButtons = document.querySelectorAll('.approve-button');
approveButtons.forEach(approveButton => {
approveButton.addEventListener('click', () => {
approveClickEventListener(approveButton);
});
});
}

View File

@ -6,6 +6,7 @@ import {initQuillValueToInput} from './quillValueToInput';
import {initComments} from './comment';
import {initVote} from './vote';
import {initTheme} from './theme';
import {initApprove} from './approve';
initBooks();
initContributors();
@ -15,3 +16,4 @@ initWallet();
initComments();
initVote();
initTheme();
initApprove();

View File

@ -150,7 +150,7 @@ def create_dummy_data():
# - comment 2
# - comment 3
# - comment 3.1 (marked)
# - comment 3.2 (included_with_interpretation)
# - comment 3.2 (approved)
# - comment 3.3
comment_1 = m.Comment(
@ -197,7 +197,7 @@ def create_dummy_data():
comment_3_2 = m.Comment(
text="Dummy Comment 3.2 Text",
user_id=user.id,
included_with_interpretation=True,
approved=True,
parent_id=comment_3.id,
interpretation_id=interpretation_2.id,
).save()

113
tests/test_approve.py Normal file
View File

@ -0,0 +1,113 @@
from flask import current_app as Response
from flask.testing import FlaskClient
from app import models as m
from tests.utils import login, create_test_book
def test_approve_interpretation(client: FlaskClient):
_, user = login(client)
create_test_book(user.id)
dummy_user = m.User(username="Bob").save()
create_test_book(dummy_user.id)
response: Response = client.post(
"/approve/interpretation/999",
data=dict(
positive=True,
),
follow_redirects=True,
)
assert response
assert response.status_code == 404
assert response.json["message"] == "Interpretation not found"
interpretation: m.Interpretation = m.Interpretation.query.filter_by(
user_id=dummy_user.id
).first()
response: Response = client.post(
f"/approve/interpretation/{interpretation.id}",
follow_redirects=True,
)
assert response
assert response.json["message"] == "You dont have permission"
interpretation: m.Interpretation = m.Interpretation.query.filter_by(
user_id=user.id
).first()
response: Response = client.post(
f"/approve/interpretation/{interpretation.id}",
follow_redirects=True,
)
assert response
assert response.json["message"] == "success"
assert response.json["approve"]
assert interpretation.approved
interpretation: m.Interpretation = m.Interpretation.query.filter_by(
user_id=user.id
).first()
response: Response = client.post(
f"/approve/interpretation/{interpretation.id}",
follow_redirects=True,
)
assert response
assert response.json["message"] == "success"
assert not response.json["approve"]
assert not interpretation.approved
def test_approve_comment(client: FlaskClient):
_, user = login(client)
create_test_book(user.id)
dummy_user = m.User(username="Bob").save()
create_test_book(dummy_user.id)
response: Response = client.post(
"/approve/comment/999",
data=dict(
positive=True,
),
follow_redirects=True,
)
assert response
assert response.status_code == 404
assert response.json["message"] == "Comment not found"
comment: m.Comment = m.Comment.query.filter_by(user_id=dummy_user.id).first()
response: Response = client.post(
f"/approve/comment/{comment.id}",
follow_redirects=True,
)
assert response
assert response.json["message"] == "You dont have permission"
comment: m.Comment = m.Comment.query.filter_by(user_id=user.id).first()
response: Response = client.post(
f"/approve/comment/{comment.id}",
follow_redirects=True,
)
assert response
assert response.json["message"] == "success"
assert response.json["approve"]
assert comment.approved
comment: m.Collection = m.Comment.query.filter_by(user_id=user.id).first()
response: Response = client.post(
f"/approve/comment/{comment.id}",
follow_redirects=True,
)
assert response
assert response.json["message"] == "success"
assert not response.json["approve"]
assert not comment.approved

View File

@ -190,7 +190,7 @@ def test_dummy_data(runner: FlaskCliRunner):
# - comment 2
# - comment 3
# - comment 3.1 (marked)
# - comment 3.2 (included_with_interpretation)
# - comment 3.2 (approved)
# - comment 3.3
comment_1: m.Comment = m.Comment.query.filter_by(
@ -243,7 +243,7 @@ def test_dummy_data(runner: FlaskCliRunner):
assert comment_3_2 in comment_3.children
assert comment_3_3 in comment_3.children
assert comment_3_1.marked
assert comment_3_2.included_with_interpretation
assert comment_3_2.approved
assert comment_1 in interpretation_2.comments
assert comment_2 in interpretation_2.comments

View File

@ -1,4 +1,6 @@
from app.models import User
from app import models as m
from random import randint
TEST_ADMIN_NAME = "bob"
TEST_ADMIN_EMAIL = "bob@test.com"
@ -6,14 +8,14 @@ TEST_ADMIN_PASSWORD = "password"
def create(username=TEST_ADMIN_NAME, password=TEST_ADMIN_PASSWORD):
user = User(username=username)
user = m.User(username=username)
user.password = password
user.save()
return user.id
def login(client, username=TEST_ADMIN_NAME, password=TEST_ADMIN_PASSWORD):
user = User.query.filter_by(username=username).first()
user = m.User.query.filter_by(username=username).first()
response = client.post(
"/login", data=dict(user_id=username, password=password), follow_redirects=True
)
@ -22,3 +24,35 @@ def login(client, username=TEST_ADMIN_NAME, password=TEST_ADMIN_PASSWORD):
def logout(client):
return client.get("/logout", follow_redirects=True)
def create_test_book(owner_id: int, entity_id: int = randint(1, 100)):
book: m.Book = m.Book(
label=f"Book {entity_id}", about=f"About {entity_id}", user_id=owner_id
).save()
version: m.BookVersion = m.BookVersion(semver="1.0.0", book_id=book.id).save()
collection: m.Collection = m.Collection(
label=f"Collection {entity_id}", version_id=version.id
).save()
section: m.Section = m.Section(
label=f"Section {entity_id}",
user_id=owner_id,
collection_id=collection.id,
version_id=version.id,
).save()
interpretation: m.Interpretation = m.Interpretation(
section_id=section.id,
label=f"Interpretation {entity_id}",
text=f"Interpretation Text {entity_id}",
user_id=owner_id,
).save()
m.Comment(
text=f"Comment {entity_id}",
user_id=owner_id,
interpretation_id=interpretation.id,
).save()