"""Logic for marketing highlights.""" from oto import response from product_digital_marketing.connectors import mysql from product_digital_marketing.constants import error from product_digital_marketing.models import highlight from product_digital_marketing.models import highlight_projection def get_marketing_highlight_by_product_id(product_id): """Fetch marketing highlight by product id. Args: product_id (int): Product id. Returns: response.Response: object containing highlight if available else not found response. """ return highlight.get_marketing_highlight_by_product_id(product_id) def upsert_marketing_highlight(product_id, highlight_data, orchard_user_id=''): """Create or update marketing highlight by product id. Args: product_id (int): Product id. highlight_data (dict): Highlight data to persist. orchard_user_id (str): Orchard user Id Returns: response.Response: object containing highlight if available else not found response. """ return highlight.upsert_marketing_highlight(product_id, highlight_data, orchard_user_id) @mysql.wrap_db_errors def copy_marketing(source_product_id, target_product_id): """Logic for copying marketing highlight for digital product. Args: source_product_id (int): Product id. target_product_id (int): Highlight data to persist. Returns: response.Response: object containing highlight if available else not found response. """ with mysql.db_session() as session: source_highlight = session.query(highlight.MarketingHighlight)\ .filter( highlight.MarketingHighlight.product_id == source_product_id)\ .first() if not source_highlight: return response.create_not_found_response() target_highlight = session.query(highlight.MarketingHighlight)\ .filter( highlight.MarketingHighlight.product_id == target_product_id)\ .first() if target_highlight: return response.create_error_response( code=error.ERROR_MESSAGE_COPY_TARGET_EXISTS, message=error.BAD_REQUEST_CODE, status=400) highlight_data = source_highlight.to_dict() # Do not copy global totals. highlight_data.pop('apple_total') highlight_data.pop('downloads_total') highlight_data.pop('spotify_total') projections_data = highlight_data.pop('projections') new_highlight = highlight.MarketingHighlight(**highlight_data) new_highlight.product_id = target_product_id session.add(new_highlight) for projection in projections_data: # Do not copy territory projection values. projection.pop('apple_projection') projection.pop('downloads_projection') projection.pop('id') projection.pop('spotify_projection') new_projection = highlight_projection.MarketingHighlightProjection( **projection ) new_projection.product_id = target_product_id session.add(new_projection) session.commit() return response.Response(message=new_highlight.to_dict(), status=201)