Compare commits
75 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4171d61db1 | |||
| 677bf8f1d1 | |||
| 15dcabc538 | |||
| 25c885d5dd | |||
| 61f5b3c320 | |||
| 5d55081464 | |||
| f54f19fa45 | |||
| 876d9758bd | |||
| 0ba6192e95 | |||
| dd5010019d | |||
| 57745e114e | |||
| 307a0c31b1 | |||
| cfb6878bea | |||
| b0f559907f | |||
| b6c8173899 | |||
| d0e3e3622b | |||
| 6055d50dbe | |||
| 321041b65a | |||
| faed6581fd | |||
| 6b04b7ab6e | |||
| a85d562fa7 | |||
| 889522d935 | |||
| 5e5586a25c | |||
| 5cf1a33e98 | |||
| f4b80e8abc | |||
| 7e86e9c91b | |||
| 4ecde312f9 | |||
| 0c17b02468 | |||
| 97f4a904cd | |||
| f7a3afcebf | |||
| b3001c3051 | |||
| 443fa56671 | |||
| 884e654bea | |||
| ff3b36bf77 | |||
| 48cd7f0878 | |||
| 456dfe376f | |||
| 64e19e8c3e | |||
| 6543ce3f0f | |||
| 3a43f699f5 | |||
| c13f529721 | |||
| f904d5935c | |||
| 945b81ab4a | |||
| c85ba4acc3 | |||
| fa50a85730 | |||
| 12c733bafc | |||
| 72352a2ed9 | |||
| 38afbca839 | |||
| ede1f8e5e1 | |||
| 45f92f60ca | |||
| 4ec9f2944a | |||
| 439ecb035c | |||
| 5a660e73dd | |||
| 007a16eb9c | |||
| c9b4fa36fe | |||
| 2a3272e514 | |||
| e420b7f1af | |||
| 7914fc6056 | |||
| 667bdd813c | |||
| 66b5155b9b | |||
| 883fcd24f6 | |||
| fbed3ef159 | |||
| 2b3b36d646 | |||
| d9dd03ecc8 | |||
| d48a942932 | |||
| 3d2e20427c | |||
| d007122782 | |||
| f4d7e9588f | |||
| 7275f12a74 | |||
| 9c166be404 | |||
| 77355b10e4 | |||
| 6c87a736a6 | |||
| 3a0ec6e840 | |||
| 18d2835304 | |||
| fba27772a4 | |||
| c9e5a78115 |
@@ -161,6 +161,11 @@ CUSTOMER_ORDER_LIST_URL=/orderlist/
|
||||
# 초기화: scripts/sql/outreach_db_init.sql (docs/DEPLOYMENT.md "안내문 발송 DB 생성"). 미설정 시 "설정 필요" 안내만.
|
||||
# OUTREACH_DB_URL=postgresql://outreach_app:replace-me@postgres-db:5432/outreach_db
|
||||
|
||||
# ─── 라이브 커머스 모듈 (live_db) — app/modules/live ───
|
||||
# 말레이시아 라이브 방송의 호스트 정보·방송 스케줄·판매금액·결과 이미지.
|
||||
# 초기화: scripts/sql/live_db_init.sql (docs/DEPLOYMENT.md "라이브 커머스 DB 생성"). 미설정 시 "설정 필요" 안내만.
|
||||
# LIVE_DB_URL=postgresql://live_app:replace-me@postgres-db:5432/live_db
|
||||
|
||||
# ─── 상품 검색 (itemcode_db 읽기 전용) ───
|
||||
# cupang 설정 화면에서 제품명을 itemcode_db 에서 검색해 등록한다(읽기만).
|
||||
# 미설정 시 검색 비활성 → 수동 등록만 가능.
|
||||
|
||||
@@ -47,6 +47,7 @@
|
||||
| `[공지]` `[긴급공지]` | `notice/` | `project_db`(024) | 수퍼관리자 | `docs/NOTICE_MODULE.md` | `erp-notice*` |
|
||||
| `[자산]` | `asset/` | `asset_db` | `asset` | `docs/ASSET_MODULE.md` | `asset.*` |
|
||||
| `[안내문 발송]` | `outreach/` | `outreach_db` | `outreach` | (모듈 CLAUDE.md) | `outreach.*` |
|
||||
| `[라이브커머스]` `[라이브]` | `live/` | `live_db` | `live` | (모듈 CLAUDE.md) | `live.*` |
|
||||
| `[공통]` `[ERP]` | `app/main.py`, `app/templates/`(셸·로그인·관리자), 인증·권한 | — | — | `docs/PROJECT_OVERVIEW.md`, `docs/DESIGN.md` | `erp*.js/css`, `styles.css` |
|
||||
| `[배포]` `[서버]` | `docker-compose*.yml`, `Dockerfile`, `scripts/` | — | — | `docs/DEPLOYMENT.md` | — |
|
||||
| `[DB]` | `scripts/sql/` | — | — | `docs/DATABASES.md` | — |
|
||||
@@ -62,6 +63,7 @@
|
||||
- `APP_ENCRYPTION_KEY`: 실적(쇼핑몰·광고 인증) + 입출고(Gmail 토큰).
|
||||
- 입출고 Gmail 연결(`inout_gmail_tokens`·`/inout/gmail/callback`, `_GMAIL_ORIGINS`): 입출고 발주 메일 + 휴가 메일(`vacation/notify.py`) + 안내문 발송(`outreach/send.py`) — 모두 보내는 사람 본인 Gmail.
|
||||
- `app/integrations/google_sheets.py`(쿠팡) · `google_slides.py`(프로젝트 회의록 보드).
|
||||
- `asset/media.py prepare_photo`(이미지 확인·메타데이터 제거): 자산 + 라이브 커머스.
|
||||
- `app/mail.py`: 프로젝트 알림 메일.
|
||||
- ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림).
|
||||
- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청) — 바꾸면 둘 다.
|
||||
|
||||
+19
@@ -26,6 +26,8 @@ from .modules.expense import CategoryStore, build_expense_store
|
||||
from .modules.expense import router as expense_router
|
||||
from .modules.inout import build_inout_items, build_inout_store
|
||||
from .modules.inout import router as inout_router
|
||||
from .modules.live import build_live_store
|
||||
from .modules.live import router as live_router
|
||||
from .modules.malaysia import build_malaysia_itemcode, build_malaysia_store
|
||||
from .modules.malaysia import router as malaysia_router
|
||||
from .modules.notice import build_notice_store
|
||||
@@ -65,6 +67,7 @@ MODULE_LABELS: dict[str, str] = {
|
||||
"asset": "자산관리",
|
||||
"inout": "입출고 관리",
|
||||
"outreach": "안내문 발송",
|
||||
"live": "라이브 커머스",
|
||||
"expense_approver": "개인경비",
|
||||
"vacation_approver": "휴가",
|
||||
}
|
||||
@@ -161,6 +164,7 @@ _MODULE_TEMPLATE_DIRS = [
|
||||
BASE_DIR / "modules" / "notice" / "templates",
|
||||
BASE_DIR / "modules" / "inout" / "templates",
|
||||
BASE_DIR / "modules" / "outreach" / "templates",
|
||||
BASE_DIR / "modules" / "live" / "templates",
|
||||
]
|
||||
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))
|
||||
templates.env.loader = ChoiceLoader(
|
||||
@@ -233,6 +237,8 @@ app.state.inout_items = build_inout_items()
|
||||
# 안내문 발송(메일 일괄·인스타 DM 반자동): OUTREACH_DB_URL 없으면 store=None(화면이 "설정 필요" 안내).
|
||||
# 메일은 보내는 사람 본인 Gmail — 입출고 Gmail 연결(inout_store.inout_gmail_tokens)을 같이 쓴다.
|
||||
app.state.outreach_store = build_outreach_store(dsn=env("OUTREACH_DB_URL") or None)
|
||||
# 라이브 커머스(말레이시아 방송 호스트·스케줄): LIVE_DB_URL 없으면 store=None(화면이 "설정 필요" 안내).
|
||||
app.state.live_store = build_live_store(dsn=env("LIVE_DB_URL") or None)
|
||||
|
||||
# 모듈 라우터 등록 — 신규 모듈 추가 시 여기 한 줄.
|
||||
app.include_router(expense_router)
|
||||
@@ -247,6 +253,7 @@ app.include_router(asset_router)
|
||||
app.include_router(notice_router)
|
||||
app.include_router(inout_router)
|
||||
app.include_router(outreach_router)
|
||||
app.include_router(live_router)
|
||||
|
||||
|
||||
def public_url_for(request: Request, route_name: str) -> str:
|
||||
@@ -459,6 +466,17 @@ def _menu_items_for(user_rec: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
"status": "ready",
|
||||
"category": "운영",
|
||||
},
|
||||
{
|
||||
"key": "live",
|
||||
"title": "라이브 커머스",
|
||||
"card_title": "라이브 커머스 · Live Commerce", # 메인 카드만 한글·영문 둘 다(사이드바는 짧게)
|
||||
"subtitle": "Malaysia",
|
||||
"description": "말레이시아 라이브 방송의 호스트 정보와 방송 스케줄·판매금액·결과 이미지를 관리합니다.",
|
||||
"url": "/live/",
|
||||
"health_url": "/live/health",
|
||||
"status": "ready",
|
||||
"category": "운영",
|
||||
},
|
||||
]
|
||||
items.append({
|
||||
"key": "asset", "title": "자산관리", "subtitle": "Asset Management",
|
||||
@@ -476,6 +494,7 @@ def _icon_svg(name: str) -> str:
|
||||
paths = {
|
||||
"inout": '<path d="M3 7l9-4 9 4v10l-9 4-9-4z"/><path d="M3 7l9 4 9-4"/><path d="M12 11v10"/>',
|
||||
"outreach": '<path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4z"/>',
|
||||
"live": '<rect x="2" y="6" width="14" height="12" rx="2"/><path d="m16 11 6-4v10l-6-4"/>',
|
||||
"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"/>',
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
|
||||
- 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력.
|
||||
- 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널).
|
||||
- HTML 편집기에서 `<img>` 태그에 마우스를 올리면 태그를 오렌지색으로 칠하고 화면 오른쪽에 폭 500px·창 높이로 파일명과 미리보기(상대 경로는 `CAFE24_SHOP_URL` 루트 기준, 색칠 한도 `HL_LIMIT` 초과 소스는 미동작).
|
||||
- HTML 편집기 `<img>` 안에서 커서 바로 뒤가 `.jpg`/`.gif`/`.png` 일 때 Ctrl+↑/↓ 로 파일명 번호 변경(없음 → `_2` → `_3` …, 내리면 `_2` 다음은 원래 이름, `_2`~`_99` 만 번호로 인식).
|
||||
- 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지, 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매) 수정.
|
||||
- 대표이미지는 `POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A`.
|
||||
NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨.
|
||||
|
||||
@@ -96,11 +96,11 @@ def guard(request: Request):
|
||||
반환이 tuple 이면 (store, user), 아니면 그대로 응답으로 돌려준다.
|
||||
"""
|
||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||
from app.store import has_module, is_admin # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return RedirectResponse(url="/login", status_code=303)
|
||||
return login_redirect(request)
|
||||
if not has_module(user, MODULE_KEY):
|
||||
return render_template(
|
||||
request,
|
||||
|
||||
@@ -122,7 +122,7 @@
|
||||
<input type="hidden" name="list_query" value="{{ list_query }}" />
|
||||
|
||||
<div class="cf24-editor-bar">
|
||||
<span class="cf24-shortcuts">단축키: 주석토글[Ctrl+/] · 줄 복사[Alt+Shift+↑↓] · 줄 이동[Alt+↑↓] · 줄 삭제[Shift+Del]</span>
|
||||
<span class="cf24-shortcuts">단축키: 주석토글[Ctrl+/] · 줄 복사[Alt+Shift+↑↓] · 줄 이동[Alt+↑↓] · 줄 삭제[Shift+Del] · 이미지 번호[Ctrl+↑↓]</span>
|
||||
<span class="cf24-editor-bar-right">
|
||||
<input class="cf24-memo" type="text" name="memo" maxlength="200"
|
||||
placeholder="변경 메모 (버전 이력에 남습니다)" />
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261015a" />
|
||||
<link rel="stylesheet" href="/static/cafe24.css?v=20261103c" />
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
@@ -122,6 +122,9 @@
|
||||
<div class="cf24-modal-body cf24-options-body" id="cf24-options-body"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{# 소스의 <img> 위에 마우스를 올리면 화면 오른쪽에 뜨는 미리보기 — setupCodeEditor 가 켜고 끈다. #}
|
||||
<div class="cf24-img-preview" id="cf24-img-preview" hidden><div class="cf24-img-preview-name"></div><img alt="이미지를 불러올 수 없습니다" /></div>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
@@ -164,14 +167,42 @@
|
||||
last = TOKEN_RE.lastIndex;
|
||||
if (m[1]) { out += '<span class="cf24-t-com">' + esc(m[1]) + "</span>"; continue; }
|
||||
if (m[2]) { out += '<span class="cf24-t-doc">' + esc(m[2]) + "</span>"; continue; }
|
||||
out += '<span class="cf24-t-pun">' + esc(m[3]) + "</span>" +
|
||||
'<span class="cf24-t-tag">' + esc(m[4]) + "</span>" +
|
||||
paintAttrs(m[5]) +
|
||||
'<span class="cf24-t-pun">' + esc(m[6]) + "</span>";
|
||||
var tag = '<span class="cf24-t-pun">' + esc(m[3]) + "</span>" +
|
||||
'<span class="cf24-t-tag">' + esc(m[4]) + "</span>" +
|
||||
paintAttrs(m[5]) +
|
||||
'<span class="cf24-t-pun">' + esc(m[6]) + "</span>";
|
||||
out += /^img$/i.test(m[4]) ? '<span class="cf24-t-img">' + tag + "</span>" : tag;
|
||||
}
|
||||
return out + esc(src.slice(last));
|
||||
}
|
||||
|
||||
// 상대 경로는 쇼핑몰 루트 기준이다: ../img/a.jpg → https://쇼핑몰/img/a.jpg
|
||||
function imgPreviewUrl(tag) {
|
||||
var m = tag.match(/\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i);
|
||||
var src = m && (m[1] || m[2] || m[3]);
|
||||
var shop = document.getElementById("cf24-url");
|
||||
if (!src || !shop) return "";
|
||||
try { return new URL(src, new URL("/", shop.value)).href; }
|
||||
catch (err) { return ""; }
|
||||
}
|
||||
|
||||
function imgFileName(url) {
|
||||
var name = new URL(url).pathname.split("/").pop();
|
||||
// URL 이 한글 파일명을 %XX 로 바꿔 놓으므로 되돌린다.
|
||||
try { return decodeURIComponent(name); }
|
||||
catch (err) { return name; }
|
||||
}
|
||||
|
||||
function showImgPreview(url) {
|
||||
var box = document.getElementById("cf24-img-preview");
|
||||
var img = box.lastElementChild;
|
||||
if (url && img.getAttribute("src") !== url) {
|
||||
img.src = url;
|
||||
box.firstElementChild.textContent = imgFileName(url);
|
||||
}
|
||||
box.hidden = !url;
|
||||
}
|
||||
|
||||
function setupCodeEditor() {
|
||||
var ta = document.getElementById("cf24-html-pc");
|
||||
var hl = document.getElementById("cf24-hl-pc");
|
||||
@@ -337,6 +368,47 @@
|
||||
applyEdit(from, to, "", lineFrom + col, lineFrom + col);
|
||||
}
|
||||
|
||||
/* Ctrl+↑/↓ — <img> 안에서 커서 바로 뒤가 .jpg/.gif/.png 이면 파일명 번호를 바꾼다.
|
||||
a.jpg → a_2.jpg → a_3.jpg …, 내릴 때는 _2 다음이 원래 이름. 커서는 확장자 앞에 그대로 둔다.
|
||||
_2~_99 만 번호로 본다(product_2024.jpg 의 2024 는 번호가 아니다).
|
||||
조건이 안 맞으면 false — 브라우저 기본 동작을 막지 않는다. */
|
||||
function stepImgSuffix(up) {
|
||||
var at = ta.selectionStart, value = ta.value;
|
||||
if (at !== ta.selectionEnd || !/^\.(jpg|gif|png)/i.test(value.slice(at, at + 4))) return false;
|
||||
var head = value.slice(value.lastIndexOf("<", at - 1), at);
|
||||
if (!/^<img\s[^>]*$/i.test(head)) return false;
|
||||
|
||||
var m = head.match(/_([2-9]|[1-9]\d)$/);
|
||||
var n = m ? Number(m[1]) : 1;
|
||||
if (up ? n >= 99 : !m) return true; // 더 갈 곳이 없다
|
||||
var next = up ? n + 1 : n - 1;
|
||||
var text = next < 2 ? "" : "_" + next;
|
||||
var from = at - (m ? m[0].length : 0);
|
||||
applyEdit(from, at, text, from + text.length, from + text.length);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* 이미지 미리보기 — 맨 위 textarea 를 판정에서 잠깐 빼고 색칠 층의 <img> 를 찾는다.
|
||||
글자 폭을 계산하지 않아 한글·탭·여러 줄 태그에서도 위치가 어긋나지 않는다.
|
||||
shortcut: HL_LIMIT 초과 소스는 색칠을 안 해 미리보기도 안 뜬다, 그런 상품이 나오면 글자 위치 계산으로 교체. */
|
||||
var hoverTag = null;
|
||||
|
||||
function setHoverTag(tag) {
|
||||
if (tag === hoverTag) return;
|
||||
if (hoverTag) hoverTag.classList.remove("cf24-t-img-on");
|
||||
if (tag) tag.classList.add("cf24-t-img-on");
|
||||
hoverTag = tag;
|
||||
showImgPreview(tag ? imgPreviewUrl(tag.textContent) : "");
|
||||
}
|
||||
|
||||
ta.addEventListener("mousemove", function (e) {
|
||||
ta.style.pointerEvents = "none";
|
||||
var el = document.elementFromPoint(e.clientX, e.clientY);
|
||||
ta.style.pointerEvents = "";
|
||||
setHoverTag(el && el.closest(".cf24-t-img"));
|
||||
});
|
||||
ta.addEventListener("mouseleave", function () { setHoverTag(null); });
|
||||
|
||||
ta.addEventListener("scroll", sync);
|
||||
ta.addEventListener("input", function () { dirty = true; refresh(); });
|
||||
ta.addEventListener("keydown", function (e) {
|
||||
@@ -356,6 +428,10 @@
|
||||
else moveLines(isDown);
|
||||
return;
|
||||
}
|
||||
if (e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey && (isUp || isDown) && stepImgSuffix(isUp)) {
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
// Shift+Delete — 줄 삭제. (윈도우 기본 동작인 "잘라내기"를 대신한다)
|
||||
if (e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey &&
|
||||
(e.key === "Delete" || e.code === "Delete")) {
|
||||
|
||||
@@ -75,11 +75,11 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
|
||||
def _guard(request: Request) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
|
||||
"""로그인+권한+store 점검을 한 번에. 페이지 핸들러 진입부에서 사용."""
|
||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||
from app.store import has_module, is_admin # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return RedirectResponse(url="/login", status_code=303)
|
||||
return login_redirect(request)
|
||||
if not has_module(user, "cupang"):
|
||||
return render_template(
|
||||
request,
|
||||
|
||||
@@ -249,7 +249,7 @@
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}
|
||||
<script src="/static/project.js?v=20261027a" defer></script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
<script src="/static/cupang-outbound.js?v=20261023d" defer></script>
|
||||
<script>
|
||||
(function () {
|
||||
|
||||
@@ -10,4 +10,5 @@
|
||||
- 작업 상태 토글(`dispatch_logs` 기록).
|
||||
- 받는 사람 이름/전화/주소는 상자 단위로 저장(작업 카드 표시 + 출고 엑셀 생성용) — **개인정보**, 로그·외부 전송 주의.
|
||||
- 배치 다운로드 zip 에 업로드 원본 + 취합 출고 엑셀(`YYYY.MM.DD(Ddd)_tictoc|shopee.xlsx`) 포함.
|
||||
- 기간별 발송 수량 엑셀(`/dispatch/period-export`, **수퍼 관리자 전용**): 날짜별·아이템별 수량(`_N` 배수 반영, 세트는 BOM 으로 낱개 분해) + 아이템×날짜 요약 시트 + 세트×날짜 요약 시트(낱개로 풀기 전 세트 수량).
|
||||
- 엑셀은 openpyxl 파싱/생성.
|
||||
|
||||
@@ -309,6 +309,41 @@ class DispatchStore:
|
||||
for r in rows
|
||||
]
|
||||
|
||||
def shipped_by_date_range(
|
||||
self, *, date_from: str, date_to: str
|
||||
) -> list[dict[str, Any]]:
|
||||
"""기간(양끝 포함) 날짜·SKU별 합산 수량 — 기간별 발송 수량 엑셀용.
|
||||
|
||||
반환: [{"dispatch_date": "YYYY-MM-DD", "seller_sku", "product_name", "qty"}].
|
||||
_N 배수 반영은 호출부(export)에서 한다.
|
||||
"""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"""
|
||||
SELECT b.dispatch_date, i.seller_sku,
|
||||
MAX(i.product_name) AS product_name,
|
||||
SUM(i.quantity)::int AS qty
|
||||
FROM dispatch_items i
|
||||
JOIN dispatch_parcels p ON p.id = i.parcel_id
|
||||
JOIN dispatch_batches b ON b.id = p.batch_id
|
||||
WHERE b.dispatch_date BETWEEN %s AND %s
|
||||
GROUP BY b.dispatch_date, i.seller_sku
|
||||
ORDER BY b.dispatch_date ASC, i.seller_sku ASC
|
||||
""",
|
||||
(date_from, date_to),
|
||||
).fetchall()
|
||||
return [
|
||||
{
|
||||
"dispatch_date": r["dispatch_date"].isoformat()
|
||||
if isinstance(r["dispatch_date"], date)
|
||||
else str(r["dispatch_date"] or ""),
|
||||
"seller_sku": r["seller_sku"] or "",
|
||||
"product_name": r["product_name"] or "",
|
||||
"qty": int(r["qty"] or 0),
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 말레이시아 재고 차감 1회성 가드
|
||||
# ════════════════════════════════════════════════════════════
|
||||
|
||||
@@ -246,6 +246,158 @@ def stock_filename(dispatch_date: str) -> str:
|
||||
return f"{stamp}_sabangnet_outbound.xlsx"
|
||||
|
||||
|
||||
# ── 기간별 발송 수량 엑셀(수퍼 관리자) ──
|
||||
def missing_set_boms(
|
||||
rows: list[dict[str, Any]], set_bom: dict[str, list[dict[str, Any]]]
|
||||
) -> list[str]:
|
||||
"""세트(MY-)인데 BOM 이 없어 낱개로 풀 수 없는 코드 목록(정렬)."""
|
||||
return sorted({
|
||||
b for b in (split_sku(r.get("seller_sku", ""))[0].strip().upper() for r in rows)
|
||||
if b.startswith(_SET_PREFIX) and b not in set_bom
|
||||
})
|
||||
|
||||
|
||||
def aggregate_shipped(
|
||||
rows: list[dict[str, Any]],
|
||||
name_map: dict[str, str] | None = None,
|
||||
set_bom: dict[str, list[dict[str, Any]]] | None = None,
|
||||
) -> tuple[list[str], dict[str, str], dict[tuple[str, str], int]]:
|
||||
"""날짜·SKU별 합산 행 → (날짜목록, {코드: 상품명}, {(날짜, 코드): 수량}).
|
||||
|
||||
seller_sku 의 _N 접미사는 배수로 곱해 실제 아이템코드로 합친다
|
||||
(예: MT-0320_3 × 2 → MT-0320 6개). 세트(set_bom 에 있는 코드)는 구성 낱개로
|
||||
풀어 (수량 × 구성수량) 을 낱개 코드에 더한다.
|
||||
"""
|
||||
name_map = name_map or {}
|
||||
set_bom = set_bom or {}
|
||||
dates: set[str] = set()
|
||||
names: dict[str, str] = {}
|
||||
qty: dict[tuple[str, str], int] = {}
|
||||
|
||||
def _add(d: str, code: str, n: int, fallback: str) -> None:
|
||||
key = (d, code)
|
||||
qty[key] = qty.get(key, 0) + n
|
||||
if not names.get(code):
|
||||
names[code] = resolve_product_name(code, name_map, fallback=fallback)
|
||||
|
||||
for r in rows:
|
||||
base, mult = split_sku(r.get("seller_sku", ""))
|
||||
code = base.strip().upper()
|
||||
if not code:
|
||||
continue
|
||||
pieces = int(r.get("qty", 0) or 0) * mult
|
||||
if pieces <= 0:
|
||||
continue
|
||||
d = r.get("dispatch_date", "") or ""
|
||||
dates.add(d)
|
||||
comps = set_bom.get(code)
|
||||
if comps: # 세트 → 낱개 분해
|
||||
for c in comps:
|
||||
cc = str(c.get("component_code", "")).strip().upper()
|
||||
n = pieces * int(c.get("component_qty", 0) or 0)
|
||||
if cc and n > 0:
|
||||
_add(d, cc, n, "")
|
||||
else:
|
||||
_add(d, code, pieces, r.get("product_name", "") or "")
|
||||
return sorted(dates), names, qty
|
||||
|
||||
|
||||
def build_period_xlsx(
|
||||
*,
|
||||
rows: list[dict[str, Any]],
|
||||
date_from: str,
|
||||
date_to: str,
|
||||
name_map: dict[str, str] | None = None,
|
||||
set_bom: dict[str, list[dict[str, Any]]] | None = None,
|
||||
) -> bytes:
|
||||
"""기간별 발송 수량 xlsx(세트는 낱개로 풀어 합산). 시트 3개.
|
||||
|
||||
- 「날짜별」: 발송 날짜 / 아이템 코드 / 상품이름 / 수량 (날짜·코드 오름차순, 맨 끝 합계)
|
||||
- 「아이템별 요약」: 아이템 코드 / 상품이름 / 날짜1..N / 합계 (맨 끝 날짜별 합계 행)
|
||||
- 「세트별 요약」: 세트 코드 / 상품이름 / 날짜1..N / 합계 — 낱개로 풀기 전 세트 단위 수량
|
||||
"""
|
||||
from openpyxl import Workbook # noqa: WPS433
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
set_bom = set_bom or {}
|
||||
dates, names, qty = aggregate_shipped(rows, name_map, set_bom)
|
||||
codes = sorted(names)
|
||||
# 세트 행만 BOM 없이 다시 합산하면 세트 단위 수량이 된다(_N 배수 반영은 같다).
|
||||
set_rows = [r for r in rows if split_sku(r.get("seller_sku", ""))[0].strip().upper() in set_bom]
|
||||
_sd, set_names, set_qty = aggregate_shipped(set_rows, name_map)
|
||||
|
||||
head_fill = PatternFill("solid", fgColor="E2E8F0")
|
||||
head_font = Font(bold=True)
|
||||
bold = Font(bold=True)
|
||||
|
||||
def _style_head(ws: Any) -> None:
|
||||
for cell in ws[1]:
|
||||
cell.fill = head_fill
|
||||
cell.font = head_font
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
wb = Workbook()
|
||||
|
||||
# 시트 1 — 날짜별 목록
|
||||
ws = wb.active
|
||||
ws.title = "날짜별"
|
||||
headers = ["발송 날짜", "아이템 코드", "상품이름", "수량"]
|
||||
ws.append(headers)
|
||||
total = 0
|
||||
for d in dates:
|
||||
for code in codes:
|
||||
n = qty.get((d, code))
|
||||
if not n:
|
||||
continue
|
||||
ws.append([d, code, names.get(code, ""), n])
|
||||
total += n
|
||||
ws.append(["합계", "", "", total])
|
||||
for cell in ws[ws.max_row]:
|
||||
cell.font = bold
|
||||
_style_head(ws)
|
||||
_autosize(ws, headers)
|
||||
|
||||
# 시트 2·3 — 코드(행) × 날짜(열) 요약. 날짜 열은 두 시트 모두 전체 발송 날짜로 맞춘다.
|
||||
def _pivot(title: str, code_label: str, p_names: dict[str, str],
|
||||
p_qty: dict[tuple[str, str], int]) -> None:
|
||||
p_codes = sorted(p_names)
|
||||
ws2 = wb.create_sheet(title)
|
||||
headers2 = [code_label, "상품이름", *dates, "합계"]
|
||||
ws2.append(headers2)
|
||||
for code in p_codes:
|
||||
per_day = [p_qty.get((d, code), 0) for d in dates]
|
||||
ws2.append([code, p_names.get(code, ""), *[n or None for n in per_day], sum(per_day)])
|
||||
day_totals = [sum(p_qty.get((d, c), 0) for c in p_codes) for d in dates]
|
||||
ws2.append(["합계", "", *day_totals, sum(day_totals)])
|
||||
for cell in ws2[ws2.max_row]:
|
||||
cell.font = bold
|
||||
_style_head(ws2)
|
||||
ws2.freeze_panes = "C2"
|
||||
_autosize(ws2, headers2)
|
||||
for i in range(3, len(headers2) + 1): # 날짜 열은 좁게 고정
|
||||
ws2.column_dimensions[get_column_letter(i)].width = 12
|
||||
|
||||
_pivot("아이템별 요약", "아이템 코드", names, qty)
|
||||
_pivot("세트별 요약", "세트 코드", set_names, set_qty)
|
||||
|
||||
wb.properties.title = f"말레이시아 발송 수량 {date_from} ~ {date_to}"
|
||||
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def period_filename(date_from: str, date_to: str) -> str:
|
||||
"""기간별 발송 수량 파일명: 2026.10.01-2026.10.28_shipped_qty.xlsx."""
|
||||
def _stamp(v: str) -> str:
|
||||
d = _parse_date(v)
|
||||
return d.strftime("%Y.%m.%d") if d else (v or "").strip()
|
||||
|
||||
return f"{_stamp(date_from)}-{_stamp(date_to)}_shipped_qty.xlsx"
|
||||
|
||||
|
||||
def _cell(value: Any) -> Any:
|
||||
"""송장/전화번호 등이 숫자로 보이면 엑셀이 과학표기/반올림 하므로 문자열 보존."""
|
||||
if isinstance(value, int):
|
||||
|
||||
@@ -131,11 +131,11 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
|
||||
def _guard(request: Request):
|
||||
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
|
||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||
from app.store import has_module, is_admin # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return RedirectResponse(url="/login", status_code=303)
|
||||
return login_redirect(request)
|
||||
if not has_module(user, "dispatch"):
|
||||
return render_template(
|
||||
request,
|
||||
@@ -477,6 +477,72 @@ def stock_export(
|
||||
)
|
||||
|
||||
|
||||
_PERIOD_MAX_DAYS = 366
|
||||
|
||||
|
||||
@router.get("/period-export")
|
||||
def period_export(
|
||||
request: Request,
|
||||
date_from: str,
|
||||
date_to: str,
|
||||
user: dict[str, Any] = Depends(_require_user),
|
||||
) -> Response:
|
||||
"""기간(양끝 포함) 날짜별·아이템별 발송 수량 xlsx — 슈퍼 관리자 전용.
|
||||
|
||||
seller_sku 의 _N 배수 반영, 세트(MY-)는 itemcode_db BOM 으로 낱개로 풀어 합산.
|
||||
"""
|
||||
if not bool(user.get("is_super_admin")):
|
||||
raise HTTPException(status_code=403, detail="기간별 발송 수량은 슈퍼 관리자만 받을 수 있습니다.")
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
raise HTTPException(status_code=503, detail="dispatch_db 미설정")
|
||||
d_from = export._parse_date(date_from)
|
||||
d_to = export._parse_date(date_to)
|
||||
if d_from is None or d_to is None:
|
||||
raise HTTPException(status_code=400, detail="시작일·종료일을 YYYY-MM-DD 로 입력하세요.")
|
||||
if d_from > d_to:
|
||||
d_from, d_to = d_to, d_from
|
||||
if (d_to - d_from).days + 1 > _PERIOD_MAX_DAYS:
|
||||
raise HTTPException(status_code=400, detail=f"기간은 최대 {_PERIOD_MAX_DAYS}일까지 가능합니다.")
|
||||
|
||||
f, t = d_from.isoformat(), d_to.isoformat()
|
||||
rows = st.shipped_by_date_range(date_from=f, date_to=t)
|
||||
if not rows:
|
||||
raise HTTPException(status_code=404, detail=f"{f} ~ {t} 기간의 발송 데이터가 없습니다.")
|
||||
|
||||
# 세트 BOM 이 없으면 낱개로 못 푼 채 파일이 만들어진다 — 조용히 틀리지 말고 알린다.
|
||||
set_bom, _sab = _itemcode_bom_and_sabangnet(request)
|
||||
missing_sets = export.missing_set_boms(rows, set_bom)
|
||||
if missing_sets:
|
||||
reader = getattr(request.app.state, "malaysia_itemcode", None)
|
||||
hint = getattr(reader, "last_error", "") or getattr(reader, "reason", "")
|
||||
detail = (
|
||||
"세트 BOM 을 찾지 못해 낱개로 풀 수 없습니다: "
|
||||
+ ", ".join(missing_sets)
|
||||
+ ". itemcode_db 의 set_components 에 해당 세트 BOM 이 등록돼 있는지 확인하세요."
|
||||
)
|
||||
if hint:
|
||||
detail += f" (itemcode 리더 오류: {hint})"
|
||||
raise HTTPException(status_code=422, detail=detail)
|
||||
|
||||
xlsx_bytes = export.build_period_xlsx(
|
||||
rows=rows, date_from=f, date_to=t,
|
||||
name_map=_itemcode_name_map(request), set_bom=set_bom,
|
||||
)
|
||||
fname = export.period_filename(f, t)
|
||||
headers = {
|
||||
"Content-Disposition": (
|
||||
f"attachment; filename=\"shipped_{f}_{t}.xlsx\"; "
|
||||
f"filename*=UTF-8''{quote(fname)}"
|
||||
)
|
||||
}
|
||||
return Response(
|
||||
content=xlsx_bytes,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers=headers,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/stock-deduct")
|
||||
def stock_deduct(
|
||||
request: Request,
|
||||
|
||||
@@ -114,7 +114,8 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="erp-card dsp-calwrap">
|
||||
<div class="dsp-calwrap" style="display:flex;flex-direction:column;gap:16px;">
|
||||
<div class="erp-card" style="margin:0;">
|
||||
<div class="cpg-card-head"><h3 style="margin:0;" data-ko="사방넷 출고 다운로드" data-en="Sabangnet Outbound Download">사방넷 출고 다운로드</h3></div>
|
||||
<p class="erp-muted" style="margin:4px 0 10px;font-size:13px;"
|
||||
data-ko="날짜를 클릭하면 그날 출고를 낱개로 분해한 사방넷 출고 엑셀을 받습니다. 사방넷에 올리면 출고로 잡혀 재고가 차감됩니다."
|
||||
@@ -143,6 +144,24 @@
|
||||
<div id="dsp-cal-deduct-note" class="erp-muted" style="font-size:12px;"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if is_super %}
|
||||
<div class="erp-card" style="margin:0;">
|
||||
<div class="cpg-card-head"><h3 style="margin:0;" data-ko="기간별 발송 수량" data-en="Shipped Qty by Period">기간별 발송 수량</h3></div>
|
||||
<p class="erp-muted" style="margin:4px 0 10px;font-size:13px;"
|
||||
data-ko="기간 안 날짜별·아이템별 발송 수량을 엑셀로 받습니다. 세트는 낱개로 풀어 합산하고, 세트 수량은 별도 시트에 담습니다. (수퍼 관리자 전용)"
|
||||
data-en="Download shipped quantities per date and item for the period. Sets are split into singles; set counts are on a separate sheet. (Super admin only)">기간 안 날짜별·아이템별 발송 수량을 엑셀로 받습니다. 세트는 낱개로 풀어 합산하고, 세트 수량은 별도 시트에 담습니다. (수퍼 관리자 전용)</p>
|
||||
<div style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
|
||||
<input type="date" id="dsp-pe-from" class="erp-input" style="flex:1 1 120px;min-width:0;padding:7px 8px;border:1px solid #cbd5e1;border-radius:8px;" />
|
||||
<span class="erp-muted">~</span>
|
||||
<input type="date" id="dsp-pe-to" class="erp-input" style="flex:1 1 120px;min-width:0;padding:7px 8px;border:1px solid #cbd5e1;border-radius:8px;" />
|
||||
</div>
|
||||
<button type="button" id="dsp-pe-dl" class="erp-btn erp-btn-primary" style="margin-top:10px;width:100%;"
|
||||
data-ko="📊 기간별 발송 수량 엑셀 다운로드" data-en="📊 Download Shipped Qty Excel">📊 기간별 발송 수량 엑셀 다운로드</button>
|
||||
<div id="dsp-pe-note" class="erp-muted" style="font-size:12px;margin-top:6px;"></div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -264,6 +283,53 @@
|
||||
render();
|
||||
})();
|
||||
|
||||
// ── 기간별 발송 수량 엑셀(수퍼 관리자) ──
|
||||
(function () {
|
||||
var btn = document.getElementById('dsp-pe-dl');
|
||||
if (!btn) return;
|
||||
var fromEl = document.getElementById('dsp-pe-from');
|
||||
var toEl = document.getElementById('dsp-pe-to');
|
||||
var note = document.getElementById('dsp-pe-note');
|
||||
function pad(n) { return (n < 10 ? '0' : '') + n; }
|
||||
function iso(d) { return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()); }
|
||||
function en() { return (window.dspLang && window.dspLang() === 'en'); }
|
||||
// 기본: 이번 달 1일 ~ 오늘
|
||||
var now = new Date();
|
||||
fromEl.value = iso(new Date(now.getFullYear(), now.getMonth(), 1));
|
||||
toEl.value = iso(now);
|
||||
|
||||
btn.onclick = function () {
|
||||
var f = fromEl.value, t = toEl.value;
|
||||
if (!f || !t) { alert(en() ? 'Pick both dates.' : '시작일과 종료일을 고르세요.'); return; }
|
||||
btn.disabled = true;
|
||||
note.textContent = en() ? 'Preparing…' : '만드는 중…';
|
||||
var url = '/dispatch/period-export?date_from=' + encodeURIComponent(f) + '&date_to=' + encodeURIComponent(t);
|
||||
fetch(url)
|
||||
.then(function (r) {
|
||||
if (!r.ok) {
|
||||
return r.json().catch(function () { return {}; }).then(function (j) {
|
||||
throw new Error((j && j.detail) || ('HTTP ' + r.status));
|
||||
});
|
||||
}
|
||||
var cd = r.headers.get('Content-Disposition') || '';
|
||||
var m = cd.match(/filename\*=UTF-8''([^;]+)/);
|
||||
var name = m ? decodeURIComponent(m[1]) : ('shipped_' + f + '_' + t + '.xlsx');
|
||||
return r.blob().then(function (b) {
|
||||
var a = document.createElement('a');
|
||||
a.href = URL.createObjectURL(b);
|
||||
a.download = name;
|
||||
document.body.appendChild(a); a.click(); a.remove();
|
||||
setTimeout(function () { URL.revokeObjectURL(a.href); }, 1000);
|
||||
note.textContent = '';
|
||||
});
|
||||
})
|
||||
.catch(function (e) {
|
||||
note.textContent = (e && e.message) || (en() ? 'Failed' : '실패');
|
||||
})
|
||||
.then(function () { btn.disabled = false; });
|
||||
};
|
||||
})();
|
||||
|
||||
// ── 받는 사람 찾기(이름/주문/패키지/송장 번호 부분 일치) ──
|
||||
(function () {
|
||||
var wrap = document.getElementById('dsp-search');
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""기간별 발송 수량 엑셀(export.aggregate_shipped / build_period_xlsx) 테스트.
|
||||
|
||||
DB 없이 집계·엑셀 생성만 검증한다.
|
||||
python -m app.modules.dispatch.tests.test_period_export
|
||||
또는 pytest 로 실행 가능.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
from app.modules.dispatch import export
|
||||
|
||||
_ROWS = [
|
||||
{"dispatch_date": "2026-10-02", "seller_sku": "MT-0320", "product_name": "A", "qty": 2},
|
||||
{"dispatch_date": "2026-10-01", "seller_sku": "MT-0320_3", "product_name": "A", "qty": 1},
|
||||
{"dispatch_date": "2026-10-01", "seller_sku": "mt-0320", "product_name": "A", "qty": 1},
|
||||
{"dispatch_date": "2026-10-01", "seller_sku": "MY-0001", "product_name": "Set", "qty": 4},
|
||||
{"dispatch_date": "2026-10-02", "seller_sku": "", "product_name": "", "qty": 9},
|
||||
]
|
||||
|
||||
|
||||
def test_aggregate_multiplier_and_merge():
|
||||
"""_N 배수 반영 + 대소문자/접미사 다른 같은 코드 합산, 빈 코드 제외(BOM 없으면 세트 그대로)."""
|
||||
dates, names, qty = export.aggregate_shipped(_ROWS, {"MT-0320": "상품A"})
|
||||
assert dates == ["2026-10-01", "2026-10-02"], dates
|
||||
assert qty[("2026-10-01", "MT-0320")] == 4 # 1×3 + 1
|
||||
assert qty[("2026-10-02", "MT-0320")] == 2
|
||||
assert qty[("2026-10-01", "MY-0001")] == 4
|
||||
assert names["MT-0320"] == "상품A" # itemcode 이름 우선
|
||||
assert names["MY-0001"] == "Set" # 없으면 파싱된 이름
|
||||
|
||||
|
||||
_BOM = {"MY-0001": [
|
||||
{"component_code": "MT-0320", "component_qty": 1},
|
||||
{"component_code": "mt-0550", "component_qty": 2},
|
||||
]}
|
||||
|
||||
|
||||
def test_aggregate_explodes_sets():
|
||||
"""세트는 BOM 으로 낱개 분해해 같은 날 같은 낱개 코드에 합산."""
|
||||
dates, names, qty = export.aggregate_shipped(_ROWS, {"MT-0550": "상품B"}, _BOM)
|
||||
assert ("2026-10-01", "MY-0001") not in qty
|
||||
assert qty[("2026-10-01", "MT-0320")] == 8 # 1×3 + 1 + 세트 4×1
|
||||
assert qty[("2026-10-01", "MT-0550")] == 8 # 세트 4×2
|
||||
assert names["MT-0550"] == "상품B"
|
||||
assert export.missing_set_boms(_ROWS, _BOM) == []
|
||||
assert export.missing_set_boms(_ROWS, {}) == ["MY-0001"]
|
||||
|
||||
|
||||
def test_build_period_xlsx_sheets():
|
||||
from openpyxl import load_workbook
|
||||
|
||||
data = export.build_period_xlsx(
|
||||
rows=_ROWS, date_from="2026-10-01", date_to="2026-10-02", name_map={}, set_bom=_BOM
|
||||
)
|
||||
wb = load_workbook(io.BytesIO(data))
|
||||
assert wb.sheetnames == ["날짜별", "아이템별 요약", "세트별 요약"]
|
||||
|
||||
ws = wb["날짜별"]
|
||||
rows = list(ws.iter_rows(values_only=True))
|
||||
assert rows[0] == ("발송 날짜", "아이템 코드", "상품이름", "수량")
|
||||
assert rows[1] == ("2026-10-01", "MT-0320", "A", 8)
|
||||
assert rows[2] == ("2026-10-01", "MT-0550", None, 8)
|
||||
assert rows[3] == ("2026-10-02", "MT-0320", "A", 2)
|
||||
assert rows[-1][0] == "합계" and rows[-1][3] == 18
|
||||
|
||||
ws2 = wb["아이템별 요약"]
|
||||
rows2 = list(ws2.iter_rows(values_only=True))
|
||||
assert rows2[0] == ("아이템 코드", "상품이름", "2026-10-01", "2026-10-02", "합계")
|
||||
assert rows2[1] == ("MT-0320", "A", 8, 2, 10)
|
||||
assert rows2[2] == ("MT-0550", None, 8, None, 8)
|
||||
assert rows2[3] == ("합계", None, 16, 2, 18)
|
||||
|
||||
# 세트는 낱개로 풀기 전 세트 단위 수량, 날짜 열은 전체 발송 날짜와 같다.
|
||||
rows3 = list(wb["세트별 요약"].iter_rows(values_only=True))
|
||||
assert rows3[0] == ("세트 코드", "상품이름", "2026-10-01", "2026-10-02", "합계")
|
||||
assert rows3[1] == ("MY-0001", "Set", 4, None, 4)
|
||||
assert rows3[2] == ("합계", None, 4, 0, 4)
|
||||
|
||||
|
||||
def test_period_filename():
|
||||
assert export.period_filename("2026-10-01", "2026-10-28") == "2026.10.01-2026.10.28_shipped_qty.xlsx"
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_aggregate_multiplier_and_merge()
|
||||
test_aggregate_explodes_sets()
|
||||
test_build_period_xlsx_sheets()
|
||||
test_period_filename()
|
||||
print("OK")
|
||||
@@ -265,11 +265,11 @@ def expense_index(request: Request) -> HTMLResponse:
|
||||
get_current_user_record,
|
||||
render_template,
|
||||
)
|
||||
from app.store import has_module, is_admin # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return RedirectResponse(url="/login", status_code=303)
|
||||
return login_redirect(request)
|
||||
if not has_module(user, "expense"):
|
||||
return render_template(
|
||||
request,
|
||||
@@ -325,11 +325,11 @@ def pending_page(request: Request) -> HTMLResponse:
|
||||
get_current_user_record,
|
||||
render_template,
|
||||
)
|
||||
from app.store import has_module, is_admin # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return RedirectResponse(url="/login", status_code=303)
|
||||
return login_redirect(request)
|
||||
if not (is_admin(user) or has_module(user, "expense_approver")):
|
||||
return render_template(
|
||||
request,
|
||||
@@ -362,11 +362,11 @@ def reports_page(request: Request) -> HTMLResponse:
|
||||
get_current_user_record,
|
||||
render_template,
|
||||
)
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
from app.store import is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return RedirectResponse(url="/login", status_code=303)
|
||||
return login_redirect(request)
|
||||
store = _store(request)
|
||||
_require_db_store(store)
|
||||
year_str = request.query_params.get("year") or str(now_kst().year)
|
||||
@@ -436,11 +436,11 @@ def approved_page(request: Request) -> HTMLResponse:
|
||||
get_current_user_record,
|
||||
render_template,
|
||||
)
|
||||
from app.store import has_module, is_admin # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return RedirectResponse(url="/login", status_code=303)
|
||||
return login_redirect(request)
|
||||
if not (is_admin(user) or has_module(user, "expense_approver")):
|
||||
return render_template(
|
||||
request,
|
||||
@@ -667,11 +667,11 @@ def settings_page(request: Request) -> HTMLResponse:
|
||||
get_current_user_record,
|
||||
render_template,
|
||||
)
|
||||
from app.store import has_module, is_admin # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return RedirectResponse(url="/login", status_code=303)
|
||||
return login_redirect(request)
|
||||
if not (is_admin(user) or has_module(user, "expense_approver")):
|
||||
return render_template(
|
||||
request,
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
- 본사 → 공장 제품 제작 발주(발주서 `PO-YYMMDD-NN`). 제품 = `itemcode_db.single_items` 단품만, 검색 `GET /inout/api/items`·저장 때 서버 재확인.
|
||||
- 물류 입고를 여러 번 나눠 입력, 품목별 발주·입고·미입고.
|
||||
- 미입고 현황(제품별 합계·발주별·지연).
|
||||
- 발주 목록 상태 보기(진행 중·완료·종결·취소·전체)는 **사람마다 기억**(2026-11-04) — `inout_settings` 키 `list_status:{이메일}`(마이그레이션 없음, 005 미적용이면 기억만 안 함). 주소에 `status` 가 있으면 저장, 없으면 저장값, 그것도 없으면 진행 중.
|
||||
- [남은 수량 모두 채우기]를 한 번 더 누르면(= [채운 수량 되돌리기]) 채우기 전 값으로(2026-10-19, `inout.js`).
|
||||
- 초과 입고는 확인 화면 후 허용(트랜잭션 안에서 발주서 잠그고 판단, `confirm_over`).
|
||||
- **전체 입고 완료(모든 품목 입고 ≥ 발주, 상태 done·over)면 더 입고 못 함**(2026-10-19) — 화면은 입고 칸·[입고 저장]·사진·[남은 수량 채우기]를 흐리게 disabled, 서버 `_add_receipt` 도 잠근 뒤 거절. 입고 기록을 지우면 다시 열림.
|
||||
@@ -32,9 +33,16 @@
|
||||
**휴가 모듈도 같은 연결을 쓴다**(2026-10-27) — 휴가 옵션 [Gmail 연결]은 세션 `_gmail_origin=vacation` 을 달고 같은 콜백(`/inout/gmail/callback`)으로 돌아오며,
|
||||
콜백이 `_gmail_callback_vacation`(휴가 권한 확인, 휴가 옵션으로 복귀)으로 넘긴다. 토큰 표·끊기는 공용 — 바꾸면 휴가 메일(`vacation/notify.py`)도 확인.
|
||||
- 보낸 기록·재발송 확인.
|
||||
- **본문 고치기**(2026-10-27): 발주 메일 미리보기 iframe 이 `designMode`(sandbox `allow-same-origin`, 스크립트 없음) — 고치면 [원래 본문으로]·닫을 때 확인,
|
||||
보낼 때만 `html` 을 함께 POST → `store.clean_mail_html`(허용 태그·표·인라인 서식만, url()·이벤트·스크립트 제거) + 글 버전 `mail_html_to_text`. 안 고치면 서버 본문 그대로. 입고 요청 메일은 고치기 없음(cid 사진).
|
||||
**서식 막대**(`initMail` 안 `RTE_BAR`, 안내문 발송 편집기와 같은 구성: 크기·굵게·기울임·밑줄·취소선·글자/배경 색·정렬·목록·링크·서식 지우기·되돌리기) = iframe `execCommand`(styleWithCSS → span style).
|
||||
Quill 은 표를 못 담아 안 씀. 크기는 fontSize 7 → px span 으로 바꿔 끼움. 선택은 본문 문서의 현재 선택 우선(막대 mousedown 때 기억은 대비용). 서버는 `text-decoration-line` → `text-decoration`.
|
||||
- **입고 담당 발주 알림 자동 발송**(2026-10-19): 발주 메일이 나가면 같은 Gmail 로 옵션 → 담당자의 입고 담당들에게 따로 보냄 — 제목은 발주 메일과 같고 내용은 발주번호·발주일·제품 코드·제품명·수량만(`store.order_notice_mail`, `router._send_order_notice`). 실패해도 공장 메일은 그대로(안내만), 미리보기 창에 받을 사람 안내.
|
||||
- **참조 기본값 `king@dbxcorp.co.kr`**(2026-10-19) — 미리보기 참조 칸에 미리 들어감, 옵션 → 공장 탭 "발주 메일 참조"에서 고침(`inout_settings` `order_mail_cc`, 행이 없으면 기본값 — 저장만 005 필요).
|
||||
|
||||
- **간단 발주 메일**(2026-11-04): 공장 이름에 "대성화학"·"인천공장"이 들어가면(`store.SIMPLE_MAIL_FACTORIES`, 띄어쓰기 무시) 품목 표 = 번호·제품 코드·제품명·수량·**박스당 수량·박스 수**·비고만, 요약 표·글 본문에서도 금액·무게·PP·은을 뺀다(단가가 공장에 나가지 않게). 색상 줄 배경·합계 수량은 그대로.
|
||||
박스 값은 발주 품목 사본이 아니라 **메일을 만들 때의 상품 정보**(`router._mail_order` → `store.line_boxes`, 뚜껑 있으면 통·뚜껑 따로, 입수 없으면 `-`). 다른 공장 메일엔 박스 칸 없음.
|
||||
|
||||
## 입고 요청 메일 (005, 2026-10-19)
|
||||
|
||||
- 입고 담당이 **입고 저장** → 발주서 화면 `?rmail={입고 id}` 로 미리보기 팝업이 바로 뜸 → [메일 발송](입고 담당 본인 Gmail, 발주 메일과 같은 연결 — Gmail 연결 권한은 발주·입고 담당 `_require(…, "mail")`). 입고 기록 줄 [보내기/다시 보내기]로 언제든.
|
||||
@@ -52,6 +60,8 @@
|
||||
|
||||
- 입고 저장 때 첨부(브라우저가 2000px JPEG 로 줄임, 10장·10MB, 파일 머리 검사, 입고와 한 트랜잭션, bytea).
|
||||
- 썸네일·크게 보기·나중에 더하기. 초과 확인은 브라우저가 먼저(사진 유지).
|
||||
- **돌리기**(2026-11-02) — 크게 보기 창 왼쪽·오른쪽 버튼(입고 담당) → `POST /inout/orders/{id}/photos/{pid}/rotate?degrees=90|270` → 서버가 **저장된 사진 자체**를 돌려 덮어씀(`store.rotate_image`, EXIF 회전을 픽셀에 반영, 같은 형식, JPEG 품질 92) — 원본 링크·입고 요청 메일도 돌린 사진. 되돌리기 = 반대로 돌리기. HEIC·움직이는 GIF 는 못 돌림(HEIC 은 버튼 숨김).
|
||||
사진 응답은 `no-cache` + ETag(돌린 뒤 예전 사진이 캐시에 남지 않게).
|
||||
|
||||
## 상품 정보 (004, 옵션 세 번째 탭)
|
||||
|
||||
@@ -87,6 +97,13 @@
|
||||
- 화면 계산만 — 발주 품목 사본·발주서 화면·**발주 메일에는 넣지 않음**(사용자 지정). 값은 지금 상품 정보(`_form_page` 의 `body_per_box`, `/api/items`).
|
||||
- 007 확인 `db.boxes_ready`(groups_ready 와 같은 방식 — 연결 열기 전, 미적용 1분 기억). 그룹·색상 조회(`_PRODUCT_SELECT_006`)는 `p.*` 라 새 열이 따라온다.
|
||||
|
||||
## 봉투·백 (008, 2026-11-04)
|
||||
|
||||
- 이름에 **"미라클 봉투"·"미라클백"** 이 들어간 상품(`store.is_bag`, 저장 안 함 — 이름으로 판단) = 옵션 → 상품 정보에서 일반 상품과 **표를 나눔**(봉투·백 표가 위). 칸: **박스당 수량**(`body_per_box` 재사용)·**1파렛트당 박스 수량**(`inout_products.boxes_per_pallet`). 뚜껑 없음(저장하면 `lid_per_box` 는 NULL).
|
||||
**단가·무게·은 칸 없음**(2026-11-04 사용자 지정) — 전에 넣은 값은 줄의 숨은 칸으로 저장 때 그대로 보내 지우지 않음. 그룹·색상 칸은 있음. 새 발주서 "단가 없는 N종"·발주서 화면과 발주 메일의 "단가 미입력 N종"(`store.order_totals`) 안내에서 봉투·백은 뺌.
|
||||
- 새 발주서 합계 줄에 봉투·백 박스·파렛트를 **통·뚜껑과 따로** 표시: 파렛트 = ⌈Σ(박스 ÷ 그 상품 1파렛트 박스)⌉. 파렛트 그림도 통처럼(`palletVis(all, cap, mixed)`, 그림 칸은 60칸까지) — 1파렛트 박스 수가 다른 상품이 섞이면 가장 큰 값으로 환산해 잔량은 %만. 입수·1파렛트 값은 `store.box_info`(`_form_page`·`/api/items`).
|
||||
- 008 확인 `db.bags_ready`(boxes_ready 와 같은 방식). 미적용이면 모두 일반 상품으로 동작.
|
||||
|
||||
## 오른쪽 달력 (2026-10-21)
|
||||
|
||||
- 입출고 **모든 화면** 2열(`.io-split` = 왼쪽 `section.io` | 오른쪽 `_calendar.html`, 1100px 미만은 한 열 300px). 스크롤해도 위에 붙음.
|
||||
|
||||
@@ -432,6 +432,19 @@ class InoutDBStore:
|
||||
if not row:
|
||||
raise ValueError("사진을 찾을 수 없습니다.")
|
||||
|
||||
def rotate_receipt_photo(self, order_id: int, photo_id: int, degrees: int) -> None:
|
||||
"""저장된 사진 자체를 돌린다(2026-11-02) — 화면·원본·입고 요청 메일 모두 돌린 사진."""
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
head = self._lock_order(conn, order_id)
|
||||
if head["cancelled_at"]:
|
||||
raise ValueError("취소된 발주서입니다.")
|
||||
row = conn.execute("SELECT p.data FROM inout_receipt_photos p JOIN inout_receipts r ON r.id = p.receipt_id "
|
||||
"WHERE p.id=%s AND r.order_id=%s", (photo_id, order_id)).fetchone()
|
||||
if not row:
|
||||
raise ValueError("사진을 찾을 수 없습니다.")
|
||||
data = store.rotate_image(bytes(row["data"]), degrees)
|
||||
conn.execute("UPDATE inout_receipt_photos SET data=%s, size_bytes=%s WHERE id=%s", (data, len(data), photo_id))
|
||||
|
||||
def get_photo(self, photo_id: int) -> dict[str, Any] | None:
|
||||
"""사진 내용(+ 발주서 id) — 보여 주기용."""
|
||||
try:
|
||||
@@ -510,6 +523,22 @@ class InoutDBStore:
|
||||
except UndefinedTable:
|
||||
raise ValueError("DB 마이그레이션 inout_db 005(물류센터 이메일·입고 요청 메일)가 아직 적용되지 않았습니다.") from None
|
||||
|
||||
# 발주 목록 상태 거르기 — 사람마다 기억(2026-11-04). 같은 설정 표에 사람별 키(마이그레이션 없음), 005 미적용이면 기억만 안 한다.
|
||||
def get_list_status(self, email: str) -> str:
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute("SELECT value FROM inout_settings WHERE key = %s",
|
||||
("list_status:" + _norm_email(email),)).fetchone()
|
||||
except UndefinedTable:
|
||||
return ""
|
||||
return row["value"] if row else ""
|
||||
|
||||
def save_list_status(self, email: str, status: str) -> None:
|
||||
try:
|
||||
self.save_settings({"list_status:" + _norm_email(email): status}, by=email)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def receipt_photo_data(self, receipt_id: int) -> list[dict[str, Any]]:
|
||||
"""입고 1건의 사진 내용(메일 본문에 넣기) — 올린 순서."""
|
||||
try:
|
||||
@@ -608,7 +637,12 @@ class InoutDBStore:
|
||||
self._need_products()
|
||||
grouped = self.groups_ready() and any("group_id" in r for r in rows)
|
||||
boxed = self.boxes_ready() and any("body_per_box" in r for r in rows)
|
||||
bagged = self.bags_ready() and any("boxes_per_pallet" in r for r in rows)
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
if bagged: # 008 — 봉투·백 1파렛트당 박스 수량
|
||||
for r in rows:
|
||||
if "boxes_per_pallet" in r:
|
||||
conn.execute("UPDATE inout_products SET boxes_per_pallet=%s WHERE item_code=%s", (r["boxes_per_pallet"], r["code"]))
|
||||
if boxed: # 007 — 통·뚜껑 박스 입수(그룹과 무관, 상품마다)
|
||||
for r in rows:
|
||||
if "body_per_box" in r:
|
||||
@@ -730,6 +764,22 @@ class InoutDBStore:
|
||||
self._boxes_checked = time.monotonic()
|
||||
return ok
|
||||
|
||||
def bags_ready(self) -> bool:
|
||||
"""008 이 적용됐나(상품 boxes_per_pallet). boxes_ready 와 같은 방식."""
|
||||
if getattr(self, "_bags_ok", False):
|
||||
return True
|
||||
if time.monotonic() - getattr(self, "_bags_checked", -1e9) < 60:
|
||||
return False
|
||||
if not self.products_ready():
|
||||
return False
|
||||
with self._pool.connection() as conn:
|
||||
ok = bool(conn.execute(
|
||||
"SELECT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = 'inout_products' "
|
||||
"AND column_name = 'boxes_per_pallet') AS ok").fetchone()["ok"])
|
||||
self._bags_ok = ok
|
||||
self._bags_checked = time.monotonic()
|
||||
return ok
|
||||
|
||||
def _need_groups(self) -> None:
|
||||
if not self.groups_ready():
|
||||
raise ValueError("DB 마이그레이션 inout_db 006(상품 그룹·색상)이 아직 적용되지 않았습니다.")
|
||||
|
||||
+50
-14
@@ -11,7 +11,7 @@
|
||||
GET /inout/settings?panel=1 옵션 팝업 내용(톱니, ERP 관리자) — 공장 목록·발주 담당·입고 담당
|
||||
POST /inout/settings/… 옵션 저장 — 팝업(X-Inout-Options: 1)이면 JSON, 아니면 목록으로 이동
|
||||
POST /inout/settings/products/import|save · /products/{code}/exclude|restore 옵션 → 상품 정보(단가·무게·은 함유량, 004)
|
||||
POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete · GET /inout/photos/{pid} 입고증 사진
|
||||
POST /inout/orders/{id}/receipts/{rid}/photos · /orders/{id}/photos/{pid}/delete|rotate · GET /inout/photos/{pid} 입고증 사진
|
||||
GET|POST /inout/orders/{id}/mail 발주 메일 미리보기·발송(발주 담당 본인 Gmail, 사람이 눌러야 보냄)
|
||||
GET|POST /inout/orders/{id}/receipts/{rid}/mail 입고 요청 메일(물류센터, 입고 담당 본인 Gmail, 005)
|
||||
POST /inout/settings/logistics 옵션 → 물류센터(입고 요청 메일 받는 주소·참조, 005)
|
||||
@@ -68,13 +68,11 @@ def _user(request: Request) -> dict[str, Any]:
|
||||
|
||||
def _page_user(request: Request) -> Any:
|
||||
"""화면 주소 — 로그인 전이면 로그인으로 보냈다가 돌아온다."""
|
||||
from urllib.parse import quote # noqa: WPS433
|
||||
|
||||
from app.main import get_current_user_record # noqa: WPS433
|
||||
from app.store import login_redirect # noqa: WPS433
|
||||
|
||||
if get_current_user_record(request) is None:
|
||||
here = str(request.url.path) + ("?" + request.url.query if request.url.query else "")
|
||||
return RedirectResponse(url="/login?next=" + quote(here, safe=""), status_code=303)
|
||||
return login_redirect(request)
|
||||
return _user(request)
|
||||
|
||||
|
||||
@@ -173,13 +171,17 @@ def _opt_date(v: Any) -> date | None:
|
||||
# 발주 목록 · 미입고 현황
|
||||
# ────────────────────────────────────────────────────────────
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
def index(request: Request, status: str = "active", factory: str = "", q: str = "", date_from: str = Query("", alias="from"),
|
||||
def index(request: Request, status: str = "", factory: str = "", q: str = "", date_from: str = Query("", alias="from"),
|
||||
date_to: str = Query("", alias="to")) -> Any:
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
status = status if status in store.STATUS_FILTERS else "active"
|
||||
saved = st.get_list_status(user.get("email", ""))
|
||||
if status not in store.STATUS_FILTERS: # 주소에 상태가 없으면 이 사람이 마지막으로 고른 보기
|
||||
status = saved if saved in store.STATUS_FILTERS else "active"
|
||||
elif status != saved:
|
||||
st.save_list_status(user.get("email", ""), status)
|
||||
orders = st.list_orders(status=status, factory_id=_opt_int(factory), q=q, date_from=_opt_date(date_from),
|
||||
date_to=_opt_date(date_to))
|
||||
return _render(request, "inout/index.html", user, {
|
||||
@@ -265,7 +267,7 @@ def _form_page(request: Request, user: dict[str, Any], st: Any, *, order: dict[s
|
||||
ln["price"] = float(price) if price is not None else None
|
||||
ln["price_label"] = store.fmt_num(price) if price is not None else ""
|
||||
bx = boxes.get(ln["code"]) or {} # 박스 입수(007) — 지금 상품 정보 값(발주 품목에 남기지 않음)
|
||||
ln["body_per_box"], ln["lid_per_box"] = bx.get("body_per_box"), bx.get("lid_per_box")
|
||||
ln.update(store.box_info(bx))
|
||||
reader = _items(request)
|
||||
catalog_n = st.catalog_count()
|
||||
return _render(request, "inout/order_form.html", user, {
|
||||
@@ -488,7 +490,7 @@ def receipt_delete(request: Request, order_id: int, receipt_id: int) -> Any:
|
||||
_PHOTO_HEADERS = {
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Content-Security-Policy": "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox",
|
||||
"Cache-Control": "private, max-age=86400",
|
||||
"Cache-Control": "private, no-cache",
|
||||
}
|
||||
|
||||
|
||||
@@ -532,6 +534,21 @@ def receipt_photo_delete(request: Request, order_id: int, photo_id: int) -> Any:
|
||||
return _redirect(f"/inout/orders/{order_id}", "사진을 지웠습니다.")
|
||||
|
||||
|
||||
@router.post("/orders/{order_id}/photos/{photo_id}/rotate")
|
||||
def receipt_photo_rotate(request: Request, order_id: int, photo_id: int, degrees: int = Query(...)) -> Any:
|
||||
"""크게 보기 창의 회전 버튼 — 창을 닫지 않게 JSON 으로 답한다(화면이 사진을 다시 받아 그림)."""
|
||||
got = _ctx(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
_require(st, user, "receive")
|
||||
try:
|
||||
st.rotate_receipt_photo(order_id, photo_id, degrees)
|
||||
except (ValueError, LookupError) as exc:
|
||||
return JSONResponse({"error": str(exc)}, status_code=400)
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
|
||||
@router.get("/photos/{photo_id}")
|
||||
def photo_view(request: Request, photo_id: int) -> Response:
|
||||
_user(request)
|
||||
@@ -539,12 +556,18 @@ def photo_view(request: Request, photo_id: int) -> Response:
|
||||
row = st.get_photo(photo_id) if st is not None else None
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404, detail="사진을 찾을 수 없습니다.")
|
||||
from hashlib import md5 # noqa: WPS433
|
||||
from urllib.parse import quote # noqa: WPS433
|
||||
|
||||
data = bytes(row["data"])
|
||||
# 돌린 사진이 하루 동안 예전 모습으로 남지 않게 — 브라우저가 매번 내용이 같은지 묻는다(no-cache + ETag)
|
||||
etag = '"' + md5(data, usedforsecurity=False).hexdigest() + '"'
|
||||
if request.headers.get("if-none-match") == etag:
|
||||
return Response(status_code=304, headers={"ETag": etag, "Cache-Control": _PHOTO_HEADERS["Cache-Control"]})
|
||||
name = quote(str(row["filename"] or f"photo-{photo_id}"))
|
||||
disp = "attachment" if row["content_type"] == "image/heic" else "inline" # HEIC 은 브라우저가 못 보여 줌 → 내려받기
|
||||
return Response(content=bytes(row["data"]), media_type=row["content_type"],
|
||||
headers={**_PHOTO_HEADERS, "Content-Disposition": f"{disp}; filename*=UTF-8''{name}"})
|
||||
return Response(content=data, media_type=row["content_type"],
|
||||
headers={**_PHOTO_HEADERS, "ETag": etag, "Content-Disposition": f"{disp}; filename*=UTF-8''{name}"})
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
@@ -640,7 +663,8 @@ async def _gmail_callback_vacation(request: Request) -> Any:
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return RedirectResponse(url="/login?next=" + quote(nxt, safe=""), status_code=303)
|
||||
if not has_module(user, origin):
|
||||
# 휴가 협의자는 휴가 권한이 없어도 연결한다 — 휴가 연결 시작 때 그 신청의 협의자인지 확인해 세션에 남긴 값(2026-11-02)
|
||||
if not request.session.pop("_gmail_consultant", False) and not has_module(user, origin):
|
||||
raise HTTPException(status_code=403, detail=denied)
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
@@ -685,6 +709,10 @@ def _mail_order(request: Request, order_id: int) -> tuple[Any, dict[str, Any], d
|
||||
order = _order_or_404(st, order_id)
|
||||
if order["cancelled_at"]:
|
||||
raise HTTPException(status_code=400, detail="취소된 발주서는 메일로 보낼 수 없습니다.")
|
||||
if store.is_simple_mail_factory(order["factory_name"]) and st.boxes_ready(): # 박스 칸 — 발주 품목에 없어 지금 상품 정보 값
|
||||
found = st.catalog_lookup([x["item_code"] for x in order["lines"]])
|
||||
for x in order["lines"]:
|
||||
x.update(store.box_info(found.get(x["item_code"]) or {}))
|
||||
return st, user, order
|
||||
|
||||
|
||||
@@ -718,6 +746,8 @@ def mail_send(request: Request, order_id: int, payload: dict[str, Any] = Body(..
|
||||
try:
|
||||
to = store.parse_emails(payload.get("to"), label="받는 사람", required=True)
|
||||
cc = store.parse_emails(payload.get("cc"), label="참조")
|
||||
# 미리보기 창에서 본문을 고쳤으면 그 HTML(2026-10-27) — 안 고쳤으면 보내지 않고 서버가 만든 본문 그대로
|
||||
edited = store.clean_mail_html(payload["html"]) if payload.get("html") else None
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc)) from None
|
||||
if order["mails"] and not payload.get("resend"):
|
||||
@@ -728,6 +758,8 @@ def mail_send(request: Request, order_id: int, payload: dict[str, Any] = Body(..
|
||||
return JSONResponse({"ok": False, "reconnect": True, "message": "Gmail 이 연결되지 않았습니다 — 먼저 [Gmail 연결]을 하세요."},
|
||||
status_code=409)
|
||||
mail = store.order_mail(order, sender_name=str(user.get("name") or ""), sender_email=email)
|
||||
if edited is not None:
|
||||
mail = {**mail, "html": edited, "text": store.mail_html_to_text(edited)}
|
||||
try:
|
||||
refresh = gmail.decrypt_token(email, row["refresh_token_enc"])
|
||||
raw = gmail.build_message(sender_name=str(user.get("name") or ""), sender_email=email, to=to, cc=cc,
|
||||
@@ -911,8 +943,10 @@ def _options_ctx(request: Request, st: Any) -> dict[str, Any]:
|
||||
known.add(e)
|
||||
reader = _items(request)
|
||||
products = st.list_products()
|
||||
bags_ready = st.bags_ready()
|
||||
for pr in products:
|
||||
pr["silver_g"] = store.silver_g(pr.get("weight_g"), pr.get("silver_pct"))
|
||||
pr["is_bag"] = bags_ready and store.is_bag(pr.get("item_name"))
|
||||
return {"products": products, "excluded": st.list_excluded(), "products_ready": st.products_ready(),
|
||||
"groups": st.list_groups(), "groups_ready": st.groups_ready(), "colors": store.COLORS,
|
||||
"boxes_ready": st.boxes_ready(),
|
||||
@@ -1071,7 +1105,9 @@ def settings_products_save(request: Request, payload: dict[str, Any] = Body(...)
|
||||
code = str((r or {}).get("code") or "").strip().upper()
|
||||
try:
|
||||
row = {"code": code, **store.validate_product_values(r)}
|
||||
if "body_per_box" in (r or {}): # 007 — 통·뚜껑 박스 입수(빈칸 = 없음)
|
||||
if "boxes_per_pallet" in (r or {}): # 008 — 봉투·백(박스당 수량·1파렛트당 박스 수량)
|
||||
row.update(store.validate_bag_values(r))
|
||||
elif "body_per_box" in (r or {}): # 007 — 통·뚜껑 박스 입수(빈칸 = 없음)
|
||||
row.update(store.validate_box_values(r))
|
||||
if "group_id" in (r or {}): # 006 — 그룹(빈칸 = 그룹 없음)·상품 자기 색상
|
||||
gid = str(r.get("group_id") or "").strip()
|
||||
@@ -1170,7 +1206,7 @@ def api_items(request: Request, q: str = "") -> JSONResponse:
|
||||
"weight_g": store.fmt_num(r["weight_g"]) if r["weight_g"] is not None else "",
|
||||
"silver_pct": store.fmt_num(r["silver_pct"], 4) if r["silver_pct"] is not None else "",
|
||||
"color": r.get("color") or "none",
|
||||
"body_per_box": r.get("body_per_box"), "lid_per_box": r.get("lid_per_box")} for r in rows]})
|
||||
**store.box_info(r)} for r in rows]})
|
||||
reader = _items(request)
|
||||
if reader is None or not reader.enabled:
|
||||
return JSONResponse({"items": [], "enabled": False,
|
||||
|
||||
+256
-27
@@ -9,6 +9,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import html as _html
|
||||
import html.parser as _html_parser
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||
@@ -247,6 +248,28 @@ def parse_emails(raw: Any, *, label: str = "이메일", required: bool = False)
|
||||
return out
|
||||
|
||||
|
||||
# 간단 발주 메일(2026-11-04) — 이 공장들엔 품목 표를 번호·제품 코드·제품명·수량·박스당 수량·박스 수·비고만, 요약에서도 금액·무게·은을 뺀다.
|
||||
SIMPLE_MAIL_FACTORIES = ("대성화학", "인천공장")
|
||||
|
||||
|
||||
def is_simple_mail_factory(name: Any) -> bool:
|
||||
"""이름 일부·띄어쓰기가 달라도 맞게 — 놓치면 단가가 공장에 나간다."""
|
||||
compact = "".join(str(name or "").split())
|
||||
return any(word in compact for word in SIMPLE_MAIL_FACTORIES)
|
||||
|
||||
|
||||
def line_boxes(x: dict[str, Any]) -> dict[str, Any]:
|
||||
"""간단 발주 메일 칸 — 박스당 수량·박스 수(올림). 뚜껑이 있으면 통·뚜껑 따로, 입수가 없으면 '-'(total None)."""
|
||||
body, lid, qty = x.get("body_per_box"), x.get("lid_per_box"), int(x["qty"])
|
||||
if not body:
|
||||
return {"per": "-", "count": "-", "total": None}
|
||||
boxes = -(-qty // body)
|
||||
if not lid:
|
||||
return {"per": f"{body:,}개", "count": f"{boxes:,}박스", "total": boxes}
|
||||
lids = -(-qty // lid)
|
||||
return {"per": f"통 {body:,}개 · 뚜껑 {lid:,}개", "count": f"통 {boxes:,} · 뚜껑 {lids:,}박스", "total": boxes + lids}
|
||||
|
||||
|
||||
def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) -> dict[str, str]:
|
||||
"""발주서 → 메일 제목·글 본문·HTML 본문(요약). order = db.get_order 결과.
|
||||
품목마다 단가·금액(수량 × 단가)·전체 무게(개당 g × 수량, kg)·PP 사용량(전체 무게 − 은 무게, kg)·은 함유량(%·전체 무게 × %, kg)
|
||||
@@ -262,16 +285,18 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
||||
who = sender_name or sender_email
|
||||
facts = [("발주번호", order["order_no"]), ("발주일", fmt_date(order["order_date"])),
|
||||
("입고 예정일", due), ("품목", f"{len(lines)}종 · 총 {total:,}개")]
|
||||
if money["amount"] is not None:
|
||||
note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else ""
|
||||
facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}"))
|
||||
simple = is_simple_mail_factory(order.get("factory_name"))
|
||||
ag_kg = money["silver_g"] / Decimal(1000) if money["silver_g"] is not None else None
|
||||
if money["pp_kg"] is not None:
|
||||
facts.append(("전체 무게", f"{fmt_num(money['pp_kg'], 3)} kg"))
|
||||
if money["pp_use_kg"] is not None:
|
||||
facts.append(("PP 사용량", f"{fmt_num(money['pp_use_kg'], 3)} kg"))
|
||||
if ag_kg is not None:
|
||||
facts.append(("은(Ag) 총량", f"{fmt_num(ag_kg, 4)} kg"))
|
||||
if not simple:
|
||||
if money["amount"] is not None:
|
||||
note = f" (단가 미입력 {money['missing_price']}종 제외)" if money["missing_price"] else ""
|
||||
facts.append(("발주 금액", f"{fmt_num(money['amount'])}원{note}"))
|
||||
if money["pp_kg"] is not None:
|
||||
facts.append(("전체 무게", f"{fmt_num(money['pp_kg'], 3)} kg"))
|
||||
if money["pp_use_kg"] is not None:
|
||||
facts.append(("PP 사용량", f"{fmt_num(money['pp_use_kg'], 3)} kg"))
|
||||
if ag_kg is not None:
|
||||
facts.append(("은(Ag) 총량", f"{fmt_num(ag_kg, 4)} kg"))
|
||||
if order.get("memo"):
|
||||
facts.append(("요청 사항", order["memo"]))
|
||||
|
||||
@@ -288,12 +313,17 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
||||
# 글 본문(HTML 을 못 보는 메일 프로그램용)
|
||||
text = [greet, "", "아래와 같이 제품 제작을 발주합니다.", ""]
|
||||
text += [f"- {k}: {v}" for k, v in facts]
|
||||
text += ["", "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · PP 사용량 · 은 함유량"]
|
||||
text += ["", "[발주 품목] 제품 코드 · 제품명 · 수량 · 박스당 수량 · 박스 수 · 비고" if simple else "[발주 품목] 수량 · 단가 · 금액 · 전체 무게 · PP 사용량 · 은 함유량"]
|
||||
for i, x in enumerate(lines, start=1):
|
||||
c = cells(x)
|
||||
text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개 · 단가 {c['price']} · 금액 {c['amount']}"
|
||||
f" · 전체 무게 {c['weight'] + 'kg' if c['weight'] != '-' else '-'}"
|
||||
f" · PP 사용량 {c['pp_use'] + 'kg' if c['pp_use'] != '-' else '-'} · 은 {c['ag']}"
|
||||
b = line_boxes(x)
|
||||
if simple:
|
||||
detail = f" · 박스당 {b['per']} · {b['count']}" if b["total"] is not None else ""
|
||||
else:
|
||||
detail = (f" · 단가 {c['price']} · 금액 {c['amount']}"
|
||||
f" · 전체 무게 {c['weight'] + 'kg' if c['weight'] != '-' else '-'}"
|
||||
f" · PP 사용량 {c['pp_use'] + 'kg' if c['pp_use'] != '-' else '-'} · 은 {c['ag']}")
|
||||
text.append(f"{i}. {x['item_code']} {x['item_name']} — {int(x['qty']):,}개{detail}"
|
||||
+ (f" ({x['memo']})" if x.get("memo") else ""))
|
||||
text += ["", "입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.", "", f"발주 담당: {who} ({sender_email})"]
|
||||
# HTML 본문 — 값은 모두 escape
|
||||
@@ -322,12 +352,14 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
||||
hexc = color_hex(x.get("color"))
|
||||
ctd = f"{td}background:{hexc};" if hexc else td
|
||||
tr_style = f' style="background:{hexc}"' if hexc else ""
|
||||
b = line_boxes(x)
|
||||
detail = (f'<td style="{ctd}{r}">{e(b["per"])}</td><td style="{ctd}{r}">{e(b["count"])}</td>') if simple else (
|
||||
f'<td style="{ctd}{r}">{e(c["price"])}</td><td style="{ctd}{r}">{e(c["amount"])}</td>'
|
||||
f'<td style="{ctd}{r}">{e(c["weight"])}</td><td style="{ctd}{r}">{e(c["pp_use"])}</td><td style="{ctd}{r}">{e(c["ag"])}</td>')
|
||||
rows.append(
|
||||
f'<tr{tr_style}><td style="{ctd}text-align:center">{i}</td>'
|
||||
f'<td style="{ctd}font-family:Consolas,monospace">{e(x["item_code"])}</td>'
|
||||
f'<td style="{ctd}">{e(x["item_name"])}</td><td style="{ctd}{r}">{int(x["qty"]):,}</td>'
|
||||
f'<td style="{ctd}{r}">{e(c["price"])}</td><td style="{ctd}{r}">{e(c["amount"])}</td>'
|
||||
f'<td style="{ctd}{r}">{e(c["weight"])}</td><td style="{ctd}{r}">{e(c["pp_use"])}</td><td style="{ctd}{r}">{e(c["ag"])}</td>'
|
||||
f'<td style="{ctd}">{e(x["item_name"])}</td><td style="{ctd}{r}">{int(x["qty"]):,}</td>{detail}'
|
||||
f'<td style="{ctd}">{e(x.get("memo") or "")}</td></tr>')
|
||||
# 합계 줄(2026-10-21) — 금액 뒤 " 원", 무게 뒤 " kg", 무게는 소수 첫째 자리에서 반올림(정수 kg)
|
||||
foot_amount = f'{fmt_num(money["amount"])} 원' if money["amount"] is not None else ""
|
||||
@@ -335,6 +367,16 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
||||
foot_use = f'{fmt_num(money["pp_use_kg"], 0)} kg' if money["pp_use_kg"] is not None else ""
|
||||
foot_ag = f'{fmt_num(ag_kg, 0)} kg' if ag_kg is not None else ""
|
||||
bg = "background:#f6f7f9;"
|
||||
box_totals = [t for t in (line_boxes(x)["total"] for x in lines) if t is not None]
|
||||
foot_boxes = f"{sum(box_totals):,}박스" if box_totals else ""
|
||||
if box_totals and len(box_totals) < len(lines):
|
||||
foot_boxes += f" (미설정 {len(lines) - len(box_totals)}종 제외)"
|
||||
head_detail = f'<th style="{td}">박스당 수량</th><th style="{td}">박스 수</th>' if simple else (
|
||||
f'<th style="{td}">단가(원)</th><th style="{td}">금액(원)</th>'
|
||||
f'<th style="{td}">전체 무게(kg)</th><th style="{td}">PP 사용량(kg)</th><th style="{td}">은(Ag) 함유량</th>')
|
||||
foot_detail = f'<th style="{td}{bg}"></th><th style="{td}{bg}{r}">{e(foot_boxes)}</th>' if simple else (
|
||||
f'<th style="{td}{bg}"></th><th style="{td}{bg}{r}">{e(foot_amount)}</th>'
|
||||
f'<th style="{td}{bg}{r}">{e(foot_pp)}</th><th style="{td}{bg}{r}">{e(foot_use)}</th><th style="{td}{bg}{r}">{e(foot_ag)}</th>')
|
||||
html = (
|
||||
'<div style="font-family:\'Malgun Gothic\',\'Apple SD Gothic Neo\',sans-serif;font-size:14px;color:#1d1d1f;line-height:1.6">'
|
||||
f"<p>{e(greet)}<br>아래와 같이 제품 제작을 발주합니다.</p>"
|
||||
@@ -342,14 +384,12 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
||||
# 두 표 사이 18px — 표 margin 은 메일 프로그램마다 무시되기도 해서 높이 18px 빈 줄로 띄운다
|
||||
'<div style="height:18px;line-height:18px;font-size:1px"> </div>'
|
||||
'<table style="border-collapse:collapse;min-width:640px;margin:0">'
|
||||
f'<thead><tr style="{bg}"><th style="{td}">No</th><th style="{td}">제품 코드</th><th style="{td}">제품명</th>'
|
||||
f'<th style="{td}">수량</th><th style="{td}">단가(원)</th><th style="{td}">금액(원)</th>'
|
||||
f'<th style="{td}">전체 무게(kg)</th><th style="{td}">PP 사용량(kg)</th><th style="{td}">은(Ag) 함유량</th>'
|
||||
f'<thead><tr style="{bg}"><th style="{td}">{"번호" if simple else "No"}</th><th style="{td}">제품 코드</th><th style="{td}">제품명</th>'
|
||||
f'<th style="{td}">수량</th>{head_detail}'
|
||||
f'<th style="{td}">비고</th></tr></thead>'
|
||||
f'<tbody>{"".join(rows)}</tbody>'
|
||||
f'<tfoot><tr><th colspan="3" style="{td}{bg}text-align:right">합계</th>'
|
||||
f'<th style="{td}{bg}{r}">{total:,}</th><th style="{td}{bg}"></th><th style="{td}{bg}{r}">{e(foot_amount)}</th>'
|
||||
f'<th style="{td}{bg}{r}">{e(foot_pp)}</th><th style="{td}{bg}{r}">{e(foot_use)}</th><th style="{td}{bg}{r}">{e(foot_ag)}</th>'
|
||||
f'<th style="{td}{bg}{r}">{total:,}</th>{foot_detail}'
|
||||
f'<th style="{td}{bg}"></th></tr></tfoot></table>'
|
||||
"<p>입고 예정일까지 물류로 입고 부탁드리며, 일정이 바뀌면 회신 부탁드립니다.</p>"
|
||||
f'<p style="color:#555">발주 담당: {e(who)} (<a href="mailto:{e(sender_email)}">{e(sender_email)}</a>)</p></div>'
|
||||
@@ -357,6 +397,138 @@ def order_mail(order: dict[str, Any], *, sender_name: str, sender_email: str) ->
|
||||
return {"subject": subject, "text": "\n".join(text), "html": html}
|
||||
|
||||
|
||||
# 발주 메일 본문 고치기(2026-10-27) — 미리보기 창에서 사람이 고친 HTML 을 그대로 보낸다.
|
||||
# 표·서식(인라인 style)은 남기고 스크립트·이벤트 속성·외부 리소스(url()·img)는 뺀다. 글 버전은 고친 HTML 에서 다시 만든다.
|
||||
MAIL_HTML_MAX = 300_000
|
||||
_MAIL_TAGS = {"div", "p", "br", "span", "b", "strong", "i", "em", "u", "s", "strike", "font", "a", "ul", "ol", "li",
|
||||
"h1", "h2", "h3", "h4", "blockquote", "sub", "sup", "hr",
|
||||
"table", "thead", "tbody", "tfoot", "tr", "th", "td", "colgroup", "col", "caption"}
|
||||
_MAIL_VOID = {"br", "hr", "col"}
|
||||
_MAIL_DROP = {"script", "style", "iframe", "object", "embed", "head", "title", "template", "noscript", "svg", "math",
|
||||
"textarea", "select", "button", "form", "input", "link", "meta"}
|
||||
_MAIL_ATTRS = {"colspan", "rowspan", "cellpadding", "cellspacing", "border", "align", "valign", "width", "height", "color"}
|
||||
_MAIL_STYLE_PROPS = {"color", "background", "background-color", "font-family", "font-size", "font-weight", "font-style",
|
||||
"text-decoration", "text-align", "vertical-align", "white-space", "line-height", "height", "width",
|
||||
"min-width", "max-width", "padding", "padding-top", "padding-right", "padding-bottom", "padding-left",
|
||||
"margin", "margin-top", "margin-right", "margin-bottom", "margin-left", "border", "border-top",
|
||||
"border-right", "border-bottom", "border-left", "border-color", "border-collapse", "border-spacing"}
|
||||
_MAIL_STYLE_VALUE_RE = re.compile(r"^[#\w\s.,%()'\"-]{1,120}$")
|
||||
_MAIL_ATTR_VALUE_RE = re.compile(r"^[#\w%.-]{1,20}$")
|
||||
|
||||
|
||||
def _mail_style(value: str) -> str:
|
||||
out = []
|
||||
for decl in value.split(";"):
|
||||
prop, _, val = decl.partition(":")
|
||||
prop, val = prop.strip().lower(), val.strip()
|
||||
if prop == "text-decoration-line": # 서식 막대(Chrome execCommand)가 밑줄·취소선을 이렇게 만든다 — 메일 프로그램은 text-decoration 만 아는 곳이 많다
|
||||
prop = "text-decoration"
|
||||
if prop in _MAIL_STYLE_PROPS and _MAIL_STYLE_VALUE_RE.match(val) and not re.search(r"url|expression|@import", val, re.I):
|
||||
out.append(f"{prop}:{val}")
|
||||
return ";".join(out)
|
||||
|
||||
|
||||
class _MailSanitizer(_html_parser.HTMLParser):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.out: list[str] = []
|
||||
self.stack: list[str] = []
|
||||
self.skip = 0
|
||||
|
||||
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||
if tag in _MAIL_DROP:
|
||||
self.skip += 1
|
||||
return
|
||||
if self.skip or tag not in _MAIL_TAGS:
|
||||
return
|
||||
extra = ""
|
||||
for k, v in attrs:
|
||||
v = (v or "").strip()
|
||||
if k == "style":
|
||||
style = _mail_style(v)
|
||||
if style:
|
||||
extra += f' style="{_html.escape(style)}"'
|
||||
elif k == "href" and tag == "a" and re.match(r"^(https?:|mailto:)", v, re.I):
|
||||
extra += f' href="{_html.escape(v)}"'
|
||||
elif k in _MAIL_ATTRS and _MAIL_ATTR_VALUE_RE.match(v):
|
||||
extra += f' {k}="{_html.escape(v)}"'
|
||||
self.out.append(f"<{tag}{extra}>")
|
||||
if tag not in _MAIL_VOID:
|
||||
self.stack.append(tag)
|
||||
|
||||
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||
if tag in _MAIL_VOID:
|
||||
self.handle_starttag(tag, attrs)
|
||||
|
||||
def handle_endtag(self, tag: str) -> None:
|
||||
if tag in _MAIL_DROP:
|
||||
self.skip = max(0, self.skip - 1)
|
||||
return
|
||||
if self.skip or tag not in self.stack:
|
||||
return
|
||||
while self.stack:
|
||||
t = self.stack.pop()
|
||||
self.out.append(f"</{t}>")
|
||||
if t == tag:
|
||||
break
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
if not self.skip:
|
||||
self.out.append(_html.escape(data, quote=False))
|
||||
|
||||
def result(self) -> str:
|
||||
self.close()
|
||||
while self.stack:
|
||||
self.out.append(f"</{self.stack.pop()}>")
|
||||
return "".join(self.out)
|
||||
|
||||
|
||||
class _MailText(_html_parser.HTMLParser):
|
||||
"""HTML → 글 버전 — 문단·줄은 줄바꿈, 표 칸은 " | " 로 잇는다."""
|
||||
|
||||
_BLOCK = {"p", "div", "tr", "li", "h1", "h2", "h3", "h4", "blockquote", "table", "hr"}
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.parts: list[str] = []
|
||||
self.cell = False # 이 줄에 이미 칸이 있다 — 다음 칸 앞에 구분자
|
||||
|
||||
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||
if tag == "br" or tag in self._BLOCK:
|
||||
self.parts.append("\n")
|
||||
self.cell = False
|
||||
elif tag in ("td", "th"):
|
||||
if self.cell:
|
||||
self.parts.append(" | ")
|
||||
self.cell = True
|
||||
if tag == "li":
|
||||
self.parts.append("- ")
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
self.parts.append(re.sub(r"\s+", " ", data.replace("\xa0", " ")))
|
||||
|
||||
|
||||
def clean_mail_html(html: Any) -> str:
|
||||
"""고친 메일 본문 HTML → 보낼 HTML(허용 태그·속성·글자 서식만). 너무 길거나 글이 없으면 ValueError."""
|
||||
raw = str(html or "")
|
||||
if len(raw) > MAIL_HTML_MAX:
|
||||
raise ValueError("메일 본문이 너무 깁니다.")
|
||||
p = _MailSanitizer()
|
||||
p.feed(raw)
|
||||
out = p.result()
|
||||
if not mail_html_to_text(out).strip():
|
||||
raise ValueError("메일 본문이 비어 있습니다.")
|
||||
return out
|
||||
|
||||
|
||||
def mail_html_to_text(html: str) -> str:
|
||||
p = _MailText()
|
||||
p.feed(str(html or ""))
|
||||
p.close()
|
||||
lines = [ln.strip() for ln in "".join(p.parts).split("\n")]
|
||||
return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip()
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 상품 정보(2026-10-16, 마이그레이션 004) — 단가·무게(개당 g = PP량)·은(Ag) 함유량(%) 수기 입력
|
||||
# 은 함량(g/개) = 무게 × 은 함유량 ÷ 100 — 저장하지 않고 계산(silver_g).
|
||||
@@ -414,7 +586,8 @@ def order_totals(lines: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
q = int(x["qty"])
|
||||
a = line_amount(q, x.get("unit_price"))
|
||||
if a is None:
|
||||
missing += 1
|
||||
if not is_bag(x.get("item_name")): # 봉투·백은 단가가 원래 없음 — "단가 미입력" 안내에서 뺀다
|
||||
missing += 1
|
||||
else:
|
||||
amount = (amount or Decimal(0)) + a
|
||||
w = to_dec(x.get("weight_g"))
|
||||
@@ -424,7 +597,7 @@ def order_totals(lines: list[dict[str, Any]]) -> dict[str, Any]:
|
||||
if w is not None and p is not None: # 개당 은 g 를 반올림하기 전 값으로 곱한다(합계 오차 방지)
|
||||
ag = (ag or Decimal(0)) + w * p / Decimal(100) * q
|
||||
use = (use or Decimal(0)) + w * q * (Decimal(100) - p) / Decimal(100000)
|
||||
return {"amount": amount, "missing_price": missing if amount is not None else len(lines), "pp_kg": pp, "silver_g": ag,
|
||||
return {"amount": amount, "missing_price": missing, "pp_kg": pp, "silver_g": ag,
|
||||
"pp_use_kg": use}
|
||||
|
||||
|
||||
@@ -453,7 +626,8 @@ def validate_product_values(values: dict[str, Any]) -> dict[str, Decimal | None]
|
||||
def has_values(p: dict[str, Any]) -> bool:
|
||||
"""단가·무게·은 함유량(·그룹·색상 006·박스 입수 007) 중 하나라도 넣었나 — 넣은 상품은 다시 불러와도 그대로 둔다."""
|
||||
return (any(p.get(k) is not None for k in PRODUCT_LIMITS) or p.get("group_id") is not None
|
||||
or (p.get("color") or "none") != "none" or any(p.get(k) is not None for k in BOX_FIELDS))
|
||||
or (p.get("color") or "none") != "none" or any(p.get(k) is not None for k in BOX_FIELDS)
|
||||
or p.get("boxes_per_pallet") is not None)
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
@@ -465,9 +639,9 @@ MAX_PER_BOX = 1_000_000
|
||||
PALLET_BOXES = 30
|
||||
|
||||
|
||||
def parse_per_box(raw: Any, *, key: str) -> int | None:
|
||||
def parse_per_box(raw: Any, *, key: str = "", label: str = "") -> int | None:
|
||||
"""박스 입수 칸 하나 — 빈칸은 None(없음·미입력), 1 이상 정수(쉼표 허용)."""
|
||||
label = BOX_FIELDS[key]
|
||||
label = label or BOX_FIELDS[key]
|
||||
s = str(raw if raw is not None else "").replace(",", "").strip()
|
||||
if not s:
|
||||
return None
|
||||
@@ -475,7 +649,7 @@ def parse_per_box(raw: Any, *, key: str) -> int | None:
|
||||
raise ValueError(f"{label}은(는) 1 이상 정수로 입력하세요.")
|
||||
n = int(s)
|
||||
if n < 1:
|
||||
raise ValueError(f"{label}은(는) 1 이상이어야 합니다(뚜껑이 없으면 빈칸).")
|
||||
raise ValueError(f"{label}은(는) 1 이상이어야 합니다(없으면 빈칸).")
|
||||
if n > MAX_PER_BOX:
|
||||
raise ValueError(f"{label}이(가) 너무 큽니다.")
|
||||
return n
|
||||
@@ -485,6 +659,26 @@ def validate_box_values(values: dict[str, Any]) -> dict[str, int | None]:
|
||||
return {k: parse_per_box(values.get(k), key=k) for k in BOX_FIELDS}
|
||||
|
||||
|
||||
# 봉투·백(2026-11-04, 마이그레이션 008) — 이름으로 판단(저장 안 함). 뚜껑 없음, 박스당 수량 = body_per_box, 1파렛트 박스 수는 상품마다.
|
||||
BAG_NAME_WORDS = ("미라클 봉투", "미라클백")
|
||||
|
||||
|
||||
def is_bag(name: Any) -> bool:
|
||||
return any(word in str(name or "") for word in BAG_NAME_WORDS)
|
||||
|
||||
|
||||
def validate_bag_values(values: dict[str, Any]) -> dict[str, int | None]:
|
||||
return {"body_per_box": parse_per_box(values.get("body_per_box"), label="박스당 수량"), "lid_per_box": None,
|
||||
"boxes_per_pallet": parse_per_box(values.get("boxes_per_pallet"), label="1파렛트당 박스 수량")}
|
||||
|
||||
|
||||
def box_info(row: dict[str, Any]) -> dict[str, Any]:
|
||||
"""발주서 화면 박스 계산 값 — 008 미적용(열 없음)이면 모두 일반 상품으로."""
|
||||
bag = "boxes_per_pallet" in row and is_bag(row.get("item_name"))
|
||||
return {"body_per_box": row.get("body_per_box"), "lid_per_box": None if bag else row.get("lid_per_box"),
|
||||
"is_bag": bag, "boxes_per_pallet": row.get("boxes_per_pallet") if bag else None}
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 상품 그룹·색상(2026-10-21, 마이그레이션 006)
|
||||
# 그룹에 은 함유량·색상을 한 번만 — 그룹 상품은 그룹 값, 그룹 없는 상품은 자기 값(effective_product).
|
||||
@@ -567,6 +761,41 @@ def validate_photos(files: list[tuple[str, bytes]], *, existing: int = 0) -> lis
|
||||
return out
|
||||
|
||||
|
||||
def rotate_image(data: bytes, degrees: int) -> bytes:
|
||||
"""사진 내용을 시계 방향 90·270도로 돌려 같은 형식으로(2026-11-02). 휴대폰 사진의 회전 정보(EXIF)는 픽셀에 반영한 뒤 돌린다."""
|
||||
from io import BytesIO # noqa: WPS433
|
||||
|
||||
from PIL import Image, ImageOps # noqa: WPS433
|
||||
|
||||
if degrees not in (90, 270):
|
||||
raise ValueError("사진은 왼쪽·오른쪽으로만 돌릴 수 있습니다.")
|
||||
kind = sniff_image(data)
|
||||
if kind == "image/heic":
|
||||
raise ValueError("HEIC 사진은 돌릴 수 없습니다 — JPG 로 바꿔 다시 올려 주세요.")
|
||||
try:
|
||||
im = Image.open(BytesIO(data))
|
||||
if getattr(im, "n_frames", 1) > 1:
|
||||
raise ValueError("움직이는 사진은 돌릴 수 없습니다.")
|
||||
icc = im.info.get("icc_profile")
|
||||
im = ImageOps.exif_transpose(im)
|
||||
# PIL 의 ROTATE_n 은 반시계 방향 — 시계 90도 = ROTATE_270
|
||||
im = im.transpose(Image.Transpose.ROTATE_270 if degrees == 90 else Image.Transpose.ROTATE_90)
|
||||
fmt = {"image/jpeg": "JPEG", "image/png": "PNG", "image/webp": "WEBP", "image/gif": "GIF"}[kind]
|
||||
opts: dict[str, Any] = {"icc_profile": icc} if icc and fmt != "GIF" else {}
|
||||
if fmt in ("JPEG", "WEBP"):
|
||||
opts["quality"] = 92
|
||||
buf = BytesIO()
|
||||
im.save(buf, format=fmt, **opts)
|
||||
except ValueError:
|
||||
raise
|
||||
except Exception as exc: # noqa: BLE001 — 깨진 파일 등(원본은 그대로 둔다)
|
||||
raise ValueError("이 사진은 돌릴 수 없습니다.") from exc
|
||||
out = buf.getvalue()
|
||||
if len(out) > MAX_PHOTO_BYTES:
|
||||
raise ValueError(f"돌린 사진이 너무 큽니다(한 장 {MAX_PHOTO_BYTES // 1024 // 1024}MB까지).")
|
||||
return out
|
||||
|
||||
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 입고 요청 메일(2026-10-19, 마이그레이션 005) — 입고 담당이 입고를 저장한 뒤 물류센터 입고 담당자에게
|
||||
# "전산 등록 부탁" 메일(입고 담당 본인 Gmail). 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = king@·bj@dbxcorp.co.kr.
|
||||
|
||||
@@ -141,6 +141,7 @@
|
||||
값을 넣은 상품은 다시 불러와도 그대로이고, 지운 단품은 다음 불러오기에서 빠집니다. 발주서 제품은 이 목록에서 고르며, 발주할 때의 값이 발주서에 남습니다.
|
||||
{% if groups_ready %}<b>그룹</b>을 고른 상품은 은 함유량·<b>색상</b>을 그룹 값으로 씁니다(<b>상품 그룹</b> 탭에서 한 번만 설정).{% endif %}
|
||||
{% if boxes_ready %}<b>통 수량(박스)</b>·<b>뚜껑 수량(박스)</b> = 통·뚜껑이 한 박스에 몇 개씩 들어가는지(뚜껑이 없으면 빈칸) — 새 발주서에서 박스 수·파렛트 수를 계산합니다.{% endif %}
|
||||
이름에 "미라클 봉투"·"미라클백"이 들어간 상품은 <b>봉투·백</b> 표에서 <b>박스당 수량</b>·<b>1파렛트당 박스 수량</b>을 넣습니다(단가·무게·은 없음).
|
||||
</p>
|
||||
<div class="io-prod-bar">
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="io-prod-import">단품 불러오기</button>
|
||||
@@ -151,14 +152,23 @@
|
||||
</div>
|
||||
{% if products %}
|
||||
<div class="io-prod-scroll">
|
||||
{# 봉투·백(008) = 일반 상품과 표를 나눔, 짧은 목록이라 위에. 박스 칸 두 개만 다르고 나머지 칸은 같다 #}
|
||||
{% set bags = products|selectattr('is_bag')|list %}
|
||||
{% for bag_table, rows in [(true, bags), (false, products|rejectattr('is_bag')|list)] if rows %}
|
||||
<div class="io-prod-part">
|
||||
{% if bags %}<div class="io-prod-part-title">{{ '봉투·백' if bag_table else '일반 상품' }} <span class="io-sub">{{ rows|length }}개</span></div>{% endif %}
|
||||
<table class="io-dlg-table io-prod-table{% if groups_ready %} has-groups{% endif %}">
|
||||
<colgroup><col class="w-code" /><col />{% if groups_ready %}<col class="w-group" />{% endif %}<col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" />{% if boxes_ready %}<col class="w-box" /><col class="w-box" />{% endif %}{% if groups_ready %}<col class="w-color" />{% endif %}<col class="w-del" /></colgroup>
|
||||
<thead><tr><th>코드</th><th>제품명</th>{% if groups_ready %}<th>그룹</th>{% endif %}<th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th>{% if boxes_ready %}<th title="통이 한 박스에 몇 개">통 수량(박스)</th><th title="뚜껑이 한 박스에 몇 개 — 뚜껑이 없으면 빈칸">뚜껑 수량(박스)</th>{% endif %}{% if groups_ready %}<th>색상</th>{% endif %}<th></th></tr></thead>
|
||||
<colgroup><col class="w-code" /><col />{% if groups_ready %}<col class="w-group" />{% endif %}{% if not bag_table %}<col class="w-num" /><col class="w-num" /><col class="w-num" /><col class="w-ag" />{% endif %}{% if boxes_ready %}<col class="w-box" /><col class="w-box" />{% endif %}{% if groups_ready %}<col class="w-color" />{% endif %}<col class="w-del" /></colgroup>
|
||||
<thead><tr><th>코드</th><th>제품명</th>{% if groups_ready %}<th>그룹</th>{% endif %}{% if not bag_table %}<th class="io-r">단가(원)</th><th class="io-r">무게·PP(g/개)</th><th class="io-r">은 함유량(%)</th><th class="io-r">은(g/개)</th>{% endif %}{% if bag_table %}<th title="한 박스에 몇 개">박스당 수량</th><th title="한 파렛트에 몇 박스">1파렛트당 박스 수량</th>{% elif boxes_ready %}<th title="통이 한 박스에 몇 개">통 수량(박스)</th><th title="뚜껑이 한 박스에 몇 개 — 뚜껑이 없으면 빈칸">뚜껑 수량(박스)</th>{% endif %}{% if groups_ready %}<th>색상</th>{% endif %}<th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for p in products %}
|
||||
{% for p in rows %}
|
||||
{% set own_pct = p.own_silver_pct if groups_ready else p.silver_pct %}
|
||||
<tr data-code="{{ p.item_code }}" data-search="{{ (p.item_code ~ ' ' ~ p.item_name ~ ' ' ~ (p.group_name or ''))|lower }}"{% if groups_ready and p.group_id %} class="is-grouped"{% endif %}>
|
||||
<td class="io-code">{{ p.item_code }}</td>
|
||||
<td class="io-code">{{ p.item_code }}{% if bag_table %}
|
||||
{# 봉투·백엔 단가·무게·은 칸이 없다 — 전에 넣은 값이 저장 때 지워지지 않게 숨은 칸으로 그대로 보낸다 #}
|
||||
<input type="hidden" data-key="unit_price" value="{{ fmt_num(p.unit_price) if p.unit_price is not none else '' }}" />
|
||||
<input type="hidden" data-key="weight_g" value="{{ fmt_num(p.weight_g) if p.weight_g is not none else '' }}" />
|
||||
<input type="hidden" data-key="silver_pct" value="{{ fmt_num(own_pct, 4) if own_pct is not none else '' }}" />{% endif %}</td>
|
||||
<td class="io-prod-name">{{ p.item_name }}</td>
|
||||
{% if groups_ready %}
|
||||
<td><select class="io-in io-group-select" data-key="group_id" aria-label="{{ p.item_code }} 그룹">
|
||||
@@ -166,12 +176,17 @@
|
||||
{% for g in groups %}<option value="{{ g.id }}" data-silver="{{ fmt_num(g.silver_pct, 4) if g.silver_pct is not none else '' }}" data-color="{{ g.color }}" {% if p.group_id == g.id %}selected{% endif %}>{{ g.name }}</option>{% endfor %}
|
||||
</select></td>
|
||||
{% endif %}
|
||||
{% if not bag_table %}
|
||||
<td><input class="io-in io-in-num" data-key="unit_price" value="{{ fmt_num(p.unit_price) if p.unit_price is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 단가" /></td>
|
||||
<td><input class="io-in io-in-num" data-key="weight_g" value="{{ fmt_num(p.weight_g) if p.weight_g is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 무게" /></td>
|
||||
<td><input class="io-in io-in-num io-own" data-key="silver_pct" value="{{ fmt_num(own_pct, 4) if own_pct is not none else '' }}" inputmode="decimal" aria-label="{{ p.item_code }} 은 함유량" />
|
||||
{% if groups_ready %}<span class="io-group-val io-r" title="그룹 값 — 그룹에서 바꿉니다">{{ fmt_num(p.silver_pct, 4) if p.silver_pct is not none else '-' }}</span>{% endif %}</td>
|
||||
<td class="io-r io-ag" title="무게 × 은 함유량 ÷ 100">{{ fmt_num(p.silver_g, 4) if p.silver_g is not none else '-' }}</td>
|
||||
{% if boxes_ready %}
|
||||
{% endif %}
|
||||
{% if bag_table %}
|
||||
<td><input class="io-in io-in-num" data-key="body_per_box" value="{{ '{:,}'.format(p.body_per_box) if p.body_per_box else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 박스당 수량" /></td>
|
||||
<td><input class="io-in io-in-num" data-key="boxes_per_pallet" value="{{ '{:,}'.format(p.boxes_per_pallet) if p.boxes_per_pallet else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 1파렛트당 박스 수량" /></td>
|
||||
{% elif boxes_ready %}
|
||||
<td><input class="io-in io-in-num" data-key="body_per_box" value="{{ '{:,}'.format(p.body_per_box) if p.body_per_box else '' }}" inputmode="numeric" aria-label="{{ p.item_code }} 통 수량(박스)" /></td>
|
||||
<td><input class="io-in io-in-num" data-key="lid_per_box" value="{{ '{:,}'.format(p.lid_per_box) if p.lid_per_box else '' }}" inputmode="numeric" placeholder="없음" aria-label="{{ p.item_code }} 뚜껑 수량(박스)" /></td>
|
||||
{% endif %}
|
||||
@@ -186,6 +201,8 @@
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="io-empty">아직 불러온 단품이 없습니다 — [단품 불러오기]를 누르세요. (그 전에는 발주서에서 코드표 단품을 바로 고릅니다)</p>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% from "inout/_macros.html" import order_badge, progress, due, n, ymd %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021f" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261104c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||
@@ -71,4 +71,4 @@
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261021e" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261104c" defer></script>{% endblock %}
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
</footer>
|
||||
</dialog>
|
||||
{%- endmacro -%}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021f" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261104c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
{% set active = order.status in ('open', 'partial') %}
|
||||
@@ -232,6 +232,10 @@
|
||||
<dialog class="io-viewer" id="io-viewer" tabindex="-1" aria-label="입고증 사진" data-order="{{ order.id }}" data-can-delete="{{ '1' if photo_admin else '' }}">
|
||||
<div class="io-viewer-bar">
|
||||
<span class="io-viewer-title" id="io-viewer-title"></span>
|
||||
{% if photo_admin %}
|
||||
<button type="button" class="io-viewer-btn io-viewer-rot" data-rotate="270" title="왼쪽으로 돌리기" aria-label="왼쪽으로 돌리기"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 4v6h6"/><path d="M3.5 15a9 9 0 1 0 2.1-9.4L3 10"/></svg></button>
|
||||
<button type="button" class="io-viewer-btn io-viewer-rot" data-rotate="90" title="오른쪽으로 돌리기" aria-label="오른쪽으로 돌리기"><svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 4v6h-6"/><path d="M20.5 15a9 9 0 1 1-2.1-9.4L21 10"/></svg></button>
|
||||
{% endif %}
|
||||
<a class="io-viewer-btn" id="io-viewer-open" href="#" target="_blank" rel="noopener">원본</a>
|
||||
{% if photo_admin %}<form method="post" id="io-viewer-del" data-erp-confirm="이 입고증 사진을 지울까요?"><button type="submit" class="io-viewer-btn">지우기</button></form>{% endif %}
|
||||
<button type="button" class="io-viewer-btn" data-close aria-label="닫기">✕</button>
|
||||
@@ -258,4 +262,4 @@
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261021e" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261104c" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021f" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261104c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||
@@ -34,7 +34,7 @@
|
||||
<tbody>
|
||||
{% for ln in lines %}
|
||||
{% set received = (order.lines | selectattr('item_code', 'equalto', ln.code) | map(attribute='received') | first) if order else 0 %}
|
||||
<tr class="io-line" data-price="{{ ln.price if ln.price is not none else '' }}"{% if boxes_ready %} data-body-box="{{ ln.body_per_box or '' }}" data-lid-box="{{ ln.lid_per_box or '' }}"{% endif %}>
|
||||
<tr class="io-line" data-price="{{ ln.price if ln.price is not none else '' }}"{% if boxes_ready %} data-body-box="{{ ln.body_per_box or '' }}" data-lid-box="{{ ln.lid_per_box or '' }}" data-bag="{{ '1' if ln.is_bag else '' }}" data-pallet-box="{{ ln.boxes_per_pallet or '' }}"{% endif %}>
|
||||
<td class="io-col-no"></td>
|
||||
<td class="io-item-cell">
|
||||
<input type="hidden" name="item_code" value="{{ ln.code }}" />
|
||||
@@ -64,13 +64,20 @@
|
||||
<span class="io-pallet-vis" data-k="vis"></span>
|
||||
<span class="erp-muted" data-k="note">1파렛트 = {{ pallet_boxes }}박스</span>
|
||||
</div>
|
||||
{# 봉투·백(008) — 상품마다 1파렛트 박스 수가 달라 통·뚜껑 파렛트와 따로 셈 #}
|
||||
<div class="io-pallet" id="io-pallet-bag" aria-live="polite" hidden>
|
||||
<span>봉투·백 <b data-k="boxes">0</b>박스</span>
|
||||
<span class="io-pallet-main">→ <b data-k="pallets">0</b>파렛트</span>
|
||||
<span class="io-pallet-vis" data-k="vis"></span>
|
||||
<span class="erp-muted" data-k="note"></span>
|
||||
</div>
|
||||
{% endif %}
|
||||
</td></tr></tfoot>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<template id="io-line-tpl">
|
||||
<tr class="io-line"{% if boxes_ready %} data-body-box="" data-lid-box=""{% endif %}>
|
||||
<tr class="io-line"{% if boxes_ready %} data-body-box="" data-lid-box="" data-bag="" data-pallet-box=""{% endif %}>
|
||||
<td class="io-col-no"></td>
|
||||
<td class="io-item-cell">
|
||||
<input type="hidden" name="item_code" value="" />
|
||||
@@ -95,4 +102,4 @@
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261021e" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261104c" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% from "inout/_macros.html" import due, n, ymd %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261021f" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/inout.css?v=20261104c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<div class="io-split">{# 2열 — 왼쪽 화면 | 오른쪽 달력(2026-10-21) #}
|
||||
@@ -91,4 +91,4 @@
|
||||
{% include "inout/_calendar.html" %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261021e" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/inout.js?v=20261104c" defer></script>{% endblock %}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# [라이브커머스] 라이브 커머스 모듈 — `app/modules/live/`, `live_db`(2026-11-04)
|
||||
|
||||
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드가 기준.
|
||||
> 정적 파일: `app/static/live.js`, `live.css`. 템플릿: `templates/live/`. 테스트: `tests/test_live.py`(`LIVE_TEST_DB_URL` 이 localhost 일 때 실제 DB).
|
||||
> 다른 모듈과 연결: 이미지 검사 = 자산 모듈 `app/modules/asset/media.py prepare_photo` 재사용(바꾸면 양쪽 확인).
|
||||
|
||||
- 말레이시아 라이브 커머스 방송의 호스트 정보·방송 스케줄. 권한키 `live`, DB `LIVE_DB_URL`(없으면 "설정 필요" 안내).
|
||||
- **호스트 설정** `/live/settings` — Full Name (as per IC)(필수)·Phone Number·Email·Address·Bank Name·Bank Account Number·Tiktok Handle(`@`·주소를 붙여 넣어도 계정명만 저장).
|
||||
**계좌 등 개인정보라 ERP 관리자만**(`is_admin`) — 화면·저장·지우기 모두. 스케줄 화면에는 `db.host_choices`(이름·틱톡·사용 여부)만 넘긴다.
|
||||
사용 안 함 = 새 방송에서 못 고름(그 호스트로 이미 등록된 방송을 고칠 때만 보임). 방송 기록이 있는 호스트는 못 지움(FK RESTRICT).
|
||||
- **스케줄표** `/live/?month=YYYY-MM`(`live` 권한자 모두) — 호스트·날짜·시작/끝 시간·방송 장소·판매금액·커미션·호스트 비용·결과 이미지. 호스트·날짜·시작·끝 시간 필수(판매금액은 방송 후 입력).
|
||||
시간은 입력한 말레이시아 시간 그대로(시간대 변환 없음, DATE·TIME). 판매금액 단위 RM(`NUMERIC(14,2)`, `store.parse_money`). 끝 시간이 시작보다 이르면 자정을 넘긴 방송.
|
||||
- **호스트 비용**(`store.session_pay`, 저장 안 함 — 화면마다 계산) = 시간 × RM 25(`HOURLY_RATE`) + 판매금액 × 10%(`COMMISSION_PERCENT`). 요율이 코드 상수라 바꾸면 지난 방송 금액도 바뀐다.
|
||||
- **달력 보기** `/live/calendar?month=`(`store.build_calendar`, 사용자가 준 화면 참고, 글자도 영어 그대로) — 줄 = 2시간 칸(06:00~24:00 늘 보임, 그보다 이른 칸은 방송이 있을 때만, 칸은 시작 시간으로 정함), 열 = 날짜, 주말 노랑, Jump to Date, 위 달 합계, 맨 아래 날짜별 TOTAL SALES·AD SPEND·HOST FEE·ROAS.
|
||||
카드 머리 = **Tiktok Handle**(없으면 이름, 색 = 호스트 id 순 `HOST_COLORS`), SALES·COM·Fee. 카드 머리를 끌어 빈 칸으로 = 옮기기(`move`, 방송 길이 유지) · 다른 카드 위 = 맞바꾸기(`swap_with`, 날짜·시간 교환). 다시 그린 뒤 가로 위치 유지(sessionStorage). 빈 칸 + = 그 날짜·시간이 채워진 추가 창.
|
||||
**AD SPEND** = 날짜별 광고비 `live_daily_ad_spend`(마이그레이션 002, `POST /live/ad-spend`, 빈칸 = 지우기), ROAS = 판매금액 ÷ 광고비(광고비 없으면 `-`). 002 미적용이면 0 으로 보이고 저장만 안내.
|
||||
- **결과 이미지** — 방송 저장과 한 트랜잭션, JPG·PNG·WebP, 한 장 8MB, 방송당 10장(`store.MAX_IMAGES`). `prepare_photo` 가 실제 이미지 확인·긴 변 2400px·EXIF(GPS 등) 제거. BYTEA 저장.
|
||||
`GET /live/images/{id}`(권한 필요, 하루 private 캐시), `?thumb=1` = 160px JPEG(그때그때 만듦). 올린 뒤 내용이 안 바뀐다는 전제 — 이미지를 고치는 기능을 넣으면 캐시도 바꿀 것.
|
||||
- 저장은 `live.js` 가 fetch → JSON `{ok, message}`(틀려도 창의 입력값 유지). 창 하나로 추가·고치기(`data-edit` JSON).
|
||||
- **한글·영문 전환**(`i18n.py`) — 위 막대 [한글|EN], 쿠키 `live_lang`(브라우저마다, path=/live, 기본 한글). 한글 문구가 키, 템플릿 `t('…')`, 오류 `LiveError(틀, 값)`(라우터가 언어에 맞게), JS `LV_T`(`JS_KEYS`).
|
||||
**새 문구는 `i18n.EN` 에도 넣는다** — `tests/test_live.py` 가 빠진 문구와 영문 화면의 한글을 잡는다. 입력한 데이터(이름·장소 등)·ERP 공용 사이드바는 번역하지 않는다.
|
||||
- 메인 카드 제목 = `main.py` `card_title`(한글·영문), 사이드바는 `title` 그대로.
|
||||
@@ -0,0 +1,21 @@
|
||||
"""라이브 커머스(live) 모듈 — 말레이시아 라이브 방송의 호스트 정보와 방송 스케줄(2026-11-04).
|
||||
|
||||
- 라우터: `router.py` (prefix=/live) · 저장소: `db.py` (live_db) · 순수 함수: `store.py`(입력 검사·표시 형식)
|
||||
- 템플릿: `templates/live/`, 화면 스크립트·스타일 `static/live.{js,css}`
|
||||
|
||||
LIVE_DB_URL 미설정이면 build_live_store 가 None → 화면이 "설정 필요" 안내(앱은 죽지 않음). 권한키 `live`.
|
||||
"""
|
||||
|
||||
from typing import Any
|
||||
|
||||
from .router import router
|
||||
|
||||
__all__ = ["router", "build_live_store"]
|
||||
|
||||
|
||||
def build_live_store(*, dsn: str | None) -> Any:
|
||||
if not dsn:
|
||||
return None
|
||||
from .db import LiveDBStore # 지연 import
|
||||
|
||||
return LiveDBStore(dsn)
|
||||
@@ -0,0 +1,175 @@
|
||||
"""live_db PostgreSQL 저장소 — 라이브 커머스 호스트·방송 스케줄·결과 이미지(2026-11-04).
|
||||
|
||||
- 연결: 환경변수 `LIVE_DB_URL` (예: postgresql://live_app:<pwd>@postgres-db:5432/live_db)
|
||||
- 스키마는 앱이 만들지 않는다 — `scripts/sql/live_db_init.sql` 을 superuser 가 먼저 적용(앱 계정은 CRUD 만).
|
||||
- 연결 풀은 lazy open — 부팅 때 DB 가 잠시 끊겨도 컨테이너가 죽지 않게(다른 모듈과 같은 방식).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, time
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from psycopg.errors import ForeignKeyViolation, UndefinedTable
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
from . import store
|
||||
from .i18n import LiveError
|
||||
|
||||
_HOST_COLUMNS = ("full_name", "phone", "email", "address", "bank_name", "bank_account", "tiktok_handle")
|
||||
|
||||
|
||||
class LiveDBStore:
|
||||
def __init__(self, dsn: str, *, min_size: int = 1, max_size: int = 4):
|
||||
self._pool = ConnectionPool(conninfo=dsn, min_size=min_size, max_size=max_size,
|
||||
kwargs={"row_factory": dict_row, "autocommit": True}, open=False)
|
||||
self._pool.open(wait=False)
|
||||
|
||||
def close(self) -> None:
|
||||
self._pool.close()
|
||||
|
||||
# ── 호스트 ─────────────────────────────────────────────
|
||||
def list_hosts(self) -> list[dict[str, Any]]:
|
||||
"""전체 정보(계좌 포함) — 설정 화면(ERP 관리자)에서만 쓴다."""
|
||||
with self._pool.connection() as conn:
|
||||
return conn.execute("SELECT * FROM live_hosts ORDER BY is_active DESC, full_name, id").fetchall()
|
||||
|
||||
def host_choices(self) -> list[dict[str, Any]]:
|
||||
"""스케줄 화면 호스트 고르기 — 개인정보·계좌는 뺀다."""
|
||||
with self._pool.connection() as conn:
|
||||
return conn.execute("SELECT id, full_name, tiktok_handle, is_active FROM live_hosts "
|
||||
"ORDER BY full_name, id").fetchall()
|
||||
|
||||
def save_host(self, host_id: int | None, values: dict[str, str], *, is_active: bool, by: str) -> int:
|
||||
cols = [values[k] for k in _HOST_COLUMNS]
|
||||
with self._pool.connection() as conn:
|
||||
if host_id is None:
|
||||
row = conn.execute(
|
||||
"INSERT INTO live_hosts (full_name, phone, email, address, bank_name, bank_account, tiktok_handle, "
|
||||
"is_active, created_by, updated_by) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id",
|
||||
(*cols, is_active, by, by)).fetchone()
|
||||
else:
|
||||
row = conn.execute(
|
||||
"UPDATE live_hosts SET full_name=%s, phone=%s, email=%s, address=%s, bank_name=%s, bank_account=%s, "
|
||||
"tiktok_handle=%s, is_active=%s, updated_by=%s WHERE id=%s RETURNING id",
|
||||
(*cols, is_active, by, host_id)).fetchone()
|
||||
if not row:
|
||||
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||
return int(row["id"])
|
||||
|
||||
def delete_host(self, host_id: int) -> None:
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute("DELETE FROM live_hosts WHERE id=%s RETURNING id", (host_id,)).fetchone()
|
||||
except ForeignKeyViolation:
|
||||
raise LiveError("방송 기록이 있는 호스트는 지울 수 없습니다 — 사용 안 함으로 바꾸세요.") from None
|
||||
if not row:
|
||||
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||
|
||||
# ── 방송 스케줄 ─────────────────────────────────────────
|
||||
def list_broadcasts(self, start: date, end: date) -> list[dict[str, Any]]:
|
||||
"""start 이상 end 미만, 날짜·시간 순. 줄마다 images = [{id, filename}](내용 제외)."""
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT b.*, h.full_name AS host_name, h.tiktok_handle FROM live_broadcasts b JOIN live_hosts h ON h.id = b.host_id "
|
||||
"WHERE b.broadcast_date >= %s AND b.broadcast_date < %s ORDER BY b.broadcast_date, b.start_time, b.id",
|
||||
(start, end)).fetchall()
|
||||
images = conn.execute(
|
||||
"SELECT id, broadcast_id, filename FROM live_broadcast_images WHERE broadcast_id = ANY(%s) ORDER BY id",
|
||||
([r["id"] for r in rows],)).fetchall()
|
||||
for r in rows:
|
||||
r["images"] = [i for i in images if i["broadcast_id"] == r["id"]]
|
||||
return rows
|
||||
|
||||
def save_broadcast(self, broadcast_id: int | None, values: dict[str, Any], images: list[dict[str, Any]], *, by: str) -> int:
|
||||
"""방송·이미지를 한 트랜잭션으로. 사용 안 함 호스트는 이미 그 호스트인 방송을 고칠 때만 허용."""
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
current = None
|
||||
if broadcast_id is not None:
|
||||
found = conn.execute("SELECT host_id FROM live_broadcasts WHERE id=%s FOR UPDATE", (broadcast_id,)).fetchone()
|
||||
if not found:
|
||||
raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
|
||||
current = found["host_id"]
|
||||
host = conn.execute("SELECT is_active FROM live_hosts WHERE id=%s", (values["host_id"],)).fetchone()
|
||||
if not host:
|
||||
raise LiveError("호스트를 찾을 수 없습니다.")
|
||||
if not host["is_active"] and values["host_id"] != current:
|
||||
raise LiveError("사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.")
|
||||
args = (values["host_id"], values["broadcast_date"], values["start_time"], values["end_time"], values["venue"],
|
||||
values["sales_amount"], by)
|
||||
if broadcast_id is None:
|
||||
broadcast_id = int(conn.execute(
|
||||
"INSERT INTO live_broadcasts (host_id, broadcast_date, start_time, end_time, venue, sales_amount, updated_by, created_by) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s) RETURNING id", (*args, by)).fetchone()["id"])
|
||||
else:
|
||||
conn.execute("UPDATE live_broadcasts SET host_id=%s, broadcast_date=%s, start_time=%s, end_time=%s, venue=%s, "
|
||||
"sales_amount=%s, updated_by=%s WHERE id=%s", (*args, broadcast_id))
|
||||
have = conn.execute("SELECT count(*) AS n FROM live_broadcast_images WHERE broadcast_id=%s", (broadcast_id,)).fetchone()["n"]
|
||||
if have + len(images) > store.MAX_IMAGES:
|
||||
raise LiveError("방송 한 건에 이미지는 {max}장까지입니다(지금 {have}장).", max=store.MAX_IMAGES, have=have)
|
||||
for im in images:
|
||||
conn.execute("INSERT INTO live_broadcast_images (broadcast_id, filename, content_type, data, width, height, created_by) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s)",
|
||||
(broadcast_id, im["filename"], im["content_type"], im["data"], im["width"], im["height"], by))
|
||||
return broadcast_id
|
||||
|
||||
def delete_broadcast(self, broadcast_id: int) -> None:
|
||||
with self._pool.connection() as conn:
|
||||
if not conn.execute("DELETE FROM live_broadcasts WHERE id=%s RETURNING id", (broadcast_id,)).fetchone():
|
||||
raise LiveError("방송을 찾을 수 없습니다.")
|
||||
|
||||
def move_broadcast(self, broadcast_id: int, day: date, start: time, *, by: str) -> None:
|
||||
"""달력에서 빈 칸으로 옮기기 — 방송 길이는 그대로."""
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
row = conn.execute("SELECT start_time, end_time FROM live_broadcasts WHERE id=%s FOR UPDATE", (broadcast_id,)).fetchone()
|
||||
if not row:
|
||||
raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
|
||||
conn.execute("UPDATE live_broadcasts SET broadcast_date=%s, start_time=%s, end_time=%s, updated_by=%s WHERE id=%s",
|
||||
(day, start, store.moved_end(row["start_time"], row["end_time"], start), by, broadcast_id))
|
||||
|
||||
def swap_broadcasts(self, first_id: int, second_id: int, *, by: str) -> None:
|
||||
"""달력에서 다른 방송 위로 놓기 — 두 방송의 날짜·시간을 맞바꾼다(id 순서로 잠가 교착 방지)."""
|
||||
if first_id == second_id:
|
||||
return
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
rows = conn.execute("SELECT id, broadcast_date, start_time, end_time FROM live_broadcasts WHERE id = ANY(%s) ORDER BY id FOR UPDATE",
|
||||
([first_id, second_id],)).fetchall()
|
||||
if len(rows) != 2:
|
||||
raise LiveError("방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).")
|
||||
for mine, other in ((rows[0], rows[1]), (rows[1], rows[0])):
|
||||
conn.execute("UPDATE live_broadcasts SET broadcast_date=%s, start_time=%s, end_time=%s, updated_by=%s WHERE id=%s",
|
||||
(other["broadcast_date"], other["start_time"], other["end_time"], by, mine["id"]))
|
||||
|
||||
# ── 날짜별 광고비(002) ───────────────────────────────────
|
||||
def ad_spends(self, start: date, end: date) -> dict[date, Decimal]:
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute("SELECT ad_date, ad_spend FROM live_daily_ad_spend WHERE ad_date >= %s AND ad_date < %s", (start, end)).fetchall()
|
||||
except UndefinedTable:
|
||||
return {}
|
||||
return {r["ad_date"]: r["ad_spend"] for r in rows}
|
||||
|
||||
def save_ad_spend(self, day: date, amount: Decimal | None, *, by: str) -> None:
|
||||
"""빈칸(None) = 지우기."""
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
if amount is None:
|
||||
conn.execute("DELETE FROM live_daily_ad_spend WHERE ad_date=%s", (day,))
|
||||
else:
|
||||
conn.execute("INSERT INTO live_daily_ad_spend (ad_date, ad_spend, updated_by) VALUES (%s,%s,%s) "
|
||||
"ON CONFLICT (ad_date) DO UPDATE SET ad_spend=EXCLUDED.ad_spend, updated_by=EXCLUDED.updated_by, updated_at=now()",
|
||||
(day, amount, by))
|
||||
except UndefinedTable:
|
||||
raise LiveError("DB 마이그레이션 live_db 002(광고비)가 아직 적용되지 않았습니다.") from None
|
||||
|
||||
# ── 결과 이미지 ─────────────────────────────────────────
|
||||
def get_image(self, image_id: int) -> dict[str, Any] | None:
|
||||
with self._pool.connection() as conn:
|
||||
return conn.execute("SELECT content_type, data FROM live_broadcast_images WHERE id=%s", (image_id,)).fetchone()
|
||||
|
||||
def delete_image(self, image_id: int) -> None:
|
||||
with self._pool.connection() as conn:
|
||||
if not conn.execute("DELETE FROM live_broadcast_images WHERE id=%s RETURNING id", (image_id,)).fetchone():
|
||||
raise LiveError("이미지를 찾을 수 없습니다.")
|
||||
@@ -0,0 +1,112 @@
|
||||
"""라이브 커머스 한글·영문 전환(2026-11-04) — 한글 문구가 키, 없으면 한글 그대로. 언어는 쿠키 `live_lang`(브라우저마다).
|
||||
|
||||
새 문구는 여기에도 넣는다 — tests/test_live.py 가 템플릿·오류 문구가 모두 있는지, 영문 화면에 한글이 없는지 확인한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
LANG_COOKIE = "live_lang"
|
||||
|
||||
EN: dict[str, str] = {
|
||||
# 위 막대·보기
|
||||
"이전 달": "Previous month", "다음 달": "Next month", "보기 방식": "View", "표": "Table", "달력": "Calendar",
|
||||
"호스트 설정": "Host Settings", "+ 방송 추가": "+ Add Broadcast", "언어": "Language",
|
||||
"방송을 추가하려면 먼저 호스트를 등록해야 합니다.": "Register a host before adding a broadcast.",
|
||||
"ERP 관리자에게 등록을 요청하세요.": "Ask an ERP admin to register one.",
|
||||
# 방송 창
|
||||
"방송 추가": "Add Broadcast", "방송 고치기": "Edit Broadcast", "호스트": "Host", "호스트를 고르세요": "Select a host",
|
||||
"사용 안 함": "Inactive", "방송 날짜": "Broadcast Date", "시작 시간": "Start Time", "끝 시간": "End Time",
|
||||
"시간은 말레이시아 시간으로 입력합니다.": "Enter times in Malaysia time.", "방송 장소": "Venue", "판매금액 (RM)": "Sales (RM)",
|
||||
"방송 후 입력": "Enter after the broadcast",
|
||||
"방송 결과 이미지 (JPG·PNG·WebP, 한 장 8MB, 방송당 {n}장까지)": "Result images (JPG, PNG, WebP, 8 MB each, up to {n} per broadcast)",
|
||||
"취소": "Cancel", "저장": "Save", "확인": "OK",
|
||||
# 표
|
||||
"날짜": "Date", "시간": "Time", "판매금액(RM)": "Sales (RM)", "커미션 10%(RM)": "Commission 10% (RM)",
|
||||
"호스트 비용(RM)": "Host Fee (RM)", "방송 결과": "Result", "고치기": "Edit", "지우기": "Delete",
|
||||
"기본 요금 RM {base} + 커미션 RM {commission}": "Base RM {base} + commission RM {commission}",
|
||||
"{date} {host} 방송을 지울까요? 결과 이미지도 함께 지워집니다.": "Delete the {date} broadcast by {host}? Its result images will be deleted too.",
|
||||
"이 달에 등록한 방송이 없습니다.": "No broadcasts this month.",
|
||||
# 달력
|
||||
"판매금액": "Sales", "커미션": "Com", "비용": "Fee", "광고비": "Ad Spend", "호스트 비용": "Host Fee", "총 판매금액": "Total Sales",
|
||||
"ROAS": "ROAS", "합계 & ROAS": "Total & ROAS", "날짜로 이동": "Jump to Date",
|
||||
"팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {n}일을 모두 볼 수 있습니다.":
|
||||
"Tip: Drag & drop any host header to move or swap dates. Scroll right to see all {n} days of the month.",
|
||||
"{date} {slot} 방송 추가": "Add broadcast on {date} {slot}", "{name} {date} {times} 고치기": "Edit {name} {date} {times}",
|
||||
"{date} 광고비 고치기": "Edit ad spend for {date}", "방송 결과 이미지": "Result images", "이미지 {n}": "IMG {n}",
|
||||
# 호스트 설정
|
||||
"◀ 스케줄표": "◀ Schedule", "+ 호스트 등록": "+ Add Host", "호스트 등록": "Add Host", "호스트 고치기": "Edit Host",
|
||||
"이름 (IC 기준)": "Full Name (as per IC)", "전화번호": "Phone Number", "이메일": "Email", "주소": "Address", "은행명": "Bank Name",
|
||||
"계좌번호": "Bank Account Number", "틱톡 핸들": "Tiktok Handle", "상태": "Status", "사용": "Active",
|
||||
"{name} 호스트를 지울까요?": "Delete host {name}?", "등록한 호스트가 없습니다.": "No hosts registered.",
|
||||
"사용 (끄면 새 방송에서 고를 수 없습니다)": "Active (when off, the host can't be selected for new broadcasts)",
|
||||
# 화면 스크립트(live.js)
|
||||
"서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.": "Could not reach the server. Your entries are kept — please try saving again.",
|
||||
"이 이미지": "this image", "{name} 를 지울까요?": "Delete {name}?", "{day} 광고비 (RM) — 비우면 지웁니다": "{day} ad spend (RM) — leave empty to clear",
|
||||
# 저장 결과·입력 오류
|
||||
"저장했습니다.": "Saved.", "옮겼습니다.": "Moved.", "광고비를 저장했습니다.": "Ad spend saved.", "방송을 지웠습니다.": "Broadcast deleted.",
|
||||
"이미지를 지웠습니다.": "Image deleted.", "호스트를 저장했습니다.": "Host saved.", "호스트를 지웠습니다.": "Host deleted.",
|
||||
"잘못된 요청입니다.": "Invalid request.",
|
||||
"이름 (IC 기준)을 입력하세요.": "Enter the Full Name (as per IC).", "{label} 이(가) 너무 깁니다({limit}자까지).": "{label} is too long (up to {limit} characters).",
|
||||
"이메일 형식이 올바르지 않습니다.": "The email format is invalid.", "전화번호는 숫자·+·-·괄호만 입력하세요.": "Phone Number may contain only digits, +, - and brackets.",
|
||||
"계좌번호는 숫자·-만 입력하세요.": "Bank Account Number may contain only digits and -.",
|
||||
"틱톡 핸들은 영문·숫자·밑줄·점만 입력하세요.": "Tiktok Handle may contain only letters, digits, underscores and dots.",
|
||||
"판매금액은 숫자로 입력하세요.": "Sales must be a number.", "판매금액은 0 이상 숫자로 입력하세요.": "Sales must be a number of 0 or more.", "판매금액이 너무 큽니다.": "Sales is too large.",
|
||||
"{label}을 입력하세요.": "Enter the {label}.", "{label}이 올바르지 않습니다.": "The {label} is invalid.",
|
||||
"호스트를 고르세요.": "Select a host.", "방송 날짜를 입력하세요.": "Enter the broadcast date.", "방송 장소가 너무 깁니다(200자까지).": "Venue is too long (up to 200 characters).",
|
||||
"끝 시간이 시작 시간과 같습니다.": "End time is the same as start time.", "날짜가 올바르지 않습니다.": "The date is invalid.",
|
||||
"호스트를 찾을 수 없습니다.": "Host not found.", "방송 기록이 있는 호스트는 지울 수 없습니다 — 사용 안 함으로 바꾸세요.": "A host with broadcasts can't be deleted — set the host to Inactive instead.",
|
||||
"방송을 찾을 수 없습니다(다른 사람이 지웠을 수 있음).": "Broadcast not found (someone may have deleted it).", "방송을 찾을 수 없습니다.": "Broadcast not found.",
|
||||
"사용 안 함으로 바뀐 호스트입니다 — 다른 호스트를 고르세요.": "This host is Inactive — select another host.",
|
||||
"방송 한 건에 이미지는 {max}장까지입니다(지금 {have}장).": "Up to {max} images per broadcast (currently {have}).", "방송 한 건에 이미지는 {max}장까지입니다.": "Up to {max} images per broadcast.",
|
||||
"DB 마이그레이션 live_db 002(광고비)가 아직 적용되지 않았습니다.": "DB migration live_db 002 (ad spend) has not been applied yet.", "이미지를 찾을 수 없습니다.": "Image not found.",
|
||||
"{name}: {detail}": "{name}: {detail}",
|
||||
# 권한·설정
|
||||
"로그인이 필요합니다.": "Please sign in.", "라이브 커머스 모듈 권한이 없습니다.": "You don't have access to the Live Commerce module.",
|
||||
"호스트 정보는 ERP 관리자만 볼 수 있습니다.": "Only ERP admins can view host information.", "라이브 커머스 DB(LIVE_DB_URL)가 설정되지 않았습니다.": "The Live Commerce DB (LIVE_DB_URL) is not configured.",
|
||||
"라이브 커머스 모듈 접근 권한이 없습니다.": "You don't have access to the Live Commerce module.",
|
||||
"라이브 커머스 모듈이 아직 설정되지 않았습니다. scripts/sql/live_db_init.sql 로 live_db 를 만들고 .env 에 LIVE_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요.":
|
||||
"The Live Commerce module is not set up yet. Create live_db with scripts/sql/live_db_init.sql, add LIVE_DB_URL to .env and restart the container.",
|
||||
# 자산 모듈 prepare_photo 오류(이미지 검사를 함께 쓴다)
|
||||
"사진은 비어 있지 않은 8 MB 이하 파일이어야 합니다.": "The image must be a non-empty file of 8 MB or less.", "JPG, PNG, WebP 사진만 등록할 수 있습니다.": "Only JPG, PNG and WebP images are allowed.",
|
||||
"사진은 2천만 화소 이하로 등록하세요.": "The image must be 20 megapixels or less.", "사진을 압축해 다시 등록하세요. 저장 크기는 5 MB 이하입니다.": "Please compress the image and try again (5 MB or less once stored).",
|
||||
"사진을 읽을 수 없습니다. 정상적인 JPG, PNG, WebP 파일을 선택하세요.": "The image can't be read. Please choose a valid JPG, PNG or WebP file.",
|
||||
}
|
||||
|
||||
# 화면 스크립트에 넘기는 문구(window.LV_T)
|
||||
JS_KEYS = ("확인", "취소", "지우기", "서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.", "이 이미지", "{name} 를 지울까요?",
|
||||
"{day} 광고비 (RM) — 비우면 지웁니다")
|
||||
|
||||
_MONTH_NAMES = ("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December")
|
||||
|
||||
|
||||
def norm_lang(raw: Any) -> str:
|
||||
return "en" if raw == "en" else "ko"
|
||||
|
||||
|
||||
def t(text: str, lang: str = "ko") -> str:
|
||||
return EN.get(text, text) if lang == "en" else text
|
||||
|
||||
|
||||
def js_text(lang: str) -> dict[str, str]:
|
||||
return {k: t(k, lang) for k in JS_KEYS}
|
||||
|
||||
|
||||
def month_label(year: int, month: int, lang: str = "ko") -> str:
|
||||
return f"{_MONTH_NAMES[month - 1]} {year}" if lang == "en" else f"{year}년 {month}월"
|
||||
|
||||
|
||||
class LiveError(ValueError):
|
||||
"""입력·저장 오류 — 언어에 맞게 다시 쓸 수 있게 문구 틀과 값을 따로 둔다. str() = 한글."""
|
||||
|
||||
def __init__(self, template: str, **params: Any):
|
||||
self.template, self.params = template, params
|
||||
super().__init__(template.format(**params))
|
||||
|
||||
def text(self, lang: str) -> str:
|
||||
return t(self.template, lang).format(**{k: t(v, lang) if isinstance(v, str) else v for k, v in self.params.items()})
|
||||
|
||||
|
||||
def error_text(exc: Exception, lang: str) -> str:
|
||||
return exc.text(lang) if isinstance(exc, LiveError) else t(str(exc), lang)
|
||||
@@ -0,0 +1,284 @@
|
||||
"""라이브 커머스(live) 라우터 — 말레이시아 라이브 방송의 호스트 정보·방송 스케줄(2026-11-04).
|
||||
|
||||
GET /live/ 스케줄표(?month=YYYY-MM) · GET /live/calendar 달력 보기(같은 달 값)
|
||||
POST /live/broadcasts 방송 추가·고치기(id 칸이 있으면 고치기) + 결과 이미지 올리기
|
||||
POST /live/broadcasts/{id}/delete 방송 지우기(이미지도 함께)
|
||||
POST /live/broadcasts/{id}/move 달력에서 끌어 옮기기(broadcast_date·start_time) 또는 맞바꾸기(swap_with)
|
||||
POST /live/ad-spend 날짜별 광고비(빈칸 = 지우기)
|
||||
GET /live/images/{id} 결과 이미지(?thumb=1 = 작은 그림) · POST /live/images/{id}/delete
|
||||
GET /live/settings 설정 — 호스트 정보(ERP 관리자만, 계좌 등 개인정보)
|
||||
POST /live/settings/hosts 호스트 추가·고치기 · POST /live/settings/hosts/{id}/delete
|
||||
권한: 모듈 권한키 `live`(스케줄), 설정은 ERP 관리자. DB: LIVE_DB_URL(live_db) — 없으면 "설정 필요" 안내.
|
||||
저장 요청은 live.js 가 fetch 로 보내고 JSON {ok, message} 를 받는다(틀려도 입력한 값이 창에 남게).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import PurePath
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
|
||||
from fastapi.responses import HTMLResponse, JSONResponse, Response
|
||||
|
||||
from app.modules.asset.media import MAX_PHOTO_BYTES, prepare_photo
|
||||
from app.timezone import today_kst
|
||||
|
||||
from . import i18n, store
|
||||
|
||||
router = APIRouter(prefix="/live", tags=["live"])
|
||||
|
||||
|
||||
def _store(request: Request) -> Any:
|
||||
return getattr(request.app.state, "live_store", None)
|
||||
|
||||
|
||||
def _lang(request: Request) -> str:
|
||||
return i18n.norm_lang(request.cookies.get(i18n.LANG_COOKIE))
|
||||
|
||||
|
||||
def _t(request: Request, text: str) -> str:
|
||||
return i18n.t(text, _lang(request))
|
||||
|
||||
|
||||
def _user(request: Request) -> dict[str, Any]:
|
||||
from app.main import get_current_user_record # noqa: WPS433
|
||||
from app.store import has_module # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail=_t(request, "로그인이 필요합니다."))
|
||||
if not has_module(user, "live"):
|
||||
raise HTTPException(status_code=403, detail=_t(request, "라이브 커머스 모듈 권한이 없습니다."))
|
||||
return user
|
||||
|
||||
|
||||
def _admin(request: Request) -> dict[str, Any]:
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
user = _user(request)
|
||||
if not is_admin(user):
|
||||
raise HTTPException(status_code=403, detail=_t(request, "호스트 정보는 ERP 관리자만 볼 수 있습니다."))
|
||||
return user
|
||||
|
||||
|
||||
def _db(request: Request) -> Any:
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
raise HTTPException(status_code=503, detail=_t(request, "라이브 커머스 DB(LIVE_DB_URL)가 설정되지 않았습니다."))
|
||||
return st
|
||||
|
||||
|
||||
def _page(request: Request) -> Any:
|
||||
"""화면 공통 — (st, user) 또는 응답(로그인·권한·설정 필요)."""
|
||||
from app.main import build_erp_nav, get_current_user_record, render_template # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return login_redirect(request)
|
||||
if not has_module(user, "live"):
|
||||
return render_template(request, "denied.html", {"reason": _t(request, "라이브 커머스 모듈 접근 권한이 없습니다."),
|
||||
"is_admin": is_admin(user)}, status_code=403)
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
return render_template(request, "denied.html", {
|
||||
"reason": _t(request, "라이브 커머스 모듈이 아직 설정되지 않았습니다. scripts/sql/live_db_init.sql 로 live_db 를 만들고 "
|
||||
".env 에 LIVE_DB_URL 을 넣은 뒤 컨테이너를 다시 시작하세요."),
|
||||
"user": user, "is_admin": is_admin(user), "nav_items": build_erp_nav(user, active="live")}, status_code=503)
|
||||
return st, user
|
||||
|
||||
|
||||
def _render(request: Request, name: str, user: dict[str, Any], ctx: dict[str, Any]) -> HTMLResponse:
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
lang = _lang(request)
|
||||
return render_template(request, name, {"user": user, "is_admin": is_admin(user), "lang": lang,
|
||||
"t": lambda text: i18n.t(text, lang), "js_text": i18n.js_text(lang),
|
||||
"nav_items": build_erp_nav(user, active="live"), **ctx})
|
||||
|
||||
|
||||
def _ok(request: Request, message: str) -> JSONResponse:
|
||||
return JSONResponse({"ok": True, "message": _t(request, message)})
|
||||
|
||||
|
||||
def _fail(request: Request, exc: Exception) -> JSONResponse:
|
||||
return JSONResponse({"ok": False, "message": i18n.error_text(exc, _lang(request))}, status_code=400)
|
||||
|
||||
|
||||
def _opt_id(raw: str) -> int | None:
|
||||
s = (raw or "").strip()
|
||||
if not s:
|
||||
return None
|
||||
if not s.isdigit():
|
||||
raise ValueError("잘못된 요청입니다.")
|
||||
return int(s)
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health(request: Request) -> JSONResponse:
|
||||
return JSONResponse({"status": "ok" if _store(request) is not None else "not_configured"})
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 스케줄표
|
||||
# ────────────────────────────────────────────────────────────
|
||||
@router.get("/", response_class=HTMLResponse)
|
||||
def index(request: Request, month: str = "") -> Any:
|
||||
got = _page(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
lang = _lang(request)
|
||||
span = store.month_range(month, today_kst(), lang)
|
||||
rows = [store.broadcast_view(b, lang) for b in st.list_broadcasts(span["start"], span["end"])]
|
||||
return _render(request, "live/index.html", user, {"view": "table", "span": span, "rows": rows, "hosts": st.host_choices(),
|
||||
"max_images": store.MAX_IMAGES})
|
||||
|
||||
|
||||
@router.get("/calendar", response_class=HTMLResponse)
|
||||
def calendar(request: Request, month: str = "") -> Any:
|
||||
got = _page(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
today, lang = today_kst(), _lang(request)
|
||||
span = store.month_range(month, today, lang)
|
||||
cal = store.build_calendar(span, st.list_broadcasts(span["start"], span["end"]), st.ad_spends(span["start"], span["end"]), today, lang)
|
||||
return _render(request, "live/calendar.html", user, {"view": "calendar", "span": span, "cal": cal, "hosts": st.host_choices(),
|
||||
"max_images": store.MAX_IMAGES})
|
||||
|
||||
|
||||
@router.post("/broadcasts/{broadcast_id}/move")
|
||||
def broadcast_move(request: Request, broadcast_id: int, broadcast_date: str = Form(""), start_time: str = Form(""),
|
||||
swap_with: str = Form("")) -> JSONResponse:
|
||||
user = _user(request)
|
||||
st = _db(request)
|
||||
try:
|
||||
other = _opt_id(swap_with)
|
||||
if other is not None:
|
||||
st.swap_broadcasts(broadcast_id, other, by=user.get("email", ""))
|
||||
else:
|
||||
day, start = store.parse_move(broadcast_date, start_time)
|
||||
st.move_broadcast(broadcast_id, day, start, by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _fail(request, exc)
|
||||
return _ok(request, "옮겼습니다.")
|
||||
|
||||
|
||||
@router.post("/ad-spend")
|
||||
def ad_spend_save(request: Request, day: str = Form(""), amount: str = Form("")) -> JSONResponse:
|
||||
user = _user(request)
|
||||
st = _db(request)
|
||||
try:
|
||||
when, _ = store.parse_move(day, "00:00")
|
||||
st.save_ad_spend(when, store.parse_money(amount), by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _fail(request, exc)
|
||||
return _ok(request, "광고비를 저장했습니다.")
|
||||
|
||||
|
||||
def _read_images(files: list[UploadFile]) -> list[dict[str, Any]]:
|
||||
"""고른 파일을 실제 이미지로 확인·메타데이터 제거(GPS 등). 틀리면 ValueError — 아무것도 저장하지 않게 DB 전에."""
|
||||
picked = [f for f in files if f.filename]
|
||||
if len(picked) > store.MAX_IMAGES:
|
||||
raise i18n.LiveError("방송 한 건에 이미지는 {max}장까지입니다.", max=store.MAX_IMAGES)
|
||||
out = []
|
||||
for f in picked:
|
||||
name = PurePath(f.filename.replace("\\", "/")).name[:200]
|
||||
try:
|
||||
data, ctype, width, height = prepare_photo(f.file.read(MAX_PHOTO_BYTES + 1))
|
||||
except ValueError as exc:
|
||||
raise i18n.LiveError("{name}: {detail}", name=name, detail=str(exc)) from None
|
||||
out.append({"filename": name, "content_type": ctype, "data": data, "width": width, "height": height})
|
||||
return out
|
||||
|
||||
|
||||
@router.post("/broadcasts")
|
||||
def broadcast_save(request: Request, id: str = Form(""), host_id: str = Form(""), broadcast_date: str = Form(""),
|
||||
start_time: str = Form(""), end_time: str = Form(""), venue: str = Form(""), sales_amount: str = Form(""),
|
||||
images: list[UploadFile] = File(default=[])) -> JSONResponse:
|
||||
user = _user(request)
|
||||
st = _db(request)
|
||||
try:
|
||||
broadcast_id = _opt_id(id)
|
||||
values = store.clean_broadcast({"host_id": host_id, "broadcast_date": broadcast_date, "start_time": start_time,
|
||||
"end_time": end_time, "venue": venue, "sales_amount": sales_amount})
|
||||
st.save_broadcast(broadcast_id, values, _read_images(images), by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _fail(request, exc)
|
||||
return _ok(request, "저장했습니다.")
|
||||
|
||||
|
||||
@router.post("/broadcasts/{broadcast_id}/delete")
|
||||
def broadcast_delete(request: Request, broadcast_id: int) -> JSONResponse:
|
||||
_user(request)
|
||||
try:
|
||||
_db(request).delete_broadcast(broadcast_id)
|
||||
except ValueError as exc:
|
||||
return _fail(request, exc)
|
||||
return _ok(request, "방송을 지웠습니다.")
|
||||
|
||||
|
||||
@router.get("/images/{image_id}")
|
||||
def image(request: Request, image_id: int, thumb: int = 0) -> Response:
|
||||
_user(request)
|
||||
row = _db(request).get_image(image_id)
|
||||
if not row:
|
||||
raise HTTPException(status_code=404, detail=_t(request, "이미지를 찾을 수 없습니다."))
|
||||
data, ctype = (store.thumbnail(row["data"]), "image/jpeg") if thumb else (bytes(row["data"]), row["content_type"])
|
||||
# 올린 뒤 내용이 바뀌지 않으므로 하루 캐시. 권한이 필요한 이미지라 private.
|
||||
return Response(data, media_type=ctype, headers={"Cache-Control": "private, max-age=86400", "X-Content-Type-Options": "nosniff"})
|
||||
|
||||
|
||||
@router.post("/images/{image_id}/delete")
|
||||
def image_delete(request: Request, image_id: int) -> JSONResponse:
|
||||
_user(request)
|
||||
try:
|
||||
_db(request).delete_image(image_id)
|
||||
except ValueError as exc:
|
||||
return _fail(request, exc)
|
||||
return _ok(request, "이미지를 지웠습니다.")
|
||||
|
||||
|
||||
# ────────────────────────────────────────────────────────────
|
||||
# 설정 — 호스트 정보(ERP 관리자만: 계좌 등 개인정보)
|
||||
# ────────────────────────────────────────────────────────────
|
||||
@router.get("/settings", response_class=HTMLResponse)
|
||||
def settings(request: Request) -> Any:
|
||||
from app.main import render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
got = _page(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
if not is_admin(user):
|
||||
return render_template(request, "denied.html", {"reason": _t(request, "호스트 정보는 ERP 관리자만 볼 수 있습니다."), "is_admin": False},
|
||||
status_code=403)
|
||||
return _render(request, "live/settings.html", user, {"hosts": st.list_hosts()})
|
||||
|
||||
|
||||
@router.post("/settings/hosts")
|
||||
def host_save(request: Request, id: str = Form(""), full_name: str = Form(""), phone: str = Form(""), email: str = Form(""),
|
||||
address: str = Form(""), bank_name: str = Form(""), bank_account: str = Form(""), tiktok_handle: str = Form(""),
|
||||
is_active: str = Form("")) -> JSONResponse:
|
||||
user = _admin(request)
|
||||
st = _db(request)
|
||||
try:
|
||||
values = store.clean_host({"full_name": full_name, "phone": phone, "email": email, "address": address, "bank_name": bank_name,
|
||||
"bank_account": bank_account, "tiktok_handle": tiktok_handle})
|
||||
st.save_host(_opt_id(id), values, is_active=bool(is_active), by=user.get("email", ""))
|
||||
except ValueError as exc:
|
||||
return _fail(request, exc)
|
||||
return _ok(request, "호스트를 저장했습니다.")
|
||||
|
||||
|
||||
@router.post("/settings/hosts/{host_id}/delete")
|
||||
def host_delete(request: Request, host_id: int) -> JSONResponse:
|
||||
_admin(request)
|
||||
try:
|
||||
_db(request).delete_host(host_id)
|
||||
except ValueError as exc:
|
||||
return _fail(request, exc)
|
||||
return _ok(request, "호스트를 지웠습니다.")
|
||||
@@ -0,0 +1,231 @@
|
||||
"""라이브 커머스 순수 함수 — 입력 검사·표시 형식(DB 없이 시험 가능)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import re
|
||||
from datetime import date, datetime, time, timedelta
|
||||
from decimal import ROUND_HALF_UP, Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
from PIL import Image
|
||||
|
||||
from .i18n import LiveError, month_label
|
||||
|
||||
MAX_IMAGES = 10 # 방송 한 건에
|
||||
MAX_SALES = Decimal("999999999999.99")
|
||||
THUMB_SIZE = 160
|
||||
# shortcut: 요율이 코드 상수라 바꾸면 지난 방송 금액도 다시 계산된다 — 요율이 바뀌는 일이 생기면 방송마다 저장하도록 바꿀 것
|
||||
HOURLY_RATE = Decimal("25") # 호스트 시간당 요금(RM)
|
||||
COMMISSION_PERCENT = Decimal("10") # 판매금액의 %
|
||||
SLOT_HOURS = 2 # 달력 한 칸
|
||||
FIRST_SLOT_HOUR = 6 # 달력에 늘 보이는 첫 칸(이보다 이른 칸은 방송이 있을 때만)
|
||||
HOST_COLORS = ("#66d4e6", "#6ee05a", "#d4f06a", "#e9cf7a", "#ec9d88", "#cdb9ea", "#f4a9c8", "#a9c4f5")
|
||||
_CENT = Decimal("0.01")
|
||||
_WEEKDAYS = ("MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY")
|
||||
_MONTHS = ("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC")
|
||||
|
||||
HOST_LIMITS = {"full_name": 200, "phone": 40, "email": 254, "address": 500, "bank_name": 100, "bank_account": 40, "tiktok_handle": 64}
|
||||
_LABELS = {"full_name": "이름 (IC 기준)", "phone": "전화번호", "email": "이메일", "address": "주소", "bank_name": "은행명",
|
||||
"bank_account": "계좌번호", "tiktok_handle": "틱톡 핸들"}
|
||||
_EMAIL_RE = re.compile(r"^[A-Za-z0-9._%+\-']+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}$")
|
||||
_PHONE_RE = re.compile(r"^\+?[0-9()\-\s]+$")
|
||||
_ACCOUNT_RE = re.compile(r"^[0-9\-\s]+$")
|
||||
_HANDLE_RE = re.compile(r"^[A-Za-z0-9._]+$")
|
||||
_HANDLE_URL_RE = re.compile(r"^(?:https?://)?(?:www\.|m\.)?tiktok\.com/@?", re.I)
|
||||
WEEKDAYS_KO = "월화수목금토일"
|
||||
_WEEKDAYS_EN_SHORT = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
|
||||
|
||||
|
||||
def clean_handle(raw: Any) -> str:
|
||||
"""'@name'·'https://www.tiktok.com/@name?lang=en' → 'name'."""
|
||||
s = _HANDLE_URL_RE.sub("", str(raw or "").strip())
|
||||
return re.split(r"[/?#]", s, maxsplit=1)[0].lstrip("@")
|
||||
|
||||
|
||||
def clean_host(values: dict[str, Any]) -> dict[str, str]:
|
||||
"""호스트 입력 검사 — 이름만 필수, 나머지는 있으면 형식 확인. 틀리면 ValueError."""
|
||||
out = {k: str(values.get(k) or "").strip() for k in HOST_LIMITS}
|
||||
out["tiktok_handle"] = clean_handle(values.get("tiktok_handle"))
|
||||
if not out["full_name"]:
|
||||
raise LiveError("이름 (IC 기준)을 입력하세요.")
|
||||
for key, limit in HOST_LIMITS.items():
|
||||
if len(out[key]) > limit:
|
||||
raise LiveError("{label} 이(가) 너무 깁니다({limit}자까지).", label=_LABELS[key], limit=limit)
|
||||
if out["email"] and not _EMAIL_RE.match(out["email"]):
|
||||
raise LiveError("이메일 형식이 올바르지 않습니다.")
|
||||
if out["phone"] and not _PHONE_RE.match(out["phone"]):
|
||||
raise LiveError("전화번호는 숫자·+·-·괄호만 입력하세요.")
|
||||
if out["bank_account"] and not _ACCOUNT_RE.match(out["bank_account"]):
|
||||
raise LiveError("계좌번호는 숫자·-만 입력하세요.")
|
||||
if out["tiktok_handle"] and not _HANDLE_RE.match(out["tiktok_handle"]):
|
||||
raise LiveError("틱톡 핸들은 영문·숫자·밑줄·점만 입력하세요.")
|
||||
return out
|
||||
|
||||
|
||||
def parse_money(raw: Any) -> Decimal | None:
|
||||
"""판매금액(RM) — 빈칸은 None(아직 입력 안 함), 0 이상, 소수 둘째 자리까지. 쉼표·RM 허용."""
|
||||
s = re.sub(r"(?i)^rm|[,\s]", "", str(raw if raw is not None else "").strip())
|
||||
if not s:
|
||||
return None
|
||||
try:
|
||||
n = Decimal(s)
|
||||
except InvalidOperation:
|
||||
raise LiveError("판매금액은 숫자로 입력하세요.") from None
|
||||
if not n.is_finite() or n < 0:
|
||||
raise LiveError("판매금액은 0 이상 숫자로 입력하세요.")
|
||||
if n > MAX_SALES:
|
||||
raise LiveError("판매금액이 너무 큽니다.")
|
||||
return n.quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
|
||||
|
||||
|
||||
def _parse_time(raw: Any, *, label: str, required: bool) -> time | None:
|
||||
s = str(raw or "").strip()
|
||||
if not s:
|
||||
if required:
|
||||
raise LiveError("{label}을 입력하세요.", label=label)
|
||||
return None
|
||||
try:
|
||||
return time.fromisoformat(s).replace(second=0, microsecond=0, tzinfo=None)
|
||||
except ValueError:
|
||||
raise LiveError("{label}이 올바르지 않습니다.", label=label) from None
|
||||
|
||||
|
||||
def clean_broadcast(values: dict[str, Any]) -> dict[str, Any]:
|
||||
"""방송 입력 검사 — 호스트·날짜·시작·끝 시간 필수(끝 시간으로 시간 요금 계산). 끝이 시작보다 이르면 자정을 넘긴 방송. 틀리면 ValueError."""
|
||||
host = str(values.get("host_id") or "").strip()
|
||||
if not host.isdigit():
|
||||
raise LiveError("호스트를 고르세요.")
|
||||
try:
|
||||
day = date.fromisoformat(str(values.get("broadcast_date") or "").strip())
|
||||
except ValueError:
|
||||
raise LiveError("방송 날짜를 입력하세요.") from None
|
||||
venue = str(values.get("venue") or "").strip()
|
||||
if len(venue) > 200:
|
||||
raise LiveError("방송 장소가 너무 깁니다(200자까지).")
|
||||
start = _parse_time(values.get("start_time"), label="시작 시간", required=True)
|
||||
end = _parse_time(values.get("end_time"), label="끝 시간", required=True)
|
||||
if start == end:
|
||||
raise LiveError("끝 시간이 시작 시간과 같습니다.")
|
||||
return {"host_id": int(host), "broadcast_date": day, "start_time": start, "end_time": end,
|
||||
"venue": venue, "sales_amount": parse_money(values.get("sales_amount"))}
|
||||
|
||||
|
||||
def parse_move(day: Any, start: Any) -> tuple[date, time]:
|
||||
"""달력 칸 — 날짜·시작 시간. 틀리면 ValueError."""
|
||||
try:
|
||||
when = date.fromisoformat(str(day or "").strip())
|
||||
except ValueError:
|
||||
raise LiveError("날짜가 올바르지 않습니다.") from None
|
||||
return when, _parse_time(start, label="시간", required=True)
|
||||
|
||||
|
||||
def moved_end(old_start: time, old_end: time | None, new_start: time) -> time | None:
|
||||
"""칸을 옮겨도 방송 길이는 그대로."""
|
||||
if old_end is None:
|
||||
return None
|
||||
return (datetime.combine(date.min, new_start) + _duration(old_start, old_end)).time()
|
||||
|
||||
|
||||
def _duration(start: time, end: time) -> timedelta:
|
||||
minutes = (end.hour * 60 + end.minute - start.hour * 60 - start.minute) % 1440 # 끝이 더 이르면 자정을 넘긴 방송
|
||||
return timedelta(minutes=minutes)
|
||||
|
||||
|
||||
def session_pay(start: time, end: time | None, sales: Decimal | None) -> dict[str, Decimal]:
|
||||
"""호스트 비용 — 기본 요금(시간 × 시간당 요금) + 커미션(판매금액 × %)."""
|
||||
hours = Decimal(_duration(start, end).seconds) / 3600 if end else Decimal(0)
|
||||
base = (hours * HOURLY_RATE).quantize(_CENT, rounding=ROUND_HALF_UP)
|
||||
commission = ((sales or Decimal(0)) * COMMISSION_PERCENT / 100).quantize(_CENT, rounding=ROUND_HALF_UP)
|
||||
return {"hours": hours, "base": base, "commission": commission, "fee": base + commission}
|
||||
|
||||
|
||||
def fmt_short(n: Decimal) -> str:
|
||||
"""카드·합계용 — 소수점 아래가 0 이면 뺀다(48, 4.80, 1,234.50)."""
|
||||
return f"{n:,.2f}".removesuffix(".00")
|
||||
|
||||
|
||||
def broadcast_view(b: dict[str, Any], lang: str = "ko") -> dict[str, Any]:
|
||||
"""방송 한 건 화면 값 — 표·달력 공통. b = db.list_broadcasts 한 줄."""
|
||||
pay = session_pay(b["start_time"], b["end_time"], b["sales_amount"])
|
||||
return {
|
||||
"date": fmt_date(b["broadcast_date"], lang), "times": fmt_times(b["start_time"], b["end_time"]),
|
||||
"host_name": b["host_name"], "tiktok_handle": b["tiktok_handle"], "venue": b["venue"],
|
||||
"sales": fmt_money(b["sales_amount"]), "commission": fmt_money(pay["commission"]), "fee": fmt_money(pay["fee"]),
|
||||
"images": b["images"], "pay": pay, "id": b["id"],
|
||||
"label": b["tiktok_handle"] or b["host_name"], "color": HOST_COLORS[b["host_id"] % len(HOST_COLORS)],
|
||||
"card_sales": fmt_short(b["sales_amount"] or Decimal(0)), "card_commission": fmt_short(pay["commission"]),
|
||||
"card_fee": fmt_short(pay["fee"]),
|
||||
"edit": {"id": b["id"], "host_id": b["host_id"], "broadcast_date": b["broadcast_date"].isoformat(),
|
||||
"start_time": f"{b['start_time']:%H:%M}", "end_time": f"{b['end_time']:%H:%M}" if b["end_time"] else "",
|
||||
"venue": b["venue"], "sales_amount": f"{b['sales_amount']:.2f}" if b["sales_amount"] is not None else "",
|
||||
"images": [{"id": i["id"], "filename": i["filename"]} for i in b["images"]]},
|
||||
}
|
||||
|
||||
|
||||
def _roas(sales: Decimal, ad_spend: Decimal) -> str:
|
||||
return f"{sales / ad_spend:.2f}" if ad_spend else "-"
|
||||
|
||||
|
||||
def build_calendar(span: dict[str, Any], broadcasts: list[dict[str, Any]], ad_spend: dict[date, Decimal], today: date, lang: str = "ko") -> dict[str, Any]:
|
||||
"""달력 보기 값 — 날짜(열)·2시간 칸(줄)·날짜별 합계·달 합계. 칸은 시작 시간으로 정한다."""
|
||||
views = [(b, broadcast_view(b, lang)) for b in broadcasts]
|
||||
used = {b["start_time"].hour // SLOT_HOURS * SLOT_HOURS for b, _ in views}
|
||||
days = []
|
||||
day = span["start"]
|
||||
while day < span["end"]:
|
||||
mine = [(b, v) for b, v in views if b["broadcast_date"] == day]
|
||||
sales = sum((b["sales_amount"] or Decimal(0) for b, _ in mine), Decimal(0))
|
||||
fee = sum((v["pay"]["fee"] for _, v in mine), Decimal(0))
|
||||
spend = ad_spend.get(day, Decimal(0))
|
||||
days.append({"iso": day.isoformat(), "date": day, "day": day.day, "weekday": _WEEKDAYS[day.weekday()] if lang == "en" else WEEKDAYS_KO[day.weekday()] + "요일",
|
||||
"label": f"{day.day} {_MONTHS[day.month - 1]}" if lang == "en" else f"{day.month}월 {day.day}일", "is_weekend": day.weekday() >= 5, "is_today": day == today,
|
||||
"count": len(mine), "sales": sales, "fee": fee, "spend": spend,
|
||||
"sales_text": fmt_short(sales), "fee_text": fmt_short(fee), "spend_text": fmt_short(spend), "roas": _roas(sales, spend)})
|
||||
day += timedelta(days=1)
|
||||
slots = []
|
||||
for hour in sorted(set(range(FIRST_SLOT_HOUR, 24, SLOT_HOURS)) | used):
|
||||
end_hour = (hour + SLOT_HOURS) % 24
|
||||
cells = [{"iso": d["iso"], "is_weekend": d["is_weekend"],
|
||||
"cards": [v for b, v in views if b["broadcast_date"] == d["date"] and b["start_time"].hour // SLOT_HOURS * SLOT_HOURS == hour]}
|
||||
for d in days]
|
||||
slots.append({"start": f"{hour:02d}:00", "end": f"{end_hour:02d}:00", "label": f"{hour:02d}:00 - {end_hour:02d}:00", "cells": cells})
|
||||
sales, fee, spend = (sum((d[k] for d in days), Decimal(0)) for k in ("sales", "fee", "spend"))
|
||||
return {"days": days, "slots": slots, "slot_note": f"{SLOT_HOURS} Hours (RM{fmt_short(HOURLY_RATE * SLOT_HOURS)} Base)" if lang == "en" else f"{SLOT_HOURS}시간 (기본 RM{fmt_short(HOURLY_RATE * SLOT_HOURS)})",
|
||||
"commission_percent": fmt_short(COMMISSION_PERCENT).split(".")[0],
|
||||
"totals": {"sales": fmt_short(sales), "fee": fmt_short(fee), "spend": fmt_short(spend), "roas": _roas(sales, spend)}}
|
||||
|
||||
|
||||
def month_range(raw: Any, today: date, lang: str = "ko") -> dict[str, Any]:
|
||||
"""'YYYY-MM'(틀리거나 없으면 이번 달) → 그 달 첫날·다음 달 첫날·앞뒤 달 주소 값·제목."""
|
||||
m = re.fullmatch(r"(\d{4})-(\d{2})", str(raw or "").strip())
|
||||
year, month = (int(m[1]), int(m[2])) if m and 2000 <= int(m[1]) <= 2100 and 1 <= int(m[2]) <= 12 else (today.year, today.month)
|
||||
start = date(year, month, 1)
|
||||
end = date(year + (month == 12), month % 12 + 1, 1)
|
||||
prev = date(year - (month == 1), (month - 2) % 12 + 1, 1)
|
||||
return {"start": start, "end": end, "prev": prev.strftime("%Y-%m"), "next": end.strftime("%Y-%m"),
|
||||
"label": month_label(year, month, lang)}
|
||||
|
||||
|
||||
def fmt_date(d: date, lang: str = "ko") -> str:
|
||||
return f"{d:%Y.%m.%d} ({_WEEKDAYS_EN_SHORT[d.weekday()]})" if lang == "en" else f"{d:%Y.%m.%d}({WEEKDAYS_KO[d.weekday()]})"
|
||||
|
||||
|
||||
def fmt_times(start: time, end: time | None) -> str:
|
||||
return f"{start:%H:%M}" + (f" ~ {end:%H:%M}" if end else "")
|
||||
|
||||
|
||||
def fmt_money(n: Decimal | None) -> str:
|
||||
return f"{n:,.2f}" if n is not None else ""
|
||||
|
||||
|
||||
def thumbnail(data: bytes) -> bytes:
|
||||
"""목록 작은 그림 — JPEG(투명은 흰 바탕). 저장할 때 이미 확인한 이미지만 들어온다."""
|
||||
with Image.open(io.BytesIO(data)) as source:
|
||||
source.thumbnail((THUMB_SIZE, THUMB_SIZE))
|
||||
rgba = source.convert("RGBA")
|
||||
canvas = Image.new("RGB", rgba.size, "white")
|
||||
canvas.paste(rgba, mask=rgba.getchannel("A"))
|
||||
out = io.BytesIO()
|
||||
canvas.save(out, format="JPEG", quality=80)
|
||||
return out.getvalue()
|
||||
@@ -0,0 +1,19 @@
|
||||
{#- 스케줄표·달력 공통 위 막대 — 달 이동, 표/달력 전환, 언어, 호스트 설정, 방송 추가. view = table | calendar -#}
|
||||
{% set here = '/live/calendar' if view == 'calendar' else '/live/' %}
|
||||
{% set can_add = hosts | selectattr('is_active') | list %}
|
||||
<div class="lv-bar">
|
||||
<a class="erp-btn erp-btn-outline" href="{{ here }}?month={{ span.prev }}" aria-label="{{ t('이전 달') }}">◀</a>
|
||||
<h2 class="lv-month">{{ span.label }}</h2>
|
||||
<a class="erp-btn erp-btn-outline" href="{{ here }}?month={{ span.next }}" aria-label="{{ t('다음 달') }}">▶</a>
|
||||
<nav class="lv-views" aria-label="{{ t('보기 방식') }}">
|
||||
<a class="erp-btn {{ 'erp-btn-primary' if view == 'table' else 'erp-btn-outline' }}" href="/live/?month={{ span.start.strftime('%Y-%m') }}"{% if view == 'table' %} aria-current="page"{% endif %}>{{ t('표') }}</a>
|
||||
<a class="erp-btn {{ 'erp-btn-primary' if view == 'calendar' else 'erp-btn-outline' }}" href="/live/calendar?month={{ span.start.strftime('%Y-%m') }}"{% if view == 'calendar' %} aria-current="page"{% endif %}>{{ t('달력') }}</a>
|
||||
</nav>
|
||||
<span class="lv-gap"></span>
|
||||
{% include "live/_lang.html" %}
|
||||
{% if is_admin %}<a class="erp-btn erp-btn-outline" href="/live/settings">{{ t('호스트 설정') }}</a>{% endif %}
|
||||
<button type="button" class="erp-btn erp-btn-primary" id="lv-add"{% if not can_add %} disabled{% endif %}>{{ t('+ 방송 추가') }}</button>
|
||||
</div>
|
||||
{% if not can_add %}
|
||||
<p class="lv-note">{{ t('방송을 추가하려면 먼저 호스트를 등록해야 합니다.') }} {% if is_admin %}<a href="/live/settings">{{ t('호스트 설정') }}</a>{% else %}{{ t('ERP 관리자에게 등록을 요청하세요.') }}{% endif %}</p>
|
||||
{% endif %}
|
||||
@@ -0,0 +1,30 @@
|
||||
{#- 방송 추가·고치기 창 — 스케줄표·달력 공통(live.js). 호스트 고르기엔 이름·틱톡만(계좌 등은 설정 화면). -#}
|
||||
<dialog class="lv-dlg" id="lv-dlg" aria-labelledby="lv-dlg-title">
|
||||
<form id="lv-form" action="/live/broadcasts">
|
||||
<h3 id="lv-dlg-title" data-add="{{ t('방송 추가') }}" data-edit="{{ t('방송 고치기') }}"></h3>
|
||||
<input type="hidden" name="id" />
|
||||
<label class="lv-field">{{ t('호스트') }}
|
||||
<select class="erp-select" name="host_id" required>
|
||||
<option value="">{{ t('호스트를 고르세요') }}</option>
|
||||
{% for h in hosts %}<option value="{{ h.id }}"{% if not h.is_active %} data-inactive="1"{% endif %}>{{ h.full_name }}{% if h.tiktok_handle %} (@{{ h.tiktok_handle }}){% endif %}{% if not h.is_active %} — {{ t('사용 안 함') }}{% endif %}</option>{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<div class="lv-row">
|
||||
<label class="lv-field">{{ t('방송 날짜') }} <input class="erp-input" type="date" name="broadcast_date" required /></label>
|
||||
<label class="lv-field">{{ t('시작 시간') }} <input class="erp-input" type="time" name="start_time" required /></label>
|
||||
<label class="lv-field">{{ t('끝 시간') }} <input class="erp-input" type="time" name="end_time" required /></label>
|
||||
</div>
|
||||
<p class="lv-sub">{{ t('시간은 말레이시아 시간으로 입력합니다.') }}</p>
|
||||
<label class="lv-field">{{ t('방송 장소') }} <input class="erp-input" type="text" name="venue" maxlength="200" /></label>
|
||||
<label class="lv-field">{{ t('판매금액 (RM)') }} <input class="erp-input lv-num" type="text" name="sales_amount" inputmode="decimal" placeholder="{{ t('방송 후 입력') }}" /></label>
|
||||
<label class="lv-field">{{ t('방송 결과 이미지 (JPG·PNG·WebP, 한 장 8MB, 방송당 {n}장까지)').format(n=max_images) }}
|
||||
<input type="file" name="images" accept="image/jpeg,image/png,image/webp" multiple />
|
||||
</label>
|
||||
<ul class="lv-saved" data-saved hidden></ul>
|
||||
<p class="lv-msg" data-msg role="alert" hidden></p>
|
||||
<div class="lv-foot">
|
||||
<button type="button" class="erp-btn erp-btn-outline" data-close>{{ t('취소') }}</button>
|
||||
<button type="submit" class="erp-btn erp-btn-primary">{{ t('저장') }}</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
@@ -0,0 +1,5 @@
|
||||
{#- 한글·영문 전환 — 누르면 쿠키에 저장하고 다시 그린다(live.js). 언어 이름은 언어와 상관없이 그대로 보인다. -#}
|
||||
<div class="lv-lang" role="group" aria-label="{{ t('언어') }}">
|
||||
<button type="button" data-lang="ko"{% if lang != 'en' %} class="is-active" aria-pressed="true"{% else %} aria-pressed="false"{% endif %}>한글</button>
|
||||
<button type="button" data-lang="en"{% if lang == 'en' %} class="is-active" aria-pressed="true"{% else %} aria-pressed="false"{% endif %}>EN</button>
|
||||
</div>
|
||||
@@ -0,0 +1,2 @@
|
||||
<script>window.LV_T = {{ js_text | tojson }};</script>
|
||||
<script src="/static/live.js?v=20261104c" defer></script>
|
||||
@@ -0,0 +1,86 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{#- 라이브 커머스 달력 보기(2026-11-04) — 줄 = 2시간 칸, 열 = 날짜, 맨 아래 = 날짜별 합계. 카드 머리 = Tiktok Handle(없으면 이름).
|
||||
카드 머리를 끌어 빈 칸으로 옮기거나 다른 카드 위에 놓아 맞바꾼다(live.js). 문구 = t()(i18n.py), 영문은 CSS 로 대문자(받은 화면과 같게). -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261104c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="lv" lang="{{ lang }}">
|
||||
{% include "live/_bar.html" %}
|
||||
|
||||
<div class="lv-kpis">
|
||||
<div class="lv-kpi"><span>{{ t('총 판매금액') }}</span><b>RM {{ cal.totals.sales }}</b></div>
|
||||
<div class="lv-kpi"><span>{{ t('광고비') }}</span><b>RM {{ cal.totals.spend }}</b></div>
|
||||
<div class="lv-kpi"><span>{{ t('호스트 비용') }}</span><b>RM {{ cal.totals.fee }}</b></div>
|
||||
<div class="lv-kpi"><span>ROAS</span><b>{{ cal.totals.roas }}</b></div>
|
||||
</div>
|
||||
|
||||
<nav class="lv-jump" aria-label="{{ t('날짜로 이동') }}">
|
||||
<span class="lv-jump-label">{{ t('날짜로 이동') }}:</span>
|
||||
{% for d in cal.days %}<button type="button" class="lv-jump-day{% if d.is_weekend %} is-weekend{% endif %}{% if d.is_today %} is-today{% endif %}" data-jump="{{ d.iso }}">{{ d.day }}</button>{% endfor %}
|
||||
</nav>
|
||||
<p class="lv-tip">{{ t('팁: 카드 머리를 끌어 옮기거나 맞바꿀 수 있습니다. 오른쪽으로 스크롤하면 이달 {n}일을 모두 볼 수 있습니다.').format(n=cal.days | length) }}</p>
|
||||
|
||||
<div class="lv-cal-wrap" id="lv-cal-wrap">
|
||||
<table class="lv-cal">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="lv-cal-time" scope="col">{{ t('시간') }}</th>
|
||||
{% for d in cal.days %}
|
||||
<th scope="col" data-day="{{ d.iso }}"{% if d.is_today %} data-today="1"{% endif %} class="{% if d.is_weekend %}is-weekend{% endif %}{% if d.is_today %} is-today{% endif %}">
|
||||
<div class="lv-cal-weekday">{{ d.weekday }} <span class="lv-cal-count">{{ d.count }}</span></div>
|
||||
<div class="lv-cal-date">{{ d.label }}</div>
|
||||
</th>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for slot in cal.slots %}
|
||||
<tr>
|
||||
<th class="lv-cal-time" scope="row">{{ slot.label }}<small>{{ cal.slot_note }}</small></th>
|
||||
{% for cell in slot.cells %}
|
||||
<td class="lv-cell{% if cell.is_weekend %} is-weekend{% endif %}" data-drop data-day="{{ cell.iso }}" data-start="{{ slot.start }}">
|
||||
{% for c in cell.cards %}
|
||||
<article class="lv-card" data-card="{{ c.id }}">
|
||||
<header class="lv-card-head" draggable="true" style="background:{{ c.color }}" title="{{ c.host_name }} · {{ c.times }}{% if c.venue %} · {{ c.venue }}{% endif %}">
|
||||
<span class="lv-card-grip" aria-hidden="true">✥</span>
|
||||
<span class="lv-card-name">{{ c.label }}</span>
|
||||
<button type="button" class="lv-card-edit" data-edit='{{ c.edit | tojson }}' aria-label="{{ t('{name} {date} {times} 고치기').format(name=c.label, date=c.date, times=c.times) }}">✎</button>
|
||||
</header>
|
||||
<div class="lv-card-nums">
|
||||
<div><span>{{ t('판매금액') }}</span><b>{{ c.card_sales }}</b></div>
|
||||
<div><span>{{ t('커미션') }} ({{ cal.commission_percent }}%)</span><b>{{ c.card_commission }}</b></div>
|
||||
</div>
|
||||
<footer class="lv-card-foot"><span>{{ t('비용') }}: <b>RM{{ c.card_fee }}</b></span>{% if c.images %}<a href="/live/images/{{ c.images[0].id }}" target="_blank" rel="noopener" title="{{ t('방송 결과 이미지') }}">{{ t('이미지 {n}').format(n=c.images | length) }}</a>{% endif %}</footer>
|
||||
</article>
|
||||
{% endfor %}
|
||||
{% if not cell.cards and hosts | selectattr('is_active') | list %}
|
||||
<button type="button" class="lv-cell-add" data-new='{{ {"broadcast_date": cell.iso, "start_time": slot.start, "end_time": slot.end} | tojson }}' aria-label="{{ t('{date} {slot} 방송 추가').format(date=cell.iso, slot=slot.label) }}">+</button>
|
||||
{% endif %}
|
||||
</td>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<th class="lv-cal-time" scope="row">{{ t('합계 & ROAS') }}</th>
|
||||
{% for d in cal.days %}
|
||||
<td>
|
||||
<dl class="lv-total">
|
||||
<div><dt>{{ t('총 판매금액') }}:</dt><dd class="is-sales">RM {{ d.sales_text }}</dd></div>
|
||||
<div><dt>{{ t('광고비') }}:</dt><dd>RM {{ d.spend_text }} <button type="button" class="lv-total-edit" data-spend="{{ d.iso }}" data-value="{{ d.spend if d.spend else '' }}" aria-label="{{ t('{date} 광고비 고치기').format(date=d.iso) }}">✎</button></dd></div>
|
||||
<div><dt>{{ t('호스트 비용') }}:</dt><dd>RM {{ d.fee_text }}</dd></div>
|
||||
<div><dt>ROAS:</dt><dd>{{ d.roas }}</dd></div>
|
||||
</dl>
|
||||
</td>
|
||||
{% endfor %}
|
||||
</tr>
|
||||
</tfoot>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{% include "live/_dialog.html" %}
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}{% include "live/_scripts.html" %}{% endblock %}
|
||||
@@ -0,0 +1,41 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{#- 라이브 커머스 스케줄표(2026-11-04) — 달마다 방송 목록. 추가·고치기 창은 달력과 공용(_dialog.html, live.js). 문구 = t()(i18n.py). -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261104c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="lv" lang="{{ lang }}">
|
||||
{% include "live/_bar.html" %}
|
||||
|
||||
<div class="erp-card-block">
|
||||
<div class="erp-table-wrap">
|
||||
<table class="erp-table lv-table">
|
||||
<thead><tr><th>{{ t('날짜') }}</th><th>{{ t('시간') }}</th><th>{{ t('호스트') }}</th><th>{{ t('방송 장소') }}</th><th class="lv-r">{{ t('판매금액(RM)') }}</th><th class="lv-r">{{ t('커미션 10%(RM)') }}</th><th class="lv-r">{{ t('호스트 비용(RM)') }}</th><th>{{ t('방송 결과') }}</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in rows %}
|
||||
<tr>
|
||||
<td class="lv-nowrap" data-label="{{ t('날짜') }}">{{ r.date }}</td>
|
||||
<td class="lv-nowrap" data-label="{{ t('시간') }}">{{ r.times }}</td>
|
||||
<td data-label="{{ t('호스트') }}">{{ r.host_name }}{% if r.tiktok_handle %}<div class="lv-sub">@{{ r.tiktok_handle }}</div>{% endif %}</td>
|
||||
<td data-label="{{ t('방송 장소') }}">{{ r.venue }}</td>
|
||||
<td class="lv-r lv-num" data-label="{{ t('판매금액(RM)') }}">{{ r.sales }}</td>
|
||||
<td class="lv-r lv-num" data-label="{{ t('커미션 10%(RM)') }}">{{ r.commission }}</td>
|
||||
<td class="lv-r lv-num" data-label="{{ t('호스트 비용(RM)') }}" title="{{ t('기본 요금 RM {base} + 커미션 RM {commission}').format(base=r.pay.base, commission=r.pay.commission) }}">{{ r.fee }}</td>
|
||||
<td data-label="{{ t('방송 결과') }}"><div class="lv-thumbs">{% for im in r.images %}<a href="/live/images/{{ im.id }}" target="_blank" rel="noopener" title="{{ im.filename }}"><img src="/live/images/{{ im.id }}?thumb=1" alt="{{ im.filename }}" loading="lazy" /></a>{% endfor %}</div></td>
|
||||
<td class="lv-actions">
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ r.edit | tojson }}'>{{ t('고치기') }}</button>
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-post="/live/broadcasts/{{ r.id }}/delete" data-confirm="{{ t('{date} {host} 방송을 지울까요? 결과 이미지도 함께 지워집니다.').format(date=r.date, host=r.host_name) }}">{{ t('지우기') }}</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="9" class="erp-empty">{{ t('이 달에 등록한 방송이 없습니다.') }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{% include "live/_dialog.html" %}
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}{% include "live/_scripts.html" %}{% endblock %}
|
||||
@@ -0,0 +1,67 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{#- 라이브 커머스 설정(2026-11-04) — 호스트 정보. 계좌 등 개인정보라 ERP 관리자만(router.settings). 추가·고치기는 같은 창(live.js). 문구 = t()(i18n.py). -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/live.css?v=20261104c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="lv" lang="{{ lang }}">
|
||||
<div class="lv-bar">
|
||||
<a class="erp-btn erp-btn-outline" href="/live/">{{ t('◀ 스케줄표') }}</a>
|
||||
<h2 class="lv-month">{{ t('호스트 설정') }}</h2>
|
||||
<span class="lv-gap"></span>
|
||||
{% include "live/_lang.html" %}
|
||||
<button type="button" class="erp-btn erp-btn-primary" id="lv-add">{{ t('+ 호스트 등록') }}</button>
|
||||
</div>
|
||||
|
||||
<div class="erp-card-block">
|
||||
<div class="erp-table-wrap">
|
||||
<table class="erp-table lv-table">
|
||||
<thead><tr><th>{{ t('이름 (IC 기준)') }}</th><th>{{ t('전화번호') }}</th><th>{{ t('이메일') }}</th><th>{{ t('주소') }}</th><th>{{ t('은행명') }}</th><th>{{ t('계좌번호') }}</th><th>{{ t('틱톡 핸들') }}</th><th>{{ t('상태') }}</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{% for h in hosts %}
|
||||
<tr{% if not h.is_active %} class="lv-off"{% endif %}>
|
||||
<td data-label="{{ t('이름 (IC 기준)') }}">{{ h.full_name }}</td>
|
||||
<td class="lv-nowrap" data-label="{{ t('전화번호') }}">{{ h.phone }}</td>
|
||||
<td data-label="{{ t('이메일') }}">{{ h.email }}</td>
|
||||
<td data-label="{{ t('주소') }}">{{ h.address }}</td>
|
||||
<td data-label="{{ t('은행명') }}">{{ h.bank_name }}</td>
|
||||
<td class="lv-nowrap" data-label="{{ t('계좌번호') }}">{{ h.bank_account }}</td>
|
||||
<td data-label="{{ t('틱톡 핸들') }}">{% if h.tiktok_handle %}@{{ h.tiktok_handle }}{% endif %}</td>
|
||||
<td class="lv-nowrap" data-label="{{ t('상태') }}">{{ t('사용') if h.is_active else t('사용 안 함') }}</td>
|
||||
<td class="lv-actions">
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-edit='{{ {"id": h.id, "full_name": h.full_name, "phone": h.phone, "email": h.email, "address": h.address, "bank_name": h.bank_name, "bank_account": h.bank_account, "tiktok_handle": h.tiktok_handle, "is_active": h.is_active} | tojson }}'>{{ t('고치기') }}</button>
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-post="/live/settings/hosts/{{ h.id }}/delete" data-confirm="{{ t('{name} 호스트를 지울까요?').format(name=h.full_name) }}">{{ t('지우기') }}</button>
|
||||
</td>
|
||||
</tr>
|
||||
{% else %}
|
||||
<tr><td colspan="9" class="erp-empty">{{ t('등록한 호스트가 없습니다.') }}</td></tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<dialog class="lv-dlg" id="lv-dlg" aria-labelledby="lv-dlg-title">
|
||||
<form id="lv-form" action="/live/settings/hosts">
|
||||
<h3 id="lv-dlg-title" data-add="{{ t('호스트 등록') }}" data-edit="{{ t('호스트 고치기') }}"></h3>
|
||||
<input type="hidden" name="id" />
|
||||
<label class="lv-field">{{ t('이름 (IC 기준)') }} <input class="erp-input" type="text" name="full_name" maxlength="200" required /></label>
|
||||
<label class="lv-field">{{ t('전화번호') }} <input class="erp-input" type="tel" name="phone" maxlength="40" /></label>
|
||||
<label class="lv-field">{{ t('이메일') }} <input class="erp-input" type="email" name="email" maxlength="254" /></label>
|
||||
<label class="lv-field">{{ t('주소') }} <textarea class="erp-input" name="address" rows="2" maxlength="500"></textarea></label>
|
||||
<div class="lv-row">
|
||||
<label class="lv-field">{{ t('은행명') }} <input class="erp-input" type="text" name="bank_name" maxlength="100" /></label>
|
||||
<label class="lv-field">{{ t('계좌번호') }} <input class="erp-input" type="text" name="bank_account" maxlength="40" inputmode="numeric" /></label>
|
||||
</div>
|
||||
<label class="lv-field">{{ t('틱톡 핸들') }} <input class="erp-input" type="text" name="tiktok_handle" maxlength="200" placeholder="@handle" /></label>
|
||||
<label class="lv-check"><input type="checkbox" name="is_active" value="1" checked /> {{ t('사용 (끄면 새 방송에서 고를 수 없습니다)') }}</label>
|
||||
<p class="lv-msg" data-msg role="alert" hidden></p>
|
||||
<div class="lv-foot">
|
||||
<button type="button" class="erp-btn erp-btn-outline" data-close>{{ t('취소') }}</button>
|
||||
<button type="submit" class="erp-btn erp-btn-primary">{{ t('저장') }}</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}{% include "live/_scripts.html" %}{% endblock %}
|
||||
@@ -90,11 +90,11 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
|
||||
def _guard(request: Request) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
|
||||
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
|
||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||
from app.store import has_module, is_admin # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return RedirectResponse(url="/login", status_code=303)
|
||||
return login_redirect(request)
|
||||
if not has_module(user, "malaysia"):
|
||||
return render_template(
|
||||
request,
|
||||
|
||||
@@ -64,7 +64,7 @@
|
||||
</section>
|
||||
</div>
|
||||
<script>window.NTC_PEOPLE = {{ people | tojson }};</script>
|
||||
<script src="/static/project.js?v=20261027a" defer></script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
<script src="/static/erp-notice-admin.js?v=20261012b" defer></script>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
> 이 모듈만 고칠 때 읽는 요약. 별도 상세 문서 없음 — 코드가 기준.
|
||||
> 정적 파일: `app/static/outreach.js`, `app/static/outreach.css`. 템플릿: `templates/outreach/`. 테스트: `tests/test_outreach.py`,
|
||||
> `tests/js/outreach.browser.test.js`(`render_outreach.py`).
|
||||
> `tests/js/outreach.browser.test.js`·`outreach_settings.browser.test.js`(`render_outreach.py`). 편집기 = `app/static/vendor/quill/`(Quill 2.0.3, BSD).
|
||||
> 다른 모듈과 연결: 메일 = 입출고 Gmail 연결(`inout_store.inout_gmail_tokens`, `app/modules/inout/gmail.py`, 콜백 `/inout/gmail/callback` 이
|
||||
> 세션 `_gmail_origin=outreach` 를 보고 `_GMAIL_ORIGINS` 로 처리) — 입출고·휴가와 같은 연결.
|
||||
|
||||
@@ -10,13 +10,31 @@
|
||||
- **주소를 보고 메일/DM 판별**(`store.detect`): `name@domain.tld` = 메일, `@계정`·`instagram.com/계정`·`ig.me/m/계정`·계정명만(영문·숫자·.·_) = 인스타 DM.
|
||||
게시물 주소(`/p/`·`/reel/`)·한글만은 오류. 같은 주소는 한 번(`UNIQUE(kind, handle)`, 이메일·계정명 소문자).
|
||||
- 리스트 추가 = 붙여넣기(한 줄에 한 사람 `주소, 이름` — 쉼표·탭·띄어쓰기, 순서는 어느 쪽이든, `store.parse_line`) → [미리보기](메일/DM/오류·중복·이미 있음) → [리스트에 추가].
|
||||
- **본문 `{이름}`** = 그 줄 이름(제목에도). 이름이 빈 줄은 보내지 않고 실패('이름 없음'), 화면에 "이름 필요" 표시. `**굵게**` = 메일 굵은 글씨(DM 은 별표만 뺌), 주소 = 메일 링크.
|
||||
- **본문 `{이름}`** = 그 줄 이름(제목에도). 이름이 빈 줄은 보내지 않고 실패('이름 없음'), 화면에 "이름 필요" 표시.
|
||||
- **메일 본문 = HTML**(설정 편집기, `fmt: "html"`) — 저장·읽을 때마다 `store.sanitize_html`(허용 태그 p·br·strong·em·u·s·span·a·ul·ol·li 등,
|
||||
style 은 color·background-color·font-size·font-weight·font-style·text-decoration·text-align 만, 링크는 http(s)/mailto, ` ` → 띄어쓰기, 빈 문단 = `<br>`).
|
||||
예전 글·기본 문구(`fmt` 없음) = `text_to_html`(줄마다 문단, `**굵게**`, 주소 링크). 메일 글 버전·DM 대체 글·{이름} 찾기 = `html_to_text`.
|
||||
`{이름}` 은 글자마다 서식이 달라도 `fill_html` 이 바꾼다. 메일 HTML 은 `<p>` 에 margin:0(메일 프로그램 문단 여백 없앰).
|
||||
- **메일** = [고른 메일 보내기] → `db.claim_for_send`(고른 줄 중 메일·대기/실패만 '발송중'으로 한 UPDATE — 두 번 눌러도·두 사람이 눌러도 한 번) →
|
||||
`send.send_batch`(백그라운드, **보내는 사람 본인 Gmail**, 한 사람에 한 통·1초 간격, 설정 사진 = 본문 아래 cid) → 보냄/실패 + `outreach_logs`.
|
||||
Gmail 연결 없으면 409(화면이 [Gmail 연결] 안내), 끊기면 남은 줄 실패. 서버 재시작 때 남은 '발송중' = 실패(`release_stuck`).
|
||||
- **인스타 DM = 반자동** — 인스타 공식 API 는 처음 연락하는 사람에게 DM 을 보낼 수 없다(상대가 먼저 보낸 24시간 안만, 자동 DM 은 약관 위반·계정 정지 위험).
|
||||
[DM 보내기] = 그 사람 이름이 든 문구 복사 + `https://ig.me/m/계정` 새 탭(누르는 순간 — 문구는 리스트 데이터에 미리 담음) → 붙여 넣어 보낸 뒤 [보냄](`dm-sent`, 기록).
|
||||
- **설정** `/outreach/settings`(모듈 권한자 누구나): 메일 제목·본문(기본 = 미라네주방 공동구매 제안 문구, `store.DEFAULT_TEMPLATE`)·보내는 이름·끝 문구(수신 거부 안내 등)·
|
||||
제목 앞 "(광고)" — 영리 목적 광고성 메일은 정보통신망법 제50조(제목 "(광고)"·수신 거부 방법) 대상일 수 있어 칸을 둠(법무 확인 권장).
|
||||
본문 아래 사진 최대 10장(서버가 가로 700px JPEG 로 줄여 `outreach_images` 에, 순서 ◀▶). [기본 문구로 되돌리기] = 칸만(저장해야 적용).
|
||||
**DM 문구** = 설정 `dm_body`(글, `store.dm_text`, 최대 1000자 `DM_MAX`, `{이름}`, 별표만 뺌) — 비어 있으면 메일 본문 글 + 끝 문구. "이름 필요"도 구분별(`needs_name(t, kind)`).
|
||||
- **탭**(2026-10-30, `templates/outreach/_tabs.html`) — [발송 리스트](`/outreach/`) [DM 수동 보내기](`/outreach/dm`) + 맨 오른쪽 설정 톱니.
|
||||
- **DM 수동 보내기 탭** `/outreach/dm`(`dm.html`, JS `outreach.js initDm`) — 3단:
|
||||
왼쪽 = 이름 넣기(붙여 넣기·.txt/.csv 첫 칸, 머리글 "이름"·빈 줄·이미 있는 이름 뺌, 넣을 때마다 목록에 더함) + 이름 목록(× 한 명씩·[전체 삭제], 브라우저만 — 저장 안 함),
|
||||
가운데 = 본문(`contenteditable="plaintext-only"`, 바로 고침, `{이름}` 자리 = 분홍 칩 — 직접 `{이름}` 이라 써도 됨), 오른쪽 = 저장한 본문 목록
|
||||
(맨 위 "설정 DM 문구(기본)" = `dm_template` = `store.dm_text(template, NAME_TAG)`, 그 아래 저장한 것 — 누르면 불러옴(고친 글 있으면 확인)·× 하나씩 지우기).
|
||||
이름을 누르면 칩이 그 이름으로 바뀌고 고친 글 + 이름을 바로 클립보드 복사 + 짧은 안내(1.6초). 글자 수 = 이름 넣은 글 기준, 1000자(`DM_MAX`) 넘으면 빨강.
|
||||
**저장한 본문** = outreach_db 마이그레이션 002 `outreach_dm_bodies`(모듈 권한자 모두 같은 목록, 제목 = 첫 글 줄 40자 `store.dm_saved_body`, 1000자까지):
|
||||
`POST /outreach/api/dm-bodies`(새 본문으로 저장)·`PUT …/{id}`(고른 본문 [저장])·`DELETE …/{id}` — 모두 `{items}` 돌려줌. 002 미적용이면 목록 안내만, API 503.
|
||||
- 설정 = 탭 줄 맨 오른쪽 톱니(`.otr-gear`, 공용 `vendor/material-symbols`). `.otr .erp-card[hidden]` — 공용 `.erp-card` display:flex 가 hidden 을 덮어
|
||||
[리스트 추가] 창이 늘 열려 있던 것 고침(2026-10-30).
|
||||
- **설정** `/outreach/settings`(모듈 권한자 누구나) — **세로 2단**: 왼쪽 메일(제목·"(광고)"·보내는 이름·본문 서식 편집기·끝 문구·본문 아래 사진),
|
||||
오른쪽 인스타 DM(서식 없는 편집기·글자 수·[메일 본문 글 가져오기]), 위 막대 [저장]·[기본 문구로 되돌리기](칸만, 저장해야 적용) — 1100px 아래는 위아래.
|
||||
입력 칸은 `form="otr-set-form"` 으로 위 막대 폼에 묶음(사진 폼과 겹치지 않게). 편집기 = Quill snow(글자 크기 px·굵게·기울임·밑줄·취소선·글자/배경 색·정렬·목록·링크·서식 지우기·되돌리기),
|
||||
저장 = `getSemanticHTML()` → `body`(fmt=html), DM `getText()` → `dm_body`. **`{이름}` 빨강 굵게 = 화면에서만**(class `otr-nametag-on`, 서버 정리 때 class 가 빠져 메일에는 안 남음).
|
||||
기본 본문 = 미라네주방 공동구매 제안 문구(`store.DEFAULT_TEMPLATE`, 글). "(광고)" — 영리 목적 광고성 메일은 정보통신망법 제50조 대상일 수 있어 칸을 둠(법무 확인 권장).
|
||||
본문 아래 사진 최대 10장(서버가 가로 700px JPEG 로 줄여 `outreach_images` 에, 순서 ◀▶).
|
||||
- 리스트 줄: 이름 바로 고치기(칸 떠나면 저장), [미리보기](메일 = 제목·HTML, DM = 글), 고른 줄 다시 대기·지우기(발송중은 못 지움), 걸러 보기(전체·메일·DM·대기·보냄·실패).
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from psycopg.errors import UndefinedTable
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
from psycopg_pool import ConnectionPool
|
||||
@@ -48,8 +49,10 @@ class OutreachDBStore:
|
||||
t = store.normalize_template(value)
|
||||
if not t["subject"]:
|
||||
raise ValueError("메일 제목을 쓰세요.")
|
||||
if not t["body"].strip():
|
||||
if not store.html_to_text(t["body"]).strip():
|
||||
raise ValueError("본문을 쓰세요.")
|
||||
if len(t["body"]) > store.BODY_MAX:
|
||||
raise ValueError("본문이 너무 깁니다(서식 포함) — 줄여 주세요.")
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO outreach_settings (key, value, updated_by, updated_at) VALUES ('template', %s, %s, now()) "
|
||||
@@ -209,6 +212,36 @@ class OutreachDBStore:
|
||||
"WHERE status = '발송중'")
|
||||
return cur.rowcount
|
||||
|
||||
# ── DM 수동 보내기 탭의 저장한 본문(마이그레이션 002) ──────────
|
||||
def list_dm_bodies(self) -> list[dict[str, Any]] | None:
|
||||
"""새로 고친 것부터. 표가 없으면(002 미적용) None — 화면이 저장 목록만 숨긴다."""
|
||||
try:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute("SELECT id, title, body, created_by, updated_by, updated_at FROM outreach_dm_bodies "
|
||||
"ORDER BY updated_at DESC, id DESC").fetchall()
|
||||
except UndefinedTable:
|
||||
return None
|
||||
return [{**dict(r), "id": int(r["id"]), "updated_at": _iso(r["updated_at"])} for r in rows]
|
||||
|
||||
def save_dm_body(self, body: Any, *, by: str, body_id: int | None = None) -> int:
|
||||
"""새로 저장(body_id 없음) 또는 그 본문 고치기. 저장한 id. 없는 id = KeyError."""
|
||||
title, text = store.dm_saved_body(body)
|
||||
by = (by or "").lower()
|
||||
with self._pool.connection() as conn:
|
||||
if body_id is None:
|
||||
return int(conn.execute(
|
||||
"INSERT INTO outreach_dm_bodies (title, body, created_by, updated_by) VALUES (%s, %s, %s, %s) RETURNING id",
|
||||
(title, text, by, by)).fetchone()["id"])
|
||||
row = conn.execute("UPDATE outreach_dm_bodies SET title = %s, body = %s, updated_by = %s, updated_at = now() "
|
||||
"WHERE id = %s RETURNING id", (title, text, by, body_id)).fetchone()
|
||||
if row is None:
|
||||
raise KeyError(body_id)
|
||||
return int(row["id"])
|
||||
|
||||
def delete_dm_body(self, body_id: int) -> None:
|
||||
with self._pool.connection() as conn:
|
||||
conn.execute("DELETE FROM outreach_dm_bodies WHERE id = %s", (body_id,))
|
||||
|
||||
def list_logs(self, *, limit: int = 200) -> list[dict[str, Any]]:
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute("SELECT * FROM outreach_logs ORDER BY sent_at DESC, id DESC LIMIT %s", (limit,)).fetchall()
|
||||
|
||||
@@ -63,15 +63,12 @@ def _db(request: Request) -> Any:
|
||||
|
||||
def _page(request: Request) -> Any:
|
||||
"""화면 공통 — (st, user) 또는 응답(로그인·권한·설정 필요)."""
|
||||
from urllib.parse import quote # noqa: WPS433
|
||||
|
||||
from app.main import build_erp_nav, get_current_user_record, render_template # noqa: WPS433
|
||||
from app.store import has_module, is_admin # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
here = str(request.url.path) + ("?" + request.url.query if request.url.query else "")
|
||||
return RedirectResponse(url="/login?next=" + quote(here, safe=""), status_code=303)
|
||||
return login_redirect(request)
|
||||
if not has_module(user, "outreach"):
|
||||
return render_template(request, "denied.html", {"reason": "안내문 발송 모듈 접근 권한이 없습니다.",
|
||||
"is_admin": is_admin(user)}, status_code=403)
|
||||
@@ -110,11 +107,11 @@ def _view(r: dict[str, Any], template: dict[str, Any]) -> dict[str, Any]:
|
||||
out = {k: r.get(k) for k in ("id", "kind", "handle", "address", "name", "memo", "status", "sent_at", "sent_by", "sent_via",
|
||||
"last_error")}
|
||||
out["kind_label"] = store.KIND_LABELS.get(r["kind"], "")
|
||||
out["needs_name"] = store.needs_name(template) and not (r.get("name") or "").strip()
|
||||
out["needs_name"] = store.needs_name(template, r["kind"]) and not (r.get("name") or "").strip()
|
||||
if r["kind"] == "instagram":
|
||||
out["dm_link"] = store.dm_link(r["handle"])
|
||||
out["profile_link"] = store.profile_link(r["handle"])
|
||||
out["dm_text"] = store.plain_text(template, r.get("name") or "")
|
||||
out["dm_text"] = store.dm_text(template, r.get("name") or "")
|
||||
return out
|
||||
|
||||
|
||||
@@ -136,11 +133,71 @@ def index(request: Request) -> Any:
|
||||
rows = [_view(r, template) for r in st.list_recipients()]
|
||||
return _render(request, "outreach/index.html", user, {
|
||||
"page_title": "안내문 발송", "page_subtitle": "메일 일괄 발송 · 인스타 DM",
|
||||
"template": template, "images": st.list_images(), "rows": rows, "logs": st.list_logs(limit=50),
|
||||
"template": template, "body_text": store.html_to_text(template["body"]), "needs_name": store.needs_name(template),
|
||||
"images": st.list_images(), "rows": rows, "logs": st.list_logs(limit=50), "active_tab": "list",
|
||||
"gmail": _gmail_state(request, user), "msg": request.query_params.get("msg", ""),
|
||||
})
|
||||
|
||||
|
||||
@router.get("/dm", response_class=HTMLResponse)
|
||||
def dm_page(request: Request) -> Any:
|
||||
"""DM 수동 보내기 탭(2026-10-30) — 이름 목록 | 고칠 수 있는 본문(화면이 {이름} 을 바꿔 복사) | 저장한 본문 목록."""
|
||||
got = _page(request)
|
||||
if not isinstance(got, tuple):
|
||||
return got
|
||||
st, user = got
|
||||
return _render(request, "outreach/dm.html", user, {
|
||||
"page_title": "안내문 발송", "page_subtitle": "DM 수동 보내기", "active_tab": "dm",
|
||||
# {이름} 을 그대로 둔 DM 문구(리스트 줄 [DM 보내기]와 같은 글) + 저장한 본문 목록(002 미적용 = None)
|
||||
"dm_template": store.dm_text(st.get_template(), store.NAME_TAG),
|
||||
"dm_bodies": st.list_dm_bodies(), "dm_max": store.DM_MAX,
|
||||
})
|
||||
|
||||
|
||||
_DM_BODIES_MIGRATION_MSG = "본문 저장 표가 없습니다 — outreach_db 마이그레이션 002(scripts/sql/outreach_db_002_dm_bodies.sql)를 적용하세요."
|
||||
|
||||
|
||||
def _dm_body_save(request: Request, payload: dict[str, Any], body_id: int | None) -> JSONResponse:
|
||||
from psycopg.errors import UndefinedTable # noqa: WPS433
|
||||
|
||||
user = _user(request)
|
||||
st = _db(request)
|
||||
try:
|
||||
saved = st.save_dm_body(payload.get("body"), by=user.get("email", ""), body_id=body_id)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
except KeyError:
|
||||
raise HTTPException(status_code=404, detail="저장한 본문이 없습니다(다른 사람이 지웠을 수 있음).")
|
||||
except UndefinedTable:
|
||||
raise HTTPException(status_code=503, detail=_DM_BODIES_MIGRATION_MSG)
|
||||
return JSONResponse({"id": saved, "items": st.list_dm_bodies() or []})
|
||||
|
||||
|
||||
@router.post("/api/dm-bodies")
|
||||
def api_dm_body_add(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""DM 수동 보내기 — 본문 새로 저장(제목 = 첫 줄)."""
|
||||
return _dm_body_save(request, payload, None)
|
||||
|
||||
|
||||
@router.put("/api/dm-bodies/{body_id:int}")
|
||||
def api_dm_body_update(request: Request, body_id: int, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""DM 수동 보내기 — 고른 저장 본문 고치기."""
|
||||
return _dm_body_save(request, payload, body_id)
|
||||
|
||||
|
||||
@router.delete("/api/dm-bodies/{body_id:int}")
|
||||
def api_dm_body_delete(request: Request, body_id: int) -> JSONResponse:
|
||||
from psycopg.errors import UndefinedTable # noqa: WPS433
|
||||
|
||||
_user(request)
|
||||
st = _db(request)
|
||||
try:
|
||||
st.delete_dm_body(body_id)
|
||||
except UndefinedTable:
|
||||
raise HTTPException(status_code=503, detail=_DM_BODIES_MIGRATION_MSG)
|
||||
return JSONResponse({"items": st.list_dm_bodies() or []})
|
||||
|
||||
|
||||
@router.get("/settings", response_class=HTMLResponse)
|
||||
def settings_page(request: Request) -> Any:
|
||||
got = _page(request)
|
||||
@@ -148,20 +205,23 @@ def settings_page(request: Request) -> Any:
|
||||
return got
|
||||
st, user = got
|
||||
return _render(request, "outreach/settings.html", user, {
|
||||
"page_title": "안내문 발송 — 설정", "page_subtitle": "메일 제목 · 본문 · 사진",
|
||||
"template": st.get_template(), "default": store.DEFAULT_TEMPLATE, "images": st.list_images(),
|
||||
"max_images": 10, "msg": request.query_params.get("msg", ""),
|
||||
"page_title": "안내문 발송 — 설정", "page_subtitle": "메일 제목 · 본문 · DM 문구 · 사진",
|
||||
"template": st.get_template(), "default": store.normalize_template(None), "images": st.list_images(),
|
||||
"max_images": 10, "dm_max": store.DM_MAX, "msg": request.query_params.get("msg", ""),
|
||||
})
|
||||
|
||||
|
||||
@router.post("/settings")
|
||||
def settings_save(request: Request, subject: str = Form(""), body: str = Form(""), sender_name: str = Form(""),
|
||||
footer: str = Form(""), ad_label: str = Form("")) -> RedirectResponse:
|
||||
footer: str = Form(""), ad_label: str = Form(""), dm_body: str = Form(""),
|
||||
fmt: str = Form("text")) -> RedirectResponse:
|
||||
"""body = 설정 화면 편집기 HTML(fmt=html, 서버가 다시 정리) — fmt 없이 오면 글로 본다."""
|
||||
user = _user(request)
|
||||
st = _db(request)
|
||||
try:
|
||||
st.save_template({"subject": subject, "body": body, "sender_name": sender_name, "footer": footer,
|
||||
"ad_label": ad_label in ("1", "on", "true")}, by=user["email"])
|
||||
st.save_template({"subject": subject, "body": body, "sender_name": sender_name, "footer": footer, "dm_body": dm_body,
|
||||
"ad_label": ad_label in ("1", "on", "true"), "fmt": "html" if fmt == "html" else "text"},
|
||||
by=user["email"])
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
return RedirectResponse(url="/outreach/settings?" + urlencode({"msg": "설정을 저장했습니다."}), status_code=303)
|
||||
@@ -303,7 +363,8 @@ def api_preview(request: Request, rid: int) -> JSONResponse:
|
||||
html = store.html_body(t, r["name"], [f"img-{im['id']}" for im in st.list_images()])
|
||||
for im in st.list_images():
|
||||
html = html.replace(f"cid:img-{im['id']}", f"/outreach/images/{im['id']}")
|
||||
return JSONResponse({"subject": store.subject_for(t, r["name"]), "html": html, "text": store.plain_text(t, r["name"]),
|
||||
return JSONResponse({"subject": store.subject_for(t, r["name"]), "html": html,
|
||||
"text": store.dm_text(t, r["name"]) if r["kind"] == "instagram" else store.plain_text(t, r["name"]),
|
||||
"kind": r["kind"], "to": r["handle"], "sender_name": t["sender_name"]})
|
||||
|
||||
|
||||
|
||||
+185
-15
@@ -1,13 +1,16 @@
|
||||
"""안내문 발송 — 순수 함수(DB 없음): 주소 판별(이메일 / 인스타그램), 리스트 붙여넣기 해석, {이름} 바꾸기, 메일 HTML·DM 글.
|
||||
|
||||
- 주소를 보고 정한다: `name@domain.tld` = 메일, `@계정`·`instagram.com/계정`·`ig.me/m/계정`·계정명만(영문·숫자·.·_) = 인스타 DM.
|
||||
- 본문 `{이름}` = 그 줄 이름. `**굵게**` 는 메일에서 굵은 글씨, DM 에서는 별표만 뺀다(인스타는 서식이 없음). 주소(https://…)는 메일에서 링크.
|
||||
- 본문 `{이름}` = 그 줄 이름. 메일 본문 = 설정 화면 편집기의 HTML(`fmt: "html"`) — 저장·읽을 때마다 `sanitize_html`(허용 태그·스타일만).
|
||||
예전 글·기본 문구(`fmt` 없음 = 글)는 `text_to_html`(`**굵게**` → 굵게, 주소 → 링크, 줄마다 문단).
|
||||
- DM 글 = 설정 `dm_body`(인스타 DM 용 글, 서식 없음). 비어 있으면 메일 본문 글 + 끝 문구.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from html import escape
|
||||
from html.parser import HTMLParser
|
||||
from typing import Any
|
||||
|
||||
NAME_TAG = "{이름}"
|
||||
@@ -27,6 +30,8 @@ DEFAULT_TEMPLATE: dict[str, Any] = {
|
||||
"sender_name": "미라네주방",
|
||||
"ad_label": False,
|
||||
"footer": "",
|
||||
"dm_body": "",
|
||||
"fmt": "text", # body 형식 — 기본 문구는 글, 설정 화면에서 저장하면 "html"
|
||||
"body": """안녕하세요, {이름}님.
|
||||
주방의 본질을 지키며 6년간 묵묵히 300억 매출의 신화를 써온 **'미라네주방'**입니다.
|
||||
저희는 지난 6년간 제품력 하나로 국내/해외 800만 개 판매를 돌파하고 호주, 동남아 등 글로벌 시장에서 인정받았습니다.
|
||||
@@ -60,7 +65,8 @@ DEFAULT_TEMPLATE: dict[str, Any] = {
|
||||
미라네주방 팀 드림
|
||||
https://miras.co.kr/""",
|
||||
}
|
||||
SUBJECT_MAX, BODY_MAX, FOOTER_MAX = 200, 20000, 2000
|
||||
SUBJECT_MAX, BODY_MAX, FOOTER_MAX = 200, 100000, 2000 # BODY_MAX = 정리한 HTML 길이
|
||||
DM_MAX = 1000 # 인스타 DM 한 통 글자 수 한도
|
||||
|
||||
|
||||
def _ig_user(value: str) -> str | None:
|
||||
@@ -145,15 +151,24 @@ def normalize_template(value: dict[str, Any] | None) -> dict[str, Any]:
|
||||
if k in v:
|
||||
v[k] = val
|
||||
v["subject"] = str(v["subject"] or "").strip()[:SUBJECT_MAX]
|
||||
v["body"] = str(v["body"] or "").replace("\r\n", "\n")[:BODY_MAX]
|
||||
body = str(v["body"] or "")[:BODY_MAX * 3]
|
||||
v["body"] = sanitize_html(body if v["fmt"] == "html" else text_to_html(body))
|
||||
v["fmt"] = "html"
|
||||
v["footer"] = str(v["footer"] or "").replace("\r\n", "\n").strip()[:FOOTER_MAX]
|
||||
v["dm_body"] = str(v["dm_body"] or "").replace("\r\n", "\n").strip()[:DM_MAX]
|
||||
v["sender_name"] = str(v["sender_name"] or "").strip()[:60]
|
||||
v["ad_label"] = bool(v["ad_label"])
|
||||
return v
|
||||
|
||||
|
||||
def needs_name(template: dict[str, Any]) -> bool:
|
||||
return NAME_TAG in (template.get("subject") or "") or NAME_TAG in (template.get("body") or "")
|
||||
def needs_name(template: dict[str, Any], kind: str = "email") -> bool:
|
||||
"""그 구분(메일/DM)으로 갈 글에 {이름}이 있는가 — DM 은 DM 문구(없으면 메일 본문)만 본다."""
|
||||
if kind == "instagram" and (template.get("dm_body") or "").strip():
|
||||
return NAME_TAG in template["dm_body"]
|
||||
body = html_to_text(template.get("body") or "")
|
||||
if kind == "instagram":
|
||||
return NAME_TAG in body or NAME_TAG in (template.get("footer") or "")
|
||||
return NAME_TAG in (template.get("subject") or "") or NAME_TAG in body
|
||||
|
||||
|
||||
def fill(text: str, name: str) -> str:
|
||||
@@ -165,29 +180,184 @@ def subject_for(template: dict[str, Any], name: str) -> str:
|
||||
return ("(광고) " + s) if template.get("ad_label") and not s.startswith("(광고)") else s
|
||||
|
||||
|
||||
def _body_text(template: dict[str, Any], name: str) -> str:
|
||||
body = fill(template.get("body") or "", name).rstrip()
|
||||
def plain_text(template: dict[str, Any], name: str) -> str:
|
||||
"""메일 글 부분(HTML 메일의 글 버전)·DM 문구가 없을 때의 DM 글 — 본문 글 + 끝 문구."""
|
||||
body = fill(html_to_text(template.get("body") or ""), name).rstrip()
|
||||
footer = (template.get("footer") or "").strip()
|
||||
return body + ("\n\n" + fill(footer, name) if footer else "")
|
||||
|
||||
|
||||
def plain_text(template: dict[str, Any], name: str) -> str:
|
||||
"""메일 글 부분·DM 글 — **굵게** 표시는 별표만 뺀다."""
|
||||
return re.sub(r"\*\*(.+?)\*\*", r"\1", _body_text(template, name))
|
||||
def dm_text(template: dict[str, Any], name: str) -> str:
|
||||
"""인스타 DM 글 — DM 문구가 있으면 그것, 없으면 메일 글(plain_text). **굵게** 는 별표만 뺀다."""
|
||||
dm = (template.get("dm_body") or "").strip()
|
||||
if not dm:
|
||||
return plain_text(template, name)
|
||||
return re.sub(r"\*\*(.+?)\*\*", r"\1", fill(dm, name))
|
||||
|
||||
|
||||
def dm_saved_body(value: Any) -> tuple[str, str]:
|
||||
"""DM 수동 보내기 탭에 저장할 본문 → (제목, 본문). 제목 = 첫 글 줄 40자(목록 표시용). 비었거나 너무 길면 ValueError."""
|
||||
body = str(value or "").replace("\r\n", "\n").strip()
|
||||
if not body:
|
||||
raise ValueError("본문을 쓰세요.")
|
||||
if len(body) > DM_MAX:
|
||||
raise ValueError(f"본문은 {DM_MAX}자까지입니다(인스타 DM 한도) — 지금 {len(body)}자.")
|
||||
title = next((ln.strip() for ln in body.split("\n") if ln.strip()), "")
|
||||
return (title[:40] + ("…" if len(title) > 40 else "")), body
|
||||
|
||||
|
||||
# ── 메일 본문 HTML ─────────────────────────────────────────
|
||||
_URL_RE = re.compile(r"https?://[^\s<>\"']+")
|
||||
_ALLOWED_TAGS = {"p", "br", "strong", "b", "em", "i", "u", "s", "strike", "span", "a", "ul", "ol", "li",
|
||||
"h1", "h2", "h3", "blockquote", "sub", "sup"}
|
||||
_DROP_WITH_CONTENT = {"script", "style", "iframe", "object", "head", "title", "template", "noscript", "svg", "math",
|
||||
"textarea", "select"}
|
||||
_STYLE_PROPS = {"color", "background-color", "font-size", "font-weight", "font-style", "text-decoration", "text-align"}
|
||||
_STYLE_VALUE_RE = re.compile(r"^[#\w\s.,%()-]{1,60}$")
|
||||
# {이름} — 편집기에서 글자마다 서식이 달라 태그가 끼어도 찾는다(태그는 남기고 글자만 이름으로)
|
||||
_NAME_IN_HTML_RE = re.compile(r"\{((?:<[^>]*>)*)이((?:<[^>]*>)*)름((?:<[^>]*>)*)\}")
|
||||
|
||||
|
||||
def _clean_style(value: str) -> str:
|
||||
out = []
|
||||
for decl in value.split(";"):
|
||||
prop, _, val = decl.partition(":")
|
||||
prop, val = prop.strip().lower(), val.strip()
|
||||
if prop in _STYLE_PROPS and _STYLE_VALUE_RE.match(val) and not re.search(r"url|expression", val, re.I):
|
||||
out.append(f"{prop}: {val}")
|
||||
return "; ".join(out)
|
||||
|
||||
|
||||
class _Sanitizer(HTMLParser):
|
||||
"""허용 태그·속성(style 은 글자 서식만, a 는 http(s)/mailto 링크만)만 남기고 글은 escape. 태그 짝은 맞춰 닫는다.
|
||||
편집기(Quill getSemanticHTML)가 띄어쓰기를 로 내보내 보통 띄어쓰기로 바꾼다(메일은 pre-wrap 이라 여러 칸도 그대로)."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.out: list[str] = []
|
||||
self.stack: list[str] = []
|
||||
self.skip = 0
|
||||
self.empty_p = False # 지금 연 <p> 에 아직 글이 없다 — 닫을 때 <br> 을 넣어 빈 줄 높이를 지킨다
|
||||
|
||||
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||
if tag in _DROP_WITH_CONTENT:
|
||||
self.skip += 1
|
||||
return
|
||||
if self.skip or tag not in _ALLOWED_TAGS:
|
||||
return
|
||||
if tag == "br":
|
||||
self.out.append("<br>")
|
||||
self.empty_p = False
|
||||
return
|
||||
a = {k: v or "" for k, v in attrs}
|
||||
extra = ""
|
||||
style = _clean_style(a.get("style", ""))
|
||||
if style:
|
||||
extra += f' style="{escape(style)}"'
|
||||
href = a.get("href", "").strip()
|
||||
if tag == "a" and re.match(r"^(https?:|mailto:)", href, re.I):
|
||||
extra += f' href="{escape(href)}"'
|
||||
self.out.append(f"<{tag}{extra}>")
|
||||
self.stack.append(tag)
|
||||
if tag == "p":
|
||||
self.empty_p = True
|
||||
|
||||
def handle_endtag(self, tag: str) -> None:
|
||||
if tag in _DROP_WITH_CONTENT:
|
||||
self.skip = max(0, self.skip - 1)
|
||||
return
|
||||
if self.skip or tag not in self.stack:
|
||||
return
|
||||
while self.stack:
|
||||
t = self.stack.pop()
|
||||
if t == "p" and self.empty_p:
|
||||
self.out.append("<br>")
|
||||
self.empty_p = False
|
||||
self.out.append(f"</{t}>")
|
||||
if t == tag:
|
||||
break
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
if self.skip:
|
||||
return
|
||||
text = data.replace("\r", "").replace("\n", " ").replace("\xa0", " ")
|
||||
if not text.strip() and (not self.stack or self.stack[-1] in ("ul", "ol")):
|
||||
return
|
||||
if text:
|
||||
self.out.append(escape(text, quote=False))
|
||||
self.empty_p = False
|
||||
|
||||
def result(self) -> str:
|
||||
self.close()
|
||||
while self.stack:
|
||||
self.handle_endtag(self.stack[-1])
|
||||
return "".join(self.out)
|
||||
|
||||
|
||||
def sanitize_html(html: str) -> str:
|
||||
p = _Sanitizer()
|
||||
p.feed(str(html or ""))
|
||||
return p.result()
|
||||
|
||||
|
||||
def text_to_html(text: str) -> str:
|
||||
"""글(예전 본문·기본 문구) → 본문 HTML — 줄마다 문단, 빈 줄 = <p><br></p>, **굵게** → <strong>, 주소 → 링크."""
|
||||
out = []
|
||||
for line in str(text or "").replace("\r\n", "\n").rstrip("\n").split("\n"):
|
||||
h = re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", escape(line, quote=False))
|
||||
h = _URL_RE.sub(lambda m: f'<a href="{m.group(0)}">{m.group(0)}</a>', h)
|
||||
out.append(f"<p>{h or '<br>'}</p>")
|
||||
return "".join(out)
|
||||
|
||||
|
||||
class _Text(HTMLParser):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.parts: list[str] = []
|
||||
|
||||
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||
if tag == "br":
|
||||
self.parts.append("\x00") # 문단 끝 바로 앞의 <br>(빈 줄 표시)은 줄을 하나 더 만들지 않는다
|
||||
elif tag == "li":
|
||||
self.parts.append("- ")
|
||||
|
||||
def handle_endtag(self, tag: str) -> None:
|
||||
if tag in ("p", "li", "h1", "h2", "h3", "blockquote"):
|
||||
if self.parts and self.parts[-1] == "\x00":
|
||||
self.parts.pop()
|
||||
self.parts.append("\n")
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
self.parts.append(data.replace("\xa0", " "))
|
||||
|
||||
|
||||
def html_to_text(html: str) -> str:
|
||||
"""본문 HTML → 글(메일 글 버전·DM·{이름} 찾기·리스트 화면 요약)."""
|
||||
p = _Text()
|
||||
p.feed(str(html or ""))
|
||||
p.close()
|
||||
return "".join(p.parts).replace("\x00", "\n").rstrip()
|
||||
|
||||
|
||||
def fill_html(html: str, name: str) -> str:
|
||||
return _NAME_IN_HTML_RE.sub(lambda m: escape(str(name or "").strip()) + m.group(1) + m.group(2) + m.group(3), str(html or ""))
|
||||
|
||||
|
||||
def _p_margin(html: str) -> str:
|
||||
"""메일 프로그램은 <p> 에 위아래 여백을 줘 편집기보다 줄 간격이 벌어진다 — margin:0 을 붙인다."""
|
||||
return re.sub(r'<p( style=")?', lambda m: '<p style="margin:0;' if m.group(1) else '<p style="margin:0"', html)
|
||||
|
||||
|
||||
def html_body(template: dict[str, Any], name: str, image_cids: list[str] | None = None) -> str:
|
||||
"""메일 HTML — 사용자 글은 늘 escape, **굵게** → <b>, 주소 → 링크, 줄바꿈 그대로, 사진은 본문 아래(cid)."""
|
||||
text = escape(_body_text(template, name))
|
||||
text = re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", text)
|
||||
text = _URL_RE.sub(lambda m: f'<a href="{m.group(0)}" style="color:#1a56db">{m.group(0)}</a>', text)
|
||||
"""메일 HTML — 본문(정리된 편집기 HTML, {이름} 바꿈) + 끝 문구(글 → escape·링크) + 사진은 본문 아래(cid)."""
|
||||
body = fill_html(sanitize_html(template.get("body") or ""), name)
|
||||
footer = (template.get("footer") or "").strip()
|
||||
if footer:
|
||||
body += "<p><br></p>" + text_to_html(fill(footer, name))
|
||||
imgs = "".join(f'<p style="margin:12px 0 0"><img src="cid:{c}" alt="" style="max-width:100%;height:auto;border-radius:6px"></p>'
|
||||
for c in (image_cids or []))
|
||||
return ('<div style="font-family:Pretendard,\'Malgun Gothic\',sans-serif;font-size:14px;line-height:1.7;color:#111;white-space:pre-wrap">'
|
||||
f"{text}</div>{imgs}")
|
||||
f"{_p_margin(body)}</div>{imgs}")
|
||||
|
||||
|
||||
def dm_link(handle: str) -> str:
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{#- 안내문 발송 탭(2026-10-30) — [발송 리스트] [DM 수동 보내기] + 맨 오른쪽 설정 톱니(실적·프로젝트와 같은 Material Symbols "settings") -#}
|
||||
<nav class="otr-tabs" aria-label="안내문 발송 메뉴">
|
||||
<div class="otr-tabs-main" role="tablist">
|
||||
<a class="otr-tab{% if active_tab == 'list' %} is-active{% endif %}" href="/outreach/" role="tab"
|
||||
aria-selected="{{ 'true' if active_tab == 'list' else 'false' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">forward_to_inbox</span>발송 리스트</a>
|
||||
<a class="otr-tab{% if active_tab == 'dm' %} is-active{% endif %}" href="/outreach/dm" role="tab"
|
||||
aria-selected="{{ 'true' if active_tab == 'dm' else 'false' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">chat</span>DM 수동 보내기</a>
|
||||
</div>
|
||||
<a class="otr-gear" href="/outreach/settings" title="설정" aria-label="설정">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">settings</span></a>
|
||||
</nav>
|
||||
@@ -0,0 +1,51 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{#- DM 수동 보내기 탭(2026-10-30) — 왼쪽 = 이름 넣기(붙여 넣기·.txt/.csv 첫 칸) + 이름 목록(한 명씩·전체 지우기),
|
||||
가운데 = 본문(고칠 수 있음, {이름} 자리는 분홍 이름 칩), 오른쪽 = 저장한 본문 목록(고르기·하나씩 지우기, outreach_db 002).
|
||||
이름을 누르면 본문의 {이름} 이 그 이름으로 바뀌고 바로 클립보드에 복사. 이름 목록은 저장하지 않음(브라우저만). -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<link rel="stylesheet" href="/static/outreach.css?v=20261030c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="otr otr-dm-page" id="otr-dm">
|
||||
{% include "outreach/_tabs.html" %}
|
||||
|
||||
<div class="otr-dm-split">
|
||||
<div class="erp-card otr-dm-left">
|
||||
<div class="otr-add-head"><b>이름</b>
|
||||
<span class="erp-muted">한 줄에 한 이름 — 붙여 넣거나 파일(.txt·.csv, 첫 칸)을 올리세요. 엑셀은 이름 칸을 복사해 붙여 넣으면 됩니다.</span></div>
|
||||
<textarea class="erp-input otr-add-text" id="otr-dm-text" rows="4" placeholder="김철수 미라네 이수진"></textarea>
|
||||
<div class="otr-add-actions">
|
||||
<button type="button" class="erp-btn erp-btn-primary" id="otr-dm-load">이름 넣기</button>
|
||||
<label class="erp-btn erp-btn-outline otr-dm-file">파일 올리기<input type="file" id="otr-dm-file" accept=".txt,.csv,text/plain,text/csv" hidden /></label>
|
||||
</div>
|
||||
<div class="otr-dm-listhead"><span class="erp-muted" id="otr-dm-sum">0명</span>
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm otr-danger" id="otr-dm-clear" disabled>전체 삭제</button></div>
|
||||
<ul class="otr-dm-names" id="otr-dm-names" aria-label="이름 목록"></ul>
|
||||
</div>
|
||||
|
||||
<div class="erp-card otr-dm-right">
|
||||
<div class="otr-add-head"><b>본문 <span class="otr-dm-cur" id="otr-dm-cur"></span></b>
|
||||
<span class="erp-muted">바로 고칠 수 있습니다. 분홍 글자 = <code>{이름}</code> 자리(왼쪽 이름을 누르면 바뀌고 복사됨, 새 자리는 <code>{이름}</code> 이라고 쓰면 됨).</span></div>
|
||||
<div class="otr-add-actions otr-dm-actions">
|
||||
<button type="button" class="erp-btn erp-btn-primary" id="otr-dm-save" disabled title="오른쪽 목록에서 고른 본문을 이 글로 바꿉니다">저장</button>
|
||||
<button type="button" class="erp-btn erp-btn-outline" id="otr-dm-saveas">새 본문으로 저장</button>
|
||||
<span class="erp-muted" id="otr-dm-count"></span>
|
||||
</div>
|
||||
<div class="otr-dm-body" id="otr-dm-body" contenteditable="plaintext-only" spellcheck="false" role="textbox" aria-multiline="true" aria-label="본문"></div>
|
||||
</div>
|
||||
|
||||
<div class="erp-card otr-dm-saved">
|
||||
<div class="otr-add-head"><b>저장한 본문</b><span class="erp-muted">누르면 가운데 본문으로 불러옵니다.</span></div>
|
||||
{% if dm_bodies is none %}
|
||||
<p class="otr-msg">본문 저장 표가 아직 없습니다 — 관리자가 outreach_db 마이그레이션 002(<code>scripts/sql/outreach_db_002_dm_bodies.sql</code>)를 적용하면 저장할 수 있습니다.</p>
|
||||
{% endif %}
|
||||
<ul class="otr-dm-names otr-dm-bodies" id="otr-dm-bodies" aria-label="저장한 본문 목록"></ul>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<script type="application/json" id="otr-data">{{ {"dm_template": dm_template, "dm_bodies": dm_bodies, "dm_max": dm_max} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/outreach.js?v=20261030c" defer></script>{% endblock %}
|
||||
@@ -2,15 +2,16 @@
|
||||
|
||||
{#- 안내문 발송(2026-10-27) — 리스트(주소 + 이름) → 메일은 [선택한 메일 보내기](본인 Gmail, 한 사람에 한 통), 인스타는 [DM 보내기](문구 복사 + DM 창)
|
||||
→ 보낸 뒤 [보냄]. 주소를 보고 메일/DM 을 정한다(store.detect). 본문 {이름} = 그 줄 이름. -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/outreach.css?v=20261027a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<link rel="stylesheet" href="/static/outreach.css?v=20261030c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="otr" id="otr" data-needs-name="{{ '1' if '{이름}' in (template.subject ~ template.body) else '' }}">
|
||||
<section class="otr" id="otr" data-needs-name="{{ '1' if needs_name else '' }}">
|
||||
{% include "outreach/_tabs.html" %}
|
||||
|
||||
<div class="otr-top">
|
||||
<div class="otr-top-main">
|
||||
<button type="button" class="erp-btn erp-btn-primary" id="otr-add-open">+ 리스트 추가</button>
|
||||
<a class="erp-btn erp-btn-outline" href="/outreach/settings">설정</a>
|
||||
</div>
|
||||
<div class="otr-gmail">
|
||||
{% if gmail.connected %}
|
||||
@@ -31,7 +32,7 @@
|
||||
<div class="erp-card otr-tpl">
|
||||
<div class="otr-tpl-head"><b>보낼 내용</b><span class="erp-muted">(설정에서 바꿉니다)</span></div>
|
||||
<div class="otr-tpl-subject">{% if template.ad_label %}(광고) {% endif %}{{ template.subject }}</div>
|
||||
<div class="otr-tpl-body">{{ template.body[:160] }}{% if template.body | length > 160 %}…{% endif %}</div>
|
||||
<div class="otr-tpl-body">{{ body_text[:160] }}{% if body_text | length > 160 %}…{% endif %}</div>
|
||||
<div class="erp-muted otr-tpl-meta">보내는 이름 {{ template.sender_name or '—' }} · 본문 아래 사진 {{ images | length }}장 · <code>{이름}</code> = 줄마다 그 사람 이름</div>
|
||||
</div>
|
||||
|
||||
@@ -99,4 +100,4 @@
|
||||
<script type="application/json" id="otr-data">{{ {"rows": rows} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/outreach.js?v=20261027a" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/outreach.js?v=20261030c" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,59 +1,93 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{#- 안내문 발송 설정(2026-10-27) — 메일 제목·본문({이름})·보내는 이름·끝 문구·(광고) 표시 + 본문 아래 사진. 메일·DM 모두 이 내용. -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/outreach.css?v=20261027a" />{% endblock %}
|
||||
{#- 안내문 발송 설정(2026-10-27) — 화면 세로 2단: 왼쪽 = 메일(제목·(광고)·보내는 이름·본문 서식 편집기·끝 문구·본문 아래 사진),
|
||||
오른쪽 = 인스타 DM(서식 없는 편집기, 비우면 메일 본문 글 + 끝 문구). 두 편집기 모두 {이름} = 빨강 굵게(화면에서만).
|
||||
편집기 = Quill(/static/vendor/quill). 입력 칸은 form="otr-set-form" 으로 위 막대의 저장 폼에 묶는다(사진 폼과 겹치지 않게). -#}
|
||||
{% block head_extra %}
|
||||
<link rel="stylesheet" href="/static/vendor/quill/quill.snow.css" />
|
||||
<link rel="stylesheet" href="/static/outreach.css?v=20261030c" />
|
||||
{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="otr otr-settings">
|
||||
<div class="otr-top"><div class="otr-top-main"><a class="erp-btn erp-btn-outline" href="/outreach/">◀ 리스트</a></div></div>
|
||||
<form method="post" action="/outreach/settings" id="otr-set-form" class="otr-set-bar">
|
||||
<a class="erp-btn erp-btn-outline" href="/outreach/">◀ 리스트</a>
|
||||
<span class="erp-muted otr-set-saved">{% if template.is_default %}기본 문구(아직 저장 안 함){% else %}마지막 저장 {{ template.updated_by }} · {{ template.updated_at[:16] | replace('T', ' ') }}{% endif %}</span>
|
||||
<span class="otr-set-bar-gap"></span>
|
||||
<input type="hidden" name="fmt" value="html" />
|
||||
<input type="hidden" name="body" id="otr-body-input" />
|
||||
<input type="hidden" name="dm_body" id="otr-dm-input" />
|
||||
<button type="button" class="erp-btn erp-btn-outline" id="otr-default" title="칸만 바꿉니다 — [저장]을 눌러야 적용">기본 문구로 되돌리기</button>
|
||||
<button type="submit" class="erp-btn erp-btn-primary">저장</button>
|
||||
</form>
|
||||
{% if msg %}<p class="otr-msg" role="status">{{ msg }}</p>{% endif %}
|
||||
|
||||
<form method="post" action="/outreach/settings" class="erp-card otr-set-card" id="otr-set-form">
|
||||
<div class="otr-tpl-head"><b>메일 제목 · 본문</b>
|
||||
<span class="erp-muted">{% if template.is_default %}기본 문구(아직 저장 안 함){% else %}마지막 저장 {{ template.updated_by }} · {{ template.updated_at[:16] | replace('T', ' ') }}{% endif %}</span></div>
|
||||
<label class="erp-field otr-field"><span>메일 제목</span>
|
||||
<input class="erp-input" type="text" name="subject" maxlength="200" required value="{{ template.subject }}" /></label>
|
||||
<label class="otr-check"><input type="checkbox" name="ad_label" value="1"{% if template.ad_label %} checked{% endif %} />
|
||||
제목 앞에 <b>(광고)</b> 붙이기 <span class="erp-muted">— 영리 목적 광고성 메일은 정보통신망법 제50조에 따라 제목 앞 "(광고)"·수신 거부 방법을 적어야 합니다(법무 확인 권장)</span></label>
|
||||
<label class="erp-field otr-field"><span>보내는 이름</span>
|
||||
<input class="erp-input" type="text" name="sender_name" maxlength="60" value="{{ template.sender_name }}" placeholder="받는 사람 메일함에 보이는 이름" /></label>
|
||||
<label class="erp-field otr-field"><span>본문 <small class="erp-muted"><code>{이름}</code> = 그 사람 이름 · <code>**굵게**</code> = 메일에서 굵은 글씨(DM 은 별표만 빠짐) · 주소는 메일에서 링크</small></span>
|
||||
<textarea class="erp-input otr-body" name="body" rows="24" required id="otr-body">{{ template.body }}</textarea></label>
|
||||
<label class="erp-field otr-field"><span>끝 문구 <small class="erp-muted">(본문 맨 아래 — 수신 거부 안내 등, 비워도 됨)</small></span>
|
||||
<textarea class="erp-input" name="footer" rows="2" maxlength="2000" placeholder="예: 더 이상 받기를 원하지 않으시면 이 메일에 '수신 거부'라고 회신해 주세요.">{{ template.footer }}</textarea></label>
|
||||
<div class="otr-set-actions">
|
||||
<button type="submit" class="erp-btn erp-btn-primary">저장</button>
|
||||
<button type="button" class="erp-btn erp-btn-outline" id="otr-default">기본 문구로 되돌리기</button>
|
||||
<span class="erp-muted">되돌리기는 칸만 바꿉니다 — [저장]을 눌러야 적용</span>
|
||||
</div>
|
||||
</form>
|
||||
<div class="otr-split">
|
||||
{#- 왼쪽 — 메일 -#}
|
||||
<div class="otr-col">
|
||||
<div class="erp-card otr-set-card">
|
||||
<div class="otr-col-head"><span class="otr-kind is-email">메일</span><b>이메일 안내문</b>
|
||||
<span class="erp-muted">[고른 메일 보내기]로 내 Gmail 에서 한 사람에 한 통씩</span></div>
|
||||
<label class="erp-field otr-field"><span>메일 제목</span>
|
||||
<input class="erp-input" type="text" name="subject" form="otr-set-form" maxlength="200" required value="{{ template.subject }}" /></label>
|
||||
<label class="otr-check"><input type="checkbox" name="ad_label" form="otr-set-form" value="1"{% if template.ad_label %} checked{% endif %} />
|
||||
<span>제목 앞에 <b>(광고)</b> 붙이기 <span class="erp-muted">— 영리 목적 광고성 메일은 정보통신망법 제50조에 따라 제목 앞 "(광고)"·수신 거부 방법을 적어야 합니다(법무 확인 권장)</span></span></label>
|
||||
<label class="erp-field otr-field"><span>보내는 이름</span>
|
||||
<input class="erp-input" type="text" name="sender_name" form="otr-set-form" maxlength="60" value="{{ template.sender_name }}" placeholder="받는 사람 메일함에 보이는 이름" /></label>
|
||||
<div class="erp-field otr-field"><span>본문 <small class="erp-muted"><code class="otr-tag">{이름}</code> = 그 사람 이름(빨강은 이 화면에서만 — 메일에는 이름이 본문 서식대로) · 되돌리기 Ctrl+Z</small></span>
|
||||
<div class="otr-editor" id="otr-body-editor"></div></div>
|
||||
<label class="erp-field otr-field"><span>끝 문구 <small class="erp-muted">(본문 맨 아래 — 수신 거부 안내 등, 비워도 됨)</small></span>
|
||||
<textarea class="erp-input" name="footer" form="otr-set-form" rows="2" maxlength="2000" placeholder="예: 더 이상 받기를 원하지 않으시면 이 메일에 '수신 거부'라고 회신해 주세요.">{{ template.footer }}</textarea></label>
|
||||
</div>
|
||||
|
||||
<div class="erp-card otr-set-card" id="images">
|
||||
<div class="otr-tpl-head"><b>본문 아래 사진</b><span class="erp-muted">메일 본문 맨 아래에 순서대로(최대 {{ max_images }}장, 가로 700px 로 줄여 저장). DM 에는 붙지 않습니다.</span></div>
|
||||
<div class="otr-images">
|
||||
{% for im in images %}
|
||||
<figure class="otr-image">
|
||||
<img src="/outreach/images/{{ im.id }}" alt="{{ im.filename }}" loading="lazy" />
|
||||
<figcaption>{{ loop.index }}. {{ im.filename }}</figcaption>
|
||||
<div class="otr-image-acts">
|
||||
{% if not loop.first %}<form method="post" action="/outreach/settings/images/{{ im.id }}/move"><input type="hidden" name="direction" value="-1" /><button class="erp-btn erp-btn-outline erp-btn-sm" title="앞으로">◀</button></form>{% endif %}
|
||||
{% if not loop.last %}<form method="post" action="/outreach/settings/images/{{ im.id }}/move"><input type="hidden" name="direction" value="1" /><button class="erp-btn erp-btn-outline erp-btn-sm" title="뒤로">▶</button></form>{% endif %}
|
||||
<form method="post" action="/outreach/settings/images/{{ im.id }}/delete" onsubmit="return confirm('이 사진을 뺄까요?');"><button class="erp-btn erp-btn-outline erp-btn-sm otr-danger">빼기</button></form>
|
||||
<div class="erp-card otr-set-card" id="images">
|
||||
<div class="otr-tpl-head"><b>본문 아래 사진</b><span class="erp-muted">메일 본문 맨 아래에 순서대로(최대 {{ max_images }}장, 가로 700px 로 줄여 저장). DM 에는 붙지 않습니다.</span></div>
|
||||
<div class="otr-images">
|
||||
{% for im in images %}
|
||||
<figure class="otr-image">
|
||||
<img src="/outreach/images/{{ im.id }}" alt="{{ im.filename }}" loading="lazy" />
|
||||
<figcaption>{{ loop.index }}. {{ im.filename }}</figcaption>
|
||||
<div class="otr-image-acts">
|
||||
{% if not loop.first %}<form method="post" action="/outreach/settings/images/{{ im.id }}/move"><input type="hidden" name="direction" value="-1" /><button class="erp-btn erp-btn-outline erp-btn-sm" title="앞으로">◀</button></form>{% endif %}
|
||||
{% if not loop.last %}<form method="post" action="/outreach/settings/images/{{ im.id }}/move"><input type="hidden" name="direction" value="1" /><button class="erp-btn erp-btn-outline erp-btn-sm" title="뒤로">▶</button></form>{% endif %}
|
||||
<form method="post" action="/outreach/settings/images/{{ im.id }}/delete" onsubmit="return confirm('이 사진을 뺄까요?');"><button class="erp-btn erp-btn-outline erp-btn-sm otr-danger">빼기</button></form>
|
||||
</div>
|
||||
</figure>
|
||||
{% else %}
|
||||
<p class="erp-muted">사진이 없습니다.</p>
|
||||
{% endfor %}
|
||||
</div>
|
||||
</figure>
|
||||
{% else %}
|
||||
<p class="erp-muted">사진이 없습니다.</p>
|
||||
{% endfor %}
|
||||
{% if images | length < max_images %}
|
||||
<form method="post" action="/outreach/settings/images" enctype="multipart/form-data" class="otr-upload">
|
||||
<input type="file" name="files" accept="image/jpeg,image/png,image/webp,image/gif" multiple required />
|
||||
<button type="submit" class="erp-btn erp-btn-primary">사진 넣기</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#- 오른쪽 — 인스타 DM -#}
|
||||
<div class="otr-col">
|
||||
<div class="erp-card otr-set-card otr-dm-card">
|
||||
<div class="otr-col-head"><span class="otr-kind is-instagram">DM</span><b>인스타 DM 문구</b>
|
||||
<span class="erp-muted">[DM 보내기]를 누르면 복사되는 글</span></div>
|
||||
<p class="erp-muted otr-note">인스타 DM 은 글자 서식·사진이 없어 글만 씁니다. <code class="otr-tag">{이름}</code> = 그 사람 이름.
|
||||
비워 두면 메일 본문 글 + 끝 문구가 그대로 복사됩니다.</p>
|
||||
<div class="otr-editor otr-editor-plain" id="otr-dm-editor"
|
||||
data-placeholder="예: 안녕하세요, {이름}님! 누적 800만 개 판매 미라클통 '미라네주방'입니다. {이름}님과 공동구매를 함께하고 싶어 연락드렸어요. 자세한 제안서는 메일로 보내드릴 수 있습니다 — 편하신 메일 주소 알려주시면 감사하겠습니다 :)"></div>
|
||||
<div class="otr-dm-foot">
|
||||
<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" id="otr-dm-from-mail">메일 본문 글 가져오기</button>
|
||||
<small class="erp-muted otr-count" id="otr-dm-count" data-max="{{ dm_max }}"></small>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{% if images | length < max_images %}
|
||||
<form method="post" action="/outreach/settings/images" enctype="multipart/form-data" class="otr-upload">
|
||||
<input type="file" name="files" accept="image/jpeg,image/png,image/webp,image/gif" multiple required />
|
||||
<button type="submit" class="erp-btn erp-btn-primary">사진 넣기</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
<script type="application/json" id="otr-default-data">{{ default | tojson }}</script>
|
||||
<script type="application/json" id="otr-current-data">{{ {"body": template.body, "dm_body": template.dm_body} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/outreach.js?v=20261027a" defer></script>{% endblock %}
|
||||
{% block scripts %}
|
||||
<script src="/static/vendor/quill/quill.js"></script>
|
||||
<script src="/static/outreach.js?v=20261030c" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -57,6 +57,8 @@
|
||||
묶어 상자 안에서 스크롤했는데, 진짜 셸에서는 상자 아래가 화면 밖에 잘리고(`overscroll-behavior: contain`) 휠이 페이지로 안 넘어갔다.
|
||||
스크롤 막대 배경(트랙) 투명 = `scrollbar-color: #c3c6cb transparent`(표 상자·실적 화면 `.erp-page`). 테스트 `tests/js/perf_sticky.browser.test.js`
|
||||
(진짜 `erp_base.html` 셸 렌더 `perf_*_shell.html` 로 휠 스크롤 — 스텁 셸로는 이 문제가 안 보였다).
|
||||
- **새로고침해도 스크롤 유지**(2026-11-02) — 수기 입력을 마치면 합계를 다시 계산하려고 새로고침하는데, 세로 스크롤은 `.erp-page` 상자라 브라우저가 복원하지 않아 맨 위로 돌아갔다.
|
||||
`performance.js keepScroll` 이 떠날 때 세로·가로 위치를 sessionStorage `perf_scroll` 에 저장 → **새로고침일 때만** 복원(같은 주소, 메뉴·기간 이동은 맨 위부터). 자동 새로 고침·업로드 뒤 새로고침도 같음.
|
||||
- 열 순서 카페24·네이버·쿠팡(윙)·쿠팡(로켓)·오늘의집·G마켓·카카오·GS샵·11번가·롯데ON·토스·애터미아자몰(마이그레이션 003).
|
||||
- 쿠팡(로켓)·애터미아자몰은 **수동 입력 전용**(`adapters/manual.py`, `manual_only` — 매출 업데이트에서 빠지고 인증 설정·연결 테스트 없음, 수동 입력 늘 켜짐).
|
||||
- **직접 추가 쇼핑몰·그룹·순서 드래그**(2026-10-22, 마이그레이션 009 `is_custom`·`is_group`·`parent_code`) — 설정 [+ 쇼핑몰 추가(수동 입력)]
|
||||
@@ -64,6 +66,12 @@
|
||||
직접 추가 쇼핑몰만 그룹 select 로 묶음, 이름 변경·삭제(삭제 = 그 쇼핑몰 수동 입력·수수료도). 매출 실적 표 그룹 열 = 보이는 하위 합계(일 합계엔 안 더함),
|
||||
▾/▸ 하위 열 접기(localStorage). ⠿ 드래그 → `PUT /api/marketplace-order` → `sort_order`, 화면 순서는 `dashboard.ordered_marketplaces`
|
||||
(그룹 바로 뒤 하위) 한 곳. 상세 `docs/PERFORMANCE_MODULE.md` "직접 추가 쇼핑몰·그룹".
|
||||
- **카페24(전체)·카페24(실적) 열**(2026-11-02, 예전 "공구 제외") — 카페24 열 이름 = 카페24(전체)(`_short_name`), 바로 오른쪽 카페24(실적) = 카페24 − 직접 추가 쇼핑몰 "자사몰(공동구매)"("카페24 공동구매"도, 이름으로 찾음·띄어쓰기 무시 — 없으면 전체 그대로, 쇼핑몰 필터·숨김과 무관하게 뺌).
|
||||
광고비 줄은 카페24(전체)와 같은 구글·메타(`dashboard._cafe24_real_column`, kind `diff`, 표 열만 — 일 합계엔 안 더함, 클릭·메모 없음). 공동구매 칸을 저장하면 그 줄 칸이 바로 바뀜(`performance.js saveManual`, td `data-diff-minus`·`data-base`), 합계 줄은 입력 마친 뒤 새로고침 때. 상세 `docs/PERFORMANCE_MODULE.md` "직접 추가 쇼핑몰·그룹".
|
||||
- **합계 기준**(2026-11-02) — 일 합계 = 카페24(실적) + 공동구매 + 나머지 쇼핑몰(카페24(전체)는 안 더함 — 공동구매가 들어 있어 중복). 일 합계·ROAS·KPI·추이·비중·월/연 누적 모두 `dashboard._summary_cells`(카페24 칸 = 실적, 그래프·누적의 카페24 줄 이름도 `summary_names` = 카페24(실적)), 표의 카페24(전체) 열만 원래 값. 광고비 탭 매출 대비 광고비·합계 ROAS = `total_sales_codes`(카페24 있으면 공동구매 코드 뺌, 같은 금액). **프로젝트 회의록 머리 카드는 아직 예전 합계**(`project/router.py` `total` — 공동구매 중복).
|
||||
- **매출 실적 표 열 숨기기**(2026-11-02) — 실적 설정 "공통 보기 설정" 카드(관리자만, `PUT /api/hidden-marketplaces`, `perf_settings` key `hidden_marketplaces`, 011 미적용 503) → **모든 사용자에게 적용**. **열만** 숨김(`dashboard.load_hidden`) — 일 합계·KPI·그래프·누적은 그대로, 그룹 열 = 보이는 하위 합계(다 숨기면 그룹 열도 없음). 쇼핑몰 필터(합계까지 바뀜)와 다름. 광고비 탭은 적용 안 함.
|
||||
- **일 합계 열 위치**(2026-11-02) — 매출 실적·광고비 표 모두 날짜 바로 오른쪽, 날짜 열과 함께 가로 고정(왼쪽 위치 `--perf-label-w` = 날짜 열 너비, `performance.js stickyHead`).
|
||||
- **기간 이동**(2026-11-02, `_period_nav.html` 공통) — 날짜 바로 좌우 화살표 SVG(글자 높이, 진한 회색), 글자 버튼 없음.
|
||||
- **매출 실적 표 모양(2026-10-22)** — `table.perf-autofit`(매출 탭만, 모든 기간 같음): 표가 100% 로 늘지 않고 **열 너비 = 내용 길이**, 날짜 열은 고정 210px 대신 자동 +
|
||||
**가로 스크롤해도 고정**(sticky left, 오른쪽 그림자). 그룹 열 = 진한 보라 머리·왼쪽 묶음 선, 하위 열 = 옅은 보라 머리(위 띠)·옅은 칸, 마지막 하위(`is-glast`, 접히면 그룹 열 `is-gclosed`) = 오른쪽 선.
|
||||
접기 단추 = 22px ⊟/⊞(SVG, 세로 막대가 돌아 바뀜). 접기·펴기 애니메이션 = 하위 칸 내용 `.perf-gc` 너비·칸 여백·투명도 260ms(`setGroup(code, fold, animate)`,
|
||||
@@ -74,9 +82,17 @@
|
||||
- KPI 는 **수수료 차감 매출 하나만** 화면 왼쪽 한 줄(`.perf-kpi-line` — 금액 + 비교 기간 대비 %, 모든 기간 공통). 총매출·수수료·월/연 누적 카드는 뺐다.
|
||||
- 일자별 표 기본 보기 = **수수료 차감 매출**(라우터 기본 `metric=net`, 예전에 고른 보기 localStorage 는 안 씀).
|
||||
- 마지막 업데이트 옆 **다음 업데이트까지 남은 시간** 초 단위 실시간(`router._auto_sync_ctx(store, kind)` — 매출 탭 = 매출 일정, 광고비 탭 = 광고비 일정 → `performance.js initNextUpdate`·`nextScheduleSlot`, `auto_sync.next_slot` 과 같은 규칙으로 화면이 다음 회차 계산, 서버 시각으로 PC 시계 보정, 자동 업데이트(env·그 종류 일정) 꺼지면 숨김).
|
||||
- **화면 자동 새로 고침**(2026-10-26) — 자동 업데이트(다른 사람이 누른 업데이트 포함)가 끝나면 매출 실적·광고비 화면이 20초 안에 reload.
|
||||
화면 데이터 `update_watch`(`router._update_watch` = 그린 때 마지막으로 끝난 작업 id, 보는 사람 것 제외) ↔ `GET /api/update-status?kind=sales|ads`
|
||||
(`jobs.last_finished` — 메모리 작업만, DB 안 읽음). 도는 중이면 끝날 때까지, 칸 입력·창(`.perf-modal`)·메뉴·확인 창이 열려 있으면 닫힐 때까지 기다림
|
||||
(마지막 업데이트 옆 안내), 탭이 안 보이면 안 묻고 다시 보이면 바로. 보는 사람이 직접 누른 업데이트는 진행 창이 새로 그린다. `performance.js initUpdateWatch`.
|
||||
|
||||
- 일자별 표 매출 칸 아래 **광고비(ROAS%)** 주황 줄(`--perf-ad`, `dashboard._ad_lines`) — 광고비 탭과 같은 값(`ad_spend.channel_roas`). 쇼핑몰 → 광고 채널은 `dashboard.sales_ad_channels`: 카페24 = 구글·메타 두 줄(이름 붙임), 네이버 = 네이버, 나머지는 `ROAS_SALES_CODE`(쿠팡 ← 쿠팡(윙)). 일 합계 = 보이는 쇼핑몰 광고비 합, ROAS = **일 합계 금액 ÷ 일 합계 광고비**(2026-10-19 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다; `roas` 총매출·`roas_net` 수수료 차감 매출 기준, 보기 기준에 따라 하나만). 광고비 표 없으면 줄 없음.
|
||||
- **매출 단위** 원·천원·백만원 — 설정 "보기 설정"(누구나, 이 브라우저 쿠키 `perf_unit`), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로.
|
||||
- **표 열 너비 자동/수동**(2026-10-27) — 설정 "보기 설정" **표 열 너비** [자동(글자 길이)]·[수동 조절](누구나, 이 브라우저 쿠키 `perf_colw`, `router._colw_ctx` → 템플릿 `colw`).
|
||||
수동 = 매출 실적·광고비 일자별 표에 `perf-colw-manual` → `performance.js initColWidths` 가 자동 너비를 잰 뒤 `table-layout:fixed`(`is-colw-fixed`, 넘치는 글자 …),
|
||||
머리글 오른쪽 경계 `.perf-colw-grip` 드래그(최소 36px)·두 번 누르면 그 열만 자동. **날짜 열(`label`)은 조절 불가 — 늘 자동 너비, 손잡이 없음, 저장값 무시**. 너비 = localStorage `perf_colw_sales`/`perf_colw_ads`(th `data-col` = 쇼핑몰·채널 코드·`label`·`total`)에 계속 유지,
|
||||
설정 [조절한 너비 초기화]가 둘 다 지움. 그룹 접기·펴기 때 열 너비도 함께 움직임(`colw.animate/settle`). 테스트 `tests/js/perf_colw.browser.test.js`.
|
||||
- **매출 단위** 원·천원·백만원(2026-11-02 모든 사용자 공통) — 설정 "공통 보기 설정"(관리자, `PUT /api/display-unit`, `perf_settings` key `display_unit`, 저장 값 없음·011 미적용 = 원, 예전 쿠키 `perf_unit` 은 안 봄), 서버가 `amount_text`(천원 정수·백만원 소수 한 자리)로 그림(`router._unit_ctx` → 템플릿 `amt`). 광고비 탭은 원 그대로. 표 열 너비는 사람(브라우저)마다 그대로.
|
||||
- 설정의 진단 카드(쇼핑몰 원본 데이터 확인·카페24 매출 대조·일별 한 번에 비교)는 2026-10-19 화면에서 뺐다(서버 API `marketplaces/{code}/reconcile`·`daily-check` 는 진단용으로 남김).
|
||||
|
||||
## 날짜 칸 메모 (2026-10-22, 마이그레이션 010 `perf_cell_memos`)
|
||||
@@ -102,7 +118,7 @@
|
||||
- 네이버: 3열 기간·4열 총비용·12열 ROAS(구매완료 광고수익률(%)), 머리글 클릭 = 일자별 보고서 항목.
|
||||
총비용·광고수익률은 **머리글 이름으로 찾음**(열 구성 바뀐 보고서 — 고정 12열이 비어 ROAS 누락됐던 문제, 2026-10-20). 광고수익률 칸이 없거나 비면 구매완료 전환매출액 ÷ 총비용. 저장된 `roas` 가 빈 예전 행은 `db.ad_roas` 가 metrics 에서 다시 구함(`ad_spend.roas_from_metrics`).
|
||||
- 일자별 보고서 창: ROAS 열은 **광고비 열 바로 오른쪽**, 네이버 "구매완료 광고수익률(%)" 머리글은 "ROAS(%)"로 표기(`ad_spend._roas_next_to_spend` → `labels`, 저장 키는 파일 머리글 그대로 — 예전 업로드도 그대로 적용).
|
||||
- 매출 대비 광고비 KPI.
|
||||
- KPI 는 **한 줄**(2026-10-30, 매출 실적처럼 `.perf-kpi-line` — 항목 `.perf-kpi-item` 을 세로 선으로 나눔, 좁은 화면은 한 항목씩): 광고비(전 기간 대비) · 매출 대비 광고비 · 연 누적 광고비. 월 누적 광고비 카드는 뺐다.
|
||||
- 광고 API 연동(마이그레이션 007 `perf_ad_credentials`·`perf_ad_source_status`) — 실적 설정 **광고 API 연동** 카드, 쇼핑몰과 같은 마스터 키로 암호화(AAD `perf:ad:…`), `ad_sources/`(채널 하나 = 파일 하나) + `ad_sync.py`, 광고비 자동 업데이트 일정(실적 설정 "자동 업데이트")대로.
|
||||
- **[광고비 업데이트]**(2026-10-20, 예전 채널별 [구글/메타 광고 불러오기] 버튼 삭제) — 광고비 탭 오른쪽 위, 매출 탭과 같은 모양:
|
||||
마지막 업데이트(광고 API 마지막 성공 가져오기 `ad_sync.last_ad_update_at`) · 다음 업데이트까지(광고비 일정 카운트다운) · 버튼.
|
||||
|
||||
@@ -507,8 +507,6 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
|
||||
cur = calc.sum_range(cells, codes, period.start, period.end)
|
||||
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
|
||||
mtd = calc.sum_range(cells, codes, month_period.start, month_period.end)
|
||||
m_prev = calc.sum_range(cells, codes, m_cmp_start, m_cmp_end)
|
||||
ytd = calc.sum_range(cells, codes, year_period.start, year_period.end)
|
||||
y_prev = calc.sum_range(cells, codes, y_cmp_start, y_cmp_end)
|
||||
|
||||
@@ -534,8 +532,6 @@ def build_ad_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
"delta": calc.pct_change(cur.gross, prev.gross), "cmp": cmp_label, "invert": True},
|
||||
{"key": "ratio", "label": f"{word} 매출 대비 광고비", "pct": ratio,
|
||||
"note": f"총매출 ₩{sales_total:,}" if sales_total else "매출 없음"},
|
||||
{"key": "mtd", "label": f"{month_period.label} 누적 광고비", "value": mtd.gross,
|
||||
"delta": calc.pct_change(mtd.gross, m_prev.gross), "cmp": m_cmp_label, "invert": True},
|
||||
{"key": "ytd", "label": f"{year_period.label} 누적 광고비", "value": ytd.gross,
|
||||
"delta": calc.pct_change(ytd.gross, y_prev.gross), "cmp": y_cmp_label, "invert": True},
|
||||
]
|
||||
|
||||
@@ -85,11 +85,11 @@ def require_store(request: Request, *, admin: bool = False) -> tuple[Any, dict[s
|
||||
def guard(request: Request, *, admin: bool = False):
|
||||
"""페이지 진입부. tuple(store, user) 이 아니면 그대로 응답으로 돌려준다."""
|
||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||
from app.store import has_module, is_admin # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return RedirectResponse(url="/login", status_code=303)
|
||||
return login_redirect(request)
|
||||
if not has_module(user, MODULE_KEY) or (admin and not is_admin(user)):
|
||||
reason = "실적 설정은 관리자만 볼 수 있습니다." if admin else f"{MODULE_NAME} 접근 권한이 없습니다."
|
||||
return render_template(request, "denied.html",
|
||||
|
||||
@@ -57,6 +57,46 @@ def _group_columns(store_rows: Sequence[Mapping[str, Any]], codes: Sequence[str]
|
||||
return cols, members
|
||||
|
||||
|
||||
# 카페24(실적) 열(2026-11-02, 예전 "공구 제외") — 카페24(전체) 바로 오른쪽, 카페24 − 공동구매. 표 열만(일 합계·그래프·누적엔 안 더함).
|
||||
# shortcut: 공동구매 쇼핑몰은 이름(띄어쓰기 무시)으로 찾는다 — 설정에서 다른 이름으로 바꾸면 빼지 않아 실적 = 전체가 된다, 자주 바뀌면 설정 값으로.
|
||||
CAFE24_GB_NAMES = ("자사몰(공동구매)", "카페24공동구매")
|
||||
CAFE24_EX_GB = "cafe24_ex_gb"
|
||||
CAFE24_REAL_NAME = "카페24(실적)"
|
||||
|
||||
|
||||
def groupbuy_code(markets: Sequence[Mapping[str, Any]]) -> str:
|
||||
"""공동구매 쇼핑몰 코드, 없으면 빈 값."""
|
||||
return next((m["code"] for m in markets if m["name"].replace(" ", "") in CAFE24_GB_NAMES), "")
|
||||
|
||||
|
||||
def total_sales_codes(markets: Sequence[Mapping[str, Any]]) -> list[str]:
|
||||
"""전체 매출에 더할 쇼핑몰 — 카페24(전체)에 공동구매가 들어 있어 카페24 가 있으면 공동구매는 뺀다(광고비 탭 매출 대비 광고비·합계 ROAS)."""
|
||||
codes = [m["code"] for m in markets]
|
||||
gb = groupbuy_code(markets)
|
||||
return [c for c in codes if c != gb] if "cafe24" in codes else codes
|
||||
|
||||
|
||||
def _summary_cells(cells: Mapping[tuple[date, str], calc.Money], gb: str) -> dict[tuple[date, str], calc.Money]:
|
||||
"""합계용 칸(2026-11-02) — 카페24 칸 = 카페24(실적)(카페24 − 공동구매). 일 합계·KPI·그래프·누적은 이 값으로 더해 공동구매가 두 번 안 들어간다."""
|
||||
out = dict(cells)
|
||||
for (d, c), m in cells.items():
|
||||
if c == gb:
|
||||
a = cells.get((d, "cafe24"), calc.Money())
|
||||
out[(d, "cafe24")] = calc.Money(gross=a.gross - m.gross, commission=a.commission - m.commission)
|
||||
return out
|
||||
|
||||
|
||||
def _cafe24_real_column(cols: list[dict[str, Any]], names: dict[str, str], short: dict[str, str], gb: str) -> None:
|
||||
"""카페24(실적) 열 머리 — 공동구매가 없으면(gb 빈 값) 전체와 같은 값이고 화면 즉시 계산도 없다."""
|
||||
col = next((c for c in cols if c["code"] == CAFE24_EX_GB), None)
|
||||
if col is None:
|
||||
return
|
||||
# base·minus = 화면이 공동구매 칸 저장 때 이 줄 칸을 바로 다시 계산할 때 씀(performance.js saveManual)
|
||||
col.update(kind="diff", base="cafe24", minus=gb)
|
||||
names[CAFE24_EX_GB] = f"{names['cafe24']} − {names[gb]}" if gb else CAFE24_REAL_NAME
|
||||
short[CAFE24_EX_GB] = CAFE24_REAL_NAME
|
||||
|
||||
|
||||
def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any] | None,
|
||||
configured: bool) -> str:
|
||||
if not marketplace.get("enabled"):
|
||||
@@ -69,15 +109,46 @@ def display_status(marketplace: Mapping[str, Any], status_row: Mapping[str, Any]
|
||||
return (status_row or {}).get("status") or "unknown"
|
||||
|
||||
|
||||
# 매출 단위(2026-10-19, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_unit) — (나누는 수, 소수 자리, 단위 이름)
|
||||
# 매출 단위(2026-10-19, 11-02 실적 설정 "공통 보기 설정" — 모든 사용자 같음, 마이그레이션 011 perf_settings) — (나누는 수, 소수 자리, 단위 이름)
|
||||
UNITS: dict[str, tuple[int, int, str]] = {"won": (1, 0, "원"), "thousand": (1000, 0, "천원"), "million": (1_000_000, 1, "백만원")}
|
||||
UNIT_COOKIE = "perf_unit"
|
||||
UNIT_SETTING = "display_unit"
|
||||
|
||||
|
||||
def normalize_unit(value: Any) -> str:
|
||||
return value if value in UNITS else "won"
|
||||
|
||||
|
||||
# 일자별 표 열 너비(2026-10-27, 실적 설정 "보기 설정" — 이 브라우저 쿠키 perf_colw) — auto = 글자 길이에 맞춤, manual = 머리글 경계 드래그
|
||||
COLW_COOKIE = "perf_colw"
|
||||
|
||||
|
||||
def normalize_colw(value: Any) -> str:
|
||||
return "manual" if value == "manual" else "auto"
|
||||
|
||||
|
||||
# 매출 실적 표 열 숨기기(2026-11-02, 실적 설정 "공통 보기 설정" — 관리자가 정하면 모든 사용자에게 적용, 마이그레이션 011 perf_settings) — 코드 목록, 열만 숨김
|
||||
HIDDEN_SETTING = "hidden_marketplaces"
|
||||
|
||||
|
||||
def _shared_setting(store: Any, key: str) -> Any:
|
||||
"""모든 사용자 공통 설정 값. 저장 값 없음·011 미적용이면 None(화면은 그대로 열린다)."""
|
||||
from .db import SettingsMigrationNeeded # noqa: WPS433
|
||||
|
||||
reader = getattr(store, "get_setting", None)
|
||||
try:
|
||||
return reader(key) if reader else None
|
||||
except SettingsMigrationNeeded:
|
||||
return None
|
||||
|
||||
|
||||
def load_hidden(store: Any) -> set[str]:
|
||||
return set(_shared_setting(store, HIDDEN_SETTING) or ())
|
||||
|
||||
|
||||
def load_unit(store: Any) -> str:
|
||||
return normalize_unit(_shared_setting(store, UNIT_SETTING))
|
||||
|
||||
|
||||
def amount_text(value: Any, unit: str = "won") -> str:
|
||||
"""금액 → 화면 글자(쉼표). 천원은 정수, 백만원은 소수 한 자리(반올림)."""
|
||||
div, places, _ = UNITS[normalize_unit(unit)]
|
||||
@@ -167,7 +238,10 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
names = {m["code"]: m["name"] for m in markets}
|
||||
short = {c: _short_name(names[c]) for c in all_codes}
|
||||
# 그룹(009) — 그룹 열 = 보이는 하위 쇼핑몰 합계(표 열만, 합계·그래프·누적은 쇼핑몰 기준 그대로)
|
||||
cols, group_members = _group_columns(store_rows, codes)
|
||||
# 표에 그릴 열 = 고른 쇼핑몰 + 카페24 바로 뒤 카페24(실적) − 숨긴 열(합계·그래프·누적은 codes 그대로)
|
||||
hidden = load_hidden(store)
|
||||
shown = [x for c in codes for x in ((c, CAFE24_EX_GB) if c == "cafe24" else (c,)) if x not in hidden]
|
||||
cols, group_members = _group_columns(store_rows, shown)
|
||||
for m in store_rows:
|
||||
if m["code"] in group_members:
|
||||
names[m["code"]] = short[m["code"]] = m["name"]
|
||||
@@ -189,7 +263,11 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
|
||||
q_start = min(period.start, cmp_start, m_cmp_start, y_cmp_start)
|
||||
q_end = max(period.end, year_period.end)
|
||||
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes), store.rate_table())
|
||||
gb = groupbuy_code(markets)
|
||||
# 공동구매를 필터로 뺐어도 카페24(실적) 계산엔 필요 — 합계·그래프는 아래에서 codes 만 더한다
|
||||
cells = calc.build_cells(store.daily_amounts(q_start, q_end, codes if not gb or gb in codes else [*codes, gb]),
|
||||
store.rate_table())
|
||||
summary = _summary_cells(cells, gb)
|
||||
# 수동 입력(설정에서 켠 쇼핑몰) — 일자별 표의 날짜 칸을 눌러 입력. 값이 있는 칸은 표시(API 값 대신 쓰는 중)
|
||||
manual_codes = [m["code"] for m in markets if m.get("manual_input") and m["code"] in codes]
|
||||
manual_amounts = getattr(store, "manual_amounts", None)
|
||||
@@ -201,8 +279,8 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
(manual_formulas(period.start, period.end, manual_codes) if manual_formulas and manual_codes else {}).items()
|
||||
if f"{d.isoformat()}|{c}" in manual_cells}
|
||||
|
||||
cur = calc.sum_range(cells, codes, period.start, period.end)
|
||||
prev = calc.sum_range(cells, codes, cmp_start, cmp_end)
|
||||
cur = calc.sum_range(summary, codes, period.start, period.end)
|
||||
prev = calc.sum_range(summary, codes, cmp_start, cmp_end)
|
||||
|
||||
period_word = {"day": "오늘" if period.start == today else "해당일", "week": "이번주" if period.start <= today <= period.end else "해당 주",
|
||||
"month": "이번달" if period.start <= today <= period.end else "해당 월",
|
||||
@@ -215,7 +293,9 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
"delta": calc.pct_change(cur.net, prev.net), "cmp": cmp_label},
|
||||
]
|
||||
|
||||
share = calc.by_code(cells, codes, period.start, period.end)
|
||||
share = calc.by_code(summary, codes, period.start, period.end)
|
||||
# 비중 그래프·월 누적 표의 카페24 줄 = 카페24(실적) — 줄을 더하면 합계와 같다
|
||||
summary_names = {**names, "cafe24": CAFE24_REAL_NAME}
|
||||
statuses = store.statuses()
|
||||
configured = configured or {}
|
||||
problems = []
|
||||
@@ -229,11 +309,18 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
|
||||
m_qs = "" if len(codes) == len(all_codes) else "".join(f"&m={c}" for c in codes)
|
||||
table = calc.main_table(period, codes, cells, today=today, holidays=holidays)
|
||||
# 일 합계 = 카페24(실적) + 공동구매 + 나머지(2026-11-02) — 공동구매를 필터로 뺐으면 실적 + 나머지.
|
||||
# 일 합계 ROAS 도 이 값 기준이라 _ad_lines 앞에서.
|
||||
for r, s in zip(table, calc.main_table(period, codes, summary, today=today, holidays=holidays)):
|
||||
r["total"] = s["total"]
|
||||
if "cafe24" in codes:
|
||||
r["cells"][CAFE24_EX_GB] = s["cells"]["cafe24"]
|
||||
_ad_lines(store, table, codes, cells, period, q_start, q_end)
|
||||
for r in table:
|
||||
for g, members in group_members.items():
|
||||
r["cells"][g] = calc.total(calc.Money(gross=r["cells"][c]["gross"], commission=r["cells"][c]["commission"])
|
||||
for c in members).as_dict()
|
||||
_cafe24_real_column(cols, names, short, gb)
|
||||
|
||||
def url(kind: str, anchor_d: date | None = None, start: date | None = None, end: date | None = None) -> str:
|
||||
if kind == "custom":
|
||||
@@ -273,10 +360,11 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
"selected_all": len(codes) == len(all_codes),
|
||||
"kpis": kpis,
|
||||
"table": table,
|
||||
"month": calc.month_summary(month_period.start.year, month_period.start.month, codes, cells),
|
||||
"year": calc.year_months(year_period.start.year, codes, cells, today=today),
|
||||
"chart_daily": calc.daily_series(period, codes, cells),
|
||||
"chart_share": [{"code": c, "name": names[c], **share[c].as_dict()} for c in codes],
|
||||
"summary_names": summary_names,
|
||||
"month": calc.month_summary(month_period.start.year, month_period.start.month, codes, summary),
|
||||
"year": calc.year_months(year_period.start.year, codes, summary, today=today),
|
||||
"chart_daily": calc.daily_series(period, codes, summary),
|
||||
"chart_share": [{"code": c, "name": summary_names[c], **share[c].as_dict()} for c in codes],
|
||||
"problems": problems,
|
||||
"manual_codes": manual_codes,
|
||||
"manual_cells": manual_cells,
|
||||
@@ -293,7 +381,7 @@ def build_dashboard(store: Any, *, kind: str, anchor: date, today: date,
|
||||
|
||||
|
||||
def _short_name(name: str) -> str:
|
||||
return {"네이버 스마트스토어": "네이버", "토스쇼핑": "토스"}.get(name, name)
|
||||
return {"네이버 스마트스토어": "네이버", "토스쇼핑": "토스", "카페24": "카페24(전체)"}.get(name, name)
|
||||
|
||||
|
||||
def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapping[str, Any],
|
||||
@@ -349,7 +437,14 @@ def build_settings(store: Any, *, configured: Mapping[str, bool], key_info: Mapp
|
||||
else:
|
||||
blocks.append({"row": r, "children": []})
|
||||
stale = {v: n for v, n in key_versions_in_use.items() if key_info.get("current_version") and v != key_info["current_version"]}
|
||||
return {"rows": rows, "blocks": blocks, "groups": groups,
|
||||
# "매출 실적 표 열 숨기기" 목록 = 매출 실적 표에 나오는 열(그룹 열은 하위를 다 숨기면 사라진다)
|
||||
hide_options: list[dict[str, str]] = []
|
||||
for r in rows:
|
||||
if not r["is_group"] and r["enabled"] and r["include_in_sales"]:
|
||||
hide_options.append({"code": r["code"], "name": _short_name(r["name"])})
|
||||
if r["code"] == "cafe24":
|
||||
hide_options.append({"code": CAFE24_EX_GB, "name": CAFE24_REAL_NAME})
|
||||
return {"rows": rows, "blocks": blocks, "groups": groups, "hide_options": hide_options, "hidden_codes": load_hidden(store),
|
||||
"custom_ready": bool(store_rows) and "is_custom" in store_rows[0],
|
||||
"key_info": key_info, "key_versions_in_use": dict(key_versions_in_use),
|
||||
"stale_key_rows": sum(stale.values()), "sample_count": sample_count,
|
||||
|
||||
@@ -238,6 +238,14 @@ def get_job(job_id: str) -> SyncJob | None:
|
||||
return _JOBS.get(job_id)
|
||||
|
||||
|
||||
def last_finished(kind: str = "sales", *, exclude_user: str = "") -> SyncJob | None:
|
||||
"""가장 최근에 끝난 그 종류의 작업(exclude_user 가 시작한 것은 뺌). 화면이 자동 업데이트(다른 사람 업데이트 포함)가 끝난 것을
|
||||
알아채 새로 그리려고(2026-10-26) — 보는 사람이 직접 누른 업데이트는 진행 창이 알아서 새로 그린다."""
|
||||
with _LOCK:
|
||||
done = [j for j in _JOBS.values() if j.finished and j.kind == kind and not (exclude_user and j.user == exclude_user)]
|
||||
return max(done, key=lambda j: j.finished_at) if done else None
|
||||
|
||||
|
||||
def running_job(kind: str = "sales") -> SyncJob | None:
|
||||
"""지금 돌고 있는 그 종류의 작업(가장 최근). 없으면 None — 다른 사람이 누른 업데이트도 같이 보여 주려고."""
|
||||
with _LOCK:
|
||||
|
||||
@@ -29,6 +29,8 @@ JSON API — 관리자
|
||||
POST /performance/api/marketplaces 쇼핑몰(수동 입력 전용)·그룹 직접 추가(009)
|
||||
DELETE /performance/api/marketplaces/{code} 직접 추가 쇼핑몰·그룹 삭제(그 쇼핑몰 수동 입력·수수료도)
|
||||
PUT /performance/api/marketplace-order 쇼핑몰 순서(설정 드래그 — 매출 실적 열 순서)
|
||||
PUT /performance/api/hidden-marketplaces 매출 실적 표 열 숨기기(모든 사용자에게 적용)
|
||||
PUT /performance/api/display-unit 매출 단위(모든 사용자에게 적용)
|
||||
GET /performance/api/marketplaces/{code}/manual-days 수동 입력해 둔 날 수(삭제 확인 문구)
|
||||
POST /performance/api/marketplaces/{code}/rates 수수료율(적용 시작일)
|
||||
DELETE /performance/api/marketplaces/{code}/rates/{id}
|
||||
@@ -146,7 +148,9 @@ def dashboard_page(
|
||||
)
|
||||
ctx["metric"] = metric if metric in ("gross", "commission", "net") else "net"
|
||||
ctx["auto_sync"] = _auto_sync_ctx(store, "sales")
|
||||
_unit_ctx(request, ctx)
|
||||
ctx["update_watch"] = _update_watch("sales", user)
|
||||
_unit_ctx(store, ctx)
|
||||
_colw_ctx(request, ctx)
|
||||
return render_template(request, "performance/index.html", {**common.base_ctx(user, active_tab="dashboard"), **ctx})
|
||||
|
||||
|
||||
@@ -173,16 +177,47 @@ def _auto_sync_ctx(store: Any, kind: str) -> dict[str, Any] | None:
|
||||
"label": auto_sync.describe(sched)}
|
||||
|
||||
|
||||
def _unit_ctx(request: Request, ctx: dict[str, Any]) -> None:
|
||||
"""매출 단위(원·천원·백만원) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_unit)에 둔다. 템플릿은 amt(v) 로 그린다."""
|
||||
from .dashboard import UNIT_COOKIE, UNITS, amount_text, normalize_unit # noqa: WPS433
|
||||
def _update_watch(kind: str, user: dict[str, Any]) -> dict[str, str]:
|
||||
"""화면 자동 새로 그리기(2026-10-26) — 그린 시점에 마지막으로 끝난 업데이트(보는 사람 것 제외). 화면이
|
||||
GET /api/update-status 로 이 값이 바뀌면(자동 업데이트 등이 끝나면) 새로 고친다."""
|
||||
from . import jobs # noqa: WPS433
|
||||
|
||||
unit = normalize_unit(request.cookies.get(UNIT_COOKIE))
|
||||
job = jobs.last_finished(kind, exclude_user=user.get("email", ""))
|
||||
return {"kind": kind, "seen": job.id if job else ""}
|
||||
|
||||
|
||||
@router.get("/api/update-status")
|
||||
def api_update_status(request: Request, kind: str = "sales") -> JSONResponse:
|
||||
"""지금 그 종류 업데이트가 도는지 · 마지막으로 끝난 업데이트(보는 사람이 시작한 것 제외) — 화면이 20초마다 본다.
|
||||
메모리의 진행 작업만 보고 DB 는 안 읽는다."""
|
||||
from . import jobs # noqa: WPS433
|
||||
|
||||
_, user = common.require_store(request)
|
||||
if kind not in jobs.KINDS:
|
||||
raise HTTPException(status_code=404, detail="알 수 없는 업데이트 종류입니다.")
|
||||
job = jobs.last_finished(kind, exclude_user=user.get("email", ""))
|
||||
return JSONResponse({"kind": kind, "running": jobs.running_job(kind) is not None, "done": job.id if job else "",
|
||||
"user": job.user if job else ""})
|
||||
|
||||
|
||||
def _unit_ctx(store: Any, ctx: dict[str, Any]) -> None:
|
||||
"""매출 단위(원·천원·백만원) — 관리자가 실적 설정 "공통 보기 설정"에서 정하면 모든 사용자에게 같게. 템플릿은 amt(v) 로 그린다."""
|
||||
from .dashboard import UNITS, amount_text, load_unit # noqa: WPS433
|
||||
|
||||
unit = load_unit(store)
|
||||
ctx["unit"] = unit
|
||||
ctx["unit_label"] = UNITS[unit][2]
|
||||
ctx["amt"] = lambda v: amount_text(v, unit)
|
||||
|
||||
|
||||
def _colw_ctx(request: Request, ctx: dict[str, Any]) -> None:
|
||||
"""일자별 표 열 너비(2026-10-27) — 실적 설정 "보기 설정"이 이 브라우저 쿠키(perf_colw)에 둔다.
|
||||
manual 이면 표에 perf-colw-manual — performance.js initColWidths 가 머리글 경계 드래그 + 너비 기억(localStorage)."""
|
||||
from .dashboard import COLW_COOKIE, normalize_colw # noqa: WPS433
|
||||
|
||||
ctx["colw"] = normalize_colw(request.cookies.get(COLW_COOKIE))
|
||||
|
||||
|
||||
@router.get("/ads", response_class=HTMLResponse)
|
||||
def ads_page(
|
||||
request: Request,
|
||||
@@ -198,13 +233,13 @@ def ads_page(
|
||||
return g
|
||||
store, user = g
|
||||
from .ad_spend import build_ad_dashboard # noqa: WPS433
|
||||
from .dashboard import _sales_marketplaces # noqa: WPS433
|
||||
from .dashboard import _sales_marketplaces, total_sales_codes # noqa: WPS433
|
||||
|
||||
today = today_kst()
|
||||
ctx = build_ad_dashboard(
|
||||
store, kind=period, anchor=_parse_date(d) or today, today=today,
|
||||
custom_from=_parse_date(from_), custom_to=_parse_date(to), holidays=_holidays(),
|
||||
sales_codes=[m["code"] for m in _sales_marketplaces(store)],
|
||||
sales_codes=total_sales_codes(_sales_marketplaces(store)),
|
||||
)
|
||||
# [광고비 업데이트](2026-10-20) — 관리자가 실적 설정에서 인증정보를 넣은 광고 연동 전부를 진행 창으로.
|
||||
# 마지막 업데이트 = 광고 API 마지막 성공 가져오기, 다음 업데이트 = 매출 자동 업데이트와 같은 회차.
|
||||
@@ -221,6 +256,8 @@ def ads_page(
|
||||
ctx["ad_last_update_at"] = last_ad_update_at(store)
|
||||
ctx["ad_running"] = jobs.running_job("ads") is not None
|
||||
ctx["auto_sync"] = _auto_sync_ctx(store, "ads")
|
||||
ctx["update_watch"] = _update_watch("ads", user)
|
||||
_colw_ctx(request, ctx)
|
||||
return render_template(request, "performance/ads.html",
|
||||
{**common.base_ctx(user, active_tab="ads", page_title="광고비"), **ctx})
|
||||
|
||||
@@ -248,7 +285,8 @@ def settings_page(request: Request):
|
||||
ctx["ad_sources"] = _ad_source_rows(store, ad_sync.configured())
|
||||
ctx["ad_api_ready"] = store.ad_api_ready()
|
||||
ctx["auto_sync_settings"] = _auto_sync_settings_ctx(store) # 카드는 관리자에게만(템플릿)
|
||||
_unit_ctx(request, ctx)
|
||||
_unit_ctx(store, ctx)
|
||||
_colw_ctx(request, ctx)
|
||||
return render_template(request, "performance/settings.html",
|
||||
{**common.base_ctx(user, active_tab="settings", page_title="실적 설정"), **ctx})
|
||||
|
||||
@@ -918,6 +956,44 @@ def api_marketplace_order(request: Request, payload: dict[str, Any] = Body(...))
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
|
||||
@router.put("/api/hidden-marketplaces")
|
||||
def api_hidden_marketplaces(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""매출 실적 표 열 숨기기(2026-11-02, 관리자, 마이그레이션 011) — 체크한 코드 전부. 모든 사용자의 표에 적용."""
|
||||
from .dashboard import CAFE24_EX_GB, HIDDEN_SETTING # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request, admin=True)
|
||||
raw = payload.get("codes")
|
||||
if not isinstance(raw, list):
|
||||
raise HTTPException(status_code=400, detail="숨길 쇼핑몰 목록이 필요합니다.")
|
||||
known = {m["code"] for m in store.list_marketplaces()} | {CAFE24_EX_GB}
|
||||
codes = sorted({str(c) for c in raw} & known)
|
||||
_save_shared_setting(store, HIDDEN_SETTING, codes, user)
|
||||
return JSONResponse({"ok": True, "codes": codes})
|
||||
|
||||
|
||||
@router.put("/api/display-unit")
|
||||
def api_display_unit(request: Request, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
"""매출 단위(2026-11-02, 관리자, 마이그레이션 011) — won·thousand·million. 모든 사용자의 매출 실적 화면에 적용."""
|
||||
from .dashboard import UNIT_SETTING, UNITS # noqa: WPS433
|
||||
|
||||
store, user = common.require_store(request, admin=True)
|
||||
unit = payload.get("unit")
|
||||
if not isinstance(unit, str) or unit not in UNITS:
|
||||
raise HTTPException(status_code=400, detail="알 수 없는 매출 단위입니다.")
|
||||
_save_shared_setting(store, UNIT_SETTING, unit, user)
|
||||
return JSONResponse({"ok": True, "unit": unit})
|
||||
|
||||
|
||||
def _save_shared_setting(store: Any, key: str, value: Any, user: dict[str, Any]) -> None:
|
||||
from .db import SettingsMigrationNeeded # noqa: WPS433
|
||||
|
||||
try:
|
||||
store.set_setting(key, value, user=user.get("email", ""))
|
||||
except SettingsMigrationNeeded:
|
||||
raise HTTPException(status_code=503, detail="저장하려면 performance_db 마이그레이션 011"
|
||||
"(scripts/sql/performance_db_011_settings.sql)을 먼저 적용해야 합니다.") from None
|
||||
|
||||
|
||||
@router.put("/api/marketplaces/{code}")
|
||||
def api_update_marketplace(request: Request, code: str, payload: dict[str, Any] = Body(...)) -> JSONResponse:
|
||||
store, _ = common.require_store(request, admin=True)
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
{# 기간 이동(2026-11-02, 매출 실적·광고비 공통) — 날짜 바로 좌우에 화살표 이미지(SVG, 글자 높이), 글자 버튼 없음 #}
|
||||
<div class="perf-nav">
|
||||
<a class="perf-nav-btn" href="{{ nav.prev }}" title="{{ period.prev_label }}" aria-label="{{ period.prev_label }}"><svg viewBox="0 0 10 16" aria-hidden="true"><path d="M8 1.5 2 8l6 6.5"/></svg></a>
|
||||
<span class="perf-nav-label">{{ period.label }}</span>
|
||||
<a class="perf-nav-btn" href="{{ nav.next }}" title="{{ period.next_label }}" aria-label="{{ period.next_label }}"><svg viewBox="0 0 10 16" aria-hidden="true"><path d="M2 1.5 8 8l-6 6.5"/></svg></a>
|
||||
</div>
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %}
|
||||
|
||||
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
||||
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
||||
@@ -24,11 +24,7 @@
|
||||
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
|
||||
</div>
|
||||
|
||||
<div class="perf-nav">
|
||||
<a class="perf-nav-btn" href="{{ nav.prev }}" title="{{ period.prev_label }}">‹ {{ period.prev_label }}</a>
|
||||
<span class="perf-nav-label">{{ period.label }}</span>
|
||||
<a class="perf-nav-btn" href="{{ nav.next }}" title="{{ period.next_label }}">{{ period.next_label }} ›</a>
|
||||
</div>
|
||||
{% include "performance/_period_nav.html" %}
|
||||
|
||||
<form class="perf-custom" id="perf-custom" method="get" action="/performance/ads"{% if period_kind != 'custom' %} hidden{% endif %}>
|
||||
<input type="hidden" name="period" value="custom" />
|
||||
@@ -61,27 +57,25 @@
|
||||
(scripts/sql/performance_db_005_ad_spend.sql)를 적용하면 입력할 수 있습니다.</div>
|
||||
{% endif %}
|
||||
|
||||
<!-- ── KPI ── -->
|
||||
<div class="perf-kpis">
|
||||
<!-- ── KPI — 한 줄(2026-10-30, 매출 실적처럼): 광고비 · 매출 대비 광고비 · 연 누적 ── -->
|
||||
<div class="perf-kpi-line">
|
||||
{% for k in kpis %}
|
||||
<div class="perf-kpi{% if k.primary %} is-primary{% endif %}">
|
||||
<div class="perf-kpi-label">{{ k.label }}</div>
|
||||
<span class="perf-kpi-item">
|
||||
<span class="perf-muted">{{ k.label }}</span>
|
||||
{% if k.key == 'ratio' %}
|
||||
<div class="perf-kpi-value">{% if k.pct is none %}–{% else %}{{ "%.1f" | format(k.pct) }}%{% endif %}</div>
|
||||
<div class="perf-kpi-delta"><span class="perf-muted">{{ k.note }}</span></div>
|
||||
<b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">{% if k.pct is none %}–{% else %}{{ "%.1f" | format(k.pct) }}%{% endif %}</b>
|
||||
<span class="perf-muted">{{ k.note }}</span>
|
||||
{% else %}
|
||||
<div class="perf-kpi-value">₩{{ "{:,}".format(k.value) }}</div>
|
||||
<div class="perf-kpi-delta">
|
||||
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
|
||||
{% else %}
|
||||
{% set up = k.delta > 0 %}
|
||||
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif up != (k.invert or false) %}is-up{% else %}is-down{% endif %}">
|
||||
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
|
||||
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
<b class="perf-kpi-line-value{% if not k.primary %} is-sub{% endif %}">₩{{ "{:,}".format(k.value) }}</b>
|
||||
{% if k.delta is none %}<span class="perf-muted">{{ k.cmp }} 비교 없음</span>
|
||||
{% else %}
|
||||
{% set up = k.delta > 0 %}
|
||||
<span class="perf-delta {% if k.delta == 0 %}is-flat{% elif up != (k.invert or false) %}is-up{% else %}is-down{% endif %}">
|
||||
{% if k.delta > 0 %}▲{% elif k.delta < 0 %}▼{% else %}–{% endif %} {{ "%.1f" | format(k.delta | abs) }}%</span>
|
||||
<span class="perf-muted">{{ k.cmp }} 대비</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</span>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
@@ -99,12 +93,13 @@
|
||||
<div class="erp-table-wrap perf-table-wrap perf-main-wrap">
|
||||
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
|
||||
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정(매출 실적 표와 같음) -#}
|
||||
<table class="perf-table perf-main perf-autofit">
|
||||
{#- 열 너비(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw) — manual = 머리글 경계 드래그로 조절, 너비는 이 브라우저에 기억(th data-col 별) -#}
|
||||
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="ads">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = {% if c == 'google' %}구글 광고 ROAS(전환 가치 ÷ 비용){% elif c == 'meta' %}메타 광고 구매 ROAS(구매 전환값 ÷ 지출 금액){% else %}보고서 ROAS(구매완료 광고수익률){% endif %}"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
|
||||
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||
<th class="perf-th-total" data-col="total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||
{% for c in codes %}{% if c in detail_channels %}<th class="perf-th-detail" data-col="{{ c }}" title="{{ names[c] }} — 눌러 일자별 광고 보고서 항목 보기. 괄호 = {% if c == 'google' %}구글 광고 ROAS(전환 가치 ÷ 비용){% elif c == 'meta' %}메타 광고 구매 ROAS(구매 전환값 ÷ 지출 금액){% else %}보고서 ROAS(구매완료 광고수익률){% endif %}"><button type="button" class="perf-detail-btn" data-detail-channel="{{ c }}">{{ names[c] }} <span class="material-symbols-outlined" aria-hidden="true">table_view</span></button></th>{% else %}<th data-col="{{ c }}" title="{{ names[c] }} — 날짜 칸을 눌러 광고비 입력.{% if roas_basis[c] %} 괄호 = ROAS({{ roas_basis[c] }} 매출 ÷ 광고비){% else %} ROAS 는 계산하지 않음(따로 입력){% endif %}">{{ names[c] }} <span class="perf-manual-mark" aria-hidden="true">✎</span></th>{% endif %}{% endfor %}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -113,6 +108,7 @@
|
||||
<th class="perf-td-label" scope="row">
|
||||
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
|
||||
</th>
|
||||
<td class="perf-num perf-td-total"><span class="v v-gross">{{ won(r.total.gross) }}</span>{{ roas(r.roas_total) }}</td>
|
||||
{% for c in codes %}
|
||||
{% set v = r.cells[c].gross %}
|
||||
{% if r.kind == 'day' and not migration_needed %}
|
||||
@@ -126,7 +122,6 @@
|
||||
<td class="perf-num"><span class="v v-gross">{{ won(v) }}</span>{{ roas(r.roas[c]) }}</td>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<td class="perf-num perf-td-total"><span class="v v-gross">{{ won(r.total.gross) }}</span>{{ roas(r.roas_total) }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
@@ -237,8 +232,9 @@
|
||||
"period_label": period.label,
|
||||
"empty_text": "기간 내 광고비가 없습니다.",
|
||||
"upload_channels": upload_channels,
|
||||
"auto_sync": auto_sync
|
||||
"auto_sync": auto_sync,
|
||||
"update_watch": update_watch
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261027b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -42,11 +42,7 @@
|
||||
<button type="button" class="perf-seg{% if period_kind == 'custom' %} is-active{% endif %}" id="perf-custom-btn">직접선택</button>
|
||||
</div>
|
||||
|
||||
<div class="perf-nav">
|
||||
<a class="perf-nav-btn" href="{{ nav.prev }}" title="{{ period.prev_label }}">‹ {{ period.prev_label }}</a>
|
||||
<span class="perf-nav-label">{{ period.label }}</span>
|
||||
<a class="perf-nav-btn" href="{{ nav.next }}" title="{{ period.next_label }}">{{ period.next_label }} ›</a>
|
||||
</div>
|
||||
{% include "performance/_period_nav.html" %}
|
||||
|
||||
<form class="perf-custom" id="perf-custom" method="get" action="/performance/"{% if period_kind != 'custom' %} hidden{% endif %}>
|
||||
<input type="hidden" name="period" value="custom" />
|
||||
@@ -137,18 +133,19 @@
|
||||
<div class="erp-table-wrap perf-table-wrap perf-main-wrap">
|
||||
{#- perf-main-wrap(2026-10-26) = 표 안에서 세로 스크롤 — 제목 행·기간 합계 행 고정 -#}
|
||||
{#- perf-autofit(2026-10-22) = 열 너비는 내용 길이만큼, 날짜 열은 가로 스크롤해도 고정 -#}
|
||||
<table class="perf-table perf-main perf-autofit">
|
||||
{#- 열 너비(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw) — manual = 머리글 경계 드래그로 조절, 너비는 이 브라우저에 기억(th data-col 별) -#}
|
||||
<table class="perf-table perf-main perf-autofit{% if colw == 'manual' %} perf-colw-manual{% endif %}" data-colw-key="sales">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="perf-th-label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||
<th class="perf-th-label" data-col="label">{% if period_kind == 'year' %}월{% else %}날짜{% endif %}</th>
|
||||
<th class="perf-th-total" data-col="total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||
{#- 그룹(2026-10-22) — 그룹 열 = 보이는 하위 쇼핑몰 합계, ⊟/⊞ 로 하위 열 접기/펴기(이 브라우저에 기억, 펼치고 접을 때 애니메이션).
|
||||
하위 열은 .perf-gc 로 내용을 감싼다 — 접을 때 그 너비를 0 으로 줄여 열이 부드럽게 닫힌다. is-glast = 그룹의 마지막 하위 열(오른쪽 묶음 선) -#}
|
||||
{% for col in cols %}{% set c = col.code %}
|
||||
{% set glast = col.kind == 'child' and (not loop.nextitem or loop.nextitem.group != col.group) %}
|
||||
{% if col.kind == 'group' %}<th class="perf-th-group" data-group-head="{{ c }}" title="{{ names[c] }} — 하위 쇼핑몰 {{ group_members[c] | length }}곳 매출 합계"><span class="perf-gh"><button type="button" class="perf-gtoggle" data-group-toggle="{{ c }}" aria-expanded="true" aria-label="{{ short_names[c] }} 하위 쇼핑몰 접기" title="하위 쇼핑몰 접기/펴기"><svg viewBox="0 0 18 18" width="18" height="18" aria-hidden="true"><rect class="g-box" x="1" y="1" width="16" height="16" rx="4"/><path class="g-h" d="M5 9h8"/><path class="g-v" d="M9 5v8"/></svg></button><span>{{ short_names[c] }}</span></span></th>
|
||||
{% else %}<th{% if col.kind == 'child' %} class="perf-th-child{% if glast %} is-glast{% endif %}" data-group-child="{{ col.group }}"{% endif %} title="{{ names[c] }}{% if c in manual_codes %} — 수동 입력(날짜 칸을 눌러 입력){% endif %}">{% if col.kind == 'child' %}<div class="perf-gc">{% endif %}{{ short_names[c] }}{% if c in manual_codes %} <span class="perf-manual-mark" aria-label="수동 입력">✎</span>{% endif %}{% if col.kind == 'child' %}</div>{% endif %}</th>{% endif %}
|
||||
{% set sub = col.kind == 'child' or (col.kind == 'diff' and col.group) %}{% set glast = sub and (not loop.nextitem or loop.nextitem.group != col.group) %}
|
||||
{% if col.kind == 'group' %}<th class="perf-th-group" data-col="{{ c }}" data-group-head="{{ c }}" title="{{ names[c] }} — 하위 쇼핑몰 {{ group_members[c] | length }}곳 매출 합계"><span class="perf-gh"><button type="button" class="perf-gtoggle" data-group-toggle="{{ c }}" aria-expanded="true" aria-label="{{ short_names[c] }} 하위 쇼핑몰 접기" title="하위 쇼핑몰 접기/펴기"><svg viewBox="0 0 18 18" width="18" height="18" aria-hidden="true"><rect class="g-box" x="1" y="1" width="16" height="16" rx="4"/><path class="g-h" d="M5 9h8"/><path class="g-v" d="M9 5v8"/></svg></button><span>{{ short_names[c] }}</span></span></th>
|
||||
{% else %}<th data-col="{{ c }}"{% if sub %} class="perf-th-child{% if glast %} is-glast{% endif %}" data-group-child="{{ col.group }}"{% endif %} title="{{ names[c] }}{% if c in manual_codes %} — 수동 입력(날짜 칸을 눌러 입력){% endif %}">{% if sub %}<div class="perf-gc">{% endif %}{{ short_names[c] }}{% if c in manual_codes %} <span class="perf-manual-mark" aria-label="수동 입력">✎</span>{% endif %}{% if sub %}</div>{% endif %}</th>{% endif %}
|
||||
{% endfor %}
|
||||
<th class="perf-th-total">{% if period_kind == 'year' %}월 합계{% else %}일 합계{% endif %}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -157,14 +154,18 @@
|
||||
<th class="perf-td-label" scope="row">
|
||||
{{ r.label }}{% if r.holiday %}<small class="perf-hol">{{ r.holiday }}</small>{% endif %}
|
||||
</th>
|
||||
<td class="perf-num perf-td-total">{{ m3(r.total) }}{% if r.ads_total %}{{ adl_total(r.ads_total) }}{% endif %}</td>
|
||||
{% for col in cols %}
|
||||
{% set c = col.code %}
|
||||
{% set m = r.cells[c] %}
|
||||
{% set glast = col.kind == 'child' and (not loop.nextitem or loop.nextitem.group != col.group) %}
|
||||
{% set gattr %}{% if col.kind == 'child' %} data-group-child="{{ col.group }}"{% endif %}{% endset %}
|
||||
{% set gc0 %}{% if col.kind == 'child' %}<div class="perf-gc">{% endif %}{% endset %}{% set gc1 %}{% if col.kind == 'child' %}</div>{% endif %}{% endset %}
|
||||
{% set sub = col.kind == 'child' or (col.kind == 'diff' and col.group) %}{% set glast = sub and (not loop.nextitem or loop.nextitem.group != col.group) %}
|
||||
{% set gattr %}{% if sub %} data-group-child="{{ col.group }}"{% endif %}{% endset %}
|
||||
{% set gc0 %}{% if sub %}<div class="perf-gc">{% endif %}{% endset %}{% set gc1 %}{% if sub %}</div>{% endif %}{% endset %}
|
||||
{% if col.kind == 'group' %}
|
||||
<td class="perf-num perf-td-group" data-group-cell="{{ c }}">{{ m3(m) }}</td>
|
||||
{% elif col.kind == 'diff' %}{#- 카페24(실적) = 카페24(전체) − 공동구매(dashboard._cafe24_real_column) — 계산 열이라 클릭·메모 없음, 광고비 줄은 카페24(전체)와 같음 -#}
|
||||
{%- set b = r.cells[col.base] %}{#- 일 행 = 공동구매 칸 저장 때 performance.js 가 base(카페24 총매출,수수료,차감) − 새 값으로 바로 바꿈 -#}
|
||||
<td class="perf-num{% if glast %} is-glast{% endif %}"{{ gattr }}{% if r.kind == 'day' and col.minus %} data-diff-minus="{{ col.minus }}" data-base="{{ b.gross }},{{ b.commission }},{{ b.net }}"{% endif %}>{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[col.base]) }}{{ gc1 }}</td>
|
||||
{% elif r.kind == 'day' and c in manual_codes %}
|
||||
{% set is_manual = (r.date ~ '|' ~ c) in manual_cells %}
|
||||
{% set fx = (formula_cells or {}).get(r.date ~ '|' ~ c) %}
|
||||
@@ -178,7 +179,6 @@
|
||||
{% if r['from'] %}data-code="{{ c }}" data-from="{{ r['from'] }}" data-to="{{ r['to'] }}"{% endif %}{% if r.kind == 'day' %} data-memo-code="{{ c }}" data-date="{{ r.date }}"{% endif %}{% if memo %} data-memo="{{ memo }}"{% endif %}>{{ gc0 }}{{ m3(m) }}{{ adl(r.ads[c]) }}{{ gc1 }}</td>
|
||||
{% endif %}
|
||||
{% endfor %}
|
||||
<td class="perf-num perf-td-total">{{ m3(r.total) }}{% if r.ads_total %}{{ adl_total(r.ads_total) }}{% endif %}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
@@ -214,7 +214,7 @@
|
||||
<tbody>
|
||||
{% for r in month.rows %}
|
||||
<tr>
|
||||
<th class="perf-td-label" scope="row">{{ names[r.code] }}</th>
|
||||
<th class="perf-td-label" scope="row">{{ summary_names[r.code] }}</th>
|
||||
<td class="perf-num">{{ won(r.gross) }}</td>
|
||||
<td class="perf-num">{{ won(r.commission) }}</td>
|
||||
<td class="perf-num">{{ won(r.net) }}</td>
|
||||
@@ -273,6 +273,7 @@
|
||||
<p class="perf-foot perf-muted">
|
||||
매출 기준: 결제는 결제일, 취소·반품은 발생일에 반영(음수). 수수료는 그날 적용되는 쇼핑몰 수수료율로 계산하며
|
||||
일·쇼핑몰 단위로 원 미만 반올림합니다. 금액을 누르면 주문 목록을 볼 수 있습니다.
|
||||
일 합계·상단 금액·그래프·누적 = 카페24(실적) + 자사몰(공동구매) + 나머지 쇼핑몰(카페24(전체)는 더하지 않음).
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@@ -288,8 +289,9 @@
|
||||
"today": today,
|
||||
"unit": unit,
|
||||
"manual_upload_names": manual_upload_names,
|
||||
"auto_sync": auto_sync
|
||||
"auto_sync": auto_sync,
|
||||
"update_watch": update_watch
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261027b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261027b" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261102b" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
@@ -142,11 +142,32 @@
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{# 보기 설정(2026-10-19) — 모듈 권한자 누구나, 이 브라우저에만(쿠키 perf_unit). 매출 실적 화면 금액·광고비 줄에 적용 #}
|
||||
{# 보기 설정(2026-10-19) — 모듈 권한자 누구나, 이 브라우저에만 #}
|
||||
<div class="erp-card perf-card" id="perf-view-opts">
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">보기 설정</h2>
|
||||
<span class="perf-muted">매출 실적 화면의 금액 단위입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다.</span>
|
||||
<span class="perf-muted">매출 실적·광고비 화면을 보는 방식입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다.</span>
|
||||
</div>
|
||||
{# 표 열 너비(2026-10-27, 쿠키 perf_colw) — 매출 실적·광고비 일자별 표. 수동 = 머리글 오른쪽 경계 드래그, 너비는 이 브라우저 localStorage(perf_colw_sales/ads) #}
|
||||
<div class="perf-opt-row">
|
||||
<span class="perf-opt-label">표 열 너비</span>
|
||||
<div class="perf-quick" role="radiogroup" aria-label="표 열 너비">
|
||||
{% for k, label in [('auto', '자동(글자 길이)'), ('manual', '수동 조절')] %}
|
||||
<button type="button" class="perf-seg{% if colw == k %} is-active{% endif %}" role="radio"
|
||||
aria-checked="{{ 'true' if colw == k else 'false' }}" data-colw="{{ k }}">{{ label }}</button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<span class="perf-muted" id="perf-colw-help">{% if colw == 'manual' %}매출 실적·광고비 표 머리글의 오른쪽 경계를 끌어 너비를 바꿉니다(두 번 누르면 그 열만 자동 너비). 바꾼 너비는 계속 유지됩니다.{% else %}열 너비가 글자 길이에 맞춰 자동으로 정해집니다.{% endif %}</span>
|
||||
<button type="button" class="erp-btn erp-btn-ghost erp-btn-sm" id="perf-colw-reset"{% if colw != 'manual' %} hidden{% endif %}>조절한 너비 초기화</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if is_admin %}
|
||||
{# 공통 보기 설정(2026-11-02, 관리자, 마이그레이션 011 perf_settings) — 매출 단위·열 숨기기, 모든 사용자에게 적용 #}
|
||||
<div class="erp-card perf-card" id="perf-shared-view">
|
||||
<div class="perf-card-head">
|
||||
<h2 class="perf-h">공통 보기 설정</h2>
|
||||
<span class="perf-muted">모든 사용자의 매출 실적 화면에 적용됩니다. 고르면 바로 저장됩니다.</span>
|
||||
</div>
|
||||
<div class="perf-opt-row">
|
||||
<span class="perf-opt-label">매출 단위</span>
|
||||
@@ -159,7 +180,17 @@
|
||||
<span class="perf-muted" id="perf-unit-example">예: 2,475,300원 →
|
||||
{% if unit == 'thousand' %}2,475{% elif unit == 'million' %}2.5{% else %}2,475,300{% endif %}</span>
|
||||
</div>
|
||||
<div class="perf-opt-row">
|
||||
<span class="perf-opt-label">숨길 쇼핑몰</span>
|
||||
<div class="perf-hide-list">
|
||||
{% for m in hide_options %}
|
||||
<label class="perf-check"><input type="checkbox" data-hide="{{ m.code }}"{% if m.code in hidden_codes %} checked{% endif %} /> {{ m.name }}</label>
|
||||
{% endfor %}
|
||||
</div>
|
||||
<span class="perf-muted">체크한 쇼핑몰은 일자별 표에서 열만 숨겨집니다. 일 합계·그래프·누적 금액은 그대로입니다.</span>
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{% if is_admin and auto_sync_settings %}
|
||||
{# 자동 업데이트 일정(2026-10-26, 마이그레이션 011 perf_settings) — 매출 실적·광고비 따로: 사용·요일·시작/끝 시각(5분 단위)·간격(5분 단위,
|
||||
@@ -316,4 +347,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261027b" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261102b" defer></script>{% endblock %}
|
||||
|
||||
@@ -125,7 +125,7 @@ def test_ad_dashboard_month():
|
||||
assert ctx["names"]["etc"] == "기타광고비" and ctx["roas_basis"]["etc"] == "" and "etc" not in ads.ROAS_SALES_CODE # 매출 쇼핑몰 없음 = ROAS 없음
|
||||
k = {x["key"]: x for x in ctx["kpis"]}
|
||||
assert k["spend"]["value"] == 270000 and k["ratio"]["pct"] == 10.0 # 270,000 ÷ 2,700,000
|
||||
assert k["ytd"]["value"] == 370000 and k["mtd"]["value"] == 270000
|
||||
assert k["ytd"]["value"] == 370000 and "mtd" not in k # 월 누적 카드 뺌(2026-10-30)
|
||||
assert ctx["upload_cells"] == ["2026-10-01|coupang_rocket"]
|
||||
assert [c["code"] for c in ctx["upload_channels"]] == ["naver", "coupang_wing", "coupang_rocket"]
|
||||
assert ctx["detail_channels"] == ["google", "meta", "naver"] # 구글(2026-10-15)·메타(2026-10-16) = 광고 API 로 가져온 항목
|
||||
|
||||
@@ -6,11 +6,12 @@ import importlib
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.performance import common, dashboard
|
||||
from app.modules.performance.adapters.registry import get_adapter
|
||||
from app.modules.performance.db import SettingsMigrationNeeded
|
||||
|
||||
TODAY = date(2026, 10, 7)
|
||||
|
||||
@@ -36,6 +37,13 @@ class _Store:
|
||||
(date(2026, 10, 6), "custom_a"): 7_000}
|
||||
self.order = None
|
||||
self.deleted = []
|
||||
self.settings = {}
|
||||
|
||||
def get_setting(self, key):
|
||||
return self.settings.get(key)
|
||||
|
||||
def set_setting(self, key, value, *, user=""):
|
||||
self.settings[key] = value
|
||||
|
||||
def list_marketplaces(self):
|
||||
return sorted((dict(r) for r in self.rows), key=lambda r: (r["sort_order"], r["code"]))
|
||||
@@ -113,8 +121,8 @@ def test_dashboard_group_column_sums_children_without_double_count():
|
||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY)
|
||||
assert ctx["codes"] == ["cafe24", "naver", "custom_b", "custom_a", "custom_c"]
|
||||
assert [(c["code"], c["kind"]) for c in ctx["cols"]] == [
|
||||
("cafe24", "shop"), ("naver", "shop"), ("group_x", "group"), ("custom_b", "child"), ("custom_a", "child"),
|
||||
("custom_c", "shop")]
|
||||
("cafe24", "shop"), (dashboard.CAFE24_EX_GB, "diff"), ("naver", "shop"), ("group_x", "group"), ("custom_b", "child"),
|
||||
("custom_a", "child"), ("custom_c", "shop")]
|
||||
assert ctx["group_members"] == {"group_x": ["custom_b", "custom_a"]}
|
||||
assert ctx["names"]["group_x"] == "오프라인"
|
||||
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||
@@ -127,7 +135,7 @@ def test_dashboard_group_column_sums_children_without_double_count():
|
||||
|
||||
def test_dashboard_filter_hides_group_when_no_child_selected():
|
||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["cafe24", "custom_c"])
|
||||
assert [c["code"] for c in ctx["cols"]] == ["cafe24", "custom_c"] and ctx["group_members"] == {}
|
||||
assert [c["code"] for c in ctx["cols"]] == ["cafe24", dashboard.CAFE24_EX_GB, "custom_c"] and ctx["group_members"] == {}
|
||||
ctx = dashboard.build_dashboard(_Store(), kind="week", anchor=TODAY, today=TODAY, selected=["custom_a"])
|
||||
assert [c["kind"] for c in ctx["cols"]] == ["group", "child"]
|
||||
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||
@@ -221,3 +229,154 @@ def test_dashboard_page_renders_group_header_and_child_cells(client):
|
||||
body = html.split("<tbody>", 1)[1].split("</tbody>", 1)[0]
|
||||
assert 'data-group-cell="group_x"' in body and "150,000" in body
|
||||
assert 'data-group-child="group_x" data-manual-code="custom_a" data-date="2026-10-05"' in body
|
||||
|
||||
|
||||
def _real(ctx, date_iso):
|
||||
return next(r for r in ctx["table"] if r.get("date") == date_iso)["cells"][dashboard.CAFE24_EX_GB]
|
||||
|
||||
|
||||
def test_cafe24_real_column():
|
||||
"""카페24(실적) = 카페24(전체) 바로 오른쪽, 카페24 − 자사몰(공동구매). 표 열만 — 일 합계엔 안 더함."""
|
||||
st = _Store()
|
||||
# 공동구매 없음 = 전체 그대로
|
||||
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
|
||||
assert _real(ctx, "2026-10-05")["gross"] == 1_000_000
|
||||
assert ctx["short_names"]["cafe24"] == "카페24(전체)" and ctx["short_names"][dashboard.CAFE24_EX_GB] == "카페24(실적)"
|
||||
|
||||
st._find("custom_c")["name"] = "자사몰 (공동구매)"
|
||||
st._find("custom_c")["parent_code"] = "group_x"
|
||||
st.manual[(date(2026, 10, 5), "custom_c")] = 300_000
|
||||
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
|
||||
assert [c["code"] for c in ctx["cols"]][:2] == ["cafe24", dashboard.CAFE24_EX_GB]
|
||||
assert ctx["cols"][1] == {"code": dashboard.CAFE24_EX_GB, "kind": "diff", "group": "", "base": "cafe24", "minus": "custom_c"}
|
||||
assert _real(ctx, "2026-10-05") == {"gross": 700_000, "commission": 0, "net": 700_000}
|
||||
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||
# 일 합계 = 카페24(실적) 700,000 + 공동구매 300,000 + 매장 150,000 — 카페24(전체) 1,000,000 은 안 더함
|
||||
assert day5["total"] == {"gross": 1_150_000, "commission": 10_000, "net": 1_140_000}
|
||||
week = next(r for r in ctx["table"] if r["kind"] == "week")
|
||||
assert week["cells"][dashboard.CAFE24_EX_GB]["gross"] == 700_000
|
||||
assert week["total"]["gross"] == 1_157_000 # 주간합계도 같은 규칙(매장 157,000)
|
||||
|
||||
# 공동구매를 필터로 빼도 실적에서는 뺀다 — 일 합계 = 실적 + 나머지
|
||||
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY, selected=["cafe24"])
|
||||
assert _real(ctx, "2026-10-05")["gross"] == 700_000
|
||||
assert next(r for r in ctx["table"] if r.get("date") == "2026-10-05")["total"]["gross"] == 700_000
|
||||
# 카페24 를 고르지 않으면 열 없음, 일 합계에 공동구매 그대로
|
||||
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY, selected=["custom_c"])
|
||||
assert dashboard.CAFE24_EX_GB not in [c["code"] for c in ctx["cols"]]
|
||||
assert next(r for r in ctx["table"] if r.get("date") == "2026-10-05")["total"]["gross"] == 300_000
|
||||
|
||||
|
||||
def test_summaries_match_day_total():
|
||||
"""KPI·추이·비중·월/연 누적도 일 합계와 같은 기준 — 공동구매가 두 번 안 들어감, 카페24 줄 = 카페24(실적)."""
|
||||
st = _Store()
|
||||
st._find("custom_c")["name"] = "자사몰(공동구매)"
|
||||
st.manual[(date(2026, 10, 5), "custom_c")] = 300_000
|
||||
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
|
||||
week_total = next(r for r in ctx["table"] if r["kind"] == "week")["total"]
|
||||
assert week_total["gross"] == 1_157_000 # 카페24(전체) 1,000,000 + 매장 157,000
|
||||
assert ctx["kpis"][0]["value"] == week_total["net"]
|
||||
assert next(p for p in ctx["chart_daily"] if p["date"] == "2026-10-05")["gross"] == 1_150_000
|
||||
assert sum(s["gross"] for s in ctx["chart_share"]) == 1_157_000
|
||||
assert next(s for s in ctx["chart_share"] if s["code"] == "cafe24")["name"] == "카페24(실적)"
|
||||
assert ctx["month"]["total"]["gross"] == 1_157_000 and ctx["year"]["total"]["gross"] == 1_157_000
|
||||
assert next(r for r in ctx["month"]["rows"] if r["code"] == "cafe24")["gross"] == 700_000
|
||||
assert ctx["year"]["rows"][9]["gross"] == 1_157_000
|
||||
# 카페24(전체) 열은 원래 값 그대로, 공동구매 열도 그대로
|
||||
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||
assert day5["cells"]["cafe24"]["gross"] == 1_000_000 and day5["cells"]["custom_c"]["gross"] == 300_000
|
||||
|
||||
|
||||
def test_total_sales_codes_drops_groupbuy_only_with_cafe24():
|
||||
m = lambda c, n: {"code": c, "name": n} # noqa: E731
|
||||
assert dashboard.total_sales_codes([m("cafe24", "카페24"), m("x", "자사몰 (공동구매)"), m("y", "네이버")]) == ["cafe24", "y"]
|
||||
assert dashboard.total_sales_codes([m("x", "자사몰(공동구매)"), m("y", "네이버")]) == ["x", "y"]
|
||||
assert dashboard.total_sales_codes([m("cafe24", "카페24"), m("y", "네이버")]) == ["cafe24", "y"]
|
||||
|
||||
|
||||
def test_day_total_roas_uses_real_total():
|
||||
"""일 합계 ROAS = 일 합계 금액(공동구매 중복 없음) ÷ 일 합계 광고비."""
|
||||
st = _Store()
|
||||
st._find("custom_c")["name"] = "자사몰(공동구매)"
|
||||
st.manual[(date(2026, 10, 5), "custom_c")] = 300_000
|
||||
st.ad_amounts = lambda s, e: ({(date(2026, 10, 5), "google"): 115_000}, {})
|
||||
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
|
||||
day5 = next(r for r in ctx["table"] if r.get("date") == "2026-10-05")
|
||||
assert day5["ads_total"]["amount"] == 115_000 and day5["ads_total"]["roas"] == 1000 # 1,150,000 ÷ 115,000
|
||||
|
||||
|
||||
def test_hidden_columns_only_hide_table_columns():
|
||||
"""열 숨기기(모든 사용자 공통 설정) — 열만 숨김, 일 합계·그래프 그대로. 하위를 다 숨기면 그룹 열도 없음."""
|
||||
st = _Store()
|
||||
st.settings[dashboard.HIDDEN_SETTING] = ["cafe24", "custom_a", "custom_b"]
|
||||
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
|
||||
assert [c["code"] for c in ctx["cols"]] == [dashboard.CAFE24_EX_GB, "naver", "custom_c"]
|
||||
assert _real(ctx, "2026-10-05")["gross"] == 1_000_000 # 전체를 숨겨도 실적은 계산됨
|
||||
assert next(r for r in ctx["table"] if r.get("date") == "2026-10-05")["total"]["gross"] == 1_150_000
|
||||
assert ctx["codes"] == ["cafe24", "naver", "custom_b", "custom_a", "custom_c"]
|
||||
st.settings[dashboard.HIDDEN_SETTING] = [dashboard.CAFE24_EX_GB]
|
||||
ctx = dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)
|
||||
assert dashboard.CAFE24_EX_GB not in [c["code"] for c in ctx["cols"]]
|
||||
|
||||
|
||||
def test_hidden_setting_missing_migration_shows_everything():
|
||||
st = _Store()
|
||||
|
||||
def raises(key):
|
||||
raise SettingsMigrationNeeded()
|
||||
|
||||
st.get_setting = raises
|
||||
assert dashboard.load_hidden(st) == set()
|
||||
assert "naver" in [c["code"] for c in dashboard.build_dashboard(st, kind="week", anchor=TODAY, today=TODAY)["cols"]]
|
||||
|
||||
|
||||
def test_api_hidden_marketplaces(client):
|
||||
"""저장값이 그대로 다른 사용자 화면에도 — 쿠키가 아니라 서버 설정(모르는 코드는 버림)."""
|
||||
r = client.put("/performance/api/hidden-marketplaces", json={"codes": ["naver", "ghost", dashboard.CAFE24_EX_GB, "naver"]})
|
||||
assert r.status_code == 200 and r.json()["codes"] == [dashboard.CAFE24_EX_GB, "naver"]
|
||||
assert client.store.settings[dashboard.HIDDEN_SETTING] == [dashboard.CAFE24_EX_GB, "naver"]
|
||||
head = TestClient(client.app).get("/performance/?period=week&d=2026-10-07").text.split("<thead>", 1)[1].split("</thead>", 1)[0]
|
||||
assert 'data-col="naver"' not in head and 'data-col="cafe24"' in head
|
||||
assert client.put("/performance/api/hidden-marketplaces", json={"codes": "naver"}).status_code == 400
|
||||
assert client.put("/performance/api/hidden-marketplaces", json={"codes": []}).json()["codes"] == []
|
||||
|
||||
def raises(key, value, *, user=""):
|
||||
raise SettingsMigrationNeeded()
|
||||
|
||||
client.store.set_setting = raises
|
||||
assert client.put("/performance/api/hidden-marketplaces", json={"codes": []}).status_code == 503
|
||||
|
||||
|
||||
def test_api_hidden_marketplaces_admin_only(client, monkeypatch):
|
||||
def require_store(request, admin=False):
|
||||
if admin:
|
||||
raise HTTPException(status_code=403)
|
||||
return client.store, {"email": "u@x"}
|
||||
|
||||
monkeypatch.setattr(common, "require_store", require_store)
|
||||
assert client.put("/performance/api/hidden-marketplaces", json={"codes": ["naver"]}).status_code == 403
|
||||
assert dashboard.HIDDEN_SETTING not in client.store.settings
|
||||
|
||||
|
||||
def test_dashboard_page_renders_cafe24_real(client):
|
||||
client.store._find("custom_c")["name"] = "자사몰(공동구매)"
|
||||
client.store.manual[(date(2026, 10, 5), "custom_c")] = 300_000
|
||||
client.store.settings[dashboard.HIDDEN_SETTING] = ["naver"]
|
||||
html = client.get("/performance/?period=week&d=2026-10-07").text
|
||||
head = html.split("<thead>", 1)[1].split("</thead>", 1)[0]
|
||||
# 날짜 → 일 합계 → 카페24(전체) → 카페24(실적)
|
||||
assert head.index('data-col="label"') < head.index('data-col="total"') < head.index('data-col="cafe24"') < head.index(f'data-col="{dashboard.CAFE24_EX_GB}"')
|
||||
assert "카페24(전체)" in head and "카페24(실적)" in head and 'data-col="naver"' not in head
|
||||
body = html.split("<tbody>", 1)[1].split("</tbody>", 1)[0]
|
||||
assert "700,000" in body
|
||||
# 일 행만 화면 즉시 계산용 값(카페24 총매출,수수료,차감) — performance.js saveManual
|
||||
assert 'data-diff-minus="custom_c" data-base="1000000,0,1000000"' in body
|
||||
|
||||
|
||||
def test_cafe24_real_shows_same_ad_lines(client):
|
||||
"""카페24(전체)의 구글·메타 광고비 줄이 카페24(실적) 칸에도 그대로."""
|
||||
client.store.ad_amounts = lambda s, e: ({(date(2026, 10, 5), "google"): 11_000, (date(2026, 10, 5), "meta"): 22_000}, {})
|
||||
body = client.get("/performance/?period=week&d=2026-10-07").text.split("<tbody>", 1)[1]
|
||||
row = next(tr for tr in body.split("<tr ") if 'data-date="2026-10-05"' in tr)
|
||||
assert row.count("<i>구글</i>11,000") == 2 and row.count("<i>메타</i>22,000") == 2
|
||||
assert row.index("<i>구글</i>") < row.index("data-code=\"naver\"")
|
||||
|
||||
@@ -121,15 +121,51 @@ def test_dashboard_page_renders_unit_and_ad_lines(monkeypatch):
|
||||
assert 'class="perf-adl"' in html and "<i>구글</i>100,000<em>(413%)</em>" in html and "<i>메타</i>50,000" in html
|
||||
assert "200,000<em>(300%)</em>" in html and "단위:" not in html
|
||||
|
||||
client.cookies.set("perf_unit", "thousand")
|
||||
# 매출 단위 = 서버 공통 설정(2026-11-02) — 예전 브라우저 쿠키는 안 봄
|
||||
client.cookies.set("perf_unit", "million")
|
||||
assert "단위:" not in client.get("/performance/?period=week&d=2026-10-07").text
|
||||
client.cookies.delete("perf_unit")
|
||||
store.get_setting = lambda key: "thousand" if key == dashboard.UNIT_SETTING else None
|
||||
html = client.get("/performance/?period=week&d=2026-10-07").text
|
||||
assert "단위: 천원" in html and "2,000<" in html and "<i>구글</i>100<em>(413%)</em>" in html
|
||||
assert "2,000,000<" not in html.split("perf-main", 1)[1].split("</table>", 1)[0]
|
||||
client.cookies.set("perf_unit", "million")
|
||||
store.get_setting = lambda key: "million" if key == dashboard.UNIT_SETTING else None
|
||||
html = client.get("/performance/?period=week&d=2026-10-07").text
|
||||
assert "단위: 백만원" in html and ">2.0<" in html and '"unit": "million"' in html
|
||||
|
||||
|
||||
def test_api_display_unit(monkeypatch):
|
||||
import importlib
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.performance import common
|
||||
|
||||
perf_router = importlib.import_module("app.modules.performance.router")
|
||||
saved = {}
|
||||
store = _Store()
|
||||
store.set_setting = lambda key, value, *, user="": saved.__setitem__(key, (value, user))
|
||||
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (store, {"email": "king@x"}))
|
||||
app = FastAPI()
|
||||
app.include_router(perf_router.router)
|
||||
client = TestClient(app)
|
||||
|
||||
assert client.put("/performance/api/display-unit", json={"unit": "thousand"}).json()["unit"] == "thousand"
|
||||
assert saved[dashboard.UNIT_SETTING] == ("thousand", "king@x")
|
||||
assert client.put("/performance/api/display-unit", json={"unit": "nope"}).status_code == 400
|
||||
assert client.put("/performance/api/display-unit", json={"unit": ["won"]}).status_code == 400
|
||||
|
||||
def not_admin(request, admin=False):
|
||||
if admin:
|
||||
raise HTTPException(status_code=403)
|
||||
return store, {"email": "u@x"}
|
||||
|
||||
monkeypatch.setattr(common, "require_store", not_admin)
|
||||
assert client.put("/performance/api/display-unit", json={"unit": "won"}).status_code == 403
|
||||
assert saved[dashboard.UNIT_SETTING] == ("thousand", "king@x")
|
||||
|
||||
|
||||
def test_total_roas_uses_whole_day_total():
|
||||
"""일 합계 ROAS = 그날 일 합계 금액(광고비 없는 쇼핑몰 매출 포함) ÷ 일 합계 광고비 — 예전엔 광고비 있는 쇼핑몰 매출만 더했다."""
|
||||
class _S(_Store):
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
"""화면 자동 새로 고침(2026-10-26) — 자동 업데이트가 끝나면 매출 실적·광고비 화면이 알아채도록:
|
||||
jobs.last_finished(종류별·보는 사람 것 제외) · GET /api/update-status · 화면 데이터 update_watch."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from fastapi import FastAPI
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app.modules.performance import auto_sync, common, jobs
|
||||
|
||||
perf_router = importlib.import_module("app.modules.performance.router")
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def clean_jobs(monkeypatch):
|
||||
monkeypatch.setattr(jobs, "_JOBS", {})
|
||||
|
||||
|
||||
def _job(kind="sales", user=auto_sync.AUTO_USER, finished=True, at=None):
|
||||
j = jobs.create_job(user=user, start=None, end=None, kind=kind)
|
||||
if finished:
|
||||
j.finish()
|
||||
if at is not None:
|
||||
j.finished_at = at
|
||||
return j
|
||||
|
||||
|
||||
def test_last_finished_by_kind_and_excludes_viewer():
|
||||
assert jobs.last_finished("sales") is None
|
||||
a = _job(at=time.time() - 100)
|
||||
b = _job(user="me@x", at=time.time() - 10) # 보는 사람이 누른 것 — 진행 창이 알아서 새로 그림
|
||||
ad = _job(kind="ads", at=time.time())
|
||||
_job(finished=False) # 도는 중인 작업은 아님
|
||||
assert jobs.last_finished("sales") is b
|
||||
assert jobs.last_finished("sales", exclude_user="me@x") is a
|
||||
assert jobs.last_finished("ads", exclude_user="me@x") is ad
|
||||
assert perf_router._update_watch("sales", {"email": "me@x"}) == {"kind": "sales", "seen": a.id}
|
||||
assert perf_router._update_watch("ads", {"email": "other@x"}) == {"kind": "ads", "seen": ad.id}
|
||||
|
||||
|
||||
def test_update_status_api(monkeypatch):
|
||||
monkeypatch.setattr(common, "require_store", lambda request, admin=False: (object(), {"email": "me@x"}))
|
||||
app = FastAPI()
|
||||
app.include_router(perf_router.router)
|
||||
c = TestClient(app)
|
||||
assert c.get("/performance/api/update-status?kind=sales").json() == {"kind": "sales", "running": False, "done": "", "user": ""}
|
||||
run = _job(finished=False)
|
||||
r = c.get("/performance/api/update-status?kind=sales").json()
|
||||
assert r["running"] and r["done"] == ""
|
||||
run.finish()
|
||||
r = c.get("/performance/api/update-status?kind=sales").json()
|
||||
assert r == {"kind": "sales", "running": False, "done": run.id, "user": auto_sync.AUTO_USER}
|
||||
_job(user="me@x") # 내 업데이트는 done 을 바꾸지 않는다
|
||||
assert c.get("/performance/api/update-status?kind=sales").json()["done"] == run.id
|
||||
assert c.get("/performance/api/update-status?kind=ads").json()["done"] == "" # 광고비는 따로
|
||||
assert c.get("/performance/api/update-status?kind=nope").status_code == 404
|
||||
@@ -51,6 +51,10 @@
|
||||
- 보드는 아사나처럼 섹션이 가로로 계속 늘어나고(넘치면 가로 스크롤) 카드의 담당자·마감일을 클릭해 그 자리에서 바꾼다.
|
||||
- 보드 카드 끌기 = 실시간 미리보기(2026-10-19, `startCardDrag`·`placeCardPh`): 원래 카드는 숨기고 점선 자리 표시(`.pj-card-ph`)가 카드 사이로 FLIP 애니메이션, 끄는 모양은 기울어진 복제(`setDragImage`). 놓은 자리 그대로 — 다른 섹션도 PUT stage 뒤 `stages/{id}/tasks/order`(정렬 "기본"일 때만, 전체 보기는 섹션 맨 끝).
|
||||
**필터를 켜도 순서 변경 가능**(2026-10-19 버그 수정 — 필터는 브라우저별 localStorage `pj_filter_<id>` 라 필터를 켜 둔 컴퓨터에서만 섹션 안 카드가 늘 제자리로 돌아갔다). 숨은 업무는 제자리(`orderWithHidden`). 카드 속 이미지 끌기가 "Files" 로 오인돼 카드 놓기를 가로채지 않게 `dragHasFiles` 는 카드·세부 업무 끌기 중 false, 카드 img 는 `-webkit-user-drag: none`. 끄는 중엔 실시간 동기화 쉼(`html.pj-card-dragging`). 컬럼 body 는 dragenter 도 preventDefault(안 하면 자리 표시가 들어온 직후 놓을 때 drop 거부).
|
||||
**연결 업무(● 다른 프로젝트 카드)도 순서 저장**(2026-10-30 버그 수정, 마이그레이션 032 `task_project_links.sort_order`) — 예전엔 연결 카드가 원 소속
|
||||
`tasks.sort_order` 로 줄을 서고 `db.reorder_tasks` 가 `tasks.stage_id = 섹션` 인 업무만 고쳐, 실시간 동기화로 다시 받으면 카드가 제자리로 돌아갔다.
|
||||
이제 `reorder_tasks` 가 연결 행 순서도 저장, `list_tasks_for_projects` 는 연결 행을 `COALESCE(l.sort_order, 원 소속 순서)` 로 정렬(`db.link_order_ready`, 032 미적용이면 예전 그대로).
|
||||
연결 카드를 다른 섹션으로 옮길 때도 놓은 자리 저장. 테스트 `tests/test_project_module.py test_reorder_keeps_linked_card_position`(실제 PG).
|
||||
- 사이드바 전체 검색(`/api/search`, 제목·설명·댓글, pg_trgm) + 프로젝트/내 작업 필터 바(찾기·상태·담당자·마감·우선순위·정렬, 클라이언트 필터).
|
||||
- 대시보드: "업무 합계(프로젝트별)" 카드, 섹션별 카드 삭제, 대시보드 업무 목록 패널에서 연 업무 창은 패널 왼쪽에(6-16·6-17·6-19).
|
||||
- 담당자별 패널 날짜 mm/dd(요일)·지난 마감 빨강(6-20).
|
||||
@@ -76,6 +80,10 @@
|
||||
- **업무를 옮기면 드라이브 파일도 이동**(2026-10-20): 섹션·프로젝트·상위 업무가 바뀌면(`api_update_task`·`move-parent`·`move-project`, `_drive_path_changed`) 백그라운드 `_relocate_drive_files` 가 업무+하위 전체(`db.task_subtree_ids`)의 설명 링크 파일을 새 폴더로(`GoogleDriveFiles.move_to` — appProperties `dbxTaskId` 가 그 업무인 파일만). 제목 변경은 안 옮김, 예전 폴더는 남김.
|
||||
- 그 밖의 업무 창 자리 → 예전처럼 첨부(`POST …/attachments`, `uploadTaskFiles`).
|
||||
- 설명란 서식 도구에 글자 색·크기(서버는 span style 의 color·font-size 만 허용, `desc_inline_style`). 주소 붙여넣기 시 자동 링크. 설명란 링크 = 굵게·기울임·밑줄 + 한 글자처럼(2026-10-19 — `normalizeEditorLinks` 가 `contenteditable=false`, 링크 바로 뒤 Backspace·앞 Delete = 링크 통째로 `execCommand delete`(Ctrl+Z 가능), 저장 HTML 에선 `getHtml` 이 잠금 표시를 뺀다). 설명란 이미지 더블클릭 = 별도 창 이미지 보기(확대·축소·끌어 이동).
|
||||
**링크 서식 = 크기·굵기만**(2026-10-30) — 잠긴 링크라 execCommand 가 안에 안 들어가, 고른 범위에 걸친 링크는 링크 안쪽 `<span style>` 하나로(`setLinkStyle`):
|
||||
크기 = 글자 크기 도구 그대로, 굵기 = 굵게 버튼·Ctrl+B(`boldWithLinks` — 링크 기본이 굵게라 "보통" = `font-weight: 400`, 서버 `desc_inline_style` 은 400 만 받음).
|
||||
글자와 같이 고르면 execCommand 가 글자에 만든 굵기를 따름(잠긴 링크가 끼면 queryCommandState 가 틀려 글자 노드 계산값으로). 링크 서식 변경은 Ctrl+Z 안 됨.
|
||||
테스트 `tests/js/board_drive.browser.test.js` 6), `tests/test_project_icons_desc_style.py`.
|
||||
- 설명란·댓글에서 @로 멤버 태그(`task_mentions`, 마이그레이션 006) → 수신함에 그 작업이 쌓임. 댓글 `@아이디` 는 아이콘+이름 칩.
|
||||
- 댓글·답글 입력칸은 Enter 등록·Shift+Enter 줄바꿈(textarea).
|
||||
- 댓글 답글·이모티콘 반응(마이그레이션 012 `task_comments.parent_id`·`task_comment_reactions`, 미적용 시 버튼 숨김·API 503). 반응 = 댓글 쓴 사람에게 알림(`type=reaction`).
|
||||
|
||||
@@ -578,6 +578,8 @@ class ProjectStore:
|
||||
if assignee_email:
|
||||
extra = "AND t.assignee_email = %(assignee)s"
|
||||
params["assignee"] = store.norm_str(assignee_email, lower=True)
|
||||
# 연결 행 순서 = 이 프로젝트에서 옮긴 자리(032), 아직 안 옮겼거나 032 미적용이면 원 소속 순서
|
||||
link_ord = "COALESCE(l.sort_order, lt.sort_order)" if self.link_order_ready() else "lt.sort_order"
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
f"""
|
||||
@@ -592,11 +594,11 @@ class ProjectStore:
|
||||
CASE WHEN x.is_linked THEN x.link_stage_id ELSE t.stage_id END AS stage_id
|
||||
FROM (
|
||||
SELECT id AS task_id, project_id AS context_project_id,
|
||||
FALSE AS is_linked, NULL::bigint AS link_stage_id
|
||||
FALSE AS is_linked, NULL::bigint AS link_stage_id, sort_order AS ord
|
||||
FROM tasks
|
||||
WHERE parent_task_id IS NULL AND project_id = ANY(%(ids)s)
|
||||
UNION ALL
|
||||
SELECT l.task_id, l.project_id, TRUE, l.stage_id
|
||||
SELECT l.task_id, l.project_id, TRUE, l.stage_id, {link_ord}
|
||||
FROM task_project_links l
|
||||
JOIN tasks lt ON lt.id = l.task_id
|
||||
WHERE l.project_id = ANY(%(ids)s)
|
||||
@@ -608,7 +610,7 @@ class ProjectStore:
|
||||
LEFT JOIN project_stages s ON s.id = t.stage_id
|
||||
LEFT JOIN project_stages es ON es.id = x.link_stage_id
|
||||
WHERE TRUE {extra}
|
||||
ORDER BY x.context_project_id, t.sort_order ASC, t.id ASC
|
||||
ORDER BY x.context_project_id, x.ord ASC, t.id ASC
|
||||
LIMIT %(limit)s
|
||||
""",
|
||||
params,
|
||||
@@ -1734,6 +1736,27 @@ class ProjectStore:
|
||||
"WHERE t.id = v.id AND t.stage_id = %s",
|
||||
([int(i) for i in ordered_ids], stage_id),
|
||||
)
|
||||
# 연결 업무(다른 프로젝트 카드)는 tasks.stage_id 가 원 소속 섹션이라 위에서 안 바뀐다 — 연결별 순서(032)에.
|
||||
# 예전엔 저장 안 돼 실시간 동기화 때 카드가 제자리로 돌아갔다(2026-10-30).
|
||||
if self.link_order_ready():
|
||||
conn.execute(
|
||||
"UPDATE task_project_links l SET sort_order = v.ord - 1 "
|
||||
"FROM unnest(%s::bigint[]) WITH ORDINALITY AS v(id, ord) "
|
||||
"WHERE l.task_id = v.id AND l.stage_id = %s",
|
||||
([int(i) for i in ordered_ids], stage_id),
|
||||
)
|
||||
|
||||
def link_order_ready(self) -> bool:
|
||||
"""task_project_links.sort_order(마이그레이션 032) 가 있는지. 한 번 켜지면 기억."""
|
||||
if getattr(self, "_link_order_ready", False):
|
||||
return True
|
||||
with self._pool.connection() as conn:
|
||||
ok = bool(conn.execute(
|
||||
"SELECT 1 FROM information_schema.columns WHERE table_schema = 'public' "
|
||||
"AND table_name = 'task_project_links' AND column_name = 'sort_order'"
|
||||
).fetchone())
|
||||
self._link_order_ready = ok
|
||||
return ok
|
||||
|
||||
def reorder_subtasks(self, *, parent_task_id: int, ordered_ids: list[int]) -> None:
|
||||
"""작업 팝업의 세부 작업 목록 드래그 재정렬 — 이 상위 작업의 세부 작업만
|
||||
|
||||
@@ -89,13 +89,11 @@ def _require_user(request: Request) -> dict[str, Any]:
|
||||
def _page_user(request: Request) -> Any:
|
||||
"""화면(HTML) 주소용 — 로그인 전이면 오류 JSON 대신 로그인 화면으로 보냈다가 이 주소로 되돌아온다
|
||||
(공유한 회의록·업무 링크를 로그인 안 된 브라우저에서 열 때, 2026-10-14). 로그인했으면 _require_user 와 같다."""
|
||||
from urllib.parse import quote # noqa: WPS433
|
||||
|
||||
from app.main import get_current_user_record # noqa: WPS433
|
||||
from app.store import login_redirect # noqa: WPS433
|
||||
|
||||
if get_current_user_record(request) is None:
|
||||
here = str(request.url.path) + ("?" + request.url.query if request.url.query else "")
|
||||
return RedirectResponse(url="/login?next=" + quote(here, safe=""), status_code=303)
|
||||
return login_redirect(request)
|
||||
return _require_user(request)
|
||||
|
||||
|
||||
@@ -2948,12 +2946,10 @@ def notifier_download(request: Request) -> Any:
|
||||
def notifier_page(request: Request) -> Any:
|
||||
"""PC 알림 프로그램 — 연결 승인(?code=)·연결된 PC 목록·내려받기."""
|
||||
from app.main import DATA_DIR, build_erp_nav, get_current_user_record, render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
from urllib.parse import quote # noqa: WPS433
|
||||
from app.store import is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
if get_current_user_record(request) is None:
|
||||
return RedirectResponse(url="/login?next=" + quote(str(request.url.path) + (
|
||||
"?" + request.url.query if request.url.query else ""), safe=""), status_code=303)
|
||||
return login_redirect(request)
|
||||
user = _require_user(request)
|
||||
st = _store(request)
|
||||
if st is None:
|
||||
|
||||
@@ -973,6 +973,9 @@ def desc_inline_style(value: str) -> str:
|
||||
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}")
|
||||
# 링크 굵기 "보통"(2026-10-30) — 링크 기본이 굵게라 보통으로 되돌릴 때만 쓴다(굵게는 값 없음)
|
||||
elif prop == "font-weight" and val in ("400", "normal") and not any(k.startswith("font-weight:") for k in kept):
|
||||
kept.append("font-weight: 400")
|
||||
return "; ".join(kept)
|
||||
|
||||
|
||||
|
||||
@@ -289,5 +289,5 @@
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261026a" defer></script>
|
||||
<script src="/static/project-meeting-cells.js?v=20261012a" defer></script>
|
||||
<script src="/static/project.js?v=20261027a" defer></script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -207,5 +207,5 @@
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project-goal-text.js?v=20261026a" defer></script>
|
||||
<script src="/static/project.js?v=20261027a" defer></script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -106,5 +106,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261027a" defer></script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -100,5 +100,5 @@
|
||||
"today": {{ today | tojson }}
|
||||
}
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261027a" defer></script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -108,5 +108,5 @@
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
<script src="/static/project.js?v=20261027a" defer></script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -476,5 +476,5 @@
|
||||
</script>
|
||||
|
||||
<script src="/static/vendor/vis-timeline/vis-timeline-graph2d.min.js"></script>
|
||||
<script src="/static/project.js?v=20261027a" defer></script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -70,5 +70,5 @@
|
||||
{% include "project/_side_modals.html" %}
|
||||
{% include "project/_member_tasks_modal.html" %}
|
||||
|
||||
<script src="/static/project.js?v=20261027a" defer></script>
|
||||
<script src="/static/project.js?v=20261030b" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -6,11 +6,26 @@
|
||||
- 월간 달력(구글식 bar) / 연차·반차 신청 / 승인 워크플로 / 옵션(승인자·통보자·잔여 연차).
|
||||
- **설정 화면 없음**(2026-10-27 삭제 — [설정] 버튼·공휴일 추가/삭제 기능 포함). `GET /vacation/settings` 는 옵션으로 넘김, 공휴일 저장 주소 없음.
|
||||
- 권한키 `vacation`(사용)·`vacation_approver`(승인).
|
||||
- **신청 화면 날짜 칸 = 프로젝트와 같은 아사나식 날짜 팝업**(2026-10-27, 공용 `app/static/erp-datepop.js`·`.css` — project.js `openDatePopover`·
|
||||
`enhanceDateInput` 을 떼어 낸 것). 시작일·종료일 input 은 숨긴 값 저장소, 옆 날짜 버튼 둘(`ErpDatePop.enhanceRange`) — 어느 쪽을 눌러도 같은
|
||||
기간 팝업(누른 칸이 먼저, 시작일 고르면 종료일 칸으로, 종료일 고르면 닫힘, 지우기 없음), 반차는 하루짜리 팝업(시작=종료). 직접 입력(10/27·1027 Enter).
|
||||
공휴일 = 국경일·대체공휴일(`router._red_holidays` → `db.holiday_map`, 작년~내년, `#vac-holidays`) — 팝업 빨강·이름 + 예상 일수에서도 뺀다(서버 compute_days 와 같은 표).
|
||||
테스트 `tests/js/vacation_datepop.browser.test.js`(`render_vacation.py`).
|
||||
- **신청 화면**(2026-11-02, `form.html`) = 위 휴가 종류 라디오(고르면 검은 배경·흰 굵은 글씨) · 왼쪽 붙박이 달력(공용 `ErpDatePop.mountRange` — 팝업과 같은 `.pj-dp-*` 서식,
|
||||
첫 클릭 시작일·둘째 클릭 종료일·셋째 새로, 하루 = 동그라미, 기간 = 둥근 막대, 반차 = 클릭마다 하루) · 오른쪽 시작일·종료일(읽기 전용, 달력이 채움)·구분·예상 일수·사유 · 아래 결재 라인.
|
||||
하루짜리는 종료 구분을 숨기고 보내지 않는다(서버 compute_days 도 시작 구분만 씀). 시작일·종료일 숨긴 칸은 브라우저 필수 검사가 안 돼 `vacation.js` 가 제출 전 확인.
|
||||
공휴일 = 국경일·대체공휴일(`router._red_holidays` → `db.holiday_map`, 작년~내년, `#vac-holidays`) — 달력 빨강·이름(10.5px, 달력 폭 380px 라야 "석가탄신일"이 안 잘림) + 예상 일수에서도 뺀다(서버 compute_days 와 같은 표).
|
||||
옵션의 입사일 버튼은 그대로 `ErpDatePop.enhance`(팝업). 테스트 `tests/js/vacation_datepop.browser.test.js`(`render_vacation.py`).
|
||||
|
||||
## 협의자 결재 (2026-11-02, 마이그레이션 `vacation_db_003_consults.sql`)
|
||||
|
||||
- 흐름: 작성중 → (협의자 있으면) **협의중** → 모두 승인 → **제출**(결재자 승인 대기) → 승인. 협의자 한 명이 반려하면 신청도 반려(`approver_email` = 그 협의자). 수정·재제출하면 협의가 처음부터(`db.submit`).
|
||||
협의중에는 결재자가 승인·반려 못 함(`approve`·`reject` 가 status='제출' 만). 일수·연차 차감은 그대로 승인 때만. 마지막 두 명 동시 처리는 `decide_consult` 가 신청 줄을 잠가 막음.
|
||||
- 표 `vacation_consults`(신청 삭제 시 CASCADE) — 이메일·이름·협의 내용·상태 대기|승인|반려·반려 사유·처리 시각. 003 전이면 `consults_ready()` False → 협의자 칸 잠김, 예전처럼 제출.
|
||||
- 신청 화면: [구성원 선택] = **ERP 등록 구성원 전체**(`router._people`, 휴가 권한 무관, 본인 제외) 아이콘 + 이름, 복수. 고른 사람마다 협의 내용 칸(`consult_email`·`consult_message` 같은 순서 — 빈 내용도 자리 유지).
|
||||
[협의자 없음] 체크 = 칸 잠김·전송 안 함. 제출인데 둘 다 없으면 400(작성중 저장은 통과). 통보자·결재자 = 옵션 값, 아이콘 + 이름 표시만.
|
||||
- 메일(`notify.py`): 제출 = 협의자마다 따로 한 통(자기 내용만, `consult_request`) + 결재자·통보자(전체 협의자·내용). 모두 승인 = `consulted`(결재자·통보자·신청자). 협의 반려 = `rejected`. 한 명 승인만으로는 메일 없음.
|
||||
- 화면: 달력 위 [내 신청 내역] `/vacation/mine`(협의자별 상태 → 결재 상태), [협의 대기 N] → `/vacation/pending#consults`(이 화면은 이제 누구나, 승인 대기 표는 결재자만, 표에 협의 내용).
|
||||
상세 = 결재 진행·협의자별 내용·협의 승인/반려. **보기 권한**: 신청자·결재자·통보자 = 전체, 협의자 = 자기 줄만(서버가 거름, 메일 기록도 안 보임).
|
||||
- **휴가 권한 없는 협의자**: 사이드바에 휴가 메뉴가 없어 메일 링크로 상세(`_guard(consult_of=…)`)에 들어와 처리한다. 달력·내역·대기 화면은 권한이 있어야 함.
|
||||
- **메일 실패 → Gmail 연결·다시 보내기**(2026-11-02): 처리는 먼저 저장(메일 때문에 결재가 막히지 않음). Gmail 미연결이면 `_notify` 가 메일을 바로 시도해 실패 기록을 남기고, 상세 위에 안내(`router._failed_mail` — 그 신청의 마지막 메일이 내가 보내다 실패한 것이고 상태가 그대로일 때, 협의자·신청자·결재자 공통).
|
||||
[Gmail 연결] → `/vacation/gmail/connect?next=/vacation/{id}` → 구글 → 상세로 복귀 → [메일 다시 보내기] `POST /vacation/{id}/mail-retry`. 협의자는 휴가 권한이 없어도 연결(세션 `_gmail_consultant`, 콜백은 `inout/router.py`). 다시 보낼 때 이미 처리한 협의자에게는 협의 요청을 안 보냄.
|
||||
- 테스트 `tests/test_vacation_options_mail.py`(메일 내용·폼·권한), `tests/test_vacation_db.py`(실제 PG 흐름).
|
||||
|
||||
## 공휴일 · 연차 (2026-10-27)
|
||||
|
||||
|
||||
+101
-11
@@ -337,15 +337,96 @@ class VacationDBStore:
|
||||
).fetchone()
|
||||
return self._req_serialize(row) if row else None
|
||||
|
||||
# ── 협의자(마이그레이션 003, 2026-11-02) — 테이블이 없으면 협의자 없음 ──
|
||||
def consults_ready(self) -> bool:
|
||||
with self._pool.connection() as conn:
|
||||
row = conn.execute("SELECT to_regclass('public.vacation_consults') AS r").fetchone()
|
||||
return bool(row and row["r"])
|
||||
|
||||
@staticmethod
|
||||
def _consult_serialize(row: dict[str, Any]) -> dict[str, Any]:
|
||||
out = dict(row)
|
||||
if isinstance(out.get("decided_at"), datetime):
|
||||
out["decided_at"] = out["decided_at"].astimezone(KST).isoformat(timespec="seconds")
|
||||
return out
|
||||
|
||||
def consults_for(self, request_ids: list[str]) -> dict[str, list[dict[str, Any]]]:
|
||||
"""{신청 id: [협의자…]} — 지정한 순서대로."""
|
||||
if not request_ids or not self.consults_ready():
|
||||
return {}
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute("SELECT * FROM vacation_consults WHERE request_id = ANY(%s) ORDER BY id",
|
||||
(list(request_ids),)).fetchall()
|
||||
out: dict[str, list[dict[str, Any]]] = {}
|
||||
for r in rows:
|
||||
out.setdefault(r["request_id"], []).append(self._consult_serialize(r))
|
||||
return out
|
||||
|
||||
def list_consults(self, *, request_id: str) -> list[dict[str, Any]]:
|
||||
return self.consults_for([request_id]).get(request_id, [])
|
||||
|
||||
def my_consults(self, *, email: str) -> list[dict[str, Any]]:
|
||||
"""내 협의 차례인 신청(협의중 + 내 줄 대기) — 시작일 순, 줄마다 my_message."""
|
||||
if not self.consults_ready():
|
||||
return []
|
||||
with self._pool.connection() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT r.*, c.message AS my_message FROM vacation_consults c JOIN vacation_requests r ON r.id = c.request_id "
|
||||
"WHERE c.email = %s AND c.state = '대기' AND r.status = '협의중' ORDER BY r.start_date, r.created_at",
|
||||
(email.lower().strip(),)).fetchall()
|
||||
return [self._req_serialize(r) for r in rows]
|
||||
|
||||
@staticmethod
|
||||
def _replace_consults(conn: Any, request_id: str, consults: list[dict[str, Any]]) -> None:
|
||||
conn.execute("DELETE FROM vacation_consults WHERE request_id = %s", (request_id,))
|
||||
for c in consults:
|
||||
conn.execute("INSERT INTO vacation_consults (request_id, email, name, message) VALUES (%s, %s, %s, %s)",
|
||||
(request_id, c["email"], c.get("name") or "", c.get("message") or ""))
|
||||
|
||||
def decide_consult(self, *, request_id: str, email: str, approve: bool, reason: str = "") -> tuple[dict[str, Any], str | None]:
|
||||
"""협의자 한 명의 승인·반려. 반환 (신청, 알릴 일): 모두 승인 → 제출로 넘어감("consulted"), 반려 → 신청도 반려("rejected"),
|
||||
아직 남은 협의자가 있으면 None. 신청 줄을 잠가 마지막 두 명이 동시에 눌러도 한 번만 넘어간다."""
|
||||
email = email.lower().strip()
|
||||
reason = (reason or "").strip()
|
||||
if not approve and not reason:
|
||||
raise ValueError("반려 사유는 필수입니다.")
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
head = conn.execute("SELECT status FROM vacation_requests WHERE id = %s FOR UPDATE", (request_id,)).fetchone()
|
||||
if not head:
|
||||
raise KeyError(request_id)
|
||||
mine = conn.execute("SELECT state FROM vacation_consults WHERE request_id = %s AND email = %s",
|
||||
(request_id, email)).fetchone()
|
||||
if not mine:
|
||||
raise PermissionError("이 신청의 협의자만 처리할 수 있습니다.")
|
||||
if head["status"] != "협의중" or mine["state"] != "대기":
|
||||
raise ValueError("협의 대기 중이 아닙니다(이미 처리됨).")
|
||||
conn.execute("UPDATE vacation_consults SET state = %s, comment = %s, decided_at = now() WHERE request_id = %s AND email = %s",
|
||||
("승인" if approve else "반려", reason, request_id, email))
|
||||
event: str | None = None
|
||||
if not approve:
|
||||
event = "rejected"
|
||||
row = conn.execute("UPDATE vacation_requests SET status = '반려', approver_email = %s, decided_at = now(), "
|
||||
"reject_reason = %s WHERE id = %s RETURNING *", (email, reason, request_id)).fetchone()
|
||||
elif conn.execute("SELECT 1 FROM vacation_consults WHERE request_id = %s AND state <> '승인' LIMIT 1", (request_id,)).fetchone():
|
||||
row = conn.execute("SELECT * FROM vacation_requests WHERE id = %s", (request_id,)).fetchone()
|
||||
else:
|
||||
event = "consulted"
|
||||
row = conn.execute("UPDATE vacation_requests SET status = '제출' WHERE id = %s RETURNING *", (request_id,)).fetchone()
|
||||
return self._req_serialize(row), event
|
||||
|
||||
def create_request(
|
||||
self, *, owner: str, owner_name: str, payload: dict[str, Any], status: str = "작성중"
|
||||
self, *, owner: str, owner_name: str, payload: dict[str, Any], status: str = "작성중",
|
||||
consults: list[dict[str, Any]] | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""consults = [{email, name, message}] — 제출이면서 협의자가 있으면 협의중으로 시작."""
|
||||
h = self._normalize_payload(payload)
|
||||
if status not in STATUSES:
|
||||
status = "작성중"
|
||||
if status == "제출" and consults:
|
||||
status = "협의중"
|
||||
days = self._calc_days(h)
|
||||
req_id = uuid.uuid4().hex[:12]
|
||||
with self._pool.connection() as conn:
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
row = conn.execute(
|
||||
"""
|
||||
INSERT INTO vacation_requests
|
||||
@@ -368,12 +449,14 @@ class VacationDBStore:
|
||||
status,
|
||||
),
|
||||
).fetchone()
|
||||
if consults:
|
||||
self._replace_consults(conn, req_id, consults)
|
||||
return self._req_serialize(row)
|
||||
|
||||
def update_request(
|
||||
self, *, request_id: str, owner: str, payload: dict[str, Any]
|
||||
self, *, request_id: str, owner: str, payload: dict[str, Any], consults: list[dict[str, Any]] | None = None
|
||||
) -> dict[str, Any]:
|
||||
"""작성중/반려 상태에서만 본인이 수정 가능."""
|
||||
"""작성중/반려 상태에서만 본인이 수정 가능. consults 를 넘기면 협의자를 그 목록으로 바꾼다(003 전이면 None)."""
|
||||
owner = owner.lower().strip()
|
||||
current = self.get_request(request_id=request_id)
|
||||
if not current:
|
||||
@@ -384,7 +467,7 @@ class VacationDBStore:
|
||||
raise ValueError(f"{current['status']} 상태에서는 수정할 수 없습니다.")
|
||||
h = self._normalize_payload(payload)
|
||||
days = self._calc_days(h)
|
||||
with self._pool.connection() as conn:
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE vacation_requests
|
||||
@@ -407,25 +490,32 @@ class VacationDBStore:
|
||||
owner,
|
||||
),
|
||||
).fetchone()
|
||||
if row and consults is not None:
|
||||
self._replace_consults(conn, request_id, consults)
|
||||
if not row:
|
||||
raise KeyError(request_id)
|
||||
return self._req_serialize(row)
|
||||
|
||||
# ── 워크플로 ──
|
||||
def submit(self, *, request_id: str, owner: str) -> dict[str, Any]:
|
||||
"""작성중/반려 → 제출 (본인)."""
|
||||
"""작성중/반려 → 제출(본인). 협의자가 있으면 협의중으로, 다시 제출하면 협의도 처음부터."""
|
||||
owner = owner.lower().strip()
|
||||
with self._pool.connection() as conn:
|
||||
ready = self.consults_ready() # 트랜잭션 전에 — 안에서 두 번째 연결을 잡지 않게
|
||||
with self._pool.connection() as conn, conn.transaction():
|
||||
has = ready and conn.execute("SELECT 1 FROM vacation_consults WHERE request_id = %s LIMIT 1", (request_id,)).fetchone()
|
||||
row = conn.execute(
|
||||
"""
|
||||
UPDATE vacation_requests
|
||||
SET status = '제출', reject_reason = '',
|
||||
SET status = %s, reject_reason = '',
|
||||
approver_email = NULL, decided_at = NULL
|
||||
WHERE id = %s AND owner = %s AND status IN ('작성중', '반려')
|
||||
RETURNING *
|
||||
""",
|
||||
(request_id, owner),
|
||||
("협의중" if has else "제출", request_id, owner),
|
||||
).fetchone()
|
||||
if row and has:
|
||||
conn.execute("UPDATE vacation_consults SET state = '대기', comment = '', decided_at = NULL WHERE request_id = %s",
|
||||
(request_id,))
|
||||
if not row:
|
||||
raise ValueError("작성중/반려 상태에서만 제출할 수 있습니다.")
|
||||
return self._req_serialize(row)
|
||||
@@ -487,7 +577,7 @@ class VacationDBStore:
|
||||
"""완전 삭제.
|
||||
|
||||
- 관리자(is_admin): 모든 상태 삭제 가능.
|
||||
- 일반 사용자: 본인 + 승인 전(작성중/제출/반려)만. 승인/취소 건은 불가.
|
||||
- 일반 사용자: 본인 + 승인 전(작성중/협의중/제출/반려)만. 승인/취소 건은 불가.
|
||||
"""
|
||||
user_email = user_email.lower().strip()
|
||||
current = self.get_request(request_id=request_id)
|
||||
@@ -496,7 +586,7 @@ class VacationDBStore:
|
||||
if not is_admin:
|
||||
if current["owner"] != user_email:
|
||||
raise PermissionError("본인 신청만 삭제할 수 있습니다.")
|
||||
if current["status"] not in ("작성중", "제출", "반려"):
|
||||
if current["status"] not in ("작성중", "협의중", "제출", "반려"):
|
||||
raise ValueError("승인/취소된 휴가는 삭제할 수 없습니다. (관리자 문의)")
|
||||
with self._pool.connection() as conn:
|
||||
cur = conn.execute(
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
제출 = 승인자 + 승인 통보자
|
||||
승인 = 승인자 + 승인 통보자 + 신청자
|
||||
반려 = 승인자 + 승인 통보자 + 신청자
|
||||
협의 완료(협의자 모두 승인) = 승인자 + 승인 통보자 + 신청자
|
||||
승인자 = 휴가 옵션의 승인자(없으면 vacation_approver 권한자 — ERP 관리자는 자동으로 넣지 않는다).
|
||||
협의자(2026-11-02)가 있으면 제출 때 협의자마다 따로 한 통 — 자기 협의 내용만. 그 밖의 메일은 협의자 전체와 협의 내용을 싣는다.
|
||||
보내는 사람 = 그 일을 한 사람(제출 = 신청자, 승인·반려 = 처리한 승인자)의 **본인 Gmail** — 입출고 발주 메일과 같은
|
||||
Gmail 연결(inout_db `inout_gmail_tokens`, gmail.send 만, 사람마다 한 번 연결). 연결이 없거나 끊겼거나 Gmail 이 실패하면
|
||||
회사 알림 메일(SMTP, app/mail.py)로 보내고 보낸 사람 이름·답장 주소를 그 사람으로 한다.
|
||||
@@ -22,13 +24,16 @@ from .store import HALF_LABELS
|
||||
|
||||
logger = logging.getLogger("app.vacation.notify")
|
||||
|
||||
EVENTS = ("submitted", "approved", "rejected")
|
||||
EVENT_WORD = {"submitted": "제출", "approved": "승인", "rejected": "반려"}
|
||||
EVENTS = ("submitted", "approved", "rejected", "consulted")
|
||||
EVENT_WORD = {"submitted": "제출", "approved": "승인", "rejected": "반려", "consult_request": "협의 요청", "consulted": "협의 완료"}
|
||||
EVENT_LEAD = {
|
||||
"submitted": "휴가 신청이 제출되었습니다. 확인 후 승인해 주세요.",
|
||||
"approved": "휴가가 승인되었습니다.",
|
||||
"rejected": "휴가가 반려되었습니다.",
|
||||
"consult_request": "휴가 협의 요청이 왔습니다. 내용을 확인하고 ERP 휴가 메뉴에서 협의 결재를 진행해 주세요.",
|
||||
"consulted": "협의가 모두 끝났습니다. 확인 후 승인해 주세요.",
|
||||
}
|
||||
LEAD_WITH_CONSULTS = "휴가 신청이 제출되었습니다. 협의자가 모두 승인하면 결재할 수 있습니다."
|
||||
_WEEKDAYS = "월화수목금토일"
|
||||
|
||||
|
||||
@@ -55,7 +60,7 @@ def approver_emails(options: dict[str, Any], users: list[dict[str, Any]]) -> lis
|
||||
|
||||
def recipients(event: str, req: dict[str, Any], options: dict[str, Any], users: list[dict[str, Any]]) -> list[str]:
|
||||
people = approver_emails(options, users) + _uniq(options.get("notifiers") or [])
|
||||
if event in ("approved", "rejected"):
|
||||
if event in ("approved", "rejected", "consulted"):
|
||||
people.append(req.get("owner") or "")
|
||||
return _uniq(people)
|
||||
|
||||
@@ -87,29 +92,39 @@ def _days(v: Any) -> str:
|
||||
|
||||
|
||||
def build(event: str, req: dict[str, Any], *, actor_name: str, actor_email: str, link: str,
|
||||
name_of: Any = None) -> dict[str, str]:
|
||||
"""제목·글·HTML. 사용자 글(사유·반려 사유·이름)은 HTML 에서 늘 escape."""
|
||||
name_of: Any = None, consult: dict[str, Any] | None = None) -> dict[str, str]:
|
||||
"""제목·글·HTML. 사용자 글(사유·반려 사유·이름)은 HTML 에서 늘 escape.
|
||||
협의 요청(consult_request)은 받는 협의자 한 명 몫(consult)만, 나머지 메일은 협의자 전체(req["consults"])와 협의 내용을 싣는다."""
|
||||
name_of = name_of or (lambda e: e)
|
||||
owner = req.get("owner_name") or name_of(req.get("owner") or "")
|
||||
word = EVENT_WORD[event]
|
||||
consults = req.get("consults") or []
|
||||
subject = f"[휴가 {word}] {owner} · {req.get('vacation_type', '')} {period_text(req)} ({_days(req.get('days'))}일)"
|
||||
rows = [("신청자", f"{owner} ({req.get('owner', '')})"), ("종류", req.get("vacation_type") or ""),
|
||||
("기간", period_text(req)), ("일수", f"{_days(req.get('days'))}일"), ("사유", req.get("reason") or "-")]
|
||||
if event == "submitted":
|
||||
rows.append(("상태", "제출 — 승인 대기"))
|
||||
if event == "consult_request":
|
||||
rows += [("상태", "협의 대기"), ("협의 내용", (consult or {}).get("message") or "-")]
|
||||
elif event == "consulted":
|
||||
rows.append(("상태", "협의 완료 — 승인 대기"))
|
||||
elif event == "submitted":
|
||||
rows.append(("상태", "협의 진행 중" if consults else "제출 — 승인 대기"))
|
||||
else:
|
||||
rows.append(("상태", word))
|
||||
rows.append((f"{word}자", f"{actor_name} ({actor_email})"))
|
||||
if event == "rejected":
|
||||
rows.append(("반려 사유", req.get("reject_reason") or "-"))
|
||||
text = "\n".join([EVENT_LEAD[event], ""] + [f"{k}: {v}" for k, v in rows] + ["", f"휴가 신청 보기: {link}"])
|
||||
if event != "consult_request":
|
||||
rows += [(f"협의자 {c.get('name') or name_of(c.get('email') or '')}",
|
||||
f"{c.get('state') or '대기'} — {c.get('message') or '협의 내용 없음'}") for c in consults]
|
||||
lead = LEAD_WITH_CONSULTS if event == "submitted" and consults else EVENT_LEAD[event]
|
||||
text = "\n".join([lead, ""] + [f"{k}: {v}" for k, v in rows] + ["", f"휴가 신청 보기: {link}"])
|
||||
tr = "".join(
|
||||
f'<tr><th style="text-align:left;padding:6px 12px 6px 0;color:#666;font-weight:600;white-space:nowrap;vertical-align:top">'
|
||||
f'{escape(k)}</th><td style="padding:6px 0;white-space:pre-wrap">{escape(str(v))}</td></tr>' for k, v in rows)
|
||||
color = {"submitted": "#1a56db", "approved": "#0f8a3a", "rejected": "#c22b10"}[event]
|
||||
color = {"approved": "#0f8a3a", "rejected": "#c22b10"}.get(event, "#1a56db")
|
||||
html = (
|
||||
'<div style="font-family:Pretendard,\'Malgun Gothic\',sans-serif;font-size:14px;color:#111;line-height:1.5">'
|
||||
f'<p style="margin:0 0 12px;font-size:16px;font-weight:700;color:{color}">{escape(EVENT_LEAD[event])}</p>'
|
||||
f'<p style="margin:0 0 12px;font-size:16px;font-weight:700;color:{color}">{escape(lead)}</p>'
|
||||
f'<table style="border-collapse:collapse;margin:0 0 16px">{tr}</table>'
|
||||
f'<p style="margin:0"><a href="{escape(link, quote=True)}" style="display:inline-block;padding:8px 14px;border-radius:6px;'
|
||||
f'background:{color};color:#fff;text-decoration:none;font-weight:600">휴가 신청 보기</a></p>'
|
||||
@@ -156,9 +171,8 @@ def _send_gmail(inout_store: Any, *, email: str, name: str, to: list[str], mail:
|
||||
|
||||
def deliver(store: Any, inout_store: Any, *, event: str, req: dict[str, Any], actor: dict[str, Any],
|
||||
users: list[dict[str, Any]], link: str) -> dict[str, Any]:
|
||||
"""받는 사람을 정해 한 통 보내고 기록한다. 반환 {ok, via, to, error} (테스트·로그용)."""
|
||||
from app import mail as smtp # noqa: WPS433
|
||||
|
||||
"""받는 사람을 정해 한 통 보내고 기록한다. 제출이면 협의자마다 자기 몫 협의 요청도 따로 한 통씩.
|
||||
반환 {ok, via, to, error} (테스트·로그용, 협의 요청 제외)."""
|
||||
if event not in EVENTS:
|
||||
raise ValueError(event)
|
||||
try:
|
||||
@@ -169,13 +183,31 @@ def deliver(store: Any, inout_store: Any, *, event: str, req: dict[str, Any], ac
|
||||
names = {_norm(u.get("email")): u.get("name") or "" for u in users}
|
||||
email = _norm(actor.get("email"))
|
||||
name = actor.get("name") or names.get(email) or email.split("@")[0]
|
||||
|
||||
def name_of(e: Any) -> str:
|
||||
return names.get(_norm(e)) or str(e).split("@")[0]
|
||||
|
||||
if event == "submitted":
|
||||
for c in req.get("consults") or []:
|
||||
if c.get("state", "대기") != "대기": # 다시 보내기 — 이미 처리한 협의자에게는 안 보냄
|
||||
continue
|
||||
mail = build("consult_request", req, actor_name=name, actor_email=email, link=link, name_of=name_of, consult=c)
|
||||
_send_and_log(store, inout_store, "consult_request", req, _uniq([c.get("email")]), mail, email, name)
|
||||
result: dict[str, Any] = {"ok": False, "via": "", "to": to, "error": ""}
|
||||
if not to:
|
||||
result["error"] = "받는 사람 없음(승인자·통보자 미지정)"
|
||||
logger.info("휴가 메일 받는 사람 없음 — %s %s", event, req.get("id"))
|
||||
return result
|
||||
mail = build(event, req, actor_name=name, actor_email=email, link=link,
|
||||
name_of=lambda e: names.get(_norm(e)) or str(e).split("@")[0])
|
||||
mail = build(event, req, actor_name=name, actor_email=email, link=link, name_of=name_of)
|
||||
return _send_and_log(store, inout_store, event, req, to, mail, email, name)
|
||||
|
||||
|
||||
def _send_and_log(store: Any, inout_store: Any, event: str, req: dict[str, Any], to: list[str], mail: dict[str, str],
|
||||
email: str, name: str) -> dict[str, Any]:
|
||||
"""한 통 보내기 — 본인 Gmail, 안 되면 회사 SMTP. 결과는 vacation_mail_log 에."""
|
||||
from app import mail as smtp # noqa: WPS433
|
||||
|
||||
result: dict[str, Any] = {"ok": False, "via": "", "to": to, "error": ""}
|
||||
ok, gmail_err = _send_gmail(inout_store, email=email, name=name, to=to, mail=mail)
|
||||
if ok:
|
||||
result.update(ok=True, via="gmail")
|
||||
|
||||
+235
-34
@@ -3,6 +3,7 @@
|
||||
- 경로: /vacation
|
||||
- 권한: 로그인 + `vacation` 모듈 권한 (관리자는 항상 통과). 서버 측 검사.
|
||||
승인/반려 = admin + (휴가 옵션에 승인자를 지정했으면 그 사람들, 아니면 `vacation_approver` 권한자) — 2026-10-27.
|
||||
- 협의자(2026-11-02, 마이그레이션 003): 신청자가 지정(복수) → 모두 승인해야 결재자에게 넘어감(상태 협의중 → 제출). 협의자는 휴가 권한이 없어도 자기 신청은 볼 수 있다.
|
||||
- 휴가 옵션(`/vacation/options`, 수정 = admin·승인자·통보자): 승인자·승인 통보자·잔여 연차. 공휴일 = 국경일 표(설정 화면 없음). 제출·승인·반려 메일은 `notify.py`
|
||||
(처리한 사람 본인 Gmail — 입출고와 같은 Gmail 연결, 없으면 회사 SMTP).
|
||||
- 데이터: VacationDBStore (vacation_db / PostgreSQL) 전용.
|
||||
@@ -61,6 +62,16 @@ def _require_approver(request: Request) -> dict[str, Any]:
|
||||
return user
|
||||
|
||||
|
||||
def _require_login(request: Request) -> dict[str, Any]:
|
||||
"""로그인만 — 협의 결재처럼 휴가 모듈 권한이 없어도 되는 곳(협의자 여부는 저장소가 확인)."""
|
||||
from app.main import get_current_user_record # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
raise HTTPException(status_code=401, detail="로그인이 필요합니다.")
|
||||
return user
|
||||
|
||||
|
||||
def _options(request: Request) -> dict[str, Any]:
|
||||
"""휴가 옵션(승인자·통보자, 마이그레이션 001). DB·001 이 없으면 빈 옵션."""
|
||||
st = _store(request)
|
||||
@@ -111,9 +122,42 @@ def _vacation_users() -> list[dict[str, Any]]:
|
||||
return out
|
||||
|
||||
|
||||
def _people() -> dict[str, dict[str, str]]:
|
||||
"""전체 구성원(휴가 권한과 무관) {이메일: 이메일·이름·사진} — 협의자 후보·결재 라인 아이콘. 이름 순."""
|
||||
from app.main import user_store # noqa: WPS433
|
||||
|
||||
rows = [{"email": u["email"].lower(), "name": u.get("name") or u["email"].split("@")[0], "picture": u.get("picture") or ""}
|
||||
for u in user_store.list_all()]
|
||||
rows.sort(key=lambda p: p["name"].lower())
|
||||
return {p["email"]: p for p in rows}
|
||||
|
||||
|
||||
def _form_consults(store: Any, owner: str, emails: list[str], messages: list[str], no_consult: str, action: str) -> list[dict[str, Any]] | None:
|
||||
"""폼의 협의자 줄 → [{email, name, message}]. 003 전이면 None(협의자 없음). 제출인데 협의자도 "협의자 없음"도 없으면 400."""
|
||||
if not store.consults_ready():
|
||||
return None
|
||||
if no_consult:
|
||||
return []
|
||||
if len(emails) != len(messages):
|
||||
raise HTTPException(status_code=400, detail="협의자 칸이 맞지 않습니다.")
|
||||
known = _people()
|
||||
out: dict[str, dict[str, Any]] = {}
|
||||
for raw, message in zip(emails, messages):
|
||||
email = raw.strip().lower()
|
||||
if email == owner.lower():
|
||||
continue
|
||||
if email not in known:
|
||||
raise HTTPException(status_code=400, detail=f"등록된 구성원만 협의자로 고를 수 있습니다: {email}")
|
||||
out[email] = {"email": email, "name": known[email]["name"], "message": message.strip()[:2000]}
|
||||
if action == "submit" and not out:
|
||||
raise HTTPException(status_code=400, detail="협의자를 고르거나 '협의자 없음'을 체크하세요.")
|
||||
return list(out.values())
|
||||
|
||||
|
||||
def _notify(bg: BackgroundTasks, request: Request, event: str, req: dict[str, Any] | None,
|
||||
actor: dict[str, Any]) -> None:
|
||||
"""제출·승인·반려 메일을 응답 뒤 백그라운드로(notify.deliver — 받는 사람·보내는 사람 규칙은 그쪽)."""
|
||||
actor: dict[str, Any], now: bool = False) -> None:
|
||||
"""제출·승인·반려 메일을 응답 뒤 백그라운드로(notify.deliver — 받는 사람·보내는 사람 규칙은 그쪽).
|
||||
Gmail 연결이 없거나 now 면 바로 — 실패 기록이 다음 화면에 보여 [Gmail 연결]·[다시 보내기]를 띄울 수 있게."""
|
||||
from app.main import env # noqa: WPS433
|
||||
|
||||
from . import notify # noqa: WPS433
|
||||
@@ -121,10 +165,20 @@ def _notify(bg: BackgroundTasks, request: Request, event: str, req: dict[str, An
|
||||
st = _store(request)
|
||||
if st is None or not req:
|
||||
return
|
||||
try:
|
||||
req = {**req, "consults": st.list_consults(request_id=req["id"])}
|
||||
except Exception: # noqa: BLE001 — 협의자 조회 실패가 처리 결과를 뒤집지 않게(메일만 협의 내용 없이)
|
||||
req = {**req, "consults": []}
|
||||
base = (env("PUBLIC_BASE_URL") or str(request.base_url)).rstrip("/")
|
||||
inout_store = getattr(request.app.state, "inout_store", None)
|
||||
bg.add_task(notify.deliver, st, inout_store, event=event, req=req, actor=dict(actor),
|
||||
users=_vacation_users(), link=f"{base}/vacation/{req['id']}")
|
||||
args = {"event": event, "req": req, "actor": dict(actor), "users": _vacation_users(), "link": f"{base}/vacation/{req['id']}"}
|
||||
if not now and _gmail_state(request, actor)["connected"]:
|
||||
bg.add_task(notify.deliver, st, inout_store, **args)
|
||||
return
|
||||
try:
|
||||
notify.deliver(st, inout_store, **args)
|
||||
except Exception: # noqa: BLE001 — 메일이 실패해도 휴가 처리는 그대로
|
||||
notify.logger.exception("휴가 메일 처리 실패 — %s %s", event, req.get("id"))
|
||||
|
||||
|
||||
def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLResponse:
|
||||
@@ -147,23 +201,26 @@ def _render_config_needed(request: Request, user: dict[str, Any]) -> HTMLRespons
|
||||
|
||||
|
||||
def _guard(
|
||||
request: Request,
|
||||
request: Request, consult_of: str = "",
|
||||
) -> tuple[Any, dict[str, Any]] | HTMLResponse | RedirectResponse:
|
||||
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용."""
|
||||
"""로그인+권한+store 점검. 페이지 핸들러 진입부에서 사용.
|
||||
consult_of = 신청 id — 휴가 권한이 없어도 그 신청의 협의자면 통과(메일 링크로 들어와 협의 결재)."""
|
||||
from app.main import get_current_user_record, render_template # noqa: WPS433
|
||||
from app.store import has_module, is_admin # noqa: WPS433
|
||||
from app.store import has_module, is_admin, login_redirect # noqa: WPS433
|
||||
|
||||
user = get_current_user_record(request)
|
||||
if user is None:
|
||||
return RedirectResponse(url="/login", status_code=303)
|
||||
if not has_module(user, "vacation"):
|
||||
return login_redirect(request)
|
||||
store = _store(request)
|
||||
allowed = has_module(user, "vacation") or (store is not None and consult_of and any(
|
||||
c["email"] == user["email"].lower() for c in store.list_consults(request_id=consult_of)))
|
||||
if not allowed:
|
||||
return render_template(
|
||||
request,
|
||||
"denied.html",
|
||||
{"reason": "휴가 관리 모듈 접근 권한이 없습니다.", "is_admin": is_admin(user)},
|
||||
status_code=403,
|
||||
)
|
||||
store = _store(request)
|
||||
if store is None:
|
||||
return _render_config_needed(request, user)
|
||||
return store, user
|
||||
@@ -184,6 +241,7 @@ def _ym(request: Request) -> tuple[int, int]:
|
||||
# 상태별 bar 스타일 클래스 (CSS 와 매핑)
|
||||
_STATUS_CLASS = {
|
||||
"작성중": "vac-bar-draft",
|
||||
"협의중": "vac-bar-submit",
|
||||
"제출": "vac-bar-submit",
|
||||
"승인": "vac-bar-approve",
|
||||
"반려": "vac-bar-reject",
|
||||
@@ -323,6 +381,7 @@ def index(request: Request) -> HTMLResponse:
|
||||
"is_admin": is_admin(user),
|
||||
"is_approver": is_approver,
|
||||
"pending_count": pending_count,
|
||||
"consult_count": len(store.my_consults(email=user["email"])),
|
||||
"nav_items": build_erp_nav(user, active="vacation"),
|
||||
"page_title": "휴가 관리",
|
||||
"page_subtitle": f"{year}년 {month}월 휴가 달력",
|
||||
@@ -344,11 +403,29 @@ def index(request: Request) -> HTMLResponse:
|
||||
# ════════════════════════════════════════════════════════════
|
||||
# 휴가 신청 — 등록 / 수정 / 상세
|
||||
# ════════════════════════════════════════════════════════════
|
||||
def _form_context(request: Request, user: dict[str, Any]) -> dict[str, Any]:
|
||||
def _approval_line(request: Request, people: dict[str, dict[str, str]]) -> dict[str, list[dict[str, str]]]:
|
||||
"""옵션에 세팅된 결재자·통보자(아이콘 + 이름) — 신청 화면·상세의 결재 라인."""
|
||||
from . import notify # noqa: WPS433
|
||||
|
||||
opts = _options(request)
|
||||
|
||||
def who(emails: list[str]) -> list[dict[str, str]]:
|
||||
return [people.get(e) or {"email": e, "name": e.split("@")[0], "picture": ""} for e in emails]
|
||||
|
||||
return {"approvers": who(notify.approver_emails(opts, _vacation_users())), "notifiers": who(opts.get("notifiers") or [])}
|
||||
|
||||
|
||||
def _form_context(request: Request, user: dict[str, Any], req: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||
from app.main import build_erp_nav # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
people = _people()
|
||||
st = _store(request)
|
||||
return {
|
||||
"members": [p for e, p in people.items() if e != user["email"].lower()],
|
||||
"consult_ready": bool(st is not None and st.consults_ready()),
|
||||
"consult_chosen": {c["email"]: c["message"] for c in st.list_consults(request_id=req["id"])} if req and st is not None else {},
|
||||
"line": _approval_line(request, people),
|
||||
"user": user,
|
||||
"is_admin": is_admin(user),
|
||||
"is_approver": _is_approver(request, user),
|
||||
@@ -422,6 +499,9 @@ def create(
|
||||
end_half: str = Form("full"),
|
||||
reason: str = Form(""),
|
||||
action: str = Form("submit"), # "draft" | "submit"
|
||||
consult_email: list[str] = Form(default=[]),
|
||||
consult_message: list[str] = Form(default=[]),
|
||||
no_consult: str = Form(""),
|
||||
user: dict[str, Any] = Depends(_require_user),
|
||||
) -> RedirectResponse:
|
||||
store = _store(request)
|
||||
@@ -431,12 +511,14 @@ def create(
|
||||
payload = _payload_from_form(
|
||||
vacation_type, start_date, end_date, start_half, end_half, reason
|
||||
)
|
||||
consults = _form_consults(store, user["email"], consult_email, consult_message, no_consult, action)
|
||||
try:
|
||||
req = store.create_request(
|
||||
owner=user["email"],
|
||||
owner_name=user.get("name") or user["email"],
|
||||
payload=payload,
|
||||
status=status,
|
||||
consults=consults,
|
||||
)
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
@@ -454,26 +536,57 @@ def pending_page(request: Request) -> HTMLResponse:
|
||||
if not isinstance(guard, tuple):
|
||||
return guard
|
||||
store, user = guard
|
||||
if not _is_approver(request, user):
|
||||
return render_template(
|
||||
request,
|
||||
"denied.html",
|
||||
{"reason": "휴가 승인자 권한이 없습니다.", "is_admin": is_admin(user)},
|
||||
status_code=403,
|
||||
)
|
||||
pending = store.list_pending()
|
||||
is_approver = _is_approver(request, user)
|
||||
pending = store.list_pending() if is_approver else []
|
||||
consults = store.my_consults(email=user["email"])
|
||||
by_req = store.consults_for([r["id"] for r in pending])
|
||||
for r in pending:
|
||||
r["consults"] = by_req.get(r["id"], [])
|
||||
return render_template(
|
||||
request,
|
||||
"vacation/pending.html",
|
||||
{
|
||||
"user": user,
|
||||
"is_admin": is_admin(user),
|
||||
"is_approver": True,
|
||||
"is_approver": is_approver,
|
||||
"nav_items": build_erp_nav(user, active="vacation"),
|
||||
"page_title": "휴가 — 승인 대기",
|
||||
"page_subtitle": f"제출 상태 {len(pending)}건",
|
||||
"page_title": "휴가 — 결재 대기",
|
||||
"page_subtitle": f"협의 {len(consults)}건" + (f" · 승인 {len(pending)}건" if is_approver else ""),
|
||||
"items": pending,
|
||||
"consult_items": consults,
|
||||
"half_labels": HALF_LABELS,
|
||||
"people": _people(),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/mine", response_class=HTMLResponse)
|
||||
def mine_page(request: Request) -> HTMLResponse:
|
||||
"""내 휴가 신청 내역 — 협의·결재 진행 상황(2026-11-02)."""
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
guard = _guard(request)
|
||||
if not isinstance(guard, tuple):
|
||||
return guard
|
||||
store, user = guard
|
||||
items = store.list_for(user["email"])
|
||||
by_req = store.consults_for([r["id"] for r in items])
|
||||
for r in items:
|
||||
r["consults"] = by_req.get(r["id"], [])
|
||||
return render_template(
|
||||
request,
|
||||
"vacation/mine.html",
|
||||
{
|
||||
"user": user,
|
||||
"is_admin": is_admin(user),
|
||||
"is_approver": _is_approver(request, user),
|
||||
"nav_items": build_erp_nav(user, active="vacation"),
|
||||
"page_title": "휴가 — 내 신청 내역",
|
||||
"page_subtitle": f"{len(items)}건",
|
||||
"items": items,
|
||||
"half_labels": HALF_LABELS,
|
||||
"people": _people(),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -729,22 +842,33 @@ def options_save(
|
||||
@router.get("/gmail/connect")
|
||||
async def gmail_connect(request: Request) -> Any:
|
||||
"""내 Gmail 연결 — 입출고와 같은 연결(같은 OAuth 클라이언트·같은 구글 리디렉션 주소 /inout/gmail/callback).
|
||||
콜백은 세션 표시(_gmail_origin=vacation)를 보고 휴가 권한으로 처리한 뒤 휴가 옵션으로 돌아온다."""
|
||||
콜백은 세션 표시(_gmail_origin=vacation)를 보고 휴가 권한으로 처리한 뒤 휴가 옵션으로 돌아온다.
|
||||
?next=/vacation/{신청 id} = 그 상세로 돌아옴 — 그 신청의 협의자면 휴가 권한이 없어도 연결(콜백에 _gmail_consultant 로 알림)."""
|
||||
import re # noqa: WPS433
|
||||
from urllib.parse import urlencode # noqa: WPS433
|
||||
|
||||
from app.main import ALLOWED_DOMAIN, public_url_for # noqa: WPS433
|
||||
from app.modules.inout import gmail # noqa: WPS433
|
||||
from app.store import has_module # noqa: WPS433
|
||||
|
||||
user = _require_user(request)
|
||||
user = _require_login(request)
|
||||
nxt = request.query_params.get("next", "")
|
||||
back = nxt if re.fullmatch(r"/vacation/[0-9a-z]+", nxt) else "/vacation/options"
|
||||
st = _store(request)
|
||||
consultant = back != "/vacation/options" and st is not None and any(
|
||||
c["email"] == user["email"].lower() for c in st.list_consults(request_id=back.rsplit("/", 1)[1]))
|
||||
if not consultant and not has_module(user, "vacation"):
|
||||
raise HTTPException(status_code=403, detail="휴가 관리 모듈 권한이 없습니다.")
|
||||
if getattr(request.app.state, "inout_store", None) is None:
|
||||
return RedirectResponse(url="/vacation/options?" + urlencode(
|
||||
return RedirectResponse(url=back + "?" + urlencode(
|
||||
{"msg": "Gmail 연결 저장소(입출고 DB)가 설정되지 않아 연결할 수 없습니다 — 회사 메일로 보냅니다."}), status_code=303)
|
||||
try:
|
||||
client = gmail.oauth_client()
|
||||
except gmail.GmailError as exc:
|
||||
return RedirectResponse(url="/vacation/options?" + urlencode({"msg": str(exc)}), status_code=303)
|
||||
return RedirectResponse(url=back + "?" + urlencode({"msg": str(exc)}), status_code=303)
|
||||
request.session["_gmail_origin"] = "vacation"
|
||||
request.session["_gmail_next"] = "/vacation/options"
|
||||
request.session["_gmail_next"] = back
|
||||
request.session["_gmail_consultant"] = bool(consultant)
|
||||
return await client.authorize_redirect(
|
||||
request, public_url_for(request, "inout_gmail_callback"),
|
||||
access_type="offline", prompt="consent", include_granted_scopes="true",
|
||||
@@ -776,7 +900,7 @@ def detail(request: Request, request_id: str) -> HTMLResponse:
|
||||
from app.main import build_erp_nav, render_template # noqa: WPS433
|
||||
from app.store import is_admin # noqa: WPS433
|
||||
|
||||
guard = _guard(request)
|
||||
guard = _guard(request, consult_of=request_id)
|
||||
if not isinstance(guard, tuple):
|
||||
return guard
|
||||
store, user = guard
|
||||
@@ -787,14 +911,21 @@ def detail(request: Request, request_id: str) -> HTMLResponse:
|
||||
{"reason": "휴가 신청을 찾을 수 없습니다.", "is_admin": is_admin(user)},
|
||||
status_code=404,
|
||||
)
|
||||
email = user["email"].lower()
|
||||
is_owner = req["owner"] == user["email"]
|
||||
is_approver = _is_approver(request, user)
|
||||
if not (is_owner or is_approver):
|
||||
consults = store.list_consults(request_id=request_id)
|
||||
mine = next((c for c in consults if c["email"] == email), None)
|
||||
see_all = is_owner or is_approver or email in (_options(request).get("notifiers") or [])
|
||||
if not (see_all or mine):
|
||||
return render_template(
|
||||
request, "denied.html",
|
||||
{"reason": "본인 또는 승인자만 조회할 수 있습니다.", "is_admin": is_admin(user)},
|
||||
{"reason": "본인·승인자·통보자·협의자만 조회할 수 있습니다.", "is_admin": is_admin(user)},
|
||||
status_code=403,
|
||||
)
|
||||
req["consults"] = consults if see_all else [mine] # 협의자는 자기 몫 협의 내용만
|
||||
people = _people()
|
||||
failed_mail = _failed_mail(store, req, email)
|
||||
return render_template(
|
||||
request,
|
||||
"vacation/detail.html",
|
||||
@@ -809,12 +940,31 @@ def detail(request: Request, request_id: str) -> HTMLResponse:
|
||||
"req": req,
|
||||
"half_labels": HALF_LABELS,
|
||||
"can_edit": is_owner and req["status"] in ("작성중", "반려"),
|
||||
"mail_log": _mail_log(store, request_id),
|
||||
"event_words": {"submitted": "제출", "approved": "승인", "rejected": "반려"},
|
||||
"can_consult": bool(mine and mine["state"] == "대기" and req["status"] == "협의중"),
|
||||
"failed_mail": failed_mail,
|
||||
"gmail": _gmail_state(request, user) if failed_mail else None,
|
||||
"msg": request.query_params.get("msg", ""),
|
||||
"people": people,
|
||||
"line": _approval_line(request, people),
|
||||
"mail_log": _mail_log(store, request_id) if see_all else [],
|
||||
"event_words": {"submitted": "제출", "approved": "승인", "rejected": "반려", "consult_request": "협의 요청", "consulted": "협의 완료"},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# 다시 보낼 의미가 있는 신청 상태 — 일이 더 진행됐거나 수정 중이면 예전 메일은 다시 보내지 않는다
|
||||
_RETRY_STATUS = {"submitted": ("협의중", "제출"), "consulted": ("제출",), "approved": ("승인",), "rejected": ("반려",)}
|
||||
|
||||
|
||||
def _failed_mail(store: Any, req: dict[str, Any], email: str) -> dict[str, Any] | None:
|
||||
"""내가 보내다 실패한 메일 — 그 신청의 마지막 메일(협의 요청은 제출과 함께 다루므로 뺌)이 실패이고 상태가 그대로일 때."""
|
||||
logs = [m for m in _mail_log(store, req["id"]) if m["event"] != "consult_request"]
|
||||
last = logs[-1] if logs else None
|
||||
if last and not last["ok"] and last["sender"] == email and req["status"] in _RETRY_STATUS.get(last["event"], ()):
|
||||
return last
|
||||
return None
|
||||
|
||||
|
||||
def _mail_log(store: Any, request_id: str) -> list[dict[str, Any]]:
|
||||
"""그 신청의 휴가 메일 기록(001) — 실패해도 상세 화면은 그대로."""
|
||||
try:
|
||||
@@ -851,7 +1001,7 @@ def edit_form(request: Request, request_id: str) -> HTMLResponse:
|
||||
{"reason": f"{req['status']} 상태에서는 수정할 수 없습니다.", "is_admin": is_admin(user)},
|
||||
status_code=409,
|
||||
)
|
||||
ctx = _form_context(request, user)
|
||||
ctx = _form_context(request, user, req)
|
||||
ctx.update(
|
||||
{
|
||||
"page_title": "휴가 신청 수정",
|
||||
@@ -876,6 +1026,9 @@ def update(
|
||||
end_half: str = Form("full"),
|
||||
reason: str = Form(""),
|
||||
action: str = Form("save"), # "save" | "submit"
|
||||
consult_email: list[str] = Form(default=[]),
|
||||
consult_message: list[str] = Form(default=[]),
|
||||
no_consult: str = Form(""),
|
||||
user: dict[str, Any] = Depends(_require_user),
|
||||
) -> RedirectResponse:
|
||||
store = _store(request)
|
||||
@@ -884,8 +1037,9 @@ def update(
|
||||
payload = _payload_from_form(
|
||||
vacation_type, start_date, end_date, start_half, end_half, reason
|
||||
)
|
||||
consults = _form_consults(store, user["email"], consult_email, consult_message, no_consult, action)
|
||||
try:
|
||||
store.update_request(request_id=request_id, owner=user["email"], payload=payload)
|
||||
store.update_request(request_id=request_id, owner=user["email"], payload=payload, consults=consults)
|
||||
if action == "submit":
|
||||
_notify(bg, request, "submitted", store.submit(request_id=request_id, owner=user["email"]), user)
|
||||
except KeyError:
|
||||
@@ -914,6 +1068,53 @@ def submit(
|
||||
return RedirectResponse(url=f"/vacation/{request_id}", status_code=303)
|
||||
|
||||
|
||||
@router.post("/{request_id}/consult")
|
||||
def consult_decide(
|
||||
request: Request,
|
||||
request_id: str,
|
||||
bg: BackgroundTasks,
|
||||
decision: str = Form(...), # "approve" | "reject"
|
||||
reject_reason: str = Form(""),
|
||||
user: dict[str, Any] = Depends(_require_login),
|
||||
) -> RedirectResponse:
|
||||
"""협의 결재 — 모두 승인하면 제출(결재자 승인 대기)로, 한 명이 반려하면 신청도 반려."""
|
||||
store = _store(request)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="vacation_db 미설정")
|
||||
try:
|
||||
req, event = store.decide_consult(request_id=request_id, email=user["email"], approve=decision == "approve",
|
||||
reason=reject_reason)
|
||||
except KeyError:
|
||||
raise HTTPException(status_code=404, detail="휴가 신청을 찾을 수 없습니다.")
|
||||
except PermissionError as exc:
|
||||
raise HTTPException(status_code=403, detail=str(exc))
|
||||
except ValueError as exc:
|
||||
raise HTTPException(status_code=409, detail=str(exc))
|
||||
if event:
|
||||
_notify(bg, request, event, req, user)
|
||||
return RedirectResponse(url=f"/vacation/{request_id}", status_code=303)
|
||||
|
||||
|
||||
@router.post("/{request_id}/mail-retry")
|
||||
def mail_retry(
|
||||
request: Request,
|
||||
request_id: str,
|
||||
bg: BackgroundTasks,
|
||||
user: dict[str, Any] = Depends(_require_login),
|
||||
) -> RedirectResponse:
|
||||
"""내가 보내다 실패한 메일 다시 보내기(Gmail 을 연결한 뒤 등) — 결과가 바로 화면에 나오게 기다렸다 돌아간다."""
|
||||
store = _store(request)
|
||||
if store is None:
|
||||
raise HTTPException(status_code=503, detail="vacation_db 미설정")
|
||||
req = store.get_request(request_id=request_id)
|
||||
if not req:
|
||||
raise HTTPException(status_code=404, detail="휴가 신청을 찾을 수 없습니다.")
|
||||
failed = _failed_mail(store, req, user["email"].lower())
|
||||
if failed:
|
||||
_notify(bg, request, failed["event"], req, user, now=True)
|
||||
return RedirectResponse(url=f"/vacation/{request_id}", status_code=303)
|
||||
|
||||
|
||||
@router.post("/{request_id}/approve")
|
||||
def approve(
|
||||
request: Request,
|
||||
|
||||
@@ -24,7 +24,8 @@ VACATION_TYPES: tuple[str, ...] = (
|
||||
)
|
||||
|
||||
# 신청 상태 워크플로
|
||||
STATUSES: tuple[str, ...] = ("작성중", "제출", "승인", "반려", "취소")
|
||||
# 협의중 = 협의자 승인 대기(2026-11-02, 마이그레이션 003) — 협의자가 모두 승인하면 제출(결재자 승인 대기)
|
||||
STATUSES: tuple[str, ...] = ("작성중", "협의중", "제출", "승인", "반려", "취소")
|
||||
|
||||
# 시작/종료일 구분
|
||||
HALVES: tuple[str, ...] = ("full", "am", "pm")
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
{#- 결재 라인 공용 조각(2026-11-02) — 아이콘 + 이름, 협의·결재 진행 상황 -#}
|
||||
{% macro face(p) -%}
|
||||
{% if p.picture %}<img class="vac-opt-face" src="{{ p.picture }}" alt="" referrerpolicy="no-referrer" />
|
||||
{%- else %}<span class="vac-opt-face is-ini">{{ (p.name or p.email)[:1] }}</span>{% endif %}
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro person(p) -%}
|
||||
<span class="vac-person">{{ face(p) }}<span class="vac-opt-name">{{ p.name or p.email }}</span></span>
|
||||
{%- endmacro %}
|
||||
|
||||
{% macro status_badge(status) -%}
|
||||
{% set badge = 'erp-badge-neutral' %}
|
||||
{% if status == '승인' %}{% set badge = 'erp-badge-success' %}
|
||||
{% elif status in ('제출', '협의중') %}{% set badge = 'erp-badge-inverse' %}
|
||||
{% elif status == '반려' %}{% set badge = 'erp-badge-danger' %}{% endif %}
|
||||
<span class="erp-badge {{ badge }}">{{ status }}</span>
|
||||
{%- endmacro %}
|
||||
|
||||
{#- 협의자별 상태 → 결재 상태. r.consults 필요 -#}
|
||||
{% macro progress(r, people) -%}
|
||||
{% set rejected_in_consult = r.consults | selectattr('state', 'equalto', '반려') | list %}
|
||||
<span class="vac-steps">
|
||||
{% for c in r.consults %}
|
||||
{% set p = people.get(c.email) or {'email': c.email, 'name': c.name, 'picture': ''} %}
|
||||
<span class="vac-step is-{{ {'대기': 'wait', '승인': 'ok', '반려': 'no'}[c.state] }}" title="협의 {{ c.state }}">{{ face(p) }}{{ p.name or p.email }} <b>{{ c.state }}</b></span>
|
||||
{% endfor %}
|
||||
{% if r.consults %}<span class="vac-step-arrow" aria-hidden="true">→</span>{% endif %}
|
||||
{% if r.status == '협의중' %}<span class="vac-step is-wait">결재 <b>협의 후</b></span>
|
||||
{% elif r.status == '제출' %}<span class="vac-step is-wait">결재 <b>대기</b></span>
|
||||
{% elif r.status == '승인' %}<span class="vac-step is-ok">결재 <b>승인</b></span>
|
||||
{% elif r.status == '반려' and not rejected_in_consult %}<span class="vac-step is-no">결재 <b>반려</b></span>
|
||||
{% elif r.status == '반려' %}<span class="vac-step">결재 <b>안 넘어감</b></span>
|
||||
{% elif r.status == '작성중' %}<span class="vac-step">결재 <b>제출 전</b></span>
|
||||
{% else %}<span class="vac-step">{{ r.status }}</span>{% endif %}
|
||||
</span>
|
||||
{%- endmacro %}
|
||||
@@ -1,10 +1,28 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% import "vacation/_macros.html" as vm %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027e" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="vac">
|
||||
<div class="erp-card vac-detail-card">
|
||||
{% if msg %}<p class="vac-opt-msg" role="status">{{ msg }}</p>{% endif %}
|
||||
{#- 내가 보내다 실패한 메일(2026-11-02) — Gmail 을 연결하고 다시 보낸다 -#}
|
||||
{% if failed_mail %}
|
||||
<div class="vac-opt-msg is-warn vac-mail-retry" role="alert">
|
||||
<b>{{ event_words.get(failed_mail.event, failed_mail.event) }} 메일을 보내지 못했습니다.</b>
|
||||
{% if gmail.connected or gmail.smtp %}
|
||||
<form method="post" action="/vacation/{{ req.id }}/mail-retry" class="vac-inline-form">
|
||||
<button type="submit" class="erp-btn erp-btn-primary">메일 다시 보내기</button>
|
||||
</form>
|
||||
{% elif gmail.available %}
|
||||
<span>내 Gmail 이 연결되어 있지 않습니다. 연결한 뒤 다시 보낼 수 있습니다.</span>
|
||||
<a class="erp-btn erp-btn-primary" href="/vacation/gmail/connect?next=/vacation/{{ req.id }}">Gmail 연결</a>
|
||||
{% else %}
|
||||
<span>메일을 보낼 방법이 설정되어 있지 않습니다. 관리자에게 알려 주세요.</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<div class="vac-detail-head">
|
||||
<div>
|
||||
@@ -13,7 +31,7 @@
|
||||
</div>
|
||||
{% set badge = 'erp-badge-neutral' %}
|
||||
{% if req.status == '승인' %}{% set badge = 'erp-badge-success' %}
|
||||
{% elif req.status == '제출' %}{% set badge = 'erp-badge-inverse' %}
|
||||
{% elif req.status in ('제출', '협의중') %}{% set badge = 'erp-badge-inverse' %}
|
||||
{% elif req.status == '반려' %}{% set badge = 'erp-badge-danger' %}{% endif %}
|
||||
<span class="erp-badge {{ badge }} vac-detail-status">{{ req.status }}</span>
|
||||
</div>
|
||||
@@ -24,7 +42,7 @@
|
||||
<div><dt>시작일</dt><dd>{{ req.start_date }} ({{ half_labels[req.start_half] }})</dd></div>
|
||||
<div><dt>종료일</dt><dd>{{ req.end_date }} ({{ half_labels[req.end_half] }})</dd></div>
|
||||
{% if req.approver_email %}
|
||||
<div><dt>승인자</dt><dd>{{ req.approver_email }}</dd></div>
|
||||
<div><dt>{{ '반려자' if req.status == '반려' else '승인자' }}</dt><dd>{{ req.approver_email }}</dd></div>
|
||||
<div><dt>결재일시</dt><dd>{{ req.decided_at }}</dd></div>
|
||||
{% endif %}
|
||||
</dl>
|
||||
@@ -43,6 +61,42 @@
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
{#- 결재 라인(2026-11-02) — 협의자별 상태·협의 내용(협의자에게는 자기 줄만, 서버가 거름), 통보자·결재자 -#}
|
||||
<div class="vac-detail-block vac-line">
|
||||
<div class="vac-detail-label">결재 진행</div>
|
||||
<p class="vac-line-progress">{{ vm.progress(req, people) }}</p>
|
||||
{% for c in req.consults %}
|
||||
{% set p = people.get(c.email) or {'email': c.email, 'name': c.name, 'picture': ''} %}
|
||||
<div class="vac-line-consult">
|
||||
<div>{{ vm.person(p) }} <span class="erp-muted">협의 {{ c.state }}{% if c.decided_at %} · {{ c.decided_at[5:16] | replace('T', ' ') }}{% endif %}</span></div>
|
||||
{% if c.message %}<p>{{ c.message }}</p>{% endif %}
|
||||
{% if c.comment %}<p class="vac-line-comment">반려 사유: {{ c.comment }}</p>{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
<div class="vac-line-row">
|
||||
<span class="vac-line-label">통보자</span>
|
||||
<div class="vac-line-body">{% for p in line.notifiers %}{{ vm.person(p) }}{% else %}<span class="erp-muted">없음</span>{% endfor %}</div>
|
||||
</div>
|
||||
<div class="vac-line-row">
|
||||
<span class="vac-line-label">결재자</span>
|
||||
<div class="vac-line-body">{% for p in line.approvers %}{{ vm.person(p) }}{% else %}<span class="erp-muted">ERP 관리자</span>{% endfor %}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{% if can_consult %}
|
||||
<div class="vac-approve-box">
|
||||
<form method="post" action="/vacation/{{ req.id }}/consult" class="vac-inline-form">
|
||||
<input type="hidden" name="decision" value="approve" />
|
||||
<button type="submit" class="erp-btn erp-btn-primary">협의 승인</button>
|
||||
</form>
|
||||
<form method="post" action="/vacation/{{ req.id }}/consult" class="vac-reject-form">
|
||||
<input type="hidden" name="decision" value="reject" />
|
||||
<input class="erp-input" type="text" name="reject_reason" placeholder="반려 사유" required />
|
||||
<button type="submit" class="erp-btn erp-btn-danger">협의 반려</button>
|
||||
</form>
|
||||
</div>
|
||||
{% endif %}
|
||||
|
||||
<!-- ── 승인자 액션 (제출 상태) ── -->
|
||||
{% if is_approver and req.status == '제출' %}
|
||||
<div class="vac-approve-box">
|
||||
@@ -91,7 +145,7 @@
|
||||
</form>
|
||||
{% endif %}
|
||||
|
||||
{% if req.status in ('작성중', '제출', '반려') and (is_owner or is_admin) %}
|
||||
{% if req.status in ('작성중', '협의중', '제출', '반려') and (is_owner or is_admin) %}
|
||||
<form method="post" action="/vacation/{{ req.id }}/delete" class="vac-inline-form"
|
||||
onsubmit="return confirm('이 휴가 신청을 삭제할까요? (복구 불가)');">
|
||||
<button type="submit" class="erp-btn erp-btn-danger">삭제</button>
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% import "vacation/_macros.html" as vm %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027e" />
|
||||
{#- 날짜 칸 = 프로젝트와 같은 아사나식 날짜 팝업(2026-10-27, erp-datepop) -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102c" />
|
||||
{#- 달력 = ERP 공용 달력 서식(2026-11-02, erp-datepop mountRange) -#}
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261027a" />{% endblock %}
|
||||
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261102a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="vac">
|
||||
@@ -11,51 +12,112 @@
|
||||
{% set action = '/vacation/new' if mode == 'new' else '/vacation/' ~ req.id ~ '/edit' %}
|
||||
<form id="vac-form" method="post" action="{{ action }}" class="erp-card vac-form-card">
|
||||
|
||||
<div class="vac-form-grid">
|
||||
<label class="erp-field"><span>휴가 종류 *</span>
|
||||
<select class="erp-select" name="vacation_type" id="vac-type" required>
|
||||
{% for t in vacation_types %}
|
||||
<option value="{{ t }}" {% if req and req.vacation_type == t %}selected{% endif %}>{{ t }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<fieldset class="vac-types">
|
||||
<legend>휴가 종류</legend>
|
||||
{% for t in vacation_types %}
|
||||
<label class="vac-type"><input type="radio" name="vacation_type" value="{{ t }}"
|
||||
{% if (req and req.vacation_type == t) or (not req and loop.first) %}checked{% endif %} /><span>{{ t }}</span></label>
|
||||
{% endfor %}
|
||||
</fieldset>
|
||||
|
||||
<label class="erp-field"><span>시작일 *</span>
|
||||
<input class="erp-input" type="date" name="start_date" id="vac-start" required
|
||||
value="{{ req.start_date if req else default_date }}" />
|
||||
</label>
|
||||
<div class="vac-form-main">
|
||||
<div class="vac-range-cal" id="vac-cal"></div>
|
||||
|
||||
<label class="erp-field" id="vac-start-half-field"><span>시작 구분</span>
|
||||
<select class="erp-select" name="start_half" id="vac-start-half">
|
||||
{% for h in halves %}
|
||||
<option value="{{ h }}" {% if req and req.start_half == h %}selected{% endif %}>{{ half_labels[h] }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<div class="vac-form-side">
|
||||
<input type="hidden" name="start_date" id="vac-start" value="{{ req.start_date if req else '' }}" />
|
||||
<input type="hidden" name="end_date" id="vac-end" value="{{ req.end_date if req else '' }}" />
|
||||
<div class="vac-form-grid">
|
||||
<label class="erp-field"><span>시작일</span>
|
||||
<input class="erp-input" type="text" id="vac-start-show" readonly placeholder="달력에서 선택" />
|
||||
</label>
|
||||
<label class="erp-field" id="vac-end-field"><span>종료일</span>
|
||||
<input class="erp-input" type="text" id="vac-end-show" readonly placeholder="달력에서 선택" />
|
||||
</label>
|
||||
<label class="erp-field" id="vac-start-half-field"><span>시작 구분</span>
|
||||
<select class="erp-select" name="start_half" id="vac-start-half">
|
||||
{% for h in halves %}
|
||||
<option value="{{ h }}" {% if req and req.start_half == h %}selected{% endif %}>{{ half_labels[h] }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label class="erp-field" id="vac-end-half-field"><span>종료 구분</span>
|
||||
<select class="erp-select" name="end_half" id="vac-end-half">
|
||||
{% for h in halves %}
|
||||
<option value="{{ h }}" {% if req and req.end_half == h %}selected{% endif %}>{{ half_labels[h] }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label class="erp-field" id="vac-end-field"><span>종료일 *</span>
|
||||
<input class="erp-input" type="date" name="end_date" id="vac-end"
|
||||
value="{{ req.end_date if req else default_date }}" />
|
||||
</label>
|
||||
<div class="vac-days-preview">
|
||||
예상 사용 일수: <strong id="vac-days-out">—</strong>
|
||||
<span class="erp-muted">(주말 · 공휴일 제외)</span>
|
||||
</div>
|
||||
|
||||
<label class="erp-field" id="vac-end-half-field"><span>종료 구분</span>
|
||||
<select class="erp-select" name="end_half" id="vac-end-half">
|
||||
{% for h in halves %}
|
||||
<option value="{{ h }}" {% if req and req.end_half == h %}selected{% endif %}>{{ half_labels[h] }}</option>
|
||||
{% endfor %}
|
||||
</select>
|
||||
</label>
|
||||
<label class="erp-field vac-reason"><span>휴가 사유</span>
|
||||
<textarea class="erp-input" name="reason" rows="5"
|
||||
placeholder="휴가 사유를 입력하세요.">{{ req.reason if req else '' }}</textarea>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label class="erp-field vac-full"><span>사유</span>
|
||||
<textarea class="erp-input" name="reason" rows="3"
|
||||
placeholder="휴가 사유를 입력하세요.">{{ req.reason if req else '' }}</textarea>
|
||||
</label>
|
||||
{#- 결재 라인 — 협의자(구성원 전체에서 복수, 사람마다 협의 내용) · 통보자·결재자(옵션 값, 고칠 수 없음) -#}
|
||||
<section class="vac-line" aria-label="결재 라인">
|
||||
<h3>결재 라인</h3>
|
||||
|
||||
<div class="vac-days-preview">
|
||||
예상 사용 일수: <strong id="vac-days-out">—</strong>
|
||||
<span class="erp-muted">(주말 · 공휴일 제외)</span>
|
||||
</div>
|
||||
<div class="vac-line-row">
|
||||
<span class="vac-line-label">협의자</span>
|
||||
<div class="vac-line-body">
|
||||
<button type="button" class="erp-btn erp-btn-outline" id="vac-pick-btn" aria-expanded="false"
|
||||
{% if not consult_ready %}disabled{% endif %}>구성원 선택</button>
|
||||
<label class="vac-check"><input type="checkbox" name="no_consult" id="vac-no-consult" value="1"
|
||||
{% if not consult_ready %}checked disabled{% endif %} /> 협의자 없음</label>
|
||||
{% if not consult_ready %}<span class="erp-muted">협의자 기능은 DB 마이그레이션 003 적용 뒤에 쓸 수 있습니다.</span>{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ul class="vac-pick" id="vac-pick" hidden>
|
||||
{% for m in members %}
|
||||
<li>
|
||||
<label class="vac-opt-person">
|
||||
<input type="checkbox" data-email="{{ m.email }}" {% if m.email in consult_chosen %}checked{% endif %} />
|
||||
{{ vm.person(m) }}
|
||||
</label>
|
||||
</li>
|
||||
{% else %}
|
||||
<li class="erp-muted">고를 수 있는 구성원이 없습니다.</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
|
||||
<div class="vac-consult-box" id="vac-consult-box" hidden>
|
||||
<p class="vac-line-sub">협의자 전달 사항 <span class="erp-muted">— 협의자마다 자기 내용만 메일로 받습니다.</span></p>
|
||||
{% for m in members %}
|
||||
{% set on = m.email in consult_chosen %}
|
||||
<div class="vac-consult-row" data-email="{{ m.email }}" {% if not on %}hidden{% endif %}>
|
||||
<input type="hidden" name="consult_email" value="{{ m.email }}" {% if not on %}disabled{% endif %} />
|
||||
{{ vm.person(m) }}
|
||||
<textarea class="erp-input" name="consult_message" rows="2" placeholder="{{ m.name }}님에게 전달할 내용"
|
||||
aria-label="{{ m.name }} 협의 내용" {% if not on %}disabled{% endif %}>{{ consult_chosen.get(m.email, '') }}</textarea>
|
||||
<button type="button" class="vac-consult-x" aria-label="{{ m.name }} 빼기">✕</button>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<div class="vac-line-row">
|
||||
<span class="vac-line-label">통보자</span>
|
||||
<div class="vac-line-body">
|
||||
{% for p in line.notifiers %}{{ vm.person(p) }}{% else %}<span class="erp-muted">없음(옵션에서 지정)</span>{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
<div class="vac-line-row">
|
||||
<span class="vac-line-label">결재자</span>
|
||||
<div class="vac-line-body">
|
||||
{% for p in line.approvers %}{{ vm.person(p) }}{% else %}<span class="erp-muted">ERP 관리자(옵션에서 지정)</span>{% endfor %}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<p class="vac-form-err" id="vac-form-err" role="alert" hidden></p>
|
||||
|
||||
<div class="erp-page-actions vac-form-actions">
|
||||
<button type="submit" class="erp-btn erp-btn-primary" name="action" value="submit">제출</button>
|
||||
@@ -72,5 +134,5 @@
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script type="application/json" id="vac-holidays">{{ holidays | tojson }}</script>
|
||||
<script src="/static/erp-datepop.js?v=20261027b" defer></script>
|
||||
<script src="/static/vacation.js?v=20261027c" defer></script>{% endblock %}
|
||||
<script src="/static/erp-datepop.js?v=20261102a" defer></script>
|
||||
<script src="/static/vacation.js?v=20261102a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027e" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="vac">
|
||||
@@ -9,6 +9,12 @@
|
||||
<div class="vac-actions">
|
||||
<div class="vac-actions-main">
|
||||
<a class="erp-btn erp-btn-primary" href="/vacation/new">+ 휴가 신청</a>
|
||||
<a class="erp-btn erp-btn-outline" href="/vacation/mine">내 신청 내역</a>
|
||||
{% if consult_count %}
|
||||
<a class="erp-btn erp-btn-outline" href="/vacation/pending#consults">협의 대기
|
||||
<span class="erp-badge erp-badge-inverse vac-mini">{{ consult_count }}</span>
|
||||
</a>
|
||||
{% endif %}
|
||||
{% if is_approver %}
|
||||
<a class="erp-btn erp-btn-outline" href="/vacation/pending">승인 대기
|
||||
{% if pending_count %}<span class="erp-badge erp-badge-inverse vac-mini">{{ pending_count }}</span>{% endif %}
|
||||
@@ -85,7 +91,7 @@
|
||||
</div>
|
||||
|
||||
<div class="vac-legend">
|
||||
<span class="vac-leg"><i class="vac-dot vac-bar-submit"></i>제출</span>
|
||||
<span class="vac-leg"><i class="vac-dot vac-bar-submit"></i>협의·제출</span>
|
||||
<span class="vac-leg"><i class="vac-dot vac-bar-approve"></i>승인</span>
|
||||
<span class="vac-leg"><i class="vac-dot vac-bar-reject"></i>반려</span>
|
||||
<span class="vac-leg"><i class="vac-dot vac-bar-cancel"></i>취소</span>
|
||||
@@ -108,7 +114,7 @@
|
||||
<strong>{{ r.owner_name or r.owner }}</strong>
|
||||
{% set badge = 'erp-badge-neutral' %}
|
||||
{% if r.status == '승인' %}{% set badge = 'erp-badge-success' %}
|
||||
{% elif r.status == '제출' %}{% set badge = 'erp-badge-inverse' %}
|
||||
{% elif r.status in ('제출', '협의중') %}{% set badge = 'erp-badge-inverse' %}
|
||||
{% elif r.status == '반려' %}{% set badge = 'erp-badge-danger' %}{% endif %}
|
||||
<span class="erp-badge {{ badge }}">{{ r.status }}</span>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% import "vacation/_macros.html" as vm %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="vac vac-options">
|
||||
<div class="vac-actions">
|
||||
<div class="vac-actions-main">
|
||||
<a class="erp-btn erp-btn-outline" href="/vacation/">◀ 달력</a>
|
||||
<a class="erp-btn erp-btn-primary" href="/vacation/new">+ 휴가 신청</a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="erp-card">
|
||||
{% if items %}
|
||||
<div class="erp-table-wrap">
|
||||
<table class="erp-table">
|
||||
<thead><tr><th>휴가종류</th><th>기간</th><th>일수</th><th>상태</th><th>결재 진행</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in items %}
|
||||
<tr>
|
||||
<td><a href="/vacation/{{ r.id }}">{{ r.vacation_type }}</a></td>
|
||||
<td>{{ r.start_date }}{% if r.end_date != r.start_date %} ~ {{ r.end_date }}{% endif %}</td>
|
||||
<td>{{ r.days }}</td>
|
||||
<td>{{ vm.status_badge(r.status) }}</td>
|
||||
<td>{{ vm.progress(r, people) }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="erp-muted">휴가 신청 내역이 없습니다.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
</section>
|
||||
{% endblock %}
|
||||
@@ -1,10 +1,10 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{#- 휴가 옵션(2026-10-27) — 승인자·승인 통보자·잔여 연차(수정 = ERP 관리자·승인자·통보자, 나머지는 보기만) + 내 Gmail 연결(누구나).
|
||||
메일: 제출 = 승인자·통보자, 승인·반려 = 승인자·통보자·신청자. 보내는 사람 = 처리한 사람 본인 Gmail(없으면 회사 메일). -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027e" />
|
||||
메일: 제출 = 승인자·통보자(+ 협의자마다 자기 몫), 협의 완료·승인·반려 = 승인자·통보자·신청자. 보내는 사람 = 처리한 사람 본인 Gmail(없으면 회사 메일). -#}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102c" />
|
||||
<link rel="stylesheet" href="/static/vendor/material-symbols/material-symbols.css" />
|
||||
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261027a" />{% endblock %}
|
||||
<link rel="stylesheet" href="/static/erp-datepop.css?v=20261102a" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="vac vac-options">
|
||||
@@ -149,5 +149,5 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/erp-datepop.js?v=20261027b" defer></script>
|
||||
<script src="/static/vacation.js?v=20261027c" defer></script>{% endblock %}
|
||||
{% block scripts %}<script src="/static/erp-datepop.js?v=20261102a" defer></script>
|
||||
<script src="/static/vacation.js?v=20261102a" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,17 +1,60 @@
|
||||
{% extends "erp_base.html" %}
|
||||
{% import "vacation/_macros.html" as vm %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261027e" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/vacation.css?v=20261102c" />{% endblock %}
|
||||
|
||||
{% block content %}
|
||||
<section class="vac">
|
||||
<div class="erp-card">
|
||||
<section class="vac vac-options">
|
||||
{#- 협의 대기(2026-11-02) — 내가 협의자인 신청. 내 몫 협의 내용만 -#}
|
||||
<div class="erp-card" id="consults">
|
||||
<div class="vac-card-head"><h2>협의 대기 <span class="erp-muted vac-opt-count">{{ consult_items | length }}건</span></h2></div>
|
||||
{% if consult_items %}
|
||||
<div class="erp-table-wrap">
|
||||
<table class="erp-table vac-pending-table">
|
||||
<thead>
|
||||
<tr><th>신청자</th><th>휴가종류</th><th>기간</th><th>일수</th><th>협의 내용</th><th class="vac-act-col">동작</th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{% for r in consult_items %}
|
||||
<tr>
|
||||
<td><a href="/vacation/{{ r.id }}">{{ r.owner_name or r.owner }}</a></td>
|
||||
<td>{{ r.vacation_type }}</td>
|
||||
<td>{{ r.start_date }}{% if r.end_date != r.start_date %} ~ {{ r.end_date }}{% endif %}</td>
|
||||
<td>{{ r.days }}</td>
|
||||
<td class="vac-reason-cell">{{ r.my_message or '-' }}</td>
|
||||
<td class="vac-act-col">
|
||||
<div class="vac-pending-acts">
|
||||
<form method="post" action="/vacation/{{ r.id }}/consult" class="vac-inline-form">
|
||||
<input type="hidden" name="decision" value="approve" />
|
||||
<button type="submit" class="erp-btn erp-btn-primary erp-btn-sm">승인</button>
|
||||
</form>
|
||||
<form method="post" action="/vacation/{{ r.id }}/consult" class="vac-reject-form">
|
||||
<input type="hidden" name="decision" value="reject" />
|
||||
<input class="erp-input erp-input-sm" type="text" name="reject_reason" placeholder="반려 사유" required />
|
||||
<button type="submit" class="erp-btn erp-btn-danger erp-btn-sm">반려</button>
|
||||
</form>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% else %}
|
||||
<p class="erp-muted">협의할 휴가 신청이 없습니다.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
|
||||
{% if is_approver %}
|
||||
<div class="erp-card" id="approvals">
|
||||
<div class="vac-card-head"><h2>승인 대기 <span class="erp-muted vac-opt-count">{{ items | length }}건</span></h2></div>
|
||||
{% if items %}
|
||||
<div class="erp-table-wrap">
|
||||
<table class="erp-table vac-pending-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>신청자</th><th>휴가종류</th><th>기간</th><th>일수</th>
|
||||
<th>사유</th><th class="vac-act-col">동작</th>
|
||||
<th>사유</th><th>협의</th><th class="vac-act-col">동작</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -22,6 +65,11 @@
|
||||
<td>{{ r.start_date }}{% if r.end_date != r.start_date %} ~ {{ r.end_date }}{% endif %}</td>
|
||||
<td>{{ r.days }}</td>
|
||||
<td class="vac-reason-cell erp-muted">{{ r.reason }}</td>
|
||||
<td class="vac-reason-cell">
|
||||
{% for c in r.consults %}
|
||||
<div class="vac-consult-brief"><b>{{ (people.get(c.email) or c).name or c.email }}</b> {{ c.state }}{% if c.message %} — {{ c.message }}{% endif %}</div>
|
||||
{% else %}<span class="erp-muted">없음</span>{% endfor %}
|
||||
</td>
|
||||
<td class="vac-act-col">
|
||||
<div class="vac-pending-acts">
|
||||
<form method="post" action="/vacation/{{ r.id }}/approve" class="vac-inline-form">
|
||||
@@ -43,5 +91,6 @@
|
||||
<p class="erp-muted">승인 대기 중인 휴가 신청이 없습니다.</p>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
+37
-1
@@ -278,7 +278,6 @@
|
||||
.cf24-shortcuts {
|
||||
font-size: var(--text-caption, 12px);
|
||||
color: #79a6dd;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 편집 폼과 코드 칸은 **줄어들지 않는다.** 아래 「예약 적용」·「버전 이력」을 펼치면
|
||||
@@ -467,6 +466,43 @@
|
||||
.cf24-t-com { color: #6e7781; font-style: italic; } /* 주석 */
|
||||
.cf24-t-doc { color: #6639ba; } /* DOCTYPE 등 선언 */
|
||||
|
||||
/* 색칠 층 안에서 <img> 태그만 마우스 판정을 받는다(미리보기용). 평소에는 위의 textarea 가 가린다. */
|
||||
.cf24-t-img { pointer-events: auto; }
|
||||
.cf24-t-img-on { background: #ffa500; }
|
||||
|
||||
/* 마우스를 통과시킨다 — 미리보기가 소스를 덮어도 hover 가 끊기지 않게. */
|
||||
.cf24-img-preview {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
right: 0;
|
||||
z-index: 1100;
|
||||
box-sizing: border-box;
|
||||
width: 500px;
|
||||
border-left: 1px solid var(--color-subtle-ash, #e5e5e5);
|
||||
background: var(--color-canvas-white, #fff);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* 한 줄 고정 높이 — 아래 이미지 높이가 이 값을 뺀 만큼이다. */
|
||||
.cf24-img-preview-name {
|
||||
box-sizing: border-box;
|
||||
height: 40px;
|
||||
padding: 0 12px;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
line-height: 40px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.cf24-img-preview img {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: calc(100vh - 40px);
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.cf24-code-hint {
|
||||
font-size: var(--text-caption, 12px);
|
||||
color: var(--color-midtone-gray, #737373);
|
||||
|
||||
@@ -102,6 +102,16 @@
|
||||
.pj-dp-day { isolation: isolate; }
|
||||
.pj-dp-day::before { z-index: -1; }
|
||||
|
||||
/* 붙박이 기간 달력(mountRange) — 시작~종료 둥근 막대, 양 끝은 선택 원. 줄이 바뀌는 곳도 둥글게 */
|
||||
.pj-dp-day.is-band::after {
|
||||
content: ""; position: absolute; top: 2px; height: 30px; left: 0; right: 0; z-index: -2; background: #dbe6fb;
|
||||
}
|
||||
.pj-dp-day.is-band-start::after { left: 50%; }
|
||||
.pj-dp-day.is-band-end::after { right: 50%; }
|
||||
.pj-dp-day.is-row-first::after { left: 4px; border-radius: 15px 0 0 15px; }
|
||||
.pj-dp-day.is-row-last::after { right: 4px; border-radius: 0 15px 15px 0; }
|
||||
.pj-dp-day.is-band-start.is-row-last::after, .pj-dp-day.is-band-end.is-row-first::after { display: none; }
|
||||
|
||||
.pj-dp-foot {
|
||||
display: flex; justify-content: space-between; align-items: center;
|
||||
margin-top: 8px; padding-top: 8px; border-top: 1px solid #eef0f2;
|
||||
|
||||
+88
-28
@@ -4,7 +4,7 @@
|
||||
· 브라우저 기본 달력(input[type=date])은 숨기고 그 옆에 날짜 버튼을 둔다 — input 은 값 저장소(.value 읽기/쓰기·change 이벤트 그대로).
|
||||
· 팝업: 위 칸(시작일·종료일 — 직접 입력 2026-10-27 / 10.27 / 10월 27일 / 1027, Enter), 월 달력(일·공휴일 빨강, 토 파랑,
|
||||
공휴일 이름은 숫자 밑, 오늘 테두리, 기간 옅은 파랑), 오늘 · 지우기. 바깥 클릭·Esc 로 닫힘, 앵커 아래(자리 없으면 위).
|
||||
window.ErpDatePop = { open(anchor, opts), close(), enhance(input, opts), enhanceRange(startInput, endInput, opts), fmt(iso), fmtFull(iso) } */
|
||||
window.ErpDatePop = { open(anchor, opts), close(), enhance(input, opts), enhanceRange(startInput, endInput, opts), mountRange(box, opts), fmt(iso), fmtFull(iso) } */
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
@@ -62,6 +62,34 @@
|
||||
}
|
||||
const HOLIDAY_SHORT = { "부처님오신날": "석가탄신일", "추석·개천절": "추석" };
|
||||
|
||||
// 요일 줄 + 6주 날짜 칸(팝업·붙박이 달력 공용). extra(iso) = 그 칸에 더할 클래스 목록
|
||||
function gridHtml(viewY, viewM, holidays, today, extra) {
|
||||
const first = new Date(viewY, viewM, 1);
|
||||
const gridStart = new Date(viewY, viewM, 1 - first.getDay());
|
||||
let days = "";
|
||||
for (let i = 0; i < 42; i++) {
|
||||
const d = new Date(gridStart.getFullYear(), gridStart.getMonth(), gridStart.getDate() + i);
|
||||
const iso = isoOf(d);
|
||||
const cls = ["pj-dp-day"];
|
||||
if (d.getMonth() !== viewM) cls.push("is-out");
|
||||
const holName = holidays[iso] || "";
|
||||
if (d.getDay() === 0 || holName) cls.push("is-sun");
|
||||
else if (d.getDay() === 6) cls.push("is-sat");
|
||||
if (iso === today) cls.push("is-today");
|
||||
cls.push.apply(cls, extra(iso, d));
|
||||
if (holName) cls.push("has-hol");
|
||||
const holShort = /\s대체$/.test(holName) ? "대체휴일" : (HOLIDAY_SHORT[holName] || holName);
|
||||
days += '<button type="button" class="' + cls.join(" ") + '" data-iso="' + iso + '"' +
|
||||
(holName ? ' title="' + esc(holName) + '"' : "") + ">" +
|
||||
'<span class="pj-dp-num">' + d.getDate() + "</span>" +
|
||||
(holName ? '<span class="pj-dp-hol">' + esc(holShort) + "</span>" : "") + "</button>";
|
||||
}
|
||||
return '<div class="pj-dp-grid">' +
|
||||
["일", "월", "화", "수", "목", "금", "토"].map(function (w, i) {
|
||||
return '<span class="pj-dp-wd' + (i === 0 ? " is-sun" : i === 6 ? " is-sat" : "") + '">' + w + "</span>";
|
||||
}).join("") + days + "</div>";
|
||||
}
|
||||
|
||||
let popEl = null, cleanup = null;
|
||||
function close() {
|
||||
if (cleanup) cleanup();
|
||||
@@ -100,27 +128,6 @@
|
||||
'" data-kind="' + kind + '" placeholder="' + esc(labels[kind]) + '" value="' + esc(fmtField(val)) + '" autocomplete="off" />';
|
||||
}
|
||||
function render() {
|
||||
const first = new Date(viewY, viewM, 1);
|
||||
const gridStart = new Date(viewY, viewM, 1 - first.getDay());
|
||||
let days = "";
|
||||
for (let i = 0; i < 42; i++) {
|
||||
const d = new Date(gridStart.getFullYear(), gridStart.getMonth(), gridStart.getDate() + i);
|
||||
const iso = isoOf(d);
|
||||
const cls = ["pj-dp-day"];
|
||||
if (d.getMonth() !== viewM) cls.push("is-out");
|
||||
const holName = holidays[iso] || "";
|
||||
if (d.getDay() === 0 || holName) cls.push("is-sun");
|
||||
else if (d.getDay() === 6) cls.push("is-sat");
|
||||
if (iso === today) cls.push("is-today");
|
||||
if (iso === due || (showStart && iso === start)) cls.push("is-selected");
|
||||
if (showStart && start && due && iso > start && iso < due) cls.push("is-inrange");
|
||||
if (holName) cls.push("has-hol");
|
||||
const holShort = /\s대체$/.test(holName) ? "대체휴일" : (HOLIDAY_SHORT[holName] || holName);
|
||||
days += '<button type="button" class="' + cls.join(" ") + '" data-iso="' + iso + '"' +
|
||||
(holName ? ' title="' + esc(holName) + '"' : "") + ">" +
|
||||
'<span class="pj-dp-num">' + d.getDate() + "</span>" +
|
||||
(holName ? '<span class="pj-dp-hol">' + esc(holShort) + "</span>" : "") + "</button>";
|
||||
}
|
||||
pop.innerHTML =
|
||||
'<div class="pj-dp-fields">' +
|
||||
(opts.allowStart ? (showStart ? field("start", start) : '<button type="button" class="pj-dp-addstart">+ ' + esc(labels.start) + "</button>") : "") +
|
||||
@@ -133,11 +140,12 @@
|
||||
'<button type="button" class="pj-dp-navbtn" data-nav="1" title="다음 달"><span class="material-symbols-outlined">chevron_right</span></button>' +
|
||||
(opts.yearNav ? '<button type="button" class="pj-dp-navbtn" data-nav="12" title="1년 뒤"><span class="material-symbols-outlined">keyboard_double_arrow_right</span></button>' : "") +
|
||||
"</div>" +
|
||||
'<div class="pj-dp-grid">' +
|
||||
["일", "월", "화", "수", "목", "금", "토"].map(function (w, i) {
|
||||
return '<span class="pj-dp-wd' + (i === 0 ? " is-sun" : i === 6 ? " is-sat" : "") + '">' + w + "</span>";
|
||||
}).join("") + days +
|
||||
"</div>" +
|
||||
gridHtml(viewY, viewM, holidays, today, function (iso) {
|
||||
const c = [];
|
||||
if (iso === due || (showStart && iso === start)) c.push("is-selected");
|
||||
if (showStart && start && due && iso > start && iso < due) c.push("is-inrange");
|
||||
return c;
|
||||
}) +
|
||||
'<div class="pj-dp-foot">' +
|
||||
'<button type="button" class="pj-dp-link pj-dp-today">오늘</button>' +
|
||||
(opts.clear === false ? "" : '<button type="button" class="pj-dp-link pj-dp-clear">지우기</button>') +
|
||||
@@ -345,5 +353,57 @@
|
||||
return { sync: sync, buttons: btns };
|
||||
}
|
||||
|
||||
window.ErpDatePop = { open: open, close: close, enhance: enhance, enhanceRange: enhanceRange, fmt: fmt, fmtFull: fmtFull, parse: parseTyped };
|
||||
// 화면에 붙박이는 기간 달력(2026-11-02, 휴가 신청) — 팝업과 같은 달력 서식(.pj-dp-*).
|
||||
// 첫 클릭 = 시작일(동그라미), 다음 클릭 = 종료일(둥근 막대), 그다음 클릭 = 새로 시작. 시작일보다 앞을 누르면 그 날이 새 시작일.
|
||||
// opts: { start, end, holidays, single() — true 면 클릭마다 하루, onChange(start, end) }. 반환 { set(start, end) }
|
||||
function mountRange(box, opts) {
|
||||
const holidays = opts.holidays || {};
|
||||
const today = isoToday();
|
||||
let start = opts.start || "", end = opts.end || opts.start || "", picking = false;
|
||||
const base = new Date((start || today) + "T00:00:00");
|
||||
let viewY = base.getFullYear(), viewM = base.getMonth();
|
||||
function bandClasses(iso, d) {
|
||||
if (!start || iso < start || iso > end) return [];
|
||||
if (start === end) return ["is-selected"];
|
||||
const c = ["is-band"];
|
||||
if (iso === start) c.push("is-selected", "is-band-start");
|
||||
else if (iso === end) c.push("is-selected", "is-band-end");
|
||||
if (d.getDay() === 0) c.push("is-row-first");
|
||||
if (d.getDay() === 6) c.push("is-row-last");
|
||||
return c;
|
||||
}
|
||||
function render() {
|
||||
box.innerHTML =
|
||||
'<div class="pj-dp-nav">' +
|
||||
'<button type="button" class="pj-dp-navbtn" data-nav="-1" title="이전 달"><span class="material-symbols-outlined">chevron_left</span></button>' +
|
||||
'<span class="pj-dp-title">' + viewY + "년 " + (viewM + 1) + "월</span>" +
|
||||
'<button type="button" class="pj-dp-navbtn" data-nav="1" title="다음 달"><span class="material-symbols-outlined">chevron_right</span></button>' +
|
||||
"</div>" + gridHtml(viewY, viewM, holidays, today, bandClasses);
|
||||
}
|
||||
box.addEventListener("click", function (e) {
|
||||
const nav = e.target.closest(".pj-dp-navbtn");
|
||||
if (nav) {
|
||||
const d = new Date(viewY, viewM + +nav.dataset.nav, 1);
|
||||
viewY = d.getFullYear(); viewM = d.getMonth();
|
||||
render();
|
||||
return;
|
||||
}
|
||||
const day = e.target.closest(".pj-dp-day");
|
||||
if (!day) return;
|
||||
const iso = day.dataset.iso;
|
||||
if (!picking || iso < start || (opts.single && opts.single())) {
|
||||
start = end = iso;
|
||||
picking = !(opts.single && opts.single());
|
||||
} else {
|
||||
end = iso;
|
||||
picking = false;
|
||||
}
|
||||
render();
|
||||
if (opts.onChange) opts.onChange(start, end);
|
||||
});
|
||||
render();
|
||||
return { set: function (s, e) { start = s; end = e; picking = false; render(); } };
|
||||
}
|
||||
|
||||
window.ErpDatePop = { open: open, close: close, enhance: enhance, enhanceRange: enhanceRange, mountRange: mountRange, fmt: fmt, fmtFull: fmtFull, parse: parseTyped };
|
||||
})();
|
||||
|
||||
@@ -192,6 +192,23 @@
|
||||
.io-mail-fields input[readonly] { background: var(--color-ghost-gray); color: #3d3f42; }
|
||||
.io-mail-sentlist { margin: 0 0 12px; padding: 10px 12px; border-radius: 8px; background: #f3fbf5; border: 1px solid #cdeed6; font-size: 12.5px; }
|
||||
.io-mail-sentlist ul { margin: 4px 0 0; padding-left: 18px; }
|
||||
/* 발주 메일 본문 서식 막대(2026-10-27) */
|
||||
.io-rte { position: relative; display: flex; flex-wrap: wrap; align-items: center; gap: 2px; padding: 4px 6px; border: 1px solid var(--color-subtle-ash); border-bottom: 0; border-radius: 8px 8px 0 0; background: #fafbfc; }
|
||||
.io-rte + .io-rte-hint + .io-mail-preview { border-radius: 0 0 8px 8px; }
|
||||
.io-rte-btn { display: inline-flex; align-items: center; justify-content: center; min-width: 28px; height: 28px; padding: 0 6px; border: 0; border-radius: 6px; background: none; color: #3d3f42; font-size: 14px; cursor: pointer; }
|
||||
.io-rte-btn:hover { background: var(--color-ghost-gray); }
|
||||
.io-rte-btn.is-active { background: #e3ebfb; color: #1a56c4; }
|
||||
.io-rte-a { font-weight: 700; border-bottom: 3px solid #d93025; line-height: 1; padding: 0 1px; }
|
||||
.io-rte-size { height: 28px; padding: 0 6px; border: 1px solid var(--color-subtle-ash); border-radius: 6px; background: #fff; font-size: 12.5px; }
|
||||
.io-rte-sep { width: 1px; height: 18px; margin: 0 4px; background: var(--color-subtle-ash); }
|
||||
.io-rte-reset { margin-left: auto; font-size: 12.5px; }
|
||||
.io-rte-pop { position: absolute; z-index: 5; display: flex; flex-wrap: wrap; gap: 6px; align-items: center; max-width: 320px; padding: 8px; border: 1px solid var(--color-subtle-ash); border-radius: 8px; background: #fff; box-shadow: 0 6px 20px rgba(0, 0, 0, .12); }
|
||||
.io-rte-pop[hidden] { display: none; }
|
||||
.io-rte-pop .io-in { width: 220px; }
|
||||
.io-rte-sw { width: 22px; height: 22px; padding: 0; border: 1px solid rgba(0, 0, 0, .15); border-radius: 4px; cursor: pointer; }
|
||||
.io-rte-sw:hover { outline: 2px solid #1a56c4; outline-offset: 1px; }
|
||||
.io-rte-sw.is-none { background: linear-gradient(to top right, #fff 45%, #d93025 45%, #d93025 55%, #fff 55%) !important; }
|
||||
.io-rte-hint { margin: 0; padding: 4px 8px; border-left: 1px solid var(--color-subtle-ash); border-right: 1px solid var(--color-subtle-ash); background: #fafbfc; font-size: 12px; color: var(--color-midtone-gray); }
|
||||
.io-mail-preview { width: 100%; height: 380px; border: 1px solid var(--color-subtle-ash); border-radius: 8px; background: #fff; }
|
||||
.io-mail-connect { padding: 8px 2px 4px; font-size: 13.5px; line-height: 1.7; }
|
||||
.io-mail-connect .erp-btn { margin-top: 6px; }
|
||||
@@ -239,6 +256,8 @@
|
||||
.io-viewer-btn { padding: 5px 12px; border: 1px solid rgba(255, 255, 255, .35); border-radius: 6px; background: rgba(0, 0, 0, .35); color: #fff;
|
||||
font: inherit; font-size: 12.5px; text-decoration: none; cursor: pointer; }
|
||||
.io-viewer-btn:hover { background: rgba(255, 255, 255, .15); }
|
||||
.io-viewer-rot { display: inline-flex; align-items: center; padding: 5px 9px; }
|
||||
.io-viewer-rot:disabled { opacity: .5; cursor: wait; }
|
||||
.io-viewer-img { max-width: 100%; max-height: 100%; object-fit: contain; }
|
||||
.io-viewer-heic { padding: 24px; text-align: center; }
|
||||
.io-viewer-nav { position: absolute; top: 50%; transform: translateY(-50%); width: 44px; height: 64px; border: 0; border-radius: 8px;
|
||||
@@ -256,6 +275,7 @@
|
||||
.io-prod-search { width: 220px; }
|
||||
.io-prod-scroll { max-height: min(440px, calc(100vh - 340px)); overflow-y: auto; border: 1px solid var(--color-subtle-ash); border-radius: 8px; }
|
||||
.io-prod-table thead th { position: sticky; top: 0; z-index: 1; background: #fafbfc; }
|
||||
.io-prod-part-title { padding: 10px 12px 6px; font-size: 13.2px; font-weight: 700; }
|
||||
.io-prod-table col.w-code { width: 128px; }
|
||||
.io-prod-table col.w-num { width: 120px; }
|
||||
.io-prod-table col.w-ag { width: 92px; }
|
||||
@@ -443,6 +463,7 @@
|
||||
.io-box-pick { border: 1px solid #cfe0fb; background: #f0f6ff; color: #1d4f91; border-radius: 6px; padding: 0 6px; height: 20px; font-size: 11.5px; cursor: pointer; }
|
||||
.io-box-pick:hover { background: #dce9ff; }
|
||||
.io-pallet { margin-top: 8px; display: flex; flex-wrap: wrap; align-items: baseline; gap: 6px 14px; font-size: 13px; }
|
||||
.io-pallet[hidden] { display: none; }
|
||||
.io-pallet b { font-variant-numeric: tabular-nums; }
|
||||
.io-pallet-main { font-size: 14px; font-weight: 600; }
|
||||
.io-pallet-main b { font-size: 16px; color: #1d4f91; }
|
||||
|
||||
+266
-27
@@ -56,6 +56,7 @@
|
||||
// 힌트 = 통·뚜껑 입수의 최소공배수(둘 다 박스가 꽉 차는 수량 단위)와 지금 수량에 가까운 그 배수(누르면 수량 칸에 넣음).
|
||||
const palletBoxes = parseInt(form.dataset.palletBoxes || "0", 10);
|
||||
const pallet = document.getElementById("io-pallet");
|
||||
const bagPallet = document.getElementById("io-pallet-bag");
|
||||
const gcd = function (a, b) { while (b) { const t = a % b; a = b; b = t; } return a; };
|
||||
const lcm = function (a, b) { return a / gcd(a, b) * b; };
|
||||
function boxCell(tr, n, has) {
|
||||
@@ -64,13 +65,14 @@
|
||||
const out = { body: 0, lid: 0, unset: has && !body };
|
||||
if (!cell) return out;
|
||||
if (!has) { cell.innerHTML = "-"; return out; }
|
||||
if (!body) { cell.innerHTML = '<span class="erp-muted" title="옵션 → 상품 정보에서 통 수량(박스)을 넣으면 계산합니다">박스 입수 미설정</span>'; return out; }
|
||||
const bag = tr.dataset.bag === "1"; // 봉투·백 — 통·뚜껑 구분 없음
|
||||
if (!body) { cell.innerHTML = '<span class="erp-muted" title="옵션 → 상품 정보에서 ' + (bag ? "박스당 수량" : "통 수량(박스)") + '을 넣으면 계산합니다">박스 입수 미설정</span>'; return out; }
|
||||
out.body = n ? Math.ceil(n / body) : 0;
|
||||
out.lid = n && lid ? Math.ceil(n / lid) : 0;
|
||||
const unit = lid ? lcm(body, lid) : body; // 통·뚜껑이 모두 꽉 차는 수량 단위
|
||||
let html = '<div class="io-box-main">통 <b>' + fmt(out.body) + "</b>박스" +
|
||||
(lid ? ' · 뚜껑 <b>' + fmt(out.lid) + "</b>박스" : ' · <span class="erp-muted">뚜껑 없음</span>') + "</div>";
|
||||
const per = "통 " + fmt(body) + "개/박스" + (lid ? " · 뚜껑 " + fmt(lid) + "개/박스" : "");
|
||||
let html = '<div class="io-box-main">' + (bag ? "" : "통 ") + "<b>" + fmt(out.body) + "</b>박스" +
|
||||
(bag ? "" : lid ? ' · 뚜껑 <b>' + fmt(out.lid) + "</b>박스" : ' · <span class="erp-muted">뚜껑 없음</span>') + "</div>";
|
||||
const per = (bag ? "" : "통 ") + fmt(body) + "개/박스" + (lid ? " · 뚜껑 " + fmt(lid) + "개/박스" : "");
|
||||
let hint;
|
||||
if (n && n % unit === 0) {
|
||||
hint = '<span class="io-box-ok">✓ ' + (lid ? "통·뚜껑 박스가 모두 꽉 찹니다" : "박스가 꽉 찹니다") + "</span>";
|
||||
@@ -105,22 +107,25 @@
|
||||
'<rect class="io-pal-base" x="1" y="' + (H + 3) + '" width="5" height="3"/><rect class="io-pal-base" x="' + (W / 2 - 2.5) + '" y="' + (H + 3) + '" width="5" height="3"/>' +
|
||||
'<rect class="io-pal-base" x="' + (W - 6) + '" y="' + (H + 3) + '" width="5" height="3"/></svg>';
|
||||
}
|
||||
function palletVis(all) {
|
||||
// cap = 1파렛트 박스 수. mixed = 1파렛트 박스 수가 다른 봉투·백이 섞임 — all 은 cap 기준 환산값이라 잔량은 %만 보여 준다.
|
||||
function palletVis(all, cap, mixed) {
|
||||
if (!all) return "";
|
||||
const full = Math.floor(all / palletBoxes), rem = all % palletBoxes, MAX = 10;
|
||||
const full = Math.floor(all / cap), rem = all % cap, MAX = 10;
|
||||
const cells = Math.min(cap, 60); // cap 은 입력값 — 아주 커도 그림 칸 수는 60칸까지(비율로 칠함)
|
||||
let html = "";
|
||||
if (full) {
|
||||
let icons = "";
|
||||
for (let i = 0; i < Math.min(full, MAX); i++) icons += palletSvg(palletBoxes, palletBoxes);
|
||||
for (let i = 0; i < Math.min(full, MAX); i++) icons += palletSvg(cells, cells);
|
||||
html += '<span class="io-pal-group" title="꽉 찬 파렛트 ' + full + '개">' + icons +
|
||||
(full > MAX ? '<span class="io-pal-more">+' + (full - MAX) + "</span>" : "") +
|
||||
'<span class="io-pal-cap">꽉 찬 파렛트 <b>' + fmt(full) + "</b></span></span>";
|
||||
}
|
||||
if (rem) {
|
||||
const pct = Math.round(rem / palletBoxes * 100);
|
||||
html += '<span class="io-pal-group is-rem" title="잔량 파렛트 ' + rem + "/" + palletBoxes + '박스">' + palletSvg(rem, palletBoxes) +
|
||||
'<span class="io-pal-cap">잔량 <b>' + rem + "</b>박스 · <b>" + pct + "%</b><br>" +
|
||||
'<span class="io-pal-need">' + (palletBoxes - rem) + "박스 더 실으면 한 파렛트</span></span></span>";
|
||||
const pct = Math.round(rem / cap * 100);
|
||||
const drawn = Math.min(cells - 1, Math.max(1, Math.round(rem / cap * cells)));
|
||||
html += '<span class="io-pal-group is-rem" title="잔량 파렛트 ' + (mixed ? pct + "%" : rem + "/" + cap + "박스") + '">' + palletSvg(drawn, cells) +
|
||||
'<span class="io-pal-cap">잔량 ' + (mixed ? "<b>" + pct + "%</b></span></span>" : "<b>" + rem + "</b>박스 · <b>" + pct + "%</b><br>" +
|
||||
'<span class="io-pal-need">' + (cap - rem) + "박스 더 실으면 한 파렛트</span></span></span>");
|
||||
} else {
|
||||
html += '<span class="io-pal-ok">✓ 모든 파렛트가 꽉 찹니다</span>';
|
||||
}
|
||||
@@ -129,6 +134,7 @@
|
||||
function renumber() {
|
||||
let q = 0, k = 0, amount = 0, missing = 0;
|
||||
let bodyBoxes = 0, lidBoxes = 0, unset = 0;
|
||||
let bagLines = 0, bagBoxes = 0, bagCapped = 0, bagShare = 0, bagCap = 0, bagMixed = false, bagUnset = 0;
|
||||
body.querySelectorAll(".io-line").forEach(function (tr, i) {
|
||||
tr.querySelector(".io-col-no").textContent = String(i + 1);
|
||||
const n = num(tr.querySelector(".io-qty").value);
|
||||
@@ -137,9 +143,22 @@
|
||||
const cell = tr.querySelector(".io-amount");
|
||||
// 금액 = 수량 × 단가(상품 정보 단가, 이미 있던 품목은 발주 당시 단가) — 표시만, 저장은 서버가 단가 사본으로
|
||||
if (cell) cell.textContent = has && price !== null && n ? (Math.round(price * n * 100) / 100).toLocaleString("ko-KR") : "-";
|
||||
if (has) { k++; q += n; if (price === null) missing++; else amount += price * n; }
|
||||
if (has) { k++; q += n; if (price !== null) amount += price * n; else if (tr.dataset.bag !== "1") missing++; } // 봉투·백은 단가가 원래 없음
|
||||
const bx = boxCell(tr, n, has);
|
||||
bodyBoxes += bx.body; lidBoxes += bx.lid; if (bx.unset) unset++;
|
||||
if (has && tr.dataset.bag === "1") {
|
||||
const cap = parseInt(tr.dataset.palletBox || "0", 10) || 0;
|
||||
bagLines++;
|
||||
bagBoxes += bx.body;
|
||||
if (cap) { // 1파렛트 박스 수가 다른 봉투·백은 차지하는 비율로 더함
|
||||
bagCapped += bx.body;
|
||||
bagShare += bx.body / cap;
|
||||
if (bagCap && cap !== bagCap) bagMixed = true;
|
||||
bagCap = Math.max(bagCap, cap);
|
||||
}
|
||||
if (bx.unset || !cap) bagUnset++;
|
||||
} else {
|
||||
bodyBoxes += bx.body; lidBoxes += bx.lid; if (bx.unset) unset++;
|
||||
}
|
||||
const unit = unitOf(tr); // ◀ ▶ = 공배수만큼(입수가 없으면 누를 수 없음)
|
||||
tr.querySelectorAll(".io-step").forEach(function (b) {
|
||||
b.disabled = !unit || (b.dataset.step === "-1" && !n);
|
||||
@@ -150,9 +169,19 @@
|
||||
const all = bodyBoxes + lidBoxes, pallets = Math.ceil(all / palletBoxes);
|
||||
const set = function (key, v) { pallet.querySelector('[data-k="' + key + '"]').textContent = v; };
|
||||
set("body", fmt(bodyBoxes)); set("lid", fmt(lidBoxes)); set("boxes", fmt(all)); set("pallets", fmt(pallets));
|
||||
pallet.querySelector('[data-k="vis"]').innerHTML = palletVis(all);
|
||||
pallet.querySelector('[data-k="vis"]').innerHTML = palletVis(all, palletBoxes);
|
||||
set("note", "1파렛트 = " + palletBoxes + "박스" + (unset ? " · 박스 입수 미설정 " + unset + "종 제외" : ""));
|
||||
}
|
||||
if (bagPallet) {
|
||||
bagPallet.hidden = !bagLines;
|
||||
const setBag = function (key, v) { bagPallet.querySelector('[data-k="' + key + '"]').textContent = v; };
|
||||
setBag("boxes", fmt(bagBoxes));
|
||||
// 섞이면 가장 큰 1파렛트 박스 수로 환산(소수 오차로 한 파렛트 더 나오지 않게 반올림 후 올림)
|
||||
const bagAll = bagMixed ? Math.ceil(Math.round(bagShare * bagCap * 1e6) / 1e6) : bagCapped;
|
||||
setBag("pallets", fmt(bagCap ? Math.ceil(bagAll / bagCap) : 0));
|
||||
bagPallet.querySelector('[data-k="vis"]').innerHTML = palletVis(bagAll, bagCap, bagMixed);
|
||||
setBag("note", bagUnset ? "박스당 수량·1파렛트당 박스 수량 미설정 " + bagUnset + "종 제외" : "");
|
||||
}
|
||||
totalQty.textContent = fmt(q);
|
||||
totalLines.textContent = fmt(k);
|
||||
if (totalAmount) totalAmount.textContent = (Math.round(amount * 100) / 100).toLocaleString("ko-KR");
|
||||
@@ -284,7 +313,10 @@
|
||||
const row = input.closest("tr");
|
||||
if (row) { // 단가(상품 정보) — 금액 계산용, 박스 입수(007) — 박스·파렛트 계산용
|
||||
row.dataset.price = it.price === null || it.price === undefined ? "" : String(it.price);
|
||||
if ("bodyBox" in row.dataset) { row.dataset.bodyBox = it.body_per_box || ""; row.dataset.lidBox = it.lid_per_box || ""; }
|
||||
if ("bodyBox" in row.dataset) {
|
||||
row.dataset.bodyBox = it.body_per_box || ""; row.dataset.lidBox = it.lid_per_box || "";
|
||||
row.dataset.bag = it.is_bag ? "1" : ""; row.dataset.palletBox = it.boxes_per_pallet || "";
|
||||
}
|
||||
const pc = row.querySelector(".io-price");
|
||||
if (pc) pc.textContent = it.unit_price || "-";
|
||||
}
|
||||
@@ -490,13 +522,13 @@
|
||||
const opt = sel.options[sel.selectedIndex];
|
||||
const grouped = !!sel.value;
|
||||
tr.classList.toggle("is-grouped", grouped);
|
||||
const vals = tr.querySelectorAll(".io-group-val");
|
||||
if (vals[0]) vals[0].textContent = (opt && opt.dataset.silver) || "-";
|
||||
if (vals[1]) {
|
||||
const silverVal = tr.querySelector(".io-group-val.io-r"), colorVal = tr.querySelector(".io-color.io-group-val"); // 봉투·백 줄엔 은 칸 없음
|
||||
if (silverVal) silverVal.textContent = (opt && opt.dataset.silver) || "-";
|
||||
if (colorVal) {
|
||||
const key = (opt && opt.dataset.color) || "none";
|
||||
const csel = tr.querySelector(".io-color-select");
|
||||
const copt = csel && Array.from(csel.options).find(function (o) { return o.value === key; });
|
||||
const sw = vals[1].querySelector(".io-swatch"), nm = vals[1].querySelector(".io-color-name");
|
||||
const sw = colorVal.querySelector(".io-swatch"), nm = colorVal.querySelector(".io-color-name");
|
||||
if (sw) { sw.style.background = (copt && copt.dataset.hex) || "#fff"; sw.classList.toggle("is-none", !(copt && copt.dataset.hex)); }
|
||||
if (nm) nm.textContent = copt ? copt.textContent : "";
|
||||
}
|
||||
@@ -531,6 +563,9 @@
|
||||
tr.hidden = !hit;
|
||||
if (hit) shown++;
|
||||
});
|
||||
body.querySelectorAll(".io-prod-part").forEach(function (part) { // 찾은 줄이 없는 표는 제목째 숨김
|
||||
part.hidden = !part.querySelector("tbody tr:not([hidden])");
|
||||
});
|
||||
const cnt = body.querySelector("#io-prod-count");
|
||||
if (cnt) cnt.dataset.base = cnt.dataset.base || cnt.textContent;
|
||||
if (cnt) cnt.textContent = q ? shown + "개 찾음" : cnt.dataset.base;
|
||||
@@ -561,7 +596,8 @@
|
||||
const v = function (k) { return tr.querySelector('[data-key="' + k + '"]').value.trim(); };
|
||||
const row = { code: tr.dataset.code, unit_price: v("unit_price"), weight_g: v("weight_g"), silver_pct: v("silver_pct") };
|
||||
if (tr.querySelector('[data-key="group_id"]')) { row.group_id = v("group_id"); row.color = v("color"); } // 006
|
||||
if (tr.querySelector('[data-key="body_per_box"]')) { row.body_per_box = v("body_per_box"); row.lid_per_box = v("lid_per_box"); } // 007
|
||||
if (tr.querySelector('[data-key="boxes_per_pallet"]')) { row.body_per_box = v("body_per_box"); row.boxes_per_pallet = v("boxes_per_pallet"); } // 008 봉투·백
|
||||
else if (tr.querySelector('[data-key="body_per_box"]')) { row.body_per_box = v("body_per_box"); row.lid_per_box = v("lid_per_box"); } // 007
|
||||
return row;
|
||||
});
|
||||
if (rows.length) await act("/inout/settings/products/save", { rows: rows });
|
||||
@@ -694,13 +730,15 @@
|
||||
const img = document.getElementById("io-viewer-img"), heic = document.getElementById("io-viewer-heic");
|
||||
const title = document.getElementById("io-viewer-title"), openA = document.getElementById("io-viewer-open");
|
||||
const del = document.getElementById("io-viewer-del");
|
||||
const rots = viewer.querySelectorAll("[data-rotate]");
|
||||
let list = [], at = 0;
|
||||
function show(i) {
|
||||
at = (i + list.length) % list.length;
|
||||
const b = list[at], id = b.dataset.photo, isHeic = b.dataset.type === "image/heic";
|
||||
img.hidden = isHeic;
|
||||
heic.hidden = !isHeic;
|
||||
if (!isHeic) img.src = "/inout/photos/" + id;
|
||||
rots.forEach(function (r) { r.hidden = isHeic; });
|
||||
if (!isHeic) img.src = "/inout/photos/" + id + (b.dataset.v ? "?v=" + b.dataset.v : "");
|
||||
openA.href = "/inout/photos/" + id;
|
||||
title.textContent = (b.dataset.name || "입고증") + " (" + (at + 1) + "/" + list.length + ")";
|
||||
if (del) del.action = "/inout/orders/" + viewer.dataset.order + "/photos/" + id + "/delete";
|
||||
@@ -714,10 +752,30 @@
|
||||
viewer.showModal();
|
||||
viewer.focus({ preventScroll: true }); // [원본]에 초점 테두리가 생기지 않게(←/→ 는 창에서 받음)
|
||||
});
|
||||
// 회전 = 서버가 저장된 사진 자체를 돌림(2026-11-02) — 창은 그대로 두고 큰 사진·썸네일만 새로 받는다
|
||||
async function rotate(degrees) {
|
||||
const b = list[at];
|
||||
rots.forEach(function (r) { r.disabled = true; });
|
||||
try {
|
||||
const res = await fetch("/inout/orders/" + viewer.dataset.order + "/photos/" + b.dataset.photo + "/rotate?degrees=" + degrees, { method: "POST" });
|
||||
const data = await res.json().catch(function () { return {}; });
|
||||
if (!res.ok) throw new Error(data.error || "사진을 돌리지 못했습니다.");
|
||||
b.dataset.v = String(Date.now());
|
||||
const thumb = b.querySelector("img");
|
||||
if (thumb) thumb.src = "/inout/photos/" + b.dataset.photo + "?v=" + b.dataset.v;
|
||||
show(at);
|
||||
} catch (err) {
|
||||
alertMsg(err.message || "사진을 돌리지 못했습니다.");
|
||||
} finally {
|
||||
rots.forEach(function (r) { r.disabled = false; });
|
||||
}
|
||||
}
|
||||
viewer.addEventListener("click", function (e) {
|
||||
if (e.target === viewer || e.target.closest("[data-close]")) viewer.close();
|
||||
const step = e.target.closest("[data-step]");
|
||||
if (step) show(at + parseInt(step.dataset.step, 10));
|
||||
const rot = e.target.closest("[data-rotate]");
|
||||
if (rot) rotate(rot.dataset.rotate);
|
||||
});
|
||||
viewer.addEventListener("keydown", function (e) {
|
||||
if (e.key === "ArrowLeft") show(at - 1);
|
||||
@@ -731,7 +789,7 @@
|
||||
// (입고 담당 본인 Gmail, 받는 사람 = 옵션 → 물류센터 이메일, 참조 기본 = 옵션 값, 본문에 입고증 사진)
|
||||
const mailBtn = document.getElementById("io-mail-btn"), mailDlg = document.getElementById("io-mail");
|
||||
if (mailBtn && mailDlg) {
|
||||
const om = initMail(mailDlg, { param: "mail", what: "발주 메일" });
|
||||
const om = initMail(mailDlg, { param: "mail", what: "발주 메일", editable: true });
|
||||
const url = "/inout/orders/" + mailBtn.dataset.order + "/mail";
|
||||
mailBtn.addEventListener("click", function () { om.open(url); });
|
||||
if (mailBtn.dataset.open === "1") om.open(url);
|
||||
@@ -749,7 +807,39 @@
|
||||
const body = dlg.querySelector("[data-mail-body]"), foot = dlg.querySelector("[data-mail-foot]");
|
||||
const msgEl = dlg.querySelector(".io-dlg-msg"), sendBtn = dlg.querySelector("[data-mail-send]");
|
||||
const titleEl = dlg.querySelector("[data-mail-title]");
|
||||
let base = "", data = null, sent = false;
|
||||
let base = "", data = null, sent = false, edited = false;
|
||||
// 발주 메일 본문 서식 막대(2026-10-27) — 안내문 발송 편집기와 같은 구성. 함수 안에 둔다(initMail 을 위에서 먼저 부른다 — TDZ)
|
||||
const RTE_TEXT_COLORS = [["#1d1d1f", "기본(검정)"], ["#6b7280", "회색"], ["#d93025", "빨강"], ["#e8710a", "주황"], ["#b58100", "노랑"],
|
||||
["#188038", "초록"], ["#1a73e8", "파랑"], ["#7b2fd0", "보라"]];
|
||||
const RTE_BG_COLORS = [["transparent", "배경 없음"], ["#fff3bf", "노랑"], ["#ffd8a8", "주황"], ["#ffc9c9", "빨강"], ["#d3f9d8", "초록"],
|
||||
["#d0ebff", "파랑"], ["#e5dbff", "보라"], ["#f1f3f5", "회색"]];
|
||||
const ic = function (d) { return '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' + d + "</svg>"; };
|
||||
const tb = function (attr, title, inner) { return '<button type="button" class="io-rte-btn" ' + attr + ' title="' + title + '" aria-label="' + title + '">' + inner + "</button>"; };
|
||||
const RTE_BAR = '<div class="io-rte" role="toolbar" aria-label="본문 서식">' +
|
||||
'<select class="io-rte-size" data-rte-size title="글자 크기" aria-label="글자 크기"><option value="">크기</option>' +
|
||||
["12px", "14px", "16px", "18px", "20px", "24px", "30px"].map(function (s) { return '<option value="' + s + '">' + s.replace("px", "") + (s === "14px" ? " (기본)" : "") + "</option>"; }).join("") +
|
||||
"</select><span class=\"io-rte-sep\"></span>" +
|
||||
tb('data-cmd="bold"', "굵게 (Ctrl+B)", "<b>B</b>") + tb('data-cmd="italic"', "기울임 (Ctrl+I)", "<i>I</i>") +
|
||||
tb('data-cmd="underline"', "밑줄 (Ctrl+U)", "<u>U</u>") + tb('data-cmd="strikeThrough"', "취소선", "<s>S</s>") +
|
||||
'<span class="io-rte-sep"></span>' +
|
||||
tb('data-pop="foreColor"', "글자 색", '<span class="io-rte-a">A</span>') +
|
||||
tb('data-pop="hiliteColor"', "배경 색", ic('<path d="M9 11l-4 4v3h3l4-4"/><path d="M14 6l4 4-6 6-4-4z"/><path d="M4 21h16" stroke="#f9ab00" stroke-width="3"/>')) +
|
||||
'<span class="io-rte-sep"></span>' +
|
||||
tb('data-cmd="justifyLeft"', "왼쪽 정렬", ic('<path d="M4 6h16M4 10h10M4 14h16M4 18h10"/>')) +
|
||||
tb('data-cmd="justifyCenter"', "가운데 정렬", ic('<path d="M4 6h16M7 10h10M4 14h16M7 18h10"/>')) +
|
||||
tb('data-cmd="justifyRight"', "오른쪽 정렬", ic('<path d="M4 6h16M10 10h10M4 14h16M10 18h10"/>')) +
|
||||
'<span class="io-rte-sep"></span>' +
|
||||
tb('data-cmd="insertOrderedList"', "번호 목록", ic('<path d="M10 6h10M10 12h10M10 18h10"/><path d="M4 5h1v4M4 15h2l-2 3h2" stroke-width="1.6"/>')) +
|
||||
tb('data-cmd="insertUnorderedList"', "글머리 목록", ic('<path d="M10 6h10M10 12h10M10 18h10"/><circle cx="5" cy="6" r="1"/><circle cx="5" cy="12" r="1"/><circle cx="5" cy="18" r="1"/>')) +
|
||||
'<span class="io-rte-sep"></span>' +
|
||||
tb('data-pop="link"', "링크", ic('<path d="M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1"/><path d="M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1"/>')) +
|
||||
tb('data-cmd="removeFormat"', "서식 지우기", ic('<path d="M6 5h12M12 5l-3 14M4 20l16-16" />')) +
|
||||
'<span class="io-rte-sep"></span>' +
|
||||
tb('data-cmd="undo"', "되돌리기 (Ctrl+Z)", ic('<path d="M9 14L4 9l5-5"/><path d="M4 9h11a5 5 0 0 1 0 10h-3"/>')) +
|
||||
tb('data-cmd="redo"', "다시 하기 (Ctrl+Y)", ic('<path d="M15 14l5-5-5-5"/><path d="M20 9H9a5 5 0 0 0 0 10h3"/>')) +
|
||||
'<button type="button" class="io-link-btn io-rte-reset" data-mail-reset hidden>원래 본문으로</button>' +
|
||||
'<div class="io-rte-pop" hidden></div></div>' +
|
||||
'<p class="io-rte-hint">본문을 눌러 바로 고칠 수 있습니다 — 글자를 고른 뒤 위 막대로 서식을 바꾸세요. 고친 내용 그대로 보냅니다.</p>';
|
||||
function say(text, bad) { msgEl.textContent = text || ""; msgEl.hidden = !text; msgEl.classList.toggle("is-bad", !!bad); }
|
||||
function esc(s) { const d = document.createElement("div"); d.textContent = s == null ? "" : String(s); return d.innerHTML; }
|
||||
function field(name) { return body.querySelector('[data-mail-field="' + name + '"]'); }
|
||||
@@ -794,10 +884,158 @@
|
||||
(notice ? '<p class="io-mail-notice">' + esc(notice) + "</p>" : "") +
|
||||
(receipt && data.photos_skipped ? '<p class="io-hint">HEIC 등 본문에 넣지 못하는 입고증 사진 ' + esc(data.photos_skipped) + "장은 빠집니다(입고 기록에는 그대로).</p>" : "") +
|
||||
(sentList ? '<div class="io-mail-sentlist"><b>보낸 기록</b><ul>' + sentList + "</ul></div>" : "") +
|
||||
'<iframe class="io-mail-preview" sandbox title="메일 본문 미리보기"></iframe>';
|
||||
body.querySelector(".io-mail-preview").srcdoc = data.html;
|
||||
(cfg.editable ? RTE_BAR : "") +
|
||||
'<iframe class="io-mail-preview" title="메일 본문 미리보기"></iframe>';
|
||||
edited = false;
|
||||
setupPreview(body.querySelector(".io-mail-preview"), data.html);
|
||||
sendBtn.textContent = (data.sent || []).length ? "다시 발송" : "메일 발송";
|
||||
}
|
||||
// 발주 메일 본문 고치기(2026-10-27) — 미리보기 iframe 을 designMode 로. 스크립트는 막고(allow-scripts 없음) 부모만 문서에 손댈 수 있게
|
||||
// allow-same-origin. 보낼 때 고쳤으면 body HTML 을 같이 보낸다(서버가 허용 태그·서식만 남김).
|
||||
// 서식 막대(RTE_BAR) = execCommand — 표·인라인 서식을 그대로 두려고 Quill 대신(Quill 은 표를 못 담는다). 글자 서식은 span style 로.
|
||||
function setupPreview(ifr, html) {
|
||||
ifr.setAttribute("sandbox", cfg.editable ? "allow-same-origin" : "");
|
||||
if (!cfg.editable) { ifr.srcdoc = html; return; }
|
||||
const bar = body.querySelector(".io-rte"), reset = bar.querySelector("[data-mail-reset]");
|
||||
const sizeSel = bar.querySelector("[data-rte-size]"), pop = bar.querySelector(".io-rte-pop");
|
||||
let doc = null, saved = null;
|
||||
function markEdited() { edited = true; reset.hidden = false; }
|
||||
function saveRange() {
|
||||
const sel = doc && doc.getSelection();
|
||||
if (sel && sel.rangeCount) saved = sel.getRangeAt(0).cloneRange();
|
||||
}
|
||||
// 본문 문서는 포커스가 막대로 가도 자기 선택을 지닌다 — 그게 있으면 그대로, 없을 때만 기억한 선택
|
||||
function restoreRange() {
|
||||
const sel = doc.getSelection();
|
||||
const keep = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : saved;
|
||||
ifr.contentWindow.focus();
|
||||
if (!keep) return;
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(keep);
|
||||
}
|
||||
function exec(cmd, value) {
|
||||
if (!doc) return;
|
||||
restoreRange();
|
||||
doc.execCommand("styleWithCSS", false, true);
|
||||
doc.execCommand(cmd, false, value == null ? null : value);
|
||||
saveRange();
|
||||
markEdited();
|
||||
refresh();
|
||||
}
|
||||
// 글자 크기 — execCommand 는 1~7 단계뿐이라 7 로 칠한 뒤 그 font 를 px 크기 span 으로 바꾼다
|
||||
function setSize(px) {
|
||||
if (!doc) return;
|
||||
restoreRange();
|
||||
doc.execCommand("styleWithCSS", false, false);
|
||||
doc.execCommand("fontSize", false, "7");
|
||||
const spans = [];
|
||||
doc.querySelectorAll('font[size="7"]').forEach(function (f) {
|
||||
const span = doc.createElement("span");
|
||||
span.style.fontSize = px;
|
||||
while (f.firstChild) span.appendChild(f.firstChild);
|
||||
f.replaceWith(span);
|
||||
span.querySelectorAll("span").forEach(function (s) { s.style.fontSize = ""; }); // 안쪽 예전 크기는 지운다
|
||||
spans.push(span);
|
||||
});
|
||||
if (spans.length) { // font 를 바꿔 끼우면 선택이 풀린다 — 바꾼 글자를 다시 고른 채로
|
||||
const r = doc.createRange();
|
||||
r.setStartBefore(spans[0]);
|
||||
r.setEndAfter(spans[spans.length - 1]);
|
||||
doc.getSelection().removeAllRanges();
|
||||
doc.getSelection().addRange(r);
|
||||
}
|
||||
saveRange();
|
||||
markEdited();
|
||||
refresh();
|
||||
}
|
||||
// 버튼 켜짐(굵게 등)·지금 글자 크기 표시
|
||||
function refresh() {
|
||||
if (!doc) return;
|
||||
bar.querySelectorAll("[data-cmd]").forEach(function (b) {
|
||||
let on = false;
|
||||
try { on = doc.queryCommandState(b.dataset.cmd); } catch (_) { /* 상태 없는 명령 */ }
|
||||
b.classList.toggle("is-active", !!on);
|
||||
});
|
||||
const sel = doc.getSelection();
|
||||
let el = sel && sel.anchorNode;
|
||||
if (el && el.nodeType === 1 && el.childNodes[sel.anchorOffset]) el = el.childNodes[sel.anchorOffset]; // 선택이 요소 경계에서 시작
|
||||
if (el && el.nodeType === 3) el = el.parentNode;
|
||||
const px = el && el.nodeType === 1 ? Math.round(parseFloat(doc.defaultView.getComputedStyle(el).fontSize)) + "px" : "";
|
||||
sizeSel.value = [].some.call(sizeSel.options, function (o) { return o.value === px; }) ? px : "";
|
||||
}
|
||||
function closePop() { pop.hidden = true; pop.innerHTML = ""; }
|
||||
function openPop(kind, anchor) {
|
||||
if (!pop.hidden && pop.dataset.kind === kind) { closePop(); return; }
|
||||
pop.dataset.kind = kind;
|
||||
if (kind === "link") {
|
||||
pop.innerHTML = '<input class="io-in" type="url" placeholder="https://… 또는 mailto:…" data-rte-url />' +
|
||||
'<button type="button" class="erp-btn erp-btn-primary erp-btn-sm" data-rte-link-ok>넣기</button>' +
|
||||
'<button type="button" class="erp-btn erp-btn-outline erp-btn-sm" data-rte-unlink>링크 빼기</button>';
|
||||
} else {
|
||||
const colors = kind === "foreColor" ? RTE_TEXT_COLORS : RTE_BG_COLORS;
|
||||
pop.innerHTML = colors.map(function (c) {
|
||||
return '<button type="button" class="io-rte-sw' + (c[0] === "transparent" ? " is-none" : "") + '" data-rte-color="' + c[0] +
|
||||
'" style="background:' + c[0] + '" title="' + c[1] + '" aria-label="' + c[1] + '"></button>';
|
||||
}).join("");
|
||||
}
|
||||
pop.style.left = anchor.offsetLeft + "px";
|
||||
pop.style.top = anchor.offsetTop + anchor.offsetHeight + 4 + "px";
|
||||
pop.hidden = false;
|
||||
const url = pop.querySelector("[data-rte-url]");
|
||||
if (url) url.focus();
|
||||
}
|
||||
ifr.addEventListener("load", function () {
|
||||
doc = ifr.contentDocument;
|
||||
saved = null;
|
||||
if (!doc) return;
|
||||
doc.designMode = "on";
|
||||
doc.body.style.outline = "none";
|
||||
doc.addEventListener("input", markEdited);
|
||||
doc.addEventListener("selectionchange", function () { saveRange(); refresh(); });
|
||||
doc.addEventListener("mousedown", closePop);
|
||||
});
|
||||
// 막대를 누르는 순간의 본문 선택을 기억(크기 고르기·링크 칸으로 포커스가 옮겨 가도 그 글자에) — 색·링크 팝업 안은 이미 기억한 선택 그대로.
|
||||
// 버튼은 기본 동작을 막아 본문 선택이 풀리지 않게
|
||||
bar.addEventListener("mousedown", function (e) {
|
||||
if (!e.target.closest(".io-rte-pop")) saveRange();
|
||||
if (e.target.closest("button")) e.preventDefault();
|
||||
});
|
||||
bar.addEventListener("click", function (e) {
|
||||
const b = e.target.closest("button");
|
||||
if (!b) return;
|
||||
if (b.dataset.cmd) { closePop(); exec(b.dataset.cmd); }
|
||||
else if (b.dataset.pop) openPop(b.dataset.pop, b);
|
||||
else if (b.dataset.rteColor) { exec(pop.dataset.kind, b.dataset.rteColor); closePop(); }
|
||||
else if (b.hasAttribute("data-rte-link-ok")) {
|
||||
const v = pop.querySelector("[data-rte-url]").value.trim();
|
||||
if (!/^(https?:\/\/|mailto:)/i.test(v)) { pop.querySelector("[data-rte-url]").focus(); return; }
|
||||
exec("createLink", v);
|
||||
closePop();
|
||||
} else if (b.hasAttribute("data-rte-unlink")) { exec("unlink"); closePop(); }
|
||||
});
|
||||
bar.addEventListener("keydown", function (e) {
|
||||
if (e.key === "Enter" && e.target.matches("[data-rte-url]")) { e.preventDefault(); pop.querySelector("[data-rte-link-ok]").click(); }
|
||||
if (e.key === "Escape" && !pop.hidden) { e.preventDefault(); e.stopPropagation(); closePop(); }
|
||||
});
|
||||
sizeSel.addEventListener("change", function () { if (sizeSel.value) setSize(sizeSel.value); else setSize("14px"); });
|
||||
reset.onclick = async function () {
|
||||
if (!(await confirmMsg("고친 내용을 버리고 원래 본문으로 되돌릴까요?"))) return;
|
||||
edited = false;
|
||||
reset.hidden = true;
|
||||
closePop();
|
||||
ifr.srcdoc = data.html;
|
||||
};
|
||||
ifr.srcdoc = html;
|
||||
}
|
||||
function editedHtml() {
|
||||
const ifr = body.querySelector(".io-mail-preview");
|
||||
return cfg.editable && edited && ifr && ifr.contentDocument ? ifr.contentDocument.body.innerHTML : "";
|
||||
}
|
||||
async function close() {
|
||||
if (edited && !sent && !(await confirmMsg("고친 본문은 저장되지 않습니다. 닫을까요?"))) return;
|
||||
edited = false;
|
||||
dlg.close();
|
||||
}
|
||||
async function open(url, title) {
|
||||
base = url;
|
||||
if (title && titleEl) titleEl.textContent = title;
|
||||
@@ -815,7 +1053,7 @@
|
||||
say("보내는 중…");
|
||||
try {
|
||||
const res = await fetch(base, { method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ to: to, cc: cc, resend: !!resend }) });
|
||||
body: JSON.stringify({ to: to, cc: cc, resend: !!resend, html: editedHtml() || undefined }) });
|
||||
const out = await res.json();
|
||||
if (out.resend_needed) {
|
||||
say("");
|
||||
@@ -838,7 +1076,8 @@
|
||||
await load();
|
||||
say("Gmail 연결을 끊었습니다.");
|
||||
});
|
||||
dlg.addEventListener("click", function (e) { if (e.target.closest("[data-close]")) dlg.close(); });
|
||||
dlg.addEventListener("click", function (e) { if (e.target.closest("[data-close]")) close(); });
|
||||
dlg.addEventListener("cancel", function (e) { if (edited && !sent) { e.preventDefault(); close(); } }); // Esc
|
||||
dlg.addEventListener("close", function () {
|
||||
const url = new URL(location.href);
|
||||
const had = url.searchParams.has(cfg.param);
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
/* 라이브 커머스(2026-11-04) — 스케줄표·호스트 설정 */
|
||||
.erp-page:has(> .lv) { box-sizing: border-box; } /* 공용 .erp-page 는 폭 100% + 안쪽 여백이라 그대로면 화면보다 넓어진다 */
|
||||
.lv { display: flex; flex-direction: column; gap: 14px; min-width: 0; }
|
||||
.lv *, .lv-dlg *, .lv-dlg *::before, .lv-dlg *::after { box-sizing: border-box; }
|
||||
.lv-dlg [hidden] { display: none !important; }
|
||||
.lv-bar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.lv-gap { flex: 1 1 auto; }
|
||||
.lv-month { margin: 0 6px; font-size: 18px; font-weight: 600; white-space: nowrap; }
|
||||
.lv-note { margin: 0; padding: 10px 14px; border-radius: 8px; background: #eef6ff; color: #0b4a8b; border: 1px solid #cfe3fb; font-size: 13px; }
|
||||
|
||||
.lv-table td { vertical-align: middle; overflow-wrap: anywhere; }
|
||||
.lv-table th { white-space: nowrap; }
|
||||
.lv-table tr.lv-off td { color: var(--color-midtone-gray, #666); }
|
||||
.lv-r { text-align: right; }
|
||||
.lv-table th.lv-r { text-align: right; }
|
||||
.lv-num { font-variant-numeric: tabular-nums; }
|
||||
.lv-nowrap { white-space: nowrap; }
|
||||
.lv-sub { margin: 0; font-size: 12px; color: var(--color-midtone-gray, #666); }
|
||||
.lv-actions { white-space: nowrap; text-align: right; }
|
||||
.lv-thumbs { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
.lv-thumbs img { display: block; width: 44px; height: 44px; object-fit: cover; border-radius: 6px; border: 1px solid var(--color-subtle-ash, #e5e5e5); }
|
||||
|
||||
/* 공용 .erp-table 은 640px 아래에서 제목 줄을 숨기고 카드로 바뀐다 — 칸 이름을 칸마다 보여 준다 */
|
||||
@media (max-width: 640px) {
|
||||
.lv-table td[data-label]::before { content: attr(data-label); display: block; font-size: 12px; font-weight: 400; color: var(--color-midtone-gray, #666); text-align: left; }
|
||||
.lv-table td.lv-r { text-align: left; }
|
||||
}
|
||||
|
||||
.lv-views { display: inline-flex; gap: 4px; margin-left: 10px; }
|
||||
.lv-lang { display: inline-flex; padding: 2px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 999px; background: #fff; }
|
||||
.lv-lang button { min-width: 40px; padding: 4px 10px; border: 0; border-radius: 999px; background: none; font-size: 12px; font-weight: 600; color: #4b5563; cursor: pointer; }
|
||||
.lv-lang button.is-active { background: #111; color: #fff; }
|
||||
/* 영문 화면은 받은 화면처럼 대문자 */
|
||||
.lv[lang="en"] .lv-kpi span, .lv[lang="en"] .lv-card-nums span, .lv[lang="en"] .lv-cal thead .lv-cal-time, .lv[lang="en"] .lv-cal tfoot .lv-cal-time, .lv[lang="en"] .lv-total dt { text-transform: uppercase; }
|
||||
|
||||
/* ── 달력 보기 ── */
|
||||
.lv-kpis { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
|
||||
.lv-kpi { display: flex; flex-direction: column; gap: 2px; padding: 10px 14px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #fff; }
|
||||
.lv-kpi span { font-size: 11px; font-weight: 600; letter-spacing: .04em; color: var(--color-midtone-gray, #666); }
|
||||
.lv-kpi b { font-size: 18px; font-variant-numeric: tabular-nums; }
|
||||
.lv-jump { display: flex; flex-wrap: wrap; align-items: center; gap: 4px; padding: 8px 12px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #fff; }
|
||||
.lv-jump-label { margin-right: 4px; font-size: 13px; font-weight: 600; color: #4b5563; }
|
||||
.lv-jump-day { min-width: 28px; height: 28px; padding: 0 4px; border: 1px solid transparent; border-radius: 6px; background: #f1f3f6; color: #1f2937; font-size: 13px; font-weight: 600; cursor: pointer; }
|
||||
.lv-jump-day:hover { background: #e2e6ec; }
|
||||
.lv-jump-day.is-weekend { background: #fff6dc; border-color: #f3e2ae; color: #8a4b08; }
|
||||
.lv-jump-day.is-today { outline: 2px solid #111; outline-offset: -2px; }
|
||||
.lv-tip { margin: 0; padding: 8px 12px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 10px; background: #f6f8fb; font-size: 13px; color: #374151; }
|
||||
|
||||
.lv-cal-wrap { overflow: auto; max-height: calc(100vh - 150px); border: 1px solid #cfd4dc; border-radius: 10px; background: #fff; }
|
||||
.lv-cal { border-collapse: separate; border-spacing: 0; min-width: max-content; }
|
||||
.lv-cal th, .lv-cal td { border-right: 1px solid #e3e6eb; border-bottom: 1px solid #e3e6eb; }
|
||||
.lv-cal thead th { position: sticky; top: 0; z-index: 2; width: 182px; min-width: 182px; padding: 8px 6px; background: #e4e8ee; text-align: center; font-weight: 700; }
|
||||
.lv-cal thead th.is-weekend { background: #f5efd3; color: #7a5c00; }
|
||||
.lv-cal thead th.is-today { box-shadow: inset 0 -3px 0 #111; }
|
||||
.lv-cal-weekday { font-size: 13px; letter-spacing: .03em; }
|
||||
.lv-cal-count { display: inline-block; min-width: 18px; padding: 0 4px; margin-left: 2px; border: 1px solid #cfd4dc; border-radius: 4px; background: #fff; color: #374151; font-size: 11px; font-weight: 600; }
|
||||
.lv-cal-date { margin-top: 2px; font-size: 11px; font-weight: 600; color: #6b7280; }
|
||||
.lv-cal .lv-cal-time { position: sticky; left: 0; z-index: 1; width: 132px; min-width: 132px; padding: 8px; background: #f6f7f9; text-align: center; font-size: 13px; font-weight: 700; white-space: nowrap; }
|
||||
.lv-cal thead .lv-cal-time { z-index: 3; background: #d9dee6; }
|
||||
.lv-cal .lv-cal-time small { display: block; margin-top: 2px; font-size: 10.5px; font-weight: 600; color: #6b7280; }
|
||||
.lv-cell { min-height: 100px; padding: 4px; vertical-align: top; background: #fff; }
|
||||
.lv-cell.is-weekend { background: #fffdf3; }
|
||||
.lv-cell.is-drop { background: #e8f1ff; box-shadow: inset 0 0 0 2px #3b82f6; }
|
||||
.lv-cell-add { display: block; width: 100%; min-height: 88px; border: 1px dashed #d8dce3; border-radius: 6px; background: transparent; color: #b0b6c0; font-size: 16px; cursor: pointer; }
|
||||
.lv-cell-add:hover, .lv-cell-add:focus-visible { border-color: #6b7280; color: #374151; }
|
||||
.lv-card { margin-bottom: 4px; border: 1.5px solid #1f2937; border-radius: 6px; background: #fff; overflow: hidden; }
|
||||
.lv-card-head { display: flex; align-items: center; gap: 4px; padding: 3px 6px; border-bottom: 1px solid #1f2937; cursor: grab; }
|
||||
.lv-card-head:active { cursor: grabbing; }
|
||||
.lv-card-grip { font-size: 12px; color: #374151; }
|
||||
.lv-card-name { flex: 1 1 auto; min-width: 0; overflow: hidden; text-align: center; text-overflow: ellipsis; white-space: nowrap; text-transform: uppercase; font-size: 13px; font-weight: 800; letter-spacing: .03em; color: #111; }
|
||||
.lv-card-edit { padding: 0 2px; border: 0; background: none; color: #374151; font-size: 13px; cursor: pointer; }
|
||||
.lv-card-nums { display: grid; grid-template-columns: 1fr 1fr; }
|
||||
.lv-card-nums div { display: flex; flex-direction: column; text-align: center; }
|
||||
.lv-card-nums div + div { border-left: 1px solid #e3e6eb; }
|
||||
.lv-card-nums span { padding: 2px 0; background: #f6f7f9; font-size: 10px; font-weight: 600; color: #4b5563; }
|
||||
.lv-card-nums b { padding: 3px 0; font-size: 14px; font-variant-numeric: tabular-nums; }
|
||||
.lv-card-foot { display: flex; justify-content: space-between; gap: 4px; padding: 2px 6px; border-top: 1px solid #e3e6eb; background: #f6f7f9; font-size: 10.5px; font-weight: 600; color: #4b5563; }
|
||||
.lv-card-foot b { color: #8a2c0d; }
|
||||
.lv-card-foot a { color: #1d4f91; }
|
||||
.lv-cal tfoot th, .lv-cal tfoot td { position: sticky; bottom: 0; z-index: 2; padding: 8px; background: #101a33; color: #fff; border-color: #2a3550; }
|
||||
.lv-cal tfoot .lv-cal-time { z-index: 3; background: #101a33; font-size: 12px; }
|
||||
.lv-total { display: flex; flex-direction: column; gap: 2px; margin: 0; font-size: 11px; font-weight: 600; }
|
||||
.lv-total div { display: flex; justify-content: space-between; gap: 6px; }
|
||||
.lv-total dt { color: #aab3c5; }
|
||||
.lv-total dd { margin: 0; font-variant-numeric: tabular-nums; color: #fbbf72; white-space: nowrap; }
|
||||
.lv-total dd.is-sales { color: #6ee7a8; }
|
||||
.lv-total-edit { padding: 0 2px; border: 0; background: none; color: #cbd5e1; font-size: 11px; cursor: pointer; }
|
||||
|
||||
.lv-dlg { width: min(560px, calc(100vw - 32px)); max-height: calc(100vh - 40px); padding: 0; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 12px; }
|
||||
.lv-dlg::backdrop { background: rgba(0, 0, 0, .35); }
|
||||
.lv-dlg form { display: flex; flex-direction: column; gap: 12px; padding: 20px 22px; }
|
||||
.lv-dlg h3 { margin: 0; font-size: 17px; font-weight: 600; }
|
||||
.lv-field { display: flex; flex: 1 1 0; flex-direction: column; gap: 4px; min-width: 0; font-size: 13px; font-weight: 500; }
|
||||
.lv-field .erp-input, .lv-field .erp-select { width: 100%; min-width: 0; font-weight: 400; }
|
||||
.lv-field textarea { resize: vertical; }
|
||||
.lv-row { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.lv-row .lv-field { flex-basis: 140px; }
|
||||
.lv-check { display: flex; align-items: center; gap: 6px; font-size: 13px; }
|
||||
.lv-saved { display: flex; flex-direction: column; gap: 6px; margin: 0; padding: 0; list-style: none; font-size: 13px; }
|
||||
.lv-saved li { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.lv-saved a { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.lv-msg { margin: 0; padding: 9px 12px; border-radius: 8px; background: #fbe9e6; color: #a1261b; border: 1px solid #efc6bf; font-size: 13px; }
|
||||
.lv-foot { display: flex; justify-content: flex-end; gap: 8px; }
|
||||
@@ -0,0 +1,191 @@
|
||||
/* 라이브 커머스(2026-11-04) — 스케줄표·달력·호스트 설정 공용: 추가·고치기 창, 저장·지우기(fetch → JSON {ok, message}, 틀려도 입력한 값이 창에 남음).
|
||||
달력: Jump to Date, 카드 끌어 옮기기·맞바꾸기, 날짜별 광고비. 다시 그린 뒤에도 보던 가로 위치 유지. */
|
||||
(function () {
|
||||
"use strict";
|
||||
const calWrap = document.getElementById("lv-cal-wrap");
|
||||
const CAL_POS = "lv_cal_left";
|
||||
function tr(text) { return (window.LV_T && window.LV_T[text]) || text; }
|
||||
const dialogText = function () { return { okText: tr("확인"), cancelText: tr("취소") }; };
|
||||
function reload() {
|
||||
if (calWrap) { try { sessionStorage.setItem(CAL_POS, String(calWrap.scrollLeft)); } catch (_) {} }
|
||||
location.reload();
|
||||
}
|
||||
// 한글·영문 전환 — 브라우저마다 기억(쿠키, /live 안에서만), 서버가 그 언어로 그린다
|
||||
document.addEventListener("click", function (e) {
|
||||
const b = e.target.closest("button[data-lang]");
|
||||
if (!b) return;
|
||||
document.cookie = "live_lang=" + b.dataset.lang + "; path=/live; max-age=31536000; SameSite=Lax" + (location.protocol === "https:" ? "; Secure" : "");
|
||||
reload();
|
||||
});
|
||||
const dlg = document.getElementById("lv-dlg");
|
||||
const form = document.getElementById("lv-form");
|
||||
if (!dlg || !form) return;
|
||||
const title = dlg.querySelector("#lv-dlg-title");
|
||||
const msg = form.querySelector("[data-msg]");
|
||||
const saved = form.querySelector("[data-saved]");
|
||||
const hostSelect = form.querySelector('select[name="host_id"]');
|
||||
const fileInput = form.querySelector('input[type="file"]');
|
||||
|
||||
function say(text) {
|
||||
msg.textContent = text || "";
|
||||
msg.hidden = !text;
|
||||
}
|
||||
|
||||
async function post(url, body) {
|
||||
try {
|
||||
const res = await fetch(url, { method: "POST", body: body, headers: { Accept: "application/json" } });
|
||||
const data = await res.json().catch(function () { return {}; });
|
||||
return { ok: res.ok && data.ok !== false, message: data.message || data.detail || "HTTP " + res.status };
|
||||
} catch (_) {
|
||||
return { ok: false, message: tr("서버에 연결하지 못했습니다. 입력한 값은 그대로 있으니 다시 저장해 보세요.") };
|
||||
}
|
||||
}
|
||||
|
||||
// 사용 안 함 호스트는 그 호스트로 이미 등록된 방송을 고칠 때만 보인다
|
||||
function showHosts(current) {
|
||||
if (!hostSelect) return;
|
||||
Array.from(hostSelect.options).forEach(function (opt) {
|
||||
const off = opt.dataset.inactive === "1" && opt.value !== String(current || "");
|
||||
opt.hidden = off;
|
||||
opt.disabled = off;
|
||||
});
|
||||
}
|
||||
|
||||
function showSaved(images) {
|
||||
if (!saved) return;
|
||||
saved.textContent = "";
|
||||
(images || []).forEach(function (im) {
|
||||
const li = document.createElement("li");
|
||||
const link = document.createElement("a");
|
||||
link.href = "/live/images/" + im.id;
|
||||
link.target = "_blank";
|
||||
link.rel = "noopener";
|
||||
link.textContent = im.filename || "#" + im.id;
|
||||
const del = document.createElement("button");
|
||||
del.type = "button";
|
||||
del.className = "erp-btn erp-btn-outline erp-btn-sm";
|
||||
del.dataset.post = "/live/images/" + im.id + "/delete";
|
||||
del.dataset.confirm = tr("{name} 를 지울까요?").replace("{name}", im.filename || tr("이 이미지"));
|
||||
del.textContent = tr("지우기");
|
||||
li.append(link, del);
|
||||
saved.appendChild(li);
|
||||
});
|
||||
saved.hidden = !saved.children.length;
|
||||
}
|
||||
|
||||
function open(row) {
|
||||
form.reset();
|
||||
say("");
|
||||
const editing = !!(row && row.id);
|
||||
title.textContent = editing ? title.dataset.edit : title.dataset.add;
|
||||
form.elements.id.value = "";
|
||||
Array.from(form.elements).forEach(function (el) {
|
||||
if (!row || !el.name || !(el.name in row)) return;
|
||||
if (el.type === "checkbox") el.checked = !!row[el.name];
|
||||
else if (el.type !== "file") el.value = row[el.name];
|
||||
});
|
||||
showHosts(editing && row.host_id);
|
||||
if (editing && hostSelect) hostSelect.value = String(row.host_id); // 위에서 보이게 한 뒤 다시 고름
|
||||
showSaved(editing && row.images);
|
||||
dlg.showModal();
|
||||
}
|
||||
|
||||
const addBtn = document.getElementById("lv-add");
|
||||
if (addBtn) addBtn.addEventListener("click", function () { open(null); });
|
||||
dlg.addEventListener("click", function (e) {
|
||||
if (e.target.closest("[data-close]")) dlg.close();
|
||||
});
|
||||
|
||||
document.addEventListener("click", async function (e) {
|
||||
const edit = e.target.closest("[data-edit]");
|
||||
if (edit && edit.tagName === "BUTTON") { open(JSON.parse(edit.dataset.edit)); return; }
|
||||
const fresh = e.target.closest("button[data-new]");
|
||||
if (fresh) { open(JSON.parse(fresh.dataset.new)); return; }
|
||||
const btn = e.target.closest("button[data-post]");
|
||||
if (!btn) return;
|
||||
if (!(await window.erpConfirm(btn.dataset.confirm, dialogText()))) return;
|
||||
const r = await post(btn.dataset.post);
|
||||
if (r.ok) { reload(); return; }
|
||||
if (dlg.open) say(r.message); else window.erpAlert(r.message, dialogText());
|
||||
});
|
||||
|
||||
form.addEventListener("submit", async function (e) {
|
||||
e.preventDefault();
|
||||
const save = form.querySelector('button[type="submit"]');
|
||||
const body = new FormData(form);
|
||||
if (fileInput && !fileInput.files.length) body.delete("images");
|
||||
save.disabled = true;
|
||||
say("");
|
||||
const r = await post(form.getAttribute("action"), body);
|
||||
if (r.ok) { reload(); return; }
|
||||
save.disabled = false;
|
||||
say(r.message);
|
||||
});
|
||||
|
||||
if (!calWrap) return;
|
||||
|
||||
// ── 달력: 날짜로 가기(TIME 열이 고정이라 그 폭만큼 띄움) ──
|
||||
function jumpTo(iso) {
|
||||
const col = calWrap.querySelector('thead th[data-day="' + iso + '"]');
|
||||
const time = calWrap.querySelector("thead .lv-cal-time");
|
||||
if (col && time) calWrap.scrollLeft += col.getBoundingClientRect().left - time.getBoundingClientRect().right;
|
||||
}
|
||||
document.addEventListener("click", function (e) {
|
||||
const b = e.target.closest("[data-jump]");
|
||||
if (b) jumpTo(b.dataset.jump);
|
||||
});
|
||||
let left = null;
|
||||
try { left = sessionStorage.getItem(CAL_POS); sessionStorage.removeItem(CAL_POS); } catch (_) {}
|
||||
if (left !== null) calWrap.scrollLeft = Number(left);
|
||||
else {
|
||||
const today = calWrap.querySelector("thead th[data-today]");
|
||||
if (today) jumpTo(today.dataset.day);
|
||||
}
|
||||
|
||||
// ── 달력: 날짜별 광고비 ──
|
||||
document.addEventListener("click", async function (e) {
|
||||
const b = e.target.closest("button[data-spend]");
|
||||
if (!b) return;
|
||||
const value = await window.erpPrompt(tr("{day} 광고비 (RM) — 비우면 지웁니다").replace("{day}", b.dataset.spend), b.dataset.value || "", dialogText());
|
||||
if (value === null || value === undefined) return;
|
||||
const body = new FormData();
|
||||
body.set("day", b.dataset.spend);
|
||||
body.set("amount", value);
|
||||
const r = await post("/live/ad-spend", body);
|
||||
if (r.ok) reload(); else window.erpAlert(r.message, dialogText());
|
||||
});
|
||||
|
||||
// ── 달력: 카드 머리를 끌어 빈 칸으로 옮기기, 다른 카드 위에 놓아 맞바꾸기 ──
|
||||
let dragging = null;
|
||||
calWrap.addEventListener("dragstart", function (e) {
|
||||
const head = e.target.closest && e.target.closest(".lv-card-head");
|
||||
if (!head) return;
|
||||
dragging = head.closest("[data-card]").dataset.card;
|
||||
e.dataTransfer.effectAllowed = "move";
|
||||
e.dataTransfer.setData("text/plain", dragging);
|
||||
});
|
||||
calWrap.addEventListener("dragend", function () {
|
||||
dragging = null;
|
||||
calWrap.querySelectorAll(".is-drop").forEach(function (c) { c.classList.remove("is-drop"); });
|
||||
});
|
||||
calWrap.addEventListener("dragover", function (e) {
|
||||
const cell = dragging && e.target.closest("[data-drop]");
|
||||
if (!cell) return;
|
||||
e.preventDefault();
|
||||
calWrap.querySelectorAll(".is-drop").forEach(function (c) { if (c !== cell) c.classList.remove("is-drop"); });
|
||||
cell.classList.add("is-drop");
|
||||
});
|
||||
calWrap.addEventListener("drop", async function (e) {
|
||||
const cell = dragging && e.target.closest("[data-drop]");
|
||||
if (!cell) return;
|
||||
e.preventDefault();
|
||||
const id = dragging;
|
||||
const onto = e.target.closest("[data-card]");
|
||||
if (onto && onto.dataset.card === id) return;
|
||||
const body = new FormData();
|
||||
if (onto) body.set("swap_with", onto.dataset.card);
|
||||
else { body.set("broadcast_date", cell.dataset.day); body.set("start_time", cell.dataset.start); }
|
||||
const r = await post("/live/broadcasts/" + id + "/move", body);
|
||||
if (r.ok) reload(); else window.erpAlert(r.message, dialogText());
|
||||
});
|
||||
})();
|
||||
+83
-3
@@ -2,7 +2,21 @@
|
||||
.erp-page:has(> .otr) { box-sizing: border-box; } /* 셸 .erp-page width:100% + 여백 → 오른쪽 넘침 방지(실적·휴가와 같음) */
|
||||
.otr { display: flex; flex-direction: column; gap: 14px; }
|
||||
.otr > * { flex-shrink: 0; }
|
||||
.otr-top { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
|
||||
.otr-top { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
|
||||
.otr-top .otr-gmail { margin-left: auto; }
|
||||
/* 탭(2026-10-30) — [발송 리스트] [DM 수동 보내기] 알약 탭 + 맨 오른쪽 설정 톱니(실적 .perf-tabs 와 같은 모양) */
|
||||
.otr-tabs { display: flex; align-items: center; gap: 8px; padding-bottom: 10px; border-bottom: 1px solid #e3e5e8; }
|
||||
.otr-tabs-main { display: inline-flex; gap: 4px; padding: 4px; border-radius: 12px; background: var(--color-ghost-gray, #f3f3f3); }
|
||||
.otr-tab { display: inline-flex; align-items: center; gap: 6px; padding: 7px 16px; border-radius: 9px; font-size: 14px; font-weight: 600;
|
||||
color: var(--color-midtone-gray, #6d6e6f); text-decoration: none; transition: background .15s, color .15s; }
|
||||
.otr-tab .material-symbols-outlined { font-size: 19px; }
|
||||
.otr-tab:hover { color: var(--color-rich-black, #1e1f21); background: rgba(255, 255, 255, .7); }
|
||||
.otr-tab.is-active, .otr-tab.is-active:hover { color: #fff; background: var(--color-deep-black, #1e1f21); box-shadow: 0 1px 3px rgba(0, 0, 0, .18); }
|
||||
.otr-tabs .otr-gear { margin-left: auto; }
|
||||
.otr-gear { display: inline-flex; align-items: center; justify-content: center; width: 36px; height: 36px; border-radius: 50%;
|
||||
color: var(--color-midtone-gray, #6d6e6f); text-decoration: none; flex: none; }
|
||||
.otr-gear .material-symbols-outlined { font-size: 22px; }
|
||||
.otr-gear:hover { color: var(--color-rich-black, #1e1f21); background: var(--color-ghost-gray, #f3f3f3); }
|
||||
.otr-top-main { display: flex; gap: 8px; }
|
||||
.otr-gmail { display: flex; align-items: center; gap: 8px; font-size: 13px; flex-wrap: wrap; }
|
||||
.otr-gmail form { margin: 0; }
|
||||
@@ -10,6 +24,7 @@
|
||||
.otr-gmail-off { color: #8a5a00; }
|
||||
.otr-msg { margin: 0; padding: 8px 12px; border-radius: 8px; background: #eef6ff; color: #1a4fa0; font-size: 13px; }
|
||||
.otr .erp-card { padding: 14px 16px; }
|
||||
.otr .erp-card[hidden] { display: none; } /* 공용 .erp-card display:flex 가 hidden 을 덮어 [리스트 추가]·DM 수동 창이 늘 열려 있었다 */
|
||||
.otr-tpl-head { display: flex; align-items: baseline; gap: 8px; margin-bottom: 8px; font-size: 14px; flex-wrap: wrap; }
|
||||
.otr-tpl-head .erp-muted { font-size: 12px; }
|
||||
.otr-tpl-subject { font-weight: 700; font-size: 15px; }
|
||||
@@ -65,9 +80,47 @@
|
||||
.otr-set-card { display: flex; flex-direction: column; gap: 10px; }
|
||||
.otr-field { display: flex; flex-direction: column; gap: 4px; }
|
||||
.otr-field .erp-input { width: 100%; min-width: 0; box-sizing: border-box; }
|
||||
.otr-body { font-size: 14px; line-height: 1.6; resize: vertical; }
|
||||
.otr-count { font-size: 12px; }
|
||||
.otr-count.is-over { color: #c22b10; font-weight: 700; }
|
||||
.otr-check { display: flex; align-items: baseline; gap: 6px; font-size: 13px; }
|
||||
.otr-set-actions { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
/* 설정 — 위 저장 막대(스크롤해도 보임) + 세로 2단(왼쪽 메일 | 오른쪽 DM), 좁으면 위아래 */
|
||||
.otr-set-bar { position: sticky; top: 0; z-index: 20; display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin: 0;
|
||||
padding: 10px 14px; background: #fff; border: 1px solid #e3e5e8; border-radius: 10px; box-shadow: 0 2px 8px rgba(15, 23, 42, .06); }
|
||||
.otr-set-saved { font-size: 12px; }
|
||||
.otr-set-bar-gap { flex: 1; }
|
||||
.otr-split { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px; align-items: start; }
|
||||
.otr-col { display: flex; flex-direction: column; gap: 16px; min-width: 0; }
|
||||
.otr-col-head { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; font-size: 15px; padding-bottom: 10px; border-bottom: 1px solid #eef0f2; }
|
||||
.otr-col-head .erp-muted { font-size: 12px; }
|
||||
.otr-dm-card { position: sticky; top: 72px; }
|
||||
.otr-note { margin: 0; font-size: 12.5px; line-height: 1.6; }
|
||||
.otr-dm-foot { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; }
|
||||
.otr-tag { color: #e11d48; font-weight: 700; }
|
||||
@media (max-width: 1100px) {
|
||||
.otr-split { grid-template-columns: minmax(0, 1fr); }
|
||||
.otr-dm-card { position: static; }
|
||||
}
|
||||
/* 편집기(Quill snow) — 메일과 같은 글꼴·크기·줄 간격, {이름} 빨강 굵게(화면에서만) */
|
||||
.otr-settings .ql-toolbar.ql-snow { border-color: #d8dce2; border-radius: 8px 8px 0 0; background: #fafbfc; font-family: inherit; }
|
||||
.otr-settings .ql-toolbar.ql-snow .ql-formats { margin-right: 8px; }
|
||||
.otr-editor.ql-container.ql-snow { border-color: #d8dce2; border-radius: 0 0 8px 8px; font-family: Pretendard, 'Malgun Gothic', sans-serif; font-size: 14px; }
|
||||
.otr-editor-plain.ql-container.ql-snow { border-top: 1px solid #d8dce2; border-radius: 8px; }
|
||||
.otr-editor .ql-editor { min-height: 420px; max-height: 68vh; overflow-y: auto; line-height: 1.7; color: #111; }
|
||||
.otr-editor-plain .ql-editor { min-height: 320px; }
|
||||
.otr-editor .ql-editor.ql-blank::before { font-style: normal; color: #9aa1aa; }
|
||||
.otr-editor .otr-nametag-on { color: #e11d48 !important; font-weight: 700 !important; }
|
||||
.otr-settings .ql-snow .ql-picker.ql-size { width: 76px; }
|
||||
.otr-settings .ql-snow .ql-picker.ql-size .ql-picker-label::before,
|
||||
.otr-settings .ql-snow .ql-picker.ql-size .ql-picker-item::before { content: "기본"; }
|
||||
.otr-settings .ql-snow .ql-picker.ql-size .ql-picker-label[data-value]::before,
|
||||
.otr-settings .ql-snow .ql-picker.ql-size .ql-picker-item[data-value]::before { content: attr(data-value); }
|
||||
.otr-settings .ql-toolbar .ql-undo, .otr-settings .ql-toolbar .ql-redo { font-size: 17px; line-height: 1; color: #444; }
|
||||
.otr-settings .ql-snow .ql-tooltip { z-index: 5; }
|
||||
.otr-settings .ql-snow .ql-tooltip::before { content: "링크:"; }
|
||||
.otr-settings .ql-snow .ql-tooltip[data-mode=link]::before { content: "링크 주소:"; }
|
||||
.otr-settings .ql-snow .ql-tooltip a.ql-action::after { content: "고치기"; }
|
||||
.otr-settings .ql-snow .ql-tooltip a.ql-remove::before { content: "빼기"; }
|
||||
.otr-settings .ql-snow .ql-tooltip.ql-editing a.ql-action::after { content: "저장"; }
|
||||
.otr-images { display: flex; gap: 12px; flex-wrap: wrap; }
|
||||
.otr-image { margin: 0; width: 200px; border: 1px solid #e3e5e8; border-radius: 8px; padding: 8px; display: flex; flex-direction: column; gap: 6px; }
|
||||
.otr-image img { width: 100%; height: 150px; object-fit: cover; border-radius: 6px; background: #f6f7f9; }
|
||||
@@ -76,3 +129,30 @@
|
||||
.otr-image-acts form { margin: 0; }
|
||||
.otr-upload { display: flex; gap: 8px; align-items: center; margin-top: 8px; flex-wrap: wrap; }
|
||||
.otr .erp-btn:disabled { opacity: .45; cursor: default; }
|
||||
|
||||
/* DM 수동 보내기 탭(2026-10-30) — 왼쪽 이름(넣기 + 목록) | 가운데 본문(바로 고침, {이름} = 분홍 칩) | 오른쪽 저장한 본문 */
|
||||
.otr-dm-file { cursor: pointer; }
|
||||
.otr-dm-split { display: grid; grid-template-columns: minmax(220px, 280px) minmax(0, 1fr) minmax(200px, 260px); gap: 14px; align-items: start; }
|
||||
.otr .otr-dm-split .erp-card { min-height: 0; }
|
||||
.otr-dm-listhead { display: flex; align-items: center; justify-content: space-between; margin-top: 10px; font-size: 13px; }
|
||||
.otr-dm-names { list-style: none; margin: 8px 0 0; padding: 4px; border: 1px solid #e3e5e8; border-radius: 8px;
|
||||
max-height: calc(100vh - 420px); min-height: 120px; overflow: auto; }
|
||||
.otr-dm-bodies { max-height: calc(100vh - 260px); margin-top: 0; }
|
||||
.otr-dm-item { display: flex; align-items: center; gap: 2px; }
|
||||
.otr-dm-name { flex: 1; min-width: 0; text-align: left; border: 0; background: none; font: inherit; font-size: 13.5px;
|
||||
padding: 7px 10px; border-radius: 6px; cursor: pointer; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.otr-dm-name:hover { background: #f3f4f6; }
|
||||
.otr-dm-name.is-active { background: #111; color: #fff; }
|
||||
.otr-dm-sub { opacity: .65; font-size: 12px; }
|
||||
.otr-dm-x { flex: none; width: 26px; height: 26px; border: 0; border-radius: 6px; background: none; color: #9a9ca1; font-size: 17px;
|
||||
line-height: 1; cursor: pointer; }
|
||||
.otr-dm-x:hover { background: #fdecec; color: #c22b10; }
|
||||
.otr-dm-empty { padding: 8px 10px; font-size: 13px; }
|
||||
.otr-dm-cur { font-weight: 400; color: #6d6e6f; font-size: 13px; }
|
||||
.otr-dm-actions { margin: 0 0 8px; }
|
||||
.otr-dm-body { border: 1px solid #d8dce2; border-radius: 8px; padding: 14px 16px; font-size: 14px; line-height: 1.7; min-height: 240px;
|
||||
white-space: pre-wrap; word-break: break-word; max-height: calc(100vh - 300px); overflow: auto; background: #fff; outline: none; }
|
||||
.otr-dm-body:focus { border-color: #8aa4d6; box-shadow: 0 0 0 3px rgba(69, 115, 210, .12); }
|
||||
.otr-dm-tag { color: #c1358a; font-weight: 700; background: #fbe8f3; border-radius: 4px; padding: 0 2px; }
|
||||
@media (max-width: 1180px) { .otr-dm-split { grid-template-columns: minmax(220px, 280px) minmax(0, 1fr); } .otr-dm-saved { grid-column: 1 / -1; } }
|
||||
@media (max-width: 760px) { .otr-dm-split { grid-template-columns: 1fr; } }
|
||||
|
||||
+310
-16
@@ -1,6 +1,7 @@
|
||||
/* 안내문 발송(2026-10-27) — 리스트 화면: 붙여 넣기 → 미리보기(메일/DM/오류) → 추가, 걸러 보기, 이름 고치기,
|
||||
메일 = 고른 줄 [고른 메일 보내기](서버가 본인 Gmail 로 한 통씩, 보내는 동안 2초마다 다시 읽음),
|
||||
DM = [DM 보내기](그 사람 이름이 들어간 문구를 클립보드에 + ig.me DM 창을 새 탭) → [보냄]. 설정 화면 = [기본 문구로 되돌리기]. */
|
||||
DM = [DM 보내기](그 사람 이름이 들어간 문구를 클립보드에 + ig.me DM 창을 새 탭) → [보냄].
|
||||
설정 화면 = 세로 2단(메일 | DM) — 메일 본문 서식 편집기·DM 편집기(Quill), {이름} 빨강 굵게, [기본 문구로 되돌리기], DM 글자 수. */
|
||||
(function () {
|
||||
"use strict";
|
||||
|
||||
@@ -17,14 +18,14 @@
|
||||
if (!res.ok) { const e = new Error(data.message || data.detail || ("HTTP " + res.status)); e.status = res.status; e.data = data; throw e; }
|
||||
return data;
|
||||
}
|
||||
function toast(msg, bad) {
|
||||
function toast(msg, bad, ms) {
|
||||
let el = document.getElementById("otr-toast");
|
||||
if (!el) { el = document.createElement("div"); el.id = "otr-toast"; el.className = "otr-toast"; document.body.appendChild(el); }
|
||||
el.textContent = msg;
|
||||
el.classList.toggle("is-bad", !!bad);
|
||||
el.hidden = false;
|
||||
clearTimeout(el._t);
|
||||
el._t = setTimeout(function () { el.hidden = true; }, 4000);
|
||||
el._t = setTimeout(function () { el.hidden = true; }, ms || 4000);
|
||||
}
|
||||
async function copyText(text) {
|
||||
try { await navigator.clipboard.writeText(text); return true; } catch (_) { /* 아래로 */ }
|
||||
@@ -38,19 +39,312 @@
|
||||
}
|
||||
|
||||
// ── 설정 화면 ──
|
||||
const defBtn = document.getElementById("otr-default");
|
||||
if (defBtn) {
|
||||
defBtn.addEventListener("click", function () {
|
||||
let d = {};
|
||||
try { d = JSON.parse(document.getElementById("otr-default-data").textContent); } catch (_) { d = {}; }
|
||||
if (!confirm("제목·본문·보내는 이름·끝 문구를 기본 문구로 바꿀까요? ([저장]을 눌러야 적용)")) return;
|
||||
const f = document.getElementById("otr-set-form");
|
||||
f.subject.value = d.subject || "";
|
||||
f.body.value = d.body || "";
|
||||
f.sender_name.value = d.sender_name || "";
|
||||
f.footer.value = d.footer || "";
|
||||
f.ad_label.checked = !!d.ad_label;
|
||||
const setForm = document.getElementById("otr-set-form");
|
||||
if (setForm) {
|
||||
if (window.Quill) initSettings(window.Quill, setForm);
|
||||
else toast("편집기를 불러오지 못했습니다 — 새로 고침해 주세요.", true);
|
||||
}
|
||||
|
||||
// 메일 본문 = 서식 편집기(글자 크기·굵게·기울임·밑줄·취소선·글자/배경 색·정렬·목록·링크·서식 지우기·되돌리기),
|
||||
// DM = 서식 없는 편집기. 두 편집기 모두 {이름} = 빨강 굵게(class 만 — 저장하면 서버가 class 를 지워 메일에는 안 남음).
|
||||
// 저장 = 메일 본문 getSemanticHTML() → body(fmt=html, 서버가 허용 태그만 남김), DM getText() → dm_body.
|
||||
function initSettings(Quill, form) {
|
||||
const TAG = "{이름}";
|
||||
const SIZES = ["12px", "16px", "18px", "20px", "24px", "30px"]; // 없음(false) = 기본 14px
|
||||
const Parchment = Quill.import("parchment");
|
||||
Quill.register(new Parchment.ClassAttributor("nametag", "otr-nametag", { scope: Parchment.Scope.INLINE }), true);
|
||||
const Size = Quill.import("attributors/style/size");
|
||||
Size.whitelist = SIZES;
|
||||
Quill.register(Size, true);
|
||||
Quill.register(Quill.import("attributors/style/align"), true);
|
||||
|
||||
function readJson(id) {
|
||||
try { return JSON.parse(document.getElementById(id).textContent) || {}; } catch (_) { return {}; }
|
||||
}
|
||||
const mail = new Quill("#otr-body-editor", {
|
||||
theme: "snow", placeholder: "메일 본문",
|
||||
modules: {
|
||||
history: { userOnly: true },
|
||||
toolbar: {
|
||||
container: [
|
||||
[{ size: [false].concat(SIZES) }],
|
||||
["bold", "italic", "underline", "strike"],
|
||||
[{ color: [] }, { background: [] }],
|
||||
[{ align: [] }],
|
||||
[{ list: "ordered" }, { list: "bullet" }],
|
||||
["link", "clean"],
|
||||
["undo", "redo"],
|
||||
],
|
||||
handlers: { undo: function () { mail.history.undo(); }, redo: function () { mail.history.redo(); } },
|
||||
},
|
||||
},
|
||||
});
|
||||
const dmEl = document.getElementById("otr-dm-editor");
|
||||
const dm = new Quill(dmEl, { theme: "snow", placeholder: dmEl.dataset.placeholder || "",
|
||||
formats: ["nametag"], modules: { toolbar: false, history: { userOnly: true } } });
|
||||
|
||||
// 도구 막대 — 되돌리기 아이콘, 한글 도움말
|
||||
const tb = mail.getModule("toolbar").container;
|
||||
tb.querySelector(".ql-undo").innerHTML = "↶";
|
||||
tb.querySelector(".ql-redo").innerHTML = "↷";
|
||||
const tips = { ".ql-size": "글자 크기", ".ql-bold": "굵게 (Ctrl+B)", ".ql-italic": "기울임 (Ctrl+I)", ".ql-underline": "밑줄 (Ctrl+U)",
|
||||
".ql-strike": "취소선", ".ql-color": "글자 색", ".ql-background": "배경 색", ".ql-align": "정렬",
|
||||
'.ql-list[value="ordered"]': "번호 목록", '.ql-list[value="bullet"]': "글머리 목록", ".ql-link": "링크",
|
||||
".ql-clean": "서식 지우기", ".ql-undo": "되돌리기 (Ctrl+Z)", ".ql-redo": "다시 하기 (Ctrl+Y)" };
|
||||
Object.keys(tips).forEach(function (sel) { tb.querySelectorAll(sel).forEach(function (el) { el.title = tips[sel]; }); });
|
||||
|
||||
// {이름} 빨강 굵게 — 지금 칠한 곳과 있어야 할 곳이 다를 때만 고친다(글자 칠 때마다 DOM 을 건드리지 않게, 한글 조합 중엔 쉼)
|
||||
function markNames(q) {
|
||||
if (q.composition && q.composition.isComposing) return;
|
||||
const text = q.getText(), want = [];
|
||||
for (let i = text.indexOf(TAG); i >= 0; i = text.indexOf(TAG, i + TAG.length)) {
|
||||
const last = want[want.length - 1];
|
||||
if (last && last[1] === i) last[1] = i + TAG.length; else want.push([i, i + TAG.length]);
|
||||
}
|
||||
const have = [];
|
||||
let pos = 0;
|
||||
q.getContents().ops.forEach(function (op) {
|
||||
const len = typeof op.insert === "string" ? op.insert.length : 1;
|
||||
if (op.attributes && op.attributes.nametag) {
|
||||
const last = have[have.length - 1];
|
||||
if (last && last[1] === pos) last[1] = pos + len; else have.push([pos, pos + len]);
|
||||
}
|
||||
pos += len;
|
||||
});
|
||||
if (JSON.stringify(want) === JSON.stringify(have)) return;
|
||||
have.forEach(function (r) { q.formatText(r[0], r[1] - r[0], "nametag", false, "silent"); });
|
||||
want.forEach(function (r) { q.formatText(r[0], r[1] - r[0], "nametag", "on", "silent"); });
|
||||
}
|
||||
function setMail(html) {
|
||||
mail.setContents(mail.clipboard.convert({ html: html || "" }), "silent");
|
||||
markNames(mail);
|
||||
}
|
||||
function setDm(text) {
|
||||
dm.setText(text || "", "silent");
|
||||
markNames(dm);
|
||||
dmCount();
|
||||
}
|
||||
|
||||
// DM 글자 수(인스타 DM 한 통 한도)
|
||||
const countEl = document.getElementById("otr-dm-count"), dmMax = Number(countEl.dataset.max) || 1000;
|
||||
function dmValue() { return dm.getText().replace(/\s+$/, ""); }
|
||||
function dmCount() {
|
||||
const n = dmValue().length;
|
||||
countEl.textContent = n ? n + " / " + dmMax + "자" : "비어 있음 — 메일 본문 글 + 끝 문구가 복사됩니다";
|
||||
countEl.classList.toggle("is-over", n > dmMax);
|
||||
}
|
||||
|
||||
let dirty = false;
|
||||
mail.on("text-change", function (d, o, source) { if (source !== "silent") { dirty = true; markNames(mail); } });
|
||||
dm.on("text-change", function (d, o, source) { if (source !== "silent") { dirty = true; markNames(dm); dmCount(); } });
|
||||
document.addEventListener("input", function (e) { if (e.target.form === form) dirty = true; });
|
||||
window.addEventListener("beforeunload", function (e) { if (dirty) { e.preventDefault(); e.returnValue = ""; } });
|
||||
|
||||
const cur = readJson("otr-current-data");
|
||||
setMail(cur.body);
|
||||
setDm(cur.dm_body);
|
||||
|
||||
document.getElementById("otr-dm-from-mail").addEventListener("click", function () {
|
||||
if (dmValue() && !confirm("지금 DM 문구를 메일 본문 글로 바꿀까요?")) return;
|
||||
setDm(mail.getText().replace(/\s+$/, ""));
|
||||
dirty = true;
|
||||
});
|
||||
document.getElementById("otr-default").addEventListener("click", function () {
|
||||
if (!confirm("제목·본문·보내는 이름·끝 문구·DM 문구를 기본 문구로 바꿀까요? ([저장]을 눌러야 적용)")) return;
|
||||
const d = readJson("otr-default-data");
|
||||
form.elements.subject.value = d.subject || "";
|
||||
form.elements.sender_name.value = d.sender_name || "";
|
||||
form.elements.footer.value = d.footer || "";
|
||||
form.elements.ad_label.checked = !!d.ad_label;
|
||||
setMail(d.body);
|
||||
setDm(d.dm_body);
|
||||
dirty = true;
|
||||
});
|
||||
form.addEventListener("submit", function (e) {
|
||||
if (!mail.getText().trim()) { e.preventDefault(); toast("메일 본문을 쓰세요.", true); mail.focus(); return; }
|
||||
if (dmValue().length > dmMax) { e.preventDefault(); toast("DM 문구가 " + dmMax + "자를 넘습니다 — 줄여 주세요.", true); dm.focus(); return; }
|
||||
document.getElementById("otr-body-input").value = mail.getSemanticHTML();
|
||||
document.getElementById("otr-dm-input").value = dmValue();
|
||||
dirty = false;
|
||||
});
|
||||
}
|
||||
|
||||
// ── DM 수동 보내기 탭(2026-10-30, /outreach/dm) — 왼쪽 이름 목록(넣기·한 명씩/전체 지우기, 브라우저만), 가운데 본문(바로 고침,
|
||||
// {이름} 자리 = 분홍 칩), 오른쪽 저장한 본문(outreach_db 002 — 고르기·저장·새로 저장·하나씩 지우기, 맨 위 = 설정 DM 문구).
|
||||
// 이름을 누르면 본문 칩이 그 이름으로 바뀌고 이름이 들어간 글을 바로 복사 + 짧은 안내.
|
||||
const dmRoot = document.getElementById("otr-dm");
|
||||
if (dmRoot) initDm();
|
||||
function initDm() {
|
||||
const TAG = "{이름}";
|
||||
const dmText = document.getElementById("otr-dm-text");
|
||||
const dmNames = document.getElementById("otr-dm-names"), dmBody = document.getElementById("otr-dm-body");
|
||||
const bodiesEl = document.getElementById("otr-dm-bodies");
|
||||
const saveBtn = document.getElementById("otr-dm-save"), saveAsBtn = document.getElementById("otr-dm-saveas");
|
||||
let data = {};
|
||||
try { data = JSON.parse(document.getElementById("otr-data").textContent) || {}; } catch (_) { data = {}; }
|
||||
const settingsText = data.dm_template || "";
|
||||
const dmMax = data.dm_max || 1000;
|
||||
let bodies = data.dm_bodies; // null = 002 미적용(저장 못 함)
|
||||
let bodyId = null; // 지금 본문이 어느 저장 본문인지(null = 설정 DM 문구, -1 = 지운 본문에서 이어 쓰는 새 글)
|
||||
let dirty = false;
|
||||
let names = [], pick = -1;
|
||||
|
||||
// 줄마다 첫 칸(탭·쉼표 앞) = 이름, 빈 줄·머리글("이름")은 뺀다
|
||||
function parseNames(text) {
|
||||
return String(text || "").split(/\r?\n/).map(function (line) {
|
||||
return line.split(/[\t,]/)[0].replace(/^["']|["']$/g, "").trim();
|
||||
}).filter(function (n) { return n && n !== "이름"; });
|
||||
}
|
||||
// 본문 편집 칸 ↔ 글 — {이름} 자리는 고칠 수 없는 칩(span[data-tag]), 줄바꿈은 글(\n)·<br>·<div> 무엇이 와도
|
||||
function bodyText() {
|
||||
let out = "";
|
||||
(function walk(node) {
|
||||
node.childNodes.forEach(function (c) {
|
||||
if (c.nodeType === 3) out += c.nodeValue;
|
||||
else if (c.nodeType !== 1) return;
|
||||
else if (c.dataset.tag != null) out += TAG;
|
||||
else if (c.tagName === "BR") out += "\n";
|
||||
else {
|
||||
if (/^(DIV|P)$/.test(c.tagName) && out && !out.endsWith("\n")) out += "\n";
|
||||
walk(c);
|
||||
}
|
||||
});
|
||||
})(dmBody);
|
||||
return out.replace(/ /g, " ");
|
||||
}
|
||||
function setBody(text) {
|
||||
const name = pick >= 0 ? names[pick] : "";
|
||||
dmBody.textContent = "";
|
||||
String(text).split(TAG).forEach(function (part, i) {
|
||||
if (i) {
|
||||
const chip = document.createElement("span");
|
||||
chip.className = "otr-dm-tag";
|
||||
chip.dataset.tag = "";
|
||||
chip.contentEditable = "false";
|
||||
chip.textContent = name || TAG;
|
||||
dmBody.appendChild(chip);
|
||||
}
|
||||
if (part) dmBody.appendChild(document.createTextNode(part));
|
||||
});
|
||||
updateCount();
|
||||
}
|
||||
function filled() { return bodyText().split(TAG).join(pick >= 0 ? names[pick] : TAG); }
|
||||
function updateCount() {
|
||||
const n = filled().length;
|
||||
const el = document.getElementById("otr-dm-count");
|
||||
el.textContent = n + " / " + dmMax + "자" + (dirty ? " · 고친 뒤 저장 안 함" : "");
|
||||
el.classList.toggle("otr-err", n > dmMax);
|
||||
}
|
||||
function renderNames() {
|
||||
dmNames.innerHTML = names.length
|
||||
? names.map(function (n, i) {
|
||||
return '<li class="otr-dm-item"><button type="button" class="otr-dm-name' + (i === pick ? " is-active" : "") + '" data-i="' + i + '">' + esc(n) +
|
||||
'</button><button type="button" class="otr-dm-x" data-del="' + i + '" title="' + esc(n) + ' 빼기" aria-label="' + esc(n) + ' 빼기">×</button></li>';
|
||||
}).join("")
|
||||
: '<li class="erp-muted otr-dm-empty">이름을 넣으면 여기에 나옵니다.</li>';
|
||||
document.getElementById("otr-dm-sum").textContent = names.length + "명";
|
||||
document.getElementById("otr-dm-clear").disabled = !names.length;
|
||||
}
|
||||
function renderBodies() {
|
||||
const cur = document.getElementById("otr-dm-cur");
|
||||
const sel = bodies && bodyId != null ? bodies.find(function (b) { return b.id === bodyId; }) : null;
|
||||
cur.textContent = sel ? "— " + sel.title : bodyId == null ? "— 설정 DM 문구" : "";
|
||||
saveBtn.disabled = !sel;
|
||||
saveAsBtn.disabled = bodies == null;
|
||||
if (!bodiesEl) return;
|
||||
bodiesEl.innerHTML = '<li class="otr-dm-item"><button type="button" class="otr-dm-name' + (bodyId == null ? " is-active" : "") +
|
||||
'" data-body="settings">설정 DM 문구 <span class="otr-dm-sub">(기본)</span></button></li>' +
|
||||
(bodies || []).map(function (b) {
|
||||
return '<li class="otr-dm-item"><button type="button" class="otr-dm-name' + (b.id === bodyId ? " is-active" : "") + '" data-body="' + b.id +
|
||||
'" title="' + esc(b.updated_by + " · " + (b.updated_at || "").slice(0, 16).replace("T", " ")) + '">' + esc(b.title) +
|
||||
'</button><button type="button" class="otr-dm-x" data-delbody="' + b.id + '" title="이 본문 지우기" aria-label="' + esc(b.title) + ' 지우기">×</button></li>';
|
||||
}).join("");
|
||||
}
|
||||
|
||||
document.getElementById("otr-dm-load").addEventListener("click", function () {
|
||||
const add = parseNames(dmText.value).filter(function (n, i, all) { return names.indexOf(n) < 0 && all.indexOf(n) === i; });
|
||||
if (!add.length) { toast("새로 넣을 이름이 없습니다(빈 칸이거나 이미 목록에 있음).", true); return; }
|
||||
names = names.concat(add);
|
||||
dmText.value = "";
|
||||
renderNames();
|
||||
});
|
||||
document.getElementById("otr-dm-file").addEventListener("change", async function (e) {
|
||||
const f = e.target.files && e.target.files[0];
|
||||
if (!f) return;
|
||||
try { dmText.value = await f.text(); document.getElementById("otr-dm-load").click(); } catch (err) { toast("파일을 읽지 못했습니다: " + err.message, true); }
|
||||
e.target.value = "";
|
||||
});
|
||||
document.getElementById("otr-dm-clear").addEventListener("click", function () {
|
||||
if (!names.length || !confirm("이름 " + names.length + "명을 목록에서 모두 지울까요?")) return;
|
||||
const text = bodyText();
|
||||
names = []; pick = -1;
|
||||
renderNames();
|
||||
setBody(text);
|
||||
});
|
||||
dmNames.addEventListener("click", async function (e) {
|
||||
const del = e.target.closest("[data-del]");
|
||||
const text = bodyText();
|
||||
if (del) { // 한 명 빼기 — 고른 사람이면 본문은 {이름} 으로
|
||||
const i = +del.dataset.del;
|
||||
names.splice(i, 1);
|
||||
if (pick === i) pick = -1; else if (pick > i) pick -= 1;
|
||||
renderNames();
|
||||
setBody(text);
|
||||
return;
|
||||
}
|
||||
const b = e.target.closest(".otr-dm-name");
|
||||
if (!b) return;
|
||||
pick = +b.dataset.i;
|
||||
renderNames();
|
||||
setBody(text);
|
||||
const name = names[pick];
|
||||
const ok = await copyText(filled());
|
||||
toast(ok ? name + " 님 문구를 클립보드에 복사했습니다." : "복사하지 못했습니다 — 본문을 직접 복사하세요.", !ok, 1600);
|
||||
});
|
||||
dmBody.addEventListener("input", function () { dirty = true; updateCount(); });
|
||||
|
||||
// 저장한 본문 — 고르기(고친 글이 있으면 확인) · 하나씩 지우기
|
||||
if (bodiesEl) bodiesEl.addEventListener("click", async function (e) {
|
||||
const del = e.target.closest("[data-delbody]");
|
||||
if (del) {
|
||||
const id = +del.dataset.delbody, b = (bodies || []).find(function (x) { return x.id === id; });
|
||||
if (!confirm("저장한 본문 '" + (b ? b.title : id) + "' 을(를) 지울까요?")) return;
|
||||
try {
|
||||
bodies = (await api("DELETE", "/outreach/api/dm-bodies/" + id)).items;
|
||||
if (bodyId === id) { bodyId = -1; dirty = true; } // 보고 있던 본문을 지우면 글은 남기고 "새 글"로
|
||||
renderBodies(); updateCount();
|
||||
toast("지웠습니다.", false, 1600);
|
||||
} catch (err) { toast("지우기 실패: " + err.message, true); }
|
||||
return;
|
||||
}
|
||||
const b = e.target.closest("[data-body]");
|
||||
if (!b) return;
|
||||
if (dirty && !confirm("고친 본문을 저장하지 않았습니다. 버리고 바꿀까요?")) return;
|
||||
if (b.dataset.body === "settings") { bodyId = null; setBody(settingsText); }
|
||||
else {
|
||||
const item = (bodies || []).find(function (x) { return x.id === +b.dataset.body; });
|
||||
if (!item) return;
|
||||
bodyId = item.id; setBody(item.body);
|
||||
}
|
||||
dirty = false;
|
||||
renderBodies(); updateCount();
|
||||
});
|
||||
async function saveBody(asNew) {
|
||||
try {
|
||||
const d = asNew ? await api("POST", "/outreach/api/dm-bodies", { body: bodyText() })
|
||||
: await api("PUT", "/outreach/api/dm-bodies/" + bodyId, { body: bodyText() });
|
||||
bodies = d.items; bodyId = d.id; dirty = false;
|
||||
renderBodies(); updateCount();
|
||||
toast(asNew ? "새 본문으로 저장했습니다." : "저장했습니다.", false, 1600);
|
||||
} catch (err) { toast("저장 실패: " + err.message, true); }
|
||||
}
|
||||
saveBtn.addEventListener("click", function () { saveBody(false); });
|
||||
saveAsBtn.addEventListener("click", function () { saveBody(true); });
|
||||
|
||||
renderNames();
|
||||
setBody(settingsText);
|
||||
renderBodies();
|
||||
if (!settingsText.trim()) toast("DM 문구가 비었습니다 — 본문을 쓰거나 설정에서 DM 문구를 넣으세요.", true);
|
||||
}
|
||||
|
||||
// ── 리스트 화면 ──
|
||||
@@ -153,7 +447,7 @@
|
||||
const r = rowOf(btn);
|
||||
if (!r) return;
|
||||
if (btn.dataset.act === "dm") {
|
||||
if (r.needs_name) { toast("이름을 먼저 넣으세요 — 본문에 {이름}이 있습니다.", true); return; }
|
||||
if (r.needs_name) { toast("이름을 먼저 넣으세요 — DM 문구에 {이름}이 있습니다.", true); return; }
|
||||
// 누르는 순간 바로(브라우저가 막지 않게) — 문구 복사 + DM 창 새 탭. 문구는 화면 데이터에 미리 있다.
|
||||
const win = window.open(r.dm_link, "_blank", "noopener");
|
||||
const ok = await copyText(r.dm_text || "");
|
||||
|
||||
+52
-29
@@ -54,7 +54,6 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
|
||||
|
||||
/* 광고비 화면 — 주황 강조(매출 실적과 구분) */
|
||||
.perf, .perf-modal { --perf-ad: #d9480f; }
|
||||
.perf-ads .perf-kpi.is-primary { border-color: var(--perf-ad); box-shadow: inset 4px 0 0 var(--perf-ad); }
|
||||
.perf-ads .perf-quick .perf-seg.is-active { background: var(--perf-ad); }
|
||||
.perf-ads .perf-chart .bar { fill: var(--perf-ad); }
|
||||
.perf-ads td.is-upload .v-gross { color: var(--perf-ad); }
|
||||
@@ -77,7 +76,6 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
|
||||
.perf-detail-tabs { flex-wrap: wrap; margin-bottom: 10px; }
|
||||
.perf-detail-tabs .perf-seg.is-active { background: var(--perf-ad); }
|
||||
.perf-ad-upload-btn { margin-left: auto; }
|
||||
.perf-kpi-pct { font-size: 26px; font-weight: 700; }
|
||||
|
||||
/* 도구 막대 */
|
||||
.perf-toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }
|
||||
@@ -89,13 +87,12 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
|
||||
.perf-seg:hover { background: var(--color-ghost-gray); }
|
||||
.perf-seg.is-active { background: var(--color-deep-black); color: #fff; }
|
||||
a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited { color: #fff; }
|
||||
.perf-nav { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.perf-nav-btn {
|
||||
font-size: 12px; padding: 5px 9px; border: 1px solid var(--perf-line); border-radius: 8px; background: #fff;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.perf-nav { display: inline-flex; align-items: center; gap: 2px; }
|
||||
/* 기간 이동 화살표(2026-11-02) — 진한 회색 SVG, 높이 = 날짜 글자 크기(1em) */
|
||||
.perf-nav-btn { display: inline-flex; padding: 4px 5px; border-radius: 6px; font-size: 14px; }
|
||||
.perf-nav-btn:hover { background: var(--color-ghost-gray); }
|
||||
.perf-nav-label { font-weight: 600; font-size: 14px; min-width: 200px; text-align: center; }
|
||||
.perf-nav-btn svg { display: block; height: 1em; width: auto; fill: none; stroke: #444; stroke-width: 2.6; stroke-linecap: round; stroke-linejoin: round; }
|
||||
.perf-nav-label { font-weight: 600; font-size: 14px; text-align: center; }
|
||||
.perf-custom { display: inline-flex; align-items: center; gap: 6px; }
|
||||
.perf-custom[hidden] { display: none; }
|
||||
/* 공통 .erp-input 의 min-width:240px 를 날짜칸에서만 푼다 */
|
||||
@@ -134,18 +131,17 @@ a.perf-seg.is-active, a.perf-seg.is-active:link, a.perf-seg.is-active:visited {
|
||||
.perf-problem { padding: 1px 8px; border-radius: 999px; background: #fbe9e6; color: var(--perf-down); font-weight: 500; }
|
||||
|
||||
/* KPI */
|
||||
.perf-kpis { display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 10px; }
|
||||
.perf-kpi { border: 1px solid var(--perf-line); border-radius: 12px; padding: 12px 14px; background: #fff; min-width: 0; }
|
||||
.perf-kpi.is-primary { border-color: #cfcfcf; box-shadow: inset 3px 0 0 var(--color-deep-black); }
|
||||
.perf-kpi-label { font-size: 12px; color: var(--color-midtone-gray); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.perf-kpi-value { font-size: 22px; font-weight: 600; letter-spacing: -.5px; margin: 2px 0; white-space: nowrap; }
|
||||
.perf-kpi.is-primary .perf-kpi-value { font-size: 24px; }
|
||||
.perf-kpi-delta { font-size: 12px; display: flex; gap: 6px; align-items: baseline; flex-wrap: wrap; }
|
||||
/* 매출 실적 KPI 한 줄(2026-10-19) — 수수료 차감 매출 금액 + 비교 기간 대비 %, 화면 왼쪽 */
|
||||
.perf-kpi-line { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; font-size: 13px; padding: 2px 2px 0; }
|
||||
.perf-kpi-line-value { font-size: 22px; font-weight: 700; letter-spacing: -.5px; color: var(--color-rich-black); white-space: nowrap; }
|
||||
/* 광고비 KPI 한 줄(2026-10-30) — 항목(이름 + 금액 + 대비 %) 여럿을 세로 선으로 나눔, 첫 항목(광고비)만 큰 글자 */
|
||||
.perf-ads .perf-kpi-line { column-gap: 0; row-gap: 4px; }
|
||||
.perf-kpi-item { display: inline-flex; align-items: baseline; gap: 6px; flex-wrap: wrap; }
|
||||
.perf-kpi-item + .perf-kpi-item { border-left: 1px solid var(--perf-line); margin-left: 14px; padding-left: 14px; }
|
||||
.perf-kpi-line-value.is-sub { font-size: 17px; }
|
||||
/* 다음 자동 업데이트까지 남은 시간(초 단위) — 숫자 폭이 바뀌어도 흔들리지 않게 */
|
||||
.perf-next-update b { font-variant-numeric: tabular-nums; }
|
||||
.perf-refresh-note { color: var(--perf-up); font-weight: 600; } /* 자동 업데이트 끝 → 새로 고침 안내 */
|
||||
.perf-delta { font-weight: 600; }
|
||||
.perf-delta.is-up { color: var(--perf-good); } /* is-up = 좋음(수수료는 줄어야 좋음, invert) */
|
||||
.perf-delta.is-down { color: var(--perf-down); }
|
||||
@@ -284,15 +280,9 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
.perf-test-result.is-ok { color: #0f8a3a; }
|
||||
.perf-test-result.is-bad { color: var(--perf-down); }
|
||||
|
||||
@media (min-width: 1281px) {
|
||||
.perf-ads .perf-kpis { grid-template-columns: repeat(4, minmax(0, 1fr)); } /* 광고비 KPI 4개 */
|
||||
}
|
||||
@media (max-width: 1280px) {
|
||||
.perf-kpis { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
}
|
||||
@media (max-width: 980px) {
|
||||
.perf-grid2 { grid-template-columns: 1fr; }
|
||||
.perf-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.perf-kpi-item + .perf-kpi-item { border-left: 0; margin-left: 0; padding-left: 0; } /* 좁으면 한 항목씩 줄바꿈 — 구분선 없이 */
|
||||
.perf-update { margin-left: 0; }
|
||||
}
|
||||
|
||||
@@ -375,7 +365,9 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
.perf-unit-suffix { margin-left: 2px; font-size: .55em; font-weight: 600; color: var(--color-midtone-gray, #777); }
|
||||
/* 보기 설정(매출 단위) */
|
||||
.perf-opt-row { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
|
||||
.perf-opt-label { font-weight: 600; }
|
||||
.perf-opt-label { font-weight: 600; min-width: 72px; }
|
||||
.perf-opt-row + .perf-opt-row { margin-top: 10px; }
|
||||
.perf-hide-list { display: flex; flex-wrap: wrap; gap: 0 12px; }
|
||||
/* 자동 업데이트 일정(2026-10-26) — 매출 실적·광고비 한 줄씩: 이름·사용 | 요일·시간·간격 | 다음 회차 */
|
||||
.perf-auto-rows { display: flex; flex-direction: column; }
|
||||
.perf-auto-row { display: grid; grid-template-columns: 130px 1fr; gap: 6px 16px; padding: 12px 0; border-top: 1px solid var(--perf-line); }
|
||||
@@ -394,8 +386,19 @@ td.is-link:hover { background: #eef2ff; text-decoration: underline; }
|
||||
.perf-day.is-sun span { color: var(--perf-sun); }
|
||||
.perf-day input:checked + span { background: #111; border-color: #111; color: #fff; }
|
||||
.perf-day input:focus-visible + span { outline: 2px solid var(--perf-good); outline-offset: 1px; }
|
||||
.perf-auto-time { width: auto; padding-right: 22px; }
|
||||
.perf-auto-interval { width: 76px; }
|
||||
/* 공용 .erp-input 은 min-width 240px — 이 카드는 글자 너비만큼 */
|
||||
#perf-auto-sync .perf-auto-time { min-width: 0; width: auto; padding-right: 4px; }
|
||||
#perf-auto-sync .perf-auto-interval { min-width: 0; width: calc(3ch + 40px); }
|
||||
/* 시간 오른쪽 아날로그 시계 — 시작 ~ 끝 바늘 사이를 빨갛게(12시간 넘는 부분은 진하게 한 번 더) */
|
||||
.perf-auto-clock { width: 64px; height: 64px; flex: 0 0 auto; margin-left: 6px; }
|
||||
.perf-auto-clock .c-face { fill: #fff; stroke: #c9c9c9; stroke-width: 1.5; }
|
||||
.perf-auto-clock .c-span { fill: var(--perf-down); fill-opacity: .78; }
|
||||
.perf-auto-clock .c-span2 { fill: #8f1414; fill-opacity: .85; }
|
||||
.perf-auto-clock .c-tick { stroke: #9a9a9a; stroke-width: 1.5; stroke-linecap: round; }
|
||||
.perf-auto-clock .c-tick.is-major { stroke: #333; stroke-width: 2.5; }
|
||||
.perf-auto-clock .c-hand { stroke: #111; stroke-width: 3; stroke-linecap: round; }
|
||||
.perf-auto-clock .c-hand.is-end { stroke-width: 2.2; }
|
||||
.perf-auto-clock .c-pin { fill: #111; }
|
||||
.perf-auto-next { grid-column: 2; }
|
||||
.perf-auto-actions { display: flex; align-items: center; gap: 10px; margin-top: 6px; }
|
||||
#perf-auto-msg.is-ok { color: var(--perf-up); }
|
||||
@@ -435,11 +438,15 @@ body.perf-dragging, body.perf-dragging * { cursor: grabbing !important; user-sel
|
||||
/* ── 매출 실적 표(2026-10-22): 열 너비 = 내용 길이(모든 기간 같음), 날짜 열 고정, 그룹·하위 열 구분, 접기 애니메이션 ── */
|
||||
.perf-main.perf-autofit { width: auto; }
|
||||
.perf-main.perf-autofit thead th.perf-th-label, .perf-main.perf-autofit .perf-td-label { width: auto; min-width: 0; max-width: none; overflow: visible; }
|
||||
/* 날짜 열 — 가로 스크롤해도 왼쪽에 고정(배경을 깔아 뒤로 지나가는 칸을 가림, 오른쪽 그림자로 경계) */
|
||||
/* 날짜 열 + 일 합계 열(2026-11-02) — 가로 스크롤해도 왼쪽에 고정(배경을 깔아 뒤로 지나가는 칸을 가림, 일 합계 오른쪽 그림자로 경계).
|
||||
일 합계 왼쪽 위치 = 날짜 열 너비(자동 너비라 performance.js stickyHead 가 --perf-label-w 로 넣는다) */
|
||||
.perf-main.perf-autofit .perf-th-label, .perf-main.perf-autofit .perf-td-label {
|
||||
position: sticky; left: 0; z-index: 2; box-shadow: inset -1px 0 0 #e3e3e3, 6px 0 6px -6px rgba(0, 0, 0, .22);
|
||||
position: sticky; left: 0; z-index: 2; box-shadow: inset -1px 0 0 #e3e3e3;
|
||||
}
|
||||
.perf-main.perf-autofit thead th.perf-th-label { z-index: 4; }
|
||||
.perf-main.perf-autofit .perf-th-total, .perf-main.perf-autofit .perf-td-total {
|
||||
position: sticky; left: var(--perf-label-w, 0); z-index: 2; box-shadow: inset -1px 0 0 #e3e3e3, 6px 0 6px -6px rgba(0, 0, 0, .22);
|
||||
}
|
||||
.perf-main.perf-autofit thead th.perf-th-label, .perf-main.perf-autofit thead th.perf-th-total { z-index: 4; }
|
||||
:where(.perf-main.perf-autofit) .perf-td-label { background: #fff; } /* 주간합계·기간 합계 줄 배경은 그 줄 규칙 그대로 */
|
||||
/* 그룹 열 = 진한 보라 머리 + 왼쪽 묶음 선, 하위 열 = 옅은 보라 머리(위 띠) + 옅은 칸, 마지막 하위 열(접히면 그룹 열)이 오른쪽 묶음 선 */
|
||||
.perf-main th.perf-th-group { background: #e6defa; color: #3d1d8a; font-weight: 800; box-shadow: inset 2px 0 0 #8a6fd8; }
|
||||
@@ -488,10 +495,26 @@ body.perf-dragging, body.perf-dragging * { cursor: grabbing !important; user-sel
|
||||
날짜 칸 가로 고정(sticky left)은 그대로. 연간 보기 "연간 합계"는 맨 아래 그대로(제목 행만 고정). */
|
||||
.perf-main-wrap { overflow-x: auto; overflow-y: hidden; }
|
||||
.perf-main-wrap .perf-main thead th { z-index: 3; }
|
||||
.perf-main-wrap .perf-main thead th.perf-th-label { z-index: 5; }
|
||||
.perf-main-wrap .perf-main thead th.perf-th-label, .perf-main-wrap .perf-main thead th.perf-th-total { z-index: 5; }
|
||||
.perf-main-wrap .perf-main tbody tr.perf-row-total:first-child > * { position: relative; z-index: 2; }
|
||||
.perf-main-wrap .perf-main tbody tr.perf-row-total:first-child > .perf-td-label { position: sticky; left: 0; z-index: 4; }
|
||||
.perf-main-wrap .perf-main tbody tr.perf-row-total:first-child > .perf-td-total { position: sticky; left: var(--perf-label-w, 0); z-index: 4; }
|
||||
/* 내려온 제목 행 아래 1px — 표 칸 사이 선(border-collapse)은 칸과 함께 안 움직여 그 틈으로 뒤 줄 글자가 비쳤다 → 칸이 직접 선을 그림 */
|
||||
.perf-main-wrap.is-stuck .perf-main thead th::after { content: ""; position: absolute; left: 0; right: 0; bottom: -1px; height: 1px; background: var(--perf-line); }
|
||||
/* 스크롤 막대 배경(트랙) 투명(2026-10-27) — 표 상자 가로 막대·실적 화면 세로 막대. 손잡이만 옅은 회색 */
|
||||
.perf-table-wrap, .erp-page:has(> .perf) { scrollbar-color: #c3c6cb transparent; }
|
||||
|
||||
/* ── 일자별 표 열 너비 수동 조절(2026-10-27, 실적 설정 "보기 설정" 쿠키 perf_colw=manual) ──
|
||||
performance.js initColWidths 가 자동 너비를 잰 뒤 th 너비·표 너비를 px 로 주고 is-colw-fixed(table-layout fixed) — 넘치는 글자는 … 로 자른다.
|
||||
머리글 오른쪽 경계 .perf-colw-grip 을 끌어 조절(마우스 올리면 선), 그룹 접기 애니메이션 동안 is-colw-anim 으로 열 너비도 함께 움직인다. */
|
||||
.perf-main.perf-colw-manual.is-colw-fixed { table-layout: fixed; }
|
||||
.perf-main.is-colw-fixed th, .perf-main.is-colw-fixed td { box-sizing: border-box; overflow: hidden; text-overflow: ellipsis; }
|
||||
.perf-main.is-colw-fixed thead th.perf-th-label, .perf-main.is-colw-fixed .perf-td-label { min-width: 0; max-width: none; }
|
||||
.perf-main.is-colw-fixed .perf-adl { overflow: hidden; text-overflow: ellipsis; }
|
||||
.perf-main.is-colw-anim, .perf-main.is-colw-anim thead th { transition: width .26s ease, padding .26s ease; }
|
||||
.perf-main-wrap.is-stuck .perf-main.is-colw-fixed thead th::after { bottom: 0; } /* 칸이 넘침을 자르므로 아래 선을 칸 안에 */
|
||||
.perf-colw-grip { position: absolute; top: 0; right: 0; bottom: 0; width: 8px; cursor: col-resize; z-index: 6; touch-action: none; }
|
||||
.perf-colw-grip::after { content: ""; position: absolute; top: 6px; bottom: 6px; right: 1px; width: 2px; border-radius: 1px; background: transparent; }
|
||||
.perf-main thead th:hover > .perf-colw-grip::after { background: #c3c6cb; }
|
||||
.perf-main thead th > .perf-colw-grip:hover::after, .perf-colw-grip.is-active::after { background: #1a56db; }
|
||||
body.perf-colw-dragging, body.perf-colw-dragging * { cursor: col-resize !important; user-select: none; }
|
||||
|
||||
+266
-11
@@ -24,7 +24,7 @@
|
||||
}
|
||||
function fmt(n) { return Number(n || 0).toLocaleString("ko-KR"); }
|
||||
function won(n) { return n ? fmt(n) : '<span class="perf-zero">–</span>'; }
|
||||
// 매출 단위(실적 설정 "보기 설정", 쿠키 perf_unit) — 서버 dashboard.amount_text 와 같은 표기(천원 정수, 백만원 소수 한 자리)
|
||||
// 매출 단위(실적 설정 "공통 보기 설정", 모든 사용자 같음) — 서버 dashboard.amount_text 와 같은 표기(천원 정수, 백만원 소수 한 자리)
|
||||
function unitWon(n, unit) {
|
||||
if (!n) return won(0);
|
||||
if (unit === "thousand") return Math.round(n / 1000).toLocaleString("ko-KR");
|
||||
@@ -252,6 +252,96 @@
|
||||
// ════════════════════════════════════════════════════
|
||||
// 대시보드
|
||||
// ════════════════════════════════════════════════════
|
||||
// 일자별 표 열 너비 수동 조절(2026-10-27) — 실적 설정 "보기 설정"에서 수동(쿠키 perf_colw=manual)이면 서버가 표에 perf-colw-manual.
|
||||
// 처음엔 자동 너비(글자 길이)를 재 두고 table-layout:fixed 로 고정, 머리글 오른쪽 경계(.perf-colw-grip)를 끌면 그 열만 그 너비로.
|
||||
// 바꾼 너비는 이 브라우저 localStorage(perf_colw_sales / perf_colw_ads, 열 = th data-col)에 계속 유지, 경계를 두 번 누르면 그 열만 자동 너비로.
|
||||
// 그룹 접기·펴기 애니메이션은 apply(접는 열)/animate/settle 로 열 너비를 0 ↔ 원래 너비로 함께 움직인다.
|
||||
const COLW_MIN = 36;
|
||||
function initColWidths(root) {
|
||||
const table = root.querySelector("table.perf-colw-manual");
|
||||
const row = table && table.tHead && table.tHead.rows[0];
|
||||
if (!row) return null;
|
||||
const KEY = "perf_colw_" + (table.dataset.colwKey || "sales");
|
||||
const heads = Array.prototype.slice.call(row.cells);
|
||||
const auto = {};
|
||||
let saved = {};
|
||||
try { saved = JSON.parse(localStorage.getItem(KEY) || "{}") || {}; } catch (_) { saved = {}; }
|
||||
function store() {
|
||||
try { localStorage.setItem(KEY, JSON.stringify(saved)); } catch (_) { /* 기억만 못 함 */ }
|
||||
}
|
||||
// 날짜 열(label)은 조절 안 함(2026-10-27) — 늘 자동 너비(글자 길이), 손잡이 없음
|
||||
function fixedCol(th) { return th.dataset.col === "label"; }
|
||||
function widthOf(th) { const c = th.dataset.col; return (!fixedCol(th) && saved[c]) || auto[c] || 80; }
|
||||
function apply(zero) { // zero = 너비 0 으로 둘 열(접는 중·펴기 직전)
|
||||
let sum = 0;
|
||||
heads.forEach(function (th) {
|
||||
const w = zero && zero.indexOf(th) >= 0 ? 0 : widthOf(th);
|
||||
th.style.width = w + "px";
|
||||
if (!th.classList.contains("is-gfolded")) sum += w;
|
||||
});
|
||||
table.style.width = sum + "px";
|
||||
table.classList.add("is-colw-fixed");
|
||||
}
|
||||
function measure() { // 자동 너비 다시 재기(접혀 안 보이는 열은 앞서 잰 값 그대로)
|
||||
table.classList.remove("is-colw-fixed", "is-colw-anim");
|
||||
heads.forEach(function (th) { th.style.width = ""; });
|
||||
table.style.width = "";
|
||||
heads.forEach(function (th) {
|
||||
const w = th.getBoundingClientRect().width;
|
||||
if (w > 0) auto[th.dataset.col] = Math.ceil(w);
|
||||
});
|
||||
apply();
|
||||
}
|
||||
heads.forEach(function (th) {
|
||||
if (fixedCol(th)) return;
|
||||
const g = document.createElement("span");
|
||||
g.className = "perf-colw-grip";
|
||||
g.setAttribute("aria-hidden", "true");
|
||||
th.appendChild(g);
|
||||
});
|
||||
measure();
|
||||
if (document.fonts && document.fonts.status !== "loaded") document.fonts.ready.then(measure); // 글꼴 늦게 오면 자동 너비 다시
|
||||
|
||||
let drag = null;
|
||||
row.addEventListener("pointerdown", function (e) {
|
||||
const g = e.target.closest(".perf-colw-grip");
|
||||
if (!g || e.button !== 0) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
drag = { th: g.parentElement, grip: g, x: e.clientX, w: widthOf(g.parentElement) };
|
||||
try { g.setPointerCapture(e.pointerId); } catch (_) { /* 캡처 못 해도 끌기는 됨 */ }
|
||||
g.classList.add("is-active");
|
||||
document.body.classList.add("perf-colw-dragging");
|
||||
});
|
||||
row.addEventListener("pointermove", function (e) {
|
||||
if (!drag) return;
|
||||
saved[drag.th.dataset.col] = Math.max(COLW_MIN, Math.round(drag.w + e.clientX - drag.x));
|
||||
apply();
|
||||
});
|
||||
function end() {
|
||||
if (!drag) return;
|
||||
drag.grip.classList.remove("is-active");
|
||||
document.body.classList.remove("perf-colw-dragging");
|
||||
drag = null;
|
||||
store();
|
||||
}
|
||||
row.addEventListener("pointerup", end);
|
||||
row.addEventListener("pointercancel", end);
|
||||
row.addEventListener("click", function (e) { if (e.target.closest(".perf-colw-grip")) e.stopPropagation(); });
|
||||
row.addEventListener("dblclick", function (e) {
|
||||
const g = e.target.closest(".perf-colw-grip");
|
||||
if (!g) return;
|
||||
delete saved[g.parentElement.dataset.col];
|
||||
store();
|
||||
apply();
|
||||
});
|
||||
return {
|
||||
apply: apply,
|
||||
animate: function (zero) { table.classList.add("is-colw-anim"); apply(zero); },
|
||||
settle: function () { table.classList.remove("is-colw-anim"); apply(); },
|
||||
};
|
||||
}
|
||||
|
||||
function initDashboard(root) {
|
||||
const data = JSON.parse((document.getElementById("perf-data") || {}).textContent || "{}");
|
||||
const METRIC_NAMES = { gross: "총매출", commission: "수수료", net: "수수료 차감 매출" };
|
||||
@@ -285,8 +375,10 @@
|
||||
const groupRun = {}; // 그룹 → 애니메이션 번호(빠르게 두 번 누르면 앞 애니메이션의 마무리를 버린다)
|
||||
let collapsed = [];
|
||||
try { collapsed = JSON.parse(localStorage.getItem(GROUP_KEY) || "[]") || []; } catch (_) { collapsed = []; }
|
||||
const colw = initColWidths(root); // 열 너비 수동 조절(보기 설정) — 그룹을 접기 전에 자동 너비를 잰다
|
||||
function setGroup(code, fold, animate) {
|
||||
const cells = Array.prototype.slice.call(root.querySelectorAll('[data-group-child="' + code + '"]'));
|
||||
const heads = cells.filter(function (n) { return n.tagName === "TH"; });
|
||||
root.querySelectorAll('[data-group-toggle="' + code + '"]').forEach(function (b) {
|
||||
b.setAttribute("aria-expanded", fold ? "false" : "true");
|
||||
b.setAttribute("aria-label", (b.getAttribute("aria-label") || "").replace(/ (접기|펴기)$/, "") + (fold ? " 펴기" : " 접기"));
|
||||
@@ -298,6 +390,7 @@
|
||||
if (groupRun[code] !== run) return;
|
||||
cells.forEach(function (n) { n.classList.remove("is-ganim", "is-gshut"); n.classList.toggle("is-gfolded", fold); });
|
||||
boxes.forEach(function (b) { b.style.maxWidth = ""; });
|
||||
if (colw) colw.settle();
|
||||
};
|
||||
if (!animate || REDUCE_MOTION || !boxes.length) { settle(); return; }
|
||||
if (fold) {
|
||||
@@ -306,12 +399,15 @@
|
||||
void root.offsetWidth; // 지금 너비에서 출발
|
||||
cells.forEach(function (n) { n.classList.add("is-gshut"); });
|
||||
boxes.forEach(function (b) { b.style.maxWidth = "0px"; });
|
||||
if (colw) colw.animate(heads); // 수동 너비 표 — 열 너비도 0 으로
|
||||
} else {
|
||||
cells.forEach(function (n) { n.classList.remove("is-gfolded", "is-ganim"); n.classList.add("is-gshut"); });
|
||||
boxes.forEach(function (b) { b.style.maxWidth = "0px"; });
|
||||
if (colw) colw.apply(heads);
|
||||
void root.offsetWidth; // 0 에서 출발
|
||||
cells.forEach(function (n) { n.classList.add("is-ganim"); n.classList.remove("is-gshut"); });
|
||||
boxes.forEach(function (b) { b.style.maxWidth = b.scrollWidth + "px"; });
|
||||
if (colw) colw.animate(); // 수동 너비 표 — 열 너비도 원래대로
|
||||
}
|
||||
setTimeout(settle, GROUP_MS + 30);
|
||||
}
|
||||
@@ -721,6 +817,17 @@
|
||||
if (s && shown[cls] != null) s.innerHTML = unitWon(shown[cls], data.unit);
|
||||
});
|
||||
td.classList.toggle("is-stale", res.net == null);
|
||||
// 카페24(실적) 열 — 공동구매 칸을 저장하면 같은 줄 칸도 바로(카페24 − 새 값). 합계 줄은 새로고침 때.
|
||||
const diff = td.parentElement.querySelector('td[data-diff-minus="' + td.dataset.manualCode + '"]');
|
||||
if (diff) {
|
||||
const base = diff.dataset.base.split(",").map(Number);
|
||||
const mine = [res.amount, res.commission, res.net];
|
||||
["v-gross", "v-commission", "v-net"].forEach(function (cls, i) {
|
||||
const s = diff.querySelector("." + cls);
|
||||
if (s && mine[i] != null) s.innerHTML = unitWon(base[i] - mine[i], data.unit);
|
||||
});
|
||||
diff.classList.toggle("is-stale", res.net == null);
|
||||
}
|
||||
manualDirty = true;
|
||||
return true;
|
||||
});
|
||||
@@ -993,6 +1100,49 @@
|
||||
// 매출 실적 화면은 늘 수수료 차감 매출로 연다(2026-10-19) — 서버 기본 data-metric="net", 예전에 고른 보기(localStorage)는 쓰지 않음
|
||||
setMetric(root.dataset.metric || "net");
|
||||
initNextUpdate(data.auto_sync);
|
||||
initUpdateWatch(data.update_watch);
|
||||
}
|
||||
|
||||
// 자동 업데이트(다른 사람이 누른 업데이트 포함)가 끝나면 화면 새로 고침(2026-10-26) — 20초마다 GET /api/update-status 로
|
||||
// 마지막으로 끝난 업데이트를 보고, 화면을 그린 때(update_watch.seen)와 다르고 지금 도는 업데이트가 없으면 reload.
|
||||
// 칸 입력 중·창(메모·진행 창 등)·확인 창·메뉴가 열려 있으면 닫힐 때까지 기다린다. 탭이 안 보이면 묻지 않고, 다시 보이면 바로 본다.
|
||||
// 보는 사람이 직접 누른 업데이트는 서버가 빼고 준다(진행 창이 알아서 새로 그림).
|
||||
const WATCH_MS = 20000;
|
||||
function initUpdateWatch(w) {
|
||||
if (!w || !w.kind) return;
|
||||
const seen = w.seen || "";
|
||||
let pending = false, asking = false;
|
||||
function busyUi() {
|
||||
const a = document.activeElement;
|
||||
if (a && a !== document.body && (/^(INPUT|TEXTAREA|SELECT)$/.test(a.tagName) || a.isContentEditable)) return true;
|
||||
return !!document.querySelector(".perf-modal, .perf-ctx, .erp-dialog-backdrop");
|
||||
}
|
||||
function note(text) {
|
||||
const lu = document.getElementById("perf-last-update");
|
||||
if (!lu) return;
|
||||
let n = lu.querySelector(".perf-refresh-note");
|
||||
if (!n) { n = el("span", { class: "perf-refresh-note" }); lu.appendChild(n); }
|
||||
n.textContent = text;
|
||||
}
|
||||
function reloadWhenFree() {
|
||||
if (busyUi()) {
|
||||
note(" · 새 데이터 있음 — 입력·창을 닫으면 새로 고칩니다");
|
||||
setTimeout(reloadWhenFree, 1500);
|
||||
return;
|
||||
}
|
||||
note(" · 새 데이터로 고치는 중…");
|
||||
location.reload();
|
||||
}
|
||||
async function check() {
|
||||
if (pending || asking || document.hidden) return;
|
||||
asking = true;
|
||||
try {
|
||||
const st = await api("GET", "/performance/api/update-status?kind=" + encodeURIComponent(w.kind));
|
||||
if (st.done && st.done !== seen && !st.running) { pending = true; reloadWhenFree(); }
|
||||
} catch (_) { /* 잠깐 끊김·로그아웃 — 다음 차례에 */ } finally { asking = false; }
|
||||
}
|
||||
setInterval(check, WATCH_MS);
|
||||
document.addEventListener("visibilitychange", function () { if (!document.hidden) check(); });
|
||||
}
|
||||
|
||||
// 다음 자동 업데이트까지 남은 시간 — 초 단위 실시간(2026-10-19). 서버가 준 다음 회차·지금 시각(PC 시계 차이 보정)으로 세고,
|
||||
@@ -1071,8 +1221,43 @@
|
||||
return "";
|
||||
}
|
||||
function dirty() { msg.textContent = "바뀐 내용이 있습니다 — [저장]을 누르세요."; msg.classList.remove("is-ok"); }
|
||||
// 아날로그 시계(12시간 문자판) — 시작 바늘 ~ 끝 바늘 사이(시계 방향)를 빨갛게, 12시간을 넘는 부분은 진한 빨강으로 한 번 더
|
||||
function drawClock(row) {
|
||||
const svg = row.querySelector(".perf-auto-clock");
|
||||
if (!svg) return;
|
||||
const s = read(row);
|
||||
function mins(hhmm) { const p = hhmm.split(":"); return Number(p[0]) * 60 + Number(p[1]); }
|
||||
const a = mins(s.start), b = mins(s.end), R = 44;
|
||||
function pt(m, r) { const t = (m % 720) / 720 * 2 * Math.PI; return [(r * Math.sin(t)).toFixed(2), (-r * Math.cos(t)).toFixed(2)]; }
|
||||
function sector(from, len, cls) {
|
||||
if (len <= 0) return "";
|
||||
if (len >= 720) return '<circle class="' + cls + '" r="' + R + '"/>';
|
||||
const p0 = pt(from, R), p1 = pt(from + len, R);
|
||||
return '<path class="' + cls + '" d="M0 0L' + p0[0] + " " + p0[1] + "A" + R + " " + R + " 0 " + (len > 360 ? 1 : 0) + " 1 " +
|
||||
p1[0] + " " + p1[1] + 'Z"/>';
|
||||
}
|
||||
let g = '<circle class="c-face" r="47"/>' + sector(a, Math.min(b - a, 720), "c-span") + sector(a + 720, b - a - 720, "c-span2");
|
||||
for (let h = 0; h < 12; h++) {
|
||||
const major = h % 3 === 0, o = pt(h * 60, 46), i = pt(h * 60, major ? 36 : 40);
|
||||
g += '<line class="c-tick' + (major ? " is-major" : "") + '" x1="' + i[0] + '" y1="' + i[1] + '" x2="' + o[0] + '" y2="' + o[1] + '"/>';
|
||||
}
|
||||
const hs = pt(a, 30), he = pt(b, 38);
|
||||
g += '<line class="c-hand" x1="0" y1="0" x2="' + hs[0] + '" y2="' + hs[1] + '"/>' +
|
||||
'<line class="c-hand is-end" x1="0" y1="0" x2="' + he[0] + '" y2="' + he[1] + '"/><circle class="c-pin" r="3.5"/>';
|
||||
const span = b - a, hours = Math.floor(span / 60), rest = span % 60;
|
||||
const title = s.start + " ~ " + s.end + " (" + (hours ? hours + "시간" : "") + (rest ? (hours ? " " : "") + rest + "분" : "") + (span ? "" : "한 번") + ")";
|
||||
svg.innerHTML = "<title>" + title + "</title>" + g;
|
||||
svg.setAttribute("aria-label", "자동 업데이트 시간대 " + title);
|
||||
}
|
||||
card.querySelectorAll(".perf-auto-row").forEach(function (row) {
|
||||
row.addEventListener("change", function () { row.classList.toggle("is-off", !read(row).enabled); dirty(); });
|
||||
const tf = row.querySelector('[data-t="end-m"]').closest(".perf-auto-field");
|
||||
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
svg.setAttribute("class", "perf-auto-clock");
|
||||
svg.setAttribute("viewBox", "-50 -50 100 100");
|
||||
svg.setAttribute("role", "img");
|
||||
tf.appendChild(svg);
|
||||
drawClock(row);
|
||||
row.addEventListener("change", function () { row.classList.toggle("is-off", !read(row).enabled); drawClock(row); dirty(); });
|
||||
row.querySelectorAll("[data-days]").forEach(function (b) {
|
||||
b.addEventListener("click", function () {
|
||||
row.querySelectorAll("[data-day]").forEach(function (c) {
|
||||
@@ -1107,13 +1292,18 @@
|
||||
}
|
||||
|
||||
function initSettings(root) {
|
||||
// 보기 설정 — 매출 단위(원·천원·백만원)를 이 브라우저 쿠키에(1년). 매출 실적 화면을 다시 열면 적용
|
||||
// 공통 보기 설정(관리자) — 매출 단위(원·천원·백만원)를 서버에, 모든 사용자의 매출 실적 화면에 적용
|
||||
const UNIT_EX = { won: "2,475,300", thousand: "2,475", million: "2.5" };
|
||||
root.querySelectorAll("#perf-view-opts [data-unit]").forEach(function (b) {
|
||||
b.addEventListener("click", function () {
|
||||
root.querySelectorAll("#perf-shared-view [data-unit]").forEach(function (b) {
|
||||
b.addEventListener("click", async function () {
|
||||
const u = b.dataset.unit;
|
||||
document.cookie = "perf_unit=" + u + "; path=/performance; max-age=31536000; SameSite=Lax";
|
||||
root.querySelectorAll("#perf-view-opts [data-unit]").forEach(function (x) {
|
||||
try {
|
||||
await api("PUT", "/performance/api/display-unit", { unit: u });
|
||||
} catch (err) {
|
||||
alertMsg("저장 실패: " + err.message);
|
||||
return;
|
||||
}
|
||||
root.querySelectorAll("#perf-shared-view [data-unit]").forEach(function (x) {
|
||||
x.classList.toggle("is-active", x === b);
|
||||
x.setAttribute("aria-checked", x === b ? "true" : "false");
|
||||
});
|
||||
@@ -1121,6 +1311,45 @@
|
||||
if (ex) ex.textContent = "예: 2,475,300원 → " + UNIT_EX[u];
|
||||
});
|
||||
});
|
||||
// 보기 설정 — 표 열 너비 자동/수동(2026-10-27, 쿠키 perf_colw 1년). 수동으로 바꾼 너비는 표 화면 localStorage 에 있고 [초기화]가 지운다
|
||||
const COLW_HELP = {
|
||||
auto: "열 너비가 글자 길이에 맞춰 자동으로 정해집니다.",
|
||||
manual: "매출 실적·광고비 표 머리글의 오른쪽 경계를 끌어 너비를 바꿉니다(두 번 누르면 그 열만 자동 너비). 바꾼 너비는 계속 유지됩니다.",
|
||||
};
|
||||
const colwReset = document.getElementById("perf-colw-reset");
|
||||
root.querySelectorAll("#perf-view-opts [data-colw]").forEach(function (b) {
|
||||
b.addEventListener("click", function () {
|
||||
const v = b.dataset.colw;
|
||||
document.cookie = "perf_colw=" + v + "; path=/performance; max-age=31536000; SameSite=Lax";
|
||||
root.querySelectorAll("#perf-view-opts [data-colw]").forEach(function (x) {
|
||||
x.classList.toggle("is-active", x === b);
|
||||
x.setAttribute("aria-checked", x === b ? "true" : "false");
|
||||
});
|
||||
const help = document.getElementById("perf-colw-help");
|
||||
if (help) help.textContent = COLW_HELP[v];
|
||||
if (colwReset) colwReset.hidden = v !== "manual";
|
||||
});
|
||||
});
|
||||
if (colwReset) colwReset.addEventListener("click", async function () {
|
||||
if (!(await confirmMsg("매출 실적·광고비 표에서 조절한 열 너비를 모두 지우고 자동 너비로 되돌릴까요?"))) return;
|
||||
try { localStorage.removeItem("perf_colw_sales"); localStorage.removeItem("perf_colw_ads"); } catch (_) { /* 저장소 없음 */ }
|
||||
colwReset.textContent = "초기화했습니다";
|
||||
setTimeout(function () { colwReset.textContent = "조절한 너비 초기화"; }, 1800);
|
||||
});
|
||||
// 공통 보기 설정 — 매출 실적 표 열 숨기기(2026-11-02, 관리자), 고르면 바로 저장(차례대로, 실패하면 그 칸만 되돌림)
|
||||
const hideBoxes = Array.from(root.querySelectorAll("#perf-shared-view [data-hide]"));
|
||||
let hideSave = Promise.resolve();
|
||||
hideBoxes.forEach(function (c) {
|
||||
c.addEventListener("change", function () {
|
||||
const codes = hideBoxes.filter(function (x) { return x.checked; }).map(function (x) { return x.dataset.hide; });
|
||||
hideSave = hideSave.then(function () {
|
||||
return api("PUT", "/performance/api/hidden-marketplaces", { codes: codes });
|
||||
}).catch(function (err) {
|
||||
c.checked = !c.checked;
|
||||
alertMsg("저장 실패: " + err.message);
|
||||
});
|
||||
});
|
||||
});
|
||||
initAutoSyncSettings(root);
|
||||
|
||||
// 사용 / 매출 집계 토글 — 바로 저장, 실패하면 되돌림
|
||||
@@ -1534,16 +1763,42 @@
|
||||
cells.forEach(function (c) { c.style.transform = v; });
|
||||
wrap.classList.toggle("is-stuck", off > 0);
|
||||
}
|
||||
const labelHead = head.querySelector(".perf-th-label");
|
||||
function layout() { // 일 합계 열 가로 고정 위치 = 날짜 열 너비(자동 너비라 CSS 만으로는 모른다)
|
||||
if (labelHead) table.style.setProperty("--perf-label-w", labelHead.getBoundingClientRect().width + "px");
|
||||
update();
|
||||
}
|
||||
window.addEventListener("scroll", update, true);
|
||||
window.addEventListener("resize", update);
|
||||
if (window.ResizeObserver) new ResizeObserver(update).observe(table);
|
||||
update();
|
||||
window.addEventListener("resize", layout);
|
||||
if (window.ResizeObserver) new ResizeObserver(layout).observe(table);
|
||||
layout();
|
||||
});
|
||||
}
|
||||
|
||||
// 새로고침해도 스크롤 위치 유지(2026-11-02) — 수기 입력·자동 새로 고침·업로드 뒤 새로고침 모두. 세로는 안쪽 스크롤 상자(.erp-page)라
|
||||
// 브라우저가 복원하지 않고, 가로는 표 상자. 떠날 때 저장 → 새로고침으로 다시 열릴 때만 복원(메뉴·기간 이동으로 들어오면 맨 위부터).
|
||||
function keepScroll(root) {
|
||||
const wrap = root.querySelector(".perf-main-wrap");
|
||||
if (!wrap) return;
|
||||
const KEY = "perf_scroll";
|
||||
const scroller = function () { return scrollParent(wrap) || document.scrollingElement; };
|
||||
window.addEventListener("pagehide", function () {
|
||||
try { sessionStorage.setItem(KEY, JSON.stringify({ url: location.href, top: scroller().scrollTop, left: wrap.scrollLeft })); } catch (_) { /* 기억만 못 함 */ }
|
||||
});
|
||||
let saved = null;
|
||||
try {
|
||||
saved = JSON.parse(sessionStorage.getItem(KEY) || "null");
|
||||
sessionStorage.removeItem(KEY);
|
||||
} catch (_) { saved = null; }
|
||||
const nav = window.performance && performance.getEntriesByType ? performance.getEntriesByType("navigation")[0] : null;
|
||||
if (!saved || saved.url !== location.href || !nav || nav.type !== "reload") return;
|
||||
scroller().scrollTop = saved.top;
|
||||
wrap.scrollLeft = saved.left;
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", function () {
|
||||
const dash = document.getElementById("perf-dash");
|
||||
if (dash) { initDashboard(dash); stickyHead(dash); }
|
||||
if (dash) { initDashboard(dash); stickyHead(dash); keepScroll(dash); }
|
||||
const set = document.getElementById("perf-settings");
|
||||
if (set) initSettings(set);
|
||||
});
|
||||
|
||||
+64
-9
@@ -5458,21 +5458,22 @@
|
||||
if (t.project_id === projectId) {
|
||||
const res = await api("PUT", "/project/api/tasks/" + taskId, { stage_id: stageId });
|
||||
mergeTask(res.task);
|
||||
// 다른 섹션에도 놓은 자리 그대로 — 기본 정렬·필터 없음일 때만 순서 저장(아니면 섹션 맨 끝)
|
||||
if (manualOrderAllowed()) {
|
||||
const orderedIds = orderedFor();
|
||||
try {
|
||||
await api("PUT", "/project/api/projects/" + projectId + "/stages/" + stageId + "/tasks/order",
|
||||
{ ordered_ids: orderedIds });
|
||||
applyStageOrder(stageId, orderedIds);
|
||||
} catch (err) { showToast("섹션은 옮겼지만 순서 저장 실패: " + err.message, "error"); }
|
||||
}
|
||||
} else {
|
||||
await api("POST", "/project/api/tasks/" + taskId + "/links",
|
||||
{ project_id: projectId, stage_id: stageId });
|
||||
t.stage_id = stageId;
|
||||
t.is_linked = true;
|
||||
}
|
||||
// 다른 섹션에도 놓은 자리 그대로 — 기본 정렬일 때만 순서 저장(아니면 섹션 맨 끝).
|
||||
// 연결 업무도(2026-10-30, 연결별 순서 = 마이그레이션 032 task_project_links.sort_order)
|
||||
if (manualOrderAllowed()) {
|
||||
const orderedIds = orderedFor();
|
||||
try {
|
||||
await api("PUT", "/project/api/projects/" + projectId + "/stages/" + stageId + "/tasks/order",
|
||||
{ ordered_ids: orderedIds });
|
||||
applyStageOrder(stageId, orderedIds);
|
||||
} catch (err) { showToast("섹션은 옮겼지만 순서 저장 실패: " + err.message, "error"); }
|
||||
}
|
||||
} catch (err) { showToast("이동 실패: " + err.message, "error"); }
|
||||
endCardDrag(true);
|
||||
renderBoard();
|
||||
@@ -8876,6 +8877,7 @@
|
||||
openStylePop(btn, cmd);
|
||||
return;
|
||||
}
|
||||
if (cmd === "bold") { boldWithLinks(); updateFmtState(); return; }
|
||||
// 체크리스트 — 글머리 목록처럼 켜고 끈다(줄마다 체크박스).
|
||||
if (cmd === "insertCheckbox") {
|
||||
toggleChecklist();
|
||||
@@ -8942,12 +8944,59 @@
|
||||
const sel = window.getSelection();
|
||||
if (range) { sel.removeAllRanges(); sel.addRange(range); }
|
||||
if (!sel.rangeCount || sel.isCollapsed) { showToast("바꿀 글자를 먼저 선택하세요.", "info"); return; }
|
||||
const links = kind === "size" ? linksIn(sel.getRangeAt(0)) : [];
|
||||
try { document.execCommand("styleWithCSS", false, false); } catch (_) {}
|
||||
try {
|
||||
if (kind === "color") document.execCommand("foreColor", false, value || RESET_COLOR);
|
||||
else document.execCommand("fontSize", false, "7");
|
||||
} catch (_) {}
|
||||
fontsToSpans(kind, value);
|
||||
links.forEach(function (a) { setLinkStyle(a, "font-size", value); });
|
||||
box.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
// ── 링크 서식(2026-10-30) — 링크는 한 글자처럼 잠겨(contenteditable=false) execCommand 굵게·크기가 안에 안 들어간다.
|
||||
// 고른 범위에 걸친 링크는 링크 안쪽 <span style> 하나로 크기·굵기만 바꾼다(링크는 그대로 한 덩어리).
|
||||
// 굵기: 링크 기본(CSS)이 굵게라 "보통"은 font-weight: 400, 굵게는 그 값을 뺀다(서버 desc_inline_style 이 400 만 받는다).
|
||||
function linksIn(range) {
|
||||
return Array.prototype.filter.call(box.querySelectorAll("a"), function (a) { return range.intersectsNode(a); });
|
||||
}
|
||||
function setLinkStyle(a, prop, value) {
|
||||
let sp = a.childNodes.length === 1 && a.firstChild.nodeName === "SPAN" && !a.firstChild.className ? a.firstChild : null;
|
||||
if (!sp) {
|
||||
sp = document.createElement("span");
|
||||
while (a.firstChild) sp.appendChild(a.firstChild);
|
||||
a.appendChild(sp);
|
||||
}
|
||||
stripInside(sp, prop);
|
||||
if (value) sp.style.setProperty(prop, value); else sp.style.removeProperty(prop);
|
||||
if (!sp.getAttribute("style")) sp.replaceWith.apply(sp, Array.prototype.slice.call(sp.childNodes));
|
||||
}
|
||||
function linkIsBold(a) {
|
||||
const sp = a.querySelector("span[style]") || a;
|
||||
return parseInt(getComputedStyle(sp).fontWeight, 10) >= 600;
|
||||
}
|
||||
// 굵게(도구 버튼·Ctrl+B) — 글자는 execCommand, 고른 링크는 같은 결과로(글자가 없으면 링크끼리 켜고 끄기)
|
||||
function boldWithLinks() {
|
||||
const sel = window.getSelection();
|
||||
const range = sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null;
|
||||
const links = range && !range.collapsed ? linksIn(range) : [];
|
||||
const allBold = links.every(linkIsBold);
|
||||
// 고른 범위의 링크 밖 글자(execCommand 뒤에도 같은 글자 노드가 <b> 로 옮겨질 뿐이라 굵기를 다시 잴 수 있다)
|
||||
const texts = [];
|
||||
if (links.length) {
|
||||
const walker = document.createTreeWalker(box, NodeFilter.SHOW_TEXT);
|
||||
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
||||
if (n.nodeValue.trim() && range.intersectsNode(n) && !n.parentElement.closest("a")) texts.push(n);
|
||||
}
|
||||
}
|
||||
try { document.execCommand("bold"); } catch (_) {}
|
||||
if (!links.length) return;
|
||||
// 글자가 있으면 execCommand 가 실제로 만든 굵기를 따른다 — 잠긴 링크가 끼면 queryCommandState·선택 범위가 틀어진다
|
||||
const now = texts.filter(function (n) { return n.isConnected && box.contains(n); });
|
||||
const bold = now.length
|
||||
? now.every(function (n) { return parseInt(getComputedStyle(n.parentElement).fontWeight, 10) >= 600; })
|
||||
: !allBold;
|
||||
links.forEach(function (a) { setLinkStyle(a, "font-weight", bold ? "" : "400"); });
|
||||
box.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
function openStylePop(btn, cmd) {
|
||||
@@ -9003,6 +9052,12 @@
|
||||
try { document.execCommand("strikeThrough"); } catch (_) {}
|
||||
updateFmtState();
|
||||
}
|
||||
// Ctrl+B — 도구 버튼과 같이 고른 링크도 굵게/보통(브라우저 기본 굵게는 잠긴 링크에 안 들어간다)
|
||||
if ((e.ctrlKey || e.metaKey) && !e.shiftKey && !e.altKey && (e.key === "b" || e.key === "B")) {
|
||||
e.preventDefault();
|
||||
boldWithLinks();
|
||||
updateFmtState();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+60
-5
@@ -160,16 +160,70 @@
|
||||
.vac-list-reason { font-size: 12px; margin-top: 4px; }
|
||||
.vac-empty { padding: 12px 0; }
|
||||
|
||||
/* ── 신청 폼 ── */
|
||||
.vac-form-card { padding: 16px; max-width: 760px; }
|
||||
/* ── 신청 폼(2026-11-02) — 위 휴가 종류 · 왼쪽 달력 · 오른쪽 날짜·사유 · 아래 결재 라인 ── */
|
||||
.vac [hidden] { display: none !important; }
|
||||
.vac-form-card { padding: 20px; max-width: 1000px; flex-shrink: 0; display: flex; flex-direction: column; gap: 20px; }
|
||||
.vac-types { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 0; padding: 0; border: 0; }
|
||||
.vac-types legend { float: left; margin-right: 12px; padding: 0; font-size: 14px; font-weight: 600; line-height: 34px; }
|
||||
.vac-type { display: inline-flex; cursor: pointer; }
|
||||
.vac-type input { position: absolute; opacity: 0; width: 0; height: 0; }
|
||||
.vac-type span { display: inline-flex; align-items: center; gap: 6px; height: 34px; padding: 0 14px; box-sizing: border-box;
|
||||
border: 1px solid var(--vac-ash); border-radius: 9999px; font-size: 14px; color: var(--vac-black); background: #fff; }
|
||||
.vac-type span::before { content: ""; width: 12px; height: 12px; box-sizing: border-box; border: 1.5px solid #a3a3a3; border-radius: 50%; }
|
||||
.vac-type:hover span { background: var(--vac-ghost); }
|
||||
.vac-type input:checked + span { background: #000; border-color: #000; color: #fff; font-weight: 700; }
|
||||
.vac-type input:checked + span::before { border: 4px solid #fff; background: #000; }
|
||||
.vac-type input:focus-visible + span { outline: 2px solid var(--vac-black); outline-offset: 2px; }
|
||||
|
||||
.vac-form-main { display: grid; grid-template-columns: 380px minmax(0, 1fr); gap: 24px; align-items: start; }
|
||||
@media (max-width: 760px) { .vac-form-main { grid-template-columns: minmax(0, 1fr); } }
|
||||
.vac-range-cal { border: 1px solid var(--vac-ash); border-radius: 12px; padding: 12px; font-size: 13px; }
|
||||
/* 붙박이 달력은 팝업보다 칸이 넓다 — 공휴일 이름을 공용 9px 보다 크게 */
|
||||
.vac-range-cal .pj-dp-hol { font-size: 10.5px; padding: 0; letter-spacing: -.6px; }
|
||||
.vac-form-side { display: flex; flex-direction: column; min-width: 0; }
|
||||
.vac-form-grid {
|
||||
display: grid; grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 12px; margin-bottom: 12px;
|
||||
}
|
||||
.vac-full { grid-column: 1 / -1; }
|
||||
.vac-days-preview { margin: 12px 0; font-size: 14px; }
|
||||
.vac-form-side .erp-input, .vac-form-side .erp-select { min-width: 0; width: 100%; box-sizing: border-box; }
|
||||
.vac-form-side input[readonly] { background: var(--vac-ghost); cursor: default; }
|
||||
.vac-reason textarea { resize: vertical; }
|
||||
.vac-days-preview { margin: 0 0 12px; font-size: 14px; }
|
||||
.vac-days-preview strong { font-size: 16px; font-weight: 600; }
|
||||
.vac-form-actions { display: flex; gap: 8px; margin-top: 8px; }
|
||||
.vac-form-err { margin: 0; color: var(--vac-red); font-size: 13px; font-weight: 600; }
|
||||
.vac-form-actions { display: flex; gap: 8px; }
|
||||
|
||||
/* 결재 라인 — 신청 화면·상세 공용 */
|
||||
.vac-line { border-top: 1px solid var(--vac-ash); padding-top: 16px; display: flex; flex-direction: column; gap: 12px; }
|
||||
.vac-line h3 { margin: 0; font-size: 15px; font-weight: 600; }
|
||||
.vac-line-row { display: flex; align-items: center; gap: 12px; }
|
||||
.vac-line-label { flex: none; width: 56px; font-size: 13px; font-weight: 600; }
|
||||
.vac-line-body { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; min-width: 0; font-size: 14px; }
|
||||
.vac-line-sub { margin: 0; font-size: 13px; font-weight: 600; }
|
||||
.vac-line-progress { margin: 0; }
|
||||
.vac-person { display: inline-flex; align-items: center; gap: 6px; min-width: 0; }
|
||||
.vac-pick { list-style: none; margin: 0; padding: 8px; display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 4px;
|
||||
max-height: 260px; overflow-y: auto; border: 1px solid var(--vac-ash); border-radius: 10px; }
|
||||
.vac-consult-box { display: flex; flex-direction: column; gap: 8px; }
|
||||
.vac-consult-row { display: grid; grid-template-columns: 140px minmax(0, 1fr) 28px; gap: 8px; align-items: center; }
|
||||
.vac-consult-row .erp-input { min-width: 0; width: 100%; box-sizing: border-box; resize: vertical; }
|
||||
.vac-consult-x { width: 28px; height: 28px; border: 0; border-radius: 6px; background: none; color: var(--vac-muted); cursor: pointer; }
|
||||
.vac-consult-x:hover { background: var(--vac-ghost); color: var(--vac-red); }
|
||||
.vac-line-consult { padding: 8px 12px; border-radius: 10px; background: var(--vac-ghost); font-size: 14px; }
|
||||
.vac-line-consult p { margin: 4px 0 0; white-space: pre-wrap; }
|
||||
.vac-line-comment { color: var(--vac-red); }
|
||||
.vac-consult-brief { font-size: 12.5px; white-space: pre-wrap; }
|
||||
|
||||
/* 협의·결재 진행 상황 */
|
||||
.vac-steps { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 4px 6px; }
|
||||
.vac-step { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px 2px 4px; border-radius: 9999px; background: var(--vac-ghost);
|
||||
font-size: 12.5px; white-space: nowrap; }
|
||||
.vac-step b { font-weight: 700; }
|
||||
.vac-step.is-ok b { color: var(--vac-green); }
|
||||
.vac-step.is-no b { color: var(--vac-red); }
|
||||
.vac-step.is-wait b { color: #b45309; }
|
||||
.vac-step .vac-opt-face { width: 18px; height: 18px; font-size: 10px; }
|
||||
.vac-step-arrow { color: var(--vac-muted); }
|
||||
|
||||
/* ── 상세 ── */
|
||||
.vac-detail-card { padding: 16px; max-width: 760px; }
|
||||
@@ -207,6 +261,7 @@
|
||||
/* ── 휴가 옵션(2026-10-27) — 승인자·승인 통보자 · 메일 ── */
|
||||
.vac-opt-msg { margin: 0 0 12px; padding: 8px 12px; border-radius: 8px; background: #eef6ff; color: #1a4fa0; font-size: 13px; }
|
||||
.vac-opt-msg.is-warn { background: #fff7e6; color: #8a5a00; }
|
||||
.vac-mail-retry { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; }
|
||||
.vac-opt-grid { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; align-items: start; }
|
||||
.vac-opt-card { padding: 16px; }
|
||||
/* .erp-page > .vac 는 화면 높이 flex 라 카드가 줄어 내용이 잘렸다(잔여 연차 줄·메일 글) — 옵션 화면은 줄이지 않고 페이지 스크롤 */
|
||||
|
||||
+81
-23
@@ -1,13 +1,12 @@
|
||||
/* 휴가 신청 폼 — 종류에 따른 필드 토글 + 예상 일수 미리보기.
|
||||
서버(store.compute_days)가 공휴일 포함 정확히 재계산한다. 여기선 주말만 제외한 근사치.
|
||||
시작일·종료일 = 프로젝트와 같은 아사나식 날짜 팝업(2026-10-27, erp-datepop.js — 숨긴 input 옆 날짜 버튼, 둘 중 어느 쪽을 눌러도
|
||||
같은 기간 팝업, 반차는 하루짜리 팝업). 공휴일 = 국경일·대체공휴일(#vac-holidays). 아래쪽은 옵션 잔여 연차 표. */
|
||||
서버(store.compute_days)가 공휴일 포함 정확히 재계산한다. 여기선 주말·공휴일을 뺀 근사치.
|
||||
시작일·종료일 = 왼쪽 붙박이 달력(2026-11-02, ErpDatePop.mountRange)에서 고르면 숨긴 칸·오른쪽 표시 칸이 따라옴, 반차는 하루.
|
||||
공휴일 = 국경일·대체공휴일(#vac-holidays). 결재 라인 = 협의자 고르기·사람별 협의 내용. 아래쪽은 옵션 잔여 연차 표. */
|
||||
(function () {
|
||||
"use strict";
|
||||
var form = document.getElementById("vac-form");
|
||||
if (!form) return;
|
||||
|
||||
var type = document.getElementById("vac-type");
|
||||
var start = document.getElementById("vac-start");
|
||||
var startHalf = document.getElementById("vac-start-half");
|
||||
var endField = document.getElementById("vac-end-field");
|
||||
@@ -17,6 +16,11 @@
|
||||
var startHalfField = document.getElementById("vac-start-half-field");
|
||||
var out = document.getElementById("vac-days-out");
|
||||
|
||||
var startShow = document.getElementById("vac-start-show");
|
||||
var endShow = document.getElementById("vac-end-show");
|
||||
var err = document.getElementById("vac-form-err");
|
||||
|
||||
function typeValue() { var c = form.querySelector('input[name="vacation_type"]:checked'); return c ? c.value : ""; }
|
||||
function isHalfType(t) { return t === "오전반차" || t === "오후반차"; }
|
||||
|
||||
// 휴가 설정의 공휴일(빨강) {날짜: 이름} — 날짜 팝업 표시 + 예상 일수에서 제외(서버 compute_days 와 같은 표)
|
||||
@@ -26,12 +30,11 @@
|
||||
return d.getFullYear() + "-" + String(d.getMonth() + 1).padStart(2, "0") + "-" + String(d.getDate()).padStart(2, "0");
|
||||
}
|
||||
|
||||
if (window.ErpDatePop) {
|
||||
window.ErpDatePop.enhanceRange(start, end, {
|
||||
labels: { start: "시작일", due: "종료일" }, holidays: holidays, singleLabel: "날짜",
|
||||
single: function () { return isHalfType(type.value); },
|
||||
});
|
||||
}
|
||||
var cal = window.ErpDatePop.mountRange(document.getElementById("vac-cal"), {
|
||||
start: start.value, end: end.value, holidays: holidays,
|
||||
single: function () { return isHalfType(typeValue()); },
|
||||
onChange: function (s, e) { start.value = s; end.value = e; err.hidden = true; recalc(); },
|
||||
});
|
||||
|
||||
function parseDate(s) {
|
||||
if (!s) return null;
|
||||
@@ -56,12 +59,15 @@
|
||||
}
|
||||
|
||||
function recalc() {
|
||||
var t = type.value;
|
||||
var half = isHalfType(t);
|
||||
var half = isHalfType(typeValue());
|
||||
var oneDay = !!start.value && start.value === end.value;
|
||||
|
||||
startShow.value = window.ErpDatePop.fmtFull(start.value);
|
||||
endShow.value = window.ErpDatePop.fmtFull(end.value);
|
||||
// 반차 종류면 종료일/구분 숨김, 단일 0.5
|
||||
endField.style.display = half ? "none" : "";
|
||||
endHalfField.style.display = half ? "none" : "";
|
||||
endHalfField.style.display = half || oneDay ? "none" : "";
|
||||
endHalf.disabled = half || oneDay; // 하루짜리는 시작 구분만 쓴다(서버 compute_days 와 같음)
|
||||
startHalfField.style.display = half ? "none" : "";
|
||||
|
||||
if (half) {
|
||||
@@ -86,19 +92,71 @@
|
||||
out.textContent = total > 0 ? String(total) : "0";
|
||||
}
|
||||
|
||||
// 시작일 변경 시 종료일이 비었거나 더 빠르면 맞춰줌
|
||||
start.addEventListener("change", function () {
|
||||
if (!end.value || parseDate(end.value) < parseDate(start.value)) {
|
||||
end.value = start.value;
|
||||
}
|
||||
recalc();
|
||||
});
|
||||
|
||||
[type, end, startHalf, endHalf].forEach(function (el) {
|
||||
if (el) el.addEventListener("change", recalc);
|
||||
// 반차로 바꾸면 기간을 시작일 하루로
|
||||
form.querySelectorAll('input[name="vacation_type"]').forEach(function (r) {
|
||||
r.addEventListener("change", function () {
|
||||
if (isHalfType(typeValue()) && start.value && end.value !== start.value) {
|
||||
end.value = start.value;
|
||||
cal.set(start.value, start.value);
|
||||
}
|
||||
recalc();
|
||||
});
|
||||
});
|
||||
[startHalf, endHalf].forEach(function (el) { el.addEventListener("change", recalc); });
|
||||
|
||||
recalc();
|
||||
|
||||
// ── 결재 라인 — 구성원 선택(복수) → 사람마다 협의 내용 칸, 협의자 없음이면 잠금 ──
|
||||
var pickBtn = document.getElementById("vac-pick-btn");
|
||||
var pick = document.getElementById("vac-pick");
|
||||
var noConsult = document.getElementById("vac-no-consult");
|
||||
var box = document.getElementById("vac-consult-box");
|
||||
function rowOf(email) { return box.querySelector('.vac-consult-row[data-email="' + CSS.escape(email) + '"]'); }
|
||||
function chosen() { return Array.from(pick.querySelectorAll("input[data-email]:checked")); }
|
||||
function paintConsults() {
|
||||
var off = noConsult.checked;
|
||||
var on = {};
|
||||
chosen().forEach(function (c) { on[c.dataset.email] = true; });
|
||||
box.querySelectorAll(".vac-consult-row").forEach(function (row) {
|
||||
var show = !off && !!on[row.dataset.email];
|
||||
row.hidden = !show;
|
||||
row.querySelectorAll("input, textarea").forEach(function (x) { x.disabled = !show; });
|
||||
});
|
||||
box.hidden = off || !chosen().length;
|
||||
pickBtn.disabled = off;
|
||||
if (off) { pick.hidden = true; pickBtn.setAttribute("aria-expanded", "false"); }
|
||||
if (chosen().length || off) err.hidden = true;
|
||||
}
|
||||
pickBtn.addEventListener("click", function () {
|
||||
pick.hidden = !pick.hidden;
|
||||
pickBtn.setAttribute("aria-expanded", String(!pick.hidden));
|
||||
});
|
||||
document.addEventListener("click", function (e) {
|
||||
if (!pick.hidden && !pick.contains(e.target) && e.target !== pickBtn) {
|
||||
pick.hidden = true;
|
||||
pickBtn.setAttribute("aria-expanded", "false");
|
||||
}
|
||||
});
|
||||
pick.addEventListener("change", paintConsults);
|
||||
noConsult.addEventListener("change", paintConsults);
|
||||
box.addEventListener("click", function (e) {
|
||||
var x = e.target.closest(".vac-consult-x");
|
||||
if (!x) return;
|
||||
var c = pick.querySelector('input[data-email="' + CSS.escape(x.closest(".vac-consult-row").dataset.email) + '"]');
|
||||
if (c) c.checked = false;
|
||||
paintConsults();
|
||||
});
|
||||
paintConsults();
|
||||
|
||||
// 숨긴 칸은 브라우저 필수 검사가 안 되므로 여기서 — 날짜는 저장에도, 협의자는 제출에만 필요
|
||||
form.addEventListener("submit", function (e) {
|
||||
var submitting = e.submitter && e.submitter.value === "submit";
|
||||
var msg = !start.value ? "달력에서 휴가 날짜를 고르세요."
|
||||
: submitting && !noConsult.checked && !chosen().length ? "협의자를 고르거나 '협의자 없음'을 체크하세요." : "";
|
||||
err.textContent = msg;
|
||||
err.hidden = !msg;
|
||||
if (msg) e.preventDefault();
|
||||
});
|
||||
})();
|
||||
|
||||
/* 휴가 옵션 — 잔여 연차 표(2026-10-27, 입사일 기준): 이름 옆 입사일 = 날짜 버튼(erp-datepop). 고르면 근속·이번 연차 기간·생기는 연차
|
||||
|
||||
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
Copyright (c) 2017-2024, Slab
|
||||
Copyright (c) 2014, Jason Chen
|
||||
Copyright (c) 2013, salesforce.com
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
1. Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
|
||||
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
|
||||
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
|
||||
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user