DROP VIEW IF EXISTS offer_pms_view_es;
CREATE VIEW offer_pms_view_es(
    id,
    user_id,
    project_id,
    offer_code,
    offer_name,
    offer_status,
    participant_type,
    first_name,
    last_name,
    partitipant_name,
    offer_id,
    editor_total_rate,
    pm_total_article_scoring
) as
SELECT
        offer_partitipants.id,
        offer_partitipants.user_id,
        offer.project_id,
        offer.offer_code,
        offer.offer_name,
        offer_partitipants.offer_status,
        offer_partitipants.participant_type,
        editor.first_name,
        editor.last_name,
        offer_partitipants.partitipant_name,
        offer_partitipants.offer_id, 
        pms_rate_view.editorTotalRate as editor_total_rate,
        pms_rate_view.pmTotalArticleScoring as pm_total_article_scoring
    FROM
        offer_partitipants
    LEFT JOIN project_offers offer ON
        offer_partitipants.offer_id = offer.id
    LEFT JOIN user ON offer_partitipants.user_id = user.id
    LEFT JOIN authors author ON
        user.id = author.user_id
    LEFT JOIN editors editor ON
        user.id = editor.user_id
    LEFT JOIN offer_deliveries offerDeliveries ON
        offer.id = offerDeliveries.offer_id
    LEFT JOIN (
        SELECT
            (
                COALESCE(pm_puntuality_rate.rate, 0) + COALESCE(pm_attitude_rate.rate, 0) + COALESCE(pm_quality_rate.rate, 0)
            ) AS editorTotalRate,
            COALESCE(
                total_article_scoring_pm_view.total_scoring,
                0
            ) AS pmTotalArticleScoring,
            editors_view.id AS editor_id
        FROM
            editors_view
        LEFT JOIN user ON editors_view.user_id = user.id
        LEFT JOIN scoring_puntuality_rate_view pm_puntuality_rate ON
            (
                editors_view.user_id = pm_puntuality_rate.user_id
            ) AND(
                pm_puntuality_rate.participant_type = 5
            )
        LEFT JOIN scoring_attitude_rate_view pm_attitude_rate ON
            (
                editors_view.user_id = pm_attitude_rate.user_id
            ) AND(
                pm_attitude_rate.participant_type = 5
            )
        LEFT JOIN scoring_quality_rate_view pm_quality_rate ON
            (
                editors_view.user_id = pm_quality_rate.user_id
            ) AND(
                pm_quality_rate.participant_type = 5
            )
        LEFT JOIN total_article_scoring_pm_view ON total_article_scoring_pm_view.user_id = user.id
    ) as pms_rate_view ON pms_rate_view.editor_id = editor.id
    WHERE participant_type = 5
    GROUP BY
        offer_id,
        user_id;