Compare commits
91 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 89ad338024 | |||
| c07a3466a0 | |||
| 5d054e59b6 | |||
| 061f18d081 | |||
| ee9c04147a | |||
| 6a1c437635 | |||
| 8045d06362 | |||
| 85e91ca882 | |||
| 11e9803965 | |||
| 90fb06c48c | |||
| ac3b90f2be | |||
| a664c4a9fc | |||
| 64aabdfbda | |||
| 98fda9923e | |||
| 53c7c85caf | |||
| c380b5e411 | |||
| 84113d1fd7 | |||
| 4715de9b5b | |||
| d7d4f61bfb | |||
| 69e594ac54 | |||
| f69219919d | |||
| 972c94d86c | |||
| f4606bddc6 | |||
| 06af036f86 | |||
| 8f46d6c13a | |||
| 701f43a1f8 | |||
| 9eea1a073a | |||
| 5278d568de | |||
| 21fc78adb9 | |||
| 4bdab1de3d | |||
| f90884e028 | |||
| 6959941128 | |||
| 18dd9531ad | |||
| 28d56fc3c5 | |||
| b8d944b3ef | |||
| a0722f26ca | |||
| 261267a523 | |||
| da27c9990a | |||
| 50153139fc | |||
| c4fb7761ad | |||
| fb7b25ba2c | |||
| e9be17faab | |||
| 133df472d1 | |||
| 569b33ece4 | |||
| 452e8a9093 | |||
| 1cfcec2bef | |||
| 2d638804d1 | |||
| b6dc82c0b3 | |||
| 2a01d97dd0 | |||
| fc3a2d0b9b | |||
| c766af691a | |||
| b7c24c07e7 | |||
| fbb6c648a5 | |||
| 8b664fc216 | |||
| 5f10f9ce45 | |||
| 46dc038e26 | |||
| c0b742af8a | |||
| 80c9904771 | |||
| 8885bbce6b | |||
| e9618d93d6 | |||
| cbf59d9bf0 | |||
| c9d5e6e017 | |||
| 15e84ba5bc | |||
| 3045944200 | |||
| e1f50e0ca5 | |||
| 9528f735b8 | |||
| 7417e661e0 | |||
| 38d0a87d6b | |||
| cd3577b299 | |||
| 9194487217 | |||
| e958743e65 | |||
| 85cf0a28b1 | |||
| 39dcda66b4 | |||
| f09b8fa2f9 | |||
| df36a5a917 | |||
| d18e801e08 | |||
| b576dd1a38 | |||
| bd0c47e6fc | |||
| 75c0370e54 | |||
| a2a39671b9 | |||
| 2a1a3e7bd9 | |||
| 5bf8c9c160 | |||
| 86622cc4dd | |||
| ed7da57066 | |||
| e2fc14a584 | |||
| d89875db7e | |||
| 321bf11f65 | |||
| 3e4c6dfad3 | |||
| d3c1ca12e9 | |||
| 090e508bf3 | |||
| 193da56edf |
@@ -43,6 +43,12 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# GOOGLE_SHEETS_CREDENTIALS=/opt/www/main/secrets/google-sheets-sa.json
|
||||
# 또는 파일 대신 JSON 본문을 통째로 (한 줄):
|
||||
# GOOGLE_SHEETS_CREDENTIALS_JSON={"type":"service_account", ...}
|
||||
#
|
||||
# 주간 회의록 "회의록 보드"(주차마다 빈 Google 슬라이드) — 위 Google 인증을 같이 쓴다.
|
||||
# OAuth 토큰은 Drive·Slides 권한까지 필요: scripts/google_sheets_authorize.py 로 다시 발급(시트 권한도 함께 들어감)
|
||||
# Cloud Console 에서 Google Drive API·Google Slides API 사용 설정. 서비스 계정이면 공유 드라이브 콘텐츠 관리자로 추가.
|
||||
# GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN=replace-me # 비우면 GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN 사용
|
||||
# MEETING_BOARD_FOLDER_ID=0AGF3CIEboPQiUk9PVA # 보드를 만들 공유 드라이브(폴더) ID — 비우면 이 기본값
|
||||
|
||||
# ─── 휴가 관리 모듈 (vacation_db) ───
|
||||
# 설정해야 모듈이 동작한다(미설정 시 "설정 필요" 안내, JSON 폴백 없음).
|
||||
@@ -163,3 +169,7 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# APP_ENCRYPTION_KEY_V1=
|
||||
# [매출 업데이트] 가 가져오는 기간(오늘 포함 최근 N일, 기본 7, 최대 90)
|
||||
# PERFORMANCE_SYNC_DAYS=7
|
||||
|
||||
# 자산관리 — 별도 asset_db. 사용자가 서버에서 asset_db_init.sql로 직접 초기화.
|
||||
# 미설정 시 등록/배정은 비활성, HWiNFO XML 분석 미리보기는 사용 가능.
|
||||
# ASSET_DB_URL=postgresql://asset_app:replace-me@postgres-db:5432/asset_db
|
||||
|
||||
@@ -16,3 +16,6 @@ PUBLIC_BASE_URL=http://localhost:8080
|
||||
|
||||
CS_ORDER_URL=https://cs.example.com
|
||||
CUSTOMER_ORDER_LIST_URL=https://orders.example.com
|
||||
|
||||
# 자산관리 개발용 DB (사용자가 직접 생성). 운영 DB 접속정보를 사용하지 마세요.
|
||||
# ASSET_DB_URL=postgresql://asset_app:replace-me@host.docker.internal:5432/asset_db
|
||||
|
||||
@@ -24,3 +24,6 @@ __pycache__/
|
||||
# dispatch 라벨 PDF 샘플(실제 고객 PII — 커밋 금지)
|
||||
docs/samples/
|
||||
tests/js/.out/
|
||||
|
||||
# HWiNFO 실물 보고서: 시리얼/MAC/사용자 정보가 포함되어 소스에 보관하지 않음
|
||||
KING-DESKTOP.XML
|
||||
|
||||
@@ -36,10 +36,15 @@ Codex는 이 저장소에서 작업을 시작하기 전에 **반드시 아래
|
||||
- 말레이시아 창고 재고관리 (`app/modules/malaysia/`, `malaysia_stock_db`) — 낱개(MT/MX/MZ) 입출고·조정, 세트(MY) BOM, 일일 재고조사(세트→낱개 자동 분해), 현재고 현황. 뚜껑(MD-)은 재고 집계 제외 — 단, 창고 랙에는 위치 확인용으로 배치 가능(`store.LID_ITEMS`). 상품은 `itemcode_db` 읽기 전용. 권한키 `malaysia`
|
||||
- 말레이시아 배송 (`app/modules/dispatch/`, `dispatch_db`) — TikTok·Shopee 출고관리. 플랫폼별 데이터 엑셀 업로드(TikTok=03_TikTok_Order_Export.xlsx, Shopee=Packing List.Doorstep Delivery.xlsx) → 1박스=1카드 출고 작업 리스트·SKU 피킹 요약·Kagayaku 전달표 자동 생성. 1박스 묶음 기준 Package ID > Tracking ID > Order ID, 같은 박스 같은 SKU 합산. 작업 상태 토글(`dispatch_logs` 기록). 받는 사람 이름/전화/주소는 박스 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용 — 개인정보). 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함. 엑셀은 openpyxl 파싱/생성. 권한키 `dispatch`. 상세는 `docs/DISPATCH_MODULE.md`
|
||||
- 카페24 상품관리 (`app/modules/cafe24/`, `cafe24_db`) — 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·자동복원·버전 롤백·일괄수정. 카페24 OAuth/API 클라이언트는 향후 주문관리와 공유하기 위해 **공통 계층 `app/integrations/cafe24/`** 에 둔다 — 라우터에서 `httpx`/`requests` 직접 호출 금지. 토큰은 Fernet 암호화 저장(`CAFE24_TOKEN_SECRET`), 로그/화면에 토큰·시크릿 절대 미출력. 쓰기 직전 항상 카페24 현재 HTML 을 다시 읽어 `BACKUP` revision 생성(로컬 값을 현재값으로 가정 금지). 예약은 DB 저장 + 별도 worker(`app/modules/cafe24/worker.py`, compose 서비스 `dbx-cafe24-worker`)가 처리 — 웹 프로세스에서 대기하지 않는다. 권한키 `cafe24`(연결/해제는 admin 전용). 상세는 `docs/CAFE24_MODULE.md`
|
||||
- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 생성시 기본 4단계 seed)·멤버 배정(`project_members`)·활동이력(`project_activity`). 메인 뷰 달력(FullCalendar)/타임라인(vis-timeline) 버튼 토글 + 보드(드래그로 단계 이동)/리스트. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 프로젝트 생성/삭제·사용자 배정은 `is_admin` 만, 배정 멤버(또는 owner)는 서브프로젝트/업무/단계 CRUD. 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md`
|
||||
- 프로젝트 관리 (`app/modules/project/`, `project_db`) — 아사나식. 프로젝트/서브프로젝트(self-FK `parent_id`, CASCADE)·업무(`tasks`: 담당자·우선순위·시작/마감)·진행단계(`project_stages` 칸반, 새 프로젝트는 섹션 없이 시작)·멤버 배정(`project_members`)·활동이력(`project_activity`). 메인 뷰 달력(FullCalendar)/타임라인(vis-timeline) 버튼 토글 + 보드(드래그로 단계 이동)/리스트. 진입 권한키 `project`(관리자 페이지 토글로 직원별 부여, admin 자동). 권한은 등급(수퍼관리자 > Admin > Pro user > User, 2026-10-12)과 멤버십 기준 — 표는 `docs/PROJECT_MODULE.md` 6-14, 공통 판단 `access.py`(관리자도 멤버가 아니면 프로젝트가 안 보임, 예외는 수퍼관리자). 멤버 배정 후보는 `project` 권한 보유 등록 사용자에서 자동 목록(`GET /project/api/assignable-users`). 업무 배정·완료 시 관리자에게 메일(`app/mail.py` stdlib smtplib, `SMTP_*`+`PROJECT_NOTIFY_EMAIL` env, 미설정 시 조용히 skip, `BackgroundTasks` 비동기). 상세는 `docs/PROJECT_MODULE.md`
|
||||
|
||||
상세는 `docs/PROJECT_OVERVIEW.md`.
|
||||
|
||||
- 자산관리 (`app/modules/asset/`, `asset_db`) — 사무집기·전산장비 등록/배정/반납/상태·구매/보증·이력.
|
||||
HWiNFO XML 분석·사양 조회·이전 보고서와 원본 보존. 권한키 `asset`, 환경변수 `ASSET_DB_URL`.
|
||||
사진 등록/갤러리·모니터 자산 조회/등록/연결·수퍼 관리자 삭제(이력/원본 보존). 기존 설치는 마이그레이션 `asset_db_002_photos_monitors.sql` 필요.
|
||||
DB 미설정 시 저장 비활성, XML 분석 미리보기 가능. DB 생성은 사용자가 서버 명령으로 직접 진행. 상세 `docs/ASSET_MODULE.md`.
|
||||
|
||||
---
|
||||
|
||||
## 개발 원칙
|
||||
@@ -47,7 +52,7 @@ Codex는 이 저장소에서 작업을 시작하기 전에 **반드시 아래
|
||||
- 기존 코드를 수정하기 전 관련 파일을 먼저 읽고 구조를 파악한다.
|
||||
- 위험 명령은 **반드시 사용자 확인 후** 실행한다 (아래 "위험 명령" 절 참고).
|
||||
- `.env`, API 키, DB 비밀번호, OAuth Secret, 토큰은 절대 Git에 올리지 않는다.
|
||||
- 신규 DB가 필요하면 **승인 요청 후** 생성하며, DB명은 반드시 `_db`로 끝낸다 (예: `inventory_db`).
|
||||
- 신규 DB가 필요하면 **서버에서 실행할 명령을 제공하고 생성은 사용자가 직접 진행한다** (사용자 지시: 2026-10-06). DB명은 반드시 `_db`로 끝낸다 (예: `inventory_db`). 대상 서버·현재 DB·백업 상태와 생성 후 스키마·앱 계정 권한·연결 확인 명령을 함께 제공한다. 기존 DB 삭제·덮어쓰기 등 위험 명령은 아래의 별도 승인 원칙을 그대로 따른다.
|
||||
- 예전 문서/코드의 `orderlist_app`은 현재 기준 `orderlist_db`이다. 발견 시 수정 대상.
|
||||
|
||||
---
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Google 슬라이드(회의록 보드) 공통 계층 — 공유 드라이브 폴더에 빈 슬라이드를 만들거나 찾는다.
|
||||
|
||||
인증은 google_sheets 와 같은 설정을 쓰되 권한 범위(scope)가 다르다(Drive + Slides).
|
||||
설정된 쪽을 자동 선택(서비스 계정 우선).
|
||||
|
||||
1) 사용자 OAuth 리프레시 토큰
|
||||
· `GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN` — 없으면 `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN`
|
||||
토큰은 Drive·Slides 권한까지 받아야 한다: `python scripts/google_sheets_authorize.py`(스프레드시트·Drive·Slides 한 번에)
|
||||
· `GOOGLE_SHEETS_OAUTH_CLIENT_ID` / `..._SECRET`(없으면 로그인용 `GOOGLE_CLIENT_ID` / `GOOGLE_CLIENT_SECRET`)
|
||||
2) 서비스 계정 JSON — `GOOGLE_SHEETS_CREDENTIALS` / `GOOGLE_SHEETS_CREDENTIALS_JSON`
|
||||
서비스 계정 이메일을 대상 공유 드라이브의 **콘텐츠 관리자** 이상으로 추가해야 한다.
|
||||
|
||||
- 회의록 보드 폴더: `MEETING_BOARD_FOLDER_ID`(기본 = 회의록 보드 공유 드라이브).
|
||||
- 같은 주차 보드를 다시 누르면 새로 만들지 않고 Drive 파일 appProperties(`dbxMeetingWeek` = 주차 시작일)로 찾는다
|
||||
— 파일 이름을 바꿔도 같은 보드가 열린다. 휴지통에 버리면 다음에 새로 만든다.
|
||||
- 비밀값(키/토큰)은 로그·화면에 절대 출력하지 않는다. 라이브러리·설정이 없으면 `enabled = False`.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
from typing import Any
|
||||
|
||||
SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/presentations"]
|
||||
TOKEN_URI = "https://oauth2.googleapis.com/token"
|
||||
DEFAULT_BOARD_FOLDER_ID = "0AGF3CIEboPQiUk9PVA"
|
||||
PRESENTATION_MIME = "application/vnd.google-apps.presentation"
|
||||
WEEK_KEY = "dbxMeetingWeek"
|
||||
|
||||
# googleapiclient 의 HTTP 클라이언트는 스레드 안전하지 않고, 같은 주차를 두 사람이 동시에 누르면
|
||||
# 보드가 두 개 생길 수 있으므로 찾기·만들기는 한 번에 하나씩.
|
||||
_LOCK = threading.Lock()
|
||||
|
||||
|
||||
class GoogleSlidesError(RuntimeError):
|
||||
"""화면에 보여도 되는 사유(비밀값 없음)."""
|
||||
|
||||
|
||||
def board_folder_id() -> str:
|
||||
return (os.getenv("MEETING_BOARD_FOLDER_ID") or "").strip() or DEFAULT_BOARD_FOLDER_ID
|
||||
|
||||
|
||||
def board_url(file_id: str) -> str:
|
||||
return f"https://docs.google.com/presentation/d/{file_id}/edit"
|
||||
|
||||
|
||||
class GoogleSlidesClient:
|
||||
def __init__(self) -> None:
|
||||
self.enabled = False
|
||||
self.reason = ""
|
||||
self.auth_mode = ""
|
||||
self._drive: Any = None
|
||||
self._slides: Any = None
|
||||
try:
|
||||
from googleapiclient.discovery import build
|
||||
except ImportError:
|
||||
self.reason = "google-api-python-client 미설치"
|
||||
return
|
||||
creds = self._service_account_creds()
|
||||
if creds is None:
|
||||
creds = self._oauth_creds()
|
||||
if creds is None:
|
||||
if not self.reason:
|
||||
self.reason = "Google 인증 미설정(GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN 또는 GOOGLE_SHEETS_* 설정 필요)"
|
||||
return
|
||||
try:
|
||||
self._drive = build("drive", "v3", credentials=creds, cache_discovery=False)
|
||||
self._slides = build("slides", "v1", credentials=creds, cache_discovery=False)
|
||||
except Exception as exc: # noqa: BLE001 — 사유만(비밀값 미출력)
|
||||
self.reason = f"Google 클라이언트 생성 실패: {type(exc).__name__}"
|
||||
return
|
||||
self.enabled = True
|
||||
|
||||
# ── 인증(google_sheets 와 같은 설정, 범위만 Drive·Slides) ──
|
||||
def _service_account_creds(self) -> Any:
|
||||
raw = (os.getenv("GOOGLE_SHEETS_CREDENTIALS_JSON") or "").strip()
|
||||
path = (os.getenv("GOOGLE_SHEETS_CREDENTIALS") or "").strip()
|
||||
if not raw and not path:
|
||||
return None
|
||||
try:
|
||||
info = json.loads(raw) if raw else json.loads(open(path, encoding="utf-8").read())
|
||||
from google.oauth2.service_account import Credentials
|
||||
|
||||
creds = Credentials.from_service_account_info(info, scopes=SCOPES)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
self.reason = f"서비스 계정 인증 실패: {type(exc).__name__}"
|
||||
return None
|
||||
self.auth_mode = "service_account"
|
||||
return creds
|
||||
|
||||
def _oauth_creds(self) -> Any:
|
||||
token = (os.getenv("GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN") or os.getenv("GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN") or "").strip()
|
||||
if not token:
|
||||
return None
|
||||
cid = (os.getenv("GOOGLE_SHEETS_OAUTH_CLIENT_ID") or os.getenv("GOOGLE_CLIENT_ID") or "").strip()
|
||||
secret = (os.getenv("GOOGLE_SHEETS_OAUTH_CLIENT_SECRET") or os.getenv("GOOGLE_CLIENT_SECRET") or "").strip()
|
||||
if not cid or not secret:
|
||||
self.reason = "GOOGLE_SHEETS_OAUTH_CLIENT_ID/SECRET 미설정"
|
||||
return None
|
||||
try:
|
||||
from google.oauth2.credentials import Credentials
|
||||
|
||||
creds = Credentials(token=None, refresh_token=token, token_uri=TOKEN_URI,
|
||||
client_id=cid, client_secret=secret, scopes=SCOPES)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
self.reason = f"OAuth 자격 생성 실패: {type(exc).__name__}"
|
||||
return None
|
||||
self.auth_mode = "oauth"
|
||||
return creds
|
||||
|
||||
# ────────────────────────────────────────────────
|
||||
def open_week_board(self, *, folder_id: str, week_key: str, title: str) -> dict[str, Any]:
|
||||
"""그 주차 보드(빈 슬라이드)를 찾고, 없으면 폴더에 만든다 → {id, url, created}."""
|
||||
if not self.enabled:
|
||||
raise GoogleSlidesError(self.reason or "Google 슬라이드 연동이 꺼져 있습니다.")
|
||||
with _LOCK:
|
||||
try:
|
||||
found = self._find(folder_id, week_key)
|
||||
if found:
|
||||
return {"id": found, "url": board_url(found), "created": False}
|
||||
file_id = self._create_blank(folder_id, week_key, title)
|
||||
except GoogleSlidesError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001
|
||||
raise GoogleSlidesError(_friendly(exc)) from None
|
||||
return {"id": file_id, "url": board_url(file_id), "created": True}
|
||||
|
||||
def _find(self, folder_id: str, week_key: str) -> str | None:
|
||||
q = (f"'{folder_id}' in parents and trashed = false and mimeType = '{PRESENTATION_MIME}' "
|
||||
f"and appProperties has {{ key='{WEEK_KEY}' and value='{week_key}' }}")
|
||||
res = self._drive.files().list(
|
||||
q=q, fields="files(id)", pageSize=1, supportsAllDrives=True, includeItemsFromAllDrives=True,
|
||||
corpora="allDrives",
|
||||
).execute()
|
||||
files = res.get("files") or []
|
||||
return files[0]["id"] if files else None
|
||||
|
||||
def _create_blank(self, folder_id: str, week_key: str, title: str) -> str:
|
||||
meta = {"name": title, "mimeType": PRESENTATION_MIME, "parents": [folder_id],
|
||||
"appProperties": {WEEK_KEY: week_key}}
|
||||
file_id = self._drive.files().create(body=meta, fields="id", supportsAllDrives=True).execute()["id"]
|
||||
# 새 프레젠테이션의 첫 장은 "제목·부제목" 틀(TITLE 레이아웃) — 틀 없는 빈 장(BLANK) 하나만 남긴다
|
||||
pres = self._slides.presentations().get(presentationId=file_id, fields="slides.objectId").execute()
|
||||
reqs: list[dict[str, Any]] = [{"createSlide": {"insertionIndex": 0, "slideLayoutReference": {"predefinedLayout": "BLANK"}}}]
|
||||
reqs += [{"deleteObject": {"objectId": s["objectId"]}} for s in pres.get("slides") or []]
|
||||
self._slides.presentations().batchUpdate(presentationId=file_id, body={"requests": reqs}).execute()
|
||||
return file_id
|
||||
|
||||
|
||||
def _friendly(exc: Exception) -> str:
|
||||
"""Google API 오류 → 화면용 문구(비밀값·원문 응답 미포함)."""
|
||||
status = getattr(getattr(exc, "resp", None), "status", None)
|
||||
text = str(exc)
|
||||
# 토큰 갱신 실패(RefreshError) — Google 이 준 OAuth 오류 코드(비밀값 아님)를 보여 원인을 바로 알 수 있게
|
||||
m = re.search(r"\b(invalid_scope|invalid_grant|invalid_client|unauthorized_client|deleted_client|access_denied|invalid_request)\b", text)
|
||||
code = m.group(1) if m else ""
|
||||
if code in ("unauthorized_client", "invalid_client", "deleted_client"):
|
||||
return (f"Google 토큰 갱신 실패({code}) — 토큰을 발급한 OAuth 클라이언트와 서버 .env 의 "
|
||||
"GOOGLE_SHEETS_OAUTH_CLIENT_ID/SECRET(없으면 GOOGLE_CLIENT_ID/SECRET)이 다릅니다.")
|
||||
if "invalid_scope" in text or "insufficient" in text.lower() or "ACCESS_TOKEN_SCOPE_INSUFFICIENT" in text:
|
||||
return "Google 권한(Drive·Slides)이 없는 토큰입니다. 토큰을 다시 발급해 주세요(scripts/google_sheets_authorize.py)."
|
||||
if "invalid_grant" in text:
|
||||
return "Google 토큰이 만료·폐기되었습니다. 토큰을 다시 발급해 주세요."
|
||||
if status == 404:
|
||||
return "회의록 보드 폴더를 찾을 수 없습니다(MEETING_BOARD_FOLDER_ID·공유 드라이브 접근 권한 확인)."
|
||||
if status == 403:
|
||||
return "Google Drive·Slides 접근이 거부되었습니다(API 사용 설정·공유 드라이브 권한 확인)."
|
||||
return f"Google 슬라이드 처리 실패({type(exc).__name__}{f' {status}' if status else ''}{f' {code}' if code else ''})."
|
||||
|
||||
|
||||
_CLIENT: GoogleSlidesClient | None = None
|
||||
_CLIENT_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def get_client() -> GoogleSlidesClient:
|
||||
"""프로세스당 하나(설정이 비어 있으면 매번 다시 확인 — .env 를 고치고 재시작 없이도 사유가 갱신되게)."""
|
||||
global _CLIENT
|
||||
with _CLIENT_LOCK:
|
||||
if _CLIENT is None or not _CLIENT.enabled:
|
||||
_CLIENT = GoogleSlidesClient()
|
||||
return _CLIENT
|
||||
+38
-2
@@ -15,6 +15,8 @@ from pydantic import BaseModel
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
|
||||
from .modules.cafe24 import build_cafe24_store
|
||||
from .modules.asset import build_asset_store
|
||||
from .modules.asset import router as asset_router
|
||||
from .modules.cafe24 import router as cafe24_router
|
||||
from .modules.cupang import build_cupang_store, build_itemcode_reader
|
||||
from .modules.cupang import router as cupang_router
|
||||
@@ -33,6 +35,8 @@ from .modules.vacation import router as vacation_router
|
||||
from .store import (
|
||||
APPROVER_KEYS,
|
||||
MODULE_KEYS,
|
||||
ROLE_LABELS,
|
||||
ROLES,
|
||||
SUPER_ADMIN_EMAIL,
|
||||
UserStore,
|
||||
allowed_modules,
|
||||
@@ -52,6 +56,7 @@ MODULE_LABELS: dict[str, str] = {
|
||||
"project": "프로젝트 관리",
|
||||
"cafe24": "카페24 상품관리",
|
||||
"performance": "실적",
|
||||
"asset": "자산관리",
|
||||
"expense_approver": "개인경비",
|
||||
"vacation_approver": "휴가",
|
||||
}
|
||||
@@ -140,6 +145,7 @@ _MODULE_TEMPLATE_DIRS = [
|
||||
BASE_DIR / "modules" / "project" / "templates",
|
||||
BASE_DIR / "modules" / "cafe24" / "templates",
|
||||
BASE_DIR / "modules" / "performance" / "templates",
|
||||
BASE_DIR / "modules" / "asset" / "templates",
|
||||
]
|
||||
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
||||
templates.env.loader = ChoiceLoader(
|
||||
@@ -202,6 +208,7 @@ app.state.cafe24_store = build_cafe24_store(dsn=env("CAFE24_DB_URL") or None)
|
||||
# 실적(쇼핑몰 통합 매출): PERFORMANCE_DB_URL 없으면 store=None(라우터가 "설정 필요" 안내).
|
||||
# 쇼핑몰 API 인증정보는 설정 화면에서 입력 → APP_ENCRYPTION_KEY 로 암호화해 performance_db 에 저장.
|
||||
app.state.performance_store = build_performance_store(dsn=env("PERFORMANCE_DB_URL") or None)
|
||||
app.state.asset_store = build_asset_store(dsn=env("ASSET_DB_URL") or None)
|
||||
|
||||
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
||||
app.include_router(expense_router)
|
||||
@@ -212,6 +219,7 @@ app.include_router(dispatch_router)
|
||||
app.include_router(project_router)
|
||||
app.include_router(cafe24_router)
|
||||
app.include_router(performance_router)
|
||||
app.include_router(asset_router)
|
||||
|
||||
|
||||
def public_url_for(request: Request, route_name: str) -> str:
|
||||
@@ -405,6 +413,11 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"category": "관리",
|
||||
},
|
||||
]
|
||||
items.append({
|
||||
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
|
||||
"description": "사무집기·전산장비의 배정·반납·구매 이력과 HWiNFO 컴퓨터 사양을 관리합니다.",
|
||||
"url": "/asset/", "health_url": "/asset/health", "status": "ready", "category": "관리",
|
||||
})
|
||||
allowed = allowed_modules(user_rec)
|
||||
for item in items:
|
||||
item["allowed"] = item["key"] in allowed
|
||||
@@ -414,6 +427,7 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
def _icon_svg(name: str) -> str:
|
||||
"""좌측 사이드바용 인라인 아이콘. 외부 의존 없는 작은 SVG."""
|
||||
paths = {
|
||||
"asset": '<rect x="3" y="3" width="18" height="13" rx="2"/><path d="M8 21h8M12 16v5"/><path d="M7 7h10M7 11h6"/>',
|
||||
"home": '<path d="M3 11 12 3l9 8"/><path d="M5 10v10h14V10"/>',
|
||||
"expense": '<rect x="3" y="6" width="18" height="13" rx="2"/><path d="M3 10h18"/><path d="M7 15h4"/>',
|
||||
"vacation": '<path d="M8 2v4"/><path d="M16 2v4"/><rect x="3" y="6" width="18" height="15" rx="2"/><path d="M3 11h18"/>',
|
||||
@@ -476,16 +490,36 @@ def build_erp_nav(
|
||||
return items
|
||||
|
||||
|
||||
def _login_orbit_names(limit: int = 40) -> list[str]:
|
||||
"""로그인 화면 왼쪽 패널 — King 주위를 도는 사용자 아이디(이메일 @ 앞, 첫 글자 대문자). 이메일·실명은 내보내지 않는다."""
|
||||
names: set[str] = set()
|
||||
try:
|
||||
users = user_store.list_all()
|
||||
except Exception: # noqa: BLE001 — 장식이라 실패해도 로그인 화면은 그대로
|
||||
return []
|
||||
for u in users:
|
||||
email = str(u.get("email") or "").lower().strip()
|
||||
local = email.split("@", 1)[0]
|
||||
if not local or email == SUPER_ADMIN_EMAIL:
|
||||
continue
|
||||
names.add(local[:1].upper() + local[1:])
|
||||
return sorted(names)[:limit]
|
||||
|
||||
|
||||
def _render_login(request: Request) -> HTMLResponse:
|
||||
return render_template(request, "login.html", {"orbit_names": _login_orbit_names()})
|
||||
|
||||
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def home(request: Request) -> HTMLResponse:
|
||||
sess = get_session_user(request)
|
||||
if not sess:
|
||||
return render_template(request, "login.html")
|
||||
return _render_login(request)
|
||||
user_rec = user_store.get(sess["email"])
|
||||
if user_rec is None:
|
||||
# 도메인은 통과했으나 저장소에 없음 — 세션 정리 후 재로그인
|
||||
request.session.clear()
|
||||
return render_template(request, "login.html")
|
||||
return _render_login(request)
|
||||
|
||||
# 슈퍼 관리자 → 업무 모듈 선택 화면(main.html).
|
||||
# 일반 사용자 → ERP 메인(좌측 메뉴 + 우측 콘텐츠).
|
||||
@@ -631,6 +665,8 @@ async def admin_page(request: Request) -> HTMLResponse:
|
||||
"module_keys": list(MODULE_KEYS),
|
||||
"module_labels": MODULE_LABELS,
|
||||
"approver_keys": list(APPROVER_KEYS),
|
||||
"roles": list(ROLES),
|
||||
"role_labels": ROLE_LABELS,
|
||||
"super_admin_email": SUPER_ADMIN_EMAIL,
|
||||
"is_admin": True,
|
||||
},
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Company asset management; PostgreSQL only, never creates databases at startup."""
|
||||
from .router import router
|
||||
|
||||
|
||||
def build_asset_store(*, dsn: str | None):
|
||||
if not dsn:
|
||||
return None
|
||||
from .db import AssetStore
|
||||
return AssetStore(dsn)
|
||||
@@ -0,0 +1,282 @@
|
||||
"""자산·보고서·이력을 함께 저장합니다. DB 생성은 사용자가 서버에서 SQL로 진행합니다."""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import date, datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from .store import AssetConflict, transition
|
||||
from .media import MAX_PHOTOS
|
||||
from .monitors import compatible_monitor, monitor_devices
|
||||
|
||||
FIELDS = ("tag", "name", "category", "manufacturer", "model", "serial", "location", "department",
|
||||
"purchased_on", "purchase_cost", "vendor", "warranty_until", "notes")
|
||||
SORTS = {"updated": "a.updated_at DESC", "name": "a.name ASC", "tag": "a.tag ASC",
|
||||
"cost": "a.purchase_cost DESC NULLS LAST", "warranty": "a.warranty_until ASC NULLS LAST"}
|
||||
|
||||
|
||||
def serialize(row):
|
||||
if row is None:
|
||||
return None
|
||||
return {k: (v.isoformat() if isinstance(v, (date, datetime)) else str(v) if isinstance(v, Decimal) else v)
|
||||
for k, v in row.items()}
|
||||
|
||||
|
||||
def filters(q="", category="", status="", location="", assignee="", warranty=False, group=""):
|
||||
conditions, params = ["a.deleted_at IS NULL"], []
|
||||
if q:
|
||||
# %와 _도 입력한 글자 그대로 검색합니다. 검색어는 SQL과 분리해서 전달합니다.
|
||||
value = "%" + q.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "%"
|
||||
conditions.append("(concat_ws(' ',a.tag,a.name,a.model,a.serial,a.manufacturer,a.location,a.department,a.assignee_email) ILIKE %s)")
|
||||
params.append(value)
|
||||
for col, value in (("category", category), ("status", status), ("location", location), ("assignee_email", assignee)):
|
||||
if value:
|
||||
conditions.append(f"a.{col} = %s")
|
||||
params.append(value)
|
||||
if warranty:
|
||||
conditions.append("a.warranty_until BETWEEN (now() AT TIME ZONE 'Asia/Seoul')::date AND (now() AT TIME ZONE 'Asia/Seoul')::date + 30 AND a.status <> 'retired'")
|
||||
if group == "furniture":
|
||||
conditions.append("a.category IN ('desk','chair','furniture')")
|
||||
elif group == "computer":
|
||||
conditions.append("a.category NOT IN ('desk','chair','furniture')")
|
||||
return " AND ".join(conditions), params
|
||||
|
||||
|
||||
class AssetStore:
|
||||
def __init__(self, dsn):
|
||||
self._pool = ConnectionPool(dsn, min_size=0, max_size=5, timeout=5, open=False,
|
||||
kwargs={"row_factory": dict_row, "autocommit": True})
|
||||
self._pool.open(wait=False)
|
||||
|
||||
def close(self):
|
||||
self._pool.close()
|
||||
|
||||
def health(self):
|
||||
with self._pool.connection(timeout=5) as conn:
|
||||
conn.execute("SELECT id,deleted_at FROM assets LIMIT 1")
|
||||
conn.execute("SELECT id FROM asset_photos LIMIT 0")
|
||||
conn.execute("SELECT monitor_key FROM asset_monitor_links LIMIT 0")
|
||||
|
||||
def list_assets(self, *, page=1, page_size=25, sort="updated", **kwargs):
|
||||
# 전체 개수와 목록을 같은 시점의 데이터로 읽어 페이지 숫자가 어긋나지 않게 합니다.
|
||||
where, params = filters(**kwargs)
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||
total = conn.execute(f"SELECT count(*) AS n FROM assets a WHERE {where}", params).fetchone()["n"]
|
||||
rows = conn.execute(
|
||||
f"SELECT a.*,r.parsed->'summary' AS specs,r.uploaded_at AS report_at FROM assets a "
|
||||
"LEFT JOIN asset_reports r ON r.id=a.latest_report_id "
|
||||
f"WHERE {where} ORDER BY {SORTS.get(sort, SORTS['updated'])},a.id LIMIT %s OFFSET %s",
|
||||
[*params, page_size, (page - 1) * page_size]).fetchall()
|
||||
return {"items": [serialize(r) for r in rows], "total": total, "page": page, "page_size": page_size}
|
||||
|
||||
def dashboard(self):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||
totals = conn.execute("""SELECT count(*) AS total,
|
||||
count(*) FILTER(WHERE status='available') AS available,
|
||||
count(*) FILTER(WHERE status='in_use') AS in_use,
|
||||
count(*) FILTER(WHERE status='maintenance') AS maintenance,
|
||||
count(*) FILTER(WHERE status='lost') AS lost,
|
||||
count(*) FILTER(WHERE status='retired') AS retired,
|
||||
coalesce(sum(purchase_cost) FILTER(WHERE status<>'retired'),0) AS purchase_total,
|
||||
count(*) FILTER(WHERE status<>'retired' AND warranty_until BETWEEN
|
||||
(now() AT TIME ZONE 'Asia/Seoul')::date AND (now() AT TIME ZONE 'Asia/Seoul')::date+30) AS warranty_soon
|
||||
FROM assets WHERE deleted_at IS NULL""").fetchone()
|
||||
categories = conn.execute("SELECT category,count(*) AS count FROM assets WHERE deleted_at IS NULL GROUP BY category ORDER BY count(*) DESC,category").fetchall()
|
||||
locations = conn.execute("SELECT DISTINCT location FROM assets WHERE location<>'' AND deleted_at IS NULL ORDER BY location").fetchall()
|
||||
activity = conn.execute("SELECT e.*,a.tag,a.name FROM asset_events e JOIN assets a ON a.id=e.asset_id WHERE a.deleted_at IS NULL ORDER BY e.id DESC LIMIT 12").fetchall()
|
||||
return {"totals": serialize(totals), "categories": categories, "locations": [r["location"] for r in locations],
|
||||
"activity": [serialize(r) for r in activity]}
|
||||
|
||||
def detail(self, asset_id):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||
asset = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL", (asset_id,)).fetchone()
|
||||
if not asset:
|
||||
raise KeyError(asset_id)
|
||||
reports = conn.execute("SELECT id,filename,sha256,uploaded_at,actor,parsed->'summary' AS summary,parsed->>'scan_time' AS scan_time FROM asset_reports WHERE asset_id=%s ORDER BY uploaded_at DESC,id DESC", (asset_id,)).fetchall()
|
||||
report = conn.execute("SELECT id,filename,uploaded_at,parsed FROM asset_reports WHERE id=%s AND asset_id=%s", (asset["latest_report_id"], asset_id)).fetchone() if asset["latest_report_id"] else None
|
||||
events = conn.execute("SELECT * FROM asset_events WHERE asset_id=%s ORDER BY id DESC LIMIT 200", (asset_id,)).fetchall()
|
||||
photos = conn.execute("SELECT id,filename,width,height,uploaded_at,actor FROM asset_photos WHERE asset_id=%s ORDER BY uploaded_at DESC,id", (asset_id,)).fetchall()
|
||||
monitors = self._monitor_matches(conn, asset_id, report["parsed"]) if report else []
|
||||
return {"asset": serialize(asset), "report": serialize(report), "reports": [serialize(r) for r in reports],
|
||||
"events": [serialize(r) for r in events], "photos": [serialize(r) for r in photos], "monitors": monitors}
|
||||
|
||||
@staticmethod
|
||||
def _lock(conn, asset_id, version):
|
||||
# 같은 자산을 동시에 변경할 때 먼저 저장한 사용자의 값을 보호합니다.
|
||||
asset = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL FOR UPDATE", (asset_id,)).fetchone()
|
||||
if not asset or asset.get("deleted_at"):
|
||||
raise KeyError(asset_id)
|
||||
if asset["version"] != version:
|
||||
raise AssetConflict("다른 사용자가 수정했습니다. 상세 화면을 새로 열고 다시 시도하세요.")
|
||||
return asset
|
||||
|
||||
@staticmethod
|
||||
def _event(conn, asset_id, actor, kind, note, changes):
|
||||
conn.execute("INSERT INTO asset_events(asset_id,actor,kind,note,changes) VALUES(%s,%s,%s,%s,%s)",
|
||||
(asset_id, actor, kind, note, Jsonb(changes)))
|
||||
|
||||
def create(self, payload, actor, report=None):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
return self._create(conn, payload, actor, report)
|
||||
|
||||
def _create(self, conn, payload, actor, report=None):
|
||||
# 모니터 등록도 같은 트랜잭션 안에서 자산 생성과 연결을 함께 처리합니다.
|
||||
data = payload.model_dump()
|
||||
asset_id = uuid.uuid4().hex
|
||||
if not data["tag"]:
|
||||
data["tag"] = "AST-" + str(conn.execute("SELECT nextval('asset_tag_seq') AS n").fetchone()["n"]).zfill(6)
|
||||
conn.execute(f"INSERT INTO assets(id,{','.join(FIELDS)}) VALUES({','.join(['%s'] * (len(FIELDS) + 1))})",
|
||||
[asset_id, *[data[k] for k in FIELDS]])
|
||||
self._event(conn, asset_id, actor, "create", "자산 등록", {"after": serialize(data)})
|
||||
if report:
|
||||
if data["category"] != "computer":
|
||||
raise ValueError("HWiNFO 보고서는 컴퓨터 자산에만 연결할 수 있습니다.")
|
||||
self._save_report(conn, asset_id, actor, *report)
|
||||
return asset_id
|
||||
|
||||
def update(self, asset_id, payload, actor):
|
||||
data = payload.model_dump(exclude={"version"})
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
old = self._lock(conn, asset_id, payload.version)
|
||||
if old["latest_report_id"] and data["category"] != "computer":
|
||||
raise ValueError("사양 보고서가 연결된 자산은 컴퓨터 분류를 유지해야 합니다.")
|
||||
if not data["tag"]:
|
||||
data["tag"] = old["tag"]
|
||||
changes = {k: {"before": serialize(old)[k], "after": serialize(data)[k]} for k in FIELDS if old[k] != data[k]}
|
||||
if changes:
|
||||
conn.execute(f"UPDATE assets SET {','.join(k+'=%s' for k in FIELDS)},version=version+1,updated_at=now() WHERE id=%s",
|
||||
[*[data[k] for k in FIELDS], asset_id])
|
||||
self._event(conn, asset_id, actor, "update", "자산 정보 수정", changes)
|
||||
|
||||
def action(self, asset_id, payload, actor):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
old = self._lock(conn, asset_id, payload.version)
|
||||
status, assignee = transition(old, payload)
|
||||
location = payload.location or old["location"]
|
||||
conn.execute("UPDATE assets SET status=%s,assignee_email=%s,location=%s,version=version+1,updated_at=now() WHERE id=%s",
|
||||
(status, assignee, location, asset_id))
|
||||
changes = {k: {"before": old[k], "after": value} for k, value in
|
||||
(("status", status), ("assignee_email", assignee), ("location", location)) if old[k] != value}
|
||||
self._event(conn, asset_id, actor, payload.action, payload.note, changes)
|
||||
|
||||
def _save_report(self, conn, asset_id, actor, filename, raw, parsed):
|
||||
# 원본과 분석 결과를 함께 저장하고 최신 보고서만 교체합니다. 이전 보고서는 남습니다.
|
||||
existing = conn.execute("SELECT id FROM asset_reports WHERE asset_id=%s AND sha256=%s", (asset_id, parsed["sha256"])).fetchone()
|
||||
if existing:
|
||||
raise AssetConflict("이 자산에 동일한 보고서가 이미 등록되어 있습니다.")
|
||||
report_id = uuid.uuid4().hex
|
||||
conn.execute("INSERT INTO asset_reports(id,asset_id,filename,sha256,raw_xml,parsed,actor) VALUES(%s,%s,%s,%s,%s,%s,%s)",
|
||||
(report_id, asset_id, filename, parsed["sha256"], raw, Jsonb(parsed), actor))
|
||||
conn.execute("UPDATE assets SET latest_report_id=%s,version=version+1,updated_at=now() WHERE id=%s", (report_id, asset_id))
|
||||
self._event(conn, asset_id, actor, "report", filename, {"report_id": report_id, "summary": parsed["summary"]})
|
||||
return report_id
|
||||
|
||||
def attach_report(self, asset_id, version, actor, filename, raw, parsed):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
asset = self._lock(conn, asset_id, version)
|
||||
if asset["category"] != "computer":
|
||||
raise ValueError("HWiNFO 보고서는 컴퓨터 자산에만 연결할 수 있습니다.")
|
||||
return self._save_report(conn, asset_id, actor, filename, raw, parsed)
|
||||
|
||||
def report(self, asset_id, report_id, *, raw=False):
|
||||
columns = "r.filename,r.raw_xml" if raw else "r.id,r.filename,r.parsed,r.uploaded_at"
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute(f"SELECT {columns} FROM asset_reports r JOIN assets a ON a.id=r.asset_id WHERE r.asset_id=%s AND r.id=%s AND a.deleted_at IS NULL", (asset_id, report_id)).fetchone()
|
||||
if not row:
|
||||
raise KeyError(report_id)
|
||||
return serialize(row)
|
||||
|
||||
def delete(self, asset_id, version, actor, note):
|
||||
# 수퍼 관리자 삭제도 이력과 원본은 보존하고 대장·다운로드에서 제외합니다.
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
self._lock(conn, asset_id, version)
|
||||
self._event(conn, asset_id, actor, "delete", note, {})
|
||||
conn.execute("UPDATE assets SET deleted_at=now(),deleted_by=%s,version=version+1,updated_at=now() WHERE id=%s", (actor, asset_id))
|
||||
|
||||
def add_photo(self, asset_id, version, actor, filename, image, mime, width, height):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
self._lock(conn, asset_id, version)
|
||||
count = conn.execute("SELECT count(*) AS n FROM asset_photos WHERE asset_id=%s", (asset_id,)).fetchone()["n"]
|
||||
if count >= MAX_PHOTOS:
|
||||
raise ValueError(f"사진은 자산당 {MAX_PHOTOS}개까지 등록할 수 있습니다.")
|
||||
photo_id = uuid.uuid4().hex
|
||||
conn.execute("INSERT INTO asset_photos(id,asset_id,filename,image,mime,width,height,actor) VALUES(%s,%s,%s,%s,%s,%s,%s,%s)",
|
||||
(photo_id, asset_id, filename, image, mime, width, height, actor))
|
||||
conn.execute("UPDATE assets SET version=version+1,updated_at=now() WHERE id=%s", (asset_id,))
|
||||
self._event(conn, asset_id, actor, "photo", filename, {"photo_id": photo_id})
|
||||
return photo_id
|
||||
|
||||
def photo(self, asset_id, photo_id):
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute("SELECT p.image,p.mime FROM asset_photos p JOIN assets a ON a.id=p.asset_id WHERE p.asset_id=%s AND p.id=%s AND a.deleted_at IS NULL", (asset_id, photo_id)).fetchone()
|
||||
if not row:
|
||||
raise KeyError(photo_id)
|
||||
return row
|
||||
|
||||
@staticmethod
|
||||
def _monitor_matches(conn, computer_id, parsed):
|
||||
result = []
|
||||
for device in monitor_devices(parsed):
|
||||
linked = conn.execute("SELECT a.* FROM asset_monitor_links l JOIN assets a ON a.id=l.monitor_asset_id WHERE l.computer_id=%s AND l.monitor_key=%s AND a.category='monitor' AND a.deleted_at IS NULL", (computer_id, device["key"])).fetchone()
|
||||
matches = conn.execute("SELECT * FROM assets WHERE category='monitor' AND deleted_at IS NULL AND lower(btrim(serial))=%s ORDER BY id LIMIT 21", (device["serial"].casefold(),)).fetchall() if device["serial"] else []
|
||||
compatible = [a for a in matches if compatible_monitor(a, device)]
|
||||
asset = linked or (compatible[0] if len(compatible) == 1 else None)
|
||||
candidates = matches if not asset else []
|
||||
# candidate_by — 후보가 같은 시리얼(같은 실물일 가능성)인지, 참고용 같은 모델·이름인지.
|
||||
# 같은 모델은 여러 대일 수 있으므로(듀얼 모니터 등) 새 등록을 막지 않는다(2026-10-07).
|
||||
candidate_by = "serial" if candidates else ""
|
||||
if not asset and not candidates:
|
||||
candidates = conn.execute("SELECT * FROM assets WHERE category='monitor' AND deleted_at IS NULL AND (lower(btrim(model))=%s OR lower(btrim(name))=%s) ORDER BY id LIMIT 20", (device["model"].casefold(), device["name"].casefold())).fetchall()
|
||||
candidate_by = "model" if candidates else ""
|
||||
result.append({**device, "asset": serialize(asset), "candidates": [serialize(r) for r in candidates],
|
||||
"candidate_by": candidate_by,
|
||||
"match": "linked" if linked else "serial" if asset else "unconfirmed"})
|
||||
return result
|
||||
|
||||
def report_monitors(self, asset_id, report_id):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
conn.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")
|
||||
row = conn.execute("SELECT r.parsed FROM asset_reports r JOIN assets a ON a.id=r.asset_id WHERE r.asset_id=%s AND r.id=%s AND a.deleted_at IS NULL", (asset_id, report_id)).fetchone()
|
||||
if not row:
|
||||
raise KeyError(report_id)
|
||||
return self._monitor_matches(conn, asset_id, row["parsed"])
|
||||
|
||||
def register_monitor(self, computer_id, index, payload, actor):
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
computer = self._lock(conn, computer_id, payload.version)
|
||||
if computer["category"] != "computer" or computer["latest_report_id"] != payload.report_id:
|
||||
raise AssetConflict("최신 컴퓨터 보고서를 다시 열고 모니터를 등록하세요.")
|
||||
row = conn.execute("SELECT parsed FROM asset_reports WHERE asset_id=%s AND id=%s", (computer_id, payload.report_id)).fetchone()
|
||||
devices = monitor_devices(row["parsed"]) if row else []
|
||||
if index < 0 or index >= len(devices):
|
||||
raise KeyError(index)
|
||||
device = devices[index]
|
||||
# 서로 다른 컴퓨터에서 동일 시리얼을 동시에 등록하는 경우도 중복을 막습니다.
|
||||
if device["serial"]:
|
||||
conn.execute("SELECT pg_advisory_xact_lock(hashtextextended(%s,0))", ("asset-monitor:" + device["serial"].casefold(),))
|
||||
if payload.asset_id:
|
||||
target = conn.execute("SELECT * FROM assets WHERE id=%s AND deleted_at IS NULL FOR UPDATE", (payload.asset_id,)).fetchone()
|
||||
if not target or target["category"] != "monitor":
|
||||
raise ValueError("등록된 모니터 자산을 선택하세요.")
|
||||
monitor_id = target["id"]
|
||||
else:
|
||||
match = self._monitor_matches(conn, computer_id, row["parsed"])[index]
|
||||
# 같은 시리얼(같은 실물)만 막는다 — 같은 모델이지만 시리얼이 다른 모니터는 새 자산으로 등록된다.
|
||||
if match["asset"] or match["candidate_by"] == "serial":
|
||||
raise AssetConflict(f"같은 시리얼({device['serial']})의 모니터가 이미 등록되어 있습니다. 기존 자산에 연결하세요."
|
||||
if device["serial"] else "이 모니터는 이미 자산에 연결되어 있습니다.")
|
||||
# 보고서의 실제 시리얼을 유지해야 이후 보고서에서도 같은 장비를 찾습니다.
|
||||
data = payload.asset.model_copy(update={"serial": device["serial"] or payload.asset.serial})
|
||||
monitor_id = self._create(conn, data, actor)
|
||||
conn.execute("INSERT INTO asset_monitor_links(computer_id,monitor_key,monitor_asset_id,actor) VALUES(%s,%s,%s,%s) ON CONFLICT(computer_id,monitor_key) DO UPDATE SET monitor_asset_id=EXCLUDED.monitor_asset_id,actor=EXCLUDED.actor,linked_at=now()",
|
||||
(computer_id, device["key"], monitor_id, actor))
|
||||
conn.execute("UPDATE assets SET version=version+1,updated_at=now() WHERE id=%s", (computer_id,))
|
||||
self._event(conn, computer_id, actor, "monitor", "모니터 자산 연결", {"monitor_asset_id": monitor_id, "model": device["model"]})
|
||||
return monitor_id
|
||||
@@ -0,0 +1,129 @@
|
||||
"""HWiNFO XML을 부품별로 읽습니다. 외부 파일이나 엔티티는 열지 않습니다."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from datetime import datetime
|
||||
from xml.etree.ElementTree import ParseError
|
||||
|
||||
from defusedxml.ElementTree import fromstring
|
||||
from defusedxml.common import DefusedXmlException
|
||||
|
||||
MAX_REPORT_BYTES = 10 * 1024 * 1024
|
||||
SECTION_LABELS = {
|
||||
"SYSTEM": "시스템", "CPU": "프로세서", "MOBO": "메인보드 · BIOS",
|
||||
"MEMORY": "메모리", "VIDEO": "그래픽", "MONITOR": "모니터",
|
||||
"DRIVES": "저장장치", "NETWORK": "네트워크", "SOUND": "오디오",
|
||||
"PORTS": "포트 · USB", "BUS": "버스 · 컨트롤러",
|
||||
}
|
||||
|
||||
|
||||
def _text(node, tag):
|
||||
return (node.findtext(tag) or "").strip()
|
||||
|
||||
|
||||
def _props(node):
|
||||
return [{"label": _text(p, "Entry"), "value": _text(p, "Description"),
|
||||
"type": _text(p, "PropertyType")} for p in node.findall("Property")]
|
||||
|
||||
|
||||
def _pick(nodes, *, types=(), labels=()):
|
||||
# 언어와 무관한 PropertyType을 먼저 사용하고, 없을 때 한글/영문 항목명을 찾습니다.
|
||||
properties = [p for n in nodes for p in n["properties"]]
|
||||
for kind in types:
|
||||
for p in properties:
|
||||
if p["type"] == kind and p["value"]:
|
||||
return p["value"]
|
||||
for label in labels:
|
||||
for p in properties:
|
||||
if p["label"].casefold() == label.casefold() and p["value"]:
|
||||
return p["value"]
|
||||
return ""
|
||||
|
||||
|
||||
def parse_hwinfo(raw: bytes) -> dict:
|
||||
if not raw or len(raw) > MAX_REPORT_BYTES:
|
||||
raise ValueError("XML 보고서는 비어 있지 않은 10 MB 이하 파일이어야 합니다.")
|
||||
try:
|
||||
# HWiNFO의 DTD 선언은 허용하되 파일을 읽지 않습니다. 엔티티는 모두 차단합니다.
|
||||
root = fromstring(raw, forbid_dtd=False, forbid_entities=True, forbid_external=True)
|
||||
except (ParseError, DefusedXmlException, ValueError, LookupError) as exc:
|
||||
raise ValueError("XML을 읽을 수 없습니다. HWiNFO XML 보고서인지 확인하세요.") from exc
|
||||
if root.tag != "HWINFO" or len(root.findall("COMPUTER")) != 1:
|
||||
raise ValueError("컴퓨터 한 대의 HWiNFO XML 보고서만 업로드할 수 있습니다.")
|
||||
computer = root.find("COMPUTER")
|
||||
sections = [{"key": "SYSTEM", "label": "시스템", "nodes": []}]
|
||||
count = 0
|
||||
|
||||
def walk(node, path, result, depth=0):
|
||||
nonlocal count
|
||||
count += 1
|
||||
if count > 30000 or depth > 64:
|
||||
raise ValueError("보고서 구조가 너무 크거나 깊습니다.")
|
||||
name = _text(node, "NodeName")
|
||||
trail = path + ([name] if name else [])
|
||||
props = _props(node)
|
||||
if props:
|
||||
result.append({"name": name or node.tag, "path": " › ".join(trail), "properties": props})
|
||||
for child in node:
|
||||
if child.tag in {"SubNodes", "SubNode"}:
|
||||
walk(child, trail, result, depth + 1)
|
||||
elif child.find("NodeName") is not None:
|
||||
walk(child, trail, result, depth + 1)
|
||||
|
||||
sections[0]["nodes"] = [{"name": _text(computer, "NodeName") or "컴퓨터",
|
||||
"path": "시스템", "properties": _props(computer)}]
|
||||
subnodes = computer.find("SubNodes")
|
||||
if subnodes is not None:
|
||||
for node in subnodes:
|
||||
group = {"key": node.tag, "label": SECTION_LABELS.get(node.tag, _text(node, "NodeName") or node.tag), "nodes": []}
|
||||
walk(node, [], group["nodes"])
|
||||
sections.append(group)
|
||||
by_key = {s["key"]: s["nodes"] for s in sections}
|
||||
get = lambda key, **kw: _pick(by_key.get(key, []), **kw)
|
||||
summary = {
|
||||
"computer_name": _text(computer, "NodeName") or get("SYSTEM", labels=("컴퓨터 이름", "Computer Name")),
|
||||
"os": get("SYSTEM", labels=("운영 체제", "Operating System")),
|
||||
"manufacturer": get("SYSTEM", labels=("컴퓨터 브랜드", "Computer Brand Name")),
|
||||
"cpu": get("CPU", types=("CPU_NAME",), labels=("프로세서 이름", "Processor Name")),
|
||||
"cores": get("CPU", labels=("프로세서 코어 수", "CPU 코어 수", "Number of CPU Cores", "Number of Processor Cores")),
|
||||
"threads": get("CPU", labels=("논리 프로세서 수", "논리 CPU 수", "Number of Logical CPUs", "Number of Logical Processors")),
|
||||
"motherboard": get("MOBO", types=("SYSTEM_MAINBOARD",)),
|
||||
"bios": get("MOBO", labels=("BIOS 버전", "BIOS Version")),
|
||||
"memory": get("MEMORY", labels=("총 메모리 크기", "Total Memory Size")),
|
||||
"gpu": get("VIDEO", types=("GFXCARD_CHIPSET", "GFXCARD")),
|
||||
"gpu_memory": get("VIDEO", labels=("그래픽 메모리", "Video Memory", "Video Memory Size")),
|
||||
"serial": get("MOBO", labels=("제품 일련 번호", "Product Serial Number", "System Serial Number")),
|
||||
}
|
||||
if summary["serial"].casefold() in {"system serial number", "to be filled by o.e.m.", "default string", "none", "n/a"}:
|
||||
summary["serial"] = ""
|
||||
if not summary["memory"]:
|
||||
mb = get("MEMORY", types=("SYSTEM_MEMORY",))
|
||||
if re.fullmatch(r"\d+(\.\d+)?", mb):
|
||||
summary["memory"] = f"{float(mb) / 1024:g} GiB"
|
||||
devices = {}
|
||||
for key, types, labels in [
|
||||
("DRIVES", ("HDD",), ("드라이브 모델", "Drive Model")),
|
||||
("MEMORY", (), ("모듈 부품 번호", "Module Part Number")),
|
||||
("MONITOR", ("MONITOR",), ("모니터 이름", "Monitor Name")),
|
||||
("NETWORK", ("NETCARD",), ("네트워크 카드", "Network Card")),
|
||||
("VIDEO", ("GFXCARD_CHIPSET", "GFXCARD"), ("그래픽 프로세서", "Video Chipset")),
|
||||
]:
|
||||
devices[key] = []
|
||||
for node in by_key.get(key, []):
|
||||
model = _pick([node], types=types, labels=labels)
|
||||
if model:
|
||||
devices[key].append({"name": model, "node": node["name"], "properties": node["properties"]})
|
||||
summary["drive_count"] = len(devices["DRIVES"])
|
||||
summary["monitor_count"] = len(devices["MONITOR"])
|
||||
if not summary["computer_name"] or not any(summary[k] for k in ("cpu", "motherboard", "memory", "gpu")):
|
||||
raise ValueError("컴퓨터 이름과 하드웨어 사양이 포함된 HWiNFO 보고서가 필요합니다.")
|
||||
scan_time = _text(computer, "ScanTime")
|
||||
try:
|
||||
scan_time = datetime.strptime(scan_time, "%d.%m.%Y %H:%M").isoformat(timespec="minutes")
|
||||
except ValueError:
|
||||
pass # 날짜 형식이 다르면 원래 보고서에 적힌 시각을 그대로 보존합니다.
|
||||
warnings = [p["value"] for p in _props(computer) if p["label"] in ("가상 머신 경고", "Virtual Machine Warning") and p["value"]]
|
||||
return {"summary": summary, "sections": sections, "devices": devices, "scan_time": scan_time,
|
||||
"warnings": warnings, "sha256": hashlib.sha256(raw).hexdigest(),
|
||||
"property_count": sum(len(n["properties"]) for s in sections for n in s["nodes"])}
|
||||
@@ -0,0 +1,38 @@
|
||||
"""사진을 실제 이미지로 확인하고 위치 정보 등 메타데이터를 제거합니다."""
|
||||
import io
|
||||
import warnings
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
MAX_PHOTO_BYTES = 8 * 1024 * 1024
|
||||
MAX_STORED_BYTES = 5 * 1024 * 1024
|
||||
MAX_PHOTOS = 10
|
||||
|
||||
|
||||
def prepare_photo(raw):
|
||||
if not raw or len(raw) > MAX_PHOTO_BYTES:
|
||||
raise ValueError("사진은 비어 있지 않은 8 MB 이하 파일이어야 합니다.")
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with Image.open(io.BytesIO(raw)) as source:
|
||||
if source.format not in {"JPEG", "PNG", "WEBP"}:
|
||||
raise ValueError("JPG, PNG, WebP 사진만 등록할 수 있습니다.")
|
||||
if source.width * source.height > 20_000_000:
|
||||
raise ValueError("사진은 2천만 화소 이하로 등록하세요.")
|
||||
source.load()
|
||||
image = ImageOps.exif_transpose(source)
|
||||
image.thumbnail((2400, 2400))
|
||||
transparent = "A" in image.getbands() or "transparency" in image.info
|
||||
mode = "RGBA" if transparent else "RGB"
|
||||
# 새 캔버스에 복사해 EXIF, GPS, 촬영기기 정보를 저장하지 않습니다.
|
||||
clean = Image.new(mode, image.size)
|
||||
clean.paste(image.convert(mode))
|
||||
output = io.BytesIO()
|
||||
clean.save(output, format="PNG" if transparent else "JPEG", **({} if transparent else {"quality": 88}))
|
||||
data = output.getvalue()
|
||||
if len(data) > MAX_STORED_BYTES:
|
||||
raise ValueError("사진을 압축해 다시 등록하세요. 저장 크기는 5 MB 이하입니다.")
|
||||
return data, "image/png" if transparent else "image/jpeg", clean.width, clean.height
|
||||
except (UnidentifiedImageError, OSError, SyntaxError, Image.DecompressionBombError, Image.DecompressionBombWarning) as exc:
|
||||
raise ValueError("사진을 읽을 수 없습니다. 정상적인 JPG, PNG, WebP 파일을 선택하세요.") from exc
|
||||
@@ -0,0 +1,47 @@
|
||||
"""이전 보고서에도 적용할 수 있도록 저장된 모니터 항목에서 식별 정보를 읽습니다."""
|
||||
import hashlib
|
||||
import re
|
||||
|
||||
|
||||
def usable_serial(value):
|
||||
value = value.strip()
|
||||
if value.casefold() in {"", "unknown", "n/a", "none", "not specified", "serial number", "알 수 없음"}:
|
||||
return ""
|
||||
if re.fullmatch(r"[0\s-]+", value):
|
||||
return ""
|
||||
return value
|
||||
|
||||
|
||||
def compatible_monitor(asset, device):
|
||||
"""다른 제조사나 다른 모델이 같은 시리얼을 쓰면 자동 연결하지 않습니다."""
|
||||
def normalized(value):
|
||||
return "".join(c for c in value.casefold() if c.isalnum())
|
||||
brand = normalized(asset.get("manufacturer", ""))
|
||||
reported_brand = normalized(device["manufacturer"])
|
||||
if brand and reported_brand and brand != reported_brand:
|
||||
return False
|
||||
model = normalized(asset.get("model", ""))
|
||||
if not model:
|
||||
return True
|
||||
return any(model == value or len(model) >= 4 and model in value
|
||||
for value in (normalized(device["model"]), normalized(device["name"])))
|
||||
|
||||
|
||||
def monitor_devices(parsed):
|
||||
devices = []
|
||||
for index, item in enumerate(parsed.get("devices", {}).get("MONITOR", [])):
|
||||
props = item.get("properties", [])
|
||||
def pick(*labels, kind=""):
|
||||
return next((p["value"].strip() for p in props if p.get("label", "").casefold() in
|
||||
{label.casefold() for label in labels} or kind and p.get("type") == kind), "")
|
||||
name = item.get("name", "모니터")
|
||||
model = pick("모니터 이름(제조업체)", "Monitor Name (Manuf)", "Monitor Name (Manufacturer)") or name
|
||||
serial = usable_serial(pick("일련 번호", "Serial Number", "Monitor Serial Number"))
|
||||
instance = pick("디바이스 인스턴스 ID", "Device Instance ID", kind="DeviceInstanceId")
|
||||
# 시리얼이 없는 장치는 모델명만으로 동일 자산이라고 판단하지 않습니다.
|
||||
identity = ("serial:" + serial.casefold() + ":" + model.casefold()) if serial else (
|
||||
"instance:" + instance.casefold() if instance else f"report:{parsed.get('sha256', '')}:{index}")
|
||||
devices.append({"index": index, "key": hashlib.sha256(identity.encode()).hexdigest(),
|
||||
"name": name, "model": model[:200], "serial": serial[:200],
|
||||
"manufacturer": name.split(" ", 1)[0][:150], "properties": props})
|
||||
return devices
|
||||
@@ -0,0 +1,304 @@
|
||||
from __future__ import annotations
|
||||
|
||||
# 화면, 권한 검사, 파일 업로드를 담당합니다. 실제 저장은 db.py에서 처리합니다.
|
||||
|
||||
import io
|
||||
import secrets
|
||||
from contextlib import contextmanager
|
||||
from typing import Annotated
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, Depends, File, Form, HTTPException, Query, Request, UploadFile
|
||||
from fastapi.responses import RedirectResponse, Response
|
||||
from openpyxl import Workbook
|
||||
from pydantic import ValidationError
|
||||
from psycopg import Error as DBError
|
||||
from psycopg.errors import UniqueViolation
|
||||
from psycopg_pool import PoolTimeout
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from .hwinfo import MAX_REPORT_BYTES, parse_hwinfo
|
||||
from .store import ActionInput, AssetConflict, AssetInput, AssetUpdate, CATEGORIES, STATUSES
|
||||
from .store import DeleteInput, MonitorInput
|
||||
from .media import MAX_PHOTO_BYTES, prepare_photo
|
||||
|
||||
router = APIRouter(prefix="/asset", tags=["asset"])
|
||||
|
||||
|
||||
def _user(request: Request):
|
||||
from app.main import get_current_user_record
|
||||
from app.store import has_module
|
||||
user = get_current_user_record(request)
|
||||
if not user:
|
||||
raise HTTPException(401, "로그인이 필요합니다.")
|
||||
if not has_module(user, "asset"):
|
||||
raise HTTPException(403, "자산관리 권한이 없습니다.")
|
||||
return user
|
||||
|
||||
|
||||
def _write(request: Request, user=Depends(_user)):
|
||||
expected = request.session.get("asset_csrf", "")
|
||||
token = request.headers.get("x-asset-csrf", "")
|
||||
if not expected or not secrets.compare_digest(expected, token):
|
||||
raise HTTPException(403, "화면을 새로 열고 다시 시도하세요.")
|
||||
return user
|
||||
|
||||
|
||||
def _super(user):
|
||||
from app.store import SUPER_ADMIN_EMAIL
|
||||
return user.get("email", "").lower() == SUPER_ADMIN_EMAIL
|
||||
|
||||
|
||||
def _super_write(user=Depends(_write)):
|
||||
if not _super(user):
|
||||
raise HTTPException(403, "수퍼 관리자만 자산을 삭제할 수 있습니다.")
|
||||
return user
|
||||
|
||||
|
||||
def _store(request):
|
||||
store = getattr(request.app.state, "asset_store", None)
|
||||
if store is None:
|
||||
raise HTTPException(503, "자산관리 DB 설정이 필요합니다. 관리자에게 문의하세요.")
|
||||
return store
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _errors():
|
||||
try:
|
||||
yield
|
||||
except AssetConflict as exc:
|
||||
raise HTTPException(409, str(exc)) from exc
|
||||
except KeyError as exc:
|
||||
raise HTTPException(404, "자산 또는 보고서를 찾을 수 없습니다.") from exc
|
||||
except ValueError as exc:
|
||||
raise HTTPException(422, str(exc)) from exc
|
||||
except UniqueViolation as exc:
|
||||
raise HTTPException(409, "이미 등록된 자산번호입니다. 다른 번호를 사용하세요.") from exc
|
||||
except (DBError, PoolTimeout) as exc:
|
||||
# DB 오류에 접속 비밀번호가 섞일 수 있어 원문 대신 일반 안내만 보여줍니다.
|
||||
raise HTTPException(503, "자산관리 DB에 연결할 수 없습니다. 설정과 초기화를 확인하세요.") from exc
|
||||
|
||||
|
||||
@router.get("/")
|
||||
def index(request: Request):
|
||||
from app.main import build_erp_nav, get_current_user_record, render_template
|
||||
from app.store import has_module, is_admin
|
||||
user = get_current_user_record(request)
|
||||
if not user:
|
||||
return RedirectResponse("/login", 303)
|
||||
if not has_module(user, "asset"):
|
||||
return render_template(request, "denied.html", {"reason": "자산관리 권한이 없습니다.", "user": user,
|
||||
"is_admin": is_admin(user)}, status_code=403)
|
||||
request.session.setdefault("asset_csrf", secrets.token_urlsafe(32))
|
||||
return render_template(request, "asset/index.html", {
|
||||
"user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="asset"),
|
||||
"page_title": "자산관리", "page_subtitle": "사무집기부터 컴퓨터 사양까지, 회사 자산을 한곳에서",
|
||||
"categories": CATEGORIES, "statuses": STATUSES, "csrf_token": request.session["asset_csrf"],
|
||||
"configured": getattr(request.app.state, "asset_store", None) is not None,
|
||||
"can_delete": _super(user),
|
||||
})
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health(request: Request, user=Depends(_user)):
|
||||
with _errors():
|
||||
_store(request).health()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.get("/api/bootstrap")
|
||||
def bootstrap(request: Request, user=Depends(_user)):
|
||||
from app.main import user_store
|
||||
with _errors():
|
||||
data = _store(request).dashboard()
|
||||
data["users"] = [{"email": u["email"], "name": u.get("name") or u["email"]} for u in user_store.list_all()]
|
||||
return data
|
||||
|
||||
|
||||
def _query(q="", category="", status="", location="", assignee="", warranty=False, group=""):
|
||||
if category and category not in CATEGORIES or status and status not in STATUSES:
|
||||
raise HTTPException(422, "분류 또는 상태 필터가 올바르지 않습니다.")
|
||||
if group not in {"", "computer", "furniture"}:
|
||||
raise HTTPException(422, "자산 구분 필터가 올바르지 않습니다.")
|
||||
return dict(q=q, category=category, status=status, location=location, assignee=assignee, warranty=warranty, group=group)
|
||||
|
||||
|
||||
@router.get("/api/assets")
|
||||
def assets(request: Request, q: str = Query("", max_length=200), category: str = "", status: str = "",
|
||||
location: str = Query("", max_length=150), assignee: str = Query("", max_length=254), warranty: bool = False,
|
||||
page: int = Query(1, ge=1, le=100000), page_size: int = Query(25, ge=1, le=100),
|
||||
sort: str = "updated", group: str = "", user=Depends(_user)):
|
||||
with _errors():
|
||||
return _store(request).list_assets(page=page, page_size=page_size, sort=sort,
|
||||
**_query(q, category, status, location, assignee, warranty, group))
|
||||
|
||||
|
||||
@router.get("/api/export")
|
||||
def export(request: Request, q: str = Query("", max_length=200), category: str = "", status: str = "",
|
||||
location: str = Query("", max_length=150), assignee: str = Query("", max_length=254), warranty: bool = False,
|
||||
group: str = "", user=Depends(_user)):
|
||||
from app.timezone import today_kst
|
||||
with _errors():
|
||||
data = _store(request).list_assets(page=1, page_size=10001, **_query(q, category, status, location, assignee, warranty, group))
|
||||
if data["total"] > 10000:
|
||||
raise HTTPException(422, "한 번에 10,000개까지 내보낼 수 있습니다. 필터를 좁혀주세요.")
|
||||
book = Workbook()
|
||||
sheet = book.active
|
||||
sheet.title = "자산대장"
|
||||
headers = ["자산번호", "자산명", "분류", "상태", "제조사", "모델", "시리얼", "위치", "부서", "사용자", "구매일", "구매금액(원)", "구매처", "보증종료", "메모", "CPU", "메모리", "GPU", "운영체제"]
|
||||
sheet.append(headers)
|
||||
for row in data["items"]:
|
||||
specs = row.get("specs") or {}
|
||||
values = [row["tag"], row["name"], CATEGORIES[row["category"]], STATUSES[row["status"]],
|
||||
*[row[k] for k in ("manufacturer", "model", "serial", "location", "department", "assignee_email", "purchased_on")],
|
||||
float(row["purchase_cost"]) if row["purchase_cost"] is not None else None,
|
||||
row["vendor"], row["warranty_until"], row["notes"], *[specs.get(k, "") for k in ("cpu", "memory", "gpu", "os")]]
|
||||
sheet.append(values)
|
||||
# =로 시작하는 자산명도 엑셀 수식 대신 일반 글자로 저장합니다.
|
||||
for cell in sheet[sheet.max_row]:
|
||||
if isinstance(cell.value, str):
|
||||
cell.data_type = "s"
|
||||
sheet.freeze_panes = "C2"
|
||||
sheet.auto_filter.ref = sheet.dimensions
|
||||
from openpyxl.styles import Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
for cell in sheet[1]:
|
||||
cell.font = Font(bold=True, color="FFFFFF")
|
||||
cell.fill = PatternFill("solid", fgColor="171717")
|
||||
for i in range(1, len(headers) + 1):
|
||||
sheet.column_dimensions[get_column_letter(i)].width = 22 if i > 2 else 28
|
||||
buffer = io.BytesIO()
|
||||
book.save(buffer)
|
||||
return Response(buffer.getvalue(), media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": f'attachment; filename="assets-{today_kst().isoformat()}.xlsx"'})
|
||||
|
||||
|
||||
@router.post("/api/assets")
|
||||
def create(request: Request, payload: AssetInput, user=Depends(_write)):
|
||||
with _errors():
|
||||
asset_id = _store(request).create(payload, user["email"])
|
||||
return {"id": asset_id}
|
||||
|
||||
|
||||
@router.get("/api/assets/{asset_id}")
|
||||
def detail(request: Request, asset_id: str, user=Depends(_user)):
|
||||
with _errors():
|
||||
return _store(request).detail(asset_id)
|
||||
|
||||
|
||||
@router.put("/api/assets/{asset_id}")
|
||||
def update(request: Request, asset_id: str, payload: AssetUpdate, user=Depends(_write)):
|
||||
with _errors():
|
||||
_store(request).update(asset_id, payload, user["email"])
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.delete("/api/assets/{asset_id}")
|
||||
def delete(request: Request, asset_id: str, payload: DeleteInput, user=Depends(_super_write)):
|
||||
with _errors():
|
||||
_store(request).delete(asset_id, payload.version, user["email"], payload.note)
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@router.post("/api/assets/{asset_id}/photos")
|
||||
async def add_photo(request: Request, asset_id: str, file: Annotated[UploadFile, File()],
|
||||
version: Annotated[int, Form(ge=1)], user=Depends(_write)):
|
||||
filename = (file.filename or "photo.jpg").replace("\\", "/").rsplit("/", 1)[-1]
|
||||
try:
|
||||
if len(filename) > 200 or any(ord(c) < 32 for c in filename):
|
||||
raise HTTPException(422, "사진 파일 이름을 확인하세요.")
|
||||
raw = await file.read(MAX_PHOTO_BYTES + 1)
|
||||
finally:
|
||||
await file.close()
|
||||
with _errors():
|
||||
image, mime, width, height = await run_in_threadpool(prepare_photo, raw)
|
||||
photo_id = await run_in_threadpool(_store(request).add_photo, asset_id, version, user["email"], filename, image, mime, width, height)
|
||||
return {"id": photo_id}
|
||||
|
||||
|
||||
@router.get("/api/assets/{asset_id}/photos/{photo_id}")
|
||||
def photo(request: Request, asset_id: str, photo_id: str, user=Depends(_user)):
|
||||
with _errors():
|
||||
row = _store(request).photo(asset_id, photo_id)
|
||||
return Response(bytes(row["image"]), media_type=row["mime"],
|
||||
headers={"X-Content-Type-Options": "nosniff", "Cache-Control": "no-store"})
|
||||
|
||||
|
||||
@router.get("/api/assets/{asset_id}/reports/{report_id}/monitors")
|
||||
def report_monitors(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
|
||||
with _errors():
|
||||
return {"items": _store(request).report_monitors(asset_id, report_id)}
|
||||
|
||||
|
||||
@router.post("/api/assets/{asset_id}/monitors/{index}")
|
||||
def register_monitor(request: Request, asset_id: str, index: int, payload: MonitorInput, user=Depends(_write)):
|
||||
with _errors():
|
||||
monitor_id = _store(request).register_monitor(asset_id, index, payload, user["email"])
|
||||
return {"id": monitor_id}
|
||||
|
||||
|
||||
@router.post("/api/assets/{asset_id}/actions")
|
||||
def action(request: Request, asset_id: str, payload: ActionInput, user=Depends(_write)):
|
||||
from app.main import user_store
|
||||
if payload.action == "checkout" and not user_store.get(payload.assignee_email.lower()):
|
||||
raise HTTPException(422, "등록된 회사 사용자를 선택하세요.")
|
||||
with _errors():
|
||||
_store(request).action(asset_id, payload, user["email"])
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
async def _report_file(file):
|
||||
filename = (file.filename or "report.xml").replace("\\", "/").rsplit("/", 1)[-1]
|
||||
if not filename.lower().endswith(".xml") or len(filename) > 200 or any(ord(c) < 32 for c in filename):
|
||||
raise HTTPException(422, "이름이 200자 이하인 XML 보고서를 선택하세요.")
|
||||
try:
|
||||
raw = await file.read(MAX_REPORT_BYTES + 1)
|
||||
finally:
|
||||
await file.close()
|
||||
with _errors():
|
||||
parsed = await run_in_threadpool(parse_hwinfo, raw)
|
||||
return filename, raw, parsed
|
||||
|
||||
|
||||
@router.post("/api/reports/preview")
|
||||
async def preview(file: Annotated[UploadFile, File()], user=Depends(_write)):
|
||||
filename, raw, parsed = await _report_file(file)
|
||||
return {"filename": filename, "summary": parsed["summary"], "scan_time": parsed["scan_time"],
|
||||
"property_count": parsed["property_count"], "warnings": parsed["warnings"]}
|
||||
|
||||
|
||||
@router.post("/api/reports/import")
|
||||
async def import_report(request: Request, file: Annotated[UploadFile, File()], payload: Annotated[str, Form(max_length=20000)], user=Depends(_write)):
|
||||
with _errors():
|
||||
try:
|
||||
data = AssetInput.model_validate_json(payload)
|
||||
except ValidationError as exc:
|
||||
raise HTTPException(422, "자산명·분류·구매일·금액을 확인하세요.") from exc
|
||||
report = await _report_file(file)
|
||||
with _errors():
|
||||
asset_id = await run_in_threadpool(_store(request).create, data, user["email"], report)
|
||||
return {"id": asset_id}
|
||||
|
||||
|
||||
@router.post("/api/assets/{asset_id}/reports")
|
||||
async def attach(request: Request, asset_id: str, file: Annotated[UploadFile, File()],
|
||||
version: Annotated[int, Form(ge=1)], user=Depends(_write)):
|
||||
filename, raw, parsed = await _report_file(file)
|
||||
with _errors():
|
||||
report_id = await run_in_threadpool(_store(request).attach_report, asset_id, version, user["email"], filename, raw, parsed)
|
||||
return {"id": report_id}
|
||||
|
||||
|
||||
@router.get("/api/assets/{asset_id}/reports/{report_id}")
|
||||
def report_detail(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
|
||||
with _errors():
|
||||
return _store(request).report(asset_id, report_id)
|
||||
|
||||
|
||||
@router.get("/api/assets/{asset_id}/reports/{report_id}/download")
|
||||
def download(request: Request, asset_id: str, report_id: str, user=Depends(_user)):
|
||||
with _errors():
|
||||
row = _store(request).report(asset_id, report_id, raw=True)
|
||||
return Response(bytes(row["raw_xml"]), media_type="application/octet-stream",
|
||||
headers={"Content-Disposition": f"attachment; filename=hwinfo.xml; filename*=UTF-8''{quote(row['filename'], safe='')}",
|
||||
"X-Content-Type-Options": "nosniff", "Cache-Control": "no-store"})
|
||||
@@ -0,0 +1,106 @@
|
||||
"""Asset validation and lifecycle rules, shared by API and storage."""
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
CATEGORIES = {"computer": "컴퓨터", "monitor": "모니터", "mouse": "마우스", "keyboard": "키보드",
|
||||
"camera": "카메라", "hub": "허브 · 네트워크", "lighting": "조명", "desk": "책상",
|
||||
"chair": "의자", "furniture": "기타 사무집기", "equipment": "기타 전산장비"}
|
||||
STATUSES = {"available": "사용 가능", "in_use": "사용 중", "maintenance": "수리 중", "lost": "분실", "retired": "폐기"}
|
||||
|
||||
|
||||
class AssetInput(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
tag: str = Field(default="", max_length=64)
|
||||
name: str = Field(min_length=1, max_length=200)
|
||||
category: str
|
||||
manufacturer: str = Field(default="", max_length=150)
|
||||
model: str = Field(default="", max_length=200)
|
||||
serial: str = Field(default="", max_length=200)
|
||||
location: str = Field(default="", max_length=150)
|
||||
department: str = Field(default="", max_length=100)
|
||||
purchased_on: date | None = None
|
||||
purchase_cost: Decimal | None = Field(default=None, ge=0, le=10**12, decimal_places=2)
|
||||
vendor: str = Field(default="", max_length=200)
|
||||
warranty_until: date | None = None
|
||||
notes: str = Field(default="", max_length=10000)
|
||||
|
||||
@field_validator("category")
|
||||
@classmethod
|
||||
def valid_category(cls, value):
|
||||
if value not in CATEGORIES:
|
||||
raise ValueError("자산 분류가 올바르지 않습니다.")
|
||||
return value
|
||||
|
||||
@model_validator(mode="after")
|
||||
def valid_dates(self):
|
||||
if self.purchased_on and self.warranty_until and self.warranty_until < self.purchased_on:
|
||||
raise ValueError("보증 종료일은 구매일 이후여야 합니다.")
|
||||
return self
|
||||
|
||||
|
||||
class AssetUpdate(AssetInput):
|
||||
version: int = Field(ge=1)
|
||||
|
||||
|
||||
class DeleteInput(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
version: int = Field(ge=1)
|
||||
note: str = Field(min_length=1, max_length=2000)
|
||||
|
||||
|
||||
class MonitorInput(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
version: int = Field(ge=1)
|
||||
report_id: str = Field(min_length=1, max_length=64)
|
||||
asset: AssetInput | None = None
|
||||
asset_id: str = Field(default="", max_length=64)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_target(self):
|
||||
if bool(self.asset) == bool(self.asset_id):
|
||||
raise ValueError("등록할 정보 또는 연결할 모니터 자산 중 하나를 지정하세요.")
|
||||
if self.asset and self.asset.category != "monitor":
|
||||
raise ValueError("모니터 분류로 등록하세요.")
|
||||
return self
|
||||
|
||||
|
||||
class ActionInput(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
|
||||
version: int = Field(ge=1)
|
||||
action: str
|
||||
assignee_email: str = Field(default="", max_length=254)
|
||||
location: str = Field(default="", max_length=150)
|
||||
note: str = Field(default="", max_length=2000)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def require_reason(self):
|
||||
if self.action in {"lost", "retired"} and not self.note:
|
||||
raise ValueError("분실·폐기 사유를 입력하세요.")
|
||||
return self
|
||||
|
||||
|
||||
class AssetConflict(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def transition(asset, payload: ActionInput):
|
||||
state = asset["status"]
|
||||
if payload.action == "checkout":
|
||||
if state != "available" or not payload.assignee_email:
|
||||
raise ValueError("사용 가능한 자산을 선택하고 배정할 사용자를 지정하세요.")
|
||||
return "in_use", payload.assignee_email.lower()
|
||||
if payload.action == "checkin":
|
||||
if state != "in_use":
|
||||
raise ValueError("사용 중인 자산만 반납할 수 있습니다.")
|
||||
return "available", ""
|
||||
if payload.action == "maintenance" and state == "available":
|
||||
return "maintenance", ""
|
||||
if payload.action == "available" and state in {"maintenance", "lost", "retired"}:
|
||||
return "available", ""
|
||||
if payload.action == "lost" and state in {"available", "in_use", "maintenance"}:
|
||||
return "lost", asset.get("assignee_email", "")
|
||||
if payload.action == "retired" and state in {"available", "maintenance", "lost"}:
|
||||
return "retired", ""
|
||||
raise ValueError("현재 상태에서 처리할 수 없습니다. 배정된 자산은 먼저 반납하세요.")
|
||||
@@ -0,0 +1,70 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% set force_sidebar_collapsed = true %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/asset.css?v=20261006c">{% endblock %}
|
||||
{% block content %}
|
||||
<div id="asset-app" class="am-workspace" data-csrf="{{ csrf_token }}" data-configured="{{ 'true' if configured else 'false' }}" data-can-delete="{{ 'true' if can_delete else 'false' }}">
|
||||
<aside class="am-nav" aria-label="자산관리 탐색">
|
||||
<div class="am-nav-brand"><span class="am-mark">A</span><div><strong>회사 자산</strong><small>ASSET MANAGEMENT</small></div></div>
|
||||
<button class="am-nav-link is-active" data-view="all"><span>전체 자산</span><span id="am-nav-total" class="am-count">—</span></button>
|
||||
<button class="am-nav-link" data-view="computer"><span>컴퓨터 · 전산장비</span></button>
|
||||
<button class="am-nav-link" data-view="furniture"><span>사무실 · 집기</span></button>
|
||||
<p class="am-nav-label">자산 상태</p>
|
||||
{% for key,label in statuses.items() %}<button class="am-nav-link" data-state="{{ key }}"><span><i class="am-dot am-dot-{{ key }}"></i>{{ label }}</span><span class="am-count" id="am-count-{{ key }}">—</span></button>{% endfor %}
|
||||
<p class="am-nav-label">확인할 항목</p>
|
||||
<button class="am-nav-link" data-view="warranty"><span>보증 만료 예정</span><span class="am-count" id="am-count-warranty">—</span></button>
|
||||
<div class="am-nav-foot"><strong>자산 한 개, 기록 하나</strong><p>개별 자산번호로 등록하고<br>배정부터 폐기까지 추적하세요.</p><button class="am-text-btn" id="am-help-open">사용 안내 ↗</button></div>
|
||||
</aside>
|
||||
<section class="am-main" aria-label="자산대장">
|
||||
<div class="am-heading"><div><p class="am-eyebrow">COMPANY INVENTORY</p><h2>회사 자산 대장</h2><p>어떤 자산이, 어디에, 누구에게 있는지 확인하세요.</p></div><div class="am-heading-actions"><button class="erp-btn erp-btn-outline" id="am-import">↑ HWiNFO 보고서</button><button class="erp-btn erp-btn-primary" id="am-create" {% if not configured %}disabled{% endif %}>+ 자산 등록</button></div></div>
|
||||
{% if not configured %}<div class="am-notice" role="status"><strong>자산관리 저장소 설정이 필요합니다.</strong><p>관리자가 자산관리 DB를 연결하면 등록·배정·반납을 사용할 수 있습니다. HWiNFO 보고서는 지금도 분석 결과를 미리 볼 수 있습니다.</p></div>{% endif %}
|
||||
<div id="am-message" class="am-message" role="status" aria-live="polite" hidden></div>
|
||||
<div class="am-kpis" aria-label="자산 현황">
|
||||
<button data-kpi="all" class="am-kpi"><span>전체 자산</span><strong id="am-total">—</strong><small>회사에 등록된 자산</small></button>
|
||||
<button data-kpi="in_use" class="am-kpi"><span><i class="am-dot am-dot-in_use"></i>사용 중</span><strong id="am-in_use">—</strong><small>직원에게 배정된 자산</small></button>
|
||||
<button data-kpi="available" class="am-kpi"><span><i class="am-dot am-dot-available"></i>사용 가능</span><strong id="am-available">—</strong><small>새로 배정할 수 있는 자산</small></button>
|
||||
<button data-kpi="maintenance" class="am-kpi"><span><i class="am-dot am-dot-maintenance"></i>수리 중</span><strong id="am-maintenance">—</strong><small>점검 · 수리 중인 자산</small></button>
|
||||
<button data-kpi="warranty" class="am-kpi"><span>보증 만료 예정</span><strong id="am-warranty_soon">—</strong><small>오늘부터 30일 이내</small></button>
|
||||
</div>
|
||||
<div class="am-register">
|
||||
<div class="am-register-head"><div><h3 id="am-list-title">전체 자산</h3><span id="am-result-count">자산을 불러오는 중</span></div><div><button class="am-text-btn" id="am-refresh" aria-label="자산 새로고침">↻ 새로고침</button><button class="erp-btn erp-btn-outline" id="am-export" {% if not configured %}disabled{% endif %}>엑셀 내보내기 ↓</button></div></div>
|
||||
<form class="am-filters" id="am-filters" role="search">
|
||||
<label class="am-search"><span aria-hidden="true">⌕</span><input id="am-query" type="search" maxlength="200" placeholder="자산명, 번호, 모델, 시리얼 검색" aria-label="자산 검색"></label>
|
||||
<select id="am-category" aria-label="분류"><option value="">모든 분류</option>{% for key,label in categories.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select>
|
||||
<select id="am-status" aria-label="상태"><option value="">모든 상태</option>{% for key,label in statuses.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select>
|
||||
<select id="am-location" aria-label="위치"><option value="">모든 위치</option></select>
|
||||
<select id="am-assignee" aria-label="배정 사용자"><option value="">모든 사용자</option></select>
|
||||
<select id="am-sort" aria-label="정렬"><option value="updated">최근 변경순</option><option value="name">자산명순</option><option value="tag">자산번호순</option><option value="cost">구매금액순</option><option value="warranty">보증종료순</option></select>
|
||||
<button type="button" class="am-text-btn" id="am-reset">초기화</button>
|
||||
</form>
|
||||
<div class="am-table-scroll"><table class="am-table"><thead><tr><th>자산</th><th>분류</th><th>상태</th><th>사용자 / 위치</th><th>구매금액</th><th>보증 종료</th><th>사양</th></tr></thead><tbody id="am-rows"><tr><td colspan="7" class="am-empty">{% if configured %}자산을 불러오는 중입니다.{% else %}등록된 자산이 여기에 표시됩니다.{% endif %}</td></tr></tbody></table></div>
|
||||
<div class="am-pagination"><span id="am-page-info">—</span><div><button class="erp-btn erp-btn-outline" id="am-prev" disabled>← 이전</button><span id="am-page-number">1</span><button class="erp-btn erp-btn-outline" id="am-next" disabled>다음 →</button></div></div>
|
||||
</div>
|
||||
<div class="am-bottom"><section class="am-panel"><div class="am-panel-head"><h3>자산 구성</h3><span>분류별 등록 수</span></div><div id="am-breakdown" class="am-breakdown"><p class="am-muted">등록된 자산이 없습니다.</p></div><div class="am-value"><span>보유 자산 구매금액 <small>폐기 제외 · 입력된 금액 기준</small></span><strong id="am-value">—</strong></div></section><section class="am-panel"><div class="am-panel-head"><h3>최근 활동</h3><span>등록 · 배정 · 반납 · 변경</span></div><div id="am-activity" class="am-activity"><p class="am-muted">활동 이력이 여기에 표시됩니다.</p></div></section></div>
|
||||
</section>
|
||||
</div>
|
||||
<dialog id="am-detail" class="am-drawer" aria-labelledby="am-detail-title"><div class="am-dialog-head"><div><small id="am-detail-tag">자산 상세</small><h2 id="am-detail-title">자산 정보</h2></div><button type="button" class="am-close" data-close="am-detail" aria-label="자산 상세 닫기">×</button></div><div id="am-detail-content"></div></dialog>
|
||||
<dialog id="am-editor" class="am-dialog" aria-labelledby="am-editor-title"><div class="am-dialog-head"><div><small>ASSET REGISTER</small><h2 id="am-editor-title">자산 등록</h2></div><button type="button" class="am-close" data-close="am-editor" aria-label="등록 창 닫기">×</button></div><form id="am-editor-form" class="am-form"><div class="am-form-grid">
|
||||
<label>자산명 <span>*</span><input name="name" maxlength="200" required placeholder="예: 디자인팀 데스크톱"></label>
|
||||
<label>자산번호<input name="tag" maxlength="64" placeholder="비워두면 자동 발급 (AST-000001)"></label>
|
||||
<label>분류 <span>*</span><select name="category" required>{% for key,label in categories.items() %}<option value="{{ key }}">{{ label }}</option>{% endfor %}</select></label>
|
||||
<label>제조사<input name="manufacturer" maxlength="150" placeholder="예: Dell, 시디즈"></label>
|
||||
<label>모델<input name="model" maxlength="200"></label><label>시리얼 번호<input name="serial" maxlength="200"></label>
|
||||
<label>위치<input name="location" maxlength="150" list="am-locations" placeholder="예: 본사 3층 디자인팀"></label><label>부서<input name="department" maxlength="100"></label>
|
||||
<label>구매일<input type="date" name="purchased_on"></label><label>구매금액 (원)<input type="number" name="purchase_cost" min="0" max="1000000000000" step="0.01" placeholder="미입력 가능"></label>
|
||||
<label>구매처<input name="vendor" maxlength="200"></label><label>보증 종료일<input type="date" name="warranty_until"></label>
|
||||
<label class="am-wide">메모<textarea name="notes" maxlength="10000" rows="3" placeholder="관리에 필요한 추가 정보를 입력하세요."></textarea></label>
|
||||
</div><p class="am-form-hint">같은 모델도 자산번호를 각각 발급합니다. 사용자 배정은 등록 후 상세 화면에서 진행합니다.</p><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-editor">취소</button><button type="submit" class="erp-btn erp-btn-primary">자산 저장</button></div></form></dialog>
|
||||
<dialog id="am-upload" class="am-dialog am-upload-dialog" aria-labelledby="am-upload-title"><div class="am-dialog-head"><div><small>HWiNFO XML IMPORT</small><h2 id="am-upload-title">컴퓨터 보고서 가져오기</h2></div><button type="button" class="am-close" data-close="am-upload" aria-label="업로드 창 닫기">×</button></div><form id="am-upload-form" class="am-form">
|
||||
<p class="am-form-hint" id="am-upload-hint">HWiNFO에서 저장한 XML 보고서를 선택하세요. 사양을 분석한 뒤 자산으로 등록합니다.</p>
|
||||
<label class="am-drop" id="am-drop"><span class="am-upload-icon">↑</span><strong>XML 보고서 선택</strong><span>파일을 여기에 놓거나 클릭하세요 · 최대 10 MB</span><input type="file" id="am-report-file" accept=".xml" aria-label="HWiNFO XML 보고서 선택" required></label>
|
||||
<div id="am-report-preview" hidden></div>
|
||||
<div id="am-import-fields" class="am-form-grid" hidden><label>자산명 <span>*</span><input id="am-import-name" maxlength="200" required></label><label>위치<input id="am-import-location" maxlength="150" list="am-locations" placeholder="예: 본사 3층"></label></div>
|
||||
<div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><span id="am-upload-status" class="am-muted"></span><button type="button" class="erp-btn erp-btn-outline" data-close="am-upload">취소</button><button type="submit" class="erp-btn erp-btn-primary" id="am-import-save" disabled>자산으로 등록</button></div>
|
||||
</form></dialog>
|
||||
<dialog id="am-action" class="am-dialog am-action-dialog" aria-labelledby="am-action-title"><div class="am-dialog-head"><div><small id="am-action-tag"></small><h2 id="am-action-title">자산 배정</h2></div><button type="button" class="am-close" data-close="am-action" aria-label="처리 창 닫기">×</button></div><form id="am-action-form" class="am-form"><p id="am-action-hint" class="am-form-hint"></p><label id="am-action-user-label">배정할 사용자 <span>*</span><select id="am-action-user"><option value="">사용자 선택</option></select></label><label>자산 위치<input id="am-action-location" list="am-locations" maxlength="150"></label><label>처리 메모<textarea id="am-action-note" maxlength="2000" rows="3" placeholder="배정 사유, 반납 상태, 수리 내용 등을 기록하세요."></textarea></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-action">취소</button><button type="submit" class="erp-btn erp-btn-primary" id="am-action-save">처리하기</button></div></form></dialog>
|
||||
<dialog id="am-help" class="am-dialog" aria-labelledby="am-help-title"><div class="am-dialog-head"><h2 id="am-help-title">자산관리 사용 안내</h2><button class="am-close" data-close="am-help" aria-label="사용 안내 닫기">×</button></div><div class="am-form am-help"><h3>01. 자산 등록</h3><p>책상·의자·마우스 등은 개별 자산으로 등록합니다. 자산번호를 비워두면 자동 발급합니다. 컴퓨터는 HWiNFO 보고서를 가져오면 이름과 주요 사양을 확인하고 등록할 수 있습니다.</p><h3>02. 배정과 반납</h3><p>사용 가능한 자산을 등록된 회사 사용자에게 배정합니다. 사용 중인 자산은 반납 후 수리·폐기할 수 있습니다. 위치·사유와 처리자가 이력에 남습니다. 분실 처리 시 기존 배정 사용자도 기록됩니다.</p><h3>03. 컴퓨터 사양</h3><p>HWiNFO → 보고서 저장 → XML 형식을 선택합니다. 핵심 사양, 부품별 상세와 보고서 전체 항목을 볼 수 있습니다. 재업로드할 때 컴퓨터 이름을 확인하세요. 이전 보고서와 원본 XML은 보존됩니다.</p><h3>04. 찾기와 내보내기</h3><p>검색·분류·상태·위치·사용자 필터를 조합합니다. 엑셀 내보내기는 현재 필터에 해당하는 자산 전체를 포함하며 최대 10,000개입니다. 보증 만료 예정은 오늘부터 30일 이내입니다.</p><p class="am-form-hint">보고서에는 시리얼·MAC 주소 등 회사 장비 정보가 포함될 수 있습니다. 자산관리 권한을 가진 사용자만 조회할 수 있습니다.</p></div></dialog>
|
||||
<datalist id="am-locations"></datalist>
|
||||
<dialog id="am-photo" class="am-dialog" aria-labelledby="am-photo-title"><div class="am-dialog-head"><h2 id="am-photo-title">자산 사진 등록</h2><button type="button" class="am-close" data-close="am-photo" aria-label="사진 등록 닫기">×</button></div><form id="am-photo-form" class="am-form"><p class="am-form-hint">JPG · PNG · WebP, 파일당 8 MB 이하 · 자산당 최대 10장. 촬영 위치 정보는 제거해 보관합니다.</p><label>사진 선택<input id="am-photo-file" type="file" accept="image/jpeg,image/png,image/webp" required></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-photo">취소</button><button type="submit" class="erp-btn erp-btn-primary">사진 저장</button></div></form></dialog>
|
||||
<dialog id="am-delete" class="am-dialog" aria-labelledby="am-delete-title"><div class="am-dialog-head"><h2 id="am-delete-title">자산 삭제</h2><button type="button" class="am-close" data-close="am-delete" aria-label="삭제 창 닫기">×</button></div><form id="am-delete-form" class="am-form"><p class="am-warning" id="am-delete-hint"></p><p class="am-form-hint">자산대장과 현황에서 제외됩니다. 사진·보고서·처리 이력은 보존됩니다.</p><label>삭제할 자산번호 확인<input id="am-delete-confirm" required autocomplete="off"></label><label>삭제 사유<textarea id="am-delete-note" required maxlength="2000" rows="3"></textarea></label><div class="am-form-error" role="alert" hidden></div><div class="am-dialog-footer"><button type="button" class="erp-btn erp-btn-outline" data-close="am-delete">취소</button><button type="submit" class="erp-btn am-danger">자산 삭제</button></div></form></dialog>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script id="am-config" type="application/json">{{ {"categories":categories,"statuses":statuses}|tojson }}</script><script src="/static/asset.js?v=20261007a" defer></script>{% endblock %}
|
||||
@@ -5,12 +5,23 @@
|
||||
바꾸지도 알림을 받지도 않는다(기록 자체는 업무 이력으로 남긴다).
|
||||
|
||||
프로젝트
|
||||
관리(=보기·작업 CRUD) : 관리자(is_admin) · 프로젝트 owner · 배정 멤버. 모두 `project` 모듈 권한이 있어야 한다.
|
||||
관리(=보기·작업 CRUD) : 프로젝트 owner · 배정 멤버 · 슈퍼관리자. 모두 `project` 모듈 권한이 있어야 한다.
|
||||
(2026-10-07 — 관리자(is_admin)도 멤버가 아닌 프로젝트는 보이지 않는다. 예외는 슈퍼관리자 한 명뿐.
|
||||
멤버 배정은 Pro user 이상(2026-10-12) — 라우터의 _require_pro, 아래 등급 표.)
|
||||
|
||||
등급(2026-10-12, app.store.ROLES) — 수퍼관리자 > admin > pro > user
|
||||
is_project_admin : 수퍼관리자·admin — 남이 만든 프로젝트·섹션도 삭제.
|
||||
is_pro : 수퍼관리자·admin·pro — 새 프로젝트 만들기, 프로젝트 이름·색·아이콘·소유자 수정,
|
||||
멤버 배정·제외(자기가 멤버인 프로젝트), 사이드바 순서, 남의 댓글 수정·삭제,
|
||||
휴지통 보기·복구, 전체 보기, 대시보드 담당자별 합계, 전체 멤버 메뉴,
|
||||
목표 표 입력·구조 변경·주차별 목표·연도 추가/삭제, 회의 완료·완료 해제·회의록 삭제.
|
||||
user : 멤버인 프로젝트의 작업·섹션·서브프로젝트·작업 삭제, 회의록 작성(완료 전까지).
|
||||
프로젝트 단위 권한은 등급과 상관없이 멤버(owner)여야 한다 — 위 is_pro 권한도 멤버인 프로젝트 안에서만.
|
||||
|
||||
작업
|
||||
FULL : 원 소속 프로젝트를 관리할 수 있음 → 보기·수정·댓글·첨부·삭제(삭제는 추가로 생성자 규칙)
|
||||
FULL : 원 소속 프로젝트를 관리할 수 있음 → 보기·수정·댓글·첨부·삭제(작업 삭제는 멤버 누구나, 2026-10-12)
|
||||
READ : 원 소속 권한은 없지만, 이 작업(또는 상위 작업)이 연결된(멀티호밍) 프로젝트를 관리할 수 있음
|
||||
→ 그 작업의 상세·하위 작업 목록·댓글·첨부 보기만. 원 소속의 다른 작업·멤버는 보이지 않는다.
|
||||
→ 그 작업의 상세·세부 작업 목록·댓글·첨부 보기만. 원 소속의 다른 작업·멤버는 보이지 않는다.
|
||||
연결된 프로젝트 안에서의 섹션 이동(POST /links, 이미 연결된 경우)은 예전처럼 허용.
|
||||
None : 권한 없음 → 403/목록에서 제외/알림·메일 대상 제외
|
||||
"""
|
||||
@@ -34,10 +45,34 @@ def default_user_lookup(email: str) -> dict[str, Any] | None:
|
||||
return user_store.get(store.norm_str(email, lower=True))
|
||||
|
||||
|
||||
def _is_admin(user: dict[str, Any] | None) -> bool:
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
def _is_super(user: dict[str, Any] | None) -> bool:
|
||||
"""슈퍼관리자(app.store.SUPER_ADMIN_EMAIL) — 모든 프로젝트를 보는 유일한 예외."""
|
||||
from app.store import SUPER_ADMIN_EMAIL # noqa: WPS433
|
||||
|
||||
return is_admin(user)
|
||||
return bool(user) and email_of(user) == SUPER_ADMIN_EMAIL
|
||||
|
||||
|
||||
def role_of(user: dict[str, Any] | None) -> str:
|
||||
"""등급 — 'super' · 'admin' · 'pro' · 'user'. 모르는 role 값은 user 로 본다."""
|
||||
if _is_super(user):
|
||||
return "super"
|
||||
role = (user or {}).get("role")
|
||||
return role if role in ("admin", "pro") else "user"
|
||||
|
||||
|
||||
def is_project_admin(user: dict[str, Any] | None) -> bool:
|
||||
"""수퍼관리자·admin — 만든 사람이 아니어도 프로젝트·섹션을 지운다."""
|
||||
return role_of(user) in ("super", "admin")
|
||||
|
||||
|
||||
def is_pro(user: dict[str, Any] | None) -> bool:
|
||||
"""수퍼관리자·admin·pro — 프로젝트 관리·목표 입력 등 운영 권한(모듈 docstring 의 등급 표)."""
|
||||
return role_of(user) in ("super", "admin", "pro")
|
||||
|
||||
|
||||
def sees_all_projects(user: dict[str, Any] | None) -> bool:
|
||||
"""멤버가 아니어도 모든 프로젝트를 보는가 — 슈퍼관리자만(모듈 권한도 있어야)."""
|
||||
return can_use_module(user) and _is_super(user)
|
||||
|
||||
|
||||
def can_use_module(user: dict[str, Any] | None) -> bool:
|
||||
@@ -51,10 +86,10 @@ def email_of(user: dict[str, Any] | None) -> str:
|
||||
|
||||
|
||||
def can_manage_project(st: Any, user: dict[str, Any] | None, project_id: Any) -> bool:
|
||||
"""프로젝트 관리(=보기·작업 CRUD) — 관리자 또는 owner/멤버. 모듈 권한이 없으면 False."""
|
||||
"""프로젝트 관리(=보기·작업 CRUD) — owner/멤버(관리자도 마찬가지), 슈퍼관리자는 전부. 모듈 권한이 없으면 False."""
|
||||
if not can_use_module(user):
|
||||
return False
|
||||
if _is_admin(user):
|
||||
if _is_super(user):
|
||||
return True
|
||||
try:
|
||||
pid = int(project_id)
|
||||
@@ -64,11 +99,11 @@ def can_manage_project(st: Any, user: dict[str, Any] | None, project_id: Any) ->
|
||||
|
||||
|
||||
def visible_project_ids(st: Any, user: dict[str, Any]) -> set[int] | None:
|
||||
"""관리할 수 있는 프로젝트 id 집합. 관리자는 None(=전체)."""
|
||||
if _is_admin(user):
|
||||
return None
|
||||
"""관리할 수 있는 프로젝트 id 집합. 슈퍼관리자는 None(=전체), 그 밖(관리자 포함)은 owner·멤버인 프로젝트만."""
|
||||
if not can_use_module(user):
|
||||
return set()
|
||||
if _is_super(user):
|
||||
return None
|
||||
return {
|
||||
int(p["id"]) for p in st.list_projects(include_archived=True, member_email=email_of(user))
|
||||
}
|
||||
|
||||
+741
-199
File diff suppressed because it is too large
Load Diff
+750
-315
File diff suppressed because it is too large
Load Diff
+121
-16
@@ -40,7 +40,7 @@ ACTION_ASSIGNED = "assigned"
|
||||
ACTION_COMPLETED = "completed"
|
||||
ACTION_STAGE_CHANGED = "stage_changed"
|
||||
ACTION_REOPENED = "reopened"
|
||||
ACTION_SUBTASK_MOVED = "subtask_moved" # 하위 업무를 다른 상위 업무로 옮김(보드 드래그)
|
||||
ACTION_SUBTASK_MOVED = "subtask_moved" # 세부 업무를 다른 상위 업무로 옮김(보드 드래그)
|
||||
|
||||
# 프로젝트 색상 팔레트 — 32색(8칸 × 4줄). 앞 16색은 아사나 프로젝트 색(아사나 색상표
|
||||
# 순서 그대로), 뒤 16색은 같은 칸(열)에 대응하는 진한 색 — 3줄째 = 1줄째의 진한 색,
|
||||
@@ -131,6 +131,22 @@ PROJECT_ICONS: tuple[str, ...] = (
|
||||
"build", # 도구
|
||||
)
|
||||
|
||||
# 아사나 아이콘(2026-10-08) — 아사나 프로젝트 아이콘과 같은 채워진 모양. 저장 값은 "asana:" + 이름,
|
||||
# 글꼴은 이 33개만 담은 채워진 Material Symbols(static/vendor/material-symbols/material-symbols-asana.woff2).
|
||||
# 이름을 늘리면 그 글꼴도 다시 받아야 한다(docs/PROJECT_MODULE.md 6-12).
|
||||
ASANA_ICON_PREFIX = "asana:"
|
||||
PROJECT_ASANA_ICONS: tuple[str, ...] = (
|
||||
"format_list_bulleted", "view_kanban", "view_timeline", "calendar_month",
|
||||
"rocket_launch", "group", "monitoring", "stars",
|
||||
"bug_report", "lightbulb", "language", "settings",
|
||||
"book_2", "desktop_windows", "check_circle", "adjust",
|
||||
"code_blocks", "campaign", "forum", "work",
|
||||
"article", "landscape", "extension", "id_card",
|
||||
"conversion_path", "speed", "workspace_premium", "steps",
|
||||
"shopping_basket", "map", "confirmation_number", "toll",
|
||||
"web",
|
||||
)
|
||||
|
||||
# 섹션(칸반 컬럼) 색상표 — 모든 편집창이 프로젝트 색상표(32색) 하나를 쓴다.
|
||||
# 섹션에서는 첫 칸(연회색 #c7c4c4, 아사나의 "색 없음")을 고르면 색 없음(NULL, 기본 회색 머리).
|
||||
STAGE_COLOR_PALETTE: tuple[str, ...] = COLOR_PALETTE
|
||||
@@ -288,8 +304,10 @@ def validate_color(color: Any) -> str:
|
||||
|
||||
|
||||
def validate_project_icon(icon: Any) -> str | None:
|
||||
"""프로젝트 아이콘 — PROJECT_ICONS 안의 이름만, 빈값/목록 밖은 None(첫 글자 표시)."""
|
||||
"""프로젝트 아이콘 — PROJECT_ICONS 안의 이름 또는 "asana:" + PROJECT_ASANA_ICONS 이름만, 빈값/목록 밖은 None(첫 글자 표시)."""
|
||||
v = norm_str(icon)
|
||||
if v.startswith(ASANA_ICON_PREFIX):
|
||||
return v if v[len(ASANA_ICON_PREFIX):] in PROJECT_ASANA_ICONS else None
|
||||
return v if v in PROJECT_ICONS else None
|
||||
|
||||
|
||||
@@ -401,6 +419,22 @@ class GoalCellConflict(RuntimeError):
|
||||
"""셀 이동 전에 다른 창에서 원본 또는 대상 내용이 바뀜."""
|
||||
|
||||
|
||||
class MeetingCellMigrationNeeded(RuntimeError):
|
||||
"""회의록 셀 병합 메타데이터(019)가 아직 없다."""
|
||||
|
||||
|
||||
class MeetingLocked(RuntimeError):
|
||||
"""회의 완료(022)된 회의록은 고칠 수 없다(관리자가 완료 해제하면 다시)."""
|
||||
|
||||
|
||||
class MeetingMigration022Needed(RuntimeError):
|
||||
"""회의 완료(잠금)는 마이그레이션 022 뒤에만 된다."""
|
||||
|
||||
|
||||
class MeetingMigration020Needed(RuntimeError):
|
||||
"""새 주차(월요일이 아닌 시작일)·결과 글 칸·주차별 목표는 마이그레이션 020 뒤에만 된다."""
|
||||
|
||||
|
||||
GOAL_YEAR = 0 # 업무 영역 글 칸 — 연간
|
||||
# 분기 글 칸(2026-10-01 상·하반기 → 1~4분기). 칸 번호는 예전 반기 칸을 그대로 이어 쓴다 — 데이터 옮기기 없이
|
||||
# 예전 상반기 글(13)은 1분기, 하반기 글(14)은 3분기에 보인다. 2분기(15)·4분기(16)는 마이그레이션 017 뒤에 저장.
|
||||
@@ -531,8 +565,9 @@ def goal_text_plain(body: Any) -> str:
|
||||
return "".join(r["text"] for r in goal_text_runs(body))
|
||||
|
||||
|
||||
def goal_text_html(body: Any) -> str:
|
||||
"""허용한 글자 서식만 HTML로 만든다. 사용자 텍스트는 항상 escape한다."""
|
||||
def goal_text_html(body: Any, *, include_size: bool = True) -> str:
|
||||
"""허용한 글자 서식만 HTML로 만든다. 사용자 텍스트는 항상 escape한다.
|
||||
월간 계획 요약에서는 include_size=False로 글자 크기만 화면 기본값을 사용한다."""
|
||||
out = []
|
||||
for run in goal_text_runs(body):
|
||||
style = []
|
||||
@@ -544,7 +579,7 @@ def goal_text_html(body: Any) -> str:
|
||||
style.append("text-decoration:" + ("underline" if run["underline"] else "none"))
|
||||
if "color" in run:
|
||||
style.append("color:" + run["color"])
|
||||
if "size" in run:
|
||||
if include_size and "size" in run:
|
||||
style.append(f'font-size:{run["size"]}px')
|
||||
text = escape(run["text"])
|
||||
out.append(f'<span style="{";".join(style)}">{text}</span>' if style else text)
|
||||
@@ -563,6 +598,23 @@ def merge_goal_texts(bodies: list[str]) -> str:
|
||||
return validate_goal_text(GOAL_RICH_PREFIX + json.dumps(runs, ensure_ascii=False))
|
||||
|
||||
|
||||
def validate_meeting_content(body: Any) -> str:
|
||||
"""회의록 편집기와 같은 서식 조각 합치기로 이동 예상값을 비교한다."""
|
||||
value = validate_goal_text(body)
|
||||
if not value.startswith(GOAL_RICH_PREFIX):
|
||||
return value
|
||||
runs: list[dict[str, Any]] = []
|
||||
keys = ("bold", "italic", "underline", "color", "size")
|
||||
for run in goal_text_runs(value):
|
||||
if runs and all(runs[-1].get(k) == run.get(k) for k in keys):
|
||||
runs[-1]["text"] += run["text"]
|
||||
else:
|
||||
runs.append(dict(run))
|
||||
if not any(len(run) > 1 for run in runs):
|
||||
return validate_goal_text("".join(run["text"] for run in runs))
|
||||
return GOAL_RICH_PREFIX + json.dumps(runs, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
|
||||
# ── 엑셀식 사각형 병합(마이그레이션 015) ──────────────────────────────
|
||||
class GoalMigration015Needed(RuntimeError):
|
||||
"""세로 병합·주간 회의록은 마이그레이션 015 뒤에만 된다."""
|
||||
@@ -605,6 +657,7 @@ def validate_goal_rect_cols(col_from: Any, col_to: Any) -> tuple[int, int]:
|
||||
MEETING_STATUS: dict[str, str] = {"": "", "done": "완료", "partial": "일부", "miss": "미달"}
|
||||
MEETING_TEXT_MAX = 4000
|
||||
MEETING_LABEL_MAX = 50
|
||||
MEETING_AMOUNT_TEXT_MAX = 100 # 정량 목표·결과 글(021, 예: "20개")
|
||||
# 첫 회의록(이전 주 회의록이 없을 때)의 구역별 줄 — 사용자 회의록 양식(2026-10). 목표 표의 업무 영역 이름과 같으면
|
||||
# 그 줄들로, 없는 구역은 빈 줄 하나. 다음 주부터는 지난주 회의록 줄을 그대로 이어받는다.
|
||||
MEETING_TEMPLATE: dict[str, tuple[str, ...]] = {
|
||||
@@ -641,20 +694,44 @@ def month_last_day(year: int, month: int) -> date:
|
||||
|
||||
|
||||
def month_weeks(year: int, month: int) -> list[tuple[date, date]]:
|
||||
"""그 달의 주(월요일~일요일) 목록 — **1주차 = 그 달 첫 월요일이 있는 주**, 주는 월요일이 속한 달의 것
|
||||
(2026-10-01 사용자 기준). 예: 2026년 10월 = 10/5·12·19·26 주, 9/28~10/4 주는 9월 마지막 주.
|
||||
월간 목표·누적은 이와 따로 늘 1일~말일."""
|
||||
"""그 달의 주차(시작일, 끝일) — 2026-10-07 사용자 기준. 주차는 늘 그 달 안(달을 넘지 않는다).
|
||||
· 1일이 월~금이면 1주차 = 1일 ~ 그 주 일요일(월요일 시작이 아니어도 1주차)
|
||||
· 1일이 토·일이면 1주차 = 1일 ~ 다음 주 일요일(토·일 + 다음 월~일)
|
||||
· 그 뒤는 월~일. 말일이 월·화이면 그 하루·이틀은 앞 주차에 붙는다(마지막 주차 = 월~다음 주 월·화).
|
||||
예: 2026년 10월(1일 목·31일 토) = 10/1~4 · 5~11 · 12~18 · 19~25 · 26~31.
|
||||
월간 목표·누적은 늘 1일~말일."""
|
||||
first = date(year, month, 1)
|
||||
last = month_last_day(year, month)
|
||||
out, mon = [], first + timedelta(days=(7 - first.weekday()) % 7)
|
||||
while mon <= last:
|
||||
out.append((mon, mon + timedelta(days=6)))
|
||||
mon += timedelta(days=7)
|
||||
wd = first.weekday()
|
||||
end = first + timedelta(days=6 - wd + (7 if wd >= 5 else 0))
|
||||
out = [(first, end)]
|
||||
s = end + timedelta(days=1)
|
||||
while s <= last:
|
||||
out.append((s, min(s + timedelta(days=6), last)))
|
||||
s += timedelta(days=7)
|
||||
if len(out) > 1 and last.weekday() <= 1: # 말일이 월·화 — 앞 주차에 붙인다
|
||||
out.pop()
|
||||
out[-1] = (out[-1][0], last)
|
||||
return out
|
||||
|
||||
|
||||
def week_period(d: date) -> tuple[date, date]:
|
||||
"""그 날짜가 든 주차(시작일, 끝일)."""
|
||||
return next(p for p in month_weeks(d.year, d.month) if p[0] <= d <= p[1])
|
||||
|
||||
|
||||
def prev_week_period(start: date) -> tuple[date, date]:
|
||||
"""바로 앞 주차(앞 달 마지막 주차일 수 있다) — 회의록의 "지난주"."""
|
||||
return week_period(start - timedelta(days=1))
|
||||
|
||||
|
||||
def week_number(start: date) -> int:
|
||||
"""주차 시작일 → 그 달 몇 주차(1부터). 주차 시작일이 아니면 그 날짜가 든 주차."""
|
||||
return next(i + 1 for i, (a, b) in enumerate(month_weeks(start.year, start.month)) if a <= start <= b)
|
||||
|
||||
|
||||
def calendar_weeks(year: int, month: int) -> list[tuple[date, date]]:
|
||||
"""작은 달력용 — 그 달 날짜가 하나라도 든 주(월요일 시작) 전부(1일이 든 주부터 말일이 든 주까지)."""
|
||||
"""작은 달력용 — 그 달 날짜가 하나라도 든 줄(월요일 시작) 전부(1일이 든 줄부터 말일이 든 줄까지)."""
|
||||
first, last = date(year, month, 1), month_last_day(year, month)
|
||||
out, mon = [], week_monday(first)
|
||||
while mon <= last:
|
||||
@@ -664,17 +741,24 @@ def calendar_weeks(year: int, month: int) -> list[tuple[date, date]]:
|
||||
|
||||
|
||||
def validate_week_start(v: Any) -> date:
|
||||
"""회의록 시작일(날짜) — 020 부터 월요일이 아닐 수 있다. 주차 시작일인지는 validate_period_start."""
|
||||
try:
|
||||
d = date.fromisoformat(str(v).strip()[:10])
|
||||
except ValueError:
|
||||
raise ValueError("주 시작일이 올바르지 않습니다.")
|
||||
if d.weekday() != 0:
|
||||
raise ValueError("주 시작일은 월요일이어야 합니다.")
|
||||
if not 2000 <= d.year <= 2100:
|
||||
raise ValueError("주 시작일이 올바르지 않습니다.")
|
||||
return d
|
||||
|
||||
|
||||
def validate_period_start(v: Any) -> date:
|
||||
"""주차 시작일만(month_weeks 의 시작일) — 새 회의록·주차별 목표."""
|
||||
d = validate_week_start(v)
|
||||
if week_period(d)[0] != d:
|
||||
raise ValueError("주차 시작일이 아닙니다. 새로고침해 주세요.")
|
||||
return d
|
||||
|
||||
|
||||
def _korean_amount(s: str) -> float:
|
||||
""""1억2천만"·"3천만"·"1.5억"·"120만"·"3천5백" → 숫자. 단위 없는 숫자는 그대로. 틀리면 ValueError."""
|
||||
def small(t: str) -> float: # 만 아래 자리 — 천·백·십
|
||||
@@ -801,6 +885,23 @@ _DESC_ALLOWED_CLASS: dict[str, str] = {"span": _MENTION_CLASS, "ul": "pj-checkli
|
||||
# 허용 태그 목록에 없어 태그는 이미 안 남지만, HTMLParser는 이 둘의 내용을
|
||||
# 별도 데이터로 넘기므로 handle_data 에서 따로 걸러야 한다.
|
||||
_DESC_RAW_TEXT_TAGS: frozenset[str] = frozenset({"script", "style"})
|
||||
# 글자 색·크기(서식 도구, 2026-10-08) — 평범한 span 의 style 에서 이 둘만, 정해진 형식만 남긴다.
|
||||
_DESC_STYLE_COLOR = re.compile(r"^(#[0-9a-f]{3}|#[0-9a-f]{6}|rgb\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}\s*\))$", re.I)
|
||||
DESC_FONT_SIZES: frozenset[str] = frozenset({"12px", "18px", "22px", "28px"})
|
||||
|
||||
|
||||
def desc_inline_style(value: str) -> str:
|
||||
"""span style → "color: …; font-size: …" 중 허용된 것만(나머지 선언·url()·expression 등은 버림)."""
|
||||
kept: list[str] = []
|
||||
for decl in (value or "").split(";"):
|
||||
if ":" not in decl:
|
||||
continue
|
||||
prop, val = (x.strip().lower() for x in decl.split(":", 1))
|
||||
if prop == "color" and _DESC_STYLE_COLOR.match(val) and not any(k.startswith("color:") for k in kept):
|
||||
kept.append(f"color: {val}")
|
||||
elif prop == "font-size" and val in DESC_FONT_SIZES and not any(k.startswith("font-size:") for k in kept):
|
||||
kept.append(f"font-size: {val}")
|
||||
return "; ".join(kept)
|
||||
|
||||
|
||||
def _desc_escape_text(text: str) -> str:
|
||||
@@ -857,7 +958,7 @@ class _DescriptionSanitizer(HTMLParser):
|
||||
# span 은 멘션 칩일 때만 속성을 갖는다 — class 가 pj-mention 이 아니면
|
||||
# data-email 까지 통째로 버린다(평범한 span 으로만 남는다).
|
||||
if tag == "span" and (dict(attrs).get("class") or "").strip() != _MENTION_CLASS:
|
||||
allowed = frozenset()
|
||||
allowed = frozenset({"style"}) # 평범한 span — 글자 색·크기만(desc_inline_style)
|
||||
kept: list[str] = []
|
||||
for name, value in attrs:
|
||||
if name not in allowed:
|
||||
@@ -873,6 +974,10 @@ class _DescriptionSanitizer(HTMLParser):
|
||||
continue
|
||||
if name == "data-checked" and value.strip() != "true":
|
||||
continue
|
||||
if name == "style":
|
||||
value = desc_inline_style(value)
|
||||
if not value:
|
||||
continue
|
||||
kept.append(f'{name}="{_desc_escape_attr(value)}"')
|
||||
attr_text = (" " + " ".join(kept)) if kept else ""
|
||||
self.out.append(f"<{tag}{attr_text}>")
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
<div class="pj-goal-format" id="pj-goal-format" role="toolbar" aria-label="선택한 글자 서식" hidden>
|
||||
<div class="pj-goal-format-group pj-goal-color-picker">
|
||||
<button type="button" class="pj-goal-format-btn pj-goal-color-toggle" data-goal-format="color" aria-label="글자 색상" title="글자 색상" aria-expanded="false" aria-controls="pj-goal-color-grid" disabled><span class="pj-goal-color-letter" aria-hidden="true">가<span class="pj-goal-color-preview"></span></span><svg class="pj-goal-format-chevron" viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.3" aria-hidden="true"><path d="m2 4 3 3 3-3"/></svg></button>
|
||||
<div class="pj-goal-color-grid" id="pj-goal-color-grid" role="group" aria-label="글자 색상 선택" hidden>
|
||||
{% for color in ('#000000', '#4B5563', '#9CA3AF', '#DC2626', '#EA580C', '#CA8A04', '#16A34A', '#0891B2', '#2563EB', '#7C3AED', '#DB2777', '#FFFFFF') %}
|
||||
<button type="button" class="pj-goal-text-swatch" data-goal-color="{{ color }}" style="--swatch: {{ color }}" title="{{ color }}" aria-label="{{ color }}" aria-pressed="false" disabled></button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="pj-goal-format-group" role="group" aria-label="글자 크기">
|
||||
<button type="button" class="pj-goal-format-btn" data-goal-format="size-up" aria-label="글자 크기 2px 키우기" title="글자 크기 2px 키우기" disabled><span class="pj-goal-font-letter" aria-hidden="true">가</span><svg class="pj-goal-font-arrow" viewBox="0 0 10 14" fill="none" stroke="currentColor" stroke-width="1.2" aria-hidden="true"><path d="M5 9V2M2 5l3-3 3 3"/></svg></button>
|
||||
<button type="button" class="pj-goal-format-btn" data-goal-format="size-down" aria-label="글자 크기 2px 줄이기" title="글자 크기 2px 줄이기" disabled><span class="pj-goal-font-letter" aria-hidden="true">가</span><svg class="pj-goal-font-arrow" viewBox="0 0 10 14" fill="none" stroke="currentColor" stroke-width="1.2" aria-hidden="true"><path d="M5 2v7M2 6l3 3 3-3"/></svg></button>
|
||||
<output class="pj-goal-size-value" data-goal-format="size" aria-label="선택한 글자 크기">14px</output>
|
||||
</div>
|
||||
<div class="pj-goal-format-group" role="group" aria-label="글자 모양">
|
||||
{% for key, label in (('bold', '굵게'), ('italic', '기울임'), ('underline', '밑줄')) %}
|
||||
<button type="button" class="pj-goal-format-btn" data-goal-format="{{ key }}" aria-label="{{ label }}" title="{{ label }}" aria-pressed="false" disabled><span class="pj-goal-font-letter" aria-hidden="true">가</span></button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="pj-goal-format-group" role="group" aria-label="서식 초기화">
|
||||
<button type="button" class="pj-goal-format-btn" data-goal-format="reset" aria-label="서식 초기화" title="서식 초기화" disabled><svg class="pj-goal-reset-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m16 3 5 5a2 2 0 0 1 0 3L11 21H7l-4-4a2 2 0 0 1 0-3L13 3a2 2 0 0 1 3 0Z"/><path d="m8 9 7 7M11 21h10"/></svg></button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -0,0 +1,22 @@
|
||||
{# 오른쪽 회의록 전용 문서. 공통 메뉴를 다시 만들지 않고 회의록의 기존 편집 기능을 그대로 사용한다. #}
|
||||
<!doctype html>
|
||||
<html lang="ko" class="pj-meeting-content">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>{{ page_title or '주간 회의록' }}</title>
|
||||
<link rel="stylesheet" href="/static/erp.css?v=20260615b" />
|
||||
<link rel="stylesheet" href="/static/erp-dialog.css?v=20260930a" />
|
||||
{% block head_extra %}{% endblock %}
|
||||
<link rel="stylesheet" href="/static/project-goal-nav.css?v=20261004e" />
|
||||
<script>
|
||||
try { document.documentElement.dataset.pjFont = localStorage.getItem('pj_font') || 'system'; } catch (_) {}
|
||||
window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};
|
||||
</script>
|
||||
<script src="/static/project-meeting-panel.js?v=20261004a" defer></script>
|
||||
</head>
|
||||
<body class="erp-body">
|
||||
<main class="erp-page">{% block content %}{% endblock %}</main>
|
||||
<script src="/static/erp-dialog.js?v=20260930a"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,6 +1,6 @@
|
||||
{# ── 프로젝트 모듈 좌측 사이드바 (공용) ──────────────────────────────
|
||||
수신함·내 업무·휴지통·프로젝트 화면이 함께 쓴다 — 어느 화면이든 프로젝트
|
||||
목록은 똑같다(관리자: 드래그 순서 변경·✎ 수정·× 삭제·우클릭 메뉴).
|
||||
목록은 똑같다(Pro user 이상: 드래그 순서 변경·✎ 수정·× 삭제·우클릭 메뉴).
|
||||
|
||||
변수:
|
||||
mention_unread 미확인 @태그 개수 (수신함 배지)
|
||||
@@ -10,16 +10,20 @@
|
||||
side_active 'inbox' | 'mytasks' | 'trash' | 'goals' | '' — 개인 메뉴 활성 표시
|
||||
goal_years "목표" 아래 연도 목록(router._goal_years_nav — 올해는 항상 포함)
|
||||
goal_year_active 목표 화면에서 보고 있는 연도
|
||||
is_admin 프로젝트 생성/수정/삭제 권한
|
||||
pj_pro Pro user 이상 — 프로젝트 생성·수정·순서·전체 보기·휴지통·전체 멤버·연도 추가
|
||||
pj_admin Admin 이상 — 남이 만든 프로젝트도 삭제(그 밖은 만든 사람만)
|
||||
목록 동작은 project.js 의 initSideTree(첫 화면을 같은 마크업으로 다시 그림),
|
||||
새 프로젝트/수정 모달은 각 화면이 include 하는 project/_side_modals.html. #}
|
||||
{# 날짜 팝업(openDatePopover)이 공휴일을 빨강으로 칠할 때 쓰는 표 — 이 사이드바는
|
||||
프로젝트 관리의 모든 화면에 들어가므로 여기서 한 번 넘긴다(main.py 의 Jinja 전역). #}
|
||||
<script>window.PJ_HOLIDAYS = {{ (pj_kr_holidays or {}) | tojson }};</script>
|
||||
<aside class="pj-side" data-is-admin="{{ 'true' if is_admin else 'false' }}"
|
||||
{# 모든 프로젝트 화면에서 같은 회의록 트리를 사용한다. #}
|
||||
<link rel="stylesheet" href="/static/project-goal-nav.css?v=20261004e" />
|
||||
<script src="/static/project-goal-nav.js?v=20261004d" defer></script>
|
||||
<aside class="pj-side" data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
|
||||
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}"
|
||||
data-me="{{ user.email }}">
|
||||
<!-- 전체 검색 — 제목·설명·댓글, 내가 볼 수 있는 모든 프로젝트(하위 업무 포함).
|
||||
<!-- 전체 검색 — 제목·설명·댓글, 내가 볼 수 있는 모든 프로젝트(세부 업무 포함).
|
||||
결과를 누르면 그 업무 팝업(/project/t/{id})으로. 어디서든 "/" 키로 포커스. -->
|
||||
<div class="pj-side-search">
|
||||
<span class="material-symbols-outlined pj-side-search-ic">search</span>
|
||||
@@ -35,14 +39,25 @@
|
||||
<span class="pj-side-navbadge" id="pj-mention-badge"
|
||||
{% if not mention_unread %}hidden{% endif %}>{{ mention_unread }}</span>
|
||||
</a>
|
||||
{# 전체 보기(2026-10-08, Pro user 이상 — 멤버인 프로젝트 범위) — 예전 프로젝트 화면 오른쪽 위 "전체 프로젝트" 토글. 지금 프로젝트(없으면 목록 첫 프로젝트)
|
||||
화면을 ?scope=all 로 연다 — 볼 수 있는 모든 프로젝트의 작업. 프로젝트 화면에서는 project.js 가 새로고침 없이 바꾼다. #}
|
||||
{% if pj_pro %}
|
||||
{% 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">
|
||||
<span class="material-symbols-outlined pj-side-navic">apps</span>
|
||||
<span class="pj-side-navtext">전체 보기</span>
|
||||
</a>
|
||||
{% endif %}
|
||||
{% endif %}
|
||||
<a class="pj-side-navlink {% if side_active == 'mytasks' %}is-active{% endif %}" href="/project/">
|
||||
<span class="material-symbols-outlined pj-side-navic">checklist</span>
|
||||
<span class="pj-side-navtext">내 작업</span>
|
||||
<span class="pj-side-navbadge pj-side-navbadge-open" id="pj-myopen-badge"
|
||||
{% if not my_open_total %}hidden{% endif %}>{{ my_open_total }}</span>
|
||||
</a>
|
||||
{# 휴지통 — 관리자만 보이고(화면·복구 API 도 관리자 전용), 지운 업무를 3개월 보관. #}
|
||||
{% if is_admin %}
|
||||
{# 휴지통 — Pro user 이상만 보이고(화면·복구 API 도 같음), 지운 업무를 3개월 보관. #}
|
||||
{% if pj_pro %}
|
||||
<a class="pj-side-navlink {% if side_active == 'trash' %}is-active{% endif %}" href="/project/trash">
|
||||
<span class="material-symbols-outlined pj-side-navic">delete</span>
|
||||
<span class="pj-side-navtext">휴지통</span>
|
||||
@@ -50,7 +65,7 @@
|
||||
{% endif %}
|
||||
{# 목표 — 누르면 바로 아래에 연도가 펼쳐지고, 연도를 누르면 오른쪽에 그해 전체 목표
|
||||
(/project/goals/{연도}). 펼침 상태는 localStorage(pj_goal_open), 목표 화면에서는 항상 펼침.
|
||||
연도 추가는 관리자만(마이그레이션 013). #}
|
||||
연도 추가는 Pro user 이상(마이그레이션 013). #}
|
||||
{% set goal_open = side_active == 'goals' %}
|
||||
<div class="pj-side-goal{% if goal_open %} is-open{% endif %}" id="pj-side-goal"
|
||||
data-force-open="{{ 'true' if goal_open else 'false' }}">
|
||||
@@ -62,10 +77,20 @@
|
||||
</button>
|
||||
<div class="pj-side-goal-years" id="pj-side-goal-years"{% if not goal_open %} hidden{% endif %}>
|
||||
{% for y in (goal_years or []) %}
|
||||
<div class="pj-side-goal-branch" data-goal-year="{{ y }}">
|
||||
{# 화살표는 하위 월을 접고 펼치고, 연도 글자는 기존 목표 화면을 연다. #}
|
||||
<div class="pj-side-goal-year-row">
|
||||
<button type="button" class="pj-side-goal-year-toggle" aria-expanded="true"
|
||||
aria-controls="pj-side-meeting-months-{{ y }}" aria-label="{{ y }}년 하위 월 접기" title="하위 월 접기">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">chevron_right</span>
|
||||
</button>
|
||||
<a class="pj-side-goal-year{% if side_active == 'goals' and y == goal_year_active %} is-active{% endif %}"
|
||||
href="/project/goals/{{ y }}">{{ y }}년</a>
|
||||
</div>
|
||||
<div class="pj-side-meeting-months" id="pj-side-meeting-months-{{ y }}" data-current-week="{{ week if goal_month is defined else '' }}"></div>
|
||||
</div>
|
||||
{% endfor %}
|
||||
{% if is_admin %}
|
||||
{% if pj_pro %}
|
||||
<button type="button" class="pj-side-goal-add" id="pj-goal-year-add"
|
||||
data-next="{{ ((goal_years or [0]) | max) + 1 }}">+ 연도 추가</button>
|
||||
{% endif %}
|
||||
@@ -76,23 +101,23 @@
|
||||
<div class="pj-side-block pj-tree-block">
|
||||
<div class="pj-side-head">
|
||||
<span>프로젝트</span>
|
||||
{% if is_admin %}
|
||||
{% if pj_pro %}
|
||||
<button type="button" class="pj-icon-btn" id="pj-new-project-side" title="새 프로젝트">+</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% macro nav_li(p) %}
|
||||
<li class="pj-tree-li" data-id="{{ p.id }}"{% if is_admin %} draggable="true"{% endif %}
|
||||
<li class="pj-tree-li" data-id="{{ p.id }}"{% if pj_pro %} draggable="true"{% endif %}
|
||||
data-name="{{ p.name }}" data-desc="{{ p.description or '' }}"
|
||||
data-start="{{ p.start_date or '' }}" data-due="{{ p.due_date or '' }}"
|
||||
data-color="{{ p.color }}" data-status="{{ p.status or 'active' }}"
|
||||
data-creator="{{ p.created_by or '' }}" data-icon="{{ p.icon or '' }}">
|
||||
<div class="pj-tree-row {% if p.id == current_pid %}is-active{% endif %}">
|
||||
{% if is_admin %}<span class="pj-tree-handle" title="드래그로 순서 변경">⣿</span>{% endif %}
|
||||
<a class="pj-tree-link" href="/project/p/{{ p.id }}"{% if is_admin %} draggable="false"{% endif %}>
|
||||
<span class="pj-tree-avatar{% if p.icon %} has-icon{% endif %}" style="background: {{ p.color }}">{% if p.icon %}<span class="material-symbols-outlined pj-proj-ic">{{ p.icon }}</span>{% else %}{{ p.name[0] | upper }}{% endif %}</span>
|
||||
{% if pj_pro %}<span class="pj-tree-handle" title="드래그로 순서 변경">⣿</span>{% endif %}
|
||||
<a class="pj-tree-link" href="/project/p/{{ p.id }}"{% if pj_pro %} draggable="false"{% endif %}>
|
||||
<span class="pj-tree-avatar{% if p.icon %} has-icon{% endif %}" style="background: {{ p.color }}">{% if p.icon %}{% set _a = p.icon.startswith("asana:") %}<span class="material-symbols-outlined pj-proj-ic{% if _a %} pj-ic-asana{% endif %}">{{ p.icon[6:] if _a else p.icon }}</span>{% else %}{{ p.name[0] | upper }}{% endif %}</span>
|
||||
<span class="pj-tree-name">{{ p.name }}</span>
|
||||
</a>
|
||||
{% if is_admin %}
|
||||
{% if pj_pro %}
|
||||
<span class="pj-tree-acts">
|
||||
<button type="button" class="pj-icon-btn pj-tree-edit" data-id="{{ p.id }}"
|
||||
data-name="{{ p.name }}" data-desc="{{ p.description or '' }}"
|
||||
@@ -121,11 +146,11 @@
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
<!-- 전체 멤버 — 등록된 전체 직원(프로젝트 권한 보유자). 관리자 전용
|
||||
(/api/all-users 도 관리자만). 아이콘 클릭 시 그 사람이 담당자인 업무를
|
||||
<!-- 전체 멤버 — 등록된 전체 직원(프로젝트 권한 보유자). Pro user 이상
|
||||
(/api/all-users 는 @태그 후보로 누구나 부른다). 아이콘 클릭 시 그 사람이 담당자인 업무를
|
||||
팝업으로 보여준다(프로젝트/세션/마감일). 수신함·내 업무·프로젝트 화면
|
||||
모두에서 보인다 — 팝업 마크업은 _member_tasks_modal.html. -->
|
||||
{% if is_admin %}
|
||||
{% if pj_pro %}
|
||||
<div class="pj-side-block">
|
||||
<div class="pj-side-head"><span>전체 멤버</span></div>
|
||||
<div class="pj-allmembers-grid" id="pj-allmembers-grid">불러오는 중…</div>
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
{# ── 좌측 프로젝트 목록(project/_side.html)용 모달 (공용) ──────────────
|
||||
"+" 새 프로젝트 / ✎ 프로젝트 수정 — 수신함·내 업무·휴지통·프로젝트 화면이
|
||||
모두 include 한다(동작은 project.js 의 initSideTree). 관리자만 쓰므로
|
||||
관리자에게만 그린다. 색상 원은 window.PJ_COLORS(color_palette, 32색),
|
||||
모두 include 한다(동작은 project.js 의 initSideTree). Pro user 이상만 쓰므로
|
||||
그들에게만 그린다. 색상 원은 window.PJ_COLORS(color_palette, 32색),
|
||||
아이콘은 window.PJ_ICONS(project_icons — Material Symbols 이름). #}
|
||||
<script>
|
||||
window.PJ_COLORS = {{ color_palette | tojson }};
|
||||
window.PJ_ICONS = {{ (project_icons or []) | tojson }};
|
||||
window.PJ_ASANA_ICONS = {{ (project_asana_icons or []) | tojson }}; {# 아사나 아이콘 탭 — 값은 "asana:" + 이름 #}
|
||||
</script>
|
||||
{% if is_admin %}
|
||||
{% if pj_pro %}
|
||||
<!-- 새 프로젝트 모달 — 좌측 프로젝트 목록의 + 버튼 -->
|
||||
<div class="pj-modal" id="pj-modal-project" hidden>
|
||||
<div class="pj-modal-card">
|
||||
@@ -21,12 +22,13 @@
|
||||
<div class="pj-field-label">색상
|
||||
<span class="pj-color-palette" id="pj-f-colors"></span>
|
||||
</div>
|
||||
<div class="pj-field-label">아이콘
|
||||
<div class="pj-field-label">아이콘<span class="pj-icon-tabs"></span>
|
||||
<div class="pj-icon-palette" id="pj-f-icons"></div>
|
||||
</div>
|
||||
<div class="pj-field-label">멤버
|
||||
<div class="pj-member-picker" id="pj-f-members">불러오는 중…</div>
|
||||
</div>
|
||||
<p class="pj-modal-msg" id="pj-f-project-msg" role="status" hidden></p>
|
||||
<div class="pj-modal-actions">
|
||||
<button type="button" class="pj-btn" data-close>취소</button>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-save-project">만들기</button>
|
||||
@@ -49,7 +51,7 @@
|
||||
<div class="pj-field-label">색상
|
||||
<span class="pj-color-palette" id="pj-e-colors"></span>
|
||||
</div>
|
||||
<div class="pj-field-label">아이콘
|
||||
<div class="pj-field-label">아이콘<span class="pj-icon-tabs"></span>
|
||||
<div class="pj-icon-palette" id="pj-e-icons"></div>
|
||||
</div>
|
||||
<label class="pj-time-toggle">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% extends "project/_meeting_content_base.html" if meeting_embedded else "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -11,17 +11,22 @@
|
||||
{%- macro num(v) -%}{% if v is not none %}{% if v == v | int %}{{ "{:,}".format(v | int) }}{% else %}{{ "{:,.2f}".format(v) }}{% endif %}{% endif %}{%- endmacro -%}
|
||||
|
||||
{% block content %}
|
||||
{# 주간 회의록 — 목표 표 월 머리를 누르면 열린다(/project/goals/{연도}/meetings/{월}?week=월요일).
|
||||
주(월~일)마다 회의록 하나: 머리(월 목표·지난주까지 누적·주당 필요 매출, 전주 목표·결과, 금주 목표·현재)
|
||||
+ 구역(목표 표 업무 영역)별 줄 — 이번주 할 일·정량 목표 | 전주 할 일·목표·결과·달성률·평가.
|
||||
전주 칸은 지난 회의록의 같은 줄(carry_from). 쇼핑몰 연결 줄의 결과·전주/금주 매출·누적은 실적 모듈에서 자동.
|
||||
입력은 관리자만(칸별 즉시 저장, project.js initGoalMeeting). DB: project_db 015 (goal_meetings·goal_meeting_items). #}
|
||||
{% set h = head if head is defined and head else {} %}
|
||||
{% set unk = h.unknown or [] %}
|
||||
{#- 머리 숫자 — 목표 표 매출 단위(예: 백만원)로, 원이거나 모르는 단위면 원. 정확한 원 금액은 말풍선 -#}
|
||||
{%- macro unitv(v) -%}{% if h.unit_mult and h.unit_mult > 1 %}{{ "{:,.1f}".format(v / h.unit_mult).rstrip('0').rstrip('.') }}<small>{{ h.sales_unit }}</small>{% else %}{{ won(v) }}<small>원</small>{% endif %}{%- endmacro -%}
|
||||
{%- macro unknown_val() -%}<span class="pj-meet-unknown" title="실적 조회 실패 — 알 수 없는 값이라 0 으로 보이지 않습니다">미확인</span>{%- endmacro -%}
|
||||
{# 주간 회의록 — 목표 표 월 머리를 누르면 열린다(/project/goals/{연도}/meetings/{월}?week=주차 시작일).
|
||||
주차(store.month_weeks — 그 달 안, 1주차는 1일부터)마다 회의록 하나: 머리 영역 3칸(월 계획 + 숫자 한 줄 | 결정 사항·메모 | 작업 등록)
|
||||
+ 구역(목표 표 업무 영역)별 줄 — 주요 업무·정량 목표 | 지난주: 전주 업무·결과(글)·전주 목표·결과(금액).
|
||||
지난주 칸은 바로 앞 주차 회의록의 같은 줄(연결키). 월 누적 실적은 실적 모듈, 월 누적 목표는 목표 표 주차별 목표 합.
|
||||
입력은 누구나(완료 전까지, 칸별 즉시 저장, project.js initGoalMeeting). DB: project_db 015·020. #}
|
||||
<div class="pj-wrap pj-inbox-view pj-goal-view pj-meet-view" data-me="{{ (user.email if user else '') | lower }}">
|
||||
<div class="pj-layout">
|
||||
{% with current_pid = 0, side_active = "goals" %}{% include "project/_side.html" %}{% endwith %}
|
||||
{% if not meeting_embedded %}{% with current_pid = 0, side_active = "goals" %}{% include "project/_side.html" %}{% endwith %}{% endif %}
|
||||
|
||||
<section class="pj-main">
|
||||
{# 머리 — 왼쪽: 제목·이전/다음 달·인쇄·회의록 삭제·주차 탭(한 줄) + 이 달 계획(달력 앞까지) / 오른쪽 위: 작은 달력 #}
|
||||
{# 머리 — 왼쪽: 제목·이전/다음 달·인쇄·회의록 삭제·주차 탭(한 줄) + 영역 3칸(월 계획·숫자 | 결정 사항 | 작업 등록) / 오른쪽 위: 작은 달력 #}
|
||||
<div class="pj-meet-headgrid">
|
||||
<div class="pj-meet-headleft">
|
||||
<div class="pj-meet-title">
|
||||
@@ -33,18 +38,24 @@
|
||||
<a class="pj-btn pj-btn-sm" href="/project/goals/{{ py }}/meetings/{{ pm }}">‹ {{ pm }}월</a>
|
||||
<a class="pj-btn pj-btn-sm" href="/project/goals/{{ ny }}/meetings/{{ nm }}">{{ nm }}월 ›</a>
|
||||
{% if meeting %}
|
||||
{# 회의록은 프로젝트 권한이 있는 누구나 고친다. [회의 완료](Pro user 이상) = 수정 잠금, 완료 뒤 [완료 해제](Pro user 이상) — 마이그레이션 022 #}
|
||||
<span class="pj-meet-title-acts">
|
||||
<button type="button" class="pj-btn pj-btn-sm" id="pj-meet-print"><span class="material-symbols-outlined">print</span> 인쇄</button>
|
||||
{% if is_admin %}<button type="button" class="pj-btn pj-btn-sm pj-btn-danger" id="pj-meet-del">회의록 삭제</button>
|
||||
{% else %}<span class="pj-goal-note">회의록은 관리자만 입력할 수 있습니다.</span>{% endif %}
|
||||
{% if pj_pro %}<button type="button" class="pj-btn pj-btn-sm pj-btn-danger" id="pj-meet-del">회의록 삭제</button>{% endif %}
|
||||
{% if meeting.can_complete %}
|
||||
{% if meeting.completed %}
|
||||
<span class="pj-meet-done-badge" title="{{ meeting.completed_at }}{% if meeting.completed_by %} · {{ meeting.completed_by }}{% endif %} — 완료된 회의록은 고칠 수 없습니다"><span class="material-symbols-outlined">lock</span>회의 완료</span>
|
||||
{% if pj_pro %}<button type="button" class="pj-btn pj-btn-sm" id="pj-meet-reopen" title="다시 고칠 수 있게 엽니다">완료 해제</button>{% endif %}
|
||||
{% elif pj_pro %}<button type="button" class="pj-btn pj-btn-sm pj-meet-complete-btn" id="pj-meet-complete" title="이 회의록을 더 고칠 수 없게 잠급니다(Pro user 이상)"><span class="material-symbols-outlined">task_alt</span>회의 완료</button>{% endif %}
|
||||
{% endif %}
|
||||
</span>
|
||||
{% endif %}
|
||||
{# 주차 탭 — 주 = 월요일~일요일, 1주차 = 그 달 첫 월요일이 있는 주(주는 월요일이 속한 달). 점 = 회의록 있음 #}
|
||||
{# 주차 탭 — 주차는 그 달 안(1일이 월~금이면 1일~일요일, 토·일이면 1일~다음 주 일요일, 말일이 월·화면 앞 주차에 붙음). 점 = 회의록 있음 #}
|
||||
<nav class="pj-meet-weeks" aria-label="주차">
|
||||
{% for w in weeks %}
|
||||
<a class="pj-meet-week{% if w.start == week %} is-on{% endif %}{% if w.now %} is-now{% endif %}"
|
||||
href="?week={{ w.start }}" title="{{ w.n }}주차 {{ w.label }}">
|
||||
{# 날짜는 짧게 — 같은 달이면 끝 월 생략(10/5~11), 달이 넘어가면 10/26~11/1 #}
|
||||
{# 날짜는 짧게 — 주차는 달을 넘지 않아 끝 월 생략(10/5~11) #}
|
||||
{% set ws = w.start.split('-') %}{% set we = w.end.split('-') %}
|
||||
<b>{{ w.n }}주차</b><span>{{ ws[1] | int }}/{{ ws[2] | int }}~{% if we[1] != ws[1] %}{{ we[1] | int }}/{% endif %}{{ we[2] | int }}</span>
|
||||
{% if w.has %}<i class="pj-meet-dot" title="회의록 있음"></i>{% endif %}
|
||||
@@ -53,33 +64,77 @@
|
||||
{% endfor %}
|
||||
</nav>
|
||||
</div>
|
||||
{# 이 달 계획 — 연간 목표 표의 그 달 열 글(업무 영역별, router._month_plan) #}
|
||||
{% if month_plan is not none %}
|
||||
<section class="pj-meet-plan">
|
||||
<div class="pj-meet-plan-head"><span class="material-symbols-outlined">event_note</span>{{ goal_month }}월 계획</div>
|
||||
{% if month_plan %}
|
||||
<div class="pj-meet-plan-grid">
|
||||
{% for a in month_plan %}
|
||||
<div class="pj-meet-plan-area" style="--goal-bg: {{ a.color or '#f4f5f7' }}">
|
||||
<b class="pj-meet-plan-name">{{ a.name }}</b>
|
||||
{% for it in a.lines %}
|
||||
<div class="pj-meet-plan-item">{% if it.label %}<span class="pj-meet-plan-label">{{ it.label }}</span>{% endif %}<span class="pj-meet-plan-text">{{ it.text }}</span>{% if it.range %}<em>{{ it.range }}</em>{% endif %}</div>
|
||||
{# ── 머리 영역 3칸(스크롤해도 보임 — 표만 아래 .pj-meet-pane 에서 스크롤) ──
|
||||
① 월 계획 + 머리 줄 오른쪽에 숫자 4개를 작게 한 줄로 ② 결정 사항·메모 ③ 작업 빠른 등록 표(project.js initMeetQuickTasks) #}
|
||||
<div class="pj-meet-board">
|
||||
<section class="pj-meet-area pj-meet-plan">
|
||||
<div class="pj-meet-plan-head">
|
||||
<span class="pj-meet-plan-title"><span class="material-symbols-outlined">event_note</span>{{ goal_month }}월 계획</span>
|
||||
{% if h %}
|
||||
<div class="pj-meet-kpiline">
|
||||
<span class="pj-meet-kpi" title="월 목표 매출(연간 목표 표){% if h.month_target_won is not none %} = {{ won(h.month_target_won) }}원{% endif %}">
|
||||
<span class="pj-meet-kpi-label">월 목표</span>
|
||||
<span class="pj-meet-kpi-val">{% if h.sales_target is not none %}{{ num(h.sales_target) }}<small>{{ h.sales_unit }}</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||
</span>
|
||||
<span class="pj-meet-kpi" title="월 누적 목표 매출{% if h.cum_target_won is not none %} {{ won(h.cum_target_won) }}원{% endif %} — 연간 목표 표에서 입력한 주차별 매출 목표의 1주차~{{ week_n }}주차 합계{% if not h.week_targets_set %} — 목표 표에서 주차별 목표를 입력하세요{% endif %}">
|
||||
<span class="pj-meet-kpi-label">누적 목표 <small>({{ week_n }}주차)</small></span>
|
||||
<span class="pj-meet-kpi-val">{% if h.cum_target_won is not none %}{{ unitv(h.cum_target_won) }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||
</span>
|
||||
<span class="pj-meet-kpi" title="월 누적 실적{% if h.mtd is not none %} {{ won(h.mtd) }}원{% endif %}(1일~{{ h.mtd_end[5:] | replace('-', '/') if h.mtd_end else '' }}){% if h.fresh_tip %} · {{ h.fresh_tip }}{% endif %}">
|
||||
<span class="pj-meet-kpi-label">누적 실적 {% if h.mtd_end %}<small>({{ h.mtd_end[5:] | replace('-', '/') }})</small>{% endif %}</span>
|
||||
<span class="pj-meet-kpi-val">{% if h.mtd is not none %}{{ unitv(h.mtd) }}{% elif 'mtd' in unk %}{{ unknown_val() }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||
</span>
|
||||
<span class="pj-meet-kpi" title="누적 목표 대비 달성{% if h.gap is not none %} {{ '+' if h.gap > 0 else '' }}{{ won(h.gap) }}원{% endif %} — 월 누적 실적 − 월 누적 목표 매출 (월 누적 실적 ÷ 월 누적 목표 매출)">
|
||||
<span class="pj-meet-kpi-label">목표 대비</span>
|
||||
{% if h.gap is not none %}<span class="pj-meet-kpi-val {{ 'is-good' if h.gap >= 0 else 'is-low' }}">{{ '+' if h.gap > 0 else '' }}{{ unitv(h.gap) }}{% if h.rate is not none %} <small class="pj-meet-kpi-rate">{{ h.rate }}%</small>{% endif %}</span>
|
||||
{% elif 'mtd' in unk and h.cum_target_won is not none %}<span class="pj-meet-kpi-val">{{ unknown_val() }}</span>
|
||||
{% else %}<span class="pj-meet-kpi-val"><span class="pj-muted">—</span></span>{% endif %}
|
||||
</span>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="pj-meet-area-body">
|
||||
{% if month_plan is none %}<p class="pj-meet-plan-empty">연간 목표 표가 없어 월 계획을 보여 줄 수 없습니다.</p>
|
||||
{% elif month_plan %}
|
||||
<div class="pj-meet-plan-grid">
|
||||
{% for a in month_plan %}
|
||||
<div class="pj-meet-plan-area" style="--goal-bg: {{ a.color or '#f4f5f7' }}">
|
||||
<b class="pj-meet-plan-name">{{ a.name }}</b>
|
||||
{% for it in a.lines %}
|
||||
<div class="pj-meet-plan-item">{% if it.label %}<span class="pj-meet-plan-label">{{ it.label }}</span>{% endif %}<span class="pj-meet-plan-text">{{ it.text_html | safe }}</span>{% if it.range %}<em>{{ it.range }}</em>{% endif %}</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}<p class="pj-meet-plan-empty">목표 표에 {{ goal_month }}월 계획이 아직 없습니다.</p>{% endif %}
|
||||
</section>
|
||||
{% endif %}
|
||||
{% else %}<p class="pj-meet-plan-empty">목표 표에 {{ goal_month }}월 계획이 아직 없습니다.</p>{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
<section class="pj-meet-area pj-meet-notes">
|
||||
<h3>결정사항 : 진행상황 수시 공유 및 완료 되어야 함</h3>
|
||||
{% if meeting %}
|
||||
{% if not meeting.completed %}<textarea id="pj-meet-notes" rows="4" placeholder="이번 회의에서 정한 것, 다음 주까지 확인할 것">{{ meeting.notes }}</textarea>
|
||||
{% else %}<div class="pj-meet-ro">{{ meeting.notes or '—' }}</div>{% endif %}
|
||||
{% else %}<p class="pj-meet-plan-empty">이 주차 회의록을 만들면 적을 수 있습니다.</p>{% endif %}
|
||||
</section>
|
||||
<section class="pj-meet-area pj-meet-quick" id="pj-meet-quick">
|
||||
<h3>작업 등록 <small>제목을 쓰고 담당자·프로젝트·섹션 칸을 눌러 고른 뒤 [적용]</small></h3>
|
||||
<div class="pj-meet-area-body">
|
||||
<table class="pj-meet-quick-table">
|
||||
<thead><tr><th>제목</th><th>담당자</th><th>프로젝트</th><th>섹션</th><th></th></tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
<button type="button" class="pj-meet-quick-add" data-quick="add">+ 줄 추가</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
{# 작은 달력 — 월요일 시작(주 = 월~일), 보고 있는 주는 영역 표시, 줄을 누르면 그 주 회의록. 점 = 회의록 있음.
|
||||
1주차 = 그 달 첫 월요일이 있는 주 — 1일 앞쪽 날짜가 든 주는 앞 달 주(흐리게, 누르면 앞 달 회의록). #}
|
||||
{# 작은 달력 — 월요일 시작 줄, 줄을 누르면 그 줄의 이 달 날짜가 든 주차 회의록(보고 있는 주차의 줄은 영역 표시). 점 = 회의록 있음. #}
|
||||
<div class="pj-meet-cal" aria-label="{{ goal_month }}월 달력">
|
||||
<div class="pj-meet-cal-head">{{ goal_year }}년 {{ goal_month }}월</div>
|
||||
<div class="pj-meet-cal-wd"><span>월</span><span>화</span><span>수</span><span>목</span><span>금</span><span class="is-sat">토</span><span class="is-sun">일</span></div>
|
||||
{% for w in cal_weeks %}
|
||||
<a class="pj-meet-cal-row{% if w.start == week %} is-on{% endif %}{% if not w.own %} is-other{% endif %}" href="{{ w.href }}"
|
||||
title="{{ w.title }}{% if w.has %} · 회의록 있음{% endif %}{% if not w.own %} — 이 주는 {{ w.title.split('월')[0] }}월 회의록{% endif %}">
|
||||
title="{{ w.title }}{% if w.has %} · 회의록 있음{% endif %}">
|
||||
{% for d in w.days %}<span class="pj-meet-cal-d{% if not d.in %} is-out{% endif %}{% if d.today %} is-today{% endif %}{% if d.wd == 5 %} is-sat{% endif %}{% if d.wd == 6 or d.hol %} is-sun{% endif %}"{% if d.hol %} title="{{ d.hol }}"{% endif %}>{{ d.d }}</span>{% endfor %}
|
||||
{% if w.has %}<i class="pj-meet-cal-dot"></i>{% endif %}
|
||||
</a>
|
||||
@@ -87,82 +142,25 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if meeting and not meeting.completed %}{% include "project/_cell_format.html" %}{% endif %}
|
||||
<div class="pj-view pj-meet-pane" id="pj-meet-pane" data-week="{{ week }}" data-year="{{ goal_year }}"
|
||||
data-month="{{ goal_month }}" data-admin="{{ 'true' if is_admin else 'false' }}">
|
||||
data-month="{{ goal_month }}" data-pro="{{ 'true' if pj_pro else 'false' }}"
|
||||
data-edit="{{ 'true' if meeting and not meeting.completed else 'false' }}">
|
||||
|
||||
{% if not meetings_enabled %}
|
||||
<div class="pj-empty">주간 회의록이 아직 준비되지 않았습니다(DB 마이그레이션 015 필요).</div>
|
||||
{% elif not meeting %}
|
||||
<div class="pj-empty pj-goal-empty">
|
||||
<p>{{ week_n }}주차({{ week }} ~ {{ week_end }}) 회의록이 아직 없습니다.</p>
|
||||
{% if is_admin %}
|
||||
<p class="pj-goal-empty-sub">만들면 앞선 회의록의 줄(구역·항목·쇼핑몰 연결)을 이어받아, 지난주 할 일·목표·결과를 나란히 리뷰할 수 있습니다.
|
||||
{% if true %}
|
||||
<p class="pj-goal-empty-sub">만들면 앞선 회의록의 줄(구역·항목)을 이어받아, 지난주 업무·목표·결과를 나란히 리뷰할 수 있습니다.
|
||||
처음이면 {{ goal_year }}년 목표 표의 업무 영역과 기본 양식 줄로 시작합니다.</p>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-meet-create">{{ week_n }}주차 회의록 만들기</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% else %}
|
||||
{% set h = head %}
|
||||
{% set edit = is_admin %}
|
||||
{% set unk = h.unknown or [] %}
|
||||
{%- macro unknown_val() -%}<span class="pj-meet-unknown" title="실적 조회 실패 — 알 수 없는 값이라 0 으로 보이지 않습니다">미확인</span>{%- endmacro -%}
|
||||
{# ── 숫자 — 한 줄 막대(월 목표 대비 누적·남은 주 필요 매출 | 전주 리뷰 | 금주 목표) ── #}
|
||||
<div class="pj-meet-kpibar">
|
||||
<div class="pj-meet-kpis">
|
||||
<div class="pj-meet-kpi">
|
||||
<span class="pj-meet-kpi-label">월 목표 매출</span>
|
||||
<span class="pj-meet-kpi-val">{% if h.sales_target is not none %}{{ num(h.sales_target) }}<small>{{ h.sales_unit }}</small>{% else %}<span class="pj-muted">목표 표에 없음</span>{% endif %}</span>
|
||||
{% if h.month_target_won is not none and h.sales_unit and h.sales_unit != '원' %}<span class="pj-meet-kpi-sub">= {{ won(h.month_target_won) }}원</span>{% endif %}
|
||||
</div>
|
||||
<div class="pj-meet-kpi"{% if h.fresh_tip %} title="{{ h.fresh_tip }}"{% endif %}>
|
||||
<span class="pj-meet-kpi-label">월 누적 실적 <small>(지난주까지)</small></span>
|
||||
<span class="pj-meet-kpi-val">{% if h.mtd is not none %}{{ won(h.mtd) }}<small>원</small>{% elif 'mtd' in unk %}{{ unknown_val() }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||
{% if h.month_target_won and h.mtd is not none %}<span class="pj-meet-kpi-sub">달성 {{ "%.1f" | format(h.mtd / h.month_target_won * 100) }}%</span>{% endif %}
|
||||
</div>
|
||||
<div class="pj-meet-kpi is-accent" title="월 목표 − 누적을 이번 주 포함 남은 주로 나눈 값">
|
||||
<span class="pj-meet-kpi-label">주당 필요 <small>(남은 {{ h.weeks_left }}주)</small></span>
|
||||
<span class="pj-meet-kpi-val">{% if h.need_per_week is not none %}{{ won(h.need_per_week) }}<small>원</small>{% elif 'mtd' in unk and h.month_target_won is not none %}{{ unknown_val() }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||
</div>
|
||||
<div class="pj-meet-kpi">
|
||||
<span class="pj-meet-kpi-label">목표 ROAS</span>
|
||||
<span class="pj-meet-kpi-val">{% if h.roas_target is not none %}{{ num(h.roas_target) }}<small>%</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pj-meet-kpis is-week">
|
||||
<div class="pj-meet-kpi">
|
||||
<span class="pj-meet-kpi-label">전주 목표</span>
|
||||
<span class="pj-meet-kpi-val">{% if h.prev_target is not none %}{{ won(h.prev_target) }}<small>원</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||
</div>
|
||||
<div class="pj-meet-kpi"{% if h.fresh_tip %} title="{{ h.fresh_tip }}"{% endif %}>
|
||||
<span class="pj-meet-kpi-label">전주 결과 <small>({{ prev_week[5:] | replace('-', '/') }}~ 실적)</small></span>
|
||||
<span class="pj-meet-kpi-val">{% if h.prev_result is not none %}{{ won(h.prev_result) }}<small>원</small>{% elif 'prev_result' in unk %}{{ unknown_val() }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||
</div>
|
||||
<div class="pj-meet-kpi">
|
||||
<span class="pj-meet-kpi-label">전주 달성률</span>
|
||||
{% if h.prev_target and h.prev_result is not none %}{% set r = h.prev_result / h.prev_target * 100 %}
|
||||
<span class="pj-meet-kpi-val {{ 'is-good' if r >= 100 else 'is-low' }}">{{ "%.1f" | format(r) }}<small>%</small></span>
|
||||
{% elif h.prev_target and 'prev_result' in unk %}<span class="pj-meet-kpi-val">{{ unknown_val() }}</span>
|
||||
{% else %}<span class="pj-meet-kpi-val"><span class="pj-muted">—</span></span>{% endif %}
|
||||
</div>
|
||||
<div class="pj-meet-kpi is-input">
|
||||
<span class="pj-meet-kpi-label">금주 목표</span>
|
||||
{% if edit %}
|
||||
<span class="pj-meet-kpi-val"><input type="text" class="pj-meet-amount" id="pj-meet-target" inputmode="decimal"
|
||||
autocomplete="off" placeholder="{{ won(h.need_per_week) if h.need_per_week is not none else '예: 30,000,000' }}"
|
||||
value="{{ won(meeting.week_target) }}" /><small>원</small></span>
|
||||
{% else %}
|
||||
<span class="pj-meet-kpi-val">{% if meeting.week_target is not none %}{{ won(meeting.week_target) }}<small>원</small>{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||
{% endif %}
|
||||
<span class="pj-meet-sub-slot">{% if h.need_per_week is not none %}<span class="pj-meet-kpi-sub">필요 {{ won(h.need_per_week) }}원</span>{% endif %}</span>
|
||||
</div>
|
||||
<div class="pj-meet-kpi"{% if h.fresh_tip %} title="{{ h.fresh_tip }}"{% endif %}>
|
||||
<span class="pj-meet-kpi-label">금주 현재 실적</span>
|
||||
<span class="pj-meet-kpi-val">{% if h.week_result is not none %}{{ won(h.week_result) }}<small>원</small>{% elif 'week_result' in unk %}{{ unknown_val() }}{% else %}<span class="pj-muted">—</span>{% endif %}</span>
|
||||
{% if meeting.week_target and h.week_result is not none %}<span class="pj-meet-kpi-sub">목표의 {{ "%.1f" | format(h.week_result / meeting.week_target * 100) }}%</span>{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{# 매출 자료 갱신 — 주차를 열면 실적 모듈 매출 업데이트(지난주 월요일 ~ 이번 주 오늘)를 한 번 더 돌리고 숫자 칸만 다시 그린다
|
||||
{% set edit = not meeting.completed %} {# 누구나 고친다 — 회의 완료(022)면 잠금 #}
|
||||
{# 매출 자료 갱신 — 주차를 열면 실적 모듈 매출 업데이트(지난 주차 시작 ~ 이 주차 오늘)를 한 번 더 돌리고 숫자 칸만 다시 그린다
|
||||
(project.js initMeetingSync, 같은 주는 10분에 한 번). 정상이면 아무것도 보이지 않는다(2026-10-01 요청 — 큰 상태 줄 없음).
|
||||
실패·일부 실패면 이 작은 안내 + [다시 시도], 실적 권한이 없으면 부르지 않고 한 줄 설명. 마지막 갱신 성공 시각은 서버 기록(data-fresh). #}
|
||||
{% if h.perf and sync_from %}<div id="pj-meet-sync" class="pj-meet-syncnote" hidden role="status" aria-live="polite"
|
||||
@@ -170,8 +168,8 @@
|
||||
<span class="material-symbols-outlined" aria-hidden="true">sync_problem</span><span class="pj-meet-sync-text"></span>
|
||||
<button type="button" class="pj-btn pj-btn-sm" id="pj-meet-sync-btn" hidden>다시 시도</button>
|
||||
</div>{% endif %}
|
||||
{% if not h.perf %}<p class="pj-goal-note">실적 모듈이 연결되지 않아 실적·누적·쇼핑몰 자동 결과는 비어 있습니다(결과는 직접 입력).</p>
|
||||
{% elif h.perf_state == 'error' %}<p class="pj-goal-note pj-meet-perf-warn">실적 모듈 쇼핑몰 목록을 읽지 못해 실적·누적·쇼핑몰 자동 결과를 <b>미확인</b>으로 표시합니다(0 원이 아님). 회의록 입력은 그대로 됩니다.</p>
|
||||
{% if not h.perf %}<p class="pj-goal-note">실적 모듈이 연결되지 않아 실적·누적은 비어 있습니다.</p>
|
||||
{% elif h.perf_state == 'error' %}<p class="pj-goal-note pj-meet-perf-warn">실적 모듈 쇼핑몰 목록을 읽지 못해 실적·누적을 <b>미확인</b>으로 표시합니다(0 원이 아님). 회의록 입력은 그대로 됩니다.</p>
|
||||
{% elif h.perf_state == 'empty' %}<p class="pj-goal-note">실적 모듈에 매출 집계 쇼핑몰이 없어 실적·누적은 비어 있습니다.</p>
|
||||
{% elif unk %}<p class="pj-goal-note pj-meet-perf-warn">일부 실적을 읽지 못했습니다 — <b>미확인</b> 칸은 0 원이 아니라 알 수 없는 값입니다.</p>{% endif %}
|
||||
|
||||
@@ -185,15 +183,22 @@
|
||||
{% if edit %}<button type="button" class="pj-meet-attend-add" id="pj-meet-attend-add"><span class="material-symbols-outlined">person_add</span>참석자</button>
|
||||
{% elif not attendee_list %}<span class="pj-muted">—</span>{% endif %}
|
||||
</div>
|
||||
{# 회의록 보드 — 그 주차의 빈 Google 슬라이드를 독립 창으로(없으면 공유 드라이브에 만든다, project.js initMeetBoard) #}
|
||||
<button type="button" class="pj-btn pj-btn-sm pj-meet-board-btn" id="pj-meet-board"
|
||||
title="이 주차의 Google 슬라이드 보드를 새 창으로 엽니다(처음이면 공유 드라이브에 빈 슬라이드를 만듭니다)">
|
||||
<span class="material-symbols-outlined">co_present</span>회의록 보드</button>
|
||||
{# 회의록 보드 링크 복사(2026-10-08) — 같은 주차 보드 주소(없으면 만든 뒤)를 클립보드로 #}
|
||||
<button type="button" class="pj-icon-btn pj-meet-board-copy" id="pj-meet-board-copy"
|
||||
title="회의록 보드 링크 복사" aria-label="회의록 보드 링크 복사"><span class="material-symbols-outlined">link</span></button>
|
||||
</div>
|
||||
|
||||
{# ── 구역별 줄 — 왼쪽: 이번주 / 오른쪽: 전주 리뷰(지난 회의록 같은 줄) ── #}
|
||||
<table class="pj-meet-table" id="pj-meet-table">
|
||||
<table class="pj-meet-table" id="pj-meet-table" data-cell-merges="{{ 'true' if meeting.cell_merges else 'false' }}">
|
||||
{# table-layout: fixed 는 첫 줄(묶음 머리, colspan)로 너비를 정하므로 열 너비는 colgroup 으로 #}
|
||||
<colgroup>
|
||||
{# is-this / is-prev — 순서 바꾸기(project.js initMeetOrder)가 이 묶음으로 열을 옮긴다 #}
|
||||
<col class="pj-meet-w-sec" /><col class="pj-meet-w-label" /><col class="is-this" /><col class="pj-meet-w-amt is-this" />
|
||||
<col class="is-prev" /><col class="pj-meet-w-amt is-prev" /><col class="pj-meet-w-amt is-prev" /><col class="pj-meet-w-rate is-prev" /><col class="pj-meet-w-eval is-prev" />
|
||||
<col class="pj-meet-w-sec" data-meet-col="section" /><col class="pj-meet-w-label" data-meet-col="label" /><col class="is-this" data-meet-col="content" /><col class="pj-meet-w-amt is-this" data-meet-col="target" />
|
||||
<col class="is-prev" data-meet-col="prev_content" /><col class="is-prev" data-meet-col="prev_note" /><col class="pj-meet-w-amt is-prev" data-meet-col="prev_target" /><col class="pj-meet-w-amt is-prev" data-meet-col="result" />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr class="pj-meet-group">
|
||||
@@ -201,19 +206,18 @@
|
||||
<th colspan="2" class="pj-meet-order-cell"><button type="button" class="pj-meet-order-btn" id="pj-meet-order"
|
||||
title="이번주와 지난주 리뷰의 순서 바꾸기(내 화면에 기억)"><span class="material-symbols-outlined">swap_horiz</span>순서 바꾸기</button></th>
|
||||
<th colspan="2" class="is-this">이번주 ({{ week[5:] | replace('-', '/') }} ~ {{ week_end[5:] | replace('-', '/') }})</th>
|
||||
{# 지난주 = 정확히 7일 전 주 — 줄의 지난주 칸·결과·달성률도 이 주 회의록의 같은 줄(연결키)만 #}
|
||||
<th colspan="5" class="is-prev">지난주 리뷰 ({{ prev_week[5:] | replace('-', '/') }} ~ {{ prev_week_end[5:] | replace('-', '/') }}){% if not h.prev_exists %} <span class="pj-meet-noprev">— 이 주 회의록 없음</span>{% endif %}</th>
|
||||
{# 지난주 = 바로 앞 주차 — 줄의 지난주 칸·결과도 그 주차 회의록의 같은 줄(연결키)만 #}
|
||||
<th colspan="4" class="is-prev">지난주 리뷰 ({{ prev_week[5:] | replace('-', '/') }} ~ {{ prev_week_end[5:] | replace('-', '/') }}){% if not h.prev_exists %} <span class="pj-meet-noprev">— 이 주 회의록 없음</span>{% endif %}</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th class="pj-meet-c-sec">구역</th>
|
||||
<th class="pj-meet-c-sec">구분</th>
|
||||
<th class="pj-meet-c-label">항목</th>
|
||||
<th class="pj-meet-c-text">이번주 할 일 · 행사</th>
|
||||
<th class="pj-meet-c-text">주요 업무</th>
|
||||
<th class="pj-meet-c-amt">정량 목표</th>
|
||||
<th class="pj-meet-c-text is-prev">지난주 할 일</th>
|
||||
<th class="pj-meet-c-amt is-prev">지난주 목표</th>
|
||||
<th class="pj-meet-c-text is-prev">전주 업무</th>
|
||||
<th class="pj-meet-c-text is-prev">결과</th>
|
||||
<th class="pj-meet-c-amt is-prev">전주 목표</th>
|
||||
<th class="pj-meet-c-amt is-prev">결과</th>
|
||||
<th class="pj-meet-c-rate is-prev">달성률</th>
|
||||
<th class="pj-meet-c-eval is-prev">평가</th>
|
||||
</tr>
|
||||
</thead>
|
||||
{% for sec in meeting.sections %}
|
||||
@@ -227,74 +231,65 @@
|
||||
</th>
|
||||
{% endif %}
|
||||
<th class="pj-meet-c-label">
|
||||
<span class="pj-meet-label"{% if edit %} data-meet-edit="label" title="눌러서 이름 수정 · 우클릭 = 줄 메뉴"{% endif %}>{{ it.label }}</span>
|
||||
{% if it.market_unknown %}<span class="pj-meet-market is-unknown" title="실적 모듈 쇼핑몰 목록을 읽지 못해 이 연결의 실적을 확인할 수 없습니다">{{ it.market_name }} · 미확인</span>
|
||||
{% elif it.market_off %}<span class="pj-meet-market is-off" title="실적 모듈에서 사용 중인 쇼핑몰이 아닙니다(실적 설정에서 사용 OFF 이거나 없는 쇼핑몰) — 결과는 직접 입력">{{ it.market_name }} · 실적 미사용</span>
|
||||
{% elif it.market_name %}<span class="pj-meet-market" title="결과를 실적 모듈 {{ it.market_name }} 매출에서 자동으로">{{ it.market_name }}</span>{% endif %}
|
||||
<span class="pj-meet-label-line">
|
||||
<span class="pj-meet-label"{% if edit %} data-meet-edit="label" title="눌러서 이름 수정 · 우클릭 = 줄 메뉴"{% endif %}>{{ it.label }}</span>
|
||||
</span>
|
||||
{% if edit %}<button type="button" class="pj-icon-btn pj-meet-more" data-meet-act="menu" title="줄 메뉴"><span class="material-symbols-outlined">more_horiz</span></button>{% endif %}
|
||||
</th>
|
||||
<td class="pj-meet-c-text">
|
||||
{% if edit %}<textarea class="pj-meet-text" rows="1" data-field="content" placeholder="이번주 할 일·행사">{{ it.content }}</textarea>
|
||||
{% else %}<div class="pj-meet-ro">{{ it.content }}</div>{% endif %}
|
||||
{% if not it.content_hidden %}
|
||||
<td class="pj-meet-c-text" rowspan="{{ it.content_span or 1 }}" data-meet-item="{{ it.id }}">
|
||||
{% if edit %}<div class="pj-meet-text pj-goal-text" contenteditable="true" role="textbox" aria-multiline="true" aria-label="{{ it.label }} 주요 업무" data-field="content" data-placeholder="주요 업무">{% if it.content_html is defined %}{{ it.content_html | safe }}{% else %}{{ it.content }}{% endif %}</div>
|
||||
{% else %}<div class="pj-meet-ro">{% if it.content_html is defined %}{{ it.content_html | safe }}{% else %}{{ it.content }}{% endif %}</div>{% endif %}
|
||||
</td>
|
||||
{% endif %}
|
||||
<td class="pj-meet-c-amt">
|
||||
{% if edit %}<input type="text" class="pj-meet-amount" data-field="target_amount" inputmode="decimal" autocomplete="off" value="{{ won(it.target_amount) }}" />
|
||||
{% else %}{{ won(it.target_amount) }}{% endif %}
|
||||
{# 이번주 실적 — data-auto = 실적(서버), % 는 화면이 서버 확정 정량 목표(tr data-target-amount)로 다시 계산(project.js paintMeetWeek) #}
|
||||
<span class="pj-meet-week-slot" data-auto="{{ it.week_auto if it.week_auto is not none else '' }}"{% if it.week_error %} data-err="1"{% endif %} data-name="{{ it.market_name }}">{% if it.week_auto is not none %}<span class="pj-meet-week-auto" title="실적 모듈 {{ it.market_name }} 이번 주({{ week[5:] | replace('-', '/') }}~ 오늘까지) 매출">이번주 실적 {{ won(it.week_auto) }}{% if it.target_amount %} · {{ "%.0f" | format(it.week_auto / it.target_amount * 100) }}%{% endif %}</span>{% elif it.week_error %}<span class="pj-meet-week-auto is-unknown" title="실적 조회 실패">이번주 실적 미확인</span>{% endif %}</span>
|
||||
{# 숫자(원, 120만·1.5억도) 또는 글(예: 20개 — 021 target_text) #}
|
||||
{% if edit %}<input type="text" class="pj-meet-amount" data-field="target_amount" autocomplete="off" value="{{ it.target_text or won(it.target_amount) }}" />
|
||||
{% else %}{{ it.target_text or won(it.target_amount) }}{% endif %}
|
||||
</td>
|
||||
{% if p %}
|
||||
<td class="pj-meet-c-text is-prev"><div class="pj-meet-ro">{{ p.content }}</div></td>
|
||||
<td class="pj-meet-c-amt is-prev">{{ won(p.target_amount) }}</td>
|
||||
<td class="pj-meet-c-amt is-prev pj-meet-c-result">
|
||||
{% if p.not_started %}
|
||||
<span class="pj-muted" title="지난 회의록의 주({{ p.period }})가 아직 시작되지 않았습니다">진행 전</span>
|
||||
{% elif p.auto_error %}
|
||||
<span class="pj-meet-unknown" title="실적 모듈 {{ p.market_name }} {{ p.period }} 매출을 읽지 못했습니다 — 알 수 없는 값이라 0 으로 보이지 않습니다">미확인</span>
|
||||
{% elif p.auto_result is not none %}
|
||||
<span class="pj-meet-auto" title="실적 모듈 {{ p.market_name }} {{ p.period }} 매출(자동){% if not p.auto_result %} — 0 이면 그 기간 실적이 아직 없습니다(실적 화면 [매출 업데이트]){% endif %}">{{ won(p.auto_result) }}</span>
|
||||
{% elif edit %}<input type="text" class="pj-meet-amount" data-field="result_amount" data-target="prev" inputmode="decimal" autocomplete="off" value="{{ won(p.result_amount) }}" placeholder="결과" />
|
||||
{% else %}{{ won(p.result_amount) }}{% endif %}
|
||||
<td class="pj-meet-c-text is-prev"><div class="pj-meet-ro">{% if p.content_html is defined %}{{ p.content_html | safe }}{% else %}{{ p.content }}{% endif %}</div></td>
|
||||
{# 결과(글) — 지난 주차 줄의 result_note(020). 미적용이면 보기만 #}
|
||||
<td class="pj-meet-c-text is-prev pj-meet-c-note">
|
||||
{% if edit and meeting.result_notes %}<textarea class="pj-meet-rnote" rows="1" data-field="result_note" data-target="prev" aria-label="{{ it.label }} 결과" placeholder="결과">{{ p.result_note or '' }}</textarea>
|
||||
{% else %}<div class="pj-meet-ro">{{ p.result_note or '' }}</div>{% endif %}
|
||||
</td>
|
||||
<td class="pj-meet-c-rate is-prev" data-rate>{% if it.rate is not none %}<span class="{{ 'is-good' if it.rate >= 100 else 'is-low' }}">{{ it.rate }}%</span>{% endif %}</td>
|
||||
<td class="pj-meet-c-eval is-prev">
|
||||
{% if edit %}
|
||||
<select class="pj-meet-eval" data-field="status" data-target="prev" data-v="{{ p.status }}">
|
||||
{% for k, v in meeting_status.items() %}<option value="{{ k }}"{% if k == p.status %} selected{% endif %}>{{ v or '—' }}</option>{% endfor %}
|
||||
</select>
|
||||
{% else %}<span class="pj-meet-eval-ro" data-v="{{ p.status }}">{{ meeting_status[p.status] or '—' }}</span>{% endif %}
|
||||
<td class="pj-meet-c-amt is-prev">{{ p.target_text or won(p.target_amount) }}</td>
|
||||
<td class="pj-meet-c-amt is-prev pj-meet-c-result">
|
||||
{% if edit %}<input type="text" class="pj-meet-amount" data-field="result_amount" data-target="prev" autocomplete="off" value="{{ p.result_text or won(p.result_amount) }}" placeholder="결과" />
|
||||
{% else %}{{ p.result_text or won(p.result_amount) }}{% endif %}
|
||||
</td>
|
||||
{% else %}
|
||||
<td class="pj-meet-c-text is-prev is-none" colspan="5"><span class="pj-muted">{% if h.prev_exists %}지난주 회의록에 없는 줄{% else %}지난주({{ prev_week[5:] | replace('-', '/') }}~) 회의록 없음{% endif %}</span></td>
|
||||
<td class="pj-meet-c-text is-prev is-none" colspan="4"><span class="pj-muted">{% if h.prev_exists %}지난주 회의록에 없는 줄{% else %}지난주({{ prev_week[5:] | replace('-', '/') }}~) 회의록 없음{% endif %}</span></td>
|
||||
{% endif %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
{% endfor %}
|
||||
</table>
|
||||
{% if edit %}<p class="pj-goal-note">글자를 선택하면 색상·크기·굵게·기울임·밑줄·서식 초기화를 사용할 수 있습니다.
|
||||
셀 오른쪽 경계는 너비 조절·더블클릭 자동 맞춤, 우클릭은 현재/전체 열 자동 맞춤입니다.
|
||||
주요 업무 셀의 위·아래·왼쪽 테두리를 끌면 내용과 서식을 옮깁니다.
|
||||
같은 구역에서 끌기·Shift+클릭으로 범위를 선택한 뒤 Del로 지우고 Ctrl+Z로 되돌립니다.
|
||||
{% if meeting.cell_merges %}우클릭으로 세로 셀 병합·병합 해제를 사용할 수 있습니다.{% endif %}</p>{% endif %}
|
||||
{% if edit %}
|
||||
<div class="pj-goal-foot">
|
||||
<button type="button" class="pj-btn" id="pj-meet-sec-new">+ 구역 추가</button>
|
||||
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 금액은 원 단위(120만·1.5억도 됨). 항목을 우클릭하거나 ⋯ 를 누르면
|
||||
줄 추가·순서·삭제·쇼핑몰 연결(결과를 실적에서 자동). 지난주 결과·평가는 지난 회의록 줄에 저장됩니다.</span>
|
||||
줄 추가·순서·삭제. 정량 목표·결과는 숫자나 글(예: 20개) 모두 됩니다. 지난주 결과는 지난 주차 회의록 줄에 저장됩니다.</span>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="pj-meet-notes">
|
||||
<h3>결정 사항 · 메모</h3>
|
||||
{% if edit %}<textarea id="pj-meet-notes" rows="4" placeholder="이번 회의에서 정한 것, 다음 주까지 확인할 것">{{ meeting.notes }}</textarea>
|
||||
{% else %}<div class="pj-meet-ro">{{ meeting.notes or '—' }}</div>{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if markets %}<script>window.PJ_MEET_MARKETS = {{ markets | tojson }};</script>{% endif %}
|
||||
<script>window.PJ_MEET_MEMBERS = {{ (meet_members or []) | tojson }};</script>
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project-meeting-cells.js?v=20261007a" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
{# 연간 목표 — 좌측 사이드바 "목표" → 연도. 스프레드시트처럼 한 표에
|
||||
① 매출(목표·실적·달성)·로아스(목표·실적) 월별 숫자
|
||||
② 업무 영역(상품·마케팅·컨텐츠·유통 …)별 연간·월별 글.
|
||||
입력·구조 변경은 관리자만(칸별 즉시 저장, project.js initGoals), 나머지는 보기만.
|
||||
입력·구조 변경은 Pro user 이상(칸별 즉시 저장, project.js initGoals), 나머지는 보기만.
|
||||
DB: project_db 013 (goal_years·goal_metrics·goal_areas·goal_rows·goal_cells). #}
|
||||
<div class="pj-wrap pj-inbox-view pj-goal-view">
|
||||
<div class="pj-layout">
|
||||
@@ -22,7 +22,7 @@
|
||||
<h2 class="pj-goal-title">{{ goal_year }}년 목표</h2>
|
||||
{% if board %}
|
||||
<div class="pj-goal-head-acts">
|
||||
{% if is_admin %}
|
||||
{% if pj_pro %}
|
||||
<label class="pj-goal-unit">매출 단위
|
||||
<input type="text" id="pj-goal-unit" maxlength="20" placeholder="예: 백만원"
|
||||
value="{{ board.sales_unit }}" data-year="{{ goal_year }}" />
|
||||
@@ -31,36 +31,14 @@
|
||||
data-year="{{ goal_year }}">연도 삭제</button>
|
||||
{% else %}
|
||||
{% if board.sales_unit %}<span class="pj-goal-unit-ro">매출 단위: {{ board.sales_unit }}</span>{% endif %}
|
||||
<span class="pj-goal-note">목표는 관리자만 입력할 수 있습니다.</span>
|
||||
<span class="pj-goal-note">목표는 Pro user 이상만 입력할 수 있습니다.</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% if is_admin and goals_enabled and board %}
|
||||
<div class="pj-goal-format" id="pj-goal-format" role="toolbar" aria-label="선택한 글자 서식" hidden>
|
||||
<div class="pj-goal-format-group pj-goal-color-picker">
|
||||
<button type="button" class="pj-goal-format-btn pj-goal-color-toggle" data-goal-format="color" aria-label="글자 색상" title="글자 색상" aria-expanded="false" aria-controls="pj-goal-color-grid" disabled><span class="pj-goal-color-letter" aria-hidden="true">가<span class="pj-goal-color-preview"></span></span><svg class="pj-goal-format-chevron" viewBox="0 0 10 10" fill="none" stroke="currentColor" stroke-width="1.3" aria-hidden="true"><path d="m2 4 3 3 3-3"/></svg></button>
|
||||
<div class="pj-goal-color-grid" id="pj-goal-color-grid" role="group" aria-label="글자 색상 선택" hidden>
|
||||
{% for color in ('#000000', '#4B5563', '#9CA3AF', '#DC2626', '#EA580C', '#CA8A04', '#16A34A', '#0891B2', '#2563EB', '#7C3AED', '#DB2777', '#FFFFFF') %}
|
||||
<button type="button" class="pj-goal-text-swatch" data-goal-color="{{ color }}" style="--swatch: {{ color }}" title="{{ color }}" aria-label="{{ color }}" aria-pressed="false" disabled></button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="pj-goal-format-group" role="group" aria-label="글자 크기">
|
||||
<button type="button" class="pj-goal-format-btn" data-goal-format="size-up" aria-label="글자 크기 2px 키우기" title="글자 크기 2px 키우기" disabled><span class="pj-goal-font-letter" aria-hidden="true">가</span><svg class="pj-goal-font-arrow" viewBox="0 0 10 14" fill="none" stroke="currentColor" stroke-width="1.2" aria-hidden="true"><path d="M5 9V2M2 5l3-3 3 3"/></svg></button>
|
||||
<button type="button" class="pj-goal-format-btn" data-goal-format="size-down" aria-label="글자 크기 2px 줄이기" title="글자 크기 2px 줄이기" disabled><span class="pj-goal-font-letter" aria-hidden="true">가</span><svg class="pj-goal-font-arrow" viewBox="0 0 10 14" fill="none" stroke="currentColor" stroke-width="1.2" aria-hidden="true"><path d="M5 2v7M2 6l3 3 3-3"/></svg></button>
|
||||
<output class="pj-goal-size-value" data-goal-format="size" aria-label="선택한 글자 크기">14px</output>
|
||||
</div>
|
||||
<div class="pj-goal-format-group" role="group" aria-label="글자 모양">
|
||||
{% for key, label in (('bold', '굵게'), ('italic', '기울임'), ('underline', '밑줄')) %}
|
||||
<button type="button" class="pj-goal-format-btn" data-goal-format="{{ key }}" aria-label="{{ label }}" title="{{ label }}" aria-pressed="false" disabled><span class="pj-goal-font-letter" aria-hidden="true">가</span></button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<div class="pj-goal-format-group" role="group" aria-label="서식 초기화">
|
||||
<button type="button" class="pj-goal-format-btn" data-goal-format="reset" aria-label="서식 초기화" title="서식 초기화" disabled><svg class="pj-goal-reset-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m16 3 5 5a2 2 0 0 1 0 3L11 21H7l-4-4a2 2 0 0 1 0-3L13 3a2 2 0 0 1 3 0Z"/><path d="m8 9 7 7M11 21h10"/></svg></button>
|
||||
</div>
|
||||
</div>
|
||||
{% if pj_pro and goals_enabled and board %}
|
||||
{% include "project/_cell_format.html" %}
|
||||
{% endif %}
|
||||
<div class="pj-view pj-goal-pane" id="pj-goal-pane">
|
||||
{% if not goals_enabled %}
|
||||
@@ -68,7 +46,7 @@
|
||||
{% elif not board %}
|
||||
<div class="pj-empty pj-goal-empty">
|
||||
<p>{{ goal_year }}년 목표가 아직 없습니다.</p>
|
||||
{% if is_admin %}
|
||||
{% if pj_pro %}
|
||||
<p class="pj-goal-empty-sub">만들면 가장 가까운 이전 연도의 업무 영역 구성을 그대로 가져옵니다(처음이면 상품·마케팅·컨텐츠·유통).</p>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-goal-create" data-year="{{ goal_year }}">{{ goal_year }}년 목표 만들기</button>
|
||||
{% endif %}
|
||||
@@ -78,19 +56,23 @@
|
||||
{% set rm = board.metrics.roas %}
|
||||
{# 월 칸은 pj-goal-m + data-h(분기 1~4) — 분기 접기(initGoals)가 이걸로 숨긴다.
|
||||
분기 칸 클래스는 예전 이름 pj-goal-half-col 그대로(연간 칸처럼 굵게·회색 합계) #}
|
||||
{# 매출 목표 칸(020) — 누르면 그 달 월 목표(직접 입력)·주차별 목표 입력 창, 맨 아래 차이(월 목표 − 주차 합계) #}
|
||||
{% macro num_cell(metric, kind, labels, mo) -%}
|
||||
<td class="pj-goal-numtd pj-goal-m{% if mo == this_month %} is-now{% endif %}" data-h="{{ (mo - 1) // 3 + 1 }}">
|
||||
{%- if is_admin -%}
|
||||
{%- set weekly = week_targets and metric == 'sales' and kind == 'target' -%}
|
||||
<td class="pj-goal-numtd pj-goal-m{% if mo == this_month %} is-now{% endif %}{% if weekly %} is-weekly{% endif %}" data-h="{{ (mo - 1) // 3 + 1 }}">
|
||||
{%- if pj_pro -%}
|
||||
<input type="text" class="pj-goal-num" inputmode="decimal" autocomplete="off"
|
||||
data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}"
|
||||
{%- if weekly %} readonly data-weekly="1" title="{{ mo }}월 목표·주차별 목표 입력"{% endif %}
|
||||
value="{{ labels.get(mo, '') }}" />
|
||||
{%- else -%}
|
||||
<span class="pj-goal-num" data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}">{{ labels.get(mo, '') }}</span>
|
||||
<span class="pj-goal-num" data-metric="{{ metric }}" data-kind="{{ kind }}" data-month="{{ mo }}"
|
||||
{%- if weekly %} data-weekly="1" tabindex="0" title="{{ mo }}월 주차별 목표 보기"{% endif %}>{{ labels.get(mo, '') }}</span>
|
||||
{%- endif -%}
|
||||
</td>
|
||||
{%- endmacro %}
|
||||
<table class="pj-goal-table" id="pj-goal-table" data-year="{{ goal_year }}"
|
||||
data-admin="{{ 'true' if is_admin else 'false' }}"
|
||||
data-pro="{{ 'true' if pj_pro else 'false' }}"
|
||||
data-halves="{{ 'true' if board.halves else 'false' }}">
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -162,7 +144,7 @@
|
||||
</tr>
|
||||
</tbody>
|
||||
|
||||
{# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색. 이름은 눌러서 그 자리에서 수정(관리자) ── #}
|
||||
{# ── 업무 영역 — 영역마다 tbody 하나, 배경은 영역 색. 이름은 눌러서 그 자리에서 수정(Pro user 이상) ── #}
|
||||
{% for area in board.areas %}
|
||||
<tbody class="pj-goal-area" data-area-id="{{ area.id }}" data-color="{{ area.color }}" style="--goal-bg: {{ area.color or '#fff' }}">
|
||||
{% for row in area.rows %}
|
||||
@@ -170,22 +152,22 @@
|
||||
{% if loop.first %}
|
||||
<th class="pj-goal-c1 pj-goal-area-name" rowspan="{{ area.rows | length }}">
|
||||
{# 구역 메뉴(색·위로·아래로·줄 추가·영역 삭제) — 우클릭 또는 ⋮ 버튼(키보드 Tab → Enter/Space, 터치 탭). project.js areaMenuItems #}
|
||||
<span class="pj-goal-area-text"{% if is_admin %} data-goal-edit="area" tabindex="0" role="button" title="눌러서 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ area.name }}</span>
|
||||
{% if is_admin %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="area" aria-haspopup="menu" aria-expanded="false"
|
||||
<span class="pj-goal-area-text"{% if pj_pro %} data-goal-edit="area" tabindex="0" role="button" title="눌러서 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ area.name }}</span>
|
||||
{% if pj_pro %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="area" aria-haspopup="menu" aria-expanded="false"
|
||||
aria-label="{{ area.name }} 구역 메뉴" title="구역 메뉴"><span class="material-symbols-outlined" aria-hidden="true">more_vert</span></button>{% endif %}
|
||||
</th>
|
||||
{% endif %}
|
||||
{# 항목 칸(2열) — 같은 항목 칸으로 묶인 줄(016 label_cont)은 묶음 첫 줄이 rowspan 으로 덮는다 #}
|
||||
{% if not row.label_cont %}
|
||||
<th class="pj-goal-c2 pj-goal-row-label"{% if (row.label_span or 1) > 1 %} rowspan="{{ row.label_span }}"{% endif %} data-label-span="{{ row.label_span or 1 }}">
|
||||
<span class="pj-goal-row-text"{% if is_admin %} data-goal-edit="row" tabindex="0" role="button" title="눌러서 줄 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ row.label }}</span>
|
||||
{% if is_admin %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="row" aria-haspopup="menu" aria-expanded="false"
|
||||
<span class="pj-goal-row-text"{% if pj_pro %} data-goal-edit="row" tabindex="0" role="button" title="눌러서 줄 이름 수정(Enter) · 우클릭·⋮ = 메뉴"{% endif %}>{{ row.label }}</span>
|
||||
{% if pj_pro %}<button type="button" class="pj-goal-menu-btn" data-goal-menu="row" aria-haspopup="menu" aria-expanded="false"
|
||||
aria-label="{{ (row.label or '이름 없는') }} 줄 메뉴" title="줄 메뉴"><span class="material-symbols-outlined" aria-hidden="true">more_vert</span></button>{% endif %}
|
||||
</th>
|
||||
{% endif %}
|
||||
{# 칸 배치는 router._goal_area_layout — 엑셀식 사각형 병합(colspan·rowspan), 가려진 칸은 없다 #}
|
||||
{% for c in row.layout %}
|
||||
{% set editable = is_admin and (c.kind != 'quarter' or (board.halves and (c.m not in (15, 16) or board.quarters))) %}
|
||||
{% set editable = pj_pro and (c.kind != 'quarter' or (board.halves and (c.m not in (15, 16) or board.quarters))) %}
|
||||
{% set merged = c.span > 1 or c.rspan > 1 %}
|
||||
<td class="pj-goal-texttd {{ 'pj-goal-m' if c.kind == 'month' else ('pj-goal-year-col' if c.kind == 'year' else 'pj-goal-half-col') }}{% if merged %} is-merged{% endif %}{% if c.now %} is-now{% endif %}"
|
||||
{% if c.kind in ('month', 'quarter') %}data-h="{{ c.h }}" {% endif %}data-month="{{ c.m }}" data-span="{{ c.span }}" data-rspan="{{ c.rspan }}"
|
||||
@@ -204,11 +186,11 @@
|
||||
</tbody>
|
||||
{% endfor %}
|
||||
</table>
|
||||
{% if is_admin %}
|
||||
{% if pj_pro %}
|
||||
<div class="pj-goal-foot">
|
||||
<button type="button" class="pj-btn" id="pj-goal-area-add">+ 업무 영역 추가</button>
|
||||
<span class="pj-goal-note">칸을 고치면 바로 저장됩니다. 글자를 드래그해 선택하면 선택한 셀 상단에서 12색 견본·크기 2px 증감·굵게·기울임·밑줄·서식 초기화를 사용할 수 있습니다. 모든 행의 셀 오른쪽 경계를 끌어 열 너비를 조절하고, 더블클릭하면 그 열의 가장 긴 문단에 맞춥니다. 숫자 칸을 비우면 지워집니다. 구역·항목 칸을 우클릭하거나 칸의 ⋮ 버튼(키보드 Tab·Enter, 터치)을 누르면 색·순서·줄 추가·삭제 메뉴가 나옵니다.
|
||||
셀 우클릭 → 현재 열·전체 열 너비 자동 맞춤(접힌 열 포함). 글 칸 하나를 클릭한 뒤 위·아래·왼쪽 테두리를 끌면 내용과 서식이 함께 이동합니다(대상에 글이 있으면 덮어쓰기 확인, Esc로 취소).
|
||||
셀 우클릭 → 현재 열·전체 열 너비 자동 맞춤(접힌 열 포함).
|
||||
{%- if board.halves %} 칸을 마우스로 끌어 여러 칸을 고른 뒤 우클릭 → 셀 병합, 병합된 칸은 우클릭 → 병합 해제(글은 왼쪽 위 칸에 남음).{% endif %}
|
||||
월 이름을 누르면 그 달 주간 회의록이 열립니다.</span>
|
||||
</div>
|
||||
@@ -220,9 +202,10 @@
|
||||
</div>
|
||||
|
||||
{% if goal_area_colors %}<script>window.PJ_GOAL_COLORS = {{ goal_area_colors | tojson }};</script>{% endif %}
|
||||
{% if week_targets %}<script>window.PJ_GOAL_WEEKS = {{ week_targets | tojson }}; window.PJ_GOAL_UNIT = {{ (board.sales_unit if board else '') | tojson }};</script>{% endif %}
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261003c" defer></script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
<script src="/static/project-goal-text.js?v=20261003d" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/project-help.css?v=20261003a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
@@ -21,9 +21,9 @@
|
||||
<li><a href="#project">프로젝트 만들기·고치기</a></li>
|
||||
<li><a href="#views">보기 전환과 필터</a></li>
|
||||
<li><a href="#board">보드 — 섹션과 작업 카드</a></li>
|
||||
<li><a href="#card-subtasks">카드에서 하위 작업 다루기</a></li>
|
||||
<li><a href="#card-subtasks">카드에서 세부 작업 다루기</a></li>
|
||||
<li><a href="#task">작업 편집 창</a></li>
|
||||
<li><a href="#subtasks">작업 창의 하위 작업</a></li>
|
||||
<li><a href="#subtasks">작업 창의 세부 작업</a></li>
|
||||
<li><a href="#dates">날짜 고르기</a></li>
|
||||
<li><a href="#list">목록 보기</a></li>
|
||||
<li><a href="#calendar">캘린더 보기</a></li>
|
||||
@@ -33,7 +33,7 @@
|
||||
<li><a href="#comments">댓글과 @태그</a></li>
|
||||
<li><a href="#inbox">수신함과 알림</a></li>
|
||||
<li><a href="#search">전체 검색과 공유 링크</a></li>
|
||||
<li><a href="#trash">휴지통 (관리자)</a></li>
|
||||
<li><a href="#trash">휴지통 (Pro user 이상)</a></li>
|
||||
<li><a href="#goals">연간 목표</a></li>
|
||||
<li><a href="#meetings">주간 회의록</a></li>
|
||||
<li><a href="#tips">단축키와 자주 묻는 질문</a></li>
|
||||
@@ -45,7 +45,7 @@
|
||||
<form id="pjh-search-form" role="search" aria-label="도움말 검색">
|
||||
<label for="pjh-query">도움말 검색</label>
|
||||
<div class="pjh-search-field">
|
||||
<input type="search" id="pjh-query" name="q" placeholder="예: 회의록, 셀 병합, 쇼핑몰 연결" autocomplete="off"
|
||||
<input type="search" id="pjh-query" name="q" placeholder="예: 회의록, 셀 병합, 매출 갱신" autocomplete="off"
|
||||
aria-describedby="pjh-search-hint pjh-search-status" aria-controls="pjh-results" />
|
||||
<button type="submit">검색</button>
|
||||
<button type="button" id="pjh-search-clear" hidden>지우기</button>
|
||||
@@ -63,7 +63,7 @@
|
||||
처음이라면 아래 다섯 단계만 따라 해도 바로 쓸 수 있어요.</p>
|
||||
<div class="pjh-quick">
|
||||
<div class="pjh-quick-step"><b>1단계</b>왼쪽 목록에서 <b style="display:inline;color:inherit">프로젝트</b>를 누릅니다.</div>
|
||||
<div class="pjh-quick-step"><b>2단계</b>보드에서 <span class="pjh-ui">+ 작업 추가</span>로 할 일을 만듭니다.</div>
|
||||
<div class="pjh-quick-step"><b>2단계</b>보드에서 <span class="pjh-ui">+ 메인 작업 추가</span>로 할 일을 만듭니다.</div>
|
||||
<div class="pjh-quick-step"><b>3단계</b>카드의 사람·달력 아이콘으로 담당자와 마감일을 정합니다.</div>
|
||||
<div class="pjh-quick-step"><b>4단계</b>카드를 눌러 설명을 쓰고, 댓글에 <kbd>@</kbd>로 동료를 부릅니다.</div>
|
||||
<div class="pjh-quick-step"><b>5단계</b>일을 마치면 <span class="pjh-ui">✓ 완료로 표시</span>를 누릅니다.</div>
|
||||
@@ -80,7 +80,7 @@
|
||||
<tr><td>프로젝트</td><td>함께 진행하는 일의 큰 묶음입니다. 예) “마케팅”, “신상품 출시”. 색상과 아이콘으로 구분합니다.</td></tr>
|
||||
<tr><td>섹션</td><td>프로젝트 안의 단계나 분류입니다. 보드에서 세로 칸 하나가 섹션입니다. 예) “할 일 · 진행 중 · 검토 · 완료”.</td></tr>
|
||||
<tr><td>작업</td><td>실제 할 일 하나입니다. 보드의 카드 한 장이 작업 하나입니다.</td></tr>
|
||||
<tr><td>하위 작업</td><td>작업을 더 잘게 나눈 할 일입니다. 작업 안에 목록으로 붙습니다. 원래 작업은 <b>상위 작업</b>이라고 부릅니다.</td></tr>
|
||||
<tr><td>세부 작업</td><td>작업을 더 잘게 나눈 할 일입니다. 작업 안에 목록으로 붙습니다. 원래 작업은 <b>상위 작업</b>이라고 부릅니다.</td></tr>
|
||||
<tr><td>담당자</td><td>그 작업을 책임지고 하는 사람 한 명입니다.</td></tr>
|
||||
<tr><td>협업자</td><td>작업의 진행 소식(완료·댓글)을 함께 받는 사람들입니다. 만든 사람·담당자·댓글 쓴 사람·@태그된 사람은 자동으로 들어갑니다.</td></tr>
|
||||
<tr><td>마감일 / 시작일</td><td>언제까지 끝낼지(마감일), 언제 시작하는지(시작일, 선택)입니다.</td></tr>
|
||||
@@ -96,20 +96,20 @@
|
||||
<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>수신함 · 내 작업 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
|
||||
<div class="pjh-map-main"><b>가운데 작업 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>오른쪽 위: 범위(이 프로젝트 / 전체 프로젝트)<br>필터 바<br>작업들</div>
|
||||
<div class="pjh-map-side"><b>왼쪽 사이드바</b>전체 검색<br>수신함 · 전체 보기(Pro user 이상) · 내 작업 · 휴지통 · 목표<br>프로젝트 목록<br>완료 프로젝트<br>전체 멤버</div>
|
||||
<div class="pjh-map-main"><b>가운데 작업 영역</b>왼쪽 위: 프로젝트 제목 · 멤버<br>그 아래: 보기 탭(보드 · 목록 · 캘린더 · 타임라인 · 대시보드)<br>필터 바<br>작업들</div>
|
||||
</div>
|
||||
<h3>왼쪽 사이드바</h3>
|
||||
<ul>
|
||||
<li><b>전체 검색</b> — 내가 볼 수 있는 모든 작업을 제목·설명·댓글로 찾습니다. (<a href="#search">18장</a>)</li>
|
||||
<li><b>수신함</b> — 나를 태그한 작업과 알림. 숫자 배지는 아직 확인하지 않은 @태그 수입니다. (<a href="#inbox">17장</a>)</li>
|
||||
<li><b>내 작업</b> — 내가 담당자인 작업 모음. 숫자 배지는 아직 끝나지 않은 작업 수입니다. (<a href="#mytasks">15장</a>)</li>
|
||||
<li><b>휴지통</b> — 지운 작업을 3개월 보관합니다. 관리자에게만 보입니다. (<a href="#trash">19장</a>)</li>
|
||||
<li><b>휴지통</b> — 지운 작업을 3개월 보관합니다. Pro user 이상에게만 보입니다. (<a href="#trash">19장</a>)</li>
|
||||
<li>왼쪽 메뉴의 오른쪽 경계를 끌면 너비를 최소 170px까지 줄일 수 있습니다. 경계에 키보드 포커스를 놓고 좌우 방향키로도 조절할 수 있으며 너비는 내 브라우저에 기억됩니다. 전체 멤버는 메뉴 너비에 맞춰 4열 또는 3열로 자동 배치됩니다.</li>
|
||||
<li><b>목표</b> — 연도를 골라 매출·로아스와 업무 영역별 연간·분기·월 계획을 봅니다. (<a href="#goals">연간 목표 설명</a>)</li>
|
||||
<li><b>주간 회의록</b> — 목표 표의 월 이름을 눌러 이번주 계획과 지난주 리뷰를 함께 봅니다. (<a href="#meetings">주간 회의록 설명</a>)</li>
|
||||
<li><b>프로젝트</b> — 내가 멤버인 프로젝트 목록입니다. 누르면 그 프로젝트 화면으로 갑니다. 완료한 프로젝트는 아래 <b>완료 프로젝트</b>에 흐리게 모입니다.</li>
|
||||
<li><b>전체 멤버</b> — 관리자에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 작업을 한눈에 봅니다.</li>
|
||||
<li><b>전체 멤버</b> — Pro user 이상에게만 보입니다. 사람 아이콘을 누르면 그 사람이 맡은 모든 작업을 한눈에 봅니다.</li>
|
||||
</ul>
|
||||
<h3>위쪽 바</h3>
|
||||
<ul>
|
||||
@@ -120,7 +120,7 @@
|
||||
기본 시스템 폰트·프리텐다드·나눔 스퀘어·나눔 스퀘어 네오·나눔 스퀘어 라운드 중 선택할 수 있습니다. 설정은 이 브라우저의 모든 Project 화면에서 기억합니다. <span class="pjh-ui">취소</span>는 변경을 적용하지 않고 닫습니다.</li>
|
||||
</ul>
|
||||
<h3>프로젝트 제목</h3>
|
||||
<p>가운데 위 프로젝트 제목에 마우스를 올리면 테두리가 생깁니다. 누르면 그 자리에서 이름을 고칩니다 — <kbd>Enter</kbd>나 바깥을 누르면 저장, <kbd>Esc</kbd>는 취소. (그 프로젝트 멤버·관리자만)</p>
|
||||
<p>가운데 위 프로젝트 제목에 마우스를 올리면 테두리가 생깁니다. 누르면 그 자리에서 이름을 고칩니다 — <kbd>Enter</kbd>나 바깥을 누르면 저장, <kbd>Esc</kbd>는 취소. (그 프로젝트 멤버인 Pro user 이상만)</p>
|
||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||
<div>여러 사람이 동시에 써도 걱정 없습니다. 다른 사람이 바꾼 내용은 <b>약 8초 안에</b> 내 화면에 자동으로 반영됩니다(새로고침하지 않아도 됩니다). 내가 입력 중인 창은 건드리지 않습니다.</div></div>
|
||||
</section>
|
||||
@@ -128,27 +128,52 @@
|
||||
<!-- 3. 권한 -->
|
||||
<section class="pjh-sec" id="roles">
|
||||
<h2><span class="pjh-num">3</span>누가 무엇을 할 수 있나요</h2>
|
||||
<p class="pjh-lead">프로젝트 관리 메뉴는 관리자 페이지에서 “프로젝트 관리” 권한을 받은 직원에게 보입니다.</p>
|
||||
<p class="pjh-lead">프로젝트 관리 메뉴는 관리자 페이지에서 “프로젝트 관리” 권한을 받은 직원에게 보입니다.
|
||||
등급은 <b>수퍼관리자 · Admin · Pro user · User</b> 네 가지이며(관리자 페이지에서 지정, 수퍼관리자는 한 명으로 고정), 등급과 상관없이
|
||||
<b>그 프로젝트의 멤버·소유자만</b> 프로젝트를 볼 수 있습니다(수퍼관리자만 예외).</p>
|
||||
<h3>프로젝트</h3>
|
||||
<table class="pjh-table">
|
||||
<tr><th>할 수 있는 일</th><th>누가</th></tr>
|
||||
<tr><td>프로젝트 보기</td><td>그 프로젝트의 <b>멤버·소유자</b>(또는 관리자). 멤버가 아니면 주소를 알아도 열리지 않습니다.</td></tr>
|
||||
<tr><td>작업·하위 작업·댓글</td><td>그 프로젝트의 멤버·소유자·관리자가 만들고 고칠 수 있습니다.</td></tr>
|
||||
<tr><td>작업·섹션·프로젝트 삭제</td><td><b>만든 사람만</b> 지울 수 있습니다(최고 관리자는 예외).</td></tr>
|
||||
<tr><td>댓글 고치기·지우기</td><td>댓글을 쓴 사람(또는 관리자)만.</td></tr>
|
||||
<tr><td>새 프로젝트, 사이드바의 프로젝트 수정·순서 바꾸기</td><td>관리자 (<span class="pjh-ui">+</span> · <span class="pjh-ui">✎</span> · <span class="pjh-ui">⣿</span> 버튼이 관리자에게만 보입니다)</td></tr>
|
||||
<tr><td>멤버 배정·제외, 프로젝트 소유자 바꾸기</td><td>관리자</td></tr>
|
||||
<tr><td>다른 프로젝트에서 연결돼 온 작업</td><td>원래 프로젝트 멤버가 아니면 <b>읽기만</b> — 내용·댓글·첨부는 보이지만 고치거나 댓글을 달 수 없습니다(연결된 보드 안에서 섹션 옮기기는 됩니다).</td></tr>
|
||||
<tr><td>멤버에서 빠졌을 때</td><td>그 프로젝트의 작업은 내 작업·수신함·알림·검색에서 사라지고, 예전 링크로도 열리지 않습니다. 새 알림도 오지 않습니다.</td></tr>
|
||||
<tr><td>휴지통 보기·복구, 전체 멤버, 대시보드의 담당자별 차트</td><td>관리자</td></tr>
|
||||
<tr><td>목표·주간 회의록 보기</td><td>프로젝트 관리 권한이 있는 직원 누구나 · <b>입력·생성·삭제·구조 편집</b>은 관리자</td></tr>
|
||||
<tr><td>프로젝트 제목 바로 고치기</td><td>그 프로젝트 멤버·소유자·관리자</td></tr>
|
||||
<tr><th>할 수 있는 일</th><th>Admin</th><th>Pro user</th><th>User</th></tr>
|
||||
<tr><td>프로젝트 보기, 작업·섹션 만들기·고치기·옮기기</td><td>O</td><td>O</td><td>O</td></tr>
|
||||
<tr><td>작업 삭제(휴지통으로)</td><td>O</td><td>O</td><td>O</td></tr>
|
||||
<tr><td>섹션 삭제</td><td>O</td><td>만든 사람만</td><td>만든 사람만</td></tr>
|
||||
<tr><td>서브프로젝트 만들기</td><td>O</td><td>O</td><td>O</td></tr>
|
||||
<tr><td>새 프로젝트 만들기 (<span class="pjh-ui">+</span>)</td><td>O</td><td>O</td><td>X</td></tr>
|
||||
<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>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>사이드바 프로젝트 순서 바꾸기 (<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>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>
|
||||
</table>
|
||||
<p>만든 사람 기록이 없는 옛 섹션·프로젝트는 Admin 이상만 지울 수 있습니다. 다른 프로젝트에서 연결돼 온 작업은 원래 프로젝트 멤버가 아니면
|
||||
<b>읽기만</b> 됩니다(연결된 보드 안에서 섹션 옮기기는 됩니다). 멤버에서 빠지면 그 프로젝트의 작업은 내 작업·수신함·알림·검색에서 사라지고,
|
||||
예전 링크로도 열리지 않습니다.</p>
|
||||
<h3>목표·주간 회의록</h3>
|
||||
<table class="pjh-table">
|
||||
<tr><th>할 수 있는 일</th><th>Admin</th><th>Pro user</th><th>User</th></tr>
|
||||
<tr><td>연간 목표 표 보기</td><td>O</td><td>O</td><td>O</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>O</td><td>O</td><td>X</td></tr>
|
||||
<tr><td>회의록 만들기·글 수정·줄 추가·삭제·칸 병합</td><td>O</td><td>O</td><td>O (완료 전까지)</td></tr>
|
||||
<tr><td>지난주 결과 입력</td><td>O</td><td>O</td><td>O (다음 주 회의록이 열려 있는 동안)</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>O</td><td>O</td><td>O</td></tr>
|
||||
<tr><td>회의록 “작업 등록 표”로 작업 만들기</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td><td>내가 멤버인 프로젝트에만</td></tr>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<!-- 4. 프로젝트 -->
|
||||
<section class="pjh-sec" id="project">
|
||||
<h2><span class="pjh-num">4</span>프로젝트 만들기·고치기</h2>
|
||||
<h3>새 프로젝트 만들기 (관리자)</h3>
|
||||
<h3>새 프로젝트 만들기 (Pro user 이상)</h3>
|
||||
<ol class="pjh-steps">
|
||||
<li>왼쪽 사이드바 <b>프로젝트</b> 제목 옆의 <span class="pjh-ui">+</span>를 누릅니다.</li>
|
||||
<li><b>이름</b>(필수)과 <b>설명</b>을 적습니다.</li>
|
||||
@@ -156,9 +181,13 @@
|
||||
<li><b>색상</b>(32가지)과 <b>아이콘</b>을 고릅니다. 아이콘 첫 칸 <span class="pjh-ui">Aa</span>를 고르면 아이콘 대신 이름 첫 글자가 나옵니다.</li>
|
||||
<li>함께할 <b>멤버</b>에 체크하고 <span class="pjh-ui">만들기</span>를 누릅니다. 만든 사람은 자동으로 프로젝트 주인이 됩니다.</li>
|
||||
</ol>
|
||||
<p>프로젝트는 만들어졌는데 일부 멤버를 배정하지 못하면 창이 닫히지 않고 <b>배정하지 못한 멤버</b>가 빨갛게 표시됩니다.
|
||||
<span class="pjh-ui">실패한 멤버 다시 배정</span>을 누르면 그 멤버만 다시 배정합니다(프로젝트를 또 만들지 않습니다).
|
||||
창을 닫으면 만든 프로젝트로 넘어가며, 남은 멤버는 프로젝트 화면에서 배정하면 됩니다.
|
||||
다른 사람을 소유자로 정해 만들면 만든 사람은 일반 멤버로 함께 들어갑니다(나중에 멤버에서 뺄 수 있습니다).</p>
|
||||
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span>
|
||||
<div>새 프로젝트는 섹션 없이 빈 보드로 시작합니다. 보드의 <span class="pjh-ui">+ 섹션 추가</span>로 “할 일 · 진행 중 · 완료”처럼 단계를 먼저 만들어 두면 편합니다. (<a href="#board">6장</a>)</div></div>
|
||||
<h3>프로젝트 수정 (관리자)</h3>
|
||||
<h3>프로젝트 수정 (Pro user 이상)</h3>
|
||||
<p>사이드바의 프로젝트 이름에 마우스를 올리면 오른쪽에 <span class="pjh-ui">✎</span>(수정)과 <span class="pjh-ui">×</span>(삭제)가 나옵니다.
|
||||
이름에서 <b>마우스 오른쪽 버튼</b>을 눌러도 <span class="pjh-ui">열기 · 수정 · 삭제</span> 메뉴가 나옵니다.</p>
|
||||
<ul>
|
||||
@@ -166,16 +195,17 @@
|
||||
<li><b>프로젝트 완료</b>에 체크하면 목록 맨 아래 “완료 프로젝트”로 옮겨지고 흐리게 보입니다.</li>
|
||||
<li>색이 밝으면(연노랑·하늘색 등) 글자와 아이콘이 자동으로 어둡게 바뀌어 잘 보입니다.</li>
|
||||
</ul>
|
||||
<h3>순서 바꾸기 (관리자)</h3>
|
||||
<p>프로젝트 이름에 마우스를 올리면 왼쪽에 손잡이 <span class="pjh-ui">⣿</span>가 나옵니다. 잡고 위아래로 끌어 놓으면 순서가 저장됩니다.</p>
|
||||
<h3>순서 바꾸기 (Pro user 이상)</h3>
|
||||
<p>프로젝트 이름에 마우스를 올리면 왼쪽에 손잡이 <span class="pjh-ui">⣿</span>가 나옵니다. 잡고 위아래로 끌어 놓으면 순서가 저장됩니다.
|
||||
순서는 모두가 같이 보는 순서이고, 내가 멤버인 프로젝트만 옮길 수 있습니다.</p>
|
||||
<h3>프로젝트 삭제</h3>
|
||||
<p><span class="pjh-ui">×</span> 또는 우클릭 <span class="pjh-ui">삭제</span>. <b>프로젝트를 만든 사람만</b> 지울 수 있고, 안의 작업도 모두 함께 지워집니다.</p>
|
||||
<p><span class="pjh-ui">×</span> 또는 우클릭 <span class="pjh-ui">삭제</span>. <b>프로젝트를 만든 사람</b>(또는 Admin 이상)만 지울 수 있고, 안의 작업도 모두 함께 지워집니다.</p>
|
||||
<div class="pjh-warn"><span class="material-symbols-outlined">warning</span>
|
||||
<div>프로젝트 삭제는 되돌릴 수 없습니다. 끝난 프로젝트는 지우기보다 <b>프로젝트 완료</b>로 표시하는 것을 권합니다.</div></div>
|
||||
<h3>멤버 배정 (관리자)</h3>
|
||||
<h3>멤버 배정 (Pro user 이상)</h3>
|
||||
<p>프로젝트 화면 제목 오른쪽에 멤버 사진이 겹쳐서 보입니다.</p>
|
||||
<ul>
|
||||
<li><span class="pjh-ui">+</span> — 멤버를 추가합니다(프로젝트 관리 권한이 있는 직원 중에서 고릅니다).</li>
|
||||
<li><span class="pjh-ui">+</span> — 멤버 배정·제외 창이 열립니다. 지금 멤버는 체크된 채로 나오며, <b>체크하면 배정, 체크를 풀면 제외</b>됩니다(제외는 확인 후). 후보는 프로젝트 관리 권한이 있는 직원이고, 소유자는 뺄 수 없습니다.</li>
|
||||
<li>사진에 마우스 → 이름이 보입니다. <b>클릭</b> → 그 사람이 이 프로젝트에서 맡은 작업 목록이 뜹니다.</li>
|
||||
<li>사진에서 <b>우클릭</b> → <span class="pjh-ui">제외</span>로 멤버에서 뺍니다.</li>
|
||||
</ul>
|
||||
@@ -195,8 +225,10 @@
|
||||
<tr><td>대시보드</td><td>완료·미완료·지연 숫자와 차트로 진행 상황을 볼 때. (<a href="#dashboard">14장</a>)</td></tr>
|
||||
</table>
|
||||
<h3>범위: 이 프로젝트 / 전체 프로젝트</h3>
|
||||
<p>화면 오른쪽 위 토글입니다. <b>이 프로젝트</b>는 지금 프로젝트만, <b>전체 프로젝트</b>는 내가 볼 수 있는 모든 프로젝트의 작업을 함께 보여줍니다.
|
||||
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 작업인지 이름이 붙습니다.</p>
|
||||
<p>프로젝트 화면은 지금 프로젝트만 보여줍니다. Pro user 이상은 왼쪽 메뉴 수신함 아래 <b>전체 보기</b>를 누르면 내가 볼 수 있는 모든 프로젝트의 작업을 함께 봅니다
|
||||
(왼쪽 프로젝트 목록에서 프로젝트를 누르면 다시 그 프로젝트만).
|
||||
전체 프로젝트일 때는 위 제목이 <b>전체 프로젝트</b>로 바뀌고, 카드 위에는 어느 프로젝트 작업인지 이름이 붙습니다.
|
||||
다른 프로젝트에서 연결돼 와 <b>읽기만 되는 작업</b>도 한 번씩 함께 보입니다.</p>
|
||||
<h3>필터 바</h3>
|
||||
<p>탭 아래 한 줄로 작업을 거르고 정렬합니다. 다섯 가지 보기 모두에 똑같이 적용되고, 프로젝트마다 이 브라우저에 기억됩니다.</p>
|
||||
<ul>
|
||||
@@ -224,7 +256,7 @@
|
||||
<li><b>순서 바꾸기</b> — 섹션 머리(이름 줄)를 잡고 좌우로 끌어 놓습니다.</li>
|
||||
<li><b>… 메뉴</b>(머리 오른쪽 <span class="pjh-ui">…</span> 또는 머리 우클릭):
|
||||
<ul>
|
||||
<li><span class="pjh-ui">작업 추가</span> · <span class="pjh-ui">이름 변경</span></li>
|
||||
<li><span class="pjh-ui">메인 작업 추가</span> · <span class="pjh-ui">이름 변경</span></li>
|
||||
<li><span class="pjh-ui">섹션 편집</span> — 색상과 <b>기본 담당자</b>를 정합니다. 색상 첫 칸(연회색)은 “색 없음”입니다.</li>
|
||||
<li><span class="pjh-ui">섹션 작업 모두 완료</span> — 그 섹션의 미완료 작업을 한 번에 완료합니다.</li>
|
||||
<li><span class="pjh-ui">완료 섹션으로 지정</span> — 이 섹션으로 옮긴 카드는 <b>자동으로 완료</b>되고, 밖으로 빼면 다시 미완료가 됩니다. 완료 섹션은 흐리게, 보드 끝에 놓입니다.</li>
|
||||
@@ -236,8 +268,8 @@
|
||||
<div><b>기본 담당자</b>를 정해 두면, 그 섹션에 담당자 없는 작업을 새로 만들거나 옮겨 올 때 그 사람이 자동으로 담당자가 됩니다. 예) “검토” 섹션의 기본 담당자 = 팀장.</div></div>
|
||||
<h3>작업 카드 다루기</h3>
|
||||
<ul>
|
||||
<li><b>상단 작업 추가</b> — 섹션 머리의 <span class="pjh-ui">+</span>는 오른쪽에서 작업 상세창을 엽니다. 제목·설명·담당자·우선순위·마감일을 설정할 수 있습니다.</li>
|
||||
<li><b>하단 작업 추가</b> — 섹션 맨 아래 <span class="pjh-ui">+ 작업 추가</span>는 보드 안에 간단한 입력 카드를 엽니다. <b>작업 이름·담당자·마감일</b>을 정한 뒤 <kbd>Enter</kbd>를 누르거나 카드 밖을 클릭하면 저장됩니다. Enter로 저장하면 다음 작업을 계속 입력할 수 있고, <kbd>Esc</kbd>로 취소할 수 있습니다.</li>
|
||||
<li><b>상단 메인 작업 추가</b> — 섹션 머리의 <span class="pjh-ui">+</span>는 오른쪽에서 작업 상세창을 엽니다. 제목·설명·담당자·우선순위·마감일을 설정할 수 있습니다.</li>
|
||||
<li><b>하단 메인 작업 추가</b> — 섹션 맨 아래 <span class="pjh-ui">+ 메인 작업 추가</span>는 보드 안에 간단한 입력 카드를 엽니다. <b>작업 이름·담당자·마감일</b>을 정한 뒤 <kbd>Enter</kbd>를 누르거나 카드 밖을 클릭하면 저장됩니다. Enter로 저장하면 다음 작업을 계속 입력할 수 있고, <kbd>Esc</kbd>로 취소할 수 있습니다.</li>
|
||||
<li><b>열기</b> — 카드를 누르면 오른쪽에 작업 편집 창이 열립니다. (<a href="#task">8장</a>)</li>
|
||||
<li><b>완료 체크</b> — 카드 제목 왼쪽의 원형 체크 버튼을 누르면 완료됩니다. 완료된 작업은 <b>녹색 원 안 흰 체크</b>와 흐린 회색 제목으로 표시되며 취소선은 없습니다. 다시 누르면 완료를 취소합니다. 읽기 전용 작업은 상태만 표시합니다.</li>
|
||||
<li><b>담당자·마감일 바로 바꾸기</b> — 카드의 사람 아이콘이나 날짜를 누르면 그 자리에서 바꿉니다. 비어 있으면 카드에 마우스를 올렸을 때 점선 원 아이콘이 나타납니다.</li>
|
||||
@@ -254,24 +286,24 @@
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<!-- 7. 카드의 하위 작업 -->
|
||||
<!-- 7. 카드의 세부 작업 -->
|
||||
<section class="pjh-sec" id="card-subtasks">
|
||||
<h2><span class="pjh-num">7</span>카드에서 하위 작업 다루기</h2>
|
||||
<p class="pjh-lead">하위 작업이 있는 카드에는 <span class="pjh-ui">3 ⤷ ▾</span> 처럼 개수 버튼이 붙습니다. 누르면 카드 아래로 하위 작업 목록이 펼쳐집니다.</p>
|
||||
<h2><span class="pjh-num">7</span>카드에서 세부 작업 다루기</h2>
|
||||
<p class="pjh-lead">세부 작업이 있는 카드에는 <span class="pjh-ui">3 ⤷ ▾</span> 처럼 개수 버튼이 붙습니다. 누르면 카드 아래로 세부 작업 목록이 펼쳐집니다.</p>
|
||||
<ul>
|
||||
<li><b>완료</b> — 줄 왼쪽 <span class="pjh-ui">✓</span>를 누릅니다.</li>
|
||||
<li><b>마감일·담당자</b> — 줄 오른쪽 날짜나 사람 아이콘을 누르면 그 자리에서 바꿉니다.</li>
|
||||
<li><b>열기</b> — 줄을 누르면 그 하위 작업이 작업처럼 편집 창으로 열립니다.</li>
|
||||
<li><b>우클릭</b> — <span class="pjh-ui">열기 · 상위 작업 열기 · 완료로 표시 · 하위 작업 삭제</span></li>
|
||||
<li><b>순서 바꾸기</b> — 펼친 하위 작업 한 줄을 끌어 같은 카드 안의 원하는 위치에 놓습니다. 보라색 선이 삽입 위치를 보여 주며, 변경한 순서는 저장됩니다.</li>
|
||||
<li><b>다른 작업으로 옮기기</b> — 하위 작업 한 줄을 끌어서 <b>다른 카드</b>에 놓으면 그 작업의 하위 작업이 됩니다(놓을 수 있는 카드는 보라색 테두리가 생깁니다). 같은 프로젝트 안에서만 옮길 수 있습니다.</li>
|
||||
<li><b>열기</b> — 줄을 누르면 그 세부 작업이 작업처럼 편집 창으로 열립니다.</li>
|
||||
<li><b>우클릭</b> — <span class="pjh-ui">열기 · 상위 작업 열기 · 완료로 표시 · 세부 작업 삭제</span></li>
|
||||
<li><b>순서 바꾸기</b> — 펼친 세부 작업 한 줄을 끌어 같은 카드 안의 원하는 위치에 놓습니다. 보라색 선이 삽입 위치를 보여 주며, 변경한 순서는 저장됩니다.</li>
|
||||
<li><b>다른 작업으로 옮기기</b> — 세부 작업 한 줄을 끌어서 <b>다른 카드</b>에 놓으면 그 작업의 세부 작업이 됩니다(놓을 수 있는 카드는 보라색 테두리가 생깁니다). 같은 프로젝트 안에서만 옮길 수 있습니다.</li>
|
||||
</ul>
|
||||
<h3>+ 하위 작업 추가</h3>
|
||||
<h3>+ 세부 작업 추가</h3>
|
||||
<ol class="pjh-steps">
|
||||
<li>펼친 목록 맨 아래 <span class="pjh-ui">+ 하위 작업 추가</span>를 누릅니다.</li>
|
||||
<li>펼친 목록 맨 아래 <span class="pjh-ui">+ 세부 작업 추가</span>를 누릅니다.</li>
|
||||
<li>새 줄의 “작업 이름 입력” 칸에 이름을 씁니다.</li>
|
||||
<li>필요하면 달력 아이콘으로 마감일, 사람 아이콘으로 담당자를 고릅니다.</li>
|
||||
<li><kbd>Enter</kbd>를 누르면 만들어지고, 빈 줄이 다시 열려 다음 하위 작업을 이어서 쓸 수 있습니다.</li>
|
||||
<li><kbd>Enter</kbd>를 누르면 만들어지고, 빈 줄이 다시 열려 다음 세부 작업을 이어서 쓸 수 있습니다.</li>
|
||||
<li>이름을 쓴 채 <b>다른 곳을 누르면</b> <kbd>Enter</kbd>와 같이 만들어지고 줄이 닫힙니다.</li>
|
||||
<li>만들지 않고 닫으려면 <kbd>Esc</kbd>를 누르거나, 빈 채로 다른 곳을 누릅니다.</li>
|
||||
</ol>
|
||||
@@ -286,11 +318,11 @@
|
||||
<tr><th>버튼</th><th>하는 일</th></tr>
|
||||
<tr><td><span class="pjh-ui"><span class="material-symbols-outlined">link</span>공유</span></td><td>이 작업의 주소를 복사합니다. 메신저로 보내면 받은 멤버가 바로 이 작업을 엽니다.</td></tr>
|
||||
<tr><td><span class="pjh-ui">✓ 완료로 표시</span></td><td>작업을 완료합니다. 다시 누르면 <span class="pjh-ui">↩ 완료 취소</span>.</td></tr>
|
||||
<tr><td><span class="pjh-ui">삭제</span></td><td>작업을 지웁니다(만든 사람만). 하위 작업이 있으면 함께 지울지 한 번 더 묻습니다. 지운 작업은 휴지통에 3개월 보관됩니다.</td></tr>
|
||||
<tr><td><span class="pjh-ui">삭제</span></td><td>작업을 지웁니다(만든 사람만). 세부 작업이 있으면 함께 지울지 한 번 더 묻습니다. 지운 작업은 휴지통에 3개월 보관됩니다.</td></tr>
|
||||
<tr><td><span class="pjh-ui">저장됨</span></td><td>저장 버튼이 없습니다 — 고치는 즉시 저장되고, 버튼 줄 오른쪽에 <span class="pjh-ui">저장 중…</span> → <span class="pjh-ui">✓ 저장됨</span>이 잠깐 보입니다. 저장이 안 되면 <span class="pjh-ui">저장 실패 · 다시 시도</span>(눌러서 다시 저장)가 뜨고, 이 상태로 창을 닫거나 다른 작업을 열면 한 번 더 저장해 본 뒤 <b>버리고 넘어갈지 / 계속 편집할지</b> 묻습니다 — 모른 채 내용이 사라지지 않습니다. 이미지를 올리는 중이면 다 올라갈 때까지 기다렸다가 넘어갑니다.</td></tr>
|
||||
</table>
|
||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||
<div><b>실시간 저장</b> — 제목은 칸을 벗어나거나 <kbd>Enter</kbd>, 설명은 입력을 멈추고 1초쯤 뒤(또는 칸을 벗어날 때), 담당자·섹션·우선순위·마감일은 바꾸는 즉시 저장됩니다. 새 작업은 <b>제목을 쓰는 순간</b> 만들어집니다(제목 없이 닫으면 만들어지지 않습니다). 협업자 · 하위 작업 · 첨부 파일 · 다른 프로젝트 추가 · 댓글도 누르는 즉시 저장됩니다.</div></div>
|
||||
<div><b>실시간 저장</b> — 제목은 칸을 벗어나거나 <kbd>Enter</kbd>, 설명은 입력을 멈추고 1초쯤 뒤(또는 칸을 벗어날 때), 담당자·섹션·우선순위·마감일은 바꾸는 즉시 저장됩니다. 새 작업은 <b>제목을 쓰는 순간</b> 만들어집니다(제목 없이 닫으면 만들어지지 않습니다). 협업자 · 세부 작업 · 첨부 파일 · 다른 프로젝트 추가 · 댓글도 누르는 즉시 저장됩니다.</div></div>
|
||||
<h3>제목과 기본 정보</h3>
|
||||
<ul>
|
||||
<li><b>제목</b> — 맨 위 큰 글씨를 눌러 바로 고칩니다.</li>
|
||||
@@ -315,9 +347,9 @@
|
||||
<li><b>@태그</b> — <kbd>@</kbd>를 누르면 사람 목록이 뜹니다. 고른 사람의 수신함에 이 작업이 쌓입니다.</li>
|
||||
</ul>
|
||||
<h3>첨부 파일</h3>
|
||||
<p><span class="pjh-ui">파일 추가</span>로 파일을 올립니다(한 파일 최대 20MB). 파일 이름을 누르면 내려받고, <span class="pjh-ui">×</span>로 지웁니다.</p>
|
||||
<p><span class="pjh-ui">파일 추가</span>로 파일을 올립니다(한 파일 최대 20MB). 파일 이름 옆에 이미지·엑셀·텍스트·PPT·문서·PDF 형식별 아이콘이 표시됩니다. 파일 이름을 누르면 내려받고, <span class="pjh-ui">×</span>로 지웁니다.</p>
|
||||
<h3>프로젝트 (다른 프로젝트에 추가)</h3>
|
||||
<p>작업 하나를 <b>여러 프로젝트의 보드에 동시에</b> 보이게 합니다. 예) 신상품 프로젝트의 작업을 디자인 프로젝트 보드에도 올리기.</p>
|
||||
<p>작업 하나를 <b>여러 프로젝트의 보드에 동시에</b> 보이게 합니다. 예) 신상품 프로젝트의 작업을 디자인 프로젝트 보드에도 올리기. 협업자 아래의 프로젝트 줄에 연결 목록·프로젝트 선택·섹션 선택·추가 버튼이 한 줄로 표시됩니다. 창이 좁으면 이 줄을 좌우로 스크롤할 수 있습니다.</p>
|
||||
<ol class="pjh-steps">
|
||||
<li>“프로젝트” 칸에서 프로젝트를 고릅니다.</li>
|
||||
<li>그 프로젝트에서 들어갈 섹션을 고릅니다.</li>
|
||||
@@ -329,22 +361,22 @@
|
||||
<p>댓글 대화창에서 파일을 보낼 때 보낼 수 없는 파일(빈 파일, 20MB 초과)이 있으면 댓글을 만들지 않고 그 파일만 빨갛게 표시합니다 — 빼고 다시 보내세요. 인터넷이 끊겨도 쓴 내용과 파일은 그대로 남아 다시 보낼 수 있고, 같은 댓글이 두 번 올라가지 않습니다. @태그는 이 작업을 볼 수 있는 사람만 고를 수 있습니다. 한글을 입력하는 중(조합 중)의 <kbd>Enter</kbd>는 글자 확정만 하고 보내지 않습니다.</p>
|
||||
</section>
|
||||
|
||||
<!-- 9. 작업 창의 하위 작업 -->
|
||||
<!-- 9. 작업 창의 세부 작업 -->
|
||||
<section class="pjh-sec" id="subtasks">
|
||||
<h2><span class="pjh-num">9</span>작업 창의 하위 작업</h2>
|
||||
<p class="pjh-lead">작업 편집 창 가운데 “하위 작업” 목록입니다. 한 줄에 하나씩, 아사나처럼 다룹니다.</p>
|
||||
<h2><span class="pjh-num">9</span>작업 창의 세부 작업</h2>
|
||||
<p class="pjh-lead">작업 편집 창 가운데 “세부 작업” 목록입니다. 한 줄에 하나씩, 아사나처럼 다룹니다.</p>
|
||||
<ul>
|
||||
<li><b>추가</b> — 목록 아래 입력칸에 이름을 쓰고, 필요하면 담당자·마감일을 고른 뒤 <span class="pjh-ui">추가</span> 또는 <kbd>Enter</kbd>.</li>
|
||||
<li><b>순서 바꾸기</b> — 줄에 마우스를 올리면 왼쪽에 <span class="pjh-ui">⠿</span> 손잡이가 나옵니다. 잡고 위아래로 끌어 놓습니다.</li>
|
||||
<li><b>완료</b> — <span class="pjh-ui">✓</span>를 누릅니다. 완료한 줄은 취소선이 그어집니다.</li>
|
||||
<li><b>이름 고치기</b> — 이름 글자를 눌러 바로 고칩니다(칸은 이름 길이만큼만 차지합니다).</li>
|
||||
<li><b>마감일·담당자</b> — 날짜 글자나 사람 아이콘을 누릅니다. 비어 있으면 줄에 마우스를 올렸을 때 점선 아이콘이 나옵니다.</li>
|
||||
<li><b>열기</b> — 줄의 빈 곳이나 오른쪽 <span class="pjh-ui">›</span>를 누르면 그 하위 작업이 편집 창으로 열립니다.</li>
|
||||
<li><b>하위 작업의 하위 작업</b> — 그 하위 작업 안에도 하위 작업이 있으면 이름 옆에 <span class="pjh-ui">N ⤷</span> 아이콘이 붙습니다(보드 카드의 펼친 목록도 같음).</li>
|
||||
<li><b>삭제</b> — 줄에서 우클릭 → <span class="pjh-ui">하위 작업 삭제</span>.</li>
|
||||
<li><b>열기</b> — 줄의 빈 곳이나 오른쪽 <span class="pjh-ui">›</span>를 누르면 그 세부 작업이 편집 창으로 열립니다.</li>
|
||||
<li><b>세부 작업의 세부 작업</b> — 그 세부 작업 안에도 세부 작업이 있으면 이름 옆에 <span class="pjh-ui">N ⤷</span> 아이콘이 붙습니다(보드 카드의 펼친 목록도 같음).</li>
|
||||
<li><b>삭제</b> — 줄에서 우클릭 → <span class="pjh-ui">세부 작업 삭제</span>.</li>
|
||||
</ul>
|
||||
<h3>하위 작업을 열었을 때</h3>
|
||||
<p>하위 작업도 작업과 똑같이 설명 · 담당자 · 마감일 · 협업자 · 첨부 파일 · 댓글을 모두 쓸 수 있습니다. 제목 위에 <span class="pjh-ui">↰ 상위 작업 이름</span>이 보이고, 누르면 상위 작업으로 돌아갑니다. 하위 작업에는 섹션이 없어서 섹션 칸은 나오지 않습니다.</p>
|
||||
<h3>세부 작업을 열었을 때</h3>
|
||||
<p>세부 작업도 작업과 똑같이 설명 · 담당자 · 마감일 · 협업자 · 첨부 파일 · 댓글을 모두 쓸 수 있습니다. 제목 위에 <span class="pjh-ui">↰ 상위 작업 이름</span>이 보이고, 누르면 상위 작업으로 돌아갑니다. 세부 작업에는 섹션이 없어서 섹션 칸은 나오지 않습니다.</p>
|
||||
</section>
|
||||
|
||||
<!-- 10. 날짜 -->
|
||||
@@ -359,7 +391,7 @@
|
||||
<li>창 바깥을 누르거나 <kbd>Esc</kbd>로 닫습니다.</li>
|
||||
</ul>
|
||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||
<div>보드 카드와 하위 작업 줄에서는 날짜를 누르는 즉시 저장됩니다. 작업 편집 창의 마감일도 고르는 즉시 저장됩니다.</div></div>
|
||||
<div>보드 카드와 세부 작업 줄에서는 날짜를 누르는 즉시 저장됩니다. 작업 편집 창의 마감일도 고르는 즉시 저장됩니다.</div></div>
|
||||
</section>
|
||||
|
||||
<!-- 11. 목록 -->
|
||||
@@ -390,9 +422,9 @@
|
||||
<h2><span class="pjh-num">13</span>타임라인 보기</h2>
|
||||
<ul>
|
||||
<li>기간이 있는(시작일 또는 마감일이 있는) 작업이 가로 막대로 나옵니다. <b>이 프로젝트</b>는 섹션별 줄, <b>전체 프로젝트</b>는 프로젝트별 줄이며 프로젝트 전체 기간이 옅은 배경으로 깔립니다.</li>
|
||||
<li>작업은 아사나처럼 <b>카드</b>로 보입니다 — 담당자 사진 · 제목 · 하위 작업이 있으면 <span class="pjh-ui">N ⤷</span> · 댓글이 있으면 <span class="pjh-ui">💬 N</span>(누르면 댓글 대화창), 아래 줄에 “마감일: 9월 23일”처럼 날짜. 기간이 있는 작업은 기간만큼 막대로 늘어납니다.</li>
|
||||
<li>카드에 하위 작업이 있으면 <span class="pjh-ui">N ⤷</span>(마우스를 올리면 “하위 작업 N개”), 설명이 있으면 줄글 아이콘이 붙습니다. 하위 작업은 작업 편집 창에서 봅니다.</li>
|
||||
<li>줄 색은 <b>섹션 편집에서 정한 섹션 색</b>입니다(색이 없는 섹션은 프로젝트 색). 왼쪽 섹션 이름 앞에도 같은 색 네모가 붙습니다. 주말은 세로줄이 옅은 회색입니다.</li>
|
||||
<li>작업은 아사나처럼 <b>카드</b>로 보입니다 — 담당자 사진 · 제목 · 세부 작업이 있으면 <span class="pjh-ui">N ⤷</span> · 댓글이 있으면 <span class="pjh-ui">💬 N</span>(누르면 댓글 대화창), 아래 줄에 “마감일: 9월 23일”처럼 날짜. 기간이 있는 작업은 기간만큼 막대로 늘어납니다.</li>
|
||||
<li>카드에 세부 작업이 있으면 <span class="pjh-ui">N ⤷</span>(마우스를 올리면 “세부 작업 N개”), 설명이 있으면 줄글 아이콘이 붙습니다. 세부 작업은 작업 편집 창에서 봅니다.</li>
|
||||
<li>줄 색은 <b>프로젝트 색</b>입니다(섹션별 색 지정은 없앴습니다 — 보드의 섹션 머리는 모두 같은 연회색). 주말은 세로줄이 옅은 회색입니다.</li>
|
||||
<li>카드(막대)를 <b>바로 끌면</b> 하루 단위로 기간 전체가 이동하고(하루짜리 작업은 마감일이 옮겨집니다), 기간 막대의 <b>양 끝을 끌면</b> 시작일이나 마감일만 바뀝니다. 먼저 눌러 선택하지 않아도 됩니다.</li>
|
||||
<li>처음 열면 하루 칸이 날짜 글자(“30일 (수)”) 폭만큼이라 한 화면에 여러 날이 보입니다. <kbd>Ctrl</kbd> + 마우스 휠로 확대·축소(하루 칸이 날짜 글자 폭이 되면 더 줄어들지 않습니다), 빈 곳을 끌면 좌우로 이동합니다(보던 구간은 기억). <span class="pjh-ui">오늘</span>로 오늘 날짜로 돌아옵니다.</li>
|
||||
<li>아래 날짜 줄은 캘린더와 같은 색입니다 — <span style="color:#1d4ed8;font-weight:700">토요일은 파랑</span>, <span style="color:#c22b10;font-weight:700">일요일·국경일·대체공휴일은 빨강</span>. 공휴일은 날짜 밑에 이름(예: 추석, 대체휴일)이 나오고, 마우스를 올리면 전체 이름이 보입니다.</li>
|
||||
@@ -407,7 +439,7 @@
|
||||
<li>위쪽 숫자 카드 4개: <b>완료된 작업 합계 · 미완료 작업 합계 · 마감일이 지난 작업 합계 · 작업 합계</b></li>
|
||||
<li><b>미완료 작업 합계(섹션별)</b> — 섹션마다 남은 일이 몇 개인지 막대로 보여줍니다. 막대에 마우스를 올리면 숫자가 나옵니다.</li>
|
||||
<li><b>작업 합계(완료 상태별)</b> — 완료와 미완료 비율을 도넛 차트로 보여줍니다.</li>
|
||||
<li><b>예정된 작업 합계(담당자별)</b> — 사람별로 일정이 잡힌 미완료 작업 수(상위 10명). <b>관리자에게만</b> 보입니다.</li>
|
||||
<li><b>담당자별 작업 합계(메인·세부 작업, 완료)</b> — 이 범위에서 사람별로 배정된 작업 <b>전부</b>(마감일이 없어도, 필터와 관계없이)를 사람마다 <b>메인 작업·세부 작업 세로 막대</b>로 보여 줍니다(막대 하나 = 그 작업 전체, 초록으로 찬 높이 = 완료율, 위 숫자 = 완료/전체와 %, 이름 아래 = 전체 완료율). 막대를 누르면 오른쪽에서 그 사람의 업무 목록(미완료·완료)이 나오고, 항목을 누르면 작업 편집 창이 열립니다. 편집 창을 닫으면 숫자와 목록이 다시 계산됩니다. 세부 작업은 세부 작업에 지정된 담당자 기준입니다. <b>Pro user 이상에게만</b> 보입니다.</li>
|
||||
<li>범위(이 프로젝트/전체 프로젝트)와 필터 바 설정을 그대로 따라 계산합니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
@@ -421,7 +453,7 @@
|
||||
<li>찾기(제목·설명·프로젝트), 마감(마감 지남·오늘·이번 주·마감일 없음), 우선순위로 거를 수 있습니다.</li>
|
||||
<li>칸 제목을 누르면 정렬합니다.</li>
|
||||
<li>줄을 누르면 그 작업의 프로젝트 화면으로 가서 작업 편집 창이 바로 열립니다. 우클릭하면 작업 메뉴가 나옵니다.</li>
|
||||
<li>내가 담당자인 하위 작업은 상위 작업 이름 아래에 들여 쓴 줄로 나옵니다.</li>
|
||||
<li>내가 담당자인 세부 작업은 상위 작업 이름 아래에 들여 쓴 줄로 나옵니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
@@ -458,7 +490,10 @@
|
||||
<h3>수신함 화면</h3>
|
||||
<ul>
|
||||
<li><b>나를 태그한 작업</b> — 누가 나를 @태그했는지와 함께 보입니다. <span class="pjh-ui">태그 모두 확인</span>으로 한 번에 확인 처리합니다.</li>
|
||||
<li><b>알림</b> — 작업 배정 · 작업 완료 · 새 댓글 · 마감 알림이 쌓입니다. 항목을 누르면 읽음이 되고, <span class="pjh-ui">확인</span>을 누르면 수신함에 머문 채 <b>오른쪽에 그 작업 창</b>이 열립니다(나를 태그한 작업도 같음). 창 맨 위 <span class="pjh-ui">프로젝트로 이동</span>을 누르면 그 작업이 있는 프로젝트 화면으로 갑니다. 창을 닫으면(→| 또는 <kbd>Esc</kbd>) 다시 수신함입니다. <kbd>Ctrl</kbd>+클릭하면 새 탭에서 프로젝트 화면으로 엽니다.</li>
|
||||
<li><b>알림</b> — 작업 배정 · 작업 완료 · 새 댓글 · 마감 알림이 쌓입니다. 수신함에는 <b>아직 확인하지 않은 것만</b> 나옵니다. 줄을 누르면 수신함에 머문 채 <b>오른쪽에 그 작업 창</b>이 열리고(나를 태그한 작업도 같음), 작업 창이 열린 채 다른 줄을 누르면 작업 창이 그 작업으로 바뀝니다. 한 번 확인한 줄은 다른 줄을 고르거나 창을 닫으면 수신함에서 빠집니다(같은 작업의 태그·알림 줄은 함께). 열지 않고 빼려면 오른쪽 클릭 → <span class="pjh-ui">확인(목록에서 빼기)</span>. 창 맨 위 <span class="pjh-ui">프로젝트로 이동</span>을 누르면 그 작업이 있는 프로젝트 화면으로 갑니다. 창을 닫으면(→| 또는 <kbd>Esc</kbd>) 다시 수신함입니다. <kbd>Ctrl</kbd>+클릭하면 새 탭에서 프로젝트 화면으로 엽니다.
|
||||
작업 창에서 저장 중이거나 저장하지 못한 내용이 있으면, 다른 줄로 바꾸거나 닫기 전에 저장이 끝나길 기다리고 다시 저장해 봅니다. 그래도 안 되면 <span class="pjh-ui">버리고 넘어가기 / 계속 편집</span>을 묻습니다(작업 창을 직접 닫을 때와 같음).
|
||||
확인(읽음) 처리가 서버에 저장되지 않은 줄은 굵게 남아 있어 다시 누를 수 있습니다.
|
||||
다른 프로젝트에서 연결돼 와 읽기만 되는 작업의 알림은, 내가 볼 수 있는 연결된 프로젝트 화면으로 열립니다(웹 팝업·PC 알림도 같음).</li>
|
||||
<li><span class="pjh-ui">알림 모두 읽음</span>으로 한 번에 읽음 처리합니다. 읽지 않은 알림에서 우클릭 → <span class="pjh-ui">읽음으로 표시</span>도 됩니다.</li>
|
||||
</ul>
|
||||
<h3>어떤 알림이 누구에게 가나요?</h3>
|
||||
@@ -478,39 +513,39 @@
|
||||
<h3>전체 검색</h3>
|
||||
<ul>
|
||||
<li>왼쪽 사이드바 맨 위 검색창. 어느 화면에서든 <kbd>/</kbd> 키를 누르면 바로 검색창으로 갑니다.</li>
|
||||
<li><b>2글자 이상</b> 입력하면 내가 볼 수 있는 모든 프로젝트의 작업(하위 작업 포함)을 <b>제목 · 설명 · 댓글</b>에서 찾습니다.</li>
|
||||
<li><b>2글자 이상</b> 입력하면 내가 볼 수 있는 모든 프로젝트의 작업(세부 작업 포함)을 <b>제목 · 설명 · 댓글</b>에서 찾습니다.</li>
|
||||
<li>결과를 누르면 그 작업이 열립니다.</li>
|
||||
</ul>
|
||||
<h3>공유 링크</h3>
|
||||
<ul>
|
||||
<li>작업 편집 창의 <span class="pjh-ui">공유</span> 또는 우클릭 <span class="pjh-ui">작업 링크 복사</span>로 주소를 복사합니다.</li>
|
||||
<li>받은 사람이 주소를 열면(로그인 전이면 로그인 후) 그 작업이 바로 열립니다. 하위 작업 링크는 하위 작업 자체가 열립니다.</li>
|
||||
<li>현재 그 작업을 볼 수 있는 멤버·소유자·관리자가 열 수 있습니다. 연결된 프로젝트 멤버는 읽기 전용으로 보며, 멤버에서 제외되면 예전 링크로도 열 수 없습니다.</li>
|
||||
<li>받은 사람이 주소를 열면(로그인 전이면 로그인 후) 그 작업이 바로 열립니다. 세부 작업 링크는 세부 작업 자체가 열립니다.</li>
|
||||
<li>현재 그 작업을 볼 수 있는 멤버·소유자가 열 수 있습니다. 연결된 프로젝트 멤버는 읽기 전용으로 보며, 멤버에서 제외되면 예전 링크로도 열 수 없습니다.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- 19. 휴지통 -->
|
||||
<section class="pjh-sec" id="trash">
|
||||
<h2><span class="pjh-num">19</span>휴지통 (관리자)</h2>
|
||||
<h2><span class="pjh-num">19</span>휴지통 (Pro user 이상)</h2>
|
||||
<ul>
|
||||
<li>지운 작업은 바로 사라지지 않고 <b>3개월 동안</b> 휴지통에 보관됩니다. 하위 작업 · 댓글 · 협업자 · 첨부 파일도 함께 보관됩니다.</li>
|
||||
<li>관리자는 왼쪽 사이드바 <b>휴지통</b>에서 지운 작업 목록(프로젝트 · 삭제한 사람 · 삭제 시각)을 봅니다.</li>
|
||||
<li>지운 작업은 바로 사라지지 않고 <b>3개월 동안</b> 휴지통에 보관됩니다. 세부 작업 · 댓글 · 협업자 · 첨부 파일도 함께 보관됩니다.</li>
|
||||
<li>Pro user 이상은 왼쪽 사이드바 <b>휴지통</b>에서 지운 작업 목록(프로젝트 · 삭제한 사람 · 삭제 시각)을 봅니다. 자기가 멤버인 프로젝트의 작업만 보입니다.</li>
|
||||
<li><span class="pjh-ui">복구</span>를 누르면 원래 프로젝트 · 섹션 자리로 그대로 돌아옵니다. 복구된 줄의 <span class="pjh-ui">복구됨 · 열기</span>로 바로 열어 볼 수 있습니다.</li>
|
||||
<li>3개월이 지나면 영구 삭제됩니다.</li>
|
||||
</ul>
|
||||
<div class="pjh-note"><span class="material-symbols-outlined">info</span>
|
||||
<div>하위 작업만 따로 지웠는데 상위 작업도 지워진 상태라면, 상위 작업을 먼저 복구해야 합니다.</div></div>
|
||||
<div>세부 작업만 따로 지웠는데 상위 작업도 지워진 상태라면, 상위 작업을 먼저 복구해야 합니다.</div></div>
|
||||
</section>
|
||||
|
||||
<!-- 20. 연간 목표 -->
|
||||
<section class="pjh-sec" id="goals">
|
||||
<h2><span class="pjh-num">20</span>연간 목표</h2>
|
||||
<p class="pjh-lead">한 해의 매출 목표·실적과 업무 계획을 한 표에서 관리합니다. 숫자는 위쪽 지표에, 실행 계획은 아래쪽 업무 영역에 적습니다. 프로젝트 관리 권한이 있는 직원은 볼 수 있고, 입력·구조 변경은 관리자만 할 수 있습니다.</p>
|
||||
<p class="pjh-lead">한 해의 매출 목표·실적과 업무 계획을 한 표에서 관리합니다. 숫자는 위쪽 지표에, 실행 계획은 아래쪽 업무 영역에 적습니다. 프로젝트 관리 권한이 있는 직원은 볼 수 있고, 입력·구조 변경은 Pro user 이상만 할 수 있습니다.</p>
|
||||
|
||||
<h3 id="goals-start">목표 열기와 연도 만들기</h3>
|
||||
<ol class="pjh-steps">
|
||||
<li>왼쪽 사이드바 <span class="pjh-ui">목표</span>를 눌러 연도 목록을 펼친 뒤 원하는 연도를 누릅니다. 올해는 목표가 아직 없어도 목록에 보입니다.</li>
|
||||
<li>관리자는 빈 연도 화면에서 <span class="pjh-ui">해당 연도 목표 만들기</span>, 또는 사이드바의 <span class="pjh-ui">+ 연도 추가</span>로 새 표를 만듭니다.</li>
|
||||
<li>Pro user 이상은 빈 연도 화면에서 <span class="pjh-ui">해당 연도 목표 만들기</span>, 또는 사이드바의 <span class="pjh-ui">+ 연도 추가</span>로 새 표를 만듭니다.</li>
|
||||
<li>가장 가까운 이전 연도의 업무 영역·줄 구성을 가져옵니다. 이전 연도가 없으면 다음 연도의 구성을 사용하고, 처음이면 상품·마케팅·컨텐츠·유통으로 시작합니다. 이전 숫자와 계획 글은 복사하지 않습니다.</li>
|
||||
<li>위쪽 <span class="pjh-ui">매출 단위</span>를 확인한 뒤 월별 숫자와 계획을 입력합니다.</li>
|
||||
</ol>
|
||||
@@ -518,7 +553,8 @@
|
||||
<h3 id="goals-metrics">매출·로아스 입력과 달성률 계산</h3>
|
||||
<table class="pjh-table">
|
||||
<tr><th>칸</th><th>입력·계산 방법</th></tr>
|
||||
<tr><td>매출 목표·실적</td><td>관리자가 월별 숫자를 직접 입력합니다. 목표 표의 실적은 회의록의 자동 매출과 별도로 관리하므로 실적 모듈에서 자동으로 채워지지 않습니다.</td></tr>
|
||||
<tr><td>매출 목표</td><td>월 칸을 누르면 그 달 입력 창이 열립니다. 맨 위 <b>월 전체 목표</b>를 직접 넣고, 아래에 <b>주차별 목표</b>(매출 단위)를 넣은 뒤 <span class="pjh-ui">저장</span>합니다. 월 목표는 주차 합계와 따로 저장되고, 맨 아래에 <b>주차 합계</b>와 <b>차이(월 목표 − 주차 합계)</b>가 나옵니다 — +면 아직 주차에 못 나눈 금액, −면 주차 합계가 월 목표를 넘은 것입니다. 주차는 <a href="#meetings-week">주간 회의록 주차</a>와 같습니다.</td></tr>
|
||||
<tr><td>매출 실적</td><td>Pro user 이상이 월별 숫자를 직접 입력합니다. 목표 표의 실적은 회의록의 자동 매출과 별도로 관리하므로 실적 모듈에서 자동으로 채워지지 않습니다.</td></tr>
|
||||
<tr><td>매출 단위</td><td>예를 들어 단위가 <b>백만원</b>이면 30은 30,000,000원입니다. 단위를 바꿔도 이미 적은 숫자는 자동 환산되지 않으므로 숫자와 단위를 함께 확인하세요.</td></tr>
|
||||
<tr><td>연간·분기 매출</td><td>해당 기간에 입력한 월 숫자의 합계입니다. 합계 칸에 따로 입력하지 않습니다.</td></tr>
|
||||
<tr><td>달성</td><td>실적 ÷ 목표 × 100입니다. 월별로 계산하며, 연간·분기는 <b>기간 전체 목표 합계</b> 대비 입력된 실적 합계로 계산합니다. 목표가 없거나 0이면 달성률을 표시하지 않습니다. 100% 이상은 초록으로 표시됩니다.</td></tr>
|
||||
@@ -543,96 +579,116 @@
|
||||
|
||||
<h3 id="goals-table">분기 접기·열 너비·행 높이</h3>
|
||||
<ul>
|
||||
<li>열은 연간 → 1~3월 → 1분기 → 4~6월 → 2분기 → 7~9월 → 3분기 → 10~12월 → 4분기 순서입니다. <b>분기 머리 칸</b>을 누르면 해당 월 3개가 접힙니다. 네모 안 <b>−</b>는 접기, <b>+</b>는 펼치기입니다.</li>
|
||||
<li>열은 연간 → 1~3월 → 1분기 → 4~6월 → 2분기 → 7~9월 → 3분기 → 10~12월 → 4분기 순서입니다. <b>분기 머리 칸</b>을 누르면 해당 월 3개가 부드럽게 접히거나 펼쳐집니다. 숫자와 글은 펼침이 끝난 뒤 나타납니다. 네모 안 <b>−</b>는 접기, <b>+</b>는 펼치기입니다.</li>
|
||||
<li>어느 행에서든 셀의 <b>오른쪽 경계</b>를 끌어 열 너비를 조절합니다. 경계를 더블클릭하면 가장 긴 문단에 맞춥니다. 직접 넣은 줄바꿈·글자 크기·굵기도 반영합니다.</li>
|
||||
<li>셀 우클릭의 <span class="pjh-ui">현재 열 너비 자동 맞춤</span>·<span class="pjh-ui">전체 열 너비 자동 맞춤</span>도 사용할 수 있습니다. 전체 맞춤은 접힌 월 열까지 포함합니다. 병합 칸은 다른 열을 유지하며 오른쪽 끝 열 너비를 조절합니다.</li>
|
||||
<li>접힘·열 너비는 내 브라우저에 기억됩니다. 행 높이는 가장 높은 글 칸에 맞춰 늘고, 글이 줄면 함께 줄어듭니다. 글은 상단 정렬입니다.</li>
|
||||
<li>접힘·열 너비는 내 브라우저에 기억됩니다. 행 높이는 가장 높은 글 칸에 맞춰 늘고, 글이 줄면 함께 줄어듭니다. 1열(업무 영역)·2열(항목 이름)은 병합된 칸도 항상 세로 가운데 정렬이며, 목표 내용은 상단 정렬입니다.</li>
|
||||
<li>가로 스크롤에서는 구분·항목·연간 칸이, 세로 스크롤에서는 머리와 매출·로아스 지표가 고정됩니다.</li>
|
||||
<li><b>월 이름</b>을 누르면 그 달의 <a href="#meetings">주간 회의록</a>으로 이동합니다.</li>
|
||||
</ul>
|
||||
|
||||
<h3 id="goals-merge">셀 병합·병합 해제·내용 이동</h3>
|
||||
<h3 id="goals-merge">셀 병합·병합 해제</h3>
|
||||
<ol class="pjh-steps">
|
||||
<li>관리자는 업무 영역의 글 칸을 마우스로 끌어 여러 칸을 선택한 뒤 우클릭 → <span class="pjh-ui">셀 병합</span>을 누릅니다.</li>
|
||||
<li>Pro user 이상은 업무 영역의 글 칸을 마우스로 끌어 여러 칸을 선택한 뒤 우클릭 → <span class="pjh-ui">셀 병합</span>을 누릅니다.</li>
|
||||
<li>가로 병합은 <b>같은 분기의 월 칸끼리</b> 가능합니다. 연간·분기 칸은 세로로만 병합합니다. 선택한 칸들의 글은 순서대로 첫 칸에 모입니다.</li>
|
||||
<li>병합된 칸을 우클릭 → <span class="pjh-ui">병합 해제</span>하면 다시 나뉩니다. 글은 왼쪽 위 칸에 남습니다.</li>
|
||||
<li>글 칸 하나를 클릭한 뒤 <b>위·아래·왼쪽 테두리</b>를 잡아 다른 글 칸으로 끌면 내용과 글자 서식이 함께 이동합니다. 오른쪽 경계는 너비 조절용입니다. 대상에 글이 있으면 덮어쓰기를 확인하고, <kbd>Esc</kbd>로 이동을 취소합니다.</li>
|
||||
</ol>
|
||||
|
||||
<h3 id="goals-save">저장 실패와 연도 삭제</h3>
|
||||
<p>저장 성공 시 칸 테두리가 잠깐 초록으로 바뀝니다. 실패하면 빨간 테두리와 안내가 나오며 입력값은 유지됩니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 저장 안 된 값이 있으면 영역·줄 추가, 병합, 내용 이동을 진행하기 전에 저장을 시도하고, 실패하면 해당 작업을 멈춥니다.</p>
|
||||
<p>저장 성공 시 칸 테두리가 잠깐 초록으로 바뀝니다. 실패하면 빨간 테두리와 안내가 나오며 입력값은 유지됩니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 저장 안 된 값이 있으면 영역·줄 추가, 병합을 진행하기 전에 저장을 시도하고, 실패하면 해당 작업을 멈춥니다.</p>
|
||||
<p>저장되지 않은 초안은 내 브라우저에도 잠시 보관합니다. 다음에 같은 화면을 열면 복원하지만, 그 사이 다른 사람이 같은 칸을 바꿨으면 자동으로 덮어쓰지 않습니다. 저장 안 된 상태로 페이지를 떠나려 하면 브라우저가 확인합니다.</p>
|
||||
<p>관리자의 <span class="pjh-ui">연도 삭제</span>는 그 연도의 숫자·업무 영역·계획 글을 삭제합니다. 확인창에 연도를 직접 입력해야 진행되며 되돌릴 수 없습니다.</p>
|
||||
<p>Pro user 이상의 <span class="pjh-ui">연도 삭제</span>는 그 연도의 숫자·업무 영역·계획 글을 삭제합니다. 확인창에 연도를 직접 입력해야 진행되며 되돌릴 수 없습니다.</p>
|
||||
</section>
|
||||
|
||||
<!-- 21. 주간 회의록 -->
|
||||
<section class="pjh-sec" id="meetings">
|
||||
<h2><span class="pjh-num">21</span>주간 회의록</h2>
|
||||
<p class="pjh-lead">월 목표를 기준으로 지난주 결과를 리뷰하고 이번주 할 일과 금액 목표를 정하는 화면입니다. 연간 목표의 월 계획, 실적 모듈의 매출, 주별 결정 사항을 함께 확인합니다. 직원은 조회할 수 있고, 생성·입력·삭제는 관리자만 할 수 있습니다.</p>
|
||||
<p class="pjh-lead">월 목표를 기준으로 지난주 결과를 리뷰하고 이번주 주요 업무와 금액 목표를 정하는 화면입니다. 연간 목표의 월 계획, 실적 모듈의 매출, 주별 결정 사항을 함께 확인합니다. 프로젝트 관리 권한이 있는 직원은 <b>누구나 회의록을 만들고 고칠 수 있습니다</b>. Pro user 이상이 <span class="pjh-ui">회의 완료</span>를 누르면 그 회의록은 아무도 고칠 수 없게 잠기고(🔒 회의 완료 표시), Pro user 이상은 <span class="pjh-ui">완료 해제</span>로 다시 열 수 있습니다. 회의록 삭제도 Pro user 이상만 합니다.</p>
|
||||
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span><div>지난주 리뷰의 <b>결과</b>(글·금액)는 다음 주 회의에서 적는 값이라, 지난주 회의록이 완료돼 있어도 이번 주 회의록이 열려 있으면 적을 수 있습니다. 이번 주 회의록까지 완료하면 함께 잠깁니다. 다음 주차 회의록이 아직 없으면 그 주 회의록이 열려 있는 동안만 결과를 고칠 수 있습니다.</div></div>
|
||||
|
||||
<h3 id="meetings-week">회의록 열기와 주차 기준</h3>
|
||||
<p>왼쪽 연도 앞 화살표를 누르면 해당 연도의 하위 월 전체를 접거나 펼칠 수 있습니다. 연도 글자를 누르면 연간 목표를 엽니다. 연도와 월의 접기·펼치기 선택은 이 브라우저에 기억됩니다.</p>
|
||||
<ol class="pjh-steps">
|
||||
<li>왼쪽 <span class="pjh-ui">목표</span>에서 연도를 선택하고 표 머리의 <b>월 이름</b>을 누릅니다.</li>
|
||||
<li>위쪽 주차 탭 또는 오른쪽 작은 달력의 주 한 줄을 눌러 주를 고릅니다. 점은 회의록이 있는 주, <span class="pjh-ui">이번 주</span>는 현재 주입니다. 이전·다음 달 버튼으로 달을 바꿉니다.</li>
|
||||
<li>한 주는 <b>월요일~일요일</b>이고, 월요일이 속한 달의 회의록입니다. 1주차는 그 달 첫 월요일이 있는 주입니다. 예: 2026년 10월 1주차는 10/5~10/11이며, 9/28~10/4는 9월 회의록입니다.</li>
|
||||
<li>작은 달력의 흐린 앞 달 주를 누르면 그 달 회의록으로 갑니다. <span class="pjh-ui">해당 연도 목표</span> 버튼은 연간 목표 표로 돌아갑니다.</li>
|
||||
<li>이미 만든 회의록은 왼쪽 목표 연도 아래의 <b>월 폴더</b>에서도 열 수 있습니다. 폴더 아이콘과 월 이름을 눌러 접거나 펼치고, 주차·날짜 항목을 누르면 오른쪽 회의록만 바뀝니다. 왼쪽 메뉴와 스크롤 위치는 유지됩니다. 입력한 칸은 이동 전에 저장하며, 저장에 실패하면 현재 회의록을 유지합니다. 접기·펼치기는 이 브라우저에 기억됩니다.</li>
|
||||
<li>위쪽 주차 탭 또는 오른쪽 작은 달력의 한 줄을 눌러 주차를 고릅니다. 달력 줄을 누르면 그 줄의 이 달 날짜가 든 주차가 열립니다. 점은 회의록이 있는 주차, <span class="pjh-ui">이번 주</span>는 현재 주차입니다. 이전·다음 달 버튼으로 달을 바꿉니다.</li>
|
||||
<li>주차는 <b>그 달 안에서만</b> 나눕니다. 기본은 월요일~일요일입니다.
|
||||
<ul>
|
||||
<li>1일이 월~금요일이면 1일부터 그 주 일요일까지가 1주차입니다. 예: 2026년 10월 1주차는 10/1(목)~10/4.</li>
|
||||
<li>1일이 토·일요일이면 1일부터 다음 주 일요일까지가 1주차입니다. 예: 2026년 8월 1주차는 8/1(토)~8/9.</li>
|
||||
<li>말일이 월·화요일이면 그 하루·이틀은 앞 주차에 붙습니다. 예: 2026년 8월 마지막 주차는 8/24~8/31(월).</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li><span class="pjh-ui">해당 연도 목표</span> 버튼은 연간 목표 표로 돌아갑니다.</li>
|
||||
</ol>
|
||||
|
||||
<h3 id="meetings-create">회의록 만들기와 이어받는 항목</h3>
|
||||
<p>선택한 주에 회의록이 없으면 관리자에게 <span class="pjh-ui">해당 주차 회의록 만들기</span>가 보입니다. 화면을 열기만 해서는 회의록이 만들어지지 않습니다.</p>
|
||||
<p>선택한 주에 회의록이 없으면 <span class="pjh-ui">해당 주차 회의록 만들기</span>가 보입니다(누구나 만들 수 있습니다). 화면을 열기만 해서는 회의록이 만들어지지 않습니다.</p>
|
||||
<ul>
|
||||
<li>줄이 있는 가장 가까운 앞선 회의록에서 <b>구역·항목 이름·색·쇼핑몰 연결·순서</b>를 이어받습니다. 앞선 회의록이 없으면 가장 가까운 다음 회의록의 구성을 가져옵니다.</li>
|
||||
<li>줄이 있는 가장 가까운 앞선 회의록에서 <b>구역·항목 이름·색·순서</b>를 이어받습니다. 앞선 회의록이 없으면 가장 가까운 다음 회의록의 구성을 가져옵니다.</li>
|
||||
<li>어느 쪽에도 회의록이 없으면 해당 연도 목표 표의 업무 영역과 기본 양식으로 시작합니다.</li>
|
||||
<li>이번주 할 일·금액·메모는 새로 적습니다. 구성을 이어받는 것과 <b>지난주 리뷰</b>는 다릅니다. 리뷰에는 정확히 7일 전 주의 같은 항목만 표시됩니다.</li>
|
||||
<li>주요 업무·금액·메모는 새로 적습니다. 구성을 이어받는 것과 <b>지난주 리뷰</b>는 다릅니다. 리뷰에는 바로 앞 주차의 같은 항목만 표시됩니다.</li>
|
||||
</ul>
|
||||
|
||||
<h3 id="meetings-month-plan">이 달 계획 확인</h3>
|
||||
<p>제목 아래 <span class="pjh-ui">해당 월 계획</span>은 연간 목표 표에 적은 월 계획을 업무 영역별로 보여 줍니다. 빈 계획은 생략하고, 병합 칸은 해당 월을 포함하는 계획을 한 번 표시합니다. 여기서는 읽기만 하므로 수정하려면 연간 목표 표로 돌아갑니다.</p>
|
||||
<p>제목 아래 <span class="pjh-ui">해당 월 계획</span>은 연간 목표 표에 적은 월 계획을 업무 영역별로 보여 줍니다. 굵게·기울임·밑줄·글자 색상과 줄바꿈·들여쓰기를 유지하고, 글자 크기는 월 계획의 기본 크기로 표시합니다. 빈 계획은 생략하고, 병합 칸은 해당 월을 포함하는 계획을 한 번 표시합니다. 여기서는 읽기만 하므로 수정하려면 연간 목표 표로 돌아갑니다.</p>
|
||||
|
||||
<h3 id="meetings-kpis">월 목표·누적·주당 필요 매출 읽기</h3>
|
||||
<h3 id="meetings-kpis">위쪽 3칸 — 월 계획·숫자, 결정 사항, 작업 등록</h3>
|
||||
<p>제목 아래 세 칸은 표를 스크롤해도 그대로 보입니다. 왼쪽은 <b>월 계획</b>이고 그 머리 줄 오른쪽에 숫자 4개(월 목표 · 누적 목표 · 누적 실적 · 목표 대비)가 작게 한 줄로 나옵니다(목표 표 매출 단위, 예: 백만원 — 숫자에 마우스를 올리면 원 단위 금액과 뜻). 가운데는 <b>결정사항</b>(진행상황 수시 공유 및 완료 되어야 할 것), 오른쪽은 <b>작업 등록</b> 표입니다.</p>
|
||||
<ol class="pjh-steps">
|
||||
<li><b>작업 등록</b> — 제목 칸에 작업 이름을 씁니다. 담당자·프로젝트·섹션 칸을 누르면 고를 수 있는 목록이 나옵니다.</li>
|
||||
<li>프로젝트는 내가 멤버인 프로젝트만 나오고, 고르면 첫 섹션이 자동으로 들어갑니다. 담당자는 그 프로젝트의 멤버·소유자 중에서 고릅니다(프로젝트를 먼저 고르면 정확합니다).</li>
|
||||
<li>맨 오른쪽 <span class="pjh-ui">적용</span>을 누르면 그 프로젝트에 작업이 만들어지고, 줄에 <b>등록됨</b> 링크가 생깁니다. 줄은 이 브라우저에 남아 있어 새로고침해도 사라지지 않습니다. <span class="pjh-ui">+ 줄 추가</span>로 줄을 늘립니다.</li>
|
||||
<li>등록된 줄의 휴지통 아이콘을 누르면 확인 후 <b>그 프로젝트의 작업도 함께 삭제</b>됩니다(휴지통에 3개월 보관). 적용 전 줄의 <span class="pjh-ui">×</span>는 줄만 지웁니다. 작업 삭제는 만든 사람만 할 수 있습니다.</li>
|
||||
</ol>
|
||||
<table class="pjh-table">
|
||||
<tr><th>지표</th><th>뜻과 출처</th></tr>
|
||||
<tr><td>월 목표 매출·목표 ROAS</td><td>연간 목표 표의 해당 월 숫자입니다. 매출 단위가 원·천원·만원·십만원·백만원·천만원·억원이면 원으로 환산합니다. 모르는 단위는 원 환산을 못 하므로 주당 필요 매출도 계산하지 못합니다.</td></tr>
|
||||
<tr><td>월 누적 실적(지난주까지)</td><td>실적 모듈의 매출 집계 쇼핑몰 매출을 <b>그 달 1일부터 선택한 주의 직전 일요일까지</b> 합칩니다. 현재 날짜·월말을 넘기지 않습니다. 이번주 매출은 이 누적에 포함하지 않습니다.</td></tr>
|
||||
<tr><td>주당 필요</td><td>(월 목표 매출 − 월 누적 실적) ÷ <b>이번주를 포함한 그 달 남은 주 수</b>입니다. 원 단위 정수로 계산하고, 이미 월 목표를 달성했다면 0원입니다.</td></tr>
|
||||
<tr><td>전주 목표</td><td>정확히 7일 전 회의록에 적은 금주 목표입니다. 그 주 회의록이 없으면 비어 있습니다.</td></tr>
|
||||
<tr><td>전주 결과·달성률</td><td>실적 모듈의 전주 월~일 매출과 그 값 ÷ 전주 목표 × 100입니다. 전주 결과는 매출 자료이므로 전주 회의록이 없어도 조회될 수 있습니다. 목표가 없거나 0이면 달성률은 없습니다.</td></tr>
|
||||
<tr><td>금주 목표·현재 실적</td><td>금주 목표는 관리자가 정하는 원 단위 금액입니다. 현재 실적은 선택한 주 월요일부터 일요일 또는 오늘 중 이른 날까지의 매출입니다. 아직 시작하지 않은 미래 주의 실적은 비어 있습니다.</td></tr>
|
||||
<tr><td>월 목표 매출</td><td>연간 목표 표의 해당 월 매출 목표(= 주차별 목표 합계)입니다. 매출 단위가 원·천원·만원·십만원·백만원·천만원·억원이면 원으로 환산해 함께 보여 줍니다.</td></tr>
|
||||
<tr><td>월 누적 목표 매출</td><td>연간 목표 표에서 입력한 <b>주차별 목표의 1주차~선택한 주차 합계</b>(원)입니다. 주차별 목표가 없으면 비어 있고, 목표 표로 가는 안내가 나옵니다.</td></tr>
|
||||
<tr><td>월 누적 실적</td><td>실적 모듈의 매출 집계 쇼핑몰 매출을 <b>그 달 1일부터 오늘까지</b> 합칩니다. 지난 주차를 보면 그 주차 마지막 날까지입니다.</td></tr>
|
||||
<tr><td>누적 목표 대비 달성</td><td>월 누적 실적 − 월 누적 목표 매출 금액(넘으면 +, 모자라면 −)과 월 누적 실적 ÷ 월 누적 목표 매출 %입니다. 100% 이상은 초록입니다.</td></tr>
|
||||
</table>
|
||||
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span><div>월 목표가 1억원이고 지난주까지 누적이 4천만원, 남은 주가 이번주 포함 3주이면 주당 필요는 2천만원입니다. 이 숫자는 계획 참고값이며 금주 목표로 자동 저장되지는 않습니다.</div></div>
|
||||
<p>월 목표·누적은 달의 1일~말일 기준이고, 주간 결과는 월요일~일요일 기준입니다. 달을 넘는 마지막 주의 주간 결과에는 다음 달 날짜가 포함될 수 있습니다.</p>
|
||||
<div class="pjh-tip"><span class="material-symbols-outlined">lightbulb</span><div>주차별 목표가 1주차 2천만, 2주차 3천만이고 2주차까지의 실적이 4천5백만원이면 누적 목표 대비 달성은 −5,000,000원(90%)입니다.</div></div>
|
||||
|
||||
<h3 id="meetings-edit">이번주 할 일·정량 목표·참석자·메모 입력</h3>
|
||||
<h3 id="meetings-edit">주요 업무·정량 목표·참석자·메모 입력</h3>
|
||||
<ol class="pjh-steps">
|
||||
<li><b>금주 목표</b>에 전체 매출 목표를 적습니다. 줄별 <b>정량 목표</b>는 각 항목의 목표 금액이며, 현재는 원 단위입니다. 금주 목표와 줄별 목표 합계는 자동으로 맞춰지지 않습니다.</li>
|
||||
<li>각 항목의 <b>이번주 할 일 · 행사</b>에 실행할 일과 일정을 적습니다.</li>
|
||||
<li>줄별 <b>정량 목표</b>에 각 항목의 이번 주차 목표를 적습니다. 금액(원 단위)뿐 아니라 <code>20개</code>처럼 글도 됩니다. 전체 매출 목표는 연간 목표 표의 주차별 목표에서 정합니다.</li>
|
||||
<li>각 항목의 <b>주요 업무</b>에 실행할 일과 일정을 적습니다.</li>
|
||||
<li><span class="pjh-ui">참석자</span>를 눌러 프로젝트 관리 권한이 있는 등록 직원 중 선택합니다. 찾기·전원 선택·모두 해제를 사용할 수 있으며, 칩의 <span class="pjh-ui">×</span>로 참석자를 뺍니다.</li>
|
||||
<li>아래 <b>결정 사항 · 메모</b>에 회의 결론과 다음주까지 확인할 일을 적습니다.</li>
|
||||
<li>참석자 오른쪽 <span class="pjh-ui">회의록 보드</span>를 누르면 그 주차의 Google 슬라이드가 새 창으로 열립니다. 처음 누르면 회의록 보드 공유 드라이브에 빈 슬라이드(제목 틀 없음)를 <b>"10월 2주차 (10/5~10/11)"</b> 같은 이름으로 만들고, 다음부터는 같은 파일을 엽니다. 직원 누구나 열 수 있으며, 슬라이드 편집 권한은 공유 드라이브 권한을 따릅니다. 창이 안 뜨면 브라우저의 팝업 허용을 확인하세요.</li>
|
||||
<li>위쪽 가운데 <b>결정사항</b>에 회의 결론과 진행상황을 수시로 공유하고 완료되어야 할 일을 적습니다.</li>
|
||||
</ol>
|
||||
<p>금액은 <code>1,200,000</code>·<code>120만</code>·<code>1.5억</code>·<code>3천만</code>·<code>1억2천만</code>처럼 입력할 수 있습니다. <kbd>Enter</kbd> 또는 칸을 떠날 때 원 단위로 저장되고, 빈칸은 값을 지웁니다. 글·메모는 입력을 약 0.8초 멈추거나 칸을 떠날 때, 참석자·평가는 바꾸는 즉시 저장됩니다.</p>
|
||||
<p>금액은 <code>1,200,000</code>·<code>120만</code>·<code>1.5억</code>·<code>3천만</code>·<code>1억2천만</code>처럼 입력할 수 있습니다. <kbd>Enter</kbd> 또는 칸을 떠날 때 원 단위로 저장되고, 빈칸은 값을 지웁니다. 숫자로 읽히지 않는 값(예: <code>20개</code>)은 적은 글 그대로 저장됩니다. 글·메모는 입력을 약 0.8초 멈추거나 칸을 떠날 때, 참석자는 바꾸는 즉시 저장됩니다.</p>
|
||||
|
||||
<h3 id="meetings-review">지난주 리뷰·결과·평가</h3>
|
||||
<p>지난주 할 일과 목표는 <b>정확히 7일 전 주의 같은 항목</b>에서 가져옵니다. 이름 변경·순서 이동·회의록 생성 순서와 관계없이 이어진 같은 줄을 찾습니다. 그 주 회의록이 없으면 “회의록 없음”, 회의록은 있지만 항목이 없으면 “지난주 회의록에 없는 줄”로 표시합니다. 몇 주 전 기록을 지난주로 대신 보여 주지 않습니다.</p>
|
||||
<p>목표·주간 회의록 표에서 입력한 글·숫자·이름이 칸보다 길면 열 너비가 자동으로 늘어납니다. 글 셀에서는 <kbd>Enter</kbd>를 한 번 누르면 바로 다음 줄로 이동합니다. 지운 뒤 너비를 줄이려면 열 너비 자동 맞춤을 사용하세요.</p>
|
||||
<p>주요 업무 셀에서는 목표 표의 셀 편집 도구를 함께 사용할 수 있습니다.</p>
|
||||
<ul>
|
||||
<li><b>결과</b> — 쇼핑몰 연결 항목은 해당 쇼핑몰의 전주 매출이 자동 표시됩니다. 연결하지 않은 항목은 관리자가 결과 금액을 직접 입력합니다.</li>
|
||||
<li><b>달성률</b> — 결과 ÷ 지난주 정량 목표 × 100입니다. 목표가 없거나 0이면 계산하지 않으며, 100% 이상은 초록으로 표시됩니다.</li>
|
||||
<li><b>평가</b> — <span class="pjh-ui">— · 완료 · 일부 · 미달</span> 중 선택합니다. 달성률과 별개로 회의에서 판단해 정합니다.</li>
|
||||
<li><b>저장 위치</b> — 이번 화면에서 입력한 지난주 결과·평가는 <b>지난주 회의록의 줄</b>에 저장됩니다. 이번주 할 일·정량 목표는 이번주 회의록에 저장됩니다.</li>
|
||||
<li><b>글자 서식</b> — 글자 일부를 선택하고 위쪽 도구에서 색·크기·굵게·기울임·밑줄을 바꿉니다. 초기화 버튼은 선택한 글자의 서식을 지웁니다.</li>
|
||||
<li><b>열 너비</b> — 회의록을 열 때마다 <b>전체 열 너비 자동 맞춤</b>으로 시작합니다. 오른쪽 경계를 끌어 조절하고, 경계를 더블클릭하거나 우클릭 메뉴에서 현재 열·전체 열 너비를 내용에 맞춥니다. 직접 바꾼 너비는 그 화면에서만 유지되고 다시 열면 자동 맞춤으로 돌아갑니다.</li>
|
||||
<li><b>세로 정렬</b> — 1열(구역)·2열(항목)은 긴 행이나 병합된 구역도 항상 세로 가운데 정렬합니다. 할 일·리뷰 내용은 상단 정렬입니다.</li>
|
||||
<li><b>범위 선택·지우기</b> — 같은 구역의 이번주 글 셀을 드래그하거나 첫 셀을 누른 뒤 <kbd>Shift</kbd>+클릭으로 선택합니다. 우클릭의 내용 지우기 또는 <kbd>Delete</kbd>로 지우고, <kbd>Ctrl</kbd>+<kbd>Z</kbd>로 되돌립니다.</li>
|
||||
<li><b>내용 이동</b> — 셀 테두리를 다른 이번주 글 셀로 끌면 내용과 서식이 함께 이동합니다. 대상에 글이 있으면 덮어쓰기를 확인합니다. 이동 중에는 두 셀의 저장을 기다립니다.</li>
|
||||
<li><b>병합·해제</b> — 같은 구역의 글 셀을 여러 줄 선택하고 우클릭의 셀 병합을 누릅니다. 해제해도 합친 글은 첫 셀에 남습니다. 병합된 줄을 이동·삭제하거나 그 사이에 줄을 추가하려면 먼저 병합을 해제하세요.</li>
|
||||
</ul>
|
||||
|
||||
<h3 id="meetings-review">지난주 리뷰·결과·정량 목표</h3>
|
||||
<p>지난주 리뷰는 <b>바로 앞 주차의 같은 항목</b>에서 가져옵니다(앞 주차가 앞 달 마지막 주차일 수 있습니다). 이름 변경·순서 이동·회의록 생성 순서와 관계없이 이어진 같은 줄을 찾습니다. 그 주차 회의록이 없으면 “회의록 없음”, 회의록은 있지만 항목이 없으면 “지난주 회의록에 없는 줄”로 표시합니다. 몇 주 전 기록을 지난주로 대신 보여 주지 않습니다.</p>
|
||||
<ul>
|
||||
<li><b>전주 업무</b> — 지난 주차에 적은 주요 업무를 그대로 보여 줍니다(읽기 전용).</li>
|
||||
<li><b>결과</b>(글) — 지난 주차 업무를 어떻게 했는지 적습니다(누구나).</li>
|
||||
<li><b>전주 목표</b> — 지난 주차 회의록에서 그 줄에 적은 정량 목표입니다.</li>
|
||||
<li><b>결과</b>(오른쪽 끝) — 지난 주차 결과를 직접 입력합니다(누구나, 다음 주 회의록이 열려 있는 동안). 금액도, <code>18개</code> 같은 글도 됩니다(실적 모듈에서 자동 입력되지 않습니다).</li>
|
||||
<li><b>저장 위치</b> — 이번 화면에서 입력한 지난주 결과(글·금액)는 <b>지난 주차 회의록의 줄</b>에 저장됩니다. 주요 업무·정량 목표는 이번 주차 회의록에 저장됩니다.</li>
|
||||
<li><span class="pjh-ui">순서 바꾸기</span>는 이번주와 지난주 리뷰의 좌우 배치만 바꿉니다. 선택은 로그인한 사람별로 내 브라우저에 기억됩니다.</li>
|
||||
</ul>
|
||||
|
||||
<h3 id="meetings-markets">쇼핑몰 연결·자동 실적·매출 갱신</h3>
|
||||
<ol class="pjh-steps">
|
||||
<li>항목을 우클릭하거나 <span class="pjh-ui">⋯</span> → <span class="pjh-ui">쇼핑몰 연결(결과 자동)…</span>에서 실적 모듈의 사용 중인 쇼핑몰을 고릅니다. 자동 결과를 쓰지 않으려면 <span class="pjh-ui">연결 안 함</span>을 선택합니다.</li>
|
||||
<li>연결된 항목의 정량 목표 아래에 이번주 실적과 목표 대비 비율이 나옵니다. 지난주 리뷰의 자동 결과는 <b>지난주 항목의 쇼핑몰 연결</b>을 기준으로 계산합니다. 이번주 연결을 바꿔도 지난주 연결은 바뀌지 않습니다.</li>
|
||||
<li>유통 구역은 항목 이름으로 일부 쇼핑몰을 추측해 연결하므로 생성 후 연결 배지를 확인하세요. 마케팅의 “네이버” 같은 광고 항목은 자동 연결하지 않습니다.</li>
|
||||
</ol>
|
||||
<h3 id="meetings-markets">매출 갱신·실적 표시</h3>
|
||||
<p>실적 모듈 매출은 위쪽 숫자 칸(월 누적 실적·누적 목표 대비 달성)에만 쓰입니다. 줄(쿠팡·네이버 등)마다의 이번주 실적·지난주 결과는 자동으로 표시·입력되지 않으며, 지난주 결과는 직접 입력합니다.</p>
|
||||
<p>실적 갱신 권한이 있으면 주차를 열 때 지난주부터 선택한 주의 오늘까지 매출을 자동 갱신합니다. 같은 주의 자동 갱신은 브라우저에서 10분 간격으로 제한하며, 성공 시에는 별도 큰 안내 없이 숫자가 바뀝니다. 실패·일부 쇼핑몰 실패 시 작은 안내와 <span class="pjh-ui">다시 시도</span>가 나옵니다. 마지막 갱신 성공 시각은 실적 모듈 기록이며 숫자에 마우스를 올려 확인할 수 있습니다.</p>
|
||||
<table class="pjh-table">
|
||||
<tr><th>표시·상태</th><th>확인할 내용</th></tr>
|
||||
<tr><td>미확인</td><td>조회에 실패해 값을 알 수 없습니다. <b>0원과 다릅니다.</b> 이에 의존하는 달성률·주당 필요 매출도 계산하지 않습니다. 안내의 다시 시도를 사용하거나 실적 연결 상태를 확인하세요.</td></tr>
|
||||
<tr><td>미확인</td><td>조회에 실패해 값을 알 수 없습니다. <b>0원과 다릅니다.</b> 이에 의존하는 누적 목표 대비 달성도 계산하지 않습니다. 안내의 다시 시도를 사용하거나 실적 연결 상태를 확인하세요.</td></tr>
|
||||
<tr><td>0원</td><td>매출 조회는 성공했지만 해당 기간에 저장된 실적이 없거나 합계가 0원입니다. 필요하면 실적 화면에서 매출 자료를 갱신하세요.</td></tr>
|
||||
<tr><td>실적 미사용</td><td>연결 쇼핑몰이 사용 중이 아니거나 목록에 없습니다. 해당 항목의 결과는 직접 입력합니다.</td></tr>
|
||||
<tr><td>실적 미연결·집계 대상 없음</td><td>자동 실적·누적이 비어 있습니다. 회의록 계획·메모는 계속 입력할 수 있습니다.</td></tr>
|
||||
<tr><td>실적 갱신 권한 없음</td><td>새 매출을 요청하지 않고 저장된 실적을 보여 줍니다. 회의록 조회 권한과 매출 갱신 권한은 별개입니다.</td></tr>
|
||||
</table>
|
||||
@@ -641,13 +697,13 @@
|
||||
<ul>
|
||||
<li>구역 이름 옆 <span class="pjh-ui">+</span>는 그 구역 끝에 줄을 추가합니다. 표 아래 <span class="pjh-ui">+ 구역 추가</span>로 새 구역을 만듭니다.</li>
|
||||
<li>항목 이름을 클릭하면 그 자리에서 고칩니다. 우클릭 또는 ⋯ 메뉴에서 <span class="pjh-ui">위에 줄 추가 · 아래에 줄 추가 · 위로 · 아래로 · 줄 삭제</span>를 사용합니다. 순서 이동은 같은 구역 안에서 합니다.</li>
|
||||
<li>줄을 삭제하면 이번주 할 일·정량 목표도 함께 삭제됩니다. 새 줄은 지난주에 이어진 항목이 없으면 지난주 리뷰가 비어 있습니다.</li>
|
||||
<li>줄을 삭제하면 주요 업무·정량 목표도 함께 삭제됩니다. 새 줄은 지난주에 이어진 항목이 없으면 지난주 리뷰가 비어 있습니다.</li>
|
||||
</ul>
|
||||
|
||||
<h3 id="meetings-save">저장 확인·인쇄·회의록 삭제</h3>
|
||||
<p>저장 실패 시 칸이 빨갛게 표시되며 입력값은 남습니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 금주 목표를 저장하거나 자동 실적을 갱신해도 다른 칸의 작성 중인 글은 유지됩니다. 저장이 안 된 상태에서는 줄 추가·순서 이동·쇼핑몰 연결 같은 작업에 앞서 저장을 다시 시도합니다. 실패하면 구조 변경을 멈춥니다. 초안 복원과 페이지 떠남 보호는 <a href="#goals-save">목표의 저장 안내</a>와 같습니다.</p>
|
||||
<p>저장 실패 시 칸이 빨갛게 표시되며 입력값은 남습니다. 다시 입력하거나 칸을 떠나면 재시도합니다. 자동 실적을 갱신해도 다른 칸의 작성 중인 글은 유지됩니다. 저장이 안 된 상태에서는 줄 추가·순서 이동 같은 작업에 앞서 저장을 다시 시도합니다. 실패하면 구조 변경을 멈춥니다. 초안 복원과 페이지 떠남 보호는 <a href="#goals-save">목표의 저장 안내</a>와 같습니다.</p>
|
||||
<p><span class="pjh-ui">인쇄</span>는 브라우저 인쇄창을 엽니다. 인쇄용 화면에서는 사이드바·작은 달력·편집 도구를 숨깁니다. 브라우저의 PDF 저장도 사용할 수 있습니다.</p>
|
||||
<p>관리자의 <span class="pjh-ui">회의록 삭제</span>는 선택한 한 주의 회의록과 줄을 삭제합니다. 다음주 화면의 지난주 리뷰도 비게 됩니다. 같은 주를 다시 만들면 항목 구성은 이어질 수 있지만 삭제한 글과 금액은 복구되지 않습니다.</p>
|
||||
<p>Pro user 이상의 <span class="pjh-ui">회의록 삭제</span>는 선택한 한 주의 회의록과 줄을 삭제합니다. 다음주 화면의 지난주 리뷰도 비게 됩니다. 같은 주를 다시 만들면 항목 구성은 이어질 수 있지만 삭제한 글과 금액은 복구되지 않습니다.</p>
|
||||
</section>
|
||||
|
||||
<!-- 22. 단축키와 FAQ -->
|
||||
@@ -658,20 +714,20 @@
|
||||
<tr><th>키</th><th>하는 일</th></tr>
|
||||
<tr><td><kbd>/</kbd></td><td>작업 화면에서는 전체 검색창, 이 도움말에서는 도움말 검색창으로 이동(입력 중이 아닐 때)</td></tr>
|
||||
<tr><td><kbd>Esc</kbd></td><td>작업 편집 창 · 날짜 창 · 메뉴 닫기, 입력 취소</td></tr>
|
||||
<tr><td><kbd>Enter</kbd></td><td>하위 작업 추가, 섹션 이름 저장, 댓글 전송, 날짜 직접 입력 확정</td></tr>
|
||||
<tr><td><kbd>Enter</kbd></td><td>세부 작업 추가, 섹션 이름 저장, 댓글 전송, 날짜 직접 입력 확정</td></tr>
|
||||
<tr><td><kbd>Ctrl</kbd> + 휠</td><td>타임라인 확대·축소</td></tr>
|
||||
<tr><td>마우스 오른쪽 버튼</td><td>작업 · 하위 작업 · 섹션 · 프로젝트에서 바로가기 메뉴</td></tr>
|
||||
<tr><td>마우스 오른쪽 버튼</td><td>작업 · 세부 작업 · 섹션 · 프로젝트에서 바로가기 메뉴</td></tr>
|
||||
</table>
|
||||
<h3>자주 묻는 질문</h3>
|
||||
<p><b>Q. 프로젝트가 목록에 안 보여요.</b><br>그 프로젝트의 멤버가 아니면 보이지 않습니다. 관리자에게 멤버 배정을 부탁하세요.</p>
|
||||
<p><b>Q. 삭제 버튼을 눌렀는데 “삭제는 만든 사람만 할 수 있습니다”라고 나와요.</b><br>작업·섹션·프로젝트는 만든 사람만 지울 수 있습니다. 만든 사람이나 최고 관리자에게 부탁하세요.</p>
|
||||
<p><b>Q. 작업을 잘못 지웠어요.</b><br>3개월 안이라면 관리자가 휴지통에서 복구할 수 있습니다.</p>
|
||||
<p><b>Q. 프로젝트가 목록에 안 보여요.</b><br>그 프로젝트의 멤버가 아니면 보이지 않습니다. 그 프로젝트의 Pro user 이상 멤버나 관리자에게 멤버 배정을 부탁하세요.</p>
|
||||
<p><b>Q. 삭제 버튼을 눌렀는데 “삭제는 만든 사람만 할 수 있습니다”라고 나와요.</b><br>섹션·프로젝트는 만든 사람(또는 Admin 이상)만 지울 수 있습니다. 작업은 멤버 누구나 휴지통으로 지울 수 있습니다.</p>
|
||||
<p><b>Q. 작업을 잘못 지웠어요.</b><br>3개월 안이라면 Pro user 이상이 휴지통에서 복구할 수 있습니다.</p>
|
||||
<p><b>Q. 카드 순서를 끌어도 안 바뀌어요.</b><br>필터를 쓰고 있거나 정렬이 “기본”이 아니면 순서를 바꿀 수 없습니다. 필터 바의 <span class="pjh-ui">초기화</span>를 누른 뒤 다시 해 보세요.</p>
|
||||
<p><b>Q. 다른 사람이 바꾼 내용이 안 보여요.</b><br>보통 8초 안에 자동으로 반영됩니다. 오래 걸리면 새로고침(<kbd>F5</kbd>)하세요.</p>
|
||||
<p><b>Q. 하위 작업을 다른 프로젝트 작업으로 옮길 수 있나요?</b><br>하위 작업은 같은 프로젝트 안의 작업으로만 옮길 수 있습니다.</p>
|
||||
<p><b>Q. 세부 작업을 다른 프로젝트 작업으로 옮길 수 있나요?</b><br>세부 작업은 같은 프로젝트 안의 작업으로만 옮길 수 있습니다.</p>
|
||||
<p><b>Q. 작업을 두 프로젝트에 같이 두고 싶어요.</b><br>작업 편집 창의 “프로젝트” 칸에서 <span class="pjh-ui">다른 프로젝트에 추가</span>를 쓰세요. (<a href="#task">8장</a>)</p>
|
||||
<p><b>Q. 목표 표의 실적과 회의록 매출이 달라요.</b><br>목표 표의 월 실적은 직접 입력한 숫자이고, 회의록 매출은 실적 모듈 자료입니다. 매출 단위와 집계 기간도 확인하세요. (<a href="#goals-metrics">숫자 지표</a> · <a href="#meetings-kpis">회의록 지표</a>)</p>
|
||||
<p><b>Q. 지난주 회의록이 있는데 리뷰가 비어 있어요.</b><br>화면의 지난주 날짜와 항목을 확인하세요. 정확히 7일 전 회의록의 이어진 같은 항목만 표시합니다. 따로 추가한 줄은 이름이 같아도 다른 항목일 수 있습니다. (<a href="#meetings-review">지난주 리뷰</a>)</p>
|
||||
<p><b>Q. 지난주 회의록이 있는데 리뷰가 비어 있어요.</b><br>화면의 지난주 날짜와 항목을 확인하세요. 바로 앞 주차 회의록의 이어진 같은 항목만 표시합니다. 따로 추가한 줄은 이름이 같아도 다른 항목일 수 있습니다. (<a href="#meetings-review">지난주 리뷰</a>)</p>
|
||||
<p><b>Q. 도움말에서 필요한 설명을 빠르게 찾고 싶어요.</b><br>이 페이지 위쪽 검색창에 단어를 입력하고 결과를 누르세요. 제목·본문의 일치 단어가 강조되고 해당 소제목으로 이동합니다. <kbd>Enter</kbd>는 첫 결과로 이동, <kbd>Esc</kbd>나 <span class="pjh-ui">지우기</span>는 검색을 초기화합니다.</p>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -18,15 +18,18 @@
|
||||
<div class="pj-section-head">
|
||||
<h2>수신함</h2>
|
||||
<div style="display:flex; gap:8px;">
|
||||
{# PC 알림 프로그램(023) — 연결·내려받기 화면은 수신함 안에서 들어간다 #}
|
||||
<a class="pj-btn pj-inbox-notifier" href="/project/notifier" title="브라우저가 뒤에 있어도 PC 화면에 알림 띄우기">
|
||||
<span class="material-symbols-outlined">desktop_windows</span>PC 알림</a>
|
||||
<button type="button" class="pj-btn" id="pj-mentions-readall">태그 모두 확인</button>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-readall">알림 모두 읽음</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pj-view pj-inbox-pane">
|
||||
|
||||
<!-- 아사나 Inbox 처럼 "나를 태그(@)한 업무"를 맨 위에 리스트로 보여준다.
|
||||
"확인"을 누르면 수신함에 머문 채 오른쪽에 그 작업 창이 열린다
|
||||
(프로젝트 화면을 ?task=&embed=1 로 iframe 에 — project.js initInboxTaskPanel). -->
|
||||
<!-- 아사나 Inbox 처럼 "나를 태그(@)한 업무"를 맨 위에 리스트로 보여준다. 확인 안 한 태그·읽지 않은 알림만.
|
||||
줄을 누르면 수신함에 머문 채 오른쪽에 그 작업 창이 열리고(project.js initInboxTaskPanel),
|
||||
확인한 줄은 다른 줄을 고르거나 창을 닫으면 목록에서 빠진다. -->
|
||||
<div class="pj-inbox-section">
|
||||
<h3 class="pj-inbox-h3">
|
||||
나를 태그한 작업
|
||||
@@ -38,8 +41,9 @@
|
||||
{% else %}
|
||||
<ul class="pj-inbox pj-mention-list" id="pj-mention-tasks">
|
||||
{% for t in mentioned_tasks %}
|
||||
<li class="pj-inbox-item pj-mention-item {% if t.unread_mentions %}is-unread{% endif %}"
|
||||
data-task-id="{{ t.id }}" data-project="{{ t.project_id }}">
|
||||
<li class="pj-inbox-item pj-mention-item {% if t.unread_mentions %}is-unread{% endif %}" tabindex="0" role="button"
|
||||
data-task-id="{{ t.id }}" data-project="{{ t.project_id }}"
|
||||
data-href="/project/t/{{ t.id }}" title="누르면 오른쪽에 작업 창">
|
||||
<span class="material-symbols-outlined pj-inbox-icon">alternate_email</span>
|
||||
<div class="pj-inbox-body">
|
||||
<div class="pj-inbox-title {% if t.completed_at %}is-done{% endif %}">{{ t.title }}</div>
|
||||
@@ -50,8 +54,6 @@
|
||||
{% if t.mention_actor %} · {% set nm = t.mention_actor.split('@')[0] %}{{ nm[:1]|upper }}{{ nm[1:] }}님이 태그{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
<a class="pj-btn pj-inbox-go" href="/project/p/{{ t.project_id }}?task={{ t.id }}"
|
||||
data-task-id="{{ t.id }}">확인</a>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
@@ -65,9 +67,10 @@
|
||||
{% else %}
|
||||
<ul class="pj-inbox" id="pj-inbox">
|
||||
{% for n in notifications %}
|
||||
<li class="pj-inbox-item {% if not n.is_read %}is-unread{% endif %}"
|
||||
<li class="pj-inbox-item {% if not n.is_read %}is-unread{% endif %}" tabindex="0" role="button"
|
||||
data-id="{{ n.id }}"
|
||||
{% if n.task_id %}data-project="{{ n.project_id }}"{% endif %}>
|
||||
{% if n.task_id %}data-project="{{ n.project_id }}" data-task-id="{{ n.task_id }}"{% endif %}
|
||||
{% if n.task_id %}data-href="/project/t/{{ n.task_id }}"{% elif n.project_id %}data-href="/project/p/{{ n.project_id }}"{% endif %}>
|
||||
<span class="material-symbols-outlined pj-inbox-icon">
|
||||
{% if n.type == 'assigned' %}assignment_ind
|
||||
{% elif n.type == 'completed' %}task_alt
|
||||
@@ -85,12 +88,6 @@
|
||||
{% if n.actor_email %}{% set nm = n.actor_email.split('@')[0] %}{{ nm[:1]|upper }}{{ nm[1:] }} · {% endif %}{{ n.created_at[:16].replace('T',' ') }}
|
||||
</div>
|
||||
</div>
|
||||
{% if n.project_id %}
|
||||
{# 작업 알림은 "확인" → 수신함에 머문 채 오른쪽에 작업 창(project.js initInboxTaskPanel) #}
|
||||
<a class="pj-btn pj-inbox-go"
|
||||
href="/project/p/{{ n.project_id }}{% if n.task_id %}?task={{ n.task_id }}{% endif %}"
|
||||
{% if n.task_id %}data-task-id="{{ n.task_id }}"{% endif %}>확인</a>
|
||||
{% endif %}
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
@@ -104,5 +101,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
{% block content %}
|
||||
{# 프로젝트 모듈의 첫 화면 = 내 업무. 예전 프로젝트 홈(카드 그리드)은 없앴다. #}
|
||||
<div class="pj-wrap pj-mytasks-view" data-me="{{ user.email }}"
|
||||
data-is-admin="{{ 'true' if is_admin else 'false' }}"
|
||||
data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
|
||||
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}">
|
||||
<div class="pj-layout">
|
||||
{% with current_pid = 0, side_active = "mytasks" %}{% include "project/_side.html" %}{% endwith %}
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{# PC 알림 프로그램(023) — 트레이 프로그램(desktop/notifier) 내려받기, 연결 승인(?code=), 연결된 PC 해제.
|
||||
토큰은 프로그램이 받아 PC 에 암호화 저장(Windows DPAPI). 이 화면은 토큰 원문을 보지 않는다. #}
|
||||
<div class="pj-wrap pj-inbox-view pj-notifier-view">
|
||||
<div class="pj-layout">
|
||||
{% with current_pid = 0, side_active = "inbox" %}{% include "project/_side.html" %}{% endwith %}
|
||||
|
||||
<section class="pj-main">
|
||||
<div class="pj-section-head"><h2><a class="pj-notifier-back" href="/project/inbox">수신함</a> › PC 알림 프로그램</h2></div>
|
||||
<div class="pj-view pj-inbox-pane pj-notifier-pane">
|
||||
{% if not notifier_enabled %}
|
||||
<div class="pj-empty">PC 알림 연결이 아직 준비되지 않았습니다(DB 마이그레이션 023 필요).</div>
|
||||
{% else %}
|
||||
|
||||
{% if code %}
|
||||
<div class="pj-notifier-card is-link" id="pj-notifier-link" data-code="{{ code }}">
|
||||
{% if link and not link.approved_at %}
|
||||
<h3>이 PC 를 내 알림에 연결할까요?</h3>
|
||||
<p>PC 이름 <b>{{ link.device_name or '-' }}</b> · 연결 코드 <b class="pj-notifier-code">{{ link.code }}</b></p>
|
||||
<p class="pj-notifier-note">알림 프로그램 창에 보이는 코드와 같을 때만 연결하세요. 연결하면 그 PC 에
|
||||
<b>{{ user.name or user.email }}</b> 님의 태그·작업 배정 알림이 뜹니다.</p>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-notifier-approve">연결</button>
|
||||
{% elif link %}
|
||||
<h3>이미 연결을 승인했습니다</h3>
|
||||
<p class="pj-notifier-note">알림 프로그램이 곧 연결을 마칩니다. 이 창은 닫아도 됩니다.</p>
|
||||
{% else %}
|
||||
<h3>연결 코드가 없거나 만료되었습니다</h3>
|
||||
<p class="pj-notifier-note">연결 코드는 10분 동안만 쓸 수 있습니다. 알림 프로그램에서 [연결]을 다시 누르세요.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="pj-notifier-card">
|
||||
<h3>설치</h3>
|
||||
<ol class="pj-notifier-steps">
|
||||
<li>{% if download_ready %}<a class="pj-btn pj-btn-primary pj-btn-sm" href="/project/notifier/download">DBXNotifier.exe 내려받기</a>
|
||||
{% else %}관리자에게 <b>DBXNotifier.exe</b> 파일을 받으세요.{% endif %}
|
||||
설치 없이 파일 하나로 실행됩니다(Windows 10·11).</li>
|
||||
<li>실행하면 화면 오른쪽 아래 트레이에 종 아이콘이 생기고 연결 창이 열립니다. [브라우저에서 연결]을 누르세요.</li>
|
||||
<li>열린 이 화면에서 코드를 확인하고 [연결]을 누르면 끝입니다. 트레이 아이콘 메뉴에서 [Windows 시작 시 실행]을 켜 두세요.</li>
|
||||
</ol>
|
||||
<p class="pj-notifier-note">나를 태그하거나 작업이 배정되면 다른 프로그램을 쓰고 있어도 화면 아래 가운데에 큰 알림 창이 뜹니다.
|
||||
[열기]를 누르면 브라우저에서 그 작업이 열립니다.</p>
|
||||
</div>
|
||||
|
||||
<div class="pj-notifier-card">
|
||||
<h3>연결된 PC</h3>
|
||||
{% if devices %}
|
||||
<table class="pj-table pj-notifier-table">
|
||||
<thead><tr><th>PC 이름</th><th>연결한 때</th><th>마지막 확인</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for d in devices %}
|
||||
<tr>
|
||||
<td>{{ d.device_name or '-' }}</td>
|
||||
<td>{{ (d.created_at or '')[:16] | replace('T', ' ') }}</td>
|
||||
<td>{{ (d.last_seen_at or '-')[:16] | replace('T', ' ') }}</td>
|
||||
<td class="pj-trash-act"><button type="button" class="pj-btn pj-btn-sm pj-notifier-revoke"
|
||||
data-id="{{ d.id }}" data-name="{{ d.device_name }}">연결 해제</button></td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<p class="pj-notifier-note">연결된 PC 가 없습니다.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script>
|
||||
(function () {
|
||||
async function post(url, body) {
|
||||
const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body || {}) });
|
||||
const data = await res.json().catch(function () { return {}; });
|
||||
if (!res.ok) throw new Error(data.detail || ("HTTP " + res.status));
|
||||
return data;
|
||||
}
|
||||
const approve = document.getElementById("pj-notifier-approve");
|
||||
if (approve) approve.addEventListener("click", async function () {
|
||||
approve.disabled = true;
|
||||
try {
|
||||
await post("/project/api/notifier/link/approve", { code: document.getElementById("pj-notifier-link").dataset.code });
|
||||
location.replace("/project/notifier?code=" + encodeURIComponent(document.getElementById("pj-notifier-link").dataset.code));
|
||||
} catch (e) { approve.disabled = false; alert("연결 실패: " + e.message); }
|
||||
});
|
||||
document.querySelectorAll(".pj-notifier-revoke").forEach(function (b) {
|
||||
b.addEventListener("click", async function () {
|
||||
if (!confirm((b.dataset.name || "이 PC") + " 의 알림 연결을 해제할까요?")) return;
|
||||
b.disabled = true;
|
||||
try { await post("/project/api/notifier/devices/" + b.dataset.id + "/revoke"); location.reload(); }
|
||||
catch (e) { b.disabled = false; alert("해제 실패: " + e.message); }
|
||||
});
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<!-- 구글 머티리얼 심볼(담당자 아이콘 등) — 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-admin="{{ 'true' if is_admin else 'false' }}"
|
||||
data-is-pro="{{ 'true' if pj_pro else 'false' }}" data-is-padmin="{{ 'true' if pj_admin else 'false' }}"
|
||||
data-is-super="{{ 'true' if user.is_super_admin else 'false' }}"
|
||||
data-me="{{ user.email }}">
|
||||
|
||||
@@ -43,13 +43,13 @@
|
||||
<div class="pj-head-left">
|
||||
<!-- 프로젝트 제목 + 이 프로젝트의 멤버 아이콘.
|
||||
마우스를 올리면 이름(data-tip → initHoverTips), 클릭하면 그 사람이
|
||||
이 프로젝트에서 맡은 업무 팝업, 우클릭(관리자)하면 제외. 목록은
|
||||
이 프로젝트에서 맡은 업무 팝업, 우클릭(Pro user 이상)하면 제외. 목록은
|
||||
renderMemberList 가 같은 마크업으로 다시 그린다.
|
||||
"전체 프로젝트" 스코프에선 제목이 "전체 프로젝트"로 바뀌고 멤버는 숨긴다
|
||||
(.pj-title-wrap.is-all-scope). -->
|
||||
<div class="pj-title-wrap" id="pj-title-wrap">
|
||||
<h1 class="pj-project-title">
|
||||
<span class="pj-project-title-pill" style="--pj-color: {{ project.color or '#4573d2' }}"><span class="material-symbols-outlined pj-pill-ic">{{ project.icon or 'folder' }}</span><span class="pj-pill-name">{{ project.name }}</span></span>
|
||||
<span class="pj-project-title-pill" style="--pj-color: {{ project.color or '#4573d2' }}">{% set _pic = project.icon or 'folder' %}{% set _a = _pic.startswith('asana:') %}<span class="material-symbols-outlined pj-pill-ic{% if _a %} pj-ic-asana{% endif %}">{{ _pic[6:] if _a else _pic }}</span><span class="pj-pill-name">{{ project.name }}</span></span>
|
||||
</h1>
|
||||
<h1 class="pj-project-title pj-all-title">
|
||||
<span class="pj-project-title-all"><span class="material-symbols-outlined pj-pill-ic">apps</span><span class="pj-pill-name">전체 프로젝트</span></span>
|
||||
@@ -66,8 +66,8 @@
|
||||
</span>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% if is_admin %}
|
||||
<button type="button" class="pj-title-addmember" id="pj-add-member" title="멤버 배정">+</button>
|
||||
{% if pj_pro %}
|
||||
<button type="button" class="pj-title-addmember" id="pj-add-member" title="멤버 배정·제외">+</button>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div class="pj-view-tabs pj-view-tabs-line" id="pj-view-tabs">
|
||||
@@ -80,7 +80,8 @@
|
||||
</div>
|
||||
<!-- 아사나처럼 기본은 "이 프로젝트"만 보여준다. 전체 프로젝트 보기는
|
||||
예전처럼 접근 가능한 모든 프로젝트를 합쳐서 보여주는 모드. -->
|
||||
<div class="pj-view-tabs" id="pj-scope-toggle">
|
||||
{# 2026-10-08 — 토글은 숨기고 왼쪽 메뉴 "전체 보기"(Pro user 이상, ?scope=all)로 바꿈. 상태 보관용으로만 남김 #}
|
||||
<div class="pj-view-tabs" id="pj-scope-toggle" style="display:none">
|
||||
<button type="button" class="pj-tab is-active" data-scope="project">이 프로젝트</button>
|
||||
<button type="button" class="pj-tab" data-scope="all">전체 프로젝트</button>
|
||||
</div>
|
||||
@@ -213,9 +214,6 @@
|
||||
<h3 id="pj-stage-modal-title">새 섹션</h3>
|
||||
<input type="hidden" id="pj-stg-id" />
|
||||
<label>이름<input type="text" id="pj-stg-name" placeholder="섹션 이름" autocomplete="off" /></label>
|
||||
<label>색상
|
||||
<span class="pj-color-palette" id="pj-stg-colors"></span>
|
||||
</label>
|
||||
<div class="pj-field-label">기본 담당자
|
||||
<div class="pj-member-picker" id="pj-stg-assignee"></div>
|
||||
<span class="pj-modal-hint pj-stg-assignee-hint">이 섹션에 작업을 새로 만들거나 카드를 옮겨오면, 담당자가 비어 있는 작업만 이 사람에게 자동 배정됩니다.</span>
|
||||
@@ -259,7 +257,7 @@
|
||||
<!-- 아사나처럼 큰 제목은 이 무테 입력칸 하나뿐이다(위의 작은 안내줄은
|
||||
없앴다 — 버튼 줄 바로 아래 공간을 아낀다). -->
|
||||
<input type="hidden" id="pj-t-id" />
|
||||
<!-- 하위 업무를 열었을 때만 — 아사나처럼 제목 위에 상위 업무 경로. 누르면 상위 업무로. -->
|
||||
<!-- 세부 업무를 열었을 때만 — 아사나처럼 제목 위에 상위 업무 경로. 누르면 상위 업무로. -->
|
||||
<button type="button" class="pj-t-parent" id="pj-t-parent" hidden title="상위 작업 열기">
|
||||
<span class="material-symbols-outlined">subdirectory_arrow_left</span>
|
||||
<span class="pj-t-parent-title" id="pj-t-parent-title"></span>
|
||||
@@ -330,6 +328,18 @@
|
||||
</div>
|
||||
<button type="button" class="pj-follow-toggle" id="pj-follow-toggle">협업자로 참여</button>
|
||||
</div>
|
||||
<!-- 프로젝트 연결 — 협업자 아래에서 목록·선택·추가를 한 줄로 표시. -->
|
||||
<div class="pj-meta-row2 pj-projects-row" id="pj-links-block" hidden>
|
||||
<span class="pj-meta-cell-label pj-projects-label">
|
||||
<span class="material-symbols-outlined pj-gicon pj-gicon-sm" aria-hidden="true">link</span> 프로젝트
|
||||
</span>
|
||||
<div class="pj-link-chips" id="pj-link-chips"></div>
|
||||
<div class="pj-link-form" id="pj-link-form">
|
||||
<select id="pj-link-project" aria-label="연결할 프로젝트"><option value="">프로젝트 선택…</option></select>
|
||||
<select id="pj-link-stage" aria-label="연결할 섹션"><option value="">섹션 선택…</option></select>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-link-save">다른 프로젝트에 추가</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -346,6 +356,9 @@
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="italic" title="기울임 (Ctrl+I)"><span class="material-symbols-outlined">format_italic</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="underline" title="밑줄 (Ctrl+U)"><span class="material-symbols-outlined">format_underlined</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="strikeThrough" title="취소선 (Ctrl+Shift+X)"><span class="material-symbols-outlined">format_strikethrough</span></button>
|
||||
{# 글자 색·크기(2026-10-08) — 누르면 고르는 창(body 에 붙음). 저장 때 서버가 span 의 color·font-size 만 남긴다 #}
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="textColor" title="글자 색"><span class="material-symbols-outlined">format_color_text</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="textSize" title="글자 크기"><span class="material-symbols-outlined">format_size</span></button>
|
||||
<span class="pj-desc-fmtsep"></span>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertUnorderedList" title="글머리 기호 목록"><span class="material-symbols-outlined">format_list_bulleted</span></button>
|
||||
<button type="button" class="pj-desc-fmtbtn" data-cmd="insertOrderedList" title="번호 매기기 목록"><span class="material-symbols-outlined">format_list_numbered</span></button>
|
||||
@@ -362,46 +375,30 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 하위 업무 — 설명 바로 아래 줄에서 팝업 너비 전체를 쓴다.
|
||||
<!-- 세부 업무 — 설명 바로 아래 줄에서 팝업 너비 전체를 쓴다.
|
||||
기존 업무 편집 시에만. -->
|
||||
<div class="pj-task-extra pj-subtask-full" id="pj-subtask-block" hidden>
|
||||
<div class="pj-extra-head">
|
||||
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">checklist</span> 하위 작업
|
||||
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">checklist</span> 세부 작업
|
||||
</div>
|
||||
<ul class="pj-subtask-list" id="pj-subtask-list"></ul>
|
||||
<div class="pj-subtask-form">
|
||||
<input type="text" id="pj-subtask-input" placeholder="하위 작업 제목…" autocomplete="off" />
|
||||
<input type="text" id="pj-subtask-input" placeholder="세부 작업 제목…" autocomplete="off" />
|
||||
<select id="pj-subtask-add-assignee"><option value="">담당자 없음</option></select>
|
||||
<input type="date" id="pj-subtask-add-due" />
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-subtask-add">추가</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 첨부파일 | 연결된 프로젝트 — 나란히 2열(팝업 너비 전체를 나눠 쓴다).
|
||||
기존 업무 편집 시에만. -->
|
||||
<div class="pj-side-2col">
|
||||
<div class="pj-task-extra" id="pj-attach-block" hidden>
|
||||
<div class="pj-extra-head">
|
||||
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">attach_file</span> 첨부 파일
|
||||
<label class="pj-upload-btn">
|
||||
파일 추가<input type="file" id="pj-attach-input" hidden />
|
||||
</label>
|
||||
</div>
|
||||
<ul class="pj-attach-list" id="pj-attach-list"></ul>
|
||||
</div>
|
||||
|
||||
<!-- 연결된 프로젝트 — 멀티호밍(아사나식). -->
|
||||
<div class="pj-task-extra" id="pj-links-block" hidden>
|
||||
<div class="pj-extra-head">
|
||||
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">link</span> 프로젝트
|
||||
</div>
|
||||
<div class="pj-link-chips" id="pj-link-chips"></div>
|
||||
<div class="pj-link-form" id="pj-link-form">
|
||||
<select id="pj-link-project"><option value="">프로젝트 선택…</option></select>
|
||||
<select id="pj-link-stage"><option value="">섹션 선택…</option></select>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-link-save">다른 프로젝트에 추가</button>
|
||||
</div>
|
||||
<!-- 첨부파일 — 팝업 너비 전체, 기존 업무 편집 시에만. -->
|
||||
<div class="pj-task-extra" id="pj-attach-block" hidden>
|
||||
<div class="pj-extra-head">
|
||||
<span class="material-symbols-outlined pj-gicon pj-gicon-sm">attach_file</span> 첨부 파일
|
||||
<label class="pj-upload-btn">
|
||||
파일 추가<input type="file" id="pj-attach-input" hidden />
|
||||
</label>
|
||||
</div>
|
||||
<ul class="pj-attach-list" id="pj-attach-list"></ul>
|
||||
</div>
|
||||
|
||||
<!-- 댓글(활동) — 팝업 너비 전체를 쓰는 맨 아래 줄. 길어지면 자체
|
||||
@@ -428,25 +425,20 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if is_admin %}
|
||||
{% if pj_pro %}
|
||||
<!-- 멤버 배정 모달 — 등록된 사용자(프로젝트 권한 보유)를 자동 목록화 -->
|
||||
<div class="pj-modal" id="pj-modal-member" hidden>
|
||||
<div class="pj-modal-card">
|
||||
<h3>멤버 배정</h3>
|
||||
<p class="pj-modal-hint">관리자 페이지에서 <b>프로젝트 관리</b> 권한을 켠 직원이 후보로 나옵니다. 여러 명을 한 번에 선택할 수 있습니다.</p>
|
||||
<h3>멤버 배정 · 제외</h3>
|
||||
<p class="pj-modal-hint">체크하면 배정, 체크를 풀면 제외됩니다(지금 멤버는 체크된 채로 나옵니다). 후보는 관리자 페이지에서
|
||||
<b>프로젝트 관리</b> 권한을 켠 직원입니다. 배정된 멤버는 모두 이 프로젝트를 보고 수정할 수 있고, 소유자는 뺄 수 없습니다.</p>
|
||||
<div class="pj-field-label">직원
|
||||
<div class="pj-member-picker" id="pj-m-users">불러오는 중…</div>
|
||||
</div>
|
||||
<label>역할
|
||||
<select id="pj-m-role">
|
||||
<option value="member" selected>멤버</option>
|
||||
<option value="manager">관리(서브·작업 관리)</option>
|
||||
</select>
|
||||
</label>
|
||||
<div class="pj-modal-actions">
|
||||
<span style="flex:1"></span>
|
||||
<button type="button" class="pj-btn" data-close>취소</button>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-save-member">배정</button>
|
||||
<button type="button" class="pj-btn pj-btn-primary" id="pj-save-member">저장</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -496,5 +488,5 @@
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261003f" />
|
||||
<link rel="stylesheet" href="/static/project.css?v=20261012a" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
{% endblock %}
|
||||
|
||||
{% block topbar_after_logout %}{% include "project/_help_btn.html" %}{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{# 휴지통 — 관리자 전용. 지운 업무(하위 업무·댓글·팔로워·첨부 포함)를 3개월
|
||||
{# 휴지통 — Pro user 이상. 지운 업무(세부 업무·댓글·팔로워·첨부 포함)를 3개월
|
||||
보관하고, [복구] 로 원래 id 그대로 되살린다(project_db 010). #}
|
||||
<div class="pj-wrap pj-inbox-view pj-trash-view">
|
||||
<div class="pj-layout">
|
||||
@@ -17,7 +17,7 @@
|
||||
<section class="pj-main">
|
||||
<div class="pj-section-head">
|
||||
<h2>휴지통</h2>
|
||||
<span class="pj-trash-note">삭제한 작업은 3개월 동안 보관된 뒤 영구 삭제됩니다. 복구는 관리자만 할 수 있습니다.</span>
|
||||
<span class="pj-trash-note">삭제한 작업은 3개월 동안 보관된 뒤 영구 삭제됩니다. 복구는 Pro user 이상만 할 수 있습니다.</span>
|
||||
</div>
|
||||
<div class="pj-view pj-inbox-pane">
|
||||
{% if not trash_enabled %}
|
||||
@@ -45,7 +45,7 @@
|
||||
<td class="pj-trash-title">{{ it.title }}</td>
|
||||
<td>{{ it.project_name or '-' }}</td>
|
||||
<td class="pj-trash-meta">
|
||||
{% if it.task_count > 1 %}하위 작업 {{ it.task_count - 1 }}{% endif %}
|
||||
{% if it.task_count > 1 %}세부 작업 {{ it.task_count - 1 }}{% endif %}
|
||||
{% if it.comment_count %}{% if it.task_count > 1 %} · {% endif %}댓글 {{ it.comment_count }}{% endif %}
|
||||
{% if it.attachment_count %} · 첨부 파일 {{ it.attachment_count }}{% endif %}
|
||||
{% if it.task_count <= 1 and not it.comment_count and not it.attachment_count %}-{% endif %}
|
||||
@@ -70,5 +70,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261003h" defer></script>
|
||||
<script src="/static/project.js?v=20261012b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+1295
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,53 @@
|
||||
/* 목표 연도 아래 월 폴더와 주간 회의록 — 좁은 왼쪽 메뉴에서도 글자는 한 줄로 표시한다. */
|
||||
/* 기존 37px 들여쓰기를 2px로 줄여 연도 트리 전체를 왼쪽으로 35px 옮긴다. */
|
||||
.pj-side-goal-years { padding-left: 2px; }
|
||||
.pj-side-goal-branch { min-width: 0; }
|
||||
.pj-side-goal-year-row { display: flex; align-items: center; min-width: 0; }
|
||||
.pj-side-goal-year-row .pj-side-goal-year { flex: 1; min-width: 0; }
|
||||
/* 연도 이동 링크와 접기 버튼은 따로 눌러 사용할 수 있다. */
|
||||
.pj-side-goal-year-toggle { display: flex; align-items: center; justify-content: center; flex: none; width: 24px; height: 30px; padding: 0; border: 0; border-radius: 6px; background: transparent; color: var(--pj-ink-soft); cursor: pointer; }
|
||||
.pj-side-goal-year-toggle:hover { background: #f1f2f4; }
|
||||
.pj-side-goal-year-toggle:focus-visible { outline: 2px solid var(--pj-accent); outline-offset: -2px; }
|
||||
.pj-side-goal-year-toggle .material-symbols-outlined { font-size: 18px; }
|
||||
.pj-side-goal-year-toggle[aria-expanded="true"] .material-symbols-outlined { transform: rotate(90deg); }
|
||||
.pj-side-meeting-months { padding-left: 8px; }
|
||||
.pj-side-meeting-months[hidden] { display: none; }
|
||||
.pj-side-meeting-month { min-width: 0; }
|
||||
.pj-side-meeting-month > summary {
|
||||
display: flex; align-items: center; gap: 5px; padding: 5px 4px;
|
||||
border-radius: 6px; cursor: pointer; color: var(--pj-ink-soft); list-style: none;
|
||||
font-size: 13px; line-height: 20px;
|
||||
}
|
||||
.pj-side-meeting-month > summary::-webkit-details-marker { display: none; }
|
||||
.pj-side-meeting-month > summary:hover { background: #f1f2f4; }
|
||||
.pj-side-meeting-month > summary:focus-visible,
|
||||
.pj-side-meeting-week:focus-visible { outline: 2px solid var(--pj-accent); outline-offset: -2px; }
|
||||
.pj-side-meeting-caret { flex: none; font-size: 16px; }
|
||||
.pj-side-meeting-month[open] .pj-side-meeting-caret { transform: rotate(90deg); }
|
||||
.pj-side-meeting-folder { flex: none; font-size: 18px; color: var(--pj-accent); }
|
||||
.pj-side-meeting-folder-open { display: none; }
|
||||
.pj-side-meeting-month[open] .pj-side-meeting-folder-closed { display: none; }
|
||||
.pj-side-meeting-month[open] .pj-side-meeting-folder-open { display: inline-block; }
|
||||
.pj-side-meeting-weeks { margin: 0 0 4px 12px; padding-left: 8px; border-left: 1px solid var(--pj-border); }
|
||||
.pj-side-meeting-week {
|
||||
display: block; min-width: 0; padding: 5px 4px; border-radius: 6px;
|
||||
color: var(--pj-ink); text-decoration: none; font-size: 12px; line-height: 18px;
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
|
||||
}
|
||||
.pj-side-meeting-week:hover { background: #f1f2f4; }
|
||||
.pj-side-meeting-week.is-active { background: var(--pj-accent-tint); color: var(--pj-accent-dark); }
|
||||
.pj-side-meeting-retry { font: inherit; font-size: 12px; color: var(--pj-ink-soft); border: 0; background: transparent; cursor: pointer; padding: 5px 8px; }
|
||||
|
||||
/* 왼쪽 메뉴와 별개로 오른쪽 회의록 문서만 바뀌는 영역. */
|
||||
.pj-meeting-panel-host { position: relative; max-width: none !important; overflow: hidden; }
|
||||
.pj-meeting-panel-frame { display: block; width: 100%; height: 100%; min-height: 0; flex: 1; border: 0; background: #fff; }
|
||||
.pj-meeting-panel-frame.is-loading { position: absolute; inset: 0; visibility: hidden; }
|
||||
.pj-meeting-panel-status { position: absolute; top: 4px; right: 8px; z-index: 2; padding: 6px 10px; border-radius: 6px; background: #f4f5f7; color: var(--pj-ink-soft); font-size: 12px; }
|
||||
.pj-meeting-panel-status.is-error { color: #b42318; background: #fff1f0; }
|
||||
html.pj-meeting-content, html.pj-meeting-content body { height: 100%; overflow: hidden; }
|
||||
html.pj-meeting-content .erp-page { height: 100%; margin: 0; padding: 0; display: flex; box-sizing: border-box; }
|
||||
html.pj-meeting-content .pj-wrap { width: 100%; min-height: 0; display: flex; flex-direction: column; padding: 0; }
|
||||
html.pj-meeting-content .pj-layout { display: flex; flex-direction: column; height: 100%; min-height: 0; }
|
||||
@media (max-width: 800px) {
|
||||
.pj-meeting-panel-host { height: 80vh; min-height: 400px; }
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
/* 생성된 회의록만 읽어서 목표 연도 아래에 월별 폴더를 만든다. */
|
||||
(function () {
|
||||
"use strict";
|
||||
function init() {
|
||||
const branches = Array.from(document.querySelectorAll(".pj-side-goal-branch"));
|
||||
if (!branches.length) return;
|
||||
let loading = false, retry = null;
|
||||
const navigation = initMeetingNavigation();
|
||||
// 연도 접기는 월 폴더를 지우지 않고 숨겨서 각 월의 펼침 상태도 그대로 남긴다.
|
||||
branches.forEach(function (branch) {
|
||||
const button = branch.querySelector(".pj-side-goal-year-toggle");
|
||||
const list = branch.querySelector(".pj-side-meeting-months");
|
||||
if (!button || !list) return;
|
||||
const key = "pj_goal_year_open:" + branch.dataset.goalYear;
|
||||
function setOpen(open) {
|
||||
list.hidden = !open;
|
||||
button.setAttribute("aria-expanded", String(open));
|
||||
const action = open ? "하위 월 접기" : "하위 월 펼치기";
|
||||
button.setAttribute("aria-label", branch.dataset.goalYear + "년 " + action);
|
||||
button.title = action;
|
||||
}
|
||||
let saved = null;
|
||||
try { saved = localStorage.getItem(key); } catch (_) {}
|
||||
setOpen(saved !== "0");
|
||||
button.addEventListener("click", function () {
|
||||
const open = list.hidden;
|
||||
setOpen(open);
|
||||
try { localStorage.setItem(key, open ? "1" : "0"); } catch (_) {}
|
||||
});
|
||||
});
|
||||
|
||||
// 문자열을 HTML로 해석하지 않고 넣어 회의록 메뉴의 글자를 그대로 표시한다.
|
||||
function icon(name, cls) {
|
||||
const span = document.createElement("span");
|
||||
span.className = "material-symbols-outlined " + cls;
|
||||
span.setAttribute("aria-hidden", "true");
|
||||
span.textContent = name;
|
||||
return span;
|
||||
}
|
||||
function render(branch, months) {
|
||||
const list = branch.querySelector(".pj-side-meeting-months");
|
||||
const current = list.dataset.currentWeek;
|
||||
list.replaceChildren();
|
||||
months.forEach(function (month) {
|
||||
const folder = document.createElement("details");
|
||||
folder.className = "pj-side-meeting-month";
|
||||
const key = "pj_goal_month_open:" + branch.dataset.goalYear + ":" + month.month;
|
||||
let saved = null;
|
||||
try { saved = localStorage.getItem(key); } catch (_) {}
|
||||
folder.open = saved == null ? month.weeks.some(function (w) { return w.start === current; }) : saved === "1";
|
||||
const summary = document.createElement("summary");
|
||||
summary.append(icon("chevron_right", "pj-side-meeting-caret"),
|
||||
icon("folder", "pj-side-meeting-folder pj-side-meeting-folder-closed"),
|
||||
icon("folder_open", "pj-side-meeting-folder pj-side-meeting-folder-open"),
|
||||
document.createTextNode(month.month + "월"));
|
||||
summary.setAttribute("aria-label", month.month + "월 주간 회의록");
|
||||
folder.append(summary);
|
||||
const weeks = document.createElement("div");
|
||||
weeks.className = "pj-side-meeting-weeks";
|
||||
month.weeks.forEach(function (week) {
|
||||
const link = document.createElement("a");
|
||||
link.className = "pj-side-meeting-week";
|
||||
link.href = week.href;
|
||||
link.textContent = week.label;
|
||||
link.title = week.label;
|
||||
link.addEventListener("click", function (event) {
|
||||
// Ctrl/⌘ 클릭과 새 탭 열기는 일반 링크의 동작을 유지한다.
|
||||
if (event.defaultPrevented || event.button || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
|
||||
if (!navigation) return;
|
||||
event.preventDefault();
|
||||
navigation.open(link.href);
|
||||
});
|
||||
if (week.start === current) {
|
||||
link.classList.add("is-active");
|
||||
link.setAttribute("aria-current", "page");
|
||||
}
|
||||
weeks.append(link);
|
||||
});
|
||||
folder.append(weeks);
|
||||
list.append(folder);
|
||||
// 접기·펼치기 선택은 같은 브라우저에서 다음 화면에도 유지한다.
|
||||
folder.addEventListener("toggle", function () {
|
||||
try { localStorage.setItem(key, folder.open ? "1" : "0"); } catch (_) {}
|
||||
});
|
||||
});
|
||||
}
|
||||
async function load() {
|
||||
if (loading) return;
|
||||
loading = true;
|
||||
if (retry) retry.disabled = true;
|
||||
try {
|
||||
const response = await fetch("/project/api/goals/meeting-nav", { credentials: "same-origin" });
|
||||
if (!response.ok) throw new Error("회의록 조회 실패");
|
||||
const data = await response.json();
|
||||
branches.forEach(function (branch) {
|
||||
const year = (data.years || []).find(function (y) { return String(y.year) === branch.dataset.goalYear; });
|
||||
render(branch, year ? year.months : []);
|
||||
});
|
||||
if (navigation) navigation.markCurrent();
|
||||
if (retry) { retry.remove(); retry = null; }
|
||||
} catch (_) {
|
||||
// 목록 조회가 실패해도 기존 목표·프로젝트 메뉴는 계속 사용할 수 있다.
|
||||
if (!retry) {
|
||||
retry = document.createElement("button");
|
||||
retry.type = "button";
|
||||
retry.className = "pj-side-meeting-retry";
|
||||
retry.textContent = "회의록 목록 다시 불러오기";
|
||||
retry.addEventListener("click", load);
|
||||
branches[branches.length - 1].after(retry);
|
||||
}
|
||||
retry.disabled = false;
|
||||
} finally { loading = false; }
|
||||
}
|
||||
load();
|
||||
}
|
||||
|
||||
// 왼쪽 메뉴는 그대로 두고 오른쪽 문서만 교체한다. 회의록 편집 이벤트·타이머는 문서와 함께 정리된다.
|
||||
function initMeetingNavigation() {
|
||||
const layout = document.querySelector(".pj-layout");
|
||||
const original = layout && layout.querySelector(".pj-main");
|
||||
if (!original) return null;
|
||||
const root = layout.closest(".pj-wrap"), originalClasses = root.className;
|
||||
const originalUrl = location.pathname + location.search;
|
||||
const originalTitle = document.title;
|
||||
const originalYears = new Set(Array.from(document.querySelectorAll(".pj-side-goal-year.is-active")));
|
||||
let host = null, frame = null, pending = null, sequence = 0, current = originalUrl;
|
||||
|
||||
function meetingUrl(value) {
|
||||
const url = new URL(value, location.href);
|
||||
if (url.origin !== location.origin || !/^\/project\/goals\/\d{4}\/meetings\/\d{1,2}$/.test(url.pathname)) return null;
|
||||
url.searchParams.delete("content");
|
||||
return url;
|
||||
}
|
||||
function markCurrent() {
|
||||
const url = meetingUrl(current), week = url && url.searchParams.get("week");
|
||||
document.querySelectorAll(".pj-side-meeting-week").forEach(function (link) {
|
||||
const selected = url && link.pathname === url.pathname && new URL(link.href).searchParams.get("week") === week;
|
||||
link.classList.toggle("is-active", !!selected);
|
||||
if (selected) link.setAttribute("aria-current", "page"); else link.removeAttribute("aria-current");
|
||||
});
|
||||
document.querySelectorAll(".pj-side-goal-year").forEach(function (link) {
|
||||
link.classList.toggle("is-active", url ? url.pathname.startsWith(link.pathname + "/") : originalYears.has(link));
|
||||
});
|
||||
}
|
||||
function ensureHost() {
|
||||
if (host) return;
|
||||
host = document.createElement("section");
|
||||
host.className = "pj-main pj-meeting-panel-host";
|
||||
original.replaceWith(host);
|
||||
root.classList.add("pj-goal-view", "pj-inbox-view", "pj-meet-view");
|
||||
}
|
||||
function status(message, failed) {
|
||||
if (!host) return;
|
||||
let box = host.querySelector(".pj-meeting-panel-status");
|
||||
if (!box) { box = document.createElement("div"); box.className = "pj-meeting-panel-status"; box.setAttribute("role", "status"); host.append(box); }
|
||||
box.textContent = message;
|
||||
box.classList.toggle("is-error", !!failed);
|
||||
}
|
||||
function clearStatus() { const box = host && host.querySelector(".pj-meeting-panel-status"); if (box) box.remove(); }
|
||||
function syncFont() {
|
||||
if (!frame) return;
|
||||
const font = document.documentElement.dataset.pjFont || "system";
|
||||
if (frame.contentDocument.documentElement.dataset.pjFont !== font) {
|
||||
frame.contentDocument.documentElement.dataset.pjFont = font;
|
||||
frame.contentWindow.dispatchEvent(new frame.contentWindow.Event("resize"));
|
||||
}
|
||||
}
|
||||
async function saveCurrent() {
|
||||
const view = frame ? frame.contentWindow : window;
|
||||
if (view.PJFlushForNavigation) await view.PJFlushForNavigation();
|
||||
}
|
||||
async function open(value, options) {
|
||||
options = options || {};
|
||||
const url = meetingUrl(value);
|
||||
if (!url) return;
|
||||
const target = url.pathname + url.search;
|
||||
if (frame && target === current && !pending) return;
|
||||
const turn = ++sequence;
|
||||
try {
|
||||
if (!options.initial) await saveCurrent();
|
||||
if (turn !== sequence) return;
|
||||
ensureHost();
|
||||
if (pending) { pending.remove(); pending = null; }
|
||||
status("회의록을 불러오는 중…", false);
|
||||
const next = document.createElement("iframe");
|
||||
next.className = "pj-meeting-panel-frame is-loading";
|
||||
next.title = "주간 회의록";
|
||||
pending = next;
|
||||
next.addEventListener("load", function () {
|
||||
if (next !== frame && turn !== sequence) { next.remove(); return; }
|
||||
try {
|
||||
if (!next.contentDocument.documentElement.classList.contains("pj-meeting-content")) throw new Error("회의록을 불러오지 못했습니다. 주차를 다시 눌러 주세요.");
|
||||
const actual = meetingUrl(next.contentWindow.location.href);
|
||||
const pane = next.contentDocument.getElementById("pj-meet-pane");
|
||||
if (pane && pane.dataset.week) actual.searchParams.set("week", pane.dataset.week);
|
||||
// 줄 추가·삭제 등으로 현재 회의록 자체가 새로고침되어도 패널을 제거하지 않는다.
|
||||
if (next === frame) {
|
||||
if (!pending) {
|
||||
current = actual.pathname + actual.search;
|
||||
clearStatus(); markCurrent(); history.replaceState({ pjMeeting: true }, "", current);
|
||||
}
|
||||
syncFont(); return;
|
||||
}
|
||||
current = actual.pathname + actual.search;
|
||||
if (frame) frame.remove();
|
||||
frame = next; pending = null;
|
||||
next.classList.remove("is-loading");
|
||||
syncFont(); clearStatus(); markCurrent();
|
||||
document.title = next.contentDocument.title;
|
||||
if (options.history !== false) history[options.initial ? "replaceState" : "pushState"]({ pjMeeting: true }, "", current);
|
||||
} catch (error) {
|
||||
if (next !== frame) { next.remove(); if (pending === next) pending = null; }
|
||||
status(error.message, true);
|
||||
if (options.history === false) history.replaceState(null, "", current);
|
||||
}
|
||||
});
|
||||
url.searchParams.set("content", "1");
|
||||
next.src = url.href;
|
||||
host.append(next);
|
||||
} catch (error) {
|
||||
if (turn !== sequence) return;
|
||||
if (host) status("이동하지 못했습니다. " + error.message, true);
|
||||
else if (window.erpAlert) window.erpAlert(error.message);
|
||||
if (options.history === false) history.replaceState(null, "", current);
|
||||
}
|
||||
}
|
||||
window.addEventListener("message", function (event) {
|
||||
if (!frame || event.origin !== location.origin || event.source !== frame.contentWindow) return;
|
||||
if (event.data && event.data.type === "pj-meeting-navigate") open(event.data.href);
|
||||
});
|
||||
window.addEventListener("resize", syncFont);
|
||||
window.addEventListener("popstate", async function () {
|
||||
const url = location.pathname + location.search;
|
||||
if (meetingUrl(url)) { open(url, { history: false }); return; }
|
||||
if (url === originalUrl && host) {
|
||||
try {
|
||||
await saveCurrent(); sequence++;
|
||||
if (pending) pending.remove();
|
||||
if (frame) frame.remove();
|
||||
host.replaceWith(original); host = frame = pending = null;
|
||||
root.className = originalClasses; current = originalUrl; document.title = originalTitle; markCurrent();
|
||||
} catch (error) { status(error.message, true); history.replaceState(null, "", current); }
|
||||
}
|
||||
});
|
||||
// 첫 회의록도 편집 코드가 붙기 전에 오른쪽 전용 문서로 분리해 중복 초기화를 막는다.
|
||||
if (meetingUrl(originalUrl)) open(originalUrl, { initial: true });
|
||||
return { open: open, markCurrent: markCurrent };
|
||||
}
|
||||
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init);
|
||||
else init();
|
||||
})();
|
||||
@@ -30,6 +30,7 @@
|
||||
function walk(node, inherited) {
|
||||
if (node.nodeType === 3) { add(node.nodeValue, inherited); return; }
|
||||
if (node.nodeType !== 1) return;
|
||||
if (node.hasAttribute("data-pj-caret-line")) return;
|
||||
if (node.tagName === "BR") { add("\n", inherited); return; }
|
||||
if (/^(SCRIPT|STYLE|IMG|IFRAME)$/.test(node.tagName)) return;
|
||||
const style = styles(node, inherited);
|
||||
@@ -64,27 +65,58 @@
|
||||
editor.replaceChildren();
|
||||
runs.forEach(function (r) {
|
||||
if (typeof r.text !== "string") return;
|
||||
const span = document.createElement("span");
|
||||
span.textContent = r.text;
|
||||
if (typeof r.bold === "boolean") span.style.fontWeight = r.bold ? "700" : "400";
|
||||
if (typeof r.italic === "boolean") span.style.fontStyle = r.italic ? "italic" : "normal";
|
||||
if (typeof r.underline === "boolean") span.style.textDecoration = r.underline ? "underline" : "none";
|
||||
if (/^#[\da-f]{6}$/i.test(r.color || "")) span.style.color = r.color;
|
||||
if (Number.isInteger(r.size) && r.size >= 10 && r.size <= 32) span.style.fontSize = r.size + "px";
|
||||
editor.appendChild(span.style.cssText ? span : document.createTextNode(r.text));
|
||||
editor.appendChild(nodeForRun(r));
|
||||
});
|
||||
caretLine(editor);
|
||||
}
|
||||
function nodeForRun(r) {
|
||||
const span = document.createElement("span");
|
||||
r.text.split("\n").forEach(function (line, i) {
|
||||
if (i) span.appendChild(document.createElement("br"));
|
||||
if (line) span.appendChild(document.createTextNode(line));
|
||||
});
|
||||
if (typeof r.bold === "boolean") span.style.fontWeight = r.bold ? "700" : "400";
|
||||
if (typeof r.italic === "boolean") span.style.fontStyle = r.italic ? "italic" : "normal";
|
||||
if (typeof r.underline === "boolean") span.style.textDecoration = r.underline ? "underline" : "none";
|
||||
if (/^#[\da-f]{6}$/i.test(r.color || "")) span.style.color = r.color;
|
||||
if (Number.isInteger(r.size) && r.size >= 10 && r.size <= 32) span.style.fontSize = r.size + "px";
|
||||
if (!span.style.cssText && r.text.includes("\n")) span.style.lineHeight = "inherit";
|
||||
return span.style.cssText || r.text.includes("\n") ? span : document.createTextNode(r.text);
|
||||
}
|
||||
function caretLine(editor) {
|
||||
// 마지막 개행 뒤의 빈 줄도 화면에 만들되 저장할 글에는 넣지 않는다.
|
||||
const runs = readRuns(editor), last = runs[runs.length - 1];
|
||||
let marker = editor.querySelector("[data-pj-caret-line]");
|
||||
if (last && last.text.endsWith("\n")) {
|
||||
if (!marker) {
|
||||
marker = document.createElement("br"); marker.setAttribute("data-pj-caret-line", "");
|
||||
const holder = document.createElement("span"); holder.appendChild(marker); editor.appendChild(holder);
|
||||
}
|
||||
marker.parentElement.style.fontSize = last.size ? last.size + "px" : "";
|
||||
marker.parentElement.style.lineHeight = last.size ? "normal" : getComputedStyle(editor).lineHeight;
|
||||
} else if (marker) {
|
||||
const holder = marker.parentElement; marker.remove();
|
||||
if (holder !== editor && !holder.childNodes.length) holder.remove();
|
||||
}
|
||||
}
|
||||
function restore(editor, start, end) {
|
||||
const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT);
|
||||
const walker = document.createTreeWalker(editor, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
|
||||
const points = [], range = document.createRange();
|
||||
let node, offset = 0;
|
||||
while ((node = walker.nextNode())) {
|
||||
points.push({ node: node, start: offset, end: offset + node.length }); offset += node.length;
|
||||
const length = node.nodeType === 3 ? node.length : node.tagName === "BR" && !node.hasAttribute("data-pj-caret-line") ? 1 : 0;
|
||||
if (length) { points.push({ node: node, start: offset, end: offset + length }); offset += length; }
|
||||
}
|
||||
function point(n) { return points.find(function (p) { return n <= p.end; }) || points[points.length - 1]; }
|
||||
const a = point(start), b = point(end);
|
||||
if (!a || !b) { range.selectNodeContents(editor); range.collapse(false); }
|
||||
else { range.setStart(a.node, Math.max(0, start - a.start)); range.setEnd(b.node, Math.max(0, end - b.start)); }
|
||||
else {
|
||||
function pointAt(p, n) {
|
||||
return p.node.nodeType === 3 ? [p.node, Math.max(0, n - p.start)] :
|
||||
[p.node.parentNode, Array.from(p.node.parentNode.childNodes).indexOf(p.node) + (n > p.start ? 1 : 0)];
|
||||
}
|
||||
range.setStart(...pointAt(a, start)); range.setEnd(...pointAt(b, end));
|
||||
}
|
||||
const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
|
||||
return range;
|
||||
}
|
||||
@@ -98,16 +130,34 @@
|
||||
if (e.isComposing || e.keyCode === 229) return;
|
||||
if (e.key === "Enter") { e.preventDefault(); insert(editor, "\n"); }
|
||||
});
|
||||
editor.addEventListener("beforeinput", function (e) {
|
||||
if (!e.isComposing && (e.inputType === "insertParagraph" || e.inputType === "insertLineBreak")) {
|
||||
e.preventDefault(); insert(editor, "\n");
|
||||
}
|
||||
});
|
||||
editor.addEventListener("input", function (e) { if (!e.isComposing) caretLine(editor); });
|
||||
editor.addEventListener("compositionend", function () { caretLine(editor); });
|
||||
editor.addEventListener("paste", function (e) {
|
||||
e.preventDefault(); insert(editor, e.clipboardData.getData("text/plain"));
|
||||
});
|
||||
paint(editor, readRuns(editor));
|
||||
}
|
||||
function insert(editor, text) {
|
||||
if (!text) return;
|
||||
const sel = window.getSelection();
|
||||
if (!sel.rangeCount || !editor.contains(sel.getRangeAt(0).commonAncestorContainer)) return;
|
||||
const range = sel.getRangeAt(0); range.deleteContents();
|
||||
const node = document.createTextNode(text); range.insertNode(node);
|
||||
range.setStartAfter(node); range.collapse(true); sel.removeAllRanges(); sel.addRange(range);
|
||||
const range = sel.getRangeAt(0), pre = document.createRange();
|
||||
pre.selectNodeContents(editor); pre.setEnd(range.startContainer, range.startOffset);
|
||||
const offset = readRuns(pre.cloneContents()).reduce((n, r) => n + r.text.length, 0); let pos = 0, style = {};
|
||||
for (const run of readRuns(editor)) {
|
||||
pos += run.text.length;
|
||||
if (pos >= offset) { STYLE_KEYS.forEach(k => { if (run[k] !== undefined) style[k] = run[k]; }); break; }
|
||||
}
|
||||
range.deleteContents();
|
||||
const node = nodeForRun(Object.assign({ text: text }, style)); range.insertNode(node);
|
||||
const caret = node.nodeType === 3 ? node : node.lastChild;
|
||||
if (caret.nodeType === 3) range.setStart(caret, caret.length); else range.setStartAfter(caret);
|
||||
range.collapse(true); sel.removeAllRanges(); sel.addRange(range);
|
||||
editor.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
function init(table, toolbar) {
|
||||
@@ -157,7 +207,8 @@
|
||||
const editor = root.closest(".pj-goal-text[contenteditable='true']");
|
||||
if (!editor || !table.contains(editor) || !editor.contains(range.endContainer)) { clear(); return; }
|
||||
const pre = document.createRange(); pre.selectNodeContents(editor); pre.setEnd(range.startContainer, range.startOffset);
|
||||
saved = { editor: editor, start: pre.toString().length, end: pre.toString().length + range.toString().length };
|
||||
const start = readRuns(pre.cloneContents()).reduce((n, r) => n + r.text.length, 0);
|
||||
saved = { editor: editor, start: start, end: start + readRuns(range.cloneContents()).reduce((n, r) => n + r.text.length, 0) };
|
||||
toolbar.querySelectorAll("button, input, select").forEach(function (el) { el.disabled = false; });
|
||||
let pos = 0;
|
||||
const chosen = readRuns(editor).filter(function (run) {
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
/* 주간 회의록 셀 편집. 글자 서식은 목표와 같은 PJGoalText/자동 저장을 사용한다. */
|
||||
(function () {
|
||||
"use strict";
|
||||
function init(opts) {
|
||||
const table = opts.table, pane = opts.pane, admin = opts.admin;
|
||||
const KEY = "pj_meet_col_w", widths = {}, defaults = {};
|
||||
const cols = Array.from(table.querySelectorAll("colgroup col"));
|
||||
let saver = null, selected = [], anchor = null, rangeDrag = null, moveDrag = null;
|
||||
let busy = false, undo = null, suppressClick = 0;
|
||||
const editableCell = n => {
|
||||
const td = n && n.closest && n.closest("td[data-meet-item]");
|
||||
return td && table.contains(td) && td.querySelector(".pj-meet-text") ? td : null;
|
||||
};
|
||||
const editorOf = td => td.querySelector(".pj-meet-text");
|
||||
const keyOf = td => (td.dataset.meetCols || "").split(",").filter(Boolean).at(-1);
|
||||
const minWidth = key => key === "section" ? 48 : key === "label" ? 96 : 40;
|
||||
cols.forEach(function (col) {
|
||||
const key = col.dataset.meetCol;
|
||||
defaults[key] = Math.max(minWidth(key), Math.round(col.getBoundingClientRect().width / opts.zoom()) || 160);
|
||||
widths[key] = defaults[key];
|
||||
});
|
||||
try {
|
||||
const saved = JSON.parse(localStorage.getItem(KEY) || "{}");
|
||||
Object.keys(widths).forEach(k => { if (Number.isFinite(saved[k]) && saved[k] > 0) widths[k] = Math.max(minWidth(k), saved[k]); });
|
||||
} catch (_) {}
|
||||
function applyWidths() {
|
||||
cols.forEach(col => { col.style.width = widths[col.dataset.meetCol] + "px"; });
|
||||
table.style.width = cols.reduce((sum, col) => sum + widths[col.dataset.meetCol], 0) + "px";
|
||||
table.style.minWidth = table.style.width;
|
||||
}
|
||||
function saveWidths() {
|
||||
try { localStorage.setItem(KEY, JSON.stringify(widths)); } catch (_) {}
|
||||
}
|
||||
function handles() {
|
||||
const keys = Array.from(table.querySelectorAll("colgroup col")).map(col => col.dataset.meetCol), occupied = [];
|
||||
Array.from(table.rows).forEach(function (tr, r) {
|
||||
occupied[r] = occupied[r] || [];
|
||||
let c = 0;
|
||||
Array.from(tr.cells).forEach(function (td) {
|
||||
while (occupied[r][c]) c++;
|
||||
const end = c + td.colSpan - 1;
|
||||
for (let rr = r; rr < r + td.rowSpan; rr++) {
|
||||
occupied[rr] = occupied[rr] || [];
|
||||
for (let cc = c; cc <= end; cc++) occupied[rr][cc] = true;
|
||||
}
|
||||
td.dataset.meetCols = keys.slice(c, end + 1).join(",");
|
||||
const handle = td.querySelector(".pj-meet-colresize") || document.createElement("span");
|
||||
handle.className = "pj-meet-colresize"; handle.dataset.col = keys[end];
|
||||
handle.title = "끌어서 너비 조절 · 더블클릭하면 내용에 맞춤";
|
||||
if (!handle.parentNode) td.appendChild(handle);
|
||||
if (admin && editableCell(td)) ["top", "bottom", "left"].forEach(function (edge) {
|
||||
if (td.querySelector('.pj-goal-move-edge[data-edge="' + edge + '"]')) return;
|
||||
const h = document.createElement("span"); h.className = "pj-goal-move-edge"; h.dataset.edge = edge;
|
||||
h.title = "테두리를 끌어 내용과 서식 이동"; td.appendChild(h);
|
||||
});
|
||||
c = end + 1;
|
||||
});
|
||||
});
|
||||
}
|
||||
handles(); applyWidths();
|
||||
let widthTouched = false; // 사람이 너비를 바꾸면 늦은 자동 맞춤(글꼴 로딩 뒤)이 덮지 않게
|
||||
const orderButton = document.getElementById("pj-meet-order");
|
||||
if (orderButton) new MutationObserver(handles).observe(table, { attributes: true, attributeFilter: ["class"] });
|
||||
function measure(td) {
|
||||
const probe = document.createElement("div"), copy = td.cloneNode(true);
|
||||
const t = table.cloneNode(false), section = td.parentElement.parentElement.cloneNode(false), row = td.parentElement.cloneNode(false);
|
||||
probe.style.cssText = "position:fixed;visibility:hidden;pointer-events:none;width:max-content;left:0;top:0";
|
||||
probe.setAttribute("aria-hidden", "true");
|
||||
t.style.cssText = "width:max-content;table-layout:auto";
|
||||
copy.querySelectorAll(".pj-meet-colresize,.pj-goal-move-edge,.pj-meet-more,.pj-meet-sec-add").forEach(n => n.remove());
|
||||
copy.querySelectorAll("input,textarea,select").forEach(function (n) {
|
||||
const text = document.createElement("span"); text.textContent = n.value; n.replaceWith(text);
|
||||
});
|
||||
[t, section, row, copy].concat(Array.from(copy.querySelectorAll("*"))).forEach(function (n) {
|
||||
n.removeAttribute("id"); n.removeAttribute("contenteditable"); n.removeAttribute("data-placeholder");
|
||||
const styles = { position: "static", width: "max-content", "min-width": "0", "max-width": "none", height: "auto",
|
||||
overflow: "visible", "white-space": "pre", "overflow-wrap": "normal", "word-break": "normal" };
|
||||
Object.keys(styles).forEach(k => n.style.setProperty(k, styles[k], "important"));
|
||||
});
|
||||
copy.style.display = "block"; row.appendChild(copy); section.appendChild(row); t.appendChild(section); probe.appendChild(t); pane.appendChild(probe);
|
||||
try { return Math.ceil(copy.getBoundingClientRect().width / opts.zoom()) + 2; }
|
||||
finally { probe.remove(); }
|
||||
}
|
||||
function fit(key) {
|
||||
widthTouched = true;
|
||||
let width = minWidth(key);
|
||||
table.querySelectorAll("[data-meet-cols]").forEach(function (td) {
|
||||
const keys = td.dataset.meetCols.split(",");
|
||||
if (!keys.includes(key)) return;
|
||||
width = Math.max(width, measure(td) - keys.reduce((s, k) => s + (k === key ? 0 : widths[k]), 0));
|
||||
});
|
||||
widths[key] = width; applyWidths(); saveWidths();
|
||||
}
|
||||
function fitAll() {
|
||||
const cells = Array.from(table.querySelectorAll("[data-meet-cols]")).map(td => ({ keys: td.dataset.meetCols.split(","), width: measure(td) }));
|
||||
Object.keys(widths).forEach(k => { widths[k] = minWidth(k); });
|
||||
cells.filter(c => c.keys.length === 1).forEach(c => { widths[c.keys[0]] = Math.max(widths[c.keys[0]], c.width); });
|
||||
cells.filter(c => c.keys.length > 1).forEach(function (c) {
|
||||
const last = c.keys.at(-1), rest = c.keys.slice(0, -1).reduce((s, k) => s + widths[k], 0);
|
||||
widths[last] = Math.max(widths[last], c.width - rest);
|
||||
});
|
||||
applyWidths(); saveWidths();
|
||||
}
|
||||
// 회의록을 열 때는 늘 전체 열 너비 자동 맞춤으로 시작한다(2026-10-07 요청 — 예전 저장 너비보다 우선).
|
||||
// 글꼴이 늦게 로드되면 글자 폭이 바뀌므로, 그 사이 사람이 너비를 바꾸지 않았으면 한 번 더 맞춘다.
|
||||
fitAll();
|
||||
if (document.fonts && document.fonts.status !== "loaded") {
|
||||
document.fonts.ready.then(function () { if (!widthTouched && table.isConnected) fitAll(); });
|
||||
}
|
||||
function widthItems(td) {
|
||||
const key = keyOf(td);
|
||||
return key ? [
|
||||
{ label: "현재 열 너비 자동 맞춤", icon: opts.icon("fit_width"), onClick: () => fit(key) },
|
||||
{ label: "전체 열 너비 자동 맞춤", icon: opts.icon("width"), onClick: fitAll },
|
||||
] : [];
|
||||
}
|
||||
const growingCells = new Set();
|
||||
let growFrame = 0;
|
||||
function queueCellGrowth(e) {
|
||||
const field = e.target.closest("input, textarea, [contenteditable='true']");
|
||||
const td = field && field.closest("td, th");
|
||||
if (!admin || !td || !table.contains(td)) return;
|
||||
growingCells.add(td);
|
||||
if (growFrame) return;
|
||||
growFrame = requestAnimationFrame(function () {
|
||||
growFrame = 0; let changed = false;
|
||||
growingCells.forEach(function (cell) {
|
||||
if (!table.contains(cell)) return;
|
||||
const keys = (cell.dataset.meetCols || "").split(",").filter(Boolean), key = keys.at(-1);
|
||||
if (!key) return;
|
||||
const width = measure(cell) - keys.slice(0, -1).reduce((sum, k) => sum + widths[k], 0);
|
||||
if (width > widths[key]) { widths[key] = width; changed = true; }
|
||||
});
|
||||
growingCells.clear();
|
||||
if (changed) { applyWidths(); saveWidths(); }
|
||||
});
|
||||
}
|
||||
table.addEventListener("input", queueCellGrowth);
|
||||
table.addEventListener("compositionend", queueCellGrowth);
|
||||
table.addEventListener("dblclick", function (e) {
|
||||
const h = e.target.closest(".pj-meet-colresize");
|
||||
if (h) { e.preventDefault(); e.stopPropagation(); fit(h.dataset.col); }
|
||||
});
|
||||
table.addEventListener("mousedown", function (e) {
|
||||
const h = e.target.closest(".pj-meet-colresize");
|
||||
if (!h || e.button !== 0) return;
|
||||
e.preventDefault(); e.stopPropagation();
|
||||
const key = h.dataset.col, x = e.clientX, before = widths[key];
|
||||
widthTouched = true;
|
||||
function move(ev) { widths[key] = Math.max(minWidth(key), Math.min(600, before + (ev.clientX - x) / opts.zoom())); applyWidths(); }
|
||||
function stop() { document.removeEventListener("mousemove", move); document.removeEventListener("mouseup", stop); window.removeEventListener("blur", stop); saveWidths(); }
|
||||
document.addEventListener("mousemove", move); document.addEventListener("mouseup", stop); window.addEventListener("blur", stop);
|
||||
});
|
||||
function paintSelection() {
|
||||
table.querySelectorAll(".is-merge-sel,.is-goal-active").forEach(td => td.classList.remove("is-merge-sel", "is-goal-active"));
|
||||
selected.forEach(td => td.classList.add("is-merge-sel"));
|
||||
if (selected.length === 1) selected[0].classList.add("is-goal-active");
|
||||
}
|
||||
function select(a, b) {
|
||||
if (!a || !b || a.closest("tbody") !== b.closest("tbody")) return;
|
||||
const rows = Array.from(a.closest("tbody").rows);
|
||||
const cells = Array.from(a.closest("tbody").querySelectorAll("td[data-meet-item]"));
|
||||
let start = Math.min(rows.indexOf(a.parentElement), rows.indexOf(b.parentElement));
|
||||
let end = Math.max(rows.indexOf(a.parentElement) + a.rowSpan - 1, rows.indexOf(b.parentElement) + b.rowSpan - 1);
|
||||
cells.forEach(function (td) {
|
||||
const i = rows.indexOf(td.parentElement);
|
||||
if (i <= end && i + td.rowSpan - 1 >= start) { start = Math.min(start, i); end = Math.max(end, i + td.rowSpan - 1); }
|
||||
});
|
||||
selected = cells.filter(td => { const i = rows.indexOf(td.parentElement); return i <= end && i + td.rowSpan - 1 >= start; });
|
||||
paintSelection();
|
||||
}
|
||||
function clearSelection() { selected = []; paintSelection(); }
|
||||
async function locked(fields, work) {
|
||||
if (busy || !saver) return;
|
||||
busy = true;
|
||||
const attrs = fields.map(e => e.getAttribute("contenteditable"));
|
||||
fields.forEach(e => { e.setAttribute("contenteditable", "false"); e.closest("td").classList.add("is-goal-move-saving"); });
|
||||
try { await saver.flush(); return await work(); }
|
||||
catch (err) { opts.toast("셀 편집 실패: " + err.message + " — 입력 내용은 화면에 유지됩니다.", "error"); }
|
||||
finally {
|
||||
fields.forEach((e, i) => { e.setAttribute("contenteditable", attrs[i]); e.closest("td").classList.remove("is-goal-move-saving"); });
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
function moveCell(a, b) {
|
||||
if (a === b) return;
|
||||
const source = editorOf(a), target = editorOf(b);
|
||||
return locked([source, target], async function () {
|
||||
const sourceBody = source.value, targetBody = target.value;
|
||||
if (!sourceBody) return;
|
||||
if (targetBody && !await opts.confirm("대상 셀의 내용을 덮어쓸까요? 내용과 서식이 함께 이동합니다.", { okText: "덮어쓰기", cancelText: "취소" })) return;
|
||||
const result = await opts.api("POST", "/project/api/goals/meeting-cells/move", {
|
||||
source_item: a.dataset.meetItem, target_item: b.dataset.meetItem, source_body: sourceBody, target_body: targetBody,
|
||||
});
|
||||
saver.replace(source, ""); saver.replace(target, result.body); clearSelection(); select(b, b);
|
||||
opts.toast("내용과 서식을 이동했습니다.");
|
||||
});
|
||||
}
|
||||
function clearCells(cells) {
|
||||
const fields = cells.map(editorOf).filter(e => e && e.value);
|
||||
return locked(fields, async function () {
|
||||
undo = fields.map(e => [e, e.value]);
|
||||
fields.forEach(e => { e.value = ""; });
|
||||
await Promise.all(fields.map(e => saver.save(e)));
|
||||
opts.toast("내용을 지웠습니다 — Ctrl+Z로 되돌리기");
|
||||
});
|
||||
}
|
||||
function undoClear() {
|
||||
const previous = (undo || []).filter(([e]) => e.isConnected); undo = null;
|
||||
return locked(previous.map(([e]) => e), async function () {
|
||||
previous.forEach(([e, value]) => { e.value = value; });
|
||||
await Promise.all(previous.map(([e]) => saver.save(e)));
|
||||
});
|
||||
}
|
||||
function mergeCells(cells) {
|
||||
const all = Array.from(table.querySelectorAll(".pj-meet-text"));
|
||||
return locked(all, async function () {
|
||||
await opts.api("POST", "/project/api/goals/meeting-cells/merge", { item_from: cells[0].dataset.meetItem, item_to: cells.at(-1).dataset.meetItem });
|
||||
saver.reload();
|
||||
});
|
||||
}
|
||||
function unmergeCells(cells) {
|
||||
return locked(Array.from(table.querySelectorAll(".pj-meet-text")), async function () {
|
||||
for (const td of cells) await opts.api("DELETE", "/project/api/goals/meeting-items/" + td.dataset.meetItem + "/cell-merge");
|
||||
saver.reload();
|
||||
});
|
||||
}
|
||||
function cancelMove() {
|
||||
moveDrag = null;
|
||||
table.querySelectorAll(".is-goal-move-target").forEach(td => td.classList.remove("is-goal-move-target"));
|
||||
document.documentElement.classList.remove("pj-goal-moving");
|
||||
}
|
||||
if (admin) {
|
||||
table.addEventListener("mousedown", function (e) {
|
||||
if (e.defaultPrevented || e.button !== 0 || busy) return;
|
||||
const td = editableCell(e.target); if (!td) return;
|
||||
if (e.target.closest(".pj-goal-move-edge")) {
|
||||
e.preventDefault(); e.stopPropagation(); rangeDrag = null;
|
||||
moveDrag = { source: td, target: null }; document.documentElement.classList.add("pj-goal-moving"); return;
|
||||
}
|
||||
if (e.shiftKey && anchor && anchor !== td && anchor.closest("tbody") === td.closest("tbody")) {
|
||||
e.preventDefault(); select(anchor, td); if (document.activeElement) document.activeElement.blur(); return;
|
||||
}
|
||||
anchor = td; select(td, td); rangeDrag = { start: td };
|
||||
});
|
||||
table.addEventListener("mouseover", function (e) {
|
||||
if (!rangeDrag || moveDrag) return;
|
||||
const td = editableCell(e.target);
|
||||
if (!td || td === rangeDrag.start || td.closest("tbody") !== rangeDrag.start.closest("tbody")) return;
|
||||
document.documentElement.classList.add("pj-goal-selecting");
|
||||
if (document.activeElement) document.activeElement.blur();
|
||||
window.getSelection().removeAllRanges(); select(rangeDrag.start, td);
|
||||
});
|
||||
document.addEventListener("mousemove", function (e) {
|
||||
if (!moveDrag) return;
|
||||
const td = editableCell(document.elementFromPoint(e.clientX, e.clientY));
|
||||
table.querySelectorAll(".is-goal-move-target").forEach(c => c.classList.remove("is-goal-move-target"));
|
||||
moveDrag.target = td && td !== moveDrag.source ? td : null;
|
||||
if (moveDrag.target) moveDrag.target.classList.add("is-goal-move-target");
|
||||
});
|
||||
document.addEventListener("mouseup", function () {
|
||||
rangeDrag = null; document.documentElement.classList.remove("pj-goal-selecting");
|
||||
if (!moveDrag) return;
|
||||
const { source, target } = moveDrag; cancelMove(); suppressClick = Date.now() + 300;
|
||||
if (target) moveCell(source, target);
|
||||
});
|
||||
table.addEventListener("click", function (e) { if (busy || (Date.now() < suppressClick && editableCell(e.target))) { e.preventDefault(); e.stopImmediatePropagation(); } }, true);
|
||||
document.addEventListener("keydown", function (e) {
|
||||
if (e.key === "Escape") { cancelMove(); rangeDrag = null; clearSelection(); document.documentElement.classList.remove("pj-goal-selecting"); }
|
||||
const active = document.activeElement;
|
||||
if (busy || (active && (active.isContentEditable || active.matches("textarea,input,select")))) return;
|
||||
if (e.key === "Delete" && selected.length) { e.preventDefault(); clearCells(selected.slice()); }
|
||||
else if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key.toLowerCase() === "z" && undo) { e.preventDefault(); undoClear(); }
|
||||
});
|
||||
window.addEventListener("blur", function () { cancelMove(); rangeDrag = null; document.documentElement.classList.remove("pj-goal-selecting"); });
|
||||
document.addEventListener("mousedown", function (e) { if (!editableCell(e.target) && !e.target.closest(".pj-ctxmenu,.pj-goal-format")) clearSelection(); }, true);
|
||||
}
|
||||
table.addEventListener("contextmenu", function (e) {
|
||||
if (busy) { e.preventDefault(); e.stopImmediatePropagation(); return; }
|
||||
const td = e.target.closest("td,th"); if (!td || !table.contains(td)) return;
|
||||
if (admin && td.matches("th.pj-meet-c-label")) return; // 기존 줄 메뉴에 너비 항목을 붙인다.
|
||||
const cell = admin && editableCell(td), items = [];
|
||||
if (cell) {
|
||||
if (!selected.includes(cell)) select(cell, cell);
|
||||
const cells = selected.slice(), merged = cells.filter(c => c.rowSpan > 1);
|
||||
if (table.dataset.cellMerges === "true" && cells.length > 1) items.push({ label: "셀 병합 (세로)", icon: opts.icon("cell_merge"), onClick: () => mergeCells(cells) });
|
||||
if (merged.length) items.push({ label: "병합 해제", icon: opts.icon("call_split"), onClick: () => unmergeCells(merged) });
|
||||
if (cells.some(c => editorOf(c).value)) items.push({ label: "내용 지우기 (Del)", icon: opts.icon("ink_eraser"), onClick: () => clearCells(cells) });
|
||||
if (saver) {
|
||||
items.push(null,
|
||||
{ label: "위에 줄 추가", icon: opts.icon("add_row_above"), onClick: () => saver.addRow(cell.closest("tbody").dataset.section, cell.dataset.meetItem, "above") },
|
||||
{ label: "아래에 줄 추가", icon: opts.icon("add_row_below"), onClick: () => {
|
||||
const rows = Array.from(cell.closest("tbody").rows), bottom = rows[rows.indexOf(cell.parentElement) + cell.rowSpan - 1];
|
||||
saver.addRow(cell.closest("tbody").dataset.section, bottom.dataset.item, "below");
|
||||
} });
|
||||
}
|
||||
}
|
||||
if (items.length) items.push(null);
|
||||
items.push(...widthItems(td));
|
||||
if (items.length) { e.preventDefault(); opts.menu(e.clientX, e.clientY, items); }
|
||||
});
|
||||
return { bindSaver: s => { saver = s; }, widthItems: widthItems };
|
||||
}
|
||||
window.PJMeetingCells = { init: init };
|
||||
})();
|
||||
@@ -0,0 +1,19 @@
|
||||
/* 오른쪽 회의록 안의 주차·달 이동도 왼쪽 메뉴를 유지하도록 부모 화면에 전달한다. */
|
||||
(function () {
|
||||
"use strict";
|
||||
if (window.parent === window) return;
|
||||
document.addEventListener("click", function (event) {
|
||||
const link = event.target.closest("a[href]");
|
||||
if (!link || event.defaultPrevented || event.button || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
|
||||
const url = new URL(link.href, location.href);
|
||||
if (url.origin !== location.origin) return;
|
||||
if (/^\/project\/goals\/\d{4}\/meetings\/\d{1,2}$/.test(url.pathname)) {
|
||||
event.preventDefault();
|
||||
url.searchParams.delete("content");
|
||||
window.parent.postMessage({ type: "pj-meeting-navigate", href: url.href }, location.origin);
|
||||
} else if (/^\/project\/goals\/\d{4}$/.test(url.pathname)) {
|
||||
// 연간 목표로 돌아갈 때는 중첩 메뉴가 생기지 않도록 바깥 화면에서 연다.
|
||||
link.target = "_top";
|
||||
}
|
||||
});
|
||||
})();
|
||||
+363
-76
@@ -315,7 +315,8 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
|
||||
border-bottom: 1px solid #e2e4ea;
|
||||
}
|
||||
/* 세션 제목 — 아사나 보드의 16px/20px, 굵기 500 */
|
||||
.pj-col-name { font-size: var(--pj-section-size); font-weight: 500; line-height: var(--pj-section-leading); }
|
||||
/* 섹션 이름은 굵게(2026-10-08) */
|
||||
.pj-col-name { font-size: var(--pj-section-size); font-weight: 700; line-height: var(--pj-section-leading); }
|
||||
/* 세션 기본 담당자 아이콘 — 이름 옆에 작게 */
|
||||
.pj-col-assignee { display: inline-flex; align-items: center; flex: 0 0 auto; }
|
||||
.pj-col-assignee .pj-avatar { width: 20px; height: 20px; box-shadow: 0 0 0 1.5px #fff; }
|
||||
@@ -331,7 +332,7 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
|
||||
.pj-col-name.pj-col-name-editable:hover { background: rgba(0,0,0,.06); }
|
||||
.pj-col-head-colored .pj-col-name.pj-col-name-editable:hover { background: rgba(255,255,255,.22); }
|
||||
.pj-col-name-input {
|
||||
font: inherit; font-size: var(--pj-section-size); font-weight: 500; color: var(--pj-ink);
|
||||
font: inherit; font-size: var(--pj-section-size); font-weight: 700; color: var(--pj-ink);
|
||||
min-width: 0; flex: 1 1 auto; max-width: 70%; padding: 2px 6px;
|
||||
border: 1px solid var(--pj-accent); border-radius: 6px; background: #fff; outline: none; line-height: var(--pj-section-leading);
|
||||
}
|
||||
@@ -499,6 +500,7 @@ html.pj-side-resizing, html.pj-side-resizing * { cursor: col-resize !important;
|
||||
border-bottom: 1px solid var(--pj-border) !important; white-space: nowrap; line-height: var(--pj-section-leading);
|
||||
}
|
||||
.pj-list-group-caret { font-size: 18px; color: var(--pj-ink-soft); }
|
||||
.pj-list-group-name { font-weight: 700; }
|
||||
.pj-list-group-count {
|
||||
color: var(--pj-ink-soft); font-weight: 700; font-size: 11px; background: #eef0f2;
|
||||
border-radius: 999px; min-width: 20px; height: 20px; padding: 0 6px;
|
||||
@@ -731,16 +733,14 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
||||
margin: 0 -22px 0 -8px; padding: 0 22px 0 8px;
|
||||
}
|
||||
.pj-task-modal-card .pj-modal-actions { flex: none; }
|
||||
/* 위에서 아래로 쭉 쌓는 단일 칼럼 — 메타 → 설명 → 하위업무 →
|
||||
(첨부파일|연결된 프로젝트 2열) → 댓글(팝업 너비 전체) 순서. 각 구간은
|
||||
/* 위에서 아래로 쭉 쌓는 단일 칼럼 — 메타(프로젝트 연결 포함) → 설명 → 하위업무 →
|
||||
첨부파일 → 댓글(팝업 너비 전체) 순서. 각 구간은
|
||||
.pj-task-extra 의 위쪽 구분선으로 나뉘고, 넘치는 부분은 이 전체가 세로로
|
||||
스크롤한다. */
|
||||
.pj-modal-body { display: flex; flex-direction: column; overflow-y: auto; }
|
||||
.pj-desc-block { min-width: 0; padding-top: 10px; margin-top: 14px; border-top: 1px solid #eef0f2; }
|
||||
.pj-subtask-full { min-width: 0; }
|
||||
/* 첨부파일 | 연결된 프로젝트 — 나란히 2열. */
|
||||
.pj-side-2col { display: grid; grid-template-columns: 1fr 1fr; gap: 0 24px; }
|
||||
.pj-side-2col .pj-task-extra { min-width: 0; }
|
||||
#pj-attach-block { min-width: 0; }
|
||||
/* 댓글 — 팝업 너비 전체, 목록 자체는 더 이상 안에서 스크롤하지 않고
|
||||
팝업 전체(.pj-modal-body)와 같이 늘어난다. */
|
||||
.pj-comment-full .pj-comment-list { max-height: none; overflow-y: visible; }
|
||||
@@ -763,7 +763,6 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
||||
.pj-comment-dock .pj-comment-form textarea { border: none !important; box-shadow: none !important; padding: 8px 8px; font-size: 14px; outline: none; background: transparent; }
|
||||
@media (max-width: 720px) {
|
||||
.pj-task-modal-card { width: 100vw; max-width: 100vw; min-width: 0; }
|
||||
.pj-side-2col { display: block; }
|
||||
}
|
||||
.pj-modal-card h3 { margin: 0 0 16px; font-size: var(--pj-heading-size); line-height: var(--pj-heading-leading); font-weight: 500; letter-spacing: normal; }
|
||||
.pj-modal-hint { margin: -6px 0 14px; font-size: 12px; color: #6b7280; }
|
||||
@@ -902,7 +901,8 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
||||
.pj-btn-complete.is-done { background: #f2f2f4; color: #6b6f76; border-color: var(--pj-border); }
|
||||
|
||||
/* 색상표(아사나) — 8칸씩 둥근 네모, 고른 색엔 체크 */
|
||||
.pj-color-palette, #pj-f-colors { display: grid; grid-template-columns: repeat(8, 26px); gap: 8px; margin-top: 6px; }
|
||||
/* 12칸씩(2026-10-08) — 32색이 3줄 */
|
||||
.pj-color-palette, #pj-f-colors { display: grid; grid-template-columns: repeat(12, 26px); gap: 8px; margin-top: 6px; }
|
||||
.pj-color-swatch {
|
||||
position: relative; width: 26px; height: 26px; padding: 0; border: none; border-radius: 6px; cursor: pointer;
|
||||
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .06);
|
||||
@@ -915,10 +915,22 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
||||
}
|
||||
.pj-color-swatch.is-dark.is-active::after { color: #fff; }
|
||||
/* 프로젝트 아이콘 고르기(아사나) — 회색 아이콘 격자, 고른 것은 보라 강조. 길면 칸 안에서 스크롤 */
|
||||
.pj-icon-palette {
|
||||
.pj-icon-palette { margin-top: 6px; }
|
||||
.pj-icon-grid {
|
||||
/* 높이 제한 없음 — 아이콘 전부가 스크롤 없이 보이고 팝업이 그만큼 길어진다 */
|
||||
display: grid; grid-template-columns: repeat(auto-fill, 38px); gap: 6px; margin-top: 6px; padding: 2px;
|
||||
display: grid; grid-template-columns: repeat(auto-fill, 38px); gap: 6px; padding: 2px;
|
||||
}
|
||||
/* [기본 아이콘] [아사나 아이콘] 탭 — "아이콘" 글자 오른쪽 */
|
||||
.pj-icon-tabs { display: inline-flex; gap: 2px; margin-left: 10px; padding: 2px; border-radius: 8px; background: #f1f2f4; vertical-align: middle; }
|
||||
.pj-icon-tab { border: none; background: transparent; padding: 3px 10px; border-radius: 6px; font: inherit; font-size: 12.5px; color: var(--pj-ink-soft); cursor: pointer; }
|
||||
.pj-icon-tab:hover { color: var(--pj-ink); }
|
||||
.pj-icon-tab.is-active { background: #fff; color: var(--pj-ink); font-weight: 600; box-shadow: 0 1px 2px rgba(16, 24, 40, .12); }
|
||||
/* 아사나 아이콘 — 채워진 모양(Material Symbols FILL 1, 쓰는 33개만 담은 글꼴). 값은 "asana:이름" */
|
||||
@font-face {
|
||||
font-family: "Material Symbols Asana"; font-style: normal; font-weight: 400; font-display: block;
|
||||
src: url(/static/vendor/material-symbols/material-symbols-asana.woff2) format("woff2");
|
||||
}
|
||||
.material-symbols-outlined.pj-ic-asana { font-family: "Material Symbols Asana"; }
|
||||
.pj-icon-pick {
|
||||
width: 38px; height: 38px; padding: 0; border: none; border-radius: 8px; background: transparent;
|
||||
color: #6d6e6f; cursor: pointer; display: inline-flex; align-items: center; justify-content: center;
|
||||
@@ -942,9 +954,17 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
||||
|
||||
.pj-attach-list, .pj-comment-list { list-style: none; margin: 0 0 6px; padding: 0; max-height: 160px; overflow-y: auto; }
|
||||
.pj-attach-item { display: flex; align-items: center; gap: 8px; padding: 5px 4px; font-size: 13px; }
|
||||
.pj-attach-item a { color: #2b4a85; text-decoration: none; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.pj-attach-item a { display: flex; align-items: center; gap: 8px; min-width: 0; color: #2b4a85; text-decoration: none; flex: 1; }
|
||||
.pj-attach-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.pj-attach-icon { flex: none; font-size: 22px; color: #6b7280; }
|
||||
.pj-attach-icon.is-image { color: #7c5ce0; }
|
||||
.pj-attach-icon.is-excel { color: #21834d; }
|
||||
.pj-attach-icon.is-text { color: #64748b; }
|
||||
.pj-attach-icon.is-ppt { color: #c85a29; }
|
||||
.pj-attach-icon.is-document { color: #356ac3; }
|
||||
.pj-attach-icon.is-pdf { color: #c43c3c; }
|
||||
.pj-attach-item a:hover { text-decoration: underline; }
|
||||
.pj-attach-size { font-size: 11px; color: #9aa1a9; }
|
||||
.pj-attach-size { flex: none; font-size: 11px; color: #9aa1a9; }
|
||||
|
||||
.pj-comment-item { display: flex; align-items: flex-start; gap: 8px; padding: 7px 2px; }
|
||||
.pj-comment-main { flex: 1; }
|
||||
@@ -992,6 +1012,8 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
||||
/* ── 새 프로젝트 모달 — 멤버 선택 ── */
|
||||
.pj-modal-card .pj-field-label { display: block; font-size: var(--pj-small-size); font-weight: 400; color: var(--pj-ink); margin-bottom: 12px; line-height: var(--pj-small-leading); }
|
||||
.pj-member-picker { display: flex; flex-wrap: wrap; gap: 4px 12px; margin-top: 5px; max-height: 140px; overflow-y: auto; padding: 6px 2px; border: 1px solid #eef0f2; border-radius: 8px; }
|
||||
/* 멤버 배정·제외 창은 목록에 스크롤 없이 사람 수만큼 늘어난다(창 전체가 화면보다 길면 창이 스크롤) */
|
||||
#pj-modal-member .pj-member-picker { max-height: none; overflow: visible; }
|
||||
.pj-member-pick { display: inline-flex !important; align-items: center; gap: 5px; font-size: 12.5px; font-weight: 500 !important; color: #333; width: auto !important; margin: 0 !important; }
|
||||
.pj-member-pick input { width: auto !important; margin: 0 !important; }
|
||||
|
||||
@@ -1006,6 +1028,12 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
||||
.pj-member-pick-avatar .pj-member-pick-icon.material-symbols-outlined { font-size: 40px; }
|
||||
.pj-member-pick-avatar img.pj-member-pick-icon { width: 36px; height: 36px; }
|
||||
.pj-member-pick-stacked .pj-member-pick-name { font-size: 12.5px; }
|
||||
/* 새 프로젝트 — 만든 뒤 배정에 실패한 멤버(다시 배정 대상)와 안내줄 */
|
||||
.pj-member-pick-stacked.is-failed { background: #fdecec; box-shadow: inset 0 0 0 1px #f1a8a8; }
|
||||
.pj-member-pick-stacked.is-failed .pj-member-pick-name { color: #b42318; }
|
||||
.pj-modal-msg { margin: 8px 0 0; padding: 8px 10px; border-radius: 6px; font-size: 12.5px; line-height: 1.5;
|
||||
background: #f5f6f8; color: #333; }
|
||||
.pj-modal-msg.is-error { background: #fdecec; color: #b42318; }
|
||||
|
||||
/* ── 좌측 사이드바 "전체 멤버" — 메뉴의 실제 내부 폭에 따라 4열↔3열, 아이콘 아래 이름(새 프로젝트
|
||||
모달의 pj-member-pick-stacked 와 같은 아이콘 크기 재사용). ── */
|
||||
@@ -1138,7 +1166,7 @@ html.pj-ui-scale #pj-timeline { zoom: calc(1 / var(--pj-z)); --tz: var(--pj-z);
|
||||
|
||||
/* ── 보드 단계 컨트롤 ── */
|
||||
.pj-col-head { position: relative; }
|
||||
.pj-col-name { font-weight: 500; font-size: var(--pj-section-size); line-height: var(--pj-section-leading); }
|
||||
.pj-col-name { font-weight: 700; font-size: var(--pj-section-size); line-height: var(--pj-section-leading); }
|
||||
.pj-icon-btn[disabled] { opacity: .3; cursor: default; }
|
||||
.pj-add-stage { width: 100%; padding: 10px; border: 1px dashed #c9cdd3; border-radius: 12px; background: #fff; color: #6b7280; font-size: 13px; font-weight: 600; cursor: pointer; }
|
||||
.pj-add-stage:hover { border-color: #1e1f21; color: #1e1f21; }
|
||||
@@ -1428,21 +1456,27 @@ label.pj-desc-fmtbtn {
|
||||
}
|
||||
|
||||
/* ── 연결된 프로젝트(멀티호밍) 칩 ── */
|
||||
.pj-link-chips { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 8px; }
|
||||
.pj-projects-row { gap: 8px; padding: 4px 0; flex-wrap: nowrap; overflow-x: auto; }
|
||||
.pj-projects-row[hidden] { display: none; }
|
||||
.pj-projects-label { display: inline-flex; align-items: center; gap: 4px; }
|
||||
.pj-link-chips { display: flex; flex: 0 1 auto; min-width: 32px; max-width: 25%; gap: 6px; overflow-x: auto; }
|
||||
.pj-link-chips .pj-empty-sm { padding: 0 2px; white-space: nowrap; }
|
||||
.pj-projects-row.is-readonly .pj-link-chips { max-width: none; flex: 1; }
|
||||
.pj-link-chip {
|
||||
display: inline-flex; align-items: center; gap: 5px; font-size: 12px; font-weight: 600;
|
||||
display: inline-flex; flex: none; align-items: center; gap: 5px; font-size: 12px; font-weight: 600; white-space: nowrap;
|
||||
padding: 3px 6px 3px 10px; border-radius: 999px; background: #eef0f2; color: #333;
|
||||
}
|
||||
.pj-link-chip .pj-link-del { border: none; background: transparent; cursor: pointer; color: #9aa1a9; font-size: 13px; line-height: 1; padding: 2px; }
|
||||
.pj-link-chip .pj-link-del:hover { color: #c22b10; }
|
||||
/* 세로로 쌓기 — 옆 칼럼이 좁아 가로 배치면 select 글자가 잘린다. */
|
||||
.pj-link-form { display: flex; flex-direction: column; gap: 6px; align-items: stretch; }
|
||||
/* 좁은 패널에서도 한 줄을 유지하며 프로젝트 줄 안에서만 가로 스크롤. */
|
||||
.pj-link-form { display: flex; flex: 1; min-width: 360px; gap: 6px; align-items: center; }
|
||||
.pj-link-form[hidden] { display: none; }
|
||||
.pj-link-form select {
|
||||
width: 100% !important; flex: none; margin: 0 !important;
|
||||
width: 0 !important; min-width: 90px; flex: 1; margin: 0 !important;
|
||||
padding: 6px 8px !important; border: 1px solid #d8dce2 !important; border-radius: 8px;
|
||||
font-size: 11.5px !important; font-family: inherit; box-sizing: border-box;
|
||||
}
|
||||
.pj-link-form .pj-btn { align-self: flex-end; }
|
||||
.pj-link-form .pj-btn { flex: none; padding: 6px 8px; font-size: 11.5px; white-space: nowrap; }
|
||||
|
||||
/* ── 알림센터 ── */
|
||||
.pj-inbox { list-style: none; margin: 0; padding: 0; }
|
||||
@@ -1456,6 +1490,10 @@ label.pj-desc-fmtbtn {
|
||||
.pj-inbox-sub { font-size: var(--pj-text-size); color: #525860; margin-top: 2px; line-height: var(--pj-text-leading); font-weight: 400; }
|
||||
.pj-inbox-meta { font-size: var(--pj-small-size); color: #9aa1a9; margin-top: 4px; line-height: var(--pj-small-leading); font-weight: 400; }
|
||||
.pj-inbox-go { align-self: center; padding: 4px 12px; font-size: 12px; }
|
||||
/* 확인한 줄이 목록에서 빠질 때(2026-10-08) */
|
||||
.pj-inbox-item { transition: opacity .2s, transform .2s; }
|
||||
.pj-inbox-item.is-leaving { opacity: 0; transform: translateX(-12px); }
|
||||
.pj-inbox-item:focus-visible { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
|
||||
|
||||
/* ── 우클릭 컨텍스트 메뉴 — 클릭 좌표 기준 고정 위치(.pj-daypop 은 앵커
|
||||
엘리먼트 기준이라 좌표 배치가 다름). z-index 는 .pj-daypop(2100) 보다
|
||||
@@ -1533,6 +1571,62 @@ img.pj-person-ic { width: 22px; height: 22px; }
|
||||
box-shadow: var(--pj-card-shadow); padding: 18px 20px 20px; min-width: 0;
|
||||
}
|
||||
.pj-dash-card-wide { grid-column: 1 / -1; }
|
||||
/* 담당자별 작업 합계 — 사람마다 메인·하위 세로 막대. 막대 = 그 작업 전체(100%), 초록 채움 = 완료율. 누르면 오른쪽 업무 목록 패널 */
|
||||
.pj-wl-legend { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; margin: -6px 0 14px; font-size: 12px; color: var(--pj-ink-soft); }
|
||||
.pj-wl-legend i { display: inline-block; width: 10px; height: 10px; border-radius: 3px; margin-right: 5px; vertical-align: -1px; }
|
||||
.pj-wl-legend i.is-done { background: var(--color-success-green, #2e9e5b); }
|
||||
.pj-wl-legend i.is-open { background: var(--pj-accent-tint); border: 1px solid #cfc6fb; }
|
||||
.pj-wl-legend .pj-wl-sum { color: var(--pj-ink); }
|
||||
.pj-wl-legend .pj-wl-hint { margin-left: auto; }
|
||||
.pj-wl-bars { display: flex; align-items: flex-end; gap: 26px; overflow-x: auto; padding-bottom: 2px; min-height: 220px; }
|
||||
.pj-wl-group { display: flex; flex-direction: column; align-items: center; flex: 0 0 auto; }
|
||||
.pj-wl-pair { display: flex; align-items: flex-end; gap: 6px; }
|
||||
.pj-wl-col {
|
||||
display: flex; flex-direction: column; align-items: center; gap: 0; padding: 2px 2px 0; border: none; background: none;
|
||||
border-radius: 8px; font: inherit; cursor: pointer;
|
||||
}
|
||||
.pj-wl-col:disabled { cursor: default; opacity: .55; }
|
||||
.pj-wl-col:not(:disabled):hover .pj-wl-track, .pj-wl-col:focus-visible .pj-wl-track { box-shadow: 0 0 0 2px var(--pj-accent); }
|
||||
.pj-wl-val { display: flex; flex-direction: column; align-items: center; font-size: 12px; font-weight: 700; color: var(--pj-ink); margin-bottom: 6px; font-variant-numeric: tabular-nums; line-height: 1.25; }
|
||||
.pj-wl-val small { font-size: 10.5px; font-weight: 600; color: var(--pj-ink-soft); }
|
||||
.pj-wl-track { position: relative; display: block; width: 30px; height: 150px; border-radius: 6px 6px 4px 4px; background: #f1f2f4; overflow: hidden; }
|
||||
.pj-wl-track.has-tasks { background: var(--pj-accent-tint); box-shadow: inset 0 0 0 1px #d9d2fb; } /* 미완료 몫 */
|
||||
.pj-wl-done {
|
||||
position: absolute; left: 0; right: 0; bottom: 0; height: 0; background: var(--color-success-green, #2e9e5b);
|
||||
transition: height .7s cubic-bezier(.22,.9,.3,1);
|
||||
}
|
||||
.pj-wl-col.is-sub .pj-wl-done { background: #5fbf86; }
|
||||
.pj-wl-kind { margin-top: 6px; font-size: 11px; color: var(--pj-ink-soft); white-space: nowrap; } /* "메인 작업"·"세부 작업" 한 줄 */
|
||||
.pj-wl-name { display: flex; flex-direction: column; align-items: center; margin-top: 4px; max-width: 110px; text-align: center; }
|
||||
.pj-wl-name b { font-size: 12.5px; font-weight: 600; color: var(--pj-ink); max-width: 110px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.pj-wl-name small { font-size: 11px; color: var(--pj-ink-soft); font-variant-numeric: tabular-nums; }
|
||||
/* 오른쪽 업무 목록 패널(body 에 붙음, 작업 편집 창(z 1000) 아래) */
|
||||
.pj-wl-drawer { position: fixed; inset: 0; z-index: 950; }
|
||||
.pj-wl-drawer-dim { position: absolute; inset: 0; background: rgba(20, 22, 26, .18); opacity: 0; transition: opacity .25s; }
|
||||
.pj-wl-panel {
|
||||
position: absolute; top: 0; right: 0; bottom: 0; width: min(420px, 92vw); display: flex; flex-direction: column;
|
||||
background: #fff; box-shadow: -12px 0 40px rgba(16, 24, 40, .16); transform: translateX(100%);
|
||||
transition: transform .26s cubic-bezier(.22,.9,.3,1);
|
||||
}
|
||||
.pj-wl-drawer.is-open .pj-wl-drawer-dim { opacity: 1; }
|
||||
.pj-wl-drawer.is-open .pj-wl-panel { transform: none; }
|
||||
.pj-wl-panel header { display: flex; align-items: flex-start; justify-content: space-between; gap: 8px; padding: 18px 18px 12px; border-bottom: 1px solid var(--pj-border); }
|
||||
.pj-wl-panel header b { display: block; font-size: 15px; }
|
||||
.pj-wl-panel header small { color: var(--pj-ink-soft); font-size: 12px; }
|
||||
.pj-wl-panel-body { flex: 1 1 auto; overflow-y: auto; padding: 8px 10px 16px; }
|
||||
.pj-wl-panel-group { margin: 12px 8px 4px; font-size: 11.5px; font-weight: 700; color: var(--pj-ink-soft); }
|
||||
.pj-wl-item {
|
||||
display: flex; align-items: center; gap: 10px; width: 100%; padding: 9px 8px; border: none; border-radius: 8px;
|
||||
background: none; font: inherit; text-align: left; cursor: pointer; color: var(--pj-ink);
|
||||
}
|
||||
.pj-wl-item:hover { background: #f5f6f8; }
|
||||
.pj-wl-item .material-symbols-outlined { font-size: 19px; color: #9aa1ab; flex: none; }
|
||||
.pj-wl-item.is-done .material-symbols-outlined { color: var(--color-success-green, #2e9e5b); }
|
||||
.pj-wl-item.is-done .pj-wl-item-title { color: var(--pj-ink-soft); text-decoration: line-through; }
|
||||
.pj-wl-item-main { display: flex; flex-direction: column; min-width: 0; flex: 1 1 auto; }
|
||||
.pj-wl-item-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13.5px; }
|
||||
.pj-wl-item-main small { color: var(--pj-ink-soft); font-size: 11.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.pj-wl-item em { flex: none; font-style: normal; font-size: 12px; color: var(--pj-ink-soft); font-variant-numeric: tabular-nums; }
|
||||
.pj-dash-card-title { font-size: 13.5px; font-weight: 700; color: var(--pj-ink); margin-bottom: 18px; }
|
||||
|
||||
/* 세로 막대(섹션별/담당자별 공용) */
|
||||
@@ -2145,8 +2239,8 @@ html.pj-ui-scale .pj-modal-chat { max-height: calc(92vh / var(--pj-z)); }
|
||||
|
||||
/* 가로·세로 스크롤은 이 칸 하나가 맡고, 머리 줄과 왼쪽 두 칸(구분·항목)은 붙어 있다 */
|
||||
.pj-goal-pane { flex: 1 1 auto; min-height: 0; overflow: auto; }
|
||||
/* width: 1px — table-layout: fixed 는 표 너비가 auto 가 아닐 때만 먹는다. 표는 칸 너비 합만큼 늘어나고,
|
||||
칸 너비가 머리 칸 width 로만 정해져야 분기 접기 애니메이션이 양방향으로 부드럽다(auto 면 펼 때 한 번에 튄다). */
|
||||
/* width: 1px — table-layout: fixed 는 표 너비가 auto 가 아닐 때만 먹는다.
|
||||
표는 머리 칸에 지정한 너비 합만큼 늘어나며, 분기를 펼쳐도 저장된 열 너비를 유지한다. */
|
||||
.pj-goal-table {
|
||||
width: 1px; border-collapse: separate; border-spacing: 0; table-layout: fixed; font-size: var(--pj-text-size);
|
||||
color: var(--pj-ink); background: #fff; border: 1px solid #dfe2e6; border-radius: 10px; line-height: var(--pj-text-leading);
|
||||
@@ -2185,7 +2279,7 @@ html.pj-ui-scale .pj-modal-chat { max-height: calc(92vh / var(--pj-z)); }
|
||||
content: ""; position: absolute; top: 6px; bottom: 6px; left: 3px; width: 2px; border-radius: 2px; background: transparent;
|
||||
}
|
||||
.pj-goal-colresize:hover::after, .pj-goal-colresize.is-dragging::after { background: var(--pj-accent); }
|
||||
/* 월 칸은 overflow: hidden(접기 애니메이션)이라 칸 밖으로 나간 손잡이가 잘린다 — 칸 안쪽 오른쪽 끝에 둔다 */
|
||||
/* 월 칸은 overflow: hidden 이라 칸 밖으로 나간 손잡이가 잘린다 — 칸 안쪽 오른쪽 끝에 둔다 */
|
||||
:where(.pj-goal-table th, .pj-goal-table td) { position: relative; }
|
||||
.pj-goal-table :is(th, td).pj-goal-m .pj-goal-colresize { right: 0; width: 7px; }
|
||||
.pj-goal-table :is(th, td).pj-goal-m .pj-goal-colresize::after { left: auto; right: 1px; }
|
||||
@@ -2214,7 +2308,7 @@ input.pj-goal-num:focus { outline: 2px solid var(--pj-accent); outline-offset: -
|
||||
|
||||
/* 업무 영역 — 영역 색(--goal-bg)이 줄 전체 배경(스프레드시트처럼) */
|
||||
.pj-goal-area > tr > th, .pj-goal-area > tr > td { background: var(--goal-bg, #fff); border-color: rgba(0, 0, 0, .07); }
|
||||
.pj-goal-area > tr > th { padding: 6px 8px; vertical-align: top; }
|
||||
.pj-goal-area > tr > th { padding: 6px 8px; vertical-align: middle; } /* 1·2열은 병합·행 높이에 관계없이 세로 가운데 */
|
||||
.pj-goal-area > tr:first-child > * { border-top: 1px solid rgba(0, 0, 0, .12); }
|
||||
.pj-goal-area-name { font-size: var(--pj-text-size); font-weight: 500 !important; }
|
||||
.pj-goal-area-text, .pj-goal-row-text { display: block; word-break: keep-all; overflow-wrap: anywhere; }
|
||||
@@ -2321,19 +2415,30 @@ html.pj-goal-selecting .pj-goal-menu-btn { pointer-events: none; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.pj-goal-fold-ic, .pj-goal-fold-v { transition: none; }
|
||||
}
|
||||
/* 접기 애니메이션 — 월 칸 너비를 0 으로(.is-shrunk) 줄인 뒤 숨김(.is-gone), 펼 땐 거꾸로(initGoals applyFold).
|
||||
줄어드는 동안 칸 안 글이 다시 줄바꿈돼 줄 높이가 출렁이지 않게 안쪽 내용은 원래 폭(--fold-w = 걸친 월 너비 합)으로 고정해 잘라 낸다. */
|
||||
/* 분기 접기 — 열은 부드럽게 움직이고, 내용은 최종 너비가 된 뒤 나타난다.
|
||||
원래 폭으로 글 높이를 유지하고, 정렬이 재계산되는 동안 내용만 가려 숫자 밀림을 방지한다. */
|
||||
.pj-goal-table .pj-goal-m { overflow: hidden; }
|
||||
.pj-goal-table.is-folding .pj-goal-m {
|
||||
.pj-goal-table .pj-goal-m.is-folding {
|
||||
transition: width .32s ease, min-width .32s ease, max-width .32s ease,
|
||||
padding .32s ease, border-right-width .32s ease;
|
||||
color: transparent !important;
|
||||
}
|
||||
.pj-goal-table.is-folding td.pj-goal-m > * { width: var(--fold-w, calc(85px * var(--span, 1) - 1px)); }
|
||||
.pj-goal-table .pj-goal-m > :is(.pj-goal-num, .pj-goal-text, .pj-goal-text-ro, .pj-goal-mlabel) {
|
||||
transition: opacity .12s ease;
|
||||
}
|
||||
.pj-goal-table .pj-goal-m.is-folding > :not(.pj-goal-colresize):not(.pj-goal-move-edge) {
|
||||
opacity: 0; transition: none; pointer-events: none;
|
||||
}
|
||||
.pj-goal-table td.pj-goal-m.is-folding > :is(.pj-goal-num, .pj-goal-text, .pj-goal-text-ro) { width: var(--fold-w); }
|
||||
.pj-goal-table thead th.pj-goal-m.is-shrunk,
|
||||
.pj-goal-table td.pj-goal-m.is-shrunk {
|
||||
width: 0; min-width: 0; max-width: 0; padding-left: 0 !important; padding-right: 0 !important; border-right-width: 0;
|
||||
}
|
||||
.pj-goal-table .pj-goal-m.is-gone { display: none; }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.pj-goal-table .pj-goal-m.is-folding,
|
||||
.pj-goal-table .pj-goal-m > :is(.pj-goal-num, .pj-goal-text, .pj-goal-text-ro, .pj-goal-mlabel) { transition: none; }
|
||||
}
|
||||
|
||||
/* 영역·줄 이름 — 눌러서 그 자리에서 수정(관리자) */
|
||||
.pj-goal-table [data-goal-edit] { cursor: text; border-radius: 5px; padding: 1px 3px; margin: -1px -3px; }
|
||||
@@ -2404,7 +2509,76 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important;
|
||||
/* 머리 — 왼쪽: 제목·인쇄·삭제 … 주차 탭(달력 쪽 끝) + 이 달 계획(달력 앞까지) / 오른쪽 위: 작은 달력(폭 174px, 글자 10.5px) */
|
||||
.pj-meet-headgrid { display: flex; align-items: flex-start; gap: 10px; margin: 8px 0 12px; }
|
||||
.pj-meet-headleft { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.pj-meet-headleft > .pj-meet-plan { margin: 0; }
|
||||
/* 머리 영역 3칸(2026-10-07) — ① 월 계획 + 숫자 한 줄 ② 결정 사항·메모 ③ 작업 등록. 머리는 스크롤되지 않아 늘 보인다 */
|
||||
.pj-meet-board { display: grid; grid-template-columns: minmax(0, 1.25fr) minmax(0, .9fr) minmax(0, 1.35fr); gap: 10px; }
|
||||
@media (max-width: 1500px) { .pj-meet-board { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } .pj-meet-quick { grid-column: 1 / -1; } }
|
||||
.pj-meet-area {
|
||||
display: flex; flex-direction: column; min-width: 0; height: 230px; margin: 0; padding: 8px 10px;
|
||||
border: 1px solid var(--pj-border); border-radius: 10px; background: #fff;
|
||||
}
|
||||
.pj-meet-area h3, .pj-meet-area.pj-meet-notes h3 { margin: 0 0 6px; font-size: 13px; font-weight: 600; }
|
||||
.pj-meet-area.pj-meet-notes { margin: 0; } /* 예전 .pj-meet-notes 여백(16px) 덮기 */
|
||||
.pj-meet-area h3 small { margin-left: 6px; font-size: 11px; font-weight: 400; color: var(--pj-ink-soft); }
|
||||
.pj-meet-area-body { flex: 1 1 auto; min-height: 0; overflow: auto; }
|
||||
.pj-meet-area.pj-meet-notes textarea, .pj-meet-area.pj-meet-notes .pj-meet-ro {
|
||||
flex: 1 1 auto; min-height: 0; max-height: none; height: auto !important; overflow-y: auto; padding: 8px 10px;
|
||||
border: 1px solid #dfe2e6; border-radius: 8px; background: #fff;
|
||||
}
|
||||
/* ① 머리 줄 — 제목 + 숫자 4개(작게 한 줄) */
|
||||
.pj-meet-plan-title { display: inline-flex; align-items: center; gap: 6px; flex: none; }
|
||||
.pj-meet-kpiline {
|
||||
display: flex; align-items: baseline; gap: 10px; flex: 1 1 0; flex-wrap: nowrap; min-width: 0; margin-left: 10px;
|
||||
font-size: 11px; overflow: hidden; white-space: nowrap; /* 늘 1행 — 좁으면 끝이 가려지고 말풍선으로 */
|
||||
}
|
||||
.pj-meet-kpiline .pj-meet-kpi { display: inline-flex; flex-direction: row; align-items: baseline; gap: 4px; padding: 0; border: none; background: none; white-space: nowrap; }
|
||||
.pj-meet-kpiline .pj-meet-kpi + .pj-meet-kpi::before { content: "·"; margin-right: 6px; color: #c4c8cf; }
|
||||
.pj-meet-kpiline .pj-meet-kpi { flex: none; }
|
||||
.pj-meet-kpiline .pj-meet-kpi-label { font-size: 11px; font-weight: 500; overflow: visible; }
|
||||
.pj-meet-kpiline .pj-meet-kpi-val { font-size: 12px; font-weight: 700; }
|
||||
.pj-meet-kpiline .pj-meet-kpi-val small { font-size: 10px; }
|
||||
.pj-meet-kpiline .pj-meet-kpi-rate { color: inherit; font-weight: 700; }
|
||||
/* ③ 작업 등록 표 — 빈 칸을 누르면 목록(body 에 붙는 메뉴) */
|
||||
.pj-meet-quick-table { width: 100%; border-collapse: collapse; table-layout: fixed; font-size: 12.5px; }
|
||||
.pj-meet-quick-table th { position: sticky; top: 0; z-index: 1; background: #f7f8f9; padding: 4px 6px; font-size: 12px; font-weight: 700; color: var(--pj-ink); text-align: center; border-bottom: 1px solid var(--pj-border); }
|
||||
.pj-meet-pick-cell.is-person { display: flex; align-items: center; gap: 6px; }
|
||||
.pj-meet-pick-cell.is-person > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; }
|
||||
.pj-meet-quick-face { width: 18px; height: 18px; flex: none; border-radius: 50%; object-fit: cover; }
|
||||
.pj-meet-quick-face.is-ini {
|
||||
display: inline-flex; align-items: center; justify-content: center; background: var(--pj-accent-tint); color: var(--pj-accent-dark);
|
||||
font-size: 10.5px; font-weight: 700;
|
||||
}
|
||||
.pj-ctxmenu-ic .pj-meet-quick-face { width: 20px; height: 20px; }
|
||||
.pj-member-pick.is-owner { opacity: .75; }
|
||||
.pj-meet-quick-table th:nth-child(1) { width: 30%; }
|
||||
.pj-meet-quick-table th:nth-child(2) { width: 17%; }
|
||||
.pj-meet-quick-table th:nth-child(3) { width: 19%; }
|
||||
.pj-meet-quick-table th:nth-child(4) { width: 15%; }
|
||||
.pj-meet-quick-table th:nth-child(5) { width: 19%; }
|
||||
.pj-meet-quick-acts { white-space: nowrap; text-align: right; }
|
||||
.pj-meet-quick-del {
|
||||
display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; margin-left: 4px; vertical-align: middle;
|
||||
border: none; border-radius: 6px; background: none; color: #9aa1ab; cursor: pointer;
|
||||
}
|
||||
.pj-meet-quick-del .material-symbols-outlined { font-size: 17px; }
|
||||
.pj-meet-quick-del:hover { background: #fdecec; color: #c22b10; }
|
||||
.pj-meet-quick-del:disabled { opacity: .4; cursor: default; }
|
||||
.pj-meet-quick-table td { padding: 2px 3px; border-bottom: 1px solid #eef0f2; vertical-align: middle; }
|
||||
.pj-meet-quick-table input { width: 100%; box-sizing: border-box; height: 26px; padding: 0 6px; border: 1px solid transparent; border-radius: 6px; background: transparent; font: inherit; }
|
||||
.pj-meet-quick-table input:hover, .pj-meet-quick-table input:focus { border-color: #dfe2e6; background: #fff; outline: none; }
|
||||
.pj-meet-pick-cell {
|
||||
display: block; width: 100%; height: 26px; padding: 0 6px; border: 1px dashed transparent; border-radius: 6px; background: none;
|
||||
font: inherit; text-align: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: pointer; color: var(--pj-ink);
|
||||
}
|
||||
.pj-meet-pick-cell.is-empty { color: #a7adb6; }
|
||||
.pj-meet-pick-cell:hover { border-color: #cfd4da; background: #fafbfc; }
|
||||
.pj-meet-quick-apply { height: 26px; padding: 0 10px; border: none; border-radius: 6px; background: var(--pj-accent); color: #fff; font: inherit; font-size: 12px; font-weight: 600; cursor: pointer; white-space: nowrap; }
|
||||
.pj-meet-quick-apply:disabled { opacity: .5; cursor: default; }
|
||||
.pj-meet-quick-done { display: inline-flex; align-items: center; gap: 4px; font-size: 11.5px; color: #1f8a4c; white-space: nowrap; }
|
||||
.pj-meet-quick-done a { color: inherit; }
|
||||
.pj-meet-quick-table tr.is-done input, .pj-meet-quick-table tr.is-done .pj-meet-pick-cell { color: var(--pj-ink-soft); pointer-events: none; }
|
||||
.pj-meet-quick-table tr.is-done .pj-meet-pick-cell.is-person { color: var(--pj-ink-soft); }
|
||||
.pj-meet-quick-add { margin-top: 4px; padding: 2px 6px; border: none; background: none; color: var(--pj-accent-dark); font: inherit; font-size: 12px; cursor: pointer; }
|
||||
@media print { .pj-meet-quick { display: none !important; } .pj-meet-area { height: auto; } }
|
||||
.pj-meet-title { flex-wrap: wrap; }
|
||||
.pj-meet-title-acts { display: inline-flex; align-items: center; gap: 6px; margin-left: 4px; }
|
||||
.pj-meet-title-acts .material-symbols-outlined { font-size: 16px; margin-right: 3px; }
|
||||
@@ -2467,8 +2641,6 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important;
|
||||
.pj-meet-unknown::before { content: "⚠ "; font-weight: 400; }
|
||||
.pj-meet-perf-warn { color: #9a4a07; }
|
||||
.pj-meet-noprev { font-weight: 500; color: rgba(0, 0, 0, .45); }
|
||||
.pj-meet-market.is-unknown { background: #fff4ec; color: #b45309; }
|
||||
.pj-meet-week-auto.is-unknown { color: #b45309; }
|
||||
.pj-meet-sync {
|
||||
display: flex; align-items: center; gap: 8px; margin: -4px 0 10px; padding: 6px 10px; border-radius: 8px;
|
||||
background: #f6f7f9; color: var(--pj-ink-soft); font-size: 12.5px;
|
||||
@@ -2481,17 +2653,28 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important;
|
||||
.pj-meet-sync.is-warn { background: #fff4ec; color: #b45309; }
|
||||
@keyframes pj-meet-spin { to { transform: rotate(360deg); } }
|
||||
@media print { .pj-meet-sync { display: none !important; } }
|
||||
/* 숫자 — 한 줄 막대(칸 9개, 좁으면 두 줄). 설명 문구는 말풍선(title) */
|
||||
/* 위쪽 고정 영역(2026-10-07) — 왼쪽 절반 숫자 4칸 | 오른쪽 절반 결정 사항·메모. 스크롤해도 위에 붙는다(.pj-meet-pane 기준).
|
||||
표 머리 줄은 이 높이(--pj-meet-top-h, project.js initMeetTop) 아래에 붙는다. 설명 문구는 말풍선(title) */
|
||||
.pj-meet-top {
|
||||
position: sticky; top: 0; z-index: 6; display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px;
|
||||
align-items: stretch; padding: 0 0 10px; background: #fff;
|
||||
}
|
||||
.pj-meet-kpibar {
|
||||
display: grid; grid-template-columns: repeat(9, minmax(0, 1fr)); margin-bottom: 10px;
|
||||
display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); align-content: stretch;
|
||||
border: 1px solid var(--pj-border); border-radius: 10px; background: #fff; overflow: hidden;
|
||||
}
|
||||
.pj-meet-kpis { display: contents; }
|
||||
.pj-meet-kpi { display: flex; flex-direction: column; gap: 1px; padding: 6px 10px; min-width: 0; border-right: 1px solid var(--pj-border); }
|
||||
.pj-meet-kpis.is-week .pj-meet-kpi:last-child { border-right: none; }
|
||||
.pj-meet-kpis:not(.is-week) .pj-meet-kpi:last-child { border-right: 2px solid #d5d9de; } /* 월 | 주 경계 */
|
||||
.pj-meet-kpi { display: flex; flex-direction: column; justify-content: center; gap: 2px; padding: 8px 12px; min-width: 0; border-right: 1px solid var(--pj-border); }
|
||||
.pj-meet-kpi:last-child { border-right: none; }
|
||||
.pj-meet-kpi.is-accent { background: #faf9ff; }
|
||||
.pj-meet-kpi.is-input { background: #fffaf4; }
|
||||
.pj-meet-kpi-sub.is-good { color: #1f8a4c; font-weight: 700; }
|
||||
.pj-meet-kpi-sub.is-low { color: #c2410c; font-weight: 700; }
|
||||
.pj-meet-kpi-link { color: var(--pj-accent-dark); text-decoration: none; }
|
||||
.pj-meet-kpi-link:hover { text-decoration: underline; }
|
||||
.pj-meet-top .pj-meet-notes { margin: 0; display: flex; flex-direction: column; min-width: 0; }
|
||||
.pj-meet-top .pj-meet-notes h3 { margin: 0 0 4px; font-size: 13px; }
|
||||
.pj-meet-top .pj-meet-notes textarea, .pj-meet-top .pj-meet-notes .pj-meet-ro {
|
||||
flex: 1 1 auto; min-height: 64px; max-height: 140px; overflow-y: auto; padding: 8px 10px;
|
||||
}
|
||||
.pj-meet-kpi-label { font-size: 11px; color: var(--pj-ink-soft); font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.pj-meet-kpi-label small { font-weight: 500; }
|
||||
.pj-meet-kpi-val { font-size: 15px; font-weight: 800; font-variant-numeric: tabular-nums; display: flex; align-items: baseline; gap: 2px; white-space: nowrap; }
|
||||
@@ -2503,11 +2686,10 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important;
|
||||
font-size: 14px; font-weight: 800; height: 24px; width: 100%; text-align: left;
|
||||
border: 1px solid #f3d2b0; border-radius: 6px; background: #fff; padding: 0 6px;
|
||||
}
|
||||
@media (max-width: 1300px) { .pj-meet-kpibar { grid-template-columns: repeat(5, minmax(0, 1fr)); } }
|
||||
@media (max-width: 1300px) { .pj-meet-kpibar { grid-template-columns: repeat(2, minmax(0, 1fr)); } .pj-meet-kpi:nth-child(2) { border-right: none; } .pj-meet-kpi:nth-child(-n+2) { border-bottom: 1px solid var(--pj-border); } }
|
||||
|
||||
/* 이 달 계획 — 연간 목표 표의 그 달 열(업무 영역별 작은 카드) */
|
||||
.pj-meet-plan { margin: 0 0 10px; padding: 8px 10px; border: 1px solid var(--pj-border); border-radius: 10px; background: #fff; }
|
||||
.pj-meet-plan-head { display: flex; align-items: center; gap: 6px; font-size: var(--pj-text-size); font-weight: 500; margin-bottom: 6px; line-height: 20px; color: var(--pj-ink); }
|
||||
.pj-meet-plan-head { display: flex; align-items: center; flex-wrap: nowrap; gap: 6px; min-width: 0; font-size: var(--pj-text-size); font-weight: 500; margin-bottom: 6px; line-height: 20px; color: var(--pj-ink); }
|
||||
.pj-meet-plan-head .material-symbols-outlined { font-size: 18px; color: var(--pj-accent); }
|
||||
.pj-meet-plan-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 6px; }
|
||||
.pj-meet-plan-area { padding: 6px 8px; border-radius: 8px; background: var(--goal-bg, #f4f5f7); font-size: 12px; line-height: 1.45; min-width: 0; }
|
||||
@@ -2516,13 +2698,35 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important;
|
||||
.pj-meet-plan-item + .pj-meet-plan-item { margin-top: 2px; }
|
||||
.pj-meet-plan-label { flex: none; font-weight: 700; color: #3b4048; }
|
||||
.pj-meet-plan-label::after { content: ":"; }
|
||||
.pj-meet-plan-text { white-space: pre-line; overflow-wrap: anywhere; }
|
||||
.pj-meet-plan-text { white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.pj-meet-plan-item em { flex: none; margin-left: auto; font-style: normal; font-size: 10.5px; color: var(--pj-ink-soft); }
|
||||
.pj-meet-plan-empty { margin: 0; font-size: 12px; color: var(--pj-ink-soft); }
|
||||
|
||||
/* 참석자 — 멤버 칩 + [참석자] 고르기 창(body 에 붙음) */
|
||||
.pj-meet-attend { display: flex; align-items: flex-start; gap: 8px; margin: 0 0 10px; font-size: 12.5px; }
|
||||
.pj-meet-attend-label { font-weight: 600; color: var(--pj-ink-soft); line-height: 30px; flex: none; }
|
||||
/* 회의 완료(잠금) — 관리자 버튼 · 완료 표시 */
|
||||
.pj-meet-complete-btn { gap: 4px; background: #e7f6ec; border-color: #b9e3c8; color: #1f7a44; }
|
||||
.pj-meet-complete-btn:hover { background: #d6f0df; }
|
||||
.pj-meet-complete-btn .material-symbols-outlined, .pj-meet-done-badge .material-symbols-outlined { font-size: 16px; }
|
||||
.pj-meet-done-badge {
|
||||
display: inline-flex; align-items: center; gap: 4px; height: 28px; padding: 0 10px; border-radius: 999px;
|
||||
background: #eef0f3; color: #4b5563; font-size: 12.5px; font-weight: 700;
|
||||
}
|
||||
/* 회의록 보드 — 파워포인트 색(#D24726)의 파스텔톤 */
|
||||
.pj-meet-board-btn {
|
||||
flex: none; align-self: center; gap: 4px;
|
||||
background: #fde8e1; border-color: #f5c3b3; color: #b7472a;
|
||||
}
|
||||
.pj-meet-board-btn:hover { background: #fbd8cc; border-color: #eea78f; color: #a33d22; }
|
||||
.pj-meet-board-btn:disabled { opacity: .6; }
|
||||
/* 회의록 보드 링크 복사(아이콘) — 보드 버튼 바로 오른쪽 */
|
||||
.pj-meet-board-copy { flex: none; align-self: center; margin-left: -4px; width: 30px; height: 30px; border-radius: 8px; color: #b7472a; }
|
||||
.pj-meet-board-copy:hover { background: #fde8e1; }
|
||||
.pj-meet-board-copy .material-symbols-outlined { font-size: 19px; }
|
||||
@media print { .pj-meet-board-copy { display: none !important; } }
|
||||
.pj-meet-board-btn .material-symbols-outlined { font-size: 17px; color: #d24726; }
|
||||
@media print { .pj-meet-board-btn { display: none !important; } }
|
||||
.pj-meet-attend-chips { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; min-height: 30px; padding: 2px; border-radius: 8px; }
|
||||
.pj-meet-chip {
|
||||
display: inline-flex; align-items: center; gap: 5px; height: 28px; padding: 0 4px 0 3px; border: 1px solid var(--pj-border);
|
||||
@@ -2567,11 +2771,11 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important;
|
||||
}
|
||||
.pj-meet-table tr > :last-child { border-right: none; }
|
||||
.pj-meet-table thead th {
|
||||
position: sticky; top: 0; z-index: 3; background: #f7f8f9; height: 32px; padding: 0 8px; font-weight: 700;
|
||||
position: sticky; top: var(--pj-meet-top-h, 0px); z-index: 3; background: #f7f8f9; height: 32px; padding: 0 8px; font-weight: 700;
|
||||
text-align: center; vertical-align: middle; white-space: nowrap;
|
||||
}
|
||||
.pj-meet-table thead tr.pj-meet-group th { top: 0; height: 26px; font-size: 12px; }
|
||||
.pj-meet-table thead tr:nth-child(2) th { top: 26px; }
|
||||
.pj-meet-table thead tr.pj-meet-group th { top: var(--pj-meet-top-h, 0px); height: 26px; font-size: 12px; }
|
||||
.pj-meet-table thead tr:nth-child(2) th { top: calc(var(--pj-meet-top-h, 0px) + 26px); }
|
||||
.pj-meet-table thead th.is-this { background: #fff7ed; color: #9a4b0b; }
|
||||
/* 이번주 ↔ 지난주 순서 바꾸기 버튼(표 왼쪽 위 빈 칸) */
|
||||
.pj-meet-order-cell { vertical-align: middle; }
|
||||
@@ -2587,64 +2791,59 @@ html.pj-goal-selecting, html.pj-goal-selecting * { user-select: none !important;
|
||||
.pj-meet-w-sec { width: 80px; }
|
||||
.pj-meet-w-label { width: 160px; }
|
||||
.pj-meet-w-amt { width: 122px; }
|
||||
.pj-meet-w-rate { width: 76px; }
|
||||
.pj-meet-w-eval { width: 88px; }
|
||||
.pj-meet-sec > tr > th, .pj-meet-sec > tr > td:not(.is-prev) { background: var(--goal-bg, #fff); border-color: rgba(0, 0, 0, .07); }
|
||||
.pj-meet-sec > tr > td.is-prev { background: #fafbfc; }
|
||||
.pj-meet-sec > tr:first-child > * { border-top: 1px solid rgba(0, 0, 0, .12); }
|
||||
.pj-meet-sec th { padding: 7px 8px; vertical-align: middle; text-align: center; }
|
||||
th.pj-meet-c-sec { position: relative; font-size: 13px; font-weight: 800; }
|
||||
.pj-meet-sec th { padding: 6px 8px; vertical-align: middle; text-align: center; } /* 구역·항목은 항상 세로 가운데 */
|
||||
th.pj-meet-c-sec { position: relative; font-size: 13px; font-weight: 800; vertical-align: middle; }
|
||||
.pj-meet-sec-add {
|
||||
display: block; margin: 4px auto 0; width: 22px; height: 22px; border: 1px dashed rgba(0, 0, 0, .25); border-radius: 6px;
|
||||
position: absolute; right: 4px; bottom: 4px; display: block; margin: 0; width: 22px; height: 22px; border: 1px dashed rgba(0, 0, 0, .25); border-radius: 6px;
|
||||
background: rgba(255, 255, 255, .6); color: var(--pj-ink-soft); cursor: pointer; line-height: 18px; opacity: 0; transition: opacity .12s;
|
||||
}
|
||||
th.pj-meet-c-sec:hover .pj-meet-sec-add, .pj-meet-sec-add:focus { opacity: 1; }
|
||||
th.pj-meet-c-label { position: relative; font-weight: 600; color: #3b4048; text-align: left; }
|
||||
.pj-meet-label { word-break: keep-all; overflow-wrap: anywhere; }
|
||||
.pj-meet-label-line { display: flex; align-items: baseline; gap: 6px; min-width: 0; }
|
||||
.pj-meet-label { min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.pj-meet-label[data-meet-edit] { cursor: text; border-radius: 5px; padding: 1px 3px; margin: -1px -3px; }
|
||||
.pj-meet-label[data-meet-edit]:hover { background: rgba(255, 255, 255, .65); box-shadow: 0 0 0 1px rgba(0, 0, 0, .14); }
|
||||
.pj-meet-label.is-editing { background: #fff; box-shadow: 0 0 0 2px var(--pj-accent); outline: none; }
|
||||
.pj-meet-label[data-meet-edit]:empty { display: inline-block; min-width: 3em; min-height: 1.4em; }
|
||||
.pj-meet-market {
|
||||
display: inline-block; margin-left: 4px; padding: 0 6px; border-radius: 999px; font-size: 10.5px; font-weight: 700;
|
||||
background: #e8f1ff; color: #1d4ed8; vertical-align: 1px;
|
||||
}
|
||||
.pj-meet-more { position: absolute; top: 3px; right: 2px; width: 24px; height: 24px; opacity: 0; transition: opacity .12s; }
|
||||
.pj-meet-more .material-symbols-outlined { font-size: 18px; }
|
||||
th.pj-meet-c-label:hover .pj-meet-more, .pj-meet-more:focus { opacity: 1; }
|
||||
textarea.pj-meet-text, .pj-meet-notes textarea {
|
||||
textarea.pj-meet-text, textarea.pj-meet-rnote, .pj-meet-notes textarea {
|
||||
display: block; width: 100%; box-sizing: border-box; min-height: 38px; padding: 6px; border: none; background: transparent;
|
||||
font: inherit; line-height: var(--pj-text-leading); color: inherit; resize: none; overflow: hidden;
|
||||
}
|
||||
textarea.pj-meet-text:focus { outline: none; }
|
||||
textarea.pj-meet-text:focus, textarea.pj-meet-rnote:focus { outline: none; }
|
||||
textarea.pj-meet-rnote { min-height: calc(var(--pj-text-leading) + 12px); padding: 6px; }
|
||||
textarea.pj-meet-rnote::placeholder { color: rgba(0, 0, 0, .28); }
|
||||
/* 같은 행의 가장 긴 내용으로 높이를 정하고, 짧은 셀은 위에서 시작한다. */
|
||||
textarea.pj-meet-text { min-height: calc(var(--pj-text-leading) + 12px); }
|
||||
.pj-meet-notes textarea:focus { outline: 2px solid var(--pj-accent); outline-offset: -2px; background: rgba(255, 255, 255, .8); }
|
||||
/* 입력 중인 칸 — 칸 전체(td) 테두리 */
|
||||
.pj-meet-table td:focus-within:not(.pj-meet-c-eval) {
|
||||
.pj-meet-table td:focus-within {
|
||||
box-shadow: inset 0 0 0 2px var(--pj-accent);
|
||||
background-image: linear-gradient(rgba(255, 255, 255, .8), rgba(255, 255, 255, .8));
|
||||
}
|
||||
.pj-meet-ro { min-height: 38px; padding: 6px; line-height: var(--pj-text-leading); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.pj-meet-table td.pj-meet-c-amt { text-align: right; vertical-align: middle; padding: 0 6px; font-variant-numeric: tabular-nums; }
|
||||
.pj-meet-ro { box-sizing: border-box; min-height: calc(var(--pj-text-leading) + 12px); padding: 6px; line-height: var(--pj-text-leading); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.pj-meet-table td.pj-meet-c-amt { text-align: right; vertical-align: top; padding: 6px 10px; font-variant-numeric: tabular-nums; }
|
||||
input.pj-meet-amount {
|
||||
display: block; width: 100%; box-sizing: border-box; height: 34px; padding: 0 4px; border: none; background: transparent;
|
||||
font: inherit; text-align: right; font-variant-numeric: tabular-nums;
|
||||
display: block; width: 100%; box-sizing: border-box; height: var(--pj-text-leading); padding: 0; border: none; background: transparent;
|
||||
font: inherit; line-height: var(--pj-text-leading); text-align: right; font-variant-numeric: tabular-nums;
|
||||
}
|
||||
input.pj-meet-amount:focus { outline: none; background: transparent; }
|
||||
.pj-meet-kpi input.pj-meet-amount:focus { outline: 2px solid var(--pj-accent); outline-offset: -1px; }
|
||||
input.pj-meet-amount::placeholder { color: rgba(0, 0, 0, .28); }
|
||||
.pj-meet-auto { color: #1d4ed8; font-weight: 600; }
|
||||
.pj-meet-market.is-off { background: #fdecec; color: #b42318; }
|
||||
.pj-meet-week-auto { display: block; padding: 0 4px 5px; font-size: 11px; color: #1d4ed8; text-align: right; white-space: nowrap; }
|
||||
.pj-meet-auto::before { content: "자동 "; font-size: 10.5px; font-weight: 700; color: #6b8fd6; }
|
||||
.pj-meet-c-rate { text-align: right; vertical-align: middle !important; padding: 0 6px !important; font-weight: 700; }
|
||||
.pj-meet-c-rate .is-good { color: #1f8a4c; }
|
||||
.pj-meet-c-rate .is-low { color: #c2410c; }
|
||||
.pj-meet-c-eval { vertical-align: middle !important; text-align: center; }
|
||||
select.pj-meet-eval { width: calc(100% - 8px); height: 28px; margin: 0 4px; border: 1px solid var(--pj-border); border-radius: 6px; background: #fff; font: inherit; }
|
||||
select.pj-meet-eval[data-v="done"], .pj-meet-eval-ro[data-v="done"] { color: #1f8a4c; font-weight: 700; }
|
||||
select.pj-meet-eval[data-v="partial"], .pj-meet-eval-ro[data-v="partial"] { color: #b45309; font-weight: 700; }
|
||||
select.pj-meet-eval[data-v="miss"], .pj-meet-eval-ro[data-v="miss"] { color: #c22b10; font-weight: 700; }
|
||||
.pj-meet-table td.is-none { vertical-align: middle; padding: 0 8px; font-size: 12px; }
|
||||
.pj-meet-table td.is-none { vertical-align: top; padding: 6px 8px; font-size: 12px; }
|
||||
.pj-meet-table tbody td, .pj-meet-table tbody th { position: relative; }
|
||||
.pj-meet-colresize { position: absolute; top: 0; right: -3px; bottom: 0; width: 6px; z-index: 5; cursor: col-resize; }
|
||||
.pj-meet-colresize:hover { background: rgba(123, 104, 238, .22); }
|
||||
.pj-meet-table td.is-merge-sel, .pj-meet-table td.is-goal-active { box-shadow: inset 0 0 0 2px var(--pj-accent); }
|
||||
.pj-meet-table td.is-goal-move-target { box-shadow: inset 0 0 0 3px var(--pj-accent); background-image: linear-gradient(var(--pj-accent-tint), var(--pj-accent-tint)); }
|
||||
.pj-meet-table td.is-goal-move-saving { pointer-events: none; opacity: .65; }
|
||||
.pj-meet-ro span { line-height: normal; }
|
||||
@media print { .pj-meet-colresize, .pj-meet-table .pj-goal-move-edge { display: none !important; } }
|
||||
.pj-meet-table td.is-saved, .pj-meet-table th.is-saved, .pj-meet-notes textarea.is-saved, #pj-meet-attendees.is-saved {
|
||||
animation: pj-goal-saved 1s ease-out;
|
||||
}
|
||||
@@ -2657,10 +2856,70 @@ select.pj-meet-eval[data-v="miss"], .pj-meet-eval-ro[data-v="miss"] { color: #c2
|
||||
.erp-sidebar, .erp-topbar, .pj-side, .pj-goal-head-acts, .pj-meet-weeks, .pj-goal-foot, .pj-meet-more, .pj-meet-sec-add,
|
||||
.pj-meet-goalbtn, .pj-meet-title .pj-btn { display: none !important; }
|
||||
.pj-meet-pane { overflow: visible; }
|
||||
.pj-meet-top { position: static; }
|
||||
.pj-meet-table thead th { position: static; }
|
||||
input.pj-meet-amount, select.pj-meet-eval { border: none; appearance: none; }
|
||||
input.pj-meet-amount { border: none; appearance: none; }
|
||||
}
|
||||
|
||||
/* 목표 표 — 매출 목표 칸(주차별 입력, 020): 누르면 주차 입력 창 */
|
||||
.pj-goal-numtd.is-weekly .pj-goal-num { cursor: pointer; }
|
||||
.pj-goal-numtd.is-weekly input.pj-goal-num:hover { background: var(--pj-accent-tint); }
|
||||
.pj-goal-wkpop {
|
||||
position: fixed; z-index: 1000; width: 330px; padding: 10px 12px; background: #fff; border: 1px solid var(--pj-border);
|
||||
border-radius: 10px; box-shadow: 0 8px 24px rgba(16, 24, 40, .16); font-size: 13px;
|
||||
}
|
||||
.pj-goal-wkpop-head { font-weight: 700; margin-bottom: 8px; }
|
||||
.pj-goal-wkpop-head small { font-weight: 500; color: var(--pj-ink-soft); }
|
||||
.pj-goal-wkpop-row { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: 4px 0; }
|
||||
.pj-goal-wkpop-row em { font-style: normal; color: var(--pj-ink-soft); font-size: 12px; }
|
||||
.pj-goal-wkpop-days {
|
||||
font-style: normal; display: inline-block; margin-left: 2px; padding: 0 6px; border-radius: 999px; background: #f1f3f6;
|
||||
color: var(--pj-ink-soft); font-size: 11px; font-weight: 600; line-height: 18px;
|
||||
}
|
||||
.pj-goal-wkpop-row input {
|
||||
width: 100px; height: 26px; padding: 0 6px; border: 1px solid var(--pj-border); border-radius: 6px; font: inherit;
|
||||
text-align: right; font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.pj-goal-wkpop-row input[readonly] { background: #f7f8f9; }
|
||||
.pj-goal-wkpop-sum { display: flex; justify-content: space-between; margin-top: 8px; padding-top: 8px; border-top: 1px solid var(--pj-border); }
|
||||
.pj-goal-wkpop-sum b { font-variant-numeric: tabular-nums; }
|
||||
/* 월 전체 목표(직접 입력) — 주차 줄과 구분선 */
|
||||
.pj-goal-wkpop-month { padding-bottom: 8px; margin-bottom: 8px; border-bottom: 1px solid var(--pj-border); font-weight: 700; }
|
||||
/* 차이 = 월 목표 − 주차 합계 — 남음(+) 주황, 넘음(−) 빨강, 딱 맞음 초록 */
|
||||
.pj-goal-wkpop-diff { margin-top: 4px; padding-top: 0; border-top: 0; }
|
||||
.pj-goal-wkpop-diff small { font-size: 11px; color: var(--pj-ink-soft); }
|
||||
.pj-goal-wkpop-diff b.is-left { color: #c2410c; }
|
||||
.pj-goal-wkpop-diff b.is-over { color: #dc2626; }
|
||||
.pj-goal-wkpop-diff b.is-even { color: #16a34a; }
|
||||
.pj-goal-wkpop-acts { display: flex; justify-content: flex-end; gap: 6px; margin-top: 10px; }
|
||||
|
||||
/* 나를 태그·작업 배정 알림 — 화면 가운데 아래 큰 팝업(body 에 붙음), 닫기 전까지 깜박인다(2026-10-07) */
|
||||
.pj-alert-pop {
|
||||
position: fixed; left: 50%; bottom: 28px; z-index: 1100; transform: translateX(-50%); width: min(560px, calc(100vw - 32px));
|
||||
max-height: 46vh; display: flex; flex-direction: column; background: #fff; border: 2px solid var(--pj-accent);
|
||||
border-radius: 16px; box-shadow: 0 18px 50px rgba(16, 24, 40, .28); overflow: hidden;
|
||||
animation: pj-alert-blink 1s ease-in-out infinite;
|
||||
}
|
||||
@keyframes pj-alert-blink {
|
||||
0%, 100% { border-color: var(--pj-accent); box-shadow: 0 18px 50px rgba(16, 24, 40, .28), 0 0 0 0 rgba(124, 92, 255, .55); }
|
||||
50% { border-color: #ff6b4a; box-shadow: 0 18px 50px rgba(16, 24, 40, .28), 0 0 0 10px rgba(255, 107, 74, .18); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .pj-alert-pop { animation: none; border-color: #ff6b4a; } }
|
||||
.pj-alert-head { display: flex; align-items: center; gap: 8px; padding: 12px 14px; background: #fff4f0; border-bottom: 1px solid #f6d6cc; }
|
||||
.pj-alert-head .material-symbols-outlined { color: #e5532f; font-size: 22px; }
|
||||
.pj-alert-head b { flex: 1 1 auto; font-size: 15px; }
|
||||
.pj-alert-list { overflow-y: auto; padding: 6px; }
|
||||
.pj-alert-item { display: flex; align-items: center; gap: 10px; padding: 10px 10px; border-radius: 10px; color: var(--pj-ink); text-decoration: none; }
|
||||
.pj-alert-item:hover { background: #f5f6f8; }
|
||||
.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; }
|
||||
.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; }
|
||||
.pj-alert-go { flex: none; font-size: 12.5px; font-weight: 600; color: var(--pj-accent-dark); }
|
||||
@media print { .pj-alert-pop { display: none !important; } }
|
||||
|
||||
/* 영역 색 고르기 팝업(body 에 붙음) */
|
||||
.pj-goal-colorpop {
|
||||
position: fixed; z-index: 1000; display: grid; grid-template-columns: repeat(8, 26px); gap: 6px;
|
||||
@@ -2765,3 +3024,31 @@ html[data-pj-font="nanum-square-round"] { --pj-font: "NanumSquareRound", var(--p
|
||||
.pj-goal-text-swatch[aria-pressed="true"] { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
|
||||
.pj-goal-text-swatch:focus-visible { outline: 2px solid var(--pj-accent); outline-offset: 2px; }
|
||||
.pj-goal-format :disabled { opacity: .45; cursor: default; }
|
||||
|
||||
/* PC 알림 프로그램 화면(/project/notifier, 023) */
|
||||
.pj-notifier-pane { display: flex; flex-direction: column; gap: 14px; max-width: 760px; padding: 16px; }
|
||||
.pj-notifier-card { padding: 14px 16px; border: 1px solid var(--pj-border); border-radius: 12px; background: #fff; }
|
||||
.pj-notifier-card.is-link { border: 2px solid var(--pj-accent); background: #faf8ff; }
|
||||
.pj-notifier-card h3 { margin: 0 0 8px; font-size: 15px; }
|
||||
.pj-notifier-card p { margin: 6px 0; }
|
||||
.pj-notifier-code { font-family: ui-monospace, Consolas, monospace; font-size: 16px; letter-spacing: 1px; color: var(--pj-accent-dark); }
|
||||
.pj-notifier-note { color: var(--pj-ink-soft); font-size: 13px; }
|
||||
.pj-notifier-steps { margin: 4px 0 8px; padding-left: 20px; line-height: 1.9; }
|
||||
.pj-notifier-table { width: 100%; }
|
||||
.pj-notifier-back { color: var(--pj-ink-soft); text-decoration: none; }
|
||||
.pj-notifier-back:hover { color: var(--pj-accent-dark); text-decoration: underline; }
|
||||
.pj-inbox-notifier { display: inline-flex; align-items: center; gap: 4px; text-decoration: none; }
|
||||
.pj-inbox-notifier .material-symbols-outlined { font-size: 18px; }
|
||||
|
||||
/* 설명란 글자 색·크기 고르기(2026-10-08) — body 에 붙는 작은 창 */
|
||||
.pj-desc-stylepop {
|
||||
position: fixed; z-index: 1200; display: flex; gap: 4px; padding: 6px; background: #fff;
|
||||
border: 1px solid var(--pj-border); border-radius: 10px; box-shadow: 0 8px 24px rgba(16, 24, 40, .16);
|
||||
}
|
||||
.pj-desc-stylepop.is-size { flex-direction: column; min-width: 120px; }
|
||||
.pj-desc-stylepop button {
|
||||
border: none; background: transparent; border-radius: 6px; cursor: pointer; font: inherit; color: var(--pj-ink);
|
||||
padding: 4px 8px; text-align: left; line-height: 1.3;
|
||||
}
|
||||
.pj-desc-stylepop button:hover { background: #f1f2f4; }
|
||||
.pj-desc-colorchip { display: inline-block; width: 22px; text-align: center; font-weight: 700; font-size: 15px; }
|
||||
|
||||
+1485
-560
File diff suppressed because it is too large
Load Diff
+34
-3
@@ -87,8 +87,9 @@ a { color: inherit; text-decoration: none; }
|
||||
|
||||
.brand-logo-mark svg { color: #fff; }
|
||||
|
||||
/* 로그인 왼쪽 위 로고 — 가로 100px, 세로는 비율대로 */
|
||||
.brand-logo-img {
|
||||
width: auto;
|
||||
width: 100px;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
@@ -705,13 +706,43 @@ a { color: inherit; text-decoration: none; }
|
||||
color: rgba(255, 255, 255, .9);
|
||||
letter-spacing: 4px;
|
||||
text-transform: none;
|
||||
top: 28%;
|
||||
right: 7%;
|
||||
top: 30%;
|
||||
right: 26%;
|
||||
z-index: 2;
|
||||
animation: kingFloat 13s ease-in-out infinite, kingSparkle 2.4s ease-in-out infinite;
|
||||
white-space: nowrap;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
/* King 주위를 도는 사용자 아이디 — 위치·크기·투명도는 login.html 스크립트가 매 프레임 정한다 */
|
||||
.shape-orbit {
|
||||
top: 0;
|
||||
left: 0;
|
||||
font-size: 24px; /* King(30px)의 80% — 앞쪽에서 이 크기, 뒤쪽은 스크립트가 75%까지 줄인다 */
|
||||
font-weight: 700;
|
||||
letter-spacing: 2px;
|
||||
color: rgba(255, 255, 255, .88);
|
||||
white-space: nowrap;
|
||||
user-select: none;
|
||||
will-change: transform, opacity;
|
||||
/* King 과 같은 반짝임(빛 번짐만 — 투명도는 앞뒤 깊이로 스크립트가 정함). 시작 시점은 사람마다 무작위 */
|
||||
animation: orbitSparkle 2.4s ease-in-out infinite;
|
||||
}
|
||||
@keyframes orbitSparkle {
|
||||
0%, 100% {
|
||||
text-shadow:
|
||||
0 0 8px rgba(255, 255, 255, .6),
|
||||
0 0 18px rgba(99, 179, 237, .5);
|
||||
}
|
||||
50% {
|
||||
text-shadow:
|
||||
0 0 16px rgba(255, 255, 255, 1),
|
||||
0 0 36px rgba(99, 179, 237, 1),
|
||||
0 0 56px rgba(147, 197, 253, .9),
|
||||
0 0 80px rgba(59, 130, 246, .6);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes shapeFloat1 {
|
||||
0%, 100% { transform: translate(0, 0); }
|
||||
25% { transform: translate(-22px, 32px); }
|
||||
|
||||
Binary file not shown.
+10
-2
@@ -33,6 +33,7 @@ MODULE_KEYS: tuple[str, ...] = (
|
||||
"project",
|
||||
"cafe24",
|
||||
"performance",
|
||||
"asset",
|
||||
"expense_approver",
|
||||
"vacation_approver",
|
||||
)
|
||||
@@ -40,6 +41,13 @@ MODULE_KEYS: tuple[str, ...] = (
|
||||
# 승인자 권한 키 — 결재 워크플로에서 별도 검사할 때 사용
|
||||
APPROVER_KEYS: tuple[str, ...] = ("expense_approver", "vacation_approver")
|
||||
|
||||
# 관리자 등급(2026-10-12) — 수퍼관리자(SUPER_ADMIN_EMAIL 한 명, 고정·추가 불가) > admin > pro > user.
|
||||
# 저장하는 role 값은 admin / pro / user 셋뿐 — 수퍼관리자는 role 이 아니라 이메일로 정해진다.
|
||||
# pro 는 프로젝트 모듈(프로젝트·목표·주간 회의록)에서만 admin 에 가까운 권한을 받고
|
||||
# (app/modules/project/access.py), 다른 모듈과 관리자 페이지에서는 user 와 같다(is_admin False).
|
||||
ROLES: tuple[str, ...] = ("admin", "pro", "user")
|
||||
ROLE_LABELS: dict[str, str] = {"admin": "Admin", "pro": "Pro user", "user": "User"}
|
||||
|
||||
|
||||
def _now_iso() -> str:
|
||||
return now_kst_iso()
|
||||
@@ -120,7 +128,7 @@ class UserStore:
|
||||
email = email.lower().strip()
|
||||
if not email or "@" not in email:
|
||||
raise ValueError("올바른 이메일 형식이 아닙니다.")
|
||||
if role not in ("admin", "user"):
|
||||
if role not in ROLES:
|
||||
raise ValueError(f"role 값이 잘못되었습니다: {role}")
|
||||
is_super = email == SUPER_ADMIN_EMAIL
|
||||
with self._lock:
|
||||
@@ -186,7 +194,7 @@ class UserStore:
|
||||
email = email.lower().strip()
|
||||
if email == SUPER_ADMIN_EMAIL:
|
||||
raise PermissionError("슈퍼 관리자 계정은 수정할 수 없습니다.")
|
||||
if role is not None and role not in ("admin", "user"):
|
||||
if role is not None and role not in ROLES:
|
||||
raise ValueError(f"role 값이 잘못되었습니다: {role}")
|
||||
with self._lock:
|
||||
data = self._read()
|
||||
|
||||
@@ -97,8 +97,9 @@
|
||||
<input type="email" name="email" required placeholder="email@dbxcorp.co.kr" style="width: 220px;" />
|
||||
<input type="text" name="name" placeholder="이름(선택)" style="width: 120px;" />
|
||||
<select name="role">
|
||||
<option value="user">user</option>
|
||||
<option value="admin">admin</option>
|
||||
{% for r in roles | reverse %}
|
||||
<option value="{{ r }}">{{ role_labels[r] }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
<button type="submit" class="erp-btn erp-btn-primary">사용자 추가</button>
|
||||
</form>
|
||||
@@ -109,7 +110,7 @@
|
||||
<thead>
|
||||
<tr>
|
||||
<th style="width: 200px;">사용자</th>
|
||||
<th style="width: 80px;">역할</th>
|
||||
<th style="width: 110px;">등급</th>
|
||||
<th>접근 권한 <span class="erp-mod-group">클릭하여 토글</span></th>
|
||||
<th style="width: 110px;">최근 로그인</th>
|
||||
<th style="width: 130px; text-align: right;">동작</th>
|
||||
@@ -138,11 +139,18 @@
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<select class="erp-select" data-field="role"
|
||||
{% if u.is_super_admin %}disabled{% endif %}>
|
||||
<option value="user" {% if u.role == 'user' %}selected{% endif %}>user</option>
|
||||
<option value="admin" {% if u.role == 'admin' %}selected{% endif %}>admin</option>
|
||||
{# 수퍼관리자는 한 명으로 고정 — 등급을 바꾸거나 다른 사람을 수퍼관리자로 만들 수 없다. #}
|
||||
{% if u.is_super_admin %}
|
||||
<select class="erp-select" data-field="role" disabled>
|
||||
<option value="admin" selected>수퍼관리자</option>
|
||||
</select>
|
||||
{% else %}
|
||||
<select class="erp-select" data-field="role">
|
||||
{% for r in roles %}
|
||||
<option value="{{ r }}" {% if u.role == r %}selected{% endif %}>{{ role_labels[r] }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
{% endif %}
|
||||
</td>
|
||||
<td class="erp-perm-cell">
|
||||
{% for key in module_keys %}
|
||||
@@ -175,8 +183,10 @@
|
||||
</div>
|
||||
|
||||
<p class="erp-section-meta" style="margin-top: var(--sp-16);">
|
||||
※ <strong>{{ super_admin_email }}</strong> 은(는) 슈퍼 관리자, 권한 변경/삭제 불가(항상 전체 접근).
|
||||
admin 역할은 기본 전체 ON 이지만 슈퍼관리자가 개별 프로그램 접근을 끌 수 있다.
|
||||
※ 등급: <strong>수퍼관리자</strong>(<strong>{{ super_admin_email }}</strong> 한 명 고정 — 권한 변경/삭제 불가, 항상 전체 접근, 더 추가할 수 없음)
|
||||
> <strong>Admin</strong> > <strong>Pro user</strong> > <strong>User</strong>.
|
||||
Admin 은 기본 전체 ON 이지만 슈퍼관리자가 개별 프로그램 접근을 끌 수 있다.
|
||||
Pro user 는 Project 모듈(프로젝트·목표·주간 회의록)에서 프로젝트 만들기·수정·멤버 배정·휴지통·목표 입력·회의 완료 등을 할 수 있고, 다른 모듈에서는 User 와 같다.
|
||||
<code>expense_approver</code> / <code>vacation_approver</code> 는 결재 승인 권한.
|
||||
</p>
|
||||
|
||||
|
||||
@@ -7,43 +7,6 @@
|
||||
<h2 class="erp-hero-title">안녕하세요, {{ user.name }}님</h2>
|
||||
<p class="erp-hero-sub" id="erp-hero-sub"></p>
|
||||
</div>
|
||||
|
||||
<div class="erp-home-grid">
|
||||
|
||||
<article class="erp-tile">
|
||||
<div class="erp-tile-head">
|
||||
<span class="erp-tile-label">바로가기</span>
|
||||
<span class="erp-badge erp-badge-neutral">개인업무</span>
|
||||
</div>
|
||||
<h3 class="erp-tile-title">개인경비</h3>
|
||||
<p class="erp-tile-desc">법인카드/개인지출 등록과 정산 신청.</p>
|
||||
<a class="erp-btn erp-btn-primary" href="/expense/">개인경비 열기</a>
|
||||
</article>
|
||||
|
||||
<article class="erp-tile">
|
||||
<div class="erp-tile-head">
|
||||
<span class="erp-tile-label">바로가기</span>
|
||||
<span class="erp-badge erp-badge-outline">준비중</span>
|
||||
</div>
|
||||
<h3 class="erp-tile-title">휴가</h3>
|
||||
<p class="erp-tile-desc">연차/반차 신청과 잔여일수 확인.</p>
|
||||
<button class="erp-btn erp-btn-outline" disabled>오픈 예정</button>
|
||||
</article>
|
||||
|
||||
<article class="erp-tile">
|
||||
<div class="erp-tile-head">
|
||||
<span class="erp-tile-label">알림</span>
|
||||
<span class="erp-badge erp-badge-outline">공지</span>
|
||||
</div>
|
||||
<h3 class="erp-tile-title">시스템 안내</h3>
|
||||
<ul class="erp-tile-list">
|
||||
<li>좌측 메뉴에서 사용 가능한 업무 모듈을 확인하세요.</li>
|
||||
<li>외부 모듈(주문/CORM)은 새 창에서 열립니다.</li>
|
||||
<li>권한이 필요한 모듈은 관리자에게 요청하세요.</li>
|
||||
</ul>
|
||||
</article>
|
||||
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<script>
|
||||
|
||||
@@ -19,7 +19,9 @@
|
||||
<div class="shape shape-4"></div>
|
||||
<div class="shape shape-5"></div>
|
||||
<div class="shape shape-6"></div>
|
||||
<div class="shape shape-king">King</div>
|
||||
<div class="shape shape-king" id="orbit-king">King</div>
|
||||
{# 등록 사용자 아이디 — King 주위를 사람마다 다른 무작위 곡선으로 돈다(아래 스크립트) #}
|
||||
{% for n in orbit_names or [] %}<div class="shape shape-orbit">{{ n }}</div>{% endfor %}
|
||||
</div>
|
||||
|
||||
<div class="brand-logo">
|
||||
@@ -74,5 +76,48 @@
|
||||
</main>
|
||||
|
||||
</div>
|
||||
<script>
|
||||
// King 을 중심으로 사용자 아이디가 돈다 — 사람마다 반지름·속도·방향·기울기·흔들림이 무작위인 타원 곡선.
|
||||
// King 자체도 CSS(kingFloat)로 떠다니므로 매 프레임 King 의 지금 위치를 중심으로 삼는다. 뒤쪽(위)은 작고 흐리게.
|
||||
(function () {
|
||||
var box = document.querySelector(".brand-shapes");
|
||||
var king = document.getElementById("orbit-king");
|
||||
var els = Array.prototype.slice.call(document.querySelectorAll(".shape-orbit"));
|
||||
if (!box || !king || !els.length) return;
|
||||
var reduce = window.matchMedia && window.matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
function rnd(a, b) { return a + Math.random() * (b - a); }
|
||||
var n = els.length;
|
||||
var orbs = els.map(function (el, i) {
|
||||
el.style.animationDelay = (-Math.random() * 2.4).toFixed(2) + "s"; // 반짝임이 한꺼번에 맞지 않게
|
||||
return {
|
||||
el: el,
|
||||
base: (i / n) * Math.PI * 2 + rnd(-0.4, 0.4),
|
||||
rx: rnd(80, 200), ry: rnd(50, 140),
|
||||
speed: rnd(0.018, 0.045) * (Math.random() < 0.5 ? -1 : 1), // 초당 바퀴 수
|
||||
tilt: rnd(-0.6, 0.6),
|
||||
wa: rnd(10, 30), wf: rnd(0.15, 0.5), wp: rnd(0, 6.28),
|
||||
wb: rnd(8, 30), wg: rnd(0.12, 0.45), wq: rnd(0, 6.28)
|
||||
};
|
||||
});
|
||||
function place(t) {
|
||||
var b = box.getBoundingClientRect(), k = king.getBoundingClientRect();
|
||||
var cx = k.left - b.left + k.width / 2, cy = k.top - b.top + k.height / 2;
|
||||
orbs.forEach(function (o) {
|
||||
var a = o.base + t * o.speed * Math.PI * 2;
|
||||
var x0 = Math.cos(a) * (o.rx + Math.sin(t * o.wf + o.wp) * o.wa);
|
||||
var y0 = Math.sin(a) * (o.ry + Math.sin(t * o.wg + o.wq) * o.wb);
|
||||
var x = x0 * Math.cos(o.tilt) - y0 * Math.sin(o.tilt);
|
||||
var y = x0 * Math.sin(o.tilt) + y0 * Math.cos(o.tilt);
|
||||
var depth = (Math.sin(a) + 1) / 2; // 0 = 뒤(위), 1 = 앞(아래)
|
||||
o.el.style.transform = "translate(" + (cx + x).toFixed(1) + "px," + (cy + y).toFixed(1) + "px) translate(-50%,-50%) scale(" + (0.75 + depth * 0.25).toFixed(3) + ")";
|
||||
o.el.style.opacity = (0.4 + depth * 0.5).toFixed(2);
|
||||
o.el.style.zIndex = depth > 0.5 ? 3 : 1;
|
||||
});
|
||||
}
|
||||
if (reduce) { place(0); return; }
|
||||
function frame(ms) { place(ms / 1000); requestAnimationFrame(frame); }
|
||||
requestAnimationFrame(frame);
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
bin/
|
||||
obj/
|
||||
dist/
|
||||
@@ -0,0 +1,355 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Drawing2D;
|
||||
using System.Drawing.Imaging;
|
||||
using System.Drawing.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace DbxNotifier
|
||||
{
|
||||
/// <summary>
|
||||
/// 큰 알림 창 — 웹 프로젝트 화면의 큰 팝업(.pj-alert-pop)과 같은 모양: 흰 카드·둥근 모서리 16·연분홍 머리(종 + "새 알림 N건" + 닫기)·
|
||||
/// 줄마다 배지(작업 배정/나를 태그)·굵은 제목·회색 둘째 줄·"열기 ›", 보라↔주황으로 1초마다 깜박이는 테두리와 빛.
|
||||
/// 다른 프로그램 위(맨 위)에 뜨지만 포커스는 빼앗지 않는다(입력 중이던 창 그대로). 둥근 모서리·그림자를 위해
|
||||
/// 픽셀 단위 투명 창(UpdateLayeredWindow)으로 직접 그린다.
|
||||
/// </summary>
|
||||
internal sealed class AlertForm : Form
|
||||
{
|
||||
public event Action<Alert> OpenClicked;
|
||||
public event Action CloseClicked;
|
||||
public event Action MoreClicked;
|
||||
|
||||
private const int MaxRows = 6;
|
||||
private const float CardW = 560, HeadH = 54, RowH = 62, Pad = 6, MoreH = 38, ShadowM = 40, BottomGap = 28, Radius = 16;
|
||||
|
||||
private static readonly Color Accent = Gfx.Hex("#7b68ee");
|
||||
private static readonly Color AccentDark = Gfx.Hex("#6453d6");
|
||||
private static readonly Color Orange = Gfx.Hex("#ff6b4a");
|
||||
private static readonly Color Ink = Gfx.Hex("#050505");
|
||||
private static readonly Color InkSoft = Gfx.Hex("#636363");
|
||||
private const string FontName = "Malgun Gothic";
|
||||
|
||||
private readonly List<Alert> _items = new List<Alert>();
|
||||
private readonly List<RectangleF> _rows = new List<RectangleF>();
|
||||
private readonly Timer _blink = new Timer { Interval = 70 };
|
||||
private readonly DateTime _t0 = DateTime.Now;
|
||||
private int _total;
|
||||
private float _s = 1f, _fontScale = -1f;
|
||||
private RectangleF _card, _close, _more;
|
||||
private int _hoverRow = -1;
|
||||
private bool _hoverClose, _hoverMore;
|
||||
private Font _fHead, _fTitle, _fSmall, _fBadge, _fGo, _fBtn;
|
||||
|
||||
public AlertForm()
|
||||
{
|
||||
FormBorderStyle = FormBorderStyle.None;
|
||||
ShowInTaskbar = false;
|
||||
StartPosition = FormStartPosition.Manual;
|
||||
TopMost = true;
|
||||
Text = "DBX 알림";
|
||||
_blink.Tick += (s, e) => Render();
|
||||
}
|
||||
|
||||
protected override CreateParams CreateParams
|
||||
{
|
||||
get
|
||||
{
|
||||
CreateParams cp = base.CreateParams;
|
||||
cp.ExStyle |= WS_EX_LAYERED | WS_EX_TOOLWINDOW | WS_EX_TOPMOST | WS_EX_NOACTIVATE;
|
||||
return cp;
|
||||
}
|
||||
}
|
||||
|
||||
protected override bool ShowWithoutActivation => true;
|
||||
|
||||
/// <summary>알림 목록을 보여 준다(처음이면 띄우고, 이미 떠 있으면 내용만 바꾼다).</summary>
|
||||
public void SetAlerts(IList<Alert> all)
|
||||
{
|
||||
_items.Clear();
|
||||
for (int i = 0; i < all.Count && i < MaxRows; i++) _items.Add(all[i]);
|
||||
_total = all.Count;
|
||||
_hoverRow = -1;
|
||||
_hoverClose = _hoverMore = false;
|
||||
if (!IsHandleCreated) CreateHandle();
|
||||
LayoutCard();
|
||||
Render();
|
||||
if (!Visible) Show();
|
||||
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW);
|
||||
_blink.Start();
|
||||
}
|
||||
|
||||
public void HidePopup()
|
||||
{
|
||||
_blink.Stop();
|
||||
Hide();
|
||||
}
|
||||
|
||||
private void EnsureFonts()
|
||||
{
|
||||
if (Math.Abs(_fontScale - _s) < 0.01f) return;
|
||||
DisposeFonts();
|
||||
_fontScale = _s;
|
||||
_fHead = new Font(FontName, 15f * _s, FontStyle.Bold, GraphicsUnit.Pixel);
|
||||
_fTitle = new Font(FontName, 14.5f * _s, FontStyle.Bold, GraphicsUnit.Pixel);
|
||||
_fSmall = new Font(FontName, 12f * _s, FontStyle.Regular, GraphicsUnit.Pixel);
|
||||
_fBadge = new Font(FontName, 11.5f * _s, FontStyle.Bold, GraphicsUnit.Pixel);
|
||||
_fGo = new Font(FontName, 12.5f * _s, FontStyle.Bold, GraphicsUnit.Pixel);
|
||||
_fBtn = new Font(FontName, 13f * _s, FontStyle.Regular, GraphicsUnit.Pixel);
|
||||
}
|
||||
|
||||
private void DisposeFonts()
|
||||
{
|
||||
foreach (Font f in new[] { _fHead, _fTitle, _fSmall, _fBadge, _fGo, _fBtn }) f?.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>카드 크기·위치 — 마우스가 있는 화면의 작업 영역 아래 가운데(웹 팝업처럼 아래에서 28px 위).</summary>
|
||||
private void LayoutCard()
|
||||
{
|
||||
_s = Gfx.SystemScale();
|
||||
EnsureFonts();
|
||||
int extra = _total - _items.Count;
|
||||
float cardH = HeadH + Pad * 2 + _items.Count * RowH + (extra > 0 ? MoreH : 0);
|
||||
float m = ShadowM * _s;
|
||||
_card = new RectangleF(m, m, CardW * _s, cardH * _s);
|
||||
_close = new RectangleF(_card.Right - 72 * _s, _card.Y + (HeadH - 32) / 2 * _s, 58 * _s, 32 * _s);
|
||||
_rows.Clear();
|
||||
float y = _card.Y + (HeadH + Pad) * _s;
|
||||
foreach (Alert _ in _items)
|
||||
{
|
||||
_rows.Add(new RectangleF(_card.X + Pad * _s, y, _card.Width - 2 * Pad * _s, RowH * _s));
|
||||
y += RowH * _s;
|
||||
}
|
||||
_more = extra > 0 ? new RectangleF(_card.X + Pad * _s, y, _card.Width - 2 * Pad * _s, MoreH * _s) : RectangleF.Empty;
|
||||
|
||||
int bw = (int)Math.Ceiling(_card.Width + 2 * m), bh = (int)Math.Ceiling(_card.Height + 2 * m);
|
||||
Rectangle wa = Screen.FromPoint(Cursor.Position).WorkingArea;
|
||||
int x = wa.Left + (wa.Width - bw) / 2;
|
||||
int top = (int)(wa.Bottom - BottomGap * _s - _card.Height - m);
|
||||
Bounds = new Rectangle(x, Math.Max(wa.Top, top), bw, bh);
|
||||
}
|
||||
|
||||
private static void DrawText(Graphics g, string t, Font f, Color c, RectangleF r,
|
||||
StringAlignment h = StringAlignment.Near, StringAlignment v = StringAlignment.Center)
|
||||
{
|
||||
// GenericTypographic — 한글 글자 사이가 벌어지지 않게(기본 StringFormat 은 글자마다 여백을 둔다)
|
||||
using (var sf = (StringFormat)StringFormat.GenericTypographic.Clone())
|
||||
using (var b = new SolidBrush(c))
|
||||
{
|
||||
sf.FormatFlags |= StringFormatFlags.NoWrap;
|
||||
sf.Trimming = StringTrimming.EllipsisCharacter;
|
||||
sf.Alignment = h;
|
||||
sf.LineAlignment = v;
|
||||
g.DrawString(t ?? "", f, b, r, sf);
|
||||
}
|
||||
}
|
||||
|
||||
private static void Fill(Graphics g, RectangleF r, float radius, Color c)
|
||||
{
|
||||
using (GraphicsPath p = Gfx.Round(r, radius))
|
||||
using (var b = new SolidBrush(c))
|
||||
g.FillPath(b, p);
|
||||
}
|
||||
|
||||
private void Render()
|
||||
{
|
||||
if (!IsHandleCreated || Width <= 0 || Height <= 0) return;
|
||||
double phase = (DateTime.Now - _t0).TotalSeconds % 1.0;
|
||||
double k = (1 - Math.Cos(phase * 2 * Math.PI)) / 2; // 0 → 1 → 0 (보라 → 주황 → 보라)
|
||||
float s = _s, rad = Radius * s;
|
||||
RectangleF c = _card;
|
||||
|
||||
using (var bmp = new Bitmap(Width, Height, PixelFormat.Format32bppArgb))
|
||||
using (Graphics g = Graphics.FromImage(bmp))
|
||||
{
|
||||
g.SmoothingMode = SmoothingMode.AntiAlias;
|
||||
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
|
||||
g.TextRenderingHint = TextRenderingHint.AntiAlias;
|
||||
g.Clear(Color.Transparent);
|
||||
|
||||
// 그림자(0 18px 50px rgba(16,24,40,.28) 비슷하게 — 겹겹이 옅게)
|
||||
for (int i = 12; i >= 1; i--)
|
||||
{
|
||||
RectangleF r = c;
|
||||
r.Offset(0, 12 * s);
|
||||
r.Inflate(i * 2.2f * s, i * 2.2f * s);
|
||||
Fill(g, r, rad + i * 2.2f * s, Color.FromArgb(6, 16, 24, 40));
|
||||
}
|
||||
// 깜박이는 주황 빛(0 0 0 10px rgba(255,107,74,.18))
|
||||
if (k > 0.02)
|
||||
{
|
||||
RectangleF r = c;
|
||||
float sp = (float)(k * 10 * s);
|
||||
r.Inflate(sp, sp);
|
||||
Fill(g, r, rad + sp, Color.FromArgb((int)(k * 0.18 * 255), Orange));
|
||||
}
|
||||
|
||||
using (GraphicsPath cardPath = Gfx.Round(c, rad))
|
||||
{
|
||||
using (var b = new SolidBrush(Color.White)) g.FillPath(b, cardPath);
|
||||
GraphicsState gs = g.Save();
|
||||
g.SetClip(cardPath, CombineMode.Intersect);
|
||||
|
||||
var head = new RectangleF(c.X, c.Y, c.Width, HeadH * s);
|
||||
using (var b = new SolidBrush(Gfx.Hex("#fff4f0"))) g.FillRectangle(b, head);
|
||||
using (var p = new Pen(Gfx.Hex("#f6d6cc"), Math.Max(1f, s))) g.DrawLine(p, c.X, head.Bottom, c.Right, head.Bottom);
|
||||
Gfx.Bell(g, new RectangleF(c.X + 16 * s, head.Y + (HeadH - 24) / 2 * s, 24 * s, 24 * s), Gfx.Hex("#e5532f"));
|
||||
DrawText(g, "새 알림 " + _total + "건", _fHead, Ink, new RectangleF(c.X + 50 * s, head.Y, _close.X - c.X - 60 * s, head.Height));
|
||||
|
||||
Fill(g, _close, 8 * s, _hoverClose ? Gfx.Hex("#f2f4f7") : Color.White);
|
||||
using (GraphicsPath bp = Gfx.Round(_close, 8 * s))
|
||||
using (var p = new Pen(Gfx.Hex("#d0d5dd"), Math.Max(1f, s)))
|
||||
g.DrawPath(p, bp);
|
||||
DrawText(g, "닫기", _fBtn, Gfx.Hex("#344054"), _close, StringAlignment.Center);
|
||||
|
||||
for (int i = 0; i < _items.Count; i++) DrawRow(g, _items[i], _rows[i], i == _hoverRow);
|
||||
|
||||
if (!_more.IsEmpty)
|
||||
{
|
||||
if (_hoverMore) Fill(g, _more, 10 * s, Gfx.Hex("#f5f6f8"));
|
||||
DrawText(g, "외 " + (_total - _items.Count) + "건 더 — 수신함에서 보기 ›", _fGo, AccentDark, _more, StringAlignment.Center);
|
||||
}
|
||||
g.Restore(gs);
|
||||
|
||||
RectangleF br = c;
|
||||
br.Inflate(-s, -s);
|
||||
using (GraphicsPath bp = Gfx.Round(br, rad - s))
|
||||
using (var pen = new Pen(Gfx.Mix(Accent, Orange, k), 2 * s))
|
||||
g.DrawPath(pen, bp);
|
||||
}
|
||||
Push(bmp);
|
||||
}
|
||||
}
|
||||
|
||||
private void DrawRow(Graphics g, Alert a, RectangleF r, bool hover)
|
||||
{
|
||||
float s = _s;
|
||||
if (hover) Fill(g, r, 10 * s, Gfx.Hex("#f5f6f8"));
|
||||
|
||||
string kind = 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);
|
||||
|
||||
const string go = "열기 ›";
|
||||
SizeF gsz = g.MeasureString(go, _fGo, PointF.Empty, StringFormat.GenericTypographic);
|
||||
float goX = r.Right - 12 * s - gsz.Width;
|
||||
DrawText(g, go, _fGo, AccentDark, new RectangleF(goX - 2 * s, r.Y, gsz.Width + 8 * s, r.Height));
|
||||
|
||||
float tx = kr.Right + 12 * s, tw = Math.Max(10, goX - 14 * s - tx);
|
||||
DrawText(g, a.CleanTitle, _fTitle, Ink, new RectangleF(tx, r.Y + 8 * s, tw, 24 * s));
|
||||
DrawText(g, a.SubLine, _fSmall, InkSoft, new RectangleF(tx, r.Y + 33 * s, tw, 20 * s));
|
||||
}
|
||||
|
||||
protected override void OnMouseMove(MouseEventArgs e)
|
||||
{
|
||||
base.OnMouseMove(e);
|
||||
int row = -1;
|
||||
for (int i = 0; i < _rows.Count; i++) if (_rows[i].Contains(e.Location)) row = i;
|
||||
bool close = _close.Contains(e.Location);
|
||||
bool more = !_more.IsEmpty && _more.Contains(e.Location);
|
||||
if (row != _hoverRow || close != _hoverClose || more != _hoverMore)
|
||||
{
|
||||
_hoverRow = row;
|
||||
_hoverClose = close;
|
||||
_hoverMore = more;
|
||||
Render();
|
||||
}
|
||||
Cursor = row >= 0 || close || more ? Cursors.Hand : Cursors.Default;
|
||||
}
|
||||
|
||||
protected override void OnMouseLeave(EventArgs e)
|
||||
{
|
||||
base.OnMouseLeave(e);
|
||||
_hoverRow = -1;
|
||||
_hoverClose = _hoverMore = false;
|
||||
Render();
|
||||
}
|
||||
|
||||
protected override void OnMouseUp(MouseEventArgs e)
|
||||
{
|
||||
base.OnMouseUp(e);
|
||||
if (e.Button != MouseButtons.Left) return;
|
||||
if (_close.Contains(e.Location)) { CloseClicked?.Invoke(); return; }
|
||||
if (!_more.IsEmpty && _more.Contains(e.Location)) { MoreClicked?.Invoke(); return; }
|
||||
for (int i = 0; i < _rows.Count; i++)
|
||||
if (_rows[i].Contains(e.Location)) { OpenClicked?.Invoke(_items[i]); return; }
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing)
|
||||
{
|
||||
_blink.Dispose();
|
||||
DisposeFonts();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
// ── Win32: 픽셀 단위 투명 창 ──
|
||||
private void Push(Bitmap bmp)
|
||||
{
|
||||
IntPtr screenDc = GetDC(IntPtr.Zero);
|
||||
IntPtr memDc = CreateCompatibleDC(screenDc);
|
||||
IntPtr hBmp = IntPtr.Zero, old = IntPtr.Zero;
|
||||
try
|
||||
{
|
||||
hBmp = bmp.GetHbitmap(Color.FromArgb(0));
|
||||
old = SelectObject(memDc, hBmp);
|
||||
var size = new SIZE { cx = bmp.Width, cy = bmp.Height };
|
||||
var src = new POINT();
|
||||
var dst = new POINT { x = Left, y = Top };
|
||||
var blend = new BLENDFUNCTION { BlendOp = 0, BlendFlags = 0, SourceConstantAlpha = 255, AlphaFormat = 1 };
|
||||
UpdateLayeredWindow(Handle, screenDc, ref dst, ref size, memDc, ref src, 0, ref blend, ULW_ALPHA);
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (old != IntPtr.Zero) SelectObject(memDc, old);
|
||||
if (hBmp != IntPtr.Zero) DeleteObject(hBmp);
|
||||
DeleteDC(memDc);
|
||||
ReleaseDC(IntPtr.Zero, screenDc);
|
||||
}
|
||||
}
|
||||
|
||||
private const int WS_EX_LAYERED = 0x80000, WS_EX_TOOLWINDOW = 0x80, WS_EX_TOPMOST = 0x8, WS_EX_NOACTIVATE = 0x08000000;
|
||||
private const int ULW_ALPHA = 2;
|
||||
private const uint SWP_NOSIZE = 0x1, SWP_NOMOVE = 0x2, SWP_NOACTIVATE = 0x10, SWP_SHOWWINDOW = 0x40;
|
||||
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct POINT { public int x, y; }
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct SIZE { public int cx, cy; }
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 1)]
|
||||
private struct BLENDFUNCTION { public byte BlendOp, BlendFlags, SourceConstantAlpha, AlphaFormat; }
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
private static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref POINT pptDst, ref SIZE psize,
|
||||
IntPtr hdcSrc, ref POINT pptSrc, int crKey, ref BLENDFUNCTION pblend, int dwFlags);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int cx, int cy, uint flags);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetDC(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern int ReleaseDC(IntPtr hWnd, IntPtr hDC);
|
||||
|
||||
[DllImport("gdi32.dll")]
|
||||
private static extern IntPtr CreateCompatibleDC(IntPtr hDC);
|
||||
|
||||
[DllImport("gdi32.dll")]
|
||||
private static extern bool DeleteDC(IntPtr hdc);
|
||||
|
||||
[DllImport("gdi32.dll")]
|
||||
private static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
|
||||
|
||||
[DllImport("gdi32.dll")]
|
||||
private static extern bool DeleteObject(IntPtr hObject);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Net.Http;
|
||||
using System.Net.Http.Headers;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Script.Serialization;
|
||||
|
||||
namespace DbxNotifier
|
||||
{
|
||||
internal sealed class Alert
|
||||
{
|
||||
public long Id;
|
||||
public string Type = "";
|
||||
public string Title = "";
|
||||
public string Body = "";
|
||||
public string Actor = "";
|
||||
public long TaskId;
|
||||
public long ProjectId;
|
||||
|
||||
public bool IsMention => Type == "mention";
|
||||
|
||||
/// <summary>제목 앞 "나를 태그함: " / "작업 배정: " 은 배지로 보여 주므로 뗀다(웹 팝업과 같게).</summary>
|
||||
public string CleanTitle
|
||||
{
|
||||
get
|
||||
{
|
||||
foreach (string p in new[] { "나를 태그함:", "작업 배정:" })
|
||||
if (Title.StartsWith(p, StringComparison.Ordinal)) return Title.Substring(p.Length).Trim();
|
||||
return Title;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>둘째 줄 — "본문 · 보낸 사람 아이디"(웹 팝업과 같게).</summary>
|
||||
public string SubLine
|
||||
{
|
||||
get
|
||||
{
|
||||
string who = Actor;
|
||||
int at = who.IndexOf('@');
|
||||
if (at > 0) who = who.Substring(0, at);
|
||||
if (who.Length > 0) who = char.ToUpperInvariant(who[0]) + who.Substring(1);
|
||||
if (Body.Length > 0 && who.Length > 0) return Body + " · " + who;
|
||||
return Body.Length > 0 ? Body : who;
|
||||
}
|
||||
}
|
||||
|
||||
// 작업 알림은 공유 링크(/project/t/{id}) — 서버가 지금 권한으로 열 수 있는 프로젝트(연결된 프로젝트 포함)로
|
||||
// 보낸다. 원 소속 주소로 열면 연결된 프로젝트에서만 읽을 수 있는 사람에게 403 이 났다.
|
||||
public string Path => TaskId > 0
|
||||
? "/project/t/" + TaskId
|
||||
: ProjectId > 0 ? "/project/p/" + ProjectId : "/project/inbox";
|
||||
}
|
||||
|
||||
internal sealed class AlertResult
|
||||
{
|
||||
public string Name = "";
|
||||
public long LatestId;
|
||||
public List<Alert> Alerts = new List<Alert>();
|
||||
}
|
||||
|
||||
internal sealed class ApiException : Exception
|
||||
{
|
||||
public readonly int Status;
|
||||
|
||||
public ApiException(int status, string message) : base(message) { Status = status; }
|
||||
}
|
||||
|
||||
/// <summary>ERP 서버 호출 — HTTPS 로 우리 서버(설정한 주소)만 부른다. 토큰은 Authorization 헤더로만 보낸다.</summary>
|
||||
internal sealed class Api : IDisposable
|
||||
{
|
||||
private readonly HttpClient _http;
|
||||
private static readonly JavaScriptSerializer Json = new JavaScriptSerializer();
|
||||
|
||||
public Api()
|
||||
{
|
||||
_http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) };
|
||||
_http.DefaultRequestHeaders.UserAgent.ParseAdd("DBXNotifier/" + typeof(Api).Assembly.GetName().Version.ToString(3));
|
||||
}
|
||||
|
||||
public void Dispose() => _http.Dispose();
|
||||
|
||||
/// <summary>서버 주소 검사 — https 만(개발용 http://localhost·127.0.0.1 예외).</summary>
|
||||
public static string NormalizeServer(string raw)
|
||||
{
|
||||
string s = (raw ?? "").Trim().TrimEnd('/');
|
||||
if (!Uri.TryCreate(s, UriKind.Absolute, out Uri u) || (u.AbsolutePath != "/" && u.AbsolutePath.Length > 0))
|
||||
throw new ArgumentException("ERP 주소가 올바르지 않습니다. 예: " + Settings.DefaultServer);
|
||||
bool local = u.Host == "localhost" || u.Host == "127.0.0.1";
|
||||
if (u.Scheme != Uri.UriSchemeHttps && !(local && u.Scheme == Uri.UriSchemeHttp))
|
||||
throw new ArgumentException("ERP 주소는 https:// 로 시작해야 합니다.");
|
||||
return u.GetLeftPart(UriPartial.Authority);
|
||||
}
|
||||
|
||||
private async Task<Dictionary<string, object>> Send(HttpMethod method, string url, string token, object body)
|
||||
{
|
||||
using (var req = new HttpRequestMessage(method, url))
|
||||
{
|
||||
if (!string.IsNullOrEmpty(token)) req.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||
if (body != null) req.Content = new StringContent(Json.Serialize(body), Encoding.UTF8, "application/json");
|
||||
using (HttpResponseMessage res = await _http.SendAsync(req).ConfigureAwait(false))
|
||||
{
|
||||
string text = await res.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||
Dictionary<string, object> d = null;
|
||||
try { d = Json.Deserialize<Dictionary<string, object>>(text); } catch { /* HTML 오류 화면 등 */ }
|
||||
if (!res.IsSuccessStatusCode)
|
||||
{
|
||||
string detail = d != null && d.TryGetValue("detail", out var x) ? x as string : null;
|
||||
throw new ApiException((int)res.StatusCode, detail ?? ("서버 오류 HTTP " + (int)res.StatusCode));
|
||||
}
|
||||
return d ?? new Dictionary<string, object>();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string Str(Dictionary<string, object> d, string key) =>
|
||||
d.TryGetValue(key, out var v) && v != null ? Convert.ToString(v) : "";
|
||||
|
||||
private static long Num(Dictionary<string, object> d, string key) =>
|
||||
d.TryGetValue(key, out var v) && v != null ? Convert.ToInt64(v) : 0;
|
||||
|
||||
public async Task<(string Code, string Poll, string ApprovePath, int ExpiresIn)> StartLink(string server, string device)
|
||||
{
|
||||
var d = await Send(HttpMethod.Post, server + "/project/api/notifier/link/start", null, new { device }).ConfigureAwait(false);
|
||||
return (Str(d, "code"), Str(d, "poll"), Str(d, "approve_path"), (int)Num(d, "expires_in"));
|
||||
}
|
||||
|
||||
/// <summary>연결 확인 — status: pending | expired | ok(token, email).</summary>
|
||||
public async Task<(string Status, string Token, string Email)> PollLink(string server, string poll)
|
||||
{
|
||||
var d = await Send(HttpMethod.Post, server + "/project/api/notifier/link/poll", null, new { poll }).ConfigureAwait(false);
|
||||
return (Str(d, "status"), Str(d, "token"), Str(d, "email"));
|
||||
}
|
||||
|
||||
public async Task<AlertResult> Alerts(string server, string token, long after)
|
||||
{
|
||||
var d = await Send(HttpMethod.Get, server + "/project/api/notifier/alerts?after=" + after, token, null).ConfigureAwait(false);
|
||||
var r = new AlertResult { Name = Str(d, "name"), LatestId = Num(d, "latest_id") };
|
||||
if (d.TryGetValue("alerts", out var list) && list is IEnumerable items)
|
||||
{
|
||||
foreach (object o in items)
|
||||
{
|
||||
if (!(o is Dictionary<string, object> a)) continue;
|
||||
r.Alerts.Add(new Alert
|
||||
{
|
||||
Id = Num(a, "id"),
|
||||
Type = Str(a, "type"),
|
||||
Title = Str(a, "title"),
|
||||
Body = Str(a, "body"),
|
||||
Actor = Str(a, "actor_email"),
|
||||
TaskId = Num(a, "task_id"),
|
||||
ProjectId = Num(a, "project_id"),
|
||||
});
|
||||
}
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
public Task MarkRead(string server, string token, long id) =>
|
||||
Send(HttpMethod.Post, server + "/project/api/notifier/alerts/" + id + "/read", token, new { });
|
||||
|
||||
public Task Logout(string server, string token) =>
|
||||
Send(HttpMethod.Post, server + "/project/api/notifier/logout", token, new { });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Drawing;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace DbxNotifier
|
||||
{
|
||||
internal static class Browser
|
||||
{
|
||||
/// <summary>기본 브라우저로 연다. 실패하면 주소를 클립보드에 복사하고 false.</summary>
|
||||
public static bool Open(string url)
|
||||
{
|
||||
try
|
||||
{
|
||||
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
try { Clipboard.SetText(url); } catch { /* 클립보드 사용 중 */ }
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// PC 연결 창 — [브라우저에서 연결] → 서버가 준 코드를 크게 보여 주고 브라우저로 승인 화면(/project/notifier?code=)을 연다.
|
||||
/// 사용자가 브라우저(이미 로그인)에서 [연결]을 누르면 2초마다 확인하던 이 창이 토큰을 받아 닫힌다.
|
||||
/// </summary>
|
||||
internal sealed class ConnectForm : Form
|
||||
{
|
||||
public string Server { get; private set; } = "";
|
||||
public string Token { get; private set; } = "";
|
||||
public string Email { get; private set; } = "";
|
||||
public bool AutoStartChecked => _auto.Checked;
|
||||
|
||||
private readonly Api _api;
|
||||
private readonly TextBox _server;
|
||||
private readonly CheckBox _auto;
|
||||
private readonly Button _go;
|
||||
private readonly Label _code, _status;
|
||||
private readonly Timer _poll = new Timer { Interval = 2000 };
|
||||
private string _pollSecret = "", _approveUrl = "";
|
||||
private DateTime _expires;
|
||||
private bool _busy;
|
||||
|
||||
public ConnectForm(Api api, string server, bool autoStart)
|
||||
{
|
||||
_api = api;
|
||||
Text = "DBX 알림 — PC 연결";
|
||||
Icon = Gfx.AppIcon(new Size(32, 32));
|
||||
Font = new Font("Malgun Gothic", 9.75f);
|
||||
AutoScaleDimensions = new SizeF(96f, 96f);
|
||||
AutoScaleMode = AutoScaleMode.Dpi;
|
||||
FormBorderStyle = FormBorderStyle.FixedDialog;
|
||||
MaximizeBox = MinimizeBox = false;
|
||||
StartPosition = FormStartPosition.CenterScreen;
|
||||
ClientSize = new Size(440, 344);
|
||||
BackColor = Color.White;
|
||||
|
||||
Controls.Add(new Label
|
||||
{
|
||||
Text = "이 PC 에 ERP 알림(나를 태그·작업 배정)을 띄우려면\n내 ERP 계정에 연결하세요.",
|
||||
Location = new Point(20, 18), AutoSize = true, MaximumSize = new Size(400, 0),
|
||||
});
|
||||
Controls.Add(new Label { Text = "ERP 주소", Location = new Point(20, 84), AutoSize = true });
|
||||
_server = new TextBox { Text = server, Location = new Point(20, 106), Width = 400 };
|
||||
Controls.Add(_server);
|
||||
_auto = new CheckBox { Text = "Windows 시작 시 자동 실행", Checked = autoStart, Location = new Point(20, 140), AutoSize = true };
|
||||
Controls.Add(_auto);
|
||||
_go = new Button
|
||||
{
|
||||
Text = "브라우저에서 연결", Location = new Point(20, 174), Size = new Size(170, 34),
|
||||
BackColor = Gfx.Hex("#7b68ee"), ForeColor = Color.White, FlatStyle = FlatStyle.Flat,
|
||||
};
|
||||
_go.FlatAppearance.BorderSize = 0;
|
||||
_go.Click += (s, e) => OnGo();
|
||||
Controls.Add(_go);
|
||||
_code = new Label
|
||||
{
|
||||
Location = new Point(200, 172), Size = new Size(220, 38), Visible = false,
|
||||
Font = new Font("Consolas", 18f, FontStyle.Bold), ForeColor = Gfx.Hex("#6453d6"), TextAlign = ContentAlignment.MiddleCenter,
|
||||
BackColor = Gfx.Hex("#f4f1ff"),
|
||||
};
|
||||
Controls.Add(_code);
|
||||
_status = new Label { Location = new Point(20, 222), Size = new Size(400, 66), ForeColor = Gfx.Hex("#636363") };
|
||||
Controls.Add(_status);
|
||||
var close = new Button { Text = "닫기", Location = new Point(340, 298), Size = new Size(80, 30), DialogResult = DialogResult.Cancel };
|
||||
Controls.Add(close);
|
||||
CancelButton = close;
|
||||
AcceptButton = _go;
|
||||
|
||||
_poll.Tick += (s, e) => OnPoll();
|
||||
}
|
||||
|
||||
private async void OnGo()
|
||||
{
|
||||
if (_approveUrl.Length > 0) // 이미 코드를 받았으면 브라우저만 다시
|
||||
{
|
||||
OpenApprove();
|
||||
return;
|
||||
}
|
||||
string server;
|
||||
try { server = Api.NormalizeServer(_server.Text); }
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
_status.Text = ex.Message;
|
||||
return;
|
||||
}
|
||||
_go.Enabled = false;
|
||||
_server.Enabled = false;
|
||||
_status.Text = "연결 요청 중…";
|
||||
try
|
||||
{
|
||||
var r = await _api.StartLink(server, Environment.MachineName);
|
||||
Server = server;
|
||||
_pollSecret = r.Poll;
|
||||
_approveUrl = server + r.ApprovePath;
|
||||
_expires = DateTime.Now.AddSeconds(r.ExpiresIn > 0 ? r.ExpiresIn : 600);
|
||||
_code.Text = r.Code;
|
||||
_code.Visible = true;
|
||||
_go.Text = "브라우저 다시 열기";
|
||||
OpenApprove();
|
||||
_poll.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_status.Text = "연결 요청 실패: " + ex.Message;
|
||||
_server.Enabled = true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_go.Enabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void OpenApprove()
|
||||
{
|
||||
_status.Text = Browser.Open(_approveUrl)
|
||||
? "브라우저 화면의 연결 코드가 오른쪽 코드와 같은지 확인하고 [연결]을 누르세요.\n(10분 안에 — 연결되면 이 창은 저절로 닫힙니다.)"
|
||||
: "브라우저를 열지 못해 주소를 복사했습니다. 브라우저 주소창에 붙여 넣으세요.\n" + _approveUrl;
|
||||
}
|
||||
|
||||
private void Reset(string message)
|
||||
{
|
||||
_poll.Stop();
|
||||
_approveUrl = _pollSecret = "";
|
||||
_code.Visible = false;
|
||||
_go.Text = "브라우저에서 연결";
|
||||
_server.Enabled = true;
|
||||
_status.Text = message;
|
||||
}
|
||||
|
||||
private async void OnPoll()
|
||||
{
|
||||
if (_busy) return;
|
||||
if (DateTime.Now > _expires)
|
||||
{
|
||||
Reset("연결 코드가 만료됐습니다. [브라우저에서 연결]을 다시 누르세요.");
|
||||
return;
|
||||
}
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
var r = await _api.PollLink(Server, _pollSecret);
|
||||
if (r.Status == "ok" && r.Token.Length > 0)
|
||||
{
|
||||
_poll.Stop();
|
||||
Token = r.Token;
|
||||
Email = r.Email;
|
||||
DialogResult = DialogResult.OK;
|
||||
Close();
|
||||
}
|
||||
else if (r.Status == "expired")
|
||||
{
|
||||
Reset("연결 코드가 만료됐습니다. [브라우저에서 연결]을 다시 누르세요.");
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 네트워크 잠깐 끊김 — 다음 확인 때 다시
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing) _poll.Dispose();
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- DBX 알림(PC 트레이 프로그램). .NET Framework 4.8 — Windows 10(1903+)·11 에 기본 설치돼 있어 런타임 설치 없이
|
||||
exe 하나로 실행된다. 압축·난독화·자체 압축 해제(백신 오탐 주원인)를 쓰지 않는 평범한 관리 코드 exe. -->
|
||||
<PropertyGroup>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net48</TargetFramework>
|
||||
<LangVersion>latest</LangVersion>
|
||||
<AssemblyName>DBXNotifier</AssemblyName>
|
||||
<RootNamespace>DbxNotifier</RootNamespace>
|
||||
<ApplicationIcon>app.ico</ApplicationIcon>
|
||||
<ApplicationManifest>app.manifest</ApplicationManifest>
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
<Deterministic>true</Deterministic>
|
||||
<DebugType>none</DebugType>
|
||||
<GenerateDocumentationFile>false</GenerateDocumentationFile>
|
||||
<!-- 파일 속성(자세히) — 회사·제품·설명·버전이 채워진 exe 가 백신·SmartScreen 평판에 유리 -->
|
||||
<Version>1.0.0</Version>
|
||||
<FileVersion>1.0.0.0</FileVersion>
|
||||
<AssemblyVersion>1.0.0.0</AssemblyVersion>
|
||||
<Company>DBX</Company>
|
||||
<Product>DBX 알림</Product>
|
||||
<AssemblyTitle>DBX 알림</AssemblyTitle>
|
||||
<Description>DBX ERP 프로젝트 알림(태그·작업 배정)을 화면에 띄우는 트레이 프로그램</Description>
|
||||
<Copyright>© 2026 DBX</Copyright>
|
||||
<NeutralLanguage>ko-KR</NeutralLanguage>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System.Windows.Forms" />
|
||||
<Reference Include="System.Drawing" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Security" />
|
||||
<Reference Include="System.Web.Extensions" />
|
||||
<EmbeddedResource Include="app.ico" LogicalName="DbxNotifier.app.ico" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Remove="tools\**" />
|
||||
<None Remove="tools\**" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,83 @@
|
||||
using System;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Drawing2D;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace DbxNotifier
|
||||
{
|
||||
/// <summary>그리기 도우미 — 둥근 사각형, 종 아이콘, 색 섞기, 내장 아이콘.</summary>
|
||||
internal static class Gfx
|
||||
{
|
||||
public static GraphicsPath Round(RectangleF r, float radius)
|
||||
{
|
||||
var p = new GraphicsPath();
|
||||
float d = Math.Min(radius * 2, Math.Min(r.Width, r.Height));
|
||||
if (d <= 0.5f)
|
||||
{
|
||||
p.AddRectangle(r);
|
||||
return p;
|
||||
}
|
||||
p.AddArc(r.X, r.Y, d, d, 180, 90);
|
||||
p.AddArc(r.Right - d, r.Y, d, d, 270, 90);
|
||||
p.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90);
|
||||
p.AddArc(r.X, r.Bottom - d, d, d, 90, 90);
|
||||
p.CloseFigure();
|
||||
return p;
|
||||
}
|
||||
|
||||
public static Color Mix(Color a, Color b, double t) => Color.FromArgb(
|
||||
(int)(a.A + (b.A - a.A) * t), (int)(a.R + (b.R - a.R) * t),
|
||||
(int)(a.G + (b.G - a.G) * t), (int)(a.B + (b.B - a.B) * t));
|
||||
|
||||
public static Color Hex(string hex, int alpha = 255)
|
||||
{
|
||||
int v = Convert.ToInt32(hex.TrimStart('#'), 16);
|
||||
return Color.FromArgb(alpha, (v >> 16) & 255, (v >> 8) & 255, v & 255);
|
||||
}
|
||||
|
||||
/// <summary>울리는 종(웹 팝업 머리의 notifications_active 와 같은 느낌) — 24 격자를 r 에 맞춰 그린다.</summary>
|
||||
public static void Bell(Graphics g, RectangleF r, Color color)
|
||||
{
|
||||
GraphicsState st = g.Save();
|
||||
g.TranslateTransform(r.X, r.Y);
|
||||
g.ScaleTransform(r.Width / 24f, r.Height / 24f);
|
||||
using (var b = new SolidBrush(color))
|
||||
using (var body = new GraphicsPath())
|
||||
{
|
||||
body.AddLine(5f, 17f, 6.6f, 15.2f);
|
||||
body.AddLine(6.6f, 15.2f, 6.6f, 10.6f);
|
||||
body.AddBezier(6.6f, 10.6f, 6.6f, 7.2f, 9.0f, 4.9f, 12f, 4.9f);
|
||||
body.AddBezier(12f, 4.9f, 15.0f, 4.9f, 17.4f, 7.2f, 17.4f, 10.6f);
|
||||
body.AddLine(17.4f, 10.6f, 17.4f, 15.2f);
|
||||
body.AddLine(17.4f, 15.2f, 19f, 17f);
|
||||
body.CloseFigure();
|
||||
g.FillPath(b, body);
|
||||
g.FillEllipse(b, 10.1f, 16.7f, 3.8f, 3.8f);
|
||||
g.FillEllipse(b, 10.9f, 3.3f, 2.2f, 2.2f);
|
||||
}
|
||||
using (var pen = new Pen(color, 1.7f) { StartCap = LineCap.Round, EndCap = LineCap.Round })
|
||||
{
|
||||
g.DrawArc(pen, 2.4f, 1.0f, 19.2f, 19.2f, 198, 40);
|
||||
g.DrawArc(pen, 2.4f, 1.0f, 19.2f, 19.2f, 302, 40);
|
||||
}
|
||||
g.Restore(st);
|
||||
}
|
||||
|
||||
/// <summary>exe 에 넣은 app.ico 에서 원하는 크기 아이콘(트레이 = 작은 아이콘 크기).</summary>
|
||||
public static Icon AppIcon(Size size)
|
||||
{
|
||||
using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream("DbxNotifier.app.ico"))
|
||||
return s == null ? SystemIcons.Information : new Icon(s, size);
|
||||
}
|
||||
|
||||
public static Icon TrayIcon() => AppIcon(SystemInformation.SmallIconSize);
|
||||
|
||||
public static float SystemScale()
|
||||
{
|
||||
using (Graphics g = Graphics.FromHwnd(IntPtr.Zero))
|
||||
return Math.Max(1f, g.DpiX / 96f);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace DbxNotifier
|
||||
{
|
||||
internal static class Program
|
||||
{
|
||||
[STAThread]
|
||||
private static void Main(string[] args)
|
||||
{
|
||||
// 한 사용자 세션에 하나만 — 두 번 실행하면 안내만 하고 끝낸다.
|
||||
using (var mutex = new Mutex(true, @"Local\DBXNotifier.SingleInstance", out bool created))
|
||||
{
|
||||
if (!created)
|
||||
{
|
||||
MessageBox.Show("DBX 알림이 이미 실행 중입니다.\n화면 오른쪽 아래 트레이의 종 아이콘을 확인하세요.",
|
||||
"DBX 알림", MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
return;
|
||||
}
|
||||
Application.EnableVisualStyles();
|
||||
Application.SetCompatibleTextRenderingDefault(false);
|
||||
bool autostart = Array.IndexOf(args, "--autostart") >= 0;
|
||||
Application.Run(new TrayApp(autostart));
|
||||
GC.KeepAlive(mutex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
# DBX 알림 (PC 트레이 프로그램)
|
||||
|
||||
ERP 프로젝트에서 **나를 태그**하거나 **작업이 배정**되면, 브라우저가 뒤에 있어도 PC 화면 아래 가운데에
|
||||
웹 팝업과 같은 모양의 큰 알림 창을 띄운다. 서버 쪽 설명은 `docs/PROJECT_MODULE.md` 6-11.
|
||||
|
||||
- 실행 파일 하나(`DBXNotifier.exe`, 약 110KB), 설치 없음, 관리자 권한 불필요
|
||||
- 실행하면 트레이(오른쪽 아래)에 종 아이콘만 남는다 — 메모리 약 25~30MB(전용), 20초마다 서버 확인
|
||||
- 대상: Windows 10(1903 이후)·11 — 기본으로 들어 있는 .NET Framework 4.8 로 동작(런타임 설치 없음)
|
||||
|
||||
## 사용
|
||||
|
||||
1. `DBXNotifier.exe` 실행 → 연결 창에서 [브라우저에서 연결]
|
||||
2. 브라우저(ERP 로그인 상태)의 `/project/notifier` 화면에서 코드가 같은지 보고 [연결] → 연결 창이 저절로 닫힘
|
||||
3. 트레이 아이콘 메뉴: 지금 알림 확인 · ERP 수신함 열기 · 알림 소리 · Windows 시작 시 실행 · 연결 해제 · 종료
|
||||
(왼쪽 클릭 = 알림이 있으면 알림 창, 없으면 수신함)
|
||||
|
||||
설정: `%APPDATA%\DBXNotifier\settings.json` — 토큰은 Windows DPAPI(현재 사용자)로 암호화. 다른 PC·사용자로 복사해도 못 쓴다.
|
||||
연결 해제는 트레이 메뉴 또는 ERP `/project/notifier` 의 [연결 해제](분실 PC 등).
|
||||
|
||||
## 빌드
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File desktop\notifier\build.ps1 # → desktop\notifier\dist\DBXNotifier.exe
|
||||
```
|
||||
|
||||
.NET SDK(6 이상)가 있으면 된다. `net48` 참조 어셈블리는 빌드 때 NuGet 에서 자동으로 받는다.
|
||||
아이콘을 바꾸려면 `tools/make_icon.py`(Pillow) 수정 후 실행 → `app.ico`.
|
||||
|
||||
서버 내려받기 버튼에 올리기: `docs/DEPLOYMENT.md` "PC 알림 프로그램 마이그레이션 (023)".
|
||||
|
||||
## 백신·SmartScreen
|
||||
|
||||
오탐을 부르는 방식은 쓰지 않는다: 실행 파일 압축(UPX)·난독화·자체 압축 해제·다른 프로세스 주입·관리자 권한·숨은 다운로드 없음.
|
||||
평범한 관리 코드 exe 에 회사·제품·버전 정보가 채워져 있고, 통신은 설정한 ERP 주소(HTTPS)로만 한다.
|
||||
"Windows 시작 시 실행"은 사용자가 고른 경우에만 현재 사용자 Run 키에 등록한다.
|
||||
|
||||
그래도 **서명하지 않은 새 exe** 는 인터넷에서 받으면 Windows SmartScreen 이 "알 수 없는 게시자" 경고를 띄울 수 있다
|
||||
(백신의 바이러스 판정과는 다르다 — [추가 정보] → [실행]). 경고를 없애는 확실한 방법은 **코드 서명 인증서**(OV/EV)로 서명하는 것:
|
||||
`build.ps1` 이 `DBX_SIGN_PFX`·`DBX_SIGN_PASSWORD` 환경변수가 있으면 서명한다. 회사 백신 관리 콘솔이 있으면 `build.ps1` 이
|
||||
출력하는 SHA-256 을 허용 목록에 넣어도 된다.
|
||||
@@ -0,0 +1,134 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Web.Script.Serialization;
|
||||
using Microsoft.Win32;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace DbxNotifier
|
||||
{
|
||||
/// <summary>
|
||||
/// 설정 — %APPDATA%\DBXNotifier\settings.json. 연결 토큰은 Windows DPAPI(현재 사용자)로 암호화해 저장하므로
|
||||
/// 파일을 다른 PC·다른 사용자로 복사해도 쓸 수 없다.
|
||||
/// </summary>
|
||||
internal sealed class Settings
|
||||
{
|
||||
public const string DefaultServer = "https://dbx.no1king.freeddns.org";
|
||||
|
||||
public string Server = DefaultServer;
|
||||
public string Token = ""; // 원문은 메모리에서만
|
||||
public long LastSeen = -1; // 이 번호까지는 본 알림(닫기 누른 것). -1 = 처음(지금 최신을 기준으로)
|
||||
public bool Sound = true;
|
||||
public string UserName = "";
|
||||
|
||||
private static readonly byte[] Entropy = Encoding.UTF8.GetBytes("DBXNotifier.v1");
|
||||
|
||||
// DBX_NOTIFIER_DIR — 테스트용 설정 폴더(없으면 %APPDATA%\DBXNotifier)
|
||||
private static string Dir =>
|
||||
Environment.GetEnvironmentVariable("DBX_NOTIFIER_DIR") is string d && d.Length > 0
|
||||
? d
|
||||
: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "DBXNotifier");
|
||||
|
||||
private static string FilePath => Path.Combine(Dir, "settings.json");
|
||||
|
||||
public bool Connected => Token.Length > 0;
|
||||
|
||||
public static Settings Load()
|
||||
{
|
||||
var s = new Settings();
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath)) return s;
|
||||
var d = new JavaScriptSerializer().Deserialize<Dictionary<string, object>>(File.ReadAllText(FilePath, Encoding.UTF8));
|
||||
if (d == null) return s;
|
||||
if (d.TryGetValue("server", out var v) && v is string server && server.Length > 0) s.Server = server;
|
||||
if (d.TryGetValue("last_seen", out v) && v != null) s.LastSeen = Convert.ToInt64(v);
|
||||
if (d.TryGetValue("sound", out v) && v is bool sound) s.Sound = sound;
|
||||
if (d.TryGetValue("user_name", out v) && v is string name) s.UserName = name;
|
||||
if (d.TryGetValue("token", out v) && v is string enc && enc.Length > 0)
|
||||
{
|
||||
byte[] raw = ProtectedData.Unprotect(Convert.FromBase64String(enc), Entropy, DataProtectionScope.CurrentUser);
|
||||
s.Token = Encoding.UTF8.GetString(raw);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 깨진 설정은 처음 상태로 — 다시 연결하면 된다.
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
public void Save()
|
||||
{
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(Dir);
|
||||
string enc = Token.Length == 0
|
||||
? ""
|
||||
: Convert.ToBase64String(ProtectedData.Protect(Encoding.UTF8.GetBytes(Token), Entropy, DataProtectionScope.CurrentUser));
|
||||
var d = new Dictionary<string, object>
|
||||
{
|
||||
["server"] = Server,
|
||||
["last_seen"] = LastSeen,
|
||||
["sound"] = Sound,
|
||||
["user_name"] = UserName,
|
||||
["token"] = enc,
|
||||
};
|
||||
string tmp = FilePath + ".tmp";
|
||||
File.WriteAllText(tmp, new JavaScriptSerializer().Serialize(d), new UTF8Encoding(false));
|
||||
if (File.Exists(FilePath)) File.Replace(tmp, FilePath, null);
|
||||
else File.Move(tmp, FilePath);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 저장 실패는 다음 저장 때 다시
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Windows 시작 시 실행 — 현재 사용자 Run 키(관리자 권한 불필요). 사용자가 켜고 끈다.</summary>
|
||||
internal static class AutoStart
|
||||
{
|
||||
private const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
|
||||
private const string Name = "DBXNotifier";
|
||||
|
||||
private static string Command => "\"" + Application.ExecutablePath + "\" --autostart";
|
||||
|
||||
public static bool Enabled
|
||||
{
|
||||
get
|
||||
{
|
||||
using (var k = Registry.CurrentUser.OpenSubKey(RunKey))
|
||||
return k?.GetValue(Name) is string;
|
||||
}
|
||||
}
|
||||
|
||||
public static void Set(bool on)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var k = Registry.CurrentUser.CreateSubKey(RunKey))
|
||||
{
|
||||
if (on) k.SetValue(Name, Command);
|
||||
else k.DeleteValue(Name, false);
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 정책으로 막힌 PC — 메뉴 체크 표시만 그대로
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>exe 를 다른 폴더로 옮겼으면 등록된 경로를 지금 위치로.</summary>
|
||||
public static void RefreshPath()
|
||||
{
|
||||
using (var k = Registry.CurrentUser.OpenSubKey(RunKey))
|
||||
{
|
||||
if (k?.GetValue(Name) is string cur && !string.Equals(cur, Command, StringComparison.OrdinalIgnoreCase))
|
||||
Set(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Media;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace DbxNotifier
|
||||
{
|
||||
/// <summary>
|
||||
/// 트레이 상주 — 20초마다 서버(/project/api/notifier/alerts?after=본 것)를 확인해 새 태그·작업 배정 알림이 있으면 큰 알림 창.
|
||||
/// 웹 화면과 같은 규칙: 처음 연결하면 지금 최신 알림을 기준으로(옛 알림을 한꺼번에 띄우지 않음), [닫기] = 본 것으로,
|
||||
/// [열기] = 브라우저로 그 작업 + 읽음 처리. 다른 곳(웹)에서 읽으면 다음 확인 때 창에서도 빠진다.
|
||||
/// </summary>
|
||||
internal sealed class TrayApp : ApplicationContext
|
||||
{
|
||||
private const int PollMs = 20000;
|
||||
|
||||
private readonly Settings _cfg = Settings.Load();
|
||||
private readonly Api _api = new Api();
|
||||
private readonly Icon _icon;
|
||||
private readonly NotifyIcon _tray;
|
||||
private readonly ContextMenuStrip _menu;
|
||||
private readonly Timer _timer = new Timer { Interval = PollMs };
|
||||
private readonly ToolStripMenuItem _miStatus, _miCheck, _miOpen, _miSound, _miAuto, _miConnect;
|
||||
private readonly List<Alert> _pending = new List<Alert>();
|
||||
private readonly HashSet<long> _opened = new HashSet<long>();
|
||||
private AlertForm _popup;
|
||||
private ConnectForm _connect;
|
||||
private bool _busy;
|
||||
private string _problem = "";
|
||||
|
||||
public TrayApp(bool autostart)
|
||||
{
|
||||
_icon = Gfx.TrayIcon();
|
||||
_menu = new ContextMenuStrip { Font = new Font("Malgun Gothic", 9f) };
|
||||
_miStatus = new ToolStripMenuItem("DBX 알림") { Enabled = false };
|
||||
_miCheck = new ToolStripMenuItem("지금 알림 확인", null, async (s, e) => await Poll(true));
|
||||
_miOpen = new ToolStripMenuItem("ERP 수신함 열기", null, (s, e) => OpenPath("/project/inbox"));
|
||||
_miSound = new ToolStripMenuItem("알림 소리", null, (s, e) => { _cfg.Sound = !_cfg.Sound; _cfg.Save(); Sync(); });
|
||||
_miAuto = new ToolStripMenuItem("Windows 시작 시 실행", null, (s, e) => { AutoStart.Set(!AutoStart.Enabled); Sync(); });
|
||||
_miConnect = new ToolStripMenuItem("연결…", null, async (s, e) => { if (_cfg.Connected) await Disconnect(); else ShowConnect(); });
|
||||
var miExit = new ToolStripMenuItem("종료", null, (s, e) => ExitThread());
|
||||
_menu.Items.AddRange(new ToolStripItem[]
|
||||
{
|
||||
_miStatus, new ToolStripSeparator(), _miCheck, _miOpen, new ToolStripSeparator(),
|
||||
_miSound, _miAuto, _miConnect, new ToolStripSeparator(), miExit,
|
||||
});
|
||||
_menu.Opening += (s, e) => Sync();
|
||||
|
||||
_tray = new NotifyIcon { Icon = _icon, Text = "DBX 알림", ContextMenuStrip = _menu, Visible = true };
|
||||
_tray.MouseClick += (s, e) => { if (e.Button == MouseButtons.Left) OnTrayClick(); };
|
||||
_timer.Tick += async (s, e) => await Poll(false);
|
||||
SystemEvents.PowerModeChanged += OnPowerModeChanged;
|
||||
AutoStart.RefreshPath();
|
||||
Sync();
|
||||
|
||||
// 메시지 루프가 돈 뒤에 시작(창·풍선 도움말이 제대로 뜨게)
|
||||
var boot = new Timer { Interval = 300 };
|
||||
boot.Tick += async (s, e) =>
|
||||
{
|
||||
boot.Stop();
|
||||
boot.Dispose();
|
||||
if (_cfg.Connected)
|
||||
{
|
||||
_timer.Start();
|
||||
await Poll(false);
|
||||
}
|
||||
else if (autostart)
|
||||
{
|
||||
Balloon("DBX 알림 연결이 필요합니다", "트레이의 종 아이콘을 오른쪽 클릭해 [연결…]을 누르세요.");
|
||||
}
|
||||
else
|
||||
{
|
||||
ShowConnect();
|
||||
}
|
||||
};
|
||||
boot.Start();
|
||||
}
|
||||
|
||||
private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs e)
|
||||
{
|
||||
if (e.Mode == PowerModes.Resume) _ = Poll(false); // 절전에서 깨면 바로 확인
|
||||
}
|
||||
|
||||
private async Task Poll(bool manual)
|
||||
{
|
||||
if (!_cfg.Connected)
|
||||
{
|
||||
if (manual) ShowConnect();
|
||||
return;
|
||||
}
|
||||
if (_busy) return;
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
AlertResult r = await _api.Alerts(_cfg.Server, _cfg.Token, _cfg.LastSeen < 0 ? -1 : _cfg.LastSeen);
|
||||
_problem = "";
|
||||
if (r.Name.Length > 0 && r.Name != _cfg.UserName)
|
||||
{
|
||||
_cfg.UserName = r.Name;
|
||||
_cfg.Save();
|
||||
}
|
||||
if (_cfg.LastSeen < 0)
|
||||
{
|
||||
_cfg.LastSeen = r.LatestId; // 처음 — 지금까지 온 알림은 띄우지 않는다
|
||||
_cfg.Save();
|
||||
}
|
||||
else
|
||||
{
|
||||
Apply(r.Alerts);
|
||||
}
|
||||
if (manual && _pending.Count == 0) Balloon("새 알림 없음", "확인하지 않은 태그·작업 배정 알림이 없습니다.");
|
||||
}
|
||||
catch (ApiException ex) when (ex.Status == 401)
|
||||
{
|
||||
ClearConnection();
|
||||
Balloon("DBX 알림 연결이 해제되었습니다", ex.Message + "\n트레이 아이콘 메뉴의 [연결…]로 다시 연결하세요.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_problem = "서버에 연결할 수 없음 — 다시 시도 중";
|
||||
if (manual) Balloon("서버에 연결할 수 없습니다", ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
Sync();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>서버의 지금 목록으로 바꾼다 — 새 번호가 있으면 창을 띄우고 소리, 다른 곳에서 읽은 것은 빠진다.</summary>
|
||||
private void Apply(List<Alert> fresh)
|
||||
{
|
||||
fresh = fresh.Where(a => !_opened.Contains(a.Id)).ToList();
|
||||
var known = new HashSet<long>(_pending.Select(a => a.Id));
|
||||
bool added = fresh.Any(a => !known.Contains(a.Id));
|
||||
_pending.Clear();
|
||||
_pending.AddRange(fresh);
|
||||
if (_pending.Count == 0)
|
||||
{
|
||||
_popup?.HidePopup();
|
||||
return;
|
||||
}
|
||||
if (added)
|
||||
{
|
||||
ShowPopup();
|
||||
if (_cfg.Sound) SystemSounds.Exclamation.Play();
|
||||
}
|
||||
else if (_popup != null && _popup.Visible)
|
||||
{
|
||||
_popup.SetAlerts(_pending);
|
||||
}
|
||||
}
|
||||
|
||||
private void ShowPopup()
|
||||
{
|
||||
if (_popup == null)
|
||||
{
|
||||
_popup = new AlertForm();
|
||||
_popup.OpenClicked += OpenAlert;
|
||||
_popup.CloseClicked += CloseAll;
|
||||
_popup.MoreClicked += () =>
|
||||
{
|
||||
OpenPath("/project/inbox");
|
||||
CloseAll();
|
||||
};
|
||||
}
|
||||
_popup.SetAlerts(_pending);
|
||||
Sync();
|
||||
}
|
||||
|
||||
private void OpenAlert(Alert a)
|
||||
{
|
||||
OpenPath(a.Path);
|
||||
_opened.Add(a.Id);
|
||||
_ = MarkRead(a.Id);
|
||||
_pending.RemoveAll(x => x.Id == a.Id);
|
||||
if (_pending.Count == 0) CloseAll();
|
||||
else _popup.SetAlerts(_pending);
|
||||
Sync();
|
||||
}
|
||||
|
||||
private async Task MarkRead(long id)
|
||||
{
|
||||
try { await _api.MarkRead(_cfg.Server, _cfg.Token, id); }
|
||||
catch { /* 다음에 웹에서 읽어도 된다 */ }
|
||||
}
|
||||
|
||||
/// <summary>[닫기] — 지금 보이는 알림까지 본 것으로(다시 뜨지 않음).</summary>
|
||||
private void CloseAll()
|
||||
{
|
||||
long max = _cfg.LastSeen;
|
||||
foreach (Alert a in _pending) max = Math.Max(max, a.Id);
|
||||
foreach (long id in _opened) max = Math.Max(max, id);
|
||||
if (max != _cfg.LastSeen)
|
||||
{
|
||||
_cfg.LastSeen = max;
|
||||
_cfg.Save();
|
||||
}
|
||||
_pending.Clear();
|
||||
_opened.Clear();
|
||||
_popup?.HidePopup();
|
||||
Sync();
|
||||
}
|
||||
|
||||
private void OnTrayClick()
|
||||
{
|
||||
if (_pending.Count > 0) ShowPopup();
|
||||
else if (!_cfg.Connected) ShowConnect();
|
||||
else OpenPath("/project/inbox");
|
||||
}
|
||||
|
||||
private void OpenPath(string path) => Browser.Open(_cfg.Server + path);
|
||||
|
||||
private void ShowConnect()
|
||||
{
|
||||
if (_connect != null)
|
||||
{
|
||||
_connect.Activate();
|
||||
return;
|
||||
}
|
||||
_connect = new ConnectForm(_api, _cfg.Server, true);
|
||||
_connect.FormClosed += (s, e) =>
|
||||
{
|
||||
ConnectForm c = _connect;
|
||||
_connect = null;
|
||||
if (c.DialogResult != DialogResult.OK || c.Token.Length == 0) return;
|
||||
_cfg.Server = c.Server;
|
||||
_cfg.Token = c.Token;
|
||||
_cfg.LastSeen = -1;
|
||||
_cfg.Save();
|
||||
AutoStart.Set(c.AutoStartChecked);
|
||||
_timer.Start();
|
||||
Balloon("DBX 알림이 연결되었습니다", c.Email + " 님의 태그·작업 배정 알림을 이 PC 화면에 띄웁니다.");
|
||||
_ = Poll(false);
|
||||
};
|
||||
_connect.Show();
|
||||
_connect.Activate();
|
||||
}
|
||||
|
||||
private async Task Disconnect()
|
||||
{
|
||||
if (MessageBox.Show("이 PC 의 DBX 알림 연결을 해제할까요?\n해제하면 알림이 오지 않습니다.", "DBX 알림",
|
||||
MessageBoxButtons.OKCancel, MessageBoxIcon.Question) != DialogResult.OK) return;
|
||||
try { await _api.Logout(_cfg.Server, _cfg.Token); }
|
||||
catch { /* 서버에서도 해제할 수 있다(ERP > Project > 수신함 > PC 알림) */ }
|
||||
ClearConnection();
|
||||
}
|
||||
|
||||
private void ClearConnection()
|
||||
{
|
||||
_timer.Stop();
|
||||
_cfg.Token = "";
|
||||
_cfg.LastSeen = -1;
|
||||
_cfg.UserName = "";
|
||||
_cfg.Save();
|
||||
_pending.Clear();
|
||||
_opened.Clear();
|
||||
_popup?.HidePopup();
|
||||
Sync();
|
||||
}
|
||||
|
||||
private void Balloon(string title, string text) => _tray.ShowBalloonTip(6000, title, text, ToolTipIcon.Info);
|
||||
|
||||
private void Sync()
|
||||
{
|
||||
bool on = _cfg.Connected;
|
||||
string who = _cfg.UserName.Length > 0 ? _cfg.UserName : "연결됨";
|
||||
_miStatus.Text = on ? "DBX 알림 — " + who : "DBX 알림 — 연결 안 됨";
|
||||
if (_problem.Length > 0) _miStatus.Text += " (" + _problem + ")";
|
||||
_miCheck.Enabled = _miOpen.Enabled = on;
|
||||
_miSound.Checked = _cfg.Sound;
|
||||
_miAuto.Checked = AutoStart.Enabled;
|
||||
_miConnect.Text = on ? "연결 해제" : "연결…";
|
||||
string tip = !on ? "DBX 알림 — 연결 안 됨"
|
||||
: _pending.Count > 0 ? "DBX 알림 — 새 알림 " + _pending.Count + "건"
|
||||
: _problem.Length > 0 ? "DBX 알림 — " + _problem
|
||||
: "DBX 알림 — 클릭하면 수신함";
|
||||
_tray.Text = tip.Length > 63 ? tip.Substring(0, 63) : tip;
|
||||
}
|
||||
|
||||
protected override void ExitThreadCore()
|
||||
{
|
||||
SystemEvents.PowerModeChanged -= OnPowerModeChanged;
|
||||
_timer.Stop();
|
||||
_timer.Dispose();
|
||||
_tray.Visible = false;
|
||||
_tray.Dispose();
|
||||
_menu.Dispose();
|
||||
_popup?.Dispose();
|
||||
_connect?.Dispose();
|
||||
_api.Dispose();
|
||||
_icon.Dispose();
|
||||
base.ExitThreadCore();
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 28 KiB |
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<assemblyIdentity version="1.0.0.0" name="DBX.Notifier" type="win32" />
|
||||
<description>DBX 알림</description>
|
||||
<!-- 관리자 권한을 요구하지 않는다(현재 사용자 권한으로만 실행). -->
|
||||
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
|
||||
<security>
|
||||
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
|
||||
</requestedPrivileges>
|
||||
</security>
|
||||
</trustInfo>
|
||||
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
|
||||
<application>
|
||||
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" /><!-- Windows 10 / 11 -->
|
||||
</application>
|
||||
</compatibility>
|
||||
<!-- 화면 배율(125%·150%·200%)에서 글자가 흐리지 않게 — 시스템 DPI 기준으로 직접 그린다. -->
|
||||
<application xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<windowsSettings>
|
||||
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
|
||||
</windowsSettings>
|
||||
</application>
|
||||
<dependency>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0"
|
||||
processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*" />
|
||||
</dependentAssembly>
|
||||
</dependency>
|
||||
</assembly>
|
||||
@@ -0,0 +1,27 @@
|
||||
# DBX 알림 빌드 — dist\DBXNotifier.exe 하나를 만든다(.NET SDK 필요, 실행 PC 에는 .NET Framework 4.8 만 있으면 됨).
|
||||
# powershell -ExecutionPolicy Bypass -File desktop\notifier\build.ps1
|
||||
# 코드 서명(선택, 백신·SmartScreen 경고를 줄이는 가장 확실한 방법):
|
||||
# $env:DBX_SIGN_PFX = 'C:\cert\dbx-codesign.pfx'; $env:DBX_SIGN_PASSWORD = '...' (비밀번호는 저장소에 남기지 않는다)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
Push-Location $here
|
||||
try {
|
||||
dotnet build -c Release
|
||||
if ($LASTEXITCODE -ne 0) { throw "빌드 실패" }
|
||||
New-Item -ItemType Directory -Force (Join-Path $here 'dist') | Out-Null
|
||||
$exe = Join-Path $here 'dist\DBXNotifier.exe'
|
||||
Copy-Item (Join-Path $here 'bin\Release\net48\DBXNotifier.exe') $exe -Force
|
||||
|
||||
if ($env:DBX_SIGN_PFX) {
|
||||
$signtool = Get-ChildItem "${env:ProgramFiles(x86)}\Windows Kits\10\bin\*\x64\signtool.exe" -ErrorAction SilentlyContinue |
|
||||
Sort-Object FullName -Descending | Select-Object -First 1
|
||||
if (-not $signtool) { throw "signtool.exe 를 찾을 수 없습니다(Windows SDK 설치 필요)." }
|
||||
& $signtool.FullName sign /fd SHA256 /f $env:DBX_SIGN_PFX /p $env:DBX_SIGN_PASSWORD /tr http://timestamp.digicert.com /td SHA256 $exe
|
||||
if ($LASTEXITCODE -ne 0) { throw "서명 실패" }
|
||||
}
|
||||
$f = Get-Item $exe
|
||||
"{0} {1:N0} KB SHA256 {2}" -f $f.FullName, ($f.Length / 1KB), (Get-FileHash $exe -Algorithm SHA256).Hash
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
"""app.ico 생성 — 보라(#7b68ee) 둥근 사각형 위 흰 종(울리는 표시). 크기별로 따로 그려 작은 트레이 크기도 또렷하게.
|
||||
|
||||
사용: python desktop/notifier/tools/make_icon.py (Pillow 필요) → desktop/notifier/app.ico
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
SIZES = [16, 20, 24, 32, 40, 48, 64, 128, 256]
|
||||
SS = 8 # 슈퍼샘플링 배율
|
||||
|
||||
|
||||
def bezier(p0, p1, p2, p3, n=24):
|
||||
out = []
|
||||
for i in range(n + 1):
|
||||
t = i / n
|
||||
a = (1 - t) ** 3
|
||||
b = 3 * (1 - t) ** 2 * t
|
||||
c = 3 * (1 - t) * t ** 2
|
||||
d = t ** 3
|
||||
out.append((a * p0[0] + b * p1[0] + c * p2[0] + d * p3[0], a * p0[1] + b * p1[1] + c * p2[1] + d * p3[1]))
|
||||
return out
|
||||
|
||||
|
||||
def draw(size: int) -> Image.Image:
|
||||
big = size * SS
|
||||
k = big / 24.0 # 24 단위 격자
|
||||
img = Image.new("RGBA", (big, big), (0, 0, 0, 0))
|
||||
g = ImageDraw.Draw(img)
|
||||
g.rounded_rectangle([0, 0, big - 1, big - 1], radius=int(5.5 * k), fill=(123, 104, 238, 255))
|
||||
white = (255, 255, 255, 255)
|
||||
small = size <= 20 # 아주 작은 크기는 종을 크게, 울림 표시는 생략
|
||||
|
||||
def P(x, y):
|
||||
# 종 중심을 (12, 12.5) 기준으로 확대
|
||||
s = 1.12 if small else 0.92
|
||||
return ((12 + (x - 12) * s) * k, (12.6 + (y - 12) * s) * k)
|
||||
|
||||
body = [P(5, 17), P(6.6, 15.2), P(6.6, 10.6)]
|
||||
body += [P(*q) for q in bezier((6.6, 10.6), (6.6, 7.2), (9.0, 4.9), (12, 4.9))[1:]]
|
||||
body += [P(*q) for q in bezier((12, 4.9), (15.0, 4.9), (17.4, 7.2), (17.4, 10.6))[1:]]
|
||||
body += [P(17.4, 15.2), P(19, 17)]
|
||||
g.polygon(body, fill=white)
|
||||
cx, cy = P(12, 18.6)
|
||||
r = 1.9 * k * (1.12 if small else 0.92)
|
||||
g.ellipse([cx - r, cy - r, cx + r, cy + r], fill=white)
|
||||
kx, ky = P(12, 4.4)
|
||||
r2 = 1.1 * k * (1.12 if small else 0.92)
|
||||
g.ellipse([kx - r2, ky - r2, kx + r2, ky + r2], fill=white)
|
||||
if not small:
|
||||
w = max(1, int(1.5 * k))
|
||||
c = P(12, 10.6)
|
||||
rr = 9.6 * 0.92 * k
|
||||
box = [c[0] - rr, c[1] - rr, c[0] + rr, c[1] + rr]
|
||||
g.arc(box, 198, 238, fill=white, width=w)
|
||||
g.arc(box, 302, 342, fill=white, width=w)
|
||||
return img.resize((size, size), Image.LANCZOS)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
out = Path(__file__).resolve().parents[1] / "app.ico"
|
||||
imgs = [draw(s) for s in SIZES]
|
||||
imgs[-1].save(out, format="ICO", sizes=[(s, s) for s in SIZES], append_images=imgs[:-1])
|
||||
print(out)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,171 @@
|
||||
# 자산관리
|
||||
|
||||
진입 `/asset/`, 권한키 `asset`. 사무집기와 전산장비를 개별 자산번호로 등록한다.
|
||||
권한이 있는 사용자는 조회·등록·수정·배정·반납·상태 변경·보고서 다운로드가 가능하다.
|
||||
관리자 페이지의 기존 권한 토글로 접근을 부여한다.
|
||||
|
||||
수퍼 관리자(`SUPER_ADMIN_EMAIL`)만 자산을 삭제할 수 있다. 일반 관리자는 삭제할 수 없다.
|
||||
삭제 창에서 자산번호와 사유를 확인하며 API도 권한·CSRF·수정 버전을 확인한다.
|
||||
삭제한 자산은 대장·현황·엑셀·상세·첨부 다운로드에서 제외한다. 사진·보고서·이력과 기존 자산번호는 보존한다.
|
||||
|
||||
## 사진과 모니터 자산
|
||||
|
||||
- 자산 상세의 기본 정보에서 사진을 등록하고 갤러리로 조회한다. 자산당 10장, 파일당 8 MB 입력 제한.
|
||||
- JPG/PNG/WebP만 실제 이미지로 검사하며 최대 2천만 화소, 2400px로 축소한다.
|
||||
EXIF/GPS 등 메타데이터를 제거한 JPEG/PNG를 DB에 보관한다(저장 파일당 5 MB 이하).
|
||||
- 컴퓨터 주요 사양 상단에 보고서의 모니터 목록을 표시한다. 등록된 모니터는 자산번호·이름·상태·사용자·위치·구매금액·보증 개요와 상세 이동을 제공한다.
|
||||
- 시리얼이 유효하고 기존 모니터 한 대와 식별 정보가 일치하면 자동으로 찾는다.
|
||||
시리얼이 없거나 중복·제조사/모델 불일치인 경우 자동 확정하지 않고 후보를 직접 연결한다.
|
||||
- 미등록 모니터는 보고서의 이름/제조사/모델/시리얼과 컴퓨터의 위치/부서를 채운 등록 창을 연다.
|
||||
생성과 컴퓨터 연결은 한 트랜잭션으로 저장한다. 동시 등록은 컴퓨터 행 잠금과 시리얼 잠금으로 보호한다.
|
||||
- 새 등록을 막는 것은 **같은 시리얼의 모니터 자산이 이미 있을 때뿐**이다(같은 실물 — 기존 자산에 연결).
|
||||
같은 모델·이름의 자산은 참고 후보로만 보여 주고(`candidate_by = "model"`), 시리얼이 다르거나 없으면 새 자산으로 등록된다
|
||||
(듀얼 모니터처럼 같은 모델 여러 대 — 2026-10-07 수정, 예전엔 같은 모델 후보만 있어도 막혔다).
|
||||
- 등록·연결은 최신 보고서에서만 가능하다. 이전 보고서도 모니터와 자산 개요를 조회할 수 있다.
|
||||
기존에 업로드한 보고서도 재업로드 없이 지원한다.
|
||||
|
||||
## 업무 흐름
|
||||
|
||||
- 현황 카드: 전체·사용 중·사용 가능·수리 중·30일 이내 보증 만료. 분류 구성·최근 활동·보유 구매금액(폐기 제외).
|
||||
- 자산대장: 검색/분류/상태/위치/사용자 필터, 정렬, 25개씩 페이지 이동. 엑셀은 현재 필터 전체(최대 10,000개).
|
||||
- 상세: 기본 정보/컴퓨터 사양/보고서/활동 이력. 구매일·금액·구매처·보증·부서·위치·메모.
|
||||
- 자산 선택 시 상세 패널은 오른쪽에서 들어온다. 바깥 영역 클릭·X·Esc로 오른쪽으로 나가며 닫힌다.
|
||||
패널 안에서 시작한 드래그는 닫지 않으며 사진/편집 창이 열린 동안 부모 패널을 유지한다.
|
||||
시스템의 모션 줄이기 설정에서는 즉시 열고 닫는다.
|
||||
- 등록: 번호를 비우면 `AST-000001` 형식으로 자동 발급. 대소문자 무관 고유. 같은 모델도 물건마다 하나씩 등록.
|
||||
- 배정: 사용 가능 → 사용 중. 등록된 회사 사용자만 배정. 반납 시 사용자 배정을 해제한다.
|
||||
- 수리: 사용 가능 → 수리 중 → 사용 가능. 배정된 자산은 먼저 반납한다.
|
||||
- 분실: 사용 가능/사용 중/수리 중 → 분실. 기존 사용자를 유지. 발견 후 사용 가능으로 복구하면 배정 해제.
|
||||
- 폐기: 사용 가능/수리 중/분실 → 폐기. 오처리는 사용 가능으로 복구. 이력·보고서는 보존한다.
|
||||
- 분실·폐기는 사유 필수. 모든 변경은 처리자·시각·변경 전/후 값을 기록한다.
|
||||
- 동시 수정은 행 잠금 + version 검사. 409 발생 시 입력을 보존하고 상세를 다시 확인하도록 안내한다.
|
||||
|
||||
## HWiNFO XML
|
||||
|
||||
HWiNFO → 보고서 저장 → XML. 한 파일에 컴퓨터 한 대, 최대 10 MB.
|
||||
실제 `KING-DESKTOP.XML` 구조를 확인했다. 한국어/영어 항목명 및 언어 독립 PropertyType을 사용한다.
|
||||
실물 보고서는 시리얼·MAC·사용자 정보가 있어 Git에 포함하지 않는다.
|
||||
|
||||
1. 업로드 시 저장하지 않고 핵심 사양을 미리 분석한다.
|
||||
2. 이름과 위치를 확인한 뒤 신규 컴퓨터로 등록한다. 제조사와 유효한 시스템 시리얼은 초기값으로 사용한다.
|
||||
3. 기존 컴퓨터에서 업로드하면 보고서만 새 버전으로 연결한다. 자산명·구매정보·배정·위치를 덮어쓰지 않는다.
|
||||
4. CPU/RAM/GPU/저장장치 요약과 부품별 펼침 목록, 항목명·값·부품명 검색을 제공한다.
|
||||
5. 이전 버전 사양 조회와 원본 다운로드. 같은 자산의 동일 SHA-256 보고서는 중복 저장하지 않는다.
|
||||
기존 보고서와 컴퓨터 이름이 다르면 확인 안내를 표시한다.
|
||||
|
||||
모든 Property를 계층 경로와 함께 보존한다. SPD 메모리 모듈과 시스템 전체 메모리를 중복 합산하지 않는다.
|
||||
같은 모델의 서로 다른 디스크/모니터도 개별 노드로 유지한다. 드라이브 수는 외장 장치도 포함한다.
|
||||
ScanTime은 보고서에 있는 시각 그대로이고 시간대는 추정하지 않는다. 업로드/활동 시각은 KST로 표시한다.
|
||||
BIOS의 기본 문자열 `System Serial Number`는 실제 시스템 시리얼로 사용하지 않는다.
|
||||
|
||||
`defusedxml`로 엔티티/외부 엔티티를 차단한다. HWiNFO 외부 DTD 선언은 허용하지만 DTD를 읽거나 내려받지 않는다.
|
||||
크기·계층 제한과 HTML 이스케이프를 적용한다. 원본 XML은 첨부로 내려받는다.
|
||||
엑셀의 사용자 텍스트는 수식으로 실행하지 않는다. 모든 API는 권한, 변경 API는 세션 CSRF 토큰을 확인한다.
|
||||
|
||||
## 저장소와 설치
|
||||
|
||||
`app/modules/asset/`의 router/store/db/hwinfo/templates, 공통 메뉴/권한에 등록.
|
||||
전용 PostgreSQL `asset_db`, `ASSET_DB_URL`. JSON 폴백 없음. 미설정 시 저장 버튼 비활성 + 안내.
|
||||
XML 분석 미리보기는 DB 없이 가능. 앱 시작 시 DB/테이블을 생성하지 않는다.
|
||||
|
||||
| 테이블 | 용도 |
|
||||
| --- | --- |
|
||||
| assets | 자산·상태·사용자·위치·현재 보고서·수정 버전 |
|
||||
| asset_reports | 원본 XML(BYTEA)·분석 JSONB·SHA-256·처리자/시각. 이전 버전 보존 |
|
||||
| asset_events | 등록·수정·배정·반납·상태·보고서 이력. 변경 전/후 값 |
|
||||
| asset_photos | 검증·재인코딩한 사진, MIME/크기/처리자/시각 |
|
||||
| asset_monitor_links | 컴퓨터의 보고서 장비 식별키와 모니터 자산 연결 |
|
||||
|
||||
자산/보고서/이력은 한 트랜잭션에서 변경한다. 원본과 분석 결과도 함께 저장하므로 별도 첨부 경로가 없다.
|
||||
앱 계정 `asset_app`은 자산 SELECT/INSERT/UPDATE, 보고서/이력 SELECT/INSERT, sequence USAGE/SELECT.
|
||||
소유자는 `postgres`. 최신 보고서의 복합 FK는 다른 자산의 보고서 연결을 막는다.
|
||||
`assets.deleted_at/deleted_by`로 삭제를 표시한다. DB 계정에 DELETE 권한은 부여하지 않는다.
|
||||
사진 SELECT/INSERT, 모니터 연결 SELECT/INSERT/UPDATE 권한을 사용한다.
|
||||
|
||||
### 기존 설치에 사진·모니터·삭제 기능 적용
|
||||
|
||||
`asset_db` / `postgres-db` / 컨테이너 포트 5432. 운영자는 현재 상태와 백업을 확인한 뒤
|
||||
`scripts/sql/asset_db_002_photos_monitors.sql`을 적용한다. 열과 테이블을 추가하는 멱등 SQL이다.
|
||||
새 환경변수는 필요 없다. 전체 초기화 SQL을 다시 실행하지 않는다.
|
||||
|
||||
```bash
|
||||
(
|
||||
set -euo pipefail
|
||||
cd /opt/www/main
|
||||
docker compose ps
|
||||
git status --short
|
||||
git pull --ff-only origin master
|
||||
docker exec postgres-db psql -U postgres -d asset_db -c 'SELECT current_database(),current_user;'
|
||||
sudo mkdir -p /var/backups/postgres
|
||||
ASSET_BACKUP="/var/backups/postgres/asset_db_before_002_$(date +%Y%m%d_%H%M%S).dump"
|
||||
sudo test ! -e "$ASSET_BACKUP"
|
||||
sudo install -m 600 /dev/null "$ASSET_BACKUP"
|
||||
docker exec postgres-db pg_dump -U postgres -F c -d asset_db | sudo tee "$ASSET_BACKUP" >/dev/null
|
||||
sudo cat "$ASSET_BACKUP" | docker exec -i postgres-db pg_restore --list >/dev/null
|
||||
echo "백업 확인: $ASSET_BACKUP"
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d asset_db < scripts/sql/asset_db_002_photos_monitors.sql
|
||||
docker compose up -d --build web
|
||||
docker compose exec -T web python -c 'from app.main import app; s=app.state.asset_store; s is not None or exit("ASSET_DB_URL 설정 필요"); s.health(); print("asset_db 연결 및 스키마 정상")'
|
||||
docker compose ps
|
||||
docker compose logs --tail=50 web
|
||||
)
|
||||
```
|
||||
|
||||
**DB 생성은 서버 실행 명령을 제공하고 사용자가 직접 진행한다 (2026-10-06).**
|
||||
`scripts/sql/asset_db_init.sql`은 재실행 시 기존 데이터·비밀번호를 변경하지 않는다.
|
||||
운영 `/opt/www/main`, PostgreSQL `postgres-db`, 컨테이너 포트 5432.
|
||||
현재 상태·DB 목록·기존 백업 위치 확인 후 진행한다. 권장 백업은 매일,
|
||||
`/var/backups/postgres/asset_db_YYYY-MM-DD.dump`(운영자가 준비; 자동 스케줄은 추가하지 않음).
|
||||
원본 XML도 pg_dump에 포함되므로 보고서가 늘면 백업 용량도 증가한다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker compose ps
|
||||
docker exec postgres-db psql -U postgres -c '\l'
|
||||
# 신규 설치 시 사용자가 대상 서버·현재 DB·기존 백업 위치 확인 후 실행:
|
||||
read -r -s -p 'asset_app password: ' ASSET_APP_PWD; echo
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres \
|
||||
-v app_password="$ASSET_APP_PWD" < scripts/sql/asset_db_init.sql
|
||||
unset ASSET_APP_PWD
|
||||
# .env: ASSET_DB_URL=postgresql://asset_app:<URL-encoded-password>@postgres-db:5432/asset_db
|
||||
docker exec postgres-db psql -U postgres -d asset_db -c '\dt'
|
||||
docker compose up -d --build web
|
||||
docker compose ps
|
||||
docker compose logs --tail=50 web
|
||||
# 로그인 후 /asset/health와 등록·배정·반납·보고서 확인
|
||||
```
|
||||
|
||||
DB·테이블·`.env`의 `ASSET_DB_URL`을 이미 준비했다면 초기화 SQL은 생략한다.
|
||||
코드를 반영한 뒤 웹 컨테이너를 재빌드하고 앱 계정의 DB 연결을 확인한다.
|
||||
아래 확인은 데이터를 추가하거나 수정하지 않는다. 일반 직원은 관리자 페이지에서 `asset` 권한을 부여한다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker compose ps
|
||||
git status --short
|
||||
git pull --ff-only origin master
|
||||
docker compose up -d --build web
|
||||
docker compose ps
|
||||
docker compose exec -T web python -c 'from app.main import app; store=app.state.asset_store; store is not None or exit("ASSET_DB_URL 설정이 필요합니다."); store.health(); print("asset_db 연결 정상")'
|
||||
docker compose logs --tail=50 web
|
||||
```
|
||||
|
||||
## 참고한 업무 패턴
|
||||
|
||||
- [Snipe-IT Overview](https://snipe-it.readme.io/docs/overview): 배정·반납·상태 구분.
|
||||
- [Snipe-IT Managing Assets](https://snipe-it.readme.io/docs/managing-assets): 개별 자산번호.
|
||||
- [EZOfficeInventory Work Orders](https://www.ezofficeinventory.com/industries/work-order-software): 상세의 정비·처리 이력.
|
||||
|
||||
기존 ERP의 단색 화면·사이드바·상태 배지·다이얼로그에 맞춰 재구성했다.
|
||||
|
||||
## 검증
|
||||
|
||||
```powershell
|
||||
python -m unittest discover -s tests -p 'test_asset*.py'
|
||||
python tests/js/render_asset.py
|
||||
node tests/js/asset.browser.test.js
|
||||
```
|
||||
|
||||
Chrome 검증은 실제 템플릿과 가짜 API를 사용해 운영 DB에 쓰지 않는다.
|
||||
실물 보고서는 `ASSET_SAMPLE_XML` 경로 또는 프로젝트 루트 `KING-DESKTOP.XML`을 사용한다.
|
||||
실물 파일이 없으면 그 검증만 건너뛰고 합성 보고서 테스트는 실행한다.
|
||||
+9
-1
@@ -17,10 +17,18 @@
|
||||
|
||||
## 명명 규칙
|
||||
|
||||
자산관리 전용 `asset_db` / 앱 계정 `asset_app` / 소유자 `postgres`.
|
||||
테이블 `assets`, `asset_reports`, `asset_events`, `asset_photos`, `asset_monitor_links`.
|
||||
원본 XML과 검증된 사진을 DB에 보존한다. 수퍼 관리자 삭제는 `assets.deleted_at/deleted_by` 표시로 처리한다.
|
||||
기존 설치 추가 마이그레이션은 `scripts/sql/asset_db_002_photos_monitors.sql`.
|
||||
`ASSET_DB_URL`, 초기화 `scripts/sql/asset_db_init.sql`(사용자가 서버에서 직접 실행).
|
||||
백업 권장: 매일 `/var/backups/postgres/asset_db_YYYY-MM-DD.dump`.
|
||||
상세 설치·권한·업무 규칙은 [ASSET_MODULE.md](ASSET_MODULE.md).
|
||||
|
||||
- 모든 DB 이름은 **소문자 + 언더스코어**, **`_db`로 끝낸다**.
|
||||
- ✅ `inventory_db`, `cs_db`
|
||||
- ❌ `inventoryApp`, `cs-database`
|
||||
- 신규 DB가 필요하면 **사용자 승인 후** 생성한다.
|
||||
- 신규 DB 생성은 **서버 실행 명령을 제공하고 사용자가 직접 진행한다** (사용자 지시: 2026-10-06). 대상·현재 상태·백업 확인과 생성 후 권한·연결 검증 명령을 함께 제공한다. 기존 DB 삭제·덮어쓰기는 별도 승인을 받는다.
|
||||
- 신규 DB 생성 시 함께 정리할 항목:
|
||||
- 용도와 책임 모듈
|
||||
- 소유자(OWNER) 계정
|
||||
|
||||
@@ -82,8 +82,102 @@ docker compose logs -f --tail=200
|
||||
|
||||
---
|
||||
|
||||
## 주간 회의록 셀 병합 마이그레이션
|
||||
|
||||
주간 회의록 셀 병합을 배포할 때는 `project_db`의 최근 백업 위치를 확인한 뒤 마이그레이션 019를 적용한다.
|
||||
DB는 공용 `postgres-db` 컨테이너의 PostgreSQL(컨테이너 포트 5432)을 사용한다. 019는 기존 글을 바꾸지 않고
|
||||
`content_row_span` 열을 추가하며, 다시 실행할 수 있다. 미적용 시 다른 셀 편집은 가능하지만 병합은 사용할 수 없다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker compose ps
|
||||
docker exec postgres-db psql -U postgres -d project_db -c 'SELECT current_database();'
|
||||
# project_db 최근 백업 위치를 확인한 후 적용
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db < scripts/sql/project_db_019_meeting_cell_editing.sql
|
||||
docker exec postgres-db psql -U postgres -d project_db -c "SELECT column_name FROM information_schema.columns WHERE table_name = 'goal_meeting_items' AND column_name = 'content_row_span';"
|
||||
```
|
||||
|
||||
## 주간 회의록 새 주차·결과 글·주차별 목표 마이그레이션 (020)
|
||||
|
||||
020은 `goal_meeting_items.result_note` 열·`goal_week_targets` 표를 추가하고, `goal_meetings` 의 "월요일만" CHECK 를 없애며,
|
||||
새 주차 규칙에 흡수된 월요일 회의록을 새 주차 시작일로 옮긴다(옮길 자리에 회의록이 있으면 NOTICE 만). 다시 실행할 수 있다.
|
||||
코드는 020 전에도 열리지만 결과 글·주차별 목표·월요일이 아닌 주차 회의록 만들기는 020 뒤에 된다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_020_$(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_020_meeting_periods.sql
|
||||
docker exec postgres-db psql -U postgres -d project_db -c "SELECT to_regclass('goal_week_targets') AS t, (SELECT count(*) FROM information_schema.columns WHERE table_name='goal_meeting_items' AND column_name='result_note') AS note;"
|
||||
```
|
||||
|
||||
## 주간 회의록 "회의록 보드"(Google 슬라이드) 설정
|
||||
|
||||
회의록 화면의 [회의록 보드] 는 주차마다 빈 Google 슬라이드를 공유 드라이브(`MEETING_BOARD_FOLDER_ID`, 기본 `0AGF3CIEboPQiUk9PVA`)에
|
||||
만들어 새 창으로 연다(`app/integrations/google_slides.py`). DB 변경 없음. 인증은 쿠팡 시트와 같은 Google 설정을 쓰되 **Drive·Slides 권한**이 더 필요하다.
|
||||
|
||||
1. Google Cloud Console(OAuth 클라이언트가 있는 프로젝트) → API 라이브러리에서 **Google Drive API**, **Google Slides API** 사용 설정
|
||||
2. 개발 PC에서 토큰 재발급(시트·Drive·Slides 권한을 한 번에 받는다) — 공유 드라이브에 쓸 수 있는 계정으로 로그인·동의
|
||||
```bash
|
||||
python scripts/google_sheets_authorize.py --client-id <ID> --client-secret <SECRET>
|
||||
```
|
||||
3. 서버 `/opt/www/main/.env` 의 `GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 을 새 토큰으로 바꾸고(쿠팡 시트도 같은 토큰으로 계속 동작)
|
||||
`docker compose up -d` 로 다시 띄운다. 토큰은 비밀값 — Git·메신저에 남기지 않는다.
|
||||
|
||||
설정이 없거나 권한이 모자라면 버튼을 눌렀을 때 사유가 안내되고(503), 회의록 다른 기능은 그대로 동작한다.
|
||||
|
||||
## PC 알림 프로그램 마이그레이션 (023)
|
||||
|
||||
023은 `notifier_links`·`notifier_tokens` 테이블만 추가한다(기존 값 그대로, 다시 실행 가능). 미적용이면 `/project/notifier` 화면은
|
||||
"마이그레이션 필요" 안내만, PC 알림 API 는 503.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_023_$(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_023_notifier.sql
|
||||
```
|
||||
|
||||
내려받기 파일(선택): 개발 PC 에서 `desktop/notifier/build.ps1` 로 만든 `dist/DBXNotifier.exe` 를 서버로 옮긴 뒤 컨테이너 데이터 볼륨에 둔다.
|
||||
없으면 화면에 "관리자에게 받으세요"만 나온다(공유 드라이브로 나눠 줘도 된다).
|
||||
|
||||
```bash
|
||||
cd /opt/www/main && docker compose exec web mkdir -p /data/notifier && docker compose cp ~/DBXNotifier.exe web:/data/notifier/DBXNotifier.exe
|
||||
```
|
||||
|
||||
## 주간 회의록 회의 완료 마이그레이션 (022)
|
||||
|
||||
022는 `goal_meetings` 에 `completed_at`·`completed_by` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 미적용이면 [회의 완료] 버튼이 나오지 않고
|
||||
회의록은 누구나 계속 고칠 수 있다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_022_$(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_022_meeting_complete.sql
|
||||
```
|
||||
|
||||
## 주간 회의록 정량 목표·결과 글 마이그레이션 (021)
|
||||
|
||||
021은 `goal_meeting_items` 에 `target_text`·`result_text` 열만 추가한다(기존 값 그대로, 다시 실행 가능). 미적용이면 정량 목표·결과는 예전처럼 숫자만 받는다.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main
|
||||
docker exec postgres-db pg_dump -U postgres project_db > ~/project_db_before_021_$(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_021_meeting_amount_text.sql
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 컨테이너 관리
|
||||
|
||||
자산관리의 `asset_db` 생성은 사용자가 서버 명령으로 직접 진행한다 (2026-10-06).
|
||||
이미 생성한 DB에 프로그램을 적용할 때는 초기화 SQL을 다시 실행할 필요가 없다.
|
||||
`ASSET_DB_URL=postgresql://asset_app:<URL-encoded-password>@postgres-db:5432/asset_db`를 설정한다.
|
||||
원본 XML까지 DB 백업에 포함되며 별도 업로드 볼륨은 필요 없다.
|
||||
자산 사진·모니터 연결·수퍼 관리자 삭제 기능을 기존 설치에 추가할 때는 `asset_db` 백업 후
|
||||
`scripts/sql/asset_db_002_photos_monitors.sql`을 먼저 적용하고 web을 재빌드한다.
|
||||
사진도 DB 백업에 포함된다. 실행 명령은 [자산관리 설치 문서](ASSET_MODULE.md#기존-설치에-사진모니터삭제-기능-적용)를 참조한다.
|
||||
DB 미설정 시에도 기존 모듈은 동작하고 자산관리에서 설정 안내/보고서 분석을 제공한다.
|
||||
상태·백업 확인과 초기화 순서는 [ASSET_MODULE.md](ASSET_MODULE.md#저장소와-설치) 참조.
|
||||
|
||||
```bash
|
||||
docker compose ps # 상태 확인
|
||||
docker compose restart web # 단일 서비스 재시작
|
||||
|
||||
+321
-47
@@ -46,14 +46,14 @@
|
||||
| 연결 env | `PROJECT_DB_URL` (미설정 시 "설정 필요" 안내, 앱은 죽지 않음) |
|
||||
| 진입 권한 | 권한키 `project` (관리자 페이지 토글로 직원별 부여, admin 자동) |
|
||||
| 멤버 배정 후보 | `project` 권한 보유 등록 사용자 자동 목록 (`GET /project/api/assignable-users`) |
|
||||
| 생성 권한 | **프로젝트·섹션·작업(하위 작업 포함) 생성은 로그인해 이 모듈에 접근할 수 있는 사용자 누구나.** 프로젝트를 만든 사람은 자동으로 owner 가 되어 그 프로젝트를 관리(`_can_manage`)할 수 있다. 다른 사람을 owner 로 지정해 만드는 건 관리자만(비관리자가 `owner_email` 을 남으로 보내면 403) |
|
||||
| 소유자 변경 | **관리자만**(2026-09-30). owner 는 멤버에서 빠져도 관리 권한이 남으므로, 일반 멤버가 스스로를 owner 로 바꿔 권한 회수를 피할 수 없게 `PUT /api/projects/{id}` 의 `owner_email` 변경은 비관리자 403(같은 값은 무시). 새 owner 는 `project` 권한이 있는 등록 사용자여야 한다(아니면 400) |
|
||||
| 수정/이동 권한 | 서브프로젝트·작업·섹션 CRUD(이름변경·완료토글·순서변경 등) = 그 프로젝트의 배정 멤버 또는 owner 또는 admin(`_require_manage`). 작업 API 는 `_require_task(write=True)` = 원 소속 프로젝트 권한(FULL) |
|
||||
| 조회 권한 | 프로젝트 화면(`/p/{id}`)·멤버/섹션/작업/활동/스냅샷 API 도 멤버·owner·admin 만(`_require_manage`). 비멤버는 403. `GET /api/users/tasks` 를 프로젝트 없이 부르면 내가 볼 수 있는 프로젝트의 작업만 돌려준다. 연결된(멀티호밍) 작업은 연결된 프로젝트 멤버에게 **읽기 전용**(6-10) |
|
||||
| 생성 권한 | **새 최상위 프로젝트는 Pro user 이상(2026-10-12, 6-14). 섹션·작업·서브프로젝트는 그 프로젝트 멤버 누구나.** 프로젝트를 만든 사람은 자동으로 owner 가 되어 그 프로젝트를 관리(`_can_manage`)할 수 있다. 다른 사람을 owner 로 지정해 만드는 것도 Pro user 이상 |
|
||||
| 소유자 변경 | **Pro user 이상**(2026-10-12, 예전 관리자만 2026-09-30). owner 는 멤버에서 빠져도 관리 권한이 남으므로, 일반 멤버가 스스로를 owner 로 바꿔 권한 회수를 피할 수 없게 `PUT /api/projects/{id}` 의 `owner_email` 변경은 비관리자 403(같은 값은 무시). 새 owner 는 `project` 권한이 있는 등록 사용자여야 한다(아니면 400) |
|
||||
| 수정/이동 권한 | 서브프로젝트·작업·섹션 CRUD(이름변경·완료토글·순서변경 등) = 그 프로젝트의 배정 멤버 또는 owner 또는 슈퍼관리자(`_require_manage`). 작업 API 는 `_require_task(write=True)` = 원 소속 프로젝트 권한(FULL) |
|
||||
| 조회 권한 | 프로젝트 화면(`/p/{id}`)·멤버/섹션/작업/활동/스냅샷 API 도 멤버·owner 만(`_require_manage`). 비멤버는 403. **관리자(is_admin)도 멤버가 아니면 못 본다 — 예외는 슈퍼관리자(`app.store.SUPER_ADMIN_EMAIL`) 한 명**(2026-10-07, `access.sees_all_projects`·`visible_project_ids`). 왼쪽 사이드바 프로젝트 목록·`GET /api/projects`·검색·수신함·알림·마감 알림·휴지통(목록·복구)도 같은 기준. 멤버 배정은 여전히 관리자만이라, 관리자는 자기가 멤버인 프로젝트에서만 배정할 수 있다(직원이 만든 프로젝트는 슈퍼관리자가 배정). `GET /api/users/tasks` 를 프로젝트 없이 부르면 내가 볼 수 있는 프로젝트의 작업만 돌려준다. 연결된(멀티호밍) 작업은 연결된 프로젝트 멤버에게 **읽기 전용**(6-10) |
|
||||
| 지금 권한 기준 | 모든 판단은 **지금** 권한(`app/modules/project/access.py`) — 멤버에서 빠진 사람은 예전 담당자·멘션·협업자 기록이 있어도 내 작업·수신함·알림·검색·상세·공유 링크·댓글·첨부에서 그 작업이 보이지 않고, 새 알림·메일도 받지 않는다(기록은 이력으로 남김) |
|
||||
| 입력 검증 | URL 의 섹션이 URL 의 프로젝트 것인지(`_stage_of_project`), 작업 생성/수정·연결 시 섹션이 그 프로젝트 것인지(`stage_in_project`), 하위 작업의 부모가 같은 프로젝트인지 확인 — 권한은 URL 의 project_id 로 보므로 이걸 안 보면 남의 프로젝트를 건드릴 수 있다. 새 담당자는 그 프로젝트를 볼 수 있는 사람만(400). 날짜 범위(시작 ≤ 마감, 같은 날이면 시작 시각 ≤ 마감 시각)는 부분 수정도 기존 값과 합친 최종 상태로 검사(400) |
|
||||
| 삭제 권한 | **프로젝트·섹션·작업 모두 "만든 사람만"**(슈퍼관리자 예외, 생성자 정보 없는 과거 데이터는 admin 허용) — `_can_delete` 하나로 통일. **그리고 지금 그 프로젝트 권한이 있어야 한다**(멤버에서 빠진 생성자는 403, DB·휴지통 변화 없음) |
|
||||
| 멤버 배정 | 여전히 관리자(`is_admin`) 전용. 비관리자가 "새 프로젝트" 모달을 열면 멤버 선택란은 안내 문구만 뜨고 시도하지 않는다(불필요한 403 방지) |
|
||||
| 삭제 권한 | **프로젝트·섹션은 Admin 이상이면 누구 것이든, 그 밖은 "만든 사람만"**(생성자 정보 없는 과거 데이터는 Admin 이상) — `_can_delete`. **작업은 멤버 누구나**(2026-10-12). **그리고 지금 그 프로젝트 권한이 있어야 한다**(멤버에서 빠진 생성자는 403, DB·휴지통 변화 없음) |
|
||||
| 멤버 배정 | Pro user 이상, 자기가 멤버인 프로젝트만(2026-10-12). User 가 "새 프로젝트" 모달을 열면 멤버 선택란은 안내 문구만 뜨고 시도하지 않는다(불필요한 403 방지) |
|
||||
| 메일 알림 | `app/mail.py` (stdlib smtplib). 작업 배정/완료 시 관리자에게 발송 |
|
||||
|
||||
## 1-1. 프로젝트 → 섹션 → 작업 (하위 작업 포함) 3단계 구조
|
||||
@@ -73,8 +73,9 @@
|
||||
경계를 더블클릭하면 그 열의 가장 긴 문단에 자동으로 맞춘다. 직접 넣은 줄바꿈은 유지하고 글꼴·크기·굵기·여백을
|
||||
반영하며, 병합 칸은 다른 열 너비를 유지한 채 선택한 열만 맞춘다. 긴 문단은 드래그 최대 너비(600px)를 넘어도
|
||||
맞추고 브라우저에 기억한다(이름 열도 자동 맞춤 가능). 현재 편집 중인 글·숫자도 내용 변경 없이 측정한다.
|
||||
목표 업무 행 높이는 가장 높은 글 칸의 자연 높이에 맞춘다. 글·이름 칸 모두 위·아래 6px 여백과 상단 정렬을
|
||||
사용하며, 글이 짧아지면 행도 줄어든다. 글이 한 줄이거나 비어 있으면 한 줄 높이만 확보하고 보기 전용도 같은 규칙이다.
|
||||
목표 업무 행 높이는 가장 높은 글 칸의 자연 높이에 맞춘다. 글·이름 칸 모두 위·아래 6px 여백을 사용한다.
|
||||
1열(업무 영역)·2열(항목 이름)은 병합 여부와 행 높이에 관계없이 항상 세로 가운데 정렬하고, 목표 글 칸은 상단 정렬한다.
|
||||
글이 짧아지면 행도 줄어든다. 글이 한 줄이거나 비어 있으면 한 줄 높이만 확보하고 보기 전용도 같은 규칙이다.
|
||||
목표 글자를 선택하면 해당 셀 상단 중앙을 기준으로 셀 위에 서식 도구가 표시되며, 색상은 지정된 12색 견본으로만 선택한다.
|
||||
기존 글의 다른 색상은 보존. 글자 선택 해제·외부 클릭·편집 셀 제거 시 도구를 닫고 기존 부분 서식·자동 저장을 재사용한다.
|
||||
|
||||
@@ -183,7 +184,8 @@
|
||||
## 2. 데이터 모델 (`scripts/sql/project_db_init.sql` + `..._002_*` ~ `..._006_*`)
|
||||
|
||||
- `projects` — `parent_id`(self-FK, NULL=최상위 / NOT NULL=서브프로젝트, `ON DELETE CASCADE`), name, description, color, owner_email, start/due_date, status(active|archived).
|
||||
- `project_members` — 프로젝트↔사용자 배정. role(manager|member), `UNIQUE(project_id, user_email)`.
|
||||
- `project_members` — 프로젝트↔사용자 배정. `UNIQUE(project_id, user_email)`. role 열(manager|member)은 남아 있지만
|
||||
2026-10-07 부터 화면·권한에서 쓰지 않는다 — 배정 창의 역할 선택을 없앴고 새 배정은 늘 member, 배정된 멤버는 모두 보기·수정.
|
||||
- `project_stages`(="섹션") — 진행단계(칸반 컬럼). **프로젝트 생성 시 자동으로
|
||||
만들지 않는다**(아사나처럼 직접 "+ 섹션 추가"로 만든다 — `create_project`
|
||||
의 `seed_stages` 기본값은 `False`). `is_done_stage`=TRUE 단계로 옮기면 작업
|
||||
@@ -237,8 +239,8 @@
|
||||
좌측 사이드바는 프로젝트·수신함 화면과 공용(`project/_side.html`, `side_active` 로
|
||||
활성 메뉴 표시) — 수신함 · 내 작업 ·
|
||||
프로젝트 트리(+ 새 프로젝트) · "전체 멤버". 프로젝트 트리는 **수신함·내 작업·휴지통·프로젝트
|
||||
네 화면 모두 같다** — 관리자에게 드래그 순서 변경(⣿)·✎ 수정·× 삭제·우클릭 메뉴(공용
|
||||
`initSideTree`, 모달은 `project/_side_modals.html` 을 각 화면이 include). "전체 멤버"는 **관리자(`is_admin`)에게만**
|
||||
네 화면 모두 같다** — Pro user 이상에게 드래그 순서 변경(⣿)·✎ 수정·× 삭제·우클릭 메뉴(공용
|
||||
`initSideTree`, 모달은 `project/_side_modals.html` 을 각 화면이 include). "전체 멤버"는 **Pro user 이상(`pj_pro`)에게만**
|
||||
그리고 수신함·내 작업·프로젝트 화면 모두에서 나온다. 아이콘 클릭 = 그 사람의 담당 작업
|
||||
팝업(`_member_tasks_modal.html`, `initMemberTasks`) — 프로젝트 화면에선 더블클릭 시 그 자리에서
|
||||
편집 팝업, 다른 화면에선 그 작업의 프로젝트 화면(`?task=`)으로 이동.
|
||||
@@ -246,7 +248,9 @@
|
||||
좌측 "내 작업"는 접이식 패널이 아니라 `/project/` 로 가는 링크다.
|
||||
**이 프로젝트의 멤버는 화면 위 제목 오른쪽**에 겹친 아바타로 둔다(`.pj-title-members`) —
|
||||
마우스를 올리면 이름(`data-tip`, `initHoverTips` 가 위임 방식이라 동적 요소에도 붙는다),
|
||||
클릭하면 그 사람이 이 프로젝트에서 맡은 작업 팝업, 우클릭(관리자)하면 제외, 옆 `+` 는 멤버 배정.
|
||||
클릭하면 그 사람이 이 프로젝트에서 맡은 작업 팝업, 우클릭(Pro user 이상)하면 제외, 옆 `+` 는 **멤버 배정·제외 창**(2026-10-07 —
|
||||
후보 전원 + 지금 멤버는 체크된 채, 체크 = 배정 `POST …/members`, 해제 = 제외 `DELETE …/members/{email}`(확인 뒤), 소유자는 잠금.
|
||||
두 API 모두 Pro user 이상 + 그 프로젝트 관리 권한(`_require_manage`)).
|
||||
좌측 트리의 작업 클릭도 페이지 이동 없이 바로 팝업(이미 로드된 전체 작업 데이터 사용).
|
||||
좌측 맨 위 **수신함**(미확인 @태그 배지)과 **내 작업**(접이식, 기본 접힘 — 작업을 고르면
|
||||
팝업이 열리며 다시 접힌다)가 있다. 예전 화면 오른쪽에 항상 떠 있던 "내 작업" 패널은 없앴고
|
||||
@@ -279,9 +283,16 @@
|
||||
CSS 의 크기는 전부 `calc(Npx * var(--tz))`(배율 모드 `--tz: .75`), vis 옵션 높이·간격도
|
||||
`uiZoom()` 을 곱한다. 배율을 토글하면(resize) 다시 그린다. **타임라인 CSS 에 px 크기를 새로 넣을
|
||||
때도 `var(--tz)` 를 곱한다.**
|
||||
- **대시보드** — 합계 타일 4개 + 미완료 작업(섹션별)·작업 합계(완료 상태별) 차트. **"예정된 작업 합계
|
||||
(담당자별)" 차트는 관리자(`is_admin`)에게만** 보인다(사람별 업무량이 드러나서). 화면 표시만 막는 것 —
|
||||
작업 데이터 자체는 멤버가 원래 볼 수 있는 범위 그대로다.
|
||||
- **대시보드** — 합계 타일 4개 + 미완료 작업(섹션별)·작업 합계(완료 상태별) 차트. **"담당자별 작업 합계(메인·하위
|
||||
작업, 완료)" 표는 Pro user 이상에게만** 보인다(사람별 업무량이 드러나서, 세부 작업 API `subtasks-summary` 도 Pro user 이상) —
|
||||
작업 데이터 자체는 멤버가 원래 볼 수 있는 범위 그대로다. (2026-10-07, 예전 "예정된 작업 합계(담당자별)" 막대 대신)
|
||||
그 범위(이 프로젝트 = 여기 연결된 작업 포함 / 전체 프로젝트)에서 사람별로 배정된 작업 **전부**(마감일·필터와 무관) —
|
||||
메인 작업(`scopeTasks()` 최상위, 중복 없이)과 하위 작업(화면 목록엔 없어 `GET /api/projects/{id}/subtasks-summary?scope=`
|
||||
— `db.list_subtasks_of`, 그 범위 메인 작업의 하위만, 하위 작업 자신의 담당자 기준)을 나눠 세고, 메인·하위·전체 완료 수와
|
||||
전체 완료율. 하위 요약은 15초 캐시(`paintWorkload`). **세로 막대**(같은 날 변경 — 사람마다 메인·하위 막대, 막대 = 그 작업 전체(100%),
|
||||
초록 채움 높이 = 완료율, 위 = 완료/전체·%. 처음엔 높이를 작업 수로 그려 많은 사람 기준에 다른 막대가 눌려 보였다 → 완료율로 수정). 막대를 누르면 오른쪽 슬라이드 패널(`openWorkloadDrawer`, body 에 붙음, z 950 — 편집 창 아래)에
|
||||
그 업무 목록(미완료·완료, 하위는 상위 작업 이름), 항목 → `openTaskById`(하위는 서버에서 받아) 편집 창. 편집 창이 닫히면
|
||||
요약을 다시 받아 대시보드·패널을 다시 그린다. 하위 요약 API 는 id·제목·마감일·완료 시각도 준다.
|
||||
- **보드** — 섹션별 칸반. `renderBoard` 는 캔버스를 통째로 다시 그리므로 **섹션 세로 스크롤(`.pj-col-body`,
|
||||
섹션 id/이름 기준)·보드 가로 스크롤을 저장했다가 되돌린다**(작업 창 닫기·완료 체크·8초 갱신 후에도 보던 자리).
|
||||
작업 창을 닫으면 펼친 카드의 하위 작업을 먼저 다 받은 뒤 한 번에 다시 그린다(짧아진 채 그리면 스크롤이 밀림). 섹션은 아사나처럼 **가로로 계속 늘어난다** — 화면을 넘치면
|
||||
@@ -355,6 +366,18 @@ docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
# 018 = 주간 회의록 줄 연결키(line_key) — 적용 전 백업, 적용·확인 방법은 6-9-3
|
||||
docker exec -i postgres-db psql -U postgres -d project_db \
|
||||
< scripts/sql/project_db_018_meeting_line_keys.sql
|
||||
# 019 = 주간 회의록 이번주 글 셀 세로 병합 — 적용 전 project_db 백업
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db \
|
||||
< scripts/sql/project_db_019_meeting_cell_editing.sql
|
||||
# 020 = 새 주차(월요일 아닌 시작일)·지난주 결과 글·주차별 매출 목표 + 흡수된 월요일 회의록 이동 — 적용 전 project_db 백업(6-9-4)
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db \
|
||||
< scripts/sql/project_db_020_meeting_periods.sql
|
||||
# 022 = 회의 완료(goal_meetings.completed_at·completed_by) — 열 추가만(6-9-4)
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db \
|
||||
< scripts/sql/project_db_022_meeting_complete.sql
|
||||
# 021 = 회의록 정량 목표·결과에 글(target_text·result_text, 예: 20개) — 열 추가만(6-9-4)
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d project_db \
|
||||
< scripts/sql/project_db_021_meeting_amount_text.sql
|
||||
|
||||
# 4) 재배포 (git pull 후 반드시 --build)
|
||||
cd /opt/www/main && docker compose up -d --build web
|
||||
@@ -501,7 +524,7 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
모든 조회 쿼리에 "삭제됨" 필터를 넣는 소프트 삭제 대신 이 방식 — 기존 화면·쿼리를 안 건드린다.
|
||||
- 첨부 실물은 지우지 않고 `DATA_DIR/project/_trash/<trash_id>/<task_id>/` 로 옮긴다(복구 시 되돌림).
|
||||
- **보관 3개월**(`expires_at`). 휴지통 화면을 열거나 작업을 지울 때 만료분을 영구 삭제(`_purge_trash`).
|
||||
- **관리자 전용**: 좌측 "휴지통" 메뉴·`/project/trash` 화면·`POST /project/api/trash/{id}/restore` 모두 `is_admin`.
|
||||
- **Pro user 이상**(2026-10-12, 예전 관리자 전용): 좌측 "휴지통" 메뉴·`/project/trash` 화면·`POST /project/api/trash/{id}/restore` 모두 `access.is_pro`.
|
||||
복구는 원래 id 그대로(`restore_trash`): 같은 id 가 이미 있으면 거부, 프로젝트가 지워졌으면 거부, 하위 작업만
|
||||
지웠는데 상위가 없으면 거부(상위 먼저 복구). 지워진 섹션은 섹션 없이, 지워진 프로젝트를 가리키는 연결/이력은 뺀다.
|
||||
복구하면 휴지통 행은 지운다.
|
||||
@@ -560,12 +583,11 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
- 연도를 누르면 `/project/goals/{연도}`(`goals.html`) — 스프레드시트 같은 한 표. 머리 줄(연간·1~12월)과 왼쪽 두 칸은 고정,
|
||||
이번 달 열 강조. **가로 스크롤 때 3열(구분·항목·연간)까지 고정** — 연간 열 `position: sticky; left: 1열+2열 너비`, 경계 그림자.
|
||||
월 칸 기본 너비 85px·연간 90px(여백 포함, `box-sizing: border-box`). 머리·왼쪽 이름은 가로 가운데 정렬이며,
|
||||
업무 영역의 이름·글은 세로 상단 정렬, 위·아래 여백 각 6px이다. 행 높이는 가장 높은 글 칸에 맞추고 글이 줄면 함께 줄어든다.
|
||||
업무 영역의 이름(1·2열)은 세로 가운데 정렬, 목표 글은 상단 정렬이며 위·아래 여백은 각 6px이다. 행 높이는 가장 높은 글 칸에 맞추고 글이 줄면 함께 줄어든다.
|
||||
**모든 열**(구분·항목·연간·1~12월·분기)은 모든 행의 셀 오른쪽 끝에서 끌어 너비 조절(더블클릭 = 가장 긴 문단에 맞춤).
|
||||
브라우저별 localStorage `pj_goal_col_w`(키 `c1`·`c2`·`y`·`m1`~`m12`·`q1`~`q4`, 기본값과 다른 칸만 저장).
|
||||
드래그는 이름 두 칸 48~320px·CSS 변수 `--goal-c1-w`·`--goal-c2-w`, 나머지 40~600px·머리 칸의 `--cw`로 조절한다.
|
||||
자동 맞춤은 긴 문단에 맞게 최대 너비를 넘어도 저장·복원한다. 접기 애니메이션의 월 칸 안쪽 고정 폭은
|
||||
`--fold-w`(병합 칸 = 걸친 월 너비 합)로 JS가 넣는다.
|
||||
자동 맞춤은 긴 문단에 맞게 최대 너비를 넘어도 저장·복원한다. 분기를 펼칠 때도 지정한 열 너비를 그대로 사용한다.
|
||||
- **틀 고정** — 세로 스크롤에도 머리 줄 + 숫자 지표(매출·로아스) 줄까지 위에 붙어 있다. 지표 칸 `position: sticky` + 줄마다 `--kpi-top`(머리 줄 높이 + 앞 지표 줄 높이 합, `stickKpi`, 창 크기 바뀌면 다시 잼). z-index: 영역 이름 칸 2(마우스 올림 6) < 지표 칸 7 < 지표 이름 칸 8 < 머리 줄 9 < 머리 이름 칸 10.
|
||||
- **숫자 지표** `goal_metrics`(year·metric `sales|roas`·kind `target|actual`·month 1~12·value NUMERIC(18,2)) —
|
||||
매출 목표/실적/달성, 로아스 목표/실적. 매출 연간 = 월 합계, 달성률 = 실적÷목표(월별, **연간·반기는 그 기간 목표 합계 전체 대비 입력된
|
||||
@@ -573,11 +595,11 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
화면에서 계산(저장 안 함). 매출 단위 글자는 `goal_years.sales_unit`.
|
||||
- **업무 영역** `goal_areas`(연도별, 이름·색 `store.GOAL_AREA_COLORS` 연한 16색 + 색 없음(빈 값 = 흰 배경)·순서) → `goal_rows`(영역 안 줄, 최소 1줄 — 마지막 줄은
|
||||
못 지움) → `goal_cells`(row × month, **0 = 연간**, 빈 글 = 행 삭제). 영역 색이 줄 전체 배경.
|
||||
- 권한: 조회는 `project` 권한자 전원, **입력·구조 변경은 관리자만**(`_require_admin`, 화면도 관리자에게만 입력칸·도구).
|
||||
- 권한: 조회는 `project` 권한자 전원, **입력·구조 변경은 Pro user 이상**(`_require_pro`, 화면도 `pj_pro` 에게만 입력칸·도구 — 6-14).
|
||||
- 연도 추가(`POST /api/goals/years {year}`)는 가장 가까운 이전 연도(없으면 다음 연도)의 영역·줄 구조를 글 없이 복사,
|
||||
목표가 하나도 없으면 `store.DEFAULT_GOAL_AREAS`(상품·마케팅·컨텐츠·유통[콜라보·인플·쿠팡·기타]). 없는 연도 화면은
|
||||
관리자에게 "목표 만들기" 버튼(GET 에서 자동 생성하지 않는다). 연도 삭제는 연도를 직접 입력해야 진행(CASCADE 전부 삭제).
|
||||
- API(전부 관리자): `PUT /api/goals/{y}` `{sales_unit}` · `DELETE /api/goals/{y}` · `PUT /api/goals/{y}/metrics`
|
||||
- API(전부 Pro user 이상): `PUT /api/goals/{y}` `{sales_unit}` · `DELETE /api/goals/{y}` · `PUT /api/goals/{y}/metrics`
|
||||
`{metric,kind,month,value}`(빈값 = 지움, 응답 `label` 은 쉼표 표기) · `POST /api/goals/{y}/areas` `{name,color}` ·
|
||||
`PUT|DELETE /api/goals/areas/{id}` · `POST /api/goals/areas/{id}/move` `{direction:-1|1}` · `POST /api/goals/areas/{id}/rows` `{label, ref_row_id?, place?: above|below}`(기준 줄 위/아래, 없으면 맨 끝) ·
|
||||
`PUT|DELETE /api/goals/rows/{id}` · `POST /api/goals/rows/{id}/move` · `PUT /api/goals/rows/{id}/cells/{month}` `{body}`.
|
||||
@@ -605,7 +627,10 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
- **업무 영역 추가 · 줄 추가는 묻지 않고 바로**(2026-10-02) — 영역은 "새 업무 영역", 줄은 빈 이름으로 만들고 표를 다시 그린 뒤
|
||||
그 이름 칸을 바로 입력 상태로(`editNewName` → `startNameEdit`, Enter 저장 · Esc 그대로).
|
||||
- **분기 접기** — 분기 **머리 칸 아무 곳이나** 누르면(`.pj-goal-fold-th`, 너비 조절 손잡이를 끈 직후 0.3초 클릭은 무시) 그 분기 월 칸을
|
||||
접었다 편다. 아이콘은 엑셀 열 그룹처럼 네모 안 − (펼침, 누르면 접힘) / + (접힘) — 바뀔 때 90° 돌며 세로 막대가 자라거나 줄어든다.
|
||||
0.32초 동안 부드럽게 접었다 편다. 애니메이션 중에는 해당 월 칸 내용만 가리고, 글 칸은 원래 폭(`--fold-w`)으로
|
||||
높이를 유지한다. 펼침이 끝난 뒤 숫자·글을 표시하므로 오른쪽 정렬 숫자가 밀리지 않는다. 분기별 타이머를 교체해
|
||||
빠른 재클릭·여러 분기 동시 전환도 마지막 상태로 마무리한다. 동작 줄이기 설정에서는 즉시 표시/숨김한다.
|
||||
아이콘은 엑셀 열 그룹처럼 네모 안 − (펼침, 누르면 접힘) / + (접힘) — 바뀔 때 90° 돌며 세로 막대가 자라거나 줄어든다.
|
||||
- **분기 색(monday.com 그룹 색 띠 방식)** — 분기마다 차분한 색 하나(1 파랑 · 2 청록 · 3 보라 · 4 남색, 달성률 빨강·초록과 안 겹치게).
|
||||
`data-h` 가 있는 칸에 `--qc`·`--qt`·`--qt2`. 머리 위 색 띠 = 월 칸 3px · 분기 칸 6px(`th::before`, 월 링크가 덮어도 보임),
|
||||
분기 열 전체 옅은 음영(`td.pj-goal-half-col[data-h]` background-image — 영역 색 위에도), 분기 칸 오른쪽 2px 경계,
|
||||
@@ -701,7 +726,9 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
- **우클릭 너비 자동 맞춤**(2026-10-03) — 목표 표의 이름·글·숫자·머리 칸 모두 "현재 열 너비 자동 맞춤" / "전체 열 너비 자동 맞춤"을 표시한다.
|
||||
보기 전용 사용자도 사용 가능하며 너비는 브라우저에 저장한다. 현재 열은 경계 더블클릭과 같고, 병합 칸은 오른쪽 끝 열을 맞춘다.
|
||||
전체 맞춤은 접힌 월 열도 포함해 각 열의 가장 긴 문단에 맞추고, 병합 글에 부족한 폭은 그 병합의 마지막 열에 더한다.
|
||||
- **셀 테두리로 내용 이동**(관리자, 2026-10-03) — 업무 영역의 연간·월·분기 글 칸 하나를 클릭한 뒤 위·아래·왼쪽 테두리를 잡아
|
||||
- **셀 테두리로 내용 이동 — 연간 목표 표에서는 2026-10-07 요청으로 화면에서 없앴다**(테두리 손잡이·드래그 코드 삭제, 누른 칸 표시
|
||||
`is-goal-active` 만 남김. `POST /api/goals/cells/move` API 는 남아 있음. 주간 회의록 표의 이동은 그대로). 아래는 예전 설명 —
|
||||
(관리자, 2026-10-03) 업무 영역의 연간·월·분기 글 칸 하나를 클릭한 뒤 위·아래·왼쪽 테두리를 잡아
|
||||
다른 글 칸에 놓으면 내용과 색·크기·굵게·기울임·밑줄을 옮긴다. 오른쪽 경계는 열 너비 조절용이다. 끄는 동안 대상 칸을 표시하고
|
||||
표 가장자리에서는 자동 스크롤한다. Esc·창 포커스 해제·원본에 놓기는 취소한다. 대상에 글이 있으면 덮어쓰기를 확인한다.
|
||||
병합 시작 칸의 글도 이동 가능하며 병합 배치·영역 색·열 너비는 유지한다. 연간·분기의 기본 글자 서식도 명시해 원본의 표시를 보존한다.
|
||||
@@ -718,17 +745,28 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
|
||||
### 6-9-2. 주간 회의록 (마이그레이션 015)
|
||||
|
||||
왼쪽 목표 연도 아래에는 생성된 회의록만 월별 폴더 트리로 표시한다(`project-goal-nav.js`·`.css`,
|
||||
`GET /project/api/goals/meeting-nav`, 프로젝트 권한자 조회). 월요일이 속한 월로 묶고 월·주차는 날짜순이다.
|
||||
월 폴더는 아이콘과 함께 접기·펼치기를 지원하며 `pj_goal_month_open:{연도}:{월}`에 선택을 기억한다.
|
||||
연도 앞 화살표는 해당 연도의 하위 월 전체를 접고 펼친다(`pj_goal_year_open:{연도}`에 선택 기억, 기본 펼침).
|
||||
연도 글자를 누르면 기존 연간 목표 화면으로 이동한다. 연도를 접어도 각 월의 접기·펼치기 상태는 유지된다.
|
||||
현재 회의록의 월은 저장된 선택이 없으면 펼치고, 주간 링크는 그 주의 회의록으로 바로 이동한다. 조회로 회의록을 만들지 않는다.
|
||||
주간 링크·회의록 안 주차/달 이동은 왼쪽 DOM과 스크롤을 유지하고 오른쪽 문서만 교체한다.
|
||||
`?content=1`은 `_meeting_content_base.html`로 공통 메뉴 없는 회의록을 반환하며 `project-meeting-panel.js`가 부모 화면에 이동을 전달한다.
|
||||
주소·뒤로/앞으로 이동·선택한 주 표시를 동기화한다. 교체 전 `PJFlushForNavigation`이 글·금액 저장을 완료하고,
|
||||
실패하면 기존 회의록을 유지한다. 새 문서가 성공적으로 로드된 후 기존 문서를 제거해 편집 이벤트·타이머 중복을 방지한다.
|
||||
|
||||
지난주 목표·결과를 리뷰하고 월 목표를 달성하기 위한 이번주 목표·할 일을 정하는 회의(WBR — Weekly Business Review)용.
|
||||
참고한 도구 방식: **WBR 지표 자동 집계**(목표 대비 누적·주당 필요 매출 = 페이싱), **Fellow·Notion 회의 템플릿의 이월**(지난 회의
|
||||
항목을 다음 회의로 이어받아 나란히 리뷰), **OKR 체크인 평가**(완료/일부/미달).
|
||||
|
||||
- 화면 `/project/goals/{연도}/meetings/{월}?week={월요일}`(`goal_meeting.html`, `initGoalMeeting`) — 목표 표 월 머리를 누르면 열린다.
|
||||
- **주차 탭**: 그 달의 주(월~일, `store.month_weeks`) — **1주차 = 그 달 첫 월요일이 있는 주**, 주는 월요일이 속한 달의 것
|
||||
(2026-10-01 사용자 기준. 예: 2026년 10월 = 10/5·12·19·26 주, 9/28~10/4 는 9월 마지막 주). 다른 달의 주를 `?week=` 로 열면
|
||||
- **주차 탭**: 그 달의 주차(`store.month_weeks`) — **2026-10-07 부터 6-9-4 규칙**(그 달 안, 1주차는 1일부터, 말일 월·화는 앞 주차에).
|
||||
아래 "1주차 = 첫 월요일" 설명은 예전 규칙. 다른 달의 날짜를 `?week=` 로 열면
|
||||
그 달 회의록 주소로 303. 점 = 회의록 있음, "이번 주" 꼬리표. 기본 선택 = 이번 주(그 달 주면) 아니면 1주차.
|
||||
‹ 이전 달 · 다음 달 › 링크, ← 목표 표.
|
||||
- **월간 목표·누적은 늘 1일~말일**(주차와 따로): 월 누적 실적 = 1일 ~ 이 주 앞(지난주 일요일, 1주차면 첫 월요일 전날)까지,
|
||||
주당 필요 매출 = (월 목표 − 누적) ÷ 그 달 남은 주 수(이 주 포함).
|
||||
- **월간 목표·누적은 늘 1일~말일**: 머리 숫자는 2026-10-07 부터 6-9-4(월 목표 · 월 누적 목표 · 월 누적 실적 · 누적 목표 대비 차액·%).
|
||||
아래 "머리 숫자" 9칸 설명(주당 필요·전주 결과·금주 목표 등)은 예전 화면.
|
||||
- 머리 배치: 왼쪽 = **[🚩 {연도}년 목표] 버튼**(연간 목표로, 큰 강조 버튼 `.pj-meet-goalbtn` — 예전 ← 화살표 대신)·제목·‹이전 달·다음 달›·
|
||||
인쇄·회의록 삭제·**주차 탭(제목 줄 오른쪽 끝 = 달력 바로 왼쪽에 붙음, 한 줄짜리 작은 탭 — `1주차 10/5~11`, 같은 달이면 끝 월 생략, 전체 기간은 말풍선)**,
|
||||
그 아래 **{월}월 계획**(달력 앞까지 너비), **오른쪽 위 = 작은 달력**(폭 174px, 날짜 10.5px·칸 높이 21px). 목표·회의록 제목은 32px 굵게(`h2.pj-goal-title`).
|
||||
@@ -751,19 +789,20 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
"지난주 회의록에 없는 줄"). 예전엔 몇 주 전 회의록 줄이 지난주 날짜 아래 보였다(점검 버그 5).
|
||||
- 첫 회의록 기본 줄 마케팅 "메타"(예전 "메타(숫자)" — 017 이 그 이름 줄만 "메타"로 바꿈).
|
||||
- **{월}월 계획**(`router._month_plan`, `.pj-meet-plan`, 머리 왼쪽 `.pj-meet-headleft` 안 — 제목 줄 아래·달력 왼쪽): 연간 목표 표의 그 달 열 글을 업무 영역별 작은 카드로
|
||||
(영역 색, `항목: 글`, 빈 칸·글 없는 영역은 뺌). 가로 병합 칸(예: 9~10월)에 적은 글도 그 달 계획으로 보이고 범위를 오른쪽에 작게,
|
||||
표시(영역 색, `항목: 글`, 빈 칸·글 없는 영역은 뺌). 굵게·기울임·밑줄·글자 색상·줄바꿈·들여쓰기를 유지하고
|
||||
글자 크기만 카드 기본값을 사용(`goal_text_html(include_size=False)`), 원본 셀 서식은 변경하지 않는다.
|
||||
가로 병합 칸(예: 9~10월)에 적은 글도 그 달 계획으로 보이고 범위를 오른쪽에 작게,
|
||||
세로 병합은 한 번만, 묶인 줄(016 `label_cont`)은 묶음 항목 이름. 목표 표가 없으면(013 미적용) 칸 자체를 숨김, 읽기만.
|
||||
- **줄**(구역 = 목표 표 업무 영역, 표의 구역 칸 rowspan): 항목 | **이번주 할 일·행사** | **정량 목표**(원, 예전 이름 "목표 금액") ‖ 지난주 리뷰: 지난주 할 일 |
|
||||
지난주 목표 | **결과** | 달성률 | **평가**(— · 완료 · 일부 · 미달). 지난주 칸 = **7일 전 주 회의록에서 같은 연결키(`line_key`, 018)의 줄**
|
||||
- **줄**(구역 = 목표 표 업무 영역, 표의 구역 칸 rowspan): 항목 | **주요 업무**(`content`, 예전 "이번주 할 일·행사") | **정량 목표**(원, 예전 이름 "목표 금액")
|
||||
‖ 지난주 리뷰: **결과**(지난주 줄 `content`, 읽기 전용 — 예전 "지난주 할 일") | **전주 목표**(지난주 줄 `target_amount`, 예전 "지난주 목표") |
|
||||
**정량 목표**(지난주 줄 `result_amount` 입력, 예전 "결과"). 달성률·평가 열은 2026-10-06 요청으로 화면에서 뺐다(`status` 열·API 검증은 DB 호환으로 남음).
|
||||
지난주 칸 = **7일 전 주 회의록에서 같은 연결키(`line_key`, 018)의 줄**
|
||||
(예전 `carry_from` 은 이력으로만 — 6-9-3).
|
||||
결과는 그 줄이 **쇼핑몰 연결**(`marketplace_code`)이면 실적 모듈의 그 주(지난 회의록 주 월~일) 그 쇼핑몰 매출 **자동**("자동" 표시),
|
||||
아니면 직접 입력 — **지난 회의록 줄의 `result_amount`·`status` 에 저장**(그 주 결과는 그 주 줄에 남는다). 달성률은 저장 즉시 화면 계산.
|
||||
지난 회의록 주가 아직 시작 전이면 "진행 전"(0 으로 보이지 않게), 연결한 쇼핑몰이 실적 모듈에서 사용 중이 아니면(사용 OFF·없는 코드)
|
||||
"실적 미사용" 표시 + 직접 입력. 자동 결과 말풍선 = 쇼핑몰·기간, 0 이면 "그 기간 실적 없음 — [매출 업데이트]" 안내.
|
||||
쇼핑몰 연결 줄은 정량 목표 아래에 **이번주 실적**(이 주 월요일~오늘, 목표 대비 %)도 보인다 — % 는 화면이 실적(`slot data-auto`)과
|
||||
**서버 확정 정량 목표**(`tr data-target-amount`)로 계산(`paintMeetWeek`): 목표 저장 즉시 다시 계산(100→200 이면 100%→50%), 목표 0·빈칸이면
|
||||
% 없음, 실적 조회 실패면 "이번주 실적 미확인", 저장 실패면 확정값 그대로. 다시 그리기(`meetRepaint`)는 실적 값만 옮겨 와 같은 방식으로 계산하고
|
||||
차례 번호(`meetRepaintSeq`)로 늦게 온 옛 화면을 버린다 — 목표 저장과 엇갈려도 옛 비율이 들어오지 않는다(점검 버그 7).
|
||||
결과 금액은 **늘 직접 입력** — **지난 회의록 줄의 `result_amount` 에 저장**(그 주 결과는 그 주 줄에 남는다).
|
||||
**줄 단위 실적 연동은 2026-10-06 요청으로 폐지** — 쇼핑몰별 지난주 자동 결과, "자동입력"/"실적 미사용" 배지, 정량 목표 아래 "이번주 실적",
|
||||
줄 메뉴의 쇼핑몰 연결이 모두 없다. 실적 모듈 매출은 머리 카드(월 누적·주당 필요·전주 결과·금주 현재 실적)에만 쓴다.
|
||||
`goal_meeting_items.marketplace_code` 열·만들 때 추측(`store.guess_meeting_market`)은 DB 호환으로 남아 있으나 화면에서 쓰지 않는다.
|
||||
다시 그리기(`meetRepaint`)는 차례 번호(`meetRepaintSeq`)로 늦게 온 옛 화면을 버린다.
|
||||
- **매출 자료 갱신**(`initMeetingSync`, **정상이면 화면 표시 없음** — 2026-10-01 상태 줄·[매출 갱신] 버튼은 요청으로 뺐다. 점검 UX 9 로
|
||||
실패·일부 실패·권한 없음일 때만 숫자 막대 아래 한 줄 안내 `#pj-meet-sync.pj-meet-syncnote`(`data-state=error|partial|noperm|running`) +
|
||||
[다시 시도] — 실패한 쇼핑몰 이름(상태), **서버가 기록한** 마지막 갱신 성공 시각(`data-fresh` = 매출 집계 쇼핑몰 중 가장 오래된 성공 시각,
|
||||
@@ -771,7 +810,7 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
`{at, state: ok|partial|error|noperm, bad}` — 일부 실패를 성공으로 기록하지 않고, 10분 안 다시 열면 부르지 않되 그 상태 안내는 유지.
|
||||
실적 모듈 권한은 서버가 미리 알려 줘(`can_sync` → `data-can`) 권한이 없으면 API 를 부르지 않고 "권한이 없어 저장된 실적" 설명, 그래도 403 이면
|
||||
noperm 으로 기억해 그 세션엔 다시 부르지 않음. 다른 업데이트에 합류(`joined`)했는데 그 작업 기간이 이 주 기간을 다 덮지 못하면 이 주 기간으로
|
||||
한 번 더. 아래는 예전 설명(동작은 같음): 주차를 열면 실적 모듈 `POST /performance/api/sync {from: 지난주 월요일, to: 이번 주 일요일·오늘 중 이른 날, background: true}` 로 쇼핑몰에서 매출을 한 번 더 받고(진행 n/m 쇼핑몰·받은 자료), 끝나면 이 화면을 서버에서 다시 받아 **숫자 칸만** 바꿔 끼운다(머리 카드·자동 결과·달성률·이번주 실적 — 입력 중인 칸·직접 입력 결과 칸·저장 안 된 글은 그대로). 같은 주는 브라우저별 10분에 한 번만 자동(sessionStorage `pj_meet_sync:{월요일}` — 줄 추가 등으로 새로고침해도 다시 부르지 않음), [매출 갱신] 버튼은 언제나. 이미 다른 매출 업데이트가 돌면 그 작업이 끝나길 기다린다. 실적 권한이 없으면 저장된 실적으로 보여 준다는 안내, 실패한 쇼핑몰은 이름·상태. 지난주가 아직 오지 않은 주(미래)는 갱신 줄이 없다.
|
||||
한 번 더. 아래는 예전 설명(동작은 같음): 주차를 열면 실적 모듈 `POST /performance/api/sync {from: 지난주 월요일, to: 이번 주 일요일·오늘 중 이른 날, background: true}` 로 쇼핑몰에서 매출을 한 번 더 받고(진행 n/m 쇼핑몰·받은 자료), 끝나면 이 화면을 서버에서 다시 받아 **숫자 칸만** 바꿔 끼운다(머리 카드 — 입력 중인 칸·직접 입력 결과 칸·저장 안 된 글은 그대로). 같은 주는 브라우저별 10분에 한 번만 자동(sessionStorage `pj_meet_sync:{월요일}` — 줄 추가 등으로 새로고침해도 다시 부르지 않음), [매출 갱신] 버튼은 언제나. 이미 다른 매출 업데이트가 돌면 그 작업이 끝나길 기다린다. 실적 권한이 없으면 저장된 실적으로 보여 준다는 안내, 실패한 쇼핑몰은 이름·상태. 지난주가 아직 오지 않은 주(미래)는 갱신 줄이 없다.
|
||||
- **참석자 = 전체 멤버에서 고르기**(2026-10-01): 칩(사진·이름, × = 빼기) + [참석자] 고르기 창(찾기·전원 선택·모두 해제·체크) —
|
||||
후보는 `project` 모듈 권한 보유 등록 사용자(`router._meet_members`, 좌측 전체 멤버와 같음). 저장은 이메일을 쉼표로 이어 그대로
|
||||
`goal_meetings.attendees`(최대 3000자), 예전 자유 입력 글자는 칩으로 남는다(`_parse_attendees`). 바뀔 때마다 바로 저장.
|
||||
@@ -787,15 +826,97 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
롯데·지마켓·카카오·오늘의집 — 마케팅의 "네이버"는 광고라 연결 안 함). 줄 추가 때도 같은 추측.
|
||||
- 편집(관리자, 칸별 즉시 저장 — 목표 표와 같은 권한, 공용 `createFieldSaver` 6-9-3): 글 0.8초 멈춤·칸 떠남, 금액 Enter·칸 떠남(서버 확정값을
|
||||
쉼표 표기로 — 요청 뒤 다시 입력 중이면 그 초안 유지), 금주 목표 저장(`PUT` 응답에 확정 `week_target`) 뒤엔 **새로고침 없이** 머리 숫자만 서버
|
||||
계산으로 다시(`meetRepaint` — 다른 칸의 저장 안 된 글 보존). 줄 작업(추가·순서·쇼핑몰 연결·삭제)은 먼저 저장 안 된 칸을 저장하고, 실패하면
|
||||
작업하지 않는다(초안 유지). **항목 우클릭·⋯ 메뉴**: 위/아래에 줄 추가 · 위로/아래로(같은 구역 안) ·
|
||||
쇼핑몰 연결(결과 자동)…(연결 안 함 + 실적 모듈 사용 중 쇼핑몰, 현재 값 체크) · 줄 삭제. 구역 칸 + = 그 구역 끝에 줄, [+ 구역 추가].
|
||||
계산으로 다시(`meetRepaint` — 다른 칸의 저장 안 된 글 보존). 줄 작업(추가·순서·삭제)은 먼저 저장 안 된 칸을 저장하고, 실패하면
|
||||
작업하지 않는다(초안 유지). **항목 우클릭·⋯ 메뉴**: 위/아래에 줄 추가 · 위로/아래로(같은 구역 안) · 줄 삭제. 구역 칸 + = 그 구역 끝에 줄, [+ 구역 추가].
|
||||
줄 이름은 눌러서 그 자리에서 수정. 회의록 삭제 = 그 주 줄 전부 삭제, 다음 주 회의록의 지난주 칸은 빈다 — 그 주를 다시 만들면 같은 연결키로
|
||||
다시 이어진다(새 회의록이라 글은 비어 있음, 018).
|
||||
- **목표와 같은 셀 편집**: 주요 업무는 공용 `PJGoalText` 편집기·글자 서식 도구(`_cell_format.html`)를 사용한다.
|
||||
글자 일부를 선택해 색·크기(10~32px)·굵게·기울임·밑줄·초기화를 적용하며, `pj-rich:v1:` 형식으로 서식을 함께 저장한다.
|
||||
지난주 글·보기 전용 화면·인쇄도 허용한 서식만 출력하고, 사용자 글은 HTML escape한다. 글 길이 제한은 보이는 글 4,000자다.
|
||||
목표·회의록 표에서 글·숫자·이름 입력 중 문단이 현재 칸보다 길면 해당 열 너비만 자동으로 늘리고 브라우저에 기억한다.
|
||||
주간 회의록의 1열(구역)·2열(항목)은 행 높이·구역 병합·열 순서와 관계없이 항상 세로 가운데 정렬한다.
|
||||
할 일·리뷰 등 내용 칸은 상단 정렬한다.
|
||||
병합 칸은 나머지 열을 유지하고 오른쪽 끝 열을 늘린다. 입력 중 지워도 너비는 자동으로 줄이지 않으며, 수동 자동 맞춤으로 줄일 수 있다.
|
||||
글 셀 Enter는 한 번에 개행하며 마지막 개행 뒤의 빈 줄·커서도 즉시 보인다. 빈 줄 표시용 요소는 저장 데이터에 포함하지 않는다.
|
||||
`project-meeting-cells.js`는 열 경계 드래그·더블클릭/우클릭 현재·전체 열 자동 맞춤, **열 때마다 전체 열 자동 맞춤으로 시작**(2026-10-07 —
|
||||
저장된 `pj_meet_col_w` 보다 우선, 글꼴 로딩 뒤 사람이 너비를 안 바꿨으면 한 번 더 맞춤),
|
||||
같은 구역 글 셀 범위 선택(드래그·Shift+클릭), 내용 지우기(Del)·되돌리기(Ctrl+Z), 테두리 드래그 내용·서식 이동을 제공한다.
|
||||
이동은 먼저 초안을 저장하고 원본·대상 예상값을 서버에서 비교한다. 값 변경은 409, 두 칸 변경은 한 트랜잭션으로 처리하며
|
||||
응답 유실 후 같은 이동을 재전송해도 글을 다시 지우지 않는다. 열 순서 변경·75% 배율에도 논리 열 기준 너비를 유지한다.
|
||||
**병합/해제(019)**는 같은 구역의 이번주 글 셀을 세로로 묶는다. 글·서식은 첫 셀에 줄바꿈으로 합치며, 해제해도 합친 글은 첫 셀에 남는다.
|
||||
금액·계산값 칸은 독립적으로 유지한다. 병합 범위 안에 줄을 삽입하거나 해당 줄을 이동·삭제하려면 먼저 병합을 해제한다.
|
||||
글 저장·이동·병합·줄 작업은 주차 머리를 먼저 잠가 동시 구조 변경을 직렬화한다. 019 미적용 시 병합 메뉴만 숨기고
|
||||
병합 API는 503을 반환하며, 다른 셀 편집 기능은 사용할 수 있다.
|
||||
- API(관리자, 조회는 `project` 권한자): `GET /api/goals/meetings/{월요일}?year=&month=`(화면과 같은 계산) · `POST|PUT|DELETE
|
||||
/api/goals/meetings/{월요일}`(PUT `{week_target, attendees, notes}`) · `POST /api/goals/meetings/{월요일}/items {section, label?,
|
||||
ref_item_id?, place?}` · `PUT|DELETE /api/goals/meeting-items/{id}`(PUT `{label, content, target_amount, result_amount, status,
|
||||
marketplace_code}`) · `POST /api/goals/meeting-items/{id}/move {direction}`. 015 미적용 503, 월요일 아님·금액 형식 400.
|
||||
셀 편집 API: `POST /api/goals/meeting-cells/move {source_item, target_item, source_body, target_body}` ·
|
||||
`POST /api/goals/meeting-cells/merge {item_from, item_to}` · `DELETE /api/goals/meeting-items/{id}/cell-merge`.
|
||||
|
||||
### 6-9-4. 새 주차 · 위쪽 고정 영역 · 지난주 결과 글 · 주차별 매출 목표 (마이그레이션 020, 2026-10-07)
|
||||
|
||||
- **주차**(`store.month_weeks` — 6-9-2·6-9-3 의 "월요일~일요일 / 7일 전" 설명을 대신한다): 주차는 **그 달 안**에서만 나눈다.
|
||||
1일이 월~금이면 1주차 = 1일 ~ 그 주 일요일, 1일이 토·일이면 1주차 = 1일 ~ 다음 주 일요일, 그 뒤 월~일,
|
||||
**말일이 월·화이면 그 하루·이틀은 앞 주차에 붙는다**. 예: 2026-10 = 10/1~4 · 5~11 · 12~18 · 19~25 · 26~31,
|
||||
2026-08 = 8/1(토)~9 · 10~16 · 17~23 · 24~31(월). 헬퍼: `week_period(날짜)` · `prev_week_period(시작일)`(= "지난주",
|
||||
앞 달 마지막 주차일 수 있음) · `week_number` · `validate_period_start`(새 회의록·주차 목표는 주차 시작일만).
|
||||
회의록 `week_start` = 주차 시작일(월요일이 아닐 수 있음). 화면 `?week=` 에 아무 날짜(예전 월요일 주소)를 주면 그 날짜가 든 주차로.
|
||||
작은 달력은 월요일 시작 줄 그대로, 줄을 누르면 그 줄의 이 달 날짜가 든 주차(한 주차가 두 줄일 수 있음).
|
||||
- **지난주** = 바로 앞 주차(`db.get_meeting` 이 `store.prev_week_period` 로 찾음) 회의록의 같은 연결키 줄.
|
||||
- **머리 영역 3칸**(2026-10-07 개편, 아래 "위쪽 고정 영역" 설명을 대신함): 제목 줄 아래 `.pj-meet-board`(머리 `.pj-meet-headgrid` 안 —
|
||||
`.pj-meet-pane` 밖이라 표를 스크롤해도 늘 보임, 칸 높이 230px·안에서 스크롤) = ① 월 계획(`router._month_plan`) + 머리 줄 오른쪽에
|
||||
숫자 4개를 작게 1행(`.pj-meet-kpiline` — 월 목표 · 누적 목표 · 누적 실적 · 목표 대비, 클래스는 `.pj-meet-kpi` 그대로라 `meetRepaint` 가 갱신)
|
||||
② 결정 사항·메모(`#pj-meet-notes`, 회의록이 있을 때) ③ **작업 등록 표**(`#pj-meet-quick`, `initMeetQuickTasks`): 제목 | 담당자 | 프로젝트 | 섹션 |
|
||||
[적용]. 빈 칸을 누르면 `showContextMenu`(body) 목록 — 프로젝트 = `GET /api/projects` 의 최상위(내가 멤버인 것), 고르면 첫 섹션 자동,
|
||||
담당자 = 그 프로젝트 멤버+소유자(`GET /api/projects/{id}/members`, 프로젝트 전이면 `PJ_MEET_MEMBERS`; 프로젝트를 바꿔 멤버가 아니면 비움),
|
||||
섹션 = `GET /api/projects/{id}/stages`. [적용] = `POST /api/projects/{id}/tasks {title, stage_id, assignee_email}`(서버가 멤버·담당자 권한 검사)
|
||||
→ 줄에 "등록됨" 링크(`/project/p/{id}?task=`) + 삭제(확인 뒤 `DELETE /api/tasks/{id}` — 그 프로젝트 작업도 삭제, 휴지통, 이미 없으면 줄만 지움),
|
||||
적용 전 줄의 × = 줄만 지움. 줄(등록된 줄 포함)은 localStorage `pj_meet_quick:{이메일}`. 예전 `#pj-meet-top`(pane 안 sticky)은 없앴다.
|
||||
- (예전) **위쪽 고정 영역**(`#pj-meet-top`, `.pj-meet-pane` 안 sticky): 왼쪽 절반 숫자 4칸 — **월 목표 매출**(목표 표, = 주차 목표 합) ·
|
||||
**월 누적 목표 매출**(주차별 목표 1주차~이 주차 합, 원) · **월 누적 실적**(1일 ~ 오늘, 지난 주차면 그 주차 끝날 — 실적 모듈) ·
|
||||
**누적 목표 대비 달성**(실적 − 누적 목표 차액 + 실적 ÷ 누적 목표 %) / 오른쪽 절반 **결정 사항·메모**(예전엔 표 아래).
|
||||
표 머리 줄 sticky top = 이 영역 높이(`--pj-meet-top-h`, `initMeetTop` 의 ResizeObserver). 예전 9칸(주당 필요·목표 ROAS·전주 목표·
|
||||
전주 결과·전주 달성률·금주 목표 입력·금주 현재 실적)은 없앴다(`goal_meetings.week_target` 열·API 는 남음). `head` 키:
|
||||
`month_target_won · week_targets_set · cum_target · cum_target_won · mtd · mtd_end · gap · rate · prev_exists · perf* · unknown · fresh*`.
|
||||
- **표 열**: 구역 | 항목 | 주요 업무 | 정량 목표 ‖ 지난주 리뷰: **전주 업무**(지난 주차 `content`) | **결과**(글, 지난 주차 줄
|
||||
`result_note` — 020, `.pj-meet-rnote` textarea, 0.8초 멈춤·칸 떠남 저장, 초안 `pj_draft:meet:item:{지난 줄}:result_note`) |
|
||||
**전주 목표**(지난 주차 `target_amount`) | **결과**(금액, 지난 주차 `result_amount`). 020 미적용이면 결과 글 칸은 보기만, API 503.
|
||||
- **주차별 매출 목표**(`goal_week_targets(week_start PK, year FK goal_years CASCADE, month, value NUMERIC)` — 목표 표 매출 단위 그대로):
|
||||
연간 목표 표 매출 **목표** 월 칸(`data-weekly`, readonly)을 누르면 그 달 입력 창(`.pj-goal-wkpop`, body 에 붙음, 보기만 하는 사람은 값만).
|
||||
맨 위 **월 전체 목표**(직접 입력) → 주차별 목표 → 맨 아래 **주차 합계**·**차이(월 목표 − 주차 합계**, + 주황 = 덜 나눔,
|
||||
− 빨강 = 넘침, 0 초록). `PUT /project/api/goals/{연도}/week-targets/{월} {month: 월 목표|"", weeks: {주차 시작일: 값|""}}`
|
||||
(관리자) → 주차 저장 + `goal_metrics(sales, target)` 에 `month` 그대로(빈값 = 지움, 주차 합계와 무관). `month` 가 없는 요청(예전
|
||||
화면 캐시)만 주차 합계를 월 목표로. 020 미적용이면 예전처럼 월 칸 직접 입력.
|
||||
- **020 마이그레이션**(`scripts/sql/project_db_020_meeting_periods.sql`, 멱등): ① `goal_meeting_items.result_note` ② `goal_meetings`
|
||||
월요일 CHECK 제거 ③ `goal_week_targets` ④ 새 주차에 흡수된 월요일 회의록(1일이 토·일인 달의 2·3일 월요일 → 1일, 말일이 월·화인 달의
|
||||
마지막 월요일 → 7일 전 월요일)을 옮김 — 옮길 자리에 회의록이 있으면 옮기지 않고 NOTICE. 이미 쓰던 9/28(월) 회의록은 9월 마지막 주차
|
||||
(9/28~30)로 그대로 남고, 10월 1주차(10/1~4)는 새로 만든다(그래서 10/5 주차의 지난주 리뷰는 10/1~4 회의록이 생겨야 채워진다).
|
||||
- 코드는 020 전에도 동작(결과 글 보기만, 주차 목표 없음, 월요일 아닌 주차 회의록 만들기만 503 안내).
|
||||
- **회의록 보드**(2026-10-07): 참석자 오른쪽 [회의록 보드] → 그 주차의 **빈 Google 슬라이드**를 독립 창(`window.open` popup, 창 이름
|
||||
`pj_meet_board_{주차}`)으로. 누르는 순간 빈 창을 먼저 열고(팝업 차단 회피) `POST /project/api/goals/meetings/{주차 시작일}/board`
|
||||
(프로젝트 권한자 누구나) 가 준 주소로 바꾼다. 서버(`app/integrations/google_slides.py`)는 공유 드라이브 `MEETING_BOARD_FOLDER_ID`
|
||||
(기본 0AGF3CIEboPQiUk9PVA)에서 Drive appProperties `dbxMeetingWeek = 주차 시작일` 인 슬라이드를 찾고, 없으면 만든다 —
|
||||
이름 `{월}월 {n}주차 ({기간})`(`router.meeting_board_title`), 첫 장의 제목·부제목 틀(TITLE 레이아웃)을 지우고 틀 없는 BLANK 한 장만.
|
||||
파일 이름을 바꿔도 같은 보드, 휴지통에 버리면 다음에 새로 만든다. 인증은 Google 시트 설정 재사용 + Drive·Slides 범위
|
||||
(`GOOGLE_SLIDES_OAUTH_REFRESH_TOKEN` 없으면 시트 토큰 — Drive·Slides 권한으로 재발급 필요, docs/DEPLOYMENT.md). DB 변경 없음.
|
||||
- **회의록 누구나 수정 · 회의 완료 잠금**(마이그레이션 022, 2026-10-07): 회의록 만들기·머리 칸·줄 추가/삭제/이동·셀 이동/병합·줄 칸 API 가
|
||||
`_require_admin` → `_require_user`(프로젝트 권한자 누구나). 회의록 삭제와 `POST /api/goals/meetings/{주차}/complete {done}`(회의 완료·완료 해제)만
|
||||
Pro user 이상(2026-10-12, 예전 관리자). `goal_meetings.completed_at`·`completed_by` 가 있으면 잠금 — `db._check_meeting_open`(머리 칸·줄 추가·`_locked_meeting_items`)이
|
||||
`store.MeetingLocked` → 409. 예외: 줄 칸 변경이 결과(`result_note`·`result_amount`·`status`)뿐이면 그 줄의 회의록이 아니라 **바로 다음 주차
|
||||
회의록**(그 결과를 적는 회의)의 잠금을 본다. 화면은 `data-edit`(완료 전이면 누구나) 로 편집 도구를 켜고, Pro user 이상에게 [회의 완료]/[완료 해제],
|
||||
완료면 "🔒 회의 완료" 표시. 022 전이면 완료 버튼 없음(`meeting.can_complete`).
|
||||
- **알림 팝업**(2026-10-07): 나를 태그(mention)하거나 작업을 배정(assigned)받으면 프로젝트 화면 가운데 아래에 깜박이는 큰 팝업(`initTaskAlerts`,
|
||||
`.pj-alert-pop`, body 에 붙음) — [닫기] 전까지 남는다. 20초마다(창을 다시 볼 때 바로) `GET /api/notifications/alerts?after=본 것`(읽지 않은
|
||||
mention·assigned 중 after 보다 새 것, 지금 볼 수 있는 작업만, 오래된 것부터 10). 본 것 = localStorage `pj_alert_seen:{이메일}`, 처음 쓰는 브라우저는
|
||||
latest_id 를 기준으로 삼아 옛 알림을 한꺼번에 띄우지 않는다. 다른 탭에서 닫으면 storage 이벤트로 함께 닫힌다. 수신함 iframe 안에선 돌지 않는다.
|
||||
- **섹션 색 없앰**(2026-10-07): 보드 섹션 머리는 모두 `#f3f3f3`(`STAGE_HEAD_BG`), 섹션 편집 창의 색 고르기 삭제(저장 때 color 를 보내지 않는다),
|
||||
타임라인 줄 색은 프로젝트 색. DB 의 `project_stages.color` 값은 남아 있지만 화면에서 쓰지 않는다.
|
||||
- **정량 목표·결과(금액)에 글**(마이그레이션 021, 2026-10-07): 입력이 숫자로 읽히면(`store.validate_meeting_amount` — 1,200,000 · 120만 ·
|
||||
1.5억) 지금처럼 `target_amount`/`result_amount`(원 정수), 아니면(예: "20개", 100자까지) `target_text`/`result_text` 에 — 둘 중 하나만
|
||||
채운다(숫자로 바꾸면 글은 비움). 화면·전주 목표는 글이 있으면 글, 없으면 쉼표 숫자. 021 전이면 글은 예전처럼 400(숫자 오류).
|
||||
입력칸은 `inputmode` 없음(글 키보드). 같은 날 함께 고침: `PUT /api/goals/meeting-items/{id}` 허용 키에 `result_note` 가 빠져
|
||||
결과 글이 저장되지 않던 문제.
|
||||
|
||||
### 6-9-3. 저장 안전장치 · 지난주 연결 · 실적 미확인 (2026-10-01 점검 반영 — `docs/reviews/GOALS_MEETINGS_REVIEW_2026-10-01.md`, 마이그레이션 018)
|
||||
|
||||
@@ -842,8 +963,8 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
|
||||
**실적 미확인(버그 6)** — `router._MeetingPerf`: `state` = `off`(실적 모듈 미연결) · `error`(쇼핑몰 목록 조회 실패) · `empty`(매출 집계 쇼핑몰 없음) · `ok`.
|
||||
조회 실패한 값은 None + `head.unknown`(`mtd`·`prev_result`·`week_result`, 기간마다 따로 → 부분 실패), 화면 "⚠ 미확인", 그 값에 기대는 달성 %·주당 필요
|
||||
매출도 계산하지 않음. 정상 조회 0건만 0원. 목록 장애면 쇼핑몰 연결 줄 결과 = 미확인(직접 입력 칸으로 바꾸지 않음, "실적 미사용"으로 오인하지 않음),
|
||||
연결 배지 "· 미확인". `head.perf` 는 예전 뜻(실적 모듈 연결 여부) 그대로 — 갱신 상자·"연결되지 않아" 문구 조건. 회의록 열기·직접 입력은 그대로.
|
||||
매출도 계산하지 않음. 정상 조회 0건만 0원. 줄 결과는 자동이 아니라 늘 직접 입력.
|
||||
`head.perf` 는 예전 뜻(실적 모듈 연결 여부) 그대로 — 갱신 상자·"연결되지 않아" 문구 조건. 회의록 열기·직접 입력은 그대로.
|
||||
|
||||
**테스트** — `tests/test_project_module.py`(`test_meeting_prev_week_links`: 역순 생성·같은 이름·다른 구역 같은 이름·이름 변경·이동·새 줄·삭제/재생성·
|
||||
건너뛴 주, 018 적용/미적용 둘 다 · `test_meeting_perf_unknown_vs_zero`: 미연결·목록 장애·매출 장애·부분 실패·정상 0·집계 쇼핑몰 없음),
|
||||
@@ -890,7 +1011,7 @@ description 을 항상 HTML로 취급하기 때문). 두 번 실행하면 이중
|
||||
`client_token`) 한 요청으로, 댓글+첨부를 한 트랜잭션(`add_comment_with_attachments`)에 만든다. 빈 파일·20MB 초과가 하나라도
|
||||
있으면 아무것도 만들지 않고 400 `detail.failed=[{index,name,reason}]` → 화면은 그 파일만 빨갛게 표시하고 입력·파일을 유지.
|
||||
DB 실패면 방금 쓴 파일도 지운다. 글 댓글(`POST /comments`)은 본문 필수 — 예전 `has_attachment` 플래그는 받지 않는다.
|
||||
`client_token` 으로 같은 댓글의 재전송(응답 유실·연타·동시 요청)은 10분간 첫 결과를 돌려준다(웹 프로세스 메모리, 단일 워커 기준).
|
||||
`client_token` 으로 같은 댓글의 재전송(응답 유실·연타·동시 요청)은 10분간 첫 결과를 돌려준다(웹 프로세스 메모리 — 보장 범위는 6-15).
|
||||
작업 창 댓글 목록도 댓글별 첨부(이미지 미리보기·파일명 다운로드, 이스케이프)를 보여 주고, 첨부 파일 목록엔 "댓글" 표시.
|
||||
|
||||
**마감 알림** — `add_reminder_notification`: 발송 기록(`task_reminders`)과 수신함 알림을 한 트랜잭션에. 알림 생성이 실패하면
|
||||
@@ -920,7 +1041,160 @@ SELECT t.id, t.title FROM tasks t JOIN project_stages s ON s.id = t.stage_id
|
||||
교정안: 날짜 역전은 담당자와 확인해 한쪽을 고치고, 빈 댓글은 작성자 확인 후 삭제, 완료 섹션 미완료는 완료로 표시하거나 섹션을 옮긴다.
|
||||
권한을 잃은 사람의 담당자·멘션·협업자 기록은 지우지 않아도 된다(화면·알림은 이미 지금 권한으로 거른다).
|
||||
|
||||
## 6-11. PC 알림 프로그램 (마이그레이션 023, 2026-10-08)
|
||||
|
||||
웹 큰 팝업(`initTaskAlerts`)은 브라우저 탭이 보일 때만 뜬다. 브라우저가 뒤에 있어도 같은 알림을 PC 화면 위에 크게 띄우는
|
||||
Windows 트레이 프로그램 **DBX 알림**(`desktop/notifier/`, C# .NET Framework 4.8 WinForms, exe 하나). 빌드·배포·백신 주의는
|
||||
`desktop/notifier/README.md`.
|
||||
|
||||
- **연결(토큰)**: 브라우저 쿠키를 쓸 수 없어 PC마다 토큰. ① 프로그램 `POST /project/api/notifier/link/start {device}`(로그인
|
||||
없음 → 화면 코드 `XXXX-XXXX` + poll 비밀값, 10분, 대기 200건 상한 429) → ② 브라우저 `/project/notifier?code=`(로그인 필요,
|
||||
없으면 `/login?next=`)에서 PC 이름·코드 확인 후 [연결] = `POST .../link/approve {code}` → ③ 프로그램 `POST .../link/poll {poll}`
|
||||
→ `pending`/`expired`/`ok`(토큰 **한 번만**). `notifier_links`·`notifier_tokens` 에는 poll·토큰 **SHA-256 만** 저장.
|
||||
PC 쪽 토큰은 Windows DPAPI(현재 사용자)로 암호화해 `%APPDATA%\DBXNotifier\settings.json`.
|
||||
- **알림**: `GET /project/api/notifier/alerts?after=` (`Authorization: Bearer`) — 웹 `/api/notifications/alerts` 와 같은
|
||||
`_alerts_payload`(태그·배정, 읽지 않은 것, 지금 볼 수 있는 작업만) + `name`. 토큰마다 **지금** 사용자 레코드·`project` 권한을
|
||||
다시 확인(해제·권한 회수 = 401 → 프로그램이 연결 끊김 안내). `POST .../alerts/{id}/read`, `POST .../logout`(토큰 해제).
|
||||
- **프로그램 동작**: 20초마다 확인(절전 해제 시 바로). 처음 연결하면 최신 번호를 기준으로(옛 알림 몰아 띄우지 않음),
|
||||
새 번호가 오면 마우스가 있는 화면 아래 가운데에 웹과 같은 모양의 큰 창(맨 위, 포커스 안 뺏음, 보라↔주황 깜박임, 최대 6줄 +
|
||||
"외 N건 더") + 알림 소리. [열기] = 기본 브라우저로 작업 + 읽음, [닫기] = 그 번호까지 본 것으로(PC 설정 `last_seen`).
|
||||
웹에서 읽은 알림은 다음 확인 때 창에서 빠진다. 웹 팝업의 "본 것"(localStorage)과는 따로다.
|
||||
- **화면** `/project/notifier`(수신함 머리의 [PC 알림] 버튼으로 들어감, 사이드바는 수신함 활성): 연결 승인 카드, 설치 안내, 내 연결된 PC 목록·[연결 해제]
|
||||
(`POST /project/api/notifier/devices/{id}/revoke`). 내려받기 `GET /project/notifier/download` = 서버
|
||||
`DATA_DIR/notifier/DBXNotifier.exe`(컨테이너 `/data/notifier/`) — 파일이 없으면 버튼 대신 "관리자에게 받으세요".
|
||||
- **웹 팝업 쉬기**: 그 사용자의 PC 알림 프로그램이 돌고 있으면(해제 안 된 토큰 중 `last_seen_at` 3분 안 — `st.notifier_active`)
|
||||
웹 `/api/notifications/alerts` 는 알림 없이 `latest_id` + `desktop: true` 만 준다. 웹은 그 번호까지 본 것으로 두므로, 프로그램을 끄면
|
||||
3분쯤 뒤 그 뒤에 온 알림부터 웹 팝업이 다시 뜬다. 사용자 단위(어느 PC 에서 켰든 모든 브라우저 팝업이 쉼). 확인 실패면 웹 팝업 그대로.
|
||||
- 023 미적용이면 화면은 안내만, notifier API 는 503.
|
||||
|
||||
## 6-12. 아사나 아이콘 · 색 12열 · 섹션 굵게 · 전체 보기 메뉴 · 설명란 글자 색/크기 (2026-10-08, 마이그레이션 없음)
|
||||
|
||||
- **프로젝트 색상표** 12칸씩(32색 = 3줄). **아이콘** 머리 "아이콘" 오른쪽 탭 [기본 아이콘](`PROJECT_ICONS`, 외곽선) /
|
||||
[아사나 아이콘](`PROJECT_ASANA_ICONS` 33개, 채워진 모양). 아사나 아이콘 값은 `"asana:" + 이름`(`projects.icon` TEXT 그대로),
|
||||
`validate_project_icon` 이 두 목록만 허용. 채워진 모양은 그 33개만 담은 글꼴
|
||||
`static/vendor/material-symbols/material-symbols-asana.woff2`(Google Fonts `FILL 1` + `icon_names=` 부분 글꼴, 약 6KB) —
|
||||
`.material-symbols-outlined.pj-ic-asana`. 목록을 늘리면 글꼴도 그 이름들로 다시 받는다. 그리는 곳: `projIconSpan`(JS)·
|
||||
`_side.html`·`project.html` 제목 알약.
|
||||
- **섹션 이름 굵게**(보드 `.pj-col-name`, 목록 묶음 `.pj-list-group-name`, 이름 바꾸기 칸).
|
||||
- **전체 보기**: 프로젝트 화면 오른쪽 위 범위 토글(`#pj-scope-toggle`)은 숨기고, 왼쪽 메뉴 수신함 아래 **전체 보기**(Pro user 이상,
|
||||
`#pj-side-allview`) — 지금 프로젝트(없으면 목록 첫 활성 프로젝트) `/project/p/{id}?scope=all`. 프로젝트 화면에서는 새로고침 없이
|
||||
`applyAllScope(true)`. `?scope=all` 은 `data-is-pro` 일 때만 따른다. 이 프로젝트로 돌아가기 = 왼쪽 목록에서 프로젝트.
|
||||
- **수신함 작업 창**: [확인]으로 연 오른쪽 작업 창은 왼쪽 수신함 영역(`.pj-inbox-view`)을 누르면 닫힌다(메뉴·모달·알림 팝업 제외).
|
||||
- **설명란 글자 색·크기**: 서식 도구 [글자 색](10색, 기본)·[글자 크기](작게 12px·보통·크게 18px·더 크게 22px·제목 28px).
|
||||
`execCommand` 가 만든 `<font>` 를 바로 `<span style>` 로 바꾸고, 서버 `sanitize_description_html` 은 평범한 span 의 style 에서
|
||||
`color`(#hex·rgb()) 와 `font-size`(`DESC_FONT_SIZES`)만 다시 조립해 남긴다(`desc_inline_style`). 멘션 칩·다른 태그의 style 은 버림.
|
||||
|
||||
## 6-13. 수신함 줄 클릭 · 용어 · 회의록 보드 링크 복사 (2026-10-08, 마이그레이션 없음)
|
||||
|
||||
- **수신함**: `inbox_page` 는 읽지 않은 알림(`unread_only`)·확인 안 한 태그(`unread_mentions`)만. [확인] 버튼 없음 — 줄(`data-href`,
|
||||
`data-task-id`)을 누르면 `initInboxTaskPanel` 이 같은 작업의 줄(태그·알림)을 모두 확인(`POST /api/mentions/read {task_id}`,
|
||||
`POST /api/notifications/{id}/read`)하고 오른쪽 iframe 작업 창을 연다. 다른 줄을 고르거나 창을 닫으면 앞서 확인한 줄은 목록에서
|
||||
빠진다(빈 목록이면 "없습니다"). 오른쪽 클릭 = 열지 않고 확인. [태그 모두 확인]·[알림 모두 읽음] = 그 목록을 비운다.
|
||||
- **용어**: 프로젝트 모듈 화면 글자 "하위 작업" → **"세부 작업"**, "작업 추가" → **"메인 작업 추가"**(세부 작업 추가는 그대로).
|
||||
대시보드 담당자별 막대 이름 "메인 작업"·"세부 작업".
|
||||
- **담당자별 작업 합계 — 세부 작업의 세부 작업까지**: `list_subtasks_of` 가 재귀 CTE 로 모든 단계(깊이 20 까지)를 돌려주고
|
||||
`root_task_id`(맨 위 메인 작업)·`parent_title`(바로 위 작업) 을 붙인다. 화면은 `root_task_id` 가 이 범위 메인 작업이면 센다.
|
||||
- **회의록 보드 링크 복사**: [회의록 보드] 오른쪽 🔗(`#pj-meet-board-copy`) — 같은 `POST …/board`(없으면 만든다)로 주소를 받아
|
||||
클립보드에(실패하면 주소 창). 한 번 받은 주소는 그 화면에서 다시 쓴다.
|
||||
|
||||
## 6-14. 관리자 등급 4단계 — 수퍼관리자 · Admin · Pro user · User (2026-10-12, 마이그레이션 없음)
|
||||
|
||||
- **등급**: 사용자 레코드 `role` 이 `admin` / `pro` / `user`(`app.store.ROLES`, 관리자 페이지 등급 선택 — 표시 Admin · Pro user · User).
|
||||
수퍼관리자는 role 이 아니라 `SUPER_ADMIN_EMAIL` 한 명(고정, 등급 변경·삭제·추가 불가). `pro` 는 **프로젝트 모듈에서만** 권한이
|
||||
늘고, 그 밖(관리자 페이지·다른 모듈·`is_admin`)에서는 `user` 와 같다. 모듈 칩 기본값도 user 처럼 전부 꺼짐.
|
||||
- **판단 함수**(`access.py`): `role_of` · `is_pro`(수퍼관리자·Admin·Pro user) · `is_project_admin`(수퍼관리자·Admin).
|
||||
라우터 `_require_pro`(예전 `_require_admin` 자리 전부), 화면 값 `_role_ctx(user)` → `is_admin`(ERP 상단 관리자 메뉴용, 그대로) ·
|
||||
`pj_pro` · `pj_admin`. 템플릿의 프로젝트 기능 버튼은 `pj_pro`, 마크업은 `data-is-pro`·`data-is-padmin`(사이드바·프로젝트·내 작업),
|
||||
목표 표·회의록은 `data-pro`.
|
||||
- **프로젝트 보기는 여전히 멤버·owner 만**(관리자도 마찬가지, 수퍼관리자만 전체 — 6-10). 아래 Pro user 권한도 멤버인 프로젝트 안에서만.
|
||||
|
||||
| 프로젝트 | Admin | Pro user | User | 서버 |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| 프로젝트 보기, 작업·섹션 만들기·고치기·옮기기 | O | O | O | `_require_manage` |
|
||||
| 작업 삭제(휴지통) | O | O | O | 멤버면 누구나 — 생성자 검사 없앰 |
|
||||
| 섹션 삭제 | O | 만든 사람만 | 만든 사람만 | `_can_delete` (기록 없는 옛 섹션 = Admin 이상) |
|
||||
| 서브프로젝트 만들기 | O | O | O | `_require_manage` |
|
||||
| 새 프로젝트 만들기 | O | O | X | `POST /api/projects` → `_require_pro` |
|
||||
| 프로젝트 이름·색·아이콘·날짜·완료 수정, 소유자 바꾸기 | O | O | X | `PUT /api/projects/{id}` → `_require_pro` + 멤버 |
|
||||
| 프로젝트 삭제 | O | 만든 사람만 | 만든 사람만 | `_can_delete` + 멤버 |
|
||||
| 멤버 배정·제외(+ 배정 후보 목록) | O | O(멤버인 프로젝트) | X | `_require_pro` + `_require_manage` |
|
||||
| 사이드바 프로젝트 순서 | O | O | X | `PUT /api/projects/order` |
|
||||
| 댓글 수정·삭제 / 댓글에 파일 붙이기 | O | 남의 것도 | 본인만 | `update_comment`·`delete_comment(is_admin=is_pro)` |
|
||||
| 휴지통 보기·복구 | O | O | X | `/trash`·`/api/trash/{id}/restore` |
|
||||
| 전체 보기 | O | O(멤버 범위) | X | 화면 `isPro` (`?scope=all` 도 isPro 일 때만) |
|
||||
| 대시보드 담당자별 작업 합계 | O | O | X(안 보임) | `GET …/subtasks-summary` → `_require_pro` |
|
||||
| 사이드바 전체 멤버 | O | O | X | 화면 `pj_pro` |
|
||||
| 수신함·내 작업·PC 알림 | O | O | O(자기 것) | 변화 없음 |
|
||||
|
||||
| 목표·주간 회의록 | Admin | Pro user | User |
|
||||
| --- | --- | --- | --- |
|
||||
| 연간 목표 표 보기 | O | O | O |
|
||||
| 목표 표 입력·구조 변경(매출·로아스, 영역·줄, 칸 병합·이동), 주차별·월 매출 목표, 연도 추가·삭제 | O | O | X |
|
||||
| 회의록 만들기·글 수정·줄 추가·삭제·칸 병합(완료 전까지), 지난주 결과(다음 주 회의록이 열려 있는 동안) | O | O | O |
|
||||
| 회의 완료·완료 해제, 회의록 삭제 | O | O | X |
|
||||
| 회의록 보드 열기·링크 복사 | O | O | O |
|
||||
| 회의록 작업 등록 표로 작업 만들기 | 멤버인 프로젝트만 | 멤버인 프로젝트만 | 멤버인 프로젝트만 |
|
||||
|
||||
- 회의록 표 첫 열 머리 글자 "구역" → **"구분"**(화면 글자만, 데이터·코드의 section 이름은 그대로).
|
||||
- 테스트: `tests/test_project_roles.py`(DB 없이 등급별 API), `tests/test_project_module.py` 의 소유자·삭제 테스트를 새 규칙으로.
|
||||
|
||||
## 6-15. 검토 반영 — 권한·열기 경로·저장·동시성 (2026-10-12, 마이그레이션 없음)
|
||||
|
||||
권한 정책(6-14 표)은 그대로 두고, 그 정책이 새던 곳을 막았다. 테스트 `tests/test_project_review_fixes.py`(DB 없이),
|
||||
`tests/test_project_meeting_lock.py`·`test_project_alerts_api.py`, `tests/js/project_ui.test.js` 의 [검토 *] 항목.
|
||||
|
||||
- **서브프로젝트 작업**: `GET /api/projects/{id}/tasks`(하위 프로젝트까지 재귀)는 작업마다 지금 권한으로 다시 거른다
|
||||
(`access.filter_visible_tasks`) — 부모 멤버라고 멤버가 아닌 자식 프로젝트 작업이 보이지 않는다. 연결된 작업의 READ 는 그대로.
|
||||
(이 API·`POST /subprojects` 는 지금 화면에서 부르지 않는다 — 외부 호출 호환 때문에 남겨 둠.)
|
||||
- **사이드바 순서** `PUT /api/projects/order`: Pro user 이상 + 보낸 id **전부** 지금 관리할 수 있는 프로젝트여야(없는 id 도 같은 403,
|
||||
하나라도 아니면 아무것도 안 바뀜). 빈 목록·정수 아님(참/거짓·소수·글자)·0 이하·중복 = 400. 순서는 예전처럼 모두가 같이 보는 순서.
|
||||
- **작업 열기 경로 하나로**: 수신함 줄·웹 큰 팝업·PC 알림 [열기] = `/project/t/{task_id}`(공유 링크). 서버(`_task_open_project`)가
|
||||
지금 권한으로 열 프로젝트를 고른다 — FULL 이면 원 소속, READ 면 내가 볼 수 있는 연결된 프로젝트. `?embed=1` 은 옮긴 주소에도
|
||||
붙는다(수신함 iframe). 알림 응답에 `href` 가 붙는다. 예전 주소 `/p/{원 소속}?task=` 로 READ 사용자가 오면 403 대신 연결된
|
||||
프로젝트로 보낸다(옛 PC 알림 프로그램·북마크). 작업 없는 프로젝트 알림은 예전처럼 `/p/{id}`.
|
||||
- **보관·서브프로젝트 화면**: `project_page`·스냅샷(scope=all)·담당자별 합계(scope=all)는 같은 범위(`_view_scope`) — 활성 최상위
|
||||
멤버 프로젝트 + **지금 연 프로젝트 하나**(보관됐거나 서브프로젝트여서 목록에 없을 때만). 다른 보관 프로젝트는 읽지 않는다. 그
|
||||
프로젝트 메타는 `view_only: true` 로 와서 사이드바 목록엔 그리지 않는다(작업 권한 판단·타임라인 그룹용).
|
||||
- **전체 보기**: 작업마다 한 행 — 원 소속 행이 있으면 그것, 원 소속을 볼 수 없어 연결된 프로젝트 행(READ)만 있으면 그중 첫 행
|
||||
(`scopeTasks`). 예전엔 원 소속 행만 남겨 이런 작업이 빠졌다. 사용자별 작업 팝업(`/api/users/tasks`, 전체 대상)도 같은 기준(READ 포함).
|
||||
- **큰 팝업 알림**(`_alerts_payload`, 웹·PC 공용): 수신자·읽지 않음·종류(태그·배정)·`id > after` 를 DB 에서 먼저 걸고
|
||||
(`list_unread_after`) **오래된 것부터** 200건씩 넘기며 지금 볼 수 있는 것 10건을 모은다(한 번에 최대 25쪽 = 5,000행).
|
||||
예전엔 최신 50건을 자른 뒤 걸러 — 배정 뒤 댓글 알림 50건, 배정 60건 이상, 볼 수 없는 알림이 앞을 채우면 팝업이 빠졌다.
|
||||
기준점(`latest_id`)·처음 연결 때 옛 알림 안 띄움·PC 프로그램이 돌면 웹 팝업 쉼은 그대로.
|
||||
- **수신함 오른쪽 작업 창**: 다른 줄로 바꾸거나 닫기(Esc·바깥 클릭·모두 확인·프로젝트 알림 이동) 전에 iframe 안 작업 창의
|
||||
`window.__pjEmbedSettle()` 을 기다린다 — 작업 창 닫기와 같은 절차(업로드·만들기·저장 대기 → 실패 칸 재시도 → "버리고 넘어가기 /
|
||||
계속 편집"). 계속 편집이면 창·입력·선택 그대로, 새 줄은 확인하지 않는다. 바꾸기는 한 번에 하나, 마지막 요청만(A→B→A·저장 중
|
||||
Esc 연타). beforeunload 경고에 기대지 않는다. 읽음/확인은 **서버가 받았을 때만** 확인으로 두고(실패면 굵게 남기고 알림), 확인된
|
||||
줄만 목록에서 뺀다. `POST /api/mentions/read` 는 006 미적용(표 없음)만 0건 성공, 그 밖의 DB 오류는 실패로 돌려준다.
|
||||
- **일반 첨부**(`POST /api/tasks/{id}/attachments`): DB 저장이 실패하면 이 요청이 쓴 파일(새 uuid 이름)만 지운다. 크기·빈 파일·
|
||||
권한·inline 정책은 그대로.
|
||||
- **새 프로젝트 창**: ① 생성(한 번만) ② 멤버 배정(사람마다)을 나눠 안내 — 배정 실패면 창을 닫지 않고 실패한 멤버를 빨갛게,
|
||||
[실패한 멤버 다시 배정]은 그 멤버만(프로젝트를 또 만들지 않음). 진행 중 연타 무시, 진행 중 닫아도 요청은 끝까지 가고 결과는 알림.
|
||||
만든 프로젝트를 되돌리려고 지우지 않는다.
|
||||
- **배지 개수**: 내 작업(`list_my_open_refs`)·수신함 태그(`list_unread_mention_refs`)·읽지 않은 알림(`list_unread_refs`)은 가벼운 열만
|
||||
제한 없이 읽어 지금 권한으로 센다(예전 1000·1000·500건 상한). 내 작업 목록은 **미완료 전부** + 최근 완료 1000건
|
||||
(`list_my_tasks(completed_limit=)`) — 오래된 완료가 새 미완료를 밀어내지 않는다.
|
||||
- **동시성**: `update_task` 는 기존 값 읽기·섹션 확인·기본 담당자·완료 섹션 여부·최종 날짜 검사·변경·이력을 한 트랜잭션에서 그
|
||||
작업 행을 잠그고(`FOR UPDATE`) 같은 연결로 한다 — 시작일·마감일을 동시에 바꿔도 역전되지 않고, 동시 완료의 완료 이력·알림은 실제로
|
||||
바뀐 한 요청에서만. `update_project` 날짜 검사도 행 잠금 뒤. (한 창 저장 직렬화와 별개 — 여러 사람 사이의 충돌 방지.)
|
||||
- **회의록**: 머리(메모·참석자·금주 목표) 수정은 그 회의록 행을 잠그고 완료 여부를 본다([회의 완료]도 같은 행을 잠근다). 결과 칸만
|
||||
고칠 때(`_check_result_open`): 다음 주차 회의록이 **있으면** 그 회의록이 열려 있을 때만, **없으면** 그 주 회의록이 열려 있을 때만
|
||||
(예전엔 다음 회의록이 없으면 완료된 주의 결과도 고칠 수 있었다). 다음 주차 = `week_period` 끝 + 1일(달이 바뀌어도, 월요일이 아닌
|
||||
시작일도). 다음 회의록 행은 `FOR SHARE` — 잠금 순서는 늘 주차 오름차순(교착 없음).
|
||||
- **소유자를 남으로 정해 만들기**: 만든 사람을 같은 트랜잭션에서 **일반 멤버 행**으로 넣는다(`create_project(member_emails=)`) —
|
||||
`created_by` 로 권한을 주지 않으니 나중에 멤버에서 빼면 권한도 없어진다. 소유자 변경 뒤 옛 소유자 권한 회수도 그대로.
|
||||
- **중복 방지 키**(`_once`, 댓글 `client_token`): 키별 잠금을 쓰는 요청 수로 관리해 0 이 되면 바로 뺀다(실패한 키도) — 결과를 먼저
|
||||
저장한 뒤 잠금을 풀어 기다리던 요청은 결과로 답한다. 실패하면 다음 요청이 새로 만든다(재시도). **보장 범위: 웹 프로세스 하나**
|
||||
— 지금 운영은 web 컨테이너 1개·uvicorn 워커 1개(Dockerfile). 워커·컨테이너를 늘리면 다른 워커로 간 재전송은 막지 못하고 재시작하면
|
||||
기록도 사라진다(그때는 DB UNIQUE 키가 필요).
|
||||
- **섹션 기본 담당자**: 자동 배정 전에 그 사람이 지금 등록된 project 권한 사용자인지도 본다(`_registered_project_user`, 사용자 목록만 —
|
||||
잠근 트랜잭션 안에서 DB 연결을 더 빌리지 않음). 기본 담당자 지정도 같은 기준. 협업자 추가는 담당자 후보와 같은 `access.can_assign`
|
||||
(예전엔 관리자는 멤버가 아니어도 넣을 수 있었다).
|
||||
|
||||
정책 결정이 필요한 것(바꾸지 않음): 배정·완료 **메일**은 `PROJECT_NOTIFY_EMAIL`(없으면 Admin 전원)에게 프로젝트·작업 제목·담당자가
|
||||
간다 — 화면에선 비멤버 Admin 이 그 프로젝트를 못 보지만 메일로는 제목을 받는다(4장 관리자 보고 정책).
|
||||
|
||||
## 7. 추후 단계
|
||||
|
||||
작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성 · 하위 작업의 하위 작업(다단계 중첩,
|
||||
아사나도 UI상 1단계만 허용해 현재 의도적으로 안 함).
|
||||
작업 라벨(태그 분류) · 반복 작업 · 템플릿 · 작업 의존성.
|
||||
(세부 작업의 세부 작업은 2026-10-08 부터 지원 — 6-13 담당자별 합계 참고.)
|
||||
|
||||
@@ -25,15 +25,24 @@
|
||||
|
||||
### 권한 키 (`MODULE_KEYS`)
|
||||
|
||||
자산관리: `app/modules/asset/`, `/asset/`, `asset_db` — 사무집기·전산장비 개별 등록,
|
||||
배정/반납/상태·구매/보증·활동 이력, HWiNFO XML 사양/보고서 보존. 상세 `docs/ASSET_MODULE.md`.
|
||||
사진 갤러리, 보고서 모니터 자산 개요·등록·연결, 수퍼 관리자 삭제(이력/원본 보존)를 제공한다.
|
||||
|
||||
| 키 | 종류 | 설명 |
|
||||
| --- | --- | --- |
|
||||
| `corm` / `order` | 접근 | 외부 모듈 진입 |
|
||||
| `expense` / `vacation` / `cupang` / `malaysia` / `performance` | 접근 | 내부 모듈 진입 (`performance` 설정 화면·API 는 추가로 `admin` 필요) |
|
||||
| `expense_approver` | 결재 | 개인경비 승인/반려/정산 |
|
||||
| `asset` | 접근 | 자산관리 조회·등록·수정·배정·반납·보고서 |
|
||||
| `vacation_approver` | 결재 | 휴가 승인/반려 (모듈 미개발) |
|
||||
|
||||
`admin` 역할은 모든 권한 자동 부여. 신규 사용자는 관리자 페이지(`/admin`)에서 이메일만으로 등록 가능.
|
||||
|
||||
관리자 등급(2026-10-12): **수퍼관리자**(`SUPER_ADMIN_EMAIL` 한 명 고정 — 변경·삭제·추가 불가) > **Admin**(`role=admin`) >
|
||||
**Pro user**(`role=pro`) > **User**(`role=user`). Pro user 는 Project 모듈(프로젝트·목표·주간 회의록)에서만 권한이 늘고
|
||||
(`app/modules/project/access.py`, 표는 `docs/PROJECT_MODULE.md` 6-14), 다른 모듈·관리자 페이지에서는 User 와 같다.
|
||||
|
||||
---
|
||||
|
||||
## 모듈 디렉토리 규약
|
||||
@@ -94,7 +103,9 @@ app/modules/<name>/
|
||||
| `malaysia_stock_db` | 말레이시아 창고 재고/세트BOM/재고조사 (`MALAYSIA_STOCK_DB_URL` 필수, JSON 폴백 없음) |
|
||||
| `performance_db` | 실적 — 쇼핑몰 설정/수수료 이력/인증정보(암호문)/매출 사건 (`PERFORMANCE_DB_URL` 필수, JSON 폴백 없음) |
|
||||
|
||||
> 신규 DB가 필요하면 **승인 요청 후** 생성하며, 이름은 `_db`로 끝낸다. 상세는 `DATABASES.md`.
|
||||
> 신규 DB 생성은 서버 실행 명령을 제공하고 사용자가 직접 진행한다 (사용자 지시: 2026-10-06). 대상·상태·백업 확인 명령을 제공하고 이름은 `_db`로 끝낸다. 기존 DB 삭제·덮어쓰기는 별도 승인 대상이다. 상세는 `DATABASES.md`.
|
||||
|
||||
자산관리는 전용 `asset_db`를 사용한다. `ASSET_DB_URL` 미설정 시 저장 비활성, XML 분석 미리보기 가능.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ itsdangerous>=2.2
|
||||
python-dotenv>=1.0
|
||||
psycopg[binary,pool]>=3.2
|
||||
python-multipart>=0.0.20
|
||||
defusedxml>=0.7.1
|
||||
openpyxl>=3.1
|
||||
pdfplumber>=0.11
|
||||
pillow>=10.0
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
"""Google 스프레드시트 쓰기용 refresh token 1회 발급 스크립트.
|
||||
"""Google 스프레드시트 쓰기·회의록 보드(Drive·Slides)용 refresh token 1회 발급 스크립트.
|
||||
|
||||
조직 정책(`iam.disableServiceAccountKeyCreation`)으로 서비스 계정 키를 만들 수 없을 때
|
||||
사용자 계정 OAuth 로 서버가 시트에 기록하도록 하기 위한 토큰을 받는다.
|
||||
|
||||
사전 준비 (Google Cloud Console)
|
||||
1. API 및 서비스 → 라이브러리 → "Google Sheets API" 사용
|
||||
1. API 및 서비스 → 라이브러리 → "Google Sheets API"·"Google Drive API"·"Google Slides API" 사용
|
||||
2. API 및 서비스 → OAuth 동의 화면 구성(내부 또는 외부)
|
||||
3. 사용자 인증 정보 → 사용자 인증 정보 만들기 → **OAuth 클라이언트 ID**
|
||||
→ 애플리케이션 유형 **데스크톱 앱** → 클라이언트 ID / 보안 비밀 확인
|
||||
@@ -14,9 +14,16 @@
|
||||
또는 환경변수로:
|
||||
GOOGLE_SHEETS_OAUTH_CLIENT_ID / GOOGLE_SHEETS_OAUTH_CLIENT_SECRET
|
||||
|
||||
브라우저가 열리면 **시트를 편집할 수 있는 계정**으로 로그인·동의한다.
|
||||
브라우저가 열리면 **시트를 편집할 수 있고 회의록 보드 공유 드라이브에 쓸 수 있는 계정**으로 로그인·동의한다.
|
||||
마지막에 출력되는 refresh token 을 서버 `.env` 의
|
||||
`GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 에 넣는다.
|
||||
`GOOGLE_SHEETS_OAUTH_REFRESH_TOKEN` 에 넣는다(시트·회의록 보드가 같이 쓴다).
|
||||
|
||||
400 redirect_uri_mismatch 가 나오면
|
||||
- 쓰는 OAuth 클라이언트가 "웹 애플리케이션" 유형이면 승인된 리디렉션 URI 에 **http://localhost:18765/** 를 추가하고
|
||||
(끝 / 포함, 반영까지 몇 분) 다시 실행한다. 포트를 바꾸면(--port N) 그 주소(http://localhost:N/)를 등록해야 한다.
|
||||
- "데스크톱 앱" 유형 클라이언트는 등록 없이 된다.
|
||||
- refresh token 은 발급한 클라이언트 ID 에 묶인다 — 서버 .env 의 GOOGLE_SHEETS_OAUTH_CLIENT_ID/SECRET
|
||||
(없으면 GOOGLE_CLIENT_ID/SECRET)이 여기서 쓴 클라이언트와 같아야 한다.
|
||||
|
||||
주의
|
||||
- 출력된 refresh token 은 비밀값이다. Git·메신저에 남기지 말 것.
|
||||
@@ -30,7 +37,12 @@ import argparse
|
||||
import os
|
||||
import sys
|
||||
|
||||
SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]
|
||||
# 스프레드시트(쿠팡 출고리스트) + Drive·Slides(주간 회의록 보드 — 공유 드라이브에 빈 슬라이드 만들기)
|
||||
SCOPES = [
|
||||
"https://www.googleapis.com/auth/spreadsheets",
|
||||
"https://www.googleapis.com/auth/drive",
|
||||
"https://www.googleapis.com/auth/presentations",
|
||||
]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
@@ -40,7 +52,8 @@ def main() -> int:
|
||||
"--client-secret", default=os.getenv("GOOGLE_SHEETS_OAUTH_CLIENT_SECRET", "")
|
||||
)
|
||||
parser.add_argument(
|
||||
"--port", type=int, default=0, help="로컬 콜백 포트(기본: 임의 포트)"
|
||||
"--port", type=int, default=18765,
|
||||
help="로컬 콜백 포트(기본 18765 — 웹 애플리케이션 클라이언트면 http://localhost:18765/ 를 리디렉션 URI 로 등록)"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
-- asset_db / postgres-db: 백업 확인 후 사용자가 서버에서 실행합니다.
|
||||
-- 기존 자산과 보고서를 유지하며 사진·모니터 연결·삭제 표시만 추가합니다.
|
||||
\set ON_ERROR_STOP on
|
||||
BEGIN;
|
||||
ALTER TABLE assets ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE assets ADD COLUMN IF NOT EXISTS deleted_by TEXT NOT NULL DEFAULT '';
|
||||
CREATE TABLE IF NOT EXISTS asset_photos (
|
||||
id TEXT PRIMARY KEY, asset_id TEXT NOT NULL REFERENCES assets(id),
|
||||
filename TEXT NOT NULL, mime TEXT NOT NULL CHECK(mime IN ('image/jpeg','image/png')),
|
||||
image BYTEA NOT NULL CHECK(octet_length(image) BETWEEN 1 AND 5242880),
|
||||
width INTEGER NOT NULL CHECK(width BETWEEN 1 AND 2400),
|
||||
height INTEGER NOT NULL CHECK(height BETWEEN 1 AND 2400),
|
||||
actor TEXT NOT NULL, uploaded_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS asset_photos_asset ON asset_photos(asset_id,uploaded_at DESC,id);
|
||||
CREATE TABLE IF NOT EXISTS asset_monitor_links (
|
||||
computer_id TEXT NOT NULL REFERENCES assets(id),
|
||||
monitor_key TEXT NOT NULL,
|
||||
monitor_asset_id TEXT NOT NULL REFERENCES assets(id),
|
||||
actor TEXT NOT NULL, linked_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY(computer_id,monitor_key), CHECK(computer_id<>monitor_asset_id)
|
||||
);
|
||||
GRANT SELECT,INSERT ON asset_photos TO asset_app;
|
||||
GRANT SELECT,INSERT,UPDATE ON asset_monitor_links TO asset_app;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,83 @@
|
||||
-- 자산관리 초기화. 사용자가 서버에서 직접 실행합니다. 대상·상태·백업 확인 후 실행.
|
||||
-- 기존 DB·역할의 데이터와 비밀번호는 변경하지 않습니다.
|
||||
-- psql -v ON_ERROR_STOP=1 -U postgres -v app_password="$APP_PWD" < this-file
|
||||
\set ON_ERROR_STOP on
|
||||
SELECT 'CREATE ROLE asset_app LOGIN PASSWORD ' || quote_literal(:'app_password')
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname='asset_app')
|
||||
\gexec
|
||||
SELECT 'CREATE DATABASE asset_db OWNER postgres ENCODING ''UTF8'' TEMPLATE template0'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pg_database WHERE datname='asset_db')
|
||||
\gexec
|
||||
GRANT CONNECT ON DATABASE asset_db TO asset_app;
|
||||
\connect asset_db
|
||||
BEGIN;
|
||||
CREATE SEQUENCE IF NOT EXISTS asset_tag_seq;
|
||||
CREATE TABLE IF NOT EXISTS assets (
|
||||
id TEXT PRIMARY KEY,
|
||||
tag TEXT NOT NULL CHECK(length(tag) BETWEEN 1 AND 64),
|
||||
name TEXT NOT NULL CHECK(length(name) BETWEEN 1 AND 200),
|
||||
category TEXT NOT NULL CHECK(category IN ('computer','monitor','mouse','keyboard','camera','hub','lighting','desk','chair','furniture','equipment')),
|
||||
status TEXT NOT NULL DEFAULT 'available' CHECK(status IN ('available','in_use','maintenance','lost','retired')),
|
||||
manufacturer TEXT NOT NULL DEFAULT '', model TEXT NOT NULL DEFAULT '', serial TEXT NOT NULL DEFAULT '',
|
||||
location TEXT NOT NULL DEFAULT '', department TEXT NOT NULL DEFAULT '',
|
||||
assignee_email TEXT NOT NULL DEFAULT '',
|
||||
purchased_on DATE, purchase_cost NUMERIC(15,2) CHECK(purchase_cost>=0 AND purchase_cost<=1000000000000),
|
||||
vendor TEXT NOT NULL DEFAULT '', warranty_until DATE, notes TEXT NOT NULL DEFAULT '',
|
||||
latest_report_id TEXT,
|
||||
version INTEGER NOT NULL DEFAULT 1 CHECK(version>=1),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(), updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
CHECK(status<>'in_use' OR assignee_email<>''),
|
||||
CHECK(status IN ('in_use','lost') OR assignee_email=''),
|
||||
CHECK(warranty_until IS NULL OR purchased_on IS NULL OR warranty_until>=purchased_on),
|
||||
CHECK(latest_report_id IS NULL OR category='computer')
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS assets_tag_unique ON assets(lower(tag));
|
||||
CREATE INDEX IF NOT EXISTS assets_status_category ON assets(status,category);
|
||||
CREATE INDEX IF NOT EXISTS assets_assignee ON assets(assignee_email);
|
||||
CREATE INDEX IF NOT EXISTS assets_location ON assets(location);
|
||||
CREATE INDEX IF NOT EXISTS assets_updated ON assets(updated_at DESC,id);
|
||||
CREATE TABLE IF NOT EXISTS asset_reports (
|
||||
id TEXT PRIMARY KEY, asset_id TEXT NOT NULL REFERENCES assets(id),
|
||||
filename TEXT NOT NULL, sha256 TEXT NOT NULL,
|
||||
raw_xml BYTEA NOT NULL CHECK(octet_length(raw_xml) BETWEEN 1 AND 10485760),
|
||||
parsed JSONB NOT NULL, actor TEXT NOT NULL, uploaded_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE(asset_id,sha256), UNIQUE(asset_id,id)
|
||||
);
|
||||
-- Composite FK prevents linking another computer's report as the current report.
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS(SELECT 1 FROM pg_constraint WHERE conname='assets_latest_report_fk' AND conrelid='assets'::regclass) THEN
|
||||
ALTER TABLE assets ADD CONSTRAINT assets_latest_report_fk
|
||||
FOREIGN KEY(id,latest_report_id) REFERENCES asset_reports(asset_id,id);
|
||||
END IF;
|
||||
END $$;
|
||||
CREATE INDEX IF NOT EXISTS asset_reports_asset ON asset_reports(asset_id,uploaded_at DESC);
|
||||
CREATE TABLE IF NOT EXISTS asset_events (
|
||||
id BIGSERIAL PRIMARY KEY, asset_id TEXT NOT NULL REFERENCES assets(id),
|
||||
actor TEXT NOT NULL, kind TEXT NOT NULL, note TEXT NOT NULL DEFAULT '',
|
||||
changes JSONB NOT NULL DEFAULT '{}', created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS asset_events_asset ON asset_events(asset_id,id DESC);
|
||||
GRANT USAGE ON SCHEMA public TO asset_app;
|
||||
GRANT SELECT,INSERT,UPDATE ON assets TO asset_app;
|
||||
GRANT SELECT,INSERT ON asset_reports,asset_events TO asset_app;
|
||||
GRANT USAGE,SELECT ON SEQUENCE asset_tag_seq,asset_events_id_seq TO asset_app;
|
||||
ALTER TABLE assets ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
|
||||
ALTER TABLE assets ADD COLUMN IF NOT EXISTS deleted_by TEXT NOT NULL DEFAULT '';
|
||||
CREATE TABLE IF NOT EXISTS asset_photos (
|
||||
id TEXT PRIMARY KEY, asset_id TEXT NOT NULL REFERENCES assets(id),
|
||||
filename TEXT NOT NULL, mime TEXT NOT NULL CHECK(mime IN ('image/jpeg','image/png')),
|
||||
image BYTEA NOT NULL CHECK(octet_length(image) BETWEEN 1 AND 5242880),
|
||||
width INTEGER NOT NULL CHECK(width BETWEEN 1 AND 2400),
|
||||
height INTEGER NOT NULL CHECK(height BETWEEN 1 AND 2400),
|
||||
actor TEXT NOT NULL, uploaded_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS asset_photos_asset ON asset_photos(asset_id,uploaded_at DESC,id);
|
||||
CREATE TABLE IF NOT EXISTS asset_monitor_links (
|
||||
computer_id TEXT NOT NULL REFERENCES assets(id), monitor_key TEXT NOT NULL,
|
||||
monitor_asset_id TEXT NOT NULL REFERENCES assets(id), actor TEXT NOT NULL,
|
||||
linked_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY(computer_id,monitor_key), CHECK(computer_id<>monitor_asset_id)
|
||||
);
|
||||
GRANT SELECT,INSERT ON asset_photos TO asset_app;
|
||||
GRANT SELECT,INSERT,UPDATE ON asset_monitor_links TO asset_app;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- 주간 회의록의 글 셀 세로 병합. 기존 평문/금액/연결키는 유지한다.
|
||||
-- 운영: /opt/www/main 에서 기존 project_db 에 적용(신규 DB 생성 없음).
|
||||
BEGIN;
|
||||
ALTER TABLE goal_meeting_items
|
||||
ADD COLUMN IF NOT EXISTS content_row_span INTEGER NOT NULL DEFAULT 1
|
||||
CHECK (content_row_span BETWEEN 1 AND 500);
|
||||
COMMENT ON COLUMN goal_meeting_items.content_row_span IS
|
||||
'같은 주·같은 구역에서 이번주 할 일 셀이 덮는 행 수. 글은 첫 행에 보존.';
|
||||
COMMIT;
|
||||
SELECT 'project_db 019 meeting cell editing ready' AS status;
|
||||
@@ -0,0 +1,89 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 020 — 주간 회의록 새 주차·결과 글 칸·주차별 매출 목표
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). DROP TABLE/TRUNCATE 없음. 운영: /opt/www/main 에서 기존 project_db 에 적용(신규 DB 생성 없음).
|
||||
--
|
||||
-- 왜(2026-10-07 사용자 요청):
|
||||
-- · 주차 = 그 달 안의 기간. 1일이 월~금이면 1일~그 주 일요일이 1주차, 1일이 토·일이면 1일~다음 주 일요일이 1주차,
|
||||
-- 그 뒤로 월~일. 말일이 월·화이면 그 하루·이틀은 앞 주차에 붙는다. → 회의록 시작일(week_start)이 월요일이 아닐 수 있다.
|
||||
-- · 지난주 리뷰에 "결과" 글 칸(지난주 줄에 저장).
|
||||
-- · 연간 목표 표에서 월 매출 목표를 주차별로 입력하고 그 합계를 월 목표로 쓴다.
|
||||
--
|
||||
-- ① goal_meeting_items.result_note — 지난주 리뷰 "결과" 글(그 주 줄에 저장)
|
||||
-- ② goal_meetings.week_start 의 "월요일만" CHECK 제거(주차 시작일은 1일일 수 있다)
|
||||
-- ③ goal_week_targets — 주차별 매출 목표(목표 표 매출 단위 그대로, 월 목표 = 그 달 주차 합계)
|
||||
-- ④ 새 주차에 흡수된 월요일 회의록을 새 주차 시작일로 옮김
|
||||
-- A) 1일이 토·일인 달의 첫 월요일(2일·3일) → 그 달 1일
|
||||
-- B) 말일이 월·화인 달의 마지막 월요일 → 7일 전 월요일(앞 주차)
|
||||
-- 옮길 자리에 이미 회의록이 있으면 옮기지 않고 NOTICE 로 알린다(합치지 않음 — 사람이 확인).
|
||||
--
|
||||
-- 적용 전 확인(조회만):
|
||||
-- SELECT week_start, to_char(week_start, 'Dy') FROM goal_meetings
|
||||
-- WHERE (EXTRACT(DAY FROM week_start) IN (2, 3) AND EXTRACT(ISODOW FROM week_start) = 1)
|
||||
-- OR (EXTRACT(ISODOW FROM week_start) = 1 AND EXTRACT(DAY FROM week_start + 2) IN (1, 2));
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
-- ① 결과 글 칸
|
||||
ALTER TABLE goal_meeting_items ADD COLUMN IF NOT EXISTS result_note TEXT NOT NULL DEFAULT '';
|
||||
COMMENT ON COLUMN goal_meeting_items.result_note IS '그 주 결과(글) — 다음 주차 회의록의 지난주 리뷰 "결과" 칸에서 입력';
|
||||
|
||||
-- ② 월요일 CHECK 제거(이름이 달라도 ISODOW 검사인 CHECK 만 찾아서)
|
||||
DO $$
|
||||
DECLARE c record;
|
||||
BEGIN
|
||||
FOR c IN
|
||||
SELECT conname FROM pg_constraint
|
||||
WHERE conrelid = 'goal_meetings'::regclass AND contype = 'c'
|
||||
AND pg_get_constraintdef(oid) ILIKE '%isodow%'
|
||||
LOOP
|
||||
EXECUTE format('ALTER TABLE goal_meetings DROP CONSTRAINT %I', c.conname);
|
||||
END LOOP;
|
||||
END $$;
|
||||
COMMENT ON TABLE goal_meetings IS '연간 목표 — 주간 회의록(week_start = 주차 시작일, 020 부터 월요일이 아닐 수 있음)';
|
||||
|
||||
-- ③ 주차별 매출 목표
|
||||
CREATE TABLE IF NOT EXISTS goal_week_targets (
|
||||
week_start DATE PRIMARY KEY, -- 주차 시작일
|
||||
year INT NOT NULL REFERENCES goal_years(year) ON DELETE CASCADE,
|
||||
month INT NOT NULL CHECK (month BETWEEN 1 AND 12),
|
||||
value NUMERIC NOT NULL CHECK (value >= 0), -- 목표 표 매출 단위(예: 백만원)
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_goal_week_targets_month ON goal_week_targets (year, month);
|
||||
COMMENT ON TABLE goal_week_targets IS '연간 목표 — 주차별 매출 목표(월 목표 = 그 달 주차 합계)';
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON goal_week_targets TO project_app;
|
||||
|
||||
-- ④ 흡수된 월요일 회의록 옮기기
|
||||
DO $$
|
||||
DECLARE r record; dst date;
|
||||
BEGIN
|
||||
FOR r IN
|
||||
SELECT week_start FROM goal_meetings
|
||||
WHERE EXTRACT(ISODOW FROM week_start) = 1
|
||||
AND (EXTRACT(DAY FROM week_start) IN (2, 3) -- A
|
||||
OR EXTRACT(DAY FROM week_start + 1) = 1 -- B 말일 = 월
|
||||
OR EXTRACT(DAY FROM week_start + 2) = 1) -- B 말일 = 화
|
||||
ORDER BY week_start
|
||||
LOOP
|
||||
IF EXTRACT(DAY FROM r.week_start) IN (2, 3) THEN
|
||||
dst := date_trunc('month', r.week_start)::date;
|
||||
ELSE
|
||||
dst := r.week_start - 7;
|
||||
END IF;
|
||||
IF EXISTS (SELECT 1 FROM goal_meetings WHERE week_start = dst) THEN
|
||||
RAISE NOTICE '회의록 % 은(는) % 주차에 흡수되지만 그 자리에 회의록이 있어 옮기지 않았습니다(확인 필요).', r.week_start, dst;
|
||||
CONTINUE;
|
||||
END IF;
|
||||
INSERT INTO goal_meetings (week_start, week_target, attendees, notes, created_by, created_at, updated_by, updated_at)
|
||||
SELECT dst, week_target, attendees, notes, created_by, created_at, updated_by, now()
|
||||
FROM goal_meetings WHERE week_start = r.week_start;
|
||||
UPDATE goal_meeting_items SET week_start = dst WHERE week_start = r.week_start;
|
||||
DELETE FROM goal_meetings WHERE week_start = r.week_start; -- 줄은 위에서 옮겼으므로 빈 머리만 지운다
|
||||
RAISE NOTICE '회의록 % → % 로 옮김', r.week_start, dst;
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'project_db 020 meeting periods ready' AS status;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 021 — 주간 회의록 정량 목표·결과에 글자 입력(예: "20개")
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 열만 추가한다(기존 값 변경·삭제 없음). 운영: /opt/www/main 에서 기존 project_db 에 적용.
|
||||
--
|
||||
-- 왜(2026-10-07 사용자 요청): 정량 목표·결과(금액) 칸에 숫자만이 아니라 "20개" 같은 글자도 적고 싶다.
|
||||
-- 숫자로 읽히는 값(1,200,000 · 120만 · 1.5억)은 지금처럼 target_amount/result_amount(원 정수)에,
|
||||
-- 숫자로 읽히지 않는 값은 아래 글 칸에 저장한다(둘 중 하나만 채워짐). 화면은 글이 있으면 글, 없으면 숫자.
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE goal_meeting_items ADD COLUMN IF NOT EXISTS target_text TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE goal_meeting_items ADD COLUMN IF NOT EXISTS result_text TEXT NOT NULL DEFAULT '';
|
||||
COMMENT ON COLUMN goal_meeting_items.target_text IS '정량 목표 — 숫자로 읽히지 않는 글(예: 20개). 숫자면 target_amount';
|
||||
COMMENT ON COLUMN goal_meeting_items.result_text IS '그 주 결과 — 숫자로 읽히지 않는 글. 숫자면 result_amount';
|
||||
|
||||
COMMIT;
|
||||
SELECT 'project_db 021 meeting amount text ready' AS status;
|
||||
@@ -0,0 +1,18 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 022 — 주간 회의록 "회의 완료"(수정 잠금)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 열만 추가한다(기존 값 변경·삭제 없음). 운영: /opt/www/main 에서 기존 project_db 에 적용.
|
||||
--
|
||||
-- 왜(2026-10-07 사용자 요청): 주간 회의록은 프로젝트 권한이 있는 누구나 고칠 수 있고, 관리자가 [회의 완료]를 누르면
|
||||
-- 그 회의록은 더 고칠 수 없다(관리자는 [완료 해제]로 다시 열 수 있다).
|
||||
-- completed_at 이 있으면 완료. 지난주 결과(글·금액)는 다음 주 회의록이 열려 있는 동안만 고칠 수 있다.
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
ALTER TABLE goal_meetings ADD COLUMN IF NOT EXISTS completed_at TIMESTAMPTZ NULL;
|
||||
ALTER TABLE goal_meetings ADD COLUMN IF NOT EXISTS completed_by TEXT NOT NULL DEFAULT '';
|
||||
COMMENT ON COLUMN goal_meetings.completed_at IS '회의 완료 시각 — 있으면 이 회의록은 수정 잠금(관리자만 완료·해제)';
|
||||
COMMENT ON COLUMN goal_meetings.completed_by IS '회의 완료를 누른 관리자 이메일';
|
||||
|
||||
COMMIT;
|
||||
SELECT 'project_db 022 meeting complete ready' AS status;
|
||||
@@ -0,0 +1,44 @@
|
||||
-- =====================================================================
|
||||
-- project_db 마이그레이션 023 — PC 알림 프로그램(DBX 알림) 연결
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 테이블만 추가한다(기존 값 변경·삭제 없음). 운영: /opt/www/main 에서 기존 project_db 에 적용.
|
||||
--
|
||||
-- 왜(2026-10-08 사용자 요청): 웹브라우저가 뒤에 있어도 태그·작업 배정 알림을 PC 화면 위에 크게 띄우는
|
||||
-- 트레이 프로그램(desktop/notifier). 브라우저 세션(쿠키)을 쓸 수 없으므로 PC마다 연결 토큰을 발급한다.
|
||||
-- ① 프로그램이 연결 요청(notifier_links: 화면 코드 + 확인용 poll 비밀값) → ② 사용자가 브라우저(로그인 상태)에서
|
||||
-- 코드를 확인하고 [연결] → ③ 프로그램이 poll 로 토큰을 한 번 받는다(notifier_tokens). 토큰·poll 값은 원문을
|
||||
-- 저장하지 않고 SHA-256 해시만 저장한다. 연결 해제 = revoked_at.
|
||||
-- =====================================================================
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS notifier_links (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
code TEXT NOT NULL UNIQUE, -- 화면에 보이는 짧은 코드(예: K7QM-4XPA)
|
||||
poll_hash TEXT NOT NULL UNIQUE, -- 프로그램만 아는 poll 비밀값의 SHA-256
|
||||
device_name TEXT NOT NULL DEFAULT '',
|
||||
email TEXT NULL, -- [연결]을 누른 사용자(승인 전 NULL)
|
||||
approved_at TIMESTAMPTZ NULL,
|
||||
consumed_at TIMESTAMPTZ NULL, -- 토큰을 내준 시각(한 번만)
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_notifier_links_expires ON notifier_links (expires_at);
|
||||
COMMENT ON TABLE notifier_links IS 'PC 알림 프로그램 연결 요청 — 10분 유효, 승인 후 토큰 1회 발급';
|
||||
|
||||
CREATE TABLE IF NOT EXISTS notifier_tokens (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
email TEXT NOT NULL,
|
||||
token_hash TEXT NOT NULL UNIQUE, -- 토큰 원문의 SHA-256
|
||||
device_name TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
last_seen_at TIMESTAMPTZ NULL,
|
||||
revoked_at TIMESTAMPTZ NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_notifier_tokens_email ON notifier_tokens (email);
|
||||
COMMENT ON TABLE notifier_tokens IS 'PC 알림 프로그램 토큰 — 사용자·PC 단위, revoked_at 이면 해제';
|
||||
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON notifier_links, notifier_tokens TO project_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO project_app;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'project_db 023 notifier ready' AS status;
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Synthetic HWiNFO export; contains no company device identifiers."""
|
||||
def prop(label, value, kind=""):
|
||||
return f"<Property><Entry>{label}</Entry><Description>{value}</Description><PropertyType>{kind}</PropertyType></Property>"
|
||||
|
||||
|
||||
def report_xml(english=False):
|
||||
return ('''<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE HWINFO SYSTEM "HWiNFO32log.dtd"><HWINFO><COMPUTER><NodeName>TEST-PC</NodeName><ScanTime>06.10.2026 01:10</ScanTime>'''
|
||||
+ prop("Operating System" if english else "운영 체제", "Windows Test")
|
||||
+ '<SubNodes><CPU><NodeName>CPU</NodeName>'
|
||||
+ prop("Number of Processor Cores" if english else "프로세서 코어 수", "8", "CPU_COUNT")
|
||||
+ prop("Number of Logical Processors" if english else "논리 프로세서 수", "16")
|
||||
+ '<SubNode><NodeName>Test Processor</NodeName>' + prop("Processor Name", "Test Processor", "CPU_NAME")
|
||||
+ '</SubNode></CPU><MOBO><NodeName>Mainboard</NodeName>' + prop("Motherboard", "Test Board", "SYSTEM_MAINBOARD")
|
||||
+ prop("Product Serial Number", "System Serial Number") + '</MOBO><MEMORY><NodeName>Memory</NodeName>'
|
||||
+ prop("Total Memory Size [MB]", "32768", "SYSTEM_MEMORY")
|
||||
+ '<SubNode><NodeName>DIMM1</NodeName>' + prop("Module Part Number", "TEST-RAM") + prop("Module Size", "16 GiB") + '</SubNode>'
|
||||
+ '<SubNode><NodeName>DIMM2</NodeName>' + prop("Module Part Number", "TEST-RAM") + prop("Module Size", "16 GiB") + '</SubNode>'
|
||||
+ '</MEMORY><VIDEO><NodeName>Test GPU</NodeName>' + prop("Video Chipset", "Test GPU", "GFXCARD_CHIPSET")
|
||||
+ '</VIDEO><DRIVES><NodeName>Drives</NodeName><SubNodes>'
|
||||
+ '<SubNode><NodeName>SSD</NodeName>' + prop("Drive Model", "Same Model SSD", "HDD") + prop("Drive Serial Number", "synthetic-1") + '</SubNode>'
|
||||
+ '<SubNode><NodeName>SSD</NodeName>' + prop("Drive Model", "Same Model SSD", "HDD") + prop("Drive Serial Number", "synthetic-2") + '</SubNode>'
|
||||
+ '</SubNodes></DRIVES></SubNodes></COMPUTER></HWINFO>').encode()
|
||||
@@ -18,10 +18,13 @@ node tests/js/box_calc_ui.test.js
|
||||
|
||||
`goals.html`·`goal_meeting.html` + `static/project.js` — 칸 저장 직렬화·늦은 응답·503·초안 보호·구조 변경 중단·이번주 실적 %·
|
||||
실적 미확인 표시·⋮ 메뉴(키보드·터치 클릭)·매출 갱신 안내를 가짜 서버(지연·실패를 직접 만듦)로 검증한다.
|
||||
회의록 글 서식·범위 지우기/되돌리기·셀 이동·병합 요청·019 미적용·열 경계 조절·열 순서 변경·보기 전용 권한도 확인한다.
|
||||
|
||||
```bash
|
||||
python tests/js/render_goals.py # → tests/js/.out/goals_*.html · meeting_*.html
|
||||
node tests/js/goals_meeting_ui.test.js # jsdom 필요(npm install jsdom 또는 NODE_PATH)
|
||||
node tests/js/goal_nav_ui.test.js # 월별 회의록 폴더·주간 링크·접기 상태 기억·조회 재시도
|
||||
node tests/js/goal_nav.browser.test.js # Playwright: 메뉴 유지·오른쪽 전환·저장 대기/실패·뒤로/앞으로
|
||||
```
|
||||
|
||||
실제 브라우저 레이아웃·입력기·터치 기기는 아니다(그건 헤드리스 크롬으로 따로 확인).
|
||||
@@ -29,7 +32,12 @@ node tests/js/goals_meeting_ui.test.js # jsdom 필요(npm install jsdom
|
||||
목표 열 자동 맞춤은 실제 Chromium에서도 검증한다. 로컬 테스트 HTML·프로젝트 CSS/폰트를 사용하며 운영 서버·DB에 연결하지 않는다.
|
||||
부분 서식과 셀 여백, 명시적 줄바꿈, 75% 배율, 600px를 넘는 긴 문단, 저장된 너비 복원을 확인한다.
|
||||
행 높이는 3줄/2줄 셀의 상단 정렬·같은 위아래 여백, 한 줄로 줄였을 때 높이 축소, 큰 글씨, 보기 전용 화면까지 확인한다.
|
||||
회의록도 3줄/2줄 셀·한 줄 행·빈 실적 영역·75% 배율·보기 전용 화면을 확인하고,
|
||||
항목명 오른쪽의 `자동입력`·`실적 미사용` 표시가 같은 줄에 들어가는지 검증한다.
|
||||
실제 마우스로 셀 테두리를 끌어 내용·부분 서식을 이동하고, 지연 응답 동안 원본을 유지하는지 확인한다.
|
||||
회의록에서는 실제 contenteditable 선택·서식 도구·초안 저장 후 이동·이번주/지난주 열 순서·75% 배율의 너비 맞춤도 확인한다.
|
||||
목표·회의록의 실제 글·숫자·항목명 입력 시 열 자동 확장(75% 배율·세로 병합 포함), 한 번 Enter의 즉시 빈 줄 표시,
|
||||
연속 개행·모바일 beforeinput 개행·IME Enter 중복 방지도 검증한다.
|
||||
우클릭 현재/전체 열 자동 맞춤은 접힌 월 열의 측정·너비 저장도 검증한다. jsdom에서는 저장 실패·409 충돌·덮어쓰기 취소·Esc 취소를 추가로 확인한다.
|
||||
|
||||
```powershell
|
||||
@@ -45,7 +53,23 @@ node tests/js/goals_autofit.browser.test.js
|
||||
|
||||
```bash
|
||||
python -m unittest discover -s tests -p test_project_goal_move.py
|
||||
python -m unittest discover -s tests -p test_project_meeting_cells.py
|
||||
```
|
||||
|
||||
실제 PostgreSQL 이동·동시 요청 검증은 `python tests/test_project_module.py`에 포함된다.
|
||||
`PROJECT_TEST_DB_URL`에 기존 로컬 테스트 DB를 지정해야 하며, 미설정 또는 로컬 주소가 아니면 건너뛴다.
|
||||
회의록 셀 테스트는 DB 연결을 대신하는 트랜잭션 모형으로 실제 저장소 메서드·API 권한/충돌·이동/병합 롤백·
|
||||
019 미적용·병합 행 작업 보호·서식 보존·안전한 템플릿 출력을 검증한다. 실제 PostgreSQL 잠금 동작 검증은 별도다.
|
||||
|
||||
# 프로젝트 화면·수신함 UI 테스트 (jsdom + 실제 Chrome)
|
||||
|
||||
`project.html`·`inbox.html` + `static/project.js` — 작업 창 저장/실패/동기화, 전체 보기의 연결된(읽기 전용) 작업,
|
||||
수신함 오른쪽 작업 창(저장 대기 뒤 바꾸기·계속 편집·A→B→A·저장 중 Esc·읽음 실패), 새 프로젝트 창(생성/멤버 배정 결과 분리·
|
||||
실패한 멤버만 다시 배정·연타)을 가짜 서버로 검증한다.
|
||||
|
||||
```powershell
|
||||
python tests/js/render_project.py # → tests/js/.out/project_*.html · inbox_render.html
|
||||
node tests/js/project_ui.test.js # jsdom
|
||||
$env:PJ_TEST_BROWSER = 'C:/Program Files/Google/Chrome/Application/chrome.exe'
|
||||
node tests/js/inbox_panel.browser.test.js # Playwright: iframe 리다이렉트 뒤 embed·저장 실패 확인창·A→B→A·iframe 안 Esc·읽음 실패
|
||||
```
|
||||
|
||||
@@ -0,0 +1,848 @@
|
||||
// Actual Chrome, real ERP template/CSS/JS, synthetic assets and controlled APIs.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const http = require("node:http");
|
||||
const path = require("node:path");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.resolve(__dirname, "../.."),
|
||||
OUT = path.join(__dirname, ".out"),
|
||||
STATIC = path.join(ROOT, "app/static");
|
||||
const parsed = JSON.parse(
|
||||
fs.readFileSync(path.join(OUT, "asset_report.json"), "utf8"),
|
||||
);
|
||||
let conflict = false,
|
||||
slow = false,
|
||||
mutations = [],
|
||||
counter = 30;
|
||||
const timestamp = "2026-10-06T01:00:00+09:00";
|
||||
const records = Array.from({ length: 30 }, (_, i) => ({
|
||||
id: "asset" + i,
|
||||
tag: "AST-" + String(i + 1).padStart(6, "0"),
|
||||
name: i === 0 ? "KING-DESKTOP" : `테스트 자산 ${i}`,
|
||||
category: i % 3 === 0 ? "computer" : i % 3 === 1 ? "chair" : "mouse",
|
||||
status: "available",
|
||||
manufacturer: "",
|
||||
model: i === 0 ? parsed.summary.motherboard : "",
|
||||
serial: "",
|
||||
location: "본사 3층",
|
||||
department: "디자인팀",
|
||||
assignee_email: "",
|
||||
purchased_on: "2026-01-01",
|
||||
purchase_cost: "1250000",
|
||||
vendor: "",
|
||||
warranty_until: "2026-10-20",
|
||||
notes: "",
|
||||
latest_report_id: i === 0 ? "report1" : null,
|
||||
version: 1,
|
||||
created_at: timestamp,
|
||||
updated_at: timestamp,
|
||||
specs: i === 0 ? parsed.summary : null,
|
||||
}));
|
||||
const users = [
|
||||
{ email: "reader@test.local", name: "담당자" },
|
||||
{ email: "staff@test.local", name: "직원" },
|
||||
];
|
||||
Object.assign(records[2], {
|
||||
name: "Registered Monitor",
|
||||
category: "monitor",
|
||||
model: "Test Display 24",
|
||||
serial: "synthetic-monitor-1",
|
||||
});
|
||||
const photoRecords = new Map(),
|
||||
monitorLinks = new Map();
|
||||
const photoPNG = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jR1kAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
function monitorItems(a) {
|
||||
return [0, 1, 2].map((i) => ({
|
||||
index: i,
|
||||
name: "Test Display " + (i + 1),
|
||||
model: "Test Display 24",
|
||||
serial: i < 2 ? "synthetic-monitor-" + (i + 1) : "",
|
||||
manufacturer: "Test",
|
||||
asset:
|
||||
records.find((r) => r.id === monitorLinks.get(a.id + ":" + i)) ||
|
||||
(i === 0 ? records.find((r) => r.id === "asset2") : null),
|
||||
candidates:
|
||||
i === 2 ? [records.find((r) => r.id === "asset2")].filter(Boolean) : [],
|
||||
}));
|
||||
}
|
||||
const events = [
|
||||
{
|
||||
id: 1,
|
||||
asset_id: "asset0",
|
||||
actor: "reader@test.local",
|
||||
kind: "create",
|
||||
note: "자산 등록",
|
||||
changes: {},
|
||||
created_at: timestamp,
|
||||
},
|
||||
];
|
||||
const reports = [
|
||||
{
|
||||
id: "report1",
|
||||
asset_id: "asset0",
|
||||
filename: "KING-DESKTOP.XML",
|
||||
uploaded_at: timestamp,
|
||||
actor: "reader@test.local",
|
||||
summary: parsed.summary,
|
||||
scan_time: parsed.scan_time,
|
||||
},
|
||||
];
|
||||
function json(res, value, code = 200) {
|
||||
res.writeHead(code, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(value));
|
||||
}
|
||||
function filter(p) {
|
||||
let rows = records.filter(
|
||||
(a) => !p.get("category") || a.category === p.get("category"),
|
||||
);
|
||||
for (const key of ["status", "location"])
|
||||
rows = rows.filter((a) => !p.get(key) || a[key] === p.get(key));
|
||||
if (p.get("assignee"))
|
||||
rows = rows.filter((a) => a.assignee_email === p.get("assignee"));
|
||||
if (p.get("group"))
|
||||
rows = rows.filter(
|
||||
(a) =>
|
||||
(p.get("group") === "furniture") ===
|
||||
["chair", "desk", "furniture"].includes(a.category),
|
||||
);
|
||||
if (p.get("q"))
|
||||
rows = rows.filter((a) => (a.name + a.tag + a.notes).includes(p.get("q")));
|
||||
return rows;
|
||||
}
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
if (url.pathname === "/asset/") {
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8");
|
||||
res.end(
|
||||
fs.readFileSync(
|
||||
path.join(
|
||||
OUT,
|
||||
url.searchParams.has("super")
|
||||
? "asset_super.html"
|
||||
: url.searchParams.has("unconfigured")
|
||||
? "asset_unconfigured.html"
|
||||
: "asset_render.html",
|
||||
),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (url.pathname.startsWith("/static/")) {
|
||||
const file = path.resolve(
|
||||
STATIC,
|
||||
"." + decodeURIComponent(url.pathname.slice(7)),
|
||||
);
|
||||
if (
|
||||
!file.startsWith(STATIC + path.sep) ||
|
||||
!fs.existsSync(file) ||
|
||||
!fs.statSync(file).isFile()
|
||||
) {
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
const types = {
|
||||
".css": "text/css",
|
||||
".js": "text/javascript",
|
||||
".woff2": "font/woff2",
|
||||
".png": "image/png",
|
||||
};
|
||||
res.setHeader(
|
||||
"Content-Type",
|
||||
types[path.extname(file)] || "application/octet-stream",
|
||||
);
|
||||
fs.createReadStream(file).pipe(res);
|
||||
return;
|
||||
}
|
||||
const route = url.pathname.slice("/asset/api/".length),
|
||||
parts = route.split("/");
|
||||
const chunks = [];
|
||||
for await (const chunk of req) chunks.push(chunk);
|
||||
const raw = Buffer.concat(chunks),
|
||||
body = req.headers["content-type"]?.includes("application/json")
|
||||
? JSON.parse(raw.toString())
|
||||
: null;
|
||||
if (req.method !== "GET") {
|
||||
assert.equal(req.headers["x-asset-csrf"], "browser-test");
|
||||
mutations.push({ route, body });
|
||||
}
|
||||
if (route === "bootstrap") {
|
||||
const totals = {
|
||||
total: records.length,
|
||||
available: 0,
|
||||
in_use: 0,
|
||||
maintenance: 0,
|
||||
lost: 0,
|
||||
retired: 0,
|
||||
warranty_soon: records.length,
|
||||
purchase_total: "37500000",
|
||||
};
|
||||
records.forEach((a) => totals[a.status]++);
|
||||
json(res, {
|
||||
totals,
|
||||
users,
|
||||
locations: ["本社", "본사 3층"],
|
||||
categories: ["computer", "chair", "mouse"].map((category) => ({
|
||||
category,
|
||||
count: records.filter((a) => a.category === category).length,
|
||||
})),
|
||||
activity: events
|
||||
.slice(-12)
|
||||
.reverse()
|
||||
.map((e) => ({
|
||||
...e,
|
||||
tag: "AST-000001",
|
||||
name: records.find((a) => a.id === e.asset_id)?.name || "Asset",
|
||||
})),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (route === "assets" && req.method === "GET") {
|
||||
const rows = filter(url.searchParams),
|
||||
page = Number(url.searchParams.get("page") || 1),
|
||||
result = {
|
||||
items: rows.slice((page - 1) * 25, page * 25),
|
||||
total: rows.length,
|
||||
page,
|
||||
page_size: 25,
|
||||
};
|
||||
if (slow && url.searchParams.get("q") === "테스트") {
|
||||
setTimeout(() => json(res, result), 500);
|
||||
return;
|
||||
}
|
||||
json(res, result);
|
||||
return;
|
||||
}
|
||||
if (route === "assets" && req.method === "POST") {
|
||||
const a = {
|
||||
...records[1],
|
||||
...body,
|
||||
id: "asset" + counter++,
|
||||
tag: body.tag || "AST-TEST",
|
||||
specs: null,
|
||||
latest_report_id: null,
|
||||
};
|
||||
records.push(a);
|
||||
json(res, { id: a.id });
|
||||
return;
|
||||
}
|
||||
if (route === "reports/preview") {
|
||||
if (raw.toString().includes("invalid.xml")) {
|
||||
json(res, { detail: "올바르지 않은 보고서입니다." }, 422);
|
||||
return;
|
||||
}
|
||||
json(res, {
|
||||
filename: "test.xml",
|
||||
summary: parsed.summary,
|
||||
property_count: parsed.property_count,
|
||||
scan_time: parsed.scan_time,
|
||||
warnings: [],
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (route === "reports/import") {
|
||||
const match = raw
|
||||
.toString()
|
||||
.match(/name="payload"\r\n\r\n([\s\S]*?)\r\n--/);
|
||||
assert.ok(match, "multipart import must carry the asset payload");
|
||||
const data = JSON.parse(match[1]);
|
||||
const a = {
|
||||
...records[0],
|
||||
...data,
|
||||
id: "asset" + counter++,
|
||||
tag: "AST-IMPORT",
|
||||
};
|
||||
records.push(a);
|
||||
json(res, { id: a.id });
|
||||
return;
|
||||
}
|
||||
if (parts[0] === "assets" && parts[1]) {
|
||||
const a = records.find((a) => a.id === parts[1]);
|
||||
if (!a) {
|
||||
json(res, { detail: "없음" }, 404);
|
||||
return;
|
||||
}
|
||||
if (parts.length === 2 && req.method === "GET") {
|
||||
json(res, {
|
||||
asset: a,
|
||||
report: a.latest_report_id ? { ...reports[0], parsed } : null,
|
||||
reports: a.latest_report_id ? reports : [],
|
||||
events: events.filter((e) => e.asset_id === a.id),
|
||||
photos: photoRecords.get(a.id) || [],
|
||||
monitors: a.latest_report_id ? monitorItems(a) : [],
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (parts.length === 2 && req.method === "DELETE") {
|
||||
assert.equal(body.version, a.version);
|
||||
records.splice(records.indexOf(a), 1);
|
||||
json(res, { ok: true });
|
||||
return;
|
||||
}
|
||||
if (parts[2] === "photos" && parts.length === 3 && req.method === "POST") {
|
||||
const match = raw.toString().match(/name="version"\r\n\r\n(\d+)/);
|
||||
assert.equal(Number(match[1]), a.version);
|
||||
const photos = photoRecords.get(a.id) || [];
|
||||
photos.push({ id: "photo" + photos.length, filename: "test.png" });
|
||||
photoRecords.set(a.id, photos);
|
||||
a.version++;
|
||||
json(res, { id: photos.at(-1).id });
|
||||
return;
|
||||
}
|
||||
if (parts[2] === "photos" && parts.length === 4) {
|
||||
res.setHeader("Content-Type", "image/png");
|
||||
res.end(photoPNG);
|
||||
return;
|
||||
}
|
||||
if (parts[2] === "monitors" && req.method === "POST") {
|
||||
assert.equal(body.version, a.version);
|
||||
let target;
|
||||
if (body.asset) {
|
||||
target = {
|
||||
...records[1],
|
||||
...body.asset,
|
||||
id: "asset" + counter++,
|
||||
tag: "AST-MONITOR",
|
||||
version: 1,
|
||||
latest_report_id: null,
|
||||
specs: null,
|
||||
};
|
||||
records.push(target);
|
||||
} else target = records.find((r) => r.id === body.asset_id);
|
||||
monitorLinks.set(a.id + ":" + parts[3], target.id);
|
||||
a.version++;
|
||||
json(res, { id: target.id });
|
||||
return;
|
||||
}
|
||||
if (parts[2] === "reports" && parts[4] === "monitors") {
|
||||
json(res, { items: monitorItems(a) });
|
||||
return;
|
||||
}
|
||||
if (parts.length === 2 && req.method === "PUT") {
|
||||
if (conflict) {
|
||||
conflict = false;
|
||||
json(
|
||||
res,
|
||||
{ detail: "다른 사용자가 수정했습니다. 다시 확인하세요." },
|
||||
409,
|
||||
);
|
||||
return;
|
||||
}
|
||||
assert.equal(body.version, a.version);
|
||||
Object.assign(a, body, { version: a.version + 1 });
|
||||
json(res, { ok: true });
|
||||
return;
|
||||
}
|
||||
if (parts[2] === "actions") {
|
||||
assert.equal(body.version, a.version);
|
||||
a.version++;
|
||||
a.status = {
|
||||
checkout: "in_use",
|
||||
checkin: "available",
|
||||
maintenance: "maintenance",
|
||||
available: "available",
|
||||
lost: "lost",
|
||||
retired: "retired",
|
||||
}[body.action];
|
||||
a.assignee_email = body.action === "checkout" ? body.assignee_email : "";
|
||||
events.push({
|
||||
id: events.length + 1,
|
||||
asset_id: a.id,
|
||||
kind: body.action,
|
||||
note: body.note,
|
||||
actor: users[0].email,
|
||||
changes: {},
|
||||
created_at: timestamp,
|
||||
});
|
||||
json(res, { ok: true });
|
||||
return;
|
||||
}
|
||||
if (parts[2] === "reports" && parts.length === 3) {
|
||||
a.latest_report_id = "report1";
|
||||
a.specs = parsed.summary;
|
||||
a.version++;
|
||||
json(res, { id: "report1" });
|
||||
return;
|
||||
}
|
||||
if (parts[2] === "reports" && parts.length === 4) {
|
||||
json(res, { ...reports[0], parsed });
|
||||
return;
|
||||
}
|
||||
}
|
||||
res.writeHead(404);
|
||||
res.end();
|
||||
});
|
||||
|
||||
(async () => {
|
||||
let browser;
|
||||
try {
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
browser = await chromium.launch({
|
||||
headless: true,
|
||||
executablePath:
|
||||
process.env.PJ_TEST_BROWSER ||
|
||||
"C:/Program Files/Google/Chrome/Application/chrome.exe",
|
||||
});
|
||||
const page = await browser.newPage({
|
||||
viewport: { width: 1600, height: 1050 },
|
||||
});
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const origin = `http://127.0.0.1:${server.address().port}`;
|
||||
await page.goto(origin + "/asset/");
|
||||
await page.locator("#am-total").filter({ hasText: "30" }).waitFor();
|
||||
assert.equal(await page.locator("#am-rows tr").count(), 25);
|
||||
// 실제 브라우저의 애니메이션 시각을 고정해 중간 위치와 닫기 완료 시점을 확인합니다.
|
||||
await page.evaluate(() => {
|
||||
const drawer = document.querySelector("#am-detail"),
|
||||
animate = drawer.animate.bind(drawer);
|
||||
drawer.animate = (frames, options) => {
|
||||
const motion = animate(frames, options);
|
||||
motion.pause();
|
||||
return motion;
|
||||
};
|
||||
});
|
||||
const finishDrawer = () =>
|
||||
page.evaluate(async () => {
|
||||
const motion = document
|
||||
.querySelector("#am-detail")
|
||||
.getAnimations()
|
||||
.find((a) => a.id === "asset-drawer");
|
||||
if (motion) {
|
||||
motion.finish();
|
||||
await motion.finished;
|
||||
}
|
||||
});
|
||||
const drawerPosition = (time) =>
|
||||
page.evaluate((time) => {
|
||||
const drawer = document.querySelector("#am-detail"),
|
||||
motion = drawer
|
||||
.getAnimations()
|
||||
.find((a) => a.id === "asset-drawer");
|
||||
if (time !== null) motion.currentTime = time;
|
||||
const rect = drawer.getBoundingClientRect();
|
||||
return {
|
||||
left: rect.left,
|
||||
width: rect.width,
|
||||
viewport: innerWidth,
|
||||
open: drawer.open,
|
||||
closing: drawer.classList.contains("am-closing"),
|
||||
};
|
||||
}, time);
|
||||
await page.locator('[data-open="asset0"]').first().click();
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
document.querySelector("#am-detail-title").textContent ===
|
||||
"KING-DESKTOP",
|
||||
);
|
||||
const entryStart = await drawerPosition(0),
|
||||
entryMiddle = await drawerPosition(140);
|
||||
assert.ok(
|
||||
Math.abs(entryStart.left - entryStart.viewport) < 2,
|
||||
"entry starts beyond the right screen edge",
|
||||
);
|
||||
assert.ok(
|
||||
entryMiddle.left < entryStart.left &&
|
||||
entryMiddle.left > entryStart.viewport - entryStart.width,
|
||||
"entry moves from right to left",
|
||||
);
|
||||
await finishDrawer();
|
||||
const atRest = await drawerPosition(null);
|
||||
assert.ok(Math.abs(atRest.left - (atRest.viewport - atRest.width)) < 2);
|
||||
await page.locator('[data-close="am-detail"]').click();
|
||||
const exitStart = await drawerPosition(0),
|
||||
exitMiddle = await drawerPosition(110);
|
||||
assert.ok(
|
||||
exitStart.open && exitStart.closing,
|
||||
"X retains the drawer until animation completion",
|
||||
);
|
||||
assert.ok(exitMiddle.left > exitStart.left, "exit moves back to the right");
|
||||
await finishDrawer();
|
||||
assert.equal(
|
||||
await page.locator("#am-detail").evaluate((el) => el.open),
|
||||
false,
|
||||
);
|
||||
assert.equal(new URL(page.url()).searchParams.has("asset"), false);
|
||||
assert.equal(
|
||||
await page.evaluate(() => document.activeElement.dataset.open),
|
||||
"asset0",
|
||||
"focus returns to the selected asset",
|
||||
);
|
||||
|
||||
await page.locator('[data-open="asset0"]').first().click();
|
||||
await finishDrawer();
|
||||
const rect = await page.locator("#am-detail").boundingBox();
|
||||
await page.mouse.move(rect.x + 100, 300);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(10, 300);
|
||||
await page.mouse.up();
|
||||
assert.equal(
|
||||
(await drawerPosition(null)).closing,
|
||||
false,
|
||||
"inside-to-outside drag must not dismiss",
|
||||
);
|
||||
await page.mouse.click(10, 400);
|
||||
assert.equal(
|
||||
(await drawerPosition(80)).closing,
|
||||
true,
|
||||
"backdrop click starts animated dismissal",
|
||||
);
|
||||
// 닫기 도중 다시 열면 취소한 닫기의 완료 콜백이 새 패널을 닫지 않습니다.
|
||||
const interrupted = await drawerPosition(null);
|
||||
await page.evaluate(() =>
|
||||
document.querySelector('#am-rows [data-open="asset0"]').click(),
|
||||
);
|
||||
assert.ok(
|
||||
Math.abs((await drawerPosition(0)).left - interrupted.left) < 2,
|
||||
"reopen continues from the current position",
|
||||
);
|
||||
await finishDrawer();
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
document.querySelector("#am-detail-title").textContent ===
|
||||
"KING-DESKTOP",
|
||||
);
|
||||
assert.equal((await drawerPosition(null)).closing, false);
|
||||
await page.keyboard.press("Escape");
|
||||
assert.equal(
|
||||
(await drawerPosition(110)).closing,
|
||||
true,
|
||||
"Escape uses the same exit animation",
|
||||
);
|
||||
await finishDrawer();
|
||||
|
||||
// 닫힌 뒤 도착하는 응답이 패널을 다시 열거나 선택 URL을 복구하지 않습니다.
|
||||
await page.route("**/asset/api/assets/asset0", async (route) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 200));
|
||||
await route.continue();
|
||||
});
|
||||
const delayedResponse = page.waitForResponse((response) =>
|
||||
response.url().endsWith("/asset/api/assets/asset0"),
|
||||
);
|
||||
await page.locator('[data-open="asset0"]').first().click();
|
||||
await drawerPosition(100);
|
||||
await page.evaluate(() =>
|
||||
document.querySelector('[data-close="am-detail"]').click(),
|
||||
);
|
||||
await finishDrawer();
|
||||
await delayedResponse;
|
||||
await page.evaluate(
|
||||
() => new Promise((resolve) => requestAnimationFrame(resolve)),
|
||||
);
|
||||
assert.equal(
|
||||
await page.locator("#am-detail").evaluate((el) => el.open),
|
||||
false,
|
||||
);
|
||||
assert.equal(new URL(page.url()).searchParams.has("asset"), false);
|
||||
await page.unroute("**/asset/api/assets/asset0");
|
||||
|
||||
await page.emulateMedia({ reducedMotion: "reduce" });
|
||||
await page.locator('[data-open="asset0"]').first().click();
|
||||
assert.equal(
|
||||
await page
|
||||
.locator("#am-detail")
|
||||
.evaluate((el) => el.getAnimations().length),
|
||||
0,
|
||||
);
|
||||
await page.locator('[data-close="am-detail"]').click();
|
||||
assert.equal(
|
||||
await page.locator("#am-detail").evaluate((el) => el.open),
|
||||
false,
|
||||
);
|
||||
await page.emulateMedia({ reducedMotion: "no-preference" });
|
||||
await page.evaluate(() => {
|
||||
delete document.querySelector("#am-detail").animate;
|
||||
});
|
||||
await page.screenshot({
|
||||
path: path.join(OUT, "asset-desktop.png"),
|
||||
fullPage: true,
|
||||
});
|
||||
await page.locator("#am-next").click();
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector("#am-page-number").textContent === "2 / 2",
|
||||
);
|
||||
assert.equal(await page.locator("#am-rows tr").count(), 5);
|
||||
await page.locator('[data-view="furniture"]').click();
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
document.querySelector("#am-result-count").textContent === "10개 자산",
|
||||
);
|
||||
assert.equal(await page.locator("#am-page-number").textContent(), "1 / 1");
|
||||
await page.locator("#am-reset").click();
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
document.querySelector("#am-result-count").textContent === "30개 자산",
|
||||
);
|
||||
slow = true;
|
||||
await page.locator("#am-query").fill("테스트");
|
||||
await page.waitForTimeout(300);
|
||||
await page.locator("#am-query").fill("KING");
|
||||
await page.waitForTimeout(800);
|
||||
assert.equal(
|
||||
await page.locator("#am-result-count").textContent(),
|
||||
"1개 자산",
|
||||
"late search response must not replace the newest result",
|
||||
);
|
||||
await page.locator('[data-open="asset0"][data-tab="specs"]').click();
|
||||
await page.locator("#am-spec-query").waitFor();
|
||||
assert.equal(
|
||||
await page.locator("[data-delete]").count(),
|
||||
0,
|
||||
"ordinary users must not see deletion",
|
||||
);
|
||||
assert.equal(await page.locator(".am-monitor-card").count(), 3);
|
||||
await page.locator('[data-monitor-open="asset2"]').click();
|
||||
await page
|
||||
.locator("#am-detail-title")
|
||||
.filter({ hasText: "Registered Monitor" })
|
||||
.waitFor();
|
||||
await page.locator("[data-return-computer]").click();
|
||||
await page.locator("#am-spec-query").waitFor();
|
||||
assert.ok(
|
||||
(await page.locator(".am-spec-card").first().textContent()).includes(
|
||||
parsed.summary.cpu,
|
||||
),
|
||||
);
|
||||
await page.locator("#am-spec-section").selectOption("MEMORY");
|
||||
await page.locator("#am-detail").evaluate((el) => {
|
||||
el.scrollTop = 0;
|
||||
});
|
||||
await page.screenshot({ path: path.join(OUT, "asset-specs.png") });
|
||||
await page.locator("#am-spec-query").fill("M378A2K43EB1");
|
||||
if (parsed.summary.computer_name === "KING-DESKTOP")
|
||||
assert.equal(await page.locator(".am-node").count(), 2);
|
||||
await page.locator('[data-detail-tab="overview"]').click();
|
||||
await page.locator("[data-edit]").click();
|
||||
await page
|
||||
.locator('#am-editor-form [name="notes"]')
|
||||
.fill("저장 전 초안 <script>window.assetInjected=true</script>");
|
||||
conflict = true;
|
||||
await page.locator('#am-editor-form [type="submit"]').click();
|
||||
await page
|
||||
.locator("#am-editor-form .am-form-error")
|
||||
.filter({ hasText: "다른 사용자" })
|
||||
.waitFor();
|
||||
assert.ok(
|
||||
(
|
||||
await page.locator('#am-editor-form [name="notes"]').inputValue()
|
||||
).includes("초안"),
|
||||
);
|
||||
await page.locator('#am-editor-form [type="submit"]').click();
|
||||
await page.waitForFunction(
|
||||
() => !document.querySelector("#am-editor").open,
|
||||
);
|
||||
await page.locator('[data-action="checkout"]').waitFor();
|
||||
assert.equal(await page.evaluate(() => window.assetInjected), undefined);
|
||||
await page.locator('[data-action="checkout"]').click();
|
||||
await page.locator("#am-action-user").selectOption("staff@test.local");
|
||||
await page.locator("#am-action-save").click();
|
||||
await page.waitForFunction(
|
||||
() => !document.querySelector("#am-action").open,
|
||||
);
|
||||
await page.locator('[data-action="checkin"]').waitFor();
|
||||
assert.equal(
|
||||
await page.locator('[data-action="retired"]').count(),
|
||||
0,
|
||||
"assigned assets cannot be retired directly",
|
||||
);
|
||||
await page.locator('[data-action="checkin"]').click();
|
||||
await page.locator("#am-action-save").click();
|
||||
await page.waitForFunction(
|
||||
() => !document.querySelector("#am-action").open,
|
||||
);
|
||||
await page.locator('[data-action="checkout"]').waitFor();
|
||||
await page.locator('[data-detail-tab="reports"]').click();
|
||||
await page.locator("[data-report]").click();
|
||||
await page.locator("#am-spec-query").waitFor();
|
||||
assert.ok(
|
||||
(await page.locator("#am-detail-content").textContent()).includes(
|
||||
"선택한 보고서",
|
||||
),
|
||||
);
|
||||
await page.locator('[data-close="am-detail"]').click();
|
||||
await page.locator("#am-import").click();
|
||||
await page.locator("#am-report-file").setInputFiles({
|
||||
name: "invalid.xml",
|
||||
mimeType: "text/xml",
|
||||
buffer: Buffer.from("<broken/>"),
|
||||
});
|
||||
await page
|
||||
.locator("#am-upload-form .am-form-error")
|
||||
.filter({ hasText: "올바르지" })
|
||||
.waitFor();
|
||||
assert.equal(await page.locator("#am-import-save").isDisabled(), true);
|
||||
await page
|
||||
.locator("#am-report-file")
|
||||
.setInputFiles(path.join(OUT, "asset_upload.xml"));
|
||||
await page.locator("#am-report-preview").waitFor({ state: "visible" });
|
||||
assert.equal(
|
||||
await page.locator("#am-import-name").inputValue(),
|
||||
parsed.summary.computer_name,
|
||||
);
|
||||
await page.screenshot({ path: path.join(OUT, "asset-import.png") });
|
||||
await page.locator("#am-import-name").fill("Uploaded workstation");
|
||||
await page.locator("#am-import-save").click();
|
||||
await page.waitForFunction(
|
||||
() => !document.querySelector("#am-upload").open,
|
||||
);
|
||||
await page
|
||||
.locator("#am-detail-title")
|
||||
.filter({ hasText: "Uploaded workstation" })
|
||||
.waitFor();
|
||||
await page.locator("#am-spec-query").waitFor();
|
||||
await page.locator("[data-attach]").click();
|
||||
await page
|
||||
.locator("#am-report-file")
|
||||
.setInputFiles(path.join(OUT, "asset_upload.xml"));
|
||||
await page.locator("#am-report-preview").waitFor({ state: "visible" });
|
||||
assert.equal(await page.locator("#am-import-fields").isVisible(), false);
|
||||
await page.locator("#am-import-save").click();
|
||||
await page.waitForFunction(
|
||||
() => !document.querySelector("#am-upload").open,
|
||||
);
|
||||
await page
|
||||
.locator("#am-detail-title")
|
||||
.filter({ hasText: "Uploaded workstation" })
|
||||
.waitFor();
|
||||
await page.keyboard.press("Escape");
|
||||
await page.locator("#am-create").click();
|
||||
await page.locator('#am-editor-form [name="name"]').fill("테스트 의자");
|
||||
await page
|
||||
.locator('#am-editor-form [name="category"]')
|
||||
.selectOption("chair");
|
||||
await page.locator('#am-editor-form [type="submit"]').click();
|
||||
await page.waitForFunction(
|
||||
() => !document.querySelector("#am-editor").open,
|
||||
);
|
||||
await page
|
||||
.locator("#am-detail-title")
|
||||
.filter({ hasText: "테스트 의자" })
|
||||
.waitFor();
|
||||
assert.equal(await page.locator('[data-detail-tab="specs"]').count(), 0);
|
||||
await page.keyboard.press("Escape");
|
||||
// 모니터 등록과 연결이 끝나면 같은 화면에서 자산 개요를 확인할 수 있습니다.
|
||||
await page.goto(origin + "/asset/?asset=asset0&tab=specs");
|
||||
await page.locator('[data-monitor-create="1"]').waitFor();
|
||||
await page.locator('[data-monitor-create="1"]').click();
|
||||
assert.equal(
|
||||
await page.locator('#am-editor-form [name="category"]').inputValue(),
|
||||
"monitor",
|
||||
);
|
||||
assert.equal(
|
||||
await page.locator('#am-editor-form [name="category"]').isDisabled(),
|
||||
true,
|
||||
);
|
||||
await page.locator('#am-editor-form [name="name"]').fill("New Monitor");
|
||||
await page.locator('#am-editor-form [type="submit"]').click();
|
||||
await page.waitForFunction(
|
||||
() => !document.querySelector("#am-editor").open,
|
||||
);
|
||||
await page
|
||||
.locator(".am-linked-overview h4")
|
||||
.filter({ hasText: "New Monitor" })
|
||||
.waitFor();
|
||||
assert.equal(await page.locator('[data-monitor-create="1"]').count(), 0);
|
||||
await page.locator('[data-monitor-link="2"]').click();
|
||||
await page.waitForFunction(
|
||||
() => document.querySelectorAll(".am-linked-overview").length === 3,
|
||||
);
|
||||
await page.screenshot({ path: path.join(OUT, "asset-monitor-links.png") });
|
||||
await page.locator('[data-detail-tab="overview"]').click();
|
||||
await page.locator("[data-photo]").click();
|
||||
await page.locator("#am-photo-file").setInputFiles({
|
||||
name: "test.png",
|
||||
mimeType: "image/png",
|
||||
buffer: photoPNG,
|
||||
});
|
||||
await page.locator('#am-photo-form [type="submit"]').click();
|
||||
await page.waitForFunction(() => !document.querySelector("#am-photo").open);
|
||||
await page.locator('.am-photo-grid img[alt="test.png"]').waitFor();
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector(".am-photo-grid img")?.naturalWidth > 0,
|
||||
);
|
||||
await page.screenshot({ path: path.join(OUT, "asset-photos.png") });
|
||||
await page.keyboard.press("Escape");
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.locator("#am-reset").click();
|
||||
await page.waitForTimeout(100);
|
||||
assert.ok(
|
||||
await page.evaluate(
|
||||
() => document.documentElement.scrollWidth <= innerWidth + 1,
|
||||
),
|
||||
"mobile document should not overflow horizontally",
|
||||
);
|
||||
await page.screenshot({
|
||||
path: path.join(OUT, "asset-mobile.png"),
|
||||
fullPage: true,
|
||||
});
|
||||
await page.locator('[data-open="asset0"]').first().click();
|
||||
await page
|
||||
.locator("#am-detail-title")
|
||||
.filter({ hasText: "KING-DESKTOP" })
|
||||
.waitFor();
|
||||
assert.ok(
|
||||
await page.evaluate(
|
||||
() =>
|
||||
document.querySelector("#am-detail").scrollWidth <= innerWidth + 1,
|
||||
),
|
||||
);
|
||||
await page.locator('.am-tabs [data-detail-tab="specs"]').click();
|
||||
await page.locator("#am-spec-query").waitFor();
|
||||
await page.locator("#am-spec-section").selectOption("MEMORY");
|
||||
await page.screenshot({ path: path.join(OUT, "asset-mobile-specs.png") });
|
||||
await page.keyboard.press("Escape");
|
||||
await page.goto(origin + "/asset/?category=chair&q=테스트");
|
||||
await page.waitForFunction(
|
||||
() =>
|
||||
document.querySelector("#am-result-count").textContent === "11개 자산",
|
||||
);
|
||||
assert.equal(await page.locator("#am-category").inputValue(), "chair");
|
||||
await page.goto(origin + "/asset/?unconfigured=1");
|
||||
assert.equal(await page.locator("#am-create").isDisabled(), true);
|
||||
await page.locator("#am-import").click();
|
||||
await page
|
||||
.locator("#am-report-file")
|
||||
.setInputFiles(path.join(OUT, "asset_upload.xml"));
|
||||
await page.locator("#am-report-preview").waitFor({ state: "visible" });
|
||||
assert.equal(await page.locator("#am-import-save").isDisabled(), true);
|
||||
// 수퍼 관리자는 자산번호·사유 확인 후 삭제하고, 취소와 잘못된 입력은 요청하지 않습니다.
|
||||
await page.goto(origin + "/asset/?super=1&asset=asset5");
|
||||
await page.locator("[data-delete]").waitFor();
|
||||
await page.locator("[data-delete]").click();
|
||||
await page.locator("#am-delete-confirm").fill("WRONG");
|
||||
await page.locator("#am-delete-note").fill("Duplicate test asset");
|
||||
await page.locator('#am-delete-form [type="submit"]').click();
|
||||
await page
|
||||
.locator("#am-delete-form .am-form-error")
|
||||
.filter({ hasText: "자산번호" })
|
||||
.waitFor();
|
||||
const before = records.length;
|
||||
await page.locator("#am-delete-confirm").fill("AST-000006");
|
||||
await page.locator('#am-delete-form [type="submit"]').click();
|
||||
await page.waitForFunction(
|
||||
() => !document.querySelector("#am-detail").open,
|
||||
);
|
||||
assert.equal(records.length, before - 1);
|
||||
assert.equal(
|
||||
records.some((a) => a.id === "asset5"),
|
||||
false,
|
||||
);
|
||||
await page.waitForFunction(
|
||||
(n) => document.querySelector("#am-total").textContent === String(n),
|
||||
records.length,
|
||||
);
|
||||
assert.deepEqual(errors, []);
|
||||
console.log(
|
||||
"ALL PASS: Chrome desktop/mobile, drawer entry/exit/backdrop/X/Escape, interrupt/reopen, late responses, reduced motion, search races, paging, specs, XSS escaping, conflict draft, create, checkout/checkin, reports, setup mode, photos, monitor registration/link/overview, super-admin deletion",
|
||||
);
|
||||
} finally {
|
||||
await browser?.close();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
})().catch((error) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,169 @@
|
||||
// 실제 브라우저에서 주차를 바꿔도 왼쪽 DOM·스크롤·폴더가 유지되고, 저장 실패 시 이동을 멈추는지 확인한다.
|
||||
// python tests/js/render_goals.py; NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/goal_nav.browser.test.js
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs"), path = require("node:path"), http = require("node:http");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.resolve(__dirname, "../.."), OUT = path.join(__dirname, ".out"), STATIC = path.join(ROOT, "app/static");
|
||||
const firstMonday = month => {
|
||||
const d = new Date(Date.UTC(2026, month - 1, 1));
|
||||
d.setUTCDate(d.getUTCDate() + (8 - d.getUTCDay()) % 7);
|
||||
return d.toISOString().slice(0, 10);
|
||||
};
|
||||
const tree = { years: [{ year: 2026, months: Array.from({ length: 12 }, (_, i) => {
|
||||
const month = i + 1, starts = month === 9 ? ["2026-09-21", "2026-09-28"] : [firstMonday(month)];
|
||||
return { month, weeks: starts.map(start => ({ start, label: start, href: `/project/goals/2026/meetings/${month}?week=${start}` })) };
|
||||
}) }] };
|
||||
let navReads = 0, topReads = 0, releaseSave = null, saving = false, failSave = false, holdSave = false;
|
||||
let failContent = false, delayWeek = "", liveVersion = "1";
|
||||
const contentReads = [], writes = [];
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
if (url.pathname === "/project/api/goals/meeting-nav") { navReads++; res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(tree)); return; }
|
||||
if (url.pathname.startsWith("/project/api/")) {
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
if (url.pathname.endsWith("/live-version")) { res.end(JSON.stringify({ ts: liveVersion })); return; }
|
||||
if (req.method === "PUT") {
|
||||
let raw = ""; for await (const chunk of req) raw += chunk;
|
||||
writes.push({ path: url.pathname, body: JSON.parse(raw) });
|
||||
if (holdSave) { saving = true; await new Promise(r => { releaseSave = r; }); saving = false; }
|
||||
if (failSave) { res.statusCode = 503; res.end(JSON.stringify({ detail: "test save failure" })); return; }
|
||||
}
|
||||
res.end("{}"); return;
|
||||
}
|
||||
if (url.pathname.startsWith("/project/goals/")) {
|
||||
const month = Number(url.pathname.split("/").pop());
|
||||
const week = url.searchParams.get("week") || firstMonday(month);
|
||||
const content = url.searchParams.get("content") === "1";
|
||||
if (content) contentReads.push(week); else topReads++;
|
||||
if (content && week === delayWeek) await new Promise(r => setTimeout(r, 150));
|
||||
if (content && failContent) { res.statusCode = 503; res.setHeader("Content-Type", "text/html"); res.end("unavailable"); return; }
|
||||
const fixture = /\/meetings\//.test(url.pathname) ? (content ? "meeting_content_admin.html" : "meeting_shell_admin.html") : "goals_shell_admin.html";
|
||||
let html = fs.readFileSync(path.join(OUT, fixture), "utf8")
|
||||
.replaceAll("2026-09-28", week).replaceAll("2026년 9월", `2026년 ${month}월`).replaceAll('data-month="9"', `data-month="${month}"`);
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(html); return;
|
||||
}
|
||||
const file = path.resolve(STATIC, "." + decodeURIComponent(url.pathname.slice(7)));
|
||||
if (!url.pathname.startsWith("/static/") || !file.startsWith(STATIC + path.sep) || !fs.existsSync(file)) { res.statusCode = 404; res.end(); return; }
|
||||
res.setHeader("Content-Type", ({ ".css": "text/css", ".js": "text/javascript", ".woff2": "font/woff2", ".woff": "font/woff" })[path.extname(file)] || "application/octet-stream");
|
||||
res.end(fs.readFileSync(file));
|
||||
});
|
||||
(async () => {
|
||||
let browser;
|
||||
try {
|
||||
await new Promise(r => server.listen(0, "127.0.0.1", r));
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.PJ_TEST_BROWSER || undefined });
|
||||
const context = await browser.newContext({ viewport: { width: 1600, height: 1000 } });
|
||||
const page = await context.newPage();
|
||||
const errors = []; page.on("pageerror", e => errors.push(e.message));
|
||||
const origin = "http://127.0.0.1:" + server.address().port;
|
||||
await page.goto(origin + "/project/goals/2026/meetings/9?week=2026-09-28");
|
||||
const currentFrame = () => page.frames().find(f => /content=1/.test(f.url()) && f.url() !== "about:blank");
|
||||
const ready = async week => {
|
||||
await page.waitForFunction(w => {
|
||||
const f = document.querySelector(".pj-meeting-panel-frame:not(.is-loading)");
|
||||
return f && f.contentDocument.getElementById("pj-meet-pane")?.dataset.week === w;
|
||||
}, week);
|
||||
};
|
||||
await ready("2026-09-28");
|
||||
assert.ok((await page.locator(".pj-meeting-panel-host").boundingBox()).height > 500, "실제 ERP 셸에서 오른쪽은 화면 높이를 사용");
|
||||
await page.locator(".pj-side-meeting-month").first().waitFor();
|
||||
// 연도 접기·펼치기는 화면 이동 없이 월 DOM과 월별 펼침 상태를 유지한다.
|
||||
const yearToggle = page.locator('[data-goal-year="2026"] .pj-side-goal-year-toggle');
|
||||
const yearMonths = page.locator('[data-goal-year="2026"] .pj-side-meeting-months');
|
||||
await page.evaluate(() => { window.yearMonthIdentity = document.querySelector('[data-goal-year="2026"] .pj-side-meeting-months'); });
|
||||
const initialUrl = page.url();
|
||||
await yearToggle.click();
|
||||
assert.equal(await yearToggle.getAttribute("aria-expanded"), "false");
|
||||
assert.ok(await yearMonths.isHidden());
|
||||
await page.locator(".pj-side").screenshot({ path: path.join(OUT, "meeting-year-collapsed.png") });
|
||||
assert.equal(page.url(), initialUrl); assert.equal(navReads, 1); assert.equal(topReads, 1);
|
||||
assert.equal(await page.evaluate(() => localStorage.getItem("pj_goal_year_open:2026")), "0");
|
||||
await yearToggle.focus(); await page.keyboard.press("Enter");
|
||||
assert.ok(await yearMonths.isVisible());
|
||||
assert.ok(await page.evaluate(() => document.querySelector('[data-goal-year="2026"] .pj-side-meeting-months') === yearMonthIdentity && yearMonthIdentity.querySelectorAll("details")[8].open));
|
||||
// 새 화면을 열어도 저장된 접힘 상태가 적용되고, 다른 연도는 영향을 받지 않는다.
|
||||
await yearToggle.click();
|
||||
const restored = await page.context().newPage();
|
||||
await restored.goto(origin + "/project/goals/2026");
|
||||
await restored.locator(".pj-side-meeting-month").first().waitFor({ state: "attached" });
|
||||
assert.ok(await restored.locator('[data-goal-year="2026"] .pj-side-meeting-months').isHidden());
|
||||
assert.equal(await restored.locator('[data-goal-year="2027"] .pj-side-goal-year-toggle').getAttribute("aria-expanded"), "true");
|
||||
assert.equal(await restored.locator('[data-goal-year="2026"] .pj-side-goal-year').getAttribute("href"), "/project/goals/2026");
|
||||
await restored.close();
|
||||
await yearToggle.focus(); await page.keyboard.press("Space");
|
||||
assert.ok(await yearMonths.isVisible());
|
||||
await page.locator(".pj-side").screenshot({ path: path.join(OUT, "meeting-year-expanded.png") });
|
||||
// 위 검증용 새 페이지의 조회 수는 이후 주차 이동 검증의 기준에서 뺀다.
|
||||
navReads = topReads = 1;
|
||||
await page.evaluate(() => {
|
||||
window.sidebarIdentity = document.querySelector(".pj-side");
|
||||
window.monthIdentity = document.querySelectorAll(".pj-side-meeting-month")[8];
|
||||
sidebarIdentity.style.height = "300px";
|
||||
sidebarIdentity.scrollTop = 200;
|
||||
window.savedSideScroll = sidebarIdentity.scrollTop;
|
||||
});
|
||||
const clickWeek = async week => page.locator(`.pj-side-meeting-week[href$="week=${week}"]`).evaluate(e => e.click());
|
||||
await clickWeek("2026-09-21"); await ready("2026-09-21");
|
||||
assert.ok(page.url().endsWith("week=2026-09-21"));
|
||||
assert.ok(await page.evaluate(() => document.querySelector(".pj-side") === sidebarIdentity && document.querySelectorAll(".pj-side-meeting-month")[8] === monthIdentity && sidebarIdentity.scrollTop === savedSideScroll && monthIdentity.open));
|
||||
assert.equal(navReads, 1); assert.equal(topReads, 1);
|
||||
assert.equal(await currentFrame().locator(".pj-side").count(), 0);
|
||||
await page.goBack(); await ready("2026-09-28");
|
||||
await page.goForward(); await ready("2026-09-21");
|
||||
// 저장 응답이 늦으면 현재 회의록을 유지하고 완료 후에만 다음 주를 연다.
|
||||
holdSave = true;
|
||||
await currentFrame().locator("#pj-meet-notes").fill("saved before changing weeks");
|
||||
const readsBeforeSave = contentReads.length;
|
||||
await clickWeek("2026-09-28");
|
||||
await page.waitForFunction(() => document.querySelector(".pj-meeting-panel-frame:not(.is-loading)").contentWindow.document.getElementById("pj-meet-notes").value === "saved before changing weeks");
|
||||
await new Promise(r => setTimeout(r, 80));
|
||||
assert.ok(saving); assert.equal(contentReads.length, readsBeforeSave);
|
||||
holdSave = false; releaseSave(); await ready("2026-09-28");
|
||||
assert.ok(writes.some(w => w.path.endsWith("2026-09-21") && w.body.notes === "saved before changing weeks"));
|
||||
failSave = true;
|
||||
await currentFrame().locator("#pj-meet-notes").fill("keep failed draft");
|
||||
await clickWeek("2026-09-21");
|
||||
await page.locator(".pj-meeting-panel-status.is-error").waitFor();
|
||||
assert.ok(page.url().endsWith("week=2026-09-28"));
|
||||
assert.equal(await currentFrame().locator("#pj-meet-notes").inputValue(), "keep failed draft");
|
||||
failSave = false; await clickWeek("2026-09-21"); await ready("2026-09-21");
|
||||
await page.evaluate(() => { window.currentPanelIdentity = document.querySelector(".pj-meeting-panel-frame:not(.is-loading)"); });
|
||||
const reloadingFrame = currentFrame();
|
||||
await Promise.all([reloadingFrame.waitForNavigation(), reloadingFrame.evaluate(() => location.reload())]); await ready("2026-09-21");
|
||||
assert.ok(await page.evaluate(() => document.querySelector(".pj-meeting-panel-frame:not(.is-loading)") === currentPanelIdentity && currentPanelIdentity.isConnected));
|
||||
// 오른쪽 안의 달 링크도 부모 주소만 갱신하고, 왼쪽 목록은 다시 읽지 않는다.
|
||||
await currentFrame().locator('a[href="/project/goals/2026/meetings/10"]').click();
|
||||
await ready("2026-10-05"); assert.ok(page.url().includes("/meetings/10?week=2026-10-05"));
|
||||
failContent = true; await clickWeek("2026-09-21");
|
||||
await page.locator(".pj-meeting-panel-status.is-error").waitFor();
|
||||
assert.ok(page.url().includes("/meetings/10?week=2026-10-05"));
|
||||
assert.equal(await currentFrame().locator("#pj-meet-pane").getAttribute("data-week"), "2026-10-05");
|
||||
failContent = false; delayWeek = "2026-09-21";
|
||||
await clickWeek("2026-09-21"); await new Promise(r => setTimeout(r, 30)); await clickWeek("2026-10-05");
|
||||
await ready("2026-10-05"); await new Promise(r => setTimeout(r, 200));
|
||||
assert.ok(page.url().includes("/meetings/10?week=2026-10-05")); delayWeek = "";
|
||||
assert.equal(navReads, 1); assert.equal(topReads, 1);
|
||||
assert.ok(await page.evaluate(() => document.querySelector(".pj-side") === sidebarIdentity && sidebarIdentity.scrollTop === savedSideScroll));
|
||||
await page.locator(".pj-meeting-panel-host").screenshot({ path: path.join(OUT, "meeting-stable-navigation.png") });
|
||||
assert.deepEqual(errors, []);
|
||||
// 연간 목표에서 회의록으로 갔다가 뒤로 가면 원래 표와 메뉴를 다시 쓰며 새로고침하지 않는다.
|
||||
const annual = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
await annual.addInitScript(() => { window.__PJ_TEST__ = true; });
|
||||
await annual.goto(origin + "/project/goals/2026");
|
||||
await annual.locator(".pj-side-meeting-month").first().waitFor();
|
||||
assert.equal(await annual.locator(".pj-side-goal-year.is-active").count(), 1);
|
||||
await annual.evaluate(() => { window.originalTable = document.getElementById("pj-goal-table"); });
|
||||
await annual.locator('.pj-side-meeting-week[href$="week=2026-09-28"]').evaluate(e => e.click());
|
||||
await annual.waitForFunction(() => !!document.querySelector(".pj-meeting-panel-frame:not(.is-loading)"));
|
||||
liveVersion = "2";
|
||||
await annual.evaluate(() => window.__pjLivePoll());
|
||||
assert.equal(await annual.evaluate(() => window.pjLiveRefreshState().applied), "1", "회의록을 보는 동안 이전 화면 자동 갱신은 보류");
|
||||
await annual.goBack();
|
||||
await annual.waitForFunction(() => document.getElementById("pj-goal-table") === window.originalTable);
|
||||
await annual.evaluate(() => window.__pjLivePoll());
|
||||
assert.equal(await annual.evaluate(() => window.pjLiveRefreshState().applied), "2", "원래 화면으로 돌아오면 자동 갱신 재개");
|
||||
assert.equal(await annual.locator(".pj-side-goal-year.is-active").count(), 1);
|
||||
await annual.close();
|
||||
console.log("ALL PASS: year collapse/keyboard/persistence, stable left DOM/scroll/folders, right-only navigation, back/forward, delayed saves, failed-save draft, inner month links and single sidebar read");
|
||||
} finally { if (releaseSave) releaseSave(); if (browser) await browser.close(); await new Promise(r => server.close(r)); }
|
||||
})().catch(e => { console.error(e); process.exitCode = 1; });
|
||||
@@ -0,0 +1,45 @@
|
||||
// 생성된 주간 회의록 트리: 월 폴더·직접 링크·선택 기억·오류 재시도를 확인한다.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs"), path = require("node:path");
|
||||
const { JSDOM } = require("jsdom");
|
||||
const script = fs.readFileSync(path.resolve(__dirname, "../../app/static/project-goal-nav.js"), "utf8");
|
||||
const html = '<div class="pj-side-goal-branch" data-goal-year="2026"><a href="/project/goals/2026">2026년</a><div class="pj-side-meeting-months" data-current-week="2026-09-28"></div></div>' +
|
||||
'<div class="pj-side-goal-branch" data-goal-year="2027"><div class="pj-side-meeting-months"></div></div>';
|
||||
const data = { years: [{ year: 2026, months: [
|
||||
{ month: 9, weeks: [{ start: "2026-09-28", label: "4주차 (9/28~10/4)", href: "/project/goals/2026/meetings/9?week=2026-09-28" }] },
|
||||
{ month: 10, weeks: [{ start: "2026-10-05", label: "1주차 (10/5~10/11)", href: "/project/goals/2026/meetings/10?week=2026-10-05" }] },
|
||||
] }] };
|
||||
const settle = () => new Promise(r => setTimeout(r, 20));
|
||||
async function env(storage, fail) {
|
||||
const dom = new JSDOM(html, { runScripts: "outside-only", url: "http://localhost/project/" });
|
||||
const w = dom.window;
|
||||
if (w.document.readyState === "loading") await new Promise(r => w.document.addEventListener("DOMContentLoaded", r));
|
||||
if (storage) w.localStorage.setItem("pj_goal_month_open:2026:9", storage);
|
||||
let calls = 0;
|
||||
w.fetch = async (url, opts) => {
|
||||
assert.equal(url, "/project/api/goals/meeting-nav"); assert.equal(opts.credentials, "same-origin");
|
||||
calls++;
|
||||
return { ok: !(fail && calls === 1), json: async () => data };
|
||||
};
|
||||
w.eval(script); await settle();
|
||||
return { w, d: w.document, calls: () => calls, close: () => dom.window.close() };
|
||||
}
|
||||
(async () => {
|
||||
let e = await env();
|
||||
const folders = e.d.querySelectorAll("details");
|
||||
assert.equal(folders.length, 2); assert.equal(folders[0].open, true); assert.equal(folders[1].open, false);
|
||||
assert.equal(e.d.querySelector('[data-goal-year="2027"] details'), null);
|
||||
assert.equal(e.d.querySelector('a[aria-current="page"]').getAttribute("href"), data.years[0].months[0].weeks[0].href);
|
||||
assert.equal(e.d.querySelectorAll(".pj-side-meeting-folder-closed").length, 2);
|
||||
assert.equal(e.d.querySelectorAll(".pj-side-meeting-folder-open").length, 2);
|
||||
folders[0].open = false; await settle();
|
||||
assert.equal(e.w.localStorage.getItem("pj_goal_month_open:2026:9"), "0");
|
||||
assert.equal(e.calls(), 1); e.close();
|
||||
e = await env("0"); assert.equal(e.d.querySelector("details").open, false); e.close();
|
||||
e = await env("1"); assert.equal(e.d.querySelector("details").open, true); e.close();
|
||||
e = await env(null, true);
|
||||
const retry = e.d.querySelector(".pj-side-meeting-retry"); assert.ok(retry); retry.click(); retry.click();
|
||||
await settle(); assert.equal(e.calls(), 2); assert.equal(e.d.querySelector(".pj-side-meeting-retry"), null);
|
||||
assert.equal(e.d.querySelectorAll("details").length, 2); e.close();
|
||||
console.log("ALL PASS: month folders, direct week links, current week, stored collapse state, single read and retry");
|
||||
})().catch(e => { console.error(e); process.exitCode = 1; });
|
||||
@@ -18,6 +18,14 @@ const server = http.createServer(function (req, res) {
|
||||
.replace("</body>", "</div></body>");
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(html); return;
|
||||
}
|
||||
if (url.pathname === "/project/goals/2026/meetings/9") {
|
||||
const fixture = url.searchParams.has("merged") ? "meeting_merged.html" : url.searchParams.has("readonly") ? "meeting_layout_ro.html" : "meeting_layout_admin.html";
|
||||
const html = fs.readFileSync(path.join(__dirname, ".out", fixture), "utf8")
|
||||
.replace('<link rel="stylesheet"', '<link rel="stylesheet" href="/static/erp.css"><link rel="stylesheet" href="/static/erp-shell.css"><link rel="stylesheet"')
|
||||
.replace("<body>", '<body style="font-family:var(--pj-font)"><div class="erp-app">')
|
||||
.replace("</body>", "</div></body>");
|
||||
res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(html); return;
|
||||
}
|
||||
if (url.pathname.startsWith("/project/api/")) {
|
||||
res.setHeader("Content-Type", "application/json"); res.end("{}"); return;
|
||||
}
|
||||
@@ -35,6 +43,100 @@ const server = http.createServer(function (req, res) {
|
||||
try {
|
||||
await new Promise(function (resolve) { server.listen(0, "127.0.0.1", resolve); });
|
||||
browser = await chromium.launch({ headless: true, executablePath: process.env.PJ_TEST_BROWSER || undefined });
|
||||
// 열 너비는 애니메이션하고, 숫자는 최종 위치에서만 표시한다(관리자·보기 전용·75% 배율).
|
||||
for (const readonly of [false, true]) {
|
||||
const folding = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
await folding.addInitScript(() => document.addEventListener("DOMContentLoaded", () => {
|
||||
const row = document.querySelector('tr[data-row-id="10"]');
|
||||
const cell = row.querySelector('td[data-month="1"]');
|
||||
cell.colSpan = 2; cell.dataset.span = "2"; cell.classList.add("is-merged");
|
||||
cell.querySelector("div").textContent = "병합한 목표\n두 번째 줄\n세 번째 줄";
|
||||
row.querySelector('td[data-month="2"]').remove();
|
||||
}));
|
||||
await folding.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026" + (readonly ? "?readonly" : ""));
|
||||
await folding.evaluate(() => localStorage.setItem("pj_goal_col_w", JSON.stringify({ m1: 150, m2: 110, m3: 175 })));
|
||||
await folding.reload();
|
||||
await folding.evaluate(async () => { await document.fonts.ready; });
|
||||
for (const zoom of [1, 0.75]) {
|
||||
const result = await folding.evaluate(async zoom => {
|
||||
document.documentElement.style.zoom = zoom;
|
||||
const table = document.getElementById("pj-goal-table");
|
||||
const q = table.querySelector('thead th[data-col="q1"]');
|
||||
const cells = Array.from(table.querySelectorAll('.pj-goal-kpi .pj-goal-m[data-h="1"]'));
|
||||
const merged = table.querySelector('tr[data-row-id="10"] td[data-month="1"]');
|
||||
const mergedHeight = merged.parentElement.getBoundingClientRect().height;
|
||||
const mergedWidth = merged.getBoundingClientRect().width;
|
||||
function snapshot() {
|
||||
return cells.map(c => {
|
||||
const box = c.getBoundingClientRect();
|
||||
const number = c.querySelector(".pj-goal-num");
|
||||
const range = document.createRange(); range.selectNodeContents(c);
|
||||
const content = number ? number.getBoundingClientRect() : range.getBoundingClientRect();
|
||||
return [box.x, box.width, content.x, content.width];
|
||||
});
|
||||
}
|
||||
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
||||
async function frames() {
|
||||
const out = [];
|
||||
let heightStable = true;
|
||||
const started = performance.now();
|
||||
while (performance.now() - started < 420) {
|
||||
await new Promise(requestAnimationFrame);
|
||||
out.push(cells.map(c => ({ width: c.getBoundingClientRect().width,
|
||||
folding: c.classList.contains("is-folding"),
|
||||
hidden: c.querySelector(".pj-goal-num") ? getComputedStyle(c.querySelector(".pj-goal-num")).opacity === "0" : getComputedStyle(c).color === "rgba(0, 0, 0, 0)" })));
|
||||
if (merged.classList.contains("is-folding")) {
|
||||
heightStable = heightStable && Math.abs(merged.parentElement.getBoundingClientRect().height - mergedHeight) < 1;
|
||||
}
|
||||
}
|
||||
assertHeightStable = assertHeightStable && heightStable;
|
||||
return out;
|
||||
}
|
||||
let assertHeightStable = true;
|
||||
const before = snapshot();
|
||||
q.click();
|
||||
const closing = await frames();
|
||||
await delay(100);
|
||||
const hiddenAfterClose = cells.every(c => getComputedStyle(c).display === "none");
|
||||
q.click();
|
||||
const opening = await frames();
|
||||
await delay(150);
|
||||
const after = snapshot();
|
||||
// 여러 분기 동시 전환과 빠른 반전: 마지막 클릭 상태만 남는다.
|
||||
const q2 = table.querySelector('thead th[data-col="q2"]');
|
||||
q.click(); q2.click(); await delay(70); q.click(); await delay(50); q.click();
|
||||
await delay(400);
|
||||
const rapidHidden = cells.every(c => getComputedStyle(c).display === "none");
|
||||
const otherHidden = Array.from(table.querySelectorAll('.pj-goal-m[data-h="2"]')).every(c => getComputedStyle(c).display === "none");
|
||||
const savedFold = JSON.parse(localStorage.getItem("pj_goal_fold_q"))[1];
|
||||
q.click(); q2.click(); await delay(500);
|
||||
return { before, after, closing, opening, hiddenAfterClose, rapidHidden, otherHidden, savedFold,
|
||||
mergedStable: assertHeightStable && Math.abs(merged.getBoundingClientRect().width - mergedWidth) < 0.1 && merged.colSpan === 2,
|
||||
clean: !table.querySelector(".is-folding"),
|
||||
widths: ["m1", "m2", "m3"].map(key => table.querySelector('thead th[data-col="' + key + '"]').getBoundingClientRect().width / zoom) };
|
||||
}, zoom);
|
||||
assert(result.hiddenAfterClose && result.rapidHidden && result.otherHidden && result.savedFold && result.clean && result.mergedStable,
|
||||
JSON.stringify({ hiddenAfterClose: result.hiddenAfterClose, rapidHidden: result.rapidHidden, otherHidden: result.otherHidden, savedFold: result.savedFold, clean: result.clean, mergedStable: result.mergedStable }));
|
||||
for (const frames of [result.closing, result.opening]) {
|
||||
assert(frames.some(frame => frame[0].width > 1 && frame[0].width < result.before[0][1] - 1), "quarter width must visibly animate");
|
||||
frames.forEach(frame => frame.forEach(cell => assert(!cell.folding || cell.hidden, "moving numeric content must stay hidden")));
|
||||
}
|
||||
result.after.forEach((cell, i) => cell.forEach((value, j) => {
|
||||
assert(Math.abs(value - result.before[i][j]) < 0.1, "quarter numeric position changed during reveal");
|
||||
}));
|
||||
result.widths.forEach((width, i) => assert(Math.abs(width - [150, 110, 175][i]) < 1));
|
||||
}
|
||||
await folding.emulateMedia({ reducedMotion: "reduce" });
|
||||
const reduced = await folding.evaluate(() => {
|
||||
const table = document.getElementById("pj-goal-table"), q = table.querySelector('thead th[data-col="q1"]');
|
||||
const cells = Array.from(table.querySelectorAll('.pj-goal-m[data-h="1"]'));
|
||||
q.click(); const hidden = cells.every(c => getComputedStyle(c).display === "none");
|
||||
q.click(); return hidden && cells.every(c => getComputedStyle(c).display !== "none") && !table.querySelector(".is-folding");
|
||||
});
|
||||
assert(reduced, "reduced motion uses immediate toggles");
|
||||
await folding.close();
|
||||
}
|
||||
console.log("PASS animated quarter widths with stable numeric reveal, saved widths and concurrent/rapid toggles at 100%/75%");
|
||||
const page = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
const errors = [], writes = [];
|
||||
page.on("pageerror", function (e) { errors.push(e.message); });
|
||||
@@ -165,7 +267,11 @@ const server = http.createServer(function (req, res) {
|
||||
border: parseFloat(cellStyle.borderTopWidth) + parseFloat(cellStyle.borderBottomWidth),
|
||||
topDifference: short.getBoundingClientRect().top - long.getBoundingClientRect().top,
|
||||
lines: new Set(Array.from(range.getClientRects()).filter(function (r) { return r.width > 0; }).map(function (r) { return r.top; })).size,
|
||||
namesAtTop: Array.from(row.querySelectorAll("th")).every(function (th) { return getComputedStyle(th).verticalAlign === "top"; }),
|
||||
namesCentered: Array.from(row.querySelectorAll("th")).every(function (th) {
|
||||
const name = th.querySelector(".pj-goal-area-text, .pj-goal-row-text");
|
||||
const box = th.getBoundingClientRect(), text = name.getBoundingClientRect();
|
||||
return getComputedStyle(th).verticalAlign === "middle" && Math.abs((box.top + box.bottom - text.top - text.bottom) / 2) <= 1;
|
||||
}),
|
||||
oneLineRow: document.querySelector('tr[data-row-id="11"]').getBoundingClientRect().height };
|
||||
});
|
||||
}
|
||||
@@ -174,7 +280,7 @@ const server = http.createServer(function (req, res) {
|
||||
assert.equal(initial.paddingTop, initial.paddingBottom);
|
||||
assert(Math.abs(initial.row - initial.editor - initial.border) <= 1, JSON.stringify(initial));
|
||||
assert(Math.abs(initial.topDifference) <= 1, "짧은 셀도 긴 셀과 같은 위치에서 상단 정렬");
|
||||
assert(initial.namesAtTop, "구역·항목 이름도 상단 정렬");
|
||||
assert(initial.namesCentered, "구역·항목 이름은 병합된 셀도 세로 가운데 정렬");
|
||||
assert(initial.oneLineRow <= 36, "한 줄 셀은 불필요한 빈 줄 없이 내용에 맞는 높이: " + initial.oneLineRow);
|
||||
if (!readonly) {
|
||||
await heightPage.evaluate(function () {
|
||||
@@ -201,48 +307,176 @@ const server = http.createServer(function (req, res) {
|
||||
console.log("PASS content row height, symmetric padding, top alignment" + (readonly ? " (read-only)" : ", shrink and large font"));
|
||||
await heightPage.close();
|
||||
}
|
||||
const interactive = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
let releaseMove, startedMove;
|
||||
const moveGate = new Promise(function (resolve) { releaseMove = resolve; });
|
||||
const moveStarted = new Promise(function (resolve) { startedMove = resolve; });
|
||||
const moveRequests = [];
|
||||
await interactive.route("**/project/api/**", async function (route) {
|
||||
const request = route.request();
|
||||
if (request.url().endsWith("/goals/cells/move")) {
|
||||
const payload = request.postDataJSON(); moveRequests.push(payload); startedMove();
|
||||
await moveGate;
|
||||
await route.fulfill({ json: { ok: true, body: payload.body } });
|
||||
for (const readonly of [false, true]) {
|
||||
const meetingPage = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
await meetingPage.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026/meetings/9" + (readonly ? "?readonly=1" : ""));
|
||||
await meetingPage.evaluate(() => document.fonts.ready);
|
||||
async function meetingMetrics() {
|
||||
return meetingPage.evaluate(function () {
|
||||
const row = document.querySelector('tr[data-item="2"]');
|
||||
const long = row.querySelector(".pj-meet-c-text:not(.is-prev) > *"), short = row.querySelector(".pj-meet-c-text.is-prev > *");
|
||||
const cell = long.closest("td"), style = getComputedStyle(long), cs = getComputedStyle(cell);
|
||||
const zoom = document.documentElement.classList.contains("pj-ui-scale") ? 0.75 : 1;
|
||||
const labels = Array.from(document.querySelectorAll(".pj-meet-market")).map(function (badge) {
|
||||
const name = badge.previousElementSibling, br = badge.getBoundingClientRect(), nr = name.getBoundingClientRect();
|
||||
return { text: badge.textContent, rightOfName: br.left >= nr.right,
|
||||
sameLine: br.top < nr.bottom && nr.top < br.bottom,
|
||||
fits: br.right <= badge.closest("th").getBoundingClientRect().right };
|
||||
});
|
||||
return { row: row.getBoundingClientRect().height / zoom, long: long.getBoundingClientRect().height / zoom,
|
||||
short: short.getBoundingClientRect().height / zoom, line: parseFloat(style.lineHeight),
|
||||
top: parseFloat(style.paddingTop), bottom: parseFloat(style.paddingBottom),
|
||||
border: parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth),
|
||||
topDifference: (short.getBoundingClientRect().top - long.getBoundingClientRect().top) / zoom,
|
||||
oneLine: document.querySelector('tr[data-item="4"]').getBoundingClientRect().height / zoom,
|
||||
noSlot: !document.querySelector(".pj-meet-week-slot"),
|
||||
cellsAtTop: Array.from(row.querySelectorAll("td")).every(c => getComputedStyle(c).verticalAlign === "top"),
|
||||
namesCentered: Array.from(document.querySelectorAll(".pj-meet-sec th")).every(th => {
|
||||
const box = th.getBoundingClientRect(), line = th.querySelector(".pj-meet-label-line");
|
||||
let text;
|
||||
if (line) text = line.getBoundingClientRect();
|
||||
else {
|
||||
const node = th.firstChild, start = node.textContent.search(/\S/);
|
||||
const range = document.createRange();
|
||||
range.setStart(node, start); range.setEnd(node, start + node.textContent.trim().length);
|
||||
text = range.getBoundingClientRect();
|
||||
}
|
||||
return getComputedStyle(th).verticalAlign === "middle" && Math.abs((box.top + box.bottom - text.top - text.bottom) / 2) / zoom <= 2;
|
||||
}),
|
||||
labels, clipped: long.scrollHeight > long.clientHeight };
|
||||
});
|
||||
}
|
||||
function checkMeeting(m, lines) {
|
||||
assert.equal(m.top, m.bottom, JSON.stringify(m));
|
||||
assert(Math.abs(m.long - (m.line * lines + m.top + m.bottom)) <= 1, JSON.stringify(m));
|
||||
assert(Math.abs(m.row - m.long - m.border) <= 1, JSON.stringify(m));
|
||||
assert(Math.abs(m.topDifference) <= 1 && m.cellsAtTop && !m.clipped, JSON.stringify(m));
|
||||
assert(m.namesCentered, "meeting section and item names must stay vertically centered");
|
||||
assert(m.oneLine <= m.line + m.top + m.bottom + m.border + 1 && m.noSlot, JSON.stringify(m));
|
||||
assert.deepEqual(m.labels, [], "shop link badges (자동입력·실적 미사용) were removed 2026-10-06");
|
||||
}
|
||||
const initial = await meetingMetrics();
|
||||
checkMeeting(initial, 3);
|
||||
assert(Math.abs(initial.short - initial.line * 2 - initial.top - initial.bottom) <= 1, JSON.stringify(initial));
|
||||
if (!readonly) {
|
||||
await meetingPage.locator('tr[data-item="2"] .pj-meet-text').fill("한 줄");
|
||||
await meetingPage.locator('tr[data-item="2"] .is-prev .pj-meet-ro').evaluate(e => { e.textContent = "한 줄"; });
|
||||
const smaller = await meetingMetrics();
|
||||
checkMeeting(smaller, 1);
|
||||
assert(smaller.row < initial.row);
|
||||
await meetingPage.locator('tr[data-item="2"] .pj-meet-text').fill("첫 번째 줄\n두 번째 줄\n세 번째 줄");
|
||||
}
|
||||
await meetingPage.evaluate(function () {
|
||||
document.documentElement.classList.add("pj-ui-scale");
|
||||
window.dispatchEvent(new Event("resize"));
|
||||
});
|
||||
checkMeeting(await meetingMetrics(), 3);
|
||||
await meetingPage.locator("#pj-meet-order").click();
|
||||
checkMeeting(await meetingMetrics(), 3);
|
||||
await meetingPage.locator("#pj-meet-table").screenshot({ path: path.join(__dirname, ".out", readonly ? "meeting-layout-ro.png" : "meeting-layout-admin.png") });
|
||||
await meetingPage.close();
|
||||
console.log("PASS meeting row height, equal padding, top alignment, inline automatic/unused labels, shrink and 75% zoom" + (readonly ? " (read-only)" : ""));
|
||||
}
|
||||
|
||||
const meetingEditing = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
let releaseMeetingMove, meetingMoveStarted;
|
||||
const meetingMoveGate = new Promise(resolve => { releaseMeetingMove = resolve; });
|
||||
const meetingMoveStart = new Promise(resolve => { meetingMoveStarted = resolve; });
|
||||
const meetingWrites = [], meetingErrors = [];
|
||||
meetingEditing.on("pageerror", e => meetingErrors.push(e.message));
|
||||
await meetingEditing.route("**/project/api/**", async function (route) {
|
||||
const req = route.request();
|
||||
if (req.method() !== "GET") meetingWrites.push({ url: req.url(), body: req.postDataJSON() });
|
||||
if (req.url().endsWith("/meeting-cells/move")) {
|
||||
meetingMoveStarted(); await meetingMoveGate;
|
||||
await route.fulfill({ json: { ok: true, body: req.postDataJSON().source_body } });
|
||||
} else await route.fulfill({ json: { ok: true } });
|
||||
});
|
||||
await meetingEditing.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026/meetings/9");
|
||||
const meetingSource = meetingEditing.locator('tr[data-item="2"] .pj-meet-text');
|
||||
const meetingTarget = meetingEditing.locator('tr[data-item="3"] .pj-meet-text');
|
||||
await meetingSource.fill("앞 선택 뒤");
|
||||
await meetingSource.evaluate(function (e) {
|
||||
const r = document.createRange(); r.setStart(e.firstChild, 2); r.setEnd(e.firstChild, 4);
|
||||
window.getSelection().removeAllRanges(); window.getSelection().addRange(r);
|
||||
e.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
|
||||
});
|
||||
for (const name of ["굵게", "기울임", "밑줄", "글자 크기 2px 키우기"]) await meetingEditing.getByRole("button", { name: name, exact: true }).click();
|
||||
await meetingEditing.getByRole("button", { name: "글자 색상", exact: true }).click();
|
||||
await meetingEditing.getByRole("button", { name: "#DC2626", exact: true }).click();
|
||||
const meetingRich = await meetingSource.evaluate(e => e.value);
|
||||
const selectedRun = JSON.parse(meetingRich.slice(11))[1];
|
||||
assert(selectedRun.bold && selectedRun.italic && selectedRun.underline && selectedRun.color === "#dc2626" && selectedRun.size === 16);
|
||||
await meetingSource.click();
|
||||
const meetingEdge = await meetingSource.locator("..").locator('.pj-goal-move-edge[data-edge="bottom"]').boundingBox();
|
||||
const meetingDest = await meetingTarget.locator("..").boundingBox();
|
||||
await meetingEditing.mouse.move(meetingEdge.x + meetingEdge.width / 2, meetingEdge.y + meetingEdge.height / 2);
|
||||
await meetingEditing.mouse.down();
|
||||
await meetingEditing.mouse.move(meetingDest.x + meetingDest.width / 2, meetingDest.y + meetingDest.height / 2, { steps: 5 });
|
||||
assert(await meetingTarget.locator("..").evaluate(td => td.classList.contains("is-goal-move-target")));
|
||||
await meetingEditing.mouse.up();
|
||||
await Promise.race([meetingMoveStart, new Promise((resolve, reject) => setTimeout(() => reject(new Error("meeting move request did not start")), 3000))]);
|
||||
assert.equal(await meetingSource.evaluate(e => e.value), meetingRich);
|
||||
releaseMeetingMove();
|
||||
await meetingEditing.waitForFunction(() => document.querySelector('tr[data-item="2"] .pj-meet-text').value === "");
|
||||
assert.equal(await meetingTarget.evaluate(e => e.value), meetingRich);
|
||||
assert(meetingWrites.findIndex(r => r.url.endsWith("/meeting-items/2")) < meetingWrites.findIndex(r => r.url.endsWith("/meeting-cells/move")));
|
||||
await meetingTarget.evaluate(e => { e.value = "명시적 줄바꿈\n너비 자동 맞춤은 이 문단 전체에 맞춥니다"; e.dispatchEvent(new Event("input", { bubbles: true })); });
|
||||
await meetingTarget.locator("..").locator(".pj-meet-colresize").dblclick();
|
||||
const fittedMeeting = await meetingEditing.locator('col[data-meet-col="content"]').evaluate(c => parseFloat(c.style.width));
|
||||
assert(fittedMeeting > 200);
|
||||
await meetingEditing.locator("#pj-meet-order").click();
|
||||
await meetingEditing.waitForFunction(() => document.getElementById("pj-meet-table").classList.contains("is-prev-first"));
|
||||
assert.equal(await meetingTarget.locator("..").getAttribute("data-meet-cols"), "content");
|
||||
await meetingEditing.evaluate(() => { document.documentElement.classList.add("pj-ui-scale"); window.dispatchEvent(new Event("resize")); });
|
||||
await meetingTarget.locator("..").locator(".pj-meet-colresize").dblclick();
|
||||
const zoomedMeeting = await meetingEditing.locator('col[data-meet-col="content"]').evaluate(c => parseFloat(c.style.width));
|
||||
assert(Math.abs(fittedMeeting - zoomedMeeting) <= 1, JSON.stringify({ fittedMeeting, zoomedMeeting }));
|
||||
await meetingTarget.click({ button: "right" });
|
||||
await meetingEditing.getByRole("menuitem", { name: "전체 열 너비 자동 맞춤" }).click();
|
||||
assert(await meetingEditing.evaluate(() => Object.keys(JSON.parse(localStorage.getItem("pj_meet_col_w"))).length === 8));
|
||||
assert.deepEqual(meetingErrors, []);
|
||||
await meetingEditing.locator("#pj-meet-table").screenshot({ path: path.join(__dirname, ".out", "meeting-cell-editing.png") });
|
||||
await meetingEditing.close();
|
||||
console.log("PASS actual meeting formatting, border move, draft save ordering, width fitting, review order and 75% zoom");
|
||||
|
||||
const mergedMeeting = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
const mergedErrors = []; mergedMeeting.on("pageerror", e => mergedErrors.push(e.message));
|
||||
await mergedMeeting.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026/meetings/9?merged");
|
||||
const mergedCell = mergedMeeting.locator('td[data-meet-item="2"]');
|
||||
assert.equal(await mergedCell.getAttribute("rowspan"), "2");
|
||||
assert.equal(await mergedMeeting.locator('td[data-meet-item="3"]').count(), 0);
|
||||
for (const order of [false, true]) {
|
||||
if (order) await mergedMeeting.locator("#pj-meet-order").click();
|
||||
await mergedMeeting.waitForFunction(() => document.querySelector('tr[data-item="3"] td.pj-meet-c-amt').dataset.meetCols === "target");
|
||||
const geometry = await mergedMeeting.evaluate(() => {
|
||||
const rect = el => el.getBoundingClientRect();
|
||||
const a = rect(document.querySelector('td[data-meet-item="2"]'));
|
||||
const b = rect(document.querySelector('tr[data-item="3"] td.pj-meet-c-amt'));
|
||||
const t = rect(document.querySelector('tr[data-item="2"] td.pj-meet-c-amt'));
|
||||
return { sameColumn: Math.abs(b.left - t.left) < 1, sameBottom: Math.abs(a.bottom - b.bottom) < 1, disjoint: a.right <= b.left + 1 };
|
||||
});
|
||||
assert(geometry.sameColumn && geometry.sameBottom && geometry.disjoint, JSON.stringify(geometry));
|
||||
await mergedCell.locator(".pj-meet-colresize").dblclick();
|
||||
}
|
||||
assert.deepEqual(mergedErrors, []); await mergedMeeting.close();
|
||||
console.log("PASS merged meeting rowspan, independent numeric cells and both column orders");
|
||||
|
||||
const interactive = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
await interactive.route("**/project/api/**", function (route) { return route.fulfill({ json: { ok: true } }); });
|
||||
await interactive.addInitScript(function () {
|
||||
localStorage.setItem("pj_goal_col_w", JSON.stringify({ y: 240, m1: 240, m2: 240 }));
|
||||
});
|
||||
await interactive.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026");
|
||||
const sourceCell = interactive.locator('tr[data-row-id="10"] td[data-month="1"]');
|
||||
const targetCell = interactive.locator('tr[data-row-id="11"] td[data-month="2"]');
|
||||
await sourceCell.locator(".pj-goal-text").evaluate(function (editor) {
|
||||
// 연간 목표 셀 끌어서 이동은 2026-10-07 요청으로 없앴다 — 이동 테두리가 없어야 한다
|
||||
await sourceCell.locator(".pj-goal-text").click();
|
||||
assert.equal(await interactive.locator("#pj-goal-table .pj-goal-move-edge").count(), 0);
|
||||
await targetCell.locator(".pj-goal-text").evaluate(function (editor) {
|
||||
editor.value = "pj-rich:v1:" + JSON.stringify([{ text: "드래그 이동", bold: true, italic: true, underline: true, size: 24, color: "#ff0000" }]);
|
||||
});
|
||||
await sourceCell.locator(".pj-goal-text").click();
|
||||
const edge = await sourceCell.locator('.pj-goal-move-edge[data-edge="bottom"]').boundingBox();
|
||||
const dest = await targetCell.boundingBox();
|
||||
await interactive.mouse.move(edge.x + edge.width / 2, edge.y + edge.height / 2);
|
||||
await interactive.mouse.down();
|
||||
await interactive.mouse.move(dest.x + dest.width / 2, dest.y + dest.height / 2, { steps: 6 });
|
||||
assert(await targetCell.evaluate(function (td) { return td.classList.contains("is-goal-move-target"); }));
|
||||
await interactive.mouse.up(); await moveStarted;
|
||||
assert.equal(moveRequests.length, 1);
|
||||
assert.equal(await sourceCell.locator(".pj-goal-text").textContent(), "드래그 이동");
|
||||
assert.equal(await targetCell.locator(".pj-goal-text").textContent(), "");
|
||||
releaseMove();
|
||||
await interactive.waitForFunction(function () {
|
||||
return document.querySelector('tr[data-row-id="10"] .pj-goal-text[data-month="1"]').textContent === "";
|
||||
});
|
||||
const moved = await targetCell.locator(".pj-goal-text").evaluate(function (editor) { return JSON.parse(editor.value.slice(11))[0]; });
|
||||
assert.equal(moved.text, "드래그 이동"); assert.equal(moved.color, "#ff0000"); assert.equal(moved.size, 24);
|
||||
assert(moved.bold && moved.italic && moved.underline);
|
||||
assert.deepEqual(await targetCell.evaluate(function (td) { return [td.colSpan, td.rowSpan]; }), [1, 1]);
|
||||
console.log("PASS actual mouse border drag, delayed atomic response, all text formats, unchanged cell geometry");
|
||||
console.log("PASS goal cells have no drag-move borders");
|
||||
|
||||
await targetCell.click({ button: "right" });
|
||||
await interactive.getByRole("menuitem", { name: "현재 열 너비 자동 맞춤" }).click();
|
||||
@@ -265,6 +499,98 @@ const server = http.createServer(function (req, res) {
|
||||
assert(all.folded && all.width > 200 && all.saved === all.width, JSON.stringify(all));
|
||||
console.log("PASS context menu single/all column fitting including collapsed columns");
|
||||
await interactive.close();
|
||||
for (const meeting of [false, true]) {
|
||||
const typing = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
const typingErrors = []; typing.on("pageerror", e => typingErrors.push(e.message));
|
||||
const url = "/project/goals/2026" + (meeting ? "/meetings/9" : "");
|
||||
await typing.goto("http://127.0.0.1:" + server.address().port + url);
|
||||
const editor = typing.locator(meeting ? 'tr[data-item="2"] .pj-meet-text' : '.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
const width = () => editor.locator("..").evaluate(td => td.getBoundingClientRect().width);
|
||||
const originalWidth = await width();
|
||||
const paragraph = "입력한 문단이 길어지면 이 셀의 열 너비가 자동으로 늘어납니다 ".repeat(4);
|
||||
await editor.fill(paragraph);
|
||||
await typing.waitForFunction(([selector, before]) => document.querySelector(selector).parentElement.getBoundingClientRect().width > before + 100,
|
||||
[meeting ? 'tr[data-item="2"] .pj-meet-text' : '.pj-goal-text[data-row="10"][data-month="1"]', originalWidth]);
|
||||
assert((await width()) > 600, "typing may grow past the manual drag limit");
|
||||
assert.equal(await editor.evaluate(e => e.value), paragraph);
|
||||
const grown = await width();
|
||||
await editor.fill("첫 줄"); await typing.waitForTimeout(40);
|
||||
assert.equal(await width(), grown, "deleting text does not shrink the user's column");
|
||||
await editor.press("End");
|
||||
const before = await editor.evaluate(e => ({ height: e.getBoundingClientRect().height, line: parseFloat(getComputedStyle(e).lineHeight) }));
|
||||
await editor.press("Enter");
|
||||
const after = await editor.evaluate(e => ({ height: e.getBoundingClientRect().height, value: e.value, caret: window.getSelection().isCollapsed }));
|
||||
assert.equal(after.value, "첫 줄\n");
|
||||
assert(after.height >= before.height + before.line - 1, JSON.stringify({ before, after }));
|
||||
assert(after.caret);
|
||||
await editor.press("End"); await editor.press("Backspace");
|
||||
assert.equal(await editor.evaluate(e => e.value), "첫 줄", "one Backspace removes the final newline after End");
|
||||
await editor.press("Enter");
|
||||
await typing.keyboard.insertText("둘째 줄");
|
||||
assert.equal(await editor.evaluate(e => e.value), "첫 줄\n둘째 줄");
|
||||
await editor.press("Enter"); await editor.press("Enter"); await typing.keyboard.insertText("넷째 줄");
|
||||
assert.equal(await editor.evaluate(e => e.value), "첫 줄\n둘째 줄\n\n넷째 줄");
|
||||
await editor.evaluate(e => {
|
||||
const event = new InputEvent("beforeinput", { inputType: "insertParagraph", bubbles: true, cancelable: true }); e.dispatchEvent(event);
|
||||
});
|
||||
assert.equal(await editor.evaluate(e => e.value), "첫 줄\n둘째 줄\n\n넷째 줄\n");
|
||||
await typing.keyboard.insertText("모바일 개행");
|
||||
await editor.evaluate(e => e.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", isComposing: true, bubbles: true, cancelable: true })));
|
||||
assert((await editor.evaluate(e => e.value)).endsWith("모바일 개행"), "IME confirmation does not insert an extra newline");
|
||||
await typing.evaluate(() => document.documentElement.classList.add("pj-ui-scale"));
|
||||
const zoomedWidth = await width();
|
||||
await editor.fill(paragraph.repeat(2)); await typing.waitForTimeout(60);
|
||||
assert((await width()) > zoomedWidth * 1.5, "live growth uses logical widths at 75% zoom");
|
||||
assert.equal(await editor.evaluate(e => e.value), paragraph.repeat(2));
|
||||
await editor.evaluate(e => { e.value = "pj-rich:v1:" + JSON.stringify([{ text: "큰 글씨", size: 32, bold: true }]); });
|
||||
await editor.press("End");
|
||||
const bigBefore = await editor.evaluate(e => e.getBoundingClientRect().height);
|
||||
await editor.press("Enter");
|
||||
const bigAfter = await editor.evaluate(e => ({ height: e.getBoundingClientRect().height, text: window.PJGoalText.readRuns(e).map(r => r.text).join("") }));
|
||||
assert.equal(bigAfter.text, "큰 글씨\n");
|
||||
assert(bigAfter.height > bigBefore + 20, "large styled Enter shows an unclipped new line at 75% zoom " + JSON.stringify({ bigBefore, bigAfter }));
|
||||
await typing.keyboard.insertText("다음 줄");
|
||||
assert.equal(await editor.evaluate(e => window.PJGoalText.readRuns(e).map(r => r.text).join("")), "큰 글씨\n다음 줄");
|
||||
await editor.evaluate(e => {
|
||||
const walker = document.createTreeWalker(e, NodeFilter.SHOW_TEXT); let text;
|
||||
while ((text = walker.nextNode())) {
|
||||
if (text.textContent.includes("다음 줄")) {
|
||||
const r = document.createRange(); r.setStart(text, 0); r.setEnd(text, 2);
|
||||
const s = window.getSelection(); s.removeAllRanges(); s.addRange(r); break;
|
||||
}
|
||||
}
|
||||
e.dispatchEvent(new MouseEvent("mouseup", { bubbles: true }));
|
||||
});
|
||||
await typing.getByRole("button", { name: "기울임", exact: true }).click();
|
||||
const multilineRuns = await editor.evaluate(e => window.PJGoalText.readRuns(e));
|
||||
assert.equal(multilineRuns.map(r => r.text).join(""), "큰 글씨\n다음 줄");
|
||||
assert(multilineRuns.some(r => r.text === "다음" && r.italic), "formatting respects newlines when calculating selection offsets");
|
||||
assert(!multilineRuns[0].italic, "the first paragraph is not formatted by selecting the second");
|
||||
const numeric = typing.locator(meeting ? 'tr[data-item="2"] .pj-meet-amount[data-field="target_amount"]' : 'input.pj-goal-num[data-month="2"]').first();
|
||||
const beforeNumber = await numeric.locator("..").evaluate(td => td.getBoundingClientRect().width);
|
||||
await numeric.fill("123,456,789,012,345,678,901,234,567,890");
|
||||
await typing.waitForTimeout(60);
|
||||
assert(await numeric.locator("..").evaluate((td, old) => td.getBoundingClientRect().width > old, beforeNumber), "numeric cells grow while editing");
|
||||
const name = typing.locator(meeting ? 'tr[data-item="2"] .pj-meet-label' : 'tr[data-row-id="10"] .pj-goal-row-text');
|
||||
await name.click();
|
||||
const beforeName = await name.locator("..").evaluate(td => td.getBoundingClientRect().width);
|
||||
await name.fill("항목 이름도 입력 길이에 맞게 자동으로 넓어집니다"); await typing.waitForTimeout(60);
|
||||
assert(await name.locator("..").evaluate((td, old) => td.getBoundingClientRect().width > old, beforeName));
|
||||
assert.deepEqual(typingErrors, []);
|
||||
await typing.close();
|
||||
console.log("PASS " + (meeting ? "meeting" : "goals") + " live text/numeric/name growth, single Enter blank line, repeated Enter, mobile input and IME");
|
||||
}
|
||||
const mergedTyping = await browser.newPage({ viewport: { width: 1600, height: 1000 } });
|
||||
await mergedTyping.goto("http://127.0.0.1:" + server.address().port + "/project/goals/2026/meetings/9?merged");
|
||||
const mergedEditor = mergedTyping.locator('td[data-meet-item="2"] .pj-meet-text');
|
||||
const otherWidth = await mergedTyping.locator('col[data-meet-col="target"]').evaluate(c => c.style.width);
|
||||
await mergedEditor.fill("세로 병합한 칸의 내용도 길이에 따라 열 너비를 늘립니다 ".repeat(5));
|
||||
await mergedTyping.waitForTimeout(60);
|
||||
assert((await mergedEditor.locator("..").boundingBox()).width > 600);
|
||||
assert.equal(await mergedEditor.locator("..").getAttribute("rowspan"), "2");
|
||||
assert.equal(await mergedTyping.locator('col[data-meet-col="target"]').evaluate(c => c.style.width), otherWidth);
|
||||
await mergedTyping.close();
|
||||
console.log("PASS merged meeting live growth preserves rowspan and independent amount widths");
|
||||
console.log("ALL PASS");
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
|
||||
+284
-103
@@ -15,7 +15,7 @@ const ROOT = path.join(__dirname, "..", "..");
|
||||
const OUT = path.join(__dirname, ".out");
|
||||
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
|
||||
const PAGE = {};
|
||||
["goals_admin", "goals_ro", "meeting_admin", "meeting_err", "meeting_ro"].forEach(function (n) {
|
||||
["goals_admin", "goals_ro", "goals_weekly_admin", "meeting_admin", "meeting_err", "meeting_ro", "meeting_member"].forEach(function (n) {
|
||||
PAGE[n] = fs.readFileSync(path.join(OUT, n + ".html"), "utf8");
|
||||
});
|
||||
const GOALS_URL = "http://localhost/project/goals/2026";
|
||||
@@ -89,6 +89,7 @@ function makeEnv(html, url, opts) {
|
||||
async function boot(env) {
|
||||
if (env.d.readyState === "loading") await new Promise(function (r) { env.d.addEventListener("DOMContentLoaded", r); });
|
||||
env.w.eval(fs.readFileSync(path.join(ROOT, "app", "static", "project-goal-text.js"), "utf8"));
|
||||
env.w.eval(fs.readFileSync(path.join(ROOT, "app", "static", "project-meeting-cells.js"), "utf8"));
|
||||
env.w.eval(JS);
|
||||
env.d.dispatchEvent(new env.w.Event("DOMContentLoaded"));
|
||||
await settle();
|
||||
@@ -219,7 +220,12 @@ function meetServer(env, st) {
|
||||
const id = Number(u.match(/meeting-items\/(\d+)/)[1]);
|
||||
if (st.itemHook) { const r = await st.itemHook(id, body, call); if (r) return r; }
|
||||
const it = st.items[id] = Object.assign(st.items[id] || { id: id }, {});
|
||||
Object.keys(body).forEach(function (k) { it[k] = /amount$/.test(k) ? amount(body[k]) : body[k]; });
|
||||
// 정량 목표·결과 — 숫자면 원 정수, 아니면(예: 20개) 글 칸(021 target_text·result_text) — 서버와 같게
|
||||
Object.keys(body).forEach(function (k) {
|
||||
if (!/amount$/.test(k)) { it[k] = body[k]; return; }
|
||||
const n = amount(body[k]), tk = k.replace("_amount", "_text");
|
||||
if (n != null && isNaN(n)) { it[k] = null; it[tk] = String(body[k]).trim(); } else { it[k] = n; it[tk] = ""; }
|
||||
});
|
||||
return { body: { ok: true, item: Object.assign({ target_amount: null, result_amount: null }, it) } };
|
||||
});
|
||||
env.route("PUT", /\/project\/api\/goals\/meetings\/2026-09-28$/, async function (u, body, call) {
|
||||
@@ -252,7 +258,7 @@ function meetServer(env, st) {
|
||||
const gate = deferred();
|
||||
const st = meetServer(env, { itemHook: async function (id, body, call) { if (body.content === "draft A") await gate.promise; } });
|
||||
await boot(env);
|
||||
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
const ta = env.d.querySelector('tr[data-item="1"] .pj-meet-text');
|
||||
ta.focus(); type(env, ta, "draft A"); ta.blur();
|
||||
await settle();
|
||||
ta.focus(); type(env, ta, "draft B");
|
||||
@@ -274,7 +280,7 @@ function meetServer(env, st) {
|
||||
const gates = [];
|
||||
const st = meetServer(env, { itemHook: async function () { const g = deferred(); gates.push(g); await g.promise; } });
|
||||
await boot(env);
|
||||
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
const ta = env.d.querySelector('tr[data-item="1"] .pj-meet-text');
|
||||
ta.focus(); type(env, ta, "x1"); ta.blur(); fire(env, ta, "blur"); fire(env, ta, "blur");
|
||||
ta.focus(); type(env, ta, "x12"); type(env, ta, "x123"); ta.blur();
|
||||
await settle();
|
||||
@@ -292,7 +298,7 @@ function meetServer(env, st) {
|
||||
let fail = true;
|
||||
const st = meetServer(env, { itemHook: function () { if (fail) return { status: 503, body: { detail: "temporary" } }; } });
|
||||
await boot(env);
|
||||
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
const ta = env.d.querySelector('tr[data-item="1"] .pj-meet-text');
|
||||
ta.focus(); type(env, ta, "important"); ta.blur();
|
||||
await settle();
|
||||
check("[1c] 실패해도 글 그대로", ta.value === "important");
|
||||
@@ -311,7 +317,7 @@ function meetServer(env, st) {
|
||||
const env2 = makeEnv(PAGE.meeting_admin, MEET_URL, { storage: { "pj_draft:meet:item:1:content": JSON.stringify(draft) } });
|
||||
const st2 = meetServer(env2);
|
||||
await boot(env2);
|
||||
const ta2 = env2.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
const ta2 = env2.d.querySelector('tr[data-item="1"] .pj-meet-text');
|
||||
check("[1c] 다시 열면 초안 되살림", ta2.value === "important");
|
||||
await wait(900); await settle();
|
||||
check("[1c] 되살린 초안 자동 저장", st2.items[1] && st2.items[1].content === "important", st2.items[1]);
|
||||
@@ -321,7 +327,7 @@ function meetServer(env, st) {
|
||||
const env3 = makeEnv(PAGE.meeting_admin, MEET_URL, { storage: { "pj_draft:meet:item:1:content": stale } });
|
||||
meetServer(env3);
|
||||
await boot(env3);
|
||||
check("[1c] 서버 값이 바뀐 칸은 초안을 덮어쓰지 않음", env3.d.querySelector('tr[data-item="1"] textarea.pj-meet-text').value === "original");
|
||||
check("[1c] 서버 값이 바뀐 칸은 초안을 덮어쓰지 않음", env3.d.querySelector('tr[data-item="1"] .pj-meet-text').value === "original");
|
||||
fail = false; void st;
|
||||
});
|
||||
// 진행 중 저장이 있으면 줄 작업(위로)은 그 저장이 끝난 뒤에, 저장 실패면 줄 작업을 하지 않는다
|
||||
@@ -331,7 +337,7 @@ function meetServer(env, st) {
|
||||
let fail = false;
|
||||
meetServer(env, { itemHook: async function (id, body) { if ("content" in body) { await gate.promise; if (fail) return { status: 503, body: { detail: "x" } }; } } });
|
||||
await boot(env);
|
||||
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
const ta = env.d.querySelector('tr[data-item="1"] .pj-meet-text');
|
||||
ta.focus(); type(env, ta, "pending text"); ta.blur();
|
||||
await settle();
|
||||
fail = true;
|
||||
@@ -400,23 +406,164 @@ function meetServer(env, st) {
|
||||
check("[2c] 지난주 결과 늦은 응답이 75 초안 유지", rin.value === "75", rin.value);
|
||||
tin.blur(); rin.blur(); await settle(); await wait(10); await settle();
|
||||
check("[2c] 최종 서버 정량 목표 300 · 지난주 결과(7일 전 주 줄 902) 75", st.items[1].target_amount === 300 && st.items[902].result_amount === 75, st.items);
|
||||
check("[2c] 지난주 달성률 = 75/200", env.d.querySelector('tr[data-item="2"] [data-rate]').textContent.trim() === "37.5%",
|
||||
env.d.querySelector('tr[data-item="2"] [data-rate]').textContent);
|
||||
check("[2c] 달성률·평가 열 없음(2026-10-06)", !env.d.querySelector("[data-rate], select.pj-meet-eval"));
|
||||
});
|
||||
await section(async function () { // 금주 목표 저장 — 새로고침하지 않고 숫자 칸만 다시(다른 칸의 미저장 글 보존)
|
||||
await section(async function () { // 지난주 결과 글(020) — 지난 주차 줄(data-prev)에 저장, 새로고침 없음
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
const st = meetServer(env, { itemHook: function (id, body) { if ("content" in body) return { status: 503, body: { detail: "x" } }; } });
|
||||
const st = meetServer(env);
|
||||
await boot(env);
|
||||
const gets0 = st.gets || 0;
|
||||
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
ta.focus(); type(env, ta, "unsaved note");
|
||||
const tgt = env.d.getElementById("pj-meet-target");
|
||||
tgt.focus(); tgt.value = "2,000"; tgt.blur();
|
||||
const note = env.d.querySelector('tr[data-item="2"] .pj-meet-rnote');
|
||||
check("[2d] 결과 글 칸 = 지난 주차 값", !!note && note.value === "샘플 결과", note && note.value);
|
||||
note.focus(); type(env, note, "결과 메모"); note.blur();
|
||||
await settle(); await wait(10); await settle();
|
||||
check("[2d] 금주 목표 저장 = 서버 확정값", st.head.week_target === 2000 && tgt.value === "2,000", st.head);
|
||||
check("[2d] 결과 글 → 지난 주차 줄(902)에 저장", st.items[902] && st.items[902].result_note === "결과 메모", st.items);
|
||||
check("[2d] 페이지 새로고침 없음", env.navigations === 0);
|
||||
check("[2d] 숫자 칸만 다시 받음(GET 1회 더)", (st.gets || 0) === gets0 + 1, st.gets);
|
||||
check("[2d] 다른 칸 미저장 글 유지", ta.value === "unsaved note");
|
||||
// 정량 목표·결과에 글(021) — "20개" 는 글 그대로, 숫자는 쉼표 표기
|
||||
const tin = env.d.querySelector('tr[data-item="2"] input[data-field="target_amount"]');
|
||||
tin.focus(); tin.value = "20개"; tin.blur();
|
||||
await settle(); await wait(10); await settle();
|
||||
check("[2d] 정량 목표 글 저장·표시(20개)", st.items[2].target_text === "20개" && tin.value === "20개", [st.items[2], tin.value]);
|
||||
const rin = env.d.querySelector('tr[data-item="2"] input[data-field="result_amount"]');
|
||||
rin.focus(); rin.value = "1200"; rin.blur();
|
||||
await settle(); await wait(10); await settle();
|
||||
check("[2d] 결과 숫자는 쉼표 표기(1,200)", st.items[902].result_amount === 1200 && rin.value === "1,200", rin.value);
|
||||
check("[2d] 금주 목표 입력칸 없음 · 숫자 4개는 월 계획 머리 줄에", !env.d.getElementById("pj-meet-target") &&
|
||||
env.d.querySelectorAll(".pj-meet-plan-head .pj-meet-kpiline .pj-meet-kpi").length === 4 && !env.d.querySelector(".pj-meet-top"));
|
||||
});
|
||||
|
||||
// ════════════════════ [2e] 주차별 매출 목표(020) — 매출 목표 칸 → 입력 창(body): 월 전체 목표 직접 입력 + 주차별 + 차이 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_weekly_admin, GOALS_URL);
|
||||
const st = goalsServer(env);
|
||||
let sent = null;
|
||||
env.route("PUT", /\/project\/api\/goals\/2026\/week-targets\/1$/, function (u, body) {
|
||||
sent = body;
|
||||
const weeks = {};
|
||||
Object.keys(body.weeks).forEach(function (k) { weeks[k] = body.weeks[k]; });
|
||||
return { body: { ok: true, value: Number(body.month), label: body.month, week_total: 600, weeks: weeks } };
|
||||
});
|
||||
await boot(env);
|
||||
const inp = env.d.querySelector('input.pj-goal-num[data-metric="sales"][data-kind="target"][data-month="1"]');
|
||||
check("[2e] 매출 목표 칸은 직접 입력 아님(readonly)", inp.readOnly && inp.dataset.weekly === "1");
|
||||
const before = inp.value;
|
||||
inp.click();
|
||||
const pop = env.d.body.querySelector(".pj-goal-wkpop");
|
||||
const month = pop && pop.querySelector("input[data-month-total]");
|
||||
const ins = pop ? Array.from(pop.querySelectorAll("input[data-start]")) : [];
|
||||
check("[2e] 창은 body 에, 월 전체 목표 칸 + 1월 주차 수만큼 입력칸", !!pop && pop.parentElement === env.d.body && !!month && ins.length === 5, ins.length);
|
||||
check("[2e] 월 전체 목표 칸 = 지금 월 목표", month && month.value === before, { month: month && month.value, before: before });
|
||||
check("[2e] 주차 날 수 표시(1월 1주차 1/1~1/4 = 4일)", pop.querySelector(".pj-goal-wkpop-days").textContent === "4일", pop.querySelector(".pj-goal-wkpop-days").textContent);
|
||||
const sumEl = pop.querySelector('[data-sum="weeks"]'), diffEl = pop.querySelector('[data-sum="diff"]');
|
||||
check("[2e] 저장된 주차 값·주차 합계", ins[0].value === "100" && ins[1].value === "200" && sumEl.textContent === "300", sumEl.textContent);
|
||||
type(env, ins[2], "300");
|
||||
check("[2e] 입력하면 주차 합계 다시 계산", sumEl.textContent === "600", sumEl.textContent);
|
||||
type(env, month, "700");
|
||||
check("[2e] 차이 = 월 목표 − 주차 합계(+ 남음)", diffEl.textContent === "+100" && diffEl.classList.contains("is-left"), diffEl.textContent);
|
||||
type(env, month, "500");
|
||||
check("[2e] 주차 합계가 넘으면 −", diffEl.textContent === "-100" && diffEl.classList.contains("is-over"), diffEl.textContent);
|
||||
type(env, month, "700");
|
||||
pop.querySelector('[data-act="save"]').click();
|
||||
await settle(); await wait(10); await settle();
|
||||
check("[2e] 월 목표·주차별 값 전송(주차 시작일 키)", sent && sent.month === "700" && sent.weeks["2026-01-12"] === "300" && Object.keys(sent.weeks).length === 5, sent);
|
||||
check("[2e] 월 목표 칸 = 입력한 월 목표(주차 합계 아님), 창 닫힘", inp.value === "700" && !env.d.body.querySelector(".pj-goal-wkpop"), inp.value);
|
||||
check("[2e] 월 목표 직접 저장 요청 없음", !st.metric);
|
||||
});
|
||||
|
||||
// ════════════════════ [2f] 회의록 보드 — 누르는 순간 창을 열고, 서버가 준 Google 슬라이드 주소로 바꾼다 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_ro, MEET_URL); // 보기만 하는 사람도 연다
|
||||
meetServer(env);
|
||||
let posted = null;
|
||||
env.route("POST", /\/project\/api\/goals\/meetings\/2026-09-28\/board$/, function (u, body) {
|
||||
posted = u;
|
||||
return { body: { ok: true, url: "https://docs.google.com/presentation/d/abc/edit", created: true, title: "9월 5주차 (9/28~9/30)" } };
|
||||
});
|
||||
await boot(env);
|
||||
const popup = { closed: false, focused: false, location: { href: "about:blank", replace: function (u) { this.href = u; } },
|
||||
document: { title: "", body: {} }, focus: function () { this.focused = true; }, close: function () { this.closed = true; } };
|
||||
let opened = null;
|
||||
env.w.open = function (url, name, features) { opened = { url: url, name: name, features: features }; return popup; };
|
||||
const btn = env.d.getElementById("pj-meet-board");
|
||||
check("[2f] 참석자 옆 회의록 보드 버튼", !!btn && !!btn.closest(".pj-meet-attend"));
|
||||
btn.click();
|
||||
check("[2f] 누르는 순간 독립 창(popup)을 연다", opened && opened.name === "pj_meet_board_2026-09-28" && /popup/.test(opened.features), opened);
|
||||
await settle(); await wait(10); await settle();
|
||||
check("[2f] 서버에 그 주차 보드 요청", !!posted);
|
||||
check("[2f] 창을 슬라이드 주소로", popup.location.href === "https://docs.google.com/presentation/d/abc/edit" && popup.focused);
|
||||
});
|
||||
|
||||
// ════════════════════ [2g] 머리 영역 3칸 — 결정 사항은 ②, 작업 등록 표(③): 칸 → 목록 → [적용] = 그 프로젝트에 작업 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
meetServer(env);
|
||||
let posted = null;
|
||||
env.route("GET", /\/project\/api\/projects$/, function () { return { body: { projects: [
|
||||
{ id: 7, name: "브랜드", parent_id: null, owner_email: "owner@test.local" }, { id: 8, name: "하위", parent_id: 7 }] } }; });
|
||||
env.route("GET", /\/project\/api\/projects\/7\/members$/, function () { return { body: { members: [{ user_email: "kim@test.local" }] } }; });
|
||||
env.route("GET", /\/project\/api\/projects\/7\/stages$/, function () { return { body: { stages: [{ id: 72, name: "진행", sort_order: 2 }, { id: 71, name: "할 일", sort_order: 1 }] } }; });
|
||||
env.route("POST", /\/project\/api\/projects\/7\/tasks$/, function (u, body) { posted = body; return { status: 201, body: { ok: true, task: { id: 555 } } }; });
|
||||
await boot(env);
|
||||
const d = env.d, board = d.querySelector(".pj-meet-board");
|
||||
check("[2g] 머리 영역: 월 계획 · 결정 사항 · 작업 등록", !!board && board.children.length === 3 &&
|
||||
!!board.querySelector(".pj-meet-notes #pj-meet-notes") && !!board.querySelector("#pj-meet-quick"));
|
||||
const tr = d.querySelector("#pj-meet-quick tbody tr");
|
||||
const title = tr.querySelector("input[data-field=title]");
|
||||
title.value = "상세페이지 수정"; title.dispatchEvent(new env.w.Event("input", { bubbles: true }));
|
||||
const pickItem = async function (kind, label) {
|
||||
d.querySelector('#pj-meet-quick tbody tr [data-pick="' + kind + '"]').click(); await settle(); await wait(5); await settle();
|
||||
const items = Array.from(d.querySelectorAll(".pj-ctxmenu-item"));
|
||||
const it = items.find(function (n) { return itemLabel(n) === label; });
|
||||
if (it) it.click();
|
||||
await settle(); await wait(5); await settle();
|
||||
return items.map(itemLabel);
|
||||
};
|
||||
const projLabels = await pickItem("project", "브랜드");
|
||||
check("[2g] 프로젝트 목록 = 최상위 프로젝트", JSON.stringify(projLabels) === JSON.stringify(["브랜드"]), projLabels);
|
||||
const row = d.querySelector("#pj-meet-quick tbody tr");
|
||||
check("[2g] 프로젝트 고르면 첫 섹션 자동", row.querySelector('[data-pick="stage"]').textContent === "할 일", row.querySelector('[data-pick="stage"]').textContent);
|
||||
const people = await pickItem("assignee", "Kim");
|
||||
check("[2g] 담당자 목록 = 그 프로젝트 소유자·멤버", people.indexOf("Owner") >= 0 && people.indexOf("Kim") >= 0, people);
|
||||
d.querySelector('#pj-meet-quick tbody tr [data-quick="apply"]').click(); await settle(); await wait(5); await settle();
|
||||
check("[2g] 적용 → 그 프로젝트에 작업 생성", posted && posted.title === "상세페이지 수정" && posted.stage_id === 71 && posted.assignee_email === "kim@test.local", posted);
|
||||
check("[2g] 등록된 줄은 '등록됨' 링크", /등록됨/.test(d.querySelector("#pj-meet-quick tbody tr").textContent) &&
|
||||
d.querySelector("#pj-meet-quick tbody tr a").getAttribute("href") === "/project/p/7?task=555");
|
||||
// 등록된 줄 삭제 → 확인 → 그 프로젝트의 작업도 삭제(DELETE), 줄 사라짐
|
||||
let deleted = null;
|
||||
env.route("DELETE", /\/project\/api\/tasks\/555$/, function (u) { deleted = u; return { body: { ok: true } }; });
|
||||
env.w.erpConfirm = function () { return Promise.resolve(true); };
|
||||
const before = d.querySelectorAll("#pj-meet-quick tbody tr").length;
|
||||
d.querySelector('#pj-meet-quick tbody tr [data-quick="delete"]').click(); await settle(); await wait(5); await settle();
|
||||
check("[2g] 등록된 작업 삭제 → 프로젝트 작업 DELETE·줄 제거", !!deleted && d.querySelectorAll("#pj-meet-quick tbody tr").length === before - 1 &&
|
||||
!d.querySelector("#pj-meet-quick tbody tr.is-done"), [deleted, before]);
|
||||
// 적용 전 줄의 × = 줄만 지움(요청 없음)
|
||||
const calls = env.calls.length, n = d.querySelectorAll("#pj-meet-quick tbody tr").length;
|
||||
d.querySelector('#pj-meet-quick tbody tr [data-quick="remove"]').click(); await settle();
|
||||
check("[2g] 적용 전 줄 × → 줄만 지움", d.querySelectorAll("#pj-meet-quick tbody tr").length === n - 1 && env.calls.length === calls);
|
||||
}, { notifyOnFail: true });
|
||||
|
||||
// ════════════════════ [2h] 회의록은 누구나 수정 · [회의 완료](관리자)면 잠금 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_member, MEET_URL);
|
||||
const st = meetServer(env);
|
||||
await boot(env);
|
||||
const d = env.d;
|
||||
check("[2h] 직원도 회의록 입력칸·메모 편집", !!d.querySelector(".pj-meet-text") && !!d.getElementById("pj-meet-notes"));
|
||||
check("[2h] 직원에겐 삭제·회의 완료 버튼 없음", !d.getElementById("pj-meet-del") && !d.getElementById("pj-meet-complete"));
|
||||
const ta = d.querySelector('tr[data-item="1"] .pj-meet-text');
|
||||
ta.focus(); type(env, ta, "직원이 적은 업무"); ta.blur(); await settle(); await wait(10); await settle();
|
||||
check("[2h] 직원 입력 저장", st.items[1] && st.items[1].content === "직원이 적은 업무", st.items[1]);
|
||||
});
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL);
|
||||
meetServer(env);
|
||||
let posted = null;
|
||||
env.route("POST", /\/project\/api\/goals\/meetings\/2026-09-28\/complete$/, function (u, body) { posted = body; return { body: { ok: true, completed: true } }; });
|
||||
env.w.erpConfirm = function () { return Promise.resolve(true); };
|
||||
await boot(env);
|
||||
env.d.getElementById("pj-meet-complete").click(); await settle(); await wait(10); await settle();
|
||||
check("[2h] 관리자 [회의 완료] → 완료 요청·새로고침", posted && posted.done === true && env.navigations === 1, [posted, env.navigations]);
|
||||
const ro = makeEnv(PAGE.meeting_ro, MEET_URL); meetServer(ro); await boot(ro);
|
||||
check("[2h] 완료된 회의록 — 입력칸 없음·완료 표시", !ro.d.querySelector(".pj-meet-text, #pj-meet-notes") && /회의 완료/.test(ro.d.querySelector(".pj-meet-done-badge").textContent));
|
||||
});
|
||||
|
||||
// ════════════════════ [3] 목표 표 — 글 저장 실패면 구조 변경·표 교체 중단 ════════════════════
|
||||
@@ -486,46 +633,29 @@ function meetServer(env, st) {
|
||||
check("[3d] 저장 실패 → 병합 요청 안 보냄, 글 유지", !st.merged && ta.value === "draft before merge");
|
||||
});
|
||||
|
||||
// ════════════════════ [7] 정량 목표 저장 → 이번주 실적 % 즉시 갱신, 다시 그리기와 엇갈려도 ════════════════════
|
||||
// ════════════════════ [7] 줄별 이번주 실적 표시 폐지(2026-10-06) — 정량 목표 저장만, 실적 글자 없음 ════════════════════
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
|
||||
const st = meetServer(env);
|
||||
meetServer(env);
|
||||
await boot(env);
|
||||
const slot = function () { return env.d.querySelector('tr[data-item="1"] .pj-meet-week-slot').textContent.trim(); };
|
||||
check("[7] 처음 = 실적 100 · 목표 100 → 100%", /100%/.test(slot()), slot());
|
||||
const tin = env.d.querySelector('tr[data-item="1"] input[data-field="target_amount"]');
|
||||
const row = env.d.querySelector('tr[data-item="1"]');
|
||||
check("[7] 이번주 실적 표시 없음", !row.querySelector(".pj-meet-week-slot") && !/이번주 실적/.test(row.textContent), row.textContent);
|
||||
const tin = row.querySelector('input[data-field="target_amount"]');
|
||||
tin.focus(); tin.value = "200"; tin.blur(); await settle(); await wait(10); await settle();
|
||||
check("[7] 목표 200 저장 → 50%", /· 50%$/.test(slot()), slot());
|
||||
tin.focus(); tin.value = "0"; tin.blur(); await settle(); await wait(10); await settle();
|
||||
check("[7] 목표 0 → % 없음", slot() === "이번주 실적 100", slot());
|
||||
tin.focus(); tin.value = ""; tin.blur(); await settle(); await wait(10); await settle();
|
||||
check("[7] 목표 삭제 → % 없음", slot() === "이번주 실적 100", slot());
|
||||
// 다시 그리기(옛 화면: 목표 100·100%)가 목표 저장 뒤에 도착해도 옛 비율이 들어오지 않는다
|
||||
const gate = deferred();
|
||||
st.getHook = async function () { await gate.promise; };
|
||||
const p = env.w.eval("null"); void p;
|
||||
tin.focus(); tin.value = "400"; tin.blur(); await settle(); await wait(10); await settle();
|
||||
check("[7] 목표 400 → 25%", /· 25%$/.test(slot()), slot());
|
||||
gate.resolve(); await settle(); await wait(10); await settle();
|
||||
check("[7] 늦게 온 옛 화면(100%)이 덮지 않음 — 지금 목표 기준 25%", /· 25%$/.test(slot()), slot());
|
||||
// 저장 실패 — 확정 목표(400)는 그대로라 25% 유지, 입력값은 남김
|
||||
st.itemHook = function () { return { status: 503, body: { detail: "x" } }; };
|
||||
tin.focus(); tin.value = "800"; tin.blur(); await settle(); await wait(10); await settle();
|
||||
check("[7] 저장 실패 → 비율은 확정값(25%), 입력 800 유지", /· 25%$/.test(slot()) && tin.value === "800", [slot(), tin.value]);
|
||||
check("[7] 목표 200 저장 → 확정값 반영", row.dataset.targetAmount === "200" && tin.value === "200", [row.dataset.targetAmount, tin.value]);
|
||||
});
|
||||
await section(async function () { // 실적 조회 실패 화면 — 미확인(0원·0% 아님)
|
||||
const env = makeEnv(PAGE.meeting_err, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "ok" }) } });
|
||||
meetServer(env, { page: PAGE.meeting_err });
|
||||
await boot(env);
|
||||
const kpi = Array.from(env.d.querySelectorAll(".pj-meet-kpi")).map(function (k) { return k.textContent.replace(/\s+/g, " ").trim(); });
|
||||
const mtd = kpi.find(function (t) { return /월 누적 실적/.test(t); });
|
||||
const mtd = kpi.find(function (t) { return /누적 실적/.test(t); });
|
||||
check("[6] 월 누적 = 미확인(0원 아님)", /미확인/.test(mtd) && !/0원|0 원/.test(mtd), mtd);
|
||||
check("[6] 주당 필요 = 미확인(목표로 계산하지 않음)", /미확인/.test(kpi.find(function (t) { return /주당 필요/.test(t); })));
|
||||
check("[6] 전주 결과·금주 실적 = 미확인", /미확인/.test(kpi.find(function (t) { return /전주 결과/.test(t); })) && /미확인/.test(kpi.find(function (t) { return /금주 현재 실적/.test(t); })));
|
||||
check("[6] 누적 목표 대비 달성 = 미확인(차액·% 계산하지 않음)", /미확인/.test(kpi.find(function (t) { return /목표 대비/.test(t); })));
|
||||
const row = env.d.querySelector('tr[data-item="1"]');
|
||||
check("[6] 쇼핑몰 연결 줄 결과 = 미확인, 직접 입력 칸으로 바뀌지 않음", /미확인/.test(row.querySelector(".pj-meet-c-result").textContent) && !row.querySelector(".pj-meet-c-result input"));
|
||||
check("[6] 이번주 실적 미확인 · 달성률 비움", /미확인/.test(row.querySelector(".pj-meet-week-slot").textContent) && row.querySelector("[data-rate]").textContent.trim() === "");
|
||||
check("[6] 회의록 입력은 그대로 가능", !!row.querySelector("textarea.pj-meet-text") && !!env.d.getElementById("pj-meet-target"));
|
||||
check("[6] 쇼핑몰 줄도 결과 = 직접 입력 칸(자동 결과 폐지)", !!row.querySelector(".pj-meet-c-result input") && !/미확인/.test(row.querySelector(".pj-meet-c-result").textContent));
|
||||
check("[6] 줄별 이번주 실적 표시 없음 · 달성률 열 없음", !row.querySelector(".pj-meet-week-slot") && !row.querySelector("[data-rate]"));
|
||||
check("[6] 회의록 입력은 그대로 가능", !!row.querySelector(".pj-meet-text") && !!env.d.getElementById("pj-meet-notes"));
|
||||
check("[6] 조회 실패 안내 문구", /미확인/.test(env.d.querySelector(".pj-meet-perf-warn").textContent));
|
||||
});
|
||||
await section(async function () { // 지난주 리뷰 머리 = 지난주(9/21~) — 지난주 회의록에 없는 줄 안내
|
||||
@@ -603,8 +733,11 @@ function meetServer(env, st) {
|
||||
// 분기 접기는 보기 전용도
|
||||
const qth = env.d.querySelector('th.pj-goal-fold-th[data-h="1"]');
|
||||
qth.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true }));
|
||||
check("[회귀] 분기 머리 클릭 → 접힘(보기 전용도)", qth.classList.contains("is-folded") && env.d.querySelector('td.pj-goal-m[data-h="1"]').classList.contains("is-shrunk"));
|
||||
check("[회귀] 분기 머리 클릭 → 접기 애니메이션(보기 전용도)", qth.classList.contains("is-folded") && env.d.querySelector('td.pj-goal-m[data-h="1"]').classList.contains("is-shrunk"));
|
||||
check("[회귀] 접기 상태 기억", /"1":true/.test(env.w.localStorage.getItem("pj_goal_fold_q") || ""));
|
||||
qth.dispatchEvent(new env.w.MouseEvent("click", { bubbles: true }));
|
||||
await wait(380);
|
||||
check("[회귀] 분기 머리 재클릭 → 펼침 완료·오래된 타이머 취소", !qth.classList.contains("is-folded") && !env.d.querySelector('td.pj-goal-m[data-h="1"]').classList.contains("is-gone") && !env.d.querySelector('td.pj-goal-m[data-h="1"]').classList.contains("is-folding"));
|
||||
});
|
||||
await section(async function () { // 회귀 — 열 너비 끌기·고정 열 변수·스크롤 위치 되살리기
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL, { session: { pj_goal_scroll: JSON.stringify(["/project/goals/2026", 120, 45]) } });
|
||||
@@ -656,7 +789,7 @@ function meetServer(env, st) {
|
||||
}) && !table.querySelector(".pj-goal-autofit-measure"));
|
||||
second.value = "짧음";
|
||||
fit("m1");
|
||||
const paragraphWidth = Math.max.apply(null, first.textContent.split("\n").map(function (line) { return line.length; })) * 10 + 15;
|
||||
const paragraphWidth = Math.max.apply(null, first.value.split("\n").map(function (line) { return line.length; })) * 10 + 15;
|
||||
check("[자동 너비] 명시적 줄바꿈 유지·문단 너비로 축소도 가능", width("m1") === paragraphWidth, [width("m1"), paragraphWidth]);
|
||||
env.d.documentElement.classList.add("pj-ui-scale"); fit("m1");
|
||||
check("[자동 너비] 75% 화면 배율에서도 같은 논리 너비", width("m1") === paragraphWidth);
|
||||
@@ -703,58 +836,12 @@ function meetServer(env, st) {
|
||||
menu(table.querySelector("th.pj-goal-area-name"));
|
||||
check("[너비 메뉴] 구역 이름 편집 메뉴에도 맞춤 제공", !!action("색 바꾸기") && !!action("현재 열 너비 자동 맞춤"));
|
||||
});
|
||||
await section(async function () {
|
||||
const gate = deferred(), env = makeEnv(PAGE.goals_admin, GOALS_URL);
|
||||
const st = goalsServer(env, { moveHook: async function (body) { await gate.promise; return { body: { ok: true, body: body.body } }; } });
|
||||
await boot(env);
|
||||
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
|
||||
type(env, source, "pj-rich:v1:" + JSON.stringify([{ text: "이동할 글", color: "#ff0000", size: 24, bold: true, italic: true, underline: true }]));
|
||||
const original = source.value;
|
||||
const drop = beginGoalMove(env, source, target);
|
||||
check("[셀 이동] 대상 미리보기·일반 범위 선택과 분리", target.closest("td").classList.contains("is-goal-move-target") && env.d.documentElement.classList.contains("pj-goal-moving"));
|
||||
drop(); await settle();
|
||||
check("[셀 이동] 먼저 초안 저장·이동은 한 번·응답 전 원본 유지", st.moves === 1 && source.value === original && target.value === "" && source.getAttribute("contenteditable") === "false" && target.getAttribute("contenteditable") === "false");
|
||||
const moveIndex = env.calls.findIndex(function (c) { return /cells\/move$/.test(c.url); });
|
||||
check("[셀 이동] 글 PUT 뒤 원자적 이동 API", moveIndex > env.calls.findIndex(function (c) { return c.method === "PUT" && /rows\/10\/cells\/1$/.test(c.url); }));
|
||||
gate.resolve(); await settle();
|
||||
const run = JSON.parse(target.value.slice(11))[0];
|
||||
check("[셀 이동] 성공 뒤 원본 비우기·대상 글과 모든 서식 보존", source.value === "" && run.text === "이동할 글" && run.color === "#ff0000" && run.size === 24 && run.bold && run.italic && run.underline);
|
||||
const count = env.calls.length; fire(env, source, "blur"); fire(env, target, "blur"); await settle();
|
||||
check("[셀 이동] 저장 기준값·초안 정리·후속 blur 중복 저장 없음", env.calls.length === count && !env.w.localStorage.getItem("pj_draft:goal:10:1") && source.getAttribute("contenteditable") === "true" && target.closest("td").classList.contains("is-goal-active"));
|
||||
});
|
||||
for (const failure of ["network", "conflict", "save"]) await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL);
|
||||
const st = goalsServer(env, { moveHook: function () { return failure === "network" ? "NETWORK" : { status: 409, body: { detail: "다른 창에서 수정" } }; },
|
||||
cellHook: failure === "save" ? function () { return { status: 503, body: { detail: "저장 장애" } }; } : null });
|
||||
await boot(env);
|
||||
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
|
||||
if (failure === "save") type(env, source, "미저장 초안");
|
||||
const before = source.value; beginGoalMove(env, source, target)(); await settle();
|
||||
check("[셀 이동 " + failure + "] 실패해도 양쪽 내용·편집 가능 상태 유지", source.value === before && target.value === "" && source.getAttribute("contenteditable") === "true" && !env.d.documentElement.classList.contains("pj-goal-moving"));
|
||||
check("[셀 이동 " + failure + "] 저장 실패면 이동 API 생략", failure !== "save" || !st.moves);
|
||||
});
|
||||
await section(async function () {
|
||||
await section(async function () { // 연간 목표 셀 끌어서 이동 — 2026-10-07 요청으로 없앰(회의록 표 이동은 그대로)
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL), st = goalsServer(env); await boot(env);
|
||||
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
|
||||
target.value = "대상 기존 글"; let confirmations = 0;
|
||||
env.w.erpConfirm = function () { confirmations++; return Promise.resolve(false); };
|
||||
beginGoalMove(env, source, target)(); await settle();
|
||||
check("[셀 이동] 덮어쓰기 취소는 두 내용 유지·이동 없음", confirmations === 1 && !st.moves && source.value === "original" && target.value === "대상 기존 글");
|
||||
env.w.erpConfirm = function () { return Promise.resolve(true); };
|
||||
beginGoalMove(env, source, target)(); await settle();
|
||||
check("[셀 이동] 확인 뒤 덮어쓰기·원본 비우기", st.moves === 1 && source.value === "" && target.textContent === "original");
|
||||
});
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.goals_admin, GOALS_URL), st = goalsServer(env); await boot(env);
|
||||
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]'), target = env.d.querySelector('.pj-goal-text[data-row="11"][data-month="2"]');
|
||||
beginGoalMove(env, source, target); key(env, env.d, "Escape"); await settle();
|
||||
check("[셀 이동] Esc 취소는 원본 유지·이동 요청 없음", !st.moves && source.value === "original" && !env.d.documentElement.classList.contains("pj-goal-moving"));
|
||||
beginGoalMove(env, source, target); env.w.dispatchEvent(new env.w.Event("blur")); await settle();
|
||||
check("[셀 이동] 창 포커스 이탈도 이동 취소·드래그 정리", !st.moves && !env.d.querySelector(".is-goal-move-target"));
|
||||
beginGoalMove(env, source, source)(); await settle();
|
||||
check("[셀 이동] 자기 셀에 놓기 = 변경 없음", !st.moves && source.value === "original");
|
||||
const ro = makeEnv(PAGE.goals_ro, GOALS_URL); goalsServer(ro); await boot(ro);
|
||||
check("[셀 이동] 보기 전용에는 이동 테두리 없음", !ro.d.querySelector(".pj-goal-move-edge"));
|
||||
const source = env.d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
check("[셀 이동 없음] 연간 목표 글 칸에 이동 테두리 없음", !env.d.querySelector("#pj-goal-table .pj-goal-move-edge"));
|
||||
source.closest("td").dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }));
|
||||
check("[셀 이동 없음] 누르면 칸 표시만", source.closest("td").classList.contains("is-goal-active") && !st.moves);
|
||||
});
|
||||
|
||||
// ════════════════════ [9] 매출 자동 갱신 — 정상 조용히 · 실패/일부 실패 안내 + 재시도 · 권한 없음 ════════════════════
|
||||
@@ -774,7 +861,7 @@ function meetServer(env, st) {
|
||||
shops: [{ name: "쿠팡", state: "done", active: true }, { name: "네이버", state: "error", label: "인증 오류", active: true }], overall: {} } } };
|
||||
} });
|
||||
await boot(env);
|
||||
const ta = env.d.querySelector('tr[data-item="1"] textarea.pj-meet-text');
|
||||
const ta = env.d.querySelector('tr[data-item="1"] .pj-meet-text');
|
||||
ta.focus(); type(env, ta, "editing while sync");
|
||||
await wait(20); await settle();
|
||||
const box = env.d.getElementById("pj-meet-sync"), btn = env.d.getElementById("pj-meet-sync-btn");
|
||||
@@ -815,7 +902,7 @@ function meetServer(env, st) {
|
||||
await wait(20); await settle();
|
||||
check("[9] 실적 권한 없음 → sync API 호출 0", !st.syncCalls && !env.calls.some(function (c) { return /performance/.test(c.url); }));
|
||||
check("[9] 권한 없음 설명(저장된 실적·마지막 갱신 시각)", /권한이 없어/.test(env.d.getElementById("pj-meet-sync").textContent) && /10\/01 14:20/.test(env.d.getElementById("pj-meet-sync").textContent));
|
||||
check("[9] 보기 전용: 입력칸 없음", !env.d.querySelector("textarea.pj-meet-text") && !env.d.getElementById("pj-meet-target"));
|
||||
check("[9] 보기 전용: 입력칸 없음", !env.d.querySelector(".pj-meet-text, .pj-meet-rnote, #pj-meet-notes"));
|
||||
});
|
||||
await section(async function () { // 10분 제한 — 최근 기록이 있으면 다시 부르지 않고 그 상태만(일부 실패면 안내 유지)
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL, { session: { "pj_meet_sync:2026-09-28": JSON.stringify({ at: Date.now(), state: "partial", bad: ["네이버"] }) } });
|
||||
@@ -848,6 +935,100 @@ function meetServer(env, st) {
|
||||
check("[회귀] 참석자 고르기 → 칩 + 저장", !!env.d.querySelector('.pj-meet-chip[data-key="a@test.local"]') && st.head.attendees === "a@test.local", st.head);
|
||||
});
|
||||
|
||||
await section(async function () { // 회의록에서도 같은 글자 서식·저장·초안 형식
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL), st = meetServer(env); await boot(env);
|
||||
const d = env.d, w = env.w, editor = d.querySelector('tr[data-item="1"] .pj-meet-text');
|
||||
type(env, editor, "앞 선택 뒤"); editor.focus();
|
||||
const range = d.createRange(); range.setStart(editor.firstChild, 2); range.setEnd(editor.firstChild, 4);
|
||||
w.getSelection().removeAllRanges(); w.getSelection().addRange(range); fire(env, editor, "mouseup");
|
||||
check("[회의록 서식] 같은 선택 글자 도구 표시", !d.getElementById("pj-goal-format").hidden);
|
||||
["bold", "italic", "underline", "size-up"].forEach(k => d.querySelector('[data-goal-format="' + k + '"]').click());
|
||||
d.querySelector('[data-goal-color="#DC2626"]').click();
|
||||
fire(env, editor, "blur"); await settle();
|
||||
const runs = JSON.parse(st.items[1].content.slice(11));
|
||||
check("[회의록 서식] 선택 부분의 색·크기·굵게·기울임·밑줄 저장", runs[1].text === "선택" && runs[1].bold && runs[1].italic && runs[1].underline && runs[1].size === 16 && runs[1].color === "#dc2626" && !runs[0].bold, runs);
|
||||
d.querySelector('[data-goal-format="reset"]').click(); fire(env, editor, "blur"); await settle();
|
||||
check("[회의록 서식] 초기화는 내용 보존·평문으로 저장", st.items[1].content === "앞 선택 뒤");
|
||||
});
|
||||
|
||||
await section(async function () { // 회의록 셀 이동 — 지연 응답·저장 순서·후속 blur
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL), st = meetServer(env); const gate = deferred(); await boot(env);
|
||||
env.route("POST", /\/meeting-cells\/move$/, async function (u, body) { await gate.promise; return { body: { ok: true, body: body.source_body } }; });
|
||||
const source = env.d.querySelector('tr[data-item="2"] .pj-meet-text'), target = env.d.querySelector('tr[data-item="3"] .pj-meet-text');
|
||||
const rich = 'pj-rich:v1:' + JSON.stringify([{ text: "이동", bold: true, italic: true, underline: true, size: 24, color: "#dc2626" }]);
|
||||
type(env, source, rich); const end = beginGoalMove(env, source, target);
|
||||
check("[회의록 이동] 대상 미리보기", target.closest("td").classList.contains("is-goal-move-target"));
|
||||
end(); await settle();
|
||||
const call = env.calls.find(c => /\/meeting-cells\/move$/.test(c.url));
|
||||
check("[회의록 이동] 초안 저장 후 이동, 응답 전 원본 유지", st.items[2].content === rich && call && source.value === rich && target.value === "" && source.getAttribute("contenteditable") === "false");
|
||||
gate.resolve(); await settle();
|
||||
check("[회의록 이동] 내용과 모든 서식 함께 반영", source.value === "" && target.value === rich && source.getAttribute("contenteditable") === "true");
|
||||
const before = env.calls.length; fire(env, source, "blur"); fire(env, target, "blur"); await settle();
|
||||
check("[회의록 이동] 후속 blur 중복 저장 없음", env.calls.length === before);
|
||||
});
|
||||
|
||||
for (const failure of ["network", "conflict", "save"]) await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL); meetServer(env, { itemHook: failure === "save" ? () => ({ status: 503 }) : null }); await boot(env);
|
||||
env.route("POST", /\/meeting-cells\/move$/, () => failure === "network" ? "NETWORK" : { status: 409 });
|
||||
const source = env.d.querySelector('tr[data-item="1"] .pj-meet-text'), target = env.d.querySelector('tr[data-item="2"] .pj-meet-text');
|
||||
if (failure === "save") type(env, source, "미저장 글");
|
||||
const before = source.value; beginGoalMove(env, source, target)(); await settle();
|
||||
check("[회의록 이동 " + failure + "] 실패 후 원본·대상·편집 가능 상태 유지", source.value === before && target.value === "" && source.getAttribute("contenteditable") === "true");
|
||||
check("[회의록 이동 " + failure + "] 저장 실패면 이동 요청 없음", failure !== "save" || !env.calls.some(c => /\/meeting-cells\/move$/.test(c.url)));
|
||||
});
|
||||
|
||||
await section(async function () { // 회의록 범위 지우기·Ctrl+Z, 병합 실패시 입력 유지
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL), st = meetServer(env); await boot(env);
|
||||
const a = env.d.querySelector('tr[data-item="2"] .pj-meet-text'), b = env.d.querySelector('tr[data-item="3"] .pj-meet-text');
|
||||
type(env, a, "첫 줄"); type(env, b, "둘째 줄"); fire(env, a, "blur"); fire(env, b, "blur"); await settle();
|
||||
a.closest("td").dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }));
|
||||
env.d.dispatchEvent(new env.w.MouseEvent("mouseup", { bubbles: true }));
|
||||
b.closest("td").dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0, shiftKey: true }));
|
||||
key(env, env.d.body, "Delete"); await settle();
|
||||
check("[회의록 범위] 선택한 두 셀만 지우고 저장", a.value === "" && b.value === "" && st.items[2].content === "" && st.items[3].content === "");
|
||||
key(env, env.d.body, "z", { ctrlKey: true }); await settle();
|
||||
check("[회의록 범위] Ctrl+Z는 내용과 저장 복원", a.value === "첫 줄" && b.value === "둘째 줄" && st.items[2].content === "첫 줄");
|
||||
env.route("POST", /\/meeting-cells\/merge$/, () => ({ status: 503 }));
|
||||
b.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
|
||||
const merge = Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(n => itemLabel(n).startsWith("셀 병합"));
|
||||
check("[회의록 병합] 같은 구역 범위에 병합 메뉴", !!merge); merge.click(); await settle();
|
||||
check("[회의록 병합] 실패 후 모든 글·편집 상태 유지", a.value === "첫 줄" && b.value === "둘째 줄" && a.getAttribute("contenteditable") === "true" && !env.navigations);
|
||||
const request = env.calls.find(c => /\/meeting-cells\/merge$/.test(c.url));
|
||||
check("[회의록 병합] 선택한 주의 줄 ID로 요청", request.body.item_from === "2" && request.body.item_to === "3");
|
||||
env.route("POST", /\/meeting-cells\/merge$/, () => ({ body: { ok: true } }));
|
||||
b.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
|
||||
Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(n => itemLabel(n).startsWith("셀 병합")).click(); await settle();
|
||||
check("[회의록 병합] 저장 성공 뒤 화면을 다시 받음", env.navigations === 1);
|
||||
});
|
||||
|
||||
await section(async function () {
|
||||
const env = makeEnv(fs.readFileSync(path.join(OUT, "meeting_merged.html"), "utf8"), MEET_URL); meetServer(env); await boot(env);
|
||||
const a = env.d.querySelector('td[data-meet-item="2"]');
|
||||
check("[회의록 병합 화면] 첫 셀만 표시하고 숫자 칸 유지", a.rowSpan === 2 && !env.d.querySelector('td[data-meet-item="3"]') && env.d.querySelectorAll('.pj-meet-amount[data-field="target_amount"]').length === 3);
|
||||
a.dispatchEvent(new env.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
|
||||
Array.from(env.d.querySelectorAll(".pj-ctxmenu-item")).find(n => itemLabel(n) === "병합 해제").click(); await settle();
|
||||
check("[회의록 병합 해제] 첫 셀 ID로 요청하고 화면 갱신", env.calls.some(c => c.method === "DELETE" && /\/meeting-items\/2\/cell-merge$/.test(c.url)) && env.navigations === 1);
|
||||
check("[회의록 병합 해제] 요청 중 합쳐진 글 보존", a.textContent.includes("병합한 계획"));
|
||||
});
|
||||
|
||||
await section(async function () {
|
||||
const env = makeEnv(PAGE.meeting_admin, MEET_URL); meetServer(env); await boot(env);
|
||||
const field = env.d.querySelector('tr[data-item="2"] .pj-meet-text'), handle = field.closest("td").querySelector(".pj-meet-colresize");
|
||||
// 열면 늘 전체 열 너비 자동 맞춤으로 시작(2026-10-07) — 저장된 너비가 있어도 맞춘 값
|
||||
const startW = parseFloat(env.d.querySelector('col[data-meet-col="content"]').style.width);
|
||||
check("[회의록 너비] 열 때 전체 자동 맞춤 결과를 기억", JSON.parse(env.w.localStorage.getItem("pj_meet_col_w")).content === startW, startW);
|
||||
handle.dispatchEvent(new env.w.MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0, clientX: 100 }));
|
||||
env.d.dispatchEvent(new env.w.MouseEvent("mousemove", { bubbles: true, clientX: 200 }));
|
||||
env.d.dispatchEvent(new env.w.MouseEvent("mouseup", { bubbles: true }));
|
||||
check("[회의록 너비] 드래그 너비 저장", JSON.parse(env.w.localStorage.getItem("pj_meet_col_w")).content === startW + 100);
|
||||
env.d.getElementById("pj-meet-order").click(); await settle();
|
||||
check("[회의록 너비] 순서 변경 후 논리 열 유지", field.closest("td").dataset.meetCols === "content");
|
||||
const ro = makeEnv(PAGE.meeting_ro, MEET_URL); meetServer(ro); await boot(ro);
|
||||
ro.d.querySelector("td.pj-meet-c-text").dispatchEvent(new ro.w.MouseEvent("contextmenu", { bubbles: true, cancelable: true }));
|
||||
const labels = Array.from(ro.d.querySelectorAll(".pj-ctxmenu-item")).map(itemLabel);
|
||||
check("[회의록 보기 전용] 너비 맞춤 제공·쓰기 도구 없음", labels.join("|") === "현재 열 너비 자동 맞춤|전체 열 너비 자동 맞춤" && !ro.d.querySelector(".pj-goal-move-edge,[contenteditable='true'],#pj-goal-format"));
|
||||
});
|
||||
|
||||
await section(async function () { // 선택한 글자만 서식·서식 초기화·저장·다시 그리기
|
||||
const env = makeEnv(PAGE.goals_admin, "http://localhost/project/goals/2026"); const st = goalsServer(env); await boot(env);
|
||||
const d = env.d, w = env.w, editor = d.querySelector('.pj-goal-text[data-row="10"][data-month="1"]');
|
||||
|
||||
@@ -46,12 +46,12 @@ const server = http.createServer(function (req, res) {
|
||||
assert.ok(rect.y >= 0 && rect.y < 300, "앵커 이동 후 소제목이 화면 위에 표시");
|
||||
await page.screenshot({ path: path.join(OUT, "help-goals.png") });
|
||||
await page.keyboard.press("/");
|
||||
await page.locator("#pjh-query").fill("쇼핑몰 연결");
|
||||
await page.locator("#pjh-query").fill("매출 갱신");
|
||||
await page.locator("#pjh-query").press("Enter");
|
||||
assert.equal(await page.evaluate(() => document.activeElement.id), "meetings-markets");
|
||||
await page.reload();
|
||||
await page.locator("#pjh-query").waitFor({ state: "visible" });
|
||||
assert.equal(await page.locator("#pjh-query").inputValue(), "쇼핑몰 연결");
|
||||
assert.equal(await page.locator("#pjh-query").inputValue(), "매출 갱신");
|
||||
assert.equal(await page.evaluate(() => document.activeElement.id), "meetings-markets");
|
||||
await page.goBack();
|
||||
assert.equal(await page.evaluate(() => document.activeElement.id), "goals-merge");
|
||||
|
||||
@@ -40,9 +40,9 @@ assert.equal(w.lastScroll, "goals-merge");
|
||||
assert.equal(d.querySelector('.pjh-toc [aria-current="location"]').hash, "#goals");
|
||||
assert.equal(new URL(w.location.href).searchParams.get("q"), "셀 병합");
|
||||
|
||||
search("7일 전");
|
||||
search("바로 앞 주차");
|
||||
assert.ok(links().some(a => a.hash === "#meetings-review"), "제목에 없는 본문 단어도 검색");
|
||||
search("쇼핑몰 연결");
|
||||
search("매출 갱신");
|
||||
assert.equal(links()[0].hash, "#meetings-markets");
|
||||
d.getElementById("pjh-search-form").dispatchEvent(new w.Event("submit", { bubbles: true, cancelable: true }));
|
||||
assert.equal(d.activeElement.id, "meetings-markets", "Enter/submit은 첫 결과 이동");
|
||||
@@ -54,7 +54,7 @@ search("로아스");
|
||||
assert.ok(links().length > 0, "한글 검색");
|
||||
search("원");
|
||||
assert.ok(links().length > 0, "한 글자 검색");
|
||||
search(" 쇼핑몰 연결 ");
|
||||
search(" 매출 갱신 ");
|
||||
assert.equal(links()[0].hash, "#meetings-markets", "연속 공백·여러 단어 검색");
|
||||
search("zz-no-help-match");
|
||||
assert.equal(links().length, 0);
|
||||
@@ -88,8 +88,8 @@ assert.equal(links()[0].hash, "#goals-merge", "조합 중 검색 안 함");
|
||||
input.dispatchEvent(new w.CompositionEvent("compositionend", { bubbles: true }));
|
||||
assert.ok(links().some(a => a.hash === "#meetings-intro"), "조합 확정 뒤 검색");
|
||||
|
||||
const restored = boot("http://localhost/project/help?q=" + encodeURIComponent("쇼핑몰 연결") + "#meetings-markets");
|
||||
assert.equal(restored.window.document.getElementById("pjh-query").value, "쇼핑몰 연결");
|
||||
const restored = boot("http://localhost/project/help?q=" + encodeURIComponent("매출 갱신") + "#meetings-markets");
|
||||
assert.equal(restored.window.document.getElementById("pjh-query").value, "매출 갱신");
|
||||
assert.equal(restored.window.document.activeElement.id, "meetings-markets", "공유 링크·새로고침 복원");
|
||||
w.history.pushState(null, "", "/project/help?q=" + encodeURIComponent("셀 병합") + "#goals-merge");
|
||||
w.dispatchEvent(new w.PopStateEvent("popstate"));
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
// 실제 브라우저 — 수신함 오른쪽 작업 창(iframe)이 다른 줄로 바뀌거나 닫히기 전에 작업 창의 저장을 기다리는지,
|
||||
// 저장 실패면 작업 창과 같은 "버리고 넘어가기 / 계속 편집"을 묻는지, 공유 링크 리다이렉트 뒤에도 embed 인지,
|
||||
// iframe 안 Esc·빠른 A→B→A·읽음 실패를 확인한다. 서버는 가짜(이 파일의 http 서버), 화면은 실제 템플릿 렌더 결과.
|
||||
// python tests/js/render_project.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/inbox_panel.browser.test.js
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs"), path = require("node:path"), http = require("node:http");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.resolve(__dirname, "../.."), OUT = path.join(__dirname, ".out"), STATIC = path.join(ROOT, "app/static");
|
||||
|
||||
const detail = (id, title) => ({ id, title, project_id: 1, stage_id: 11, description: "", priority: "normal",
|
||||
assignee_email: "", subtasks: [], links: [], followers: [], access: "full", completed_at: null });
|
||||
let putStatus = 200, holdPut = false, releasePut = null, failNotiRead = false;
|
||||
const puts = [], reads = [];
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, "http://localhost");
|
||||
const json = (code, body) => { res.statusCode = code; res.setHeader("Content-Type", "application/json"); res.end(JSON.stringify(body)); };
|
||||
if (url.pathname === "/project/inbox") { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(fs.readFileSync(path.join(OUT, "inbox_render.html"))); return; }
|
||||
const tm = /^\/project\/t\/(\d+)$/.exec(url.pathname);
|
||||
if (tm) { // 공유 링크 — 서버(router.task_permalink)처럼 embed 를 이어서 보낸다
|
||||
res.statusCode = 303;
|
||||
res.setHeader("Location", `/project/p/1?task=${tm[1]}${url.searchParams.get("embed") === "1" ? "&embed=1" : ""}`);
|
||||
res.end(); return;
|
||||
}
|
||||
if (url.pathname === "/project/p/1") { res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(fs.readFileSync(path.join(OUT, "project_render.html"))); return; }
|
||||
if (url.pathname.startsWith("/project/api/")) {
|
||||
let raw = ""; for await (const c of req) raw += c;
|
||||
const body = raw ? JSON.parse(raw) : null;
|
||||
const task = /^\/project\/api\/tasks\/(\d+)$/.exec(url.pathname);
|
||||
if (task && req.method === "GET") return json(200, { task: detail(+task[1], "작업 " + task[1]) });
|
||||
if (task && req.method === "PUT") {
|
||||
puts.push({ id: +task[1], body });
|
||||
if (holdPut) await new Promise(r => { releasePut = r; });
|
||||
return putStatus >= 400 ? json(putStatus, { detail: "서버 오류" }) : json(200, { task: Object.assign(detail(+task[1], "작업"), body) });
|
||||
}
|
||||
if (url.pathname === "/project/api/mentions/read") { reads.push("m" + (body && body.task_id)); return json(200, { ok: true, marked: 1 }); }
|
||||
const nr = /^\/project\/api\/notifications\/(\d+)\/read$/.exec(url.pathname);
|
||||
if (nr) { reads.push("n" + nr[1]); return failNotiRead ? json(500, { detail: "db" }) : json(200, { ok: true }); }
|
||||
if (url.pathname.endsWith("/comments")) return json(200, { comments: [], events: [], features: {} });
|
||||
if (url.pathname.endsWith("/attachments")) return json(200, { attachments: [] });
|
||||
if (url.pathname.endsWith("/members")) return json(200, { members: [{ user_email: "me@test.local" }] });
|
||||
if (url.pathname.endsWith("/live-version")) return json(200, { ts: "v1" });
|
||||
if (url.pathname.endsWith("/alerts")) return json(200, { me: "me@test.local", latest_id: 0, alerts: [] });
|
||||
return json(200, {});
|
||||
}
|
||||
if (url.pathname.startsWith("/static/")) {
|
||||
const file = path.join(STATIC, decodeURIComponent(url.pathname.slice("/static/".length)));
|
||||
if (file.startsWith(STATIC) && fs.existsSync(file)) {
|
||||
res.setHeader("Content-Type", file.endsWith(".js") ? "text/javascript" : file.endsWith(".css") ? "text/css" : "application/octet-stream");
|
||||
res.end(fs.readFileSync(file)); return;
|
||||
}
|
||||
}
|
||||
res.statusCode = 404; res.end("");
|
||||
});
|
||||
|
||||
(async function () {
|
||||
await new Promise(r => server.listen(0, "127.0.0.1", r));
|
||||
const base = "http://127.0.0.1:" + server.address().port;
|
||||
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
|
||||
const page = await browser.newPage({ viewport: { width: 1920, height: 1080 } }); // 작업 창이 왼쪽 목록을 가리지 않는 보통 PC 화면
|
||||
const dialogs = [];
|
||||
let dialogAnswer = false;
|
||||
page.on("dialog", async d => { dialogs.push(d.type() + ":" + d.message().slice(0, 20)); if (dialogAnswer) await d.accept(); else await d.dismiss(); });
|
||||
const pass = [];
|
||||
const ok = (name, cond, extra) => { assert.ok(cond, name + (extra === undefined ? "" : " → " + JSON.stringify(extra))); pass.push(name); console.log("PASS " + name); };
|
||||
try {
|
||||
await page.goto(base + "/project/inbox");
|
||||
const frameOf = () => page.frames().find(f => f !== page.mainFrame());
|
||||
const frameUrl = () => (frameOf() ? frameOf().url() : "");
|
||||
const waitModal = async () => {
|
||||
await page.waitForFunction(() => { const f = document.querySelector(".pj-inbox-panel iframe"); const d = f && f.contentDocument;
|
||||
const m = d && d.getElementById("pj-modal-task"); return !!(m && !m.hidden && d.getElementById("pj-t-id").value); });
|
||||
};
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="101"]');
|
||||
await waitModal();
|
||||
ok("공유 링크 리다이렉트 뒤에도 embed 화면(작업 창만)", /\/project\/p\/1\?/.test(frameUrl()) && /embed=1/.test(frameUrl()) &&
|
||||
await frameOf().evaluate(() => document.documentElement.classList.contains("pj-embed")), frameUrl());
|
||||
ok("같은 작업의 태그·알림을 함께 확인", reads.includes("m101") && reads.includes("n901"), reads);
|
||||
|
||||
// ① 저장 실패 → 다른 줄 → 묻기 → 계속 편집: 창·입력 그대로
|
||||
putStatus = 500;
|
||||
const fr = frameOf();
|
||||
await fr.fill("#pj-t-title", "작업 101 고침");
|
||||
await fr.evaluate(() => document.getElementById("pj-t-title").blur());
|
||||
await page.waitForTimeout(150);
|
||||
dialogAnswer = false;
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
|
||||
await page.waitForTimeout(400);
|
||||
ok("저장 실패면 바꾸기 전에 묻고(작업 창과 같은 확인), 계속 편집이면 그대로", dialogs.length === 1 && /\?task=|\/p\/1/.test(frameUrl()) &&
|
||||
await fr.evaluate(() => document.getElementById("pj-t-title").value) === "작업 101 고침" &&
|
||||
!reads.includes("m102"), { dialogs, url: frameUrl(), reads });
|
||||
|
||||
// ② 저장 대기 중 A→B→A — 확인 뒤 A 그대로, 새 줄 안 열림
|
||||
putStatus = 200; holdPut = true;
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
|
||||
await page.waitForTimeout(150);
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="101"]');
|
||||
await page.waitForTimeout(100);
|
||||
ok("저장이 끝나기 전엔 창을 바꾸지 않는다", frameOf() === fr && releasePut !== null);
|
||||
holdPut = false; releasePut(); releasePut = null;
|
||||
await page.waitForTimeout(500);
|
||||
ok("A→B→A 빨리 — 저장 성공 뒤 A 작업 창 그대로(다시 읽지 않음)", frameOf() === fr &&
|
||||
await fr.evaluate(() => document.getElementById("pj-t-id").value) === "101" && puts[puts.length - 1].body.title === "작업 101 고침" &&
|
||||
!reads.includes("m102"), { puts: puts.length, reads });
|
||||
|
||||
// ③ 저장 성공 상태에서 B → 바로 바뀌고 이탈 경고 없음
|
||||
const before = dialogs.length;
|
||||
await page.click('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
|
||||
await waitModal();
|
||||
await page.waitForFunction(() => document.querySelector(".pj-inbox-panel iframe").contentDocument.getElementById("pj-t-id").value === "102");
|
||||
ok("저장된 상태면 묻지 않고 B 로(beforeunload 경고도 없음)", dialogs.length === before && reads.includes("m102"), dialogs);
|
||||
|
||||
// ④ iframe 안 포커스에서 Esc — 작업 창이 닫히며 패널도 닫힘, 확인한 줄은 목록에서 빠짐
|
||||
const fr2 = frameOf();
|
||||
await fr2.focus("#pj-t-title");
|
||||
await page.keyboard.press("Escape");
|
||||
await page.waitForFunction(() => !document.querySelector(".pj-inbox-panel").classList.contains("is-open"));
|
||||
await page.waitForTimeout(400);
|
||||
ok("iframe 안에서 Esc → 패널 닫힘, 확인한 태그 줄은 빠짐", await page.evaluate(() =>
|
||||
!document.querySelector('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]')));
|
||||
|
||||
// ⑤ 읽음 실패한 알림 줄은 남는다
|
||||
failNotiRead = true;
|
||||
await page.click('#pj-inbox .pj-inbox-item[data-id="903"]', { button: "right" });
|
||||
await page.click(".pj-ctxmenu button, .pj-ctxmenu [role=menuitem], .pj-ctxmenu li");
|
||||
await page.waitForTimeout(400);
|
||||
ok("읽음 처리 실패 — 줄이 남고 굵게(읽지 않음)", await page.evaluate(() => {
|
||||
const li = document.querySelector('#pj-inbox .pj-inbox-item[data-id="903"]'); return !!li && li.classList.contains("is-unread"); }));
|
||||
console.log("\nALL PASS (" + pass.length + ")");
|
||||
} finally {
|
||||
await browser.close();
|
||||
server.close();
|
||||
}
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
+272
-2
@@ -15,6 +15,8 @@ const WATCHDOG = setTimeout(function () { console.log("TIMEOUT — 어딘가에
|
||||
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const html = fs.readFileSync(path.join(__dirname, ".out", "project_render.html"), "utf8");
|
||||
const adminHtml = fs.readFileSync(path.join(__dirname, ".out", "project_admin_render.html"), "utf8");
|
||||
const inboxHtml = fs.readFileSync(path.join(__dirname, ".out", "inbox_render.html"), "utf8");
|
||||
const JS = fs.readFileSync(path.join(ROOT, "app", "static", "project.js"), "utf8");
|
||||
|
||||
const fails = [];
|
||||
@@ -29,8 +31,8 @@ function deferred() {
|
||||
return { promise: p, resolve: resolve, reject: reject };
|
||||
}
|
||||
|
||||
function makeEnv() {
|
||||
const dom = new JSDOM(html, { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/project/p/1" });
|
||||
function makeEnv(page) {
|
||||
const dom = new JSDOM(page || html, { runScripts: "dangerously", pretendToBeVisual: true, url: "http://localhost/project/p/1" });
|
||||
const w = dom.window, d = w.document;
|
||||
w.__PJ_TEST__ = true;
|
||||
w.HTMLDialogElement.prototype.showModal = function () { this.open = true; };
|
||||
@@ -628,6 +630,274 @@ function titleVal(d) { return d.getElementById("pj-t-title").value; }
|
||||
env.w.localStorage.setItem("pj_side_w", "250"); await boot(env);
|
||||
check("[왼쪽 메뉴] 저장값이 기본 너비와 같아도 명시적으로 복원", env.d.querySelector(".pj-layout").style.getPropertyValue("--pj-side-w") === "250px");
|
||||
}
|
||||
// 파일 형식은 확장자 우선, 확장자 없는 파일은 MIME 으로 구분한다.
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const samples = [
|
||||
["사진.JPG", "application/octet-stream", "image"],
|
||||
["매출.XLSX", "application/octet-stream", "excel"],
|
||||
["매출.csv", "text/csv", "excel"],
|
||||
["메모.txt", "text/plain", "text"],
|
||||
["발표.pptx", "application/octet-stream", "ppt"],
|
||||
["보고서.docx", "application/octet-stream", "document"],
|
||||
["한글.hwpx", "application/octet-stream", "document"],
|
||||
["자료.pdf", "application/pdf", "pdf"],
|
||||
["이미지", "image/png", "image"],
|
||||
["시트", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "excel"],
|
||||
["발표", "application/vnd.ms-powerpoint", "ppt"],
|
||||
["문서", "application/msword", "document"],
|
||||
["텍스트", "text/plain; charset=utf-8", "text"],
|
||||
["<b>파일</b>.zip", "application/zip", "file"],
|
||||
];
|
||||
env.route("GET", /\/project\/api\/tasks\/101\/attachments/, function () {
|
||||
return { body: { attachments: samples.map(function (s, i) {
|
||||
return { id: 80 + i, filename: s[0], content_type: s[1], size_bytes: 123, comment_id: i === 0 ? 7 : null };
|
||||
}) } };
|
||||
});
|
||||
env.route("GET", /\/project\/api\/projects$/, function () { return { body: { projects: [{ id: 2, name: "P2" }] } }; });
|
||||
env.route("GET", /\/project\/api\/projects\/2\/stages$/, function () { return { body: { stages: [{ id: 21, name: "할 일" }] } }; });
|
||||
env.route("POST", /\/project\/api\/tasks\/101\/links$/, function () { return { body: {} }; });
|
||||
const P = await boot(env), d = env.d;
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
const items = Array.from(d.querySelectorAll("#pj-attach-list .pj-attach-item"));
|
||||
check("[첨부 아이콘] 모든 파일에 형식별 아이콘·이름·다운로드 링크", items.length === samples.length && items.every(function (li, i) {
|
||||
const icon = li.querySelector(".pj-attach-icon");
|
||||
return icon && icon.classList.contains("is-" + samples[i][2]) && icon.getAttribute("aria-label") &&
|
||||
li.querySelector(".pj-attach-name").textContent === samples[i][0] &&
|
||||
li.querySelector("a").getAttribute("href") === "/project/api/attachments/" + (80 + i) + "/download";
|
||||
}));
|
||||
check("[첨부 아이콘] 파일명 HTML 이스케이프·댓글 배지·삭제 유지", !items[13].querySelector("b") && !!items[0].querySelector(".pj-attach-from-comment") && !!items[0].querySelector(".pj-attach-del"));
|
||||
const row = d.getElementById("pj-links-block");
|
||||
check("[프로젝트 줄] 협업자 바로 아래·설명 위로 이동", d.getElementById("pj-followers-row").nextElementSibling === row && !!row.closest(".pj-meta-list") && !row.hidden);
|
||||
d.getElementById("pj-link-project").value = "2";
|
||||
d.getElementById("pj-link-project").dispatchEvent(new env.w.Event("change")); await settle();
|
||||
d.getElementById("pj-link-save").click(); await settle();
|
||||
check("[프로젝트 줄] 선택한 프로젝트·섹션으로 기존 연결 API 호출", env.calls.some(function (c) {
|
||||
return c.method === "POST" && c.url === "/project/api/tasks/101/links" && c.body.project_id === 2 && c.body.stage_id === 21;
|
||||
}));
|
||||
}
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
env.route("GET", /\/project\/api\/tasks\/101$/, function () { return { body: { task: detail(101, "읽기 전용", {
|
||||
access: "read", links: [{ project_id: 2, project_name: "P2", stage_name: "할 일" }],
|
||||
}) } }; });
|
||||
const P = await boot(env);
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
const d = env.d;
|
||||
check("[프로젝트 줄] 읽기 전용은 연결 목록만 표시", d.getElementById("pj-link-form").hidden && d.getElementById("pj-links-block").classList.contains("is-readonly") && !!d.querySelector(".pj-link-chip") && !d.querySelector(".pj-link-del"));
|
||||
}
|
||||
// ── 대시보드 담당자별 작업 합계 — 사람마다 메인·하위 세로 막대(완료/전체), 막대 → 오른쪽 업무 목록, 항목 → 편집 창 ──
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
env.d.querySelector(".pj-project-view").dataset.isPro = "true";
|
||||
let asked = null;
|
||||
env.route("GET", /\/project\/api\/projects\/1\/subtasks-summary\?scope=project$/, function (u) {
|
||||
asked = u;
|
||||
return { body: { subtasks: [
|
||||
{ id: 501, parent_task_id: 101, title: "하위 1", assignee_email: "me@test.local", assignee_name: "Me", done: true, completed_at: "2026-09-29T10:00:00+09:00" },
|
||||
{ id: 502, parent_task_id: 101, title: "하위 2", assignee_email: "bob@test.local", assignee_name: "Bob", done: false },
|
||||
{ id: 503, parent_task_id: 103, title: "다른 프로젝트 하위", assignee_email: "bob@test.local", assignee_name: "Bob", done: true },
|
||||
// 세부 작업의 세부 작업(2026-10-08) — root_task_id 로 맨 위 메인 작업을 따져 센다
|
||||
{ id: 504, parent_task_id: 501, root_task_id: 101, depth: 2, parent_title: "하위 1", title: "하위 1-1", assignee_email: "me@test.local", assignee_name: "Me", done: false },
|
||||
{ id: 505, parent_task_id: 503, root_task_id: 103, depth: 2, parent_title: "다른 프로젝트 하위", title: "다른 1-1", assignee_email: "bob@test.local", assignee_name: "Bob", done: true },
|
||||
] } };
|
||||
});
|
||||
env.route("GET", /\/project\/api\/tasks\/502$/, function () { return { body: { task: detail(502, "하위 2", { parent_task_id: 101 }) } }; });
|
||||
const P = await boot(env);
|
||||
P.state().tasks.forEach(function (t) {
|
||||
if (t.id === 101) Object.assign(t, { assignee_email: "me@test.local", assignee_name: "Me", completed_at: "2026-09-29T10:00:00+09:00" });
|
||||
if (t.id === 102) Object.assign(t, { assignee_email: "me@test.local", assignee_name: "Me" });
|
||||
if (t.id === 301) Object.assign(t, { assignee_email: "bob@test.local", assignee_name: "Bob" });
|
||||
});
|
||||
env.d.querySelector('.pj-tab[data-view="dashboard"]').click(); await settle();
|
||||
const groups = Array.from(env.d.querySelectorAll(".pj-wl-group")).map(function (g) {
|
||||
return [g.querySelector(".pj-wl-name b").textContent].concat(Array.from(g.querySelectorAll(".pj-wl-val")).map(function (v) { return v.firstChild.textContent; })).join("|");
|
||||
});
|
||||
check("[대시보드 담당자별] 하위 작업 요청(이 프로젝트 범위)", !!asked);
|
||||
check("[대시보드 담당자별] 세로 막대: 사람별 메인·세부 완료/전체(세부의 세부 포함, 다른 프로젝트 제외)",
|
||||
JSON.stringify(groups) === JSON.stringify(["Me|1/2|1/2", "Bob|0/1|0/1"]), groups);
|
||||
// 막대 = 그 작업 전체, 채움 = 완료율(작업 수가 아니라) — Me 메인 1/2 → 50%, 하위 1/1 → 100%, Bob 0/1 → 0%
|
||||
const pcts = Array.from(env.d.querySelectorAll(".pj-wl-done")).map(function (f) { return f.dataset.pct; });
|
||||
check("[대시보드 담당자별] 채움 높이 = 완료율", JSON.stringify(pcts) === JSON.stringify(["50", "50", "0", "0"]), pcts);
|
||||
const sum = env.d.querySelector(".pj-wl-sum").textContent.replace(/\s+/g, " ");
|
||||
check("[대시보드 담당자별] 전체 완료 2/6 (33%)", /2 \/ 6 \(33%\)/.test(sum), sum);
|
||||
// 막대 → 오른쪽 패널(body 에) → 항목 → 편집 창
|
||||
env.d.querySelectorAll(".pj-wl-group")[1].querySelector(".pj-wl-col.is-sub").click(); await settle();
|
||||
const drawer = env.d.body.querySelector(".pj-wl-drawer");
|
||||
const items = drawer ? Array.from(drawer.querySelectorAll(".pj-wl-item-title")).map(function (n) { return n.textContent; }) : [];
|
||||
check("[대시보드 담당자별] 하위 막대 → 오른쪽 패널에 업무 목록(상위 작업 표시)", !!drawer && drawer.parentElement === env.d.body &&
|
||||
JSON.stringify(items) === JSON.stringify(["하위 2"]) && /상위: 작업 A/.test(drawer.textContent), [items, drawer && drawer.textContent]);
|
||||
drawer.querySelector(".pj-wl-item").click(); await settle();
|
||||
check("[대시보드 담당자별] 항목 → 작업 편집 창(하위 작업은 서버에서 받아)", !env.d.getElementById("pj-modal-task").hidden &&
|
||||
env.d.getElementById("pj-t-title").value === "하위 2", env.d.getElementById("pj-t-title").value);
|
||||
}
|
||||
// ── 나를 태그·작업 배정 알림 팝업 — 본 것 이후 새 알림만, 깜박이는 팝업, 닫기 전까지 유지 ──
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
const asked = [];
|
||||
env.route("GET", /\/project\/api\/notifications\/alerts/, function (u) {
|
||||
asked.push(u);
|
||||
const after = /after=(\d+)/.exec(u);
|
||||
if (!after) return { body: { me: "me@test.local", latest_id: 5, alerts: [] } };
|
||||
return { body: { me: "me@test.local", latest_id: 5, alerts: [
|
||||
{ id: 4, type: "assigned", title: "작업 배정: 촬영 준비", body: "P1 · 마감 -", task_id: 101, project_id: 1, actor_email: "bob@test.local" },
|
||||
{ id: 5, type: "mention", title: "나를 태그함: 작업 A", body: "P1 · 댓글", task_id: 101, project_id: 1, actor_email: "bob@test.local" }] } };
|
||||
});
|
||||
env.w.localStorage.setItem("pj_alert_seen:me@test.local", "3");
|
||||
await boot(env); await settle(); await wait(10); await settle();
|
||||
const pop = env.d.body.querySelector(".pj-alert-pop");
|
||||
check("[알림 팝업] 본 것(3) 이후 새 알림 2건을 body 에 팝업", !!pop && pop.querySelectorAll(".pj-alert-item").length === 2 &&
|
||||
/촬영 준비/.test(pop.textContent) && /나를 태그/.test(pop.textContent) && asked.some(function (u) { return /after=3/.test(u); }), asked);
|
||||
pop.querySelector("[data-alert-close]").click();
|
||||
check("[알림 팝업] 닫기 → 사라지고 본 것 = 5", !env.d.body.querySelector(".pj-alert-pop") && env.w.localStorage.getItem("pj_alert_seen:me@test.local") === "5");
|
||||
}
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
env.route("GET", /\/project\/api\/notifications\/alerts/, function () { return { body: { me: "me@test.local", latest_id: 9, alerts: [] } }; });
|
||||
await boot(env); await settle();
|
||||
check("[알림 팝업] 처음 쓰는 브라우저 — 옛 알림 안 띄우고 기준점만", !env.d.body.querySelector(".pj-alert-pop") && env.w.localStorage.getItem("pj_alert_seen:me@test.local") === "9");
|
||||
}
|
||||
// ── 멤버 배정·제외 — 지금 멤버는 체크된 채로, 체크 = 배정 · 해제 = 제외(확인 뒤) ──
|
||||
{
|
||||
const env = makeEnv(adminHtml); baseRoutes(env);
|
||||
env.route("GET", /\/project\/api\/assignable-users$/, function () { return { body: { users: [
|
||||
{ email: "me@test.local", id: "me", name: "Me", avatar: "" },
|
||||
{ email: "bob@test.local", id: "bob", name: "Bob", avatar: "" },
|
||||
{ email: "carol@test.local", id: "carol", name: "Carol", avatar: "" }] } }; });
|
||||
const added = [], removed = [];
|
||||
env.route("POST", /\/project\/api\/projects\/1\/members$/, function (u, body) { added.push(body.user_email); return { body: { member: { user_email: body.user_email } } }; });
|
||||
env.route("DELETE", /\/project\/api\/projects\/1\/members\/.+$/, function (u) { removed.push(decodeURIComponent(u.split("/").pop())); return { body: { ok: true } }; });
|
||||
await boot(env);
|
||||
const d = env.d;
|
||||
d.getElementById("pj-add-member").click(); await settle();
|
||||
const box = function (e) { return d.querySelector('#pj-m-users input[value="' + e + '"]'); };
|
||||
check("[멤버 배정·제외] 지금 멤버 체크·나머지 해제", box("bob@test.local").checked && box("me@test.local").checked && !box("carol@test.local").checked);
|
||||
box("bob@test.local").checked = false; box("carol@test.local").checked = true;
|
||||
env.setConfirm(true);
|
||||
d.getElementById("pj-save-member").click(); await settle(); await wait(10); await settle();
|
||||
check("[멤버 배정·제외] 체크 = 배정, 해제 = 제외(확인 뒤)", JSON.stringify(added) === '["carol@test.local"]' &&
|
||||
JSON.stringify(removed) === '["bob@test.local"]' && env.confirms === 1, [added, removed, env.confirms]);
|
||||
const shown = Array.from(d.querySelectorAll(".pj-tmember")).map(function (n) { return n.dataset.email; });
|
||||
check("[멤버 배정·제외] 머리 멤버 아이콘 갱신", shown.indexOf("bob@test.local") < 0 && shown.indexOf("carol@test.local") >= 0, shown);
|
||||
}
|
||||
// ── [검토 A] 전체 보기 — 원 소속을 볼 수 없는 연결된 작업(301, 읽기 전용)도 한 번 나온다 ──
|
||||
{
|
||||
const env = makeEnv(adminHtml); baseRoutes(env);
|
||||
await boot(env);
|
||||
const d = env.d;
|
||||
d.getElementById("pj-side-allview").click(); await settle();
|
||||
const cards = function (id) { return d.querySelectorAll('.pj-card[data-task-id="' + id + '"]').length; };
|
||||
check("[전체 보기] 연결된 작업(원 소속 못 봄)도 한 장, 원 소속 작업은 그대로 한 장", cards(301) === 1 && cards(101) === 1 && cards(103) === 1,
|
||||
[cards(301), cards(101), cards(103)]);
|
||||
}
|
||||
// ── [검토 7] 수신함 iframe 안쪽 — __pjEmbedSettle 이 작업 창 닫기와 같은 저장 절차를 탄다 ──
|
||||
{
|
||||
const env = makeEnv(); baseRoutes(env);
|
||||
env.d.documentElement.classList.add("pj-embed");
|
||||
let putStatus = 500; const puts = [];
|
||||
env.route("PUT", /\/project\/api\/tasks\/101$/, function (u, b) {
|
||||
puts.push(b);
|
||||
return putStatus >= 400 ? { status: putStatus, body: { detail: "서버 오류" } } : { body: { task: Object.assign(detail(101, "작업 A"), b) } };
|
||||
});
|
||||
const P = await boot(env); const d = env.d; const modal = d.getElementById("pj-modal-task");
|
||||
await P.openTaskModal(taskOf(P, 101)); await settle();
|
||||
const ta = d.getElementById("pj-t-title");
|
||||
ta.value = "작업 A3"; ta.dispatchEvent(new env.w.Event("blur")); await settle();
|
||||
env.setConfirm(false); // 계속 편집
|
||||
const ok1 = await env.w.__pjEmbedSettle(); await settle();
|
||||
check("[수신함 iframe] 저장 실패 → 다시 시도 후 묻고, 계속 편집이면 false·입력 유지",
|
||||
ok1 === false && !modal.hidden && titleVal(d) === "작업 A3" && env.confirms === 1 && puts.length >= 2, [ok1, env.confirms, puts.length]);
|
||||
putStatus = 200;
|
||||
const ok2 = await env.w.__pjEmbedSettle(); await settle();
|
||||
check("[수신함 iframe] 다시 — 재시도 성공이면 true(묻지 않음)", ok2 === true && env.confirms === 1 && puts[puts.length - 1].title === "작업 A3",
|
||||
[ok2, env.confirms]);
|
||||
}
|
||||
// ── [검토 7] 수신함 작업 창 — 바꾸기·닫기 전 저장 대기, 계속 편집이면 그대로, A→B→A, 저장 중 Esc, 읽음 실패 ──
|
||||
{
|
||||
const env = makeEnv(inboxHtml); baseRoutes(env);
|
||||
const reads = [];
|
||||
env.route("POST", /\/project\/api\/mentions\/read$/, function (u, b) { reads.push("m" + (b && b.task_id)); return { body: { ok: true, marked: 1 } }; });
|
||||
let failNoti = true;
|
||||
env.route("POST", /\/project\/api\/notifications\/\d+\/read$/, function (u) {
|
||||
reads.push("n" + u.split("/")[4]);
|
||||
return failNoti ? { status: 500, body: { detail: "db" } } : { body: { ok: true } };
|
||||
});
|
||||
await boot(env);
|
||||
const d = env.d;
|
||||
const A = d.querySelector('#pj-mention-tasks .pj-inbox-item[data-task-id="101"]');
|
||||
const B = d.querySelector('#pj-mention-tasks .pj-inbox-item[data-task-id="102"]');
|
||||
const N901 = d.querySelector('#pj-inbox .pj-inbox-item[data-id="901"]');
|
||||
const frame = function () { const p = d.body.querySelector(".pj-inbox-panel"); return p && p.querySelector("iframe"); };
|
||||
const src = function () { return frame() ? frame().getAttribute("src") : ""; };
|
||||
A.click(); await settle();
|
||||
check("[수신함] 줄 → 오른쪽 작업 창 = 공유 링크 + embed", src() === "/project/t/101?embed=1", src());
|
||||
check("[수신함] 같은 작업의 태그·알림을 함께 확인", reads.indexOf("m101") >= 0 && reads.indexOf("n901") >= 0, reads);
|
||||
await settle();
|
||||
check("[수신함] 알림 읽음 실패 — 굵게(읽지 않음) 그대로", N901.classList.contains("is-unread"));
|
||||
let gate = deferred(), settles = 0;
|
||||
frame().contentWindow.__pjEmbedSettle = function () { settles++; return gate.promise; };
|
||||
B.click(); await settle();
|
||||
check("[수신함] 작업 창 저장 확인 중엔 바꾸지 않음", src() === "/project/t/101?embed=1" && settles === 1, [src(), settles]);
|
||||
A.click(); await settle(); // A→B→A 빨리
|
||||
gate.resolve(true); await settle();
|
||||
check("[수신함] A→B→A — 확인 뒤 A 그대로, B 는 열거나 확인하지 않음",
|
||||
src() === "/project/t/101?embed=1" && reads.indexOf("m102") < 0 && B.classList.contains("is-unread") && settles === 1, [src(), reads, settles]);
|
||||
gate = deferred();
|
||||
B.click(); await settle(); gate.resolve(false); await settle();
|
||||
check("[수신함] 계속 편집 — 창·선택 그대로, 새 줄 확인 안 함",
|
||||
src() === "/project/t/101?embed=1" && A.classList.contains("is-selected") && !B.classList.contains("is-selected") && reads.indexOf("m102") < 0);
|
||||
gate = deferred(); settles = 0;
|
||||
const esc = function () { d.dispatchEvent(new env.w.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); };
|
||||
esc(); await settle(); esc(); await settle();
|
||||
const panelEl = d.body.querySelector(".pj-inbox-panel");
|
||||
check("[수신함] 저장 중 Esc(두 번) — 확인 하나만, 끝나기 전엔 열린 채", panelEl.classList.contains("is-open") && settles === 1, settles);
|
||||
gate.resolve(true); await settle();
|
||||
check("[수신함] 저장이 끝나면 닫힘", !panelEl.classList.contains("is-open"));
|
||||
await wait(260); await settle();
|
||||
check("[수신함] 확인된 태그 줄은 빠지고, 읽음 실패한 알림 줄은 남는다", !A.isConnected && N901.isConnected, [A.isConnected, N901.isConnected]);
|
||||
failNoti = false;
|
||||
B.click(); await settle(); await settle();
|
||||
check("[수신함] 닫힌 뒤 다른 줄 — 바로 열림", src() === "/project/t/102?embed=1", src());
|
||||
}
|
||||
// ── [검토 9] 새 프로젝트 — 생성과 멤버 배정 결과를 따로, 실패한 멤버만 다시, 연타해도 한 번 생성 ──
|
||||
{
|
||||
const env = makeEnv(adminHtml); baseRoutes(env);
|
||||
env.route("GET", /\/project\/api\/assignable-users$/, function () { return { body: { users: [
|
||||
{ email: "bob@test.local", id: "bob", name: "Bob", avatar: "" },
|
||||
{ email: "carol@test.local", id: "carol", name: "Carol", avatar: "" }] } }; });
|
||||
let creates = 0, failCarol = true;
|
||||
const memberCalls = [];
|
||||
const createGate = deferred();
|
||||
env.route("POST", /\/project\/api\/projects$/, async function () {
|
||||
creates++;
|
||||
await createGate.promise;
|
||||
return { status: 201, body: { project: { id: 9, name: "새 프로젝트" } } };
|
||||
});
|
||||
env.route("POST", /\/project\/api\/projects\/9\/members$/, function (u, b) {
|
||||
memberCalls.push(b.user_email);
|
||||
return failCarol && b.user_email === "carol@test.local" ? { status: 400, body: { detail: "배정 불가" } } : { status: 201, body: { member: {} } };
|
||||
});
|
||||
await boot(env);
|
||||
const d = env.d;
|
||||
d.getElementById("pj-new-project-side").click(); await settle();
|
||||
d.getElementById("pj-f-name").value = "새 프로젝트";
|
||||
d.querySelectorAll("#pj-f-members input[type=checkbox]").forEach(function (c) { c.checked = true; });
|
||||
const save = d.getElementById("pj-save-project");
|
||||
save.click(); save.click(); await settle(); // 연타
|
||||
createGate.resolve(); await settle(); await settle();
|
||||
const modal = d.getElementById("pj-modal-project");
|
||||
const msg = d.getElementById("pj-f-project-msg");
|
||||
const carol = d.querySelector('#pj-f-members input[value="carol@test.local"]').closest(".pj-member-pick");
|
||||
check("[새 프로젝트] 연타해도 한 번만 생성", creates === 1, creates);
|
||||
check("[새 프로젝트] 배정 실패 — 창 유지, 생성됨·실패 멤버 안내, 실패 표시",
|
||||
!modal.hidden && !msg.hidden && /만들어졌습니다/.test(msg.textContent) && /배정 불가/.test(msg.textContent) &&
|
||||
carol.classList.contains("is-failed") && /다시 배정/.test(save.textContent), [modal.hidden, msg.textContent, save.textContent]);
|
||||
failCarol = false;
|
||||
save.click(); await settle(); await settle();
|
||||
check("[새 프로젝트] 다시 배정 — 실패한 멤버만, 프로젝트는 다시 만들지 않음, 끝나면 닫힘",
|
||||
creates === 1 && JSON.stringify(memberCalls) === JSON.stringify(["bob@test.local", "carol@test.local", "carol@test.local"]) && modal.hidden,
|
||||
[creates, memberCalls, modal.hidden]);
|
||||
}
|
||||
clearTimeout(WATCHDOG);
|
||||
console.log(fails.length ? "\nFAILED: " + fails.join(", ") : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Render the real asset workspace for browser validation; no DB or user data."""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import jinja2
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from app.modules.asset.store import CATEGORIES, STATUSES
|
||||
from app.modules.asset.hwinfo import parse_hwinfo
|
||||
from asset_fixtures import report_xml
|
||||
|
||||
env = jinja2.Environment(loader=jinja2.ChoiceLoader([
|
||||
jinja2.FileSystemLoader(ROOT / "app/modules/asset/templates"),
|
||||
jinja2.FileSystemLoader(ROOT / "app/templates"),
|
||||
]), autoescape=True)
|
||||
out = ROOT / "tests/js/.out"
|
||||
out.mkdir(exist_ok=True, parents=True)
|
||||
for configured in (True, False):
|
||||
html = env.get_template("asset/index.html").render(
|
||||
user={"email": "reader@test.local", "name": "Reader"}, nav_items=[], is_admin=False,
|
||||
page_title="자산관리", page_subtitle="회사 자산을 한곳에서", categories=CATEGORIES, statuses=STATUSES,
|
||||
csrf_token="browser-test", configured=configured, can_delete=False)
|
||||
(out / ("asset_render.html" if configured else "asset_unconfigured.html")).write_text(html, encoding="utf-8")
|
||||
(out / "asset_super.html").write_text(env.get_template("asset/index.html").render(
|
||||
user={"email":"super@test.local","name":"Super"},nav_items=[],is_admin=True,
|
||||
categories=CATEGORIES,statuses=STATUSES,csrf_token="browser-test",configured=True,can_delete=True),encoding="utf-8")
|
||||
sample = ROOT / "KING-DESKTOP.XML"
|
||||
raw = sample.read_bytes() if sample.exists() else report_xml()
|
||||
(out / "asset_report.json").write_text(json.dumps(parse_hwinfo(raw), ensure_ascii=False), encoding="utf-8")
|
||||
# Synthetic file for upload tests, never copy the private source XML into artifacts.
|
||||
(out / "asset_upload.xml").write_bytes(report_xml())
|
||||
print("Asset template and report analysis rendered to tests/js/.out")
|
||||
@@ -46,7 +46,7 @@ def board() -> dict:
|
||||
|
||||
def goals_ctx(admin: bool) -> dict:
|
||||
return {
|
||||
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "nav_projects": [], "goal_years": [2026],
|
||||
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "pj_pro": admin, "pj_admin": 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)),
|
||||
@@ -55,13 +55,23 @@ def goals_ctx(admin: bool) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def week_targets() -> dict:
|
||||
"""2026년 달마다 주차(store.month_weeks) — 1월 1·2주차만 값(100·200)."""
|
||||
out = {}
|
||||
for mo in range(1, 13):
|
||||
out[mo] = [{"start": a.isoformat(), "n": i + 1, "days": (b - a).days + 1, "label": f"{a.month}/{a.day}~{b.month}/{b.day}",
|
||||
"value": {(1, 0): "100", (1, 1): "200"}.get((mo, i), "")}
|
||||
for i, (a, b) in enumerate(store.month_weeks(2026, mo))]
|
||||
return out
|
||||
|
||||
|
||||
def meeting_view(err: bool) -> dict:
|
||||
"""회의록 2026-09-28 주 — 유통 쿠팡(쇼핑몰 연결, 이번주 실적 100, 정량 목표 100), 상품1(직접 입력 결과)."""
|
||||
"""회의록 2026-09-28 주 — 유통 쿠팡(쇼핑몰 연결 — 화면엔 자동 실적 없음, 정량 목표 100), 상품1(직접 입력 결과)."""
|
||||
prev_cou = {"id": 901, "week_start": "2026-09-21", "content": "지난주 행사", "target_amount": 100, "result_amount": None,
|
||||
"status": "", "marketplace_code": "coupang", "period": "9/21~9/27", "not_started": False,
|
||||
"market_off": False, "auto_error": err, "auto_result": None if err else 80,
|
||||
"result": None if err else 80, "market_name": "쿠팡"}
|
||||
prev_p1 = {"id": 902, "week_start": "2026-09-21", "content": "샘플", "target_amount": 200, "result_amount": 100,
|
||||
prev_p1 = {"id": 902, "week_start": "2026-09-21", "content": "샘플", "result_note": "샘플 결과", "target_amount": 200, "result_amount": 100,
|
||||
"status": "partial", "marketplace_code": "", "period": "9/21~9/27", "not_started": False,
|
||||
"market_off": False, "auto_error": False, "auto_result": None, "result": 100, "market_name": ""}
|
||||
it_cou = {"id": 1, "section": "유통", "section_color": "", "label": "쿠팡", "content": "original",
|
||||
@@ -74,7 +84,7 @@ def meeting_view(err: bool) -> dict:
|
||||
it_new = {"id": 3, "section": "상품", "section_color": "#fde2e4", "label": "새 줄", "content": "",
|
||||
"target_amount": None, "marketplace_code": "", "market_name": "", "market_off": False,
|
||||
"market_unknown": False, "week_auto": None, "week_error": False, "prev": None, "rate": None}
|
||||
meeting = {"week_start": "2026-09-28", "week_target": 1000, "attendees": "", "notes": "메모 원본",
|
||||
meeting = {"week_start": "2026-09-28", "week_target": 1000, "attendees": "", "notes": "메모 원본", "cell_merges": True, "result_notes": True,
|
||||
"items": [it_p1, it_new, it_cou],
|
||||
"sections": [{"name": "상품", "color": "#fde2e4", "rows": [it_p1, it_new]},
|
||||
{"name": "유통", "color": "", "rows": [it_cou]}]}
|
||||
@@ -82,6 +92,8 @@ def meeting_view(err: bool) -> dict:
|
||||
"mtd": None if err else 0, "mtd_end": "2026-09-27", "weeks_left": 1,
|
||||
"need_per_week": None if err else 10000, "prev_target": 500, "prev_exists": True,
|
||||
"prev_result": None if err else 0, "week_result": None if err else 0,
|
||||
"week_targets_set": True, "cum_target": 4000.0, "cum_target_won": 4000,
|
||||
"gap": None if err else -4000, "rate": None if err else 0.0,
|
||||
"perf": True, "perf_state": "error" if err else "ok",
|
||||
"unknown": ["mtd", "prev_result", "week_result"] if err else [],
|
||||
"fresh_oldest": "" if err else "10/01 14:20",
|
||||
@@ -91,8 +103,8 @@ def meeting_view(err: bool) -> dict:
|
||||
|
||||
def meeting_ctx(admin: bool, err: bool, can_sync: bool = True) -> dict:
|
||||
view = meeting_view(err)
|
||||
return {
|
||||
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "nav_projects": [], "goal_years": [2026],
|
||||
ctx = {
|
||||
"user": {"email": ME, "is_super_admin": False}, "is_admin": admin, "pj_pro": admin, "pj_admin": 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,
|
||||
@@ -102,6 +114,41 @@ def meeting_ctx(admin: bool, err: bool, can_sync: bool = True) -> dict:
|
||||
"can_sync": can_sync, "meeting_status": store.MEETING_STATUS, "meet_members": [], "month_plan": None,
|
||||
"attendee_list": [], **copy.deepcopy(view),
|
||||
}
|
||||
# 회의록은 누구나 고친다(2026-10-07) — 보기 전용은 "회의 완료"된 회의록뿐. 관리자 아닌 화면 = 완료된 회의록으로 시험
|
||||
ctx["meeting"].update(can_complete=True, completed=not admin, completed_at="2026-10-02 18:00" if not admin else "",
|
||||
completed_by="admin@test.local" if not admin else "")
|
||||
return ctx
|
||||
|
||||
|
||||
def member_ctx() -> dict:
|
||||
ctx = meeting_ctx(False, False, can_sync=False)
|
||||
ctx["meeting"].update(completed=False, completed_at="", completed_by="")
|
||||
return ctx
|
||||
|
||||
|
||||
def meeting_layout_ctx(admin: bool) -> dict:
|
||||
ctx = meeting_ctx(admin, False, can_sync=False)
|
||||
meeting = ctx["meeting"]
|
||||
product = meeting["sections"][0]["rows"][0]
|
||||
product["content"] = "첫 번째 줄\n두 번째 줄\n세 번째 줄"
|
||||
product["prev"]["content"] = "첫 번째 줄\n두 번째 줄"
|
||||
inactive = copy.deepcopy(meeting["sections"][1]["rows"][0])
|
||||
inactive.update(id=4, label="네이버", section="마케팅", content="한 줄", marketplace_code="naver",
|
||||
market_name="네이버 스마트스토어", market_off=True, week_auto=None)
|
||||
inactive["prev"].update(id=904, content="한 줄", auto_result=None, market_off=True,
|
||||
marketplace_code="naver", market_name="네이버 스마트스토어")
|
||||
meeting["items"].append(inactive)
|
||||
meeting["sections"].append({"name": "마케팅", "color": "", "rows": [inactive]})
|
||||
return ctx
|
||||
|
||||
|
||||
def meeting_merged_ctx() -> dict:
|
||||
ctx = meeting_ctx(True, False, can_sync=False)
|
||||
a, b = ctx["meeting"]["sections"][0]["rows"]
|
||||
a.update(content_span=2, content_hidden=False,
|
||||
content_html=store.goal_text_html(store.GOAL_RICH_PREFIX + '[{"text":"병합한 계획\\n두 번째 줄","bold":true,"size":24}]'))
|
||||
b["content_hidden"] = True
|
||||
return ctx
|
||||
|
||||
|
||||
def main() -> None:
|
||||
@@ -114,9 +161,18 @@ def main() -> None:
|
||||
pages = {
|
||||
"goals_admin.html": ("project/goals.html", goals_ctx(True)),
|
||||
"goals_ro.html": ("project/goals.html", goals_ctx(False)),
|
||||
# 주차별 매출 목표(020) — 매출 목표 칸이 주차 입력 창을 연다
|
||||
"goals_weekly_admin.html": ("project/goals.html", goals_ctx(True) | {"week_targets": week_targets()}),
|
||||
"meeting_admin.html": ("project/goal_meeting.html", meeting_ctx(True, False)),
|
||||
"meeting_err.html": ("project/goal_meeting.html", meeting_ctx(True, True)),
|
||||
"meeting_ro.html": ("project/goal_meeting.html", meeting_ctx(False, False, can_sync=False)),
|
||||
# 관리자 아닌 직원 + 아직 완료 전 회의록 — 누구나 고친다(2026-10-07)
|
||||
"meeting_member.html": ("project/goal_meeting.html", member_ctx()),
|
||||
"meeting_layout_admin.html": ("project/goal_meeting.html", meeting_layout_ctx(True)),
|
||||
"meeting_layout_ro.html": ("project/goal_meeting.html", meeting_layout_ctx(False)),
|
||||
"meeting_merged.html": ("project/goal_meeting.html", meeting_merged_ctx()),
|
||||
"meeting_content_admin.html": ("project/goal_meeting.html", meeting_ctx(True, False, can_sync=False) | {"meeting_embedded": True}),
|
||||
"meeting_content_ro.html": ("project/goal_meeting.html", meeting_ctx(False, False, can_sync=False) | {"meeting_embedded": True}),
|
||||
}
|
||||
for name, (tpl, ctx) in pages.items():
|
||||
html = env.get_template(tpl).render(**ctx)
|
||||
@@ -124,6 +180,21 @@ def main() -> None:
|
||||
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
|
||||
print("rendered:", path)
|
||||
|
||||
# 왼쪽을 유지하는 브라우저 검증은 실제 ERP 기본 레이아웃도 사용한다.
|
||||
shell_env = jinja2.Environment(loader=jinja2.ChoiceLoader([
|
||||
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "project", "templates")),
|
||||
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "templates")),
|
||||
]), autoescape=True)
|
||||
shell_env.globals["pj_kr_holidays"] = {}
|
||||
for name, ctx in [("meeting_shell_admin.html", meeting_ctx(True, False, can_sync=False)),
|
||||
("goals_shell_admin.html", goals_ctx(True))]:
|
||||
ctx.update(nav_items=[], force_sidebar_collapsed=True, page_title="목표·회의록 검증", goal_years=[2027, 2026])
|
||||
ctx["user"]["name"] = "Tester"
|
||||
html = shell_env.get_template("project/goals.html" if name.startswith("goals") else "project/goal_meeting.html").render(**ctx)
|
||||
path = os.path.join(OUT_DIR, name)
|
||||
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
|
||||
print("rendered:", path)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -50,8 +50,38 @@ def main() -> None:
|
||||
jinja2.FileSystemLoader(os.path.join(ROOT, "app", "modules", "project", "templates")),
|
||||
]))
|
||||
env.globals["pj_kr_holidays"] = {}
|
||||
for name, admin in (("project_render.html", False), ("project_admin_render.html", True)):
|
||||
render_one(env, name, admin)
|
||||
render_inbox(env)
|
||||
|
||||
|
||||
def render_inbox(env) -> None:
|
||||
"""수신함(project/inbox.html) — 태그한 작업 101·102, 알림(작업 101·102·프로젝트만)."""
|
||||
def mt(tid: int, title: str) -> dict:
|
||||
return {"id": tid, "title": title, "project_id": 1, "project_name": "P1", "project_color": "#4573d2",
|
||||
"unread_mentions": 1, "stage_name": "할 일", "due_label": "", "mention_actor": "bob@test.local",
|
||||
"completed_at": None}
|
||||
|
||||
def nt(nid: int, ntype: str, title: str, task_id: int | None) -> dict:
|
||||
return {"id": nid, "type": ntype, "title": title, "body": "P1", "task_id": task_id, "project_id": 1,
|
||||
"is_read": False, "actor_email": "bob@test.local", "created_at": "2026-10-12T09:00:00+09:00"}
|
||||
|
||||
html = env.get_template("project/inbox.html").render(
|
||||
user={"email": ME, "is_super_admin": False}, is_admin=False, pj_pro=False, pj_admin=False,
|
||||
nav_projects=PROJECTS, goal_years=[2026], my_open_total=0, mention_unread=2,
|
||||
color_palette=["#4573d2"], project_icons=["folder"], project_asana_icons=[],
|
||||
mentioned_tasks=[mt(101, "작업 A"), mt(102, "작업 B")],
|
||||
notifications=[nt(901, "assigned", "작업 배정: 작업 A", 101), nt(902, "comment", "새 댓글: 작업 B", 102),
|
||||
nt(903, "completed", "프로젝트 알림", None)],
|
||||
)
|
||||
path = os.path.join(OUT_DIR, "inbox_render.html")
|
||||
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
|
||||
print("rendered:", path)
|
||||
|
||||
|
||||
def render_one(env, name: str, admin: bool) -> None:
|
||||
html = env.get_template("project/project.html").render(
|
||||
user={"email": ME, "is_super_admin": False}, is_admin=False, can_manage=True,
|
||||
user={"email": ME, "is_super_admin": False}, is_admin=admin, pj_pro=admin, pj_admin=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=["할 일", "완료"],
|
||||
@@ -62,7 +92,7 @@ def main() -> None:
|
||||
my_open_total=0, mention_unread=0,
|
||||
)
|
||||
os.makedirs(OUT_DIR, exist_ok=True)
|
||||
path = os.path.join(OUT_DIR, "project_render.html")
|
||||
path = os.path.join(OUT_DIR, name)
|
||||
io.open(path, "w", encoding="utf-8", newline="\n").write(html)
|
||||
print("rendered:", path)
|
||||
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
import copy
|
||||
import importlib
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.testclient import TestClient
|
||||
from openpyxl import load_workbook
|
||||
from pydantic import ValidationError
|
||||
from starlette.middleware.sessions import SessionMiddleware
|
||||
|
||||
from asset_fixtures import prop, report_xml
|
||||
from app.modules.asset.db import AssetStore, FIELDS, filters
|
||||
from app.modules.asset.hwinfo import MAX_REPORT_BYTES, parse_hwinfo
|
||||
from app.modules.asset.store import ActionInput, AssetConflict, AssetInput, AssetUpdate, transition
|
||||
|
||||
api = importlib.import_module("app.modules.asset.router")
|
||||
|
||||
|
||||
class ParserTests(unittest.TestCase):
|
||||
def test_korean_and_english(self):
|
||||
for english in (False, True):
|
||||
p = parse_hwinfo(report_xml(english))
|
||||
s = p["summary"]
|
||||
self.assertEqual((s["cpu"], s["memory"], s["cores"], s["threads"]), ("Test Processor", "32 GiB", "8", "16"))
|
||||
self.assertEqual(s["serial"], "")
|
||||
self.assertEqual(p["scan_time"], "2026-10-06T01:10")
|
||||
self.assertEqual(s["drive_count"], 2)
|
||||
self.assertEqual(len(p["devices"]["MEMORY"]), 2)
|
||||
self.assertNotEqual(p["devices"]["DRIVES"][0]["properties"], p["devices"]["DRIVES"][1]["properties"])
|
||||
|
||||
def test_actual_sample(self):
|
||||
path = Path(os.getenv("ASSET_SAMPLE_XML") or Path(__file__).resolve().parents[1] / "KING-DESKTOP.XML")
|
||||
if not path.exists():
|
||||
self.skipTest("Real report is not present; synthetic tests still run")
|
||||
p = parse_hwinfo(path.read_bytes())
|
||||
s = p["summary"]
|
||||
self.assertEqual(s["computer_name"], "KING-DESKTOP")
|
||||
self.assertEqual(s["cpu"], "AMD Ryzen 7 5800X")
|
||||
self.assertEqual(s["memory"], "32 GiB")
|
||||
self.assertEqual((s["drive_count"], s["monitor_count"]), (4, 3))
|
||||
self.assertEqual(s["gpu"], "NVIDIA GeForce RTX 4060 Ti")
|
||||
self.assertEqual(len(p["devices"]["MEMORY"]), 2)
|
||||
self.assertGreater(p["property_count"], 3000)
|
||||
self.assertEqual(s["serial"], "")
|
||||
|
||||
def test_dtd_is_never_fetched(self):
|
||||
xml = report_xml().replace(b'HWiNFO32log.dtd', b'file:///does-not-exist.dtd')
|
||||
self.assertEqual(parse_hwinfo(xml)["summary"]["computer_name"], "TEST-PC")
|
||||
|
||||
def test_entities_rejected_in_utf8_and_utf16(self):
|
||||
attacks = ['<!DOCTYPE HWINFO [<!ENTITY x SYSTEM "file:///private">]>', '<!DOCTYPE HWINFO [<!ENTITY x "secret">]>']
|
||||
for declaration in attacks:
|
||||
text = declaration + '<HWINFO><COMPUTER><NodeName>&x;</NodeName></COMPUTER></HWINFO>'
|
||||
for raw in (text.encode(), ('<?xml version="1.0" encoding="UTF-16"?>' + text).encode("utf-16")):
|
||||
with self.assertRaises(ValueError):
|
||||
parse_hwinfo(raw)
|
||||
|
||||
def test_bad_input(self):
|
||||
for raw in (b"", b"<broken>", b"<html/>", b"<HWINFO><COMPUTER/><COMPUTER/></HWINFO>", b"<HWINFO><COMPUTER><NodeName>X</NodeName></COMPUTER></HWINFO>", b"x" * (MAX_REPORT_BYTES + 1)):
|
||||
with self.assertRaises(ValueError):
|
||||
parse_hwinfo(raw)
|
||||
|
||||
def test_deep_tree_rejected(self):
|
||||
raw = b'<HWINFO><COMPUTER><NodeName>X</NodeName><SubNodes><CPU>' + b'<SubNode>' * 70 + b'</SubNode>' * 70 + b'</CPU></SubNodes></COMPUTER></HWINFO>'
|
||||
with self.assertRaises(ValueError):
|
||||
parse_hwinfo(raw)
|
||||
|
||||
def test_properties_preserve_blank_labels_unicode_and_html_as_text(self):
|
||||
xml = report_xml().replace(b'</MOBO>', (prop("", "<script>bad</script>") + '</MOBO>').encode())
|
||||
p = parse_hwinfo(xml)
|
||||
properties = [p for s in p["sections"] for n in s["nodes"] for p in n["properties"]]
|
||||
self.assertIn({"label": "", "value": "<script>bad</script>", "type": ""}, properties)
|
||||
|
||||
|
||||
class RuleTests(unittest.TestCase):
|
||||
def test_invalid_category_cost_dates_extra(self):
|
||||
for values in ({"category": "unknown"}, {"purchase_cost": -1}, {"purchased_on": "2026-10-06", "warranty_until": "2026-01-01"}, {"status": "in_use"}, {"name": " "}, {"purchase_cost": "nan"}):
|
||||
with self.assertRaises(ValidationError):
|
||||
AssetInput.model_validate({"name": "Asset", "category": "desk", **values})
|
||||
|
||||
def test_required_reason(self):
|
||||
for action in ("lost", "retired"):
|
||||
with self.assertRaises(ValidationError):
|
||||
ActionInput(version=1, action=action)
|
||||
|
||||
def test_lifecycle_and_assignment(self):
|
||||
a = {"status": "available", "assignee_email": ""}
|
||||
self.assertEqual(transition(a, ActionInput(version=1, action="checkout", assignee_email="Reader@Test.Local")), ("in_use", "reader@test.local"))
|
||||
a.update(status="in_use", assignee_email="reader@test.local")
|
||||
self.assertEqual(transition(a, ActionInput(version=1, action="lost", note="lost")), ("lost", "reader@test.local"))
|
||||
for action in ("maintenance", "retired", "checkout", "available"):
|
||||
with self.assertRaises(ValueError):
|
||||
transition(a, ActionInput(version=1, action=action, note="test", assignee_email="other@test.local"))
|
||||
self.assertEqual(transition(a, ActionInput(version=1, action="checkin")), ("available", ""))
|
||||
|
||||
def test_search_parameterized_and_group(self):
|
||||
clause, params = filters(q="100%_\\'", group="furniture", location="HQ", warranty=True)
|
||||
self.assertNotIn("100%", clause)
|
||||
self.assertEqual(params[0], "%100\\%\\_\\\\'%")
|
||||
self.assertIn("IN ('desk','chair','furniture')", clause)
|
||||
self.assertIn("Asia/Seoul", clause)
|
||||
|
||||
|
||||
class Rows:
|
||||
def __init__(self, row=None): self.row = row
|
||||
def fetchone(self): return self.row
|
||||
|
||||
|
||||
class Connection:
|
||||
"""Transaction model verifies rollback, versions and lock-before-write in actual store methods."""
|
||||
def __init__(self):
|
||||
self.assets, self.reports, self.events, self.calls = {}, {}, [], []
|
||||
self.in_tx, self.locked, self.fail_event, self.sequence = False, set(), False, 0
|
||||
|
||||
@contextmanager
|
||||
def transaction(self):
|
||||
before = copy.deepcopy((self.assets, self.reports, self.events))
|
||||
self.in_tx = True; self.locked = set()
|
||||
try:
|
||||
yield self
|
||||
except Exception:
|
||||
self.assets, self.reports, self.events = before
|
||||
raise
|
||||
finally:
|
||||
self.in_tx = False
|
||||
|
||||
def execute(self, sql, params=()):
|
||||
self.calls.append((sql, params))
|
||||
if sql.startswith("SELECT nextval"):
|
||||
self.sequence += 1; return Rows({"n": self.sequence})
|
||||
if sql.startswith("SELECT * FROM assets"):
|
||||
self.assert_tx()
|
||||
assert "FOR UPDATE" in sql
|
||||
self.locked.add(params[0]); return Rows(copy.deepcopy(self.assets.get(params[0])))
|
||||
if sql.startswith("INSERT INTO assets"):
|
||||
self.assert_tx()
|
||||
row = dict(zip(("id", *FIELDS), params))
|
||||
row.update(status="available", assignee_email="", version=1, latest_report_id=None)
|
||||
self.assets[row["id"]] = row; self.locked.add(row["id"]); return Rows()
|
||||
if sql.startswith("SELECT id FROM asset_reports"):
|
||||
return Rows(next((r for r in self.reports.values() if r["asset_id"] == params[0] and r["sha256"] == params[1]), None))
|
||||
if sql.startswith("INSERT INTO asset_reports"):
|
||||
self.assert_tx(); assert params[1] in self.locked
|
||||
self.reports[params[0]] = dict(zip(("id", "asset_id", "filename", "sha256", "raw_xml", "parsed", "actor"), params)); return Rows()
|
||||
if sql.startswith("UPDATE assets SET latest_report_id"):
|
||||
self.assert_tx(); assert params[-1] in self.locked
|
||||
self.assets[params[-1]]["latest_report_id"] = params[0]; self.assets[params[-1]]["version"] += 1; return Rows()
|
||||
if sql.startswith("UPDATE assets SET status="):
|
||||
self.assert_tx(); assert params[-1] in self.locked
|
||||
self.assets[params[-1]].update(zip(("status", "assignee_email", "location"), params[:3]))
|
||||
self.assets[params[-1]]["version"] += 1; return Rows()
|
||||
if sql.startswith("UPDATE assets SET tag="):
|
||||
self.assert_tx(); assert params[-1] in self.locked
|
||||
self.assets[params[-1]].update(zip(FIELDS, params[:-1])); self.assets[params[-1]]["version"] += 1; return Rows()
|
||||
if sql.startswith("INSERT INTO asset_events"):
|
||||
self.assert_tx(); assert params[0] in self.locked
|
||||
if self.fail_event: raise RuntimeError("event write failed")
|
||||
self.events.append(params); return Rows()
|
||||
raise AssertionError(sql)
|
||||
|
||||
def assert_tx(self): assert self.in_tx
|
||||
|
||||
|
||||
class Pool:
|
||||
def __init__(self, conn): self.conn = conn
|
||||
@contextmanager
|
||||
def connection(self): yield self.conn
|
||||
|
||||
|
||||
class TransactionTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.conn = Connection(); self.store = object.__new__(AssetStore); self.store._pool = Pool(self.conn)
|
||||
self.payload = AssetInput(name="Computer", category="computer", location="HQ")
|
||||
self.raw = report_xml(); self.parsed = parse_hwinfo(self.raw)
|
||||
self.asset_id = self.store.create(self.payload, "actor@test.local")
|
||||
|
||||
def test_create_auto_tag_and_log(self):
|
||||
self.assertEqual(self.conn.assets[self.asset_id]["tag"], "AST-000001")
|
||||
self.assertEqual(self.conn.events[0][2], "create")
|
||||
|
||||
def test_stale_version_no_writes(self):
|
||||
before = copy.deepcopy(self.conn.assets)
|
||||
with self.assertRaises(AssetConflict):
|
||||
self.store.action(self.asset_id, ActionInput(version=9, action="checkout", assignee_email="user@test.local"), "actor")
|
||||
self.assertEqual(before, self.conn.assets)
|
||||
|
||||
def test_checkout_checkin_atomic_and_log(self):
|
||||
self.store.action(self.asset_id, ActionInput(version=1, action="checkout", assignee_email="user@test.local", location="Desk"), "actor")
|
||||
a = self.conn.assets[self.asset_id]
|
||||
self.assertEqual((a["status"], a["version"], a["location"]), ("in_use", 2, "Desk"))
|
||||
self.store.action(self.asset_id, ActionInput(version=2, action="checkin"), "actor")
|
||||
self.assertEqual(a["assignee_email"], "")
|
||||
self.assertEqual(len(self.conn.events), 3)
|
||||
|
||||
def test_event_failure_rolls_back_action(self):
|
||||
self.conn.fail_event = True
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.store.action(self.asset_id, ActionInput(version=1, action="maintenance"), "actor")
|
||||
self.assertEqual(self.conn.assets[self.asset_id]["status"], "available")
|
||||
self.assertEqual(self.conn.assets[self.asset_id]["version"], 1)
|
||||
|
||||
def test_report_preserves_manual_data_and_old_versions(self):
|
||||
first = self.store.attach_report(self.asset_id, 1, "actor", "first.xml", self.raw, self.parsed)
|
||||
raw = self.raw.replace(b"Test Processor", b"Updated Processor")
|
||||
second = self.store.attach_report(self.asset_id, 2, "actor", "second.xml", raw, parse_hwinfo(raw))
|
||||
a = self.conn.assets[self.asset_id]
|
||||
self.assertEqual((a["name"], a["location"], a["latest_report_id"], a["version"]), ("Computer", "HQ", second, 3))
|
||||
self.assertIn(first, self.conn.reports)
|
||||
self.assertEqual(len(self.conn.reports), 2)
|
||||
|
||||
def test_duplicate_report_no_version_increment(self):
|
||||
self.store.attach_report(self.asset_id, 1, "actor", "x.xml", self.raw, self.parsed)
|
||||
with self.assertRaises(AssetConflict):
|
||||
self.store.attach_report(self.asset_id, 2, "actor", "x.xml", self.raw, self.parsed)
|
||||
self.assertEqual(self.conn.assets[self.asset_id]["version"], 2)
|
||||
|
||||
def test_report_and_asset_roll_back_when_log_fails(self):
|
||||
self.conn.fail_event = True
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.store.attach_report(self.asset_id, 1, "actor", "x.xml", self.raw, self.parsed)
|
||||
self.assertFalse(self.conn.reports)
|
||||
self.assertIsNone(self.conn.assets[self.asset_id]["latest_report_id"])
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.store.create(self.payload, "actor", ("x.xml", self.raw, self.parsed))
|
||||
self.assertEqual(len(self.conn.assets), 1)
|
||||
|
||||
def test_category_cannot_detach_existing_reports(self):
|
||||
self.store.attach_report(self.asset_id, 1, "actor", "x.xml", self.raw, self.parsed)
|
||||
with self.assertRaises(ValueError):
|
||||
self.store.update(self.asset_id, AssetUpdate(name="Desk", category="desk", version=2), "actor")
|
||||
self.assertEqual(self.conn.assets[self.asset_id]["category"], "computer")
|
||||
|
||||
def test_update_keeps_assignment(self):
|
||||
self.store.action(self.asset_id, ActionInput(version=1, action="checkout", assignee_email="user@test.local"), "actor")
|
||||
self.store.update(self.asset_id, AssetUpdate(name="Renamed", category="computer", version=2), "actor")
|
||||
a = self.conn.assets[self.asset_id]
|
||||
self.assertEqual((a["name"], a["status"], a["assignee_email"], a["tag"]), ("Renamed", "in_use", "user@test.local", "AST-000001"))
|
||||
|
||||
|
||||
class APITests(unittest.TestCase):
|
||||
def test_delete_requires_true_super_admin_csrf_reason_and_version(self):
|
||||
calls=[]
|
||||
self.app.state.asset_store=SimpleNamespace(delete=lambda *args: calls.append(args))
|
||||
payload={"version":1,"note":"Duplicate entry"}
|
||||
for user in ({"email":"admin@test.local","role":"admin","is_super_admin":True},self.user):
|
||||
self.user=user
|
||||
self.assertEqual(self.client.request("DELETE","/asset/api/assets/a",json=payload,headers=self.headers).status_code,403)
|
||||
from app.store import SUPER_ADMIN_EMAIL
|
||||
self.user={"email":SUPER_ADMIN_EMAIL,"role":"admin","is_super_admin":True}
|
||||
self.assertEqual(self.client.request("DELETE","/asset/api/assets/a",json=payload).status_code,403)
|
||||
self.assertEqual(self.client.request("DELETE","/asset/api/assets/a",json={"version":1,"note":" "},headers=self.headers).status_code,422)
|
||||
self.assertEqual(self.client.request("DELETE","/asset/api/assets/a",json=payload,headers=self.headers).status_code,200)
|
||||
self.assertEqual(calls,[("a",1,SUPER_ADMIN_EMAIL,"Duplicate entry")])
|
||||
|
||||
def test_photos_validated_authorized_and_bound_to_asset(self):
|
||||
from PIL import Image
|
||||
image=io.BytesIO();Image.new("RGB",(10,20),"blue").save(image,"PNG")
|
||||
calls=[]
|
||||
self.app.state.asset_store=SimpleNamespace(add_photo=lambda *args: calls.append(args) or "p",photo=lambda *args: {"image":image.getvalue(),"mime":"image/png"})
|
||||
path="/asset/api/assets/a/photos"
|
||||
self.assertEqual(self.client.post(path,files={"file":("fake.jpg",b"<svg/>")},data={"version":1},headers=self.headers).status_code,422)
|
||||
self.assertEqual(self.client.post(path,files={"file":("photo.png",image.getvalue())},data={"version":1}).status_code,403)
|
||||
result=self.client.post(path,files={"file":("photo.png",image.getvalue())},data={"version":1},headers=self.headers)
|
||||
self.assertEqual(result.status_code,200);self.assertEqual(calls[0][:4],("a",1,self.user["email"],"photo.png"))
|
||||
self.assertEqual(self.client.get(path+"/p").headers["content-type"],"image/png")
|
||||
self.user=None
|
||||
self.assertEqual(self.client.get(path+"/p").status_code,401)
|
||||
|
||||
def test_monitor_registration_permission_payload_and_version(self):
|
||||
calls=[]
|
||||
self.app.state.asset_store=SimpleNamespace(register_monitor=lambda *args:calls.append(args) or "monitor")
|
||||
path="/asset/api/assets/pc/monitors/0"
|
||||
data={"version":3,"report_id":"r","asset":{"name":"Display","category":"monitor"}}
|
||||
self.assertEqual(self.client.post(path,json=data).status_code,403)
|
||||
self.assertEqual(self.client.post(path,json=data,headers=self.headers).status_code,200)
|
||||
self.assertEqual((calls[0][0],calls[0][1],calls[0][2].version),("pc",0,3))
|
||||
data["asset"]["category"]="desk"
|
||||
self.assertEqual(self.client.post(path,json=data,headers=self.headers).status_code,422)
|
||||
|
||||
def setUp(self):
|
||||
self.user = {"email": "reader@test.local", "name": "Reader", "role": "user", "modules": {"asset": True}}
|
||||
self.user_store = SimpleNamespace(get=lambda email: self.user if email == self.user["email"] else None, list_all=lambda: [self.user])
|
||||
self.main = SimpleNamespace(get_current_user_record=lambda req: self.user,
|
||||
user_store=self.user_store, render_template=lambda *a, **kw: HTMLResponse("page", status_code=kw.get("status_code", 200)), build_erp_nav=lambda *a, **kw: [])
|
||||
self.patch = patch.dict(sys.modules, {"app.main": self.main}); self.patch.start(); self.addCleanup(self.patch.stop)
|
||||
self.app = FastAPI(); self.app.add_middleware(SessionMiddleware, secret_key="test-only-secret")
|
||||
self.app.state.asset_store = None; self.app.include_router(api.router)
|
||||
@self.app.get("/test-session")
|
||||
def session(request: Request):
|
||||
request.session["asset_csrf"] = "test-token"; return {"ok": True}
|
||||
self.client = TestClient(self.app)
|
||||
self.client.get("/test-session"); self.headers = {"X-Asset-CSRF": "test-token"}
|
||||
|
||||
def test_login_and_permission_required_every_read(self):
|
||||
paths = ["/asset/health", "/asset/api/bootstrap", "/asset/api/assets", "/asset/api/assets/a", "/asset/api/export", "/asset/api/assets/a/reports/r", "/asset/api/assets/a/reports/r/download", "/asset/api/assets/a/photos/p", "/asset/api/assets/a/reports/r/monitors"]
|
||||
self.user = None
|
||||
for path in paths: self.assertEqual(self.client.get(path).status_code, 401)
|
||||
self.user = {"role": "user", "email": "x", "modules": {}}
|
||||
for path in paths: self.assertEqual(self.client.get(path).status_code, 403)
|
||||
|
||||
def test_missing_csrf_and_no_db(self):
|
||||
payload = {"name": "Desk", "category": "desk"}
|
||||
self.assertEqual(self.client.post("/asset/api/assets", json=payload).status_code, 403)
|
||||
self.assertEqual(self.client.post("/asset/api/assets", json=payload, headers=self.headers).status_code, 503)
|
||||
self.assertEqual(self.client.get("/asset/api/assets").status_code, 503)
|
||||
|
||||
def test_preview_without_database(self):
|
||||
result = self.client.post("/asset/api/reports/preview", files={"file": ("test.xml", report_xml())}, headers=self.headers)
|
||||
self.assertEqual(result.status_code, 200, result.text)
|
||||
self.assertEqual(result.json()["summary"]["memory"], "32 GiB")
|
||||
|
||||
def test_preview_security(self):
|
||||
for filename, raw in (("x.html", report_xml()), ("x.xml", b"<html/>")):
|
||||
self.assertEqual(self.client.post("/asset/api/reports/preview", files={"file": (filename, raw)}, headers=self.headers).status_code, 422)
|
||||
self.assertEqual(self.client.post("/asset/api/reports/preview", files={"file": ("test.xml", report_xml())}).status_code, 403)
|
||||
|
||||
def test_import_stores_asset_and_report_together(self):
|
||||
conn = Connection()
|
||||
store = object.__new__(AssetStore)
|
||||
store._pool = Pool(conn)
|
||||
self.app.state.asset_store = store
|
||||
result = self.client.post("/asset/api/reports/import", data={"payload": '{"name":"Imported PC","category":"computer","location":"HQ"}'},
|
||||
files={"file": ("report.xml", report_xml())}, headers=self.headers)
|
||||
self.assertEqual(result.status_code, 200, result.text)
|
||||
asset = conn.assets[result.json()["id"]]
|
||||
self.assertEqual((asset["name"], asset["location"], asset["version"]), ("Imported PC", "HQ", 2))
|
||||
self.assertIn(asset["latest_report_id"], conn.reports)
|
||||
self.assertEqual(len(conn.events), 2)
|
||||
|
||||
def test_upload_existing_validates_target_and_version(self):
|
||||
conn = Connection()
|
||||
store = object.__new__(AssetStore)
|
||||
store._pool = Pool(conn)
|
||||
self.app.state.asset_store = store
|
||||
asset_id = store.create(AssetInput(name="Desk", category="desk"), "actor")
|
||||
result = self.client.post(f"/asset/api/assets/{asset_id}/reports", data={"version": "1"},
|
||||
files={"file": ("report.xml", report_xml())}, headers=self.headers)
|
||||
self.assertEqual(result.status_code, 422)
|
||||
asset_id = store.create(AssetInput(name="PC", category="computer"), "actor")
|
||||
result = self.client.post(f"/asset/api/assets/{asset_id}/reports", data={"version": "99"},
|
||||
files={"file": ("report.xml", report_xml())}, headers=self.headers)
|
||||
self.assertEqual(result.status_code, 409)
|
||||
self.assertFalse(conn.reports)
|
||||
|
||||
def test_unknown_assignment_rejected(self):
|
||||
result = self.client.post("/asset/api/assets/a/actions", json={"version": 1, "action": "checkout", "assignee_email": "outsider@test.local"}, headers=self.headers)
|
||||
self.assertEqual(result.status_code, 422)
|
||||
|
||||
def test_conflict_and_missing_entity(self):
|
||||
def conflict(*args): raise AssetConflict("conflict")
|
||||
self.app.state.asset_store = SimpleNamespace(update=conflict)
|
||||
self.assertEqual(self.client.put("/asset/api/assets/a", json={"name": "Asset", "category": "desk", "version": 1}, headers=self.headers).status_code, 409)
|
||||
def missing(*args): raise KeyError("no")
|
||||
self.app.state.asset_store = SimpleNamespace(detail=missing)
|
||||
self.assertEqual(self.client.get("/asset/api/assets/a").status_code, 404)
|
||||
|
||||
def test_export_literal_formulas_and_filters(self):
|
||||
record = {**AssetInput(name="=2+2", category="desk", purchase_cost=0).model_dump(mode="json"), "status": "available", "assignee_email": "", "specs": {}}
|
||||
seen = []
|
||||
def listing(**kwargs): seen.append(kwargs); return {"items": [record], "total": 1}
|
||||
self.app.state.asset_store = SimpleNamespace(list_assets=listing)
|
||||
response = self.client.get("/asset/api/export?group=furniture&location=HQ")
|
||||
self.assertEqual(response.status_code, 200)
|
||||
book = load_workbook(io.BytesIO(response.content)); cell = book.active["B2"]
|
||||
self.assertEqual((cell.value, cell.data_type), ("=2+2", "s"))
|
||||
self.assertEqual(book.active["L2"].value, 0)
|
||||
self.assertEqual((seen[0]["group"], seen[0]["location"]), ("furniture", "HQ"))
|
||||
|
||||
def test_download_bound_to_asset_and_attachment(self):
|
||||
args = []
|
||||
def report(*values, **kwargs): args.append((values, kwargs)); return {"filename": "테스트.xml", "raw_xml": report_xml()}
|
||||
self.app.state.asset_store = SimpleNamespace(report=report)
|
||||
response = self.client.get("/asset/api/assets/own/reports/report/download")
|
||||
self.assertEqual(response.content, report_xml())
|
||||
self.assertIn("attachment", response.headers["content-disposition"])
|
||||
self.assertEqual(args[0], (("own", "report"), {"raw": True}))
|
||||
|
||||
|
||||
if __name__ == "__main__": unittest.main()
|
||||
@@ -0,0 +1,183 @@
|
||||
"""삭제 권한, 사진 검증, 모니터 중복과 동시 수정 보호를 확인합니다."""
|
||||
import copy
|
||||
import io
|
||||
import unittest
|
||||
from contextlib import contextmanager
|
||||
from types import SimpleNamespace
|
||||
|
||||
from PIL import Image
|
||||
|
||||
import test_asset as fixtures
|
||||
from app.modules.asset.db import AssetStore
|
||||
from app.modules.asset.media import MAX_PHOTO_BYTES, prepare_photo
|
||||
from app.modules.asset.monitors import monitor_devices
|
||||
from app.modules.asset.store import AssetConflict, AssetInput, DeleteInput, MonitorInput
|
||||
from asset_fixtures import report_xml
|
||||
from app.modules.asset.hwinfo import parse_hwinfo
|
||||
|
||||
|
||||
def monitor_report(serial="SN-1"):
|
||||
parsed = parse_hwinfo(report_xml())
|
||||
parsed["devices"]["MONITOR"] = [{"name": "Test Display", "properties": [
|
||||
{"label": "Monitor Name (Manuf)", "value": "Display 24", "type": "MONITOR"},
|
||||
{"label": "Serial Number", "value": serial, "type": ""}]}]
|
||||
return parsed
|
||||
|
||||
|
||||
class Result:
|
||||
def __init__(self, rows): self.rows = rows
|
||||
def fetchone(self): return self.rows[0] if self.rows else None
|
||||
def fetchall(self): return self.rows
|
||||
|
||||
|
||||
class FeatureConnection(fixtures.Connection):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.photos, self.links = {}, {}
|
||||
|
||||
@contextmanager
|
||||
def transaction(self):
|
||||
before = copy.deepcopy((self.photos, self.links))
|
||||
try:
|
||||
with super().transaction(): yield self
|
||||
except Exception:
|
||||
self.photos, self.links = before
|
||||
raise
|
||||
|
||||
def execute(self, sql, params=()):
|
||||
if sql.startswith("SELECT a.* FROM asset_monitor_links"):
|
||||
target = self.links.get(tuple(params))
|
||||
row = self.assets.get(target)
|
||||
return Result([row] if row and not row.get("deleted_at") else [])
|
||||
if sql.startswith("SELECT * FROM assets") and "FOR UPDATE" not in sql:
|
||||
rows = [a for a in self.assets.values() if a["category"] == "monitor" and not a.get("deleted_at")]
|
||||
if "btrim(serial)" in sql: rows = [a for a in rows if a["serial"].strip().casefold() == params[0]]
|
||||
else: rows = [a for a in rows if a["model"].strip().casefold() == params[0] or a["name"].strip().casefold() == params[1]]
|
||||
return Result(rows)
|
||||
if sql.startswith("SELECT parsed FROM asset_reports"):
|
||||
row=self.reports.get(params[1])
|
||||
return Result([{"parsed": row["parsed"].obj}] if row and row["asset_id"] == params[0] else [])
|
||||
if sql.startswith("SELECT pg_advisory"):
|
||||
self.assert_tx(); return Result([])
|
||||
if sql.startswith("SELECT count(*) AS n FROM asset_photos"):
|
||||
return Result([{"n":sum(p["asset_id"] == params[0] for p in self.photos.values())}])
|
||||
if sql.startswith("INSERT INTO asset_photos"):
|
||||
self.photos[params[0]] = dict(zip(("id","asset_id","filename","image","mime","width","height","actor"),params))
|
||||
return Result([])
|
||||
if sql.startswith("INSERT INTO asset_monitor_links"):
|
||||
self.links[tuple(params[:2])] = params[2]; return Result([])
|
||||
if sql.startswith("UPDATE assets SET version="):
|
||||
self.assets[params[0]]["version"] += 1; return Result([])
|
||||
if sql.startswith("UPDATE assets SET deleted_at="):
|
||||
self.assets[params[1]].update(deleted_at="deleted",deleted_by=params[0])
|
||||
self.assets[params[1]]["version"] += 1; return Result([])
|
||||
return super().execute(sql,params)
|
||||
|
||||
|
||||
class FeatureStoreTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.conn=FeatureConnection(); self.store=object.__new__(AssetStore);self.store._pool=fixtures.Pool(self.conn)
|
||||
self.computer=self.store.create(AssetInput(name="PC",category="computer"),"actor")
|
||||
self.parsed=monitor_report()
|
||||
self.report=self.store.attach_report(self.computer,1,"actor","report.xml",report_xml(),self.parsed)
|
||||
|
||||
def monitor_payload(self, **kwargs):
|
||||
return MonitorInput(version=self.conn.assets[self.computer]["version"],report_id=self.report,**kwargs)
|
||||
|
||||
def test_registration_connects_and_prevents_duplicates(self):
|
||||
target=self.store.register_monitor(self.computer,0,self.monitor_payload(asset=AssetInput(name="Monitor",category="monitor",model="Display 24")),"actor")
|
||||
self.assertEqual(self.conn.assets[target]["serial"],"SN-1")
|
||||
match=self.store._monitor_matches(self.conn,self.computer,self.parsed)[0]
|
||||
self.assertEqual((match["asset"]["id"],match["match"]),(target,"linked"))
|
||||
with self.assertRaises(AssetConflict):
|
||||
self.store.register_monitor(self.computer,0,self.monitor_payload(asset=AssetInput(name="Duplicate",category="monitor")),"actor")
|
||||
self.assertEqual(len(self.conn.assets),2)
|
||||
|
||||
def test_ambiguous_serial_and_model_require_selection(self):
|
||||
for i in range(2): self.store.create(AssetInput(name="Display",category="monitor",model="Display 24",serial="SN-1"),"actor")
|
||||
match=self.store._monitor_matches(self.conn,self.computer,self.parsed)[0]
|
||||
self.assertIsNone(match["asset"]);self.assertEqual(len(match["candidates"]),2)
|
||||
target=match["candidates"][1]["id"]
|
||||
self.store.register_monitor(self.computer,0,self.monitor_payload(asset_id=target),"actor")
|
||||
self.assertEqual(self.store._monitor_matches(self.conn,self.computer,self.parsed)[0]["asset"]["id"],target)
|
||||
unknown=monitor_report("0")
|
||||
match=self.store._monitor_matches(self.conn,"other-computer",unknown)[0]
|
||||
self.assertIsNone(match["asset"]);self.assertEqual(len(match["candidates"]),2)
|
||||
|
||||
def test_same_model_different_serial_can_be_registered(self):
|
||||
# 같은 모델(듀얼 모니터 등)이 이미 있어도 시리얼이 다르면 새 자산으로 등록된다(2026-10-07)
|
||||
other = self.store.create(AssetInput(name="Display", category="monitor", model="Display 24", serial="SN-OTHER"), "actor")
|
||||
match = self.store._monitor_matches(self.conn, self.computer, self.parsed)[0]
|
||||
self.assertIsNone(match["asset"]); self.assertEqual(match["candidate_by"], "model")
|
||||
self.assertEqual([c["id"] for c in match["candidates"]], [other])
|
||||
target = self.store.register_monitor(self.computer, 0, self.monitor_payload(asset=AssetInput(name="Second", category="monitor", model="Display 24")), "actor")
|
||||
self.assertNotEqual(target, other); self.assertEqual(self.conn.assets[target]["serial"], "SN-1")
|
||||
|
||||
def test_same_serial_still_blocks_new_registration(self):
|
||||
self.store.create(AssetInput(name="Other", category="monitor", serial="SN-1", model="Different Model", manufacturer="Another"), "actor")
|
||||
self.assertEqual(self.store._monitor_matches(self.conn, self.computer, self.parsed)[0]["candidate_by"], "serial")
|
||||
with self.assertRaises(AssetConflict):
|
||||
self.store.register_monitor(self.computer, 0, self.monitor_payload(asset=AssetInput(name="Dup", category="monitor")), "actor")
|
||||
|
||||
def test_existing_unique_serial_matches_automatically(self):
|
||||
target=self.store.create(AssetInput(name="Existing",category="monitor",serial="sn-1"),"actor")
|
||||
match=self.store._monitor_matches(self.conn,self.computer,self.parsed)[0]
|
||||
self.assertEqual((match["asset"]["id"],match["match"]),(target,"serial"))
|
||||
|
||||
def test_different_model_same_serial_is_not_auto_linked(self):
|
||||
self.store.create(AssetInput(name="Other",category="monitor",serial="SN-1",model="Different Model",manufacturer="Another"),"actor")
|
||||
match=self.store._monitor_matches(self.conn,self.computer,self.parsed)[0]
|
||||
self.assertIsNone(match["asset"]);self.assertEqual(len(match["candidates"]),1)
|
||||
|
||||
def test_stale_report_and_non_monitor_link_do_not_write(self):
|
||||
before=copy.deepcopy(self.conn.assets)
|
||||
for payload in (MonitorInput(version=2,report_id="old",asset_id=self.computer),MonitorInput(version=1,report_id=self.report,asset_id=self.computer)):
|
||||
with self.assertRaises(AssetConflict): self.store.register_monitor(self.computer,0,payload,"actor")
|
||||
with self.assertRaises(ValueError): self.store.register_monitor(self.computer,0,self.monitor_payload(asset_id=self.computer),"actor")
|
||||
self.assertEqual(before,self.conn.assets);self.assertFalse(self.conn.links)
|
||||
|
||||
def test_link_and_creation_roll_back_if_audit_fails(self):
|
||||
self.conn.fail_event=True
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.store.register_monitor(self.computer,0,self.monitor_payload(asset=AssetInput(name="New",category="monitor")),"actor")
|
||||
self.assertEqual(len(self.conn.assets),1);self.assertFalse(self.conn.links)
|
||||
|
||||
def test_photo_limit_version_and_transaction(self):
|
||||
for i in range(10):
|
||||
self.store.add_photo(self.computer,2+i,"actor","photo.jpg",b"image","image/jpeg",10,10)
|
||||
with self.assertRaises(ValueError): self.store.add_photo(self.computer,12,"actor","photo.jpg",b"image","image/jpeg",10,10)
|
||||
with self.assertRaises(AssetConflict): self.store.add_photo(self.computer,2,"actor","photo.jpg",b"image","image/jpeg",10,10)
|
||||
self.assertEqual(len(self.conn.photos),10)
|
||||
self.conn.photos.clear(); self.conn.fail_event=True
|
||||
with self.assertRaises(RuntimeError): self.store.add_photo(self.computer,12,"actor","photo.jpg",b"image","image/jpeg",10,10)
|
||||
self.assertFalse(self.conn.photos);self.assertEqual(self.conn.assets[self.computer]["version"],12)
|
||||
|
||||
def test_deletion_preserves_reports_and_blocks_later_writes(self):
|
||||
self.store.delete(self.computer,2,"super","Wrong entry")
|
||||
self.assertEqual(len(self.conn.reports),1)
|
||||
self.assertEqual(self.conn.events[-1][2],"delete")
|
||||
with self.assertRaises(KeyError): self.store.delete(self.computer,3,"super","Again")
|
||||
with self.assertRaises(KeyError): self.store.attach_report(self.computer,3,"actor","x.xml",report_xml(),self.parsed)
|
||||
|
||||
|
||||
class MediaTests(unittest.TestCase):
|
||||
def test_images_reencoded_without_exif_and_resized(self):
|
||||
original=Image.new("RGB",(3000,1000),"red");data=io.BytesIO()
|
||||
exif=Image.Exif();exif[271]="Private camera"
|
||||
original.save(data,"JPEG",exif=exif)
|
||||
raw,mime,width,height=prepare_photo(data.getvalue())
|
||||
self.assertEqual((mime,width,height),("image/jpeg",2400,800))
|
||||
with Image.open(io.BytesIO(raw)) as result: self.assertFalse(result.getexif())
|
||||
transparent=io.BytesIO();Image.new("RGBA",(10,10),(0,0,0,0)).save(transparent,"PNG")
|
||||
self.assertEqual(prepare_photo(transparent.getvalue())[1],"image/png")
|
||||
|
||||
def test_fake_svg_oversized_and_large_dimensions_rejected(self):
|
||||
for raw in (b"",b"not a photo",b"<svg/>",b"x"*(MAX_PHOTO_BYTES+1)):
|
||||
with self.assertRaises(ValueError): prepare_photo(raw)
|
||||
raw=io.BytesIO();Image.new("RGB",(5000,5000)).save(raw,"PNG")
|
||||
with self.assertRaises(ValueError): prepare_photo(raw.getvalue())
|
||||
|
||||
def test_unknown_serial_does_not_identify_same_model(self):
|
||||
self.assertEqual(monitor_devices(monitor_report("00000"))[0]["serial"],"")
|
||||
one=monitor_report();two=monitor_report("SN-2")
|
||||
self.assertNotEqual(monitor_devices(one)[0]["key"],monitor_devices(two)[0]["key"])
|
||||
@@ -0,0 +1,41 @@
|
||||
"""실제 앱의 메뉴·권한 화면·자산 라우터 연결을 격리된 환경에서 확인합니다."""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class MainIntegrationTests(unittest.TestCase):
|
||||
def test_registered_module_and_unconfigured_workspace(self):
|
||||
env = dict(os.environ)
|
||||
# 운영 DSN과 런타임 데이터는 사용하지 않습니다.
|
||||
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE", "MALAYSIA_STOCK", "ITEMCODE", "EXPENSE"):
|
||||
env[key + "_DB_URL"] = ""
|
||||
env.update(SESSION_SECRET_KEY="local-asset-test-only", SESSION_COOKIE_SECURE="false")
|
||||
with tempfile.TemporaryDirectory(prefix="asset-integration-") as directory:
|
||||
env["DATA_DIR"] = directory
|
||||
code = '''
|
||||
from unittest.mock import patch
|
||||
from fastapi.testclient import TestClient
|
||||
import app.main as main
|
||||
from app.store import MODULE_KEYS
|
||||
user={"email":"admin@test.local","name":"Admin","role":"admin","is_super_admin":True,"modules":{}}
|
||||
with patch.object(main,"get_current_user_record",return_value=user),patch.object(main,"get_session_user",return_value=user),patch.object(main.user_store,"get",return_value=user),patch.object(main.user_store,"list_all",return_value=[user]):
|
||||
client=TestClient(main.app)
|
||||
for path in ("/","/admin","/asset/"):
|
||||
result=client.get(path)
|
||||
assert result.status_code == 200,(path,result.status_code)
|
||||
assert main.MODULE_LABELS["asset"] in result.text,path
|
||||
assert client.get("/asset/health").status_code == 503
|
||||
assert "asset" in MODULE_KEYS
|
||||
assert any(x["key"] == "asset" and x["active"] for x in main.build_erp_nav(user,active="asset"))
|
||||
print("Real app menu/admin/workspace registration OK")
|
||||
'''
|
||||
result = subprocess.run([sys.executable, "-c", code], cwd=Path(__file__).resolve().parents[1], env=env,
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=45)
|
||||
self.assertEqual(result.returncode, 0, result.stdout + result.stderr)
|
||||
|
||||
|
||||
if __name__ == "__main__": unittest.main()
|
||||
@@ -0,0 +1,80 @@
|
||||
"""프로젝트는 멤버(owner 포함)만 — 관리자도 멤버가 아니면 안 보인다, 예외는 슈퍼관리자(2026-10-07). DB 없이."""
|
||||
import importlib
|
||||
import sys
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.project import access
|
||||
from app.store import SUPER_ADMIN_EMAIL
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
|
||||
ADMIN = {"email": "admin@test.local", "role": "admin"}
|
||||
SUPER = {"email": SUPER_ADMIN_EMAIL, "role": "admin"}
|
||||
MEMBER = {"email": "bob@test.local", "role": "user"}
|
||||
|
||||
|
||||
class FakeStore:
|
||||
"""프로젝트 1 = bob 멤버, 2 = admin 멤버. list_projects(member_email) 는 그 사람이 owner·멤버인 것만."""
|
||||
members = {1: {"bob@test.local"}, 2: {"admin@test.local"}}
|
||||
|
||||
def __init__(self):
|
||||
self.member_email_asked = "unset"
|
||||
|
||||
def is_member(self, project_id, user_email):
|
||||
return user_email in self.members.get(project_id, set())
|
||||
|
||||
def list_projects(self, include_archived=False, member_email=None):
|
||||
self.member_email_asked = member_email
|
||||
return [{"id": pid, "parent_id": None, "name": f"P{pid}"} for pid, ms in self.members.items()
|
||||
if member_email is None or member_email in ms]
|
||||
|
||||
|
||||
class MembersOnlyTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.st = FakeStore()
|
||||
p = patch.object(access, "can_use_module", side_effect=lambda u: bool(u))
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
|
||||
def test_admin_sees_only_member_projects(self):
|
||||
self.assertFalse(access.can_manage_project(self.st, ADMIN, 1))
|
||||
self.assertTrue(access.can_manage_project(self.st, ADMIN, 2))
|
||||
self.assertEqual(access.visible_project_ids(self.st, ADMIN), {2})
|
||||
self.assertFalse(access.sees_all_projects(ADMIN))
|
||||
|
||||
def test_member_and_super_admin(self):
|
||||
self.assertTrue(access.can_manage_project(self.st, MEMBER, 1))
|
||||
self.assertFalse(access.can_manage_project(self.st, MEMBER, 2))
|
||||
self.assertTrue(access.can_manage_project(self.st, SUPER, 1))
|
||||
self.assertIsNone(access.visible_project_ids(self.st, SUPER)) # 전체
|
||||
self.assertTrue(access.sees_all_projects(SUPER))
|
||||
|
||||
def test_sidebar_list_is_member_only_for_admin(self):
|
||||
self.assertEqual([p["id"] for p in api._nav_projects(self.st, ADMIN, True)], [2])
|
||||
self.assertEqual(self.st.member_email_asked, "admin@test.local")
|
||||
self.assertEqual(sorted(p["id"] for p in api._nav_projects(self.st, SUPER, True)), [1, 2])
|
||||
self.assertIsNone(self.st.member_email_asked)
|
||||
|
||||
def test_project_list_api_is_member_only_for_admin(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
client = TestClient(app)
|
||||
with patch.object(api, "_require_user", return_value=ADMIN), patch.object(api, "_db_or_503", return_value=self.st):
|
||||
r = client.get("/project/api/projects")
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
self.assertEqual([p["id"] for p in r.json()["projects"]], [2])
|
||||
|
||||
def test_trash_is_filtered_to_member_projects(self):
|
||||
st = SimpleNamespace(list_trash=lambda: [{"id": 7, "project_id": 1}, {"id": 8, "project_id": 2}],
|
||||
**{k: getattr(self.st, k) for k in ("is_member", "list_projects")})
|
||||
self.assertEqual([t["id"] for t in api._visible_trash(st, ADMIN)], [8])
|
||||
self.assertEqual([t["id"] for t in api._visible_trash(st, SUPER)], [7, 8])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,117 @@
|
||||
"""알림 팝업 API — 기준점·태그/배정만·읽지 않은 것·after 이후·오래된 것부터. DB 없이 가짜 저장소로."""
|
||||
import importlib
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
|
||||
ROWS = [ # 최신순(list_notifications 와 같게)
|
||||
{"id": 9, "type": "completed", "title": "완료", "is_read": False, "task_id": 1, "project_id": 1},
|
||||
{"id": 8, "type": "mention", "title": "나를 태그함: A", "is_read": False, "task_id": 1, "project_id": 1},
|
||||
{"id": 7, "type": "assigned", "title": "작업 배정: B", "is_read": True, "task_id": 2, "project_id": 1},
|
||||
{"id": 6, "type": "assigned", "title": "작업 배정: C", "is_read": False, "task_id": 3, "project_id": 1},
|
||||
{"id": 2, "type": "assigned", "title": "작업 배정: 옛것", "is_read": False, "task_id": 4, "project_id": 1},
|
||||
]
|
||||
|
||||
|
||||
class FakeStore:
|
||||
"""list_notifications(최신순) + list_unread_after(DB 쪽 조건·오래된 것부터) — db.py 와 같은 의미."""
|
||||
desktop = False
|
||||
|
||||
def __init__(self, rows=None):
|
||||
self.rows = list(ROWS if rows is None else rows)
|
||||
self.pages = 0
|
||||
|
||||
def notifier_active(self, email):
|
||||
return self.desktop
|
||||
|
||||
def list_notifications(self, recipient_email, unread_only=False, limit=100):
|
||||
rows = sorted((r for r in self.rows if not unread_only or not r["is_read"]), key=lambda r: -r["id"])
|
||||
return rows[:limit]
|
||||
|
||||
def list_unread_after(self, recipient_email, after_id, types, limit=200):
|
||||
self.pages += 1
|
||||
rows = sorted((r for r in self.rows if not r["is_read"] and r["id"] > after_id and r["type"] in types),
|
||||
key=lambda r: r["id"])
|
||||
return rows[:limit]
|
||||
|
||||
|
||||
class AlertsApiTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
self.client = TestClient(app)
|
||||
|
||||
def get(self, qs="", desktop=False, st=None, visible=None):
|
||||
st = st or FakeStore()
|
||||
st.desktop = desktop
|
||||
vis = visible or (lambda st, user, items: items)
|
||||
with patch.object(api, "_require_user", return_value={"email": "Me@Test.local"}), \
|
||||
patch.object(api, "_db_or_503", return_value=st), \
|
||||
patch.object(api, "_visible_notifications", side_effect=vis):
|
||||
return self.client.get("/project/api/notifications/alerts" + qs).json()
|
||||
|
||||
def test_without_after_returns_only_baseline(self):
|
||||
out = self.get()
|
||||
self.assertEqual((out["me"], out["latest_id"], out["alerts"]), ("me@test.local", 9, []))
|
||||
|
||||
def test_after_returns_unread_mentions_and_assignments_oldest_first(self):
|
||||
out = self.get("?after=5")
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8]) # 완료 알림(9)·읽은 것(7)·옛것(2) 제외
|
||||
self.assertEqual(out["alerts"][1]["type"], "mention")
|
||||
self.assertNotIn("desktop", out)
|
||||
|
||||
def test_alert_links_use_task_permalink(self):
|
||||
# 작업 알림은 /project/t/{id} — 연결된 프로젝트에서만 읽을 수 있는 사람도 403 없이 열린다
|
||||
out = self.get("?after=5")
|
||||
self.assertEqual([a["href"] for a in out["alerts"]], ["/project/t/3", "/project/t/1"])
|
||||
st = FakeStore([{"id": 3, "type": "mention", "is_read": False, "task_id": None, "project_id": 4}])
|
||||
self.assertEqual(self.get("?after=0", st=st)["alerts"][0]["href"], "/project/p/4")
|
||||
|
||||
def test_pc_notifier_running_silences_web_popup(self):
|
||||
out = self.get("?after=5", desktop=True)
|
||||
self.assertEqual((out["alerts"], out["latest_id"], out["desktop"]), ([], 9, True))
|
||||
|
||||
def test_notifier_check_failure_keeps_web_popup(self):
|
||||
class Broken(FakeStore):
|
||||
def notifier_active(self, email):
|
||||
raise RuntimeError("db down")
|
||||
out = self.get("?after=5", st=Broken())
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [6, 8])
|
||||
|
||||
# ── 예전엔 최신 50건을 자른 뒤 걸러서 빠지던 경우들 ──
|
||||
def test_assignment_behind_fifty_comment_alerts_is_not_lost(self):
|
||||
rows = [{"id": 1, "type": "assigned", "title": "배정", "is_read": False, "task_id": 1, "project_id": 1}]
|
||||
rows += [{"id": 100 + i, "type": "comment", "title": "댓글", "is_read": False, "task_id": 1, "project_id": 1}
|
||||
for i in range(50)]
|
||||
out = self.get("?after=0", st=FakeStore(rows))
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [1])
|
||||
|
||||
def test_more_than_sixty_assignments_page_oldest_first(self):
|
||||
rows = [{"id": i, "type": "assigned", "title": f"배정{i}", "is_read": False, "task_id": i, "project_id": 1}
|
||||
for i in range(1, 66)]
|
||||
st = FakeStore(rows)
|
||||
out = self.get("?after=0", st=st)
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], list(range(1, 11))) # 오래된 것부터 10건
|
||||
out = self.get("?after=10", st=st) # 닫으면 그 뒤 것(화면이 본 것=10 으로 다시 묻는다)
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], list(range(11, 21)))
|
||||
out = self.get("?after=60", st=st)
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [61, 62, 63, 64, 65])
|
||||
|
||||
def test_invisible_alerts_ahead_do_not_hide_visible_ones(self):
|
||||
# 앞쪽 450건은 지금 볼 수 없는 작업(권한 회수) — 페이지를 넘겨 그 뒤의 볼 수 있는 알림을 찾는다
|
||||
rows = [{"id": i, "type": "mention", "title": "x", "is_read": False, "task_id": 9, "project_id": 9}
|
||||
for i in range(1, 451)]
|
||||
rows.append({"id": 500, "type": "mention", "title": "보임", "is_read": False, "task_id": 1, "project_id": 1})
|
||||
st = FakeStore(rows)
|
||||
out = self.get("?after=0", st=st,
|
||||
visible=lambda st, user, items: [n for n in items if n["project_id"] == 1])
|
||||
self.assertEqual([a["id"] for a in out["alerts"]], [500])
|
||||
self.assertEqual(st.pages, 3) # 200·200·51 — 끝까지 읽고 멈춘다
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,75 @@
|
||||
"""대시보드 담당자별 작업 합계 — 하위 작업 요약 API(subtasks-summary) 범위·권한. DB 없이 가짜 저장소로."""
|
||||
import importlib
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
|
||||
|
||||
class FakeStore:
|
||||
def __init__(self):
|
||||
self.asked_projects, self.asked_parents = None, None
|
||||
|
||||
def list_projects(self, include_archived, member_email):
|
||||
return [{"id": 1, "parent_id": None}, {"id": 2, "parent_id": None}, {"id": 5, "parent_id": 1}]
|
||||
|
||||
def get_project(self, project_id):
|
||||
# 7 = 보관된 프로젝트(활성 목록에 없음), 5 = 서브프로젝트
|
||||
return {"id": project_id, "parent_id": 1 if project_id == 5 else None,
|
||||
"status": "archived" if project_id == 7 else "active"}
|
||||
|
||||
def list_tasks_for_projects(self, project_ids):
|
||||
self.asked_projects = project_ids
|
||||
return [{"id": 10 * pid} for pid in project_ids]
|
||||
|
||||
def list_subtasks_of(self, parent_ids):
|
||||
self.asked_parents = parent_ids
|
||||
return [{"parent_task_id": parent_ids[0], "assignee_email": "a@test", "assignee_name": "A", "done": True}]
|
||||
|
||||
|
||||
class SubtaskSummaryTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
self.client = TestClient(app)
|
||||
self.st = FakeStore()
|
||||
|
||||
def call(self, scope, pid=1):
|
||||
with patch.object(api, "_require_user", return_value={"email": "me@test", "role": "pro"}), \
|
||||
patch.object(api, "_db_or_503", return_value=self.st), \
|
||||
patch.object(api, "_require_manage", return_value=None), \
|
||||
patch.object(api, "_accessible_project_ids", return_value=None):
|
||||
return self.client.get(f"/project/api/projects/{pid}/subtasks-summary?scope={scope}")
|
||||
|
||||
def test_project_scope_uses_only_this_project(self):
|
||||
r = self.call("project")
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
self.assertEqual(self.st.asked_projects, [1])
|
||||
self.assertEqual(self.st.asked_parents, [10])
|
||||
self.assertEqual(r.json()["subtasks"][0]["done"], True)
|
||||
|
||||
def test_all_scope_uses_top_level_projects(self):
|
||||
self.call("all")
|
||||
self.assertEqual(self.st.asked_projects, [1, 2]) # 서브프로젝트(5) 제외 — 스냅샷과 같은 범위
|
||||
|
||||
def test_all_scope_adds_open_archived_or_subproject_only(self):
|
||||
# 지금 연 프로젝트가 보관(7)·서브프로젝트(5)면 그 하나만 더한다(다른 보관 프로젝트는 읽지 않는다)
|
||||
self.call("all", pid=7)
|
||||
self.assertEqual(self.st.asked_projects, [1, 2, 7])
|
||||
self.call("all", pid=5)
|
||||
self.assertEqual(self.st.asked_projects, [1, 2, 5])
|
||||
|
||||
def test_no_access_is_rejected(self):
|
||||
with patch.object(api, "_require_user", return_value={"email": "me@test", "role": "pro"}), \
|
||||
patch.object(api, "_db_or_503", return_value=self.st), \
|
||||
patch.object(api, "_require_manage", side_effect=HTTPException(403)):
|
||||
self.assertEqual(self.client.get("/project/api/projects/1/subtasks-summary").status_code, 403)
|
||||
self.assertIsNone(self.st.asked_parents)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -1,6 +1,8 @@
|
||||
import json
|
||||
import unittest
|
||||
from types import SimpleNamespace
|
||||
from app.modules.project import store
|
||||
from app.modules.project.router import _month_plan
|
||||
|
||||
|
||||
def rich(runs):
|
||||
@@ -8,6 +10,40 @@ def rich(runs):
|
||||
|
||||
|
||||
class GoalRichTextTests(unittest.TestCase):
|
||||
def test_summary_keeps_all_styles_except_font_size(self):
|
||||
body = rich([{"text": "<계획>\n 다음 줄", "bold": True, "italic": True,
|
||||
"underline": True, "color": "#DC2626", "size": 32},
|
||||
{"text": " 해제", "bold": False, "italic": False,
|
||||
"underline": False, "size": 10}])
|
||||
html = store.goal_text_html(body, include_size=False)
|
||||
for style in ("font-weight:700", "font-style:italic", "text-decoration:underline",
|
||||
"color:#dc2626", "font-weight:400", "font-style:normal", "text-decoration:none"):
|
||||
self.assertIn(style, html)
|
||||
self.assertIn("<계획>\n 다음 줄", html)
|
||||
self.assertNotIn("font-size", html)
|
||||
self.assertIn("font-size:32px", store.goal_text_html(body))
|
||||
self.assertIn("font-size:10px", store.goal_text_html(body))
|
||||
|
||||
def test_month_plan_preserves_formatted_merged_cells_and_literal_legacy_text(self):
|
||||
body = rich([{"text": "<img src=x onerror=alert(1)>\n 계획", "bold": True,
|
||||
"italic": True, "underline": True, "color": "#2563EB", "size": 24}])
|
||||
rows = [{"label": "인플", "cells": {7: body}, "merges": {7: (3, 2)}},
|
||||
{"label": "숨긴 줄", "cells": {}, "merges": {}},
|
||||
{"label": "쿠팡", "cells": {9: "<b>평문</b>"}, "merges": {}},
|
||||
{"label": "빈 칸", "cells": {9: rich([{"text": " ", "bold": True}])}, "merges": {}}]
|
||||
fake = SimpleNamespace(goals_enabled=lambda: True,
|
||||
get_goal_board=lambda **kw: {"areas": [{"name": "유통", "color": "#cdebf8", "rows": rows}]})
|
||||
plans = _month_plan(fake, 2026, 9)
|
||||
lines = plans[0]["lines"]
|
||||
self.assertEqual(len(lines), 2)
|
||||
self.assertEqual(lines[0]["range"], "7~9월")
|
||||
self.assertEqual(lines[0]["text"], store.goal_text_plain(body))
|
||||
self.assertEqual(lines[0]["text_html"], store.goal_text_html(body, include_size=False))
|
||||
self.assertNotIn("<img", lines[0]["text_html"])
|
||||
self.assertNotIn("font-size", lines[0]["text_html"])
|
||||
self.assertEqual(lines[1]["text_html"], "<b>평문</b>")
|
||||
self.assertEqual(rows[0]["cells"][7], body)
|
||||
|
||||
def test_selected_styles_are_safe_and_legacy_text_stays_literal(self):
|
||||
body = rich([{"text": "<img src=x onerror=alert(1)>", "bold": True,
|
||||
"color": "#FF0000", "size": 20, "onclick": "alert(1)"},
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
"""아사나 아이콘 값 검증 · 설명란 글자 색/크기 sanitize (2026-10-08)."""
|
||||
import importlib
|
||||
import unittest
|
||||
|
||||
store = importlib.import_module("app.modules.project.store")
|
||||
|
||||
|
||||
class ProjectIconTests(unittest.TestCase):
|
||||
def test_basic_and_asana_icons_accepted(self):
|
||||
self.assertEqual(store.validate_project_icon("rocket_launch"), "rocket_launch")
|
||||
self.assertEqual(store.validate_project_icon("asana:rocket_launch"), "asana:rocket_launch")
|
||||
|
||||
def test_unknown_or_malformed_rejected(self):
|
||||
for v in ("asana:", "asana:nope", "asana:asana:rocket_launch", "nope", "Asana:rocket_launch", ""):
|
||||
self.assertIsNone(store.validate_project_icon(v), v)
|
||||
|
||||
|
||||
class DescStyleTests(unittest.TestCase):
|
||||
def clean(self, html):
|
||||
return store.sanitize_description_html(html)
|
||||
|
||||
def test_color_and_allowed_size_kept(self):
|
||||
out = self.clean('<span style="color: rgb(224, 62, 62); font-size: 22px">a</span><span style="color:#ABC">b</span>')
|
||||
self.assertEqual(out, '<span style="color: rgb(224, 62, 62); font-size: 22px">a</span><span style="color: #abc">b</span>')
|
||||
|
||||
def test_other_declarations_and_sizes_dropped(self):
|
||||
out = self.clean('<span style="background:url(javascript:x); font-size: 99px; color: red; position:fixed">a</span>')
|
||||
self.assertEqual(out, "<span>a</span>")
|
||||
|
||||
def test_style_injection_attempts_dropped(self):
|
||||
out = self.clean('<span style="color: #fff;}body{display:none">a</span>'
|
||||
'<span style="color: expression(alert(1))">b</span>')
|
||||
# 선언을 다시 조립하므로 "}body{…" 같은 나머지는 사라지고 검증된 색만 남는다
|
||||
self.assertEqual(out, '<span style="color: #fff">a</span><span>b</span>')
|
||||
|
||||
def test_style_only_on_plain_span(self):
|
||||
self.assertEqual(self.clean('<p style="color:#fff">a</p>'), "<p>a</p>")
|
||||
self.assertEqual(self.clean('<span class="pj-mention" data-email="a@b.c" style="color:#fff">@a</span>'),
|
||||
'<span class="pj-mention" data-email="a@b.c">@a</span>')
|
||||
self.assertEqual(self.clean('<font color="#ff0000">a</font>'), "a")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,121 @@
|
||||
"""회의록 보드(Google 슬라이드) — 가짜 Drive·Slides 로 찾기·빈 슬라이드 만들기·API 를 검증한다. 네트워크·DB 없이 실행."""
|
||||
import importlib
|
||||
import unittest
|
||||
from datetime import date
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.integrations import google_slides as gs
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
|
||||
|
||||
class Call:
|
||||
def __init__(self, result):
|
||||
self.result = result
|
||||
|
||||
def execute(self):
|
||||
return self.result
|
||||
|
||||
|
||||
class FakeDrive:
|
||||
def __init__(self, existing=None):
|
||||
self.existing, self.created, self.queries = existing, [], []
|
||||
|
||||
def files(self):
|
||||
return self
|
||||
|
||||
def list(self, **kw):
|
||||
self.queries.append(kw)
|
||||
return Call({"files": [{"id": self.existing}] if self.existing else []})
|
||||
|
||||
def create(self, body, fields, supportsAllDrives):
|
||||
assert supportsAllDrives is True
|
||||
self.created.append(body)
|
||||
return Call({"id": "new-file"})
|
||||
|
||||
|
||||
class FakeSlides:
|
||||
def __init__(self):
|
||||
self.batches = []
|
||||
|
||||
def presentations(self):
|
||||
return self
|
||||
|
||||
def get(self, presentationId, fields):
|
||||
return Call({"slides": [{"objectId": "title-slide"}]})
|
||||
|
||||
def batchUpdate(self, presentationId, body):
|
||||
self.batches.append((presentationId, body))
|
||||
return Call({})
|
||||
|
||||
|
||||
def client_with(drive, slides):
|
||||
c = gs.GoogleSlidesClient.__new__(gs.GoogleSlidesClient)
|
||||
c.enabled, c.reason, c.auth_mode = True, "", "oauth"
|
||||
c._drive, c._slides = drive, slides
|
||||
return c
|
||||
|
||||
|
||||
class MeetingBoardTests(unittest.TestCase):
|
||||
def test_existing_board_is_reused_without_creating(self):
|
||||
drive, slides = FakeDrive(existing="abc"), FakeSlides()
|
||||
out = client_with(drive, slides).open_week_board(folder_id="F", week_key="2026-10-05", title="10월 2주차 (10/5~10/11)")
|
||||
self.assertEqual(out, {"id": "abc", "url": "https://docs.google.com/presentation/d/abc/edit", "created": False})
|
||||
self.assertEqual(drive.created, [])
|
||||
q = drive.queries[0]["q"]
|
||||
self.assertIn("'F' in parents", q)
|
||||
self.assertIn("key='dbxMeetingWeek' and value='2026-10-05'", q)
|
||||
self.assertTrue(drive.queries[0]["supportsAllDrives"] and drive.queries[0]["includeItemsFromAllDrives"])
|
||||
|
||||
def test_new_board_is_blank_slide_in_folder(self):
|
||||
drive, slides = FakeDrive(), FakeSlides()
|
||||
out = client_with(drive, slides).open_week_board(folder_id="F", week_key="2026-10-05", title="10월 2주차 (10/5~10/11)")
|
||||
self.assertTrue(out["created"])
|
||||
body = drive.created[0]
|
||||
self.assertEqual(body["parents"], ["F"])
|
||||
self.assertEqual(body["name"], "10월 2주차 (10/5~10/11)")
|
||||
self.assertEqual(body["mimeType"], gs.PRESENTATION_MIME)
|
||||
self.assertEqual(body["appProperties"], {"dbxMeetingWeek": "2026-10-05"})
|
||||
# 제목·부제목 틀이 있는 첫 장은 지우고 틀 없는 빈 장(BLANK) 하나만
|
||||
reqs = slides.batches[0][1]["requests"]
|
||||
self.assertEqual(reqs[0]["createSlide"]["slideLayoutReference"], {"predefinedLayout": "BLANK"})
|
||||
self.assertEqual(reqs[1:], [{"deleteObject": {"objectId": "title-slide"}}])
|
||||
|
||||
def test_disabled_client_and_api_errors_have_safe_messages(self):
|
||||
off = gs.GoogleSlidesClient.__new__(gs.GoogleSlidesClient)
|
||||
off.enabled, off.reason = False, "Google 인증 미설정"
|
||||
with self.assertRaises(gs.GoogleSlidesError):
|
||||
off.open_week_board(folder_id="F", week_key="2026-10-05", title="t")
|
||||
self.assertIn("토큰을 다시 발급", gs._friendly(RuntimeError("invalid_scope: Bad Request")))
|
||||
self.assertIn("OAuth 클라이언트", gs._friendly(RuntimeError("('unauthorized_client: Unauthorized', {'error': 'unauthorized_client'})")))
|
||||
self.assertIn("만료·폐기", gs._friendly(RuntimeError("('invalid_grant: Bad Request', {})")))
|
||||
|
||||
def test_title_uses_month_week_and_period(self):
|
||||
self.assertEqual(api.meeting_board_title(date(2026, 10, 5)), "10월 2주차 (10/5~10/11)")
|
||||
self.assertEqual(api.meeting_board_title(date(2026, 11, 1)), "11월 1주차 (11/1~11/8)")
|
||||
|
||||
def test_api_returns_url_and_maps_errors(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
client = TestClient(app)
|
||||
fake = client_with(FakeDrive(existing="abc"), FakeSlides())
|
||||
with patch.object(api, "_require_user", return_value={"email": "u@test"}), \
|
||||
patch.object(gs, "get_client", return_value=fake):
|
||||
r = client.post("/project/api/goals/meetings/2026-10-05/board")
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
self.assertEqual(r.json()["url"], "https://docs.google.com/presentation/d/abc/edit")
|
||||
self.assertEqual(client.post("/project/api/goals/meetings/2026-10-06/board").status_code, 400) # 주차 시작일 아님
|
||||
off = gs.GoogleSlidesClient.__new__(gs.GoogleSlidesClient)
|
||||
off.enabled, off.reason = False, "Google 인증 미설정"
|
||||
with patch.object(api, "_require_user", return_value={"email": "u@test"}), \
|
||||
patch.object(gs, "get_client", return_value=off):
|
||||
r = client.post("/project/api/goals/meetings/2026-10-05/board")
|
||||
self.assertEqual(r.status_code, 503)
|
||||
self.assertIn("Google 인증 미설정", r.json()["detail"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,276 @@
|
||||
"""회의록 실제 저장소/API의 권한·충돌·롤백·병합 글 보존을 DB 연결 없이 검증한다."""
|
||||
import copy
|
||||
import importlib
|
||||
import json
|
||||
import unittest
|
||||
from contextlib import contextmanager
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.project import store
|
||||
from app.modules.project.db import ProjectStore
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
|
||||
|
||||
class Result:
|
||||
def __init__(self, rows=()):
|
||||
self.rows = list(rows)
|
||||
|
||||
def fetchone(self):
|
||||
return self.rows[0] if self.rows else None
|
||||
|
||||
def fetchall(self):
|
||||
return self.rows
|
||||
|
||||
|
||||
class Connection:
|
||||
def __init__(self):
|
||||
self.rows = {}
|
||||
for n in range(1, 5):
|
||||
self.rows[n] = dict(id=n, week_start=date(2026, 9, 28), section="상품" if n < 4 else "유통",
|
||||
section_color="", label=f"줄{n}", content="원본" if n == 1 else "대상" if n == 2 else "",
|
||||
content_row_span=1, target_amount=100 * n, result_amount=None, status="",
|
||||
marketplace_code="", carry_from=None, sort_order=n)
|
||||
self.calls, self.depth, self.locked = [], 0, False
|
||||
self.writes, self.fail_write, self.rollbacks = 0, None, 0
|
||||
|
||||
@contextmanager
|
||||
def transaction(self):
|
||||
before = copy.deepcopy(self.rows)
|
||||
self.depth += 1
|
||||
try:
|
||||
yield
|
||||
except Exception:
|
||||
self.rows = before
|
||||
self.rollbacks += 1
|
||||
raise
|
||||
finally:
|
||||
self.depth -= 1
|
||||
self.locked = False
|
||||
|
||||
def execute(self, sql, params):
|
||||
self.calls.append((sql, params))
|
||||
if sql == "SELECT week_start FROM goal_meeting_items WHERE id = %s":
|
||||
return Result([copy.deepcopy(self.rows[params[0]])] if params[0] in self.rows else [])
|
||||
if sql.startswith("SELECT week_start FROM goal_meetings"):
|
||||
assert self.depth > 0
|
||||
self.locked = True
|
||||
return Result([{"week_start": params[0]}])
|
||||
if sql.startswith("SELECT id, week_start") and "FROM goal_meeting_items" in sql:
|
||||
return Result(copy.deepcopy(r) for r in self.rows.values() if r["week_start"] == params[0])
|
||||
if sql.startswith("UPDATE goal_meeting_items SET"):
|
||||
assert self.locked and self.depth > 0, "Every cell write must hold the meeting lock until commit"
|
||||
self.writes += 1
|
||||
if self.writes == self.fail_write:
|
||||
raise RuntimeError("second write failed")
|
||||
item = self.rows[params[-1]]
|
||||
if "content_row_span = 1," in sql:
|
||||
item["content_row_span"] = 1
|
||||
keys = [s.strip().split(" = ")[0] for s in sql.split(" SET ")[1].split(" WHERE ")[0].split(",") if "%s" in s]
|
||||
item.update(zip(keys, params[:-1]))
|
||||
return Result([copy.deepcopy(item)])
|
||||
raise AssertionError(sql)
|
||||
|
||||
|
||||
class MeetingCellTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.conn = Connection()
|
||||
|
||||
@contextmanager
|
||||
def connection():
|
||||
yield self.conn
|
||||
|
||||
self.st = ProjectStore.__new__(ProjectStore)
|
||||
self.st._pool = SimpleNamespace(connection=connection)
|
||||
self.st._table_exists = lambda conn, name: True
|
||||
self.st._column_exists = lambda conn, table, col: col == "content_row_span"
|
||||
self.payload = dict(source_item=1, target_item=2, source_body="원본", target_body="대상", updated_by="ADMIN@TEST.LOCAL")
|
||||
|
||||
def test_atomic_move_preserves_rich_text_and_numeric_values(self):
|
||||
rich = store.validate_goal_text(store.GOAL_RICH_PREFIX + json.dumps([
|
||||
dict(text="서식", bold=True, italic=True, underline=True, color="#dc2626", size=24)]))
|
||||
self.conn.rows[1]["content"] = rich
|
||||
self.assertEqual(self.st.move_meeting_cell(**(self.payload | {"source_body": rich})), rich)
|
||||
self.assertEqual(self.conn.rows[1]["content"], "")
|
||||
self.assertEqual(self.conn.rows[2]["content"], rich)
|
||||
self.assertEqual(self.conn.rows[2]["target_amount"], 200)
|
||||
self.assertEqual(self.conn.rows[2]["updated_by"], "admin@test.local")
|
||||
self.assertEqual(self.st.move_meeting_cell(**(self.payload | {"source_body": rich})), rich)
|
||||
self.assertEqual(self.conn.writes, 2, "Lost-response retry must not rewrite cells")
|
||||
|
||||
def test_second_write_failure_rolls_back_both_cells(self):
|
||||
before = copy.deepcopy(self.conn.rows)
|
||||
self.conn.fail_write = 2
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.st.move_meeting_cell(**self.payload)
|
||||
self.assertEqual(self.conn.rows, before)
|
||||
self.assertEqual(self.conn.rollbacks, 1)
|
||||
|
||||
def test_equivalent_rich_runs_match_editor_and_empty_move_is_rejected(self):
|
||||
rich = store.GOAL_RICH_PREFIX + json.dumps([dict(text="원", bold=True), dict(text="본", bold=True)])
|
||||
expected = store.validate_meeting_content(rich)
|
||||
self.conn.rows[1]["content"] = rich
|
||||
self.assertEqual(self.st.move_meeting_cell(**(self.payload | {"source_body": expected})), expected)
|
||||
self.assertEqual(self.conn.rows[2]["content"], expected)
|
||||
before = copy.deepcopy(self.conn.rows)
|
||||
with self.assertRaises(ValueError):
|
||||
self.st.move_meeting_cell(**(self.payload | {"source_body": ""}))
|
||||
self.assertEqual(self.conn.rows, before)
|
||||
|
||||
def test_stale_source_or_target_never_overwrites(self):
|
||||
for item in (1, 2):
|
||||
with self.subTest(item=item):
|
||||
self.setUp()
|
||||
self.conn.rows[item]["content"] = "다른 창에서 변경"
|
||||
before = copy.deepcopy(self.conn.rows)
|
||||
with self.assertRaises(store.GoalCellConflict):
|
||||
self.st.move_meeting_cell(**self.payload)
|
||||
self.assertEqual(self.conn.rows, before)
|
||||
|
||||
def test_different_week_and_hidden_cells_cannot_be_written(self):
|
||||
self.conn.rows[2]["week_start"] = date(2026, 9, 21)
|
||||
with self.assertRaises(KeyError):
|
||||
self.st.move_meeting_cell(**self.payload)
|
||||
self.conn.rows[2]["week_start"] = date(2026, 9, 28)
|
||||
self.conn.rows[1]["content_row_span"] = 2
|
||||
with self.assertRaises(store.GoalCellConflict):
|
||||
self.st.move_meeting_cell(**self.payload)
|
||||
with self.assertRaises(store.GoalCellConflict):
|
||||
self.st.update_meeting_item(item_id=2, fields={"content": "hidden"})
|
||||
|
||||
def test_merge_unmerge_preserves_all_text_and_formats(self):
|
||||
self.conn.rows[1]["content"] = store.validate_goal_text(store.GOAL_RICH_PREFIX + json.dumps([dict(text="원본", bold=True)]))
|
||||
out = self.st.merge_meeting_cells(item_from=1, item_to=3)
|
||||
self.assertEqual(out["row_span"], 3)
|
||||
self.assertEqual(store.goal_text_plain(out["body"]), "원본\n대상")
|
||||
self.assertTrue(store.goal_text_runs(out["body"])[0]["bold"])
|
||||
self.assertEqual([self.conn.rows[n]["content"] for n in (2, 3)], ["", ""])
|
||||
self.st.unmerge_meeting_cell(item_id=1)
|
||||
self.assertEqual(self.conn.rows[1]["content_row_span"], 1)
|
||||
self.assertEqual(self.conn.rows[1]["content"], out["body"])
|
||||
|
||||
def test_merge_validation_and_rollback(self):
|
||||
for endpoint in (1, 4):
|
||||
with self.subTest(endpoint=endpoint), self.assertRaises(ValueError):
|
||||
self.st.merge_meeting_cells(item_from=1, item_to=endpoint)
|
||||
before = copy.deepcopy(self.conn.rows)
|
||||
self.conn.fail_write = 2
|
||||
with self.assertRaises(RuntimeError):
|
||||
self.st.merge_meeting_cells(item_from=1, item_to=3)
|
||||
self.assertEqual(self.conn.rows, before)
|
||||
|
||||
def test_existing_merge_must_be_selected_whole(self):
|
||||
self.st.merge_meeting_cells(item_from=1, item_to=2)
|
||||
with self.assertRaises(store.GoalCellConflict):
|
||||
self.st.merge_meeting_cells(item_from=2, item_to=3)
|
||||
self.assertEqual(self.st.merge_meeting_cells(item_from=1, item_to=3)["row_span"], 3)
|
||||
|
||||
def test_merged_rows_require_unmerge_before_delete_or_reorder(self):
|
||||
self.st.merge_meeting_cells(item_from=1, item_to=2)
|
||||
with self.assertRaises(ValueError):
|
||||
self.st.delete_meeting_item(item_id=1)
|
||||
with self.assertRaises(ValueError):
|
||||
self.st.move_meeting_item(item_id=3, direction=-1)
|
||||
|
||||
def test_plain_and_rich_saves_share_move_lock_and_visible_length_limit(self):
|
||||
rich = store.GOAL_RICH_PREFIX + json.dumps([dict(text="가", bold=True)] * 4000)
|
||||
out = self.st.update_meeting_item(item_id=1, fields={"content": rich})
|
||||
self.assertEqual(len(store.goal_text_plain(out["content"])), 4000)
|
||||
with self.assertRaises(ValueError):
|
||||
self.st.update_meeting_item(item_id=1, fields={"content": "가" * 4001})
|
||||
safe = store.goal_text_html(store.validate_goal_text(store.GOAL_RICH_PREFIX + json.dumps([
|
||||
dict(text="<script>alert(1)</script>", color="red;display:none", size=200)])))
|
||||
self.assertNotIn("<script>", safe)
|
||||
self.assertNotIn("display:none", safe)
|
||||
|
||||
def test_http_permissions_conflict_validation_and_migration(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
app.state.project_store = self.st
|
||||
client = TestClient(app)
|
||||
endpoints = [("POST", "/meeting-cells/move", self.payload),
|
||||
("POST", "/meeting-cells/merge", dict(item_from=1, item_to=2)),
|
||||
("DELETE", "/meeting-items/1/cell-merge", None)]
|
||||
with patch.object(api, "_require_user", return_value=dict(role="admin", email="admin@test.local")):
|
||||
url = "/project/api/goals/meeting-cells/move"
|
||||
self.assertEqual(client.post(url, json={}).status_code, 400)
|
||||
self.assertEqual(client.post(url, json=self.payload | {"source_body": None}).status_code, 400)
|
||||
self.assertEqual(client.post(url, json=self.payload | {"target_body": "changed"}).status_code, 409)
|
||||
self.st._meeting_cells = lambda conn: False
|
||||
self.assertEqual(client.post("/project/api/goals/meeting-cells/merge", json=dict(item_from=1, item_to=2)).status_code, 503)
|
||||
self.assertEqual(client.post(url, json=self.payload).status_code, 200, "Move/formatting work without 019")
|
||||
# 회의록은 누구나 고친다(2026-10-07) — 관리자가 아니어도 셀 이동·병합·해제를 막지 않는다(잠금은 회의 완료로)
|
||||
with patch.object(api, "_require_user", return_value=dict(role="user", email="user@test.local")):
|
||||
for method, endpoint, body in endpoints:
|
||||
self.assertNotEqual(client.request(method, "/project/api/goals" + endpoint, json=body).status_code, 403)
|
||||
|
||||
def test_amount_cells_accept_text_after_021_and_result_note_reaches_store(self):
|
||||
"""정량 목표·결과 — 숫자면 원 정수 칸, 글(예: 20개)이면 글 칸(021). 지난주 결과 글(result_note, 020)은 API 를 거쳐 저장된다."""
|
||||
self.st._column_exists = lambda conn, table, col: col in {"content_row_span", "result_note", "target_text"}
|
||||
for r in self.conn.rows.values():
|
||||
r.update(result_note="", target_text="", result_text="")
|
||||
out = self.st.update_meeting_item(item_id=1, fields={"target_amount": "20개", "result_amount": "120만"})
|
||||
self.assertEqual((out["target_amount"], out["target_text"]), (None, "20개"))
|
||||
self.assertEqual((out["result_amount"], out["result_text"]), (1_200_000, ""))
|
||||
out = self.st.update_meeting_item(item_id=1, fields={"target_amount": "1,000"})
|
||||
self.assertEqual((out["target_amount"], out["target_text"]), (1000, ""), "숫자로 바꾸면 글은 지운다")
|
||||
with self.assertRaises(ValueError):
|
||||
self.st.update_meeting_item(item_id=1, fields={"target_amount": "가" * 101})
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
app.state.project_store = self.st
|
||||
client = TestClient(app)
|
||||
with patch.object(api, "_require_user", return_value=dict(role="admin", email="admin@test.local")):
|
||||
r = client.put("/project/api/goals/meeting-items/2", json={"result_note": "잘함", "result_amount": "3박스"})
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
self.assertEqual(self.conn.rows[2]["result_note"], "잘함")
|
||||
self.assertEqual((self.conn.rows[2]["result_amount"], self.conn.rows[2]["result_text"]), (None, "3박스"))
|
||||
# 021 전 — 글은 예전처럼 숫자 오류(400), 숫자는 그대로 저장
|
||||
for k in ("_meeting_v21_ok", "_meeting_v20_ok"):
|
||||
self.st.__dict__.pop(k, None)
|
||||
self.st._column_exists = lambda conn, table, col: col == "content_row_span"
|
||||
with self.assertRaises(ValueError):
|
||||
self.st.update_meeting_item(item_id=3, fields={"target_amount": "20개"})
|
||||
self.assertEqual(self.st.update_meeting_item(item_id=3, fields={"target_amount": "5"})["target_amount"], 5)
|
||||
|
||||
def test_rendered_meeting_keeps_merge_geometry_and_escapes_rich_text(self):
|
||||
from pathlib import Path
|
||||
from jinja2 import ChoiceLoader, DictLoader, Environment, FileSystemLoader
|
||||
|
||||
root = Path(__file__).resolve().parents[1]
|
||||
rich = store.validate_goal_text(store.GOAL_RICH_PREFIX + json.dumps([
|
||||
dict(text="<img onerror=alert(1)>\n계획", bold=True, size=24, color="#dc2626")]))
|
||||
self.conn.rows[1]["content"] = rich
|
||||
self.st.merge_meeting_cells(item_from=1, item_to=2)
|
||||
items = [self.st._meeting_item(copy.deepcopy(r)) | {"prev": None} for r in self.conn.rows.values()]
|
||||
head = dict(week_start="2026-09-28", notes="", attendees="", week_target=None,
|
||||
items=items, prev_meeting=None, cell_merges=True)
|
||||
fake = SimpleNamespace(get_meeting=lambda **kw: copy.deepcopy(head),
|
||||
goal_month_targets=lambda **kw: dict(sales_unit="원", sales_target=None, roas_target=None))
|
||||
request = SimpleNamespace(app=SimpleNamespace(state=SimpleNamespace(performance_store=None)))
|
||||
view = api._meeting_view(request, fake, year=2026, month=9, week=date(2026, 9, 28))
|
||||
rows = view["meeting"]["sections"][0]["rows"]
|
||||
self.assertEqual(rows[0]["content_span"], 2)
|
||||
self.assertTrue(rows[1]["content_hidden"])
|
||||
env = Environment(loader=ChoiceLoader([
|
||||
DictLoader({"erp_base.html": "{% block head_extra %}{% endblock %}{% block content %}{% endblock %}"}),
|
||||
FileSystemLoader(root / "app/modules/project/templates")]), autoescape=True)
|
||||
html = env.get_template("project/goal_meeting.html").render(
|
||||
user=dict(email="test@local"), is_admin=True, pj_pro=True, goal_year=2026, goal_month=9,
|
||||
meetings_enabled=True, week="2026-09-28", week_end="2026-10-04", prev_week="2026-09-21",
|
||||
prev_week_end="2026-09-27", meeting_status=store.MEETING_STATUS, pj_kr_holidays={},
|
||||
nav_projects=[], goal_years=[2026], color_palette=[], project_icons=[], meet_members=[], month_plan=None, **view)
|
||||
self.assertIn('rowspan="2" data-meet-item="1"', html)
|
||||
self.assertNotIn('data-meet-item="2"', html)
|
||||
self.assertIn("<img onerror=alert(1)>", html)
|
||||
self.assertNotIn("<img onerror=", html)
|
||||
self.assertIn("font-weight:700", html)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,115 @@
|
||||
"""주간 회의록 — 누구나 수정, 회의 완료(022)면 잠금. 지난주 결과는 다음 주 회의록이 열려 있는 동안만. DB 없이."""
|
||||
import importlib
|
||||
import unittest
|
||||
from contextlib import contextmanager
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.project import store
|
||||
from app.modules.project.db import ProjectStore
|
||||
from tests.test_project_meeting_cells import Connection, Result
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
|
||||
|
||||
class LockConnection(Connection):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.completed = set() # 완료된 주차 시작일
|
||||
# 있는 회의록 — 9/28 주차(9/28~9/30)와 바로 다음 주차(10/1, 목요일 시작 — 달이 바뀐다)
|
||||
self.meetings = {date(2026, 9, 28), date(2026, 10, 1)}
|
||||
self.shared = [] # FOR SHARE 로 잠근 주차(다음 회의록)
|
||||
|
||||
def execute(self, sql, params=()):
|
||||
if sql.startswith("SELECT completed_at FROM goal_meetings WHERE week_start = %s"):
|
||||
if sql.endswith("FOR SHARE"):
|
||||
assert self.depth > 0, "다음 회의록 잠금은 트랜잭션 안에서"
|
||||
self.shared.append(params[0])
|
||||
if params[0] not in self.meetings:
|
||||
return Result([])
|
||||
return Result([{"completed_at": "done" if params[0] in self.completed else None}])
|
||||
if sql.startswith("UPDATE goal_meetings SET"):
|
||||
assert self.locked and self.depth > 0, "머리 변경은 회의록 행을 잠근 트랜잭션 안에서"
|
||||
self.calls.append((sql, params))
|
||||
return Result([{"week_start": params[-1]}])
|
||||
return super().execute(sql, params)
|
||||
|
||||
|
||||
class MeetingLockTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.conn = LockConnection()
|
||||
|
||||
@contextmanager
|
||||
def connection():
|
||||
yield self.conn
|
||||
|
||||
self.st = ProjectStore.__new__(ProjectStore)
|
||||
self.st._pool = SimpleNamespace(connection=connection)
|
||||
self.st._table_exists = lambda conn, name: True
|
||||
self.st._column_exists = lambda conn, table, col: col in {"content_row_span", "completed_at", "result_note"}
|
||||
for r in self.conn.rows.values():
|
||||
r["result_note"] = ""
|
||||
|
||||
def test_completed_meeting_rejects_edits(self):
|
||||
self.conn.completed.add(date(2026, 9, 28))
|
||||
with self.assertRaises(store.MeetingLocked):
|
||||
self.st.update_meeting_item(item_id=1, fields={"content": "x"})
|
||||
with self.assertRaises(store.MeetingLocked):
|
||||
self.st.move_meeting_item(item_id=2, direction=1)
|
||||
|
||||
def test_last_week_result_follows_next_meeting(self):
|
||||
# 9/28 주차(9/28~9/30)가 완료돼도 다음 주차(10/1) 회의록이 열려 있으면 결과는 적을 수 있다
|
||||
self.conn.completed.add(date(2026, 9, 28))
|
||||
out = self.st.update_meeting_item(item_id=1, fields={"result_note": "잘 됨", "result_amount": "100"})
|
||||
self.assertEqual((out["result_note"], out["result_amount"]), ("잘 됨", 100))
|
||||
self.assertEqual(self.conn.shared, [date(2026, 10, 1)]) # 달이 바뀐 다음 주차(목요일 시작)를 잠그고 확인
|
||||
self.conn.completed.add(date(2026, 10, 1))
|
||||
with self.assertRaises(store.MeetingLocked):
|
||||
self.st.update_meeting_item(item_id=1, fields={"result_note": "늦게"})
|
||||
|
||||
def test_completed_week_without_next_meeting_is_locked(self):
|
||||
# 예전엔 다음 주차 회의록이 없으면 완료된 회의록의 결과도 고칠 수 있었다
|
||||
self.conn.meetings.discard(date(2026, 10, 1))
|
||||
self.conn.completed.add(date(2026, 9, 28))
|
||||
with self.assertRaises(store.MeetingLocked):
|
||||
self.st.update_meeting_item(item_id=1, fields={"result_note": "다음 회의 전"})
|
||||
self.assertEqual(self.conn.rows[1]["result_note"], "")
|
||||
|
||||
def test_open_week_without_next_meeting_accepts_result(self):
|
||||
self.conn.meetings.discard(date(2026, 10, 1))
|
||||
out = self.st.update_meeting_item(item_id=1, fields={"result_note": "이번 주 결과"})
|
||||
self.assertEqual(out["result_note"], "이번 주 결과")
|
||||
|
||||
def test_header_update_checks_lock_inside_row_lock(self):
|
||||
self.st.update_meeting(week_start=date(2026, 9, 28), fields={"notes": "메모"})
|
||||
sqls = [s for s, _ in self.conn.calls]
|
||||
lock = next(i for i, s in enumerate(sqls) if s.startswith("SELECT week_start FROM goal_meetings") and "FOR UPDATE" in s)
|
||||
upd = next(i for i, s in enumerate(sqls) if s.startswith("UPDATE goal_meetings SET"))
|
||||
self.assertLess(lock, upd)
|
||||
self.conn.completed.add(date(2026, 9, 28))
|
||||
with self.assertRaises(store.MeetingLocked):
|
||||
self.st.update_meeting(week_start=date(2026, 9, 28), fields={"notes": "잠김"})
|
||||
self.assertEqual(sum(1 for s, _ in self.conn.calls if s.startswith("UPDATE goal_meetings SET")), 1)
|
||||
|
||||
def test_anyone_edits_but_only_admin_completes(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
app.state.project_store = self.st
|
||||
client = TestClient(app)
|
||||
member = dict(role="user", email="member@test.local")
|
||||
with patch.object(api, "_require_user", return_value=member):
|
||||
r = client.put("/project/api/goals/meeting-items/1", json={"content": "누구나"})
|
||||
self.assertEqual(r.status_code, 200, r.text)
|
||||
self.assertEqual(client.post("/project/api/goals/meetings/2026-09-28/complete", json={"done": True}).status_code, 403)
|
||||
self.conn.completed.add(date(2026, 9, 28))
|
||||
r = client.put("/project/api/goals/meeting-items/1", json={"content": "잠김"})
|
||||
self.assertEqual(r.status_code, 409, r.text)
|
||||
self.assertIn("회의가 완료", r.json()["detail"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,61 @@
|
||||
"""회의록 메뉴의 권한·저장된 주만 조회·월 경계를 DB 연결 없이 확인한다."""
|
||||
import importlib
|
||||
import sys
|
||||
import unittest
|
||||
from datetime import date
|
||||
from types import SimpleNamespace
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
api = importlib.import_module("app.modules.project.router")
|
||||
|
||||
|
||||
class MeetingNavTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
app = FastAPI()
|
||||
app.include_router(api.router)
|
||||
self.client = TestClient(app)
|
||||
|
||||
def test_saved_weeks_are_grouped_once_under_their_month(self):
|
||||
# 주차는 그 달 안(2026-10-07 규칙) — 9/28 회의록은 9월 5주차(9/28~9/30), 10월 1주차는 10/1~10/4
|
||||
query = Mock(return_value=["2026-09-28", "2026-10-05", "2026-10-19", "2025-12-29", "2026-09-28"])
|
||||
st = SimpleNamespace(list_goal_years=lambda: [2025, 2026, 2027], meeting_weeks=query)
|
||||
with patch.object(api, "_require_user", return_value={"email": "reader@test"}), \
|
||||
patch.object(api, "_store", return_value=st), patch.object(api, "today_kst", return_value=date(2026, 10, 4)):
|
||||
result = self.client.get("/project/api/goals/meeting-nav")
|
||||
self.assertEqual(result.status_code, 200)
|
||||
years = result.json()["years"]
|
||||
self.assertEqual([y["year"] for y in years], [2026, 2025])
|
||||
self.assertEqual([m["month"] for m in years[0]["months"]], [9, 10])
|
||||
september = years[0]["months"][0]["weeks"]
|
||||
self.assertEqual(len(september), 1)
|
||||
self.assertEqual(september[0]["label"], "5주차 (9/28~9/30)")
|
||||
self.assertEqual(september[0]["href"], "/project/goals/2026/meetings/9?week=2026-09-28")
|
||||
self.assertEqual([w["label"] for w in years[0]["months"][1]["weeks"]],
|
||||
["2주차 (10/5~10/11)", "4주차 (10/19~10/25)"])
|
||||
self.assertEqual(years[1]["months"][0]["weeks"][0]["label"], "5주차 (12/29~12/31)")
|
||||
query.assert_called_once_with(start=date(2025, 1, 1), end=date(2027, 12, 31))
|
||||
|
||||
def test_no_meetings_returns_empty_tree(self):
|
||||
st = SimpleNamespace(list_goal_years=lambda: [], meeting_weeks=lambda **kw: [])
|
||||
with patch.object(api, "_require_user", return_value={}), patch.object(api, "_store", return_value=st):
|
||||
self.assertEqual(self.client.get("/project/api/goals/meeting-nav").json(), {"years": []})
|
||||
|
||||
def test_unauthorized_requests_do_not_query_database(self):
|
||||
for status in (401, 403):
|
||||
with self.subTest(status=status), patch.object(api, "_require_user", side_effect=HTTPException(status)), \
|
||||
patch.object(api, "_store") as query:
|
||||
self.assertEqual(self.client.get("/project/api/goals/meeting-nav").status_code, status)
|
||||
query.assert_not_called()
|
||||
|
||||
def test_other_month_redirect_keeps_content_only_mode(self):
|
||||
# 다른 달의 월요일 링크가 들어와도 오른쪽 전용 화면을 유지한다.
|
||||
main_stub = SimpleNamespace(build_erp_nav=Mock(), render_template=Mock())
|
||||
with patch.dict(sys.modules, {"app.main": main_stub}), patch.object(api, "_require_user", return_value={}), \
|
||||
patch.object(api, "_store", return_value=SimpleNamespace()):
|
||||
response = self.client.get("/project/goals/2026/meetings/10?week=2026-09-28&content=1", follow_redirects=False)
|
||||
self.assertEqual(response.status_code, 303)
|
||||
self.assertEqual(response.headers["location"], "/project/goals/2026/meetings/9?week=2026-09-28&content=1")
|
||||
main_stub.render_template.assert_not_called()
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user