Skip to content

Commit

Permalink
Removing content fron engagement table (#2426)
Browse files Browse the repository at this point in the history
  • Loading branch information
VineetBala-AOT authored Mar 26, 2024
1 parent b3dd910 commit 29c2e00
Show file tree
Hide file tree
Showing 20 changed files with 226 additions and 100 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""remove_content_from_engagement
Revision ID: 734f160dd120
Revises: f3842579261c
Create Date: 2024-03-20 21:01:24.327334
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = '734f160dd120'
down_revision = 'f3842579261c'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('engagement', 'content')
op.drop_column('engagement', 'rich_content')
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('engagement', sa.Column('rich_content', postgresql.JSON(astext_type=sa.Text()), autoincrement=False, nullable=True))
op.add_column('engagement', sa.Column('content', sa.TEXT(), autoincrement=False, nullable=True))
# ### end Alembic commands ###
10 changes: 9 additions & 1 deletion met-api/src/met_api/constants/engagement_content_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,19 @@
Each value in this corresponds to a specific section or content element.
"""
from enum import IntEnum
from enum import Enum, IntEnum


class EngagementContentType(IntEnum):
"""Enum of engagement content type."""

Summary = 1
Custom = 2


class EngagementContentDefaultValues(Enum):
"""Default enum of engagement content type."""

Title = 'Summary'
Icon = 'faRectangleList'
Type = 'Summary'
4 changes: 0 additions & 4 deletions met-api/src/met_api/models/engagement.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,6 @@ class Engagement(BaseModel):
status = db.relationship('EngagementStatus', backref='engagement')
published_date = db.Column(db.DateTime, nullable=True)
scheduled_date = db.Column(db.DateTime, nullable=True)
content = db.Column(db.Text, unique=False, nullable=False)
rich_content = db.Column(JSON, unique=False, nullable=False)
banner_filename = db.Column(db.String(), unique=False, nullable=True)
surveys = db.relationship('Survey', backref='engagement', cascade='all, delete')
status_block = db.relationship('EngagementStatusBlock', backref='engagement')
Expand Down Expand Up @@ -123,8 +121,6 @@ def update_engagement(cls, engagement: EngagementSchema) -> Engagement:
updated_date=datetime.utcnow(),
updated_by=engagement.get('updated_by', None),
banner_filename=engagement.get('banner_filename', None),
content=engagement.get('content', None),
rich_content=engagement.get('rich_content', None),
is_internal=engagement.get('is_internal', record.is_internal),
consent_message=engagement.get('consent_message', record.consent_message),
)
Expand Down
8 changes: 8 additions & 0 deletions met-api/src/met_api/models/engagement_summary_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ def get_summary_content(cls, content_id) -> list[EngagementSummary]:
.all()
return summary_content

@classmethod
def get_summary_content_by_engagement_id(cls, engagement_id) -> list[EngagementSummary]:
"""Get engagement summary content by engagement id."""
summary_content = db.session.query(EngagementSummary) \
.filter(EngagementSummary.engagement_id == engagement_id) \
.first()
return summary_content

@classmethod
def update_summary_content(cls, content_id, summary_content_data: dict) -> EngagementSummary:
"""Update engagement summary content."""
Expand Down
6 changes: 3 additions & 3 deletions met-api/src/met_api/resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@
API.add_namespace(SUBSCRIPTION_API)
API.add_namespace(COMMENT_API)
API.add_namespace(EMAIL_VERIFICATION_API)
API.add_namespace(ENGAGEMENT_CONTENT_API)
API.add_namespace(ENGAGEMENT_CUSTOM_CONTENT_API, path='/engagement_content/<string:content_id>/custom')
API.add_namespace(ENGAGEMENT_SUMMARY_CONTENT_API, path='/engagement_content/<string:content_id>/summary')
API.add_namespace(ENGAGEMENT_CONTENT_API, path='/engagement/<int:engagement_id>/content')
API.add_namespace(ENGAGEMENT_CUSTOM_CONTENT_API, path='/content/<int:content_id>/custom')
API.add_namespace(ENGAGEMENT_SUMMARY_CONTENT_API, path='/content/<int:content_id>/summary')
API.add_namespace(FEEDBACK_API)
API.add_namespace(WIDGET_API)
API.add_namespace(CONTACT_API)
Expand Down
6 changes: 3 additions & 3 deletions met-api/src/met_api/resources/engagement_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@


@cors_preflight('GET, POST, OPTIONS')
@API.route('/engagement/<engagement_id>')
@API.route('')
class EngagementContent(Resource):
"""Resource for managing a engagement content."""

Expand Down Expand Up @@ -69,7 +69,7 @@ def post(engagement_id):


@cors_preflight('PATCH')
@API.route('/engagement/<engagement_id>/sort_index')
@API.route('/sort_index')
class EngagementContentSort(Resource):
"""Resource for managing engagement contents sort order with engagements."""

Expand All @@ -88,7 +88,7 @@ def patch(engagement_id):


@cors_preflight('GET, DELETE, PATCH')
@API.route('/<engagement_content_id>/engagements/<engagement_id>')
@API.route('/<engagement_content_id>')
class EngagementContentEdit(Resource):
"""Resource for managing engagement contents with engagements."""

Expand Down
2 changes: 1 addition & 1 deletion met-api/src/met_api/resources/engagement_custom_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

@cors_preflight('GET, POST, PATCH, OPTIONS')
@API.route('')
class Map(Resource):
class CustomContent(Resource):
"""Resource for managing engagement custom content."""

@staticmethod
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

@cors_preflight('GET, POST, PATCH, OPTIONS')
@API.route('')
class Map(Resource):
class SummaryContent(Resource):
"""Resource for managing engagement summary content."""

@staticmethod
Expand Down
2 changes: 0 additions & 2 deletions met-api/src/met_api/schemas/engagement.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ class Meta: # pylint: disable=too-few-public-methods
updated_date = fields.Str(data_key='updated_date')
published_date = fields.Str(data_key='published_date')
scheduled_date = fields.Str(data_key='scheduled_date')
content = fields.Str(data_key='content')
rich_content = fields.Str(data_key='rich_content')
banner_filename = fields.Str(data_key='banner_filename')
engagement_status = fields.Nested(EngagementStatusSchema)
surveys = fields.List(fields.Nested(EngagementSurveySchema))
Expand Down
23 changes: 22 additions & 1 deletion met-api/src/met_api/services/engagement_content_service.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
"""Service for engagement content management."""
from http import HTTPStatus
from flask import current_app

from met_api.constants.engagement_content_type import EngagementContentType
from met_api.constants.membership_type import MembershipType
from met_api.exceptions.business_exception import BusinessException
from met_api.models.engagement_content import EngagementContent as EngagementContentModel
from met_api.schemas.engagement_content import EngagementContentSchema
from met_api.services.engagement_custom_content_service import EngagementCustomContentService
from met_api.services import authorization
from met_api.utils.roles import Role

Expand Down Expand Up @@ -36,10 +38,29 @@ def create_engagement_content(engagement_content_data, engagement_id):
sort_index = EngagementContentService._find_higest_sort_index(engagement_id)

engagement_content_data['sort_index'] = sort_index + 1

created_content = EngagementContentService._create_content(engagement_id, engagement_content_data)
created_content.commit()

if engagement_content_data.get('content_type') == EngagementContentType.Custom.name:
EngagementContentService.create_default_custom_content(engagement_id, created_content.id)

return EngagementContentSchema().dump(created_content)

@staticmethod
def create_default_custom_content(eng_id: int, eng_content_id: int):
"""Create default engagement custom content."""
default_summary_content = {
'engagement_id': eng_id
}
try:
EngagementCustomContentService.create_custom_content(eng_content_id, default_summary_content)
except Exception as exc: # noqa: B902
current_app.logger.error('Failed to create default engagement summary content', exc)
raise BusinessException(
error='Failed to create default engagement summary content.',
status_code=HTTPStatus.INTERNAL_SERVER_ERROR) from exc

@staticmethod
def _find_higest_sort_index(engagement_id):
# find the highest sort order of the engagement content
Expand All @@ -58,7 +79,7 @@ def _create_content(engagement_id, engagement_content_data: dict):
engagement_content_model.icon_name = engagement_content_data.get('icon_name')
engagement_content_model.content_type = EngagementContentType[engagement_content_data.get('content_type')]
engagement_content_model.sort_index = engagement_content_data.get('sort_index')
engagement_content_model.is_internal = engagement_content_data.get('is_internal')
engagement_content_model.is_internal = engagement_content_data.get('is_internal', False)
engagement_content_model.flush()
return engagement_content_model

Expand Down
44 changes: 41 additions & 3 deletions met-api/src/met_api/services/engagement_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from flask import current_app

from met_api.constants.engagement_content_type import EngagementContentDefaultValues
from met_api.constants.engagement_status import Status
from met_api.constants.membership_type import MembershipType
from met_api.exceptions.business_exception import BusinessException
Expand All @@ -17,8 +18,9 @@
from met_api.services import authorization
from met_api.services.engagement_settings_service import EngagementSettingsService
from met_api.services.engagement_slug_service import EngagementSlugService
from met_api.services.engagement_content_service import EngagementContentService
from met_api.services.engagement_summary_content_service import EngagementSummaryContentService
from met_api.services.object_storage_service import ObjectStorageService

from met_api.services.project_service import ProjectService
from met_api.utils import email_util, notification
from met_api.utils.enums import SourceAction, SourceType
Expand Down Expand Up @@ -157,6 +159,9 @@ def create_engagement(request_json: dict):
EngagementService.validate_fields(request_json)
eng_model = EngagementService._create_engagement_model(request_json)

eng_content = EngagementService.create_default_engagement_content(eng_model.id)
EngagementService.create_default_summary_content(eng_model.id, eng_content['id'], request_json)

if request_json.get('status_block'):
EngagementService._create_eng_status_block(eng_model.id, request_json)
eng_model.commit()
Expand All @@ -182,14 +187,47 @@ def _create_engagement_model(engagement_data: dict) -> EngagementModel:
published_date=None,
scheduled_date=None,
banner_filename=engagement_data.get('banner_filename', None),
content=engagement_data.get('content', None),
rich_content=engagement_data.get('rich_content', None),
is_internal=engagement_data.get('is_internal', False),
consent_message=engagement_data.get('consent_message', None)
)
new_engagement.save()
return new_engagement

@staticmethod
def create_default_engagement_content(eng_id):
"""Create default engagement content for the given engagement ID."""
default_engagement_content = {
'title': EngagementContentDefaultValues.Title.value,
'icon_name': EngagementContentDefaultValues.Icon.value,
'content_type': EngagementContentDefaultValues.Type.value,
'engagement_id': eng_id
}
try:
eng_content = EngagementContentService.create_engagement_content(default_engagement_content, eng_id)
except Exception as exc: # noqa: B902
current_app.logger.error('Failed to create default engagement content', exc)
raise BusinessException(
error='Failed to create default engagement content.',
status_code=HTTPStatus.INTERNAL_SERVER_ERROR) from exc

return eng_content

@staticmethod
def create_default_summary_content(eng_id: int, eng_content_id: int, content_data: dict):
"""Create default summary content for the engagement ID, mandatory for each engagement."""
default_summary_content = {
'engagement_id': eng_id,
'content': content_data.get('content', None),
'rich_content': content_data.get('rich_content', None)
}
try:
EngagementSummaryContentService.create_summary_content(eng_content_id, default_summary_content)
except Exception as exc: # noqa: B902
current_app.logger.error('Failed to create default engagement summary content', exc)
raise BusinessException(
error='Failed to create default engagement summary content.',
status_code=HTTPStatus.INTERNAL_SERVER_ERROR) from exc

@staticmethod
def _create_eng_status_block(eng_id, engagement_data: dict):
"""Save engagement."""
Expand Down
13 changes: 9 additions & 4 deletions met-api/src/met_api/services/engagement_translation_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from met_api.models.engagement import Engagement as EngagementModel
from met_api.models.engagement_slug import EngagementSlug as EngagementSlugModel
from met_api.models.engagement_status_block import EngagementStatusBlock as EngagementStatusBlockModel
from met_api.models.engagement_summary_content import EngagementSummary as EngagementSummaryModel
from met_api.models.engagement_translation import EngagementTranslation as EngagementTranslationModel
from met_api.models.language import Language as LanguageModel
from met_api.schemas.engagement_translation import EngagementTranslationSchema
Expand Down Expand Up @@ -41,6 +42,8 @@ def create_engagement_translation(translation_data, pre_populate=True):
"""Create engagement translation."""
try:
engagement = EngagementModel.find_by_id(translation_data['engagement_id'])
summary_content = EngagementSummaryModel.get_summary_content_by_engagement_id(
translation_data['engagement_id'])
if not engagement:
raise ValueError('Engagement to translate was not found')

Expand All @@ -56,7 +59,9 @@ def create_engagement_translation(translation_data, pre_populate=True):

if pre_populate:
# prepopulate translation with base language data
EngagementTranslationService._get_default_language_values(engagement, translation_data)
EngagementTranslationService._get_default_language_values(engagement,
summary_content,
translation_data)

created_engagement_translation = EngagementTranslationModel.create_engagement_translation(
translation_data)
Expand Down Expand Up @@ -117,14 +122,14 @@ def _verify_engagement_translation(engagement_translation_id):
return engagement_translation

@staticmethod
def _get_default_language_values(engagement, translation_data):
def _get_default_language_values(engagement, summary_content, translation_data):
"""Populate the default values."""
engagement_id = engagement.id
translation_data['name'] = engagement.name
translation_data['description'] = engagement.description
translation_data['rich_description'] = engagement.rich_description
translation_data['content'] = engagement.content
translation_data['rich_content'] = engagement.rich_content
translation_data['content'] = summary_content.content
translation_data['rich_content'] = summary_content.rich_content
translation_data['consent_message'] = engagement.consent_message

engagement_slug = EngagementSlugModel.find_by_engagement_id(engagement_id)
Expand Down
3 changes: 0 additions & 3 deletions met-api/tests/unit/api/test_engagement.py
Original file line number Diff line number Diff line change
Expand Up @@ -351,7 +351,6 @@ def test_patch_engagement(client, jwt, session, engagement_info, side_effect, ex
'start_date': fake.date(),
'end_date': fake.date(),
'description': fake.text(),
'content': fake.text(),
'created_date': fake.date(),
}

Expand All @@ -367,7 +366,6 @@ def test_patch_engagement(client, jwt, session, engagement_info, side_effect, ex
assert engagement_edits.get('start_date') in rv.json.get('start_date')
assert engagement_edits.get('end_date') in rv.json.get('end_date')
assert rv.json.get('description') == engagement_edits.get('description')
assert rv.json.get('content') == engagement_edits.get('content')
assert engagement_edits.get('created_date') in rv.json.get('created_date')

with patch.object(EngagementService, 'edit_engagement', side_effect=side_effect):
Expand All @@ -392,7 +390,6 @@ def test_patch_engagement_by_member(client, jwt, session): # pylint:disable=unu
'start_date': fake.date(),
'end_date': fake.date(),
'description': fake.text(),
'content': fake.text(),
'created_date': fake.date(),
}

Expand Down
Loading

0 comments on commit 29c2e00

Please sign in to comment.