import { _ as policyIcon, a as transferIcon, b as bankIcon } from "../js/database-export-CGwyHyM--1776148658686.js"; import { _ as coinsIcon, a as cashIcon } from "../js/database-dollar-DDq4bT-e-1776148658686.js"; import { _ as arrowIcon } from "../js/arrow-Cf0JWzXk-1776148658686.js"; import { _ as helpIcon } from "../js/help-BgsLqEJs-1776148658686.js"; const API_BASE_URL = "https://jvapi.haiyihy.com"; const labels = { en: { agency_center: "Agency Center", my_available_salary: "My available salary", my_salary_details: "Salary details", today_host_task: "My task as a host today is:", host_type: "Host type", minutes: "Minutes", gift_task: "Gift Task", platform_policy: "Platform policy", exchange_coins: "Exchange coins", transfer: "Transfer", cash_withdraw: "Cash withdraw", bank_accounts: "Bank Accounts", team_member: "Team Member", team_bill: "Team Bill", invite_members: "Invite Members", prompt: "Prompt", fill_info_tips: "Please complete your withdrawal information first.", card_issue_tips: "Make sure the bank card and identity information are valid.", to_improve: "To improve", completed: "Completed", in_progress: "In progress", out_of_account: "Out of account", failed_to_load_data: "Failed to load data. Please try again." }, ar: {}, tr: {}, bn: {} }; let commonHeaders = { authorization: "Bearer undefined", "req-app-intel": "version=1.0.0;build=1;model=SM-G9550;sysVersion=9;channel=Google", "req-client": "Android", "req-imei": "8fa54d728ab449e04f9292329ed44bda", "req-lang": "id-ID", "req-sys-origin": "origin=ATYOU;originChild=ATYOU", "req-version": "V2", "req-zone": "Asia/Shanghai" }; const state = { lang: resolveLanguage(), userProfile: null, teamInfo: null, identityInfo: null, salaryInfo: { currentSalary: "0.00" }, taskInfo: { anchorType: "Chat", minutesProgress: 0, minutesTotal: 120, giftTask: 0 }, memberQuantity: 0, memberWorkTotal: "0.00", teamBill: { date: "–", hostSalary: "–", agentSalary: "–", total: "–", status: "–" }, bankCards: [], defaultBankCard: null, withdrawInfo: null, withdrawEnabled: false, showFillInfoModal: false }; const rolePriority = { guest: 0, anchor: 1, agent: 2, bd: 3, bdLeader: 4, freightAgent: 5, yumiManager: 6, admin: 7 }; const roleDefaultPages = { admin: "/admin-center", yumiManager: "/admin-center", freightAgent: "/coin-seller", agent: "/agency-center", bdLeader: "/bd-leader-center", bd: "/bd-center", anchor: "/host-center", guest: "/apply" }; const rolePages = { yumiManager: [ "/admin-center", "/invite-bd-leader", "/invite-bd", "/invite-recharge-agency", "/invite-agency", "/item-distribution", "/my-BDLeader-teams", "/my-BD-teams", "/my-agency-teams", "/my-recharge-agency", "/admin-policy" ], admin: [ "/admin-center", "/invite-bd-leader", "/invite-bd", "/invite-recharge-agency", "/invite-agency", "/item-distribution", "/my-BDLeader-teams", "/my-BD-teams", "/my-agency-teams", "/my-recharge-agency", "/admin-policy" ], freightAgent: ["/agency-center", "/coin-seller", "/seller-records", "/coin-seller-search"], agent: [ "/agency-center", "/transfer", "/exchange-gold-coins", "/message", "/platform-policy", "/agency-setting", "/team-member", "/information-details", "/history-salary", "/invite-members", "/team-bill" ], bdLeader: [ "/bd-leader-center", "/invite-bd-leader", "/invite-bd", "/bd-center", "/transfer", "/exchange-gold-coins", "/message", "/invite-agency", "/bd-item-distribution", "/team-member", "/history-salary", "/agency-list", "/available-income", "/income-details", "/policy", "/bd-list" ], bd: [ "/bd-center", "/transfer", "/exchange-gold-coins", "/message", "/invite-agency", "/bd-item-distribution", "/team-member", "/history-salary", "/agency-list", "/available-income", "/income-details", "/policy" ], anchor: [ "/host-center", "/transfer", "/exchange-gold-coins", "/message", "/platform-policy", "/host-setting", "/information-details", "/history-salary", "/invite-members", "/team-bill" ], guest: ["/apply", "/language"] }; const publicPages = [ "/apply", "/language", "/not_app", "/404", "/error", "/pay-result", "/map", "/top-list", "/weekly-star", "/ranking", "/games-king", "/couple", "/invitation-to-register", "/invitation/invite-new-user", "/recharge-reward", "/login-reward", "/activities/lesser-bairam", "/activities/lucky-dollars-season3", "/activities/spring-festival", "/recharge", "/recharge-pay-way", "/recharge-guide", "/recharge-agency-recruit", "/search-payee", "/cash-withdraw", "/cash-out", "/cash-out-details", "/bank-cards", "/bank-card", "/KYC", "/good-ID" ]; function resolveLanguage() { const params = new URLSearchParams(window.location.search); const hashQuery = window.location.hash.includes("?") ? window.location.hash.split("?")[1] : ""; const hashParams = new URLSearchParams(hashQuery); const lang = params.get("lang") || hashParams.get("lang") || navigator.language || "en"; if (lang.startsWith("ar")) return "ar"; if (lang.startsWith("tr")) return "tr"; if (lang.startsWith("bn")) return "bn"; return "en"; } function t(key) { return labels[state.lang]?.[key] || labels.en[key] || key; } function setLanguage() { document.documentElement.lang = state.lang; document.documentElement.dir = state.lang === "ar" ? "rtl" : "ltr"; document.querySelector("[data-action='language']").textContent = state.lang.toUpperCase(); document.querySelectorAll("[data-i18n]").forEach((node) => { node.textContent = t(node.dataset.i18n); }); } function setIcons() { const iconMap = { policy: policyIcon, transfer: transferIcon, bank: bankIcon, coins: coinsIcon, cash: cashIcon, arrow: arrowIcon, help: helpIcon }; document.querySelectorAll("[data-icon]").forEach((img) => { img.src = iconMap[img.dataset.icon] || ""; }); } function isMobileDevice() { return /Android|iPad|iPhone|iPod/.test(navigator.userAgent); } function isAppEnvironment() { return Boolean(window.app || window.webkit || window.FlutterPageControl); } function splitHeaderPairs(value) { const result = {}; if (!value) return result; value.split(";").forEach((item) => { const index = item.indexOf("="); if (index > -1) result[item.slice(0, index)] = item.slice(index + 1); }); return result; } function parseAccessOrigin(raw) { const data = JSON.parse(raw); const appIntel = splitHeaderPairs(data["Req-App-Intel"]); const sysOrigin = splitHeaderPairs(data["Req-Sys-Origin"]); return { reqLang: data["Req-Lang"], authorization: data.Authorization, buildVersion: appIntel.build, appVersion: appIntel.version, appChannel: appIntel.channel, reqImei: data["Req-Imei"], sysOrigin: sysOrigin.origin, sysOriginChild: sysOrigin.child }; } function setHeadersFromApp(headers) { const next = {}; if (headers.authorization) next.authorization = headers.authorization; if (headers.reqLang) next["req-lang"] = headers.reqLang; if (headers.appVersion || headers.buildVersion || headers.appChannel) { const intel = []; if (headers.appVersion) intel.push(`version=${headers.appVersion}`); if (headers.buildVersion) intel.push(`build=${headers.buildVersion}`); if (headers.appChannel) intel.push(`channel=${headers.appChannel}`); next["req-app-intel"] = intel.join(";"); } if (headers.reqImei) next["req-imei"] = headers.reqImei; if (headers.sysOrigin) { const origin = [`origin=${headers.sysOrigin}`]; if (headers.sysOriginChild) origin.push(`child=${headers.sysOriginChild}`); next["req-sys-origin"] = origin.join(";"); } commonHeaders = { ...commonHeaders, ...next }; } function requestAccessOrigin() { return new Promise((resolve) => { window.renderData = resolve; window.getIosAccessOriginParam = resolve; if (!isAppEnvironment()) { setHeadersFromApp({ authorization: "", reqLang: state.lang, appVersion: "1.0.0", buildVersion: "1", appChannel: "Web", reqImei: "H5-STATIC", sysOrigin: "LIKEI", sysOriginChild: "LIKEI" }); resolve(null); return; } let attempt = 0; const poll = () => { attempt += 1; if (window.app && typeof window.app.getAccessOrigin === "function") { resolve(window.app.getAccessOrigin()); return; } if (attempt < 50) { window.setTimeout(poll, 100); return; } if (window.FlutterApp && typeof window.FlutterApp.postMessage === "function") { window.FlutterApp.postMessage("requestAccessOrigin"); } }; if (isMobileDevice()) { poll(); return; } resolve(null); }); } async function connectToApp() { const raw = await requestAccessOrigin(); if (raw) setHeadersFromApp(parseAccessOrigin(raw)); } async function apiGet(path) { const response = await fetch(`${API_BASE_URL}${path}`, { method: "GET", headers: commonHeaders }); const data = await response.json().catch(() => ({})); if (!response.ok || data.status === false) { const error = new Error(data.errorMsg || data.message || `Request failed: ${response.status}`); error.response = data; throw error; } return data; } function readCachedJson(key) { const raw = localStorage.getItem(key); if (!raw) return null; try { return JSON.parse(raw); } catch (error) { console.warn(`Failed to parse ${key}:`, error); return null; } } function writeCachedJson(key, value) { if (value === null || value === undefined) { localStorage.removeItem(key); return; } localStorage.setItem(key, JSON.stringify(value)); } function getUserId() { return state.userProfile?.id || readCachedJson("userProfile")?.id || null; } function getTeamId() { return state.teamInfo?.id || readCachedJson("teamInfo")?.id || null; } function formatMoney(value) { if (value === null || value === undefined || value === "") return "0"; const number = Number(value); if (Number.isNaN(number)) return String(value); return number.toFixed(2); } function formatBillStatus(status) { return { SETTLED: t("completed"), UNPAID: t("in_progress"), HANG_UP: t("out_of_account"), PAY_OUT: t("completed") }[status] || status || "–"; } function getIdentityRoles(identity) { if (!identity) return ["guest"]; const roles = []; if (identity.freightAgent) roles.push("freightAgent"); if (identity.agent) roles.push("agent"); if (identity.bdLeader) roles.push("bdLeader"); if (identity.bd) roles.push("bd"); if (identity.anchor) roles.push("anchor"); if (identity.yumi_manager || identity.yumiManager) roles.push("yumiManager"); if (identity.admin) roles.push("admin"); return roles.length ? roles : ["guest"]; } function getPrimaryRole(roles) { return roles.reduce((primary, role) => (rolePriority[role] > rolePriority[primary] ? role : primary), "guest"); } function getAllowedPages(roles) { const pages = new Set([...publicPages, "/loading"]); roles.forEach((role) => { (rolePages[role] || []).forEach((page) => pages.add(page)); }); return pages; } function getCurrentRoutePath() { const pathWithoutSlash = window.location.pathname.replace(/\/+$/, "") || "/"; const pathWithoutIndex = pathWithoutSlash.replace(/\/index\.html$/, "") || "/"; return pathWithoutIndex.replace(/^\/h5(?=\/|$)/, "") || "/"; } function applyPermissionRedirect() { const roles = getIdentityRoles(state.identityInfo); const primaryRole = getPrimaryRole(roles); const allowedPages = getAllowedPages(roles); const currentPath = getCurrentRoutePath(); if (!allowedPages.has(currentPath)) { navigateTo(roleDefaultPages[primaryRole] || "/apply"); } } async function fetchIdentity() { const result = await apiGet("/app/h5/identity"); if (result.status && result.body) state.identityInfo = result.body; } async function fetchUserProfile() { const result = await apiGet("/team/member/profile"); if (result.status && result.body) { state.userProfile = result.body; writeCachedJson("userProfile", result.body); } } async function fetchTeamInfo() { const result = await apiGet("/team/entry"); if (result.status && result.body) { state.teamInfo = result.body.teamProfile || result.body; writeCachedJson("teamInfo", state.teamInfo); } else { state.teamInfo = null; writeCachedJson("teamInfo", null); } } async function fetchBankBalance() { const result = await apiGet("/wallet/bank/balance"); if (result.status && typeof result.body === "number") { state.salaryInfo.currentSalary = result.body.toFixed(2); } else { state.salaryInfo.currentSalary = "0"; } } async function fetchWorkStatistics() { const userId = getUserId(); if (!userId) return; const result = await apiGet(`/team/member/work/statistics-now?dataType=DAILY&memberId=${encodeURIComponent(userId)}`); if (result.status && result.body) { const ownTime = Number(result.body.ownTime) || 0; const otherTime = Number(result.body.otherTime) || 0; const progress = ownTime + otherTime; state.taskInfo.anchorType = "Chat"; state.taskInfo.minutesProgress = Math.min(progress, state.taskInfo.minutesTotal); state.taskInfo.giftTask = result.body.acceptGiftValue || 0; } } async function fetchMemberWorkTotal() { const userId = getUserId(); if (!userId) return; const result = await apiGet(`/team/member-work?userId=${encodeURIComponent(userId)}`); if (!result.status || !result.body) return; const targets = result.body.targets || []; const isAgent = Boolean(state.identityInfo?.agent); const isAnchor = Boolean(state.identityInfo?.anchor); const total = targets.reduce((sum, item, index) => { if (index === 0) return sum; const settlement = item.target?.settlementResult || {}; if (isAgent) { return sum + Number(settlement.ownSalary || 0) + Number(settlement.memberSalary || 0); } if (isAnchor) { return sum + Number(settlement.memberSalary || 0); } return sum; }, 0); state.memberWorkTotal = total.toFixed(2); } async function fetchTeamMemberCount() { const teamId = getTeamId(); if (!teamId) return; try { const result = await apiGet(`/team/members/count?id=${encodeURIComponent(teamId)}`); if (result.status && result.body) { state.memberQuantity = result.body.memberQuantity || 0; } } catch (error) { console.error("Failed to fetch team member count:", error); state.memberQuantity = 87; } } async function fetchTeamBill() { const teamId = getTeamId(); if (!teamId) return; const result = await apiGet(`/team/bill?id=${encodeURIComponent(teamId)}`); if (!result.status || !Array.isArray(result.body) || !result.body[0]) return; const bill = result.body[0]; const billBelong = String(bill.billBelong || ""); state.teamBill = { date: billBelong.length >= 6 ? `${billBelong.slice(0, 4)}.${billBelong.slice(4, 6)}` : "–", hostSalary: bill.settleResult?.memberSalary?.toFixed(2) || "–", agentSalary: bill.settleResult?.ownSalary?.toFixed(2) || "–", total: bill.settleResult?.totalSalary?.toFixed(2) || "–", status: formatBillStatus(bill.status) }; } async function fetchBankCards() { const result = await apiGet("/wallet/bank-card/list"); if (result.status && result.body) { state.bankCards = result.body; state.defaultBankCard = state.bankCards.find((card) => card.use) || null; } } async function fetchWithdrawInfo() { const result = await apiGet("/wallet/withdraw-info/list"); if (result.status && Array.isArray(result.body) && result.body.length > 0) { const info = result.body[0]; let previewUrls = []; try { previewUrls = JSON.parse(info.passportFrontUrl || "[]").map((item) => item); } catch (error) { console.warn("Failed to parse withdraw info preview urls:", error); } state.withdrawInfo = { ...info, previewUrls }; } } async function fetchWithdrawEnabled() { const result = await apiGet("/wallet/bank/host-salary/withdraw/enabled"); if (result.status) state.withdrawEnabled = Boolean(result.body); } function render() { document.getElementById("currentSalary").textContent = `$${state.salaryInfo.currentSalary}`; document.getElementById("anchorType").textContent = state.taskInfo.anchorType; document.getElementById("minutesProgress").textContent = state.taskInfo.minutesProgress; document.getElementById("minutesTotal").textContent = state.taskInfo.minutesTotal; document.getElementById("giftTask").textContent = state.taskInfo.giftTask; document.querySelectorAll(".cash-withdraw-row").forEach((node) => { node.hidden = !state.withdrawEnabled; }); document.getElementById("fillInfoModal").hidden = !state.showFillInfoModal; } function showToast(message) { const toast = document.getElementById("toast"); toast.textContent = message; toast.hidden = false; window.clearTimeout(showToast.timer); showToast.timer = window.setTimeout(() => { toast.hidden = true; }, 2500); } function closePage() { if (window.history.length > 1) { window.history.back(); return; } if (window.app && typeof window.app.closePage === "function") { window.app.closePage(); return; } if (window.FlutterPageControl && typeof window.FlutterPageControl.postMessage === "function") { window.FlutterPageControl.postMessage("close_page"); } } function navigateTo(target) { const url = new URL(target, window.location.origin); const currentLang = new URLSearchParams(window.location.search).get("lang"); if (currentLang && !url.searchParams.has("lang")) url.searchParams.set("lang", currentLang); window.location.href = `${url.pathname}${url.search}${url.hash}`; } function openCashWithdraw() { if (!state.withdrawInfo || !state.defaultBankCard) { state.showFillInfoModal = true; render(); return; } navigateTo("/cash-withdraw"); } function bindEvents() { const actions = { back: closePage, language: () => navigateTo("/language"), message: () => navigateTo("/message"), salaryDetails: () => navigateTo("/history-salary"), platformPolicy: () => navigateTo("/platform-policy?from=agencycenter"), exchangeCoins: () => navigateTo("/exchange-gold-coins"), transfer: () => navigateTo("/transfer"), cashWithdraw: openCashWithdraw, bankAccounts: () => navigateTo("/agency-setting"), teamMember: () => navigateTo(`/team-member?source=agency-center&members=${state.memberQuantity}`), teamBill: () => navigateTo("/team-bill"), inviteMembers: () => navigateTo("/invite-members"), completeInfo: () => navigateTo("/agency-setting") }; document.querySelectorAll("[data-action]").forEach((node) => { const handler = actions[node.dataset.action]; if (handler) node.addEventListener("click", handler); }); document.getElementById("fillInfoModal").addEventListener("click", (event) => { if (event.target.id === "fillInfoModal") { state.showFillInfoModal = false; render(); } }); } async function initializeData() { const firstWave = [ fetchUserProfile(), fetchTeamInfo(), fetchBankBalance(), fetchWithdrawEnabled(), fetchBankCards(), fetchWithdrawInfo(), fetchIdentity() ]; const firstResults = await Promise.allSettled(firstWave); firstResults.forEach((result) => { if (result.status === "rejected") console.warn("Agency center data request failed:", result.reason); }); applyPermissionRedirect(); const secondWave = [ fetchWorkStatistics(), fetchTeamMemberCount(), fetchTeamBill(), fetchMemberWorkTotal() ]; const secondResults = await Promise.allSettled(secondWave); secondResults.forEach((result) => { if (result.status === "rejected") console.warn("Agency center dependent request failed:", result.reason); }); } async function init() { setLanguage(); setIcons(); bindEvents(); render(); localStorage.setItem("identity", JSON.stringify({ identity: "AGENCY" })); localStorage.removeItem("payee"); try { await connectToApp(); await initializeData(); } catch (error) { console.warn("Agency center initialization failed:", error); showToast(error.response?.errorMsg || error.message || t("failed_to_load_data")); } finally { render(); } } init();