Merge branch 'feat/perf-net-kpi-drive-files'
This commit is contained in:
@@ -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 폴백 없음).
|
||||
|
||||
@@ -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/<id>/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
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
{% block head_extra %}
|
||||
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019h" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019i" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
||||
{% endblock %}
|
||||
@@ -64,7 +64,7 @@
|
||||
</section>
|
||||
</div>
|
||||
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
|
||||
<script src="/static/project.js?v=20261019e" defer></script>
|
||||
<script src="/static/project.js?v=20261019f" defer></script>
|
||||
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -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` 는 진단용으로 남김).
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019e" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019f" />{% endblock %}
|
||||
|
||||
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
||||
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
||||
@@ -224,4 +224,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261019d" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261019e" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019e" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019f" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -16,6 +16,14 @@
|
||||
{%- for a in lines or [] -%}<span class="perf-adl" title="{{ (a.label ~ ' ') if a.label }}광고비 {{ '{:,}'.format(a.amount) }}원{% if a.roas is not none %} · ROAS {{ '{:,}'.format(a.roas) }}%{% endif %}">{% if a.label %}<i>{{ a.label }}</i>{% endif %}{{ amt(a.amount) }}{% if a.roas is not none %}<em>({{ "{:,}".format(a.roas) }}%)</em>{% endif %}</span>{%- endfor -%}
|
||||
{%- endmacro -%}
|
||||
|
||||
{#- 일 합계 광고비(ROAS%) — ROAS = 일 합계 금액 ÷ 일 합계 광고비. 수수료 차감 매출 보기면 차감 매출 기준, 그 밖엔 총매출 기준 -#}
|
||||
{%- macro adl_total(a) -%}
|
||||
{%- for key, cls in (("roas", "for-gross"), ("roas_net", "for-net")) -%}
|
||||
{%- set rs = a[key] -%}
|
||||
<span class="perf-adl perf-adl-tot {{ cls }}" title="광고비 합계 {{ '{:,}'.format(a.amount) }}원{% if rs is not none %} · ROAS {{ '{:,}'.format(rs) }}% (일 합계 {{ '수수료 차감 매출' if key == 'roas_net' else '총매출' }} ÷ 광고비){% endif %}">{{ amt(a.amount) }}{% if rs is not none %}<em>({{ "{:,}".format(rs) }}%)</em>{% endif %}</span>
|
||||
{%- endfor -%}
|
||||
{%- endmacro -%}
|
||||
|
||||
{#- 한 칸에 총매출/수수료/차감매출 세 값을 넣고, 보기 전환은 CSS(data-metric)로. -#}
|
||||
{%- macro m3(m) -%}
|
||||
<span class="v v-gross">{{ won(m.gross) }}</span><span class="v v-commission">{{ won(m.commission) }}</span><span class="v v-net">{{ won(m.net) }}</span>
|
||||
@@ -72,6 +80,10 @@
|
||||
<div class="perf-update">
|
||||
<span class="perf-muted" id="perf-last-update">마지막 업데이트
|
||||
<b>{{ (last_update_at or '')[:16] | replace('T', ' ') or '—' }}</b></span>
|
||||
{% if auto_sync %}
|
||||
{# 다음 자동 업데이트까지 남은 시간 — 초 단위로 실시간(performance.js initNextUpdate, 2026-10-19) #}
|
||||
<span class="perf-muted perf-next-update" id="perf-next-update" title="자동 업데이트: 매일 {{ auto_sync.hours[0] }}~{{ auto_sync.hours[1] }}시 {{ auto_sync.slot }}분마다">다음 업데이트까지 <b>—</b></span>
|
||||
{% endif %}
|
||||
{# 업데이트 중에도 누를 수 있다 — 진행 중인 업데이트(수동·자동)의 진행 창을 다시 연다(2026-10-19) #}
|
||||
<button type="button" class="erp-btn erp-btn-primary{% if running %} is-running{% endif %}" id="perf-sync-btn"
|
||||
title="{% if running %}업데이트 진행 상황 보기{% else %}지금 보고 있는 기간({{ period.label }}, 오늘까지)의 매출을 쇼핑몰에서 다시 가져옵니다{% endif %}">
|
||||
@@ -93,24 +105,18 @@
|
||||
{% endif %}
|
||||
<div class="perf-notice" id="perf-sync-result" hidden></div>
|
||||
|
||||
<!-- ── KPI ── -->
|
||||
<div class="perf-kpis">
|
||||
{% for k in kpis %}
|
||||
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
|
||||
<div class="perf-kpi-label">{{ k.label }}</div>
|
||||
<div class="perf-kpi-value">{{ money(k.value) }}</div>
|
||||
<div class="perf-kpi-delta">
|
||||
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
|
||||
{% else %}
|
||||
{% set up = k.delta > 0 %}
|
||||
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif up != (k.invert or false) %}is-up{% else %}is-down{% endif %}">
|
||||
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
|
||||
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
<!-- ── KPI — 수수료 차감 매출 한 줄(금액 + 비교 기간 대비 %, 2026-10-19) ── -->
|
||||
{% for k in kpis %}
|
||||
<div class="perf-kpi-line" title="{{ k.label }}">
|
||||
<b class="perf-kpi-line-value">{{ money(k.value) }}</b>
|
||||
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
|
||||
{% else %}
|
||||
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif k.delta > 0 %}is-up{% else %}is-down{% endif %}">
|
||||
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
|
||||
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
|
||||
<!-- ── 일자 × 쇼핑몰 ── -->
|
||||
<div class="erp-card perf-card">
|
||||
@@ -155,7 +161,7 @@
|
||||
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}>{{ m3(m) }}{{ adl(r.ads[c]) }}</td>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<td class="perf-num perf-td-total">{{ m3(r.total) }}{% if r.ads_total %}{{ adl([r.ads_total]) }}{% endif %}</td>
|
||||
<td class="perf-num perf-td-total">{{ m3(r.total) }}{% if r.ads_total %}{{ adl_total(r.ads_total) }}{% endif %}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
@@ -263,8 +269,9 @@
|
||||
"period_end": period.end.isoformat(),
|
||||
"today": today,
|
||||
"unit": unit,
|
||||
"manual_upload_names": manual_upload_names
|
||||
"manual_upload_names": manual_upload_names,
|
||||
"auto_sync": auto_sync
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261019d" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261019e" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019e" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261019f" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
@@ -219,4 +219,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261019d" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261019e" defer></script>{% endblock %}
|
||||
|
||||
@@ -65,8 +65,8 @@ def test_ad_lines_under_sales_cells():
|
||||
# 쿠팡 = 쿠팡(윙) 광고비, ROAS = 쿠팡 매출 ÷ 광고비 = 600,000 ÷ 200,000
|
||||
assert day5["ads"]["coupang"] == [{"label": "", "amount": 200_000, "roas": 300}]
|
||||
assert "naver" not in day5["ads"] # 그날 네이버 광고비 없음 → 줄 없음
|
||||
# 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = 그 쇼핑몰들 매출 합 ÷ 광고비 합
|
||||
assert day5["ads_total"] == {"amount": 350_000, "roas": 743} # 2,600,000 ÷ 350,000
|
||||
# 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = 일 합계 금액 ÷ 일 합계 광고비(총매출·수수료 차감 매출 두 기준, 2026-10-19)
|
||||
assert day5["ads_total"] == {"amount": 350_000, "roas": 743, "roas_net": 743} # 2,600,000 ÷ 350,000(수수료율 없음)
|
||||
day6 = next(r for r in ctx["table"] if r.get("date") == "2026-10-06")
|
||||
assert day6["ads"]["naver"] == [{"label": "", "amount": 300_000, "roas": 150}]
|
||||
week = next(r for r in ctx["table"] if r["kind"] == "week")
|
||||
@@ -78,7 +78,7 @@ def test_ad_lines_under_sales_cells():
|
||||
def test_ad_lines_follow_shop_filter_and_missing_table():
|
||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["coupang"])
|
||||
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||
assert list(day5["ads"]) == ["coupang"] and day5["ads_total"] == {"amount": 200_000, "roas": 300}
|
||||
assert list(day5["ads"]) == ["coupang"] and day5["ads_total"] == {"amount": 200_000, "roas": 300, "roas_net": 300}
|
||||
ctx = dashboard.build_dashboard(_Store(ads_missing=True), kind="week", anchor=TODAY, today=TODAY)
|
||||
assert all(r["ads"] == {} and r["ads_total"] is None for r in ctx["table"]) # 광고비 표 없어도 매출 화면은 그대로
|
||||
|
||||
@@ -128,3 +128,26 @@ def test_dashboard_page_renders_unit_and_ad_lines(monkeypatch):
|
||||
client.cookies.set("perf_unit", "million")
|
||||
html = client.get("/performance/?period=week&d=2026-10-07").text
|
||||
assert "단위: 백만원" in html and ">2.0<" in html and '"unit": "million"' in html
|
||||
|
||||
|
||||
def test_total_roas_uses_whole_day_total():
|
||||
"""일 합계 ROAS = 그날 일 합계 금액(광고비 없는 쇼핑몰 매출 포함) ÷ 일 합계 광고비 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다."""
|
||||
class _S(_Store):
|
||||
def ad_amounts(self, start, end):
|
||||
rows = {(date(2026, 10, 5), "google"): 100_000}
|
||||
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
|
||||
return rows, {k: "manual" for k in rows}
|
||||
|
||||
def ad_roas(self, start, end):
|
||||
return {}
|
||||
|
||||
ctx = dashboard.build_dashboard(_S(), kind="week", anchor=TODAY, today=TODAY)
|
||||
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||
assert day5["total"]["gross"] == 2_600_000 # 카페24 2,000,000 + 쿠팡 600,000(광고비 없음)
|
||||
assert day5["ads_total"] == {"amount": 100_000, "roas": 2600, "roas_net": 2600}
|
||||
|
||||
|
||||
def test_kpi_is_net_only():
|
||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
|
||||
assert [k["key"] for k in ctx["kpis"]] == ["net"]
|
||||
assert ctx["kpis"][0]["value"] == 2_600_000 + 1_234_567
|
||||
|
||||
@@ -46,7 +46,8 @@
|
||||
- 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다.
|
||||
- 사이드바 메뉴: 수신함·전체 보기(Pro user 이상 — 예전 오른쪽 위 "전체 프로젝트" 토글, `?scope=all`, 기본 대시보드)·내 작업(접이식)·목표.
|
||||
- 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다.
|
||||
- 보드 카드 끌기 = 실시간 미리보기(2026-10-19, `startCardDrag`·`placeCardPh`): 원래 카드는 숨기고 점선 자리 표시(`.pj-card-ph`)가 카드 사이로 FLIP 애니메이션, 끄는 모양은 기울어진 복제(`setDragImage`). 놓은 자리 그대로 — 다른 섹션도 PUT stage 뒤 `stages/{id}/tasks/order`(기본 정렬·필터 없음일 때만, 전체 보기는 섹션 맨 끝). 끄는 중엔 실시간 동기화 쉼(`html.pj-card-dragging`). 컬럼 body 는 dragenter 도 preventDefault(안 하면 자리 표시가 들어온 직후 놓을 때 drop 거부).
|
||||
- 보드 카드 끌기 = 실시간 미리보기(2026-10-19, `startCardDrag`·`placeCardPh`): 원래 카드는 숨기고 점선 자리 표시(`.pj-card-ph`)가 카드 사이로 FLIP 애니메이션, 끄는 모양은 기울어진 복제(`setDragImage`). 놓은 자리 그대로 — 다른 섹션도 PUT stage 뒤 `stages/{id}/tasks/order`(정렬 "기본"일 때만, 전체 보기는 섹션 맨 끝).
|
||||
**필터를 켜도 순서 변경 가능**(2026-10-19 버그 수정 — 필터는 브라우저별 localStorage `pj_filter_<id>` 라 필터를 켜 둔 컴퓨터에서만 섹션 안 카드가 늘 제자리로 돌아갔다). 숨은 업무는 제자리(`orderWithHidden`). 카드 속 이미지 끌기가 "Files" 로 오인돼 카드 놓기를 가로채지 않게 `dragHasFiles` 는 카드·세부 업무 끌기 중 false, 카드 img 는 `-webkit-user-drag: none`. 끄는 중엔 실시간 동기화 쉼(`html.pj-card-dragging`). 컬럼 body 는 dragenter 도 preventDefault(안 하면 자리 표시가 들어온 직후 놓을 때 drop 거부).
|
||||
- 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터).
|
||||
- 대시보드: "업무 합계(프로젝트별)" 카드, 섹션별 카드 삭제, 대시보드 업무 목록 패널에서 연 업무 창은 패널 왼쪽에(6-16·6-17·6-19).
|
||||
- 담당자별 패널 날짜 mm/dd(요일)·지난 마감 빨강(6-20).
|
||||
@@ -56,7 +57,10 @@
|
||||
## 업무 창 / 댓글 / 협업자
|
||||
|
||||
- 작업 창은 **저장 버튼 없이 실시간 저장**(칸별 PUT, `saveField`/`saveChain`, 새 작업은 제목이 생기는 순간 생성).
|
||||
- **파일 끌어 놓기 = 첨부**(2026-10-19): 업무 창 아무 곳(`.pj-task-modal-card`, 설명칸 포함)·보드 메인 업무 카드에 파일을 놓으면 `POST /project/api/tasks/{id}/attachments`(여러 개 차례로, `uploadTaskFiles`). 종류 "Files" 로 카드·세부 업무 끌기와 구분, 받는 곳 밖에 놓친 파일은 document 가 막아 화면이 파일로 넘어가지 않음.
|
||||
- **파일 끌어 놓기**(2026-10-19): 종류 "Files" 로 카드·세부 업무 끌기와 구분, 받는 곳 밖에 놓친 파일은 document 가 막아 화면이 파일로 넘어가지 않음.
|
||||
- **설명란·세부 업무 목록·보드 카드(펼친 세부 업무 줄) → 구글 드라이브**: `POST /project/api/tasks/{id}/drive-files`(`app/integrations/google_drive.py`, 최상위 `PROJECT_DRIVE_FOLDER_ID` 기본 `1Zdak2FtACRJ6peOnA9zD22hsbbsTixJG` 아래 `프로젝트/섹션/업무/세부 업무` 폴더 자동, 세부 업무 섹션 = 맨 위 업무 섹션). 링크 제목 = 파일 이름.확장자(새 탭). 설명란 = 놓은 자리(`descEditor.insertDriveFiles`, 올리는 중 표시·저장 미룸), 세부 업무 줄·카드 = `append=true` 로 서버가 설명 끝에 붙임 — 단 지금 업무 창에 열린 업무면 편집기 끝에(옛 설명 저장이 링크를 덮지 않게, `dropDriveFilesOnTask`).
|
||||
- **링크를 지우면 드라이브 휴지통**: `api_update_task` 가 설명 저장 전후 드라이브 링크 id 를 비교 → 백그라운드 `_sync_drive_links` — 우리가 올린 파일(appProperties `dbxTaskId`)만, 다른 업무 설명에 같은 링크가 있으면 그대로(`db.description_mentions`), 링크가 다시 생기면 휴지통에서 꺼냄. DB 변경 없음.
|
||||
- 그 밖의 업무 창 자리 → 예전처럼 첨부(`POST …/attachments`, `uploadTaskFiles`).
|
||||
- 설명란 서식 도구에 글자 색·크기(서버는 span style 의 color·font-size 만 허용, `desc_inline_style`). 주소 붙여넣기 시 자동 링크. 설명란 이미지 더블클릭 = 별도 창 이미지 보기(확대·축소·끌어 이동).
|
||||
- 설명란·댓글에서 @로 멤버 태그(`task_mentions`, 마이그레이션 006) → 수신함에 그 작업이 쌓임. 댓글 `@아이디` 는 아이콘+이름 칩.
|
||||
- 댓글·답글 입력칸은 Enter 등록·Shift+Enter 줄바꿈(textarea).
|
||||
|
||||
@@ -661,6 +661,16 @@ class ProjectStore:
|
||||
).fetchone()
|
||||
return self._serialize(row) if row else None
|
||||
|
||||
def description_mentions(self, *, text: str, exclude_task_id: int) -> bool:
|
||||
"""다른 업무 설명에 text(드라이브 파일 id 등)가 들어 있나 — 링크를 지운 파일을 휴지통에 넣기 전 확인."""
|
||||
like = "%" + text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT 1 FROM tasks WHERE id <> %s AND description LIKE %s LIMIT 1",
|
||||
(int(exclude_task_id), like),
|
||||
).fetchone()
|
||||
return row is not None
|
||||
|
||||
def create_task(
|
||||
self,
|
||||
*,
|
||||
|
||||
@@ -1705,6 +1705,12 @@ def api_update_task(
|
||||
_notify_completed(bg, request, st, project=project, task=task, actor=user["email"])
|
||||
skipped: list[str] = []
|
||||
if "description" in payload:
|
||||
# 드라이브 파일 링크를 지우면 그 파일을 휴지통으로 / 되살리면 꺼낸다(2026-10-19, 백그라운드)
|
||||
from app.integrations.google_drive import file_ids_in # noqa: WPS433
|
||||
|
||||
before, after = file_ids_in(existing.get("description") or ""), file_ids_in(payload["description"])
|
||||
if before != after:
|
||||
bg.add_task(_sync_drive_links, st, task_id, before - after, after - before)
|
||||
skipped = _record_mentions(
|
||||
st, task=task,
|
||||
emails=store.extract_mentions_from_html(payload["description"]),
|
||||
@@ -2492,6 +2498,108 @@ def api_delete_attachment(request: Request, attachment_id: int) -> JSONResponse:
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 업무 파일 → 구글 드라이브(2026-10-19) — 설명란·보드 카드·세부 업무 줄에 파일을 끌어 놓으면
|
||||
# 드라이브 `프로젝트/섹션/업무/세부 업무` 폴더에 올리고 설명란에 "파일 이름.확장자" 링크.
|
||||
# 설명에서 링크를 지우면 그 파일을 드라이브 휴지통으로(api_update_task → _sync_drive_links).
|
||||
# ────────────────────────────────────────────────────────────
|
||||
_MAX_DRIVE_BYTES = 200 * 1024 * 1024 # 200MB
|
||||
|
||||
|
||||
def _drive_folder_names(st: Any, task: dict[str, Any]) -> list[str]:
|
||||
"""[프로젝트, 섹션, 업무, (세부 업무…)] — 섹션은 맨 위 업무의 섹션(세부 업무는 섹션이 없을 수 있다)."""
|
||||
chain = [task]
|
||||
seen = {int(task["id"])}
|
||||
while chain[-1].get("parent_task_id") and len(chain) < 10:
|
||||
parent = st.get_task(task_id=chain[-1]["parent_task_id"])
|
||||
if parent is None or int(parent["id"]) in seen:
|
||||
break
|
||||
seen.add(int(parent["id"]))
|
||||
chain.append(parent)
|
||||
chain.reverse()
|
||||
top = chain[0]
|
||||
return [top.get("project_name") or "", top.get("stage_name") or "섹션 없음"] + [t.get("title") or "" for t in chain]
|
||||
|
||||
|
||||
def drive_link_html(url: str, name: str) -> str:
|
||||
"""설명란 링크 — 제목 = 파일 이름.확장자, 새 탭에서 열기."""
|
||||
import html as _html # noqa: WPS433
|
||||
|
||||
return (f'<a href="{_html.escape(url, quote=True)}" target="_blank" rel="noopener noreferrer">'
|
||||
f"{_html.escape(name)}</a>")
|
||||
|
||||
|
||||
@router.post("/api/tasks/{task_id}/drive-files")
|
||||
def api_upload_drive_file(
|
||||
request: Request, task_id: int, file: UploadFile = File(...), append: bool = Form(False),
|
||||
) -> JSONResponse:
|
||||
"""파일 하나를 구글 드라이브 업무 폴더에 올린다 → {file: {id, name, url}, link_html}.
|
||||
append=true 면 서버가 그 업무 설명 끝에 링크 줄을 붙이고 바뀐 업무를 같이 돌려준다(보드 카드·세부 업무 줄에 놓을 때 —
|
||||
설명란을 열어 둔 업무는 화면이 커서 자리에 직접 넣고 평소처럼 저장)."""
|
||||
from app.integrations import google_drive # noqa: WPS433
|
||||
|
||||
user = _require_user(request)
|
||||
st = _db_or_503(request)
|
||||
task = _task_or_404(st, task_id)
|
||||
_require_task(st, user, task, write=True)
|
||||
client = google_drive.get_client()
|
||||
if not client.enabled:
|
||||
raise HTTPException(status_code=503, detail=f"구글 드라이브 연동이 꺼져 있습니다({client.reason}).")
|
||||
stream = file.file
|
||||
stream.seek(0, 2)
|
||||
size = stream.tell()
|
||||
stream.seek(0)
|
||||
if size > _MAX_DRIVE_BYTES:
|
||||
raise HTTPException(status_code=413, detail="파일이 너무 큽니다(최대 200MB).")
|
||||
if size <= 0:
|
||||
raise HTTPException(status_code=400, detail="빈 파일입니다.")
|
||||
name = (file.filename or "file").replace("\\", "_").replace("/", "_").strip() or "file"
|
||||
try:
|
||||
folder = client.ensure_folder_path(_drive_folder_names(st, task))
|
||||
up = client.upload(folder_id=folder, name=name, stream=stream,
|
||||
mimetype=file.content_type or "application/octet-stream", task_id=task_id)
|
||||
except google_drive.GoogleDriveError as exc:
|
||||
raise HTTPException(status_code=502, detail=str(exc))
|
||||
link = drive_link_html(up["url"], up["name"])
|
||||
out: dict[str, Any] = {"file": up, "link_html": link}
|
||||
if append:
|
||||
cur = st.get_task(task_id=task_id) or task
|
||||
desc = store.sanitize_description_html((cur.get("description") or "") + f"<p>{link}</p>")
|
||||
try:
|
||||
out["task"] = st.update_task(task_id=task_id, fields={"description": desc}, actor=user["email"],
|
||||
assignee_allowed=_registered_project_user)
|
||||
except (ValueError, KeyError):
|
||||
# 파일은 올라갔다 — 링크만 못 붙임(화면이 링크를 알려 준다)
|
||||
out["append_failed"] = True
|
||||
return JSONResponse(out, status_code=201)
|
||||
|
||||
|
||||
def _sync_drive_links(st: Any, task_id: int, removed: set[str], added: set[str]) -> None:
|
||||
"""설명란 드라이브 링크가 빠지면 그 파일을 휴지통으로, 다시 생기면 휴지통에서 꺼낸다(백그라운드).
|
||||
우리가 올린 파일(appProperties dbxTaskId)만, 그리고 다른 업무 설명에 같은 링크가 남아 있으면 휴지통에 넣지 않는다."""
|
||||
from app.integrations import google_drive # noqa: WPS433
|
||||
|
||||
client = google_drive.get_client()
|
||||
if not client.enabled:
|
||||
return
|
||||
for fid in removed:
|
||||
try:
|
||||
if st.description_mentions(text=fid, exclude_task_id=task_id):
|
||||
continue
|
||||
info = client.ours(fid)
|
||||
if info and not info["trashed"]:
|
||||
client.set_trashed(fid, True)
|
||||
except Exception: # noqa: BLE001 — 저장은 이미 끝났다(파일만 남음)
|
||||
logger.warning("드라이브 파일 휴지통 이동 실패: task=%s file=%s", task_id, fid)
|
||||
for fid in added:
|
||||
try:
|
||||
info = client.ours(fid)
|
||||
if info and info["trashed"]:
|
||||
client.set_trashed(fid, False)
|
||||
except Exception: # noqa: BLE001
|
||||
logger.warning("드라이브 파일 복구 실패: task=%s file=%s", task_id, fid)
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# JSON API — 단계 이름/순서 편집
|
||||
# ────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -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=20261019h" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019i" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -289,5 +289,5 @@
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project-meeting-cells.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261019e" defer></script>
|
||||
<script src="/static/project.js?v=20261019f" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019h" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019i" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% 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=20261019e" defer></script>
|
||||
<script src="/static/project.js?v=20261019f" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019h" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019i" />
|
||||
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
@@ -278,7 +278,7 @@
|
||||
<li><b>열기</b> — 카드를 누르면 오른쪽에 업무 편집 창이 열립니다. (<a href="#task">8장</a>)</li>
|
||||
<li><b>완료 체크</b> — 카드 제목 왼쪽의 원형 체크 버튼을 누르면 완료됩니다. 완료된 업무는 <b>녹색 원 안 흰 체크</b>와 흐린 회색 제목으로 표시되며 취소선은 없습니다. 다시 누르면 완료를 취소합니다. 읽기 전용 업무는 상태만 표시합니다.</li>
|
||||
<li><b>담당자·마감일 바로 바꾸기</b> — 카드의 사람 아이콘이나 날짜를 누르면 그 자리에서 바꿉니다. 비어 있으면 카드에 마우스를 올렸을 때 점선 원 아이콘이 나타납니다.</li>
|
||||
<li><b>파일 첨부</b> — 컴퓨터의 파일을 카드 위로 끌어 오면 카드에 점선과 <span class="pjh-ui">놓으면 이 업무에 첨부</span>가 보이고, 놓으면 그 업무의 첨부 파일로 올라갑니다(여러 개 가능).</li>
|
||||
<li><b>파일 → 구글 드라이브</b> — 컴퓨터의 파일을 카드 위로 끌어 오면 카드에 점선과 <span class="pjh-ui">놓으면 드라이브에 올리고 설명에 링크</span>가 보이고, 놓으면 구글 드라이브 업무 폴더에 올라간 뒤 그 업무 설명 끝에 <b>파일 이름.확장자</b> 링크가 붙습니다(여러 개 가능). 펼친 세부 업무 줄에 놓으면 그 세부 업무 설명에 붙습니다. 자세한 규칙은 <a href="#task-drive">구글 드라이브 파일</a>.</li>
|
||||
<li><b>옮기기</b> — 카드를 끌어 다른 섹션에 놓으면 섹션이 바뀌고, 같은 섹션 안에서 위아래로 놓으면 순서가 바뀝니다.
|
||||
끄는 동안 카드는 살짝 기울어진 모양으로 마우스를 따라오고, 카드 사이를 지나는 순간 <b>점선 자리</b>가 그 사이로 옮겨 가며 다른 카드가 미끄러지듯 비켜납니다 — 놓으면 그 자리에 그대로 들어갑니다(다른 섹션도 같음). 섹션 밖에 놓으면 원래 자리로 돌아갑니다.</li>
|
||||
<li><b>우클릭 메뉴</b> — <span class="pjh-ui">열기 · 업무 링크 복사 · 완료로 표시 · 삭제</span></li>
|
||||
@@ -356,7 +356,12 @@
|
||||
</ul>
|
||||
<h3>첨부 파일</h3>
|
||||
<p><span class="pjh-ui">파일 추가</span>로 파일을 올립니다(한 파일 최대 20MB). 파일 이름 옆에 이미지·엑셀·텍스트·PPT·문서·PDF 형식별 아이콘이 표시됩니다. 파일 이름을 누르면 내려받고, <span class="pjh-ui">×</span>로 지웁니다.</p>
|
||||
<p><b>끌어 놓기</b> — 컴퓨터의 파일을 업무 창 <b>아무 곳에나</b> 끌어 오면 창 전체에 점선 안내가 뜨고, 놓으면 첨부 파일로 올라갑니다(여러 개 한꺼번에, 설명칸에 놓아도 첨부). 아직 제목을 쓰지 않은 새 업무·읽기 전용 업무에는 첨부되지 않습니다. 보드의 메인 업무 카드에 파일을 놓아도 그 업무에 첨부됩니다.</p>
|
||||
<p><b>끌어 놓기</b> — 컴퓨터의 파일을 업무 창의 설명란·세부 업무 목록 <b>밖</b>에 끌어 오면 창 전체에 점선 안내가 뜨고, 놓으면 첨부 파일로 올라갑니다(여러 개 한꺼번에). 설명란·세부 업무 목록에 놓으면 첨부가 아니라 구글 드라이브에 올라갑니다(아래). 아직 제목을 쓰지 않은 새 업무·읽기 전용 업무에는 넣을 수 없습니다.</p>
|
||||
<h3 id="task-drive">구글 드라이브 파일</h3>
|
||||
<p><b>설명란에 파일 끌어 놓기</b> — 설명란 위에 점선과 <span class="pjh-ui">놓으면 구글 드라이브에 올리고 이 자리에 링크</span>가 보이고, 놓으면 구글 드라이브에 올라간 뒤 <b>놓은 자리</b>에 <b>파일 이름.확장자</b> 링크가 들어갑니다(누르면 새 탭에서 드라이브 파일). 올리는 동안은 그 자리에 <span class="pjh-ui">구글 드라이브에 올리는 중…</span>이 보입니다.</p>
|
||||
<p><b>세부 업무에 놓기</b> — 업무 창 세부 업무 목록의 줄, 보드 카드의 펼친 세부 업무 줄에 놓으면 그 세부 업무 설명 끝에 링크가 붙습니다. 세부 업무 목록의 빈 곳·보드 카드에 놓으면 그 업무 설명 끝에 붙습니다.</p>
|
||||
<p><b>폴더</b> — 업무 파일 폴더 아래 <b>프로젝트 이름 / 섹션 이름 / 업무 이름 / 세부 업무 이름</b> 폴더를 자동으로 만들어 넣습니다(같은 이름 폴더가 있으면 그 폴더). 폴더는 올릴 때의 이름으로 만들어지고, 나중에 업무 이름을 바꿔도 이미 만든 폴더 이름은 그대로입니다.</p>
|
||||
<p><b>링크를 지우면</b> — 설명에서 링크를 지우고 저장되면 그 파일이 구글 드라이브 <b>휴지통</b>으로 갑니다(30일 안에는 드라이브 휴지통에서 되살릴 수 있고, 링크를 다시 붙여 넣거나 되돌리기로 살리면 휴지통에서 자동으로 꺼냅니다). 같은 링크가 다른 업무 설명에 남아 있으면 지우지 않습니다. 여기서 올린 파일만 해당되고, 직접 붙여 넣은 다른 드라이브 링크는 건드리지 않습니다.</p>
|
||||
<h3>프로젝트 (다른 프로젝트에 추가)</h3>
|
||||
<p>업무 하나를 <b>여러 프로젝트의 보드에 동시에</b> 보이게 합니다. 예) 신상품 프로젝트의 업무를 디자인 프로젝트 보드에도 올리기. 협업자 아래의 프로젝트 줄에 연결 목록·프로젝트 선택·섹션 선택·추가 버튼이 한 줄로 표시됩니다. 창이 좁으면 이 줄을 좌우로 스크롤할 수 있습니다.</p>
|
||||
<ol class="pjh-steps">
|
||||
@@ -738,7 +743,7 @@
|
||||
<p><b>Q. 프로젝트가 목록에 안 보여요.</b><br>그 프로젝트의 멤버가 아니면 보이지 않습니다. 그 프로젝트의 Pro user 이상 멤버나 관리자에게 멤버 배정을 부탁하세요.</p>
|
||||
<p><b>Q. 삭제 버튼을 눌렀는데 “삭제는 만든 사람만 할 수 있습니다”라고 나와요.</b><br>섹션·프로젝트는 만든 사람(또는 Admin 이상)만 지울 수 있습니다. 업무는 멤버 누구나 휴지통으로 지울 수 있습니다.</p>
|
||||
<p><b>Q. 업무를 잘못 지웠어요.</b><br>3개월 안이라면 Pro user 이상이 휴지통에서 복구할 수 있습니다.</p>
|
||||
<p><b>Q. 카드 순서를 끌어도 안 바뀌어요.</b><br>필터를 쓰고 있거나 정렬이 “기본”이 아니면 순서를 바꿀 수 없습니다. 필터 바의 <span class="pjh-ui">초기화</span>를 누른 뒤 다시 해 보세요.</p>
|
||||
<p><b>Q. 카드 순서를 끌어도 안 바뀌어요.</b><br>정렬이 “기본”이 아니면 순서를 바꿀 수 없습니다. 필터 바의 정렬을 <span class="pjh-ui">기본</span>으로 바꾼 뒤 다시 해 보세요. 필터(상태·담당자 등)를 켜 둔 채로는 바꿀 수 있고, 필터로 숨은 업무는 제자리에 그대로 있습니다.</p>
|
||||
<p><b>Q. 다른 사람이 바꾼 내용이 안 보여요.</b><br>보통 8초 안에 자동으로 반영됩니다. 오래 걸리면 새로고침(<kbd>F5</kbd>)하세요.</p>
|
||||
<p><b>Q. 세부 업무를 다른 프로젝트 업무로 옮길 수 있나요?</b><br>세부 업무는 같은 프로젝트 안의 업무로만 옮길 수 있습니다.</p>
|
||||
<p><b>Q. 업무를 두 프로젝트에 같이 두고 싶어요.</b><br>업무 편집 창의 “프로젝트” 칸에서 <span class="pjh-ui">다른 프로젝트에 추가</span>를 쓰세요. (<a href="#task">8장</a>)</p>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019h" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019i" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -106,5 +106,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261019e" defer></script>
|
||||
<script src="/static/project.js?v=20261019f" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019h" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019i" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261019e" defer></script>
|
||||
<script src="/static/project.js?v=20261019f" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019h" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019i" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -108,5 +108,5 @@
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261019e" defer></script>
|
||||
<script src="/static/project.js?v=20261019f" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019h" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019i" />
|
||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<!-- 타임라인 vis-timeline — self-host -->
|
||||
@@ -472,5 +472,5 @@
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20261019e" defer></script>
|
||||
<script src="/static/project.js?v=20261019f" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019h" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261019i" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -70,5 +70,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261019e" defer></script>
|
||||
<script src="/static/project.js?v=20261019f" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -143,6 +143,11 @@ a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited {
|
||||
.perf-kpi-value { font-size: 22px; font-weight: 600; letter-spacing: -.5px; margin: 2px 0; white-space: nowrap; }
|
||||
.perf-kpi.is-primary .perf-kpi-value { font-size: 24px; }
|
||||
.perf-kpi-delta { font-size: 12px; display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; }
|
||||
/* 매출 실적 KPI 한 줄(2026-10-19) — 수수료 차감 매출 금액 + 비교 기간 대비 %, 화면 왼쪽 */
|
||||
.perf-kpi-line { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; font-size: 13px; padding: 2px 2px 0; }
|
||||
.perf-kpi-line-value { font-size: 22px; font-weight: 700; letter-spacing: -.5px; color: var(--color-rich-black); white-space: nowrap; }
|
||||
/* 다음 자동 업데이트까지 남은 시간(초 단위) — 숫자 폭이 바뀌어도 흔들리지 않게 */
|
||||
.perf-next-update b { font-variant-numeric: tabular-nums; }
|
||||
.perf-delta { font-weight: 600; }
|
||||
.perf-delta.is-up { color: var(--perf-good); } /* is-up = 좋음(수수료는 줄어야 좋음, invert) */
|
||||
.perf-delta.is-down { color: var(--perf-down); }
|
||||
@@ -358,6 +363,10 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
.perf-adl i { margin-right: 3px; font-style: normal; font-weight: 500; opacity: .8; }
|
||||
.perf-adl em { margin-left: 1px; font-style: normal; font-weight: 500; opacity: .85; }
|
||||
.perf .perf-main td.is-editing .perf-adl { visibility: hidden; }
|
||||
/* 일 합계 광고비(ROAS%) — ROAS 는 일 합계 금액 ÷ 광고비라 표시 기준(수수료 차감 매출 / 그 밖)에 따라 하나만 */
|
||||
.perf .perf-adl-tot { display: none; }
|
||||
.perf[data-metric="net"] .perf-adl-tot.for-net,
|
||||
.perf:not([data-metric="net"]) .perf-adl-tot.for-gross { display: block; }
|
||||
.perf-adl-note { display: inline-flex; align-items: center; gap: 5px; color: var(--perf-ad); font-weight: 600; }
|
||||
.perf-adl-key { width: 10px; height: 10px; border-radius: 3px; background: var(--perf-ad); }
|
||||
.perf-unit-note { margin-left: 4px; }
|
||||
|
||||
@@ -244,7 +244,6 @@
|
||||
function initDashboard(root) {
|
||||
const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}");
|
||||
const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" };
|
||||
const KEY = "perf_metric";
|
||||
const FIXED_METRIC = root.dataset.fixedMetric || ""; // 광고비 화면 = 금액 하나(gross)뿐
|
||||
const MANUAL_API = data.manual_api || "/performance/api/manual-sales/";
|
||||
const MANUAL_WORD = data.manual_word || "총매출";
|
||||
@@ -258,7 +257,6 @@
|
||||
root.querySelectorAll(".perf-metric .perf-seg").forEach(function (b) {
|
||||
b.classList.toggle("is-active", b.dataset.metric === m);
|
||||
});
|
||||
if (!FIXED_METRIC) { try { localStorage.setItem(KEY, m); } catch (_) {} }
|
||||
drawDaily(m);
|
||||
drawShare(m);
|
||||
root.querySelectorAll(".perf-metric-name").forEach(function (n) { n.textContent = METRIC_NAMES[m]; });
|
||||
@@ -788,9 +786,52 @@
|
||||
box.innerHTML = svg(W, H, g);
|
||||
}
|
||||
|
||||
let saved = null;
|
||||
try { saved = localStorage.getItem(KEY); } catch (_) {}
|
||||
setMetric(saved || root.dataset.metric || "gross");
|
||||
// 매출 실적 화면은 늘 수수료 차감 매출로 연다(2026-10-19) — 서버 기본 data-metric="net", 예전에 고른 보기(localStorage)는 쓰지 않음
|
||||
setMetric(root.dataset.metric || "net");
|
||||
initNextUpdate(data.auto_sync);
|
||||
}
|
||||
|
||||
// 다음 자동 업데이트까지 남은 시간 — 초 단위 실시간(2026-10-19). 서버가 준 다음 회차·지금 시각(PC 시계 차이 보정)으로 세고,
|
||||
// 회차가 지나면 1분 동안 "자동 업데이트 중" 뒤 같은 규칙(auto_sync.next_slot: KST hours[0]시 정각 ~ hours[1]시 정각, slot 분마다)으로 다음 회차.
|
||||
function initNextUpdate(cfg) {
|
||||
const span = document.getElementById("perf-next-update");
|
||||
if (!span || !cfg || !cfg.next_at) return;
|
||||
span.innerHTML = '<span class="perf-next-label">다음 업데이트까지 </span><b></b>';
|
||||
const label = span.firstChild, box = span.lastChild;
|
||||
const KST = 9 * 3600000, step = (cfg.slot || 30) * 60000;
|
||||
const first = cfg.hours ? cfg.hours[0] : 9, last = cfg.hours ? cfg.hours[1] : 19;
|
||||
const skew = cfg.now ? Date.parse(cfg.now) - Date.now() : 0;
|
||||
function now() { return Date.now() + skew; }
|
||||
function nextSlot(after) {
|
||||
let t = Math.floor((after + KST) / step) * step + step; // KST 벽시계(ms)
|
||||
for (let i = 0; i < 48 * 2 + 2; i++) {
|
||||
const d = new Date(t), h = d.getUTCHours(), m = d.getUTCMinutes();
|
||||
if ((h >= first && h < last) || (h === last && m === 0)) return t - KST;
|
||||
t += step;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function two(n) { return (n < 10 ? "0" : "") + n; }
|
||||
function left(ms) {
|
||||
const s = Math.max(0, Math.ceil(ms / 1000));
|
||||
const h = Math.floor(s / 3600), m = Math.floor((s % 3600) / 60), sec = s % 60;
|
||||
if (h) return h + "시간 " + two(m) + "분 " + two(sec) + "초";
|
||||
if (m) return m + "분 " + two(sec) + "초";
|
||||
return sec + "초";
|
||||
}
|
||||
let due = Date.parse(cfg.next_at);
|
||||
function tick() {
|
||||
const t = now();
|
||||
if (t >= due) {
|
||||
if (t - due < 60000) { label.hidden = true; box.textContent = "자동 업데이트 중"; return; }
|
||||
due = nextSlot(t);
|
||||
if (due == null) { span.hidden = true; return; }
|
||||
}
|
||||
label.hidden = false;
|
||||
box.textContent = left(due - t);
|
||||
}
|
||||
tick();
|
||||
setInterval(tick, 1000);
|
||||
}
|
||||
|
||||
// ════════════════════════════════════════════════════
|
||||
|
||||
+22
-3
@@ -427,6 +427,8 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
|
||||
/* 카드 끌기 실시간 미리보기(2026-10-19) — 원래 카드는 숨기고 놓일 자리에 점선 자리 표시,
|
||||
끄는 모양은 살짝 기울어진 그림자 카드(setDragImage 용, 화면 밖에 잠깐 붙였다 뗀다). */
|
||||
.pj-card.is-drag-src { display: none; }
|
||||
/* 카드 속 이미지(아바타·표지)를 잡고 끌어도 이미지가 아니라 카드가 끌리게 — 이미지 끌기는 "Files" 를 실어 카드 놓기가 거부됐다 */
|
||||
.pj-card img { -webkit-user-drag: none; user-drag: none; }
|
||||
.pj-card-ph {
|
||||
flex: none; box-sizing: border-box; border-radius: var(--pj-card-radius);
|
||||
border: 2px dashed var(--pj-accent); background: var(--pj-accent-tint);
|
||||
@@ -469,16 +471,33 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
|
||||
/* 파일을 카드에 끌어 놓기 = 이 업무에 첨부(2026-10-19) — 점선 + "놓으면 첨부" 안내, 올리는 동안 흐리게 */
|
||||
.pj-card.is-file-drop { position: relative; outline: 2px dashed var(--pj-accent); outline-offset: -2px; background: var(--pj-accent-tint); }
|
||||
.pj-card.is-file-drop::after {
|
||||
content: "놓으면 이 업무에 첨부"; position: absolute; right: 8px; bottom: 6px; padding: 2px 8px; border-radius: 999px;
|
||||
content: "놓으면 드라이브에 올리고 설명에 링크"; position: absolute; right: 8px; bottom: 6px; padding: 2px 8px; border-radius: 999px;
|
||||
background: var(--pj-accent); color: #fff; font-size: 11px; font-weight: 700; pointer-events: none;
|
||||
}
|
||||
.pj-card.is-file-drop.is-file-drop-sub::after { content: "놓으면 이 세부 업무 설명에 드라이브 링크"; }
|
||||
/* 파일 → 구글 드라이브(2026-10-19) — 놓을 곳(설명란·세부 업무 줄) 점선 안내, 올리는 중 표시 */
|
||||
.pj-card-sub.is-drive-over,
|
||||
.pj-subtask-row.is-drive-over { outline: 2px dashed var(--pj-accent); outline-offset: -2px; background: var(--pj-accent-tint); border-radius: 6px; }
|
||||
.pj-subtask-list.is-drive-over { outline: 2px dashed var(--pj-accent); outline-offset: 2px; border-radius: 8px; }
|
||||
.pj-desc-wrap.is-drive-over { position: relative; outline: 2px dashed var(--pj-accent); outline-offset: 2px; border-radius: 8px; }
|
||||
.pj-desc-wrap.is-drive-over::after {
|
||||
content: "놓으면 구글 드라이브에 올리고 이 자리에 링크"; position: absolute; right: 8px; top: 6px; z-index: 5; padding: 2px 8px;
|
||||
border-radius: 999px; background: var(--pj-accent); color: #fff; font-size: 11px; font-weight: 700; pointer-events: none;
|
||||
}
|
||||
.pj-card-sub.is-file-uploading,
|
||||
.pj-subtask-row.is-file-uploading { animation: pj-file-up 1s ease-in-out infinite alternate; }
|
||||
.pj-drive-uploading {
|
||||
display: inline-block; margin: 0 2px; padding: 0 8px; border-radius: 999px; background: var(--pj-accent-tint);
|
||||
color: var(--pj-accent); font-size: 12px; font-weight: 600; user-select: none;
|
||||
animation: pj-file-up 1s ease-in-out infinite alternate;
|
||||
}
|
||||
.pj-card.is-file-uploading { opacity: .6; animation: pj-file-up 1s ease-in-out infinite alternate; }
|
||||
@keyframes pj-file-up { from { opacity: .45; } to { opacity: .8; } }
|
||||
/* 업무 창 아무 곳에 파일 끌어 놓기 — 창 전체 점선 안내(읽기 전용·저장 전 새 업무는 회색 안내) */
|
||||
.pj-task-modal-card.is-file-over::after {
|
||||
content: "여기에 놓으면 첨부 파일로 올라갑니다"; position: absolute; inset: 8px; z-index: 60; pointer-events: none;
|
||||
content: "여기에 놓으면 첨부 파일로 올라갑니다 (설명란·세부 업무에 놓으면 구글 드라이브 링크)"; position: absolute; inset: 8px; z-index: 60; pointer-events: none;
|
||||
display: flex; align-items: center; justify-content: center; border: 3px dashed var(--pj-accent); border-radius: 12px;
|
||||
background: rgba(241, 238, 255, .88); color: var(--pj-accent); font-size: 16px; font-weight: 700;
|
||||
background: rgba(241, 238, 255, .6); color: var(--pj-accent); font-size: 16px; font-weight: 700;
|
||||
}
|
||||
.pj-task-modal-card.is-file-over.is-file-blocked::after {
|
||||
content: "이 업무에는 지금 첨부할 수 없습니다(저장 전·읽기 전용)"; border-color: #9ca3af; color: #6b7280; background: rgba(243, 244, 246, .9);
|
||||
|
||||
+204
-25
@@ -3630,8 +3630,11 @@
|
||||
}
|
||||
// 보드 카드 순서 바꾸기는 "기본 정렬 + 필터 없음"일 때만 — 가려진 카드가 있거나
|
||||
// 다른 기준으로 정렬돼 있으면 놓은 자리가 실제 순서와 어긋난다(아사나도 같다).
|
||||
// 보드 카드 순서를 손으로 바꿀 수 있는가 — 정렬이 "기본"일 때. 필터(상태·담당자·마감·우선순위·찾기)는 막지 않는다
|
||||
// (2026-10-19): 필터 설정은 브라우저(localStorage pj_filter_…)마다 남아, 필터를 켜 둔 컴퓨터에서만 섹션 안 카드가
|
||||
// 늘 제자리로 돌아가던 버그. 숨은 업무는 제자리에 두고 보이는 카드끼리의 새 순서만 반영한다(orderWithHidden).
|
||||
function manualOrderAllowed() {
|
||||
return taskFilter.sort === "manual" && !taskFilterActive(taskFilter);
|
||||
return taskFilter.sort === "manual";
|
||||
}
|
||||
|
||||
const FB = {
|
||||
@@ -5202,6 +5205,18 @@
|
||||
// 세션"만 연결(POST .../links)로 바꾼다.
|
||||
// 드롭 지점(마우스 Y)이 이 컬럼의 카드들 중 어디에 해당하는지 인덱스로.
|
||||
// 드래그 중인 카드 자신은 계산에서 제외(자기 위치가 기준을 흔들지 않게).
|
||||
// 섹션 전체 순서(full, 옮기는 업무 뺌)에 옮기는 업무를 넣는다 — 화면에 보이는 카드 순서(visible, 옮기는 업무 포함)에서
|
||||
// 바로 앞 카드 뒤(없으면 바로 뒤 카드 앞, 둘 다 없으면 맨 끝). 필터로 숨은 업무는 원래 자리 그대로(예전엔 맨 뒤로 밀렸다).
|
||||
function orderWithHidden(full, visible, movingId) {
|
||||
const out = full.filter(function (id) { return id !== movingId; });
|
||||
const i = visible.indexOf(movingId);
|
||||
const before = i > 0 ? out.indexOf(visible[i - 1]) : -1;
|
||||
const after = i >= 0 && i + 1 < visible.length ? out.indexOf(visible[i + 1]) : -1;
|
||||
if (before >= 0) out.splice(before + 1, 0, movingId);
|
||||
else if (after >= 0) out.splice(after, 0, movingId);
|
||||
else out.push(movingId);
|
||||
return out;
|
||||
}
|
||||
function cardDropIndex(body, clientY, excludeTaskId) {
|
||||
const cards = Array.prototype.slice.call(body.querySelectorAll(".pj-card[data-task-id]"))
|
||||
.filter(function (c) { return String(c.dataset.taskId) !== String(excludeTaskId); });
|
||||
@@ -5346,19 +5361,19 @@
|
||||
// 놓을 자리 = 자리 표시 위치(없으면 마우스 위치)
|
||||
let idx = phIndex(body);
|
||||
if (idx < 0) idx = cardDropIndex(body, e.clientY, taskId);
|
||||
// 자리 표시 기준 이 섹션 카드 순서(끈 카드 포함) + 화면에 없는 이 섹션 업무는 뒤에
|
||||
// 자리 표시 기준 이 섹션 카드 순서(끈 카드 포함)
|
||||
const domIds = phCards(body).map(function (c) { return parseInt(c.dataset.taskId, 10); })
|
||||
.filter(function (id) { return id !== taskId; });
|
||||
domIds.splice(idx, 0, taskId);
|
||||
function orderedFor() {
|
||||
const rest = tasks.filter(function (x) {
|
||||
return x.stage_id === stageId && x.context_project_id === projectId && domIds.indexOf(x.id) < 0;
|
||||
const full = tasks.filter(function (x) {
|
||||
return x.stage_id === stageId && x.context_project_id === projectId && x.id !== taskId;
|
||||
}).map(function (x) { return x.id; });
|
||||
return domIds.concat(rest);
|
||||
return orderWithHidden(full, domIds, taskId);
|
||||
}
|
||||
if (t.stage_id === stageId) {
|
||||
if (!manualOrderAllowed()) {
|
||||
showToast("필터·정렬을 쓰는 중에는 카드 순서를 바꿀 수 없습니다. (정렬: 기본, 필터 초기화 후 가능)", "error");
|
||||
showToast("정렬을 쓰는 중에는 카드 순서를 바꿀 수 없습니다. (필터 바의 정렬을 '기본'으로 바꾼 뒤 가능)", "error");
|
||||
endCardDrag(true);
|
||||
return;
|
||||
}
|
||||
@@ -6251,35 +6266,56 @@
|
||||
e.preventDefault();
|
||||
showContextMenu(e.clientX, e.clientY, taskContextItems(t));
|
||||
});
|
||||
// 파일을 카드에 끌어 놓으면 이 업무에 첨부(2026-10-19) — 카드 끌기(text/plain)·세부 업무 끌기와는 종류("Files")로 구분
|
||||
// 파일을 카드에 끌어 놓으면 구글 드라이브에 올리고 그 업무 설명에 "파일 이름.확장자" 링크(2026-10-19 — 예전엔 첨부).
|
||||
// 펼친 세부 업무 줄에 놓으면 그 세부 업무 설명에. 카드 끌기(text/plain)·세부 업무 끌기와는 종류("Files")로 구분
|
||||
let fileDepth = 0;
|
||||
function fileSubRow(e) {
|
||||
const r = e.target && e.target.closest ? e.target.closest(".pj-card-sub[data-sub-id]") : null;
|
||||
return r && card.contains(r) ? r : null;
|
||||
}
|
||||
function markFileSub(row) {
|
||||
card.querySelectorAll(".pj-card-sub.is-drive-over").forEach(function (x) { if (x !== row) x.classList.remove("is-drive-over"); });
|
||||
if (row) row.classList.add("is-drive-over");
|
||||
card.classList.toggle("is-file-drop-sub", !!row);
|
||||
}
|
||||
card.addEventListener("dragenter", function (e) {
|
||||
if (!dragHasFiles(e)) return;
|
||||
e.preventDefault();
|
||||
fileDepth++;
|
||||
card.classList.add("is-file-drop");
|
||||
markFileSub(fileSubRow(e));
|
||||
});
|
||||
card.addEventListener("dragover", function (e) {
|
||||
if (!dragHasFiles(e)) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.dataTransfer.dropEffect = "copy";
|
||||
markFileSub(fileSubRow(e));
|
||||
});
|
||||
card.addEventListener("dragleave", function (e) {
|
||||
if (!dragHasFiles(e)) return;
|
||||
if (--fileDepth <= 0) { fileDepth = 0; card.classList.remove("is-file-drop"); }
|
||||
if (--fileDepth <= 0) { fileDepth = 0; card.classList.remove("is-file-drop"); markFileSub(null); }
|
||||
});
|
||||
card.addEventListener("drop", async function (e) {
|
||||
if (!dragHasFiles(e)) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const row = fileSubRow(e);
|
||||
const files = Array.prototype.slice.call(e.dataTransfer.files || []);
|
||||
fileDepth = 0;
|
||||
card.classList.remove("is-file-drop");
|
||||
card.classList.add("is-file-uploading");
|
||||
const out = await uploadTaskFiles(t.id, e.dataTransfer.files);
|
||||
card.classList.remove("is-file-uploading");
|
||||
reportUpload(out, t.title || "");
|
||||
if (currentTaskId === t.id && !taskModal.hidden) loadAttachments(t.id); // 열려 있는 업무 창도 바로
|
||||
markFileSub(null);
|
||||
if (!files.length) return;
|
||||
const target = row || card;
|
||||
target.classList.add("is-file-uploading");
|
||||
try {
|
||||
if (row) {
|
||||
const st = row.querySelector(".pj-card-sub-title");
|
||||
await dropDriveFilesOnTask(parseInt(row.dataset.subId, 10), files, st ? st.textContent.trim() : "");
|
||||
} else {
|
||||
await dropDriveFilesOnTask(t.id, files, t.title || "");
|
||||
}
|
||||
} finally { target.classList.remove("is-file-uploading"); }
|
||||
});
|
||||
}
|
||||
return card;
|
||||
@@ -7817,8 +7853,51 @@
|
||||
if (out.ok) showToast((where ? "‘" + where + "’에 " : "") + "파일 " + out.ok + "개를 첨부했습니다.");
|
||||
if (out.errors.length) showToast("업로드 실패 — " + out.errors.join(" / "), "error");
|
||||
}
|
||||
// 끌고 있는 것이 "파일"인가(카드 끌기·글자 끌기와 구분)
|
||||
// ── 업무 파일 → 구글 드라이브(2026-10-19) — 드라이브 `프로젝트/섹션/업무/세부 업무` 폴더에 올리고 설명란에
|
||||
// "파일 이름.확장자" 링크. 설명에서 링크를 지우면 서버가 그 파일을 드라이브 휴지통으로 보낸다.
|
||||
// append=true → 서버가 그 업무 설명 끝에 링크를 붙인다(보드 카드·세부 업무 줄 — 설명란을 열어 두지 않은 업무).
|
||||
async function uploadDriveFile(taskId, file, append) {
|
||||
const fd = new FormData();
|
||||
fd.append("file", file);
|
||||
if (append) fd.append("append", "true");
|
||||
const res = await fetch("/project/api/tasks/" + taskId + "/drive-files", { method: "POST", body: fd });
|
||||
if (!res.ok) { let m = res.statusText; try { m = (await res.json()).detail; } catch (_) {} throw new Error(m || ("HTTP " + res.status)); }
|
||||
const data = await res.json();
|
||||
if (data.append_failed) throw new Error("드라이브에는 올렸지만 설명에 링크를 못 붙였습니다 — " + data.file.url);
|
||||
return { url: data.file.url, name: data.file.name, task: data.task || null };
|
||||
}
|
||||
// 여러 파일을 차례로 올려 그 업무 설명 끝에 붙인다 → { ok, errors, task(마지막으로 바뀐 업무) }
|
||||
async function appendDriveFiles(taskId, files) {
|
||||
const out = { ok: 0, errors: [], task: null };
|
||||
for (const f of Array.prototype.slice.call(files || [])) {
|
||||
try { const r = await uploadDriveFile(taskId, f, true); out.ok++; if (r.task) out.task = r.task; }
|
||||
catch (e) { out.errors.push(f.name + ": " + e.message); }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function reportDrive(out, where) {
|
||||
if (out.ok) showToast((where ? "‘" + where + "’ " : "") + "설명에 구글 드라이브 파일 링크 " + out.ok + "개를 넣었습니다.");
|
||||
if (out.stale) showToast("파일은 구글 드라이브에 올라갔지만 업무 창이 바뀌어 설명에 링크를 넣지 못했습니다.", "error");
|
||||
if (out.errors.length) showToast("드라이브 업로드 실패 — " + out.errors.join(" / "), "error");
|
||||
}
|
||||
// 보드 카드·업무 창 세부 업무 줄 → 그 업무 설명에 링크. 지금 업무 창(설명란)에 열려 있는 업무면 서버가 아니라
|
||||
// 편집기 맨 끝에 넣는다(서버가 붙인 뒤 창의 옛 설명이 저장돼 링크가 지워지고 파일이 휴지통으로 가지 않게).
|
||||
async function dropDriveFilesOnTask(taskId, files, where) {
|
||||
if (descEditor && !taskModal.hidden && !taskReadOnly && String(currentTaskId) === String(taskId)) {
|
||||
const out = await descEditor.insertDriveFiles(files, null, null, function (f) { return uploadDriveFile(taskId, f, false); });
|
||||
reportDrive(out, where);
|
||||
return out;
|
||||
}
|
||||
const out = await appendDriveFiles(taskId, files);
|
||||
if (out.task) { try { mergeTask(out.task); } catch (_) {} }
|
||||
reportDrive(out, where);
|
||||
return out;
|
||||
}
|
||||
// 끌고 있는 것이 "파일"인가(카드 끌기·글자 끌기와 구분). 화면 안 카드·세부 업무 끌기 중이면 아니다 —
|
||||
// 카드 속 이미지(아바타 등)를 잡고 끌면 브라우저가 "Files" 를 같이 실어, 파일 받기 칸이 카드 끌기를 가로채
|
||||
// 놓을 때 카드가 제자리로 돌아가던 경우를 막는다(2026-10-19).
|
||||
function dragHasFiles(e) {
|
||||
if (cardDrag || dragSub) return false;
|
||||
return !!(e.dataTransfer && Array.prototype.indexOf.call(e.dataTransfer.types || [], "Files") >= 0);
|
||||
}
|
||||
const attachInput = el("pj-attach-input");
|
||||
@@ -7829,25 +7908,49 @@
|
||||
if (out.errors.length) alert("업로드 실패: " + out.errors.join("\n"));
|
||||
loadAttachments(currentTaskId);
|
||||
});
|
||||
// ── 업무 창 아무 곳에나 파일을 끌어 놓으면 첨부(2026-10-19) — 창 전체에 점선 안내가 뜨고, 놓으면 [첨부 파일]에 올라간다.
|
||||
// 설명칸에 놓아도 글에 끼워 넣지 않고 첨부로. 아직 저장 전인 새 업무·읽기 전용이면 안내만.
|
||||
// ── 업무 창에 파일 끌어 놓기 — 놓는 자리에 따라(2026-10-19):
|
||||
// · 설명란 → 구글 드라이브에 올리고 놓은 자리에 "파일 이름.확장자" 링크(설명란 위 점선 안내)
|
||||
// · 세부 업무 목록의 줄 → 그 세부 업무 설명 끝에 드라이브 링크(줄 점선 안내), 목록 빈 곳 → 이 업무 설명 끝에
|
||||
// · 그 밖의 곳 → 예전처럼 [첨부 파일](창 전체 점선 안내)
|
||||
// 아직 저장 전인 새 업무·읽기 전용이면 안내만.
|
||||
(function wireTaskFileDrop() {
|
||||
const card = taskModal && taskModal.querySelector(".pj-task-modal-card");
|
||||
if (!card) return;
|
||||
let depth = 0;
|
||||
const clear = function () { depth = 0; card.classList.remove("is-file-over"); };
|
||||
const descBox = el("pj-t-desc");
|
||||
const descWrap = descBox ? descBox.parentElement : null;
|
||||
const subList = el("pj-subtask-list");
|
||||
let depth = 0, hot = null;
|
||||
function blocked() { return !currentTaskId || !canManage || taskReadOnly; }
|
||||
// 놓는 자리 → { kind: "desc" | "sub" | "subs" | "attach", el, id }
|
||||
function zoneOf(target) {
|
||||
const t = target && target.nodeType === 1 ? target : target && target.parentElement;
|
||||
if (!t) return { kind: "attach", el: null };
|
||||
if (descWrap && descWrap.contains(t)) return { kind: "desc", el: descWrap };
|
||||
const row = subList && t.closest ? t.closest(".pj-subtask-row") : null;
|
||||
if (row && subList.contains(row) && row.dataset.id) return { kind: "sub", el: row, id: row.dataset.id };
|
||||
if (subList && subList.contains(t)) return { kind: "subs", el: subList };
|
||||
return { kind: "attach", el: null };
|
||||
}
|
||||
function mark(z) {
|
||||
if (hot && (!z || hot !== z.el)) { hot.classList.remove("is-drive-over"); hot = null; }
|
||||
const drive = z && z.kind !== "attach";
|
||||
card.classList.toggle("is-file-over", !!z && (!drive || blocked()));
|
||||
card.classList.toggle("is-file-blocked", !!z && blocked());
|
||||
if (drive && !blocked() && z.el) { z.el.classList.add("is-drive-over"); hot = z.el; }
|
||||
}
|
||||
const clear = function () { depth = 0; mark(null); card.classList.remove("is-file-over", "is-file-blocked"); };
|
||||
card.addEventListener("dragenter", function (e) {
|
||||
if (!dragHasFiles(e)) return;
|
||||
e.preventDefault();
|
||||
depth++;
|
||||
card.classList.add("is-file-over");
|
||||
card.classList.toggle("is-file-blocked", !currentTaskId || !canManage || taskReadOnly);
|
||||
mark(zoneOf(e.target));
|
||||
});
|
||||
card.addEventListener("dragover", function (e) {
|
||||
if (!dragHasFiles(e)) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.dataTransfer.dropEffect = (!currentTaskId || !canManage || taskReadOnly) ? "none" : "copy";
|
||||
e.dataTransfer.dropEffect = blocked() ? "none" : "copy";
|
||||
mark(zoneOf(e.target));
|
||||
});
|
||||
card.addEventListener("dragleave", function (e) {
|
||||
if (!dragHasFiles(e)) return;
|
||||
@@ -7857,11 +7960,30 @@
|
||||
if (!dragHasFiles(e)) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const z = zoneOf(e.target);
|
||||
clear();
|
||||
if (!canManage || taskReadOnly) { showToast("이 업무에는 파일을 첨부할 수 없습니다(읽기 전용).", "error"); return; }
|
||||
if (!canManage || taskReadOnly) { showToast("이 업무에는 파일을 넣을 수 없습니다(읽기 전용).", "error"); return; }
|
||||
if (!currentTaskId) { showToast("업무 이름을 먼저 넣어 업무를 만든 뒤 파일을 끌어 놓으세요.", "error"); return; }
|
||||
const taskId = currentTaskId;
|
||||
const out = await uploadTaskFiles(taskId, e.dataTransfer.files);
|
||||
const files = Array.prototype.slice.call(e.dataTransfer.files || []);
|
||||
if (!files.length) return;
|
||||
if (z.kind === "desc" && descEditor) {
|
||||
const x = e.clientX, y = e.clientY;
|
||||
const out = await descEditor.insertDriveFiles(files, x, y, function (f) { return uploadDriveFile(taskId, f, false); });
|
||||
reportDrive(out, "");
|
||||
return;
|
||||
}
|
||||
if (z.kind === "sub") {
|
||||
const name = z.el.querySelector(".pj-subtask-title") || {};
|
||||
const title = (name.value || name.textContent || "").trim();
|
||||
z.el.classList.add("is-file-uploading");
|
||||
const out = await appendDriveFiles(parseInt(z.id, 10), files);
|
||||
z.el.classList.remove("is-file-uploading");
|
||||
reportDrive(out, title);
|
||||
return;
|
||||
}
|
||||
if (z.kind === "subs") { await dropDriveFilesOnTask(taskId, files, ""); return; }
|
||||
const out = await uploadTaskFiles(taskId, files);
|
||||
reportUpload(out, "");
|
||||
if (currentTaskId === taskId) loadAttachments(taskId);
|
||||
});
|
||||
@@ -8849,9 +8971,9 @@
|
||||
let pendingUploads = 0;
|
||||
let idleWaiters = [];
|
||||
let editorGen = 0;
|
||||
function beginUpload() {
|
||||
function beginUpload(label) {
|
||||
pendingUploads++;
|
||||
if (hint) hint.textContent = "이미지 업로드 중…";
|
||||
if (hint) hint.textContent = label || "이미지 업로드 중…";
|
||||
}
|
||||
function endUpload() {
|
||||
pendingUploads = Math.max(0, pendingUploads - 1);
|
||||
@@ -8928,8 +9050,65 @@
|
||||
imgInput.value = "";
|
||||
});
|
||||
|
||||
// ── 파일 끌어 놓기 → 구글 드라이브(2026-10-19) — 놓은 자리에 "올리는 중" 표시를 두고, 올라가면 그 자리를
|
||||
// "파일 이름.확장자" 링크(새 탭)로 바꾼다. 올리는 동안은 저장을 미룬다(isUploading). upload(file) → Promise<{url, name}>.
|
||||
// x·y 가 없으면 설명 맨 끝에. 반환 { ok, errors: ["파일: 이유"], stale: 올렸지만 창이 바뀌어 못 넣음 }
|
||||
function caretRangeAt(x, y) {
|
||||
let r = null;
|
||||
try {
|
||||
if (document.caretRangeFromPoint) r = document.caretRangeFromPoint(x, y);
|
||||
else if (document.caretPositionFromPoint) {
|
||||
const p = document.caretPositionFromPoint(x, y);
|
||||
if (p) { r = document.createRange(); r.setStart(p.offsetNode, p.offset); r.collapse(true); }
|
||||
}
|
||||
} catch (_) { r = null; }
|
||||
return r && box.contains(r.startContainer) ? r : null;
|
||||
}
|
||||
async function insertDriveFiles(files, x, y, upload) {
|
||||
const list = Array.prototype.slice.call(files || []);
|
||||
const out = { ok: 0, errors: [], stale: false };
|
||||
if (!list.length || box.getAttribute("contenteditable") === "false") return out;
|
||||
const myGen = editorGen;
|
||||
let at = x != null && y != null ? caretRangeAt(x, y) : null;
|
||||
if (!at) { at = document.createRange(); at.selectNodeContents(box); at.collapse(false); }
|
||||
const mark = document.createElement("span");
|
||||
mark.className = "pj-drive-uploading";
|
||||
mark.setAttribute("contenteditable", "false");
|
||||
mark.textContent = "구글 드라이브에 올리는 중… (" + list.length + "개)";
|
||||
at.insertNode(mark);
|
||||
beginUpload("파일을 구글 드라이브에 올리는 중…");
|
||||
const links = [];
|
||||
try {
|
||||
for (const f of list) {
|
||||
try { links.push(await upload(f)); out.ok++; }
|
||||
catch (e) { out.errors.push(f.name + ": " + e.message); }
|
||||
}
|
||||
} finally {
|
||||
if (myGen !== editorGen || !mark.isConnected) {
|
||||
out.stale = links.length > 0;
|
||||
mark.remove();
|
||||
} else {
|
||||
const frag = document.createDocumentFragment();
|
||||
links.forEach(function (l, i) {
|
||||
if (i) frag.appendChild(document.createElement("br"));
|
||||
const a = document.createElement("a");
|
||||
a.href = l.url; a.target = "_blank"; a.rel = "noopener noreferrer";
|
||||
a.textContent = l.name;
|
||||
frag.appendChild(a);
|
||||
});
|
||||
if (links.length) frag.appendChild(document.createTextNode(" "));
|
||||
mark.replaceWith(frag);
|
||||
lastRange = null;
|
||||
box.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
endUpload();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
return {
|
||||
setTaskId: setTaskId,
|
||||
insertDriveFiles: insertDriveFiles,
|
||||
setHtml: function (html) {
|
||||
selectImg(null); lastRange = null;
|
||||
box.innerHTML = html || "";
|
||||
|
||||
@@ -125,6 +125,17 @@ docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('g
|
||||
|
||||
설정이 없거나 권한이 모자라면 버튼을 눌렀을 때 사유가 안내되고(503), 회의록 다른 기능은 그대로 동작한다.
|
||||
|
||||
## Project 업무 파일 → 구글 드라이브 설정 (2026-10-19)
|
||||
|
||||
업무 설명란·보드 카드·세부 업무 줄에 파일을 끌어 놓으면 구글 드라이브 `PROJECT_DRIVE_FOLDER_ID`(기본 `1Zdak2FtACRJ6peOnA9zD22hsbbsTixJG`)
|
||||
아래 `프로젝트/섹션/업무/세부 업무` 폴더에 올리고 설명에 링크를 넣는다(`app/integrations/google_drive.py`). DB 변경 없음.
|
||||
인증은 위 회의록 보드와 같은 Google 설정(Drive 권한)을 쓴다.
|
||||
|
||||
- 그 폴더에 **편집 권한**이 있는 계정이어야 한다 — OAuth 토큰이면 토큰을 발급한 계정, 서비스 계정이면 서비스 계정 이메일을 폴더에 편집자로 추가.
|
||||
서비스 계정은 저장 용량이 없어 **내 드라이브 폴더에는 못 올린다**(공유 드라이브 폴더 필요) — 그 경우 화면에 사유가 뜬다.
|
||||
- 링크를 본 사람이 파일을 열려면 그 폴더가 직원들에게 공유돼 있어야 한다(드라이브 폴더 공유 설정).
|
||||
- 설명에서 링크를 지우면 그 파일을 드라이브 휴지통으로(30일 뒤 드라이브가 지움). 이 기능으로 올린 파일만(appProperties `dbxTaskId`).
|
||||
|
||||
## 주간 회의록 항목 칸 묶음 마이그레이션 (027)
|
||||
|
||||
027은 `goal_meeting_items.label_cont` 열만 추가한다(기본 false, 기존 값 그대로, 다시 실행 가능). 미적용이면 "주요 업무" 칸의
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
// 실제 브라우저 — 보드 카드 끌기(필터를 켠 브라우저에서도 섹션 안 순서 변경, 숨은 업무는 제자리)와
|
||||
// 파일 → 구글 드라이브(설명란 = 놓은 자리에 링크, 보드 카드 = 서버가 설명 끝에 링크 append) (2026-10-19).
|
||||
// 서버는 가짜(이 파일의 http 서버), 화면은 실제 템플릿 렌더 결과.
|
||||
// python tests/js/render_project.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/board_drive.browser.test.js
|
||||
const fs = require("node:fs"), path = require("node:path"), http = require("node:http");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.resolve(__dirname, "../.."), OUT = path.join(__dirname, ".out"), STATIC = path.join(ROOT, "app/static");
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra) : "")); fails.push(name); }
|
||||
}
|
||||
|
||||
// 렌더된 보드(할 일 섹션 = 작업 A·B) 에 완료된 C(필터 "미완료"로 숨김)와 D 를 더한다
|
||||
function boardHtml() {
|
||||
let html = fs.readFileSync(path.join(OUT, "project_render.html"), "utf8");
|
||||
return html.replace(/(<script id="pj-data" type="application\/json">)([\s\S]*?)(<\/script>)/, function (_, a, json, c) {
|
||||
const data = JSON.parse(json);
|
||||
const base = data.tasks.find(function (t) { return t.id === 101; });
|
||||
base.description = "<p>앞 글</p>";
|
||||
data.tasks.push(Object.assign({}, base, { description: "", id: 104, title: "작업 C(완료)", completed_at: "2026-10-01T00:00:00+09:00", sort_order: 104 }));
|
||||
data.tasks.push(Object.assign({}, base, { description: "", id: 105, title: "작업 D", sort_order: 105 }));
|
||||
return a + JSON.stringify(data) + c;
|
||||
});
|
||||
}
|
||||
|
||||
const orders = [], drives = [], puts = [];
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
const json = (code, body) => { res.statusCode = code; res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(body)); };
|
||||
if (url.pathname === "/project/p/1") { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(boardHtml()); return; }
|
||||
if (url.pathname.startsWith("/project/api/")) {
|
||||
const chunks = []; for await (const c of req) chunks.push(c);
|
||||
const raw = Buffer.concat(chunks).toString("utf8");
|
||||
const order = /^\/project\/api\/projects\/1\/stages\/(\d+)\/tasks\/order$/.exec(url.pathname);
|
||||
if (order) { orders.push({ stage: +order[1], ids: JSON.parse(raw).ordered_ids }); return json(200, { ok: true }); }
|
||||
const drive = /^\/project\/api\/tasks\/(\d+)\/drive-files$/.exec(url.pathname);
|
||||
if (drive && req.method === "POST") {
|
||||
const name = (/filename="([^"]+)"/.exec(raw) || [])[1] || "file";
|
||||
const append = /name="append"\r\n\r\ntrue/.test(raw);
|
||||
drives.push({ id: +drive[1], name: name, append: append });
|
||||
const f = { id: "FILE" + drives.length + "abcdefgh", name: name, url: "https://drive.google.com/file/d/FILE" + drives.length + "abcdefgh/view" };
|
||||
const out = { file: f, link_html: "" };
|
||||
if (append) out.task = { id: +drive[1], project_id: 1, context_project_id: 1, stage_id: 11, title: "작업", description: '<p><a href="' + f.url + '">' + name + "</a></p>" };
|
||||
return json(201, out);
|
||||
}
|
||||
const task = /^\/project\/api\/tasks\/(\d+)$/.exec(url.pathname);
|
||||
if (task && req.method === "GET") return json(200, { task: { id: +task[1], title: "작업 " + task[1], project_id: 1, context_project_id: 1, stage_id: 11,
|
||||
description: "<p>앞 글</p>", priority: "normal", assignee_email: "", subtasks: [], links: [], followers: [], access: "full", completed_at: null } });
|
||||
if (task && req.method === "PUT") {
|
||||
const body = JSON.parse(raw); puts.push({ id: +task[1], body: body });
|
||||
return json(200, { task: Object.assign({ id: +task[1], title: "작업", project_id: 1, context_project_id: 1, stage_id: 11 }, body) });
|
||||
}
|
||||
if (url.pathname.endsWith("/comments")) return json(200, { comments: [], events: [], features: {} });
|
||||
if (url.pathname.endsWith("/attachments")) return json(200, { attachments: [] });
|
||||
if (url.pathname.endsWith("/members")) return json(200, { members: [{ user_email: "me@test.local" }] });
|
||||
if (url.pathname.endsWith("/live-version")) return json(200, { ts: "v1" });
|
||||
if (url.pathname.endsWith("/alerts")) return json(200, { me: "me@test.local", latest_id: 0, alerts: [] });
|
||||
return json(200, {});
|
||||
}
|
||||
if (url.pathname.startsWith("/static/")) {
|
||||
const file = path.join(STATIC, decodeURIComponent(url.pathname.slice("/static/".length)));
|
||||
if (file.startsWith(STATIC) && fs.existsSync(file)) {
|
||||
res.setHeader("Content-Type", file.endsWith(".js") ? "text/javascript" : file.endsWith(".css") ? "text/css" : "application/octet-stream");
|
||||
res.end(fs.readFileSync(file)); return;
|
||||
}
|
||||
}
|
||||
res.statusCode = 404; res.end("");
|
||||
});
|
||||
|
||||
// 파일 끌어 놓기 흉내 — 진짜 File 을 담은 DataTransfer 로 dragenter·dragover·drop
|
||||
async function dropFile(page, selector, name) {
|
||||
await page.evaluate(function (a) {
|
||||
const target = document.querySelector(a.sel);
|
||||
const r = target.getBoundingClientRect();
|
||||
const dt = new DataTransfer();
|
||||
dt.items.add(new File(["hello"], a.name, { type: "text/plain" }));
|
||||
const opts = { bubbles: true, cancelable: true, dataTransfer: dt, clientX: r.left + 10, clientY: r.top + Math.min(10, r.height / 2) };
|
||||
["dragenter", "dragover", "drop"].forEach(function (k) { target.dispatchEvent(new DragEvent(k, opts)); });
|
||||
}, { sel: selector, name: name });
|
||||
}
|
||||
|
||||
(async function () {
|
||||
await new Promise(r => server.listen(0, "127.0.0.1", r));
|
||||
const base = "http://127.0.0.1:" + server.address().port;
|
||||
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
page.on("pageerror", e => console.log("PAGEERR", e.message));
|
||||
// 이 브라우저에는 "미완료만" 필터가 저장돼 있다(다른 컴퓨터는 없음) — 예전엔 이 상태에서 섹션 안 이동이 늘 제자리로
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem("pj_filter_1", JSON.stringify({ status: "open" }));
|
||||
localStorage.setItem("pj_view", "board");
|
||||
});
|
||||
await page.goto(base + "/project/p/1");
|
||||
await page.waitForSelector('.pj-card[data-task-id="105"]');
|
||||
check("필터(미완료) — 완료된 C 는 보드에 안 보임", !(await page.$('.pj-card[data-task-id="104"]')));
|
||||
|
||||
// ── 1) 섹션 안 카드 끌기: D 를 A 위로
|
||||
const a = await page.locator('.pj-card[data-task-id="101"]').boundingBox();
|
||||
const d = await page.locator('.pj-card[data-task-id="105"]').boundingBox();
|
||||
await page.mouse.move(d.x + d.width / 2, d.y + d.height / 2);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(d.x + d.width / 2, d.y + d.height / 2 - 8, { steps: 3 });
|
||||
for (let i = 1; i <= 12; i++) await page.mouse.move(a.x + a.width / 2, d.y + (a.y + 4 - d.y) * i / 12, { steps: 2 });
|
||||
await page.waitForTimeout(150);
|
||||
await page.mouse.up();
|
||||
await page.waitForTimeout(400);
|
||||
check("필터를 켠 채 섹션 안 이동 — 순서 저장 요청", orders.length === 1, orders);
|
||||
check("숨은 C 는 제자리, D 는 A 앞", orders[0] && JSON.stringify(orders[0].ids) === JSON.stringify([105, 101, 102, 104]), orders[0]);
|
||||
const ids = await page.$$eval('.pj-col-body .pj-card[data-task-id]', els => els.map(e => +e.dataset.taskId));
|
||||
check("보드도 D·A·B 순서로 다시 그림", JSON.stringify(ids.slice(0, 3)) === JSON.stringify([105, 101, 102]), ids);
|
||||
|
||||
// ── 2) 보드 카드에 파일 놓기 → 서버가 설명 끝에 링크(append)
|
||||
await dropFile(page, '.pj-card[data-task-id="102"] .pj-card-title', "견적서.pdf");
|
||||
await page.waitForTimeout(400);
|
||||
check("보드 카드 파일 → drive-files(append) 한 번", drives.length === 1 && drives[0].id === 102 && drives[0].append && drives[0].name === "견적서.pdf", drives);
|
||||
|
||||
// ── 3) 업무 창 설명란에 파일 놓기 → 놓은 자리에 "파일 이름.확장자" 링크 + 설명 저장
|
||||
await page.click('.pj-card[data-task-id="101"] .pj-card-title');
|
||||
await page.waitForSelector("#pj-t-desc", { state: "visible" });
|
||||
await page.waitForFunction(() => document.getElementById("pj-t-desc").textContent.includes("앞 글"));
|
||||
await dropFile(page, "#pj-t-desc", "도면 v2.dwg");
|
||||
await page.waitForFunction(() => !!document.querySelector('#pj-t-desc a[href*="drive.google.com"]'), null, { timeout: 5000 }).catch(() => {});
|
||||
const link = await page.evaluate(() => {
|
||||
const x = document.querySelector('#pj-t-desc a[href*="drive.google.com"]');
|
||||
return x ? { text: x.textContent, href: x.getAttribute("href"), target: x.getAttribute("target"),
|
||||
busy: !!document.querySelector("#pj-t-desc .pj-drive-uploading") } : null;
|
||||
});
|
||||
check("설명란 파일 → drive-files(append 아님)", drives.length === 2 && drives[1].id === 101 && !drives[1].append, drives);
|
||||
check("설명란에 '파일 이름.확장자' 링크(새 탭)", link && link.text === "도면 v2.dwg" && /\/file\/d\/FILE2abcdefgh\/view$/.test(link.href) && link.target === "_blank" && !link.busy, link);
|
||||
await page.waitForTimeout(1600); // 설명 자동 저장(1.2초)
|
||||
const descPut = puts.filter(p => p.id === 101 && p.body.description != null).pop();
|
||||
check("링크가 들어간 설명 저장", !!descPut && descPut.body.description.includes("FILE2abcdefgh") &&
|
||||
/앞.*도면 v2\.dwg<\/a>.*글/.test(descPut.body.description), descPut); // 놓은 자리(앞|글 사이)에 링크
|
||||
|
||||
// ── 4) 업무 창이 열린 업무의 카드에 놓으면 서버 append 대신 편집기 끝에(옛 설명 저장이 링크를 지우지 않게)
|
||||
await dropFile(page, '.pj-card[data-task-id="101"] .pj-card-title', "사진.jpg");
|
||||
await page.waitForTimeout(500);
|
||||
const n = await page.$$eval('#pj-t-desc a[href*="drive.google.com"]', els => els.map(e => e.textContent));
|
||||
check("열린 업무 카드 → 편집기에 링크(append 아님)", drives.length === 3 && !drives[2].append && n.indexOf("사진.jpg") >= 0, { drives: drives, n: n });
|
||||
} finally { await browser.close(); server.close(); }
|
||||
console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
})();
|
||||
@@ -20,7 +20,7 @@ sys.path.insert(0, ROOT)
|
||||
OUT_DIR = os.path.join(ROOT, "tests", "js", ".out")
|
||||
|
||||
from app.modules.performance.ad_spend import build_ad_dashboard # noqa: E402
|
||||
from app.modules.performance.dashboard import build_dashboard, build_settings # noqa: E402
|
||||
from app.modules.performance.dashboard import amount_text, build_dashboard, build_settings # noqa: E402
|
||||
|
||||
BASE_STUB = ("{% block head_extra %}{% endblock %}<body><main class='erp-page'>{% block content %}{% endblock %}</main>"
|
||||
"{% block scripts %}{% endblock %}</body>")
|
||||
@@ -80,9 +80,12 @@ def env() -> jinja2.Environment:
|
||||
def main() -> None:
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
e = env()
|
||||
base = {"user": {"email": "me@test.local"}, "is_admin": True, "nav_items": [], "page_title": "실적", "page_subtitle": ""}
|
||||
base = {"user": {"email": "me@test.local"}, "is_admin": True, "nav_items": [], "page_title": "실적", "page_subtitle": "",
|
||||
"unit": "won", "unit_label": "원", "amt": lambda v: amount_text(v)}
|
||||
ctx = build_dashboard(FakeStore(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||
html = e.get_template("performance/index.html").render(**base, active_tab="dashboard", metric="gross", **ctx)
|
||||
# 다음 자동 업데이트(router._auto_sync_ctx 와 같은 모양) — 화면이 초 단위로 센다
|
||||
ctx["auto_sync"] = {"next_at": "2026-10-07T10:30:00+09:00", "now": "2026-10-07T10:17:25.000+09:00", "hours": [9, 19], "slot": 30}
|
||||
html = e.get_template("performance/index.html").render(**base, active_tab="dashboard", metric="net", **ctx)
|
||||
with open(os.path.join(OUT_DIR, "perf_dash.html"), "w", encoding="utf-8") as f:
|
||||
f.write(html)
|
||||
actx = build_ad_dashboard(FakeStore(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
"""업무 파일 → 구글 드라이브(2026-10-19) — 폴더 경로·업로드 API·설명 링크 append·링크 지우면 휴지통. DB·Google 없이 가짜로."""
|
||||
import importlib
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.integrations import google_drive
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
ME = {"email": "me@test.local", "role": "user"}
|
||||
|
||||
|
||||
class FakeDrive:
|
||||
enabled = True
|
||||
reason = ""
|
||||
|
||||
def __init__(self):
|
||||
self.paths, self.uploads, self.trash = [], [], []
|
||||
self.meta = {}
|
||||
|
||||
def ensure_folder_path(self, names, root=None):
|
||||
self.paths.append(list(names))
|
||||
return "FOLDER"
|
||||
|
||||
def upload(self, *, folder_id, name, stream, mimetype, task_id):
|
||||
self.uploads.append({"folder": folder_id, "name": name, "data": stream.read(), "task_id": task_id})
|
||||
fid = "F%dabcdefghij" % len(self.uploads)
|
||||
return {"id": fid, "name": name, "url": google_drive.file_url(fid)}
|
||||
|
||||
def ours(self, file_id):
|
||||
return self.meta.get(file_id)
|
||||
|
||||
def set_trashed(self, file_id, trashed):
|
||||
self.trash.append((file_id, trashed))
|
||||
|
||||
|
||||
class Store(MagicMock):
|
||||
TASKS = {
|
||||
1: {"id": 1, "project_id": 7, "project_name": "신제품", "stage_name": "기획", "title": "패키지 디자인",
|
||||
"parent_task_id": None, "description": "<p>기존</p>"},
|
||||
2: {"id": 2, "project_id": 7, "project_name": "신제품", "stage_name": None, "title": "시안 A",
|
||||
"parent_task_id": 1, "description": ""},
|
||||
}
|
||||
|
||||
def get_task(self, task_id):
|
||||
t = self.TASKS.get(int(task_id))
|
||||
return dict(t) if t else None
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.st = Store()
|
||||
self.st.update_task.side_effect = lambda task_id, fields, actor, assignee_allowed=None: {
|
||||
**self.st.get_task(task_id), **fields}
|
||||
self.drive = FakeDrive()
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
app.state.project_store = self.st
|
||||
app.state.data_dir = tempfile.mkdtemp(prefix="pj-drive-")
|
||||
self.client = TestClient(app, raise_server_exceptions=False)
|
||||
for p in (patch.object(api, "_require_user", return_value=ME), patch.object(api, "_db_or_503", return_value=self.st),
|
||||
patch.object(api, "_require_task", return_value="full"),
|
||||
patch.object(google_drive, "get_client", return_value=self.drive)):
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
|
||||
|
||||
class HelperTests(unittest.TestCase):
|
||||
def test_file_ids_in_description(self):
|
||||
html = ('<p><a href="https://drive.google.com/file/d/AbC_12-xyz9/view" target="_blank">a.pdf</a> '
|
||||
'<a href="https://example.com/file/d/zzzzzzzzzzzz/view">x</a></p>')
|
||||
self.assertEqual(google_drive.file_ids_in(html), {"AbC_12-xyz9"})
|
||||
self.assertEqual(google_drive.file_ids_in(""), set())
|
||||
|
||||
def test_folder_name_and_query_escape(self):
|
||||
self.assertEqual(google_drive.folder_name(" 기획\n 2차 "), "기획 2차")
|
||||
self.assertEqual(google_drive.folder_name(""), "(이름 없음)")
|
||||
self.assertEqual(google_drive._q("A's \\ b"), "A\\'s \\\\ b")
|
||||
|
||||
def test_folder_path_project_section_task_subtask(self):
|
||||
st = Store()
|
||||
self.assertEqual(api._drive_folder_names(st, st.get_task(1)), ["신제품", "기획", "패키지 디자인"])
|
||||
# 세부 업무 = 맨 위 업무의 섹션 + 업무 + 세부 업무
|
||||
self.assertEqual(api._drive_folder_names(st, st.get_task(2)), ["신제품", "기획", "패키지 디자인", "시안 A"])
|
||||
|
||||
def test_link_html_escapes_name(self):
|
||||
html = api.drive_link_html("https://drive.google.com/file/d/X1234567890/view", "<견적>.pdf")
|
||||
self.assertIn("<견적>.pdf</a>", html)
|
||||
self.assertIn('target="_blank"', html)
|
||||
|
||||
|
||||
class UploadApiTests(Base):
|
||||
def test_upload_returns_link_without_touching_description(self):
|
||||
r = self.client.post("/project/api/tasks/1/drive-files", files={"file": ("도면 v2.dwg", b"abc", "application/acad")})
|
||||
self.assertEqual(r.status_code, 201, r.text)
|
||||
body = r.json()
|
||||
self.assertEqual(body["file"]["name"], "도면 v2.dwg")
|
||||
self.assertTrue(body["file"]["url"].startswith("https://drive.google.com/file/d/"))
|
||||
self.assertEqual(self.drive.paths, [["신제품", "기획", "패키지 디자인"]])
|
||||
self.assertEqual(self.drive.uploads[0]["data"], b"abc")
|
||||
self.assertEqual(self.drive.uploads[0]["task_id"], 1)
|
||||
self.st.update_task.assert_not_called()
|
||||
|
||||
def test_upload_append_adds_link_to_subtask_description(self):
|
||||
r = self.client.post("/project/api/tasks/2/drive-files", files={"file": ("시안.png", b"png", "image/png")},
|
||||
data={"append": "true"})
|
||||
self.assertEqual(r.status_code, 201, r.text)
|
||||
self.assertEqual(self.drive.paths, [["신제품", "기획", "패키지 디자인", "시안 A"]])
|
||||
fields = self.st.update_task.call_args.kwargs["fields"]
|
||||
self.assertIn('href="https://drive.google.com/file/d/F1abcdefghij/view"', fields["description"])
|
||||
self.assertIn(">시안.png</a>", fields["description"])
|
||||
self.assertEqual(r.json()["task"]["description"], fields["description"])
|
||||
|
||||
def test_empty_file_and_disabled_drive(self):
|
||||
r = self.client.post("/project/api/tasks/1/drive-files", files={"file": ("a.txt", b"", "text/plain")})
|
||||
self.assertEqual(r.status_code, 400)
|
||||
self.drive.enabled = False
|
||||
self.drive.reason = "Google 인증 미설정"
|
||||
r = self.client.post("/project/api/tasks/1/drive-files", files={"file": ("a.txt", b"x", "text/plain")})
|
||||
self.assertEqual(r.status_code, 503)
|
||||
self.assertIn("Google 인증 미설정", r.json()["detail"])
|
||||
|
||||
def test_drive_error_is_502_with_message(self):
|
||||
self.drive.ensure_folder_path = MagicMock(side_effect=google_drive.GoogleDriveError("업무 파일 폴더를 찾을 수 없습니다"))
|
||||
r = self.client.post("/project/api/tasks/1/drive-files", files={"file": ("a.txt", b"x", "text/plain")})
|
||||
self.assertEqual(r.status_code, 502)
|
||||
self.assertIn("폴더", r.json()["detail"])
|
||||
|
||||
|
||||
class LinkSyncTests(Base):
|
||||
def test_removed_link_trashes_our_file_added_link_restores(self):
|
||||
self.drive.meta = {"GONE1234567": {"trashed": False, "task_id": "1"},
|
||||
"BACK1234567": {"trashed": True, "task_id": "1"},
|
||||
"KEEP1234567": {"trashed": False, "task_id": "1"},
|
||||
"OTHER123456": None}
|
||||
self.st.description_mentions.side_effect = lambda text, exclude_task_id: text == "KEEP1234567"
|
||||
api._sync_drive_links(self.st, 1, {"GONE1234567", "KEEP1234567", "OTHER123456"}, {"BACK1234567"})
|
||||
self.assertIn(("GONE1234567", True), self.drive.trash)
|
||||
self.assertIn(("BACK1234567", False), self.drive.trash)
|
||||
# 다른 업무 설명에 남은 링크·우리가 올리지 않은 파일은 그대로
|
||||
self.assertNotIn(("KEEP1234567", True), self.drive.trash)
|
||||
self.assertNotIn(("OTHER123456", True), self.drive.trash)
|
||||
|
||||
def test_description_save_schedules_sync(self):
|
||||
old = '<p><a href="https://drive.google.com/file/d/GONE1234567/view">a.pdf</a></p>'
|
||||
self.st.TASKS = {1: {**Store.TASKS[1], "description": old}}
|
||||
with patch.object(api, "_sync_drive_links") as sync, patch.object(api, "_record_mentions", return_value=[]):
|
||||
r = self.client.put("/project/api/tasks/1", json={"description": "<p>링크 지움</p>"})
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
sync.assert_called_once()
|
||||
_, task_id, removed, added = sync.call_args.args
|
||||
self.assertEqual((task_id, removed, added), (1, {"GONE1234567"}, set()))
|
||||
|
||||
def test_description_save_without_link_change_does_not_sync(self):
|
||||
with patch.object(api, "_sync_drive_links") as sync, patch.object(api, "_record_mentions", return_value=[]):
|
||||
r = self.client.put("/project/api/tasks/1", json={"description": "<p>글만 바뀜</p>"})
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
sync.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user