7 Commits

Author SHA1 Message Date
king 7a7e19636f Merge branch 'feat/project-allview-users' 2026-11-11 10:25:31 +09:00
king 34b8e2fb6b feat(프로젝트): 왼쪽 "전체 보기" 메뉴를 볼 사람을 Project 옵션에서 지정
- 옵션 창 "프로젝트 화면" 분류에 처음 여는 탭과 묶어 대상자 선택(아이콘+이름 체크, 전체 선택/해제)
- 옵션 키 all_view_users(이메일 목록, DB 변경 없음) — 설정 전(null)은 예전처럼 Pro user 이상
- 사이드바 pj_all_view(access.can_all_view), project.js canAllView 로 메뉴 표시만 판단
- assignable-users 에 pro 표시(기본 체크용), 도움말·모듈 CLAUDE.md 갱신, 정적 파일 ?v= 올림

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:25:29 +09:00
king 7c53b16566 Merge branch 'feat/cafe24-sync-shop-flags' 2026-11-10 15:31:37 +09:00
king 8043110197 feat(카페24): 품목 진열·판매 멀티쇼핑몰 일괄 맞춤 스크립트
- python -m app.modules.cafe24.sync_variant_flags --shops 3,4 [--apply]
- 옵션 상품 전체의 기본몰(1) 품목 진열·판매를 지정 쇼핑몰에 같은 값으로(다른 값만 PUT)
- 기본 미리보기, BEFORE 줄로 원래 값 출력(되돌리기용), 감사 actor SYNC_SHOPS

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:31:33 +09:00
king 9f57f5d15e Merge branch 'feat/cafe24-variant-all-shops' 2026-11-10 15:15:39 +09:00
king 4cd349c3a1 feat(카페24): 품목 진열·판매를 모든 멀티쇼핑몰에 같이 반영
- 옵션/품목 팝업 저장 시 기본몰(1)에 반영된 행의 진열·판매만
  CAFE24_SHOP_NOS(예 1,2,3)의 다른 쇼핑몰에도 같은 값으로 PUT
- 추가금액(통화 다름)·자체코드·순서는 기본몰만
- 다른 쇼핑몰 실패는 응답 shop_failed·감사 기록·화면 경고(기본몰 반영 유지)
- 쇼핑몰 목록 API 는 mall.read_store 권한이 필요해 번호를 환경변수로 받음

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 15:15:32 +09:00
king 5e9c1dac88 Merge branch 'feat/cafe24-option-key-nav' 2026-11-10 01:03:56 +09:00
36 changed files with 446 additions and 79 deletions
+5
View File
@@ -126,6 +126,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
# 미설정 시 카페24 기본 도메인(https://<mall_id>.cafe24.com)으로 대체된다.
# CAFE24_SHOP_URL=https://www.miras.co.kr
#
# 멀티쇼핑몰 번호(쉼표). 옵션/품목 팝업에서 바꾼 품목 진열·판매를 이 쇼핑몰 모두에 같은 값으로
# 보낸다(추가금액·자체코드는 기본몰 1 만). 번호는 카페24 관리자 → 멀티쇼핑몰 관리에서 확인.
# 미설정 시 1(기본몰)만.
# CAFE24_SHOP_NOS=1,2,3
#
# 카페24 읽기 지연 유예시간(분). 카페24 관리자 API 는 PUT 뒤 한동안 GET 에서 예전
# 값을 돌려준다. 이 시간 안에 우리가 쓴 값이 있으면, GET 이 그 이전 값을 돌려줘도
# 마지막 쓰기(revision·스냅샷)를 화면·적용 기준으로 삼는다. 지나면 카페24 값을 믿는다.
+2 -2
View File
@@ -486,7 +486,7 @@ VARIANT_UNKNOWN = "unknown" # 요청이 도달했을 수 있으나 응답을
def update_variants(
client: Cafe24Client, product_no: int, requests: list[dict[str, Any]]
client: Cafe24Client, product_no: int, requests: list[dict[str, Any]], *, shop_no: int = 1
) -> list[dict[str, Any]]:
"""여러 품목 부분 수정 — **행별 결과**를 돌려준다(요청 순서 그대로).
@@ -506,7 +506,7 @@ def update_variants(
continue
try:
payload = client.put(
f"/admin/products/{no}/variants", json={"shop_no": 1, "requests": chunk}, product_no=no
f"/admin/products/{no}/variants", json={"shop_no": int(shop_no), "requests": chunk}, product_no=no
)
except Cafe24Error as exc:
status = VARIANT_UNKNOWN if getattr(exc, "maybe_applied", False) else VARIANT_FAILED
+1
View File
@@ -12,6 +12,7 @@
- HTML 편집기에서 `<img>` 태그에 마우스를 올리면 태그를 오렌지색으로 칠하고 화면 오른쪽에 폭 500px·창 높이로 파일명과 미리보기(상대 경로는 `CAFE24_SHOP_URL` 루트 기준, 색칠 한도 `HL_LIMIT` 초과 소스는 미동작).
- HTML 편집기에서 커서가 `<img>` 태그 안 어디에 있든 Ctrl+↑/↓ 로 `src` 파일명(`.jpg`/`.gif`/`.png`) 번호 변경. 없음 → `_2` → `_3` …, 이미 `_숫자` 면 다음 숫자부터. 내릴 때는 원래 번호(없었으면 원래 이름) 아래로 안 감 — 다른 편집이 끼거나 다른 이미지로 옮기면 그때 번호가 새 원래 번호.
- 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지, 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매) 수정.
품목 진열·판매는 `CAFE24_SHOP_NOS`(예 1,2,3)의 모든 멀티쇼핑몰에 같은 값으로 보냄(추가금액 등은 기본몰만).
- 대표이미지는 `POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A`.
NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨.
- 옵션/품목 팝업 「판매 가격」 열: 기본 정보 판매가 + 추가금액을 보여주고, 입력하면 추가금액을 역산(`cafe24-options.js` `bindSalePrice`). 저장되는 값은 추가금액뿐.
+9
View File
@@ -42,6 +42,15 @@ def read_lag_grace_minutes() -> int:
return store.parse_grace_minutes(os.getenv("CAFE24_READ_LAG_GRACE_MIN"))
def shop_nos() -> list[int]:
"""품목 진열·판매를 함께 맞출 멀티쇼핑몰 번호. `CAFE24_SHOP_NOS`(예: 1,2,3), 기본 [1]."""
import os # noqa: WPS433
from . import store # noqa: WPS433
return store.parse_shop_nos(os.getenv("CAFE24_SHOP_NOS"))
def require_user(request: Request) -> dict[str, Any]:
from app.main import get_current_user_record # noqa: WPS433
from app.store import has_module # noqa: WPS433
+20 -1
View File
@@ -37,7 +37,7 @@ from app.integrations.cafe24 import Cafe24Error, build_cafe24_api, products
from app.timezone import now_kst
from . import store, writes
from .common import read_lag_grace_minutes, require_store
from .common import read_lag_grace_minutes, require_store, shop_nos
from .routes_products import load_product, locked_json, remember_write
logger = logging.getLogger("cafe24.product_info")
@@ -636,6 +636,7 @@ def variants_update(
"failed": {code: 사유}, "unknown": {code: 사유}}
100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을
다시 보내지 않게). 하나도 반영되지 않았으면 502.
진열·판매는 `CAFE24_SHOP_NOS` 의 다른 쇼핑몰에도 같은 값으로 보낸다 — 실패는 "shop_failed".
"""
st, user = require_store(request)
actor = str(user.get("email") or "")
@@ -673,9 +674,26 @@ def variants_update(
failed[code] = result["error"]
record_error = _save_snapshot_safe(st, product_no, "variants", by_code) if by_code else ""
# 멀티쇼핑몰: 진열·판매는 쇼핑몰마다 따로라 기본몰(1)에 반영된 행의 진열·판매만
# 다른 쇼핑몰에도 똑같이 보낸다. 추가금액(통화가 다름)·자체코드·순서는 보내지 않는다.
flags = [
{"variant_code": code, **{k: sent[code][k] for k in ("display", "selling") if k in sent[code]}}
for code in by_code if {"display", "selling"} & set(sent.get(code) or {})
]
shop_failed: dict[str, str] = {}
for shop in (shop_nos()[1:] if flags else []):
bad = [r for r in products.update_variants(api.client, product_no, flags, shop_no=shop)
if r["status"] != products.VARIANT_OK]
if bad:
shop_failed[str(shop)] = f"{len(bad)}건 — {bad[0]['error']}"
detail = "; ".join(
f"{code}: " + ", ".join(f"{k}={v}" for k, v in patch.items()) for code, patch in by_code.items()
)
if flags and len(shop_nos()) > 1:
detail = f"[진열·판매 쇼핑몰 {','.join(map(str, shop_nos()))}] " + detail
if shop_failed:
detail += " / 다른 쇼핑몰 실패: " + "; ".join(f"{s}번 {e}" for s, e in shop_failed.items())
if failed or unknown:
detail = (f"성공 {len(by_code)} / 실패 {len(failed)} / 결과 모름 {len(unknown)} — " + detail)
first = next(iter({**failed, **unknown}.values()), "")
@@ -696,5 +714,6 @@ def variants_update(
"updated": {code: _variant_view({"variant_code": code, **patch}) for code, patch in by_code.items()},
"failed": failed,
"unknown": unknown,
"shop_failed": shop_failed,
"record_warning": record_error,
}
+9
View File
@@ -506,6 +506,15 @@ WRITE_REVISION_TYPES: tuple[str, ...] = (REVISION_MANUAL, REVISION_SCHEDULED, RE
DEFAULT_READ_LAG_GRACE_MIN = 360
def parse_shop_nos(value: object) -> list[int]:
"""`CAFE24_SHOP_NOS`("1,2,3") → [1, 2, 3]. 기본 쇼핑몰 1 은 항상 맨 앞, 잘못된 값은 버린다."""
out = [1]
for part in str(value or "").replace(" ", "").split(","):
if part.isdigit() and int(part) > 0 and int(part) not in out:
out.append(int(part))
return out
def parse_grace_minutes(value: object, default: int = DEFAULT_READ_LAG_GRACE_MIN) -> int:
try:
minutes = int(str(value or "").strip())
+113
View File
@@ -0,0 +1,113 @@
"""일회성 — 모든 옵션 상품의 품목 진열·판매를 기본몰(1) 값으로 다른 멀티쇼핑몰에 맞춘다.
# 미리보기(쓰지 않음): 바뀔 품목만 출력
docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags --shops 3,4
# 실제 반영 — 출력(바꾸기 전 값 포함)을 파일로 남겨 둔다
docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags --shops 3,4 --apply > sync.log
기본몰 값은 화면과 같은 기준(읽기 지연 보정)으로 읽는다. 다른 쇼핑몰에 없는 품목은 건너뛴다.
진열·판매만 보낸다(추가금액·자체코드는 건드리지 않음). 출력의 BEFORE 줄 = 되돌릴 때 쓸 원래 값.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
from typing import Any
def plan_flag_sync(base: list[dict[str, Any]], shop_variants: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""기본몰 품목(display/selling = bool) vs 다른 쇼핑몰 GET 품목('T'/'F') → 바꿀 PUT 요청."""
from app.integrations.cafe24 import products # noqa: WPS433
other = {str(v.get("variant_code") or ""): v for v in shop_variants}
out = []
for v in base:
o = other.get(v["variant_code"])
if o is None:
continue
req = {k: ("T" if v[k] else "F") for k in ("display", "selling")
if products._flag(o.get(k)) != v[k]} # noqa: SLF001
if req:
out.append({"variant_code": v["variant_code"], **req})
return out
def main(argv: list[str] | None = None) -> int:
from app.integrations.cafe24 import build_cafe24_api # noqa: WPS433
from . import build_cafe24_store # noqa: WPS433
ap =argparse.ArgumentParser()
ap.add_argument("--shops", required=True, help="맞출 쇼핑몰 번호(쉼표), 예: 3,4")
ap.add_argument("--apply", action="store_true", help="실제로 카페24에 쓴다(없으면 미리보기)")
args = ap.parse_args(argv)
shops = [int(s) for s in args.shops.split(",") if s.strip().isdigit() and int(s) > 1]
if not shops:
print("--shops 에 2 이상 쇼핑몰 번호가 필요합니다.", file=sys.stderr)
return 2
st = build_cafe24_store(dsn=os.environ["CAFE24_DB_URL"])
try:
return _run(st, build_cafe24_api(st), shops, args.apply)
finally:
st.close()
def _run(st: Any, api: Any, shops: list[int], apply: bool) -> int:
from app.integrations.cafe24 import products # noqa: WPS433
from . import writes # noqa: WPS433
from .routes_product_info import _load_options_and_variants # noqa: WPS433
items, truncated = products.list_all_products(api.client)
if truncated:
print("상품이 상한(1000)을 넘어 일부만 처리합니다.", file=sys.stderr)
mode = "APPLY" if apply else "DRY-RUN"
total = failed = 0
for item in items:
no = int(item["product_no"])
if str(item.get("has_option") or "T") == "F":
continue
try:
base = _load_options_and_variants(st, api, no)["variants"]
except Exception as exc: # noqa: BLE001 — 한 상품 실패가 나머지를 막지 않게
print(f"ERROR {no} 기본몰 조회 실패: {exc}")
failed += 1
continue
for shop in shops:
try:
got = api.client.get(f"/admin/products/{no}/variants", params={"shop_no": shop}, product_no=no)
except Exception as exc: # noqa: BLE001
print(f"ERROR {no} shop {shop} 조회 실패: {exc}")
failed += 1
continue
shop_vars = got.get("variants") if isinstance(got.get("variants"), list) else []
reqs = plan_flag_sync(base, shop_vars)
if not reqs:
continue
before = {str(v.get("variant_code")): {"display": v.get("display"), "selling": v.get("selling")}
for v in shop_vars if str(v.get("variant_code")) in {r["variant_code"] for r in reqs}}
print("BEFORE " + json.dumps({"product_no": no, "shop_no": shop, "variants": before}, ensure_ascii=False))
print(f"{mode} {no} shop {shop}: {len(reqs)}건 " + json.dumps(reqs, ensure_ascii=False))
total += len(reqs)
if not apply:
continue
bad = [r for r in products.update_variants(api.client, no, reqs, shop_no=shop)
if r["status"] != products.VARIANT_OK]
failed += len(bad)
writes.audit_safe(
st, actor="SYNC_SHOPS", action="update_variants", product_no=no,
result="FAIL" if bad else "SUCCESS",
detail=(f"[쇼핑몰 {shop} 진열·판매 = 기본몰] " + json.dumps(reqs, ensure_ascii=False)
+ (f" / 실패 {len(bad)}: {bad[0]['error']}" if bad else ""))[:900],
)
if bad:
print(f"ERROR {no} shop {shop}: 실패 {len(bad)}건 — {bad[0]['error']}")
print(f"{mode} 끝 — 상품 {len(items)}개 확인, 바꿀/바꾼 품목 {total}건, 오류 {failed}건")
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())
@@ -130,7 +130,7 @@
{% endblock %}
{% block scripts %}
<script src="/static/cafe24-options.js?v=20261110b"></script>
<script src="/static/cafe24-options.js?v=20261110c"></script>
<script>
(function () {
var pane = document.getElementById("cf24-editor-pane");
+2
View File
@@ -396,6 +396,8 @@ class FakeCafe24:
self._variant_puts += 1
if self.fail_variant_chunk and self._variant_puts == self.fail_variant_chunk:
raise self.variant_error or Cafe24ApiError("품목 수정 거절", status=422)
if (json or {}).get("shop_no", 1) != 1: # 다른 쇼핑몰 — 기본몰 상태는 그대로
return {"variants": [dict(r) for r in (json or {}).get("requests") or []]}
out = []
for r in (json or {}).get("requests") or []:
for var in self.variants:
+16
View File
@@ -1086,6 +1086,22 @@ def test_resolve_description_accepts_iso_created_at():
assert (html, state) == ("NEW", store.SYNC_PENDING)
def test_parse_shop_nos():
assert store.parse_shop_nos(None) == [1]
assert store.parse_shop_nos("2, 3,1,x,0,3") == [1, 2, 3]
def test_plan_flag_sync():
from app.modules.cafe24.sync_variant_flags import plan_flag_sync
base = [{"variant_code": "A", "display": True, "selling": False},
{"variant_code": "B", "display": True, "selling": True},
{"variant_code": "C", "display": False, "selling": False}]
shop = [{"variant_code": "A", "display": "F", "selling": "F"},
{"variant_code": "B", "display": "T", "selling": "T"}] # C 는 그 쇼핑몰에 없음
assert plan_flag_sync(base, shop) == [{"variant_code": "A", "display": "T"}]
def test_parse_grace_minutes():
assert store.parse_grace_minutes("30") == 30
assert store.parse_grace_minutes("") == store.DEFAULT_READ_LAG_GRACE_MIN
@@ -2,7 +2,7 @@
{% block head_extra %}
{# 출고리스트 작성 팝업의 날짜 칸은 프로젝트 화면의 날짜 팝업을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
<link rel="stylesheet" href="/static/project.css?v=20261111a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<link rel="stylesheet" href="/static/cupang.css?v=20261023d" />
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
@@ -249,7 +249,7 @@
{% endblock %}
{% block scripts %}
<script src="/static/project.js?v=20261030b" defer></script>
<script src="/static/project.js?v=20261111a" defer></script>
<script src="/static/cupang-outbound.js?v=20261023d" defer></script>
<script>
(function () {
@@ -2,7 +2,7 @@
{% block head_extra %}
{# 프로젝트 화면 부품(설명 편집기·날짜 팝업·멤버 고르기)을 그대로 쓴다 — project.js 는 PJ_LIB_ONLY 로 부품만 #}
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
<link rel="stylesheet" href="/static/project.css?v=20261111a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<script>window.PJ_LIB_ONLY = true; window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
{% endblock %}
@@ -64,7 +64,7 @@
</section>
</div>
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
<script src="/static/project.js?v=20261030b" defer></script>
<script src="/static/project.js?v=20261111a" defer></script>
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
{% endif %}
{% endblock %}
+6 -2
View File
@@ -24,7 +24,8 @@
- **수퍼관리자(`SUPER_ADMIN_EMAIL` 한 명 고정, 추가 불가) > Admin(`role=admin`) > Pro user(`role=pro`) > User**.
- 판단: `access.is_pro`(Pro user 이상)·`access.is_project_admin`(Admin 이상), 라우터 `_require_pro`, 화면 `pj_pro`·`pj_admin`(`_role_ctx`). `is_admin` 은 ERP 상단 관리자 메뉴용 그대로. pro 는 프로젝트 모듈 밖에서는 user 와 같다.
- Pro user 이상: 새 프로젝트·프로젝트 이름/색/아이콘/소유자 수정·멤버 배정(자기가 멤버인 프로젝트)·사이드바 순서·남의 댓글 수정/삭제·휴지통·전체 보기·담당자별 합계·전체 멤버·소유자 변경.
- Pro user 이상: 새 프로젝트·프로젝트 이름/색/아이콘/소유자 수정·멤버 배정(자기가 멤버인 프로젝트)·사이드바 순서·남의 댓글 수정/삭제·휴지통·담당자별 합계·전체 멤버·소유자 변경.
- 전체 보기 메뉴 = Project 옵션 대상자(아래 "Project 옵션" 절, `access.can_all_view`, 화면 `pj_all_view`).
- Admin 이상 또는 만든 사람: 프로젝트·섹션 삭제. 멤버 누구나: 작업 삭제·서브프로젝트(표는 6-14).
- 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동).
- 배정 멤버(또는 owner)만 그 프로젝트를 조회 — **관리자도 멤버가 아니면 안 보임, 예외는 슈퍼관리자뿐**(2026-10-07, `access.sees_all_projects`; 사이드바 목록·검색·휴지통·알림도 같은 기준, 화면·API 모두 비멤버 403).
@@ -47,7 +48,7 @@
- 첫 화면(`/project/`)은 **내 작업 목록**(프로젝트 홈 카드 화면은 폐지). 내 업무 화면 줄 클릭 = 오른쪽 업무 창(iframe).
- 프로젝트 화면은 캘린더(FullCalendar)/타임라인(vis-timeline)/보드/목록/대시보드 뷰 토글.
- 좌측 사이드바는 수신함·내 작업·휴지통·프로젝트 화면 공용(`templates/project/_side.html` + 프로젝트 목록 동작 `initSideTree`, 새 프로젝트/수정 모달 `_side_modals.html`) — 프로젝트 목록(순서 변경·✎·×)은 어느 화면에서나 같다.
- 사이드바 메뉴: 수신함·전체 보기(Pro user 이상 — 예전 오른쪽 위 "전체 프로젝트" 토글, `?scope=all`, 기본 대시보드)·내 작업(접이식)·목표.
- 사이드바 메뉴: 수신함·전체 보기(Project 옵션 대상자 — 예전 오른쪽 위 "전체 프로젝트" 토글, `?scope=all`, 기본 대시보드)·내 작업(접이식)·목표.
- 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다.
- 보드 카드 끌기 = 실시간 미리보기(2026-10-19, `startCardDrag`·`placeCardPh`): 원래 카드는 숨기고 점선 자리 표시(`.pj-card-ph`)가 카드 사이로 FLIP 애니메이션, 끄는 모양은 기울어진 복제(`setDragImage`). 놓은 자리 그대로 — 다른 섹션도 PUT stage 뒤 `stages/{id}/tasks/order`(정렬 "기본"일 때만, 전체 보기는 섹션 맨 끝).
**필터를 켜도 순서 변경 가능**(2026-10-19 버그 수정 — 필터는 브라우저별 localStorage `pj_filter_<id>` 라 필터를 켜 둔 컴퓨터에서만 섹션 안 카드가 늘 제자리로 돌아갔다). 숨은 업무는 제자리(`orderWithHidden`). 카드 속 이미지 끌기가 "Files" 로 오인돼 카드 놓기를 가로채지 않게 `dragHasFiles` 는 카드·세부 업무 끌기 중 false, 카드 img 는 `-webkit-user-drag: none`. 끄는 중엔 실시간 동기화 쉼(`html.pj-card-dragging`). 컬럼 body 는 dragenter 도 preventDefault(안 하면 자리 표시가 들어온 직후 놓을 때 drop 거부).
@@ -111,6 +112,9 @@
- 왼쪽 분류 | 오른쪽 설정. 새 옵션도 이 창에.
- 폰트 = 누구나·이 브라우저(localStorage `pj_font`).
- 처음 여는 탭·보드 카드 표지 = **수퍼관리자·Admin 만 수정·모든 사용자에게 적용**(서버 `project_options` 마이그레이션 029, `GET/PUT /project/api/options`, `store.normalize_project_options`).
- **"전체 보기" 메뉴를 볼 사람**(2026-11-11) = 프로젝트 화면 분류에 처음 여는 탭과 묶음. 옵션 키 `all_view_users`(이메일 목록, DB 변경 없음 — 029 키·값 표),
`null`(설정 전) = 예전처럼 Pro user 이상. 후보 = `GET /api/assignable-users`(아이콘+이름 `memberPickHtml`, `pro` 표시로 기본 체크) + [전체 선택/해제].
메뉴 표시만 정함(데이터는 멤버 범위 그대로) — 사이드바 `pj_all_view`(`_role_ctx(user, request)`), `project.js canAllView`(`data-all-view`). 대시보드 담당자별 합계는 여전히 Pro user 이상.
- 긴급 공지 = 수퍼관리자만.
## 연간 목표 (마이그레이션 013, `goal_*` 테이블, 6-9)
+8
View File
@@ -70,6 +70,14 @@ def is_pro(user: dict[str, Any] | None) -> bool:
return role_of(user) in ("super", "admin", "pro")
def can_all_view(user: dict[str, Any] | None, allowed: list[str] | None) -> bool:
"""왼쪽 "전체 보기" 메뉴를 보는가 — Project 옵션 all_view_users(목록에 든 사람만), 설정 전(None)이면 Pro user 이상.
메뉴 표시만 정한다 — 전체 보기도 멤버인 프로젝트 범위라 데이터 권한은 그대로(모듈 권한은 화면 진입에서 이미 확인)."""
if allowed is None:
return is_pro(user)
return str((user or {}).get("email") or "").strip().lower() in allowed
def sees_all_projects(user: dict[str, Any] | None) -> bool:
"""멤버가 아니어도 모든 프로젝트를 보는가 — 슈퍼관리자만(모듈 권한도 있어야)."""
return can_use_module(user) and _is_super(user)
+19 -15
View File
@@ -105,12 +105,15 @@ def _require_pro(request: Request) -> dict[str, Any]:
return user
def _role_ctx(user: dict[str, Any]) -> dict[str, Any]:
"""화면 공용 등급 값 — is_admin 은 ERP 공통(상단 관리자 메뉴), pj_pro·pj_admin 은 프로젝트 모듈 버튼용."""
def _role_ctx(user: dict[str, Any], request: Request | None = None) -> dict[str, Any]:
"""화면 공용 등급 값 — is_admin 은 ERP 공통(상단 관리자 메뉴), pj_pro·pj_admin 은 프로젝트 모듈 버튼용,
pj_all_view 는 왼쪽 "전체 보기" 메뉴(Project 옵션 all_view_users — request 가 없으면 옵션 기본값 기준)."""
from app.store import is_admin # noqa: WPS433
opts = _project_options(_store(request) if request is not None else None)
return {"is_admin": is_admin(user), "pj_pro": access.is_pro(user),
"pj_admin": access.is_project_admin(user)}
"pj_admin": access.is_project_admin(user),
"pj_all_view": access.can_all_view(user, opts["all_view_users"])}
def _can_manage(request: Request, st: Any, user: dict[str, Any], project_id: int) -> bool:
@@ -429,7 +432,7 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
"scripts/sql/project_db_init.sql 로 project_db 를 초기화한 뒤 "
"컨테이너를 재기동하세요.",
"user": user,
**_role_ctx(user),
**_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"),
},
status_code=503,
@@ -678,7 +681,7 @@ def my_tasks_page(request: Request) -> HTMLResponse:
"project/mytasks.html",
{
"user": user,
**_role_ctx(user),
**_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"),
"page_title": "내 업무",
"page_subtitle": "내가 담당자인 업무를 한 곳에서 봅니다.",
@@ -726,7 +729,7 @@ def task_permalink(request: Request, task_id: int):
{
"reason": reason,
"user": user,
**_role_ctx(user),
**_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"),
},
status_code=status,
@@ -806,7 +809,7 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
"reason": "이 프로젝트의 멤버만 볼 수 있습니다. "
"프로젝트 관리자에게 멤버 배정을 요청하세요.",
"user": user,
**_role_ctx(user),
**_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"),
},
status_code=403,
@@ -896,7 +899,7 @@ def project_page(request: Request, project_id: int) -> HTMLResponse:
"project/project.html",
{
"user": user,
**_role_ctx(user),
**_role_ctx(user, request),
"pj_options": _project_options(st),
"can_manage": can_manage,
"nav_items": build_erp_nav(user, active="project"),
@@ -967,7 +970,7 @@ def _db_or_503(request: Request) -> Any:
def _project_options(st: Any) -> dict[str, Any]:
"""시스템 Project 옵션(처음 여는 탭·보드 카드 표지) — 읽기 실패해도 화면은 기본값으로 연다."""
"""시스템 Project 옵션(처음 여는 탭·보드 카드 표지·전체 보기 대상자) — 읽기 실패해도 화면은 기본값으로 연다."""
if st is None:
return store.normalize_project_options(None)
try:
@@ -1218,6 +1221,7 @@ def api_assignable_users(request: Request) -> JSONResponse:
"name": u.get("name") or u["email"].split("@")[0],
"id": u["email"].split("@")[0],
"avatar": u.get("picture") or "",
"pro": access.is_pro(u), # Project 옵션 "전체 보기" 대상자 기본값(설정 전 = Pro user 이상)
}
for u in user_store.list_all()
if has_module(u, "project")
@@ -2963,7 +2967,7 @@ def notifier_page(request: Request) -> Any:
"project/notifier.html",
{
"user": user,
**_role_ctx(user),
**_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, admin),
"goal_years": _goal_years_nav(st),
@@ -3114,7 +3118,7 @@ def trash_page(request: Request) -> HTMLResponse:
"project/trash.html",
{
"user": user,
**_role_ctx(user),
**_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, True),
"goal_years": _goal_years_nav(st),
@@ -3191,7 +3195,7 @@ def help_page(request: Request) -> HTMLResponse:
"project/help.html",
{
"user": user,
**_role_ctx(user),
**_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"),
"page_title": "프로젝트 관리 도움말",
"page_subtitle": "처음 쓰는 분을 위한 기능 안내",
@@ -3240,7 +3244,7 @@ def inbox_page(request: Request) -> HTMLResponse:
"project/inbox.html",
{
"user": user,
**_role_ctx(user),
**_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": nav_projects,
"goal_years": _goal_years_nav(st),
@@ -3450,7 +3454,7 @@ def goals_page(request: Request, year: int) -> HTMLResponse:
"project/goals.html",
{
"user": user,
**_role_ctx(user),
**_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, admin),
"goal_years": _goal_years_nav(st),
@@ -4001,7 +4005,7 @@ def goal_meeting_page(request: Request, year: int, month: int, week: str | None
"project/goal_meeting.html",
{
"user": user,
**_role_ctx(user),
**_role_ctx(user, request),
"nav_items": build_erp_nav(user, active="project"),
"nav_projects": _nav_projects(st, user, admin),
"goal_years": _goal_years_nav(st),
+21
View File
@@ -383,7 +383,21 @@ PROJECT_VIEWS: tuple[str, ...] = ("board", "list", "calendar", "timeline", "dash
PROJECT_OPTION_DEFAULTS: dict[str, Any] = {
"default_view": "board", # 왼쪽에서 프로젝트를 열 때 처음 보이는 탭
"board_cover": True, # 보드 카드 표지(설명의 첫 이미지)
"all_view_users": None, # 왼쪽 "전체 보기" 메뉴를 볼 사람(이메일 목록) — None = 예전처럼 Pro user 이상
}
ALL_VIEW_USERS_MAX = 2000
def _email_list(raw: Any) -> list[str] | None:
"""이메일 목록 → 소문자·중복 제거·정렬. 목록이 아니거나 이상한 값이 끼면 None."""
if not isinstance(raw, list) or len(raw) > ALL_VIEW_USERS_MAX:
return None
out: set[str] = set()
for e in raw:
if not isinstance(e, str) or "@" not in e or len(e) > 254:
return None
out.add(e.strip().lower())
return sorted(out)
def normalize_project_options(raw: dict[str, Any] | None) -> dict[str, Any]:
@@ -394,6 +408,8 @@ def normalize_project_options(raw: dict[str, Any] | None) -> dict[str, Any]:
out["default_view"] = raw["default_view"]
if isinstance(raw.get("board_cover"), bool):
out["board_cover"] = raw["board_cover"]
if raw.get("all_view_users") is not None:
out["all_view_users"] = _email_list(raw["all_view_users"])
return out
@@ -413,6 +429,11 @@ def validate_project_options(payload: Any) -> dict[str, Any]:
if not isinstance(payload["board_cover"], bool):
raise ValueError("카드 표지 값이 올바르지 않습니다.")
out["board_cover"] = payload["board_cover"]
if "all_view_users" in payload:
v = payload["all_view_users"]
out["all_view_users"] = None if v is None else _email_list(v)
if v is not None and out["all_view_users"] is None:
raise ValueError("전체 보기 대상자 값이 올바르지 않습니다.")
return out
@@ -1,6 +1,6 @@
{# Project 옵션 — 상단 바 톱니. 왼쪽 분류(일반·프로젝트 화면·보드·관리자) | 오른쪽 설정. 저장 버튼을 눌러야 한꺼번에 반영된다.
· 일반(폰트) — 모두에게 보이고 이 브라우저에만 저장(localStorage pj_font, 아래 인라인 스크립트가 복원).
· 프로젝트 화면(처음 여는 탭)·보드(카드 표지) — 수퍼관리자·Admin(pj_admin)만 보이고, 서버(project_options, 마이그레이션 029)에
· 프로젝트 화면(처음 여는 탭·"전체 보기" 메뉴 대상자)·보드(카드 표지) — 수퍼관리자·Admin(pj_admin)만 보이고, 서버(project_options, 마이그레이션 029)에
저장해 모든 사용자에게 적용. 창을 열 때 GET /project/api/options, 저장은 PUT. project.html 이 data-default-view·
data-board-cover 로 받아 project.js 가 쓴다. 저장하면 "pj-options-change" 이벤트로 보던 보드에 바로 반영.
· 관리자(긴급 공지) — 수퍼관리자만(공지 화면이 수퍼관리자 전용). #}
@@ -62,7 +62,16 @@
<label><input type="radio" name="default_view" value="timeline"><span class="material-symbols-outlined">view_timeline</span>타임라인</label>
<label><input type="radio" name="default_view" value="dashboard"><span class="material-symbols-outlined">monitoring</span>대시보드</label>
</div>
<small class="pj-options-note">왼쪽 "전체 보기"는 지금처럼 대시보드로 열립니다.</small>
</div>
{# 전체 보기 대상자(2026-11-11) — 체크한 사람에게만 왼쪽 "전체 보기" 메뉴가 보인다. 설정 전(all_view_users=null)이면
Pro user 이상이 체크된 채로 열린다. 후보 = project 권한 보유자(GET /project/api/assignable-users). #}
<div class="pj-options-row is-stack">
<div class="pj-options-allview-head">
<span class="pj-options-label" id="pj-options-allview-label"><b>"전체 보기" 메뉴를 볼 사람</b><small>체크한 사람에게만 왼쪽 "전체 보기"가 보입니다(멤버인 프로젝트만 모아 봄, 대시보드로 열림)</small></span>
<button type="button" class="pj-btn pj-options-allview-all" id="pj-options-allview-all">전체 선택</button>
</div>
<div class="pj-member-picker pj-options-allview" id="pj-options-allview" role="group" aria-labelledby="pj-options-allview-label"></div>
<small class="pj-options-note" id="pj-options-allview-count"></small>
</div>
</div>
</section>
@@ -105,4 +114,4 @@
document.documentElement.dataset.pjFont = pf;
} catch (_) {}
</script>
<script src="/static/project-options.js?v=20261016c" defer></script>
<script src="/static/project-options.js?v=20261111a" defer></script>
@@ -10,7 +10,8 @@
side_active 'inbox' | 'mytasks' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시
goal_years "목표" 아래 연도 목록(router._goal_years_nav — 올해는 항상 포함)
goal_year_active 목표 화면에서 보고 있는 연도
pj_pro Pro user 이상 — 프로젝트 생성·수정·순서·전체 보기·휴지통·전체 멤버·연도 추가
pj_pro Pro user 이상 — 프로젝트 생성·수정·순서·휴지통·전체 멤버·연도 추가
pj_all_view "전체 보기" 메뉴 — Project 옵션 대상자(설정 전이면 Pro user 이상, router._role_ctx)
pj_admin Admin 이상 — 남이 만든 프로젝트도 삭제(그 밖은 만든 사람만)
목록 동작은 project.js 의 initSideTree(첫 화면을 같은 마크업으로 다시 그림),
새 프로젝트/수정 모달은 각 화면이 include 하는 project/_side_modals.html. #}
@@ -39,9 +40,9 @@
<span class="pj-side-navbadge" id="pj-mention-badge"
{% if not mention_unread %}hidden{% endif %}>{{ mention_unread }}</span>
</a>
{# 전체 보기(2026-10-08, Pro user 이상 — 멤버인 프로젝트 범위) — 예전 프로젝트 화면 오른쪽 위 "전체 프로젝트" 토글. 지금 프로젝트(없으면 목록 첫 프로젝트)
{# 전체 보기(2026-10-08 — 멤버인 프로젝트 범위, 2026-11-11 부터 볼 사람은 Project 옵션 "프로젝트 화면" 대상자) — 예전 프로젝트 화면 오른쪽 위 "전체 프로젝트" 토글. 지금 프로젝트(없으면 목록 첫 프로젝트)
화면을 ?scope=all 로 연다 — 볼 수 있는 모든 프로젝트의 작업. 프로젝트 화면에서는 project.js 가 새로고침 없이 바꾼다. #}
{% if pj_pro %}
{% if pj_all_view %}
{% set _all_pid = current_pid or ((nav_projects | rejectattr("status", "equalto", "completed") | list | first or {}).id or 0) %}
{% if _all_pid %}
<a class="pj-side-navlink" id="pj-side-allview" href="/project/p/{{ _all_pid }}?scope=all">
@@ -1,7 +1,7 @@
{% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
<link rel="stylesheet" href="/static/project.css?v=20261111a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -289,5 +289,5 @@
<script src="/static/project-goal-text.js?v=20261026a" defer></script>
<script src="/static/project-meeting-cells.js?v=20261012a" defer></script>
<script src="/static/project.js?v=20261030b" defer></script>
<script src="/static/project.js?v=20261111a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
<link rel="stylesheet" href="/static/project.css?v=20261111a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -207,5 +207,5 @@
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project-goal-text.js?v=20261026a" defer></script>
<script src="/static/project.js?v=20261030b" defer></script>
<script src="/static/project.js?v=20261111a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
<link rel="stylesheet" href="/static/project.css?v=20261111a" />
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -96,7 +96,7 @@
<h2><span class="pjh-num">2</span>화면 구성</h2>
<div class="pjh-map" aria-hidden="true">
<div class="pjh-map-top"><span><b>위쪽 바</b>화면 이름</span><span>🔔 알림 · 내 이름 · 로그아웃 · <b style="display:inline">?</b> 도움말 · 옵션</span></div>
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 전체 보기(Pro user 이상) · 내 업무 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 전체 보기(옵션에서 고른 사람) · 내 업무 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
<div class="pjh-map-main"><b>가운데 업무 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>필터 바<br>업무들</div>
</div>
<h3>왼쪽 사이드바</h3>
@@ -120,7 +120,7 @@
<b>일반</b>: 폰트(기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드, 미리보기) — 누구나 바꿀 수 있고 이 브라우저에만 적용됩니다.
아래 프로젝트 화면·보드 분류는 수퍼관리자·Admin 에게만 보이고, 바꾸면 <b>모든 사용자</b>에게 적용됩니다(다른 사람은 다음에 화면을 열 때부터). 관리자(긴급 공지) 분류는 수퍼관리자에게만 보입니다.
분류 제목 옆 표시(이 브라우저에만 / 모든 사용자에게)로 적용 범위를 알 수 있습니다.
<b>프로젝트 화면</b>: 처음 여는 탭 — 왼쪽에서 프로젝트를 고르면 바로 보일 보기(보드·목록·캘린더·타임라인·대시보드). 왼쪽 "전체 보기"는 늘 대시보드로 열립니다.
<b>프로젝트 화면</b>: 처음 여는 탭 — 왼쪽에서 프로젝트를 고르면 바로 보일 보기(보드·목록·캘린더·타임라인·대시보드). <b>"전체 보기" 메뉴를 볼 사람</b> — 직원 아이콘을 체크한 사람에게만 왼쪽 "전체 보기"가 보입니다([전체 선택]으로 한 번에, 처음엔 Pro user 이상이 체크돼 있음). "전체 보기"는 늘 대시보드로 열립니다.
<b>보드</b>: 카드 표지 이미지 — 끄면 메인 업무 설명에 이미지가 있어도 보드 카드에 표지를 보여 주지 않습니다(보던 보드에 바로 반영).
<span class="pjh-ui">기본값으로</span>는 창 안의 값만 처음으로 돌립니다(저장해야 반영). <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li>
</ul>
@@ -151,7 +151,7 @@
<tr><td>사이드바 프로젝트 순서 바꾸기 (<span class="pjh-ui">⣿</span>)</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>댓글 고치기·지우기</td><td>O</td><td>남의 댓글도</td><td>본인 댓글만</td></tr>
<tr><td>휴지통 보기·복구</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>전체 보기(모든 프로젝트 업무 함께 보기)</td><td>O</td><td>O (멤버인 프로젝트 범위)</td><td>X</td></tr>
<tr><td>전체 보기(모든 프로젝트 업무 함께 보기)</td><td colspan="3">Project 옵션 → 프로젝트 화면에서 고른 사람(처음엔 Pro user 이상, 멤버인 프로젝트 범위)</td></tr>
<tr><td>대시보드 “담당자별 업무 합계”</td><td>O</td><td>O</td><td>X (안 보임)</td></tr>
<tr><td>사이드바 “전체 멤버”</td><td>O</td><td>O</td><td>X</td></tr>
<tr><td>수신함·내 업무·PC 알림</td><td>O</td><td>O</td><td>O (자기 것)</td></tr>
@@ -230,7 +230,7 @@
<tr><td>대시보드</td><td>완료·미완료·지연 숫자와 차트로 진행 상황을 볼 때. (<a href="#dashboard">14장</a>)</td></tr>
</table>
<h3>범위: 이 프로젝트 / 전체 프로젝트</h3>
<p>프로젝트 화면은 지금 프로젝트만 보여줍니다. Pro user 이상은 왼쪽 메뉴 수신함 아래 <b>전체 보기</b>를 누르면 내가 볼 수 있는 모든 프로젝트의 업무를 함께 봅니다
<p>프로젝트 화면은 지금 프로젝트만 보여줍니다. Project 옵션에서 고른 사람(처음엔 Pro user 이상)은 왼쪽 메뉴 수신함 아래 <b>전체 보기</b>를 누르면 내가 볼 수 있는 모든 프로젝트의 업무를 함께 봅니다
(왼쪽 프로젝트 목록에서 프로젝트를 누르면 다시 그 프로젝트만).
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 업무인지 이름이 붙습니다.
다른 프로젝트에서 연결돼 와 <b>읽기만 되는 업무</b>도 한 번씩 함께 보입니다.</p>
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
<link rel="stylesheet" href="/static/project.css?v=20261111a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -106,5 +106,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261030b" defer></script>
<script src="/static/project.js?v=20261111a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
<link rel="stylesheet" href="/static/project.css?v=20261111a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -100,5 +100,5 @@
"today": {{ today | tojson }}
}
</script>
<script src="/static/project.js?v=20261030b" defer></script>
<script src="/static/project.js?v=20261111a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
<link rel="stylesheet" href="/static/project.css?v=20261111a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -108,5 +108,5 @@
});
})();
</script>
<script src="/static/project.js?v=20261030b" defer></script>
<script src="/static/project.js?v=20261111a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
<link rel="stylesheet" href="/static/project.css?v=20261111a" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — self-host -->
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
<!-- 타임라인 vis-timeline — self-host -->
@@ -27,7 +27,7 @@
<div class="pj-wrap pj-project-view"
data-project-id="{{ project.id }}"
data-can-manage="{{ 'true' if can_manage else 'false' }}"
data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-all-view="{{ 'true' if pj_all_view else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}"
data-default-view="{{ pj_options.default_view if pj_options else 'board' }}"
data-board-cover="{{ '0' if pj_options and not pj_options.board_cover else '1' }}"
@@ -476,5 +476,5 @@
</script>
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
<script src="/static/project.js?v=20261030b" defer></script>
<script src="/static/project.js?v=20261111a" defer></script>
{% endblock %}
@@ -1,7 +1,7 @@
{% extends "erp_base.html" %}
{% block head_extra %}
<link rel="stylesheet" href="/static/project.css?v=20261027a" />
<link rel="stylesheet" href="/static/project.css?v=20261111a" />
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
{% endblock %}
@@ -70,5 +70,5 @@
{% include "project/_side_modals.html" %}
{% include "project/_member_tasks_modal.html" %}
<script src="/static/project.js?v=20261030b" defer></script>
<script src="/static/project.js?v=20261111a" defer></script>
{% endblock %}
+7 -2
View File
@@ -888,10 +888,15 @@
setMsg(msg, "품목 " + patches.length + "건 반영 중…", "");
return apiJson("PUT", "/cafe24/products/" + no + "/variants", { rows: patches });
});
var shopWarn = "";
chain
.then(function () { return load(); })
.then(function (data) {
var bad = Object.keys((data && data.shop_failed) || {});
if (bad.length) shopWarn = " 단, 다른 쇼핑몰(" + bad.join(", ") + "번) 진열/판매 반영 실패: " + data.shop_failed[bad[0]];
return load();
})
.then(function () {
setMsg(body.querySelector("#cf24-u-msg"), "카페24에 반영했습니다.", "is-ok");
setMsg(body.querySelector("#cf24-u-msg"), "카페24에 반영했습니다." + shopWarn, shopWarn ? "is-err" : "is-ok");
})
.catch(function (err) {
setMsg(msg, "실패: " + err.message + " — 화면을 다시 불러옵니다.", "is-err");
+63 -5
View File
@@ -7,7 +7,8 @@
"nanum-square-neo": "NanumSquareNeo", "nanum-square-round": "NanumSquareRound" };
const VIEWS = ["board", "list", "calendar", "timeline", "dashboard"];
const FONT_DEFAULT = "system";
const SYS_DEFAULTS = { default_view: "board", board_cover: true }; // 서버 store.PROJECT_OPTION_DEFAULTS 와 같게
// 서버 store.PROJECT_OPTION_DEFAULTS 와 같게 — all_view_users null = Pro user 이상(후보 목록의 pro 표시)
const SYS_DEFAULTS = { default_view: "board", board_cover: true, all_view_users: null };
const form = document.getElementById("pj-options-form");
const select = document.getElementById("pj-options-font"), preview = document.getElementById("pj-options-preview");
const error = document.getElementById("pj-options-error"), save = document.getElementById("pj-options-save");
@@ -20,6 +21,11 @@
const cover = document.getElementById("pj-options-cover");
const views = form.elements.default_view || null;
const sysControls = [cover].concat(Array.from(views || [])).filter(Boolean);
// "전체 보기" 메뉴 대상자 — 프로젝트 화면 분류(수퍼관리자·Admin 창에만)
const allPicker = document.getElementById("pj-options-allview");
const allBtn = document.getElementById("pj-options-allview-all");
const allCount = document.getElementById("pj-options-allview-count");
let users = null; // 후보(project 권한자) — 못 읽었으면 null(그때는 대상자를 저장하지 않음)
const localControls = [select, cancel, closeX, reset];
let sys = null; // 서버에서 읽은 시스템 옵션 — 못 읽었으면 null(그때는 폰트만 저장)
let openSeq = 0; // 창을 다시 열면 앞의 늦은 응답은 버린다
@@ -35,9 +41,41 @@
return data || {};
}
function currentFont() { const f = document.documentElement.dataset.pjFont; return Object.hasOwn(names, f) ? f : FONT_DEFAULT; }
// 서버 응답 → 비교용 값. 대상자는 지금 후보에 있는 사람만, 설정 전(null)이면 Pro user 이상.
function sysFrom(o) {
return { default_view: o.default_view, board_cover: !!o.board_cover, all_view_users: resolveAllView(o.all_view_users) };
}
function resolveAllView(list) {
if (!users) return null;
return users.filter(function (u) { return list ? list.indexOf(u.email.toLowerCase()) >= 0 : u.pro; })
.map(function (u) { return u.email.toLowerCase(); }).sort();
}
function allBoxes() { return allPicker ? Array.from(allPicker.querySelectorAll("input[type=checkbox]")) : []; }
function pickedAllView() { return allBoxes().filter(function (b) { return b.checked; }).map(function (b) { return b.value.toLowerCase(); }).sort(); }
function paintAllView() {
if (!allPicker) return;
const boxes = allBoxes(), on = boxes.filter(function (b) { return b.checked; }).length;
const all = boxes.length > 0 && on === boxes.length;
allBtn.textContent = all ? "전체 해제" : "전체 선택";
allCount.textContent = users ? on + "명 / " + boxes.length + "명" : "";
}
function renderAllView() {
if (!allPicker) return;
const pick = window.PJLib && window.PJLib.memberPickHtml;
allPicker.innerHTML = (users || []).map(function (u) {
return pick ? pick(u) : '<label class="pj-member-pick"><input type="checkbox" value="' + u.email.replace(/"/g, "&quot;") + '"> ' +
u.name.replace(/[&<>"]/g, function (c) { return "&#" + c.charCodeAt(0) + ";"; }) + "</label>";
}).join("");
allPicker.querySelectorAll("label").forEach(function (l, i) { l.title = users[i].email; });
}
function fillSys(o) {
if (views) views.value = o.default_view;
if (cover) cover.checked = o.board_cover;
if (allPicker && users) {
const on = Array.isArray(o.all_view_users) ? o.all_view_users : resolveAllView(null);
allBoxes().forEach(function (b) { b.checked = on.indexOf(b.value.toLowerCase()) >= 0; });
}
paintAllView();
}
function paint() {
const font = names[select.value];
@@ -57,6 +95,7 @@
save.disabled = on;
localControls.forEach(function (c) { c.disabled = on; });
sysControls.forEach(function (c) { c.disabled = on || !sys; });
allBoxes().concat(allBtn ? [allBtn] : []).forEach(function (c) { c.disabled = on || !sys || !users; });
}
function close() { if (!save.disabled) dialog.close(); }
async function loadSys() {
@@ -64,9 +103,15 @@
const seq = ++openSeq;
sys = null; busy(false); // 읽는 동안 시스템 칸은 잠금
try {
const data = await request("GET");
// 대상자 후보는 따로 — 못 읽어도 처음 여는 탭·카드 표지는 저장할 수 있게
const people = allPicker ? fetch("/project/api/assignable-users").then(function (r) {
if (!r.ok) throw new Error(r.statusText); return r.json();
}).then(function (d) { return d.users || []; }).catch(function () { return null; }) : Promise.resolve(null);
const [data, list] = await Promise.all([request("GET"), people]);
if (seq !== openSeq) return;
sys = { default_view: data.options.default_view, board_cover: !!data.options.board_cover };
users = list; renderAllView();
if (allPicker && !users) setError('"전체 보기" 대상자 후보를 불러오지 못했습니다. 대상자는 저장되지 않습니다.');
sys = sysFrom(data.options);
fillSys(sys);
} catch (err) {
if (seq !== openSeq) return;
@@ -76,7 +121,7 @@
}
button.addEventListener("click", function () {
select.value = currentFont(); fillSys(SYS_DEFAULTS); paint(); setError("");
select.value = currentFont(); users = null; renderAllView(); fillSys(SYS_DEFAULTS); paint(); setError("");
showPane(tabs[0].dataset.pane); dialog.showModal(); tabs[0].focus();
loadSys();
});
@@ -92,6 +137,14 @@
showPane(tabs[(i + (e.key === "ArrowDown" ? 1 : tabs.length - 1)) % tabs.length].dataset.pane, true);
});
select.addEventListener("change", paint);
if (allPicker) {
allPicker.addEventListener("change", paintAllView);
allBtn.addEventListener("click", function () {
const boxes = allBoxes(), all = boxes.every(function (b) { return b.checked; });
boxes.forEach(function (b) { b.checked = !all; });
paintAllView();
});
}
reset.addEventListener("click", function () {
select.value = FONT_DEFAULT; paint();
if (sys) fillSys(SYS_DEFAULTS);
@@ -109,6 +162,10 @@
if (sys) {
if (views && VIEWS.indexOf(views.value) >= 0 && views.value !== sys.default_view) sysChanges.default_view = views.value;
if (cover && cover.checked !== sys.board_cover) sysChanges.board_cover = cover.checked;
if (allPicker && users && sys.all_view_users) {
const picked = pickedAllView();
if (picked.join(",") !== sys.all_view_users.join(",")) sysChanges.all_view_users = picked;
}
}
busy(true); setError("");
try {
@@ -119,12 +176,13 @@
const changed = Object.keys(sysChanges);
if (changed.length) {
const data = await request("PUT", sysChanges);
sys = { default_view: data.options.default_view, board_cover: !!data.options.board_cover };
sys = sysFrom(data.options);
}
if (fontValue !== currentFont()) changed.push("font");
localStorage.setItem("pj_font", fontValue);
document.documentElement.dataset.pjFont = fontValue;
// project.js 가 듣는다 — 보드 표지가 바뀌면 보던 보드를 다시 그린다(다른 사용자는 다음에 화면을 열 때부터).
// "전체 보기" 메뉴 대상자는 다음에 화면을 열 때부터(왼쪽 메뉴는 서버가 그린다).
if (changed.length) {
window.dispatchEvent(new CustomEvent("pj-options-change", {
detail: { options: Object.assign({ font: fontValue }, sys || {}), changed: changed },
+5
View File
@@ -3282,6 +3282,11 @@ label.pj-options-row[for] { cursor: pointer; }
.pj-options-views label:has(input:checked) { border-color: var(--pj-accent); background: var(--pj-accent-tint); color: var(--pj-accent-dark); font-weight: 600; box-shadow: 0 0 0 1px var(--pj-accent) inset; }
.pj-options-views label:has(input:checked) .material-symbols-outlined { color: var(--pj-accent); }
.pj-options-views label:has(input:focus-visible) { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
/* 프로젝트 화면 — "전체 보기" 메뉴 대상자(아이콘+이름 체크, 멤버 배정 창과 같은 모양) */
.pj-options-allview-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; }
.pj-options-allview-all { flex: none; white-space: nowrap; }
.pj-options-allview { max-height: 220px; margin-top: 0; }
.pj-options-allview:empty::before { content: "불러오는 중…"; padding: 6px; font-size: 12px; color: var(--pj-ink-soft); }
/* 켜기/끄기 스위치 */
.pj-switch { position: relative; flex: none; display: inline-block; width: 40px; height: 22px; }
.pj-switch input { position: absolute; inset: 0; margin: 0; opacity: 0; cursor: pointer; }
+5 -4
View File
@@ -3479,6 +3479,7 @@
// 등급(2026-10-12) — isPro = Pro user 이상(프로젝트 수정·멤버 배정·전체 보기·담당자별 합계·남의 댓글 수정),
// isPAdmin = Admin 이상(남이 만든 섹션도 삭제).
const isPro = root.dataset.isPro === "true";
const canAllView = root.dataset.allView === "true"; // 왼쪽 "전체 보기" 메뉴 — Project 옵션 대상자(서버 pj_all_view)
const isPAdmin = root.dataset.isPadmin === "true";
// 시스템 Project 옵션(서버 project_options, 수퍼관리자·Admin 이 바꾸면 모든 사용자에게) — 보드 카드 표지 켬/끔.
// 옵션 창에서 저장하면 pj-options-change 로 바로 바뀐다(아래).
@@ -3653,7 +3654,7 @@
const saved = localStorage.getItem(VIEW_KEY);
const preferred = root.dataset.defaultView; // 시스템 옵션(서버가 넣어 줌)
if ((qs.has("y") || qs.has("m")) && saved && VIEWS.indexOf(saved) >= 0) currentView = saved;
else if (isPro && qs.get("scope") === "all") currentView = "dashboard";
else if (canAllView && qs.get("scope") === "all") currentView = "dashboard";
else if (qs.get("embed") !== "1" && VIEWS.indexOf(preferred) >= 0) currentView = preferred; // 업무 창 패널(iframe)은 그대로 보드
} catch (_) {}
@@ -3815,7 +3816,7 @@
});
}
if (moveScopeHighlight) moveScopeHighlight(false);
// 전체 보기(2026-10-08) — 오른쪽 위 토글 대신 왼쪽 메뉴 "전체 보기"(관리자만, ?scope=all). 토글은 숨겨 두고 상태만 쓴다.
// 전체 보기(2026-10-08) — 오른쪽 위 토글 대신 왼쪽 메뉴 "전체 보기"(Project 옵션 대상자만, ?scope=all). 토글은 숨겨 두고 상태만 쓴다.
const allViewLink = el("pj-side-allview");
function applyAllScope(on) {
viewScope = on ? "all" : "project";
@@ -3829,8 +3830,8 @@
r.classList.toggle("is-active", !on);
});
}
if (isPro && new URLSearchParams(location.search).get("scope") === "all") applyAllScope(true); // 첫 그리기 전에
if (allViewLink && isPro) {
if (canAllView && new URLSearchParams(location.search).get("scope") === "all") applyAllScope(true); // 첫 그리기 전에
if (allViewLink && canAllView) {
allViewLink.addEventListener("click", function (e) {
if (e.ctrlKey || e.metaKey || e.shiftKey || e.button === 1) return;
e.preventDefault(); // 같은 화면 안에서 바로 전환
+8
View File
@@ -482,6 +482,13 @@ cafe24_oauth_tokens 저장
`quantity`, `image`…). `PUT /admin/products/{no}/variants` body `{"shop_no":1,
"requests":[{variant_code, custom_variant_code, additional_amount, display, selling…}]}`
1회 100건(초과 시 나눠 보냄). 재고(`quantity`)는 이 화면에서 건드리지 않는다.
- **멀티쇼핑몰 진열·판매**(2026-11-10): 품목 진열·판매는 쇼핑몰(`shop_no`)마다 따로다. 화면은
기본몰(1) 값을 보여 주고, 저장하면 기본몰에 반영된 행의 **진열·판매만** `CAFE24_SHOP_NOS`
(예 `1,2,3`)의 다른 쇼핑몰에도 같은 값으로 PUT 한다. 추가금액(통화가 다름)·자체코드·순서는
기본몰만. 다른 쇼핑몰 실패는 응답 `shop_failed`·감사 기록에 남기고 화면에 경고(기본몰 반영은 유지).
쇼핑몰 목록 API(`/admin/shops`)는 `mall.read_store` 권한이 필요해 쓰지 않고 번호를 환경변수로 받는다.
기존 상품 일괄 맞춤(일회성): `docker exec dbx-main python -m app.modules.cafe24.sync_variant_flags
--shops 3,4 [--apply]` — 없으면 미리보기, 출력 `BEFORE` 줄 = 원래 값(되돌리기용), 감사 actor `SYNC_SHOPS`.
- "옵션별 상품 이름" 은 옵션값(`option_text`)이고, "옵션별 썸네일" 은 `option_image_file`
(+ `option_link_image` 에도 같은 경로) 이며,
화면의 옵션값 썸네일은 **`option_image_file` → `option_link_image` → 그 옵션값을 가진
@@ -569,6 +576,7 @@ CAFE24_REDIRECT_URI=https://dbx.no1king.freeddns.org/cafe24/oauth/callback
CAFE24_API_VERSION=2026-03-01
CAFE24_TOKEN_SECRET=<openssl rand -hex 32>
CAFE24_SHOP_URL=https://www.miras.co.kr # 선택 — 다이렉트 주소용 커스텀 도메인
CAFE24_SHOP_NOS=1,2,3 # 선택 — 품목 진열·판매를 같이 맞출 멀티쇼핑몰 번호(기본 1)
# 디자인 보관함 FTP (OAuth 와 별개 계정) — 모바일 스와이프 / PC·모바일 상품상세
CAFE24_FTP_HOST=miraskitchen.ftp.cafe24.com # 선택 — 미설정 시 {mall_id}.ftp.cafe24.com
+2 -2
View File
@@ -46,7 +46,7 @@ def board() -> dict:
def goals_ctx(admin: bool) -> dict:
return {
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "pj_pro": admin, "pj_admin": admin, "nav_projects": [], "goal_years": [2026],
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "pj_pro": admin, "pj_admin": admin, "pj_all_view": admin, "nav_projects": [], "goal_years": [2026],
"goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"],
"project_icons": ["folder"], "goals_enabled": True, "goal_year": 2026, "board": board(),
"months": list(range(1, 13)),
@@ -106,7 +106,7 @@ def meeting_view(err: bool) -> dict:
def meeting_ctx(admin: bool, err: bool, can_sync: bool = True) -> dict:
view = meeting_view(err)
ctx = {
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "pj_pro": admin, "pj_admin": admin, "nav_projects": [], "goal_years": [2026],
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "pj_pro": admin, "pj_admin": admin, "pj_all_view": admin, "nav_projects": [], "goal_years": [2026],
"goal_year_active": 2026, "my_open_total": 0, "mention_unread": 0, "color_palette": ["#4573d2"],
"project_icons": ["folder"], "goal_year": 2026, "goal_month": 9, "meetings_enabled": True,
"weeks": [{"start": "2026-09-28", "end": "2026-10-04", "n": 4, "label": "9/28~10/4", "has": True, "now": False,
+1 -1
View File
@@ -105,7 +105,7 @@ def render_inbox(env) -> None:
def render_one(env, name: str, admin: bool, sup: bool = False) -> None:
html = env.get_template("project/project.html").render(
user={"email": ME, "is_super_admin": sup}, is_admin=admin, pj_pro=admin, pj_admin=admin, can_manage=True,
user={"email": ME, "is_super_admin": sup}, is_admin=admin, pj_pro=admin, pj_admin=admin, pj_all_view=admin, can_manage=True,
project=PROJECTS[0], current_project_id=1, stages=STAGES[1], tasks=TASKS,
members=[{"user_email": ME, "role": "member"}, {"user_email": "bob@test.local", "role": "member"}],
projects_meta=PROJECTS, nav_projects=PROJECTS, stages_by_project=STAGES, board_stage_names=["할 일", "완료"],
+49
View File
@@ -492,6 +492,55 @@ def test_route_09_variants_partial_success():
assert resp.status_code == 502
def test_route_09b_display_selling_to_all_shops(monkeypatch):
monkeypatch.setenv("CAFE24_SHOP_NOS", "1,2,3")
no, cafe = _new_product()
created = _create_options(no, ["A", "B"])
a, b = (v["variant_code"] for v in created["variants"])
cafe.calls.clear()
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": [
{"variant_code": a, "display": "off", "additional_amount": "500"},
{"variant_code": b, "custom_variant_code": "X1"}]})
assert resp.status_code == 200, resp.text
assert resp.json()["shop_failed"] == {}
puts = [c[2] for c in cafe.calls if c[0] == "PUT" and c[1].endswith("/variants")]
assert [p["shop_no"] for p in puts] == [1, 2, 3]
# 다른 쇼핑몰엔 진열·판매만, 진열/판매를 안 바꾼 행(b)은 안 보낸다
assert puts[1]["requests"] == puts[2]["requests"] == [{"variant_code": a, "display": "F"}]
# 다른 쇼핑몰 실패는 경고로만(기본몰 반영은 성공)
cafe._variant_puts = 0
cafe.fail_variant_chunk = 2
resp = req("PUT", f"/cafe24/products/{no}/variants", json={"rows": [{"variant_code": a, "selling": "off"}]})
cafe.fail_variant_chunk = 0
assert resp.status_code == 200 and resp.json()["ok"]
assert list(resp.json()["shop_failed"]) == ["2"]
def test_sync_variant_flags_script(monkeypatch, capsys):
from app.integrations import cafe24 as integ
from app.integrations.cafe24 import products as cp
from app.modules.cafe24 import sync_variant_flags
no, cafe = _new_product()
created = _create_options(no, ["A", "B"])
a = created["variants"][0]["variant_code"]
before = [dict(v) for v in cafe.variants]
assert req("PUT", f"/cafe24/products/{no}/variants",
json={"rows": [{"variant_code": a, "display": "off"}]}).status_code == 200
cafe.stale_variants = before # 다른 쇼핑몰(과 지연된 GET)은 아직 진열함
monkeypatch.setenv("CAFE24_DB_URL", os.environ["CAFE24_TEST_DB_URL"])
monkeypatch.setattr(integ, "build_cafe24_api", lambda st, **kw: fakes.FakeApi(MULTI))
monkeypatch.setattr(cp, "list_all_products", lambda client: ([{"product_no": no}], False))
cafe.calls.clear()
assert sync_variant_flags.main(["--shops", "3"]) == 0
assert not [c for c in cafe.calls if c[0] == "PUT"] # 미리보기는 쓰지 않음
assert sync_variant_flags.main(["--shops", "3", "--apply"]) == 0
puts = [c[2] for c in cafe.calls if c[0] == "PUT"]
assert puts == [{"shop_no": 3, "requests": [{"variant_code": a, "display": "F"}]}]
assert "BEFORE" in capsys.readouterr().out
def test_route_10_rename_with_lagging_variants_keeps_rows():
no, cafe = _new_product()
created = _create_options(no, ["Black", "Red"])
+30 -11
View File
@@ -16,6 +16,7 @@ store = importlib.import_module("app.modules.project.store")
ADMIN = {"email": "Boss@Test.local", "role": "admin"}
USER = {"email": "me@test.local", "role": "user"}
PRO = {"email": "pro@test.local", "role": "pro"}
D = dict(store.PROJECT_OPTION_DEFAULTS)
class FakeStore:
@@ -39,22 +40,40 @@ class FakeStore:
class NormalizeTests(unittest.TestCase):
def test_defaults_when_nothing_saved(self):
self.assertEqual(store.normalize_project_options(None), {"default_view": "board", "board_cover": True})
self.assertEqual(store.normalize_project_options({}), {"default_view": "board", "board_cover": True})
self.assertEqual(store.normalize_project_options(None), D)
self.assertEqual(store.normalize_project_options({}), D)
def test_bad_or_unknown_saved_values_fall_back(self):
out = store.normalize_project_options({"default_view": "gantt", "board_cover": "no", "x": 1})
self.assertEqual(out, {"default_view": "board", "board_cover": True})
self.assertEqual(out, D)
def test_saved_values_used(self):
out = store.normalize_project_options({"default_view": "timeline", "board_cover": False})
self.assertEqual(out, {"default_view": "timeline", "board_cover": False})
self.assertEqual(out, dict(D, default_view="timeline", board_cover=False))
def test_all_view_users_normalized(self):
out = store.normalize_project_options({"all_view_users": ["B@x.kr", "a@x.kr", "b@x.kr"]})
self.assertEqual(out["all_view_users"], ["a@x.kr", "b@x.kr"])
self.assertEqual(store.normalize_project_options({"all_view_users": []})["all_view_users"], [])
self.assertIsNone(store.normalize_project_options({"all_view_users": "x"})["all_view_users"])
self.assertEqual(store.validate_project_options({"all_view_users": ["Me@X.kr"]}), {"all_view_users": ["me@x.kr"]})
self.assertEqual(store.validate_project_options({"all_view_users": None}), {"all_view_users": None})
def test_can_all_view(self):
access = importlib.import_module("app.modules.project.access")
self.assertTrue(access.can_all_view(PRO, None)) # 설정 전 = Pro user 이상(예전 그대로)
self.assertFalse(access.can_all_view(USER, None))
self.assertTrue(access.can_all_view(USER, ["me@test.local"]))
self.assertFalse(access.can_all_view(ADMIN, ["me@test.local"]))
self.assertTrue(access.can_all_view(ADMIN, ["boss@test.local"])) # 대소문자 무시
self.assertFalse(access.can_all_view(ADMIN, []))
def test_validate_keeps_only_sent_keys(self):
self.assertEqual(store.validate_project_options({"board_cover": False}), {"board_cover": False})
def test_validate_rejects(self):
for bad in ({}, None, [], {"default_view": "gantt"}, {"board_cover": 0}, {"board_cover": "false"}, {"font": "x"}):
for bad in ({}, None, [], {"default_view": "gantt"}, {"board_cover": 0}, {"board_cover": "false"}, {"font": "x"},
{"all_view_users": "a@x.kr"}, {"all_view_users": ["noemail"]}, {"all_view_users": [1]}):
with self.subTest(bad=bad), self.assertRaises(ValueError):
store.validate_project_options(bad)
@@ -73,7 +92,7 @@ class OptionsApiTests(unittest.TestCase):
def test_anyone_with_module_reads_with_can_edit_flag(self):
st = FakeStore({"default_view": "list"})
out = self.call("GET", USER, st).json()
self.assertEqual(out, {"options": {"default_view": "list", "board_cover": True}, "can_edit": False})
self.assertEqual(out, {"options": dict(D, default_view="list"), "can_edit": False})
self.assertTrue(self.call("GET", ADMIN, st).json()["can_edit"])
def test_admin_saves_only_sent_keys(self):
@@ -81,7 +100,7 @@ class OptionsApiTests(unittest.TestCase):
res = self.call("PUT", ADMIN, st, {"board_cover": False})
self.assertEqual(res.status_code, 200)
self.assertEqual(st.writes, [({"board_cover": False}, "Boss@Test.local")])
self.assertEqual(res.json()["options"], {"default_view": "calendar", "board_cover": False})
self.assertEqual(res.json()["options"], dict(D, default_view="calendar", board_cover=False))
def test_user_and_pro_cannot_save(self):
for who in (USER, PRO):
@@ -92,21 +111,21 @@ class OptionsApiTests(unittest.TestCase):
def test_invalid_payload_400_without_write(self):
st = FakeStore()
for body in ({"default_view": "gantt"}, {"board_cover": "yes"}, {}, {"font": "pretendard"}):
for body in ({"default_view": "gantt"}, {"board_cover": "yes"}, {}, {"font": "pretendard"}, {"all_view_users": ["x"]}):
with self.subTest(body=body):
self.assertEqual(self.call("PUT", ADMIN, st, body).status_code, 400)
self.assertEqual(st.writes, [])
def test_migration_missing_read_defaults_write_503(self):
st = FakeStore(missing=True)
self.assertEqual(self.call("GET", USER, st).json()["options"], {"default_view": "board", "board_cover": True})
self.assertEqual(self.call("GET", USER, st).json()["options"], D)
res = self.call("PUT", ADMIN, st, {"board_cover": False})
self.assertEqual(res.status_code, 503)
self.assertIn("029", res.json()["detail"])
def test_page_reader_never_fails(self):
self.assertEqual(api._project_options(None), {"default_view": "board", "board_cover": True})
self.assertEqual(api._project_options(FakeStore(broken=True)), {"default_view": "board", "board_cover": True})
self.assertEqual(api._project_options(None), D)
self.assertEqual(api._project_options(FakeStore(broken=True)), D)
if __name__ == "__main__":
+4 -3
View File
@@ -72,9 +72,10 @@ class RoleHelperTests(unittest.TestCase):
self.assertFalse(api._can_delete(USER, None))
def test_role_ctx(self):
self.assertEqual(api._role_ctx(PRO), {"is_admin": False, "pj_pro": True, "pj_admin": False})
self.assertEqual(api._role_ctx(ADMIN), {"is_admin": True, "pj_pro": True, "pj_admin": True})
self.assertEqual(api._role_ctx(USER), {"is_admin": False, "pj_pro": False, "pj_admin": False})
# pj_all_view — 옵션(전체 보기 대상자) 설정 전이면 Pro user 이상(request 없음 = 기본값)
self.assertEqual(api._role_ctx(PRO), {"is_admin": False, "pj_pro": True, "pj_admin": False, "pj_all_view": True})
self.assertEqual(api._role_ctx(ADMIN), {"is_admin": True, "pj_pro": True, "pj_admin": True, "pj_all_view": True})
self.assertEqual(api._role_ctx(USER), {"is_admin": False, "pj_pro": False, "pj_admin": False, "pj_all_view": False})
class UserStoreRoleTests(unittest.TestCase):