diff --git a/.env.example b/.env.example index c328a6b..2edac20 100644 --- a/.env.example +++ b/.env.example @@ -49,6 +49,10 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/ # Cloud Console 에서 Google Drive API·Google Slides API 사용 설정. 서비스 계정이면 공유 드라이브 콘텐츠 관리자로 추가. # GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN=replace-me # 비우면 GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN 사용 # MEETING_BOARD_FOLDER_ID=0AGF3CIEboPQiUk9PVA # 보드를 만들 공유 드라이브(폴더) ID — 비우면 이 기본값 +# +# Project 업무 파일 → 구글 드라이브(설명란·보드 카드·세부 업무에 파일 끌어 놓기) — 위 Google 인증(Drive 권한)을 같이 쓴다. +# 그 아래 프로젝트/섹션/업무/세부 업무 폴더를 자동으로 만든다. 서비스 계정이면 공유 드라이브 폴더여야 올라간다. +# PROJECT_DRIVE_FOLDER_ID=1Zdak2FtACRJ6peOnA9zD22hsbbsTixJG # 업무 파일 최상위 폴더 ID — 비우면 이 기본값 # ─── 휴가 관리 모듈 (vacation_db) ─── # 설정해야 모듈이 동작한다(미설정 시 "설정 필요" 안내, JSON 폴백 없음). diff --git a/app/integrations/google_drive.py b/app/integrations/google_drive.py new file mode 100644 index 0000000..b968110 --- /dev/null +++ b/app/integrations/google_drive.py @@ -0,0 +1,186 @@ +"""Google 드라이브 — 업무 파일 올리기(설명란·보드 카드·세부 업무에 파일 끌어 놓기, 2026-10-19). + +인증은 google_slides 와 같은 설정(서비스 계정 우선, 없으면 OAuth 리프레시 토큰 — Drive 권한 포함)을 쓴다. + +- 최상위 폴더 `PROJECT_DRIVE_FOLDER_ID`(기본 = 업무 파일 폴더). 그 아래 `프로젝트/섹션/업무/세부 업무` 폴더를 이름으로 + 찾고 없으면 만든다(휴지통 폴더 제외). 같은 경로를 두 사람이 동시에 만들지 않게 폴더 찾기·만들기는 한 번에 하나씩. +- 올린 파일은 appProperties `dbxTaskId` = 업무 id — 설명란에서 링크를 지우면 **우리가 올린 파일만** 휴지통으로 보낸다 + (다른 사람이 붙여 넣은 드라이브 링크는 건드리지 않음). 링크를 되살리면(되돌리기·잘라 붙이기) 휴지통에서 꺼낸다. + 휴지통 파일은 드라이브가 30일 뒤 지운다. +- 서비스 계정은 내 드라이브 저장 용량이 없어 "공유 드라이브" 폴더여야 올라간다(OAuth 토큰이면 그 사용자 드라이브도 됨). +- 비밀값(키/토큰)은 로그·화면에 절대 출력하지 않는다. 라이브러리·설정이 없으면 `enabled = False`. +""" + +from __future__ import annotations + +import os +import re +import threading +from typing import Any, BinaryIO, Iterable + +from app.integrations.google_slides import GoogleSlidesClient, _friendly + +DEFAULT_FOLDER_ID = "1Zdak2FtACRJ6peOnA9zD22hsbbsTixJG" +FOLDER_MIME = "application/vnd.google-apps.folder" +TASK_KEY = "dbxTaskId" +CHUNK = 8 * 1024 * 1024 +# 설명란 링크에서 드라이브 파일 id — 우리가 넣는 링크 모양(https://drive.google.com/file/d//view) +FILE_LINK_RE = re.compile(r"https://drive\.google\.com/file/d/([A-Za-z0-9_-]{10,})") + +# 폴더 찾기·만들기는 한 번에 하나(같은 폴더가 두 개 생기지 않게). 파일 올리기·휴지통은 호출마다 따로 만든 +# 서비스 객체로(googleapiclient 의 HTTP 는 스레드 안전하지 않다) — 큰 파일이 다른 사람 업로드를 막지 않게. +_FOLDER_LOCK = threading.Lock() + + +class GoogleDriveError(RuntimeError): + """화면에 보여도 되는 사유(비밀값 없음).""" + + +def root_folder_id() -> str: + return (os.getenv("PROJECT_DRIVE_FOLDER_ID") or "").strip() or DEFAULT_FOLDER_ID + + +def file_url(file_id: str) -> str: + return f"https://drive.google.com/file/d/{file_id}/view" + + +def file_ids_in(html: str) -> set[str]: + """설명 HTML 안의 드라이브 파일 링크 id 들.""" + return set(FILE_LINK_RE.findall(html or "")) + + +def folder_name(name: Any) -> str: + """폴더 이름 — 앞뒤 공백·줄바꿈 정리, 너무 길면 자름, 비면 "(이름 없음)".""" + s = re.sub(r"\s+", " ", str(name or "")).strip()[:120] + return s or "(이름 없음)" + + +def _q(value: str) -> str: + """Drive 검색어 따옴표 안 글자(역슬래시·작은따옴표 이스케이프).""" + return value.replace("\\", "\\\\").replace("'", "\\'") + + +class GoogleDriveFiles(GoogleSlidesClient): + """google_slides 의 인증(서비스 계정·OAuth)을 그대로 쓰고 Drive 만 연다.""" + + def __init__(self) -> None: # noqa: D107 — 부모 __init__ 대신(Slides 서비스는 만들지 않음) + self.enabled = False + self.reason = "" + self.auth_mode = "" + self._creds: Any = None + try: + import googleapiclient.discovery # noqa: F401 + import googleapiclient.http # noqa: F401 + except ImportError: + self.reason = "google-api-python-client 미설치" + return + creds = self._service_account_creds() + if creds is None: + creds = self._oauth_creds() + if creds is None: + if not self.reason: + self.reason = "Google 인증 미설정(GOOGLE_SHEETS_CREDENTIALS 또는 GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN 필요)" + return + self._creds = creds + self.enabled = True + + def _service(self) -> Any: + from googleapiclient.discovery import build + + return build("drive", "v3", credentials=self._creds, cache_discovery=False) + + def _check(self) -> None: + if not self.enabled: + raise GoogleDriveError(self.reason or "Google 드라이브 연동이 꺼져 있습니다.") + + # ──────────────────────────────────────────────── + def ensure_folder_path(self, names: Iterable[str], *, root: str | None = None) -> str: + """root 아래 names 순서대로 폴더를 찾거나 만들고 마지막 폴더 id.""" + self._check() + parent = root or root_folder_id() + with _FOLDER_LOCK: + try: + drive = self._service() + for raw in names: + name = folder_name(raw) + q = (f"'{_q(parent)}' in parents and name = '{_q(name)}' and mimeType = '{FOLDER_MIME}' " + "and trashed = false") + res = drive.files().list( + q=q, fields="files(id)", pageSize=1, supportsAllDrives=True, includeItemsFromAllDrives=True, + corpora="allDrives", orderBy="createdTime", + ).execute() + found = res.get("files") or [] + if found: + parent = found[0]["id"] + continue + parent = drive.files().create( + body={"name": name, "mimeType": FOLDER_MIME, "parents": [parent]}, + fields="id", supportsAllDrives=True, + ).execute()["id"] + except GoogleDriveError: + raise + except Exception as exc: # noqa: BLE001 + raise GoogleDriveError(_friendly_drive(exc)) from None + return parent + + def upload(self, *, folder_id: str, name: str, stream: BinaryIO, mimetype: str, task_id: int) -> dict[str, Any]: + """폴더에 파일 하나 → {id, name, url}. 이름은 원래 파일 이름.확장자 그대로.""" + self._check() + from googleapiclient.http import MediaIoBaseUpload + + try: + media = MediaIoBaseUpload(stream, mimetype=mimetype or "application/octet-stream", chunksize=CHUNK, + resumable=True) + meta = {"name": name, "parents": [folder_id], "appProperties": {TASK_KEY: str(int(task_id))}} + f = self._service().files().create(body=meta, media_body=media, fields="id,name", + supportsAllDrives=True).execute() + except Exception as exc: # noqa: BLE001 + raise GoogleDriveError(_friendly_drive(exc)) from None + return {"id": f["id"], "name": f.get("name") or name, "url": file_url(f["id"])} + + def ours(self, file_id: str) -> dict[str, Any] | None: + """우리가 올린 파일이면 {trashed, task_id}, 아니면(남의 파일·없는 파일·권한 없음) None.""" + self._check() + try: + f = self._service().files().get(fileId=file_id, fields="trashed,appProperties", + supportsAllDrives=True).execute() + except Exception: # noqa: BLE001 — 지워졌거나 볼 수 없는 파일은 건드리지 않는다 + return None + tid = (f.get("appProperties") or {}).get(TASK_KEY) + if not tid: + return None + return {"trashed": bool(f.get("trashed")), "task_id": tid} + + def set_trashed(self, file_id: str, trashed: bool) -> None: + self._check() + try: + self._service().files().update(fileId=file_id, body={"trashed": bool(trashed)}, + supportsAllDrives=True).execute() + except Exception as exc: # noqa: BLE001 + raise GoogleDriveError(_friendly_drive(exc)) from None + + +def _friendly_drive(exc: Exception) -> str: + status = getattr(getattr(exc, "resp", None), "status", None) + text = str(exc) + if "storageQuotaExceeded" in text or "do not have storage quota" in text: + return ("서비스 계정은 내 드라이브에 파일을 올릴 수 없습니다 — 업무 파일 폴더를 공유 드라이브에 두거나 " + "OAuth 토큰(GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN)을 쓰세요.") + if status == 404: + return "업무 파일 폴더를 찾을 수 없습니다(PROJECT_DRIVE_FOLDER_ID·폴더 공유 권한 확인)." + if status == 403 and "insufficient" not in text.lower(): + return "Google 드라이브 접근이 거부되었습니다(폴더 편집 권한·Drive API 사용 설정 확인)." + return _friendly(exc).replace("Google 슬라이드 처리 실패", "Google 드라이브 처리 실패") + + +_CLIENT: GoogleDriveFiles | None = None +_CLIENT_LOCK = threading.Lock() + + +def get_client() -> GoogleDriveFiles: + """프로세스당 하나(설정이 비어 있으면 매번 다시 확인 — .env 를 고치고 재시작 없이도 사유가 갱신되게).""" + global _CLIENT + with _CLIENT_LOCK: + if _CLIENT is None or not _CLIENT.enabled: + _CLIENT = GoogleDriveFiles() + return _CLIENT diff --git a/app/modules/notice/templates/notice/admin.html b/app/modules/notice/templates/notice/admin.html index 0f483ec..5447f80 100644 --- a/app/modules/notice/templates/notice/admin.html +++ b/app/modules/notice/templates/notice/admin.html @@ -2,7 +2,7 @@ {% block head_extra %} {# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #} - + {% endblock %} @@ -64,7 +64,7 @@ - + {% endif %} {% endblock %} diff --git a/app/modules/performance/CLAUDE.md b/app/modules/performance/CLAUDE.md index 94d6f60..7fd78a3 100644 --- a/app/modules/performance/CLAUDE.md +++ b/app/modules/performance/CLAUDE.md @@ -43,7 +43,11 @@ ## 매출 실적 화면 (2026-10-19) -- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합(ROAS = 매출 합 ÷ 광고비 합). 광고비 표 없으면 줄 없음. +- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 %, 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다. +- 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀). +- 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx` → `performance.js initNextUpdate`, 자동 업데이트 규칙 `auto_sync.next_slot` 과 같게 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트 꺼지면 숨김). + +- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = **일 합계 금액 ÷ 일 합계 광고비**(2026-10-19 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다; `roas` 총매출·`roas_net` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음. - **매출 단위** 원·천원·백만원 — 설정 "보기 설정"(누구나, 이 브라우저 쿠키 `perf_unit`), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로. - 설정의 진단 카드(쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교)는 2026-10-19 화면에서 뺐다(서버 API `marketplaces/{code}/reconcile`·`daily-check` 는 진단용으로 남김). diff --git a/app/modules/performance/dashboard.py b/app/modules/performance/dashboard.py index d736cf6..98fcf2f 100644 --- a/app/modules/performance/dashboard.py +++ b/app/modules/performance/dashboard.py @@ -53,7 +53,9 @@ def amount_text(value: Any, unit: str = "won") -> str: def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cells: Mapping[Any, Any], period: Any, q_start: date, q_end: date) -> None: """매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값(ROAS = 그 쇼핑몰 매출 ÷ 광고비, 구글·메타·네이버는 보고서 ROAS). - 카페24 = 구글·메타 두 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합(ROAS = 매출 합 ÷ 광고비 합). + 카페24 = 구글·메타 두 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합. + 일 합계 ROAS 는 단순하게 일 합계 금액 ÷ 일 합계 광고비(2026-10-19) — roas = 총매출 기준, roas_net = 수수료 차감 매출 기준 + (화면 표시 기준에 따라 하나만 보인다). 예전엔 광고비가 있는 쇼핑몰 매출만 더해 일 합계 금액과 맞지 않았다. 광고비 표(005)가 없거나 읽기 실패면 줄 없음.""" from . import ad_spend # noqa: WPS433 @@ -87,7 +89,7 @@ def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cel for r in table: s = date.fromisoformat(r["from"]) if r.get("from") else period.start e = date.fromisoformat(r["to"]) if r.get("to") else period.end - tot_spend = tot_sales = 0 + tot_spend = 0 for c in codes: lines = [] for ch, label in by_code.get(c, ()): @@ -100,9 +102,10 @@ def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cel tot_spend += amt if lines: r["ads"][c] = lines - tot_sales += sales(c, s, e) if tot_spend: - r["ads_total"] = {"amount": tot_spend, "roas": ad_spend.roas(tot_sales, tot_spend)} + tot = r.get("total") or {} + r["ads_total"] = {"amount": tot_spend, "roas": ad_spend.roas(tot.get("gross") or 0, tot_spend), + "roas_net": ad_spend.roas(tot.get("net") or 0, tot_spend)} def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]: @@ -152,28 +155,16 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date, cur = calc.sum_range(cells, codes, period.start, period.end) prev = calc.sum_range(cells, codes, cmp_start, cmp_end) - mtd = calc.sum_range(cells, codes, month_period.start, month_period.end) - m_prev = calc.sum_range(cells, codes, m_cmp_start, m_cmp_end) - ytd = calc.sum_range(cells, codes, year_period.start, year_period.end) - y_prev = calc.sum_range(cells, codes, y_cmp_start, y_cmp_end) - has_prev = prev.gross != 0 or prev.commission != 0 period_word = {"day": "오늘" if period.start == today else "해당일", "week": "이번주" if period.start <= today <= period.end else "해당 주", "month": "이번달" if period.start <= today <= period.end else "해당 월", "year": "올해" if period.start <= today <= period.end else "해당 연도", "custom": "선택 기간"}[period.kind] + # KPI 는 수수료 차감 매출 하나만(2026-10-19) — 화면 왼쪽 한 줄(금액 + 비교 기간 대비 %). + # 총매출·수수료·월 누적·연 누적 카드는 뺐다(아래 표·월/연 누적 카드에 같은 값이 있다). kpis = [ - {"key": "gross", "label": f"{period_word} 총매출", "value": cur.gross, "primary": True, - "delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label}, {"key": "net", "label": f"{period_word} 수수료 차감 매출", "value": cur.net, "primary": True, "delta": calc.pct_change(cur.net, prev.net), "cmp": cmp_label}, - {"key": "commission", "label": f"{period_word} 수수료", "value": cur.commission, - "delta": calc.pct_change(cur.commission, prev.commission) if has_prev else None, "cmp": cmp_label, - "invert": True}, - {"key": "mtd", "label": f"{month_period.label} 누적 매출", "value": mtd.gross, - "delta": calc.pct_change(mtd.gross, m_prev.gross), "cmp": m_cmp_label}, - {"key": "ytd", "label": f"{year_period.label} 누적 매출", "value": ytd.gross, - "delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label}, ] share = calc.by_code(cells, codes, period.start, period.end) diff --git a/app/modules/performance/router.py b/app/modules/performance/router.py index 0f379b9..2285d73 100644 --- a/app/modules/performance/router.py +++ b/app/modules/performance/router.py @@ -116,7 +116,7 @@ def dashboard_page( from_: str | None = Query(None, alias="from"), to: str | None = None, m: list[str] = Query(default=[]), - metric: str = "gross", + metric: str = "net", ): from app.main import render_template # noqa: WPS433 @@ -134,11 +134,27 @@ def dashboard_page( custom_from=_parse_date(from_), custom_to=_parse_date(to), selected=m, holidays=_holidays(), configured=creds.configured_codes(list(all_adapters())), ) - ctx["metric"] = metric if metric in ("gross", "commission", "net") else "gross" + ctx["metric"] = metric if metric in ("gross", "commission", "net") else "net" + ctx["auto_sync"] = _auto_sync_ctx() _unit_ctx(request, ctx) return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx}) +def _auto_sync_ctx() -> dict[str, Any] | None: + """다음 자동 업데이트까지 남은 시간(2026-10-19) — 화면이 초 단위로 센다. 회차가 지나면 화면이 같은 규칙 + (hours·slot, KST)으로 다음 회차를 계산한다. 서버 시각(now)으로 PC 시계 차이를 보정. 자동 업데이트가 꺼져 있으면 None.""" + from app.timezone import now_kst # noqa: WPS433 + + from . import auto_sync # noqa: WPS433 + + if not auto_sync.enabled(): + return None + hours = auto_sync.hour_window() + now = now_kst() + return {"next_at": auto_sync.next_slot(now, hours).isoformat(), "now": now.isoformat(timespec="milliseconds"), + "hours": list(hours), "slot": auto_sync.SLOT_MINUTES} + + def _unit_ctx(request: Request, ctx: dict[str, Any]) -> None: """매출 단위(원·천원·백만원) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_unit)에 둔다. 템플릿은 amt(v) 로 그린다.""" from .dashboard import UNIT_COOKIE, UNITS, amount_text, normalize_unit # noqa: WPS433 diff --git a/app/modules/performance/templates/performance/ads.html b/app/modules/performance/templates/performance/ads.html index bf0e758..06044d5 100644 --- a/app/modules/performance/templates/performance/ads.html +++ b/app/modules/performance/templates/performance/ads.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#} {%- macro roas(p) -%}{%- if p is not none -%}({{ "{:,}".format(p) }}%){%- endif -%}{%- endmacro -%} @@ -224,4 +224,4 @@ } | tojson }} {% endblock %} -{% block scripts %}{% endblock %} +{% block scripts %}{% endblock %} diff --git a/app/modules/performance/templates/performance/index.html b/app/modules/performance/templates/performance/index.html index 940a9dd..c85b2ca 100644 --- a/app/modules/performance/templates/performance/index.html +++ b/app/modules/performance/templates/performance/index.html @@ -1,6 +1,6 @@ {% extends "erp_base.html" %} -{% block head_extra %}{% endblock %} +{% block head_extra %}{% endblock %} {%- macro won(v) -%} {%- if v is none -%} @@ -16,6 +16,14 @@ {%- for a in lines or [] -%}{% if a.label %}{{ a.label }}{% endif %}{{ amt(a.amount) }}{% if a.roas is not none %}({{ "{:,}".format(a.roas) }}%){% endif %}{%- endfor -%} {%- endmacro -%} +{#- 일 합계 광고비(ROAS%) — ROAS = 일 합계 금액 ÷ 일 합계 광고비. 수수료 차감 매출 보기면 차감 매출 기준, 그 밖엔 총매출 기준 -#} +{%- macro adl_total(a) -%} + {%- for key, cls in (("roas", "for-gross"), ("roas_net", "for-net")) -%} + {%- set rs = a[key] -%} + {{ amt(a.amount) }}{% if rs is not none %}({{ "{:,}".format(rs) }}%){% endif %} + {%- endfor -%} +{%- endmacro -%} + {#- 한 칸에 총매출/수수료/차감매출 세 값을 넣고, 보기 전환은 CSS(data-metric)로. -#} {%- macro m3(m) -%} {{ won(m.gross) }}{{ won(m.commission) }}{{ won(m.net) }} @@ -72,6 +80,10 @@
마지막 업데이트 {{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }} + {% if auto_sync %} + {# 다음 자동 업데이트까지 남은 시간 — 초 단위로 실시간(performance.js initNextUpdate, 2026-10-19) #} + 다음 업데이트까지 — + {% endif %} {# 업데이트 중에도 누를 수 있다 — 진행 중인 업데이트(수동·자동)의 진행 창을 다시 연다(2026-10-19) #}