33 Commits

Author SHA1 Message Date
king e9f57b6ff6 Merge branch 'fix/cafe24-variant-toggle-center' 2026-11-17 10:36:24 +09:00
king 262ae7fdf8 fix(카페24): 옵션/품목 팝업 토글 버튼 가운데 정렬
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:36:24 +09:00
king 083eebfd95 Merge branch 'feat/cafe24-variant-th-center' 2026-11-17 10:29:58 +09:00
king 0f4608cb43 style(카페24): 옵션/품목 팝업 표 헤더 굵게·가운데 정렬
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:29:57 +09:00
king 8e5a682f0d Merge branch 'feat/cafe24-variant-inventory' 2026-11-17 10:08:54 +09:00
king b0e816cbdc feat(카페24): 옵션/품목 팝업에 재고관리·재고 수량·품절표시 설정
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 10:07:53 +09:00
king c39139a605 Merge branch 'feat/performance-yoy-kakao-pf' 2026-11-16 11:34:57 +09:00
king 91fd454b2c feat(실적): 매출 KPI 전년 같은 기간 대비 · 광고비 카톡 플친 열
- 매출 실적 KPI 줄에 전월 대비 옆 "전년 같은 기간 대비" % (연 보기 제외)
- 광고비 탭 카톡 플친(kakao_pf) 열 — 직접 입력, ROAS 없음
- 매출 탭 카페24 칸 광고비 줄에 구글·메타 다음 카톡 플친

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 11:34:56 +09:00
king 78d2e665ee Merge branch 'chore/malaysia-add-my1007' 2026-11-15 03:29:50 +09:00
king 4af44f2f7a chore(말레이시아재고): 신규 세트 MY-1007 malaysia_items 등록 SQL
BOM·구성 낱개는 이미 등록돼 있고 malaysia_items 에만 MY-1007 이 빠져
재고 화면 세트 목록에 안 보이던 것을 채운다. 이름은 itemcode_db 에서 psql 변수로 받는다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 03:29:48 +09:00
king 60d5ca417d Merge branch 'feat/cafe24-keep-variant-price' 2026-11-15 03:15:32 +09:00
king 2465874198 feat(카페24): 판매가 변경 시 품목 판매 가격 유지 — 추가금액 자동 조정
기본 정보에서 판매가를 바꾸면 같은 잠금 안에서 옵션 품목 추가금액을
(옛 판매가 - 새 판매가)만큼 옮겨 품목 판매 가격(판매가+추가금액)을 그대로 둔다.
품목 조정 실패는 판매가 저장을 되돌리지 않고 화면 메시지로 알린다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 03:15:26 +09:00
king f982a5fa9c Merge branch 'feat/project-timepicker-all' 2026-11-11 15:22:01 +09:00
king aa701ed611 feat(프로젝트): 시각 고르기를 공용 시각 팝업으로 — 옵션 알림 시각·긴급 공지 띄울 시각
- project.js openTimePopover·enhanceTimeInput(PJLib): 날짜 팝업 모양, 시 00~23·분 5분 단위, 끝에서 멈춤
- 모달 dialog 안이면 그 창 안 popover, 아니면 body

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:22:00 +09:00
king 8bcf9b4b20 Merge branch 'feat/project-daily-on-create' 2026-11-11 15:03:14 +09:00
king dd648d4752 feat(프로젝트): 메인 업무·세부 업무 추가 칸 날짜 팝업에도 [매일]
- POST tasks 의 repeat_daily: true = 만든 뒤 켬(033 미적용 503), 화면은 data-daily-ready(db.daily_ready)일 때만 버튼

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:03:12 +09:00
king 37df7be461 Merge branch 'fix/project-timepop-inert' 2026-11-11 14:50:56 +09:00
king 6e69abcfa3 fix(프로젝트): 옵션 시각 팝업 휠·마우스 오버·클릭 안 먹던 문제 — 모달 창 안에 붙임, 지우기·확인 동작·색
모달 dialog 가 열려 있으면 창 밖(body) 요소는 inert 라 popover 를 body 에 붙이면 마우스가 통과했다.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:50:55 +09:00
king 0e6bb53c9c Merge branch 'feat/project-options-timepicker' 2026-11-11 14:46:54 +09:00
king 117f40c96f feat(프로젝트): Project 옵션 알림 시각 고르기를 날짜 팝업 모양으로 — 시 00~23·분 5분 단위, 끝에서 멈춤
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:46:53 +09:00
king ec0eb0a295 Merge branch 'feat/project-daily-tasks' 2026-11-11 14:36:00 +09:00
king 7f94e5efe7 feat(프로젝트): 매일 하는 업무 — 날짜 팝업 [매일]·반복 아이콘·시각별 알림
- 마이그레이션 033 tasks.repeat_daily — [매일]이면 마감일·시각 비움, 마감일을 고르면 꺼짐(미적용이면 버튼 숨김·PUT 503)
- 마감 칸(카드·목록·내 업무·세부 업무·업무 창)에 반복 아이콘 + "매일"
- reminders.run_daily_alerts: 영업일, Project 옵션 daily_alert_times 중 지난 가장 늦은 시각마다 담당자(없으면 협업자)에게 type=daily 알림(task_reminders 로 중복 방지, 데몬 1분 주기)
- 큰 알림 팝업·PC 알림 프로그램에서 매일 업무 줄은 노란 배경
- Project 옵션 "알림" 분류: 알림 시각 여러 개 추가·삭제(최대 12)
- 도움말·모듈 CLAUDE.md·DEPLOYMENT(033) 갱신, 테스트 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 14:35:59 +09:00
king 3045bc6f99 Merge branch 'feat/project-options-size' 2026-11-11 10:32:40 +09:00
king 1678f00c1b feat(프로젝트): Project 옵션 창 크기 800×750 고정
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 10:32:39 +09:00
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
king 282ee559e0 feat(카페24): 옵션 팝업 이름·코드·추가금액 칸에도 키 이동 적용
- 옵션값 이름, 자체 품목코드, 추가금액 칸에서 Enter/아래 화살표는 아래 행, 위 화살표는 위 행으로 이동
- 한글 조합 중에는 이동하지 않음

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-10 01:03:55 +09:00
king 1096fd68ab Merge branch 'feat/cafe24-option-sale-price' 2026-11-10 00:59:45 +09:00
55 changed files with 1360 additions and 191 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
+5 -1
View File
@@ -12,9 +12,13 @@
- 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`). 저장되는 값은 추가금액뿐. Enter·↓ 아래 행, ↑ 위 행으로 이동.
- 옵션/품목 팝업 「판매 가격」 열: 기본 정보 판매가 + 추가금액을 보여주고, 입력하면 추가금액을 역산(`cafe24-options.js` `bindSalePrice`). 저장되는 값은 추가금액뿐.
- 기본 정보에서 판매가를 바꾸면 같은 잠금 안에서 품목 추가금액을 (옛 판매가 − 새 판매가)만큼 옮겨 품목 판매 가격을 유지(`_keep_variant_sale_prices`, `store.shift_additional_amounts`). 공급가·소비자가는 품목과 무관. 판매가는 이미 반영됐으므로 품목 조정 실패는 화면 메시지(`variants_error`)로만.
- 옵션/품목 팝업 「재고관리」(use_inventory)·「재고」(quantity)·「품절표시」(display_soldout) 열: 같은 PUT variants 로 기본몰에만 보냄(재고는 쇼핑몰 공통).
- 옵션/품목 팝업 옵션값 이름·자체 품목코드·추가금액·판매 가격·재고 칸: Enter·↓ 아래 행, ↑ 위 행 같은 열로 이동(한글 조합 중에는 이동 안 함).
- 옵션/품목 팝업(단일 옵션 화면) 「모바일 스와이프 복사(코드)」: `// 상품명` + `"품목코드": "/web/…썸네일 경로",` 줄들을 클립보드로
(`cafe24-options.js` `swipeCode` — 행에 지금 보이는 썸네일 기준, 도메인/CDN 은 떼고 `/web/` 부터).
「모바일 스와이프 복사(이름)」은 키가 품목코드 대신 옵션값 이름(`swipeCode(tbody, true)`, 품목코드 있는 행만).
+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
+59 -4
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")
@@ -145,12 +145,46 @@ def product_basic(
raise _http_from_cafe24(exc) from exc
remember_write(st, product_no, updated if isinstance(updated, dict) else {})
shifted = (_keep_variant_sale_prices(st, api, product_no, before["price"], changes["price"])
if "price" in changes else {})
merged = {**current, **(updated if isinstance(updated, dict) else {}), **changes}
detail = ", ".join(f"{k}: '{before[k]}' → '{v}'" for k, v in changes.items())
if shifted.get("detail"):
detail += f" / 품목 추가금액 조정: {shifted['detail']}"
writes.audit_safe(st, actor=actor, action="update_basic", product_no=product_no,
result="SUCCESS", detail=detail)
logger.info("카페24 상품 %s 기본정보 변경 (%s): %s", product_no, actor, detail)
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged)}
return {"ok": True, "changed": list(changes.keys()), "product": _scalar_view(merged),
"variants_shifted": shifted.get("count", 0), "variants_error": shifted.get("error", "")}
def _keep_variant_sale_prices(st: Any, api: Any, product_no: int, old_price: str, new_price: str) -> dict[str, Any]:
"""판매가가 바뀐 뒤 품목 판매 가격(판매가 + 추가금액)이 그대로이도록 추가금액을 옮긴다.
판매가는 이미 반영됐으므로 실패해도 예외를 올리지 않고 {"error": …} 로 알린다.
반환 {"count": 반영된 품목 수, "error": 사유, "detail": 감사 로그용}.
"""
try:
variants = _load_options_and_variants(st, api, product_no)["effective_variants"]
requests = store.build_variant_updates(store.shift_additional_amounts(variants, old_price, new_price))
except (Cafe24Error, ValueError) as exc:
logger.warning("카페24 상품 %s 품목 추가금액 조정 준비 실패: %s", product_no, exc)
return {"error": f"품목 추가금액 조정 실패: {exc}", "detail": f"실패 {exc}"}
if not requests:
return {}
results = products.update_variants(api.client, product_no, requests)
sent = {r["variant_code"]: r["additional_amount"] for r in requests}
ok = {r["variant_code"]: sent[r["variant_code"]] for r in results if r["status"] == products.VARIANT_OK}
bad = [r for r in results if r["status"] != products.VARIANT_OK]
if ok:
_save_snapshot_safe(st, product_no, "variants", {c: {"additional_amount": a} for c, a in ok.items()})
detail = "; ".join(f"{c}={a}" for c, a in ok.items())
error = ""
if bad:
error = f"품목 {len(bad)}건 추가금액 조정 실패 — {bad[0]['error']} (옵션/품목 창에서 확인하세요)"
detail += f" / 실패 {len(bad)}건: {bad[0]['error']}"
logger.warning("카페24 상품 %s 품목 추가금액 조정 %s건 실패: %s", product_no, len(bad), bad[0]["error"])
return {"count": len(ok), "error": error, "detail": detail}
# ════════════════════════════════════════════════════════════
@@ -223,6 +257,7 @@ def _variant_view(v: dict[str, Any]) -> dict[str, Any]:
"selling": products._flag(v.get("selling")), # noqa: SLF001
"quantity": v.get("quantity"),
"use_inventory": products._flag(v.get("use_inventory"), default=False), # noqa: SLF001
"display_soldout": products._flag(v.get("display_soldout"), default=False), # noqa: SLF001
"image": str(v.get("image") or ""),
}
@@ -630,12 +665,13 @@ def variants_update(
product_no: int,
payload: dict[str, Any] = Body(default_factory=dict),
) -> dict[str, Any]:
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매를 한 번에 바꾼다 — **행별 결과**.
"""품목 여러 건의 자체코드 · 추가금액 · 진열 · 판매 · 재고(사용·수량·품절표시)를 한 번에 바꾼다 — **행별 결과**.
응답 {"ok": 전부 성공?, "partial": 일부만?, "updated": {code: 반영된 값},
"failed": {code: 사유}, "unknown": {code: 사유}}
100건 묶음 중 일부가 실패해도 성공한 행은 성공으로 기록·표시한다(화면이 그 행을
다시 보내지 않게). 하나도 반영되지 않았으면 502.
진열·판매는 `CAFE24_SHOP_NOS` 의 다른 쇼핑몰에도 같은 값으로 보낸다 — 실패는 "shop_failed".
"""
st, user = require_store(request)
actor = str(user.get("email") or "")
@@ -662,7 +698,8 @@ def variants_update(
code = result["variant_code"]
if result["status"] == products.VARIANT_OK:
patch = dict(sent.get(code) or {})
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order"):
for key in ("custom_variant_code", "additional_amount", "display", "selling", "display_order",
"use_inventory", "display_soldout", "quantity"):
value = (result.get("variant") or {}).get(key)
if value is not None:
patch[key] = value
@@ -673,9 +710,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 +750,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,
}
+36 -1
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())
@@ -1062,6 +1071,24 @@ def parse_additional_amount(value: object) -> str | None:
return f"{number}.00"
def shift_additional_amounts(variants: list[dict], old_price: object, new_price: object) -> list[dict]:
"""판매가 old → new 일 때 품목 판매 가격(판매가 + 추가금액)이 그대로이도록 추가금액을 옮긴 행들.
build_variant_updates 에 그대로 넣는 화면 행 모양. 판매가가 같거나 숫자가 아니면 [].
"""
try:
delta = int(round(float(old_price))) - int(round(float(new_price))) # type: ignore[arg-type]
except (TypeError, ValueError):
return []
if not delta:
return []
return [
{"variant_code": str(v["variant_code"]),
"additional_amount": str(int(round(float(v.get("additional_amount") or 0))) + delta)}
for v in variants if v.get("variant_code")
]
def build_variant_updates(rows: list[dict]) -> list[dict]:
"""화면 행 목록 → PUT /variants `requests` 배열. 바뀔 것이 없는 행은 뺀다."""
out: list[dict] = []
@@ -1079,9 +1106,17 @@ def build_variant_updates(rows: list[dict]) -> list[dict]:
amount = parse_additional_amount(row["additional_amount"])
if amount is not None:
item["additional_amount"] = amount
for flag in ("display", "selling"):
for flag in ("display", "selling", "use_inventory", "display_soldout"):
if row.get(flag) is not None:
item[flag] = "T" if parse_tristate(row[flag]) else "F"
if row.get("quantity") is not None and str(row["quantity"]).strip() != "":
try:
qty = int(str(row["quantity"]).strip().replace(",", ""))
except ValueError:
raise ValueError("재고 수량은 숫자여야 합니다.") from None
if not 0 <= qty <= ADDITIONAL_AMOUNT_MAX:
raise ValueError("재고 수량은 0 이상이어야 합니다.")
item["quantity"] = qty
# 진열 순서(1~300) — 카페24 문서: 조합형 옵션 품목에만. 화면의 드래그 정렬이 보낸다.
if row.get("display_order") is not None:
try:
+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=20261110a"></script>
<script src="/static/cafe24-options.js?v=20261110c"></script>
<script>
(function () {
var pane = document.getElementById("cf24-editor-pane");
@@ -929,6 +929,7 @@
window.erpAlert("상품명은 비울 수 없습니다.");
return;
}
if ("price" in payload) lines.push("\n※ 옵션 품목은 판매 가격이 그대로이도록 추가금액을 함께 조정합니다.");
window.erpConfirm("다음 항목을 카페24에 바로 반영합니다. 계속할까요?\n\n" + lines.join("\n"))
.then(function (ok) {
if (!ok) return;
@@ -943,7 +944,10 @@
form.querySelector('[name="retail_price"]').value = p.retail_price ? String(parseInt(p.retail_price, 10)) : "";
commitValues(form);
if (p.product_name) paintTitle(p.product_name);
setMsg(msg, (data.changed && data.changed.length) ? "카페24에 반영했습니다." : "변경된 값이 없어 보내지 않았습니다.", "is-ok");
var done = (data.changed && data.changed.length) ? "카페24에 반영했습니다." : "변경된 값이 없어 보내지 않았습니다.";
if (data.variants_shifted) done += " 품목 " + data.variants_shifted + "건 추가금액 조정.";
if (data.variants_error) setMsg(msg, done + " " + data.variants_error, "is-err");
else setMsg(msg, done, "is-ok");
})
.catch(function (err) { setMsg(msg, "실패: " + err.message, "is-err"); })
.then(function () { btn.disabled = false; });
+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:
+60
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
@@ -1288,6 +1304,38 @@ def test_delete_variant_wrapper():
assert client.calls[-1][:2] == ("DELETE", "/admin/products/7/variants/P000000R000A")
def test_shift_additional_amounts_keeps_sale_price():
"""판매가 7900 → 12700: 품목 판매 가격(판매가+추가금액)은 그대로, 추가금액만 -4800."""
variants = [{"variant_code": "P000000R000A", "additional_amount": "0.00"},
{"variant_code": "P000000R000B", "additional_amount": "18000.00"}]
assert store.shift_additional_amounts(variants, "7900.00", "12700.00") == [
{"variant_code": "P000000R000A", "additional_amount": "-4800"},
{"variant_code": "P000000R000B", "additional_amount": "13200"},
]
assert store.shift_additional_amounts(variants, "7900.00", "7900") == []
assert store.shift_additional_amounts(variants, "", "7900") == []
def test_keep_variant_sale_prices_puts_shifted_amounts():
from types import SimpleNamespace
from app.modules.cafe24 import routes_product_info as rpi
client = _RouteClient({
"GET /admin/products/7/options": {"option": {"has_option": "T", "options": []}},
"GET /admin/products/7/variants": {"variants": [
{"variant_code": "P000000R000A", "additional_amount": "6000.00"}]},
"PUT /admin/products/7/variants": {"variants": [
{"variant_code": "P000000R000A", "additional_amount": "1000.00"}]},
})
st = fakes.MemoryStore()
out = rpi._keep_variant_sale_prices(st, SimpleNamespace(client=client), 7, "7900.00", "12900.00")
assert out["count"] == 1 and out["error"] == ""
put = [c for c in client.calls if c[0] == "PUT"][-1]
assert put[2]["requests"] == [{"variant_code": "P000000R000A", "additional_amount": "1000.00"}]
assert st.get_write_snapshot(7)["variants"]["data"]["P000000R000A"]["additional_amount"] == "1000.00"
def test_build_variant_updates():
rows = [
{"variant_code": "p000000r000a", "custom_variant_code": " ABC ", "additional_amount": "1,000", "display": "on"},
@@ -1305,6 +1353,18 @@ def test_build_variant_updates():
pass
else:
raise AssertionError("bad code accepted")
# 재고관리 사용 · 수량 · 품절표시
assert store.build_variant_updates([
{"variant_code": "P000000R000A", "use_inventory": "on", "quantity": "1,200", "display_soldout": "off"},
{"variant_code": "P000000R000B", "quantity": ""}, # 빈 수량 → 변경 없음
]) == [{"variant_code": "P000000R000A", "use_inventory": "T", "display_soldout": "F", "quantity": 1200}]
for bad in ("-1", "x"):
try:
store.build_variant_updates([{"variant_code": "P000000R000A", "quantity": bad}])
except ValueError:
pass
else:
raise AssertionError(bad)
# 드래그 정렬 → display_order (1~300)
assert store.build_variant_updates([{"variant_code": "P000000R000A", "display_order": "3"}]) == [
{"variant_code": "P000000R000A", "display_order": 3}
@@ -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=20261111f" />
<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=20261111d" 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=20261111f" />
<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/erp-notice-admin.js?v=20261012b" defer></script>
<script src="/static/project.js?v=20261111d" defer></script>
<script src="/static/erp-notice-admin.js?v=20261111a" defer></script>
{% endif %}
{% endblock %}
+3 -2
View File
@@ -79,7 +79,7 @@
## 매출 실적 화면 (2026-10-19)
- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 %, 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다.
- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 % + **전년 같은 기간 대비 %**(2026-11-16, `calc.Period.yoy_range` — 1년 전 같은 날짜, 진행 중이면 오늘까지, 연 보기는 직전 비교가 이미 전년이라 없음), 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다.
- 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀).
- 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx(store, kind)` — 매출 탭 = 매출 일정, 광고비 탭 = 광고비 일정 → `performance.js initNextUpdate`·`nextScheduleSlot`, `auto_sync.next_slot` 과 같은 규칙으로 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트(env·그 종류 일정) 꺼지면 숨김).
- **화면 자동 새로 고침**(2026-10-26) — 자동 업데이트(다른 사람이 누른 업데이트 포함)가 끝나면 매출 실적·광고비 화면이 20초 안에 reload.
@@ -87,7 +87,7 @@
(`jobs.last_finished` — 메모리 작업만, DB 안 읽음). 도는 중이면 끝날 때까지, 칸 입력·창(`.perf-modal`)·메뉴·확인 창이 열려 있으면 닫힐 때까지 기다림
(마지막 업데이트 옆 안내), 탭이 안 보이면 안 묻고 다시 보이면 바로. 보는 사람이 직접 누른 업데이트는 진행 창이 새로 그린다. `performance.js initUpdateWatch`.
- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = **일 합계 금액 ÷ 일 합계 광고비**(2026-10-19 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다; `roas` 총매출·`roas_net` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음.
- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타·카톡 플친 줄(이름 붙임, 카페24(전체)·카페24(실적) 같은 줄), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = **일 합계 금액 ÷ 일 합계 광고비**(2026-10-19 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다; `roas` 총매출·`roas_net` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음.
- **열 접기**(2026-11-06) — 매출 실적·광고비 일자별 표 머리글 위 작은 화살표 버튼(`.perf-cfold`, `performance.js initColFold`)으로 열 하나씩 접기/펴기(날짜 열 빼고, 일 합계·그룹 열 포함).
접은 열 = 26px 띠(`is-cfold`, 칸 내용 숨김·클릭/메모 안 됨, 너비는 JS `CFOLD_W` 와 CSS 같게, 수동 열 너비 표도 같음). **로그인한 사람 본인에게만** —
`PUT /api/my-col-fold {kind: sales|ads, cols}` → `perf_settings` key `col_fold:<이메일 sha1>`(key 64자 제한) = `{sales, ads}`, 화면은 표 `data-col-fold`(라우터 `_load_col_fold`). 011 미적용이면 다 펼침·저장 503.
@@ -124,6 +124,7 @@
- 탭은 [매출 실적]·[광고비]·[틱톡] + 맨 오른쪽 설정 톱니.
- **표 모양(2026-10-22)** — 매출 실적 표와 같은 `perf-autofit`(열 너비 = 내용 길이, 날짜 열 가로 스크롤 고정).
- **기타광고비** 열(`etc`, 애터미아자몰 오른쪽, 2026-10-22) — 쇼핑몰에 딸리지 않은 광고비 직접 입력. 매출 쇼핑몰이 없어(`ad_spend.NO_SALES`) ROAS 없음·매출 탭 광고비 줄에 안 나옴, 광고비 합계·매출 대비 광고비에는 들어감.
- **카톡 플친** 열(`kakao_pf`, 메타 오른쪽, 2026-11-16) — 직접 입력, `NO_SALES` 라 ROAS 없음. 매출 탭 카페24 칸 아래 구글·메타 다음 줄, 일 합계 광고비에도 더함.
- `ad_spend.py`, 마이그레이션 005 `perf_ad_spend`. 구글·메타·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰 일 광고비를 연·월·일로.
- 칸 = "광고비(ROAS%)"(ROAS = 그 쇼핑몰 매출 ÷ 광고비). 구글·메타·네이버는 계산 안 함 — 광고 보고서 ROAS(마이그레이션 006 `roas`·`metrics`).
- 날짜 칸 직접 입력 + 쿠팡(윙)·쿠팡(로켓)·네이버 광고 보고서 업로드.
+2 -1
View File
@@ -35,6 +35,7 @@ from .manual_upload import MAX_AMOUNT, MAX_DATA_ROWS, MAX_ERRORS, MAX_FILE_BYTES
CHANNELS: tuple[tuple[str, str], ...] = (
("google", "구글"),
("meta", "메타"),
("kakao_pf", "카톡 플친"), # 2026-11-16 — 카카오톡 플러스친구(자사몰 광고, 직접 입력), ROAS 없음, 매출 탭 카페24 줄에 구글·메타 아래
("naver", "네이버"),
("coupang_wing", "쿠팡(윙)"),
("coupang_rocket", "쿠팡(로켓)"),
@@ -55,7 +56,7 @@ CHANNEL_CODES = tuple(c for c, _ in CHANNELS)
# 여러 날(주·월·합계)의 ROAS = Σ(그날 ROAS × 그날 광고비) ÷ Σ광고비(ROAS 가 있는 날만) = 광고 매출 합 ÷ 광고비 합.
FILE_ROAS = frozenset({"google", "meta", "naver"})
NO_ROAS = FILE_ROAS # 예전 이름(계산 안 하는 채널)
NO_SALES = frozenset({"etc"}) # 매출 쇼핑몰이 없는 채널 — ROAS 를 계산하지 않고 매출 탭 광고비 줄에도 안 나온다
NO_SALES = frozenset({"etc", "kakao_pf"}) # ROAS 를 계산하지 않는 채널 — 매출 탭 광고비 줄은 sales_ad_channels 에 적은 것만(카톡 플친 = 카페24)
ROAS_SALES_CODE: dict[str, str] = {c: c for c in CHANNEL_CODES if c not in FILE_ROAS and c not in NO_SALES}
ROAS_SALES_CODE["coupang_wing"] = "coupang"
TIKTOK = "tiktok" # 광고 API 채널이지만 CHANNELS 에 없다 — 틱톡 탭(build_tiktok_dashboard)에서만 보인다
+11
View File
@@ -156,6 +156,17 @@ class Period:
unit = {"day": "전일", "week": "전주", "month": "전월", "year": "전년"}.get(self.kind, "직전 기간")
return prev_start, prev_end, f"{unit} {note}".strip()
def yoy_range(self, today: date) -> tuple[date, date, str]:
"""1년 전 같은 날짜 범위(2026-11-16 매출 KPI 전년 대비). 진행 중인 기간이면 오늘까지만. 2/29 → 2/28."""
def back(d: date) -> date:
try:
return d.replace(year=d.year - 1)
except ValueError:
return d.replace(year=d.year - 1, day=28)
end = today if self.start <= today < self.end else self.end
return back(self.start), back(end), "전년 같은 기간"
def resolve_period(
kind: str,
+9 -4
View File
@@ -161,7 +161,7 @@ def amount_text(value: Any, unit: str = "won") -> str:
def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cells: Mapping[Any, Any],
period: Any, q_start: date, q_end: date) -> None:
"""매출 칸 아래 광고비(ROAS%) — 광고비 화면과 같은 값(ROAS = 그 쇼핑몰 매출 ÷ 광고비, 구글·메타·네이버는 보고서 ROAS).
카페24 = 구글·메타 두 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합.
카페24 = 구글·메타·카톡 플친 줄. 행마다 r["ads"][쇼핑몰] = [{label, amount, roas}], r["ads_total"] = 보이는 쇼핑몰 광고비 합.
일 합계 ROAS 는 단순하게 일 합계 금액 ÷ 일 합계 광고비(2026-10-19) — roas = 총매출 기준, roas_net = 수수료 차감 매출 기준
(화면 표시 기준에 따라 하나만 보인다). 예전엔 광고비가 있는 쇼핑몰 매출만 더해 일 합계 금액과 맞지 않았다.
광고비 표(005)가 없거나 읽기 실패면 줄 없음."""
@@ -217,11 +217,11 @@ def _ad_lines(store: Any, table: list[dict[str, Any]], codes: Sequence[str], cel
def sales_ad_channels() -> dict[str, tuple[tuple[str, str], ...]]:
"""쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타(자사몰 광고), 네이버 = 네이버 광고,
"""쇼핑몰(매출 코드) → 그 아래 보일 광고 채널 [(채널, 줄 이름)]. 카페24 = 구글·메타·카톡 플친(자사몰 광고), 네이버 = 네이버 광고,
나머지는 광고비 화면의 ROAS 매출 쇼핑몰(쿠팡(윙) 광고 → 쿠팡 매출)."""
from . import ad_spend # noqa: WPS433
out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타")), "naver": (("naver", ""),)}
out: dict[str, tuple[tuple[str, str], ...]] = {"cafe24": (("google", "구글"), ("meta", "메타"), ("kakao_pf", "카톡 플친")), "naver": (("naver", ""),)}
for ch, c in ad_spend.ROAS_SALES_CODE.items():
out[c] = out.get(c, ()) + ((ch, ""),)
return out
@@ -261,7 +261,10 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
m_cmp_start, m_cmp_end, m_cmp_label = month_period.compare_range(today)
y_cmp_start, y_cmp_end, y_cmp_label = year_period.compare_range(today)
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
# 전년 같은 기간 대비(2026-11-16) — 연 보기는 직전 비교가 이미 전년이라 뺀다
yoy = period.yoy_range(today) if period.kind != "year" else None
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start, *(yoy[:1] if yoy else ()))
q_end = max(period.end, year_period.end)
gb = groupbuy_code(markets)
# 공동구매를 필터로 뺐어도 카페24(실적) 계산엔 필요 — 합계·그래프는 아래에서 codes 만 더한다
@@ -292,6 +295,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
{"key": "net", "label": f"{period_word} 수수료 차감 매출", "value": cur.net, "primary": True,
"delta": calc.pct_change(cur.net, prev.net), "cmp": cmp_label},
]
if yoy:
kpis[0].update(yoy_delta=calc.pct_change(cur.net, calc.sum_range(summary, codes, yoy[0], yoy[1]).net), yoy_cmp=yoy[2])
share = calc.by_code(summary, codes, period.start, period.end)
# 비중 그래프·월 누적 표의 카페24 줄 = 카페24(실적) — 줄을 더하면 합계와 같다
@@ -111,6 +111,14 @@
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
<span class="perf-muted">{{ k.cmp }} 대비</span>
{% endif %}
{% if k.yoy_cmp %}
{% if k.yoy_delta is none %}<span class="perf-muted">{{ k.yoy_cmp }} 비교 없음</span>
{% else %}
<span class="perf-delta {% if k.yoy_delta == 0 %}is-flat{% elif k.yoy_delta > 0 %}is-up{% else %}is-down{% endif %}">
{% if k.yoy_delta > 0 %}▲{% elif k.yoy_delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.yoy_delta | abs) }}%</span>
<span class="perf-muted">{{ k.yoy_cmp }} 대비</span>
{% endif %}
{% endif %}
</div>
{% endfor %}
@@ -120,7 +120,7 @@ class _Store:
def test_ad_dashboard_month():
ctx = ads.build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7),
sales_codes=["cafe24"])
assert ctx["codes"] == ["google", "meta", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao",
assert ctx["codes"] == ["google", "meta", "kakao_pf", "naver", "coupang_wing", "coupang_rocket", "ohouse", "gmarket", "kakao",
"gsshop", "elevenst", "lotteon", "toss", "atomy", "etc"] # 기타광고비(2026-10-22) = 애터미아자몰 오른쪽
assert ctx["names"]["etc"] == "기타광고비" and ctx["roas_basis"]["etc"] == "" and "etc" not in ads.ROAS_SALES_CODE # 매출 쇼핑몰 없음 = ROAS 없음
k = {x["key"]: x for x in ctx["kpis"]}
@@ -51,7 +51,7 @@ class _Store:
def test_sales_ad_channels_mapping():
m = dashboard.sales_ad_channels()
assert m["cafe24"] == (("google", "구글"), ("meta", "메타"))
assert m["cafe24"] == (("google", "구글"), ("meta", "메타"), ("kakao_pf", "카톡 플친"))
assert m["naver"] == (("naver", ""),) and m["coupang"] == (("coupang_wing", ""),)
assert m["coupang_rocket"] == (("coupang_rocket", ""),) and "google" not in m
@@ -187,6 +187,29 @@ def test_kpi_is_net_only():
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
assert [k["key"] for k in ctx["kpis"]] == ["net"]
assert ctx["kpis"][0]["value"] == 2_600_000 + 1_234_567
assert ctx["kpis"][0]["yoy_cmp"] == "전년 같은 기간" and ctx["kpis"][0]["yoy_delta"] is None # 작년 매출 없음
assert "yoy_cmp" not in dashboard.build_dashboard(_Store(), kind="year", anchor=TODAY, today=TODAY)["kpis"][0]
def test_kakao_pf_line_under_cafe24():
"""카톡 플친(2026-11-16) — 광고비 탭 열, ROAS 없음, 매출 탭 카페24 칸 아래 구글·메타 다음 줄."""
from app.modules.performance import ad_spend
assert ad_spend.CHANNEL_NAMES["kakao_pf"] == "카톡 플친" and "kakao_pf" not in ad_spend.ROAS_SALES_CODE
class _S(_Store):
def ad_amounts(self, start, end):
rows = {(date(2026, 10, 5), "google"): 100_000, (date(2026, 10, 5), "kakao_pf"): 30_000}
rows = {k: v for k, v in rows.items() if start <= k[0] <= end}
return rows, {k: "manual" for k in rows}
def ad_roas(self, start, end):
return {}
day5 = next(r for r in dashboard.build_dashboard(_S(), kind="week", anchor=TODAY, today=TODAY)["table"]
if r.get("date") == "2026-10-05")
assert [(a["label"], a["amount"], a["roas"]) for a in day5["ads"]["cafe24"]] == [("구글", 100_000, None), ("카톡 플친", 30_000, None)]
assert day5["ads_total"]["amount"] == 130_000
def test_pages_render_formula_cells_future_inputs_and_total_on_top(monkeypatch):
@@ -160,6 +160,11 @@ def test_periods():
# 진행 중인 달 — 전월 같은 날까지(말일 넘지 않게)
s, e, _ = calc.resolve_period("month", date(2026, 3, 31)).compare_range(today=date(2026, 3, 31))
assert (s, e) == (date(2026, 2, 1), date(2026, 2, 28))
# 전년 같은 기간 — 진행 중이면 오늘까지, 2/29 → 2/28
s, e, label = calc.resolve_period("month", date(2026, 11, 16)).yoy_range(today=date(2026, 11, 16))
assert (s, e, label) == (date(2025, 11, 1), date(2025, 11, 16), "전년 같은 기간")
s, e, _ = calc.resolve_period("month", date(2028, 2, 10)).yoy_range(today=date(2028, 3, 5))
assert (s, e) == (date(2027, 2, 1), date(2027, 2, 28))
assert calc.pct_change(110, 100) == 10.0 and calc.pct_change(5, 0) is None and calc.pct_change(0, 0) is None
+17 -2
View File
@@ -17,6 +17,8 @@
- 용어는 **"업무"**(2026-10-13 "작업"에서 다시 통일 — 화면·메시지·알림 제목, 코드·DB 는 그대로)·"세부 업무"·"메인 업무 추가". ERP 메뉴 이름은 "Project"(`app/main.py` 모듈 목록 title).
- 화면 기능을 바꾸면 도움말(`/project/help`)도 같이 고친다.
- UI 버그는 로컬 헤드리스 크롬/엣지로 렌더·좌표 덤프해 재현 후 고칠 것.
- **시각 고르기 = 공용 시각 팝업**(2026-11-11, `openTimePopover`·`enhanceTimeInput`, `PJLib` 로도) — 날짜 팝업 모양, 시 00~23·분 5분 단위, 끝에서 멈춤.
프로젝트(긴급 공지 포함)에서 `<input type="time">` 기본 시계 금지. 모달 dialog 안 칸이면 그 창 안에 popover 로 붙음(body 면 inert 로 마우스가 안 먹음).
- 날짜 팝업(`openDatePopover`·`enhanceDateInput`·`.pj-datepop` CSS)은 다른 모듈용 공용 복사본이 있다 — `app/static/erp-datepop.js`·`.css`
(2026-10-27, 휴가 신청 날짜 칸). 모양·동작을 바꾸면 그쪽도 같이 고칠 것(나중에 프로젝트도 공용 파일로 옮기면 하나가 됨).
@@ -24,7 +26,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 +50,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 거부).
@@ -95,6 +98,14 @@
## 알림
- **매일 하는 업무**(2026-11-11, 마이그레이션 033 `tasks.repeat_daily`) — 날짜 팝업 `openDatePopover({allowDaily, daily})` 아래 [매일](repeat 아이콘) =
`{due_date: null, repeat_daily: true}`(서버 `db.update_task` 가 마감일·시각 비움, 마감일을 고르면 자동으로 꺼짐). 업무 행에 `repeat_daily` 키가 있을 때만(=033 적용) 버튼이 보인다.
카드·목록·내 업무·세부 업무·업무 창 마감 칸 = `dueInfo(…, daily)` → `.is-daily`(CSS ::before repeat 아이콘 + "매일", 노랑).
알림 = `reminders.run_daily_alerts`(데몬 1분 주기, 영업일, `daily_alert_times` 중 지난 가장 늦은 시각 하나 — `task_reminders` kind `daily@HH:MM`·그날로 중복 방지)
→ 담당자(없으면 협업자)에게 `type=daily` 알림 → 큰 팝업 `_ALERT_TYPES` 에 포함, 줄 배경 노랑(`.pj-alert-item.is-daily`), PC 알림 프로그램 `Alert.IsDaily`.
추가 칸(보드 아래 메인 업무 추가·카드 세부 업무 추가 줄)에도 [매일] — `data-daily-ready`(`db.daily_ready`), `POST …/tasks` 의 `repeat_daily: true` = 만든 뒤 `update_task` 로 켬.
033 미적용이면 [매일] 숨김·PUT/POST 503·알림 skip.
- 수신함은 확인 안 한 태그·읽지 않은 알림만(2026-10-08) — [확인] 버튼 없이 줄을 누르면 읽음·확인 처리(같은 작업 줄 함께) + 페이지 이동 없이 오른쪽 iframe 패널, 다른 줄을 고르거나 패널을 닫으면 그 줄은 목록에서 빠짐.
- 나를 태그하거나 작업이 배정되면 프로젝트 화면 가운데 아래에 깜박이는 큰 팝업(닫기 전까지, `initTaskAlerts` + `GET /api/notifications/alerts`).
- **마감 지난 내 업무 위쪽 알림**(`static/erp-overdue.js`, ERP 모든 화면, `GET /project/api/my-overdue`, 닫으면 1시간 뒤 다시 — 새로 지난 업무는 바로)(6-17).
@@ -111,6 +122,10 @@
- 왼쪽 분류 | 오른쪽 설정. 새 옵션도 이 창에.
- 폰트 = 누구나·이 브라우저(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 이상.
- **알림 분류 — 매일 하는 업무 알림 시각**(2026-11-11) = 옵션 키 `daily_alert_times`(["HH:MM"…] 최대 12, 기본 ["09:00"], 빈 목록 = 끔). 행마다 시각 칸 + 휴지통, [알림 추가].
- 긴급 공지 = 수퍼관리자만.
## 연간 목표 (마이그레이션 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)
+45 -3
View File
@@ -888,6 +888,14 @@ class ProjectStore:
for k in ("start_time", "due_time"):
if k in fields:
clean[k] = store.validate_time(fields[k])
# 매일 하는 업무(033) — 켜면 마감일·마감 시각을 비운다(마감일 없이 매일).
if "repeat_daily" in fields:
if not isinstance(fields["repeat_daily"], bool):
raise ValueError("매일 반복 값이 올바르지 않습니다.")
clean["repeat_daily"] = fields["repeat_daily"]
if fields["repeat_daily"]:
clean["due_date"] = None
clean["due_time"] = None
newly_assigned: str | None = None
newly_completed = False
@@ -899,7 +907,11 @@ class ProjectStore:
prev = self._serialize(row)
sets: list[str] = []
params: list[Any] = []
for k in ("title", "description", "priority", "start_date", "due_date", "start_time", "due_time"):
# 마감일을 고르면 매일 반복은 꺼진다(열이 있을 때만 — 033 미적용이면 키가 없다)
if clean.get("due_date") and prev.get("repeat_daily") and "repeat_daily" not in clean:
clean["repeat_daily"] = False
for k in ("title", "description", "priority", "start_date", "due_date", "start_time", "due_time",
"repeat_daily"):
if k in clean:
sets.append(f"{k} = %s")
params.append(clean[k])
@@ -1746,6 +1758,18 @@ class ProjectStore:
([int(i) for i in ordered_ids], stage_id),
)
def daily_ready(self) -> bool:
"""tasks.repeat_daily(마이그레이션 033, 매일 하는 업무) 가 있는지. 한 번 켜지면 기억."""
if getattr(self, "_daily_ready", False):
return True
with self._pool.connection() as conn:
ok = bool(conn.execute(
"SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' "
"AND table_name = 'tasks' AND column_name = 'repeat_daily'"
).fetchone())
self._daily_ready = ok
return ok
def link_order_ready(self) -> bool:
"""task_project_links.sort_order(마이그레이션 032) 가 있는지. 한 번 켜지면 기억."""
if getattr(self, "_link_order_ready", False):
@@ -2268,9 +2292,27 @@ class ProjectStore:
).fetchall()
return [self._serialize(r) for r in rows]
def list_open_daily_tasks(self) -> list[dict[str, Any]]:
"""매일 하는 업무(033 repeat_daily) 중 미완료 + 팔로워 목록. 보관 프로젝트는 뺀다.
033 미적용이면 psycopg_errors.UndefinedColumn(알림 데몬이 그날은 건너뜀)."""
with self._pool.connection() as conn:
rows = conn.execute(
"""
SELECT t.id, t.title, t.assignee_email, t.project_id, t.parent_task_id, p.name AS project_name,
COALESCE((SELECT array_agg(f.user_email ORDER BY f.user_email)
FROM task_followers f WHERE f.task_id = t.id),
'{}'::text[]) AS followers
FROM tasks t
JOIN projects p ON p.id = t.project_id
WHERE t.repeat_daily AND t.completed_at IS NULL AND p.status <> 'archived'
ORDER BY t.id
""",
).fetchall()
return [self._serialize(r) for r in rows]
def add_reminder_notification(
self, *, task_id: int, kind: str, due_date: str, recipient_email: str,
project_id: int | None, title: str, body: str,
project_id: int | None, title: str, body: str, ntype: str | None = None,
) -> bool:
"""마감 알림 발송 기록 + 수신함 알림을 한 트랜잭션에. 처음이면 둘 다 넣고 True,
이미 보냈으면(UNIQUE) False. 알림 생성이 실패하면 발송 기록도 되돌려져 다음 실행에서
@@ -2289,7 +2331,7 @@ class ProjectStore:
"INSERT INTO project_notifications "
"(recipient_email, actor_email, project_id, task_id, type, title, body) "
"VALUES (%s,'',%s,%s,%s,%s,%s)",
(rcpt, project_id, task_id, kind, store.norm_str(title), store.norm_str(body)),
(rcpt, project_id, task_id, ntype or kind, store.norm_str(title), store.norm_str(body)),
)
return True
+70 -12
View File
@@ -15,6 +15,11 @@
"오늘 아직 안 돌았고, 설정 시각이 지났고, 영업일이면" 한 번 돈다. 여러 프로세스가
동시에 돌아도 위 UNIQUE 덕분에 중복 알림이 없다.
매일 하는 업무(033 tasks.repeat_daily, run_daily_alerts) — Project 옵션 daily_alert_times 시각(KST, 영업일)이
지나면 미완료 매일 업무의 담당자(없으면 협업자)에게 수신함 알림(type=daily, 큰 팝업에 따로 색). 데몬은 1분마다 깨어
지난 시각 중 가장 늦은 것 하나만 보낸다(서버가 꺼져 있다 켜져도 몇 번씩 쏟아지지 않게). 중복 방지는 같은
task_reminders(kind='daily@HH:MM', due_date=그날).
환경변수:
PROJECT_REMINDERS false 면 끈다(기본 켜짐)
PROJECT_REMINDER_HOUR 실행 시각(KST 0~23, 기본 9)
@@ -41,6 +46,7 @@ logger = logging.getLogger("project.reminders")
KIND_DUE_SOON = "due_soon"
KIND_DUE_TODAY = "due_today"
KIND_OVERDUE = "overdue"
NTYPE_DAILY = "daily"
OVERDUE_WINDOW_DAYS = 7
@@ -139,6 +145,39 @@ def run_due_reminders(
return counts
def daily_slot(times: list[str], hhmm: str) -> str | None:
"""설정 시각들 중 지금(hhmm)까지 지난 가장 늦은 시각 — 없으면 None."""
passed = [t for t in times if t <= hhmm]
return max(passed) if passed else None
def run_daily_alerts(
st: Any, *, today: date, slot: str, lookup: access.UserLookup | None = None,
) -> int:
"""매일 하는 업무 알림 한 번(그날 slot 시각분). 새로 만든 알림 수. 수신자·권한·중복 규칙은 마감 알림과 같다."""
made = 0
for t in st.list_open_daily_tasks():
assignee = store.norm_str(t.get("assignee_email"), lower=True)
wanted = [assignee] if assignee else store.normalize_emails(t.get("followers") or [])
try:
recipients = access.filter_recipients(st, t, wanted, lookup)
except Exception: # noqa: BLE001 - 권한 확인이 안 되면 이번엔 보내지 않는다
logger.warning("매일 업무 알림 수신자 확인 실패: task=%s", t["id"])
continue
for rcpt in recipients:
try:
created = st.add_reminder_notification(
task_id=t["id"], kind=f"daily@{slot}", due_date=today.isoformat(), recipient_email=rcpt,
project_id=t["project_id"], title=f"매일 업무: {t['title']}",
body=f"{t.get('project_name') or ''} · 매일 {slot}", ntype=NTYPE_DAILY,
)
except Exception: # noqa: BLE001 - 기록도 되돌려졌으니 다음 실행에서 다시 시도
logger.warning("매일 업무 알림 생성 실패(다음 실행에 재시도): task=%s", t["id"])
continue
made += int(bool(created))
return made
def _send_digests(digest: dict[str, list[tuple[str, dict[str, Any]]]], today: date) -> None:
from app.mail import send_email # noqa: WPS433
@@ -176,22 +215,41 @@ def start_reminder_thread(st: Any) -> bool:
def _loop() -> None:
last_run: date | None = None
last_due_try = 0.0
daily_done: tuple[date, str] | None = None # 마지막으로 보낸 (날짜, 시각)
while True:
now = now_kst()
today = now.date()
if time.monotonic() - last_due_try >= 300: # 마감 알림은 예전처럼 5분마다 확인
last_due_try = time.monotonic()
try:
if last_run != today and now.hour >= hour and is_workday(today):
counts = run_due_reminders(st, today=today)
last_run = today
logger.info("마감 알림 실행: %s", counts)
except Exception as exc: # noqa: BLE001
if type(exc).__name__ == "UndefinedTable":
# 008 마이그레이션 미적용 — 오늘은 더 시도하지 않는다(로그 도배 방지)
logger.warning("마감 알림 skip — project_db_008 마이그레이션 필요")
last_run = now_kst().date()
else:
logger.warning("마감 알림 실패(%s) — 5분 뒤 재시도", type(exc).__name__)
try:
now = now_kst()
today = now.date()
if last_run != today and now.hour >= hour and is_workday(today):
counts = run_due_reminders(st, today=today)
last_run = today
logger.info("마감 알림 실행: %s", counts)
if is_workday(today):
times = store.normalize_project_options(st.get_project_options())["daily_alert_times"]
slot = daily_slot(times, now.strftime("%H:%M"))
if slot and daily_done not in ((today, slot), (today, "skip")):
made = run_daily_alerts(st, today=today, slot=slot)
daily_done = (today, slot)
if made:
logger.info("매일 업무 알림 %s: %d건", slot, made)
except Exception as exc: # noqa: BLE001
if type(exc).__name__ == "UndefinedTable":
# 008 마이그레이션 미적용 — 오늘은 더 시도하지 않는다(로그 도배 방지)
logger.warning("마감 알림 skip — project_db_008 마이그레이션 필요")
last_run = now_kst().date()
if type(exc).__name__ in ("UndefinedColumn", "UndefinedTable"):
daily_done = (today, "skip") # 033(또는 008) 미적용 — 오늘은 그만(로그 도배 방지)
logger.warning("매일 업무 알림 skip — project_db_033 마이그레이션 필요")
else:
logger.warning("마감 알림 실패(%s) — 5분 뒤 재시도", type(exc).__name__)
time.sleep(300)
logger.warning("매일 업무 알림 실패(%s) — 1분 뒤 재시도", type(exc).__name__)
time.sleep(60)
threading.Thread(target=_loop, name="project-reminders", daemon=True).start()
return True
+33 -16
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,8 +899,9 @@ 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),
"pj_daily_ready": st.daily_ready(), # 033 — 새 업무·세부 업무 추가 칸 날짜 팝업의 [매일]
"can_manage": can_manage,
"nav_items": build_erp_nav(user, active="project"),
"page_title": project["name"],
@@ -967,7 +971,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 +1222,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")
@@ -1545,12 +1550,22 @@ def _create_task_for(
"""작업 만들기 공통(작업 창 등) — 권한(멤버)·담당자 확인·만들기·자동 협업자·배정/완료 알림·@태그.
돌려주는 값: (작업, 태그하지 못한 이메일). 회의록 [적용]은 같은 확인·후처리를 쓰되 만들기만 줄 잠금 트랜잭션 안에서."""
project, followers = _task_create_checks(request, st, user, project_id, payload)
daily = payload.get("repeat_daily", False) # 추가 칸 날짜 팝업 [매일](033) — 만든 뒤 켠다(마감일은 비움)
if not isinstance(daily, bool):
raise HTTPException(status_code=400, detail="매일 반복 값이 올바르지 않습니다.")
try:
task = st.create_task(**_task_create_fields(user, project_id, payload))
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except KeyError as exc:
raise HTTPException(status_code=404, detail=str(exc))
if daily:
try:
task = st.update_task(task_id=task["id"], fields={"repeat_daily": True}, actor=user["email"])
except UndefinedColumn:
raise HTTPException(status_code=503, detail="DB 마이그레이션 033(매일 하는 업무)이 아직 적용되지 않았습니다.")
task.pop("_newly_assigned", None)
task.pop("_newly_completed", None)
return task, _task_created_effects(request, st, user, project, task, followers, bg)
@@ -1673,6 +1688,8 @@ def api_update_task(
try:
task = st.update_task(task_id=task_id, fields=payload, actor=user["email"],
assignee_allowed=_registered_project_user)
except UndefinedColumn:
raise HTTPException(status_code=503, detail="DB 마이그레이션 033(매일 하는 업무)이 아직 적용되지 않았습니다.")
except ValueError as exc:
raise HTTPException(status_code=400, detail=str(exc))
except KeyError:
@@ -2813,7 +2830,7 @@ def _alerts_payload(st: Any, user: dict[str, Any], after: int) -> dict[str, Any]
return out
_ALERT_TYPES = ("mention", "assigned")
_ALERT_TYPES = ("mention", "assigned", "daily") # daily = 매일 하는 업무(reminders.run_daily_alerts, 033)
_ALERT_MAX = 10 # 한 번에 띄우는 최대 건수(오래된 것부터 — 닫으면 그 뒤 것)
_ALERT_PAGE = 200
_ALERT_SCAN_PAGES = 25 # 한 번 확인에 읽는 최대 행(200 × 25) — 볼 수 없는 알림이 아주 많아도 요청이 끝나게
@@ -2963,7 +2980,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 +3131,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 +3208,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 +3257,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 +3467,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 +4018,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),
+51
View File
@@ -383,7 +383,41 @@ 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 이상
"daily_alert_times": ["09:00"], # 매일 업무(033 repeat_daily) 알림 시각들(KST, 영업일)
}
ALL_VIEW_USERS_MAX = 2000
DAILY_ALERT_TIMES_MAX = 12
def _time_list(raw: Any) -> list[str] | None:
"""'HH:MM' 목록 → 정규화·중복 제거·정렬. 목록이 아니거나 잘못된 시각이 끼면 None(빈 목록 = 알림 끔)."""
if not isinstance(raw, list) or len(raw) > DAILY_ALERT_TIMES_MAX:
return None
out: set[str] = set()
for t in raw:
if not isinstance(t, str):
return None
try:
v = validate_time(t)
except ValueError:
return None
if v is None:
return None
out.add(v)
return sorted(out)
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 +428,13 @@ 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"])
times = _time_list(raw.get("daily_alert_times"))
if times is not None:
out["daily_alert_times"] = times
else:
out["daily_alert_times"] = list(PROJECT_OPTION_DEFAULTS["daily_alert_times"])
return out
@@ -413,6 +454,16 @@ 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("전체 보기 대상자 값이 올바르지 않습니다.")
if "daily_alert_times" in payload:
times = _time_list(payload["daily_alert_times"])
if times is None:
raise ValueError(f"매일 업무 알림 시각이 올바르지 않습니다(HH:MM, 최대 {DAILY_ALERT_TIMES_MAX}개).")
out["daily_alert_times"] = times
return out
@@ -1,8 +1,9 @@
{# 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" 이벤트로 보던 보드에 바로 반영.
· 알림(매일 하는 업무 알림 시각 여러 개) — 수퍼관리자·Admin, 모든 사용자.
· 관리자(긴급 공지) — 수퍼관리자만(공지 화면이 수퍼관리자 전용). #}
<button type="button" class="pj-help-btn" id="pj-options-btn" aria-label="Project 옵션" title="Project 옵션">
<span class="material-symbols-outlined">settings</span>
@@ -24,6 +25,8 @@
<span class="material-symbols-outlined">space_dashboard</span>프로젝트 화면</button>
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-board" id="pj-opt-tab-board" data-pane="board" tabindex="-1">
<span class="material-symbols-outlined">view_kanban</span>보드</button>
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-alert" id="pj-opt-tab-alert" data-pane="alert" tabindex="-1">
<span class="material-symbols-outlined">notifications</span>알림</button>
{% endif %}
{% if user and user.is_super_admin %}
<button type="button" role="tab" aria-selected="false" aria-controls="pj-opt-pane-admin" id="pj-opt-tab-admin" data-pane="admin" tabindex="-1">
@@ -62,7 +65,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>
@@ -76,6 +88,18 @@
</label>
</div>
</section>
{# 알림(2026-11-11) — 매일 하는 업무(033 repeat_daily) 알림 시각 여러 개(daily_alert_times, 영업일, 서버 reminders.py). #}
<section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-alert" aria-labelledby="pj-opt-tab-alert" data-pane="alert" hidden>
<h3>알림 <span class="pj-options-badge is-global"><span class="material-symbols-outlined">groups</span>모든 사용자에게 적용</span></h3>
<div class="pj-options-group">
<div class="pj-options-row is-stack">
<span class="pj-options-label" id="pj-options-daily-label"><b>매일 하는 업무 알림 시각</b><small>날짜 팝업에서 [매일]로 정한 업무를 이 시각마다 담당자(없으면 협업자)에게 알립니다 — 평일(공휴일 제외)</small></span>
<ol class="pj-options-times" id="pj-options-daily-times" aria-labelledby="pj-options-daily-label"></ol>
<div><button type="button" class="pj-btn" id="pj-options-daily-add"><span class="material-symbols-outlined" style="font-size:16px;vertical-align:-3px">add</span> 알림 추가</button></div>
<small class="pj-options-note">알림이 하나도 없으면 매일 업무 알림을 보내지 않습니다.</small>
</div>
</div>
</section>
{% endif %}
{% if user and user.is_super_admin %}
<section class="pj-options-pane" role="tabpanel" id="pj-opt-pane-admin" aria-labelledby="pj-opt-tab-admin" data-pane="admin" hidden>
@@ -105,4 +129,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=20261111e" 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=20261111f" />
<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=20261111d" 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=20261111f" />
<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=20261111d" 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=20261111f" />
<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>
@@ -118,10 +118,11 @@
<li><span class="pjh-ui"><span class="material-symbols-outlined">help</span></span> 물음표 — 지금 보고 있는 이 도움말을 새 탭으로 엽니다.</li>
<li><span class="pjh-ui"><span class="material-symbols-outlined">settings</span></span> 도움말 오른쪽의 옵션 — 왼쪽 분류를 골라 설정을 바꾸고 <span class="pjh-ui">저장</span>을 누르면 한꺼번에 적용되고 창이 닫힙니다.
<b>일반</b>: 폰트(기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드, 미리보기) — 누구나 바꿀 수 있고 이 브라우저에만 적용됩니다.
아래 프로젝트 화면·보드 분류는 수퍼관리자·Admin 에게만 보이고, 바꾸면 <b>모든 사용자</b>에게 적용됩니다(다른 사람은 다음에 화면을 열 때부터). 관리자(긴급 공지) 분류는 수퍼관리자에게만 보입니다.
아래 프로젝트 화면·보드·알림 분류는 수퍼관리자·Admin 에게만 보이고, 바꾸면 <b>모든 사용자</b>에게 적용됩니다(다른 사람은 다음에 화면을 열 때부터). 관리자(긴급 공지) 분류는 수퍼관리자에게만 보입니다.
분류 제목 옆 표시(이 브라우저에만 / 모든 사용자에게)로 적용 범위를 알 수 있습니다.
<b>프로젝트 화면</b>: 처음 여는 탭 — 왼쪽에서 프로젝트를 고르면 바로 보일 보기(보드·목록·캘린더·타임라인·대시보드). 왼쪽 "전체 보기"는 늘 대시보드로 열립니다.
<b>프로젝트 화면</b>: 처음 여는 탭 — 왼쪽에서 프로젝트를 고르면 바로 보일 보기(보드·목록·캘린더·타임라인·대시보드). <b>"전체 보기" 메뉴를 볼 사람</b> — 직원 아이콘을 체크한 사람에게만 왼쪽 "전체 보기"가 보입니다([전체 선택]으로 한 번에, 처음엔 Pro user 이상이 체크돼 있음). "전체 보기"는 늘 대시보드로 열립니다.
<b>보드</b>: 카드 표지 이미지 — 끄면 메인 업무 설명에 이미지가 있어도 보드 카드에 표지를 보여 주지 않습니다(보던 보드에 바로 반영).
<b>알림</b>: 매일 하는 업무 알림 시각 — <span class="pjh-ui">알림 추가</span>로 여러 개, 시각은 각각 정하고 휴지통 아이콘으로 뺍니다(처음엔 오전 9시 하나, 모두 빼면 매일 업무 알림 없음).
<span class="pjh-ui">기본값으로</span>는 창 안의 값만 처음으로 돌립니다(저장해야 반영). <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li>
</ul>
<h3>프로젝트 제목</h3>
@@ -151,7 +152,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 +231,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>
@@ -291,6 +292,7 @@
<tr><td style="color:#3f8f6b">오늘 · 내일</td><td>곧 마감(초록)</td></tr>
<tr><td style="color:#c22b10">어제 · 09/20(일)</td><td>마감이 지남(빨강). <b>완료한 업무도</b> 지난 마감일은 빨강으로 남아 늦게 끝낸 것을 알 수 있습니다.</td></tr>
<tr><td>09/30(수)</td><td>그 밖의 날짜(기본 글자색)</td></tr>
<tr><td style="color:#b07a00"><span class="material-symbols-outlined" style="font-size:15px;vertical-align:-3px">repeat</span>매일</td><td><b>매일 하는 업무</b> — 마감일 없이 매일 해야 하는 업무. 날짜 창 아래 <span class="pjh-ui">매일</span>을 누르면 정해지고(다시 누르거나 날짜를 고르면 풀림), 정한 시각마다 알림이 갑니다(17장).</td></tr>
</table>
</section>
@@ -524,6 +526,7 @@
<tr><td>업무 완료 · 새 댓글</td><td>담당자와 협업자</td></tr>
<tr><td>마감 알림</td><td>담당자(담당자가 없으면 협업자 전원). 영업일 아침 9시에 “내일 마감 · 오늘 마감 · 마감 지남”을 한 번씩 알려줍니다.</td></tr>
<tr><td>@태그</td><td>태그된 사람(수신함의 “나를 태그한 업무”)</td></tr>
<tr><td>매일 업무</td><td>담당자(없으면 협업자). <b>매일 하는 업무</b>(마감일 칸 <span class="material-symbols-outlined" style="font-size:15px;vertical-align:-3px">repeat</span>매일)가 끝나지 않았으면 평일(공휴일 제외) Project 옵션 → 알림에서 정한 시각마다 화면 아래 큰 알림에 <b>노란 줄</b>로 뜹니다(PC 알림 프로그램도).</td></tr>
</table>
<p>내가 한 행동은 나에게 알리지 않습니다. 회사 설정에 따라 업무 배정·완료는 관리자 메일로도 갑니다.</p>
</section>
@@ -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=20261111f" />
<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=20261111d" 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=20261111f" />
<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=20261111d" 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=20261111f" />
<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=20261111d" 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=20261111f" />
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — 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-daily-ready="{{ '1' if pj_daily_ready else '' }}" 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=20261111d" 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=20261111f" />
<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=20261111d" defer></script>
{% endblock %}
+64 -31
View File
@@ -149,10 +149,16 @@
return out + "</select>";
}
// 품목 토글 — [켜짐, 꺼짐] 표기
var FLAG_LABELS = {
display: ["진열", "미진열"], selling: ["판매", "중지"],
use_inventory: ["사용", "미사용"], display_soldout: ["표시", "안함"]
};
var FLAGS = Object.keys(FLAG_LABELS);
function toggleBtn(flag, on) {
var label = flag === "display" ? (on ? "진열" : "미진열") : (on ? "판매" : "중지");
return '<button type="button" class="cf24-v-toggle' + (on ? " is-on" : "") + '" data-flag="' + flag +
'" data-on="' + (on ? 1 : 0) + '" data-initial="' + (on ? 1 : 0) + '">' + label + "</button>";
'" data-on="' + (on ? 1 : 0) + '" data-initial="' + (on ? 1 : 0) + '">' + FLAG_LABELS[flag][on ? 0 : 1] + "</button>";
}
function paintToggle(btn, on, resetInitial) {
@@ -160,7 +166,25 @@
if (resetInitial) btn.dataset.initial = btn.dataset.on;
btn.classList.toggle("is-on", on);
btn.classList.toggle("is-dirty", btn.dataset.on !== btn.dataset.initial);
btn.textContent = btn.dataset.flag === "display" ? (on ? "진열" : "미진열") : (on ? "판매" : "중지");
btn.textContent = FLAG_LABELS[btn.dataset.flag][on ? 0 : 1];
}
// 재고관리 · 재고 수량 · 품절표시 칸 (진열·판매 다음)
var INVENTORY_TH = '<th class="cf24-v-flag">재고관리</th><th class="cf24-v-qty">재고</th><th class="cf24-v-flag">품절표시</th>';
function inventoryCells(variant) {
var qty = variant && variant.quantity != null ? String(variant.quantity) : "0";
return '<td class="cf24-v-flag">' + toggleBtn("use_inventory", !!(variant && variant.use_inventory)) + "</td>" +
'<td class="cf24-v-qty"><input type="text" name="quantity" inputmode="numeric" value="' + esc(qty) + '" /></td>' +
'<td class="cf24-v-flag">' + toggleBtn("display_soldout", !!(variant && variant.display_soldout)) + "</td>";
}
// 행의 품목 입력 요소들 — 저장 패치(variantPatch/newRowPatch)용
function variantFields(tr, into) {
into.custom = tr.querySelector('[name="custom_variant_code"]');
into.amount = tr.querySelector('[name="additional_amount"]');
into.quantity = tr.querySelector('[name="quantity"]');
FLAGS.forEach(function (flag) { into[flag] = tr.querySelector('.cf24-v-toggle[data-flag="' + flag + '"]'); });
return into;
}
function bindToggles(container) {
@@ -338,13 +362,14 @@
e.target.value = salePrice(e.target.closest("tr").querySelector('[name="additional_amount"]').value);
});
tbody.addEventListener("keydown", function (e) {
if (!e.target.classList.contains("cf24-sale-price")) return;
// isComposing: 한글 조합 중 Enter 는 글자 확정용이다 — 여기서 옮기면 글자가 깨지거나 두 칸 내려간다.
if (e.isComposing || !e.target.matches('[name="option_text"], [name="custom_variant_code"], [name="additional_amount"], .cf24-sale-price, [name="quantity"]')) return;
var down = e.key === "Enter" || e.key === "ArrowDown";
if (!down && e.key !== "ArrowUp") return;
e.preventDefault();
var tr = e.target.closest("tr")[down ? "nextElementSibling" : "previousElementSibling"];
if (!tr) return;
var next = tr.querySelector(".cf24-sale-price");
var next = tr.cells[e.target.closest("td").cellIndex].querySelector('input[type="text"]');
next.focus();
next.select();
});
@@ -424,6 +449,7 @@
salePriceCell(variant ? variant.additional_amount : "0") +
'<td class="cf24-v-flag">' + toggleBtn("display", variant ? !!variant.display : true) + "</td>" +
'<td class="cf24-v-flag">' + toggleBtn("selling", variant ? !!variant.selling : true) + "</td>" +
inventoryCells(variant) +
'<td class="cf24-u-del">' + (awaiting ? "" : '<button type="button" class="cf24-u-remove" title="' + (isNewRow ? "행 삭제" : "품목 삭제 (카페24에 바로 반영)") + '">✕</button>') + "</td>" +
"</tr>";
}
@@ -448,7 +474,7 @@
"</div>" +
'<div class="cf24-u-tablewrap"><table class="cf24-variants cf24-u-table"><thead><tr>' +
'<th class="cf24-u-drag"></th><th class="cf24-u-thumb">썸네일</th><th>옵션값 이름</th><th class="cf24-v-syscode">품목코드</th>' +
'<th class="cf24-v-code">자체 품목코드</th><th class="cf24-v-amount">추가금액</th><th class="cf24-v-amount">판매 가격</th><th class="cf24-v-flag">진열</th><th class="cf24-v-flag">판매</th><th class="cf24-u-del"></th>' +
'<th class="cf24-v-code">자체 품목코드</th><th class="cf24-v-amount">추가금액</th><th class="cf24-v-amount">판매 가격</th><th class="cf24-v-flag">진열</th><th class="cf24-v-flag">판매</th>' + INVENTORY_TH + '<th class="cf24-u-del"></th>' +
"</tr></thead><tbody id=\"cf24-u-body\">";
rows.forEach(function (r, i) { html += rowHtml(r, canDrag, i); });
if (isNew) html += rowHtml({ index: null, value: null, variant: null }, true, null);
@@ -568,8 +594,8 @@
link: tr.querySelector('[name="option_link_image"]').value,
custom: tr.querySelector('[name="custom_variant_code"]').value,
amount: tr.querySelector('[name="additional_amount"]').value,
display: tr.querySelector('.cf24-v-toggle[data-flag="display"]').dataset.on,
selling: tr.querySelector('.cf24-v-toggle[data-flag="selling"]').dataset.on
quantity: tr.querySelector('[name="quantity"]').value,
flags: FLAGS.map(function (flag) { return tr.querySelector('.cf24-v-toggle[data-flag="' + flag + '"]').dataset.on; })
};
});
}
@@ -597,11 +623,12 @@
set('[name="option_text"]', k.text);
set('[name="custom_variant_code"]', k.custom);
set('[name="additional_amount"]', k.amount);
set('[name="quantity"]', k.quantity);
if (k.image) { tr.querySelector('[name="option_image_file"]').value = k.image; }
if (k.link) { tr.querySelector('[name="option_link_image"]').value = k.link; }
["display", "selling"].forEach(function (flag) {
FLAGS.forEach(function (flag, i) {
var btn = tr.querySelector('.cf24-v-toggle[data-flag="' + flag + '"]');
if (btn && btn.dataset.on !== k[flag]) paintToggle(btn, k[flag] === "1", false);
if (btn && btn.dataset.on !== k.flags[i]) paintToggle(btn, k.flags[i] === "1", false);
});
});
}
@@ -765,7 +792,7 @@
/* ── 저장 (통합) ── */
function collectUnified(tbody) {
return Array.prototype.map.call(tbody.children, function (tr, i) {
return {
return variantFields(tr, {
tr: tr,
position: i,
isNew: tr.classList.contains("is-new"),
@@ -773,12 +800,8 @@
code: tr.dataset.code || "",
text: tr.querySelector('[name="option_text"]').value.trim(),
image: tr.querySelector('[name="option_image_file"]').value,
link: tr.querySelector('[name="option_link_image"]').value,
custom: tr.querySelector('[name="custom_variant_code"]'),
amount: tr.querySelector('[name="additional_amount"]'),
display: tr.querySelector('.cf24-v-toggle[data-flag="display"]'),
selling: tr.querySelector('.cf24-v-toggle[data-flag="selling"]')
};
link: tr.querySelector('[name="option_link_image"]').value
});
});
}
@@ -800,20 +823,25 @@
var any = false;
if (r.custom.value !== r.custom.defaultValue) { patch.custom_variant_code = r.custom.value.trim(); any = true; }
if (r.amount.value !== r.amount.defaultValue) { patch.additional_amount = r.amount.value.trim() || "0"; any = true; }
if (r.display.dataset.on !== r.display.dataset.initial) { patch.display = r.display.dataset.on === "1" ? "on" : "off"; any = true; }
if (r.selling.dataset.on !== r.selling.dataset.initial) { patch.selling = r.selling.dataset.on === "1" ? "on" : "off"; any = true; }
if (r.quantity.value !== r.quantity.defaultValue) { patch.quantity = r.quantity.value.trim() || "0"; any = true; }
FLAGS.forEach(function (flag) {
if (r[flag].dataset.on !== r[flag].dataset.initial) { patch[flag] = r[flag].dataset.on === "1" ? "on" : "off"; any = true; }
});
if (withOrder) { patch.display_order = r.position + 1; any = true; }
return any ? patch : null;
}
// 새 행(아직 품목 없음)의 초기 패치 — 기본값(빈 코드·0원·진열·판매)과 다른 것만
// 새 행(아직 품목 없음)의 초기 패치 — 기본값(빈 코드·0원·진열·판매·재고관리 미사용·재고 0·품절표시 안함)과 다른 것만
function newRowPatch(r, code) {
var p = { variant_code: code };
var any = false;
if (r.custom.value.trim()) { p.custom_variant_code = r.custom.value.trim(); any = true; }
if (amountPlain(r.amount.value) !== "0") { p.additional_amount = r.amount.value.trim(); any = true; }
if (r.display.dataset.on !== "1") { p.display = "off"; any = true; }
if (r.selling.dataset.on !== "1") { p.selling = "off"; any = true; }
if (amountPlain(r.quantity.value) !== "0") { p.quantity = r.quantity.value.trim(); any = true; }
FLAGS.forEach(function (flag) {
var defaultOn = flag === "display" || flag === "selling";
if ((r[flag].dataset.on === "1") !== defaultOn) { p[flag] = defaultOn ? "off" : "on"; any = true; }
});
return any ? p : null;
}
@@ -865,7 +893,7 @@
var lines = [];
if (optionsChanged) lines.push("옵션명·옵션값 이름/썸네일/표시방식");
if (patches.length) lines.push("품목 " + patches.length + "건 (자체코드·추가금액·진열/판매" + (orderChanged ? "·순서" : "") + ")");
if (patches.length) lines.push("품목 " + patches.length + "건 (자체코드·추가금액·진열/판매·재고" + (orderChanged ? "·순서" : "") + ")");
window.erpConfirm("카페24에 바로 반영합니다. 계속할까요?\n\n- " + lines.join("\n- ")).then(function (ok) {
if (!ok) return;
saveBtn.disabled = true;
@@ -887,10 +915,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");
@@ -1007,7 +1040,7 @@
html += '<p class="cf24-muted">품목이 아직 조회되지 않았습니다. 잠시 뒤 창을 닫았다 다시 여세요.</p>';
} else {
html += '<div class="cf24-variants-wrap"><table class="cf24-variants"><thead><tr><th class="cf24-v-imgcol"></th><th>옵션</th><th class="cf24-v-syscode">품목코드</th>' +
'<th class="cf24-v-code">자체 품목코드</th><th class="cf24-v-amount">추가금액</th><th class="cf24-v-amount">판매 가격</th><th class="cf24-v-flag">진열</th><th class="cf24-v-flag">판매</th><th class="cf24-u-del"></th></tr></thead><tbody>';
'<th class="cf24-v-code">자체 품목코드</th><th class="cf24-v-amount">추가금액</th><th class="cf24-v-amount">판매 가격</th><th class="cf24-v-flag">진열</th><th class="cf24-v-flag">판매</th>' + INVENTORY_TH + '<th class="cf24-u-del"></th></tr></thead><tbody>';
variants.forEach(function (v) {
var label = v.options.map(function (o) { return o.value; }).join(" / ") || v.variant_code;
html += '<tr class="cf24-v-item" data-code="' + esc(v.variant_code) + '">' +
@@ -1018,6 +1051,7 @@
'<td class="cf24-v-amount"><input type="text" name="additional_amount" inputmode="numeric" value="' + esc(amountPlain(v.additional_amount)) + '" /></td>' +
salePriceCell(v.additional_amount) +
'<td class="cf24-v-flag">' + toggleBtn("display", !!v.display) + "</td><td class=\"cf24-v-flag\">" + toggleBtn("selling", !!v.selling) + "</td>" +
inventoryCells(v) +
'<td class="cf24-u-del"><button type="button" class="cf24-u-remove" data-code="' + esc(v.variant_code) + '" title="품목 삭제 (카페24에 바로 반영)">✕</button></td></tr>';
});
html += "</tbody></table></div><div class=\"cf24-side-actions\" style=\"margin-top:8px;\"><span class=\"cf24-muted\" id=\"cf24-var-msg\"></span>" +
@@ -1100,9 +1134,7 @@
var saveBtn = body.querySelector("#cf24-var-save");
var rows = [];
wrap.querySelectorAll("tr[data-code]").forEach(function (tr) {
var r = { code: tr.dataset.code, custom: tr.querySelector('[name="custom_variant_code"]'), amount: tr.querySelector('[name="additional_amount"]'),
display: tr.querySelector('.cf24-v-toggle[data-flag="display"]'), selling: tr.querySelector('.cf24-v-toggle[data-flag="selling"]') };
var p = variantPatch(r, false);
var p = variantPatch(variantFields(tr, { code: tr.dataset.code }), false);
if (p) rows.push(p);
});
if (!rows.length) { setMsg(msg, "바뀐 품목이 없습니다.", ""); return; }
@@ -1119,6 +1151,7 @@
if (!tr) return;
if (u.custom_variant_code !== undefined) tr.querySelector('[name="custom_variant_code"]').value = u.custom_variant_code;
if (u.additional_amount !== undefined) tr.querySelector('[name="additional_amount"]').value = amountPlain(u.additional_amount);
if (u.quantity != null) tr.querySelector('[name="quantity"]').value = String(u.quantity);
tr.querySelectorAll(".cf24-v-toggle").forEach(function (btn) {
if (u[btn.dataset.flag] !== undefined) paintToggle(btn, !!u[btn.dataset.flag], true);
});
@@ -1126,8 +1159,8 @@
if (v.variant_code !== code) return;
if (u.custom_variant_code !== undefined) v.custom_variant_code = u.custom_variant_code;
if (u.additional_amount !== undefined) v.additional_amount = u.additional_amount;
if (u.display !== undefined) v.display = !!u.display;
if (u.selling !== undefined) v.selling = !!u.selling;
if (u.quantity != null) v.quantity = u.quantity;
FLAGS.forEach(function (flag) { if (u[flag] !== undefined) v[flag] = !!u[flag]; });
});
});
commitValues(wrap);
+5 -2
View File
@@ -1331,7 +1331,8 @@ body.cf24-modal-open {
}
.cf24-variants th {
font-weight: 500;
font-weight: 700;
text-align: center;
font-size: 12px;
color: var(--color-midtone-gray, #737373);
white-space: nowrap;
@@ -1348,7 +1349,9 @@ body.cf24-modal-open {
.cf24-v-code { width: 132px; }
.cf24-v-amount { width: 90px; }
.cf24-v-amount input { text-align: right; }
.cf24-v-flag { width: 56px; text-align: center; }
.cf24-v-qty { width: 70px; }
.cf24-v-qty input { text-align: right; }
.cf24-variants .cf24-v-flag { width: 56px; text-align: center; }
/* 품목코드 — 클릭하면 클립보드로. 눌리는 것임을 커서·밑줄로 알린다. */
.cf24-v-copy {
+1
View File
@@ -54,6 +54,7 @@
});
// ── 날짜 — 프로젝트 날짜 팝업 ──
L.enhanceDateInput(dateEl, { placeholder: "날짜(비우면 바로)" });
if (L.enhanceTimeInput) L.enhanceTimeInput(timeEl, { placeholder: "00:00" }); // 프로젝트 공용 시각 팝업(5분 단위)
// ── 받는 사람 — 프로젝트 멤버 고르기 모양 ──
peopleBox.innerHTML = people.map(L.memberPickHtml).join("") || '<span class="pj-empty-sm">등록된 사람이 없습니다.</span>';
function toAll() { return root.querySelector('input[name="ntc-to"]:checked').value === "all"; }
+128 -6
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, daily_alert_times: ["09:00"] };
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,15 @@
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");
// 매일 하는 업무 알림 시각(여러 개) — 알림 분류(수퍼관리자·Admin 창에만)
const timesBox = document.getElementById("pj-options-daily-times");
const timesAdd = document.getElementById("pj-options-daily-add");
const TIMES_MAX = 12; // 서버 store.DAILY_ALERT_TIMES_MAX
let users = null; // 후보(project 권한자) — 못 읽었으면 null(그때는 대상자를 저장하지 않음)
const localControls = [select, cancel, closeX, reset];
let sys = null; // 서버에서 읽은 시스템 옵션 — 못 읽었으면 null(그때는 폰트만 저장)
let openSeq = 0; // 창을 다시 열면 앞의 늦은 응답은 버린다
@@ -35,9 +45,88 @@
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),
daily_alert_times: (o.daily_alert_times || []).slice().sort() };
}
function timeBtns() { return timesBox ? Array.from(timesBox.querySelectorAll(".pj-time-btn")) : []; }
// 고른 시각들 — 빈 칸은 빼고 중복 제거·정렬(서버도 같게 정규화)
function pickedTimes() {
const out = [];
timeBtns().forEach(function (b) { const v = b.dataset.value || ""; if (v && out.indexOf(v) < 0) out.push(v); });
return out.sort();
}
function setTimeBtn(btn, v) {
btn.dataset.value = v || "";
btn.querySelector(".pj-time-text").textContent = v || "시각 선택";
btn.classList.toggle("is-empty", !v);
}
// 시각 고르기 = 프로젝트 공용 날짜 팝업 모양 시각 팝업(project.js openTimePopover — 옵션 창 안에 붙어 휠·클릭이 먹음)
function openTimePop(btn) {
if (!window.PJLib || !window.PJLib.openTimePopover) return;
window.PJLib.openTimePopover(btn, { value: btn.dataset.value || "", onChange: function (v) { setTimeBtn(btn, v); } });
}
function closeTimePop() { if (window.PJLib && window.PJLib.closeTimePopover) window.PJLib.closeTimePopover(); }
function renumberTimes() {
if (!timesBox) return;
Array.from(timesBox.children).forEach(function (li, i) { li.firstChild.textContent = "알림 " + (i + 1); });
timesAdd.disabled = !sys || timesBox.children.length >= TIMES_MAX;
}
function addTimeRow(v) {
const li = document.createElement("li");
li.innerHTML = '<span></span><button type="button" class="pj-time-btn" aria-label="알림 시각" title="시각 바꾸기">' +
'<span class="pj-time-text"></span><span class="material-symbols-outlined">schedule</span></button>' +
'<button type="button" class="pj-time-del" title="이 알림 빼기" aria-label="이 알림 빼기"><span class="material-symbols-outlined">delete</span></button>';
const tb = li.querySelector(".pj-time-btn"), del = li.querySelector(".pj-time-del");
setTimeBtn(tb, v);
tb.disabled = del.disabled = !sys;
tb.addEventListener("click", function () { if (document.querySelector(".pj-timepop")) closeTimePop(); else openTimePop(tb); });
del.addEventListener("click", function () { closeTimePop(); li.remove(); renumberTimes(); });
timesBox.appendChild(li);
renumberTimes();
return li;
}
function fillTimes(list) {
if (!timesBox) return;
closeTimePop();
timesBox.innerHTML = "";
(list || []).forEach(addTimeRow);
renumberTimes();
}
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;
fillTimes(o.daily_alert_times);
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 +146,11 @@
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; });
if (timesBox) {
timesBox.querySelectorAll("input, button").forEach(function (c) { c.disabled = on || !sys; });
timesAdd.disabled = on || !sys || timesBox.children.length >= TIMES_MAX;
}
}
function close() { if (!save.disabled) dialog.close(); }
async function loadSys() {
@@ -64,9 +158,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 +176,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 +192,19 @@
showPane(tabs[(i + (e.key === "ArrowDown" ? 1 : tabs.length - 1)) % tabs.length].dataset.pane, true);
});
select.addEventListener("change", paint);
if (timesAdd) timesAdd.addEventListener("click", function () {
if (timesBox.children.length >= TIMES_MAX) return;
const tb = addTimeRow("").querySelector(".pj-time-btn");
tb.focus(); openTimePop(tb);
});
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);
@@ -99,7 +212,7 @@
cancel.addEventListener("click", close);
closeX.addEventListener("click", close);
dialog.addEventListener("cancel", function (e) { if (save.disabled) e.preventDefault(); });
dialog.addEventListener("close", function () { openSeq++; button.focus(); });
dialog.addEventListener("close", function () { closeTimePop(); openSeq++; button.focus(); });
form.addEventListener("submit", async function (e) {
e.preventDefault(); if (save.disabled) return;
const fontValue = select.value, font = names[fontValue];
@@ -109,6 +222,14 @@
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 (timesBox) {
const t = pickedTimes();
if (t.join(",") !== sys.daily_alert_times.join(",")) sysChanges.daily_alert_times = t;
}
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 +240,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 },
+49 -1
View File
@@ -2021,6 +2021,15 @@ img.pj-person-ic { width: 22px; height: 22px; }
/* 마감일 표기 색 — 오늘·내일 초록, 어제·지남 빨강(아사나) */
.pj-card-due.is-soon, .pj-card-sub-due.is-soon, .pj-due-label.is-soon, .pj-due-btn.is-soon { color: #3f8f6b; }
.pj-card-due.is-overdue, .pj-card-sub-due.is-overdue, .pj-due-label.is-overdue { color: #c22b10; }
/* 매일 하는 업무(033) — 마감일 자리에 반복 아이콘 + "매일"(업무 창 버튼은 JS 가 아이콘을 repeat 로) */
.pj-card-due.is-daily, .pj-card-sub-due.is-daily, .pj-due-label.is-daily, .pj-subtask-due.is-daily, .pj-due-btn.is-daily { color: #b07a00; }
.pj-card-due.is-daily::before, .pj-card-sub-due.is-daily::before, .pj-due-label.is-daily::before, .pj-subtask-due.is-daily::before {
content: "repeat"; font-family: "Material Symbols Outlined"; font-size: 1.15em; line-height: 1; vertical-align: -0.2em; margin-right: 2px;
font-feature-settings: "liga"; -webkit-font-smoothing: antialiased;
}
.pj-dp-daily { display: inline-flex; align-items: center; gap: 2px; }
.pj-dp-daily .material-symbols-outlined { font-size: 17px; }
.pj-dp-daily.is-on { background: #fff5d6; color: #b07a00; }
/* ── 멘션(@태그) ── */
.pj-mention {
@@ -3166,6 +3175,12 @@ input.pj-meet-amount::placeholder { color: rgba(0, 0, 0, .28); }
.pj-alert-kind { flex: none; padding: 2px 8px; border-radius: 999px; font-size: 11.5px; font-weight: 700; }
.pj-alert-kind.is-mention { background: #eef2ff; color: #4053c8; }
.pj-alert-kind.is-assigned { background: #e7f6ec; color: #1f8a4c; }
/* 매일 하는 업무(033) 알림 — 줄 배경을 따로(노랑) */
.pj-alert-item.is-daily { background: #fff5d6; box-shadow: inset 3px 0 0 #f0a800; }
.pj-alert-item.is-daily + .pj-alert-item.is-daily { margin-top: 4px; }
.pj-alert-item.is-daily:hover { background: #ffedb8; }
.pj-alert-kind.is-daily { display: inline-flex; align-items: center; gap: 2px; background: #f0a800; color: #fff; }
.pj-alert-kind.is-daily .material-symbols-outlined { font-size: 14px; }
.pj-alert-text { display: flex; flex-direction: column; min-width: 0; flex: 1 1 auto; }
.pj-alert-text b { font-size: 14.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pj-alert-text small { color: var(--pj-ink-soft); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -3240,7 +3255,8 @@ html[data-pj-font="nanum-square"] { --pj-font: "NanumSquare", var(--pj-system-fo
html[data-pj-font="nanum-square-neo"] { --pj-font: "NanumSquareNeo", var(--pj-system-font); }
html[data-pj-font="nanum-square-round"] { --pj-font: "NanumSquareRound", var(--pj-system-font); }
/* ── Project 옵션 대화창(_options.html) — 데스크톱 프로그램 설정 창처럼 왼쪽 분류 | 오른쪽 설정 ── */
.pj-options-dialog { width: min(720px, calc(100vw - 40px)); max-height: min(600px, calc(100vh - 40px)); box-sizing: border-box; padding: 0; border: 1px solid #d8dce2; border-radius: 12px; color: var(--pj-ink); font-family: var(--pj-font); box-shadow: 0 12px 40px #0003; overflow: hidden; }
/* 크기 고정 800×750(2026-11-11) — 화면이 그보다 작을 때만 줄어든다 */
.pj-options-dialog { width: min(800px, calc(100vw - 40px)); height: min(750px, calc(100vh - 40px)); max-width: none; max-height: none; box-sizing: border-box; padding: 0; border: 1px solid #d8dce2; border-radius: 12px; color: var(--pj-ink); font-family: var(--pj-font); box-shadow: 0 12px 40px #0003; overflow: hidden; }
.pj-options-dialog[open] { display: flex; }
.pj-options-dialog::backdrop { background: #0005; }
.pj-options-dialog form { display: flex; flex-direction: column; width: 100%; min-height: 0; }
@@ -3282,6 +3298,38 @@ 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-times { display: flex; flex-direction: column; gap: 6px; margin: 0; padding: 0; list-style: none; }
.pj-options-times li { display: flex; align-items: center; gap: 8px; font-size: 13px; }
.pj-options-times li > span:first-child { min-width: 52px; color: var(--pj-ink-soft); }
.pj-time-btn { display: inline-flex; align-items: center; gap: 8px; height: 36px; padding: 0 10px; border: 1px solid #d8dce2; border-radius: 8px; background: #fff; color: var(--pj-ink); font: inherit; font-size: 13.5px; font-variant-numeric: tabular-nums; cursor: pointer; }
.pj-time-btn:hover:not(:disabled) { border-color: #4573d2; }
.pj-time-btn:disabled { opacity: .6; cursor: default; }
.pj-time-btn .material-symbols-outlined { font-size: 18px; color: #6d6e6f; }
.pj-time-btn.is-empty .pj-time-text { color: #9aa1a9; }
.pj-options-times .pj-time-del { display: inline-flex; padding: 4px; border: 0; border-radius: 6px; background: none; color: #6d6e6f; cursor: pointer; }
.pj-options-times .pj-time-del:hover { background: #fdecec; color: #b42318; }
/* 시각 고르기 팝업 — 날짜 팝업(.pj-datepop) 모양 그대로 + 시·분 두 열(돌아가지 않는 목록). popover(top layer) 기본값을 지운다. */
.pj-timepop { width: 200px; }
.pj-timepop[popover] { inset: auto; margin: 0; overflow: visible; }
.pj-tp-value { display: flex; align-items: center; justify-content: center; font-size: 15px; font-weight: 600; font-variant-numeric: tabular-nums; }
.pj-tp-heads, .pj-tp-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.pj-tp-heads span { text-align: center; font-size: 12px; font-weight: 600; color: #6d6e6f; padding: 2px 0 4px; }
.pj-tp-col { height: 238px; overflow-y: auto; overscroll-behavior: contain; scrollbar-width: thin; display: flex; flex-direction: column; gap: 2px; }
.pj-tp-item { flex: none; height: 32px; border: 0; border-radius: 16px; background: transparent; font: inherit; font-size: 13.5px; font-variant-numeric: tabular-nums; color: var(--pj-ink); cursor: pointer; }
.pj-tp-item:hover { background: #f1f2f4; }
.pj-tp-item.is-selected { background: #4573d2; color: #fff; font-weight: 600; }
.pj-timepop .pj-dp-link { transition: background .12s, color .12s; }
.pj-timepop .pj-dp-link[data-tp="clear"]:hover { background: #fdecec; color: #b42318; }
.pj-timepop .pj-dp-link[data-tp="ok"] { color: #4573d2; }
.pj-timepop .pj-dp-link[data-tp="ok"]:hover { background: #4573d2; color: #fff; }
.pj-timepop .pj-dp-link:active { transform: translateY(1px); }
.pj-options-times:empty::before { content: "알림 없음"; font-size: 12px; color: var(--pj-ink-soft); }
.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; }
+211 -45
View File
@@ -448,7 +448,9 @@
const a = new Date(String(iso).slice(0, 10) + "T00:00:00"), b = new Date(baseIso + "T00:00:00");
return Math.round((a - b) / 86400000);
}
function dueInfo(iso, done) {
// daily = 매일 하는 업무(033 repeat_daily) — 마감일 대신 반복 아이콘(CSS .is-daily::before) + "매일".
function dueInfo(iso, done, daily) {
if (daily) return { text: "매일", cls: "is-daily" };
if (!iso) return null;
const diff = dayDiff(iso, isoToday());
let text, cls = "";
@@ -460,10 +462,11 @@
return { text: text, cls: cls };
}
// 마감일 칸 말풍선 — 지난 날짜(빨강)면 "마감일 지남", 아니면 "마감일 변경".
function dueTip(di) { return di && di.cls === "is-overdue" ? "마감일 지남" : "마감일 변경"; }
function dueTip(di) { return di && di.cls === "is-overdue" ? "마감일 지남" : di && di.cls === "is-daily" ? "매일 하는 업무(눌러서 변경)" : "마감일 변경"; }
// ── 아사나식 날짜 팝업 — 마감일(과 선택적으로 시작일)을 월 달력에서 고른다.
// opts: { start, due, allowStart, onChange(patch) }. 날짜를 누를 때마다
// opts: { start, due, allowStart, daily, allowDaily, onChange(patch) }. allowDaily = 아래 [매일] 버튼(매일 하는 업무,
// 033) — 누르면 onChange({due_date: null, repeat_daily: true}) 하고 닫힘, 날짜를 고르면 repeat_daily: false. 날짜를 누를 때마다
// onChange({due_date[, start_date]}) 로 바로 저장하고, 마감일을 고르면 팝업을
// 닫는다(시작일을 고른 땐 마감일을 이어서 고르게 열어 둠). 바깥 클릭·Esc 로 닫힘. "지우기" = 둘 다 비우고 닫기. 앵커 아래(자리가
// 없으면 위)에 뜨고 꼬리가 앵커를 가리킨다. 한 번에 하나만.
@@ -504,6 +507,7 @@
let start = opts.start ? String(opts.start).slice(0, 10) : "";
let due = opts.due ? String(opts.due).slice(0, 10) : "";
let showStart = !!(opts.allowStart && start);
let daily = !!(opts.allowDaily && opts.daily);
let active = "due";
const base = new Date((due || start || today) + "T00:00:00");
let viewY = base.getFullYear(), viewM = base.getMonth();
@@ -518,6 +522,7 @@
function emit() {
const patch = { due_date: due || null };
if (opts.allowStart) patch.start_date = start || null;
if (opts.allowDaily) patch.repeat_daily = daily;
if (opts.onChange) opts.onChange(patch);
}
function field(kind, val, ph) {
@@ -554,7 +559,7 @@
(opts.allowStart
? (showStart ? field("start", start, "시작일") : '<button type="button" class="pj-dp-addstart">+ 시작일</button>')
: "") +
field("due", due, "마감일") +
field("due", due, daily ? "매일 하는 업무" : "마감일") +
"</div>" +
'<div class="pj-dp-nav">' +
'<button type="button" class="pj-dp-navbtn" data-nav="-1" title="이전 달"><span class="material-symbols-outlined">chevron_left</span></button>' +
@@ -569,6 +574,10 @@
"</div>" +
'<div class="pj-dp-foot">' +
'<button type="button" class="pj-dp-link pj-dp-today">오늘</button>' +
(opts.allowDaily
? '<button type="button" class="pj-dp-link pj-dp-daily' + (daily ? " is-on" : "") + '" title="마감일 없이 매일 하는 업무' +
(daily ? "(다시 누르면 해제)" : "") + '"><span class="material-symbols-outlined">repeat</span>매일</button>'
: "") +
'<button type="button" class="pj-dp-link pj-dp-clear">지우기</button>' +
"</div>";
wire();
@@ -587,6 +596,7 @@
return;
}
due = iso;
daily = false;
if (start && start > iso) start = iso;
emit();
closeDatePopover();
@@ -636,7 +646,13 @@
pick(today);
});
pop.querySelector(".pj-dp-clear").addEventListener("click", function () {
start = ""; due = ""; emit(); closeDatePopover();
start = ""; due = ""; daily = false; emit(); closeDatePopover();
});
const dailyBtn = pop.querySelector(".pj-dp-daily");
if (dailyBtn) dailyBtn.addEventListener("click", function () {
daily = !daily;
if (daily) due = "";
emit(); closeDatePopover();
});
}
function focusActive() {
@@ -741,6 +757,135 @@
sync();
}
// ── 시각 고르기 팝업(2026-11-11, 프로젝트 공용 — Project 옵션 알림 시각·긴급 공지 띄울 시각) ──
// 날짜 팝업(.pj-datepop)과 같은 카드·꼬리·파란 선택. 시(00~23)·분(00~55, 5분 단위) 두 열 — 브라우저 기본
// 시계처럼 돌아가지 않고 끝에서 멈춘다. 시 = 바꾸고 열어 둠, 분 = 바꾸고 닫음, [확인] = 지금 값 넣고 닫기,
// [지우기] = 비우고 닫기. opts: { value: "HH:MM"|"", onChange(v) }.
// 모달 대화창(dialog[open]) 안의 칸이면 그 창 **안에** popover(top layer)로 붙인다 — 창 밖(body)에 붙이면
// 모달 때문에 inert 라 휠·마우스 오버·클릭이 안 먹는다. 그 밖에는 body(배율 .pj-ui-scale 밖).
let timePopEl = null, timePopCleanup = null;
function closeTimePopover() {
if (timePopCleanup) timePopCleanup();
timePopCleanup = null;
if (timePopEl) {
try { if (timePopEl.matches(":popover-open")) timePopEl.hidePopover(); } catch (_) {}
timePopEl.remove(); timePopEl = null;
}
}
function openTimePopover(anchor, opts) {
closeTimePopover();
const pad2 = function (n) { return (n < 10 ? "0" : "") + n; };
const cur = /^\d{2}:\d{2}/.test(opts.value || "") ? opts.value.slice(0, 5) : "";
let h = cur ? cur.slice(0, 2) : "", m = cur ? cur.slice(3, 5) : "";
const hours = [], mins = [];
for (let i = 0; i < 24; i++) hours.push(pad2(i));
for (let i = 0; i < 60; i += 5) mins.push(pad2(i));
function col(kind, list, sel) {
return '<div class="pj-tp-col" data-kind="' + kind + '">' + list.map(function (v) {
return '<button type="button" class="pj-tp-item' + (v === sel ? " is-selected" : "") + '" data-v="' + v + '">' + v + "</button>";
}).join("") + "</div>";
}
const pop = document.createElement("div");
pop.className = "pj-datepop pj-timepop";
pop.innerHTML = '<div class="pj-dp-fields"><span class="pj-dp-field is-active pj-tp-value"></span></div>' +
'<div class="pj-tp-heads"><span>시</span><span>분</span></div>' +
'<div class="pj-tp-cols">' + col("h", hours, h) + col("m", mins, m) + "</div>" +
'<div class="pj-dp-foot"><button type="button" class="pj-dp-link" data-tp="clear">지우기</button>' +
'<button type="button" class="pj-dp-link" data-tp="ok">확인</button></div>';
function paintHead() { pop.querySelector(".pj-tp-value").textContent = (h || "--") + ":" + (m || "--"); }
paintHead();
const host = anchor.closest("dialog[open]");
if (host) { pop.setAttribute("popover", "manual"); host.appendChild(pop); try { pop.showPopover(); } catch (_) {} }
else document.body.appendChild(pop);
function emit(v) { if (opts.onChange) opts.onChange(v); }
function commit() { if (h) emit(h + ":" + (m || "00")); }
pop.addEventListener("click", function (e) {
const it = e.target.closest(".pj-tp-item");
if (it) {
const kind = it.parentNode.dataset.kind;
it.parentNode.querySelectorAll(".is-selected").forEach(function (x) { x.classList.remove("is-selected"); });
it.classList.add("is-selected");
if (kind === "h") { h = it.dataset.v; if (!m) m = "00"; } else { m = it.dataset.v; if (!h) h = "09"; }
paintHead(); commit();
if (kind === "m") { closeTimePopover(); anchor.focus(); }
return;
}
const act = e.target.closest("[data-tp]");
if (!act) return;
if (act.dataset.tp === "clear") emit(""); else commit();
closeTimePopover(); anchor.focus();
});
// 자리 — 앵커 아래(자리 없으면 위), 꼬리가 앵커 가운데(openDatePopover place 와 같음).
// 배율(zoom) 안의 dialog 에 붙었으면 left/top 값도 배율만큼 줄어 보이므로 나눠 준다(currentCSSZoom).
const z = pop.currentCSSZoom || 1;
const r = anchor.getBoundingClientRect();
const vw = document.documentElement.clientWidth, vh = document.documentElement.clientHeight;
const w = pop.offsetWidth * z, ph = pop.offsetHeight * z, ax = r.left + r.width / 2;
const left = Math.min(Math.max(8, ax - w / 2), vw - w - 8);
const below = r.bottom + 10 + ph <= vh - 8 || r.top - 10 - ph < 8;
pop.classList.toggle("is-above", !below);
pop.style.left = left / z + "px";
pop.style.top = (below ? r.bottom + 10 : r.top - 10 - ph) / z + "px";
pop.style.setProperty("--pj-dp-tail", Math.min(Math.max(ax - left, 16), w - 16) / z + "px");
// 고른 값이 보이게 — 열 안에서만 스크롤(맨 위 00 부터, 끝에서 멈춤)
pop.querySelectorAll(".pj-tp-col").forEach(function (c) {
const sel = c.querySelector(".is-selected");
if (sel) c.scrollTop = sel.offsetTop - c.offsetTop - (c.clientHeight - sel.offsetHeight) / 2;
});
function onDown(e) { if (!pop.contains(e.target) && !anchor.contains(e.target)) closeTimePopover(); }
function onKey(e) { if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closeTimePopover(); anchor.focus(); } }
document.addEventListener("pointerdown", onDown, true);
document.addEventListener("keydown", onKey, true);
window.addEventListener("resize", closeTimePopover);
timePopEl = pop;
timePopCleanup = function () {
document.removeEventListener("pointerdown", onDown, true);
document.removeEventListener("keydown", onKey, true);
window.removeEventListener("resize", closeTimePopover);
};
}
// <input type="time"> 를 시각 버튼으로 — 브라우저 기본 시계 대신 openTimePopover. input 은 숨긴 값 저장소
// (value 읽기/쓰기·change 이벤트 그대로, value 를 쓰면 버튼 글자도 바뀜 — enhanceDateInput 과 같은 방식).
function enhanceTimeInput(input, opts) {
if (!input || input.dataset.pjTime) return;
opts = opts || {};
input.dataset.pjTime = "1";
input.style.display = "none";
const btn = document.createElement("button");
btn.type = "button";
btn.className = "pj-time-btn";
btn.innerHTML = '<span class="pj-time-text"></span><span class="material-symbols-outlined">schedule</span>';
if (input.getAttribute("aria-label")) btn.setAttribute("aria-label", input.getAttribute("aria-label"));
input.after(btn);
const desc = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value");
Object.defineProperty(input, "value", {
configurable: true,
get: function () { return desc.get.call(this); },
set: function (v) { desc.set.call(this, v); sync(); },
});
function sync() {
const v = (input.value || "").slice(0, 5);
btn.querySelector(".pj-time-text").textContent = v || opts.placeholder || "시각 선택";
btn.classList.toggle("is-empty", !v);
btn.disabled = input.disabled;
btn.title = v ? "시각 변경" : "시각 지정";
}
btn.addEventListener("click", function (e) {
e.preventDefault();
if (timePopEl) { closeTimePopover(); return; }
openTimePopover(btn, {
value: input.value,
onChange: function (v) {
if ((input.value || "").slice(0, 5) === v) return;
input.value = v;
input.dispatchEvent(new Event("input", { bubbles: true }));
input.dispatchEvent(new Event("change", { bubbles: true }));
},
});
});
sync();
}
// ── 탭 그룹(뷰 탭/스코프 토글, 둘 다 .pj-view-tabs 마크업 공유)에 슬라이드
// 하이라이트를 붙인다 — is-active 를 단순 배경색 대신, 실제 위치가 움직이는
// 절대배치 요소 하나로 표현한다. 탭 클릭·초기 렌더·리사이즈마다 위치 재계산.
@@ -3230,8 +3375,8 @@
{
key: "due", label: "마감", cls: "pj-mtk-date",
html: function (t) {
if (!t.due_date) return "-";
const di = dueInfo(t.due_date, !!t.completed_at);
if (!t.due_date && !t.repeat_daily) return "-";
const di = dueInfo(t.due_date, !!t.completed_at, t.repeat_daily);
return '<span class="pj-due-label ' + di.cls + (di.cls === "is-overdue" ? " pj-mtk-overdue" : "") + '">' +
escapeHtml(di.text) + "</span>";
},
@@ -3479,6 +3624,8 @@
// 등급(2026-10-12) — isPro = Pro user 이상(프로젝트 수정·멤버 배정·전체 보기·담당자별 합계·남의 댓글 수정),
// isPAdmin = Admin 이상(남이 만든 섹션도 삭제).
const isPro = root.dataset.isPro === "true";
const canAllView = root.dataset.allView === "true";
const dailyReady = root.dataset.dailyReady === "1"; // 033 — 새 업무·세부 업무 추가 칸 날짜 팝업에도 [매일] // 왼쪽 "전체 보기" 메뉴 — Project 옵션 대상자(서버 pj_all_view)
const isPAdmin = root.dataset.isPadmin === "true";
// 시스템 Project 옵션(서버 project_options, 수퍼관리자·Admin 이 바꾸면 모든 사용자에게) — 보드 카드 표지 켬/끔.
// 옵션 창에서 저장하면 pj-options-change 로 바로 바뀐다(아래).
@@ -3653,7 +3800,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 +3962,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 +3976,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(); // 같은 화면 안에서 바로 전환
@@ -5101,9 +5248,10 @@
av.title = draft.assignee ? idOf(draft.assignee) : "담당자 지정";
}
function paintDue() {
const di = dueInfo(draft.due, false);
due.innerHTML = di ? escapeHtml(di.text) : DUE_EMPTY_ICON_SVG;
due.title = draft.due || "마감일 지정";
const di = dueInfo(draft.due, false, draft.daily);
due.innerHTML = !di ? DUE_EMPTY_ICON_SVG
: draft.daily ? '<span class="pj-due-label is-daily">' + escapeHtml(di.text) + "</span>" : escapeHtml(di.text);
due.title = draft.daily ? "매일 하는 업무" : draft.due || "마감일 지정";
}
function paintFol() {
fol.innerHTML = followerIconHtml(draft.followers);
@@ -5154,8 +5302,12 @@
});
due.addEventListener("click", function () {
openDatePopover(due, {
due: draft.due, allowStart: false,
onChange: function (patch) { if (!current()) return; draft.due = patch.due_date || null; paintDue(); refocus(); },
due: draft.due, allowStart: false, daily: !!draft.daily, allowDaily: dailyReady,
onChange: function (patch) {
if (!current()) return;
draft.due = patch.due_date || null; draft.daily = !!patch.repeat_daily;
paintDue(); refocus();
},
});
});
function close() {
@@ -5177,6 +5329,7 @@
assignee_email: draft.assignee, assignee_name: draft.assignee ? idOf(draft.assignee) : "",
due_date: draft.due || null,
followers: draft.followers,
...(draft.daily ? { repeat_daily: true } : {}),
});
if (!current()) return;
mergeTask(res.task);
@@ -5715,7 +5868,8 @@
// 없으면 applyTaskPatch 로 업무에 저장.
function openDuePicker(t, anchorEl, onPick) {
const save = onPick || function (patch) { applyTaskPatch(t, patch, "마감일 변경 실패"); };
openDatePopover(anchorEl, { start: t.start_date, due: t.due_date, allowStart: true, onChange: save });
openDatePopover(anchorEl, { start: t.start_date, due: t.due_date, allowStart: true,
daily: !!t.repeat_daily, allowDaily: "repeat_daily" in t, onChange: save }); // repeat_daily 키 = 033 적용됨
}
// ── 카드 세부 업무 펼치기(아사나처럼) — 카드의 "N ⤷ ▾" 버튼을 누르면 카드
@@ -5735,7 +5889,7 @@
});
}
function cardSubRowHtml(sub) {
const di = dueInfo(sub.due_date, !!sub.completed_at);
const di = dueInfo(sub.due_date, !!sub.completed_at, sub.repeat_daily);
return '<div class="pj-card-sub' + (sub.completed_at ? " is-done" : "") + '" data-sub-id="' + sub.id + '">' +
'<button type="button" class="pj-card-sub-check" title="' + (sub.completed_at ? "완료 취소" : "완료로 표시") + '">' +
'<span class="material-symbols-outlined">check_circle</span></button>' +
@@ -5743,7 +5897,7 @@
subMetaHtml(sub, "pj-card-sub-nsubs") +
// 마감일 — 있으면 날짜, 없으면 아사나처럼 점선 원 달력 아이콘(줄에 마우스를
// 올리면 보임). 둘 다 누르면 날짜 선택.
(sub.due_date
(di
? '<span class="pj-card-sub-due ' + di.cls + '" data-tip="' + dueTip(di) + '">' + escapeHtml(di.text) + "</span>"
: '<span class="pj-card-sub-due is-empty" data-tip="마감일 추가">' + DUE_EMPTY_ICON_SVG + "</span>") +
// 담당자 — 있으면 아바타, 없으면 아사나처럼 점선 원 사람 아이콘(줄에
@@ -6013,7 +6167,7 @@
if (!draft.followers) draft.followers = [];
inp.value = draft.title;
function paintDue() {
const di = dueInfo(draft.due, false);
const di = dueInfo(draft.due, false, draft.daily);
dueEl.className = "pj-card-sub-due pj-card-subnew-due" + (di ? " " + di.cls : " is-empty");
dueEl.innerHTML = di ? escapeHtml(di.text) : DUE_EMPTY_ICON_SVG;
dueEl.dataset.tip = di ? dueTip(di) : "마감일 지정";
@@ -6040,7 +6194,7 @@
draft.focused = document.activeElement === inp;
// 날짜 팝업·담당자 메뉴를 쓰는 중이면 닫지 않는다.
if (draft.focused || datePopEl || ctxMenuEl) return;
if (!draft.title.trim() && !draft.due && !draft.assignee && !draft.followers.length) closeDraft();
if (!draft.title.trim() && !draft.due && !draft.daily && !draft.assignee && !draft.followers.length) closeDraft();
}, 150);
});
inp.addEventListener("keydown", function (e) {
@@ -6050,9 +6204,9 @@
});
dueEl.addEventListener("click", function () {
openDatePopover(dueEl, {
due: draft.due, allowStart: false,
due: draft.due, allowStart: false, daily: !!draft.daily, allowDaily: dailyReady,
// 날짜를 고르면 팝업이 닫히므로 이어서 이름을 칠 수 있게 입력칸으로 돌아간다.
onChange: function (patch) { draft.due = patch.due_date || null; paintDue(); refocus(); },
onChange: function (patch) { draft.due = patch.due_date || null; draft.daily = !!patch.repeat_daily; paintDue(); refocus(); },
});
});
// 바깥을 누르면 Enter 와 같다 — 이름이 있으면 만들고 줄을 닫는다(아사나). 이름이 없으면
@@ -6071,7 +6225,7 @@
if (subDrafts[t.id] !== draft) return;
if (inp.isConnected) draft.title = inp.value;
if (draft.title.trim()) createFromDraft(false);
else if (!draft.due && !draft.assignee && !draft.followers.length) closeDraft();
else if (!draft.due && !draft.daily && !draft.assignee && !draft.followers.length) closeDraft();
}, 0);
}
if (subOutsideDown[t.id]) document.removeEventListener("pointerdown", subOutsideDown[t.id], true);
@@ -6120,6 +6274,7 @@
assignee_email: draft.assignee || "",
assignee_name: draft.assignee ? idOf(draft.assignee) : "",
followers: draft.followers,
...(draft.daily ? { repeat_daily: true } : {}),
});
const subs = subsCache[t.id] || (subsCache[t.id] = []);
// 새 줄 협업자 아이콘 — 서버 자동 협업자와 같은 규칙(만든 사람·담당자·고른 협업자)
@@ -6269,9 +6424,9 @@
// 누르면 서버에서 받아 멤버 메뉴. 한 번 받은(고른) 협업자는 이 화면에 머무는 동안 카드에 보인다(cardFollowers).
(canManage ? cardFolHtml(cardFollowers[t.id]) : "") +
(function () {
const di = dueInfo(t.due_date, !!t.completed_at);
const di = dueInfo(t.due_date, !!t.completed_at, t.repeat_daily);
return '<span class="pj-card-due pj-card-edit-hit' + (di ? " " + di.cls : " is-empty") +
'" title="' + (t.due_date ? dueTip(di) : "마감일 추가") + '">' +
'" title="' + (di ? dueTip(di) : "마감일 추가") + '">' +
// 마감일 없음 — 세부 업무 줄과 같은 점선 원 달력 아이콘만(카드에 마우스를 올리면 보임).
(di ? escapeHtml(di.text) : DUE_EMPTY_ICON_SVG) + "</span>";
})() +
@@ -6455,7 +6610,7 @@
{ key: "stage", label: "섹션", text: function (t) { return t.stage_name || "-"; }, sort: function (t) { return t.stage_name || ""; } },
{ key: "priority", label: "우선순위", text: function (t) { return priorityLabels[t.priority] || t.priority || "-"; }, sort: function (t) { return ({ low: 0, normal: 1, high: 2 })[t.priority]; } },
{ key: "start", label: "시작", text: function (t) { return t.start_date || "-"; }, sort: function (t) { return t.start_date || ""; } },
{ key: "due", label: "마감", text: function (t) { const di = dueInfo(t.due_date, !!t.completed_at); return di ? di.text : "-"; }, sort: function (t) { return t.due_date || ""; } },
{ key: "due", label: "마감", text: function (t) { const di = dueInfo(t.due_date, !!t.completed_at, t.repeat_daily); return di ? di.text : "-"; }, sort: function (t) { return t.due_date || ""; } },
];
// "이 프로젝트" 스코프 — 아사나 리스트 뷰처럼 세션이 컬럼이 아니라 그룹
// 구분선이 된다(renderListGrouped). 그래서 세션 컬럼은 뺀다.
@@ -6528,9 +6683,9 @@
tr.innerHTML = cols.map(function (c) {
let inner = escapeHtml(String(c.text(t)));
if (c.key === "title") inner += cmtBadge(t);
if (c.key === "due" && t.due_date) {
const di = dueInfo(t.due_date, !!t.completed_at);
inner = '<span class="pj-due-label ' + di.cls + '" title="' + t.due_date + '">' + escapeHtml(di.text) + "</span>";
if (c.key === "due" && (t.due_date || t.repeat_daily)) {
const di = dueInfo(t.due_date, !!t.completed_at, t.repeat_daily);
inner = '<span class="pj-due-label ' + di.cls + '" title="' + (t.due_date || "매일 하는 업무") + '">' + escapeHtml(di.text) + "</span>";
}
if (c.key === "assignee" && t.assignee_email) {
inner = '<span class="pj-assignee">' + avatarHtml(t.assignee_email, "pj-gicon-sm") + escapeHtml(idOf(t.assignee_email)) + "</span>";
@@ -7351,6 +7506,7 @@
body = { priority: el("pj-t-priority").value };
} else if (key === "due") {
body = { due_date: el("pj-t-due").value || null };
if (el("pj-t-due").dataset.daily) body.repeat_daily = el("pj-t-due").dataset.daily === "1";
}
if (!body) return Promise.resolve(true);
setAutoState("saving");
@@ -7756,6 +7912,8 @@
: (presetStageId != null ? presetStageId : (stages[0] ? stages[0].id : ""));
el("pj-t-priority").value = task ? (task.priority || "normal") : "normal";
el("pj-t-due").value = task ? (task.due_date || "") : "";
// 매일 하는 업무(033) — "" = 열 없음(미적용, [매일] 숨김), "0"/"1" = 꺼짐/켜짐
el("pj-t-due").dataset.daily = task && "repeat_daily" in task ? (task.repeat_daily ? "1" : "0") : "";
currentTaskData = task || null;
syncDueBtn(); // 완료 여부(지남 표시)를 보려면 currentTaskData 다음에
el("pj-delete-task").hidden = !task;
@@ -7872,12 +8030,16 @@
const v = el("pj-t-due").value;
const btn = el("pj-t-due-btn");
if (!btn) return;
const di = dueInfo(v, !!(currentTaskData && currentTaskData.completed_at));
const daily = el("pj-t-due").dataset.daily === "1";
const di = dueInfo(v, !!(currentTaskData && currentTaskData.completed_at), daily);
el("pj-t-due-text").textContent = di ? di.text : "";
btn.classList.toggle("has-date", !!v);
btn.classList.toggle("has-date", !!di);
btn.classList.toggle("is-daily", daily);
const ic = btn.querySelector(".material-symbols-outlined");
if (ic) ic.textContent = daily ? "repeat" : "calendar_month";
btn.classList.toggle("is-overdue", !!di && di.cls === "is-overdue");
btn.classList.toggle("is-soon", !!di && di.cls === "is-soon");
btn.title = v ? "마감일 " + v + " (눌러서 변경)" : "마감일 지정";
btn.title = daily ? "매일 하는 업무 (눌러서 변경)" : v ? "마감일 " + v + " (눌러서 변경)" : "마감일 지정";
}
if (el("pj-t-due-btn")) {
// 아사나식 날짜 팝업 — 숨긴 #pj-t-due 값을 바꾸고 change 를 보내면
@@ -7885,9 +8047,10 @@
el("pj-t-due-btn").addEventListener("click", function () {
const inp = el("pj-t-due");
openDatePopover(el("pj-t-due-btn"), {
due: inp.value, allowStart: false,
due: inp.value, allowStart: false, daily: inp.dataset.daily === "1", allowDaily: !!inp.dataset.daily,
onChange: function (patch) {
inp.value = patch.due_date || "";
if ("repeat_daily" in patch) inp.dataset.daily = patch.repeat_daily ? "1" : "0";
inp.dispatchEvent(new Event("change", { bubbles: true }));
},
});
@@ -9546,10 +9709,10 @@
checkBtn.title = sub.completed_at ? "완료 취소" : "완료로 표시";
}
function renderDue() {
const di = dueInfo(sub.due_date, !!sub.completed_at);
const di = dueInfo(sub.due_date, !!sub.completed_at, sub.repeat_daily);
dueEl.className = "pj-subtask-due" + (di ? " " + di.cls : " is-empty");
dueEl.innerHTML = di ? escapeHtml(di.text) : DUE_EMPTY_ICON_SVG;
dueEl.title = sub.due_date ? dueTip(di) : "마감일 추가";
dueEl.title = di ? dueTip(di) : "마감일 추가";
}
function renderAv() {
const e = sub.assignee_email || "";
@@ -9598,12 +9761,14 @@
dueEl.addEventListener("click", function (e) {
e.stopPropagation();
openDatePopover(dueEl, {
due: sub.due_date, allowStart: false,
due: sub.due_date, allowStart: false, daily: !!sub.repeat_daily, allowDaily: "repeat_daily" in sub,
onChange: async function (p) {
const prev = sub.due_date;
sub.due_date = p.due_date || null;
const prev = { due_date: sub.due_date, repeat_daily: sub.repeat_daily };
const body = { due_date: p.due_date || null };
if ("repeat_daily" in p) body.repeat_daily = p.repeat_daily;
Object.assign(sub, body);
renderDue();
if (!(await patch({ due_date: sub.due_date }))) { sub.due_date = prev; renderDue(); }
if (!(await patch(body))) { Object.assign(sub, prev); renderDue(); }
},
});
});
@@ -13547,14 +13712,14 @@
"<b>새 알림 " + items.length + "건</b>" +
'<button type="button" class="pj-btn pj-btn-sm" data-alert-close>닫기</button></div>' +
'<div class="pj-alert-list">' + items.map(function (n) {
const isMention = n.type === "mention";
const isMention = n.type === "mention", isDaily = n.type === "daily"; // daily = 매일 하는 업무(033) — 줄 배경 따로
// 서버가 준 주소(작업 = /project/t/{id} — 연결된 프로젝트에서만 읽을 수 있는 작업도 열린다)
const href = n.href || (n.task_id ? "/project/t/" + n.task_id
: n.project_id ? "/project/p/" + n.project_id : "/project/inbox");
return '<a class="pj-alert-item" href="' + escapeHtml(href) + '" data-alert-open="' + escapeHtml(n.id) + '">' +
'<span class="pj-alert-kind ' + (isMention ? "is-mention" : "is-assigned") + '">' +
(isMention ? "나를 태그" : "업무 배정") + "</span>" +
'<span class="pj-alert-text"><b>' + escapeHtml(String(n.title || "").replace(/^(나를 태그함|업무 배정|작업 배정):\s*/, "")) + "</b>" +
return '<a class="pj-alert-item' + (isDaily ? " is-daily" : "") + '" href="' + escapeHtml(href) + '" data-alert-open="' + escapeHtml(n.id) + '">' +
'<span class="pj-alert-kind ' + (isDaily ? "is-daily" : isMention ? "is-mention" : "is-assigned") + '">' +
(isDaily ? '<span class="material-symbols-outlined">repeat</span>매일 업무' : isMention ? "나를 태그" : "업무 배정") + "</span>" +
'<span class="pj-alert-text"><b>' + escapeHtml(String(n.title || "").replace(/^(나를 태그함|업무 배정|작업 배정|매일 업무):\s*/, "")) + "</b>" +
"<small>" + escapeHtml((n.body || "") + (n.actor_email ? " · " + capName(idOf(n.actor_email)) : "")) + "</small></span>" +
'<span class="pj-alert-go">열기 ›</span></a>';
}).join("") + "</div>";
@@ -13573,6 +13738,7 @@
// 공용 말풍선만 켠다(프로젝트 알림 팝업 확인·실시간 동기화 등이 그 화면에서 돌지 않게).
window.PJLib = {
createDescEditor: createDescEditor, enhanceDateInput: enhanceDateInput,
enhanceTimeInput: enhanceTimeInput, openTimePopover: openTimePopover, closeTimePopover: closeTimePopover,
memberPickHtml: memberPickHtml, showToast: showToast,
};
document.addEventListener("DOMContentLoaded", function () {
+6 -4
View File
@@ -225,13 +225,15 @@ namespace DbxNotifier
private void DrawRow(Graphics g, Alert a, RectangleF r, bool hover)
{
float s = _s;
if (hover) Fill(g, r, 10 * s, Gfx.Hex("#f5f6f8"));
// 매일 하는 업무 = 노란 줄 배경(웹 팝업 .pj-alert-item.is-daily 와 같은 색)
if (a.IsDaily) Fill(g, r, 10 * s, Gfx.Hex(hover ? "#ffedb8" : "#fff5d6"));
else if (hover) Fill(g, r, 10 * s, Gfx.Hex("#f5f6f8"));
string kind = a.IsMention ? "나를 태그" : "업무 배정";
string kind = a.IsDaily ? "매일 업무" : a.IsMention ? "나를 태그" : "업무 배정";
SizeF ks = g.MeasureString(kind, _fBadge, PointF.Empty, StringFormat.GenericTypographic);
var kr = new RectangleF(r.X + 10 * s, r.Y + (r.Height - 22 * s) / 2, ks.Width + 18 * s, 22 * s);
Fill(g, kr, 11 * s, a.IsMention ? Gfx.Hex("#eef2ff") : Gfx.Hex("#e7f6ec"));
DrawText(g, kind, _fBadge, a.IsMention ? Gfx.Hex("#4053c8") : Gfx.Hex("#1f8a4c"), kr, StringAlignment.Center);
Fill(g, kr, 11 * s, a.IsDaily ? Gfx.Hex("#f0a800") : a.IsMention ? Gfx.Hex("#eef2ff") : Gfx.Hex("#e7f6ec"));
DrawText(g, kind, _fBadge, a.IsDaily ? Color.White : a.IsMention ? Gfx.Hex("#4053c8") : Gfx.Hex("#1f8a4c"), kr, StringAlignment.Center);
const string go = "열기 ›";
SizeF gsz = g.MeasureString(go, _fGo, PointF.Empty, StringFormat.GenericTypographic);
+2 -1
View File
@@ -20,13 +20,14 @@ namespace DbxNotifier
public long ProjectId;
public bool IsMention => Type == "mention";
public bool IsDaily => Type == "daily"; // 매일 하는 업무(project_db 033) — 줄 배경을 따로
/// <summary>제목 앞 "나를 태그함: " / "업무 배정: "(예전 알림은 "작업 배정: ") 은 배지로 보여 주므로 뗀다(웹 팝업과 같게).</summary>
public string CleanTitle
{
get
{
foreach (string p in new[] { "나를 태그함:", "업무 배정:", "작업 배정:" })
foreach (string p in new[] { "나를 태그함:", "업무 배정:", "작업 배정:", "매일 업무:" })
if (Title.StartsWith(p, StringComparison.Ordinal)) return Title.Substring(p.Length).Trim();
return Title;
}
+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
+10
View File
@@ -426,6 +426,16 @@ cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres proj
cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_032_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_032_link_sort_order.sql && docker compose up --build -d --no-deps web
```
## 매일 하는 업무 마이그레이션 (project_db 033)
033은 `tasks` 에 `repeat_daily` 열(기본 false)과 부분 인덱스 하나만 추가한다(다시 실행 가능, 기존 값 변경 없음, 새 환경변수 없음).
날짜 팝업 [매일]·마감 칸 반복 아이콘·매일 업무 알림(Project 옵션 → 알림 시각, 영업일) — 미적용이면 앱은 예전 그대로([매일] 숨김, 알림 skip).
되돌리기 = `ALTER TABLE tasks DROP COLUMN repeat_daily;`(앱은 열이 없으면 예전 방식).
```bash
cd /opt/www/main && git pull && docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_033_$(date +%Y%m%d%H%M).sql && docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_033_repeat_daily.sql && docker compose up --build -d --no-deps web
```
## 안내문 발송 DM 본문 저장 마이그레이션 (outreach_db 002)
002는 `outreach_dm_bodies` 표 하나만 추가한다(다시 실행 가능, 기존 표·값 변경 없음, 새 환경변수 없음, `outreach_app` 에 CRUD·시퀀스 권한).
@@ -0,0 +1,17 @@
-- ════════════════════════════════════════════════════════════
-- 마이그레이션: 신규 세트 MY-1007 등록
-- malaysia_items 에 세트 MY-1007(kind='set')을 추가한다 — 재고 화면 세트 목록 노출용.
-- BOM(MT-1800·MT-2200·MT-3200 각 1개)은 itemcode_db.set_components 에 이미 있음(확인됨).
-- 구성 낱개 MT-1800/2200/3200 은 malaysia_items 에 이미 있음(확인됨).
-- 이름은 psql 변수 name 으로 받는다(itemcode_db.set_items.name). 비면 코드로.
-- NAME=$(docker exec postgres-db psql -U postgres -d itemcode_db -tAc "SELECT name FROM set_items WHERE item_code='MY-1007'")
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -v name="$NAME" -U postgres -d malaysia_stock_db < scripts/sql/malaysia_stock_db_add_my1007.sql
-- superuser/owner 로 실행. 멱등(재실행 시 이름·활성만 갱신, 순서 유지).
-- ════════════════════════════════════════════════════════════
INSERT INTO malaysia_items (item_code, item_name, kind, sort_order)
SELECT 'MY-1007', COALESCE(NULLIF(trim(:'name'), ''), 'MY-1007'), 'set',
(SELECT COALESCE(MAX(sort_order), 0) + 1 FROM malaysia_items)
ON CONFLICT (item_code) DO UPDATE
SET item_name = EXCLUDED.item_name,
kind = EXCLUDED.kind,
active = TRUE;
@@ -0,0 +1,19 @@
-- =====================================================================
-- project_db 마이그레이션 033 — 매일 하는 업무(마감일 없이 매일 반복)
-- =====================================================================
-- 멱등(idempotent). tasks 에 repeat_daily 열 하나만 추가(기존 값 변경 없음, 새 환경변수 없음).
-- 운영: /opt/www/main 에서 기존 project_db 에 적용(적용 전 pg_dump 백업).
--
-- 날짜 팝업 [매일]로 켠다 — 켜면 마감일·마감 시각은 비운다(마감일을 고르면 다시 꺼짐).
-- 마감일 칸에는 반복 아이콘, 알림 데몬(reminders.py)이 Project 옵션 daily_alert_times 시각마다(영업일)
-- 담당자(없으면 협업자)에게 "매일 업무" 알림(type=daily)을 만든다 — 중복 방지는 기존 task_reminders
-- (kind = 'daily@HH:MM', due_date = 그날).
-- 미적용이면 앱은 예전 그대로(날짜 팝업에 [매일] 없음, 매일 알림 skip).
-- 되돌리기: ALTER TABLE tasks DROP COLUMN repeat_daily;
-- =====================================================================
BEGIN;
ALTER TABLE tasks ADD COLUMN IF NOT EXISTS repeat_daily BOOLEAN NOT NULL DEFAULT false;
CREATE INDEX IF NOT EXISTS idx_tasks_repeat_daily_open ON tasks (id) WHERE repeat_daily AND completed_at IS NULL;
COMMIT;
+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"])
+62
View File
@@ -0,0 +1,62 @@
"""매일 하는 업무(033 tasks.repeat_daily) 알림 — 시각 고르기·수신자·중복. DB 없이 가짜 저장소로.
실제 DB(열·update_task 규칙)는 tests/test_project_module.py test_repeat_daily_* 가 본다.
"""
import importlib
import unittest
from datetime import date
from unittest.mock import patch
rem = importlib.import_module("app.modules.project.reminders")
class FakeStore:
def __init__(self, tasks):
self.tasks = tasks
self.sent = set()
self.made = []
def list_open_daily_tasks(self):
return list(self.tasks)
def add_reminder_notification(self, **kw):
key = (kw["task_id"], kw["kind"], kw["due_date"], kw["recipient_email"])
if key in self.sent:
return False
self.sent.add(key)
self.made.append(kw)
return True
def _visible(st, task, wanted, lookup=None):
return [e for e in wanted if e != "gone@x.kr"] # 권한 잃은 사람은 뺀다
class DailyAlertTests(unittest.TestCase):
def test_slot_is_latest_passed_time(self):
self.assertIsNone(rem.daily_slot(["09:00", "14:00"], "08:59"))
self.assertEqual(rem.daily_slot(["09:00", "14:00"], "09:00"), "09:00")
self.assertEqual(rem.daily_slot(["09:00", "14:00"], "23:59"), "14:00")
self.assertIsNone(rem.daily_slot([], "12:00"))
def test_assignee_else_followers_once_per_slot(self):
st = FakeStore([
{"id": 1, "title": "청소", "assignee_email": "A@x.kr", "followers": ["b@x.kr"], "project_id": 7, "project_name": "P"},
{"id": 2, "title": "보고", "assignee_email": "", "followers": ["b@x.kr", "gone@x.kr"], "project_id": 7},
])
with patch.object(rem.access, "filter_recipients", side_effect=_visible):
self.assertEqual(rem.run_daily_alerts(st, today=date(2026, 11, 11), slot="09:00"), 2)
self.assertEqual(rem.run_daily_alerts(st, today=date(2026, 11, 11), slot="09:00"), 0) # 같은 시각은 한 번
self.assertEqual(rem.run_daily_alerts(st, today=date(2026, 11, 11), slot="14:00"), 2) # 다음 시각은 또
first = st.made[0]
self.assertEqual((first["recipient_email"], first["kind"], first["ntype"]), ("a@x.kr", "daily@09:00", "daily"))
self.assertEqual(first["title"], "매일 업무: 청소")
self.assertEqual({m["recipient_email"] for m in st.made if m["task_id"] == 2}, {"b@x.kr"})
def test_daily_is_popup_alert_type(self):
api = importlib.import_module("app.modules.project.router")
self.assertIn("daily", api._ALERT_TYPES)
if __name__ == "__main__":
unittest.main()
+36
View File
@@ -1653,6 +1653,42 @@ def test_reorder_keeps_linked_card_position():
assert ST.get_task(task_id=lk["id"])["sort_order"] == lk["sort_order"]
def test_repeat_daily_task_and_alerts():
"""매일 하는 업무(2026-11-11, 마이그레이션 033) — [매일]이면 마감일을 비우고, 마감일을 고르면 꺼짐.
알림 데몬은 미완료 매일 업무의 담당자에게 시각마다 한 번(type=daily, 큰 팝업)."""
from datetime import date as _d
from app.modules.project import reminders
a = _project("P-daily", ADMIN, (ALICE,))
sa = _stage(a["id"], by=ADMIN)
t = ST.create_task(project_id=a["id"], title="매일 청소", stage_id=sa["id"], assignee_email=ALICE,
due_date="2026-12-01", created_by=ALICE)
r = req("PUT", f"/project/api/tasks/{t['id']}", ALICE, json={"due_date": None, "repeat_daily": True})
assert r.status_code == 200, r.text
got = r.json()["task"]
assert got["repeat_daily"] is True and got["due_date"] is None, got
assert req("PUT", f"/project/api/tasks/{t['id']}", ALICE, json={"repeat_daily": "yes"}).status_code == 400
assert t["id"] in [x["id"] for x in ST.list_open_daily_tasks()]
today = _d(2026, 11, 11)
assert reminders.run_daily_alerts(ST, today=today, slot="09:00") >= 1
assert reminders.run_daily_alerts(ST, today=today, slot="09:00") == 0 # 같은 시각은 한 번
alerts = req("GET", "/project/api/notifications/alerts?after=0", ALICE).json()["alerts"]
assert any(n["type"] == "daily" and n["task_id"] == t["id"] for n in alerts), alerts
# 마감일을 고르면 매일 반복은 꺼진다(repeat_daily 를 안 보내도)
got = req("PUT", f"/project/api/tasks/{t['id']}", ALICE, json={"due_date": "2026-12-05"}).json()["task"]
assert got["repeat_daily"] is False and got["due_date"] == "2026-12-05", got
assert t["id"] not in [x["id"] for x in ST.list_open_daily_tasks()]
# 추가 칸(보드 새 업무·세부 업무)에서 [매일]로 만들기 — POST repeat_daily
r = req("POST", f"/project/api/projects/{a['id']}/tasks", ALICE,
json={"title": "매일 점검", "stage_id": sa["id"], "due_date": None, "repeat_daily": True})
assert r.status_code == 201, r.text
assert r.json()["task"]["repeat_daily"] is True and "_newly_assigned" not in r.json()["task"]
r = req("POST", f"/project/api/projects/{a['id']}/tasks", ALICE,
json={"title": "세부 매일", "parent_task_id": t["id"], "repeat_daily": True})
assert r.status_code == 201 and r.json()["task"]["repeat_daily"] is True, r.text
assert req("POST", f"/project/api/projects/{a['id']}/tasks", ALICE, json={"title": "x", "repeat_daily": 1}).status_code == 400
assert ST.daily_ready() is True
def test_move_stage_to_other_project():
"""섹션째 다른 프로젝트로(2026-10-26) — 섹션 + 업무 + 세부 업무(모든 단계), 섹션은 맨 끝, 연결 정리, 권한."""
a = _project("P-smA", ADMIN, (ALICE, BOB))
+42 -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,52 @@ 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_daily_alert_times(self):
self.assertEqual(D["daily_alert_times"], ["09:00"])
out = store.normalize_project_options({"daily_alert_times": ["14:00", "9:00", "09:00"]})
self.assertEqual(out["daily_alert_times"], ["09:00", "14:00"])
self.assertEqual(store.normalize_project_options({"daily_alert_times": []})["daily_alert_times"], []) # 빈 목록 = 끔
self.assertEqual(store.normalize_project_options({"daily_alert_times": ["25:00"]})["daily_alert_times"], ["09:00"])
self.assertEqual(store.validate_project_options({"daily_alert_times": ["18:30", "08:05"]}),
{"daily_alert_times": ["08:05", "18:30"]})
for bad in ("09:00", ["9시"], [""], [None], ["24:00"], ["09:00"] * 0 + [f"{h:02d}:00" for h in range(13)]):
with self.subTest(bad=bad), self.assertRaises(ValueError):
store.validate_project_options({"daily_alert_times": bad})
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 +104,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 +112,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 +123,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):