feat(project): 파일 끌어 놓기 → 구글 드라이브 링크, 필터 켠 보드 카드 순서 버그 수정

- 설명란·세부 업무 목록·보드 카드에 파일을 놓으면 드라이브 프로젝트/섹션/업무/세부 업무
  폴더에 올리고 설명에 "파일 이름.확장자" 링크(PROJECT_DRIVE_FOLDER_ID)
- 설명에서 링크를 지우면 우리가 올린 파일만 드라이브 휴지통, 되살리면 복구
- 브라우저별 필터(localStorage)가 켜져 있으면 섹션 안 카드가 제자리로 돌아가던 버그 —
  필터 중에도 순서 변경 허용, 숨은 업무는 제자리. 카드 속 이미지 끌기 오인 방지

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-19 23:19:16 +09:00
parent ee96c924fc
commit 52ca60df9a
19 changed files with 887 additions and 50 deletions
+186
View File
@@ -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 %}
+6 -2
View File
@@ -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).
+10
View File
@@ -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,
*,
+108
View File
@@ -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 %}
+22 -3
View File
@@ -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
View File
@@ -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 || "";