c9bce7c976
엑셀식 칸 병합 (예전 Shift+클릭·병합 버튼·오른쪽/왼쪽 칸 병합 메뉴 대체)
- 글 칸을 마우스로 끌어(또는 Shift+클릭) 사각형 선택 → 우클릭 "셀 병합 (N줄 × M칸)" / "병합 해제"
- 같은 업무 영역 안 세로(row_span) + 같은 반기 월 칸 가로, 연간·상·하반기 칸은 세로로만
- 걸친 병합은 엑셀처럼 범위를 넓혀 흡수, 글은 왼쪽 위부터 이어 왼쪽 위 칸에, 해제하면 왼쪽 위 칸에 남음
- POST /api/goals/areas/{id}/merge {row_from,row_to,col_from,col_to} (db.merge_goal_rect), router._goal_area_layout(colspan·rowspan)
- 가려진 칸 저장 거절(세로 포함), 병합 안쪽 줄 끼우기 +1 / 가려진 줄 지우기 -1, 세로 병합에 걸린 줄 이동 거절
주간 회의록 (/project/goals/{연도}/meetings/{월}, 목표 표 월 머리 클릭)
- 주(월~일) 탭, 주마다 회의록: 이번주 할 일·목표 금액 | 지난주 할 일·목표·결과·달성률·평가
- 앞선 회의록 줄 이어받기(carry_from), 처음이면 목표 표 업무 영역 + 기본 양식 줄(유통 줄 쇼핑몰 연결 추측)
- 머리: 월 목표·지난주까지 누적·주당 필요 매출(페이싱)·전주 목표/결과/달성률·금주 목표/현재 실적
- 쇼핑몰 연결 줄의 결과·누적·주간 매출은 실적 모듈 performance_store 읽기 전용(없으면 직접 입력)
- 금액 입력 120만·1.5억·3천만·1억2천만, 참석자·결정 사항 메모, 줄 메뉴(추가·순서·쇼핑몰 연결·삭제), 인쇄
마이그레이션 015(project_db): goal_cell_merges.row_span + CHECK 교체, goal_meetings, goal_meeting_items
캐시 버전 20261001c, 테스트(DB 회귀 test_goal_rect_merges·test_goal_meetings)·문서 갱신
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
690 lines
46 KiB
Python
690 lines
46 KiB
Python
"""프로젝트 관리 모듈 — 권한·저장·댓글 첨부·알림 회귀 테스트 (실제 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")
|
||
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) # 프로젝트 모듈 권한 없음
|
||
|
||
|
||
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] 소유자 변경은 관리자만
|
||
# ════════════════════════════════════════════════════════════
|
||
def test_owner_change_admin_only():
|
||
p = _project("P-owner", ADMIN, (BOB,))
|
||
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"
|
||
# 같은 값을 같이 보내는 건(화면 저장) 통과
|
||
assert req("PUT", f"/project/api/projects/{p['id']}", BOB, 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
|
||
# 생성: 비관리자가 남을 소유자로 지정 → 거절, 본인·미지정 → 본인이 소유자
|
||
assert req("POST", "/project/api/projects", BOB, json={"name": "n1", "owner_email": CAROL}).status_code == 403
|
||
r = req("POST", "/project/api/projects", BOB, json={"name": "n2"})
|
||
assert r.status_code == 201 and r.json()["project"]["owner_email"] == BOB
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════
|
||
# [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")
|
||
# 현재 멤버인 타인 → 생성자 규칙으로 거절
|
||
assert req("DELETE", f"/project/api/tasks/{t['id']}", BOB).status_code == 403
|
||
# 멤버에서 빠진 생성자 → 거절, 행·댓글·휴지통 변화 없음
|
||
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,))
|
||
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
|
||
# 프로젝트도 같은 규칙(부분 수정 포함)
|
||
pu = f"/project/api/projects/{p['id']}"
|
||
assert req("PUT", pu, BOB, json={"start_date": "2026-11-01", "due_date": "2026-10-01"}).status_code == 400
|
||
assert req("PUT", pu, BOB, json={"due_date": "2026-10-01"}).status_code == 200
|
||
assert req("PUT", pu, BOB, json={"start_date": "2026-11-01"}).status_code == 400
|
||
assert req("POST", "/project/api/projects", BOB, 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(7, 12) == (7, 12)
|
||
assert store.validate_goal_month(13, allow_year=True) == 13
|
||
for args in ((6, 7), (3, 3), (0, 2), (11, 13)):
|
||
try:
|
||
store.validate_goal_merge(*args)
|
||
except ValueError:
|
||
continue
|
||
raise AssertionError(args)
|
||
|
||
|
||
# ════════════════════════════════════════════════════════════
|
||
# 연간 목표 — 상·하반기 글 칸 · 월 칸 병합(마이그레이션 014) · 로아스 % 표기
|
||
# ════════════════════════════════════════════════════════════
|
||
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 적용 필요"
|
||
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·14), 범위 밖(15)은 400, 비관리자는 403
|
||
assert cell(13, "상반기 글").status_code == 200 and cell(14, "하반기 글").status_code == 200
|
||
assert cell(15, "x").status_code == 400
|
||
assert cell(13, "y", BOB).status_code == 403
|
||
for m, body in ((2, "이월"), (3, "삼월"), (5, "오월")):
|
||
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})
|
||
# 반기를 넘는 병합·한 칸 병합은 400
|
||
assert merge(5, 8).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
|
||
# 걸친 병합은 흡수: 3~5 → 2~5, 글은 월 순서대로 이어진다
|
||
r = merge(3, 5)
|
||
assert r.json() == {"ok": True, "row_id": rid, "start": 2, "span": 4, "row_span": 1}, r.text
|
||
row = ST.get_goal_board(year=year)["areas"][0]["rows"][0]
|
||
assert row["merges"] == {2: (4, 1)} and row["cells"][2] == "이월\n삼월\n오월" and 5 not in row["cells"]
|
||
assert row["cells"][13] == "상반기 글" and row["cells"][14] == "하반기 글"
|
||
# 해제 — 글은 시작 월에 남음, 없는 병합 해제는 404
|
||
assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/2", ADMIN).status_code == 200
|
||
assert req("DELETE", f"/project/api/goals/rows/{rid}/merge/2", ADMIN).status_code == 404
|
||
row = ST.get_goal_board(year=year)["areas"][0]["rows"][0]
|
||
assert row["merges"] == {} and row["cells"][2] == "이월\n삼월\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
|
||
# 사각형 2줄 × 2칸(3~4월) → 걸친 병합으로 넓히기: 4월 r2 ~ 5월 r3 → 3~5월 × r2~r3
|
||
assert merge(r1, r2, 3, 4).json()["row_span"] == 2
|
||
r = merge(r2, r3, 4, 5)
|
||
assert r.json() == {"ok": True, "row_id": r1, "start": 3, "span": 3, "row_span": 3}, r.text
|
||
assert rows()[0]["cells"].get(3) == "사월2"
|
||
# 세로 병합에 걸린 줄 이동 거절, 걸리지 않은 맨 아래 줄(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), 3: (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), 3: (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), 3: (3, 3)}
|
||
# 해제 — 글은 왼쪽 위 칸에
|
||
assert req("DELETE", f"/project/api/goals/rows/{r1}/merge/0", ADMIN).status_code == 200
|
||
b = rows()
|
||
assert b[0]["merges"] == {3: (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_meetings():
|
||
"""주간 회의록: 만들기(처음 = 목표 표 영역 + 기본 양식 줄, 유통 줄 쇼핑몰 추측), 다음 주 = 지난 회의록 줄 이어받기
|
||
(carry_from → prev), 금액 표기(만·억), 평가 값 검사, 줄 추가/이동/삭제, 화면·권한."""
|
||
base = date(2001, 1, 1) + timedelta(days=7 * (int(RUN, 16) % 400)) # 월요일(앞선 회의록이 없을 먼 과거)
|
||
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:
|
||
assert req("POST", f"/project/api/goals/meetings/{w1}", BOB, json={"year": w1.year}).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
|
||
assert put(coupang["id"], {"target_amount": "abc"}).status_code == 400
|
||
assert put(coupang["id"], {"status": "bogus"}).status_code == 400
|
||
assert put(coupang["id"], {"content": "x"}, BOB).status_code == 403
|
||
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}
|
||
# 지난주 결과·평가는 지난 회의록 줄에 저장
|
||
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
|
||
|
||
|
||
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
|