File size: 11,444 Bytes
ef78361
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
"""Trigger metric trend charts β€” Plotly mini charts for action items dashboard."""
from __future__ import annotations

from collections import defaultdict
from datetime import date, timedelta

import plotly.graph_objects as go
import streamlit as st

CHART_HEIGHT = 260
MINI_LAYOUT = dict(
    margin=dict(t=30, b=40, l=50, r=20),
    height=CHART_HEIGHT,
    legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
    xaxis=dict(tickformat="%m/%d"),
)


def _get_client():
    from core.supabase_client import get_supabase_client
    return get_supabase_client()


@st.cache_data(ttl=120)
def _fetch_visibility_data(campaign_id: int, start_date: str, end_date: str) -> list[dict]:
    """Cached fetch for visibility trend data."""
    client = _get_client()
    try:
        result = (
            client.table("report_visibility_daily")
            .select("task_date, brand_name, brand_type, visibility_pct")
            .eq("campaign_id", campaign_id)
            .gte("task_date", start_date)
            .lte("task_date", end_date)
            .order("task_date")
            .execute()
        )
        return result.data or []
    except Exception:
        return []


@st.cache_data(ttl=120)
def _fetch_citation_type_data(campaign_id: int, start_date: str, end_date: str) -> list[dict]:
    """Cached fetch for citation type trend data."""
    client = _get_client()
    try:
        result = (
            client.table("report_source_daily")
            .select("task_date, source_host_type, citation_count")
            .eq("campaign_id", campaign_id)
            .eq("agg_level", "host")
            .gte("task_date", start_date)
            .lte("task_date", end_date)
            .order("task_date")
            .execute()
        )
        return result.data or []
    except Exception:
        return []


@st.cache_data(ttl=120)
def _fetch_negative_rate_data(campaign_id: int, start_date: str, end_date: str) -> list[dict]:
    """Cached fetch for negative sentiment rate data."""
    client = _get_client()
    try:
        result = client.rpc("get_nudge_export_data", {
            "p_campaign_id": campaign_id,
            "p_in_house_only": False,
            "p_date_from": f"{start_date}T00:00:00+00:00",
            "p_date_to": f"{_next_day(end_date)}T00:00:00+00:00",
            "p_limit": 10000,
        }).execute()
        data = result.data or {}
        return data.get("rows", []) if isinstance(data, dict) else []
    except Exception:
        return []


@st.cache_data(ttl=120)
def _fetch_action_items_history(campaign_id: int) -> list[dict]:
    """Cached fetch for action items history data."""
    client = _get_client()
    try:
        result = (
            client.table("action_items")
            .select("created_at, completed_at, status")
            .eq("campaign_id", campaign_id)
            .order("created_at")
            .limit(5000)
            .execute()
        )
        return result.data or []
    except Exception:
        return []


# ============================================================================
# Chart 1: Visibility trend (own brand vs competitor average)
# ============================================================================

def render_visibility_trend(campaign_id: int, start_date: str, end_date: str):
    """Show daily own-brand vs competitor average visibility."""
    rows = _fetch_visibility_data(campaign_id, start_date, end_date)

    if not rows:
        st.info("κ°€μ‹œμ„± 데이터가 μ—†μŠ΅λ‹ˆλ‹€.")
        return

    # Group by date: own avg, competitor avg
    own_by_date: dict[str, list[float]] = defaultdict(list)
    comp_by_date: dict[str, list[float]] = defaultdict(list)

    for r in rows:
        d = r["task_date"]
        pct = r.get("visibility_pct", 0)
        if r.get("brand_type") == "PRIMARY":
            own_by_date[d].append(pct)
        else:
            comp_by_date[d].append(pct)

    dates = sorted(set(list(own_by_date.keys()) + list(comp_by_date.keys())))
    own_avgs = [
        sum(own_by_date[d]) / len(own_by_date[d]) if own_by_date.get(d) else None
        for d in dates
    ]
    comp_avgs = [
        sum(comp_by_date[d]) / len(comp_by_date[d]) if comp_by_date.get(d) else None
        for d in dates
    ]

    fig = go.Figure()
    fig.add_trace(go.Scatter(
        x=dates, y=own_avgs,
        mode="lines+markers", name="μžμ‚¬",
        line=dict(color="#3B82F6", width=2),
        marker=dict(size=5),
    ))
    fig.add_trace(go.Scatter(
        x=dates, y=comp_avgs,
        mode="lines+markers", name="κ²½μŸμ‚¬ 평균",
        line=dict(color="#EF4444", width=2, dash="dash"),
        marker=dict(size=5),
    ))
    fig.update_layout(
        title=dict(text="μžμ‚¬ vs κ²½μŸμ‚¬ κ°€μ‹œμ„±", font=dict(size=13)),
        yaxis_title="Visibility %",
        **MINI_LAYOUT,
    )
    st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False})


# ============================================================================
# Chart 2: Citation type trend (OFFICIAL % + top channel concentration)
# ============================================================================

def render_citation_type_trend(campaign_id: int, start_date: str, end_date: str):
    """Show daily OFFICIAL citation % and top channel concentration."""
    rows = _fetch_citation_type_data(campaign_id, start_date, end_date)

    if not rows:
        st.info("인용 데이터가 μ—†μŠ΅λ‹ˆλ‹€.")
        return

    # Group by date
    by_date: dict[str, dict[str, int]] = defaultdict(lambda: defaultdict(int))
    for r in rows:
        d = r["task_date"]
        ht = r.get("source_host_type") or "UNKNOWN"
        by_date[d][ht] += r.get("citation_count", 0)

    dates = sorted(by_date.keys())
    official_pcts = []
    top_channel_pcts = []

    for d in dates:
        type_counts = by_date[d]
        total = sum(type_counts.values())
        if total > 0:
            official_pcts.append(round(type_counts.get("OFFICIAL", 0) / total * 100, 1))
            max_count = max(type_counts.values())
            top_channel_pcts.append(round(max_count / total * 100, 1))
        else:
            official_pcts.append(0)
            top_channel_pcts.append(0)

    fig = go.Figure()
    fig.add_trace(go.Scatter(
        x=dates, y=official_pcts,
        mode="lines+markers", name="OFFICIAL %",
        line=dict(color="#7C3AED", width=2),
        marker=dict(size=5),
    ))
    fig.add_trace(go.Scatter(
        x=dates, y=top_channel_pcts,
        mode="lines+markers", name="Top 채널 %",
        line=dict(color="#F59E0B", width=2, dash="dot"),
        marker=dict(size=5),
    ))
    # Threshold lines
    fig.add_hline(y=10, line_dash="dash", line_color="#EF4444", opacity=0.5,
                  annotation_text="OFFICIAL 10%", annotation_position="bottom right")
    fig.add_hline(y=50, line_dash="dash", line_color="#F97316", opacity=0.5,
                  annotation_text="집쀑 50%", annotation_position="top right")
    fig.update_layout(
        title=dict(text="인용 μœ ν˜• 좔이", font=dict(size=13)),
        yaxis_title="%",
        **MINI_LAYOUT,
    )
    st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False})


# ============================================================================
# Chart 3: Negative sentiment rate trend
# ============================================================================

def render_negative_rate_trend(campaign_id: int, start_date: str, end_date: str):
    """Show daily in-house brand negative sentiment rate."""
    rows = _fetch_negative_rate_data(campaign_id, start_date, end_date)

    if not rows:
        st.info("감성 뢄석 데이터가 μ—†μŠ΅λ‹ˆλ‹€.")
        return

    if len(rows) >= 10000:
        st.warning("감성 데이터가 10,000건을 μ΄ˆκ³Όν•˜μ—¬ μΌλΆ€λ§Œ ν‘œμ‹œλ©λ‹ˆλ‹€. 기간을 μ’ν˜€λ³΄μ„Έμš”.")

    # Group by date
    total_by_date: dict[str, int] = defaultdict(int)
    neg_by_date: dict[str, int] = defaultdict(int)

    for r in rows:
        d = (r.get("analyzed_at") or "")[:10]
        if not d:
            continue
        total_by_date[d] += 1
        if r.get("overall_polarity") == "negative":
            neg_by_date[d] += 1

    dates = sorted(total_by_date.keys())
    neg_rates = [
        round(neg_by_date.get(d, 0) / total_by_date[d] * 100, 1) if total_by_date[d] > 0 else 0
        for d in dates
    ]

    fig = go.Figure()
    fig.add_trace(go.Scatter(
        x=dates, y=neg_rates,
        mode="lines+markers", name="λΆ€μ • λΉ„μœ¨",
        line=dict(color="#EF4444", width=2),
        marker=dict(size=5),
        fill="tozeroy",
        fillcolor="rgba(239,68,68,0.1)",
    ))
    fig.add_hline(y=30, line_dash="dash", line_color="#F97316", opacity=0.5,
                  annotation_text="κ²½κ³  30%", annotation_position="top right")
    fig.update_layout(
        title=dict(text="λΆ€μ • 감성 λΉ„μœ¨ 좔이", font=dict(size=13)),
        yaxis_title="λΆ€μ • %",
        **MINI_LAYOUT,
    )
    st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False})


# ============================================================================
# Chart 4: Action items history (created vs completed per week)
# ============================================================================

def render_action_items_history(campaign_id: int):
    """Show weekly created vs completed action items."""
    rows = _fetch_action_items_history(campaign_id)

    if not rows:
        st.info("μ•‘μ…˜μ•„μ΄ν…œ 이λ ₯이 μ—†μŠ΅λ‹ˆλ‹€.")
        return

    # Group by ISO week
    created_by_week: dict[str, int] = defaultdict(int)
    completed_by_week: dict[str, int] = defaultdict(int)

    for r in rows:
        c_date = (r.get("created_at") or "")[:10]
        if c_date:
            week = _iso_week_label(c_date)
            created_by_week[week] += 1

        if r.get("status") == "completed" and r.get("completed_at"):
            d_date = r["completed_at"][:10]
            week = _iso_week_label(d_date)
            completed_by_week[week] += 1

    weeks = sorted(set(list(created_by_week.keys()) + list(completed_by_week.keys())))
    created_vals = [created_by_week.get(w, 0) for w in weeks]
    completed_vals = [completed_by_week.get(w, 0) for w in weeks]

    fig = go.Figure()
    fig.add_trace(go.Bar(
        x=weeks, y=created_vals, name="생성",
        marker_color="#6366F1",
    ))
    fig.add_trace(go.Bar(
        x=weeks, y=completed_vals, name="μ™„λ£Œ",
        marker_color="#10B981",
    ))
    fig.update_layout(
        title=dict(text="주별 μ•‘μ…˜μ•„μ΄ν…œ 생성/μ™„λ£Œ", font=dict(size=13)),
        barmode="group",
        yaxis_title="건수",
        **MINI_LAYOUT,
    )
    st.plotly_chart(fig, use_container_width=True, config={"displayModeBar": False})


# ============================================================================
# Helpers
# ============================================================================

def _next_day(date_str: str) -> str:
    """Return next day as ISO string (for half-open TIMESTAMPTZ filter)."""
    d = date.fromisoformat(date_str)
    return (d + timedelta(days=1)).isoformat()


def _iso_week_label(date_str: str) -> str:
    """Convert date string to 'MM/DD' label of the week's Monday."""
    d = date.fromisoformat(date_str)
    monday = d - timedelta(days=d.weekday())
    return monday.strftime("%m/%d")