Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5126943a78 | |||
| 97d002a06c | |||
| 4171d61db1 | |||
| 677bf8f1d1 | |||
| 15dcabc538 | |||
| 25c885d5dd | |||
| 61f5b3c320 | |||
| 5d55081464 | |||
| f54f19fa45 | |||
| 876d9758bd | |||
| 0ba6192e95 |
@@ -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"/>',
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
- 카페24 관리자에 들어가지 않고 상품 상세페이지(description HTML) 조회·편집·즉시적용·예약적용·버전 이력.
|
||||
- 3분할 화면(목록 | HTML 편집기 | 상품 정보 패널).
|
||||
- HTML 편집기에서 `<img>` 태그에 마우스를 올리면 태그를 오렌지색으로 칠하고 화면 오른쪽에 폭 500px·창 높이로 파일명과 미리보기(상대 경로는 `CAFE24_SHOP_URL` 루트 기준, 색칠 한도 `HL_LIMIT` 초과 소스는 미동작).
|
||||
- HTML 편집기에서 커서가 `<img>` 태그 안 어디에 있든 Ctrl+↑/↓ 로 `src` 파일명(`.jpg`/`.gif`/`.png`) 번호 변경. 없음 → `_2` → `_3` …, 이미 `_숫자` 면 다음 숫자부터. 내릴 때는 원래 번호(없었으면 원래 이름) 아래로 안 감 — 다른 편집이 끼거나 다른 이미지로 옮기면 그때 번호가 새 원래 번호.
|
||||
- 정보 패널(`routes_product_info.py`, `_side.html`)에서 상품명·판매가·공급가·소비자가, 대표이미지, 옵션(생성/이름·썸네일·표시방식 수정/삭제)·품목(자체코드·추가금액·진열·판매) 수정.
|
||||
- 대표이미지는 `POST /admin/products/{no}/images` 에 base64 data URI + `image_upload_type=A`.
|
||||
NNEditor 업로드 경로를 PUT `detail_image` 에 넣는 방식은 적용 안 됨.
|
||||
|
||||
@@ -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="변경 메모 (버전 이력에 남습니다)" />
|
||||
|
||||
@@ -368,6 +368,41 @@
|
||||
applyEdit(from, to, "", lineFrom + col, lineFrom + col);
|
||||
}
|
||||
|
||||
/* Ctrl+↑/↓ — 커서가 <img> 태그 안 어디에 있든 src 파일명(.jpg/.gif/.png)의 번호를 바꾼다.
|
||||
a.jpg → a_2.jpg → a_3.jpg …, a_5.jpg → a_6.jpg …. 내릴 때는 원래 번호(없었으면 원래 이름) 아래로 안 간다.
|
||||
원래 번호는 imgStep 에 기억한다 — 이 단축키 말고 소스가 바뀌거나 다른 이미지로 옮기면 그때 번호가 새 원래 번호.
|
||||
조건이 안 맞으면 false — 브라우저 기본 동작을 막지 않는다. */
|
||||
var imgStep = null;
|
||||
|
||||
function stepImgSuffix(up) {
|
||||
var at = ta.selectionStart, value = ta.value;
|
||||
if (at !== ta.selectionEnd) return false;
|
||||
|
||||
var tagRe = /<img\s(?:"[^"]*"|'[^']*'|[^>"'])*>/gi, tag;
|
||||
while ((tag = tagRe.exec(value)) && tagRe.lastIndex <= at);
|
||||
if (!tag || tag.index >= at) return false;
|
||||
|
||||
var src = tag[0].match(/\ssrc\s*=\s*(?:"([^"]*)|'([^']*)|([^\s>"']+))/i);
|
||||
var path = src && (src[1] || src[2] || src[3]);
|
||||
var file = path && path.match(/^(.*)\.(?:jpg|gif|png)(?=[?#]|$)/i);
|
||||
if (!file) return false;
|
||||
|
||||
var ext = tag.index + src.index + src[0].length - path.length + file[1].length; // 확장자 시작 위치
|
||||
var num = file[1].match(/_(\d{1,15})$/); // 16자리부터는 숫자 계산이 어긋나 번호로 보지 않는다
|
||||
var orig = imgStep && imgStep.value === value && imgStep.ext === ext ? imgStep.orig : (num ? num[1] : "");
|
||||
var n = num ? Number(num[1]) : 1;
|
||||
if (!up && n <= (orig ? Number(orig) : 1)) return true; // 원래 번호 아래로는 안 간다
|
||||
|
||||
var next = up ? n + 1 : n - 1;
|
||||
// a_01 → a_02 처럼 원래 자릿수를 유지한다.
|
||||
var text = !orig && next < 2 ? "" : "_" + String(next).padStart(orig.length, "0");
|
||||
var from = ext - (num ? num[0].length : 0);
|
||||
var caret = at >= ext ? at + text.length - (ext - from) : at <= from ? at : from + text.length;
|
||||
applyEdit(from, ext, text, caret, caret);
|
||||
imgStep = { value: ta.value, ext: from + text.length, orig: orig };
|
||||
return true;
|
||||
}
|
||||
|
||||
/* 이미지 미리보기 — 맨 위 textarea 를 판정에서 잠깐 빼고 색칠 층의 <img> 를 찾는다.
|
||||
글자 폭을 계산하지 않아 한글·탭·여러 줄 태그에서도 위치가 어긋나지 않는다.
|
||||
shortcut: HL_LIMIT 초과 소스는 색칠을 안 해 미리보기도 안 뜬다, 그런 상품이 나오면 글자 위치 계산으로 교체. */
|
||||
@@ -408,6 +443,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")) {
|
||||
|
||||
@@ -40,6 +40,9 @@
|
||||
- **입고 담당 발주 알림 자동 발송**(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")`). 입고 기록 줄 [보내기/다시 보내기]로 언제든.
|
||||
|
||||
@@ -709,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
|
||||
|
||||
|
||||
|
||||
+60
-21
@@ -248,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)
|
||||
@@ -263,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"]))
|
||||
|
||||
@@ -289,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
|
||||
@@ -323,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 ""
|
||||
@@ -336,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>"
|
||||
@@ -343,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>'
|
||||
|
||||
@@ -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 %}
|
||||
@@ -278,7 +278,6 @@
|
||||
.cf24-shortcuts {
|
||||
font-size: var(--text-caption, 12px);
|
||||
color: #79a6dd;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* 편집 폼과 코드 칸은 **줄어들지 않는다.** 아래 「예약 적용」·「버전 이력」을 펼치면
|
||||
|
||||
@@ -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());
|
||||
});
|
||||
})();
|
||||
@@ -39,6 +39,7 @@ MODULE_KEYS: tuple[str, ...] = (
|
||||
"asset",
|
||||
"inout",
|
||||
"outreach",
|
||||
"live",
|
||||
"expense_approver",
|
||||
"vacation_approver",
|
||||
)
|
||||
|
||||
@@ -80,7 +80,7 @@
|
||||
|
||||
<div class="erp-card-head">
|
||||
<div>
|
||||
<div class="erp-card-title">{{ item.title }}</div>
|
||||
<div class="erp-card-title">{{ item.card_title or item.title }}</div>
|
||||
<div class="erp-card-subtitle">{{ item.subtitle }}</div>
|
||||
</div>
|
||||
{% if item.status == 'preparing' %}
|
||||
|
||||
@@ -305,6 +305,18 @@ DDL: `scripts/sql/outreach_db_init.sql` (멱등). DB·역할(`outreach_app`)·
|
||||
| `outreach_logs` | 보낸 기록(메일·DM, 성공·오류) — 줄을 지워도 남음, 본문·토큰은 안 남김 |
|
||||
| `outreach_dm_bodies` | DM 수동 보내기 탭의 저장한 본문({이름} 이 든 글, 최대 1000자, 제목 = 첫 줄) — 마이그레이션 `outreach_db_002_dm_bodies.sql`(2026-10-30) |
|
||||
|
||||
## live_db 스키마 / 초기화 (라이브 커머스, 2026-11-04)
|
||||
|
||||
DDL: `scripts/sql/live_db_init.sql` (멱등). DB·역할(`live_app`)·테이블·인덱스·트리거. **JSON 폴백 없음** — `LIVE_DB_URL` 미설정 시 "설정 필요" 안내.
|
||||
생성·연결 명령은 `docs/DEPLOYMENT.md` "라이브 커머스 DB 생성". 호스트 계좌·주소 등 개인정보 포함(평문 저장, 화면은 ERP 관리자만).
|
||||
|
||||
| 테이블 | 용도 |
|
||||
| --- | --- |
|
||||
| `live_hosts` | 호스트 — Full Name (as per IC)·Phone Number·Email·Address·Bank Name·Bank Account Number·Tiktok Handle(@ 없이), `is_active` |
|
||||
| `live_broadcasts` | 방송 스케줄 — `host_id`(FK RESTRICT)·`broadcast_date`·`start_time`·`end_time`(말레이시아 시간 그대로)·`venue`·`sales_amount`(RM, NULL = 미입력) |
|
||||
| `live_broadcast_images` | 방송 결과 이미지(메타데이터 제거 후 BYTEA, 방송을 지우면 CASCADE) — 방송당 최대 10장(앱에서 확인) |
|
||||
| `live_daily_ad_spend` | 날짜별 광고비(RM) — 달력 보기 AD SPEND·ROAS. 마이그레이션 `live_db_002_ad_spend.sql`(init 에도 포함) |
|
||||
|
||||
## malaysia_stock_db 스키마 / 초기화
|
||||
|
||||
DDL: `scripts/sql/malaysia_stock_db_init.sql` (멱등). DB·역할(`malaysia_app`)·테이블·인덱스·트리거·창고/아이템 seed 를 한 번에 생성. **JSON 폴백 없음** — `MALAYSIA_STOCK_DB_URL` 미설정 시 모듈이 "설정 필요" 안내만 표시. 상품명은 `itemcode_db` 읽기 전용 재사용.
|
||||
|
||||
@@ -375,6 +375,28 @@ docker exec dbx-main python -c "import os,psycopg; psycopg.connect(os.environ['O
|
||||
백업: 매일 `docker exec postgres-db pg_dump -U postgres outreach_db > /var/backups/postgres/outreach_db_$(date +%F).sql`.
|
||||
백업: 매일 `docker exec postgres-db pg_dump -U postgres inout_db > /var/backups/postgres/inout_db_$(date +%F).sql`.
|
||||
|
||||
## 라이브 커머스 DB 생성 (live_db, 2026-11-04)
|
||||
|
||||
입출고 DB 와 같은 방법(새 DB — 기존 DB·데이터는 건드리지 않음, 초기화 SQL 멱등, 비밀번호는 URL 인코딩). 호스트 계좌·주소 등 개인정보가 들어가므로 백업 파일 권한에 주의.
|
||||
|
||||
```bash
|
||||
cd /opt/www/main && git pull
|
||||
docker exec postgres-db psql -U postgres -lqt | cut -d'|' -f1 | grep -w live_db || echo "live_db 없음 — 새로 만든다"
|
||||
read -s -p "live_app password: " APP_PWD; echo
|
||||
docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -v app_password="$APP_PWD" < scripts/sql/live_db_init.sql
|
||||
ENC=$(APP_PWD="$APP_PWD" python3 -c "import os,urllib.parse;print(urllib.parse.quote(os.environ['APP_PWD'],safe=''))")
|
||||
grep -q "^LIVE_DB_URL=" .env && sed -i "s|^LIVE_DB_URL=.*|LIVE_DB_URL=postgresql://live_app:${ENC}@postgres-db:5432/live_db|" .env \
|
||||
|| printf '\nLIVE_DB_URL=postgresql://live_app:%s@postgres-db:5432/live_db\n' "$ENC" >> .env
|
||||
docker compose up --build -d --no-deps web
|
||||
docker exec dbx-main python -c "import os,psycopg; psycopg.connect(os.environ['LIVE_DB_URL']).execute('select 1 from live_hosts limit 1'); print('DB OK')"
|
||||
```
|
||||
|
||||
이미 만든 live_db 에는 `scripts/sql/live_db_002_ad_spend.sql`(날짜별 광고비 표 하나 추가, 다시 실행 가능)을 백업 뒤 적용한다 — 초기화 SQL 을 다시 돌리면 `live_app` 비밀번호를 다시 넣게 되므로 쓰지 않는다.
|
||||
되돌리기 = `DROP TABLE live_daily_ad_spend;`(광고비 값만 사라짐).
|
||||
|
||||
그다음 ERP 관리자 화면에서 쓸 사람에게 **라이브 커머스** 권한 → ERP 관리자가 라이브 커머스 → 호스트 설정에서 호스트 등록.
|
||||
백업: 매일 `docker exec postgres-db pg_dump -U postgres live_db > /var/backups/postgres/live_db_$(date +%F).sql`.
|
||||
|
||||
## 연간 목표 주차별 매출 목표 두 칸 마이그레이션 (project_db 030)
|
||||
|
||||
030은 `goal_week_targets` 에 `value_dist`(유통·인플)·`value_mall`(카페24·네이버) 열만 추가한다(다시 실행 가능, 기존 값 변경 없음, 새 환경변수 없음).
|
||||
@@ -597,6 +619,7 @@ docker compose down # 컨테이너 제거 (볼륨 유지)
|
||||
| `APP_ENCRYPTION_KEY_VERSION` | 현재 마스터 키 버전(기본 1). 교체 시 올리고 예전 키는 `APP_ENCRYPTION_KEY_V{n}` 로 남긴 뒤 설정 화면에서 재암호화(`docs/PERFORMANCE_MODULE.md`) |
|
||||
| `PERFORMANCE_SYNC_DAYS` | [매출 업데이트] 수집 기간(오늘 포함 최근 N일, 기본 7, 최대 90) |
|
||||
| `OUTREACH_DB_URL` | 안내문 발송 DB DSN (예: `postgresql://outreach_app:<pwd>@postgres-db:5432/outreach_db`, 비밀번호는 URL 인코딩). 미설정 시 모듈 비활성(설정 필요 안내). 권한키 `outreach`. 메일은 `INOUT_DB_URL` 의 Gmail 연결 재사용 |
|
||||
| `LIVE_DB_URL` | 라이브 커머스 DB DSN (예: `postgresql://live_app:<pwd>@postgres-db:5432/live_db`, 비밀번호는 URL 인코딩). 미설정 시 모듈 비활성(설정 필요 안내). 권한키 `live` |
|
||||
| `INOUT_DB_URL` | 입출고 관리 DB DSN (예: `postgresql://inout_app:<pwd>@postgres-db:5432/inout_db`). 미설정 시 입출고 모듈 비활성(설정 필요 안내). 권한키 `inout`. 제품은 `ITEMCODE_DB_URL`(단품) 재사용 |
|
||||
|
||||
---
|
||||
|
||||
@@ -119,6 +119,7 @@ cupang·malaysia 와 같은 DSN). 화면에서 코드·이름으로 검색(`GET
|
||||
사람이 **[메일 발송]**을 눌러야만 보낸다(자동 발송 없음). 머리 **[발주 메일 보내기 / 다시 보내기]**로 언제든 다시 연다.
|
||||
- **본문**(`store.order_mail`) = 인사(공장 담당자 이름) · 발주번호·발주일·입고 예정일·품목 수·총수량·요청 사항(메모) 표 ·
|
||||
품목 표(No·제품 코드·제품명·수량·비고, 합계) · 보낸 사람. HTML + 글 본문(둘 다), 값은 모두 escape. 제목 `[발주] {번호} · {공장} · {첫 품목} 외 n종`.
|
||||
- **간단 발주 메일**(2026-11-04, 사용자 요청): 공장 이름에 "대성화학"·"인천공장"이 들어가면(띄어쓰기 무시) 품목 표 = 번호·제품 코드·제품명·수량·박스당 수량·박스 수·비고, 요약 표·글 본문에서도 금액·무게·PP·은을 뺀다. 박스 값은 메일을 만들 때의 상품 정보(올림, 뚜껑 있으면 통·뚜껑 따로, 입수 없으면 `-`, 합계는 있는 줄만).
|
||||
- **보내는 계정** = 누른 사람(발주 담당)의 Gmail — Gmail API `users.messages.send`(`gmail.py`).
|
||||
사람마다 처음 한 번 **[Gmail 연결]**: 구글 동의 화면(로그인과 같은 OAuth 클라이언트, 범위 `openid email gmail.send` 만, `hd=` 회사 도메인,
|
||||
`login_hint` = ERP 계정) → `/inout/gmail/callback` 에서 **고른 구글 계정 = ERP 로그인 계정**인지(다르면 거절), gmail.send 허락·갱신 토큰 확인 →
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
| 입출고 관리 | 본사 → 공장 제품 제작 발주, 물류 입고(여러 번 나눠), 발주 대비 미입고·초과 입고 관리 (`app/modules/inout/`, `inout_db`) — 발주 담당·입고 담당·공장은 모듈 옵션에서 지정, 제품은 `itemcode_db` 단품 읽기 전용. `docs/INOUT_MODULE.md` |
|
||||
| 긴급 공지 | 수퍼관리자가 정한 시각에 전체/고른 사람의 ERP 화면 정가운데에 띄우는 공지(`app/modules/notice/`, project_db 024) — [확인] 전까지 다시 뜸, 확인 현황. `docs/NOTICE_MODULE.md` |
|
||||
| 안내문 발송 | 리스트(이메일·인스타 주소 + 이름)에 `{이름}`을 넣은 안내문 — 메일 일괄 발송(보내는 사람 본인 Gmail)·인스타 DM 반자동(문구 복사 + DM 창) (`app/modules/outreach/`, `outreach_db`) |
|
||||
| 라이브 커머스 | 말레이시아 라이브 방송의 호스트 정보(설정)와 스케줄표(호스트·날짜·시간·판매금액·장소·결과 이미지) (`app/modules/live/`, `live_db`) |
|
||||
| 실적 | 쇼핑몰 통합 매출 (`app/modules/performance/`) — 쇼핑몰별 어댑터로 수집 → `performance_db` 저장 → 일자×쇼핑몰 표·KPI·월/연 누적·그래프. 수수료율 이력, API 인증정보는 설정 화면 입력 + AES-256-GCM 암호화 저장. 1단계는 모의 데이터·구조까지(실제 API 는 쇼핑몰별로 순차 연동). `docs/PERFORMANCE_MODULE.md` |
|
||||
|
||||
### 권한 키 (`MODULE_KEYS`)
|
||||
@@ -39,6 +40,7 @@
|
||||
| `expense_approver` | 결재 | 개인경비 승인/반려/정산 |
|
||||
| `asset` | 접근 | 자산관리 조회·등록·수정·배정·반납·보고서 |
|
||||
| `outreach` | 접근 | 안내문 발송 — 리스트·메일 발송·DM·설정 |
|
||||
| `live` | 접근 | 라이브 커머스 스케줄표 보기·고치기(호스트 정보 설정은 ERP 관리자만) |
|
||||
| `inout` | 접근 | 입출고 관리 조회. 발주·입고 입력은 모듈 옵션의 발주 담당·입고 담당(ERP 관리자는 둘 다 + 옵션) |
|
||||
| `vacation_approver` | 결재 | 휴가 승인/반려 (모듈 미개발) |
|
||||
|
||||
@@ -114,6 +116,7 @@ app/modules/<name>/
|
||||
| `vacation_db` | 휴가 신청/공휴일/연차잔여 (`VACATION_DB_URL` 필수, JSON 폴백 없음) |
|
||||
| `malaysia_stock_db` | 말레이시아 창고 재고/세트BOM/재고조사 (`MALAYSIA_STOCK_DB_URL` 필수, JSON 폴백 없음) |
|
||||
| `outreach_db` | 안내문 발송 — 리스트·보낸 기록·제목/본문 설정·사진 (`OUTREACH_DB_URL` 필수, JSON 폴백 없음) |
|
||||
| `live_db` | 라이브 커머스 — 호스트 정보·방송 스케줄·결과 이미지 (`LIVE_DB_URL` 필수, JSON 폴백 없음) |
|
||||
| `performance_db` | 실적 — 쇼핑몰 설정/수수료 이력/인증정보(암호문)/매출 사건 (`PERFORMANCE_DB_URL` 필수, JSON 폴백 없음) |
|
||||
|
||||
> 신규 DB 생성은 서버 실행 명령을 제공하고 사용자가 직접 진행한다 (사용자 지시: 2026-10-06). 대상·상태·백업 확인 명령을 제공하고 이름은 `_db`로 끝낸다. 기존 DB 삭제·덮어쓰기는 별도 승인 대상이다. 상세는 `DATABASES.md`.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
-- =====================================================================
|
||||
-- live_db 마이그레이션 002 — 날짜별 광고비(달력 보기 맨 아래 AD SPEND·ROAS)(2026-11-04)
|
||||
-- =====================================================================
|
||||
-- 멱등(idempotent). 표 하나만 추가(기존 표·값 변경 없음). 운영: /opt/www/main 에서 기존 live_db 에 적용(백업 먼저).
|
||||
-- docker exec -i postgres-db psql -v ON_ERROR_STOP=1 -U postgres -d live_db < scripts/sql/live_db_002_ad_spend.sql
|
||||
-- 되돌리기: DROP TABLE live_daily_ad_spend; (광고비 값만 사라짐 — 실행 전 백업)
|
||||
-- =====================================================================
|
||||
\set ON_ERROR_STOP on
|
||||
BEGIN;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS live_daily_ad_spend (
|
||||
ad_date DATE PRIMARY KEY,
|
||||
ad_spend NUMERIC(14,2) NOT NULL CHECK (ad_spend >= 0),
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE live_daily_ad_spend IS '라이브 커머스 — 날짜별 광고비(RM)';
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON live_daily_ad_spend TO live_app;
|
||||
|
||||
COMMIT;
|
||||
SELECT 'live_db 002 ad spend ready' AS status;
|
||||
@@ -0,0 +1,127 @@
|
||||
-- =====================================================================
|
||||
-- live_db 초기화 스크립트 (PostgreSQL) — 라이브 커머스 모듈(2026-11-04)
|
||||
-- =====================================================================
|
||||
-- 말레이시아 라이브 커머스 방송 — 호스트 정보(설정)와 방송 스케줄(호스트·날짜·시간·판매금액·장소·결과 이미지).
|
||||
-- 멱등(idempotent): 여러 번 실행해도 안전. 기존 데이터를 삭제하지 않는다. DROP/TRUNCATE 없음(트리거 다시 만들기만).
|
||||
--
|
||||
-- 실행 방법 (운영 PostgreSQL 컨테이너명: postgres-db, 백업 먼저):
|
||||
--
|
||||
-- 1) DB / 역할 / 테이블 생성 (superuser 로 1회)
|
||||
-- read -s -p "live_app password: " APP_PWD; echo
|
||||
-- docker exec -i postgres-db psql -U postgres -v app_password="$APP_PWD" < scripts/sql/live_db_init.sql
|
||||
--
|
||||
-- 2) main-app .env 에 연결 정보 등록
|
||||
-- LIVE_DB_URL=postgresql://live_app:<APP_PWD>@postgres-db:5432/live_db
|
||||
--
|
||||
-- 3) main-app 재기동
|
||||
-- cd /opt/www/main && docker compose up -d --build --no-deps web
|
||||
-- =====================================================================
|
||||
|
||||
\set ON_ERROR_STOP on
|
||||
|
||||
SELECT 'CREATE DATABASE live_db ENCODING ''UTF8'' TEMPLATE template0'
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pg_database WHERE datname = 'live_db')
|
||||
\gexec
|
||||
|
||||
SELECT 'CREATE ROLE live_app LOGIN PASSWORD ' || quote_literal(:'app_password')
|
||||
WHERE NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'live_app')
|
||||
\gexec
|
||||
|
||||
SELECT 'ALTER ROLE live_app WITH LOGIN PASSWORD ' || quote_literal(:'app_password')
|
||||
\gexec
|
||||
|
||||
GRANT CONNECT ON DATABASE live_db TO live_app;
|
||||
|
||||
\connect live_db
|
||||
|
||||
CREATE OR REPLACE FUNCTION live_set_updated_at() RETURNS trigger AS $$
|
||||
BEGIN
|
||||
NEW.updated_at := now();
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$ LANGUAGE plpgsql;
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 1) 호스트 — 설정에서 미리 등록(개인정보·계좌 포함, 설정 화면은 ERP 관리자만)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS live_hosts (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
full_name TEXT NOT NULL CHECK (char_length(full_name) BETWEEN 1 AND 200), -- Full Name (as per IC)
|
||||
phone TEXT NOT NULL DEFAULT '',
|
||||
email TEXT NOT NULL DEFAULT '',
|
||||
address TEXT NOT NULL DEFAULT '',
|
||||
bank_name TEXT NOT NULL DEFAULT '',
|
||||
bank_account TEXT NOT NULL DEFAULT '',
|
||||
tiktok_handle TEXT NOT NULL DEFAULT '', -- @ 없이
|
||||
is_active BOOLEAN NOT NULL DEFAULT TRUE, -- FALSE = 새 방송에서 못 고름
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE live_hosts IS '라이브 커머스 — 호스트 정보(개인정보·계좌 포함)';
|
||||
DROP TRIGGER IF EXISTS trg_live_hosts_updated_at ON live_hosts;
|
||||
CREATE TRIGGER trg_live_hosts_updated_at BEFORE UPDATE ON live_hosts
|
||||
FOR EACH ROW EXECUTE FUNCTION live_set_updated_at();
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 2) 방송 스케줄 — 날짜·시간은 입력한 말레이시아 시간 그대로(시간대 변환 없음), 판매금액 단위 RM
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS live_broadcasts (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
host_id BIGINT NOT NULL REFERENCES live_hosts(id) ON DELETE RESTRICT, -- 방송 기록이 있는 호스트는 못 지움
|
||||
broadcast_date DATE NOT NULL,
|
||||
start_time TIME NOT NULL,
|
||||
end_time TIME,
|
||||
venue TEXT NOT NULL DEFAULT '',
|
||||
sales_amount NUMERIC(14,2) CHECK (sales_amount IS NULL OR sales_amount >= 0), -- NULL = 아직 입력 안 함
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE live_broadcasts IS '라이브 커머스 — 방송 스케줄';
|
||||
CREATE INDEX IF NOT EXISTS idx_live_broadcasts_date ON live_broadcasts (broadcast_date, start_time);
|
||||
CREATE INDEX IF NOT EXISTS idx_live_broadcasts_host ON live_broadcasts (host_id);
|
||||
DROP TRIGGER IF EXISTS trg_live_broadcasts_updated_at ON live_broadcasts;
|
||||
CREATE TRIGGER trg_live_broadcasts_updated_at BEFORE UPDATE ON live_broadcasts
|
||||
FOR EACH ROW EXECUTE FUNCTION live_set_updated_at();
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 3) 방송 결과 이미지 — 서버가 확인·메타데이터 제거 후 저장(방송을 지우면 함께 지워짐)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS live_broadcast_images (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
broadcast_id BIGINT NOT NULL REFERENCES live_broadcasts(id) ON DELETE CASCADE,
|
||||
filename TEXT NOT NULL DEFAULT '',
|
||||
content_type TEXT NOT NULL,
|
||||
data BYTEA NOT NULL,
|
||||
width INTEGER NOT NULL DEFAULT 0,
|
||||
height INTEGER NOT NULL DEFAULT 0,
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE live_broadcast_images IS '라이브 커머스 — 방송 결과 이미지';
|
||||
CREATE INDEX IF NOT EXISTS idx_live_images_broadcast ON live_broadcast_images (broadcast_id, id);
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 3-1) 날짜별 광고비 — 마이그레이션 002 와 같음(달력 보기 AD SPEND·ROAS)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
CREATE TABLE IF NOT EXISTS live_daily_ad_spend (
|
||||
ad_date DATE PRIMARY KEY,
|
||||
ad_spend NUMERIC(14,2) NOT NULL CHECK (ad_spend >= 0),
|
||||
updated_by TEXT NOT NULL DEFAULT '',
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
COMMENT ON TABLE live_daily_ad_spend IS '라이브 커머스 — 날짜별 광고비(RM)';
|
||||
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
-- 4) 권한 (live_app: CRUD only)
|
||||
-- ════════════════════════════════════════════════════════════
|
||||
GRANT USAGE ON SCHEMA public TO live_app;
|
||||
GRANT SELECT, INSERT, UPDATE, DELETE ON live_hosts, live_broadcasts, live_broadcast_images, live_daily_ad_spend TO live_app;
|
||||
GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO live_app;
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO live_app;
|
||||
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT USAGE, SELECT ON SEQUENCES TO live_app;
|
||||
|
||||
SELECT 'live_db ready' AS status;
|
||||
@@ -2,6 +2,7 @@
|
||||
import base64
|
||||
import email
|
||||
import json
|
||||
import re
|
||||
import unittest
|
||||
from datetime import date
|
||||
from email import policy
|
||||
@@ -118,6 +119,50 @@ class MailContentTests(unittest.TestCase):
|
||||
self.assertTrue(m2["text"].startswith("안녕하세요."))
|
||||
self.assertNotIn("요청 사항", m2["text"])
|
||||
|
||||
def test_order_mail_simple_factories(self):
|
||||
"""대성화학·인천공장 — 표는 번호·제품 코드·제품명·수량·박스당 수량·박스 수·비고만, 단가·금액·무게·은은 어디에도 없음. 다른 공장은 그대로."""
|
||||
from decimal import Decimal as D
|
||||
|
||||
priced = [{"item_code": "MT-0320", "item_name": "통", "qty": 100, "memo": "흰색", "unit_price": D("7777"),
|
||||
"weight_g": D("50"), "silver_pct": D("3")}]
|
||||
for name in ("대성화학", "(주)대성화학", "인천공장", "인천 공장"):
|
||||
with self.subTest(name=name):
|
||||
m = s.order_mail(_order(factory_name=name, lines=priced), sender_name="K", sender_email="k@x.com")
|
||||
head = m["html"][m["html"].index("<thead>"):m["html"].index("</thead>")]
|
||||
self.assertEqual(re.findall(r"<th[^>]*>([^<]*)</th>", head), ["번호", "제품 코드", "제품명", "수량", "박스당 수량", "박스 수", "비고"])
|
||||
row = m["html"][m["html"].index("<tbody>"):m["html"].index("</tbody>")]
|
||||
self.assertEqual(row.count("<td"), 7)
|
||||
self.assertEqual(m["html"][m["html"].index("<tfoot>"):].count("<th"), 5) # 합계(3칸 합침)·수량·박스당 빈칸·박스·비고
|
||||
for part in (m["html"], m["text"]):
|
||||
self.assertNotRegex(part, "단가|금액|무게|PP|은\\(|7,777|777,700")
|
||||
self.assertIn("1. MT-0320 통 — 100개 (흰색)", m["text"])
|
||||
self.assertIn("발주번호", m["html"])
|
||||
other = s.order_mail(_order(lines=[dict(priced[0], body_per_box=30)]), sender_name="K", sender_email="k@x.com")
|
||||
for part in ("단가(원)", "금액(원)", "전체 무게(kg)", "PP 사용량(kg)", "은(Ag) 함유량", "7,777"):
|
||||
self.assertIn(part, other["html"])
|
||||
self.assertIn(">No</th>", other["html"])
|
||||
self.assertIn("단가 7,777", other["text"])
|
||||
self.assertNotIn("박스", other["html"].replace("박스당 24개", "")) # 다른 공장엔 박스 칸 없음(요청 사항 글 제외)
|
||||
|
||||
def test_order_mail_simple_boxes(self):
|
||||
"""박스당 수량·박스 수(올림) — 뚜껑 있으면 통·뚜껑 따로, 입수 없으면 '-', 합계는 있는 줄만."""
|
||||
self.assertEqual(s.line_boxes({"qty": 100, "body_per_box": 30}), {"per": "30개", "count": "4박스", "total": 4})
|
||||
self.assertEqual(s.line_boxes({"qty": 90, "body_per_box": 30})["total"], 3)
|
||||
self.assertEqual(s.line_boxes({"qty": 1000, "body_per_box": 120, "lid_per_box": 500}),
|
||||
{"per": "통 120개 · 뚜껑 500개", "count": "통 9 · 뚜껑 2박스", "total": 11})
|
||||
self.assertEqual(s.line_boxes({"qty": 5}), {"per": "-", "count": "-", "total": None})
|
||||
lines = [{"item_code": "A", "item_name": "봉투", "qty": 2600, "memo": "", "body_per_box": 100, "lid_per_box": None},
|
||||
{"item_code": "B", "item_name": "통", "qty": 1000, "memo": "흰색", "body_per_box": 120, "lid_per_box": 500},
|
||||
{"item_code": "C", "item_name": "없음", "qty": 5, "memo": ""}]
|
||||
m = s.order_mail(_order(factory_name="대성화학", memo="", lines=lines), sender_name="K", sender_email="k@x.com")
|
||||
self.assertIn(">100개</td>", m["html"])
|
||||
self.assertIn(">26박스</td>", m["html"])
|
||||
self.assertIn("통 9 · 뚜껑 2박스", m["html"])
|
||||
self.assertIn("37박스 (미설정 1종 제외)", m["html"])
|
||||
self.assertIn("1. A 봉투 — 2,600개 · 박스당 100개 · 26박스", m["text"])
|
||||
self.assertIn("2. B 통 — 1,000개 · 박스당 통 120개 · 뚜껑 500개 · 통 9 · 뚜껑 2박스 (흰색)", m["text"])
|
||||
self.assertIn("3. C 없음 — 5개", m["text"])
|
||||
|
||||
def test_build_message_utf8_and_alternative(self):
|
||||
raw = gmail.build_message(sender_name="킹", sender_email="king@dbxcorp.co.kr", to=["a@x.com", "b@y.com"], cc=["c@z.com"],
|
||||
subject="[발주] 테스트 · 한글", text="본문", html="<p>본문</p>")
|
||||
|
||||
@@ -461,6 +461,47 @@ def body(c):
|
||||
st.exclude_product(code, by=admin["email"])
|
||||
print("OK")
|
||||
run(body)
|
||||
''', {"INOUT_TEST_DB_URL": DSN})
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
@unittest.skipUnless(DB_ENABLED, "INOUT_TEST_DB_URL(localhost) not set")
|
||||
def test_simple_factory_mail_shows_boxes(self):
|
||||
"""대성화학 메일 미리보기 — 상품 정보의 박스 입수로 박스 칸이 차고 단가는 없음. 다른 공장은 예전 표."""
|
||||
res = _run('''
|
||||
import re, uuid
|
||||
from app.modules.inout.db import InoutDBStore
|
||||
st = InoutDBStore(__import__("os").environ["INOUT_TEST_DB_URL"])
|
||||
main.app.state.inout_store = st
|
||||
main.app.state.inout_items = Items()
|
||||
tag = uuid.uuid4().hex[:6].upper()
|
||||
admin = U("admin-%s@t.local" % tag.lower(), role="admin")
|
||||
users.append(admin)
|
||||
CODE = "ZS-%s-A" % tag
|
||||
|
||||
def order_for(c, factory):
|
||||
c.post("/inout/settings/factories", data={"name": factory, "is_active": "1"}, headers={"X-Inout-Options": "1"})
|
||||
fid = next(f["id"] for f in st.list_factories() if f["name"] == factory)
|
||||
r = c.post("/inout/orders/new", data={"factory_id": fid, "order_date": "2026-11-04", "item_code": [CODE],
|
||||
"item_name": [""], "qty": ["100"], "line_memo": [""]}, follow_redirects=False)
|
||||
return int(re.search(r"/inout/orders/(\\d+)", r.headers["location"]).group(1))
|
||||
|
||||
def body(c):
|
||||
who["u"] = admin
|
||||
st.import_products([{"code": CODE, "name": "통 " + tag}], by=admin["email"])
|
||||
try:
|
||||
r = c.post("/inout/settings/products/save", headers={"X-Inout-Options": "1"}, json={"rows": [
|
||||
{"code": CODE, "unit_price": "7777", "weight_g": "", "silver_pct": "", "body_per_box": "30", "lid_per_box": ""}]})
|
||||
assert r.json()["ok"], r.text
|
||||
html = c.get("/inout/orders/%d/mail" % order_for(c, "대성화학-" + tag)).json()["html"]
|
||||
assert "박스당 수량" in html and ">30개</td>" in html and ">4박스</td>" in html, html
|
||||
assert "단가" not in html and "7,777" not in html
|
||||
html = c.get("/inout/orders/%d/mail" % order_for(c, "보통공장-" + tag)).json()["html"]
|
||||
assert "박스당 수량" not in html and "7,777" in html
|
||||
finally:
|
||||
st.exclude_product(CODE, by=admin["email"])
|
||||
print("OK")
|
||||
run(body)
|
||||
''', {"INOUT_TEST_DB_URL": DSN})
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
"""라이브 커머스(live, 2026-11-04).
|
||||
|
||||
1) store — 호스트·방송 입력 검사, 판매금액, 달 범위, 표시 형식, 작은 그림.
|
||||
2) 실제 앱(격리된 하위 프로세스) — 메뉴·권한 칩·"설정 필요" 안내(DB 없이 늘 실행).
|
||||
3) 전체 흐름(LIVE_TEST_DB_URL 이 localhost 일 때만) — 호스트 등록·권한·스케줄·이미지·지우기.
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from datetime import date, time
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from PIL import Image
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
from app.modules.live import i18n, store # noqa: E402
|
||||
|
||||
DSN = os.getenv("LIVE_TEST_DB_URL", "")
|
||||
DB_ENABLED = bool(DSN) and urlparse(DSN).hostname in ("localhost", "127.0.0.1")
|
||||
|
||||
PRELUDE = '''
|
||||
from unittest.mock import patch
|
||||
from fastapi.testclient import TestClient
|
||||
import app.main as main
|
||||
|
||||
def U(email, role="user", live=True):
|
||||
return {"email": email, "name": email.split("@")[0], "role": role, "is_super_admin": False, "modules": {"live": live}}
|
||||
|
||||
who = {"u": None}
|
||||
|
||||
def run(body):
|
||||
with patch.object(main, "get_current_user_record", side_effect=lambda r: who["u"]), \\
|
||||
patch.object(main, "get_session_user", side_effect=lambda r: who["u"]), \\
|
||||
patch.object(main.user_store, "get", side_effect=lambda e: who["u"]), \\
|
||||
patch.object(main.user_store, "list_all", side_effect=lambda: [who["u"]]):
|
||||
body(TestClient(main.app))
|
||||
'''
|
||||
|
||||
|
||||
def _run(code: str, extra_env: dict[str, str] | None = None) -> subprocess.CompletedProcess:
|
||||
env = dict(os.environ)
|
||||
for key in ("ASSET", "CAFE24", "CUPANG", "VACATION", "PROJECT", "DISPATCH", "PERFORMANCE", "MALAYSIA_STOCK",
|
||||
"ITEMCODE", "EXPENSE", "INOUT", "OUTREACH", "LIVE"):
|
||||
env[key + "_DB_URL"] = ""
|
||||
env.update(SESSION_SECRET_KEY="local-live-test-only", SESSION_COOKIE_SECURE="false", PERFORMANCE_AUTO_SYNC="false")
|
||||
env.update(extra_env or {})
|
||||
with tempfile.TemporaryDirectory(prefix="live-web-") as directory:
|
||||
env["DATA_DIR"] = directory
|
||||
return subprocess.run([sys.executable, "-c", PRELUDE + code], cwd=ROOT, env=env, capture_output=True,
|
||||
text=True, encoding="utf-8", timeout=90)
|
||||
|
||||
|
||||
class StoreTests(unittest.TestCase):
|
||||
def test_clean_host(self):
|
||||
got = store.clean_host({"full_name": " Siti Aisyah ", "phone": "+60 12-345 6789", "email": "siti@example.my", "address": "KL",
|
||||
"bank_name": "Maybank", "bank_account": "1234-5678", "tiktok_handle": "@siti.live"})
|
||||
self.assertEqual((got["full_name"], got["tiktok_handle"]), ("Siti Aisyah", "siti.live"))
|
||||
self.assertEqual(store.clean_host({"full_name": "A"})["phone"], "") # Full Name 만 필수
|
||||
for bad in ({}, {"full_name": " "}, {"full_name": "A", "email": "nope"}, {"full_name": "A", "phone": "abc"},
|
||||
{"full_name": "A", "bank_account": "12a"}, {"full_name": "A", "tiktok_handle": "한글"},
|
||||
{"full_name": "x" * 201}):
|
||||
with self.assertRaises(ValueError, msg=bad):
|
||||
store.clean_host(bad)
|
||||
|
||||
def test_clean_handle(self):
|
||||
for raw in ("@siti.live", "siti.live", "https://www.tiktok.com/@siti.live?lang=en", "tiktok.com/@siti.live/video/1"):
|
||||
self.assertEqual(store.clean_handle(raw), "siti.live", raw)
|
||||
|
||||
def test_parse_money(self):
|
||||
self.assertIsNone(store.parse_money(""))
|
||||
self.assertEqual(store.parse_money("RM 1,234.5"), Decimal("1234.50"))
|
||||
self.assertEqual(store.parse_money("0"), Decimal("0.00"))
|
||||
for bad in ("-1", "abc", "NaN", "Infinity", "1e20"):
|
||||
with self.assertRaises(ValueError, msg=bad):
|
||||
store.parse_money(bad)
|
||||
|
||||
def test_clean_broadcast(self):
|
||||
got = store.clean_broadcast({"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20:00", "end_time": "22:00",
|
||||
"venue": " Studio ", "sales_amount": "100"})
|
||||
self.assertEqual(got, {"host_id": 3, "broadcast_date": date(2026, 11, 4), "start_time": time(20, 0), "end_time": time(22, 0),
|
||||
"venue": "Studio", "sales_amount": Decimal("100.00")})
|
||||
good = {"host_id": "3", "broadcast_date": "2026-11-04", "start_time": "20:00", "end_time": "22:00"}
|
||||
for over in ({"host_id": ""}, {"host_id": "x"}, {"broadcast_date": ""}, {"broadcast_date": "2026-13-01"}, {"start_time": ""},
|
||||
{"start_time": "25:00"}, {"end_time": ""}, {"end_time": "nope"}, {"end_time": "20:00"}, {"venue": "x" * 201}, {"sales_amount": "-5"}):
|
||||
with self.assertRaises(ValueError, msg=over):
|
||||
store.clean_broadcast({**good, **over})
|
||||
|
||||
def test_month_range(self):
|
||||
today = date(2026, 11, 4)
|
||||
self.assertEqual(store.month_range("", today)["label"], "2026년 11월")
|
||||
self.assertEqual(store.month_range("", today, "en")["label"], "November 2026")
|
||||
self.assertEqual(store.month_range("bad", today)["start"], date(2026, 11, 1))
|
||||
self.assertEqual(store.month_range("2026-13", today)["start"], date(2026, 11, 1))
|
||||
dec = store.month_range("2026-12", today)
|
||||
self.assertEqual((dec["start"], dec["end"], dec["prev"], dec["next"]), (date(2026, 12, 1), date(2027, 1, 1), "2026-11", "2027-01"))
|
||||
jan = store.month_range("2027-01", today)
|
||||
self.assertEqual((jan["end"], jan["prev"], jan["next"]), (date(2027, 2, 1), "2026-12", "2027-02"))
|
||||
|
||||
def test_format(self):
|
||||
self.assertEqual(store.fmt_date(date(2026, 11, 4)), "2026.11.04(수)")
|
||||
self.assertEqual(store.fmt_date(date(2026, 11, 4), "en"), "2026.11.04 (Wed)")
|
||||
self.assertEqual(store.fmt_times(time(20, 0), time(22, 30)), "20:00 ~ 22:30")
|
||||
self.assertEqual(store.fmt_times(time(20, 0), None), "20:00")
|
||||
self.assertEqual(store.fmt_money(Decimal("1234.5")), "1,234.50")
|
||||
self.assertEqual(store.fmt_money(None), "")
|
||||
|
||||
def test_session_pay(self):
|
||||
"""호스트 비용 = 시간 × RM 25 + 판매금액 10%. 받은 화면의 예: 2시간·판매 48 → 50 + 4.8."""
|
||||
p = store.session_pay(time(12, 0), time(14, 0), Decimal("48"))
|
||||
self.assertEqual((p["base"], p["commission"], p["fee"]), (Decimal("50.00"), Decimal("4.80"), Decimal("54.80")))
|
||||
self.assertEqual(store.session_pay(time(22, 0), time(0, 0), None)["fee"], Decimal("50.00")) # 자정까지
|
||||
self.assertEqual(store.session_pay(time(23, 0), time(1, 30), None)["base"], Decimal("62.50")) # 자정 넘김·30분
|
||||
self.assertEqual(store.session_pay(time(12, 0), None, Decimal("10"))["fee"], Decimal("1.00")) # 끝 시간 없음 = 기본 요금 없음
|
||||
self.assertEqual(store.session_pay(time(12, 0), time(14, 0), Decimal("0.05"))["commission"], Decimal("0.01")) # 반올림
|
||||
self.assertEqual((store.fmt_short(Decimal("48")), store.fmt_short(Decimal("4.80")), store.fmt_short(Decimal("1234.5"))), ("48", "4.80", "1,234.50"))
|
||||
|
||||
def test_moved_end(self):
|
||||
self.assertEqual(store.moved_end(time(12, 0), time(14, 30), time(20, 0)), time(22, 30))
|
||||
self.assertEqual(store.moved_end(time(12, 0), time(14, 0), time(22, 0)), time(0, 0)) # 자정으로 넘어감
|
||||
self.assertIsNone(store.moved_end(time(12, 0), None, time(20, 0)))
|
||||
self.assertEqual(store.parse_move("2026-11-04", "20:00"), (date(2026, 11, 4), time(20, 0)))
|
||||
for bad in (("", "20:00"), ("2026-11-04", ""), ("nope", "20:00")):
|
||||
with self.assertRaises(ValueError):
|
||||
store.parse_move(*bad)
|
||||
|
||||
def test_build_calendar(self):
|
||||
def b(id, day, start, end, sales=None, host=1, handle="yaya"):
|
||||
return {"id": id, "host_id": host, "host_name": "Yaya", "tiktok_handle": handle, "broadcast_date": day, "start_time": start,
|
||||
"end_time": end, "venue": "", "sales_amount": sales, "images": []}
|
||||
span = store.month_range("2026-11", date(2026, 11, 4))
|
||||
cal = store.build_calendar(span, [b(1, date(2026, 11, 4), time(12, 0), time(14, 0), Decimal("48")),
|
||||
b(2, date(2026, 11, 4), time(22, 0), time(0, 0), handle=""),
|
||||
b(3, date(2026, 11, 7), time(13, 30), time(15, 0))],
|
||||
{date(2026, 11, 4): Decimal("24")}, date(2026, 11, 4), "en")
|
||||
ko = store.build_calendar(span, [], {}, date(2026, 11, 4))
|
||||
self.assertEqual((ko["days"][3]["weekday"], ko["days"][3]["label"], ko["slot_note"]), ("수요일", "11월 4일", "2시간 (기본 RM50)"))
|
||||
self.assertEqual(len(cal["days"]), 30)
|
||||
self.assertEqual([s["label"] for s in cal["slots"]][0], "06:00 - 08:00")
|
||||
self.assertEqual([s["label"] for s in cal["slots"]][-1], "22:00 - 00:00")
|
||||
self.assertEqual(len(cal["slots"]), 9)
|
||||
self.assertEqual(cal["slot_note"], "2 Hours (RM50 Base)")
|
||||
d4 = cal["days"][3]
|
||||
self.assertEqual((d4["weekday"], d4["label"], d4["count"], d4["is_today"], d4["is_weekend"]), ("WEDNESDAY", "4 NOV", 2, True, False))
|
||||
self.assertEqual((d4["sales_text"], d4["spend_text"], d4["fee_text"], d4["roas"]), ("48", "24", "104.80", "2.00"))
|
||||
self.assertEqual(cal["days"][6]["is_weekend"], True) # 11-07 토
|
||||
self.assertEqual(cal["days"][0]["roas"], "-") # 광고비 없음
|
||||
noon = next(s for s in cal["slots"] if s["start"] == "12:00")
|
||||
self.assertEqual(noon["cells"][3]["cards"][0]["label"], "yaya") # 카드 머리 = Tiktok Handle
|
||||
self.assertEqual((noon["cells"][3]["cards"][0]["card_sales"], noon["cells"][3]["cards"][0]["card_commission"], noon["cells"][3]["cards"][0]["card_fee"]),
|
||||
("48", "4.80", "54.80"))
|
||||
late = next(s for s in cal["slots"] if s["start"] == "22:00")
|
||||
self.assertEqual((late["end"], late["cells"][3]["cards"][0]["label"]), ("00:00", "Yaya")) # 핸들 없으면 이름
|
||||
self.assertEqual(next(s for s in cal["slots"] if s["start"] == "12:00")["cells"][6]["cards"][0]["id"], 3) # 13:30 = 12~14 칸
|
||||
self.assertEqual(cal["totals"]["sales"], "48")
|
||||
# 06시보다 이른 칸은 방송이 있을 때만
|
||||
early = store.build_calendar(span, [b(9, date(2026, 11, 1), time(3, 0), time(5, 0))], {}, date(2026, 11, 4))
|
||||
self.assertEqual(early["slots"][0]["label"], "02:00 - 04:00")
|
||||
self.assertEqual(len(early["slots"]), 10)
|
||||
|
||||
def test_thumbnail(self):
|
||||
for mode, fmt in (("RGB", "JPEG"), ("RGBA", "PNG")):
|
||||
raw = io.BytesIO()
|
||||
Image.new(mode, (800, 400)).save(raw, format=fmt)
|
||||
with Image.open(io.BytesIO(store.thumbnail(raw.getvalue()))) as im:
|
||||
self.assertEqual((im.format, im.size), ("JPEG", (160, 80)))
|
||||
|
||||
|
||||
class I18nTests(unittest.TestCase):
|
||||
def test_every_text_has_english(self):
|
||||
"""템플릿·오류·권한 문구가 모두 영문 표에 있다 — 새 문구를 넣고 빠뜨리면 여기서 걸린다."""
|
||||
live = ROOT / "app" / "modules" / "live"
|
||||
keys = set(i18n.JS_KEYS) | set(store._LABELS.values()) | {"시작 시간", "끝 시간"}
|
||||
for path in (live / "templates" / "live").glob("*.html"):
|
||||
keys |= set(re.findall(r"\bt\('([^']+)'\)", path.read_text(encoding="utf-8")))
|
||||
for name in ("store.py", "db.py", "router.py"):
|
||||
text = (live / name).read_text(encoding="utf-8")
|
||||
keys |= set(re.findall(r'LiveError\("([^"]+)"', text))
|
||||
keys |= set(re.findall(r'_t\(request, "([^"]+)"\)', text))
|
||||
keys |= set(re.findall(r'_ok\(request, "([^"]+)"\)', text))
|
||||
keys |= set(re.findall(r'raise ValueError\("([^"]+)"', text))
|
||||
keys |= set(re.findall(r'ValueError\("([^"]+)"', (ROOT / "app" / "modules" / "asset" / "media.py").read_text(encoding="utf-8")))
|
||||
self.assertGreater(len(keys), 80)
|
||||
self.assertEqual(sorted(k for k in keys if k not in i18n.EN), [])
|
||||
self.assertEqual(sorted(k for k, v in i18n.EN.items() if re.search("[가-힣]", v)), [])
|
||||
|
||||
def test_error_text(self):
|
||||
err = i18n.LiveError("{label} 이(가) 너무 깁니다({limit}자까지).", label="이메일", limit=254)
|
||||
self.assertEqual(str(err), "이메일 이(가) 너무 깁니다(254자까지).")
|
||||
self.assertEqual(i18n.error_text(err, "en"), "Email is too long (up to 254 characters).")
|
||||
self.assertEqual(i18n.error_text(err, "ko"), str(err))
|
||||
self.assertEqual(i18n.error_text(ValueError("잘못된 요청입니다."), "en"), "Invalid request.")
|
||||
nested = i18n.LiveError("{name}: {detail}", name="a{b}.jpg", detail="JPG, PNG, WebP 사진만 등록할 수 있습니다.")
|
||||
self.assertEqual(nested.text("en"), "a{b}.jpg: Only JPG, PNG and WebP images are allowed.")
|
||||
self.assertEqual((i18n.norm_lang("en"), i18n.norm_lang("ko"), i18n.norm_lang("<x>"), i18n.norm_lang(None)), ("en", "ko", "ko", "ko"))
|
||||
|
||||
|
||||
class WebTests(unittest.TestCase):
|
||||
def test_main_card_title_both_languages(self):
|
||||
res = _run('''
|
||||
def body(c):
|
||||
who["u"] = U("a@test.local", role="admin")
|
||||
page = c.get("/modules").text # 카드 화면(수퍼관리자 홈과 같은 main.html)
|
||||
assert "라이브 커머스 · Live Commerce" in page, page[:300]
|
||||
nav = [i for i in main.build_erp_nav(who["u"], active="live") if i["key"] == "live"]
|
||||
assert nav and nav[0]["label"] == "라이브 커머스" # 사이드바는 짧게
|
||||
print("OK")
|
||||
run(body)
|
||||
''')
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
def test_registered_and_unconfigured(self):
|
||||
res = _run('''
|
||||
from app.store import MODULE_KEYS
|
||||
assert "live" in MODULE_KEYS and main.MODULE_LABELS["live"] == "라이브 커머스"
|
||||
|
||||
def body(c):
|
||||
who["u"] = U("a@test.local", role="admin")
|
||||
assert c.get("/live/health").json() == {"status": "not_configured"}
|
||||
r = c.get("/live/")
|
||||
assert r.status_code == 503 and "LIVE_DB_URL" in r.text and "라이브 커머스" in r.text, r.status_code
|
||||
assert c.post("/live/broadcasts", data={}).status_code == 503
|
||||
who["u"] = U("b@test.local", live=False)
|
||||
assert c.get("/live/").status_code == 403
|
||||
assert c.post("/live/broadcasts", data={}).status_code == 403
|
||||
assert c.get("/live/images/1").status_code == 403
|
||||
print("OK")
|
||||
run(body)
|
||||
''')
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
@unittest.skipUnless(DB_ENABLED, "LIVE_TEST_DB_URL(localhost) not set")
|
||||
def test_full_flow(self):
|
||||
res = _run('''
|
||||
import io, re, uuid
|
||||
from PIL import Image
|
||||
from app.modules.live.db import LiveDBStore
|
||||
st = LiveDBStore(__import__("os").environ["LIVE_TEST_DB_URL"])
|
||||
main.app.state.live_store = st
|
||||
tag = uuid.uuid4().hex[:8]
|
||||
admin, staff, outsider = U("admin-%s@t.local" % tag, role="admin"), U("staff-%s@t.local" % tag), U("out-%s@t.local" % tag, live=False)
|
||||
ACCOUNT = "9988%s" % int(tag, 16)
|
||||
NAME = "Siti <b>" + tag
|
||||
|
||||
def jpeg():
|
||||
raw = io.BytesIO()
|
||||
exif = Image.Exif(); exif[0x010F] = "SECRET-CAMERA"
|
||||
Image.new("RGB", (3000, 1500), "red").save(raw, format="JPEG", exif=exif)
|
||||
return raw.getvalue()
|
||||
|
||||
def body(c):
|
||||
host = {"full_name": NAME, "phone": "+60 12-345", "email": "siti@example.my", "address": "Kuala Lumpur",
|
||||
"bank_name": "Maybank", "bank_account": ACCOUNT, "tiktok_handle": "@siti.%s" % tag, "is_active": "1"}
|
||||
# ── 호스트 설정 = ERP 관리자만 ──
|
||||
who["u"] = staff
|
||||
assert c.get("/live/settings").status_code == 403
|
||||
assert c.post("/live/settings/hosts", data=host).status_code == 403
|
||||
assert c.post("/live/settings/hosts/1/delete").status_code == 403
|
||||
assert 'href="/live/settings"' not in c.get("/live/").text
|
||||
who["u"] = admin
|
||||
bad = c.post("/live/settings/hosts", data={**host, "email": "nope"})
|
||||
assert bad.status_code == 400 and "이메일" in bad.json()["message"]
|
||||
r = c.post("/live/settings/hosts", data=host)
|
||||
assert r.json()["ok"], r.text
|
||||
hid = next(h["id"] for h in st.list_hosts() if h["full_name"] == NAME)
|
||||
page = c.get("/live/settings").text
|
||||
for field in ("이름 (IC 기준)", "전화번호", "이메일", "주소", "은행명", "계좌번호", "틱톡 핸들"):
|
||||
assert field in page, field
|
||||
assert ACCOUNT in page and "Siti <b>" in page and "<b>" + tag not in page
|
||||
assert st.list_hosts() and next(h for h in st.list_hosts() if h["id"] == hid)["tiktok_handle"] == "siti." + tag
|
||||
|
||||
# ── 스케줄: 일반 권한자도 추가·고치기, 화면에 계좌·주소 없음 ──
|
||||
who["u"] = staff
|
||||
page = c.get("/live/?month=2031-03").text
|
||||
assert 'value="%d"' % hid in page and "@siti." + tag in page
|
||||
assert ACCOUNT not in page and "Kuala Lumpur" not in page and "Maybank" not in page
|
||||
show = {"host_id": hid, "broadcast_date": "2031-03-05", "start_time": "20:00", "end_time": "22:30", "venue": "KL Studio", "sales_amount": "1,234.5"}
|
||||
assert c.post("/live/broadcasts", data={**show, "host_id": ""}).status_code == 400
|
||||
assert c.post("/live/broadcasts", data={**show, "host_id": 99999999}).status_code == 400
|
||||
junk = c.post("/live/broadcasts", data=show, files=[("images", ("x.jpg", b"not an image", "image/jpeg"))])
|
||||
assert junk.status_code == 400 and "x.jpg" in junk.json()["message"]
|
||||
assert "KL Studio" not in c.get("/live/?month=2031-03").text # 이미지가 틀리면 방송도 저장 안 됨
|
||||
r = c.post("/live/broadcasts", data=show, files=[("images", ("../../evil.jpg", jpeg(), "image/jpeg"))])
|
||||
assert r.json()["ok"], r.text
|
||||
page = c.get("/live/?month=2031-03").text
|
||||
assert "2031.03.05(수)" in page and "20:00 ~ 22:30" in page and "KL Studio" in page and "1,234.50" in page
|
||||
assert ">123.45</td>" in page and ">185.95</td>" in page # 커미션 10%·호스트 비용(2.5시간 × 25 + 123.45)
|
||||
assert "KL Studio" not in c.get("/live/?month=2031-04").text
|
||||
row = st.list_broadcasts(__import__("datetime").date(2031, 3, 1), __import__("datetime").date(2031, 4, 1))
|
||||
row = next(b for b in row if b["host_id"] == hid)
|
||||
bid, img = row["id"], row["images"][0]
|
||||
assert img["filename"] == "evil.jpg" and len(row["images"]) == 1 # 파일 이름의 경로 제거
|
||||
|
||||
# ── 이미지: 크기 줄임·EXIF 제거·권한 ──
|
||||
r = c.get("/live/images/%d" % img["id"])
|
||||
assert r.status_code == 200 and r.headers["content-type"] == "image/jpeg" and "private" in r.headers["cache-control"]
|
||||
assert b"SECRET-CAMERA" not in r.content
|
||||
assert Image.open(io.BytesIO(r.content)).size == (2400, 1200)
|
||||
assert Image.open(io.BytesIO(c.get("/live/images/%d?thumb=1" % img["id"]).content)).size == (160, 80)
|
||||
assert c.get("/live/images/99999999").status_code == 404
|
||||
who["u"] = outsider
|
||||
assert c.get("/live/images/%d" % img["id"]).status_code == 403
|
||||
assert c.post("/live/images/%d/delete" % img["id"]).status_code == 403
|
||||
who["u"] = staff
|
||||
|
||||
# ── 고치기: 값 바뀜, 이미지 유지 + 더하기, 판매금액 지우기, 10장 제한 ──
|
||||
r = c.post("/live/broadcasts", data={**show, "id": bid, "venue": "PJ Studio", "sales_amount": "", "end_time": "21:00"})
|
||||
assert r.json()["ok"], r.text
|
||||
page = c.get("/live/?month=2031-03").text
|
||||
assert "PJ Studio" in page and "1,234.50" not in page and "20:00 ~ 21:00" in page
|
||||
assert c.post("/live/broadcasts", data={**show, "end_time": ""}).status_code == 400 # 끝 시간 필수
|
||||
|
||||
# ── 달력: 카드 머리 = Tiktok Handle, Fee, 옮기기(길이 유지)·맞바꾸기, 광고비·ROAS, 권한 ──
|
||||
c.post("/live/broadcasts", data={**show, "id": bid, "sales_amount": "48", "start_time": "12:00", "end_time": "14:00", "broadcast_date": "2031-03-05"})
|
||||
cal = c.get("/live/calendar?month=2031-03").text
|
||||
assert "날짜로 이동" in cal and "토요일" in cal and "12:00 - 14:00" in cal and "2시간 (기본 RM50)" in cal
|
||||
assert '<span class="lv-card-name">siti.%s</span>' % tag in cal and "RM54.80" in cal and ">4.80</b>" in cal
|
||||
|
||||
# ── 영문: 화면 세 개 모두 한글 없음(입력한 데이터 제외)·날짜·오류·권한 문구 ──
|
||||
def no_korean(url):
|
||||
page = c.get(url).text
|
||||
assert 'class="lv-lang"' in page and "window.LV_T" in page
|
||||
part = page[page.index('<section class="lv"'):page.index("</dialog>")].replace(">한글<", "><") # 화면 + 창(공용 셸 제외)
|
||||
left = re.findall("[가-힣][^<>\\"]*", part)
|
||||
assert not left, (url, left[:5])
|
||||
return page
|
||||
c.cookies.set("live_lang", "en")
|
||||
page = no_korean("/live/?month=2031-03")
|
||||
assert 'lang="en"' in page and "March 2031" in page and "2031.03.05 (Wed)" in page and "Commission 10% (RM)" in page
|
||||
cal = no_korean("/live/calendar?month=2031-03")
|
||||
assert "Jump to Date" in cal and "SATURDAY" in cal and "1 MAR" in cal and "2 Hours (RM50 Base)" in cal and ">Sales<" in cal and "Com (10%)" in cal and "Fee: <b>RM54.80" in cal
|
||||
assert "Total Sales:" in cal and "Ad Spend:" in cal and "Host Fee:" in cal and "Total & ROAS" in cal
|
||||
assert c.post("/live/broadcasts", data={**show, "id": bid, "sales_amount": "abc"}).json()["message"] == "Sales must be a number."
|
||||
assert c.post("/live/broadcasts", data={**show, "id": bid, "end_time": ""}).json()["message"] == "Enter the End Time."
|
||||
junk = c.post("/live/broadcasts", data=show, files=[("images", ("x.jpg", b"not an image", "image/jpeg"))]).json()["message"]
|
||||
assert junk == "x.jpg: The image can't be read. Please choose a valid JPG, PNG or WebP file.", junk
|
||||
assert c.post("/live/settings/hosts", data=host).json()["detail"] == "Only ERP admins can view host information."
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "1"}).json()["message"] == "Ad spend saved."
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": ""}).json()["ok"]
|
||||
who["u"] = admin
|
||||
page = no_korean("/live/settings")
|
||||
for field in ("Full Name (as per IC)", "Phone Number", "Email", "Address", "Bank Name", "Bank Account Number", "Tiktok Handle"):
|
||||
assert field in page, field
|
||||
who["u"] = staff
|
||||
c.cookies.set("live_lang", "<bad>") # 모르는 값 = 한글
|
||||
assert "2031년 3월" in c.get("/live/?month=2031-03").text
|
||||
c.cookies.delete("live_lang")
|
||||
assert ACCOUNT not in cal and "Maybank" not in cal
|
||||
day = __import__("datetime").date
|
||||
def one(i):
|
||||
return next(b for b in st.list_broadcasts(day(2031, 3, 1), day(2031, 4, 1)) if b["id"] == i)
|
||||
assert c.post("/live/broadcasts/%d/move" % bid, data={"broadcast_date": "2031-03-07", "start_time": "22:00"}).json()["ok"]
|
||||
got = one(bid)
|
||||
assert (got["broadcast_date"], str(got["start_time"]), str(got["end_time"])) == (day(2031, 3, 7), "22:00:00", "00:00:00")
|
||||
assert c.post("/live/broadcasts/%d/move" % bid, data={"broadcast_date": "bad", "start_time": "22:00"}).status_code == 400
|
||||
assert c.post("/live/broadcasts/99999999/move", data={"broadcast_date": "2031-03-07", "start_time": "22:00"}).status_code == 400
|
||||
c.post("/live/broadcasts", data={**show, "broadcast_date": "2031-03-09", "start_time": "08:00", "end_time": "09:00", "venue": "Second"})
|
||||
other = next(b["id"] for b in st.list_broadcasts(day(2031, 3, 9), day(2031, 3, 10)) if b["venue"] == "Second")
|
||||
assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": other}).json()["ok"]
|
||||
a, b2 = one(bid), one(other)
|
||||
assert (a["broadcast_date"], str(a["start_time"]), str(a["end_time"])) == (day(2031, 3, 9), "08:00:00", "09:00:00")
|
||||
assert (b2["broadcast_date"], str(b2["start_time"]), str(b2["end_time"])) == (day(2031, 3, 7), "22:00:00", "00:00:00")
|
||||
assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": 99999999}).status_code == 400
|
||||
assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": bid}).json()["ok"]
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "24"}).json()["ok"]
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "12"}).json()["ok"] # 덮어쓰기
|
||||
assert st.ad_spends(day(2031, 3, 1), day(2031, 4, 1)) == {day(2031, 3, 9): __import__("decimal").Decimal("12.00")}
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "-1"}).status_code == 400
|
||||
assert c.post("/live/ad-spend", data={"day": "bad", "amount": "1"}).status_code == 400
|
||||
assert "4.00" in c.get("/live/calendar?month=2031-03").text # ROAS 48 ÷ 12
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": ""}).json()["ok"] # 빈칸 = 지우기
|
||||
assert st.ad_spends(day(2031, 3, 1), day(2031, 4, 1)) == {}
|
||||
assert c.post("/live/broadcasts/%d/delete" % other).json()["ok"]
|
||||
c.post("/live/broadcasts", data={**show, "id": bid}) # 아래 시험을 위해 원래 값으로
|
||||
who["u"] = outsider
|
||||
assert c.get("/live/calendar").status_code == 403
|
||||
assert c.post("/live/broadcasts/%d/move" % bid, data={"swap_with": bid}).status_code == 403
|
||||
assert c.post("/live/ad-spend", data={"day": "2031-03-09", "amount": "1"}).status_code == 403
|
||||
who["u"] = staff
|
||||
many = [("images", ("%d.jpg" % i, jpeg(), "image/jpeg")) for i in range(10)]
|
||||
r = c.post("/live/broadcasts", data={**show, "id": bid}, files=many)
|
||||
assert r.status_code == 400 and "10장" in r.json()["message"], r.text # 이미 1장 + 10장
|
||||
assert c.post("/live/broadcasts", data={**show, "id": 99999999}).status_code == 400
|
||||
assert c.post("/live/broadcasts", data={**show, "id": "x"}).status_code == 400
|
||||
|
||||
# ── 호스트: 방송이 있으면 못 지움, 사용 안 함이면 새 방송 불가·기존 방송 고치기는 가능 ──
|
||||
who["u"] = admin
|
||||
r = c.post("/live/settings/hosts/%d/delete" % hid)
|
||||
assert r.status_code == 400 and "사용 안 함" in r.json()["message"]
|
||||
assert c.post("/live/settings/hosts", data={**host, "id": hid, "is_active": ""}).json()["ok"]
|
||||
who["u"] = staff
|
||||
assert 'data-inactive="1"' in c.get("/live/?month=2031-03").text
|
||||
r = c.post("/live/broadcasts", data=show)
|
||||
assert r.status_code == 400 and "사용 안 함" in r.json()["message"]
|
||||
assert c.post("/live/broadcasts", data={**show, "id": bid}).json()["ok"]
|
||||
|
||||
# ── 지우기: 이미지 하나, 방송(이미지도), 그 뒤 호스트 ──
|
||||
assert c.post("/live/images/%d/delete" % img["id"]).json()["ok"]
|
||||
assert c.get("/live/images/%d" % img["id"]).status_code == 404
|
||||
assert c.post("/live/broadcasts", data={**show, "id": bid}, files=[("images", ("a.png", jpeg(), "image/jpeg"))]).json()["ok"]
|
||||
assert c.post("/live/broadcasts/%d/delete" % bid).json()["ok"]
|
||||
assert c.post("/live/broadcasts/%d/delete" % bid).status_code == 400
|
||||
who["u"] = admin
|
||||
assert c.post("/live/settings/hosts/%d/delete" % hid).json()["ok"]
|
||||
assert c.post("/live/settings/hosts/%d/delete" % hid).status_code == 400
|
||||
print("OK")
|
||||
run(body)
|
||||
''', {"LIVE_TEST_DB_URL": DSN})
|
||||
self.assertEqual(res.returncode, 0, res.stdout + res.stderr)
|
||||
self.assertIn("OK", res.stdout)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user