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:
@@ -43,6 +43,12 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# GOOGLE_SHEETS_CREDENTIALS=/opt/www/main/secrets/google-sheets-sa.json
|
||||
# 또는 파일 대신 JSON 본문을 통째로 (한 줄):
|
||||
# GOOGLE_SHEETS_CREDENTIALS_JSON={"type":"service_account", ...}
|
||||
#
|
||||
# 주간 회의록 "회의록 보드"(주차마다 빈 Google 슬라이드) — 위 Google 인증을 같이 쓴다.
|
||||
# OAuth 토큰은 Drive·Slides 권한까지 필요: scripts/google_sheets_authorize.py 로 다시 발급(시트 권한도 함께 들어감)
|
||||
# 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 — 비우면 이 기본값
|
||||
|
||||
# ─── 휴가 관리 모듈 (vacation_db) ───
|
||||
# 설정해야 모듈이 동작한다(미설정 시 "설정 필요" 안내, JSON 폴백 없음).
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -110,6 +110,21 @@ docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < s
|
||||
docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('goal_week_targets') AS t, (SELECT count(*) FROM information_schema.columns WHERE table_name='goal_meeting_items' AND column_name='result_note') AS note;"
|
||||
```
|
||||
|
||||
## 주간 회의록 "회의록 보드"(Google 슬라이드) 설정
|
||||
|
||||
회의록 화면의 [회의록 보드] 는 주차마다 빈 Google 슬라이드를 공유 드라이브(`MEETING_BOARD_FOLDER_ID`, 기본 `0AGF3CIEboPQiUk9PVA`)에
|
||||
만들어 새 창으로 연다(`app/integrations/google_slides.py`). DB 변경 없음. 인증은 쿠팡 시트와 같은 Google 설정을 쓰되 **Drive·Slides 권한**이 더 필요하다.
|
||||
|
||||
1. Google Cloud Console(OAuth 클라이언트가 있는 프로젝트) → API 라이브러리에서 **Google Drive API**, **Google Slides API** 사용 설정
|
||||
2. 개발 PC에서 토큰 재발급(시트·Drive·Slides 권한을 한 번에 받는다) — 공유 드라이브에 쓸 수 있는 계정으로 로그인·동의
|
||||
```bash
|
||||
python scripts/google_sheets_authorize.py --client-id <ID> --client-secret <SECRET>
|
||||
```
|
||||
3. 서버 `/opt/www/main/.env` 의 `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 을 새 토큰으로 바꾸고(쿠팡 시트도 같은 토큰으로 계속 동작)
|
||||
`docker compose up -d` 로 다시 띄운다. 토큰은 비밀값 — Git·메신저에 남기지 않는다.
|
||||
|
||||
설정이 없거나 권한이 모자라면 버튼을 눌렀을 때 사유가 안내되고(503), 회의록 다른 기능은 그대로 동작한다.
|
||||
|
||||
## 주간 회의록 정량 목표·결과 글 마이그레이션 (021)
|
||||
|
||||
021은 `goal_meeting_items` 에 `target_text`·`result_text` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 미적용이면 정량 목표·결과는 예전처럼 숫자만 받는다.
|
||||
|
||||
@@ -867,6 +867,13 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
마지막 월요일 → 7일 전 월요일)을 옮김 — 옮길 자리에 회의록이 있으면 옮기지 않고 NOTICE. 이미 쓰던 9/28(월) 회의록은 9월 마지막 주차
|
||||
(9/28~30)로 그대로 남고, 10월 1주차(10/1~4)는 새로 만든다(그래서 10/5 주차의 지난주 리뷰는 10/1~4 회의록이 생겨야 채워진다).
|
||||
- 코드는 020 전에도 동작(결과 글 보기만, 주차 목표 없음, 월요일 아닌 주차 회의록 만들기만 503 안내).
|
||||
- **회의록 보드**(2026-10-07): 참석자 오른쪽 [회의록 보드] → 그 주차의 **빈 Google 슬라이드**를 독립 창(`window.open` popup, 창 이름
|
||||
`pj_meet_board_{주차}`)으로. 누르는 순간 빈 창을 먼저 열고(팝업 차단 회피) `POST /project/api/goals/meetings/{주차 시작일}/board`
|
||||
(프로젝트 권한자 누구나) 가 준 주소로 바꾼다. 서버(`app/integrations/google_slides.py`)는 공유 드라이브 `MEETING_BOARD_FOLDER_ID`
|
||||
(기본 0AGF3CIEboPQiUk9PVA)에서 Drive appProperties `dbxMeetingWeek = 주차 시작일` 인 슬라이드를 찾고, 없으면 만든다 —
|
||||
이름 `{월}월 {n}주차 ({기간})`(`router.meeting_board_title`), 첫 장의 제목·부제목 틀(TITLE 레이아웃)을 지우고 틀 없는 BLANK 한 장만.
|
||||
파일 이름을 바꿔도 같은 보드, 휴지통에 버리면 다음에 새로 만든다. 인증은 Google 시트 설정 재사용 + Drive·Slides 범위
|
||||
(`GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN` 없으면 시트 토큰 — Drive·Slides 권한으로 재발급 필요, docs/DEPLOYMENT.md). DB 변경 없음.
|
||||
- **정량 목표·결과(금액)에 글**(마이그레이션 021, 2026-10-07): 입력이 숫자로 읽히면(`store.validate_meeting_amount` — 1,200,000 · 120만 ·
|
||||
1.5억) 지금처럼 `target_amount`/`result_amount`(원 정수), 아니면(예: "20개", 100자까지) `target_text`/`result_text` 에 — 둘 중 하나만
|
||||
채운다(숫자로 바꾸면 글은 비움). 화면·전주 목표는 글이 있으면 글, 없으면 쉼표 숫자. 021 전이면 글은 예전처럼 400(숫자 오류).
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""Google 스프레드시트 쓰기용 refresh token 1회 발급 스크립트.
|
||||
"""Google 스프레드시트 쓰기·회의록 보드(Drive·Slides)용 refresh token 1회 발급 스크립트.
|
||||
|
||||
조직 정책(`iam.disableServiceAccountKeyCreation`)으로 서비스 계정 키를 만들 수 없을 때
|
||||
사용자 계정 OAuth 로 서버가 시트에 기록하도록 하기 위한 토큰을 받는다.
|
||||
|
||||
사전 준비 (Google Cloud Console)
|
||||
1. API 및 서비스 → 라이브러리 → "Google Sheets API" 사용
|
||||
1. API 및 서비스 → 라이브러리 → "Google Sheets API"·"Google Drive API"·"Google Slides API" 사용
|
||||
2. API 및 서비스 → OAuth 동의 화면 구성(내부 또는 외부)
|
||||
3. 사용자 인증 정보 → 사용자 인증 정보 만들기 → **OAuth 클라이언트 ID**
|
||||
→ 애플리케이션 유형 **데스크톱 앱** → 클라이언트 ID / 보안 비밀 확인
|
||||
@@ -14,9 +14,9 @@
|
||||
또는 환경변수로:
|
||||
GOOGLE_SHEETS_OAUTH_CLIENT_ID / GOOGLE_SHEETS_OAUTH_CLIENT_SECRET
|
||||
|
||||
브라우저가 열리면 **시트를 편집할 수 있는 계정**으로 로그인·동의한다.
|
||||
브라우저가 열리면 **시트를 편집할 수 있고 회의록 보드 공유 드라이브에 쓸 수 있는 계정**으로 로그인·동의한다.
|
||||
마지막에 출력되는 refresh token 을 서버 `.env` 의
|
||||
`GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 에 넣는다.
|
||||
`GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 에 넣는다(시트·회의록 보드가 같이 쓴다).
|
||||
|
||||
주의
|
||||
- 출력된 refresh token 은 비밀값이다. Git·메신저에 남기지 말 것.
|
||||
@@ -30,7 +30,12 @@ import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
|
||||
# 스프레드시트(쿠팡 출고리스트) + Drive·Slides(주간 회의록 보드 — 공유 드라이브에 빈 슬라이드 만들기)
|
||||
SCOPES = [
|
||||
"https://www.googleapis.com/auth/spreadsheets",
|
||||
"https://www.googleapis.com/auth/drive",
|
||||
"https://www.googleapis.com/auth/presentations",
|
||||
]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
|
||||
@@ -459,6 +459,29 @@ function meetServer(env, st) {
|
||||
check("[2e] 월 목표 직접 저장 요청 없음", !st.metric);
|
||||
});
|
||||
|
||||
// ════════════════════ [2f] 회의록 보드 — 누르는 순간 창을 열고, 서버가 준 Google 슬라이드 주소로 바꾼다 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_ro, MEET_URL); // 보기만 하는 사람도 연다
|
||||
meetServer(env);
|
||||
let posted = null;
|
||||
env.route("POST", /\/project\/api\/goals\/meetings\/2026-09-28\/board$/, function (u, body) {
|
||||
posted = u;
|
||||
return { body: { ok: true, url: "https://docs.google.com/presentation/d/abc/edit", created: true, title: "9월 5주차 (9/28~9/30)" } };
|
||||
});
|
||||
await boot(env);
|
||||
const popup = { closed: false, focused: false, location: { href: "about:blank", replace: function (u) { this.href = u; } },
|
||||
document: { title: "", body: {} }, focus: function () { this.focused = true; }, close: function () { this.closed = true; } };
|
||||
let opened = null;
|
||||
env.w.open = function (url, name, features) { opened = { url: url, name: name, features: features }; return popup; };
|
||||
const btn = env.d.getElementById("pj-meet-board");
|
||||
check("[2f] 참석자 옆 회의록 보드 버튼", !!btn && !!btn.closest(".pj-meet-attend"));
|
||||
btn.click();
|
||||
check("[2f] 누르는 순간 독립 창(popup)을 연다", opened && opened.name === "pj_meet_board_2026-09-28" && /popup/.test(opened.features), opened);
|
||||
await settle(); await wait(10); await settle();
|
||||
check("[2f] 서버에 그 주차 보드 요청", !!posted);
|
||||
check("[2f] 창을 슬라이드 주소로", popup.location.href === "https://docs.google.com/presentation/d/abc/edit" && popup.focused);
|
||||
});
|
||||
|
||||
// ════════════════════ [3] 목표 표 — 글 저장 실패면 구조 변경·표 교체 중단 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { promptAnswer: "새 영역" });
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
"""회의록 보드(Google 슬라이드) — 가짜 Drive·Slides 로 찾기·빈 슬라이드 만들기·API 를 검증한다. 네트워크·DB 없이 실행."""
|
||||
import importlib
|
||||
import unittest
|
||||
from datetime import date
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.integrations import google_slides as gs
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
|
||||
|
||||
class Call:
|
||||
def __init__(self, result):
|
||||
self.result = result
|
||||
|
||||
def execute(self):
|
||||
return self.result
|
||||
|
||||
|
||||
class FakeDrive:
|
||||
def __init__(self, existing=None):
|
||||
self.existing, self.created, self.queries = existing, [], []
|
||||
|
||||
def files(self):
|
||||
return self
|
||||
|
||||
def list(self, **kw):
|
||||
self.queries.append(kw)
|
||||
return Call({"files": [{"id": self.existing}] if self.existing else []})
|
||||
|
||||
def create(self, body, fields, supportsAllDrives):
|
||||
assert supportsAllDrives is True
|
||||
self.created.append(body)
|
||||
return Call({"id": "new-file"})
|
||||
|
||||
|
||||
class FakeSlides:
|
||||
def __init__(self):
|
||||
self.batches = []
|
||||
|
||||
def presentations(self):
|
||||
return self
|
||||
|
||||
def get(self, presentationId, fields):
|
||||
return Call({"slides": [{"objectId": "title-slide"}]})
|
||||
|
||||
def batchUpdate(self, presentationId, body):
|
||||
self.batches.append((presentationId, body))
|
||||
return Call({})
|
||||
|
||||
|
||||
def client_with(drive, slides):
|
||||
c = gs.GoogleSlidesClient.__new__(gs.GoogleSlidesClient)
|
||||
c.enabled, c.reason, c.auth_mode = True, "", "oauth"
|
||||
c._drive, c._slides = drive, slides
|
||||
return c
|
||||
|
||||
|
||||
class MeetingBoardTests(unittest.TestCase):
|
||||
def test_existing_board_is_reused_without_creating(self):
|
||||
drive, slides = FakeDrive(existing="abc"), FakeSlides()
|
||||
out = client_with(drive, slides).open_week_board(folder_id="F", week_key="2026-10-05", title="10월 2주차 (10/5~10/11)")
|
||||
self.assertEqual(out, {"id": "abc", "url": "https://docs.google.com/presentation/d/abc/edit", "created": False})
|
||||
self.assertEqual(drive.created, [])
|
||||
q = drive.queries[0]["q"]
|
||||
self.assertIn("'F' in parents", q)
|
||||
self.assertIn("key='dbxMeetingWeek' and value='2026-10-05'", q)
|
||||
self.assertTrue(drive.queries[0]["supportsAllDrives"] and drive.queries[0]["includeItemsFromAllDrives"])
|
||||
|
||||
def test_new_board_is_blank_slide_in_folder(self):
|
||||
drive, slides = FakeDrive(), FakeSlides()
|
||||
out = client_with(drive, slides).open_week_board(folder_id="F", week_key="2026-10-05", title="10월 2주차 (10/5~10/11)")
|
||||
self.assertTrue(out["created"])
|
||||
body = drive.created[0]
|
||||
self.assertEqual(body["parents"], ["F"])
|
||||
self.assertEqual(body["name"], "10월 2주차 (10/5~10/11)")
|
||||
self.assertEqual(body["mimeType"], gs.PRESENTATION_MIME)
|
||||
self.assertEqual(body["appProperties"], {"dbxMeetingWeek": "2026-10-05"})
|
||||
# 제목·부제목 틀이 있는 첫 장은 지우고 틀 없는 빈 장(BLANK) 하나만
|
||||
reqs = slides.batches[0][1]["requests"]
|
||||
self.assertEqual(reqs[0]["createSlide"]["slideLayoutReference"], {"predefinedLayout": "BLANK"})
|
||||
self.assertEqual(reqs[1:], [{"deleteObject": {"objectId": "title-slide"}}])
|
||||
|
||||
def test_disabled_client_and_api_errors_have_safe_messages(self):
|
||||
off = gs.GoogleSlidesClient.__new__(gs.GoogleSlidesClient)
|
||||
off.enabled, off.reason = False, "Google 인증 미설정"
|
||||
with self.assertRaises(gs.GoogleSlidesError):
|
||||
off.open_week_board(folder_id="F", week_key="2026-10-05", title="t")
|
||||
self.assertIn("토큰을 다시 발급", gs._friendly(RuntimeError("invalid_scope: Bad Request")))
|
||||
|
||||
def test_title_uses_month_week_and_period(self):
|
||||
self.assertEqual(api.meeting_board_title(date(2026, 10, 5)), "10월 2주차 (10/5~10/11)")
|
||||
self.assertEqual(api.meeting_board_title(date(2026, 11, 1)), "11월 1주차 (11/1~11/8)")
|
||||
|
||||
def test_api_returns_url_and_maps_errors(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
client = TestClient(app)
|
||||
fake = client_with(FakeDrive(existing="abc"), FakeSlides())
|
||||
with patch.object(api, "_require_user", return_value={"email": "u@test"}), \
|
||||
patch.object(gs, "get_client", return_value=fake):
|
||||
r = client.post("/project/api/goals/meetings/2026-10-05/board")
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
self.assertEqual(r.json()["url"], "https://docs.google.com/presentation/d/abc/edit")
|
||||
self.assertEqual(client.post("/project/api/goals/meetings/2026-10-06/board").status_code, 400) # 주차 시작일 아님
|
||||
off = gs.GoogleSlidesClient.__new__(gs.GoogleSlidesClient)
|
||||
off.enabled, off.reason = False, "Google 인증 미설정"
|
||||
with patch.object(api, "_require_user", return_value={"email": "u@test"}), \
|
||||
patch.object(gs, "get_client", return_value=off):
|
||||
r = client.post("/project/api/goals/meetings/2026-10-05/board")
|
||||
self.assertEqual(r.status_code, 503)
|
||||
self.assertIn("Google 인증 미설정", r.json()["detail"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user