feat(말레이시아 실적): 한글·영문 전환 + OS 언어 기본값
- 말레이시아 실적 탭 줄에 [한글|EN] 토글(쿠키 mperf_lang), 고른 적 없으면 브라우저·OS 첫 언어(Accept-Language) ko → 한글, 그 밖 → 영어(app/lang.py) - 영문이면 performance-en.js(사전·패턴·낱말 치환, 창·알림까지) — 한국 실적 화면은 그대로 - 말레이시아 실적 공휴일 = 말레이시아 공휴일(live/holidays.py, 화면 언어로) - 라이브 커머스·말레이시아 재고도 같은 기본 언어 규칙 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -68,6 +68,7 @@
|
||||
- `asset/media.py prepare_photo`(이미지 확인·메타데이터 제거): 자산 + 라이브 커머스.
|
||||
- `app/mail.py`: 프로젝트 알림 메일.
|
||||
- ERP 모든 화면 스크립트: `erp-notice.js`(공지) · `erp-overdue.js`(프로젝트 마감 알림).
|
||||
- 한영 전환 기본 언어 `app/lang.py`(고른 값 없으면 브라우저·OS 언어 ko → 한글, 그 밖 → 영어): 말레이시아 실적 + 라이브 커머스(서버) + 말레이시아 재고(`malaysia.js` 같은 규칙). 말레이시아 공휴일 `live/holidays.py`: 라이브 + 말레이시아 실적.
|
||||
- 아사나식 날짜 팝업: 프로젝트(`project.js` 안) + 공용 복사본 `erp-datepop.js/css`(휴가 신청·입출고 날짜 칸·라이브 오른쪽 달력) — 바꾸면 둘 다.
|
||||
- 국경일·대체공휴일 표 `project/store.py KR_HOLIDAYS`: 프로젝트 캘린더·날짜 팝업 + 휴가(달력·일수 계산 `vacation/db.holiday_map`) + 입출고(오른쪽 달력·날짜 칸).
|
||||
|
||||
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
"""한글·영문 화면 언어 고르기(2026-11-20) — 한영 전환이 있는 모듈 공통(말레이시아 실적·라이브 커머스).
|
||||
|
||||
사용자가 토글로 고른 값(쿠키)이 있으면 그것, 없으면 접속한 브라우저의 첫 언어(Accept-Language — 보통 OS 기본 언어)가
|
||||
한국어(ko…)면 한국어, 그 밖의 언어면 영어. 머리글이 없으면(스크립트·테스트) 한국어.
|
||||
말레이시아 재고관리는 화면 스크립트(malaysia.js)가 같은 규칙을 navigator.language 로 쓴다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
def detect_lang(chosen: Any, accept_language: str | None) -> str:
|
||||
if chosen in ("ko", "en"):
|
||||
return chosen
|
||||
first = (accept_language or "").split(",")[0].split(";")[0].strip().lower()
|
||||
if not first or first == "*":
|
||||
return "ko"
|
||||
return "ko" if first.startswith("ko") else "en"
|
||||
@@ -33,6 +33,6 @@
|
||||
`GET /live/images/{id}`(권한 필요, 하루 private 캐시), `?thumb=1` = 160px JPEG(그때그때 만듦). 올린 뒤 내용이 안 바뀐다는 전제 — 이미지를 고치는 기능을 넣으면 캐시도 바꿀 것.
|
||||
- 라이브 커머스 화면은 공용 최대 폭(1550px)을 풀어 **화면 전체 너비**를 쓴다(`live.css` 맨 위, 스케줄표·달력·호스트 설정).
|
||||
- 저장은 `live.js` 가 fetch → JSON `{ok, message}`(틀려도 창의 입력값 유지). 창 하나로 추가·고치기(`data-edit` JSON).
|
||||
- **한글·영문 전환**(`i18n.py`) — 위 막대 [한글|EN], 쿠키 `live_lang`(브라우저마다, path=/live, 기본 한글). 한글 문구가 키, 템플릿 `t('…')`, 오류 `LiveError(틀, 값)`(라우터가 언어에 맞게), JS `LV_T`(`JS_KEYS`).
|
||||
- **한글·영문 전환**(`i18n.py`) — 위 막대 [한글|EN], 쿠키 `live_lang`(브라우저마다, path=/live). 고른 적 없으면 브라우저·OS 첫 언어가 ko… → 한글, 그 밖 → 영어(2026-11-20, `app/lang.py detect_lang`, 말레이시아 실적과 같은 규칙). 한글 문구가 키, 템플릿 `t('…')`, 오류 `LiveError(틀, 값)`(라우터가 언어에 맞게), JS `LV_T`(`JS_KEYS`).
|
||||
**새 문구는 `i18n.EN` 에도 넣는다** — `tests/test_live.py` 가 빠진 문구와 영문 화면의 한글을 잡는다. 입력한 데이터(이름·장소 등)·ERP 공용 사이드바는 번역하지 않는다.
|
||||
- 메인 카드 제목 = `main.py` `card_title`(한글·영문), 사이드바는 `title` 그대로.
|
||||
|
||||
@@ -35,7 +35,9 @@ def _store(request: Request) -> Any:
|
||||
|
||||
|
||||
def _lang(request: Request) -> str:
|
||||
return i18n.norm_lang(request.cookies.get(i18n.LANG_COOKIE))
|
||||
from app.lang import detect_lang # noqa: WPS433 — 고른 값(쿠키) 없으면 브라우저·OS 언어(2026-11-20)
|
||||
|
||||
return detect_lang(request.cookies.get(i18n.LANG_COOKIE), request.headers.get("accept-language"))
|
||||
|
||||
|
||||
def _t(request: Request, text: str) -> str:
|
||||
|
||||
@@ -32,4 +32,4 @@
|
||||
<div style="display:flex;justify-content:flex-end;margin-bottom:8px;">
|
||||
<button type="button" id="mys-lang-toggle" class="erp-btn erp-btn-outline">ENG</button>
|
||||
</div>
|
||||
<script src="/static/malaysia.js?v=20260622a"></script>
|
||||
<script src="/static/malaysia.js?v=20261120a"></script>
|
||||
|
||||
@@ -26,6 +26,16 @@
|
||||
|
||||
- 쇼핑몰 표(사용·매출 집계·수동 입력·수수료율·이름·그룹·순서·추가/삭제) + 보기 설정 + 공통 보기 설정(열 숨기기). API 인증·광고 API·자동 업데이트·암호화 키·과거 매출·테스트 데이터 카드 없음, 매출 단위 = RM 고정.
|
||||
|
||||
## 한글·영문 전환 (2026-11-20)
|
||||
|
||||
- 탭 줄 오른쪽(톱니 왼쪽) [한글|EN] — 쿠키 `mperf_lang`(path=/malaysia/performance). 고른 적 없으면 브라우저·OS 첫 언어(`Accept-Language`) ko… → 한글, 그 밖 → 영어(`app/lang.py`, 라이브·말레이시아 재고도 같은 규칙).
|
||||
- 서버가 언어를 정한다: `variant.use_malaysia` 가 `variant.lang()` 설정 → 템플릿 `lang`, `.perf data-lang`, 머리 제목(`common.base_ctx`), 공휴일(말레이시아 — `live/holidays.py` 공유).
|
||||
- 영문이면 `static/performance-en.js` 를 performance.js 앞에 싣는다 — 한국 실적과 같은 템플릿·JS 라 **한글을 그대로 그린 뒤 바꾼다**
|
||||
(사전 `EN` · 패턴 `RULES` · 낱말 `PHRASES`, 나중에 생기는 창·메뉴·알림까지). 번역이 끝날 때까지 `.perf` 숨김(못 실으면 1.5초 뒤 보임).
|
||||
굵은 글자 섞인 긴 안내 문단은 템플릿에 `{% if lang == 'en' %}` 로 따로 썼다.
|
||||
- **실적 화면 문구를 새로 넣거나 바꾸면 `performance-en.js` 에도** — `tests/js/perf_malaysia_en.browser.test.js` 가 영문 화면·창·알림에 한글이 남았는지 찍어 준다.
|
||||
- 쇼핑몰 이름(DB 값)은 낱말 치환(틱톡·쇼피·라자다·쇼핑몰·라이브커머스) — 다른 이름으로 바꾸면 그 이름은 한글 그대로일 수 있다.
|
||||
|
||||
## DB
|
||||
|
||||
- `malaysia_performance_db` = performance_db **구조만 복사**(`pg_dump --schema-only`) + seed. 역할 `performance_app` 공유. 만드는 순서는 seed 파일 머리말.
|
||||
|
||||
@@ -132,12 +132,17 @@ def base_ctx(user: dict[str, Any], *, active_tab: str, page_title: str = "") ->
|
||||
v = variant.current()
|
||||
if not v.is_kr and page_title:
|
||||
page_title = f"말레이시아 {page_title}"
|
||||
subtitle = "쇼핑몰 통합 매출" if v.is_kr else "틱톡·쇼피·라자다 매출"
|
||||
if variant.lang() == "en": # 말레이시아 실적 영문 — 화면 머리 제목(나머지 글자는 performance-en.js)
|
||||
page_title = {"말레이시아 광고비": "Malaysia Ad Spend", "말레이시아 실적 설정": "Malaysia Sales Settings"}.get(
|
||||
page_title, "Malaysia Sales")
|
||||
subtitle = "TikTok · Shopee · Lazada sales"
|
||||
return {
|
||||
"user": user,
|
||||
"is_admin": is_admin(user),
|
||||
"nav_items": build_erp_nav(user, active=v.module_key),
|
||||
"active_tab": active_tab,
|
||||
"page_title": page_title or v.module_name,
|
||||
"page_subtitle": "쇼핑몰 통합 매출" if v.is_kr else "틱톡·쇼피·라자다 매출",
|
||||
"page_subtitle": subtitle,
|
||||
**variant.template_ctx(),
|
||||
}
|
||||
|
||||
@@ -96,6 +96,10 @@ def _parse_date(value: Any, *, field: str = "날짜") -> date | None:
|
||||
|
||||
|
||||
def _holidays() -> dict[str, str]:
|
||||
if not variant.current().is_kr: # 말레이시아 실적 — 말레이시아 공휴일(라이브 커머스 표 공유, 화면 언어로)
|
||||
from app.modules.live.holidays import holiday_names # noqa: WPS433
|
||||
|
||||
return holiday_names(variant.lang())
|
||||
try:
|
||||
from app.modules.project.store import KR_HOLIDAYS # noqa: WPS433 — 공휴일 표 공유(읽기 전용)
|
||||
|
||||
|
||||
@@ -10,6 +10,13 @@
|
||||
role="tab" aria-selected="{{ 'true' if active_tab == 'ads' else 'false' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">campaign</span>광고비</a>
|
||||
</div>
|
||||
{% if not pv.is_kr %}
|
||||
{#- 한글·영문 전환(2026-11-20, 말레이시아 실적만) — 누르면 쿠키(mperf_lang)에 저장하고 다시 그린다(performance.js). 고른 적 없으면 브라우저·OS 언어 -#}
|
||||
<div class="perf-lang" role="group" aria-label="Language" translate="no">
|
||||
<button type="button" data-perf-lang="ko"{% if lang != 'en' %} class="is-active" aria-pressed="true"{% else %} aria-pressed="false"{% endif %}>한글</button>
|
||||
<button type="button" data-perf-lang="en"{% if lang == 'en' %} class="is-active" aria-pressed="true"{% else %} aria-pressed="false"{% endif %}>EN</button>
|
||||
</div>
|
||||
{% endif %}
|
||||
<a class="perf-tab-gear{% if active_tab == 'settings' %} is-active{% endif %}" href="{{ pv.base }}/settings"
|
||||
title="{{ '실적 설정' if is_admin else '수수료 설정' }}" aria-label="{{ '실적 설정' if is_admin else '수수료 설정' }}">
|
||||
<span class="material-symbols-outlined" aria-hidden="true">settings</span></a>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261120a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261120b" />{% endblock %}
|
||||
|
||||
{#- ROAS 덧붙임 — "광고비(ROAS%)". 광고비가 없으면 아무것도 안 붙는다. -#}
|
||||
{%- macro roas(p) -%}{%- if p is not none -%}<span class="perf-roas">({{ "{:,}".format(p) }}%)</span>{%- endif -%}{%- endmacro -%}
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
{% block content %}
|
||||
{#- 광고비 — 매출 실적과 같은 기간 이동·표·그래프. 날짜 칸을 눌러 직접 입력(파란 숫자), 업로드로 들어온 값은 주황 숫자. -#}
|
||||
<section class="perf perf-ads" id="perf-dash" data-metric="gross" data-fixed-metric="gross" data-base="{{ pv.base }}"{% if pv.scale != 1 %} data-cents="1"{% endif %}>
|
||||
<section class="perf perf-ads" id="perf-dash" data-metric="gross" data-fixed-metric="gross" data-base="{{ pv.base }}"{% if pv.scale != 1 %} data-cents="1"{% endif %} data-lang="{{ lang }}">
|
||||
{% include "performance/_tabs.html" %}
|
||||
|
||||
<div class="perf-toolbar">
|
||||
@@ -120,6 +120,10 @@
|
||||
네이버는 광고 보고서의 ROAS(구매완료 광고수익률), 구글은 구글 광고 API 의 ROAS(전환 가치 ÷ 비용)를 씁니다 — 네이버·구글·메타 머리글을 누르면 일자별 보고서 항목.
|
||||
파란 숫자 = 직접 입력, 파랑 굵은 숫자 = 계산식(1000+2000 처럼 = 없이 입력하면 바로 계산), 주황 숫자 = 파일 업로드 값, 초록 숫자 = 광고 API 값. 쿠팡(윙)·쿠팡(로켓)·네이버는 [파일 업로드]로 광고 보고서를 올리면 날짜별로 한 번에 들어갑니다.
|
||||
구글·메타는 [구글 광고 불러오기]·[메타 광고 불러오기](관리자가 실적 설정 → 광고 API 연동을 마친 뒤) 또는 매출 자동 업데이트 때 들어옵니다.</p>
|
||||
{% elif lang == 'en' %}
|
||||
<p class="perf-muted perf-manual-help">Click a date cell to enter that day's <b>ad spend</b> (RM, 2 decimals) — Enter saves and moves down, Esc cancels, saving an empty cell clears it.
|
||||
Cells show <b>ad spend (ROAS%)</b> — ROAS = that marketplace's (shop + live commerce) gross sales ÷ ad spend (total column = all sales).
|
||||
Blue = entered value, bold blue = formula (type 10.5+20 without = and it is calculated).</p>
|
||||
{% else %}
|
||||
<p class="perf-muted perf-manual-help">날짜 칸을 눌러 그날 <b>광고비</b>(RM, 소수 2자리)를 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소, 비우고 저장하면 지움.
|
||||
칸은 <b>광고비(ROAS%)</b> — ROAS = 그 쇼핑몰(쇼핑몰 + 라이브커머스) 매출 실적 총매출 ÷ 광고비(합계 열은 전체 매출).
|
||||
@@ -208,6 +212,10 @@
|
||||
매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
|
||||
구글·메타는 [광고비 업데이트]·자동 업데이트(매출과 같은 시각)로 광고 API 에서 가져옵니다.
|
||||
</p>
|
||||
{% elif lang == 'en' %}
|
||||
<p class="perf-foot perf-muted">
|
||||
Amounts in RM. ROAS = that marketplace's (shop + live commerce) sales ÷ ad spend × 100. Ad spend to sales = ad spend ÷ gross sales of the same period.
|
||||
</p>
|
||||
{% else %}
|
||||
<p class="perf-foot perf-muted">
|
||||
금액 단위 RM. ROAS = 그 쇼핑몰(쇼핑몰 + 라이브커머스) 매출 ÷ 광고비 × 100. 매출 대비 광고비 = 같은 기간 광고비 ÷ 매출 실적 총매출.
|
||||
@@ -235,4 +243,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261120a" defer></script>{% endblock %}
|
||||
{% block scripts %}{% if lang == 'en' %}<script src="/static/performance-en.js?v=20261120a" defer></script>{% endif %}<script src="/static/performance.js?v=20261120b" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261120a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261120b" />{% endblock %}
|
||||
|
||||
{%- macro won(v) -%}
|
||||
{%- if v is none -%}<span class="perf-na"></span>
|
||||
@@ -30,7 +30,7 @@
|
||||
{%- endmacro -%}
|
||||
|
||||
{% block content %}
|
||||
<section class="perf" id="perf-dash" data-metric="{{ metric }}" data-base="{{ pv.base }}"{% if pv.scale != 1 %} data-cents="1"{% endif %}>
|
||||
<section class="perf" id="perf-dash" data-metric="{{ metric }}" data-base="{{ pv.base }}"{% if pv.scale != 1 %} data-cents="1"{% endif %} data-lang="{{ lang }}">
|
||||
{% include "performance/_tabs.html" %}
|
||||
|
||||
<!-- ── 기간 · 필터 · 업데이트 ── -->
|
||||
@@ -194,7 +194,11 @@
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{% if manual_codes and period_kind != 'year' %}
|
||||
{% if manual_codes and period_kind != 'year' and lang == 'en' %}
|
||||
<p class="perf-muted perf-manual-help">Click a date cell of a ✎ column to enter its <b>gross sales</b> (RM) — Enter saves and moves down, Esc cancels,
|
||||
saving an empty cell clears it. Type a formula without = such as <b>10.5+20</b> and it is calculated. Blue = entered value, bold blue = formula.
|
||||
Commission uses the rate of that day; totals and charts are recalculated when you finish entering.</p>
|
||||
{% elif manual_codes and period_kind != 'year' %}
|
||||
<p class="perf-muted perf-manual-help">✎ 표시 쇼핑몰은 날짜 칸을 눌러 <b>총매출</b>을 직접 입력합니다 — Enter 저장 후 아래 칸, Esc 취소,
|
||||
비우고 저장하면 {% if pv.is_kr %}다시 API 수집값{% else %}지움{% endif %}. <b>{{ '1000+2000' if pv.is_kr else '10.5+20' }}</b> 처럼 = 없이 계산식을 넣으면 바로 계산됩니다. 파란 숫자 = 수동 입력값, 파랑 굵은 숫자 = 계산식. 수수료는 그날 수수료율로 계산되고, 입력을 마치면 합계·그래프가 다시 계산됩니다.</p>
|
||||
{% endif %}
|
||||
@@ -286,6 +290,11 @@
|
||||
일·쇼핑몰 단위로 원 미만 반올림합니다. 금액을 누르면 주문 목록을 볼 수 있습니다.
|
||||
일 합계·상단 금액·그래프·누적 = 카페24(실적) + 자사몰(공동구매) + 나머지 쇼핑몰(카페24(전체)는 더하지 않음).
|
||||
</p>
|
||||
{% elif lang == 'en' %}
|
||||
<p class="perf-foot perf-muted">
|
||||
Amounts in RM (2 decimals). For each marketplace, enter shop sales and live commerce sales separately; the marketplace group column is their sum.
|
||||
Commission uses the rate in effect that day, rounded to the sen. Daily total, headline amount, charts and cumulative = all shops and live commerce.
|
||||
</p>
|
||||
{% else %}
|
||||
<p class="perf-foot perf-muted">
|
||||
금액 단위 RM(소수 2자리). 쇼핑몰마다 쇼핑몰 매출과 라이브커머스 매출을 따로 입력하고, 쇼핑몰 그룹 열 = 두 매출 합계입니다.
|
||||
@@ -311,4 +320,4 @@
|
||||
} | tojson }}</script>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261120a" defer></script>{% endblock %}
|
||||
{% block scripts %}{% if lang == 'en' %}<script src="/static/performance-en.js?v=20261120a" defer></script>{% endif %}<script src="/static/performance.js?v=20261120b" defer></script>{% endblock %}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
{% extends "erp_base.html" %}
|
||||
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261120a" />{% endblock %}
|
||||
{% block head_extra %}<link rel="stylesheet" href="/static/performance.css?v=20261120b" />{% endblock %}
|
||||
|
||||
{%- macro when(v) -%}{{ (v or '')[:16] | replace('T', ' ') or '—' }}{%- endmacro -%}
|
||||
|
||||
{% block content %}
|
||||
<section class="perf perf-settings" id="perf-settings" data-base="{{ pv.base }}"{% if pv.scale != 1 %} data-cents="1"{% endif %}>
|
||||
<section class="perf perf-settings" id="perf-settings" data-base="{{ pv.base }}"{% if pv.scale != 1 %} data-cents="1"{% endif %} data-lang="{{ lang }}">
|
||||
{% include "performance/_tabs.html" %}
|
||||
|
||||
{# 일반 사용자(실적 권한)는 쇼핑몰별 수수료율만 — 사용·집계 토글·API 인증정보·연결 상태·아래 카드는 관리자만(서버 API 도 관리자만) #}
|
||||
@@ -23,6 +23,7 @@
|
||||
{% if is_admin %}
|
||||
{% if api_cols %}<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. API 인증정보는 [설정]에서 입력합니다.
|
||||
수동 입력을 켜면 실적 일자별 표에서 그 쇼핑몰 날짜 칸에 매출을 직접 넣을 수 있고, API 가 설정돼 있어도 매출 업데이트(수동·자동)에서 빠집니다.</span>
|
||||
{% elif lang == 'en' %}<span class="perf-muted">Active · Include in sales · Manual entry · Commission rate are saved immediately. Sales are entered in the date cells of the daily sales table (RM, 2 decimals).</span>
|
||||
{% else %}<span class="perf-muted">사용 · 매출 집계 · 수동 입력 · 수수료율은 바로 저장됩니다. 매출은 매출 실적 일자별 표의 날짜 칸에 직접 입력합니다(RM, 소수 2자리).</span>{% endif %}
|
||||
{% else %}
|
||||
<span class="perf-muted">쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.</span>
|
||||
@@ -351,4 +352,4 @@
|
||||
</section>
|
||||
{% endblock %}
|
||||
|
||||
{% block scripts %}<script src="/static/performance.js?v=20261120a" defer></script>{% endblock %}
|
||||
{% block scripts %}{% if lang == 'en' %}<script src="/static/performance-en.js?v=20261120a" defer></script>{% endif %}<script src="/static/performance.js?v=20261120b" defer></script>{% endblock %}
|
||||
|
||||
@@ -186,3 +186,38 @@ def test_sample_lists_malaysia_shops(client):
|
||||
assert r.status_code == 200
|
||||
head = next(openpyxl.load_workbook(io.BytesIO(r.content)).active.iter_rows(values_only=True))
|
||||
assert head[:3] == ("날짜", "틱톡 쇼핑몰", "틱톡 라이브커머스") and len(head) == 7
|
||||
|
||||
|
||||
def test_detect_lang_rule():
|
||||
"""한영 전환(2026-11-20) — 고른 값(쿠키) 먼저, 없으면 브라우저·OS 첫 언어: ko… = 한국어, 그 밖 = 영어, 머리글 없음 = 한국어."""
|
||||
from app.lang import detect_lang
|
||||
|
||||
assert detect_lang(None, "ko-KR,ko;q=0.9,en-US;q=0.8") == "ko" and detect_lang(None, "ko") == "ko"
|
||||
assert detect_lang(None, "en-US,en;q=0.9,ko;q=0.8") == "en" and detect_lang(None, "ms-MY,ms") == "en"
|
||||
assert detect_lang(None, "") == "ko" and detect_lang(None, None) == "ko" and detect_lang("<x>", "zh-CN") == "en"
|
||||
assert detect_lang("ko", "en-US") == "ko" and detect_lang("en", "ko-KR") == "en"
|
||||
|
||||
|
||||
def test_malaysia_page_language(client):
|
||||
url = "/malaysia/performance/?period=week&d=2026-10-07"
|
||||
en = client.get(url, headers={"Accept-Language": "en-US,en;q=0.9"}).text
|
||||
assert 'data-lang="en"' in en and "performance-en.js" in en and 'data-perf-lang="en" class="is-active"' in en
|
||||
assert "Malaysia Sales" in en and "Deepavali" not in en # 머리 제목 영문, 공휴일은 말레이시아 표(10월 주엔 없음)
|
||||
ko = client.get(url, headers={"Accept-Language": "ko-KR,ko"}).text
|
||||
assert 'data-lang="ko"' in ko and "performance-en.js" not in ko
|
||||
client.cookies.set("mperf_lang", "ko")
|
||||
assert "performance-en.js" not in client.get(url, headers={"Accept-Language": "en-US"}).text # 고른 값이 먼저
|
||||
client.cookies.clear()
|
||||
kr = client.get("/performance/?period=week&d=2026-10-07", headers={"Accept-Language": "en-US"}).text
|
||||
assert 'data-lang="ko"' in kr and "performance-en.js" not in kr and 'data-perf-lang' not in kr # 한국 실적은 늘 한글·토글 없음
|
||||
|
||||
|
||||
def test_malaysia_holidays(my):
|
||||
perf_router = importlib.import_module("app.modules.performance.router")
|
||||
|
||||
assert perf_router._holidays()["2026-08-31"] == "독립기념일"
|
||||
token = variant._lang.set("en")
|
||||
try:
|
||||
assert perf_router._holidays()["2026-08-31"] == "Merdeka Day"
|
||||
finally:
|
||||
variant._lang.reset(token)
|
||||
|
||||
@@ -12,6 +12,10 @@ from dataclasses import dataclass, field
|
||||
from decimal import ROUND_HALF_UP, Decimal
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Request
|
||||
|
||||
from app.lang import detect_lang
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Variant:
|
||||
@@ -47,15 +51,23 @@ MY = Variant(
|
||||
)
|
||||
|
||||
_current: ContextVar[Variant] = ContextVar("perf_variant", default=KR)
|
||||
# 화면 언어(2026-11-20) — 말레이시아 실적만 한영 전환(쿠키 → 없으면 브라우저·OS 언어, app/lang.py). 한국 실적은 늘 ko.
|
||||
LANG_COOKIE = "mperf_lang"
|
||||
_lang: ContextVar[str] = ContextVar("perf_lang", default="ko")
|
||||
|
||||
|
||||
def current() -> Variant:
|
||||
return _current.get()
|
||||
|
||||
|
||||
async def use_malaysia() -> None:
|
||||
def lang() -> str:
|
||||
return _lang.get()
|
||||
|
||||
|
||||
async def use_malaysia(request: Request) -> None:
|
||||
"""말레이시아 마운트 의존성 — async 라 요청 태스크 컨텍스트에 설정되고 동기 핸들러(스레드풀)로 복사된다."""
|
||||
_current.set(MY)
|
||||
_lang.set(detect_lang(request.cookies.get(LANG_COOKIE), request.headers.get("accept-language")))
|
||||
|
||||
|
||||
def num_text(value: Any) -> str:
|
||||
@@ -83,5 +95,5 @@ def input_text(value: Any) -> str:
|
||||
|
||||
|
||||
def template_ctx() -> dict[str, Any]:
|
||||
"""모든 실적 화면 공통 — pv(인스턴스), num·money·inval(금액 글자)."""
|
||||
return {"pv": current(), "num": num_text, "money_t": money_text, "inval": input_text}
|
||||
"""모든 실적 화면 공통 — pv(인스턴스), num·money·inval(금액 글자), lang(ko|en — 영문이면 performance-en.js 가 번역)."""
|
||||
return {"pv": current(), "num": num_text, "money_t": money_text, "inval": input_text, "lang": lang()}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* 대상 셀렉터는 UI 크롬(제목/헤더/버튼/라벨/배지/옵션/안내문)으로 한정 →
|
||||
* 데이터 셀(상품코드/수량)은 건드리지 않음.
|
||||
* - 상품명: 서버가 data-ko / data-en 을 함께 렌더 → 언어에 맞게 textContent 교체.
|
||||
* - 선택값은 localStorage('mys_lang') 에 저장, 모든 화면 공통 적용.
|
||||
* - 선택값은 localStorage('mys_lang') 에 저장, 모든 화면 공통 적용. 저장값이 없으면 브라우저·OS 언어(ko → 한글, 그 밖 → 영어).
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
@@ -173,13 +173,18 @@
|
||||
document.documentElement.setAttribute("data-mys-lang", lang);
|
||||
}
|
||||
|
||||
// 고른 값(localStorage) 이 없으면 브라우저·OS 기본 언어 — 한국어(ko…)면 한글, 그 밖은 영어(2026-11-20, app/lang.py 와 같은 규칙)
|
||||
function current() {
|
||||
return localStorage.getItem("mys_lang") === "en" ? "en" : "ko";
|
||||
var saved = null;
|
||||
try { saved = localStorage.getItem("mys_lang"); } catch (_) { /* 저장소 없음 */ }
|
||||
if (saved === "en" || saved === "ko") return saved;
|
||||
var os = String((navigator.languages && navigator.languages[0]) || navigator.language || "ko").toLowerCase();
|
||||
return os.indexOf("ko") === 0 ? "ko" : "en";
|
||||
}
|
||||
|
||||
function toggle() {
|
||||
var next = current() === "en" ? "ko" : "en";
|
||||
localStorage.setItem("mys_lang", next);
|
||||
try { localStorage.setItem("mys_lang", next); } catch (_) { /* 기억만 못 함 */ }
|
||||
applyLang(next);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,269 @@
|
||||
/* 말레이시아 실적 영문 화면(2026-11-20) — 서버가 영문(lang=en)일 때만 performance.js 앞에 싣는다. 한국 실적은 안 쓴다.
|
||||
*
|
||||
* 같은 템플릿·performance.js 를 한국 실적과 함께 쓰므로 한글을 고치지 않고, 그린 뒤 글자를 바꾼다:
|
||||
* ① 사전(EN — 한글 문구 그대로가 키) ② 패턴(RULES — 날짜·기간·이름이 섞인 글) ③ 낱말 치환(PHRASES — 결과에 한글이 안 남을 때만).
|
||||
* .perf 안 글자·title·aria-label·placeholder, 나중에 생기는 창·메뉴·말풍선(MutationObserver), 알림·확인 창 문구(erpAlert·erpConfirm·alert·confirm).
|
||||
* 못 바꾼 글은 한글 그대로 두고 window.__perfI18nMissing 에 모은다 — tests/js/perf_malaysia_en.browser.test.js 가 화면에 한글이 없는지 본다.
|
||||
* 새 화면 문구를 넣으면 여기에도 영문을 넣는다. 긴 안내 문단(굵은 글자 섞임)은 템플릿에 {% if lang == 'en' %} 로 따로 쓴다.
|
||||
*/
|
||||
(function () {
|
||||
"use strict";
|
||||
const ROOT = document.querySelector(".perf[data-lang='en']");
|
||||
if (!ROOT) return;
|
||||
const HANGUL = /[가-힣]/;
|
||||
|
||||
const EN = {
|
||||
// 탭·기간·표
|
||||
"매출 실적": "Sales", "광고비": "Ad Spend", "실적 설정": "Settings", "수수료 설정": "Commission settings",
|
||||
"말레이시아 실적 메뉴": "Malaysia Sales menu", "말레이시아 실적 설정": "Settings", "기간 선택": "Period", "이번달": "This month",
|
||||
"올해": "This year", "직접선택": "Custom", "조회": "Apply", "전체": "All", "적용": "Apply", "표시 기준": "Show",
|
||||
"총매출": "Gross sales", "수수료": "Commission", "수수료 차감 매출": "Net sales", "매출": "Sales",
|
||||
"엑셀 업로드": "Excel upload", "파일 업로드": "File upload", "단위: RM": "Unit: RM", "광고비(ROAS%)": "Ad spend (ROAS%)",
|
||||
"날짜": "Date", "월": "Month", "일 합계": "Daily total", "월 합계": "Monthly total", "기간 합계": "Period total",
|
||||
"연간 합계": "Annual total", "주간합계": "Week total", "합계": "Total", "쇼핑몰": "Marketplace", "채널": "Channel",
|
||||
"매출 비중": "Share", "비중": "Share", "그룹": "Group", "수동 입력": "Manual entry", "ROAS": "ROAS",
|
||||
"일별 매출 추이": "Daily sales trend", "월별 매출 추이": "Monthly sales trend", "쇼핑몰별 비중": "Share by marketplace",
|
||||
"일별 광고비 추이": "Daily ad spend trend", "월별 광고비 추이": "Monthly ad spend trend", "채널별 비중": "Share by channel",
|
||||
"일자별 × 쇼핑몰": "Daily × marketplace", "월별 × 쇼핑몰": "Monthly × marketplace",
|
||||
"일자별 × 광고 채널": "Daily × ad channel", "월별 × 광고 채널": "Monthly × ad channel",
|
||||
"기간 내 매출이 없습니다.": "No sales in this period.", "기간 내 광고비가 없습니다.": "No ad spend in this period.",
|
||||
"매출 없음": "No sales", "하위 쇼핑몰 접기/펴기": "Collapse / expand sub columns",
|
||||
"수동 입력 쇼핑몰 매출을 엑셀 파일로 한 번에 입력": "Enter manual sales from an Excel file",
|
||||
"매출에 포함된 쇼핑몰이 없습니다.": "No marketplaces are included in sales.", "에서 쇼핑몰 사용을 켜세요.": "— turn marketplaces on.",
|
||||
"매출 아래 주황 숫자 = 그 쇼핑몰 광고비(ROAS%) — 광고비 탭과 같은 값. 쇼핑몰 그룹(합계) 칸 아래, ROAS = 쇼핑몰 + 라이브커머스 매출 ÷ 광고비":
|
||||
"Orange figures = that marketplace's ad spend (ROAS%), same as the Ad Spend tab. Shown under the marketplace group (total) cell; ROAS = shop + live commerce sales ÷ ad spend",
|
||||
"중지됨": "Stopped",
|
||||
// 설정
|
||||
"쇼핑몰 설정": "Marketplaces", "사용": "Active", "매출 집계": "In sales", "수수료율": "Commission rate",
|
||||
"미설정": "Not set", "변경": "Change", "이름 변경": "Rename", "삭제": "Delete", "그룹 없음": "No group",
|
||||
"직접 추가": "Custom", "+ 쇼핑몰 추가(수동 입력)": "+ Add marketplace (manual)", "+ 그룹 추가": "+ Add group",
|
||||
"끌어서 순서 변경": "Drag to reorder", "끌어서 순서 변경(그룹은 하위 쇼핑몰과 함께 움직임)": "Drag to reorder (a group moves with its sub marketplaces)",
|
||||
"사용 여부": "Active", "매출 집계에 포함": "Include in sales",
|
||||
"⠿ 를 끌어 순서를 바꾸면 매출 실적 열 순서에 그대로 반영됩니다. 그룹은 직접 추가한 쇼핑몰만 묶을 수 있습니다.":
|
||||
"Drag ⠿ to reorder — the sales table columns follow. Only custom marketplaces can be grouped.",
|
||||
"실적 설정에서 직접 추가한 쇼핑몰": "Marketplace added in settings",
|
||||
"수동 입력 전용 쇼핑몰 — API 연동이 없어 늘 켜져 있습니다": "Manual-only marketplace — always on (no API)",
|
||||
"API 연동 없이 실적 일자별 표에 매출을 직접 입력하는 쇼핑몰을 추가": "Add a marketplace whose sales you enter by hand in the daily table",
|
||||
"직접 추가한 쇼핑몰을 묶는 그룹 — 그룹 매출 = 하위 쇼핑몰 매출 합계": "A group of custom marketplaces — group sales = sum of its marketplaces",
|
||||
"그룹 — 그룹으로 묶으면 매출 실적에서 그룹 열이 하위 쇼핑몰 매출 합계": "Group — the group column shows the sum of its marketplaces",
|
||||
"보기 설정": "View settings", "표 열 너비": "Column width", "자동(글자 길이)": "Auto (fit text)", "수동 조절": "Manual",
|
||||
"조절한 너비 초기화": "Reset widths", "초기화했습니다": "Reset",
|
||||
"매출 실적·광고비 화면을 보는 방식입니다. 이 브라우저에만 적용되며 고르면 바로 저장됩니다.":
|
||||
"How the Sales and Ad Spend screens look. Applies to this browser only and saves immediately.",
|
||||
"열 너비가 글자 길이에 맞춰 자동으로 정해집니다.": "Column widths fit the text automatically.",
|
||||
"매출 실적·광고비 표 머리글의 오른쪽 경계를 끌어 너비를 바꿉니다(두 번 누르면 그 열만 자동 너비). 바꾼 너비는 계속 유지됩니다.":
|
||||
"Drag the right edge of a header to resize (double-click for auto width). Widths are kept.",
|
||||
"매출 실적·광고비 표에서 조절한 열 너비를 모두 지우고 자동 너비로 되돌릴까요?": "Clear all adjusted column widths and go back to auto width?",
|
||||
"공통 보기 설정": "Shared view settings", "모든 사용자의 매출 실적 화면에 적용됩니다. 고르면 바로 저장됩니다.":
|
||||
"Applies to everyone's Sales screen. Saves immediately.",
|
||||
"숨길 쇼핑몰": "Hidden columns",
|
||||
"체크한 쇼핑몰은 일자별 표에서 열만 숨겨집니다. 일 합계·그래프·누적 금액은 그대로입니다.":
|
||||
"Checked marketplaces are hidden from the daily table only. Totals, charts and cumulative amounts stay the same.",
|
||||
"수수료율은": "Commission rates apply from the", "적용 시작일": "Effective date",
|
||||
"부터 반영되고, 그 전 실적은 예전 요율로 계산됩니다(과거 실적이 바뀌지 않음).": "; earlier sales keep the old rate (past results don't change).",
|
||||
"쇼핑몰별 수수료율을 설정합니다. 바로 저장되며 실적 화면의 수수료·수수료 차감 매출에 반영됩니다.":
|
||||
"Set the commission rate per marketplace. Saved immediately and used for commission and net sales.",
|
||||
// 창(performance.js)
|
||||
"닫기": "Close", "업로드": "Upload", "취소": "Cancel", "저장": "Save", "확인": "OK", "샘플 파일 받기": "Download sample",
|
||||
"수동 입력 엑셀 업로드": "Excel upload (manual sales)", "엑셀 파일": "Excel file", "엑셀 파일을 고르세요.": "Choose an Excel file.",
|
||||
"올리는 중…": "Uploading…", "불러오는 중…": "Loading…", "없음": "None",
|
||||
"1열에": "Column 1:", ", 2열부터": ", from column 2:", "쇼핑몰 이름": "marketplace names",
|
||||
"을 머리글로 적고 그날": "as headers, then each day's", "을 넣습니다. 값이 있는 칸만 반영되고(같은 날 값은 덮어씀) 빈 칸은 기존 값 그대로입니다.":
|
||||
". Only filled cells are saved (overwriting that day); empty cells stay as they are.",
|
||||
"반영할 값이 없습니다(값이 있는 칸이 없음).": "Nothing to save (no filled cells).",
|
||||
"창을 닫으면 표·합계·그래프가 다시 계산됩니다.": "Totals and charts are recalculated when you close this window.",
|
||||
"메모 삽입": "Insert note", "메모 수정": "Edit note", "메모 삭제": "Delete note", "메모": "Note",
|
||||
"메모를 입력하세요 (Ctrl+Enter 저장)": "Type a note (Ctrl+Enter to save)",
|
||||
"수수료율(%)": "Commission rate (%)", "예: 5, 10.8, 15.35": "e.g. 5, 10.8, 15.35", "처음부터(과거 전체)": "From the start (all past)",
|
||||
"이 날짜부터 새 요율로 계산하고, 그 전 실적은 예전 요율을 유지합니다.": "The new rate applies from this date; earlier sales keep the old rate.",
|
||||
"변경 이력": "Change history", "요율": "Rate", "변경자": "Changed by", "처음부터": "From the start",
|
||||
"이력이 없습니다(현재 0%).": "No history (currently 0%).",
|
||||
"이 수수료 이력을 삭제할까요? 해당 기간 실적의 수수료가 다시 계산됩니다.": "Delete this rate? Commission for that period will be recalculated.",
|
||||
"쇼핑몰 추가(수동 입력)": "Add marketplace (manual)", "그룹 추가": "Add group", "이름": "Name",
|
||||
"그룹 이름 변경": "Rename group", "쇼핑몰 이름 변경": "Rename marketplace", "언어": "Language",
|
||||
"숫자 또는 1000+2000 같은 계산식만 입력하세요.": "Enter a number or a formula such as 10.5+20.",
|
||||
// 서버 오류(말레이시아 실적에서 날 수 있는 것)
|
||||
"금액이 너무 큽니다.": "The amount is too large.", "날짜가 필요합니다.": "A date is required.",
|
||||
"알 수 없는 쇼핑몰입니다.": "Unknown marketplace.", "알 수 없는 광고 채널입니다.": "Unknown ad channel.",
|
||||
"이 쇼핑몰은 수동 입력을 쓰지 않습니다(실적 설정에서 켜세요).": "Manual entry is off for this marketplace (turn it on in Settings).",
|
||||
"이름을 입력하세요.": "Enter a name.", "그룹은 다른 그룹에 넣을 수 없습니다.": "A group can't be put in another group.",
|
||||
"그룹은 이름만 바꿀 수 있습니다.": "Only a group's name can be changed.", "그룹을 찾지 못했습니다.": "Group not found.",
|
||||
"수동 입력 전용 쇼핑몰은 수동 입력을 끌 수 없습니다.": "Manual entry can't be turned off for a manual-only marketplace.",
|
||||
"수수료 이력을 찾지 못했습니다.": "Rate history not found.", "수수료율은 0 ~ 100 사이여야 합니다.": "The rate must be between 0 and 100.",
|
||||
"수수료율은 소수점 셋째 자리까지 입력할 수 있습니다.": "Up to 3 decimal places.",
|
||||
"수수료율은 숫자로 입력하세요(예: 5, 10.8, 15.35).": "Enter the rate as a number (e.g. 5, 10.8, 15.35).",
|
||||
"적용 시작일을 입력하세요.": "Enter the effective date.", "순서 목록이 비었습니다.": "The order list is empty.",
|
||||
"순서 목록에 같은 쇼핑몰이 두 번 있습니다.": "A marketplace appears twice in the order.", "파일을 고르세요.": "Choose a file.",
|
||||
"숫자와 + - * / ( ) 만 입력할 수 있습니다.": "Only numbers and + - * / ( ) are allowed.", "계산식이 끝나지 않았습니다.": "The formula is incomplete.",
|
||||
"0으로 나눌 수 없습니다.": "Can't divide by 0.", "괄호가 맞지 않습니다.": "Brackets don't match.",
|
||||
"계산식이 올바르지 않습니다.": "The formula is invalid.", "계산식이 너무 깁니다.": "The formula is too long.", "계산할 수 없는 식입니다.": "Can't calculate this formula.",
|
||||
"빈 파일입니다.": "The file is empty.", "파일이 너무 큽니다(5MB 이하).": "The file is too large (5 MB max).",
|
||||
"엑셀(.xlsx) 파일을 읽을 수 없습니다. 샘플 파일 양식으로 저장해 올려 주세요.": "Can't read the Excel (.xlsx) file. Save it in the sample format and upload again.",
|
||||
"1행에 날짜와 쇼핑몰 이름 머리글이 없습니다.": "Row 1 needs Date and marketplace name headers.",
|
||||
"기본 쇼핑몰은 삭제할 수 없습니다(사용을 끄세요).": "Built-in marketplaces can't be deleted (turn them off instead).",
|
||||
"기본 쇼핑몰은 이름·그룹을 바꿀 수 없습니다.": "Built-in marketplaces can't be renamed or grouped.",
|
||||
"요청 실패": "Request failed",
|
||||
// 쇼핑몰 이름(seed — 바꾼 이름은 낱말 치환으로)
|
||||
"틱톡": "TikTok", "쇼피": "Shopee", "라자다": "Lazada",
|
||||
};
|
||||
|
||||
const MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
|
||||
const DOW = { "월": "Mon", "화": "Tue", "수": "Wed", "목": "Thu", "금": "Fri", "토": "Sat", "일": "Sun" };
|
||||
const list = function (s) { return s.split(", ").map(tr).join(", "); };
|
||||
// 값이 섞인 글 — [정규식, (일치) → 영문]. 위에서부터 처음 맞는 것.
|
||||
const RULES = [
|
||||
[/^(\d{4})년 (\d{1,2})월 (\d{1,2})일 ~ (?:(\d{4})년 )?(\d{1,2})월 (\d{1,2})일$/, function (m) {
|
||||
return MON[m[2] - 1] + " " + m[3] + (m[4] && m[4] !== m[1] ? ", " + m[1] : "") + " – " + MON[m[5] - 1] + " " + m[6] + ", " + (m[4] || m[1]); }],
|
||||
[/^(\d{4})년 (\d{1,2})월 (\d{1,2})일 \((.)\)$/, function (m) { return DOW[m[4]] + ", " + MON[m[2] - 1] + " " + m[3] + ", " + m[1]; }],
|
||||
[/^(\d{4})년 (\d{1,2})월$/, function (m) { return MON[m[2] - 1] + " " + m[1]; }],
|
||||
[/^(\d{4})년$/, function (m) { return m[1]; }],
|
||||
[/^(\d{2}\/\d{2})\((.)\)$/, function (m) { return m[1] + " " + DOW[m[2]]; }],
|
||||
[/^주간합계 \((.+)\)$/, function (m) { return "Week total (" + m[1] + ")"; }],
|
||||
[/^(\d{4})년 누적$/, function (m) { return m[1] + " year to date"; }],
|
||||
[/^(\d{4})년 누적 광고비$/, function (m) { return m[1] + " ad spend YTD"; }],
|
||||
[/^(\d{4})년 (\d{1,2})월 쇼핑몰별 누적 실적$/, function (m) { return MON[m[2] - 1] + " " + m[1] + " by marketplace"; }],
|
||||
[/^(\d{4})년 (\d{1,2})월 채널별 광고비$/, function (m) { return MON[m[2] - 1] + " " + m[1] + " ad spend by channel"; }],
|
||||
[/^(.+) 대비$/, function (m) { return "vs " + tr(m[1]).toLowerCase(); }],
|
||||
[/^(.+) 비교 없음$/, function (m) { return "no comparison with " + tr(m[1]).toLowerCase(); }],
|
||||
[/^쇼핑몰: (\d+)곳$/, function (m) { return "Marketplaces: " + m[1]; }],
|
||||
[/^쇼핑몰: 전체$/, function () { return "Marketplaces: All"; }],
|
||||
[/^하위 쇼핑몰 (\d+)곳 — /, function (m) { return m[1] + " sub marketplaces — the group column on Sales = their sum (commission at each marketplace's rate)"; }],
|
||||
[/^(.+) — 하위 쇼핑몰 (\d+)곳 매출 합계$/, function (m) { return tr(m[1]) + " — sum of " + m[2] + " sub marketplaces"; }],
|
||||
[/^(.+) — 수동 입력\(날짜 칸을 눌러 입력\)$/, function (m) { return tr(m[1]) + " — manual entry (click a date cell)"; }],
|
||||
[/^(.+) 하위 쇼핑몰 (접기|펴기)$/, function (m) { return (m[2] === "접기" ? "Collapse " : "Expand ") + tr(m[1]); }],
|
||||
[/^(.+) 열 (접기|펴기)$/, function (m) { return (m[2] === "접기" ? "Collapse column " : "Expand column ") + tr(m[1]); }],
|
||||
[/^(.+) — 날짜 칸을 눌러 광고비 입력\. 괄호 = ROAS\((.+) 매출 ÷ 광고비\)$/, function (m) {
|
||||
return tr(m[1]) + " — click a date cell to enter ad spend. Brackets = ROAS (" + tr(m[2]) + " sales ÷ ad spend)"; }],
|
||||
[/^총매출 RM (.+)$/, function (m) { return "Gross sales RM " + m[1]; }],
|
||||
[/^(\d{1,2})월 (.+)$/, function (m) { return MON[m[1] - 1] + " " + m[2]; }], // 그래프 말풍선 "10월 1,834.55 RM"
|
||||
[/^(\d{1,2})월$/, function (m) { return MON[m[1] - 1]; }],
|
||||
[/^입력 가능한 쇼핑몰: (.*)$/, function (m) { return "Marketplaces you can enter: " + list(m[1]); }],
|
||||
[/^건너뛴 열: (.*)$/, function (m) { return "Skipped columns: " + m[1].split(", ").map(function (c) {
|
||||
return c.replace(/^(.*)\((알 수 없는 쇼핑몰|수동 입력 꺼짐)\)$/, function (_, n, why) {
|
||||
return tr(n) + " (" + (why === "수동 입력 꺼짐" ? "manual entry off" : "unknown marketplace") + ")"; }); }).join(", "); }],
|
||||
[/^(.+) · (\d{4}\.\d{2}\.\d{2}) 메모$/, function (m) { return "Note · " + tr(m[1]) + " · " + m[2]; }],
|
||||
[/^(메모 삽입|메모 수정) · (.+) · (\d{4}\.\d{2}\.\d{2})$/, function (m) { return tr(m[1]) + " · " + tr(m[2]) + " · " + m[3]; }],
|
||||
[/^(.+) 칸의 메모를 지울까요\?$/, function (m) { return "Delete the note in " + tr(m[1]) + "?"; }],
|
||||
[/^(.+) 수수료율$/, function (m) { return tr(m[1]) + " commission rate"; }],
|
||||
[/^쇼핑몰 \[(.+)\]을 삭제할까요\?(?: 입력해 둔 매출 ([\d,]+)일치와 수수료율도 함께 지워지며 되돌릴 수 없습니다\.)?$/, function (m) {
|
||||
return "Delete marketplace [" + tr(m[1]) + "]?" + (m[2] ? " Its " + m[2] + " days of entered sales and commission rates will be deleted too. This can't be undone." : ""); }],
|
||||
[/^그룹 \[(.+)\]을 삭제할까요\? 하위 쇼핑몰은 지워지지 않고 그룹 없음이 됩니다\.$/, function (m) {
|
||||
return "Delete group [" + tr(m[1]) + "]? Its marketplaces stay, with no group."; }],
|
||||
[/^([\d,]+)칸 반영 \((.+)\)$/, function (m) { return m[1] + " cells saved (" + m[2] + ")"; }],
|
||||
[/^(.+) ([\d,]+)일$/, function (m) { return tr(m[1]) + " " + m[2] + " days"; }],
|
||||
[/^저장 실패\((.+?)\): (.*)$/, function (m) { return "Save failed (" + m[1] + "): " + tr(m[2]); }],
|
||||
[/^(저장|삭제|메모 저장|메모 삭제|순서 저장|업로드) 실패: (.*)$/, function (m) {
|
||||
return { "저장": "Save", "삭제": "Delete", "메모 저장": "Saving the note", "메모 삭제": "Deleting the note", "순서 저장": "Saving the order", "업로드": "Upload" }[m[1]] + " failed: " + tr(m[2]); }],
|
||||
[/^업로드 실패 \((\d+)\)$/, function (m) { return "Upload failed (" + m[1] + ")"; }],
|
||||
[/^접은 열을 저장하지 못했습니다: (.*)$/, function (m) { return "Couldn't save folded columns: " + tr(m[1]); }],
|
||||
[/^요청 실패 \((\d+)\)$/, function (m) { return "Request failed (" + m[1] + ")"; }],
|
||||
[/^(.*) \(숫자 또는 1000\+2000 같은 계산식\)$/, function (m) { return tr(m[1]) + " (a number or a formula such as 10.5+20)"; }],
|
||||
[/^같은 이름\((.+)\)이 이미 있습니다\.$/, function (m) { return "The name (" + m[1] + ") already exists."; }],
|
||||
[/^이름은 (\d+)자까지입니다\.$/, function (m) { return "Names can be up to " + m[1] + " characters."; }],
|
||||
[/^메모는 ([\d,]+)자까지 쓸 수 있습니다\.$/, function (m) { return "Notes can be up to " + m[1] + " characters."; }],
|
||||
[/^잘못된 칸이 (\d+)개(\+?) 있어 아무것도 저장하지 않았습니다\. 고친 뒤 다시 올려 주세요\.$/, function (m) {
|
||||
return m[1] + m[2] + " invalid cells — nothing was saved. Fix them and upload again."; }],
|
||||
[/^([A-Z]+\d+): 금액이 숫자가 아닙니다\((.*)\)\.$/, function (m) { return m[1] + ": the amount is not a number (" + m[2] + ")."; }],
|
||||
[/^([A-Z]+\d+): 금액이 너무 큽니다\.$/, function (m) { return m[1] + ": the amount is too large."; }],
|
||||
[/^([A-Z]+\d+): 날짜를 읽을 수 없습니다\((.*)\)\.$/, function (m) { return m[1] + ": can't read the date (" + m[2] + ")."; }],
|
||||
[/^(\d+)행: 날짜가 비어 있습니다\.$/, function (m) { return "Row " + m[1] + ": the date is empty."; }],
|
||||
[/^([A-Z]+\d+): (.+) (\d{4}-\d{2}-\d{2}) 이 ([A-Z]+\d+) 와 겹칩니다\.$/, function (m) {
|
||||
return m[1] + ": " + tr(m[2]) + " " + m[3] + " overlaps " + m[4] + "."; }],
|
||||
[/^([A-Z]+\d+) (.+): 같은 쇼핑몰 열이 두 번 있습니다\.$/, function (m) { return m[1] + " " + tr(m[2]) + ": the same marketplace column appears twice."; }],
|
||||
[/^반영할 쇼핑몰 열이 없습니다\./, function () { return "No columns to save — use the names of marketplaces with manual entry on as headers."; }],
|
||||
[/^한 번에 ([\d,]+)일까지 올릴 수 있습니다\.$/, function (m) { return "Up to " + m[1] + " days per upload."; }],
|
||||
[/^(.+) 형식이 올바르지 않습니다\(YYYY-MM-DD\)\.$/, function (m) { return tr(m[1]) + " must be YYYY-MM-DD."; }],
|
||||
];
|
||||
|
||||
// 낱말 치환 — 긴 것부터. 결과에 한글이 하나도 안 남을 때만 쓴다(문장이 반쯤 바뀌지 않게).
|
||||
const PHRASES = [
|
||||
["라이브커머스", "Live Commerce"], ["쇼핑몰", "Shop"], ["틱톡", "TikTok"], ["쇼피", "Shopee"], ["라자다", "Lazada"],
|
||||
["수수료 차감 매출", "net sales"], ["매출 대비 광고비", "ad spend to sales"], ["누적 광고비", "ad spend YTD"],
|
||||
["전년 같은 기간", "same period last year"], ["전월 같은 기간", "same period last month"], ["전주 같은 기간", "same period last week"],
|
||||
["전일 같은 기간", "same time yesterday"], ["직전 기간 같은 기간", "same span of the previous period"],
|
||||
["같은 기간", "same period"], ["직전 기간", "previous period"],
|
||||
["이번달", "This month"], ["이번주", "This week"], ["올해", "This year"], ["오늘", "Today"], ["선택 기간", "Selected period"],
|
||||
["해당 월", "That month"], ["해당 주", "That week"], ["해당 연도", "That year"], ["해당일", "That day"],
|
||||
["이전달", "Previous month"], ["다음달", "Next month"], ["이전주", "Previous week"], ["다음주", "Next week"],
|
||||
["이전해", "Previous year"], ["다음해", "Next year"], ["다음날", "Next day"],
|
||||
["전월", "last month"], ["전주", "last week"], ["전년", "last year"], ["전일", "previous day"],
|
||||
["이전", "Previous"], ["다음", "Next"], ["광고비", "ad spend"], ["매출", "sales"], ["누적", "YTD"], ["대체", "(Replacement)"],
|
||||
["날짜", "date"], ["시작일", "start date"], ["종료일", "end date"],
|
||||
].sort(function (a, b) { return b[0].length - a[0].length; });
|
||||
|
||||
const missing = window.__perfI18nMissing = [];
|
||||
const done = new Map();
|
||||
function tr(text) {
|
||||
if (!text || !HANGUL.test(text)) return text;
|
||||
if (done.has(text)) return done.get(text);
|
||||
const lead = text.match(/^\s*/)[0], tail = text.match(/\s*$/)[0], core = text.trim();
|
||||
let out = EN[core];
|
||||
if (out === undefined) {
|
||||
for (let i = 0; i < RULES.length; i++) {
|
||||
const m = core.match(RULES[i][0]);
|
||||
if (m) { out = RULES[i][1](m); break; }
|
||||
}
|
||||
}
|
||||
if ((out === undefined || HANGUL.test(out)) && core.indexOf("\n") >= 0) { // 여러 줄 알림 — 줄마다
|
||||
const lines = core.split("\n").map(tr);
|
||||
out = lines.some(function (l) { return HANGUL.test(l); }) ? undefined : lines.join("\n");
|
||||
}
|
||||
if (out === undefined || HANGUL.test(out)) {
|
||||
let s = core;
|
||||
PHRASES.forEach(function (p) { s = s.split(p[0]).join(p[1]); });
|
||||
out = HANGUL.test(s) ? undefined : s.replace(/\s+/g, " ").replace(/^([a-z])/, function (c) { return c.toUpperCase(); });
|
||||
}
|
||||
if (out === undefined) { if (missing.indexOf(core) < 0) missing.push(core); }
|
||||
const res = out === undefined ? text : lead + out + tail;
|
||||
done.set(text, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
const ATTRS = ["title", "aria-label", "placeholder"];
|
||||
function noText(el) { return !el || !!el.closest("[translate='no'], script, style, textarea"); }
|
||||
function fixAttrs(el) {
|
||||
if (el.closest("[translate='no']")) return;
|
||||
ATTRS.forEach(function (a) {
|
||||
const v = el.getAttribute(a);
|
||||
if (v && HANGUL.test(v)) { const t = tr(v); if (t !== v) el.setAttribute(a, t); }
|
||||
});
|
||||
}
|
||||
function fixText(n) {
|
||||
if (HANGUL.test(n.nodeValue) && !noText(n.parentElement)) { const v = tr(n.nodeValue); if (v !== n.nodeValue) n.nodeValue = v; }
|
||||
}
|
||||
function walk(root) {
|
||||
if (!root) return;
|
||||
if (root.nodeType === 3) { fixText(root); return; }
|
||||
if (root.nodeType !== 1) return;
|
||||
fixAttrs(root);
|
||||
const tw = document.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
|
||||
for (let n = tw.nextNode(); n; n = tw.nextNode()) {
|
||||
if (n.nodeType === 3) fixText(n); else fixAttrs(n);
|
||||
}
|
||||
}
|
||||
|
||||
// 알림·확인 창 문구 — 창을 그리기 전에 바꾼다(erp-dialog.js 창의 [확인]·[취소] 단추는 아래 관찰자가 바꾼다).
|
||||
["erpAlert", "erpConfirm", "erpPrompt"].forEach(function (name) {
|
||||
const orig = window[name];
|
||||
if (typeof orig === "function") window[name] = function (msg) { const a = Array.prototype.slice.call(arguments); a[0] = tr(String(msg)); return orig.apply(this, a); };
|
||||
});
|
||||
["alert", "confirm"].forEach(function (name) {
|
||||
const orig = window[name];
|
||||
window[name] = function (msg) { return orig.call(window, tr(String(msg == null ? "" : msg))); };
|
||||
});
|
||||
|
||||
// 이 화면 것만 — .perf 안 + 실적 창·메뉴·말풍선(perf-…)·알림 창. ERP 셸(사이드바·공지 등)은 건드리지 않는다.
|
||||
function mine(node) {
|
||||
const el = node.nodeType === 1 ? node : node.parentElement;
|
||||
return !!el && (ROOT.contains(el) || !!el.closest('[class*="perf-"], .erp-dialog-backdrop'));
|
||||
}
|
||||
walk(ROOT);
|
||||
ROOT.classList.add("is-i18n");
|
||||
new MutationObserver(function (records) {
|
||||
records.forEach(function (r) {
|
||||
if (r.type !== "childList") { if (mine(r.target)) walk(r.target); return; }
|
||||
r.addedNodes.forEach(function (n) { if (mine(n)) walk(n); });
|
||||
});
|
||||
}).observe(document.body, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ATTRS });
|
||||
window.__perfI18n = tr;
|
||||
})();
|
||||
@@ -49,6 +49,13 @@ a.perf-tab.is-active:link, a.perf-tab.is-active:visited { color: #fff; }
|
||||
border-radius: 50%; color: var(--color-midtone-gray); text-decoration: none;
|
||||
}
|
||||
.perf-tab-gear .material-symbols-outlined { font-size: 22px; }
|
||||
/* 한글·영문 전환(말레이시아 실적, 2026-11-20) — 톱니 바로 왼쪽. 영문 화면은 번역(performance-en.js)이 끝날 때까지 숨김(한글이 번쩍이지 않게) */
|
||||
.perf-lang { margin-left: auto; display: inline-flex; padding: 2px; border: 1px solid var(--color-subtle-ash, #e5e5e5); border-radius: 999px; background: #fff; }
|
||||
.perf-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; }
|
||||
.perf-lang button.is-active { background: #111; color: #fff; }
|
||||
.perf-lang + .perf-tab-gear { margin-left: 0; }
|
||||
.perf[data-lang="en"]:not(.is-i18n) { visibility: hidden; animation: perf-i18n-reveal 0s linear 1.5s forwards; } /* 스크립트를 못 실어도 1.5초 뒤엔 보인다 */
|
||||
@keyframes perf-i18n-reveal { to { visibility: visible; } }
|
||||
.perf-tab-gear:hover { color: var(--color-rich-black); background: var(--color-ghost-gray, #f3f3f3); }
|
||||
.perf-tab-gear.is-active { color: #fff; background: var(--color-deep-black, #1e1f21); }
|
||||
|
||||
|
||||
@@ -49,6 +49,14 @@
|
||||
if (a >= 10000) return s + Math.round(a / 10000).toLocaleString("ko-KR") + "만";
|
||||
return s + fmt(a);
|
||||
}
|
||||
// 한글·영문 전환(말레이시아 실적, 2026-11-20) — 고른 언어를 쿠키(mperf_lang, 이 모듈 주소에만)에 두고 다시 그린다(서버가 언어를 정함)
|
||||
document.addEventListener("click", function (e) {
|
||||
const b = e.target.closest && e.target.closest("button[data-perf-lang]");
|
||||
if (!b || b.classList.contains("is-active")) return;
|
||||
document.cookie = "mperf_lang=" + b.dataset.perfLang + "; path=" + BASE + "; max-age=31536000; SameSite=Lax" +
|
||||
(location.protocol === "https:" ? "; Secure" : "");
|
||||
location.reload();
|
||||
});
|
||||
function alertMsg(msg, opts) { return window.erpAlert ? window.erpAlert(msg, opts) : Promise.resolve(window.alert(msg)); }
|
||||
function confirmMsg(msg) { return window.erpConfirm ? window.erpConfirm(msg) : Promise.resolve(window.confirm(msg)); }
|
||||
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
// 말레이시아 실적 영문 화면(2026-11-20) — 실제 브라우저. performance-en.js 번역 뒤 화면·창·메뉴·알림에 한글이 하나도 없는지.
|
||||
// python tests/js/render_performance.py
|
||||
// NODE_PATH=<playwright 경로> PJ_TEST_BROWSER=<Chrome 경로> node tests/js/perf_malaysia_en.browser.test.js
|
||||
// 한글이 남으면 그 글을 모두 찍는다 — performance-en.js EN·RULES·PHRASES 에 넣으면 된다.
|
||||
const fs = require("fs"), path = require("path");
|
||||
const { chromium } = require("playwright");
|
||||
const ROOT = path.join(__dirname, "..", "..");
|
||||
const fails = [];
|
||||
function check(name, cond, extra) {
|
||||
if (cond) console.log("PASS " + name);
|
||||
else { console.log("FAIL " + name + (extra !== undefined ? " → " + JSON.stringify(extra, null, 1) : "")); fails.push(name); }
|
||||
}
|
||||
const S = function (f) { return fs.readFileSync(path.join(ROOT, "app", "static", f), "utf8"); };
|
||||
function load(file) {
|
||||
return fs.readFileSync(path.join(__dirname, ".out", file), "utf8")
|
||||
.replace(/<link rel="stylesheet" href="\/static\/performance\.css[^"]*" \/>/, function () { return "<style>" + S("performance.css") + "</style>"; })
|
||||
.replace(/<script src="\/static\/performance-en\.js[^"]*" defer><\/script>/, function () { return "<script>" + S("performance-en.js") + "</script>"; })
|
||||
.replace(/<script src="\/static\/performance\.js[^"]*" defer><\/script>/, function () { return "<script>" + S("performance.js") + "</script>"; });
|
||||
}
|
||||
// 화면에 남은 한글 — .perf 안 + 실적 창·메뉴·말풍선 + 알림 창(글자·title·aria-label·placeholder), 한영 토글(translate=no) 빼고
|
||||
function leftovers() {
|
||||
const H = /[가-힣]/, out = [];
|
||||
const roots = Array.from(document.querySelectorAll('.perf, [class*="perf-"], .erp-dialog-backdrop')).filter(function (r) {
|
||||
return !r.parentElement || !r.parentElement.closest('.perf, [class*="perf-"], .erp-dialog-backdrop');
|
||||
});
|
||||
roots.forEach(function (r) {
|
||||
const tw = document.createTreeWalker(r, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
|
||||
for (let n = r; n; n = tw.nextNode()) {
|
||||
const el = n.nodeType === 1 ? n : n.parentElement;
|
||||
if (!el || el.closest("[translate='no'], script, style")) continue;
|
||||
if (n.nodeType === 3 && H.test(n.nodeValue)) out.push(n.nodeValue.trim());
|
||||
if (n.nodeType === 1) ["title", "aria-label", "placeholder"].forEach(function (a) { const v = n.getAttribute(a); if (v && H.test(v)) out.push("@" + a + ": " + v); });
|
||||
}
|
||||
});
|
||||
return Array.from(new Set(out.concat(window.__perfI18nMissing || [])));
|
||||
}
|
||||
|
||||
(async function () {
|
||||
const browser = await chromium.launch(process.env.PJ_TEST_BROWSER ? { executablePath: process.env.PJ_TEST_BROWSER } : {});
|
||||
const dialogs = [];
|
||||
async function open(file, url, api) {
|
||||
const p = await browser.newPage({ viewport: { width: 1400, height: 900 } });
|
||||
p.on("dialog", function (d) { dialogs.push(d.message()); d.accept().catch(function () {}); });
|
||||
await p.route("**/*", function (r) {
|
||||
if (!/\/api\//.test(r.request().url())) return r.fulfill({ status: 200, contentType: "text/html; charset=utf-8", body: load(file) });
|
||||
const res = api ? api(r.request()) : { status: 200, body: {} };
|
||||
r.fulfill({ status: res.status || 200, contentType: "application/json", body: JSON.stringify(res.body) });
|
||||
});
|
||||
await p.goto("http://perf.test" + url);
|
||||
return p;
|
||||
}
|
||||
try {
|
||||
// 매출 실적 — 표·그래프·업로드 창·메모 메뉴·메모 창·잘못된 입력 알림
|
||||
let p = await open("perf_my_dash_en.html", "/malaysia/performance/");
|
||||
check("번역 끝나면 화면 보임(is-i18n)", await p.$eval(".perf", function (r) { return r.classList.contains("is-i18n") && getComputedStyle(r).visibility === "visible"; }));
|
||||
check("탭·KPI 영문", /Sales/.test(await p.textContent(".perf-tabs")) && /last week/.test(await p.textContent(".perf-kpi-line")));
|
||||
await p.click("#perf-manual-upload");
|
||||
await p.waitForTimeout(150);
|
||||
let left = await p.evaluate(leftovers);
|
||||
check("매출 실적 + 업로드 창 — 한글 없음", left.length === 0, left);
|
||||
await p.keyboard.press("Escape");
|
||||
await p.click('td.is-manual-cell[data-manual-code="custom_tiktok_live"][data-date="2026-10-05"]', { button: "right" });
|
||||
await p.waitForTimeout(100);
|
||||
const ctx = await p.$$eval(".perf-ctx button", function (bs) { return bs.map(function (b) { return b.textContent.trim(); }); });
|
||||
check("메모 메뉴 영문", ctx.length > 0 && ctx.every(function (t) { return !/[가-힣]/.test(t); }), ctx);
|
||||
await p.click(".perf-ctx button");
|
||||
await p.waitForTimeout(150);
|
||||
left = await p.evaluate(leftovers);
|
||||
check("메모 창 — 한글 없음", left.length === 0, left);
|
||||
await p.keyboard.press("Escape");
|
||||
await p.click('td.is-manual-cell[data-manual-code="custom_shopee_live"][data-date="2026-10-06"]');
|
||||
await p.keyboard.type("12a");
|
||||
await p.keyboard.press("Enter");
|
||||
await p.waitForTimeout(300);
|
||||
await p.close();
|
||||
|
||||
p = await open("perf_my_dash_year_en.html", "/malaysia/performance/?period=year");
|
||||
left = await p.evaluate(leftovers);
|
||||
check("연간 보기 — 한글 없음", left.length === 0, left);
|
||||
await p.close();
|
||||
|
||||
// 광고비
|
||||
p = await open("perf_my_ads_en.html", "/malaysia/performance/ads");
|
||||
left = await p.evaluate(leftovers);
|
||||
check("광고비 — 한글 없음", left.length === 0, left);
|
||||
await p.close();
|
||||
|
||||
// 설정 — 수수료율 창·쇼핑몰 추가 창·삭제 확인
|
||||
p = await open("perf_my_settings_en.html", "/malaysia/performance/settings", function (req) {
|
||||
if (/manual-days/.test(req.url())) return { body: { days: 3 } };
|
||||
if (/rates/.test(req.url())) return { body: { rates: [{ id: 1, effective_from: "2026-10-01", rate: "5" }] } };
|
||||
return { status: 400, body: { detail: "기본 쇼핑몰은 삭제할 수 없습니다(사용을 끄세요)." } };
|
||||
});
|
||||
left = await p.evaluate(leftovers);
|
||||
check("설정 — 한글 없음", left.length === 0, left);
|
||||
await p.click('tr[data-code="custom_tiktok_shop"] [data-act="rate"]');
|
||||
await p.waitForTimeout(250);
|
||||
left = await p.evaluate(leftovers);
|
||||
check("수수료율 창 — 한글 없음", left.length === 0, left);
|
||||
await p.keyboard.press("Escape");
|
||||
await p.click("#perf-add-shop");
|
||||
await p.waitForTimeout(150);
|
||||
left = await p.evaluate(leftovers);
|
||||
check("쇼핑몰 추가 창 — 한글 없음", left.length === 0, left);
|
||||
await p.keyboard.press("Escape");
|
||||
await p.click('tr[data-code="custom_tiktok_shop"] [data-act="delete"]');
|
||||
await p.waitForTimeout(300);
|
||||
await p.close();
|
||||
|
||||
const bad = dialogs.filter(function (m) { return /[가-힣]/.test(m); });
|
||||
check("알림·확인 창 문구 영문(" + dialogs.length + "개)", dialogs.length >= 2 && bad.length === 0, { bad: bad, all: dialogs });
|
||||
} finally { await browser.close(); }
|
||||
console.log(fails.length ? "\n" + fails.length + " FAILED" : "\nALL PASS");
|
||||
process.exit(fails.length ? 1 : 0);
|
||||
})();
|
||||
@@ -168,17 +168,33 @@ def render_malaysia(e: jinja2.Environment, base: dict) -> None:
|
||||
"""말레이시아 실적(2026-11-20) — perf_my_dash.html · perf_my_ads.html (perf_malaysia.browser.test.js). 금액 = 센."""
|
||||
from app.modules.performance.tests.test_malaysia_variant import _Store # noqa: WPS433
|
||||
|
||||
from app.modules.live.holidays import holiday_names # noqa: WPS433
|
||||
|
||||
token = variant._current.set(variant.MY)
|
||||
try:
|
||||
mb = {**base, **variant.template_ctx(), "unit": "rm", "unit_label": "RM", "amt": lambda v: amount_text(v, "rm")}
|
||||
ctx = build_dashboard(_Store(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7))
|
||||
ctx.update(auto_sync=None, update_watch=None)
|
||||
with open(os.path.join(OUT_DIR, "perf_my_dash.html"), "w", encoding="utf-8") as f:
|
||||
f.write(e.get_template("performance/index.html").render(**mb, active_tab="dashboard", metric="gross", **ctx))
|
||||
actx = build_ad_dashboard(_Store(), kind="week", anchor=date(2026, 10, 7), today=date(2026, 10, 7), sales_codes=[])
|
||||
actx.update(auto_sync=None, update_watch=None)
|
||||
with open(os.path.join(OUT_DIR, "perf_my_ads.html"), "w", encoding="utf-8") as f:
|
||||
f.write(e.get_template("performance/ads.html").render(**mb, active_tab="ads", **actx))
|
||||
# 한글(perf_my_*.html) + 영문(perf_my_*_en.html, perf_malaysia_en.browser.test.js — 그룹 하나·연간 보기도)
|
||||
for lang, sfx in (("ko", ""), ("en", "_en")):
|
||||
ltoken = variant._lang.set(lang)
|
||||
try:
|
||||
mb = {**base, **variant.template_ctx(), "unit": "rm", "unit_label": "RM", "amt": lambda v: amount_text(v, "rm")}
|
||||
hol = holiday_names(lang)
|
||||
for kind, name in (("week", "dash"), ("year", "dash_year")):
|
||||
ctx = build_dashboard(_Store(), kind=kind, anchor=date(2026, 10, 7), today=date(2026, 10, 7), holidays=hol)
|
||||
ctx.update(auto_sync=None, update_watch=None)
|
||||
if kind == "year" and not sfx:
|
||||
continue
|
||||
with open(os.path.join(OUT_DIR, f"perf_my_{name}{sfx}.html"), "w", encoding="utf-8") as f:
|
||||
f.write(e.get_template("performance/index.html").render(**mb, active_tab="dashboard", metric="gross", **ctx))
|
||||
actx = build_ad_dashboard(_Store(), kind="month", anchor=date(2026, 10, 7), today=date(2026, 10, 7), sales_codes=[],
|
||||
holidays=hol)
|
||||
actx.update(auto_sync=None, update_watch=None)
|
||||
with open(os.path.join(OUT_DIR, f"perf_my_ads{sfx}.html"), "w", encoding="utf-8") as f:
|
||||
f.write(e.get_template("performance/ads.html").render(**mb, active_tab="ads", **actx))
|
||||
sctx = build_settings(_Store(), configured={}, key_info={"ok": True}, key_versions_in_use={}, sample_count=0)
|
||||
with open(os.path.join(OUT_DIR, f"perf_my_settings{sfx}.html"), "w", encoding="utf-8") as f:
|
||||
f.write(e.get_template("performance/settings.html").render(**mb, active_tab="settings", **sctx))
|
||||
finally:
|
||||
variant._lang.reset(ltoken)
|
||||
finally:
|
||||
variant._current.reset(token)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user