feat(project): meeting board button opens a blank Google Slides deck
A "회의록 보드" button next to attendees opens the week's Google Slides deck in its own window. The deck is found (Drive appProperties) or created in the shared drive MEETING_BOARD_FOLDER_ID as one BLANK slide, named like "10월 2주차 (10/5~10/11)". Needs a token with Drive and Slides scopes; the authorize script now requests them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,177 @@
|
||||
"""Google 슬라이드(회의록 보드) 공통 계층 — 공유 드라이브 폴더에 빈 슬라이드를 만들거나 찾는다.
|
||||
|
||||
인증은 google_sheets 와 같은 설정을 쓰되 권한 범위(scope)가 다르다(Drive + Slides).
|
||||
설정된 쪽을 자동 선택(서비스 계정 우선).
|
||||
|
||||
1) 사용자 OAuth 리프레시 토큰
|
||||
· `GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN` — 없으면 `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN`
|
||||
토큰은 Drive·Slides 권한까지 받아야 한다: `python scripts/google_sheets_authorize.py`(스프레드시트·Drive·Slides 한 번에)
|
||||
· `GOOGLE_SHEETS_OAUTH_CLIENT_ID` / `..._SECRET`(없으면 로그인용 `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`)
|
||||
2) 서비스 계정 JSON — `GOOGLE_SHEETS_CREDENTIALS` / `GOOGLE_SHEETS_CREDENTIALS_JSON`
|
||||
서비스 계정 이메일을 대상 공유 드라이브의 **콘텐츠 관리자** 이상으로 추가해야 한다.
|
||||
|
||||
- 회의록 보드 폴더: `MEETING_BOARD_FOLDER_ID`(기본 = 회의록 보드 공유 드라이브).
|
||||
- 같은 주차 보드를 다시 누르면 새로 만들지 않고 Drive 파일 appProperties(`dbxMeetingWeek` = 주차 시작일)로 찾는다
|
||||
— 파일 이름을 바꿔도 같은 보드가 열린다. 휴지통에 버리면 다음에 새로 만든다.
|
||||
- 비밀값(키/토큰)은 로그·화면에 절대 출력하지 않는다. 라이브러리·설정이 없으면 `enabled = False`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
from typing import Any
|
||||
|
||||
SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/presentations"]
|
||||
TOKEN_URI = "https://oauth2.googleapis.com/token"
|
||||
DEFAULT_BOARD_FOLDER_ID = "0AGF3CIEboPQiUk9PVA"
|
||||
PRESENTATION_MIME = "application/vnd.google-apps.presentation"
|
||||
WEEK_KEY = "dbxMeetingWeek"
|
||||
|
||||
# googleapiclient 의 HTTP 클라이언트는 스레드 안전하지 않고, 같은 주차를 두 사람이 동시에 누르면
|
||||
# 보드가 두 개 생길 수 있으므로 찾기·만들기는 한 번에 하나씩.
|
||||
_LOCK = threading.Lock()
|
||||
|
||||
|
||||
class GoogleSlidesError(RuntimeError):
|
||||
"""화면에 보여도 되는 사유(비밀값 없음)."""
|
||||
|
||||
|
||||
def board_folder_id() -> str:
|
||||
return (os.getenv("MEETING_BOARD_FOLDER_ID") or "").strip() or DEFAULT_BOARD_FOLDER_ID
|
||||
|
||||
|
||||
def board_url(file_id: str) -> str:
|
||||
return f"https://docs.google.com/presentation/d/{file_id}/edit"
|
||||
|
||||
|
||||
class GoogleSlidesClient:
|
||||
def __init__(self) -> None:
|
||||
self.enabled = False
|
||||
self.reason = ""
|
||||
self.auth_mode = ""
|
||||
self._drive: Any = None
|
||||
self._slides: Any = None
|
||||
try:
|
||||
from googleapiclient.discovery import build
|
||||
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_SLIDES_OAUTH_REFRESH_TOKEN 또는 GOOGLE_SHEETS_* 설정 필요)"
|
||||
return
|
||||
try:
|
||||
self._drive = build("drive", "v3", credentials=creds, cache_discovery=False)
|
||||
self._slides = build("slides", "v1", credentials=creds, cache_discovery=False)
|
||||
except Exception as exc: # noqa: BLE001 — 사유만(비밀값 미출력)
|
||||
self.reason = f"Google 클라이언트 생성 실패: {type(exc).__name__}"
|
||||
return
|
||||
self.enabled = True
|
||||
|
||||
# ── 인증(google_sheets 와 같은 설정, 범위만 Drive·Slides) ──
|
||||
def _service_account_creds(self) -> Any:
|
||||
raw = (os.getenv("GOOGLE_SHEETS_CREDENTIALS_JSON") or "").strip()
|
||||
path = (os.getenv("GOOGLE_SHEETS_CREDENTIALS") or "").strip()
|
||||
if not raw and not path:
|
||||
return None
|
||||
try:
|
||||
info = json.loads(raw) if raw else json.loads(open(path, encoding="utf-8").read())
|
||||
from google.oauth2.service_account import Credentials
|
||||
|
||||
creds = Credentials.from_service_account_info(info, scopes=SCOPES)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
self.reason = f"서비스 계정 인증 실패: {type(exc).__name__}"
|
||||
return None
|
||||
self.auth_mode = "service_account"
|
||||
return creds
|
||||
|
||||
def _oauth_creds(self) -> Any:
|
||||
token = (os.getenv("GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN") or os.getenv("GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN") or "").strip()
|
||||
if not token:
|
||||
return None
|
||||
cid = (os.getenv("GOOGLE_SHEETS_OAUTH_CLIENT_ID") or os.getenv("GOOGLE_CLIENT_ID") or "").strip()
|
||||
secret = (os.getenv("GOOGLE_SHEETS_OAUTH_CLIENT_SECRET") or os.getenv("GOOGLE_CLIENT_SECRET") or "").strip()
|
||||
if not cid or not secret:
|
||||
self.reason = "GOOGLE_SHEETS_OAUTH_CLIENT_ID/SECRET 미설정"
|
||||
return None
|
||||
try:
|
||||
from google.oauth2.credentials import Credentials
|
||||
|
||||
creds = Credentials(token=None, refresh_token=token, token_uri=TOKEN_URI,
|
||||
client_id=cid, client_secret=secret, scopes=SCOPES)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
self.reason = f"OAuth 자격 생성 실패: {type(exc).__name__}"
|
||||
return None
|
||||
self.auth_mode = "oauth"
|
||||
return creds
|
||||
|
||||
# ────────────────────────────────────────────────
|
||||
def open_week_board(self, *, folder_id: str, week_key: str, title: str) -> dict[str, Any]:
|
||||
"""그 주차 보드(빈 슬라이드)를 찾고, 없으면 폴더에 만든다 → {id, url, created}."""
|
||||
if not self.enabled:
|
||||
raise GoogleSlidesError(self.reason or "Google 슬라이드 연동이 꺼져 있습니다.")
|
||||
with _LOCK:
|
||||
try:
|
||||
found = self._find(folder_id, week_key)
|
||||
if found:
|
||||
return {"id": found, "url": board_url(found), "created": False}
|
||||
file_id = self._create_blank(folder_id, week_key, title)
|
||||
except GoogleSlidesError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise GoogleSlidesError(_friendly(exc)) from None
|
||||
return {"id": file_id, "url": board_url(file_id), "created": True}
|
||||
|
||||
def _find(self, folder_id: str, week_key: str) -> str | None:
|
||||
q = (f"'{folder_id}' in parents and trashed = false and mimeType = '{PRESENTATION_MIME}' "
|
||||
f"and appProperties has {{ key='{WEEK_KEY}' and value='{week_key}' }}")
|
||||
res = self._drive.files().list(
|
||||
q=q, fields="files(id)", pageSize=1, supportsAllDrives=True, includeItemsFromAllDrives=True,
|
||||
corpora="allDrives",
|
||||
).execute()
|
||||
files = res.get("files") or []
|
||||
return files[0]["id"] if files else None
|
||||
|
||||
def _create_blank(self, folder_id: str, week_key: str, title: str) -> str:
|
||||
meta = {"name": title, "mimeType": PRESENTATION_MIME, "parents": [folder_id],
|
||||
"appProperties": {WEEK_KEY: week_key}}
|
||||
file_id = self._drive.files().create(body=meta, fields="id", supportsAllDrives=True).execute()["id"]
|
||||
# 새 프레젠테이션의 첫 장은 "제목·부제목" 틀(TITLE 레이아웃) — 틀 없는 빈 장(BLANK) 하나만 남긴다
|
||||
pres = self._slides.presentations().get(presentationId=file_id, fields="slides.objectId").execute()
|
||||
reqs: list[dict[str, Any]] = [{"createSlide": {"insertionIndex": 0, "slideLayoutReference": {"predefinedLayout": "BLANK"}}}]
|
||||
reqs += [{"deleteObject": {"objectId": s["objectId"]}} for s in pres.get("slides") or []]
|
||||
self._slides.presentations().batchUpdate(presentationId=file_id, body={"requests": reqs}).execute()
|
||||
return file_id
|
||||
|
||||
|
||||
def _friendly(exc: Exception) -> str:
|
||||
"""Google API 오류 → 화면용 문구(비밀값·원문 응답 미포함)."""
|
||||
status = getattr(getattr(exc, "resp", None), "status", None)
|
||||
text = str(exc)
|
||||
if "invalid_scope" in text or "insufficient" in text.lower() or "ACCESS_TOKEN_SCOPE_INSUFFICIENT" in text:
|
||||
return "Google 권한(Drive·Slides)이 없는 토큰입니다. 토큰을 다시 발급해 주세요(scripts/google_sheets_authorize.py)."
|
||||
if "invalid_grant" in text:
|
||||
return "Google 토큰이 만료·폐기되었습니다. 토큰을 다시 발급해 주세요."
|
||||
if status == 404:
|
||||
return "회의록 보드 폴더를 찾을 수 없습니다(MEETING_BOARD_FOLDER_ID·공유 드라이브 접근 권한 확인)."
|
||||
if status == 403:
|
||||
return "Google Drive·Slides 접근이 거부되었습니다(API 사용 설정·공유 드라이브 권한 확인)."
|
||||
return f"Google 슬라이드 처리 실패({type(exc).__name__}{f' {status}' if status else ''})."
|
||||
|
||||
|
||||
_CLIENT: GoogleSlidesClient | None = None
|
||||
_CLIENT_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def get_client() -> GoogleSlidesClient:
|
||||
"""프로세스당 하나(설정이 비어 있으면 매번 다시 확인 — .env 를 고치고 재시작 없이도 사유가 갱신되게)."""
|
||||
global _CLIENT
|
||||
with _CLIENT_LOCK:
|
||||
if _CLIENT is None or not _CLIENT.enabled:
|
||||
_CLIENT = GoogleSlidesClient()
|
||||
return _CLIENT
|
||||
@@ -3268,6 +3268,29 @@ def api_update_meeting(request: Request, week_start: str, payload: dict[str, Any
|
||||
return JSONResponse(out)
|
||||
|
||||
|
||||
def meeting_board_title(ws: date) -> str:
|
||||
"""회의록 보드 파일 이름 — 그 주차의 월 + 주차 + 기간. 예: 10월 2주차 (10/5~10/11)."""
|
||||
a, b = store.week_period(ws)
|
||||
return f"{a.month}월 {store.week_number(a)}주차 ({a.month}/{a.day}~{b.month}/{b.day})"
|
||||
|
||||
|
||||
@router.post("/api/goals/meetings/{week_start}/board")
|
||||
def api_open_meeting_board(request: Request, week_start: str) -> JSONResponse:
|
||||
"""회의록 보드 — 그 주차의 빈 Google 슬라이드(공유 드라이브 MEETING_BOARD_FOLDER_ID)를 찾거나 만들어 주소를 돌려준다.
|
||||
회의록을 볼 수 있는 사람 누구나(빈 슬라이드 하나라 관리자 전용으로 막지 않음). 같은 주차는 늘 같은 파일."""
|
||||
from app.integrations.google_slides import GoogleSlidesError, board_folder_id, get_client # noqa: WPS433
|
||||
|
||||
_require_user(request)
|
||||
ws = _goal_call(store.validate_period_start, week_start)
|
||||
title = meeting_board_title(ws)
|
||||
try:
|
||||
board = get_client().open_week_board(folder_id=board_folder_id(), week_key=ws.isoformat(), title=title)
|
||||
except GoogleSlidesError as exc:
|
||||
logger.warning("meeting board unavailable: %s", exc) # 사유 문구만(비밀값 없음)
|
||||
raise HTTPException(status_code=503, detail=str(exc))
|
||||
return JSONResponse({"ok": True, "url": board["url"], "created": board["created"], "title": title})
|
||||
|
||||
|
||||
@router.delete("/api/goals/meetings/{week_start}")
|
||||
def api_delete_meeting(request: Request, week_start: str) -> JSONResponse:
|
||||
_require_admin(request)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261007b" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261007c" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -162,6 +162,10 @@
|
||||
{% if edit %}<button type="button" class="pj-meet-attend-add" id="pj-meet-attend-add"><span class="material-symbols-outlined">person_add</span>참석자</button>
|
||||
{% elif not attendee_list %}<span class="pj-muted">—</span>{% endif %}
|
||||
</div>
|
||||
{# 회의록 보드 — 그 주차의 빈 Google 슬라이드를 독립 창으로(없으면 공유 드라이브에 만든다, project.js initMeetBoard) #}
|
||||
<button type="button" class="pj-btn pj-btn-sm pj-meet-board-btn" id="pj-meet-board"
|
||||
title="이 주차의 Google 슬라이드 보드를 새 창으로 엽니다(처음이면 공유 드라이브에 빈 슬라이드를 만듭니다)">
|
||||
<span class="material-symbols-outlined">co_present</span>회의록 보드</button>
|
||||
</div>
|
||||
|
||||
{# ── 구역별 줄 — 왼쪽: 이번주 / 오른쪽: 전주 리뷰(지난 회의록 같은 줄) ── #}
|
||||
@@ -263,5 +267,5 @@
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project-meeting-cells.js?v=20261007a" defer></script>
|
||||
<script src="/static/project.js?v=20261007c" defer></script>
|
||||
<script src="/static/project.js?v=20261007d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -207,5 +207,5 @@
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project.js?v=20261007c" defer></script>
|
||||
<script src="/static/project.js?v=20261007d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -614,6 +614,7 @@
|
||||
<li>줄별 <b>정량 목표</b>에 각 항목의 이번 주차 목표를 적습니다. 금액(원 단위)뿐 아니라 <code>20개</code>처럼 글도 됩니다. 전체 매출 목표는 연간 목표 표의 주차별 목표에서 정합니다.</li>
|
||||
<li>각 항목의 <b>주요 업무</b>에 실행할 일과 일정을 적습니다.</li>
|
||||
<li><span class="pjh-ui">참석자</span>를 눌러 프로젝트 관리 권한이 있는 등록 직원 중 선택합니다. 찾기·전원 선택·모두 해제를 사용할 수 있으며, 칩의 <span class="pjh-ui">×</span>로 참석자를 뺍니다.</li>
|
||||
<li>참석자 오른쪽 <span class="pjh-ui">회의록 보드</span>를 누르면 그 주차의 Google 슬라이드가 새 창으로 열립니다. 처음 누르면 회의록 보드 공유 드라이브에 빈 슬라이드(제목 틀 없음)를 <b>"10월 2주차 (10/5~10/11)"</b> 같은 이름으로 만들고, 다음부터는 같은 파일을 엽니다. 직원 누구나 열 수 있으며, 슬라이드 편집 권한은 공유 드라이브 권한을 따릅니다. 창이 안 뜨면 브라우저의 팝업 허용을 확인하세요.</li>
|
||||
<li>위쪽 오른쪽 <b>결정 사항 · 메모</b>에 회의 결론과 다음주까지 확인할 일을 적습니다.</li>
|
||||
</ol>
|
||||
<p>금액은 <code>1,200,000</code>·<code>120만</code>·<code>1.5억</code>·<code>3천만</code>·<code>1억2천만</code>처럼 입력할 수 있습니다. <kbd>Enter</kbd> 또는 칸을 떠날 때 원 단위로 저장되고, 빈칸은 값을 지웁니다. 숫자로 읽히지 않는 값(예: <code>20개</code>)은 적은 글 그대로 저장됩니다. 글·메모는 입력을 약 0.8초 멈추거나 칸을 떠날 때, 참석자는 바꾸는 즉시 저장됩니다.</p>
|
||||
|
||||
@@ -104,5 +104,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261007c" defer></script>
|
||||
<script src="/static/project.js?v=20261007d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261007c" defer></script>
|
||||
<script src="/static/project.js?v=20261007d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -492,5 +492,5 @@
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20261007c" defer></script>
|
||||
<script src="/static/project.js?v=20261007d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -70,5 +70,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261007c" defer></script>
|
||||
<script src="/static/project.js?v=20261007d" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -2554,6 +2554,9 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important;
|
||||
/* 참석자 — 멤버 칩 + [참석자] 고르기 창(body 에 붙음) */
|
||||
.pj-meet-attend { display: flex; align-items: flex-start; gap: 8px; margin: 0 0 10px; font-size: 12.5px; }
|
||||
.pj-meet-attend-label { font-weight: 600; color: var(--pj-ink-soft); line-height: 30px; flex: none; }
|
||||
.pj-meet-board-btn { flex: none; align-self: center; gap: 4px; }
|
||||
.pj-meet-board-btn .material-symbols-outlined { font-size: 17px; }
|
||||
@media print { .pj-meet-board-btn { display: none !important; } }
|
||||
.pj-meet-attend-chips { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; min-height: 30px; padding: 2px; border-radius: 8px; }
|
||||
.pj-meet-chip {
|
||||
display: inline-flex; align-items: center; gap: 5px; height: 28px; padding: 0 4px 0 3px; border: 1px solid var(--pj-border);
|
||||
|
||||
@@ -10125,11 +10125,42 @@
|
||||
else window.addEventListener("resize", apply);
|
||||
}
|
||||
|
||||
// ── 회의록 보드 — 그 주차의 빈 Google 슬라이드를 독립 창으로. 팝업 차단을 피하려고 누르는 순간 빈 창을 먼저 열고,
|
||||
// 서버(POST …/board — 없으면 공유 드라이브에 만든다)가 주소를 주면 그 창을 슬라이드로 바꾼다. 같은 주차는 같은 창 이름.
|
||||
function initMeetBoard(week) {
|
||||
const btn = el("pj-meet-board");
|
||||
if (!btn) return;
|
||||
btn.addEventListener("click", async function () {
|
||||
const w = window.open("", "pj_meet_board_" + week, "popup=yes,width=1400,height=900");
|
||||
if (w) {
|
||||
try {
|
||||
if (w.location.href === "about:blank") {
|
||||
w.document.title = "회의록 보드";
|
||||
w.document.body.innerHTML = '<p style="font:14px sans-serif;padding:24px;color:#555">회의록 보드를 여는 중…</p>';
|
||||
}
|
||||
} catch (_) {} // 이미 슬라이드가 열린 창(다른 출처)이면 그대로 두고 주소만 바꾼다
|
||||
}
|
||||
btn.disabled = true;
|
||||
try {
|
||||
const res = await api("POST", "/project/api/goals/meetings/" + week + "/board", {});
|
||||
if (w && !w.closed) { w.location.replace(res.url); w.focus(); }
|
||||
else showToast("팝업이 차단되어 창을 열지 못했습니다. 이 사이트의 팝업을 허용한 뒤 다시 눌러 주세요.", "error");
|
||||
if (res.created) showToast("회의록 보드를 만들었습니다: " + res.title);
|
||||
} catch (e) {
|
||||
if (w && !w.closed) w.close();
|
||||
showToast("회의록 보드를 열지 못했습니다: " + e.message, "error");
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function initGoalMeeting() {
|
||||
const pane = el("pj-meet-pane");
|
||||
if (!pane) return;
|
||||
initMeetOrder();
|
||||
initMeetTop(pane);
|
||||
initMeetBoard(pane.dataset.week);
|
||||
const week = pane.dataset.week, year = pane.dataset.year;
|
||||
const isAdmin = pane.dataset.admin === "true";
|
||||
const SCROLL_KEY = "pj_meet_scroll";
|
||||
|
||||
Reference in New Issue
Block a user