|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from collections import defaultdict |
| 4 | + |
| 5 | +from admin_api.dashboard.params import ( |
| 6 | + REVENUE_NET, |
| 7 | + CheckinTrendParamsSerializer, |
| 8 | + DashboardParams, |
| 9 | + RevenueTrendParamsSerializer, |
| 10 | + SalesTrendParamsSerializer, |
| 11 | +) |
| 12 | +from admin_api.dashboard.registry import chart |
| 13 | +from core.util.dateutil import period_label, period_label_range |
| 14 | +from django.db.models import Min, OuterRef, Subquery |
| 15 | +from shop.order.models import OrderProductRelation |
| 16 | +from shop.payment_history.models import PaymentHistory |
| 17 | + |
| 18 | + |
| 19 | +def first_paid_at_subquery() -> Subquery: |
| 20 | + """OPR 의 주문에 대한 첫 PaymentHistory.created_at (판매 시각). OPR 컨텍스트용(OuterRef order_id).""" |
| 21 | + return Subquery( |
| 22 | + PaymentHistory.objects.filter_active() |
| 23 | + .filter(order_id=OuterRef("order_id")) |
| 24 | + .order_by("created_at") |
| 25 | + .values("created_at")[:1] |
| 26 | + ) |
| 27 | + |
| 28 | + |
| 29 | +def assemble_product_series(agg: dict[tuple[str, object], object], names: dict[object, str], p) -> dict: |
| 30 | + """{(label, product_id): value} + {product_id: name} → series + 연속 data(빈 버킷 0).""" |
| 31 | + series = [{"key": str(pid), "name": name} for pid, name in names.items()] |
| 32 | + data = [] |
| 33 | + for label in period_label_range(p.date_from, p.date_to, p.granularity): |
| 34 | + values = {str(pid): agg.get((label, pid), 0) for pid in names} |
| 35 | + data.append({"label": label, "values": values}) |
| 36 | + return {"series": series, "data": data} |
| 37 | + |
| 38 | + |
| 39 | +def checkin_counts_by_label(p) -> dict[str, int]: |
| 40 | + """현재 used 인 티켓 OPR 의 '최초 used 전이' 시각(history)을 주기별로 집계. {label: count}.""" |
| 41 | + historical = OrderProductRelation.history.model |
| 42 | + target_ids = ( |
| 43 | + p.ticket_opr_qs().filter(status=OrderProductRelation.OrderProductStatus.used).values_list("id", flat=True) |
| 44 | + ) |
| 45 | + rows = ( |
| 46 | + historical.objects.filter(id__in=target_ids, status=OrderProductRelation.OrderProductStatus.used) |
| 47 | + .values("id") |
| 48 | + .annotate(checked_at=Min("history_date")) |
| 49 | + .filter(checked_at__gte=p.date_from, checked_at__lt=p.date_to) |
| 50 | + ) |
| 51 | + counts: dict[str, int] = defaultdict(int) |
| 52 | + for row in rows: |
| 53 | + counts[period_label(row["checked_at"], p.granularity)] += 1 |
| 54 | + return counts |
| 55 | + |
| 56 | + |
| 57 | +@chart( |
| 58 | + id="line-sales-trend", |
| 59 | + title="판매 추이", |
| 60 | + type="line", |
| 61 | + params_serializer=SalesTrendParamsSerializer, |
| 62 | + unit="건", |
| 63 | +) |
| 64 | +def _sales_trend(p: DashboardParams) -> dict: |
| 65 | + rows = ( |
| 66 | + p.ticket_opr_qs() |
| 67 | + .filter(status__in=OrderProductRelation.PURCHASED_STOCK_STATUS) |
| 68 | + .annotate(paid_at=first_paid_at_subquery()) |
| 69 | + .filter(paid_at__gte=p.date_from, paid_at__lt=p.date_to) |
| 70 | + .values_list("product_id", "product__name", "paid_at") |
| 71 | + ) |
| 72 | + agg: dict[tuple[str, object], int] = defaultdict(int) |
| 73 | + names: dict[object, str] = {} |
| 74 | + for pid, name, paid_at in rows: |
| 75 | + names.setdefault(pid, name) |
| 76 | + agg[(period_label(paid_at, p.granularity), pid)] += 1 |
| 77 | + return assemble_product_series(agg, names, p) |
| 78 | + |
| 79 | + |
| 80 | +@chart( |
| 81 | + id="line-revenue-trend", |
| 82 | + title="매출 추이", |
| 83 | + type="line", |
| 84 | + params_serializer=RevenueTrendParamsSerializer, |
| 85 | + unit="원", |
| 86 | + options={"value_format": ",.0f"}, |
| 87 | +) |
| 88 | +def _revenue_trend(p: DashboardParams) -> dict: |
| 89 | + # 순매출 = 환불 제외(paid+used). 총매출 = 환불 포함 결제총액. (판매 시각 기준 — 환불 시점은 미반영) |
| 90 | + statuses = ( |
| 91 | + OrderProductRelation.PURCHASED_STOCK_STATUS |
| 92 | + if p.revenue_type == REVENUE_NET |
| 93 | + else OrderProductRelation.PURCHASED_OR_REFUNDED_STATUS |
| 94 | + ) |
| 95 | + rows = ( |
| 96 | + p.ticket_opr_qs() |
| 97 | + .filter(status__in=statuses) |
| 98 | + .annotate(paid_at=first_paid_at_subquery()) |
| 99 | + .filter(paid_at__gte=p.date_from, paid_at__lt=p.date_to) |
| 100 | + .values_list("product_id", "product__name", "price", "donation_price", "paid_at") |
| 101 | + ) |
| 102 | + agg: dict[tuple[str, object], int] = defaultdict(int) |
| 103 | + names: dict[object, str] = {} |
| 104 | + for pid, name, price, donation, paid_at in rows: |
| 105 | + names.setdefault(pid, name) |
| 106 | + agg[(period_label(paid_at, p.granularity), pid)] += price + donation |
| 107 | + return assemble_product_series(agg, names, p) |
| 108 | + |
| 109 | + |
| 110 | +@chart( |
| 111 | + id="line-checkin-trend", title="체크인 추이", type="line", params_serializer=CheckinTrendParamsSerializer, unit="명" |
| 112 | +) |
| 113 | +def _checkin_trend(p: DashboardParams) -> dict: |
| 114 | + counts = checkin_counts_by_label(p) |
| 115 | + data = [ |
| 116 | + {"label": label, "values": {"checkin": counts.get(label, 0)}} |
| 117 | + for label in period_label_range(p.date_from, p.date_to, p.granularity) |
| 118 | + ] |
| 119 | + return {"series": [{"key": "checkin", "name": "체크인 수"}], "data": data} |
| 120 | + |
| 121 | + |
| 122 | +@chart( |
| 123 | + id="line-checkin-rate-trend", |
| 124 | + title="체크인율 추이", |
| 125 | + type="line", |
| 126 | + params_serializer=CheckinTrendParamsSerializer, |
| 127 | + unit="%", |
| 128 | +) |
| 129 | +def _checkin_rate_trend(p: DashboardParams) -> dict: |
| 130 | + counts = checkin_counts_by_label(p) |
| 131 | + total = p.ticket_opr_qs().filter(status__in=OrderProductRelation.PURCHASED_STOCK_STATUS).count() |
| 132 | + data = [] |
| 133 | + cumulative = 0 |
| 134 | + for label in period_label_range(p.date_from, p.date_to, p.granularity): |
| 135 | + cumulative += counts.get(label, 0) |
| 136 | + pct = round(cumulative / total * 100, 1) if total else 0.0 |
| 137 | + data.append({"label": label, "values": {"rate": pct}}) |
| 138 | + return {"series": [{"key": "rate", "name": "체크인율"}], "data": data} |
0 commit comments