// ─────────────────────────────────────────────────────────── // Huio Control Panel — Payments View (cp-payments-view.jsx) // P0: Organizer Payments Journal & Accounting (R2 Edition) // ─────────────────────────────────────────────────────────── if (!window.CP_STYLES) throw new Error('[cp-payments-view] window.CP_STYLES not loaded'); function formatVnd(amount) { if (amount === undefined || amount === null) return '0 ₫'; const num = typeof amount === 'string' ? parseInt(amount, 10) : amount; if (isNaN(num)) return '0 ₫'; return num.toLocaleString('vi-VN') + ' ₫'; } function formatDate(isoStr) { if (!isoStr) return '—'; try { const d = new Date(isoStr); if (isNaN(d.getTime())) return isoStr; return d.toLocaleDateString('vi-VN', { day: '2-digit', month: '2-digit', year: 'numeric' }); } catch { return isoStr; } } function formatDateTime(isoStr) { if (!isoStr) return '—'; try { const d = new Date(isoStr); if (isNaN(d.getTime())) return isoStr; return d.toLocaleString('vi-VN', { day: '2-digit', month: '2-digit', year: 'numeric', hour: '2-digit', minute: '2-digit' }); } catch { return isoStr; } } // ───── Standard Pricing Plans Specification (matching pricing.json & huio.vn) ───── const PRICING_PLANS = { organizer_basic: { id: 'organizer_basic', code: 'basic', nameVi: 'Gói Cơ bản', nameEn: 'Basic Plan', priceMonthly: 250000, priceYearly: 2400000, featuresVi: [ 'Tối đa 10 dây hụi đang chạy', 'Không giới hạn thành viên tham gia mỗi dây', '1 tài khoản ngân hàng nhận tiền', 'Đầy đủ tính năng tạo dây, kỳ, khui, hoa hồng, xuất phiếu', 'Lưu trữ đám mây, sao lưu và đồng bộ thời gian thực', 'Chưa bao gồm đối soát ngân hàng tự động' ], featuresEn: [ 'Up to 10 active groups', 'Unlimited members per group', '1 receiving bank account', 'Full rounds, bidding, dues, commission & statements export', 'Cloud storage and real-time synchronization', 'Does not include automated bank reconciliation' ] }, organizer_pro: { id: 'organizer_pro', code: 'pro', nameVi: 'Gói Pro', nameEn: 'Pro Plan', priceMonthly: 500000, priceYearly: 4800000, featuresVi: [ 'Không giới hạn dây hụi và thành viên', 'Tự động tính toán dòng tiền, hốt hụi, hoa hồng chính xác', 'Xuất sổ hụi, bảng kê chi tiết dạng hình ảnh/PDF/Excel gửi thành viên', 'Nhiều tài khoản ngân hàng nhận tiền', 'Đồng bộ và đối soát tự động qua VietQR ngân hàng (khi kích hoạt tiện ích)' ], featuresEn: [ 'Unlimited active groups and members', 'Automated cashflow, bidding calculation & commission', 'Batch export of statements in Image/PDF/Excel', 'Multiple receiving bank accounts', 'Automated bank reconciliation via VietQR' ] }, organizer_business: { id: 'organizer_business', code: 'business', nameVi: 'Gói Business', nameEn: 'Business Plan', priceMonthly: 750000, priceYearly: 7200000, featuresVi: [ 'Không giới hạn dây hụi và thành viên', 'Toàn bộ tính năng cao cấp của Gói Pro', 'Hỗ trợ kỹ thuật & vận hành ưu tiên 1:1, chuyên viên đồng hành', 'Cấu hình báo cáo riêng và hỗ trợ quy mô lớn' ], featuresEn: [ 'Unlimited active groups and members', 'All premium features of Pro Plan', 'Priority 1:1 operations and technical support', 'Custom report layouts & dedicated account manager' ] } }; function normalizePlanKey(planKey) { if (!planKey) return 'organizer_pro'; const clean = String(planKey).toLowerCase().trim(); if (clean === 'organizer_business' || clean === 'business') return 'organizer_business'; if (clean === 'organizer_basic' || clean === 'basic') return 'organizer_basic'; return 'organizer_pro'; } function getClientPlanName(planKey, lang = 'vi') { const normKey = normalizePlanKey(planKey); const planInfo = PRICING_PLANS[normKey]; return lang === 'vi' ? planInfo.nameVi : planInfo.nameEn; } function buildCskhConfirmationMessage({ userName = 'Chị', amountStr = '500.000 ₫', planKey = 'organizer_pro', periodEnd = null, externalRef = '', lang = 'vi' }) { const normKey = normalizePlanKey(planKey); const planInfo = PRICING_PLANS[normKey]; const planName = lang === 'vi' ? planInfo.nameVi : planInfo.nameEn; const expDate = periodEnd ? new Date(periodEnd).toLocaleDateString('vi-VN') : (lang === 'vi' ? '1 tháng' : '1 month'); const refStr = externalRef ? ` (Mã GD: ${externalRef.trim()})` : ''; const featuresList = (lang === 'vi' ? planInfo.featuresVi : planInfo.featuresEn) .map(f => f.startsWith('Chưa') || f.startsWith('Does not') ? `ℹ️ ${f}` : `✅ ${f}`) .join('\n'); if (lang === 'vi') { return `Dạ Huio xin chào chị ${userName},\n\nHuio đã nhận được khoản thanh toán ${amountStr} cho ${planName} (thời hạn đến ${expDate}${refStr}).\n\nTài khoản Chủ hụi của chị đã được kích hoạt đầy đủ các tính năng của ${planName}:\n${featuresList}\n\nChị vào lại ứng dụng Huio để bắt đầu sử dụng nhé: https://huio.app\nNếu cần hỗ trợ thêm trong quá trình tạo dây hụi, chị nhắn em bất cứ lúc nào nha! Em cảm ơn chị nhiều ạ ❤️`; } else { return `Hello ${userName},\n\nHuio has received your payment of ${amountStr} for ${planName} (valid until ${expDate}${refStr}).\n\nYour account is now active with ${planName} features:\n${featuresList}\n\nPlease reopen Huio app to continue: https://huio.app\nFeel free to contact us anytime if you need assistance! ❤️`; } } // ───── Modals ───── function ReceiptLightboxModal({ isOpen, onClose, receiptUrl, supabaseClient }) { const [signedUrl, setSignedUrl] = React.useState(''); const [loading, setLoading] = React.useState(true); React.useEffect(() => { if (!isOpen || !receiptUrl) { setSignedUrl(''); setLoading(false); return; } if (receiptUrl.startsWith('http://') || receiptUrl.startsWith('https://') || receiptUrl.startsWith('data:')) { setSignedUrl(receiptUrl); setLoading(false); return; } setLoading(true); if (supabaseClient?.storage) { supabaseClient.storage .from('payment-receipts') .createSignedUrl(receiptUrl, 3600) .then(({ data, error }) => { if (!error && data?.signedUrl) { setSignedUrl(data.signedUrl); } else { console.error('Failed to get signed url for receipt:', error); setSignedUrl(receiptUrl); } }) .catch(err => { console.error('Error creating signed url:', err); setSignedUrl(receiptUrl); }) .finally(() => setLoading(false)); } else { setSignedUrl(receiptUrl); setLoading(false); } }, [isOpen, receiptUrl, supabaseClient]); if (!isOpen || !receiptUrl) return null; return (
e.stopPropagation()} > {loading ? (
Đang tải biên lai...
) : ( Biên lai thanh toán )}
); } function RecordPaymentModal({ isOpen, onClose, users = [], onSubmit, lang = 'vi', t = (k) => k, preselectedUser = null, preselectedPlan = 'organizer_pro', supabaseClient = null }) { const [selectedUserId, setSelectedUserId] = React.useState(preselectedUser?.id || ''); const [paidAt, setPaidAt] = React.useState(() => { const now = new Date(); now.setMinutes(now.getMinutes() - now.getTimezoneOffset()); return now.toISOString().slice(0, 16); }); const [method, setMethod] = React.useState('bank_transfer'); const [externalRef, setExternalRef] = React.useState(''); const [payerName, setPayerName] = React.useState(''); // Subscription parameters const [hasSub, setHasSub] = React.useState(true); const [plan, setPlan] = React.useState(normalizePlanKey(preselectedPlan)); const [billingCycle, setBillingCycle] = React.useState('monthly'); // 'monthly' | 'yearly' const [periodStart, setPeriodStart] = React.useState(() => new Date().toISOString().slice(0, 10)); const [periodEnd, setPeriodEnd] = React.useState(() => { const d = new Date(); d.setDate(d.getDate() + 30); return d.toISOString().slice(0, 10); }); const [subAmount, setSubAmount] = React.useState(500000); const [clientRequestInfo, setClientRequestInfo] = React.useState(null); // Receipt screenshot state const [receiptFile, setReceiptFile] = React.useState(null); const [receiptPreview, setReceiptPreview] = React.useState(''); const [isUploadingReceipt, setIsUploadingReceipt] = React.useState(false); // Addons const [hasConnector, setHasConnector] = React.useState(false); const [connectorAmount, setConnectorAmount] = React.useState(150000); const [hasOther, setHasOther] = React.useState(false); const [otherAmount, setOtherAmount] = React.useState(0); const [otherDesc, setOtherDesc] = React.useState(''); const [note, setNote] = React.useState(''); const [isSubmitting, setIsSubmitting] = React.useState(false); const [rawMemo, setRawMemo] = React.useState(''); // Auto-calculate periodEnd based on periodStart and billingCycle const recalculateDates = (startStr, cycle) => { if (!startStr) return; try { const d = new Date(startStr); if (isNaN(d.getTime())) return; if (cycle === 'yearly') { d.setFullYear(d.getFullYear() + 1); } else { d.setDate(d.getDate() + 30); } setPeriodEnd(d.toISOString().slice(0, 10)); } catch (e) { console.warn('Failed to calc period end:', e); } }; // Auto-update amount based on plan and cycle const updatePlanAndAmount = (targetPlan, targetCycle) => { const norm = normalizePlanKey(targetPlan); setPlan(norm); setBillingCycle(targetCycle); const planInfo = PRICING_PLANS[norm]; const amount = targetCycle === 'yearly' ? planInfo.priceYearly : planInfo.priceMonthly; setSubAmount(amount); }; // Fetch pending subscription requests or current plan when selectedUserId changes React.useEffect(() => { if (!isOpen || !selectedUserId) { setClientRequestInfo(null); return; } const matchedUser = users.find(u => u.id === selectedUserId); if (matchedUser?.name && !payerName) { setPayerName(matchedUser.name); } let isMounted = true; (async () => { // 1. Check if user has an active pending request in organizer_subscription_requests if (supabaseClient) { try { const { data: req } = await supabaseClient .from('organizer_subscription_requests') .select('*') .eq('user_id', selectedUserId) .eq('status', 'pending') .order('created_at', { ascending: false }) .limit(1) .maybeSingle(); if (isMounted && req) { setClientRequestInfo(req); const reqPlan = normalizePlanKey(req.plan); const reqCycle = req.billing_cycle === 'yearly' ? 'yearly' : 'monthly'; updatePlanAndAmount(reqPlan, reqCycle); recalculateDates(periodStart, reqCycle); return; } } catch (err) { console.warn('[RecordPaymentModal] failed to fetch subscription request:', err); } } // 2. If no request, detect user's current plan and active subscription expires_at if (matchedUser) { const curPlan = matchedUser.plan || matchedUser.subscription?.plan || 'organizer_basic'; const targetPlan = curPlan === 'organizer_business' || curPlan === 'business' ? 'organizer_business' : curPlan === 'organizer_pro' || curPlan === 'pro' ? 'organizer_pro' : 'organizer_basic'; if (isMounted) { updatePlanAndAmount(targetPlan, 'monthly'); // If current subscription expires in future, start from that date const expAt = matchedUser.subscription?.expires_at || matchedUser.expires_at; if (expAt && new Date(expAt) > new Date()) { const nextStart = new Date(expAt).toISOString().slice(0, 10); setPeriodStart(nextStart); recalculateDates(nextStart, 'monthly'); } else { const todayStr = new Date().toISOString().slice(0, 10); setPeriodStart(todayStr); recalculateDates(todayStr, 'monthly'); } } } })(); return () => { isMounted = false; }; }, [isOpen, selectedUserId, supabaseClient]); // Handle Quick Memo Parser const handleMemoChange = (val) => { setRawMemo(val); if (!val || !val.trim()) return; const text = val.trim(); // 1. Phone matching: extracts 09... or +84... const phoneMatch = text.match(/(?:(?:\+84)|0)[35789]\d{8}/); if (phoneMatch) { const rawDigits = phoneMatch[0].replace(/\D/g, ''); const localPhone = rawDigits.startsWith('84') ? '0' + rawDigits.slice(2) : rawDigits; const matched = users.find(u => { const uDigits = (u.phone || '').replace(/\D/g, ''); return uDigits.endsWith(localPhone.slice(1)); }); if (matched) { setSelectedUserId(matched.id); if (matched.name && !payerName) setPayerName(matched.name); } } // 2. Display ID matching: HUIO XXXXX or HUIO-XXXXX const displayMatch = text.match(/HUIO[\s-_:]*(?:HUIO-?)?([A-Z0-9]{4,8})\b/i); if (displayMatch && displayMatch[1]) { const code = displayMatch[1].toUpperCase(); const matched = users.find(u => { const dId = (u.display_id || u.displayId || '').toUpperCase(); return dId.includes(code) || u.id.slice(0, 8).toUpperCase() === code; }); if (matched) { setSelectedUserId(matched.id); if (matched.name && !payerName) setPayerName(matched.name); } } // 3. Date extraction: YYMMDD-HH:mm:ss (e.g. 201026-12:58:48) const dateMatch = text.match(/(\d{2})(\d{2})(\d{2})-(\d{2}):(\d{2}):(\d{2})/); if (dateMatch) { const [_, yy, mm, dd, hh, min] = dateMatch; const year = 2000 + parseInt(yy, 10); setPaidAt(`${year}-${mm}-${dd}T${hh}:${min}`); } // 4. Amount extraction const amountMatch = text.match(/(?:250[.,]?000|500[.,]?000|750[.,]?000|2[.,]?400[.,]?000|4[.,]?800[.,]?000|7[.,]?200[.,]?000)/); if (amountMatch) { const cleanAmt = parseInt(amountMatch[0].replace(/\D/g, ''), 10); setSubAmount(cleanAmt); if (cleanAmt === 250000) updatePlanAndAmount('organizer_basic', 'monthly'); else if (cleanAmt === 500000) updatePlanAndAmount('organizer_pro', 'monthly'); else if (cleanAmt === 750000) updatePlanAndAmount('organizer_business', 'monthly'); else if (cleanAmt === 2400000) updatePlanAndAmount('organizer_basic', 'yearly'); else if (cleanAmt === 4800000) updatePlanAndAmount('organizer_pro', 'yearly'); else if (cleanAmt === 7200000) updatePlanAndAmount('organizer_business', 'yearly'); } if (!note) { setNote(text); } }; const handleReceiptFileChange = (e) => { const file = e.target.files?.[0]; if (!file) return; setReceiptFile(file); const previewUrl = URL.createObjectURL(file); setReceiptPreview(previewUrl); }; const removeReceiptFile = () => { setReceiptFile(null); setReceiptPreview(''); }; React.useEffect(() => { if (isOpen) { if (preselectedUser?.id) { setSelectedUserId(preselectedUser.id); if (preselectedUser.name) setPayerName(preselectedUser.name); } if (preselectedPlan) { updatePlanAndAmount(preselectedPlan, 'monthly'); } } }, [isOpen, preselectedUser, preselectedPlan]); if (!isOpen) return null; const totalAmount = (hasSub ? Number(subAmount) || 0 : 0) + (hasConnector ? Number(connectorAmount) || 0 : 0) + (hasOther ? Number(otherAmount) || 0 : 0); const handleSubmit = async (e) => { e.preventDefault(); if (!selectedUserId) { alert(lang === 'vi' ? 'Vui lòng chọn Chủ hụi' : 'Please select an organizer'); return; } if (totalAmount <= 0) { alert(lang === 'vi' ? 'Tổng số tiền phải lớn hơn 0' : 'Total amount must be greater than 0'); return; } // Auto-generate internal reference if externalRef is empty let finalRef = externalRef.trim(); if (!finalRef) { const datePart = new Date().toISOString().slice(2, 10).replace(/-/g, ''); const randPart = Math.random().toString(36).slice(2, 6).toUpperCase(); finalRef = `HUIO-INT-${datePart}-${randPart}`; } setIsSubmitting(true); let uploadedReceiptUrl = null; try { // Upload receipt screenshot if selected if (receiptFile && supabaseClient?.storage) { setIsUploadingReceipt(true); const fileExt = receiptFile.name.split('.').pop() || 'png'; const cleanName = receiptFile.name.replace(/[^a-zA-Z0-9.-]/g, '_'); const storagePath = `${selectedUserId}/${Date.now()}_${cleanName}`; const { data: uploadData, error: uploadErr } = await supabaseClient.storage .from('payment-receipts') .upload(storagePath, receiptFile, { upsert: true }); if (uploadErr) { console.error('Error uploading receipt screenshot:', uploadErr); alert((lang === 'vi' ? 'Cảnh báo: Không thể tải ảnh квитанции lên bucket: ' : 'Warning: Receipt upload failed: ') + uploadErr.message); } else { uploadedReceiptUrl = uploadData?.path || storagePath; } } const items = []; if (hasSub) { const planObj = PRICING_PLANS[plan] || PRICING_PLANS.organizer_pro; items.push({ kind: 'subscription', plan, amount_vnd: Number(subAmount) || 0, quantity: 1, description: `${lang === 'vi' ? planObj.nameVi : planObj.nameEn} (${billingCycle === 'yearly' ? (lang === 'vi' ? '1 năm' : '1 year') : (lang === 'vi' ? '1 tháng' : '1 month')})` }); } if (hasConnector) { items.push({ kind: 'bank_connector_fee', plan: null, amount_vnd: Number(connectorAmount) || 0, quantity: 1, description: 'Phí kết nối ngân hàng / SePay' }); } if (hasOther && otherAmount > 0) { items.push({ kind: 'other', plan: null, amount_vnd: Number(otherAmount) || 0, quantity: 1, description: otherDesc || 'Khoản thu khác' }); } await onSubmit({ userId: selectedUserId, paidAt: new Date(paidAt).toISOString(), method, externalRef: finalRef, payerName: payerName.trim() || null, items, plan: hasSub ? plan : null, periodStart: hasSub ? periodStart : null, periodEnd: hasSub ? periodEnd : null, note: note.trim() || null, receiptUrl: uploadedReceiptUrl, source: 'manual' }); // Prompt to copy CSKH confirmation message const wantCopy = window.confirm( lang === 'vi' ? '✅ Đã ghi nhận thanh toán thành công!\n\nBạn có muốn sao chép tin nhắn xác nhận CSKH để gửi cho khách hàng qua Zalo/Telegram ngay không?' : '✅ Payment recorded successfully!\n\nDo you want to copy the Customer Care confirmation message to send to the client now?' ); if (wantCopy) { const userObj = users.find(u => u.id === selectedUserId); const userName = payerName || userObj?.name || (lang === 'vi' ? 'Chị' : 'Customer'); const amountStr = window.vnd ? window.vnd(totalAmount) : (totalAmount.toLocaleString('vi-VN') + ' ₫'); const msg = buildCskhConfirmationMessage({ userName, amountStr, planKey: plan, periodEnd, externalRef: finalRef, lang }); if (navigator?.clipboard?.writeText) { navigator.clipboard.writeText(msg).then(() => { alert(lang === 'vi' ? '✅ Đã sao chép tin nhắn CSKH vào bộ nhớ tạm!' : '✅ Copied customer care message to clipboard!'); }).catch(() => { prompt(lang === 'vi' ? 'Tin nhắn CSKH:' : 'Customer Care message:', msg); }); } else { prompt(lang === 'vi' ? 'Tin nhắn CSKH:' : 'Customer Care message:', msg); } } onClose(); } catch (err) { alert(err.message || 'Lỗi ghi nhận thanh toán'); } finally { setIsSubmitting(false); setIsUploadingReceipt(false); } }; const organizerUsers = users.filter(u => u.role === 'organizer' || u.role === 'both' || u.id === selectedUserId); return (
e.stopPropagation()} >

{lang === 'vi' ? 'Ghi nhận thanh toán Chủ hụi' : 'Record Organizer Payment'}

{lang === 'vi' ? 'Hộ kinh doanh Số Việt Huio · Đồng bộ kế toán & CTV' : 'Official HKD Revenue & Commissions'}
{/* Quick Memo / Receipt Parser */}
handleMemoChange(e.target.value)} style={{ width: '100%', padding: '6px 10px', fontSize: '12px', borderRadius: 'var(--hu-r-sm)', border: '1px solid var(--hu-border)', background: 'var(--hu-bg)', color: 'var(--hu-fg)' }} />
{/* Client Request Alert Banner (if pending request found) */} {clientRequestInfo && (
🎯 {lang === 'vi' ? 'Khách đã yêu cầu gói trên ứng dụng:' : 'Customer requested plan:'}{' '} {getClientPlanName(clientRequestInfo.plan, lang)} ({clientRequestInfo.billing_cycle === 'yearly' ? '1 năm' : '1 tháng'}) — {formatVnd(clientRequestInfo.amount_vnd)}
{lang === 'vi' ? 'Đã tự điền' : 'Auto-filled'}
)} {/* Organizer Select */}
{/* Paid At */}
setPaidAt(e.target.value)} required style={{ width: '100%', padding: '8px 12px', borderRadius: 'var(--hu-r-sm)', border: '1.5px solid var(--hu-border)', background: 'var(--hu-bg)', color: 'var(--hu-fg)' }} />
{/* Method */}
{/* External Reference with Help Hint & Optional */}
setExternalRef(e.target.value)} placeholder={lang === 'vi' ? 'VD: FT26... / MBVCB... (để trống tự tạo)' : 'e.g. FT26... (leave blank to auto-generate)'} style={{ width: '100%', padding: '8px 12px', borderRadius: 'var(--hu-r-sm)', border: '1.5px solid var(--hu-border)', background: 'var(--hu-bg)', color: 'var(--hu-fg)' }} />
💡 {lang === 'vi' ? 'MB Bank: Mã GD / FT trong Chi tiết GD; Vietcombank: Số tham chiếu. Nếu để trống, hệ thống tự sinh mã nội bộ.' : 'MB Bank: Transaction / FT code; Vietcombank: Reference number. If empty, an internal code is generated.'}
{/* Payer Name */}
setPayerName(e.target.value)} placeholder="VD: NGUYEN VAN A" style={{ width: '100%', padding: '8px 12px', borderRadius: 'var(--hu-r-sm)', border: '1.5px solid var(--hu-border)', background: 'var(--hu-bg)', color: 'var(--hu-fg)' }} />
{lang === 'vi' ? 'Họ tên hiển thị trong tin nhắn cảm ơn CSKH' : 'Name shown in Customer Care message'}
{/* Receipt Upload & Preview Box */}
{receiptPreview && ( )}
{receiptPreview && (
Receipt preview {(receiptFile.size / 1024).toFixed(1)} KB
)}
{/* Line Items & Plan Selection Box */}
{lang === 'vi' ? 'Chi tiết gói dịch vụ & Khoản thu' : 'Payment Breakdown'} {lang === 'vi' ? 'Tự động tính theo bảng giá chuẩn' : 'Calculated per pricing standard'}
{/* Item 1: Subscription with Plan and Billing Cycle */}
{hasSub && (
{/* Plan Dropdown */} {/* Cycle Toggle */}
)}
{hasSub && (
{ setPeriodStart(e.target.value); recalculateDates(e.target.value, billingCycle); }} style={{ width: '100%', fontSize: '12px', padding: '6px' }} />
setPeriodEnd(e.target.value)} style={{ width: '100%', fontSize: '12px', padding: '6px' }} />
setSubAmount(Number(e.target.value))} style={{ width: '100%', fontSize: '12px', padding: '6px' }} />
)}
{/* Item 2: Connector fee */}
{hasConnector && (
setConnectorAmount(Number(e.target.value))} style={{ width: '120px', fontSize: '12px', padding: '4px' }} />
)}
{/* Item 3: Other fee */}
{hasOther && (
setOtherDesc(e.target.value)} style={{ width: '130px', fontSize: '12px', padding: '4px' }} /> setOtherAmount(Number(e.target.value))} style={{ width: '110px', fontSize: '12px', padding: '4px' }} />
)}
{/* Total Summary */}
{lang === 'vi' ? 'TỔNG CỘNG THANH TOÁN:' : 'TOTAL PAYMENT:'} {formatVnd(totalAmount)}
{/* Note */}