Merchant Portal

Đăng nhập để theo dõi dòng tiền thời gian thực.

Overview

❓ Guide

Financial Overview

Loading domains...

Gross Volume

$0.00

Total Fees

-$0.00

Net Revenue

$0.00

Conversion Rate

0%

Drop-off Rate

0%

Recent Transactions

Order ID Payment Date Amount (Gross) Fees Net Amount Status
Loading data...

Quản Lý Đơn Hàng

Chi tiết mọi luồng tiền vào hệ thống. Các đơn "Đã chốt" đã được thanh toán về ví của bạn.

🛒 SỐ LƯỢNG ĐƠN (ĐÃ LỌC)

0 đơn

0 thành công | 0 đang chờ

💰 TỔNG THU ĐÃ LỌC (GROSS)

$0.00

Tính trên các đơn Paid

🔻 PHÍ & PHẠT (TRONG KỲ LỌC)

-$0.00

Phí cổng, thuê & hoàn/phạt

✨ THỰC NHẬN ĐÃ LỌC (NET)

$0.00

Chưa chốt: $0.00
Order ID / Customer Website Gate (Cổng) Amount (Gross) Date Status Action
Đang tải dữ liệu...

Gateway Analytics

Gateway Performance (Based on Orders)

Gateway NamePaid OrdersGross VolumeTotal FeesNet Revenue
No successful transactions yet.

Daily Volume Limits (Your Gateways)

TypeNode / Gateway NameDaily LimitUsed TodayRemainingProgress
No active gateways configured.

Kế Toán & Rút Tiền

Số Dư Khả Dụng & Rút Tiền

CÓ THỂ RÚT (AVAILABLE BALANCE)

$0.00

Thông Tin Nhận Tiền

* Hiện tại hệ thống chỉ hỗ trợ thanh toán qua Wordfist.

Lịch Sử Rút Tiền (Payout Requests)

Ngày Yêu CầuTài Khoản NhậnSố TiềnTrạng Thái / Proof
Đang tải dữ liệu...

Revenue Reconciliation & Settlement History

Settled DatePeriodOrdersGrossTotal FeesNet PayoutPDF Invoice
No settlement records yet.

Accounting & Revenue Reconciliation

Reconcile unsettled orders by website, deduct gateway/refund/dispute fees, and lock periods with PDF invoices.

1. Unsettled Revenue by Website

Website / Period Unsettled Orders Gross Volume Fees / Refund / Dispute Net Revenue Action
Loading reconciliation...

2. Locked Settlement History (PDF Invoices)

Settled Date Website / Target Period Orders Gross Total Fees Net Amount Action
No settlement records yet.

Payout & Account Reconciliation Ledger

Track payouts from gateways to your Bank, verify actual Bank receipt, log outgoing transfers, and export PDF statements.

1. Account Balance Summary (Verified vs Pending Bank)

Gateway Account Gross Payout In Verified in Bank Total Fees Net Payable Sent Out ⚖️ Remaining
Loading account balances...

📥 Record Incoming Payout (Gateway → Bank)

Estimated Net After Fees: $0.00

📤 Record Outgoing Transfer (Send to Partner / Wallet)

2. Detailed Payout & Bank Verification Ledger

to
Date Account Type Gross / Sent Fees / Net Bank Verification Details / Proof Action
No payout records yet.

Payment Gateways Configuration

Connect your own Stripe Holder (Web B), Shopify, PayPal, or Crypto gateways.

🔀 Master Routing Switch (Primary Gateway)
Select your #1 priority gateway. Automatic failover will route to other active gateways if limits are reached.

Add New Payment Gateway

Your Configured Gateways

Gateway / Name Endpoint / Limits Active Action
Loading gateways...

Website Management & Gateway Routing

Add your stores, assign specific payment gateways per website, and toggle collection on/off.

Add New Website

Loading your gateways...
Enable Payment Collection
Allow this website to accept payments immediately

Connected Websites

Website URL Assigned Gateways Collect Action
Loading websites...

Sub-User Management (Resell)

Create sub-accounts for your clients, assign websites, and control which gateways they can use.

🔗 Client Login URL:

Create New Sub-User

Loading gateways...

Active Sub-Users

Username / Login Websites Assigned Gateways Action
Loading sub-users...

Global Anti-Fraud Blacklist Shield

Block high-risk buyers across all connected stores. Reports are aggregated network-wide to protect all payment gateways.

🛡️ Protected by 0 Global Entries

Report Fraudulent Buyer

Aggregated System Blacklist

Blocked Email / IP Reason Source Action
Loading global blacklist...

Cảnh Báo & Tự Động Hóa (Telegram)

Thiết Lập Bot Thông Báo

Nhập cấu hình Bot Telegram để nhận thông báo đơn hàng và mã 2FA.

Hướng dẫn:
  1. Chat với @BotFather trên Telegram để tạo Bot và lấy Token.
    • Các câu lệnh theo thứ tự: /start > /newbot
    • /start > Chọn NameBot > Lấy mã "HTTP API"
  2. Chat với @userinfobot để lấy Chat ID của bạn.

Tuỳ Chọn Thông Báo

Tích Hợp & Plugin

🔹 techiReg for WooCommerce

Phiên bản: Mới nhất

✓ Plugin WooCommerce
⬇️ Tải Plugin (.zip)

🔸 techiReg for Magento 2

Phiên bản: Mới nhất

✓ Module Magento 2
⬇️ Tải Module (.zip)

💳 techiReg Stripe Holder (Website B)

Version: v1.0.0 (Latest)

✓ Stealth Stripe Bridge Plugin (WordPress)
⬇️ Download (.zip)

🌟 Lưu ý: Cổng "VIP Custom Invoice (Manual)"

Đây là cổng thanh toán đặc biệt dành cho khách hàng mua số lượng lớn hoặc khi cổng thanh toán chính bảo trì. Quy trình hoạt động như sau:

  • Khách hàng chọn phương thức này và đặt hàng trên website của bạn.
  • Đơn hàng sẽ ngay lập tức được chốt thành công trên web và đưa vào trạng thái On-Hold (Tạm giữ). Hệ thống không gọi API sang techiReg.
  • Bạn sẽ nhận được thông báo qua Telegram/Email về đơn hàng VIP này.
  • Bạn dùng tài khoản Stripe/PayPal của mình tạo một hóa đơn thủ công (Payment Link) và gửi qua email cho khách hàng để họ thanh toán.
  • Sau khi khách thanh toán xong hóa đơn, bạn vào web đổi trạng thái đơn thành Processing/Completed.

Hệ thống techiReg sử dụng cơ chế Định tuyến Tên miền (Domain Routing). Bạn không cần API Key, chỉ cần 3 bước:

1
Cài đặt Plugin:
Tải plugin ở thẻ bên cạnh. Vào WordPress Admin > Plugins > Add New > Upload Plugin và Kích hoạt.
2
Bật cổng thanh toán:
Đi tới WooCommerce > Settings > Payments. Bật các cổng thanh toán techiReg mà bạn muốn cung cấp cho khách.
3
Cấu hình Webhook:
Bấm Manage ở cổng thanh toán vừa bật. Dán đường dẫn Webhook dưới đây vào ô Webhook URL và lưu lại.
https://techireg.com/api/create-payment

Cài Đặt Tài Khoản & Bảo Mật

Thông Tin Hồ Sơ

Thay Đổi Mật Khẩu

👁️
👁️

Bảo Mật 2FA (Xác thực 2 bước)

Khi bật tính năng này, mỗi lần đăng nhập hệ thống sẽ gửi một mã PIN 6 số qua Bot Telegram của bạn để đảm bảo an toàn tuyệt đối cho dòng tiền.

Xác thực qua Telegram Đang tắt

Hỗ Trợ Kỹ Thuật (Admin Support)

Nếu bạn cần hỗ trợ tích hợp, báo cáo giao dịch lỗi hoặc yêu cầu rút tiền (Payout), vui lòng liên hệ trực tiếp với bộ phận Admin techiReg.

AD
techiReg Admin Support
💬 @techiReg_AI
Notification Message
`); win.document.close(); } // --- TÍNH NĂNG ĐỔI MẬT KHẨU --- function togglePasswordVis(inputId) { const input = document.getElementById(inputId); if (input.type === "password") { input.type = "text"; } else { input.type = "password"; } } async function changeClientPassword() { if(!currentUser) return; const oldPw = document.getElementById('old_client_password').value; const newPw = document.getElementById('new_client_password').value; if(!oldPw || !newPw) return showClientToast("Vui lòng điền đủ Mật khẩu cũ và mới!", true); if(oldPw !== currentUser.password) return showClientToast("Mật khẩu cũ không chính xác!", true); if(newPw.length < 6) return showClientToast("Mật khẩu mới phải có ít nhất 6 ký tự!", true); try { const res = await fetch(`${BASE_URL}/api/client/change-password`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, old_password: oldPw, new_password: newPw }) }); const data = await res.json(); if(data.status === 'success') { showClientToast("Đổi mật khẩu thành công!", false); currentUser.password = newPw; document.getElementById('old_client_password').value = ''; document.getElementById('new_client_password').value = ''; } else { showClientToast(data.message, true); } } catch(e) { showClientToast("Lỗi kết nối máy chủ.", true); } } // --- HÀM CHUYỂN ĐỔI TAB HƯỚNG DẪN WOOCOMMERCE & MAGENTO --- function switchGuideTab(tab, btnElement) { document.querySelectorAll('.guide-tab-btn').forEach(b => { b.classList.remove('active'); b.style.color = '#64748b'; b.style.borderBottomColor = 'transparent'; }); btnElement.classList.add('active'); btnElement.style.color = 'var(--primary)'; btnElement.style.borderBottomColor = 'var(--primary)'; document.querySelectorAll('.guide-content').forEach(c => c.style.display = 'none'); document.getElementById('guide-' + tab).style.display = 'block'; } // ======================================================== // SUB-USER MANAGEMENT (RESELLER) // ======================================================== function toggleAllSubGws(cb) { document.querySelectorAll('.sub-gw-cb').forEach(el => { el.checked = false; el.disabled = cb.checked; }); } async function loadSubUsers() { if (!currentUser) return; const tbody = document.getElementById('subusers_table_body'); const badge = document.getElementById('subuser_quota_badge'); const gwBox = document.getElementById('sub_gw_list'); const urlEl = document.getElementById('subuser_login_url_text'); if (urlEl) urlEl.innerText = window.location.origin + '/client'; if (!tbody) return; try { const res = await fetch(`${BASE_URL}/api/client/subusers/list`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password }) }); const data = await res.json(); if (data.status === 'success') { const list = data.subusers || []; cachedTenantGws = data.gateways || []; const maxSub = data.quota?.max_subusers || 2; if (badge) badge.innerText = `Quota: ${list.length} / ${maxSub} Sub-Users`; // Render checkbox chọn cổng cho form tạo Sub-User if (gwBox) { if (!cachedTenantGws.length) { gwBox.innerHTML = 'No gateways configured yet. Add gateways in Gateways Config first.'; } else { const isAll = document.getElementById('sub_gw_all')?.checked; gwBox.innerHTML = ''; cachedTenantGws.forEach(g => { const statusDot = g.is_active == 1 ? '🟢' : '🔴'; gwBox.innerHTML += ``; }); } } if (list.length === 0) { tbody.innerHTML = 'No sub-users created yet.'; return; } tbody.innerHTML = ''; list.forEach(s => { const gwsStr = (!s.allowed_gateways || s.allowed_gateways.toUpperCase() === 'ALL') ? 'ALL' : s.allowed_gateways; const gwBadges = gwsStr === 'ALL' ? `` : gwsStr.split(',').map(x => `${x.trim()}`).join(''); const safeSites = (s.allowed_sites || '').replace(/'/g, "\\'"); const safeGws = gwsStr.replace(/'/g, "\\'"); tbody.innerHTML += ` ${s.username}
${s.allowed_sites || 'All assigned'} ${gwBadges}
`; }); } else { tbody.innerHTML = `${data.message}`; } } catch (e) { tbody.innerHTML = 'Connection error.'; } } async function createSubUser() { if (!currentUser) return; const sub_username = document.getElementById('sub_username').value.trim(); const sub_password = document.getElementById('sub_password').value.trim(); const sub_allowed_sites = document.getElementById('sub_allowed_sites').value.trim(); const sub_permissions = document.getElementById('sub_permissions').value; if (!sub_username || !sub_password) return showClientToast("Please enter Username and Password!", true); if (sub_password.length < 6) return showClientToast("Password must be at least 6 characters!", true); const isAll = document.getElementById('sub_gw_all')?.checked; let sub_allowed_gateways = 'ALL'; if (!isAll) { const picked = Array.from(document.querySelectorAll('.sub-gw-cb:checked')).map(cb => cb.value); if (!picked.length) return showClientToast("Please select at least 1 gateway or check 'All Active Gateways'!", true); sub_allowed_gateways = picked.join(', '); } try { const res = await fetch(`${BASE_URL}/api/client/subusers/add`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password, sub_username, sub_password, sub_allowed_sites, sub_allowed_gateways, sub_permissions }) }); const data = await res.json(); if (data.status === 'success') { showClientToast(`Sub-user "${sub_username}" created successfully!`, false); document.getElementById('sub_username').value = ''; document.getElementById('sub_password').value = ''; document.getElementById('sub_allowed_sites').value = ''; loadSubUsers(); } else { showClientToast(data.message || "Failed to create sub-user.", true); } } catch (e) { showClientToast("Server connection error.", true); } } // ======================================================== // RESET PASS SUB-USER + TENANT GATEWAYS + STRIPE HOLDER PLUGIN + I18N // ======================================================== async function editSubUserPass(subId, subName, curSites, curPerm) { const newPass = prompt(`Reset password for sub-user "${subName}" (leave blank to keep current):`, ""); if (newPass === null) return; const newSites = prompt(`Assigned Websites for "${subName}" (comma-separated):`, curSites); if (newSites === null) return; try { const res = await fetch(`${BASE_URL}/api/client/subusers/update`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password, sub_id: subId, new_password: newPass.trim(), sub_allowed_sites: newSites.trim(), sub_permissions: curPerm }) }); if ((await res.json()).status === 'success') { showClientToast(`Updated sub-user "${subName}"!`, false); loadSubUsers(); } else showClientToast("Update failed.", true); } catch (e) { showClientToast("Connection error.", true); } } async function loadTenantGateways() { if (!currentUser) return; const tbody = document.getElementById('tenant_gateways_body'); const badge = document.getElementById('gw_quota_badge'); if (!tbody) return; try { const res = await fetch(`${BASE_URL}/api/client/gateways/list`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password }) }); const data = await res.json(); if (data.status === 'success') { const list = data.gateways || []; if (badge) badge.innerText = `Quota: ${list.length} / ${data.max_gateways || 3} Gateways`; if (!list.length) return tbody.innerHTML = 'No gateways configured yet. Add your first gateway on the left.'; tbody.innerHTML = ''; list.forEach(g => { const checked = g.is_active == 1 ? 'checked' : ''; tbody.innerHTML += ` ${g.account_name}
${g.gateway_type}${(g.gateway_type === 'shopify' && g.extra_config && g.extra_config.includes('admin_access_token')) ? ' ' : ''} ${g.domain_url || 'API Direct'}
Limit: ${g.daily_limit > 0 ? '$'+g.daily_limit+'/day' : '∞'} | Max: ${g.max_per_order > 0 ? '$'+g.max_per_order : '∞'} `; }); } } catch (e) { tbody.innerHTML = 'Connection error.'; } } async function addTenantGateway() { if (!currentUser) return; const payload = { username: currentUser.username, password: currentUser.password, gateway_type: document.getElementById('tgw_type').value, account_name: document.getElementById('tgw_name').value.trim(), domain_url: document.getElementById('tgw_url').value.trim(), api_key: document.getElementById('tgw_key').value.trim(), extra_config: (document.getElementById('tgw_type').value === 'shopify' && document.getElementById('tgw_shopify_token')?.value.trim()) ? JSON.stringify({ shopify_mode: 'api', admin_access_token: document.getElementById('tgw_shopify_token').value.trim() }) : '', daily_limit: document.getElementById('tgw_daily').value, max_per_order: document.getElementById('tgw_max').value }; if (!payload.account_name || (!payload.api_key && !payload.extra_config)) return showClientToast("Please enter Account Name and API Key / Token!", true); try { const res = await fetch(`${BASE_URL}/api/client/gateways/add`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); const data = await res.json(); if (data.status === 'success') { showClientToast(`Added gateway "${payload.account_name}"!`, false); document.getElementById('tgw_name').value = ''; document.getElementById('tgw_url').value = ''; document.getElementById('tgw_key').value = ''; if (document.getElementById('tgw_shopify_token')) document.getElementById('tgw_shopify_token').value = ''; loadTenantGateways(); } else showClientToast(data.message || "Failed to add gateway.", true); } catch (e) { showClientToast("Connection error.", true); } } async function toggleTenantGateway(gwId, isActive) { try { await fetch(`${BASE_URL}/api/client/gateways/toggle`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password, gateway_id: gwId, is_active: isActive }) }); showClientToast(isActive ? "Gateway enabled!" : "Gateway paused safely.", false); } catch (e) {} } async function deleteTenantGateway(gwId, gwName) { if (!confirm(`Delete gateway "${gwName}"?`)) return; try { await fetch(`${BASE_URL}/api/client/gateways/delete`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password, gateway_id: gwId }) }); showClientToast(`Deleted "${gwName}".`, false); loadTenantGateways(); } catch (e) {} } async function loadPublicPlugins() { try { const res = await fetch(`${BASE_URL}/api/public/plugins`); const d = await res.json(); if (d.status === 'success' && d.stripe_holder) { const lnk = document.getElementById('stripe_holder_download_link'); const ver = document.getElementById('display_stripe_holder_version'); const cl = document.getElementById('display_stripe_holder_changelog'); if (lnk) lnk.href = d.stripe_holder.url || '#'; if (ver) ver.innerText = `Version: v${d.stripe_holder.version || '1.0.0'} (Latest)`; if (cl && d.stripe_holder.changelog) { cl.innerHTML = `✨ ${d.stripe_holder.changelog}`; cl.style.display = 'block'; } } } catch (e) {} } const portalI18n = { en: { m_overview: "📊 Overview", m_orders: "🛒 Order Management", m_gates: "🚥 Gateway Analytics", m_settlements: "📜 Revenue & Settlements", m_accounting: "🏦 Accounting & Recon", m_payout_ledger: "💳 Payout & Acc Ledger", m_gateways: "🔌 Gateways Config", m_blacklist: "🚫 Anti-Fraud Blacklist", m_domains: "🌐 Website Management", m_subusers: "👥 User Management", m_alerts: "🤖 Telegram Automation", m_plugin: "🔌 Plugin Integration", m_settings: "⚙️ Security & Settings", btn_logout: "Logout", ov_title: "Financial Overview", ov_export: "Export Quick Report (CSV)", ov_gross: "Gross Volume", ov_fees: "Total Fees", ov_net: "Net Revenue", ov_conv: "Conversion Rate", ov_drop: "Drop-off Rate", ov_recent: "Recent Transactions", th_oid: "Order ID", th_date: "Payment Date", th_gross: "Amount (Gross)", th_fees: "Fees", th_net: "Net Amount", th_status: "Status", ga_title: "Gateway Analytics", ga_perf: "Gateway Performance (Based on Orders)", ga_limits: "Daily Volume Limits (Your Gateways)", gw_title: "Payment Gateways Configuration", gw_sub: "Connect your own Stripe Holder (Web B), Shopify, PayPal, or Crypto gateways.", gw_add_head: "Add New Payment Gateway" }, vi: { m_overview: "📊 Tổng Quan", m_orders: "🛒 Quản Lý Đơn Hàng", m_gates: "🚥 Thống Kê Gate", m_settlements: "📜 Đối Soát Doanh Thu", m_accounting: "🏦 Kế Toán & Đối Soát", m_payout_ledger: "💳 Payout & Đối Soát Acc", m_gateways: "🔌 Cấu Hình Cổng (Gateways)", m_blacklist: "🚫 Danh Sách Đen", m_domains: "🌐 Quản Trị Website", m_subusers: "👥 Quản Lý Tài Khoản Phụ", m_alerts: "🤖 Tự Động Hóa (Bot)", m_plugin: "🔌 Tích Hợp Plugin", m_settings: "⚙️ Cài Đặt Bảo Mật", btn_logout: "Đăng xuất", ov_title: "Tổng Quan Tài Chính", ov_export: "Xuất Báo Cáo Nhanh (CSV)", ov_gross: "Tổng Thu (Gross)", ov_fees: "Tổng Phí & Phạt", ov_net: "Doanh Thu (Net)", ov_conv: "Tỷ Lệ Chốt Đơn", ov_drop: "Tỷ Lệ Rớt Đơn", ov_recent: "Giao Dịch Gần Đây", th_oid: "Mã Đơn (Order ID)", th_date: "Ngày Thanh Toán", th_gross: "Khách Trả (Gross)", th_fees: "Phí Bị Trừ", th_net: "Thực Nhận (Net)", th_status: "Trạng Thái", ga_title: "Thống Kê Gate (Cổng Thanh Toán)", ga_perf: "Hiệu Suất Theo Gate (Dựa trên dữ liệu đơn hàng)", ga_limits: "Giới Hạn Thu Trong Ngày (Daily Limits)", gw_title: "Cấu Hình Cổng Thanh Toán", gw_sub: "Tự thêm cổng Stripe Holder (Web B), Shopify, PayPal hoặc Crypto của riêng bạn.", gw_add_head: "Thêm Cổng Thanh Toán Mới" } }; // Bộ từ điển dịch toàn diện mọi danh mục, bảng, nút bấm & dữ liệu động (VI <-> EN) const fullDictPairs = [ ["Đăng nhập để theo dõi dòng tiền thời gian thực.", "Sign in to monitor your real-time payment routing & revenue."], ["Tên đăng nhập (Username)", "Username"], ["Mật khẩu (Password)", "Password"], ["Sai tên đăng nhập hoặc mật khẩu.", "Invalid username or password."], ["Xác thực 2 Bước", "Two-Factor Authentication (2FA)"], ["Mã PIN 6 số đã được gửi qua Bot Telegram của bạn.", "A 6-digit PIN has been sent to your Telegram Bot."], ["Nhập mã PIN...", "Enter 6-digit PIN..."], ["Xác Nhận Đăng Nhập", "Verify & Sign In"], ["Mã PIN không đúng hoặc đã hết hạn.", "Invalid or expired PIN."], ["Đăng Nhập", "Sign In"], ["Quay lại", "Back"], ["Tổng Quan (Overview)", "Overview"], ["Chi tiết mọi luồng tiền vào hệ thống. Các đơn \"Đã chốt\" đã được thanh toán về ví của bạn.", "Detailed log of all incoming transactions across your connected websites."], ["Tải Toàn Bộ Đơn Hàng (CSV)", "Export All Orders (CSV)"], ["🔍 Tìm Mã Đơn / Email Khách", "🔍 Search Order ID / Customer Email"], ["Nhập từ khóa...", "Search keyword..."], ["Tất cả Website", "All Websites"], ["🚥 Gate (Cổng)", "🚥 Gateway"], ["Tất cả Gate", "All Gateways"], ["🚦 Trạng Thái", "🚦 Status"], ["Mọi trạng thái", "All Statuses"], ["Thành công (Paid)", "Paid / Completed"], ["Đang chờ (Pending)", "Pending"], ["Lỗi / Dispute", "Error / Dispute"], ["Đã Hoàn tiền", "Refunded"], ["📅 Thời Gian", "📅 Time Range"], ["Tất cả thời gian", "All Time"], ["Hôm nay", "Today"], ["Tuần này", "This Week"], ["Tháng này", "This Month"], ["Tùy chỉnh...", "Custom Range..."], ["📅 Từ ngày:", "📅 From Date:"], ["📅 Đến ngày:", "📅 To Date:"], ["🛒 SỐ LƯỢNG ĐƠN (ĐÃ LỌC)", "🛒 FILTERED ORDERS"], ["💰 TỔNG THU ĐÃ LỌC (GROSS)", "💰 FILTERED GROSS"], ["🔻 PHÍ & PHẠT (TRONG KỲ LỌC)", "🔻 FEES & PENALTIES"], ["✨ THỰC NHẬN ĐÃ LỌC (NET)", "✨ FILTERED NET"], ["Tính trên các đơn Paid", "Calculated on Paid orders"], ["Phí cổng, thuê & hoàn/phạt", "Gateway & refund/dispute fees"], ["Gate (Cổng)", "Gateway"], ["Quản Lý Đơn Hàng", "Order Management"], ["Quản Trị Hệ Sinh Thái", "Website Management"], ["Quản lý các tên miền được phép kết nối.", "Manage all domains authorized to connect with your payment routing."], ["Danh Sách Tên Miền (Domains)", "Connected Domains"], ["+ Đề Xuất Tích Hợp Web Mới", "+ Add / Request New Website"], ["Tên Miền (URL)", "Domain (URL)"], ["Trạng Thái Kích Hoạt", "Status"], ["Hành Động", "Action"], ["Đang Kích Hoạt", "Active"], ["Gỡ Bỏ", "Remove"], ["Chưa có tên miền nào được tích hợp.", "No domains connected yet."], ["Cảnh Báo & Tự Động Hóa (Telegram)", "Telegram Alerts & Automation"], ["Thiết Lập Bot Thông Báo", "Configure Notification Bot"], ["Nhập cấu hình Bot Telegram để nhận thông báo đơn hàng và mã 2FA.", "Enter your Telegram Bot credentials to receive instant order alerts and 2FA codes."], ["💾 Lưu Cấu Hình Telegram", "💾 Save Telegram Config"], ["🔌 Kiểm Tra Kết Nối Bot", "🔌 Test Bot Connection"], ["Tuỳ Chọn Thông Báo", "Notification Preferences"], ["Nhận mã PIN đăng nhập 2FA.", "Receive 2FA login PIN codes."], ["Nhận thông báo khi có đơn", "Notify when an order is"], ["thành công.", "successfully."], ["Nhận cảnh báo khi đơn bị", "Alert when an order is"], ["Tích Hợp & Plugin", "Plugin Integration"], ["Vui lòng tải file .zip bên dưới và cài đè lên website.", "Please download the .zip file below and upload it to your website."], ["Vui lòng tải file .zip bên dưới và cập nhật qua Terminal.", "Please download the .zip file below and update via Terminal."], ["Phiên bản: Mới nhất", "Version: Latest"], ["⬇️ Tải Plugin (.zip)", "⬇️ Download Plugin (.zip)"], ["⬇️ Tải Module (.zip)", "⬇️ Download Module (.zip)"], ["🌟 Lưu ý: Cổng \"VIP Custom Invoice (Manual)\"", "🌟 Note: \"VIP Custom Invoice (Manual)\" Gateway"], ["Cài Đặt Tài Khoản & Bảo Mật", "Account & Security Settings"], ["Thông Tin Hồ Sơ", "Profile Information"], ["Tên Hiển Thị (Merchant Name)", "Merchant Name"], ["Thay Đổi Mật Khẩu", "Change Password"], ["Mật Khẩu Hiện Tại", "Current Password"], ["Nhập mật khẩu đang dùng...", "Enter current password..."], ["Mật Khẩu Mới", "New Password"], ["Nhập mật khẩu mới (ít nhất 6 ký tự)...", "Enter new password (min 6 chars)..."], ["Cập Nhật Mật Khẩu", "Update Password"], ["Bảo Mật 2FA (Xác thực 2 bước)", "2FA Security (Two-Factor Auth)"], ["Khi bật tính năng này, mỗi lần đăng nhập hệ thống sẽ gửi một mã PIN 6 số qua Bot Telegram của bạn để đảm bảo an toàn tuyệt đối cho dòng tiền.", "When enabled, every login requires a 6-digit PIN sent to your Telegram Bot for maximum security."], ["Xác thực qua Telegram", "Telegram Authentication"], ["Đang bật (An toàn)", "Enabled (Protected)"], ["Đang tắt", "Disabled"], ["Hỗ Trợ Kỹ Thuật (Admin Support)", "Technical Support"], ["Nếu bạn cần hỗ trợ tích hợp, báo cáo giao dịch lỗi hoặc yêu cầu rút tiền (Payout), vui lòng liên hệ trực tiếp với bộ phận Admin techiReg.", "Need help with plugin setup, gateway routing, or subscription upgrades? Contact techiReg Support directly."], ["Không có Gate nào được cấp quyền.", "No active gateways configured."], ["Chưa có giao dịch thành công.", "No successful transactions yet."], ["Chưa có giao dịch.", "No transactions yet."], ["Không tìm thấy đơn hàng phù hợp.", "No matching orders found."], ["Đang tải dữ liệu...", "Loading data..."], ["Thành công", "Paid"], ["Đang chờ", "Pending"], ["Không khả dụng", "N/A"], ["Y/c Refund", "Refund"], ["Nộp Bằng Chứng", "Submit Evidence"], ["Không giới hạn (Unlimited)", "Unlimited"], ["Phiên bản:", "Version:"], ["(Mới nhất)", "(Latest)"], // --- BỔ SUNG DỊCH 100% TAB TELEGRAM AUTOMATION --- ["VD: 123456789:ABCdefGHI...", "e.g. 123456789:ABCdefGHI..."], ["VD: 987654321", "e.g. 987654321"], ["Hướng dẫn:", "Instructions:"], ["trên Telegram để tạo Bot và lấy Token.", "on Telegram to create a Bot and get your Token."], ["để lấy Chat ID của bạn.", "to get your Chat ID."], ["Chat với", "Chat with"], ["Các câu lệnh theo thứ tự:", "Commands in order:"], ["Chọn NameBot > Lấy mã \"HTTP API\"", "Choose Bot Name > Copy the \"HTTP API\" token"], // --- BỔ SUNG DỊCH 100% TAB PLUGIN INTEGRATION --- ["Có bản cập nhật mới", "New update available"], ["Điểm mới ở bản", "What's new in"], ["Ghi chú:", "Note:"], ["Hệ thống techiReg sử dụng cơ chế Định tuyến Tên miền (Domain Routing). Bạn không cần API Key, chỉ cần 3 bước:", "techiReg uses Domain Routing. No API Key is required—just follow 3 simple steps:"], ["Cài đặt Plugin:", "Install Plugin:"], ["Tải plugin ở thẻ bên cạnh. Vào WordPress Admin >", "Download the plugin on the left. Go to WordPress Admin >"], ["và Kích hoạt.", "and Activate."], ["Bật cổng thanh toán:", "Enable Payment Gateways:"], ["Đi tới", "Go to"], [". Bật các cổng thanh toán techiReg mà bạn muốn cung cấp cho khách.", ". Enable the techiReg payment gateways you want to offer."], ["Cấu hình Webhook:", "Configure Webhook:"], ["Bấm", "Click"], ["ở cổng thanh toán vừa bật. Dán đường dẫn Webhook dưới đây vào ô Webhook URL và lưu lại.", "on the enabled gateway. Paste the Webhook URL below and click Save."], // --- BỔ SUNG DỊCH HƯỚNG DẪN MAGENTO 2 --- ["Hướng Dẫn Cài Đặt (Dành cho website Dùng Magento)", "Setup Guide (For Magento 2 Websites)"], ["Giải nén file:", "Extract Archive:"], ["Giải nén tệp", "Extract the"], ["vừa tải về. Bạn sẽ có một thư mục tên là", "file you downloaded. You will get a folder named"], ["Tải lên Server:", "Upload to Server:"], ["Truy cập vào thư mục gốc của website Magento, copy thư mục vừa giải nén thả vào đường dẫn:", "Go to your Magento root directory and upload the extracted folder to:"], ["(Lưu ý tạo thêm thư mục TechiReg/Payment nếu chưa có).", "(Create the TechiReg/Payment directory if it does not exist)."], ["Chạy Lệnh Kích Hoạt:", "Run Activation Commands:"], ["Mở cửa sổ dòng lệnh (Terminal/SSH) trỏ về thư mục gốc của Magento và chạy 3 lệnh sau:", "Open Terminal/SSH in your Magento root folder and run these 3 commands:"], ["✅ Vậy là xong! Nút thanh toán \"💳 Secured Payment (Credit Card / PayPal / Crypto)\" sẽ tự động xuất hiện tại trang Checkout Magento.", "✅ All done! The \"💳 Secured Payment (Credit Card / PayPal / Crypto)\" option will automatically appear on your Magento Checkout."], // --- BỔ SUNG DỊCH KHUNG VIP CUSTOM INVOICE --- ["Đây là cổng thanh toán đặc biệt dành cho khách hàng mua số lượng lớn hoặc khi cổng thanh toán chính bảo trì. Quy trình hoạt động như sau:", "This is a dedicated gateway for high-value orders or when primary gateways are under maintenance. How it works:"], ["Khách hàng chọn phương thức này và đặt hàng trên website của bạn.", "Customers select this method and place an order on your website."], ["Đơn hàng sẽ ngay lập tức được chốt thành công trên web và đưa vào trạng thái", "The order is immediately placed and set to"], ["On-Hold (Tạm giữ)", "On-Hold"], [". Hệ thống không gọi API sang techiReg.", ". No external API call is triggered."], ["Bạn sẽ nhận được thông báo qua Telegram/Email về đơn hàng VIP này.", "You will receive an instant Telegram/Email alert for this VIP order."], ["Bạn dùng tài khoản Stripe/PayPal của mình tạo một hóa đơn thủ công (Payment Link) và", "Create a manual Payment Link via your Stripe/PayPal account and"], ["gửi qua email cho khách hàng", "email it to the customer"], ["để họ thanh toán.", "to complete payment."], ["Sau khi khách thanh toán xong hóa đơn, bạn vào web đổi trạng thái đơn thành", "Once paid, update the order status on your website to"], ["website đang tích hợp.", "connected website(s)."], [" đơn", " orders"], [" thành công | ", " paid | "], [" đang chờ", " pending"], ["Chờ chốt sổ:", "Unsettled:"], ["Chưa chốt:", "Unsettled:"], ["Có ", "Active: "] ]; let isTranslatingDOM = false; function translateDOM(lang) { if (isTranslatingDOM) return; isTranslatingDOM = true; const fromIdx = lang === 'en' ? 0 : 1; const toIdx = lang === 'en' ? 1 : 0; const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, null, false); let node; while ((node = walker.nextNode())) { const pTag = node.parentElement?.tagName; if (!pTag || ['SCRIPT', 'STYLE', 'PRE', 'CODE'].includes(pTag)) continue; if (node.parentElement.hasAttribute('data-i18n')) continue; let text = node.nodeValue; if (!text || !text.trim()) continue; let updated = text; for (const pair of fullDictPairs) { if (updated.includes(pair[fromIdx])) { updated = updated.split(pair[fromIdx]).join(pair[toIdx]); } } if (updated !== text) node.nodeValue = updated; } document.querySelectorAll('input[placeholder], textarea[placeholder]').forEach(el => { let ph = el.getAttribute('placeholder'); let updated = ph; for (const pair of fullDictPairs) { if (updated.includes(pair[fromIdx])) updated = updated.split(pair[fromIdx]).join(pair[toIdx]); } if (updated !== ph) el.setAttribute('placeholder', updated); }); isTranslatingDOM = false; } function setPortalLang(lang) { if (!portalI18n[lang]) lang = 'en'; localStorage.setItem('techireg_lang', lang); const sel = document.getElementById('portalLangSelect'); if (sel) sel.value = lang; document.querySelectorAll('[data-i18n]').forEach(el => { const k = el.getAttribute('data-i18n'); if (portalI18n[lang][k]) el.innerText = portalI18n[lang][k]; }); translateDOM(lang); if (typeof renderHelpDrawerForTab === 'function') renderHelpDrawerForTab(currentPortalTab); } // Tự động dịch ngay cả khi bảng dữ liệu tải xong sau đăng nhập const domLangObserver = new MutationObserver(() => { const curLang = localStorage.getItem('techireg_lang') || 'en'; if (curLang === 'en') translateDOM('en'); }); domLangObserver.observe(document.body, { childList: true, subtree: true }); function updateGatewayFormFields() { const type = document.getElementById('tgw_type')?.value || 'stripe'; const wrapUrl = document.getElementById('wrap_tgw_url'); const lblUrl = document.getElementById('lbl_tgw_url'); const inpUrl = document.getElementById('tgw_url'); const lblKey = document.getElementById('lbl_tgw_key'); const inpKey = document.getElementById('tgw_key'); if (document.getElementById('wrap_tgw_shopify_api')) document.getElementById('wrap_tgw_shopify_api').style.display = 'none'; if (type === 'stripe') { wrapUrl.style.display = 'block'; lblUrl.innerText = 'Holder Website URL (Web B)'; inpUrl.placeholder = 'https://your-holder-site.com'; lblKey.innerText = 'Holder API Key'; inpKey.placeholder = 'Paste Holder API Key from Web B...'; } else if (type === 'shopify') { wrapUrl.style.display = 'block'; lblUrl.innerText = 'Shopify Store URL'; inpUrl.placeholder = 'https://your-store.myshopify.com'; lblKey.innerText = '$1 Product Variant ID (Fallback / Webhook)'; inpKey.placeholder = 'e.g. 44123456789012'; if (document.getElementById('wrap_tgw_shopify_api')) document.getElementById('wrap_tgw_shopify_api').style.display = 'block'; } else if (type === 'paypal') { wrapUrl.style.display = 'block'; lblUrl.innerText = 'PayPal.me Link (or Live Client ID)'; inpUrl.placeholder = 'https://paypal.me/yourname'; lblKey.innerText = 'PayPal Secret Key (type "payme" if using link)'; inpKey.placeholder = 'Secret Key or type: payme'; } else if (type === 'nowpayments') { wrapUrl.style.display = 'none'; inpUrl.value = ''; lblKey.innerText = 'NOWPayments API Key'; inpKey.placeholder = 'Paste NOWPayments API Key...'; } } let subTimerInterval = null; function startSubCountdown(planCode, expireDateStr) { const badge = document.getElementById('sub_countdown_badge'); if (!badge || !expireDateStr) return; badge.style.display = 'inline-block'; const targetTime = new Date(expireDateStr.replace(' ', 'T') + 'Z').getTime(); const updateTick = () => { const diff = targetTime - Date.now(); if (diff <= 0) { badge.style.background = '#fef2f2'; badge.style.color = '#dc2626'; badge.style.borderColor = '#fecaca'; badge.innerText = `⛔ ${planCode.toUpperCase()} • EXPIRED`; clearInterval(subTimerInterval); return; } const d = Math.floor(diff / 86400000); const h = Math.floor((diff % 86400000) / 3600000); const m = Math.floor((diff % 3600000) / 60000); const s = Math.floor((diff % 60000) / 1000); badge.innerText = `⏳ ${planCode.toUpperCase()} • ${d}d ${h}h ${m}m ${s}s left`; }; updateTick(); if (subTimerInterval) clearInterval(subTimerInterval); subTimerInterval = setInterval(updateTick, 1000); } // ======================================================== // WEBSITE MANAGEMENT + GATEWAY ASSIGNMENT LOGIC // ======================================================== let cachedTenantGws = []; function toggleAllNewWebGws(cb) { document.querySelectorAll('.new-web-gw-cb').forEach(el => { el.checked = false; el.disabled = cb.checked; }); } async function loadTenantWebsites() { if (!currentUser) return; const tbody = document.getElementById('domain_list_body'); const gwBox = document.getElementById('new_web_gw_list'); const badge = document.getElementById('web_quota_badge'); if (!tbody) return; try { const res = await fetch(`${BASE_URL}/api/client/websites/list`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password }) }); const data = await res.json(); if (data.status === 'success') { const sites = data.websites || []; cachedTenantGws = data.gateways || []; if (badge) badge.innerText = `Quota: ${sites.length} / ${data.max_websites || 3} Websites`; // Render danh sách checkbox cổng đã cài ở Gateways Config if (gwBox) { if (!cachedTenantGws.length) { gwBox.innerHTML = 'No gateways found. Please add gateways in Gateways Config first.'; } else { const isAll = document.getElementById('new_web_gw_all')?.checked; gwBox.innerHTML = ''; cachedTenantGws.forEach(g => { gwBox.innerHTML += ``; }); } } // Render bảng Website if (!sites.length) { tbody.innerHTML = 'No websites added yet. Add your first store on the left.'; return; } tbody.innerHTML = ''; sites.forEach(s => { const isAll = (!s.assigned_gateways || s.assigned_gateways === 'ALL'); const gwBadges = isAll ? `` : s.assigned_gateways.split(',').map(x => `${x.trim()}`).join(''); const checked = s.is_active == 1 ? 'checked' : ''; const safeUrl = s.domain_url.replace(/'/g, "\\'"); const safeGws = (s.assigned_gateways || 'ALL').replace(/'/g, "\\'"); tbody.innerHTML += ` ${s.domain_url} ${gwBadges}
`; }); } } catch (e) { tbody.innerHTML = 'Connection error.'; } } async function addTenantWebsite() { if (!currentUser) return; const domain_url = document.getElementById('new_web_url').value.trim(); if (!domain_url) return showClientToast("Please enter Website URL!", true); const isAll = document.getElementById('new_web_gw_all').checked; let assigned_gateways = 'ALL'; if (!isAll) { const picked = Array.from(document.querySelectorAll('.new-web-gw-cb:checked')).map(cb => cb.value); if (!picked.length) return showClientToast("Please select at least 1 gateway or check 'All Active Gateways'!", true); assigned_gateways = picked.join(', '); } const is_active = document.getElementById('new_web_active').checked; try { const res = await fetch(`${BASE_URL}/api/client/websites/add`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password, domain_url, assigned_gateways, is_active }) }); const d = await res.json(); if (d.status === 'success') { showClientToast(`Added ${domain_url} successfully!`, false); document.getElementById('new_web_url').value = ''; loadTenantWebsites(); } else showClientToast(d.message || "Failed to add website.", true); } catch (e) { showClientToast("Connection error.", true); } } async function toggleWebsiteActive(siteId, isActive) { try { await fetch(`${BASE_URL}/api/client/websites/update`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password, site_id: siteId, is_active: isActive }) }); showClientToast(isActive ? "Payment collection enabled!" : "Payment collection paused.", false); } catch (e) {} } // ======================================================== // QUICK SWITCH GATEWAYS MODAL (WEBSITE & SUB-USER) // ======================================================== let qsgTarget = { mode: '', id: null, label: '' }; function editWebsiteGateways(siteId, url, currentGws) { openQuickSwitchGw('website', siteId, url, currentGws); } function openQuickSwitchGw(mode, targetId, label, currentGws) { qsgTarget = { mode, id: targetId, label }; const modal = document.getElementById('quickSwitchGwModal'); const listBox = document.getElementById('qsg_checkbox_list'); const allCb = document.getElementById('qsg_all_cb'); document.getElementById('qsg_title').innerText = mode === 'website' ? `🔄 Switch Gateways: ${label}` : `🔄 Client Gateways: ${label}`; document.getElementById('qsg_subtitle').innerText = 'Tick the healthy gateways you want to route immediately. Uncheck any broken gateway.'; const isAll = (!currentGws || currentGws.toUpperCase() === 'ALL'); const selectedArr = isAll ? [] : currentGws.split(',').map(x => x.trim()); allCb.checked = isAll; if (!cachedTenantGws.length) { listBox.innerHTML = 'No gateways found in Gateways Config.'; } else { listBox.innerHTML = ''; cachedTenantGws.forEach(g => { const isChecked = !isAll && selectedArr.includes(g.account_name); const statusBadge = g.is_active == 1 ? '● Active' : '● Paused'; listBox.innerHTML += ` `; }); } modal.style.display = 'flex'; } function toggleQsgAll(cb) { document.querySelectorAll('.qsg-item-cb').forEach(el => { el.checked = false; el.disabled = cb.checked; }); } function closeQuickSwitchGw() { document.getElementById('quickSwitchGwModal').style.display = 'none'; } async function saveQuickSwitchGw() { const isAll = document.getElementById('qsg_all_cb').checked; let newGws = 'ALL'; if (!isAll) { const picked = Array.from(document.querySelectorAll('.qsg-item-cb:checked')).map(c => c.value); if (!picked.length) return showClientToast('Select at least 1 gateway or check All Active Gateways!', true); newGws = picked.join(', '); } try { if (qsgTarget.mode === 'website') { const res = await fetch(`${BASE_URL}/api/client/websites/update`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password, site_id: qsgTarget.id, assigned_gateways: newGws }) }); if ((await res.json()).status === 'success') { showClientToast(`Switched gateways for ${qsgTarget.label}!`, false); closeQuickSwitchGw(); loadTenantWebsites(); } } else if (qsgTarget.mode === 'subuser') { const res = await fetch(`${BASE_URL}/api/client/subusers/update`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password, sub_id: qsgTarget.id, sub_allowed_gateways: newGws }) }); if ((await res.json()).status === 'success') { showClientToast(`Updated gateways for client "${qsgTarget.label}"!`, false); closeQuickSwitchGw(); loadSubUsers(); } } } catch (e) { showClientToast('Connection error.', true); } } function copySubUserCreds(subUsername) { const text = `Portal Login URL: ${window.location.origin}/client\nUsername: ${subUsername}`; navigator.clipboard.writeText(text).then(() => { showClientToast(`Copied login URL & username for "${subUsername}"!`, false); }); } async function deleteTenantWebsite(siteId, url) { if (!confirm(`Delete website "${url}"?`)) return; try { await fetch(`${BASE_URL}/api/client/websites/delete`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password, site_id: siteId }) }); showClientToast(`Deleted ${url}.`, false); loadTenantWebsites(); } catch (e) {} } // ======================================================== // TENANT ACCOUNTING & RECONCILIATION LOGIC // ======================================================== let tenantSettledOrderIds = []; let tenantSettlementList = []; async function loadTenantAccounting() { if (!currentUser) return; try { const res = await fetch(`${BASE_URL}/api/client/accounting/data`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password }) }); const d = await res.json(); if (d.status === 'success') { tenantSettledOrderIds = (d.settled_orders || []).map(String); tenantSettlementList = d.settlements || []; renderTenantReconTable(); renderTenantSettlementHistory(); } } catch (e) {} } function renderTenantReconTable() { const tbody = document.getElementById('ta_recon_body'); if (!tbody) return; const tf = document.getElementById('ta_time_filter').value; const customWrap = document.getElementById('ta_custom_dates'); if (customWrap) customWrap.style.display = tf === 'CUSTOM' ? 'flex' : 'none'; const startD = document.getElementById('ta_start_date')?.value || ''; const endD = document.getElementById('ta_end_date')?.value || ''; const gwPct = parseFloat(document.getElementById('ta_gw_fee_pct')?.value) || 0; const opsPct = parseFloat(document.getElementById('ta_ops_fee_pct')?.value) || 0; let timeLabel = 'All Time'; if (tf === 'TODAY') timeLabel = 'Today'; else if (tf === 'WEEK') timeLabel = 'This Week'; else if (tf === 'MONTH') timeLabel = 'This Month'; else if (tf === 'CUSTOM') timeLabel = `${startD || '...'} to ${endD || '...'}`; const todayStr = new Date().toISOString().split('T')[0]; const monthStr = todayStr.substring(0, 7); const cNow = new Date(); const weekStart = new Date(cNow.setDate(cNow.getDate() - cNow.getDay())).toISOString().split('T')[0]; const settledSet = new Set(tenantSettledOrderIds); const validSt = ['completed', 'paid', 'processing', 'error', 'refund done']; const stats = {}; (rawClientData || []).forEach(r => { const st = (r.status || '').toLowerCase(); if (!validSt.includes(st)) return; if (settledSet.has(String(r.order_id))) return; let rDate = todayStr; if (r.created_at) { const dt = new Date(r.created_at + 'Z'); rDate = dt.getFullYear() + '-' + String(dt.getMonth() + 1).padStart(2, '0') + '-' + String(dt.getDate()).padStart(2, '0'); } if (tf === 'TODAY' && rDate !== todayStr) return; if (tf === 'WEEK' && rDate < weekStart) return; if (tf === 'MONTH' && !rDate.startsWith(monthStr)) return; if (tf === 'CUSTOM') { if (startD && rDate < startD) return; if (endD && rDate > endD) return; } const dom = (r.source_domain || 'Direct API').replace(/^https?:\/\//, '').replace(/\/$/, ''); if (!stats[dom]) stats[dom] = { orders: 0, gross: 0, gwFee: 0, opsFee: 0, penFee: 0, order_ids: [] }; const isPaid = ['completed', 'paid', 'processing'].includes(st); const amt = isPaid ? (parseFloat(String(r.amount).replace(/,/g, '')) || 0) : 0; stats[dom].orders++; stats[dom].order_ids.push(String(r.order_id)); stats[dom].gross += amt; stats[dom].gwFee += amt * (gwPct / 100); stats[dom].opsFee += amt * (opsPct / 100); stats[dom].penFee += (parseFloat(r.refund_amount) || 0) + (parseFloat(r.dispute_fee) || 0); }); const domains = Object.keys(stats); if (!domains.length) { tbody.innerHTML = 'All eligible orders in this period have been settled.'; return; } tbody.innerHTML = ''; domains.forEach(dom => { const s = stats[dom]; const totalFees = s.gwFee + s.opsFee + s.penFee; const net = s.gross - totalFees; const rowKey = dom.replace(/[^a-zA-Z0-9]/g, '_'); const encIds = encodeURIComponent(JSON.stringify(s.order_ids)); tbody.innerHTML += ` ${dom}
${timeLabel} ${s.orders} orders $${s.gross.toFixed(2)} GW (${gwPct}%): -$${s.gwFee.toFixed(2)}
Ops (${opsPct}%): -$${s.opsFee.toFixed(2)}
Ref/Disp: -$${s.penFee.toFixed(2)} $${net.toFixed(2)}
`; }); } function editTenantReconNet(rowKey, dom) { const el = document.getElementById(`ta_net_${rowKey}`); const cur = parseFloat((el?.innerText || '0').replace(/[^0-9.-]/g, '')) || 0; const nv = prompt(`Adjust Net Revenue for "${dom}":`, cur.toFixed(2)); if (nv !== null && !isNaN(nv)) { el.innerText = `$${parseFloat(nv).toFixed(2)}`; showClientToast('Net amount adjusted. Click "Settle & Lock" to save.', false); } } async function confirmTenantSettle(dom, timeLabel, ordersCount, gross, totalFees, rowKey, encIds) { const netVal = parseFloat((document.getElementById(`ta_net_${rowKey}`)?.innerText || '0').replace(/[^0-9.-]/g, '')) || 0; if (!confirm(`Confirm locking settlement for "${dom}" (${timeLabel})?\nOrders: ${ordersCount}\nGross: $${gross}\nNet: $${netVal.toFixed(2)}`)) return; const order_ids = JSON.parse(decodeURIComponent(encIds)); try { const res = await fetch(`${BASE_URL}/api/client/accounting/settle`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password, target_label: dom, time_range: timeLabel, total_orders: ordersCount, gross_amount: gross, total_fees: totalFees, net_amount: netVal, order_ids }) }); if ((await res.json()).status === 'success') { showClientToast(`Settled & locked ${ordersCount} orders for ${dom}!`, false); loadTenantAccounting(); } } catch (e) { showClientToast('Connection error.', true); } } function renderTenantSettlementHistory() { const tbody = document.getElementById('ta_history_body'); if (!tbody) return; if (!tenantSettlementList.length) { tbody.innerHTML = 'No settlement records yet.'; return; } tbody.innerHTML = ''; tenantSettlementList.forEach(s => { const dStr = s.created_at ? s.created_at.split(' ')[0] : ''; const enc = encodeURIComponent(JSON.stringify({ username: s.target_label, time_range: s.time_range, total_orders: s.total_orders, gross_amount: s.gross_amount, total_fees: s.total_fees, net_amount: s.net_amount, created_at: s.created_at })); tbody.innerHTML += ` ${dStr} ${s.target_label} ${s.time_range} ${s.total_orders} $${parseFloat(s.gross_amount).toFixed(2)} -$${parseFloat(s.total_fees).toFixed(2)} $${parseFloat(s.net_amount).toFixed(2)}
`; }); } async function deleteTenantSettlement(stlId) { if (!confirm('Delete this settlement record and unlock its orders back to Unsettled?')) return; try { const res = await fetch(`${BASE_URL}/api/client/accounting/delete`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password, settlement_id: stlId }) }); if ((await res.json()).status === 'success') { showClientToast('Settlement deleted & orders unlocked!', false); loadTenantAccounting(); } } catch (e) {} } // ======================================================== // TENANT PAYOUT & ACCOUNT LEDGER + BANK VERIFICATION + PDF // ======================================================== let tenantPayoutRows = []; function previewTplNet() { const amt = parseFloat(document.getElementById('tpl_in_amt')?.value) || 0; const gf = parseFloat(document.getElementById('tpl_in_gw_fee')?.value) || 0; const rf = parseFloat(document.getElementById('tpl_in_rent_fee')?.value) || 0; const net = amt - (amt * (gf + rf) / 100); const el = document.getElementById('tpl_in_net_preview'); if (el) el.innerText = `$${net.toFixed(2)}`; } async function loadTenantPayoutLedger() { if (!currentUser) return; const today = new Date().toISOString().split('T')[0]; if (document.getElementById('tpl_in_date') && !document.getElementById('tpl_in_date').value) document.getElementById('tpl_in_date').value = today; if (document.getElementById('tpl_out_date') && !document.getElementById('tpl_out_date').value) document.getElementById('tpl_out_date').value = today; try { const res = await fetch(`${BASE_URL}/api/client/payout-ledger/list`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password }) }); const d = await res.json(); if (d.status === 'success') { tenantPayoutRows = d.payouts || []; const accNames = [...new Set([...(d.gateways || []).map(g => g.account_name), ...tenantPayoutRows.map(p => p.gateway_account)])].filter(Boolean); const dl = document.getElementById('tpl_acc_datalist'); if (dl) dl.innerHTML = accNames.map(a => `' + accNames.map(a => ``).join(''); if (accNames.includes(cur)) fAcc.value = cur; } renderTenantPayoutLedger(); } } catch (e) {} } function getFilteredTenantPayouts() { const fAcc = document.getElementById('tpl_filter_acc')?.value || 'ALL'; const fFrom = document.getElementById('tpl_filter_from')?.value || ''; const fTo = document.getElementById('tpl_filter_to')?.value || ''; return tenantPayoutRows.filter(p => { if (fAcc !== 'ALL' && p.gateway_account !== fAcc) return false; if (fFrom && (p.payout_date || '') < fFrom) return false; if (fTo && (p.payout_date || '') > fTo) return false; return true; }); } function renderTenantPayoutLedger() { const list = getFilteredTenantPayouts(); const sBody = document.getElementById('tpl_summary_body'); const lBody = document.getElementById('tpl_ledger_body'); if (!sBody || !lBody) return; // 1. Account Summary const accMap = {}; list.forEach(p => { const k = p.gateway_account || 'Unknown'; if (!accMap[k]) accMap[k] = { gross: 0, verifiedGross: 0, fees: 0, net: 0, sent: 0 }; if (p.entry_type === 'send_out') { accMap[k].sent += parseFloat(p.sent_amount) || 0; } else { const g = parseFloat(p.amount) || 0; accMap[k].gross += g; if (p.bank_status === 'verified') accMap[k].verifiedGross += g; accMap[k].fees += parseFloat(p.fee_amount) || 0; accMap[k].net += parseFloat(p.net_amount) || 0; } }); const accKeys = Object.keys(accMap); if (!accKeys.length) { sBody.innerHTML = 'No account data yet. Record your first payout below.'; } else { sBody.innerHTML = ''; accKeys.forEach(k => { const a = accMap[k]; const rem = a.net - a.sent; sBody.innerHTML += ` ${k} $${a.gross.toFixed(2)} $${a.verifiedGross.toFixed(2)} -$${a.fees.toFixed(2)} $${a.net.toFixed(2)} $${a.sent.toFixed(2)} $${rem.toFixed(2)} `; }); } // 2. Detailed Ledger if (!list.length) { lBody.innerHTML = 'No records match this filter.'; return; } lBody.innerHTML = ''; list.forEach(p => { const isOut = p.entry_type === 'send_out'; const typeBadge = isOut ? `📤 Send Out` : ``; const bankCell = isOut ? `Transfer Logged` : (p.bank_status === 'verified' ? `` : ``); const proofHtml = p.proof_url ? `View Proof` : ''; const details = [p.recipient_id ? `To: ${p.recipient_id}` : '', p.note || '', proofHtml].filter(Boolean).join(' • '); lBody.innerHTML += ` ${p.payout_date || ''} ${p.gateway_account} ${typeBadge} $${(isOut ? parseFloat(p.sent_amount) : parseFloat(p.amount)).toFixed(2)} ${isOut ? '-' : `-$${parseFloat(p.fee_amount).toFixed(2)} → $${parseFloat(p.net_amount).toFixed(2)}`} ${bankCell} ${details || '-'} `; }); } async function submitTenantPayout(type) { if (!currentUser) return; let payload = { username: currentUser.username, password: currentUser.password, entry_type: type }; if (type === 'payout_in') { payload.gateway_account = document.getElementById('tpl_in_acc').value.trim(); payload.payout_date = document.getElementById('tpl_in_date').value; payload.amount = document.getElementById('tpl_in_amt').value; payload.gw_fee_percent = document.getElementById('tpl_in_gw_fee').value; payload.rental_fee_percent = document.getElementById('tpl_in_rent_fee').value; payload.note = document.getElementById('tpl_in_note').value.trim(); if (!payload.gateway_account || !payload.amount) return showClientToast('Please enter Account Name and Gross Payout!', true); } else { payload.gateway_account = document.getElementById('tpl_out_acc').value.trim(); payload.payout_date = document.getElementById('tpl_out_date').value; payload.sent_amount = document.getElementById('tpl_out_amt').value; payload.recipient_id = document.getElementById('tpl_out_rec').value.trim(); payload.proof_url = document.getElementById('tpl_out_proof').value.trim(); payload.note = document.getElementById('tpl_out_note').value.trim(); if (!payload.gateway_account || !payload.sent_amount) return showClientToast('Please enter Account Name and Amount Sent!', true); } try { const res = await fetch(`${BASE_URL}/api/client/payout-ledger/add`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); if ((await res.json()).status === 'success') { showClientToast(type === 'payout_in' ? 'Payout recorded (Pending Bank verification)!' : 'Outgoing transfer recorded!', false); if (type === 'payout_in') { document.getElementById('tpl_in_amt').value = ''; document.getElementById('tpl_in_note').value = ''; previewTplNet(); } else { document.getElementById('tpl_out_amt').value = ''; document.getElementById('tpl_out_proof').value = ''; document.getElementById('tpl_out_note').value = ''; } loadTenantPayoutLedger(); } } catch (e) { showClientToast('Connection error.', true); } } async function verifyTenantBankPayout(payoutId) { if (!confirm('Confirm that this payout amount has actually arrived in your Bank account?')) return; try { const res = await fetch(`${BASE_URL}/api/client/payout-ledger/verify-bank`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password, payout_id: payoutId }) }); if ((await res.json()).status === 'success') { showClientToast('✅ Bank receipt verified!', false); loadTenantPayoutLedger(); } } catch (e) {} } async function deleteTenantPayout(payoutId) { if (!confirm('Delete this ledger record?')) return; try { const res = await fetch(`${BASE_URL}/api/client/payout-ledger/delete`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ username: currentUser.username, password: currentUser.password, payout_id: payoutId }) }); if ((await res.json()).status === 'success') { showClientToast('Record deleted.', false); loadTenantPayoutLedger(); } } catch (e) {} } function exportTenantPayoutPDF() { const list = getFilteredTenantPayouts(); if (!list.length) return showClientToast('No records to export!', true); const fAcc = document.getElementById('tpl_filter_acc')?.value || 'ALL'; const fFrom = document.getElementById('tpl_filter_from')?.value || 'Start'; const fTo = document.getElementById('tpl_filter_to')?.value || 'Now'; let totGross = 0, totVerified = 0, totFees = 0, totNet = 0, totSent = 0; const rowsHtml = list.map(p => { const isOut = p.entry_type === 'send_out'; if (isOut) totSent += parseFloat(p.sent_amount) || 0; else { totGross += parseFloat(p.amount) || 0; if (p.bank_status === 'verified') totVerified += parseFloat(p.amount) || 0; totFees += parseFloat(p.fee_amount) || 0; totNet += parseFloat(p.net_amount) || 0; } return ` ${p.payout_date || ''} ${p.gateway_account} ${isOut ? 'Send Out' : 'Payout In'} $${(isOut ? parseFloat(p.sent_amount) : parseFloat(p.amount)).toFixed(2)} ${isOut ? '-' : '-$' + parseFloat(p.fee_amount).toFixed(2)} ${isOut ? '-' : '$' + parseFloat(p.net_amount).toFixed(2)} ${isOut ? (p.recipient_id || 'Transfer') : (p.bank_status === 'verified' ? 'Verified in Bank' : 'Pending Bank')} `; }).join(''); const win = window.open('', '_blank'); win.document.write(`Payout Statement - ${currentUser.username}

${currentUser.username} — Payout & Bank Statement

Account Filter: ${fAcc} | Period: ${fFrom} → ${fTo}

Gross Payout
$${totGross.toFixed(2)}
Verified in Bank
$${totVerified.toFixed(2)}
Net After Fees
$${totNet.toFixed(2)}
Total Sent Out
$${totSent.toFixed(2)}
Remaining
$${(totNet - totSent).toFixed(2)}
${rowsHtml}
DateAccountTypeAmountFeesNetBank Status / Recipient