Files
dbx-main/tests/test_project_module.py
T
king 96f54db0b1 feat(project): 섹션째 다른 프로젝트로 · 회의록 글 칸 하이퍼링크 · 업무 등록 표 하위 업무·줄 클릭 업무 창
- 보드 섹션 머리를 왼쪽 프로젝트 목록에 놓으면 확인 창 → POST /api/stages/{id}/move-project
  (db.move_stage_to_project 한 트랜잭션: 섹션 + 업무 + 세부 업무, 대상 맨 끝, 원·대상 멤버만, 남의 연결은 원 프로젝트에 섹션 없음)
- 목표·회의록 글 칸 서식 도구 🔗 — pj-rich 조각 link(http(s)만, 서버 store.goal_link), 주소 붙여넣기 = 링크, Ctrl+클릭 = 새 탭
- 회의록 업무 등록 표: 등록된 줄 [+] = 바로 아래 세부 업무 초안, 세부 업무 줄은 상위 줄 아래 들여쓰기,
  등록된 줄 어디든 클릭 = 오른쪽 업무 창, ↳ 상위 = 상위 업무 창
- 도움말·CLAUDE.md·PROJECT_MODULE.md 6-26, 정적 파일 버전 20261026a
- 테스트: test_move_stage_to_other_project(실제 PG), 링크 서버 검증, project_ui [섹션 이동], goals_meeting_ui [2g5],
  goal_text_link.browser.test.js

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 12:29:14 +09:00

1672 lines
112 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""프로젝트 관리 모듈 — 권한·저장·댓글 첨부·알림 회귀 테스트 (실제 PostgreSQL + FastAPI TestClient).
운영 DB 와 분리된 **로컬 테스트용 PostgreSQL** 에서만 돈다. 가상의 사용자·프로젝트만 만든다.
# 1) 로컬 테스트 DB 에 스키마 적용(최초 1회): project_db_init.sql + project_db_0*.sql
# 2) 실행
PROJECT_TEST_DB_URL=postgresql://postgres@localhost:55432/project_db \
python tests/test_project_module.py
PROJECT_TEST_DB_URL 이 없거나 localhost/127.0.0.1 이 아니면 전부 건너뛴다(운영 DB 보호).
메일은 app.mail.send_email 을 가짜로 바꿔 기록만 한다(실제 발송 없음).
"""
from __future__ import annotations
import io
import os
import sys
import tempfile
import threading
import types
import uuid
from datetime import date, timedelta
from urllib.parse import urlparse
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
DSN = os.getenv("PROJECT_TEST_DB_URL", "")
_host = urlparse(DSN).hostname if DSN else None
ENABLED = bool(DSN) and _host in ("localhost", "127.0.0.1")
# ── app.main 대역(전체 앱을 띄우지 않고 프로젝트 라우터만 시험) ──────────────
class _Users:
def __init__(self) -> None:
self.d: dict[str, dict] = {}
def add(self, email: str, *, role: str = "user", project: bool = True, super_: bool = False) -> str:
email = email.lower()
self.d[email] = {"email": email, "name": email.split("@")[0], "role": role,
"modules": {"project": project}, "is_super_admin": super_}
return email
def get(self, email: str):
return self.d.get((email or "").lower())
def list_all(self):
return list(self.d.values())
USERS = _Users()
SENT_MAIL: list[dict] = []
if ENABLED:
from fastapi.responses import HTMLResponse
fake_main = types.ModuleType("app.main")
fake_main.user_store = USERS
def _current(request):
return USERS.get(request.headers.get("x-test-user", ""))
fake_main.get_current_user_record = _current
fake_main.build_erp_nav = lambda user, active="": []
fake_main.render_template = lambda request, name, ctx, status_code=200: HTMLResponse(
f"{name}|{ctx.get('reason', '')}", status_code=status_code)
sys.modules["app.main"] = fake_main
for k in list(os.environ):
if k.startswith("SMTP_") or k == "PROJECT_NOTIFY_EMAIL":
os.environ.pop(k)
import app.mail as _mail # noqa: E402
_mail.send_email = lambda **kw: SENT_MAIL.append(kw)
from fastapi import FastAPI # noqa: E402
from fastapi.testclient import TestClient # noqa: E402
from app.modules.project import reminders # noqa: E402
from app.modules.project import router as project_api_router # noqa: E402 - 패키지가 APIRouter 를 내보낸다
from app.modules.project.db import ProjectStore # noqa: E402
from app.timezone import today_kst # noqa: E402
ST = ProjectStore(DSN)
DATA_DIR = tempfile.mkdtemp(prefix="pj-test-")
APP = FastAPI()
APP.include_router(project_api_router)
APP.state.project_store = ST
APP.state.data_dir = DATA_DIR
CLIENT = TestClient(APP)
RUN = uuid.uuid4().hex[:6]
ADMIN = USERS.add(f"admin-{RUN}@test.local", role="admin")
PRO = USERS.add(f"pro-{RUN}@test.local", role="pro") # Pro user(2026-10-12)
SUPER = USERS.add("king@dbxcorp.co.kr", role="admin", super_=True)
ALICE = USERS.add(f"alice-{RUN}@test.local")
BOB = USERS.add(f"bob-{RUN}@test.local")
CAROL = USERS.add(f"carol-{RUN}@test.local")
DAVE = USERS.add(f"dave-{RUN}@test.local") # 프로젝트 권한은 있으나 어디에도 멤버 아님
EVE = USERS.add(f"eve-{RUN}@test.local", project=False) # 프로젝트 모듈 권한 없음
# ── pytest 실행 범위(2026-10-15 검토 F10) ─────────────────────────────────
# DB 가 없으면 이 파일 전체를 명시적으로 skip(예전엔 import 준비만 건너뛰어 ST·ADMIN 등이 없어 NameError).
# 가짜 app.main 은 이 파일 테스트 동안만 sys.modules 에 둔다 — pytest 는 모든 파일을 먼저 import 하므로 import 때 바꿔 끼우면
# 다른 DB 테스트 파일(test_cafe24_db ↔ test_project_module)의 가짜가 서로 덮어써 사용자 조회가 틀렸다.
# 직접 실행(python tests/…)은 위 import 때 설치한 가짜를 그대로 쓴다.
try:
import pytest
except ImportError: # 직접 실행은 pytest 없이도 돈다
pytest = None
if pytest is not None:
pytestmark = pytest.mark.skipif(not ENABLED, reason="PROJECT_TEST_DB_URL(localhost) 미설정 — 실제 PostgreSQL 통합 테스트는 건너뜀")
@pytest.fixture(autouse=True, scope="module")
def _own_app_main():
if not ENABLED:
yield
return
prev = sys.modules.get("app.main")
sys.modules["app.main"] = fake_main
try:
yield
finally:
if prev is None:
sys.modules.pop("app.main", None)
else:
sys.modules["app.main"] = prev
def req(method: str, url: str, who: str, **kw):
return CLIENT.request(method, url, headers={"x-test-user": who}, **kw)
def _project(name: str, owner: str, members: tuple[str, ...] = ()) -> dict:
p = ST.create_project(name=f"{name}-{uuid.uuid4().hex[:4]}", owner_email=owner, created_by=owner)
for m in members:
ST.add_member(project_id=p["id"], user_email=m)
return p
def _stage(pid: int, name: str = "할 일", done: bool = False, by: str = "") -> dict:
return ST.add_stage(project_id=pid, name=name, is_done_stage=done, created_by=by)
def _count(sql: str, *args) -> int:
with ST._pool.connection() as conn: # noqa: SLF001 - 테스트 전용 확인 쿼리
return int(conn.execute(sql, args).fetchone()["n"])
# ════════════════════════════════════════════════════════════
# [07] 프로젝트 수정·소유자 변경은 Pro user 이상(2026-10-12)
# ════════════════════════════════════════════════════════════
def test_owner_change_admin_only():
# 관리자도 멤버가 아닌 프로젝트는 못 다룬다(2026-10-07) — 소유자를 남에게 넘긴 뒤에도 바꿀 수 있게 멤버로 둔다
p = _project("P-owner", ADMIN, (BOB, ADMIN, PRO))
r = req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": BOB})
assert r.status_code == 403, r.text
assert ST.get_project(project_id=p["id"])["owner_email"] == ADMIN
r = req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"owner_email": CAROL, "name": "x"})
assert r.status_code == 403 and ST.get_project(project_id=p["id"])["name"] != "x"
# User 는 이름만 바꾸는 것도 안 된다, Pro user 멤버는 된다(같은 소유자 값을 같이 보내는 화면 저장 포함)
assert req("PUT", f"/project/api/projects/{p['id']}", BOB, json={"name": "no"}).status_code == 403
assert req("PUT", f"/project/api/projects/{p['id']}", PRO, json={"owner_email": ADMIN, "name": "ok"}).status_code == 200
# 관리자: 모듈 권한 없는 사람은 소유자 불가, 정상 사용자는 가능
assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": EVE}).status_code == 400
assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": CAROL}).status_code == 200
assert ST.get_project(project_id=p["id"])["owner_email"] == CAROL
# 소유자에서 빠지면(관리자가 다시 바꿈) 멤버가 아닌 CAROL 은 관리 권한을 잃는다
assert req("PUT", f"/project/api/projects/{p['id']}", ADMIN, json={"owner_email": ADMIN}).status_code == 200
assert req("GET", f"/project/api/projects/{p['id']}/snapshot", CAROL).status_code == 403
# 생성: User 는 새 프로젝트 불가, Pro user 는 본인·미지정 → 본인이 소유자
assert req("POST", "/project/api/projects", BOB, json={"name": "n1"}).status_code == 403
r = req("POST", "/project/api/projects", PRO, json={"name": "n2"})
assert r.status_code == 201 and r.json()["project"]["owner_email"] == PRO
# ════════════════════════════════════════════════════════════
# [06] 삭제 — 생성자 규칙 + 지금 권한
# ════════════════════════════════════════════════════════════
def test_delete_requires_current_access():
p = _project("P-del", ADMIN, (ALICE, BOB))
s = _stage(p["id"], by=ADMIN)
t = req("POST", f"/project/api/projects/{p['id']}/tasks", ALICE, json={"title": "alice task", "stage_id": s["id"]}).json()["task"]
ST.add_comment(task_id=t["id"], author_email=ALICE, author_name="a", body="hi")
trash_before = _count("SELECT COUNT(*) AS n FROM project_trash")
# 작업 삭제는 멤버 누구나(2026-10-12) — 남(BOB)이 만든 작업도 ALICE 가 지울 수 있다
t_bob = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "bob task", "stage_id": s["id"]}).json()["task"]
assert req("DELETE", f"/project/api/tasks/{t_bob['id']}", ALICE).status_code == 200
trash_before = _count("SELECT COUNT(*) AS n FROM project_trash")
# 멤버에서 빠진 생성자 → 거절, 행·댓글·휴지통 변화 없음
ST.remove_member(project_id=p["id"], user_email=ALICE)
assert req("DELETE", f"/project/api/tasks/{t['id']}", ALICE).status_code == 403
assert ST.get_task(task_id=t["id"]) is not None
assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id = %s", t["id"]) == 1
assert _count("SELECT COUNT(*) AS n FROM project_trash") == trash_before
# 다시 멤버가 된 생성자 → 삭제(휴지통)
ST.add_member(project_id=p["id"], user_email=ALICE)
r = req("DELETE", f"/project/api/tasks/{t['id']}", ALICE)
assert r.status_code == 200 and ST.get_task(task_id=t["id"]) is None
# 프로젝트 삭제: 만든 사람이어도 지금 권한이 없으면 거절, 슈퍼관리자는 예외
p2 = _project("P-del2", ALICE)
ST.update_project(project_id=p2["id"], fields={"owner_email": ADMIN}) # 관리자가 소유자를 바꿈
assert req("DELETE", f"/project/api/projects/{p2['id']}", ALICE).status_code == 403
assert ST.get_project(project_id=p2["id"]) is not None
assert req("DELETE", f"/project/api/projects/{p2['id']}", SUPER).status_code == 200
# ════════════════════════════════════════════════════════════
# [02] 권한 회수 후 조회·변경·알림
# ════════════════════════════════════════════════════════════
def test_revoked_member_loses_everything():
p = _project("P-rev", ADMIN, (ALICE, BOB))
s = _stage(p["id"], by=ADMIN)
t = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB,
json={"title": "shared", "stage_id": s["id"], "assignee_email": ALICE,
"description": f'<span class="pj-mention" data-email="{ALICE}">@a</span>'}).json()["task"]
c = req("POST", f"/project/api/tasks/{t['id']}/comments", ALICE, json={"body": "mine"}).json()["comment"]
assert any(x["id"] == t["id"] for x in req("GET", "/project/api/my-tasks", ALICE).json()["tasks"])
assert any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", ALICE).json()["tasks"])
assert any(n["task_id"] == t["id"] for n in req("GET", "/project/api/notifications", ALICE).json()["notifications"])
ST.remove_member(project_id=p["id"], user_email=ALICE)
assert not any(x["id"] == t["id"] for x in req("GET", "/project/api/my-tasks", ALICE).json()["tasks"])
assert not any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", ALICE).json()["tasks"])
assert not any(n.get("task_id") == t["id"] for n in req("GET", "/project/api/notifications", ALICE).json()["notifications"])
for m, u, body in (("GET", f"/project/api/tasks/{t['id']}", None),
("GET", f"/project/api/tasks/{t['id']}/comments", None),
("GET", f"/project/api/tasks/{t['id']}/attachments", None),
("PUT", f"/project/api/tasks/{t['id']}", {"title": "x"}),
("PUT", f"/project/api/comments/{c['id']}", {"body": "edited"}),
("DELETE", f"/project/api/comments/{c['id']}", None),
("POST", f"/project/api/tasks/{t['id']}/followers", {})):
r = req(m, u, ALICE, json=body) if body is not None else req(m, u, ALICE)
assert r.status_code == 403, (m, u, r.status_code)
assert ST.get_comment(comment_id=c["id"])["body"] == "mine"
assert req("GET", f"/project/t/{t['id']}", ALICE, follow_redirects=False).status_code == 403 # 옛 공유 링크
# 완료 알림은 권한 잃은 담당자에게 가지 않는다(담당자 기록은 남음)
before = _count("SELECT COUNT(*) AS n FROM project_notifications WHERE recipient_email=%s AND task_id=%s", ALICE, t["id"])
assert req("PUT", f"/project/api/tasks/{t['id']}", BOB, json={"completed": True}).status_code == 200
assert _count("SELECT COUNT(*) AS n FROM project_notifications WHERE recipient_email=%s AND task_id=%s", ALICE, t["id"]) == before
assert ST.get_task(task_id=t["id"])["assignee_email"] == ALICE
# 권한 없는 사람을 새 담당자로 지정할 수 없다
assert req("PUT", f"/project/api/tasks/{t['id']}", BOB, json={"assignee_email": DAVE}).status_code == 400
# 관리자·owner·멤버는 그대로
assert req("GET", f"/project/api/tasks/{t['id']}", ADMIN).status_code == 200
assert req("GET", f"/project/api/tasks/{t['id']}", BOB).status_code == 200
# ════════════════════════════════════════════════════════════
# [08] 비멤버 @태그
# ════════════════════════════════════════════════════════════
def test_mentions_only_for_people_who_can_see():
p = _project("P-men", ADMIN, (BOB,))
s = _stage(p["id"], by=ADMIN)
desc = "".join(f'<span class="pj-mention" data-email="{e}">@x</span>' for e in (DAVE, EVE, "ghost@nowhere.test"))
r = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "m", "stage_id": s["id"], "description": desc})
t = r.json()["task"]
assert set(r.json()["mention_skipped"]) == {DAVE, EVE, "ghost@nowhere.test"}
assert _count("SELECT COUNT(*) AS n FROM task_mentions WHERE task_id=%s", t["id"]) == 0
r = req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "@dave hi", "mentions": [DAVE]})
assert r.status_code == 201 and r.json()["mention_skipped"] == [DAVE]
assert not req("GET", "/project/api/mentions", DAVE).json()["tasks"] or \
all(x["id"] != t["id"] for x in req("GET", "/project/api/mentions", DAVE).json()["tasks"])
# 멘션이 접근 권한을 만들지 않는다
assert req("GET", f"/project/api/tasks/{t['id']}", DAVE).status_code == 403
# 연결된 프로젝트 멤버는 태그 가능(읽기 권한)
p2 = _project("P-men2", ADMIN, (BOB, CAROL))
s2 = _stage(p2["id"], by=ADMIN)
assert req("POST", f"/project/api/tasks/{t['id']}/links", BOB, json={"project_id": p2["id"], "stage_id": s2["id"]}).status_code == 201
r = req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "@carol", "mentions": [CAROL]})
assert r.json()["mention_skipped"] == []
assert any(x["id"] == t["id"] for x in req("GET", "/project/api/mentions", CAROL).json()["tasks"])
# 태그 후보 API 도 같은 기준
cands = {u["email"] for u in req("GET", f"/project/api/all-users?task_id={t['id']}", BOB).json()["users"]}
assert CAROL in cands and BOB in cands and DAVE not in cands and EVE not in cands
# ════════════════════════════════════════════════════════════
# [12] 연결된 프로젝트 — 읽기 전용
# ════════════════════════════════════════════════════════════
def test_linked_task_is_read_only():
home = _project("P-home", ADMIN, (BOB,))
other = _project("P-link", ADMIN, (BOB, CAROL))
secret = _project("P-secret", ADMIN, (BOB,))
hs, os_ = _stage(home["id"], by=ADMIN), _stage(other["id"], by=ADMIN)
os2 = _stage(other["id"], name="진행", by=ADMIN)
ss = _stage(secret["id"], by=ADMIN)
t = ST.create_task(project_id=home["id"], title="linked", stage_id=hs["id"], created_by=BOB)
sib = ST.create_task(project_id=home["id"], title="sibling", stage_id=hs["id"], created_by=BOB)
sub = ST.create_task(project_id=home["id"], title="child", parent_task_id=t["id"], created_by=BOB)
for pid, sid in ((other["id"], os_["id"]), (secret["id"], ss["id"])):
assert req("POST", f"/project/api/tasks/{t['id']}/links", BOB, json={"project_id": pid, "stage_id": sid}).status_code == 201
r = req("GET", f"/project/api/tasks/{t['id']}", CAROL)
assert r.status_code == 200 and r.json()["task"]["access"] == "read"
assert [ln["project_id"] for ln in r.json()["task"]["links"]] == [other["id"]] # 비밀 프로젝트는 숨김
assert r.json()["task"]["followers"] is None
assert req("GET", f"/project/api/tasks/{sub['id']}", CAROL).json()["task"]["access"] == "read" # 하위 작업도 읽기
assert req("GET", f"/project/api/tasks/{sib['id']}", CAROL).status_code == 403 # 원 소속의 다른 작업은 안 보임
assert req("GET", f"/project/api/projects/{home['id']}/members", CAROL).status_code == 403
assert req("GET", f"/project/api/tasks/{t['id']}/comments", CAROL).status_code == 200
for m, u, body in (("PUT", f"/project/api/tasks/{t['id']}", {"title": "hack"}),
("POST", f"/project/api/tasks/{t['id']}/comments", {"body": "hi"}),
("DELETE", f"/project/api/tasks/{t['id']}", None)):
r = req(m, u, CAROL, json=body) if body is not None else req(m, u, CAROL)
assert r.status_code == 403, (m, u, r.status_code)
assert ST.get_task(task_id=t["id"])["title"] == "linked"
# 연결된 프로젝트 안의 섹션 이동은 예전처럼 허용
assert req("POST", f"/project/api/tasks/{t['id']}/links", CAROL, json={"project_id": other["id"], "stage_id": os2["id"]}).status_code == 201
# 공유 링크 — 연결된 프로젝트 화면으로
r = req("GET", f"/project/t/{t['id']}", CAROL, follow_redirects=False)
assert r.status_code == 303 and r.headers["location"] == f"/project/p/{other['id']}?task={t['id']}"
# 전체 스냅샷에서 연결 행은 연결된 프로젝트 맥락으로 한 번씩(원 소속 행은 CAROL 에게 없음)
snap = req("GET", f"/project/api/projects/{other['id']}/snapshot?scope=all", CAROL).json()
rows = [x for x in snap["tasks"] if x["id"] == t["id"]]
assert [(x["context_project_id"], x["is_linked"]) for x in rows] == [(other["id"], True)]
# 연결 해제 후엔 볼 수 없다
assert req("DELETE", f"/project/api/tasks/{t['id']}/links/{other['id']}", BOB).status_code == 200
assert req("GET", f"/project/api/tasks/{t['id']}", CAROL).status_code == 403
# ════════════════════════════════════════════════════════════
# [03] 파일 댓글 — 원자적 등록·재전송 중복 방지
# ════════════════════════════════════════════════════════════
def test_file_comment_atomic_and_idempotent():
p = _project("P-file", ADMIN, (BOB, CAROL))
s = _stage(p["id"], by=ADMIN)
t = ST.create_task(project_id=p["id"], title="files", stage_id=s["id"], created_by=BOB)
url = f"/project/api/tasks/{t['id']}/comments/files"
n0 = _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"])
# JSON 경로: 예전 has_attachment 플래그로 빈 댓글을 만들 수 없다
assert req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "", "has_attachment": True}).status_code == 400
# 한 파일이라도 문제면(빈 파일) 아무것도 만들지 않고 어느 파일인지 알려 준다
r = req("POST", url, BOB, files=[("files", ("ok.txt", b"hello", "text/plain")), ("files", ("empty.txt", b"", "text/plain"))])
assert r.status_code == 400 and [f["name"] for f in r.json()["detail"]["failed"]] == ["empty.txt"]
assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0
assert not os.path.isdir(os.path.join(DATA_DIR, "project", str(t["id"]))) or \
not os.listdir(os.path.join(DATA_DIR, "project", str(t["id"])))
# 정상: 본문 없이 파일 두 개, 같은 토큰으로 두 번 보내도 한 번만
files = [("files", ("a.png", b"\x89PNG....", "image/png")), ("files", ("b.pdf", b"%PDF-1", "application/pdf"))]
r1 = req("POST", url, BOB, data={"client_token": "tok-1"}, files=files)
r2 = req("POST", url, BOB, data={"client_token": "tok-1"}, files=files)
assert r1.status_code == 201 and r2.status_code == 201
assert r1.json()["comment"]["id"] == r2.json()["comment"]["id"] and r2.json().get("duplicate")
cid = r1.json()["comment"]["id"]
assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0 + 1
assert _count("SELECT COUNT(*) AS n FROM task_attachments WHERE comment_id=%s", cid) == 2
# DB 저장 실패 → 방금 쓴 파일도 지우고 댓글 없음
orig = ST.add_comment_with_attachments
ST.add_comment_with_attachments = lambda **kw: (_ for _ in ()).throw(RuntimeError("db down"))
try:
before_files = set(os.listdir(os.path.join(DATA_DIR, "project", str(t["id"]))))
try:
req("POST", url, BOB, files=[("files", ("c.txt", b"data", "text/plain"))])
except RuntimeError:
pass # TestClient 가 서버 예외를 그대로 올린다(운영에선 500)
assert set(os.listdir(os.path.join(DATA_DIR, "project", str(t["id"])))) == before_files
finally:
ST.add_comment_with_attachments = orig
assert _count("SELECT COUNT(*) AS n FROM task_comments WHERE task_id=%s", t["id"]) == n0 + 1
# 남의 댓글에 파일을 붙일 수 없다
r = req("POST", f"/project/api/tasks/{t['id']}/attachments", CAROL,
data={"comment_id": str(cid)}, files={"file": ("x.txt", b"x", "text/plain")})
assert r.status_code == 403
# 동시에 같은 토큰 두 개 → 댓글 하나
out = []
ths = [threading.Thread(target=lambda: out.append(req("POST", url, BOB, data={"client_token": "tok-par"},
files=[("files", ("p.txt", b"p", "text/plain"))]).json()))
for _ in range(2)]
[th.start() for th in ths]
[th.join() for th in ths]
assert len({o["comment"]["id"] for o in out}) == 1
# ════════════════════════════════════════════════════════════
# [04] 날짜 범위
# ════════════════════════════════════════════════════════════
def test_date_range_validation():
p = _project("P-date", ADMIN, (BOB, PRO))
s = _stage(p["id"], by=ADMIN)
base = f"/project/api/projects/{p['id']}/tasks"
assert req("POST", base, BOB, json={"title": "bad", "stage_id": s["id"], "start_date": "2026-10-05", "due_date": "2026-10-01"}).status_code == 400
t = req("POST", base, BOB, json={"title": "ok", "stage_id": s["id"], "start_date": "2026-10-01", "due_date": "2026-10-05"}).json()["task"]
u = f"/project/api/tasks/{t['id']}"
assert req("PUT", u, BOB, json={"due_date": "2026-09-30"}).status_code == 400 # 한쪽만 바꿔도 최종 상태 검사
assert ST.get_task(task_id=t["id"])["due_date"] == "2026-10-05"
assert req("PUT", u, BOB, json={"start_date": None}).status_code == 200 # null 로 지우기
assert req("PUT", u, BOB, json={"due_date": "2026-09-30"}).status_code == 200 # 시작일 없으면 허용
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "18:00", "due_time": "09:00"}).status_code == 400
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "00:00", "due_time": "23:59"}).status_code == 200
assert req("PUT", u, BOB, json={"start_date": "2026-09-30", "start_time": "09:00", "due_time": "09:00"}).status_code == 200
# 프로젝트도 같은 규칙(부분 수정 포함) — 프로젝트 수정은 Pro user 이상 멤버(2026-10-12)
pu = f"/project/api/projects/{p['id']}"
assert req("PUT", pu, PRO, json={"start_date": "2026-11-01", "due_date": "2026-10-01"}).status_code == 400
assert req("PUT", pu, PRO, json={"due_date": "2026-10-01"}).status_code == 200
assert req("PUT", pu, PRO, json={"start_date": "2026-11-01"}).status_code == 400
assert req("POST", "/project/api/projects", PRO, json={"name": "d", "start_date": "2026-11-02", "due_date": "2026-11-01"}).status_code == 400
# ════════════════════════════════════════════════════════════
# [11] 완료 섹션에 바로 만든 작업
# ════════════════════════════════════════════════════════════
def test_create_in_done_stage_completes():
p = _project("P-done", ADMIN, (ALICE, BOB))
todo, done = _stage(p["id"], by=ADMIN), _stage(p["id"], name="완료", done=True, by=ADMIN)
SENT_MAIL.clear()
r = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "done now", "stage_id": done["id"], "assignee_email": ALICE})
t = r.json()["task"]
assert t["completed_at"] and "_newly_completed" not in t
assert _count("SELECT COUNT(*) AS n FROM project_activity WHERE task_id=%s AND action='completed'", t["id"]) == 1
assert _count("SELECT COUNT(*) AS n FROM project_notifications WHERE task_id=%s AND type='completed' AND recipient_email=%s", t["id"], ALICE) == 1
# 일반 섹션 생성 → 미완료, 완료 섹션으로 이동 → 완료(이력 1건 더), 이탈 → 미완료
t2 = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "later", "stage_id": todo["id"]}).json()["task"]
assert not t2["completed_at"]
assert req("PUT", f"/project/api/tasks/{t2['id']}", BOB, json={"stage_id": done["id"]}).json()["task"]["completed_at"]
assert not req("PUT", f"/project/api/tasks/{t2['id']}", BOB, json={"stage_id": todo["id"]}).json()["task"]["completed_at"]
# 섹션 없는 하위 작업: 수동 완료/취소
sub = req("POST", f"/project/api/projects/{p['id']}/tasks", BOB, json={"title": "sub", "parent_task_id": t2["id"]}).json()["task"]
assert sub["stage_id"] is None and not sub["completed_at"]
assert req("PUT", f"/project/api/tasks/{sub['id']}", BOB, json={"completed": True}).json()["task"]["completed_at"]
assert not req("PUT", f"/project/api/tasks/{sub['id']}", BOB, json={"completed": False}).json()["task"]["completed_at"]
# ════════════════════════════════════════════════════════════
# [15] 마감 알림 — 원자적·재시도·중복 방지·권한
# ════════════════════════════════════════════════════════════
def test_due_reminders_atomic_and_access():
p = _project("P-rem", ADMIN, (ALICE, BOB))
s = _stage(p["id"], by=ADMIN)
today = today_kst()
t_ok = ST.create_task(project_id=p["id"], title=f"rem-ok-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB)
t_gone = ST.create_task(project_id=p["id"], title=f"rem-gone-{RUN}", stage_id=s["id"], assignee_email=ALICE, due_date=today.isoformat(), created_by=BOB)
t_fail = ST.create_task(project_id=p["id"], title=f"FAILME-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB)
ST.remove_member(project_id=p["id"], user_email=ALICE)
q = "SELECT COUNT(*) AS n FROM project_notifications WHERE task_id=%s AND type='due_today'"
qr = "SELECT COUNT(*) AS n FROM task_reminders WHERE task_id=%s"
with ST._pool.connection() as conn: # noqa: SLF001 - 테스트 DB 에서만: 알림 생성 실패 흉내
conn.execute(f"ALTER TABLE project_notifications ADD CONSTRAINT test_fail_{RUN} CHECK (title NOT LIKE '%%FAILME-{RUN}%%')")
try:
reminders.run_due_reminders(ST, today=today, lookup=USERS.get)
assert _count(q, t_ok["id"]) == 1 and _count(q, t_gone["id"]) == 0
assert _count(q, t_fail["id"]) == 0 and _count(qr, t_fail["id"]) == 0 # 실패 → 기록도 되돌려짐
finally:
with ST._pool.connection() as conn: # noqa: SLF001
conn.execute(f"ALTER TABLE project_notifications DROP CONSTRAINT test_fail_{RUN}")
reminders.run_due_reminders(ST, today=today, lookup=USERS.get) # 재실행: 실패분만 생성
assert _count(q, t_fail["id"]) == 1 and _count(q, t_ok["id"]) == 1
# 동시 실행에도 중복 없음
t_par = ST.create_task(project_id=p["id"], title=f"rem-par-{RUN}", stage_id=s["id"], assignee_email=BOB, due_date=today.isoformat(), created_by=BOB)
ths = [threading.Thread(target=reminders.run_due_reminders, args=(ST,), kwargs={"today": today, "lookup": USERS.get}) for _ in range(4)]
[th.start() for th in ths]
[th.join() for th in ths]
assert _count(q, t_par["id"]) == 1
assert _count(q, t_gone["id"]) == 0 and _count(qr, t_gone["id"]) == 0
# ════════════════════════════════════════════════════════════
# [01] 전체 범위 스냅샷 — 다른 프로젝트의 생성·삭제·섹션 변경·권한 회수
# ════════════════════════════════════════════════════════════
def test_snapshot_all_scope():
a = _project("P-sa", ADMIN, (BOB,))
b = _project("P-sb", ADMIN, (BOB,))
sa, sb = _stage(a["id"], by=ADMIN), _stage(b["id"], by=ADMIN)
tb = ST.create_task(project_id=b["id"], title="in b", stage_id=sb["id"], created_by=BOB)
snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json()
assert {a["id"], b["id"]} <= {x["id"] for x in snap["projects"]}
assert any(x["id"] == tb["id"] for x in snap["tasks"]) and str(b["id"]) in snap["stages_by_project"]
sb2 = _stage(b["id"], name="new", by=ADMIN)
ST.delete_task(task_id=tb["id"], deleted_by=BOB)
snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json()
assert not any(x["id"] == tb["id"] for x in snap["tasks"])
assert sb2["id"] in [s["id"] for s in snap["stages_by_project"][str(b["id"])]]
ST.remove_member(project_id=b["id"], user_email=BOB)
snap = req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).json()
assert b["id"] not in {x["id"] for x in snap["projects"]} and str(b["id"]) not in snap["stages_by_project"]
ST.remove_member(project_id=a["id"], user_email=BOB)
assert req("GET", f"/project/api/projects/{a['id']}/snapshot?scope=all", BOB).status_code == 403
_ = sa
def test_store_date_range_unit():
from app.modules.project import store
store.validate_date_range(None, "2026-01-01")
store.validate_date_range("2026-01-01", None, "10:00", None)
store.validate_date_range("2026-01-01", "2026-01-01", "23:59", None)
for args in (("2026-01-02", "2026-01-01"), ("2026-01-01", "2026-01-01", "10:01", "10:00")):
try:
store.validate_date_range(*args)
except ValueError:
continue
raise AssertionError(args)
def test_store_goal_merge_unit():
from app.modules.project import store
assert store.validate_goal_merge(3, 1) == (1, 3)
assert store.validate_goal_merge(10, 12) == (10, 12)
assert store.validate_goal_month(13, allow_year=True) == 13
assert store.validate_goal_month(16, allow_year=True) == 16
for bad in (17, -1):
try:
store.validate_goal_month(bad, allow_year=True)
except ValueError:
continue
raise AssertionError(bad)
# 분기를 넘는 병합(3~4월, 6~7월, 7~12월)은 거절
for args in ((3, 4), (6, 7), (7, 12), (3, 3), (0, 2), (11, 13)):
try:
store.validate_goal_merge(*args)
except ValueError:
continue
raise AssertionError(args)
def test_store_goal_quarters_unit():
"""분기 칸(2026-10-01 상·하반기 → 1~4분기): 칸 순서·묶음·사각형 범위."""
from app.modules.project import store
assert store.GOAL_COL_ORDER == (0, 1, 2, 3, 13, 4, 5, 6, 15, 7, 8, 9, 14, 10, 11, 12, 16)
assert [store.goal_quarter_of(m) for m in (1, 3, 4, 6, 7, 9, 10, 12)] == [1, 1, 2, 2, 3, 3, 4, 4]
assert store.GOAL_QUARTER_COL == {1: 13, 2: 15, 3: 14, 4: 16}
assert store.goal_col_group(13) == "q1" and store.goal_col_group(14) == "q3"
assert store.goal_col_group(5) == store.goal_col_group(6) != store.goal_col_group(7)
assert store.validate_goal_rect_cols(4, 6) == (4, 3)
assert store.validate_goal_rect_cols(15, 15) == (15, 1)
for a, b in ((3, 4), (3, 13), (6, 15), (0, 1)):
try:
store.validate_goal_rect_cols(a, b)
except ValueError:
continue
raise AssertionError((a, b))
assert store.MEETING_TEMPLATE["마케팅"][0] == "메타"
# ════════════════════════════════════════════════════════════
# 연간 목표 — 상·하반기 글 칸 · 월 칸 병합(마이그레이션 014) · 로아스 % 표기
# ════════════════════════════════════════════════════════════
def test_goal_cell_content_move():
"""실제 PostgreSQL: 서식 포함 이동·동시 이동 충돌·권한·병합 가림·응답 유실 재시도."""
from app.modules.project import store
year = 2060 + int(RUN, 16) % 40
assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201
try:
board = ST.get_goal_board(year=year)
rid = board["areas"][0]["rows"][0]["id"]
rich = store.validate_goal_text(store.GOAL_RICH_PREFIX + '[{"text":"move","color":"#ff0000","size":24,"bold":true,"italic":true,"underline":true}]')
ST.set_goal_cell(row_id=rid, month=1, body=rich)
payload = {"source_row": rid, "source_month": 1, "target_row": rid, "target_month": 2,
"source_body": rich, "target_body": "", "body": rich}
endpoint = "/project/api/goals/cells/move"
assert req("POST", endpoint, BOB, json=payload).status_code == 403
assert req("POST", endpoint, ADMIN, json=payload | {"target_month": 17}).status_code == 400
ST.set_goal_cell(row_id=rid, month=2, body="another edit")
assert req("POST", endpoint, ADMIN, json=payload).status_code == 409
ST.set_goal_cell(row_id=rid, month=2, body="")
assert req("POST", endpoint, ADMIN, json=payload).json() == {"ok": True, "body": rich}
assert req("POST", endpoint, ADMIN, json=payload).status_code == 200
cells = ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"]
assert 1 not in cells and cells[2] == rich
# 같은 원본을 서로 다른 대상으로 동시에 이동하면 한 요청만 성공한다.
ST.set_goal_cell(row_id=rid, month=1, body=rich)
ST.set_goal_cell(row_id=rid, month=2, body="")
barrier = threading.Barrier(2)
results = []
def move_to(month):
barrier.wait()
try:
ST.move_goal_cell(source_row=rid, source_month=1, target_row=rid, target_month=month,
source_body=rich, target_body="", body=rich, updated_by=ADMIN)
results.append("ok")
except store.GoalCellConflict:
results.append("conflict")
workers = [threading.Thread(target=move_to, args=(m,)) for m in (2, 3)]
for t in workers: t.start()
for t in workers: t.join(timeout=10)
assert sorted(results) == ["conflict", "ok"], results
aid = board["areas"][0]["id"]
ST.merge_goal_rect(area_id=aid, row_from=rid, row_to=rid, col_from=4, col_to=5)
hidden = payload | {"source_month": 2 if 2 in ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"] else 3,
"target_month": 5}
assert req("POST", endpoint, ADMIN, json=hidden).status_code == 409
finally:
ST.delete_goal_year(year=year)
def test_goal_halves_and_merges():
year = 2060 + int(RUN, 16) % 40
ST.delete_goal_year(year=year) if year in ST.list_goal_years() else None
assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201
try:
board = ST.get_goal_board(year=year)
assert board["halves"] is True, "마이그레이션 014 적용 필요"
assert board["quarters"] is True, "마이그레이션 017 적용 필요"
rid = board["areas"][0]["rows"][0]["id"]
aid0 = board["areas"][0]["id"]
cell = lambda m, body, who=ADMIN: req( # noqa: E731
"PUT", f"/project/api/goals/rows/{rid}/cells/{m}", who, json={"body": body})
# 분기 글 칸(13 = 1분기 · 15 = 2분기 · 14 = 3분기 · 16 = 4분기), 범위 밖(17)은 400, 비관리자는 403
for m, body in ((13, "1분기 글"), (15, "2분기 글"), (14, "3분기 글"), (16, "4분기 글")):
assert cell(m, body).status_code == 200, m
assert cell(17, "x").status_code == 400
assert cell(13, "y", BOB).status_code == 403
for m, body in ((2, "이월"), (3, "삼월")):
assert cell(m, body).status_code == 200
merge = lambda s, e: req( # noqa: E731 — 엑셀식 병합 API(한 줄 가로)
"POST", f"/project/api/goals/areas/{aid0}/merge", ADMIN,
json={"row_from": rid, "row_to": rid, "col_from": s, "col_to": e})
# 분기를 넘는 병합(3~4월, 사이에 1분기 칸)·한 칸 병합은 400
assert merge(3, 4).status_code == 400 and merge(4, 4).status_code == 400
r = merge(2, 3)
assert r.status_code == 200 and r.json() == {"ok": True, "row_id": rid, "start": 2, "span": 2, "row_span": 1}, r.text
cells = ST.get_goal_board(year=year)["areas"][0]["rows"][0]["cells"]
assert cells[2] == "이월\n삼월" and 3 not in cells
# 병합된 칸의 가운데 월에 늦게 온 저장은 거절(글은 시작 월에만)
assert cell(3, "늦은 저장").status_code == 400
# 걸친 병합은 흡수: 1~2 → 1~3, 글은 월 순서대로 이어진다
r = merge(1, 2)
assert r.json() == {"ok": True, "row_id": rid, "start": 1, "span": 3, "row_span": 1}, r.text
row = ST.get_goal_board(year=year)["areas"][0]["rows"][0]
assert row["merges"] == {1: (3, 1)} and row["cells"][1] == "이월\n삼월" and 2 not in row["cells"]
assert row["cells"][13] == "1분기 글" and row["cells"][15] == "2분기 글" and row["cells"][16] == "4분기 글"
# 해제 — 글은 시작 월에 남음, 없는 병합 해제는 404
assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/1", ADMIN).status_code == 200
assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/1", ADMIN).status_code == 404
row = ST.get_goal_board(year=year)["areas"][0]["rows"][0]
assert row["merges"] == {} and row["cells"][1] == "이월\n삼월"
# 로아스 % 표기(입력에 % 가 있어도 숫자로 저장)
r = req("PUT", f"/project/api/goals/{year}/metrics", ADMIN,
json={"metric": "roas", "kind": "target", "month": 1, "value": "499%"})
assert r.status_code == 200 and r.json()["label"] == "499%" and r.json()["value"] == 499
r = req("PUT", f"/project/api/goals/{year}/metrics", ADMIN,
json={"metric": "sales", "kind": "target", "month": 1, "value": "1,200"})
assert r.json()["label"] == "1,200"
# 영역·줄 이름(그 자리 수정이 쓰는 API) — 영역 이름은 빈 값 400, 줄 이름은 빈 값 허용
aid = ST.get_goal_board(year=year)["areas"][0]["id"]
assert req("PUT", f"/project/api/goals/areas/{aid}", ADMIN, json={"name": ""}).status_code == 400
assert req("PUT", f"/project/api/goals/areas/{aid}", ADMIN, json={"name": "상품2"}).status_code == 200
assert req("PUT", f"/project/api/goals/rows/{rid}", ADMIN, json={"label": ""}).status_code == 200
# 줄 추가 — 기준 줄 위/아래(ref_row_id + place), 없으면 맨 끝. 다른 영역 줄 기준은 404, place 오류는 400
add = lambda body, who=ADMIN: req( # noqa: E731
"POST", f"/project/api/goals/areas/{aid}/rows", who, json=body)
labels = lambda: [r["label"] for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731
before = labels()
assert add({"label": "끝"}).status_code == 201
assert add({"label": "아래", "ref_row_id": rid, "place": "below"}).status_code == 201
assert add({"label": "위", "ref_row_id": rid, "place": "above"}).status_code == 201
assert labels() == ["위", before[0], "아래"] + before[1:] + ["끝"], labels()
areas = ST.get_goal_board(year=year)["areas"]
if len(areas) > 1:
assert add({"label": "x", "ref_row_id": areas[1]["rows"][0]["id"]}).status_code == 404
assert add({"label": "x", "ref_row_id": rid, "place": "left"}).status_code == 400
assert add({"label": "x", "ref_row_id": "abc"}).status_code == 400
assert add({"label": "x"}, BOB).status_code == 403
finally:
ST.delete_goal_year(year=year)
# ════════════════════════════════════════════════════════════
# 연간 목표 — 엑셀식 사각형 병합 · 주간 회의록(마이그레이션 015)
# ════════════════════════════════════════════════════════════
def test_goal_rect_merges():
"""세로 병합(같은 영역 연속 줄)·연간/반기 칸 세로 병합, 걸친 병합 흡수, 가린 칸 저장 거절,
줄 끼우기/지우기에 따라 row_span 증감, 세로 병합에 걸린 줄 이동 거절, 다른 영역 줄 404."""
year = 2060 + (int(RUN, 16) + 7) % 40
ST.delete_goal_year(year=year) if year in ST.list_goal_years() else None
assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201
try:
assert ST.get_goal_board(year=year)["rect"] is True, "마이그레이션 015 적용 필요"
aid = ST.get_goal_board(year=year)["areas"][0]["id"]
rows = lambda: ST.get_goal_board(year=year)["areas"][0]["rows"] # noqa: E731
while len(rows()) < 4: # 이전 연도 구조를 복사해 줄이 더 있을 수도 — 앞 4줄로 시험
req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN, json={"label": "채움"})
r1, r2, r3, r4 = [r["id"] for r in rows()][:4]
put = lambda rid, m, body: req("PUT", f"/project/api/goals/rows/{rid}/cells/{m}", ADMIN, json={"body": body}) # noqa: E731
assert put(r1, 0, "연간1").status_code == 200 and put(r2, 0, "연간2").status_code == 200
assert put(r2, 4, "사월2").status_code == 200
merge = lambda a, b, c0, c1, who=ADMIN: req( # noqa: E731
"POST", f"/project/api/goals/areas/{aid}/merge", who,
json={"row_from": a, "row_to": b, "col_from": c0, "col_to": c1})
# 연간 칸 세로 3줄 — 글은 위에서부터 이어 붙어 맨 위 칸에
r = merge(r1, r3, 0, 0)
assert r.status_code == 200 and r.json() == {"ok": True, "row_id": r1, "start": 0, "span": 1, "row_span": 3}, r.text
b = rows()
assert b[0]["merges"] == {0: (1, 3)} and b[0]["cells"][0] == "연간1\n연간2" and 0 not in b[1]["cells"]
assert put(r2, 0, "가린 칸").status_code == 400 # 가려진 칸 저장 거절
# 연간 + 1월 가로(묶음이 다름)·비관리자·다른 영역 줄 → 400·403·404
assert merge(r1, r1, 0, 1).status_code == 400
assert merge(r1, r2, 3, 4, BOB).status_code == 403
other = ST.get_goal_board(year=year)["areas"]
if len(other) > 1:
assert merge(r1, other[1]["rows"][0]["id"], 3, 3).status_code == 404
# 분기를 넘는 사각형(3~4월)은 400
assert merge(r1, r2, 3, 4).status_code == 400
# 사각형 2줄 × 2칸(4~5월) → 걸친 병합으로 넓히기: 5월 r2 ~ 6월 r3 → 4~6월 × r1~r3
assert merge(r1, r2, 4, 5).json()["row_span"] == 2
r = merge(r2, r3, 5, 6)
assert r.json() == {"ok": True, "row_id": r1, "start": 4, "span": 3, "row_span": 3}, r.text
assert rows()[0]["cells"].get(4) == "사월2"
# 2분기 칸(15) 세로 병합(017)
r = merge(r1, r2, 15, 15)
assert r.status_code == 200 and r.json()["start"] == 15 and r.json()["row_span"] == 2, r.text
assert req("DELETE", f"/project/api/goals/rows/{r1}/merge/15", ADMIN).status_code == 200
# 세로 병합에 걸린 줄 이동 거절, 걸리지 않은 맨 아래 줄(r4)은 위로 못 감(r3 이 걸림) / 병합 해제 뒤엔 됨
assert req("POST", f"/project/api/goals/rows/{r2}/move", ADMIN, json={"direction": 1}).status_code == 400
assert req("POST", f"/project/api/goals/rows/{r4}/move", ADMIN, json={"direction": -1}).status_code == 400
# 병합 안쪽에 줄 끼우기 → row_span +1, 가려진 줄 지우기 → -1
assert req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN,
json={"label": "끼움", "ref_row_id": r1, "place": "below"}).status_code == 201
assert rows()[0]["merges"] == {0: (1, 4), 4: (3, 4)}
assert req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN,
json={"label": "아래", "ref_row_id": r4, "place": "below"}).status_code == 201
assert rows()[0]["merges"] == {0: (1, 4), 4: (3, 4)} # 병합 밖이면 그대로
ins = rows()[1]["id"]
assert req("DELETE", f"/project/api/goals/rows/{ins}", ADMIN).status_code == 200
assert rows()[0]["merges"] == {0: (1, 3), 4: (3, 3)}
# 해제 — 글은 왼쪽 위 칸에
assert req("DELETE", f"/project/api/goals/rows/{r1}/merge/0", ADMIN).status_code == 200
b = rows()
assert b[0]["merges"] == {4: (3, 3)} and b[0]["cells"][0] == "연간1\n연간2"
assert put(r2, 0, "이제 됨").status_code == 200
finally:
ST.delete_goal_year(year=year)
def test_goal_label_groups():
"""항목 칸(2열) 묶음(016): 3열 추가(same_label) 아래 = 이어 붙음, 묶음 첫 줄 위 = 새 줄이 첫 줄(이름 넘겨받음),
묶음 첫 줄 삭제 → 다음 줄이 첫 줄(이름 넘겨받음), 묶인 줄 이동 400, 항목 칸 나누기, 새 연도 복사에 묶음 유지."""
year = 2060 + (int(RUN, 16) + 13) % 40
for y in (year, year + 1):
ST.delete_goal_year(year=y) if y in ST.list_goal_years() else None
assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year}).status_code == 201
try:
assert ST.get_goal_board(year=year)["groups"] is True, "마이그레이션 016 적용 필요"
aid = ST.get_goal_board(year=year)["areas"][0]["id"]
rows = lambda: [(r["label"], r["label_cont"]) for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731
ids = lambda: [r["id"] for r in ST.get_goal_board(year=year)["areas"][0]["rows"]] # noqa: E731
first = ids()[0]
assert req("PUT", f"/project/api/goals/rows/{first}", ADMIN, json={"label": "마케팅1"}).status_code == 200
add = lambda body: req("POST", f"/project/api/goals/areas/{aid}/rows", ADMIN, json=body) # noqa: E731
assert add({"ref_row_id": first, "place": "below", "same_label": True}).status_code == 201
assert rows()[:2] == [("마케팅1", False), ("", True)]
# 같은 항목 칸 위(첫 줄 위) — 새 줄이 첫 줄, 이름을 넘겨받고 예전 첫 줄은 이어 붙음
r = add({"ref_row_id": first, "place": "above", "same_label": True})
assert r.status_code == 201
assert rows()[:3] == [("마케팅1", False), ("", True), ("", True)], rows()
assert ids()[1] == first
assert add({"same_label": True}).status_code == 400 # 기준 줄 없음
# 묶인 줄 이동 거절
assert req("POST", f"/project/api/goals/rows/{first}/move", ADMIN, json={"direction": 1}).status_code == 400
# 묶음 첫 줄 삭제 → 다음 줄이 첫 줄 + 이름
head = ids()[0]
assert req("DELETE", f"/project/api/goals/rows/{head}", ADMIN).status_code == 200
assert rows()[:2] == [("마케팅1", False), ("", True)], rows()
# 새 연도 복사 — 묶음 유지
assert req("POST", "/project/api/goals/years", ADMIN, json={"year": year + 1}).status_code == 201
nxt = [(r["label"], r["label_cont"]) for r in ST.get_goal_board(year=year + 1)["areas"][0]["rows"]]
assert nxt[:2] == [("마케팅1", False), ("", True)], nxt
# 항목 칸 나누기
r = req("POST", f"/project/api/goals/rows/{ids()[0]}/split-label", ADMIN)
assert r.status_code == 200 and r.json()["split"] == 1
assert rows()[:2] == [("마케팅1", False), ("", False)]
assert req("POST", f"/project/api/goals/rows/{ids()[0]}/split-label", BOB).status_code == 403
finally:
for y in (year, year + 1):
ST.delete_goal_year(year=y) if y in ST.list_goal_years() else None
def test_goal_meetings():
"""주간 회의록: 만들기(처음 = 목표 표 영역 + 기본 양식 줄, 유통 줄 쇼핑몰 추측), 다음 주 = 지난 회의록 줄 이어받기
(carry_from → prev), 금액 표기(만·억), 평가 값 검사, 줄 추가/이동/삭제, 화면·권한."""
base = date(2001, 1, 1) + timedelta(days=7 * (int(RUN, 16) % 400)) # 월요일(앞선 회의록이 없을 먼 과거)
while not 8 <= base.day <= 14: # 달 가운데 월요일 — 두 주차 모두 월~일, 앞 주차 = 7일 전(020 주차 규칙)
base += timedelta(days=7)
assert base.weekday() == 0
w1, w2 = base, base + timedelta(days=7)
for w in (w2, w1):
try:
ST.delete_meeting(week_start=w)
except KeyError:
pass
try:
# 회의 완료(잠금)는 관리자만 — 회의록 만들기·고치기는 누구나(2026-10-07)
assert req("POST", f"/project/api/goals/meetings/{w1}/complete", BOB, json={"done": True}).status_code == 403
assert req("POST", f"/project/api/goals/meetings/{w1 + timedelta(days=1)}", ADMIN, json={}).status_code == 400
r = req("POST", f"/project/api/goals/meetings/{w1}", ADMIN, json={"year": w1.year})
assert r.status_code == 201 and r.json()["created"] is True, r.text
assert req("POST", f"/project/api/goals/meetings/{w1}", ADMIN, json={"year": w1.year}).json()["created"] is False
m1 = ST.get_meeting(week_start=w1)
secs = [s for s in dict.fromkeys(it["section"] for it in m1["items"])]
assert secs[:4] == ["상품", "마케팅", "컨텐츠", "유통"], secs
coupang = next(it for it in m1["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
assert coupang["marketplace_code"] == "coupang"
assert next(it for it in m1["items"] if it["section"] == "마케팅" and it["label"] == "네이버")["marketplace_code"] == ""
put = lambda iid, body, who=ADMIN: req("PUT", f"/project/api/goals/meeting-items/{iid}", who, json=body) # noqa: E731
r = put(coupang["id"], {"content": "추석 타임딜", "target_amount": "1,200만"})
assert r.status_code == 200 and r.json()["item"]["target_amount"] == 12_000_000, r.text
# 숫자가 아닌 정량 목표 — 021 이면 글 칸(target_text), 전이면 400
with ST._pool.connection() as conn: # noqa: SLF001
v21 = ST._meeting_v21(conn) # noqa: SLF001
r = put(coupang["id"], {"target_amount": "abc"})
if v21:
assert r.status_code == 200 and r.json()["item"]["target_text"] == "abc" and r.json()["item"]["target_amount"] is None, r.text
else:
assert r.status_code == 400
assert put(coupang["id"], {"target_amount": "1,200만"}).json()["item"]["target_amount"] == 12_000_000
assert put(coupang["id"], {"status": "bogus"}).status_code == 400
assert put(coupang["id"], {"content": "추석 타임딜"}, BOB).status_code == 200 # 누구나 수정
assert req("PUT", f"/project/api/goals/meetings/{w1}", ADMIN,
json={"week_target": "3천만", "attendees": "대표", "notes": "메모"}).status_code == 200
# 다음 주 — 줄을 이어받고 전주 칸(prev)에 지난주 할 일·목표
assert req("POST", f"/project/api/goals/meetings/{w2}", ADMIN, json={"year": w2.year}).status_code == 201
m2 = ST.get_meeting(week_start=w2)
assert len(m2["items"]) == len(m1["items"]) and all(it["content"] == "" for it in m2["items"])
c2 = next(it for it in m2["items"] if it["carry_from"] == coupang["id"])
assert c2["prev"]["content"] == "추석 타임딜" and c2["prev"]["target_amount"] == 12_000_000
assert m2["prev_meeting"] == {"week_start": w1.isoformat(), "week_target": 30_000_000}
# 회의 완료(022) — w1 을 잠그면 w1 의 주요 업무는 못 고치지만, 지난주 결과는 다음 주(w2)가 열려 있으니 적을 수 있다
r = req("POST", f"/project/api/goals/meetings/{w1}/complete", ADMIN, json={"done": True})
if r.status_code == 200:
assert put(coupang["id"], {"content": "잠김"}, BOB).status_code == 409
assert put(coupang["id"], {"result_amount": "100"}, BOB).status_code == 200
assert req("POST", f"/project/api/goals/meetings/{w1}/complete", ADMIN, json={"done": False}).json()["completed"] is False
else:
assert r.status_code == 503, r.text # 022 미적용
# 지난주 결과·평가는 지난 회의록 줄에 저장
assert put(coupang["id"], {"result_amount": "1.5억", "status": "done"}).json()["item"]["result_amount"] == 150_000_000
# 줄 추가(기준 줄 아래)·이동(같은 구역 안)·삭제, 새 구역
r = req("POST", f"/project/api/goals/meetings/{w2}/items", ADMIN,
json={"section": "유통", "label": "롯데온", "ref_item_id": c2["id"], "place": "below"})
assert r.status_code == 201, r.text
new_id = r.json()["id"]
labels = [it["label"] for it in ST.get_meeting(week_start=w2)["items"]]
assert labels[labels.index("쿠팡") + 1] == "롯데온"
assert next(it for it in ST.get_meeting(week_start=w2)["items"] if it["id"] == new_id)["marketplace_code"] == "lotteon"
assert req("POST", f"/project/api/goals/meeting-items/{new_id}/move", ADMIN, json={"direction": -1}).status_code == 200
labels = [it["label"] for it in ST.get_meeting(week_start=w2)["items"]]
assert labels.index("롯데온") < labels.index("쿠팡")
assert req("POST", f"/project/api/goals/meetings/{w2}/items", ADMIN, json={"section": "물류"}).status_code == 201
assert ST.get_meeting(week_start=w2)["items"][-1]["section"] == "물류"
assert req("DELETE", f"/project/api/goals/meeting-items/{new_id}", ADMIN).status_code == 200
# 화면 — 그 달 주차 탭, 회의록 줄
page = req("GET", f"/project/goals/{w2.year}/meetings/{w2.month}?week={w2}", BOB)
assert page.status_code == 200 and page.text.startswith("project/goal_meeting.html"), page.text
v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", BOB)
assert v.status_code == 200 and v.json()["meeting"]["week_start"] == w2.isoformat()
# 지난 회의록을 지우면 다음 주 전주 칸은 비고(carry_from NULL), 회의록은 남는다
assert req("DELETE", f"/project/api/goals/meetings/{w1}", ADMIN).status_code == 200
assert all(it["prev"] is None for it in ST.get_meeting(week_start=w2)["items"])
finally:
for w in (w2, w1):
try:
ST.delete_meeting(week_start=w)
except KeyError:
pass
def _meet_weeks(seed: int, n: int) -> list[date]:
"""지난 주들(실적 기간이 "진행 전"이 아니게) — test_goal_meetings(2001~2008)와 겹치지 않는 2010~2018 의 월요일 n 개(n ≤ 4).
020 주차 규칙에서도 모두 주차 시작일이고 앞 주차 = 7일 전이 되게 같은 달 4~6일 월요일부터."""
base = date(2010, 1, 4) + timedelta(days=7 * ((int(RUN, 16) + seed * 60) % 400))
while not 4 <= base.day <= 6:
base += timedelta(days=7)
assert base.weekday() == 0 and n <= 4
return [base + timedelta(days=7 * i) for i in range(n)]
def _drop_meetings(weeks: list[date]) -> None:
for w in weeks:
try:
ST.delete_meeting(week_start=w)
except KeyError:
pass
def _create_meeting(w: date) -> None:
r = req("POST", f"/project/api/goals/meetings/{w}", ADMIN, json={"year": w.year})
assert r.status_code == 201, r.text
# ════════════════════════════════════════════════════════════
# [G4·G5] 회의록 "지난주" — 정확히 7일 전 주, 생성 순서·이름 변경·같은 이름·삭제/재생성과 무관(018 line_key)
# ════════════════════════════════════════════════════════════
def test_meeting_prev_week_links():
"""지난주 = 정확히 7일 전 주 회의록의 같은 연결키 줄. 018 미적용이면 carry_from 이 7일 전 주일 때만."""
w0, w1, w2, w3 = _meet_weeks(1, 4)
_drop_meetings([w0, w1, w2, w3])
with ST._pool.connection() as conn: # noqa: SLF001
keyed = ST._meeting_keys(conn) # noqa: SLF001
print(" meeting line_key(018):", "applied" if keyed else "not applied — carry_from fallback")
try:
# ① 역순 생성 — 다음 주(w3)를 먼저(양식), 앞 주(w2)를 나중에
_create_meeting(w3)
_create_meeting(w2)
m3 = ST.get_meeting(week_start=w3)
assert m3["prev_meeting"] is not None and m3["prev_meeting"]["week_start"] == w2.isoformat()
if keyed:
assert all(it["prev"] is not None for it in m3["items"]), "역순 생성인데 지난주 줄이 빠짐"
for it in m3["items"]:
assert it["prev"]["week_start"] == w2.isoformat()
assert (it["prev"]["section"], it["prev"]["label"]) == (it["section"], it["label"])
# 다른 구역의 같은 이름(마케팅 "네이버" ↔ 유통 "네이버")이 섞이지 않는다
navers = [it for it in m3["items"] if it["label"] == "네이버"]
assert len(navers) == 2 and len({it["prev"]["id"] for it in navers}) == 2
assert all(it["prev"]["section"] == it["section"] for it in navers)
else:
assert all(it["prev"] is None for it in m3["items"]), "018 미적용 — 역순 생성 연결은 안 됨(문서화된 제한)"
# ② 지난주(w2) 결과를 w2 줄에 저장 → w3 화면에서 보인다(그 주 데이터만)
m2 = ST.get_meeting(week_start=w2)
cou2 = next(it for it in m2["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
assert req("PUT", f"/project/api/goals/meeting-items/{cou2['id']}", ADMIN,
json={"content": "w2 쿠팡 행사", "target_amount": "100", "result_amount": "50"}).status_code == 200
cou3 = next(it for it in ST.get_meeting(week_start=w3)["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
if keyed:
assert cou3["prev"]["id"] == cou2["id"] and cou3["prev"]["content"] == "w2 쿠팡 행사"
# ③ 이름 변경·순서 이동에도 연결 유지
assert req("PUT", f"/project/api/goals/meeting-items/{cou3['id']}", ADMIN, json={"label": "쿠팡 로켓"}).status_code == 200
assert req("POST", f"/project/api/goals/meeting-items/{cou3['id']}/move", ADMIN, json={"direction": -1}).status_code == 200
again = next(it for it in ST.get_meeting(week_start=w3)["items"] if it["id"] == cou3["id"])
assert again["prev"]["id"] == cou2["id"]
# ④ 같은 이름의 새 줄은 지난주와 연결되지 않고, 기존 줄 연결도 그대로
r = req("POST", f"/project/api/goals/meetings/{w3}/items", ADMIN,
json={"section": "유통", "label": "쿠팡", "ref_item_id": cou3["id"], "place": "below"})
new_id = r.json()["id"]
items3 = {it["id"]: it for it in ST.get_meeting(week_start=w3)["items"]}
assert items3[new_id]["prev"] is None and items3[cou3["id"]]["prev"]["id"] == cou2["id"]
# ⑤ 앞 주 삭제 → 지난주 칸 빔, 다시 만들면(앞선 회의록 없음 → 다음 주 w3 양식·키) 다시 연결
ST.delete_meeting(week_start=w2)
assert all(it["prev"] is None for it in ST.get_meeting(week_start=w3)["items"])
_create_meeting(w2)
items3 = {it["id"]: it for it in ST.get_meeting(week_start=w3)["items"]}
assert items3[cou3["id"]]["prev"] is not None and items3[cou3["id"]]["prev"]["week_start"] == w2.isoformat()
assert items3[cou3["id"]]["prev"]["content"] == "" # 새 회의록 — 예전 글이 섞이지 않는다
# ⑥ 한 주 건너뜀 — w0 를 만들고 w1 없이 w2 를 보면 지난주(w1) 자료 없음(w0 결과를 지난주로 보이지 않음)
_drop_meetings([w2, w3])
_create_meeting(w0)
cou0 = next(it for it in ST.get_meeting(week_start=w0)["items"] if it["section"] == "유통" and it["label"] == "쿠팡")
req("PUT", f"/project/api/goals/meeting-items/{cou0['id']}", ADMIN, json={"target_amount": "100", "result_amount": "50"})
_create_meeting(w2)
m2 = ST.get_meeting(week_start=w2)
assert m2["prev_meeting"] is None and all(it["prev"] is None for it in m2["items"])
v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", ADMIN).json()
assert v["head"]["prev_exists"] is False
assert all("rate" not in it for it in v["meeting"]["items"]) # 달성률 열 폐지(2026-10-06)
# w1 을 만들면 w2 의 지난주 = w1(그 주 줄, 비어 있음) — w0 의 50/100 이 아니다
_create_meeting(w1)
v = req("GET", f"/project/api/goals/meetings/{w2}?year={w2.year}&month={w2.month}", ADMIN).json()
assert v["head"]["prev_exists"] is True
prevs = [it["prev"] for it in v["meeting"]["items"] if it["prev"]]
if keyed:
assert prevs and all(p["week_start"] == w1.isoformat() for p in prevs)
assert all(p["week_start"] == w1.isoformat() for p in prevs)
assert all("rate" not in it for it in v["meeting"]["items"]) # 달성률 열 폐지(2026-10-06)
finally:
_drop_meetings([w0, w1, w2, w3])
# ════════════════════════════════════════════════════════════
# [G6] 실적 조회 장애 ≠ 0원 — 목록 장애·매출 조회 장애·부분 실패·정상 0건·미연결·집계 쇼핑몰 없음
# ════════════════════════════════════════════════════════════
class _FakePerf:
def __init__(self, *, list_error=False, sales_error=None, markets=None, amounts=None):
self.list_error, self.sales_error = list_error, sales_error or (lambda a, b: False)
self.markets = markets if markets is not None else [
{"code": "coupang", "name": "쿠팡", "enabled": True, "include_in_sales": True}]
self.amounts = amounts or {}
self.calls = []
def list_marketplaces(self):
if self.list_error:
raise RuntimeError("perf db down")
return self.markets
def daily_amounts(self, start, end, codes):
self.calls.append((start, end))
if self.sales_error(start, end):
raise RuntimeError("sales query failed")
return {(d, c): v for (d, c), v in self.amounts.items() if start <= d <= end and c in codes}
def statuses(self):
return {"coupang": {"last_success_sync_at": "2026-10-01T14:20:00+09:00"}}
def test_meeting_perf_unknown_vs_zero():
"""실적 모듈 장애는 미확인(None + head.unknown), 정상 무매출만 0. 그 값에 기대는 누적 목표 대비 차액·%도 비움.
월 누적 목표 = 주차별 목표(1주차~이 주차) 합, 월 누적 실적 = 1일 ~ 이 주차 끝(지난 주차)."""
from app.modules.project import store
(w,) = _meet_weeks(2, 1)
# 그 달 셋째 주 — 월 누적(1일~지난주 일요일)과 전주 결과(지난주 월~일) 조회 기간이 서로 다르게
weeks = store.month_weeks(w.year, w.month)
w = weeks[2][0]
month_first = date(w.year, w.month, 1)
_drop_meetings([w, w - timedelta(days=7)])
orig_targets = ST.goal_month_targets
ST.goal_month_targets = lambda **kw: {"sales_unit": "원", "sales_target": 1000.0, "sales_actual": None, "roas_target": None}
orig_week_targets = ST.goal_week_targets
ST.goal_week_targets = lambda **kw: {}
try:
_create_meeting(w - timedelta(days=7))
_create_meeting(w)
prev = ST.get_meeting(week_start=w - timedelta(days=7))
cou_prev = next(it for it in prev["items"] if it["label"] == "쿠팡")
req("PUT", f"/project/api/goals/meeting-items/{cou_prev['id']}", ADMIN, json={"target_amount": "100"})
url = f"/project/api/goals/meetings/{w}?year={w.year}&month={w.month}"
def view(perf):
APP.state.performance_store = perf
try:
r = req("GET", url, ADMIN)
assert r.status_code == 200, r.text
return r.json()
finally:
APP.state.performance_store = None
def coupang_row(v):
return next(it for it in v["meeting"]["items"] if it["label"] == "쿠팡" and it["section"] == "유통")
# 실적 모듈 미연결 — perf False, 값 없음(미확인 아님)
v = view(None)
assert v["head"]["perf"] is False and v["head"]["perf_state"] == "off" and v["head"]["unknown"] == []
# 쇼핑몰 목록 장애 — 0 이 아니라 미확인, 누적 대비 차액도 계산하지 않음, 회의록은 열림
v = view(_FakePerf(list_error=True))
h = v["head"]
assert h["perf"] is True and h["perf_state"] == "error"
assert h["mtd"] is None and h["gap"] is None and "mtd" in h["unknown"], h
row = coupang_row(v)
# 지난주 결과는 실적에서 자동으로 채우지 않는다(2026-10-06) — 직접 입력이 없으면 비어 있음
assert row["prev"]["result"] is None and "rate" not in row
assert row["market_off"] is False
assert v["markets"] == []
# 매출 조회 장애(목록은 정상) — 미확인
v = view(_FakePerf(sales_error=lambda a, b: True))
h = v["head"]
assert h["perf_state"] == "ok" and h["mtd"] is None and "mtd" in h["unknown"]
# 정상 조회 0 건 — 진짜 0원(미확인 아님). 주차별 목표가 없으면 누적 목표·차액은 비움
v = view(_FakePerf())
h = v["head"]
assert h["mtd"] == 0 and h["unknown"] == [], h
assert h["week_targets_set"] is False and h["cum_target_won"] is None and h["gap"] is None
assert h["fresh_oldest"] == "10/01 14:20" and "쿠팡 10/01 14:20" in h["fresh_tip"]
# 월 누적 실적 = 1일 ~ 이 주차 끝 / 월 누적 목표 = 1주차~이 주차 주차별 목표 합 → 차액·%
week_end = store.week_period(w)[1]
ST.goal_week_targets = lambda **kw: {a.isoformat(): 1000.0 for a, _ in weeks}
v = view(_FakePerf(amounts={(month_first, "coupang"): 30, (week_end, "coupang"): 40,
(week_end + timedelta(days=1), "coupang"): 999}))
h = v["head"]
assert h["mtd"] == 70 and h["mtd_end"] == week_end.isoformat(), h
assert h["cum_target_won"] == 3000 and h["gap"] == 70 - 3000 and h["rate"] == round(70 / 3000 * 100, 1), h
ST.goal_week_targets = lambda **kw: {}
# 매출 집계 쇼핑몰 없음 — 0 원으로 보이지 않게(empty, 미확인도 아님)
v = view(_FakePerf(markets=[{"code": "coupang", "name": "쿠팡", "enabled": True, "include_in_sales": False}]))
assert v["head"]["perf_state"] == "empty" and v["head"]["mtd"] is None and v["head"]["unknown"] == []
# 금주 목표 저장 응답 = 서버 확정값(원 정수)
r = req("PUT", f"/project/api/goals/meetings/{w}", ADMIN, json={"week_target": "120만"})
assert r.status_code == 200 and r.json()["week_target"] == 1_200_000
finally:
ST.goal_month_targets = orig_targets
ST.goal_week_targets = orig_week_targets
_drop_meetings([w, w - timedelta(days=7)])
# ════════════════════════════════════════════════════════════
# [검토 2026-10-12] 실제 DB — 동시성·조회 범위·알림 페이지·배지·회의록 결과 잠금
# ════════════════════════════════════════════════════════════
def _race(fns):
"""함수들을 최대한 같은 순간에 돌리고 (결과 또는 예외) 목록."""
gate = threading.Barrier(len(fns))
out: list = [None] * len(fns)
def run(i, fn):
gate.wait()
try:
out[i] = fn()
except Exception as exc: # noqa: BLE001
out[i] = exc
ths = [threading.Thread(target=run, args=(i, f)) for i, f in enumerate(fns)]
[t.start() for t in ths]
[t.join() for t in ths]
return out
def test_review_task_dates_never_invert_under_race():
p = _project("P-race", ADMIN, (BOB,))
s = _stage(p["id"], by=ADMIN)
for _ in range(10):
t = ST.create_task(project_id=p["id"], title="race", stage_id=s["id"],
start_date="2026-10-10", due_date="2026-10-20", created_by=BOB)
_race([lambda: ST.update_task(task_id=t["id"], fields={"start_date": "2026-10-18"}),
lambda: ST.update_task(task_id=t["id"], fields={"due_date": "2026-10-12"})])
got = ST.get_task(task_id=t["id"])
assert got["start_date"] <= got["due_date"], got # 한쪽은 지금 값으로 검사돼 거절된다
# 프로젝트도 같은 규칙
for _ in range(5):
q = ST.create_project(name=f"race-{uuid.uuid4().hex[:4]}", owner_email=ADMIN, created_by=ADMIN,
start_date="2026-10-10", due_date="2026-10-20")
_race([lambda: ST.update_project(project_id=q["id"], fields={"start_date": "2026-10-18"}),
lambda: ST.update_project(project_id=q["id"], fields={"due_date": "2026-10-12"})])
got = ST.get_project(project_id=q["id"])
assert got["start_date"] <= got["due_date"], got
def test_review_concurrent_completion_logs_once():
p = _project("P-done-race", ADMIN, (BOB,))
s = _stage(p["id"], by=ADMIN)
t = ST.create_task(project_id=p["id"], title="once", stage_id=s["id"], created_by=BOB)
outs = _race([lambda: ST.update_task(task_id=t["id"], fields={"completed": True}, actor=BOB) for _ in range(4)])
assert sum(1 for o in outs if isinstance(o, dict) and o["_newly_completed"]) == 1, outs
assert _count("SELECT COUNT(*) AS n FROM project_activity WHERE task_id = %s AND action = 'completed'", t["id"]) == 1
def test_review_subproject_tasks_and_archived_scope():
parent = _project("P-parent", ADMIN, (BOB, CAROL))
child = ST.create_project(name=f"child-{uuid.uuid4().hex[:4]}", parent_id=parent["id"], owner_email=ADMIN, created_by=ADMIN)
ST.add_member(project_id=child["id"], user_email=CAROL)
tp = ST.create_task(project_id=parent["id"], title="부모", created_by=ADMIN)
tc = ST.create_task(project_id=child["id"], title="자식", created_by=ADMIN)
ids = lambda who: sorted(t["id"] for t in req("GET", f"/project/api/projects/{parent['id']}/tasks", who).json()["tasks"])
assert ids(BOB) == [tp["id"]] # 부모 멤버·자식 비멤버 — 자식 작업 안 보임
assert ids(CAROL) == sorted([tp["id"], tc["id"]])
assert req("GET", f"/project/api/projects/{parent['id']}/tasks", ADMIN).status_code == 200 # ADMIN = owner
# 보관된 프로젝트를 열어도 자기 작업은 받는다(스냅샷)
arch = _project("P-arch", BOB)
ta = ST.create_task(project_id=arch["id"], title="보관 작업", created_by=BOB)
ST.update_project(project_id=arch["id"], fields={"status": "archived"})
snap = req("GET", f"/project/api/projects/{arch['id']}/snapshot?scope=all", BOB).json()
assert ta["id"] in [t["id"] for t in snap["tasks"]]
assert [x["id"] for x in snap["projects"] if x.get("view_only")] == [arch["id"]]
def test_review_alert_paging_and_badges():
me = USERS.add(f"alert-{uuid.uuid4().hex[:6]}@test.local")
p = _project("P-alert", ADMIN, (me,))
t = ST.create_task(project_id=p["id"], title="x", created_by=ADMIN)
ST.add_notification(recipient_email=me, actor_email=ADMIN, project_id=p["id"], task_id=t["id"], type="assigned", title="배정")
for _ in range(55):
ST.add_notification(recipient_email=me, actor_email=ADMIN, project_id=p["id"], task_id=t["id"], type="comment", title="댓글")
out = req("GET", "/project/api/notifications/alerts?after=0", me).json()
assert [a["type"] for a in out["alerts"]] == ["assigned"] and out["alerts"][0]["href"] == f"/project/t/{t['id']}"
assert req("GET", "/project/api/notifications/unread-count", me).json()["unread"] == 56
# 권한을 잃은 프로젝트의 알림은 배지에서 빠진다(기록은 그대로)
ST.remove_member(project_id=p["id"], user_email=me)
assert req("GET", "/project/api/notifications/unread-count", me).json()["unread"] == 0
# 내 작업 배지·목록 — 미완료는 전부, 완료는 최근 것만
q = _project("P-my", ADMIN, (me,))
open_ids = [ST.create_task(project_id=q["id"], title=f"o{i}", assignee_email=me, created_by=ADMIN)["id"] for i in range(3)]
done_ids = []
for i in range(3):
d = ST.create_task(project_id=q["id"], title=f"d{i}", assignee_email=me, created_by=ADMIN)
ST.update_task(task_id=d["id"], fields={"completed": True})
done_ids.append(d["id"])
rows = ST.list_my_tasks(assignee_email=me, completed_limit=1)
assert sorted(r["id"] for r in rows if not r["completed_at"]) == sorted(open_ids)
assert [r["id"] for r in rows if r["completed_at"]] == [done_ids[-1]]
assert req("GET", "/project/api/my-tasks/open-count", me).json()["open"] == 3
ST.add_mentions(task_id=open_ids[0], emails=[me], actor_email=ADMIN)
assert req("GET", "/project/api/mentions/unread-count", me).json()["unread"] == 1
def test_review_reorder_and_creator_membership():
mine = _project("P-ord", PRO)
other = _project("P-ord-other", ADMIN)
assert req("PUT", "/project/api/projects/order", PRO, json={"ordered_ids": [mine["id"], other["id"]]}).status_code == 403
assert req("PUT", "/project/api/projects/order", PRO, json={"ordered_ids": [mine["id"], mine["id"]]}).status_code == 400
assert req("PUT", "/project/api/projects/order", PRO, json={"ordered_ids": [mine["id"]]}).status_code == 200
r = req("POST", "/project/api/projects", PRO, json={"name": f"own-{RUN}", "owner_email": ALICE})
assert r.status_code == 201, r.text
pid = r.json()["project"]["id"]
assert ST.get_project(project_id=pid)["owner_email"] == ALICE
assert req("GET", f"/project/p/{pid}", PRO).status_code == 200 # 만든 직후 자기 프로젝트를 연다(멤버 행)
ST.remove_member(project_id=pid, user_email=PRO)
assert req("GET", f"/project/p/{pid}", PRO).status_code == 403 # created_by 로는 권한이 남지 않는다
def test_owner_is_member_on_create_and_owner_change():
"""소유자도 멤버 행으로(2026-10-20) — 만들 때·소유자를 바꿀 때, 소유자는 멤버에서 뺄 수 없다."""
r = req("POST", "/project/api/projects", PRO, json={"name": f"owner-mem-{RUN}", "owner_email": ALICE})
assert r.status_code == 201, r.text
pid = r.json()["project"]["id"]
emails = {m["user_email"] for m in ST.list_members(project_id=pid)}
assert {ALICE, PRO} <= emails # 소유자 + 만든 사람
assert req("DELETE", f"/project/api/projects/{pid}/members/{ALICE}", PRO).status_code == 400
assert req("PUT", f"/project/api/projects/{pid}", PRO, json={"owner_email": PRO}).status_code == 200
assert req("DELETE", f"/project/api/projects/{pid}/members/{ALICE}", PRO).status_code == 200 # 예전 소유자는 뺄 수 있다
ST.remove_member(project_id=pid, user_email=PRO) # 멤버 행이 지워져도
ST.update_project(project_id=pid, fields={"owner_email": ALICE})
assert ALICE in {m["user_email"] for m in ST.list_members(project_id=pid)} # 새 소유자는 다시 멤버
def test_review_meeting_result_lock_rules():
from app.modules.project import store
w2 = date(2031, 10, 1) # 수요일 시작 1주차(달 경계)
w1 = store.prev_week_period(w2)[0] # 9월 마지막 주차
_drop_meetings([w1, w2])
try:
_create_meeting(w1)
item = ST.get_meeting(week_start=w1)["items"][0]["id"]
put = lambda body: req("PUT", f"/project/api/goals/meeting-items/{item}", BOB, json=body).status_code
ST.set_meeting_completed(week_start=w1, done=True, by=ADMIN)
assert put({"result_note": "다음 회의 전"}) == 409 # 다음 주차 회의록이 없으면 그 주가 완료되면 잠김
_create_meeting(w2)
assert put({"result_note": "다음 회의에서"}) == 200 # 다음 주차 회의록이 열려 있으면 결과는 적을 수 있다
assert put({"content": "내용"}) == 409 # 주요 업무는 그 주 완료로 잠김(잠금 차이 보존)
ST.set_meeting_completed(week_start=w2, done=True, by=ADMIN)
assert put({"result_note": "늦게"}) == 409
r = req("PUT", f"/project/api/goals/meetings/{w2}", BOB, json={"notes": "잠김"})
assert r.status_code == 409, r.text # 완료된 회의록 머리도
finally:
_drop_meetings([w1, w2])
def test_review_meeting_section_move():
"""구역(첫 열) 통째로 위/아래 — 묶음 안 줄 순서 그대로, 다음 주 회의록이 바뀐 순서를 이어받는다."""
from app.modules.project import store
w1 = store.month_weeks(2031, 11)[1][0] # 11월 2주차 시작일(주차 시작일이어야 회의록을 만든다)
w2 = store.week_period(w1)[1] + timedelta(days=1)
_drop_meetings([w1, w2])
try:
_create_meeting(w1)
secs = lambda w: [s for i, s in enumerate(r["section"] for r in ST.get_meeting(week_start=w)["items"])
if i == 0 or s != ST.get_meeting(week_start=w)["items"][i - 1]["section"]]
before = secs(w1)
assert len(before) >= 2, before
items = ST.get_meeting(week_start=w1)["items"]
second = next(r for r in items if r["section"] == before[1])
labels_second = [r["label"] for r in items if r["section"] == before[1]]
r = req("POST", f"/project/api/goals/meeting-items/{second['id']}/move-section", BOB, json={"direction": -1})
assert r.status_code == 200, r.text
after = secs(w1)
assert after[:2] == [before[1], before[0]] and after[2:] == before[2:], (before, after)
assert [r["label"] for r in ST.get_meeting(week_start=w1)["items"] if r["section"] == before[1]] == labels_second
_create_meeting(w2)
assert secs(w2) == after # 다음 회의록은 바뀐 구역 순서를 이어받는다
ST.set_meeting_completed(week_start=w1, done=True, by=ADMIN)
assert req("POST", f"/project/api/goals/meeting-items/{second['id']}/move-section", BOB,
json={"direction": 1}).status_code == 409 # 회의 완료 뒤 잠금
finally:
_drop_meetings([w1, w2])
def test_review_meeting_label_groups():
"""항목 칸 묶음(027) — 주요 업무 칸에서 추가(same_label)는 같은 항목 칸 안에(아래 = 이어 붙음, 묶음 첫 줄 위 = 새 줄이
첫 줄·이름 넘겨받음), 화면은 항목 칸 rowspan, 묶인 줄은 순서 이동 거절, 다음 주 회의록이 묶음을 이어받음,
첫 줄 삭제 = 아래 줄이 이름을 이어받음, 항목 칸 나누기, 회의 완료 뒤 잠금."""
from app.modules.project import store
w1 = store.month_weeks(2032, 2)[1][0]
w2 = store.week_period(w1)[1] + timedelta(days=1)
_drop_meetings([w1, w2])
try:
_create_meeting(w1)
rows = lambda w=w1: ST.get_meeting(week_start=w)["items"] # noqa: E731
a = rows()[0]
url = f"/project/api/goals/meetings/{w1}/items"
r = req("POST", url, BOB, json={"section": a["section"], "ref_item_id": a["id"], "place": "below", "same_label": True})
assert r.status_code == 201, r.text
b_id = r.json()["id"]
cur = rows()
k = [x["id"] for x in cur].index(a["id"])
assert cur[k + 1]["id"] == b_id and cur[k + 1]["label_cont"] and cur[k + 1]["label"] == "" and not cur[k]["label_cont"]
# 묶음 첫 줄 위 → 새 줄이 첫 줄(이름 넘겨받음), 기준 줄은 이어 붙음
r = req("POST", url, BOB, json={"section": a["section"], "ref_item_id": a["id"], "place": "above", "same_label": True})
assert r.status_code == 201, r.text
c_id = r.json()["id"]
cur = rows()
ids = [x["id"] for x in cur]
k = ids.index(c_id)
assert ids[k:k + 3] == [c_id, a["id"], b_id], ids
assert cur[k]["label"] == a["label"] and not cur[k]["label_cont"]
assert cur[k + 1]["label"] == "" and cur[k + 1]["label_cont"] and cur[k + 2]["label_cont"]
# 줄마다 연결키는 따로(지난주 리뷰가 줄 단위로 이어짐)
assert len({cur[k + n]["line_key"] for n in range(3)}) == 3
# 화면 — 회의록 화면이 그려지고(이 테스트 환경은 템플릿을 실제로 그리지 않음 — 표 모양은 jsdom [2h]),
# 화면용 묶음 계산(라우터 도우미) = 항목 칸 rowspan 3 · 이어 붙은 줄은 항목 칸 없음
from app.modules.project.router import _meeting_label_spans
page = req("GET", f"/project/goals/{w1.year}/meetings/{w1.month}?week={w1}&content=1", BOB)
assert page.status_code == 200, page.text[:300]
sec_rows = [x for x in rows() if x["section"] == a["section"]]
_meeting_label_spans(sec_rows)
spans = {x["id"]: (x.get("label_span"), x["label_hidden"], x["label_shown"]) for x in sec_rows}
assert spans[c_id][:2] == (3, False) and spans[a["id"]][1] and spans[b_id][1], spans
assert spans[b_id][2] == a["label"]
# 묶인 줄은 옮길 수 없다(항목 칸을 나눈 뒤)
r = req("POST", f"/project/api/goals/meeting-items/{a['id']}/move", BOB, json={"direction": 1})
assert r.status_code == 400 and "항목 칸" in r.text, r.text
# 같은 항목 칸 추가는 기준 줄이 필요
assert req("POST", url, BOB, json={"section": a["section"], "same_label": True}).status_code == 400
# 다음 주 회의록 — 묶음을 그대로 이어받음(연결키 기준)
_create_meeting(w2)
by_key = {x["line_key"]: x for x in rows(w2)}
assert [bool(by_key[cur[k + n]["line_key"]]["label_cont"]) for n in range(3)] == [False, True, True]
assert by_key[cur[k]["line_key"]]["label"] == a["label"]
# 첫 줄(c) 삭제 → 바로 아래 줄(a)이 첫 줄이 되고 이름을 이어받음
assert req("DELETE", f"/project/api/goals/meeting-items/{c_id}", BOB).status_code == 200
cur = rows()
k = [x["id"] for x in cur].index(a["id"])
assert not cur[k]["label_cont"] and cur[k]["label"] == a["label"] and cur[k + 1]["id"] == b_id and cur[k + 1]["label_cont"]
# 항목 칸 나누기 → b 가 따로(이름 빈 칸)
r = req("POST", f"/project/api/goals/meeting-items/{a['id']}/split-label", BOB)
assert r.status_code == 200 and r.json()["split"] == 1, r.text
cur = rows()
k = [x["id"] for x in cur].index(b_id)
assert not cur[k]["label_cont"] and cur[k]["label"] == ""
assert req("POST", f"/project/api/goals/meeting-items/{a['id']}/move", BOB, json={"direction": 1}).status_code == 200
# 회의 완료 뒤 잠금
ST.set_meeting_completed(week_start=w1, done=True, by=ADMIN)
assert req("POST", url, BOB, json={"section": a["section"], "ref_item_id": a["id"], "place": "below",
"same_label": True}).status_code == 409
finally:
_drop_meetings([w1, w2])
def _clear_quick(*weeks) -> None:
"""작업 등록 표 테스트 주차 비우기(로컬 테스트 DB — 앞선 실패한 실행의 줄이 남지 않게)."""
with ST._pool.connection() as conn: # noqa: SLF001
conn.execute("DELETE FROM goal_meeting_tasks WHERE week_start = ANY(%s)", (list(weeks),))
def test_review_meeting_quick_tasks_shared():
"""작업 등록 표(025) — 주차별 한 표를 모두가 같이 본다. 남의 프로젝트 이름은 가리고, [적용]은 동시에 눌러도 작업 하나."""
from app.modules.project import store
w = store.month_weeks(2031, 12)[1][0]
other = store.month_weeks(2031, 12)[2][0]
_clear_quick(w, other)
p = _project("P-quick", ADMIN, (BOB,))
s = _stage(p["id"], by=ADMIN)
done = _stage(p["id"], name="완료", done=True, by=ADMIN)
url = f"/project/api/goals/meetings/{w}/quick-tasks"
r = req("POST", url, BOB, json={"title": "상세페이지 수정", "project_id": p["id"], "stage_id": s["id"], "assignee_email": BOB})
assert r.status_code == 201, r.text
row = r.json()["task"]
# 다른 사람(ALICE — 이 프로젝트 멤버 아님)도 같은 표를 본다 — 프로젝트 이름은 가림
seen = req("GET", url, ALICE).json()["tasks"]
assert [x["id"] for x in seen] == [row["id"]] and seen[0]["title"] == "상세페이지 수정"
assert seen[0]["visible"] is False and seen[0]["project_name"] == "(볼 수 없는 프로젝트)"
assert req("GET", f"/project/api/goals/meetings/{other}/quick-tasks", BOB).json()["tasks"] == [] # 주차마다 따로
# 남의 프로젝트는 고를 수 없다
assert req("POST", url, ALICE, json={"title": "x", "project_id": p["id"]}).status_code == 403
# 고치기 — 다른 프로젝트 섹션은 거절, 제목은 저장
assert req("PUT", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB, json={"stage_id": 10 ** 9}).status_code == 400
assert req("PUT", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB, json={"title": "상세페이지 수정2"}).status_code == 200
# [적용] — 비멤버는 403, 멤버가 동시에 4번 눌러도 작업 하나
assert req("POST", f"/project/api/goals/meeting-quick-tasks/{row['id']}/apply", ALICE).status_code == 403
outs = _race([lambda: req("POST", f"/project/api/goals/meeting-quick-tasks/{row['id']}/apply", BOB) for _ in range(4)])
assert sorted(o.status_code for o in outs) == [200, 200, 200, 201], [o.status_code for o in outs]
tid = next(o.json()["task"]["task_id"] for o in outs if o.status_code == 201)
assert _count("SELECT COUNT(*) AS n FROM tasks WHERE project_id = %s AND title = %s", p["id"], "상세페이지 수정2") == 1
t = ST.get_task(task_id=tid)
assert t["stage_id"] == s["id"] and t["assignee_email"] == BOB
# 등록된 줄은 더 못 고침(409), 다시 [적용]해도 그대로
assert req("PUT", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB, json={"title": "x"}).status_code == 409
# 작업 칸 — 방금 만든 작업을 고르면 그 작업의 세부 작업으로(섹션 없음)
r = req("POST", url, BOB, json={"title": "세부 하나", "project_id": p["id"], "parent_task_id": tid})
sub = r.json()["task"]
assert sub["parent_task_id"] == tid and sub["parent_task_title"] == "상세페이지 수정2"
r = req("POST", f"/project/api/goals/meeting-quick-tasks/{sub['id']}/apply", BOB)
assert r.status_code == 201, r.text
st_ = ST.get_task(task_id=r.json()["task"]["task_id"])
assert st_["parent_task_id"] == tid and st_["stage_id"] is None
# 회의 완료면 잠금
_drop_meetings([w])
try:
_create_meeting(w)
ST.set_meeting_completed(week_start=w, done=True, by=ADMIN)
assert req("POST", url, BOB, json={"title": "늦게"}).status_code == 409
assert req("DELETE", f"/project/api/goals/meeting-quick-tasks/{sub['id']}", BOB).status_code == 409
finally:
_drop_meetings([w])
assert req("DELETE", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB).status_code == 200
assert req("DELETE", f"/project/api/goals/meeting-quick-tasks/{sub['id']}", BOB).status_code == 200
assert req("GET", url, BOB).json()["tasks"] == []
_ = done
def test_review_meeting_quick_parent_task_column():
"""작업 칸(026) — 그 프로젝트의 작업만, 프로젝트를 바꾸면 비움, 고른 작업이 사라지면 [적용] 400."""
from app.modules.project import store
w = store.month_weeks(2032, 1)[1][0]
_clear_quick(w)
p = _project("P-quick-pt", ADMIN, (BOB,))
q = _project("P-quick-pt2", ADMIN, (BOB,))
s = _stage(p["id"], by=ADMIN)
base = ST.create_task(project_id=p["id"], title="기존 작업", stage_id=s["id"], created_by=ADMIN)
other = ST.create_task(project_id=q["id"], title="다른 프로젝트 작업", created_by=ADMIN)
url = f"/project/api/goals/meetings/{w}/quick-tasks"
put = lambda i, body: req("PUT", f"/project/api/goals/meeting-quick-tasks/{i}", BOB, json=body)
assert req("POST", url, BOB, json={"title": "x", "project_id": p["id"], "parent_task_id": other["id"]}).status_code == 400
row = req("POST", url, BOB, json={"title": "세부", "project_id": p["id"], "parent_task_id": base["id"]}).json()["task"]
assert row["parent_task_id"] == base["id"]
moved = put(row["id"], {"project_id": q["id"]}).json()["task"]
assert moved["parent_task_id"] is None and moved["stage_id"] is None # 프로젝트가 바뀌면 작업·섹션을 비움
assert put(row["id"], {"project_id": p["id"], "parent_task_id": base["id"]}).json()["task"]["parent_task_id"] == base["id"]
# 고른 작업이 지워지면 [적용]은 400(줄은 그대로)
ST.delete_task(task_id=base["id"], deleted_by=ADMIN)
assert req("POST", f"/project/api/goals/meeting-quick-tasks/{row['id']}/apply", BOB).status_code == 400
assert req("GET", url, BOB).json()["tasks"][0]["task_id"] is None
req("DELETE", f"/project/api/goals/meeting-quick-tasks/{row['id']}", BOB)
def test_review_meeting_apply_is_one_transaction():
"""2026-10-15 검토 F02 — [적용]: 업무 INSERT 와 줄 연결(task_id)이 한 트랜잭션.
줄 연결이 DB 에서 실패하면 만든 업무도 롤백(고아·재시도 중복 없음), 알림은 커밋 뒤에만,
풀 연결 1개로도 동작(잠근 연결을 쥔 채 같은 풀의 두 번째 연결을 기다리지 않음)."""
import time as _time
from app.modules.project import store
w = store.month_weeks(2032, 2)[1][0]
_clear_quick(w)
p = _project("P-apply-tx", ADMIN, (BOB, CAROL))
s = _stage(p["id"], by=ADMIN)
url = f"/project/api/goals/meetings/{w}/quick-tasks"
title = f"연결실패-{RUN}"
row = req("POST", url, BOB, json={"title": title, "project_id": p["id"], "stage_id": s["id"],
"assignee_email": CAROL}).json()["task"]
apply = f"/project/api/goals/meeting-quick-tasks/{row['id']}/apply"
inbox = lambda: _count("SELECT COUNT(*) AS n FROM project_notifications WHERE title = %s", f"업무 배정: {title}") # noqa: E731
# ① 줄 연결(UPDATE … SET task_id)을 DB 에서 실패시킨다 — 테스트 전용 트리거(로컬 테스트 DB 에서만)
with ST._pool.connection() as conn: # noqa: SLF001
conn.execute("CREATE OR REPLACE FUNCTION pj_test_fail_link() RETURNS trigger AS $$ BEGIN "
"IF NEW.task_id IS NOT NULL AND NEW.title LIKE '연결실패-%' THEN RAISE EXCEPTION 'link failed (test)'; "
"END IF; RETURN NEW; END $$ LANGUAGE plpgsql")
conn.execute("DROP TRIGGER IF EXISTS pj_test_fail_link ON goal_meeting_tasks")
conn.execute("CREATE TRIGGER pj_test_fail_link BEFORE UPDATE ON goal_meeting_tasks "
"FOR EACH ROW EXECUTE FUNCTION pj_test_fail_link()")
try:
for _ in range(2): # 재시도해도 고아 업무가 쌓이지 않는다
try:
r = req("POST", apply, BOB)
assert r.status_code >= 500, r.text
except Exception as exc: # noqa: BLE001 — TestClient 가 서버 예외를 그대로 올림
assert "link failed" in str(exc), exc
assert _count("SELECT COUNT(*) AS n FROM tasks WHERE title = %s", title) == 0 # 업무도 롤백
assert ST.get_meeting_task(item_id=row["id"])["task_id"] is None
assert inbox() == 0 # 알림은 커밋 뒤에만
finally:
with ST._pool.connection() as conn: # noqa: SLF001
conn.execute("DROP TRIGGER IF EXISTS pj_test_fail_link ON goal_meeting_tasks")
conn.execute("DROP FUNCTION IF EXISTS pj_test_fail_link()")
# ② 트리거를 걷고 다시 — 업무는 정확히 하나, 배정 알림도 하나
r = req("POST", apply, BOB)
assert r.status_code == 201, r.text
assert _count("SELECT COUNT(*) AS n FROM tasks WHERE title = %s", title) == 1 and inbox() == 1
assert req("POST", apply, BOB).status_code == 200 # 다시 눌러도 그대로
assert _count("SELECT COUNT(*) AS n FROM tasks WHERE title = %s", title) == 1
# ③ 풀 연결 1개 — 예전 구조(잠근 연결 + create_task 의 두 번째 연결)는 여기서 풀 대기에 걸렸다
small = ProjectStore(DSN, max_size=1)
try:
APP.state.project_store = small
row2 = req("POST", url, BOB, json={"title": f"풀1-{RUN}", "project_id": p["id"], "stage_id": s["id"]}).json()["task"]
t0 = _time.monotonic()
r = req("POST", f"/project/api/goals/meeting-quick-tasks/{row2['id']}/apply", BOB)
assert r.status_code == 201 and _time.monotonic() - t0 < 10, (r.status_code, _time.monotonic() - t0)
finally:
APP.state.project_store = ST
small.close()
# ④ 그사이 줄이 바뀌면(확인한 값과 다르면) 만들지 않고 409 — 확인하지 않은 값으로 업무가 생기지 않게
row3 = req("POST", url, BOB, json={"title": f"바뀜-{RUN}", "project_id": p["id"], "stage_id": s["id"]}).json()["task"]
snap = ST.get_meeting_task(item_id=row3["id"])
ST.update_meeting_task(item_id=row3["id"], fields={"title": f"바뀜2-{RUN}"}, by=BOB)
try:
ST.apply_meeting_task(item_id=row3["id"], task_fields={"project_id": p["id"], "title": snap["title"],
"stage_id": s["id"], "created_by": BOB}, expect=snap)
raise AssertionError("409 가 나야 한다")
except store.GoalCellConflict:
pass
assert _count("SELECT COUNT(*) AS n FROM tasks WHERE title LIKE %s", f"바뀜%-{RUN}") == 0
_clear_quick(w)
def test_subtask_followers_and_reaction_alert():
"""업무 창 세부 업무 줄의 협업자(상세 응답 subtasks[].followers) + 댓글 이모티콘 반응 알림(2026-10-13)."""
p = _project("P-subfol", ADMIN, (ALICE, BOB))
s = _stage(p["id"], by=ADMIN)
t = ST.create_task(project_id=p["id"], title="부모", stage_id=s["id"], created_by=ALICE)
sub = ST.create_task(project_id=p["id"], title="세부", parent_task_id=t["id"], created_by=ALICE)
subs = lambda: {x["id"]: x for x in req("GET", f"/project/api/tasks/{t['id']}", ALICE).json()["task"]["subtasks"]}
assert subs()[sub["id"]]["followers"] == []
assert req("POST", f"/project/api/tasks/{sub['id']}/followers", ALICE, json={"email": BOB}).status_code == 200
assert subs()[sub["id"]]["followers"] == [BOB]
assert req("POST", f"/project/api/tasks/{sub['id']}/followers", ALICE, json={"email": DAVE}).status_code == 400 # 비멤버 불가
# 반응 알림 — 켤 때만 댓글 쓴 사람에게(어떤 이모티콘인지 제목에), 끌 때·자기 댓글은 알림 없음
c = req("POST", f"/project/api/tasks/{t['id']}/comments", ALICE, json={"body": "확인 부탁"}).json()["comment"]
q = "SELECT COUNT(*) AS n FROM project_notifications WHERE recipient_email=%s AND task_id=%s AND type='reaction'"
assert req("POST", f"/project/api/comments/{c['id']}/reactions", BOB, json={"emoji": "👍"}).status_code == 200
assert _count(q, ALICE, t["id"]) == 1
with ST._pool.connection() as conn: # noqa: SLF001
title = conn.execute("SELECT title FROM project_notifications WHERE recipient_email=%s AND task_id=%s AND type='reaction'",
(ALICE, t["id"])).fetchone()["title"]
assert "👍" in title and "부모" in title
req("POST", f"/project/api/comments/{c['id']}/reactions", BOB, json={"emoji": "👍"}) # 끄기
req("POST", f"/project/api/comments/{c['id']}/reactions", ALICE, json={"emoji": "🎉"}) # 자기 댓글
assert _count(q, ALICE, t["id"]) == 1
# 멤버에서 빠진 댓글 작성자에게는 가지 않는다
ST.remove_member(project_id=p["id"], user_email=ALICE)
req("POST", f"/project/api/comments/{c['id']}/reactions", BOB, json={"emoji": "✅"})
assert _count(q, ALICE, t["id"]) == 1
def test_create_with_followers_and_my_overdue():
"""세부 업무를 만들 때 협업자 같이 등록(비멤버면 400, 아무것도 안 만듦) + 마감 지난 내 업무 API(2026-10-13)."""
p = _project("P-crfol", ADMIN, (ALICE, BOB))
s = _stage(p["id"], by=ADMIN)
t = ST.create_task(project_id=p["id"], title="부모", stage_id=s["id"], created_by=ALICE)
url = f"/project/api/projects/{p['id']}/tasks"
r = req("POST", url, ALICE, json={"title": "세부-협업", "parent_task_id": t["id"], "followers": [BOB, BOB.upper()]})
assert r.status_code == 201
# 세부 업무는 만든 사람(ALICE)을 자동 협업자로 넣지 않는다 — 고른 사람만(2026-10-14)
assert ST.list_followers(task_id=r.json()["task"]["id"]) == [BOB]
r0 = req("POST", url, ALICE, json={"title": "세부-빈", "parent_task_id": t["id"], "assignee_email": BOB})
assert r0.status_code == 201 and ST.list_followers(task_id=r0.json()["task"]["id"]) == []
rm = req("POST", url, ALICE, json={"title": "메인", "stage_id": s["id"]}) # 메인 업무는 그대로 만든 사람 자동
assert rm.status_code == 201 and ST.list_followers(task_id=rm.json()["task"]["id"]) == [ALICE]
n_before = _count("SELECT COUNT(*) AS n FROM tasks WHERE parent_task_id=%s", t["id"])
assert req("POST", url, ALICE, json={"title": "x", "parent_task_id": t["id"], "followers": [DAVE]}).status_code == 400
assert req("POST", url, ALICE, json={"title": "x", "parent_task_id": t["id"], "followers": "bob"}).status_code == 400
assert _count("SELECT COUNT(*) AS n FROM tasks WHERE parent_task_id=%s", t["id"]) == n_before
# 마감 지난 내 업무 — 어제 마감 미완료(세부 포함)만, 오늘·완료·남의 업무·볼 수 없게 된 업무는 빠짐
y = (today_kst() - timedelta(days=1)).isoformat()
old = ST.create_task(project_id=p["id"], title="지난-메인", stage_id=s["id"], assignee_email=BOB, due_date=y, created_by=ALICE)
sub = ST.create_task(project_id=p["id"], title="지난-세부", parent_task_id=t["id"], assignee_email=BOB, due_date=y, created_by=ALICE)
ST.create_task(project_id=p["id"], title="오늘", stage_id=s["id"], assignee_email=BOB, due_date=today_kst().isoformat(), created_by=ALICE)
done = ST.create_task(project_id=p["id"], title="끝난", stage_id=s["id"], assignee_email=BOB, due_date=y, created_by=ALICE)
ST.update_task(task_id=done["id"], fields={"completed": True}, actor=ALICE)
ST.create_task(project_id=p["id"], title="남의", stage_id=s["id"], assignee_email=ALICE, due_date=y, created_by=ALICE)
got = req("GET", "/project/api/my-overdue", BOB).json()
mine = {x["id"]: x for x in got["tasks"] if x["project_id"] == p["id"]}
assert set(mine) == {old["id"], sub["id"]}, mine
assert mine[sub["id"]]["parent_title"] == "부모" and got["today"] == today_kst().isoformat()
assert req("GET", "/project/api/my-overdue", EVE).status_code == 403 # Project 권한 없음 → 화면 알림은 조용히 멈춤
ST.remove_member(project_id=p["id"], user_email=BOB)
assert not [x for x in req("GET", "/project/api/my-overdue", BOB).json()["tasks"] if x["project_id"] == p["id"]]
def test_assignee_is_never_follower():
"""담당자는 협업자가 아니다(2026-10-13) — 만들 때·배정할 때·협업자 추가 API·정리 SQL(028)."""
import pathlib
p = _project("P-asgfol", ADMIN, (ALICE, BOB, CAROL))
s = _stage(p["id"], by=ADMIN)
url = f"/project/api/projects/{p['id']}/tasks"
# 만든 사람이 담당자 + 고른 협업자에 담당자가 섞여도 → 담당자는 빠진다
t = req("POST", url, ALICE, json={"title": "규칙", "stage_id": s["id"], "assignee_email": ALICE,
"followers": [ALICE, BOB]}).json()["task"]
assert ST.list_followers(task_id=t["id"]) == [BOB]
# 담당자를 협업자로 직접 넣으면 400
assert req("POST", f"/project/api/tasks/{t['id']}/followers", ALICE, json={"email": ALICE}).status_code == 400
assert req("POST", f"/project/api/tasks/{t['id']}/followers", ALICE, json={}).status_code == 400 # 나 = 담당자
# 협업자(BOB)를 담당자로 바꾸면 협업자에서 빠진다 — 예전 담당자(ALICE)는 자동으로 들어가지 않는다
assert req("PUT", f"/project/api/tasks/{t['id']}", ALICE, json={"assignee_email": BOB}).status_code == 200
assert ST.list_followers(task_id=t["id"]) == []
# 댓글 단 담당자도 협업자가 되지 않는다(댓글 쓴 사람 자동 협업자 규칙보다 우선)
req("POST", f"/project/api/tasks/{t['id']}/comments", BOB, json={"body": "담당자 댓글"})
req("POST", f"/project/api/tasks/{t['id']}/comments", CAROL, json={"body": "협업자 댓글"})
assert ST.list_followers(task_id=t["id"]) == [CAROL]
# 정리 SQL — 예전 데이터(담당자가 협업자에도 있음)를 지운다, 두 번 돌려도 같다
with ST._pool.connection() as conn: # noqa: SLF001
conn.execute("INSERT INTO task_followers (task_id, user_email) VALUES (%s, %s)", (t["id"], BOB))
sql = (pathlib.Path(__file__).resolve().parent.parent / "scripts" / "sql" / "project_db_028_followers_exclude_assignee.sql").read_text(encoding="utf-8")
for _ in range(2):
with ST._pool.connection() as conn: # noqa: SLF001
conn.execute(sql)
assert ST.list_followers(task_id=t["id"]) == [CAROL]
def test_move_task_to_other_project():
"""업무를 다른 프로젝트로 옮기기(2026-10-13) — 세부 업무 함께, 대상 섹션·기본 담당자·완료 섹션, 연결 정리, 권한."""
a = _project("P-mvA", ADMIN, (ALICE, BOB))
b = _project("P-mvB", ADMIN, (ALICE,))
c = _project("P-mvC", ADMIN, (BOB,)) # ALICE 는 멤버 아님
sa = _stage(a["id"], by=ADMIN)
sb = _stage(b["id"], name="진행", by=ADMIN)
sb_done = _stage(b["id"], name="완료", done=True, by=ADMIN)
req("PUT", f"/project/api/projects/{b['id']}/stages/{sb['id']}", ADMIN, json={"default_assignee_email": ALICE})
t = ST.create_task(project_id=a["id"], title="옮길 업무", stage_id=sa["id"], created_by=ALICE)
sub = ST.create_task(project_id=a["id"], title="세부", parent_task_id=t["id"], created_by=ALICE)
subsub = ST.create_task(project_id=a["id"], title="세부의 세부", parent_task_id=sub["id"], created_by=ALICE)
assert req("POST", f"/project/api/tasks/{t['id']}/links", ALICE, json={"project_id": b["id"], "stage_id": sb["id"]}).status_code == 201
url = f"/project/api/tasks/{t['id']}/move-project"
# 권한 — 대상 프로젝트 멤버가 아니면 403, 세부 업무만은 400, 남의 섹션은 400, 같은 프로젝트는 400
assert req("POST", url, ALICE, json={"project_id": c["id"], "stage_id": None}).status_code == 403
assert req("POST", f"/project/api/tasks/{sub['id']}/move-project", ALICE, json={"project_id": b["id"]}).status_code == 400
assert req("POST", url, ALICE, json={"project_id": b["id"], "stage_id": sa["id"]}).status_code == 400
assert req("POST", url, ALICE, json={"project_id": a["id"], "stage_id": sa["id"]}).status_code == 400
assert ST.get_task(task_id=t["id"])["project_id"] == a["id"]
# 이동 — 세부 업무(모든 단계)까지 대상 프로젝트로, 섹션 기본 담당자 자동 배정, 대상 쪽 연결은 지움
r = req("POST", url, ALICE, json={"project_id": b["id"], "stage_id": sb["id"]})
assert r.status_code == 200, r.text
moved = r.json()["task"]
assert moved["project_id"] == b["id"] and moved["stage_id"] == sb["id"] and moved["assignee_email"] == ALICE
assert ST.get_task(task_id=sub["id"])["project_id"] == b["id"] and ST.get_task(task_id=subsub["id"])["project_id"] == b["id"]
assert _count("SELECT COUNT(*) AS n FROM task_project_links WHERE task_id=%s AND project_id=%s", t["id"], b["id"]) == 0
assert _count("SELECT COUNT(*) AS n FROM project_activity WHERE task_id=%s AND action='project_moved' AND project_id=%s", t["id"], b["id"]) == 1
# 옛 프로젝트 멤버(BOB, B 비멤버)는 이제 못 본다 / 새 프로젝트 멤버는 본다
assert req("GET", f"/project/api/tasks/{t['id']}", BOB).status_code == 403
assert req("GET", f"/project/api/tasks/{sub['id']}", ALICE).status_code == 200
# 완료 섹션으로 옮기면 완료 처리
t2 = ST.create_task(project_id=a["id"], title="완료로", stage_id=sa["id"], assignee_email=BOB, created_by=ALICE)
r2 = req("POST", f"/project/api/tasks/{t2['id']}/move-project", ALICE, json={"project_id": b["id"], "stage_id": sb_done["id"]})
assert r2.status_code == 200 and r2.json()["task"]["completed_at"]
assert BOB in r2.json()["unseen"] # 담당자가 B 멤버가 아님 — 화면이 안내
def test_move_stage_to_other_project():
"""섹션째 다른 프로젝트로(2026-10-26) — 섹션 + 업무 + 세부 업무(모든 단계), 섹션은 맨 끝, 연결 정리, 권한."""
a = _project("P-smA", ADMIN, (ALICE, BOB))
b = _project("P-smB", ADMIN, (ALICE,))
c = _project("P-smC", ADMIN, (BOB,)) # ALICE 는 멤버 아님
sa = _stage(a["id"], name="옮길 섹션", by=ADMIN)
sa2 = _stage(a["id"], name="남는 섹션", by=ADMIN)
_stage(b["id"], name="B 기존", by=ADMIN)
sb2 = _stage(b["id"], name="B 둘째", by=ADMIN)
t = ST.create_task(project_id=a["id"], title="섹션 업무", stage_id=sa["id"], assignee_email=BOB, created_by=ALICE)
sub = ST.create_task(project_id=a["id"], title="세부", parent_task_id=t["id"], created_by=ALICE)
subsub = ST.create_task(project_id=a["id"], title="세부의 세부", parent_task_id=sub["id"], created_by=ALICE)
stay = ST.create_task(project_id=a["id"], title="남는 업무", stage_id=sa2["id"], created_by=ALICE)
# 대상 프로젝트로 걸린 연결(→ 원 소속이 되니 지움) · C 업무가 이 섹션에 연결(→ A 에 "섹션 없음"으로 남음)
assert req("POST", f"/project/api/tasks/{t['id']}/links", ALICE, json={"project_id": b["id"], "stage_id": sb2["id"]}).status_code == 201
ct = ST.create_task(project_id=c["id"], title="C 업무", created_by=BOB)
assert req("POST", f"/project/api/tasks/{ct['id']}/links", BOB, json={"project_id": a["id"], "stage_id": sa["id"]}).status_code == 201
url = f"/project/api/stages/{sa['id']}/move-project"
# 권한·검증 — 대상 비멤버 403, 원 프로젝트 비멤버 403, 같은 프로젝트 400, 없는 섹션 404
assert req("POST", url, ALICE, json={"project_id": c["id"]}).status_code == 403
assert req("POST", f"/project/api/stages/{sb2['id']}/move-project", BOB, json={"project_id": a["id"]}).status_code == 403
assert req("POST", url, ALICE, json={"project_id": a["id"]}).status_code == 400
assert req("POST", url, ALICE, json={}).status_code == 400
assert req("POST", "/project/api/stages/99999999/move-project", ALICE, json={"project_id": b["id"]}).status_code == 404
assert ST.get_stage(stage_id=sa["id"])["project_id"] == a["id"]
# 이동
r = req("POST", url, ALICE, json={"project_id": b["id"]})
assert r.status_code == 200, r.text
body = r.json()
assert body["stage"]["project_id"] == b["id"] and body["task_count"] == 1
assert body["stage"]["sort_order"] > sb2["sort_order"] # 대상 프로젝트 맨 끝
assert BOB in body["unseen"] # 담당자 BOB 은 B 멤버가 아님
for tid in (t["id"], sub["id"], subsub["id"]):
assert ST.get_task(task_id=tid)["project_id"] == b["id"]
moved = ST.get_task(task_id=t["id"])
assert moved["stage_id"] == sa["id"] and moved["assignee_email"] == BOB # 섹션·담당자 그대로
assert ST.get_task(task_id=stay["id"])["project_id"] == a["id"] # 다른 섹션 업무는 그대로
assert _count("SELECT COUNT(*) AS n FROM task_project_links WHERE task_id=%s AND project_id=%s", t["id"], b["id"]) == 0
assert _count("SELECT COUNT(*) AS n FROM task_project_links WHERE task_id=%s AND project_id=%s AND stage_id IS NULL",
ct["id"], a["id"]) == 1
assert _count("SELECT COUNT(*) AS n FROM project_activity WHERE task_id=%s AND action='project_moved' AND project_id=%s",
t["id"], b["id"]) == 1
assert sa["id"] in [s["id"] for s in ST.list_stages(project_id=b["id"])]
assert sa["id"] not in [s["id"] for s in ST.list_stages(project_id=a["id"])]
# 빈 섹션도 옮겨진다(이력은 프로젝트에만)
empty = _stage(a["id"], name="빈 섹션", by=ADMIN)
r2 = req("POST", f"/project/api/stages/{empty['id']}/move-project", ALICE, json={"project_id": b["id"]})
assert r2.status_code == 200 and r2.json()["task_count"] == 0
if __name__ == "__main__":
if not ENABLED:
print("SKIP: PROJECT_TEST_DB_URL(localhost) not set")
sys.exit(0)
n = 0
for name, fn in sorted(globals().items()):
if name.startswith("test_") and callable(fn):
fn()
n += 1
print("ok", name)
print(f"{n} tests passed")
ST.close()
_ = io, timedelta