diff --git a/.gitignore b/.gitignore index eada38c..7c0fb33 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. +.idea/ # dependencies /node_modules @@ -59,3 +60,9 @@ next-env.d.ts !.env.example *.tsbuildinfo + +/cloudflare/dist/ +/cloudflare/.state/ +/cloudflare/.work/ +/cloudflare/siphoned.zip +/cloudflare/.wrangler/ diff --git a/README.md b/README.md index df89b30..26eb30a 100644 --- a/README.md +++ b/README.md @@ -23,3 +23,11 @@ The live card uses bundled OFL-licensed Vazirmatn regular/bold fonts. Persian la ## Energy palette and icon The primary color is cyan-blue (`#56d3ff`) over deep navy (`#080f18`). The vector vial in `lib/energy-art.mjs` is shared by the hero, brand, live card, SVG/ICO/PNG favicon and Apple touch icon. It follows the cyan energy, dark metal bands and brass cap visible in the Siphoned Energy item reference: https://www.albiondatabase.com/items/siphoned-energy (icon: https://assets.albiondatabase.com/icons/items/UNIQUE_GVGTOKEN_GENERIC.png). Run `node scripts/generate-favicon.mjs` after changing the vector. Warning/debt colors remain amber/red to communicate balance status. + +## Player pages + +Every member has a public, case-insensitive `/@player_name` account page, linked from player names in the leaderboard and guild history. It shows balance, rank, readiness and the exact required top-up, totals, a complete balance timeline, and searchable deposit/withdrawal history with the balance after each transaction. History loads progressively; CSV exports the full account regardless of the selected filter. Balances start from zero at the beginning of imported history. Timestamps retain the game timezone; transactions within the same second have no known in-game order. + +The shared account link copies a fresh `?t=` timestamp. Player-specific Twitter/Open Graph images show balance, readiness, top-up, rank, totals, and the five latest transactions. Next/Vinext uses `/api/player-image?player=...`; the offline Cloudflare package generates one PNG per player during its usual build. Unknown players return HTTP 404. Player metadata has its own canonical URL and never inherits the guild-wide preview. + +Validation: `node --test lib/*.test.mjs cloudflare/src/worker.test.mjs`, `npx tsc --noEmit --incremental false`, and `node cloudflare/build.mjs`. diff --git a/app/[handle]/page.tsx b/app/[handle]/page.tsx new file mode 100644 index 0000000..8cdccc1 --- /dev/null +++ b/app/[handle]/page.tsx @@ -0,0 +1,29 @@ +import type {Metadata} from 'next'; +import {notFound} from 'next/navigation'; +import {readLedger} from '../../lib/server'; +import {siteOrigin,ledgerSnapshot} from '../../lib/share'; +import {playerSnapshot} from '../../lib/player.mjs'; +import {shareTimestamp,withShareTimestamp} from '../../lib/share-link.mjs'; +import {persianNumber as n} from '../../lib/persian-text'; +import {playerCardWidth,playerCardHeight} from '../../lib/player-card'; +import PlayerPage from '../../components/player-page'; +export const dynamic='force-dynamic'; +type Props={params:Promise<{handle:string}>;searchParams:Promise>}; +async function account(params:Props['params']) { + const {handle}=await params; + if(!handle.startsWith('@')||handle.length<2||handle.length>65)notFound(); + const rows=await readLedger(), profile=playerSnapshot(rows,handle.slice(1)); + if(!profile)notFound(); + return {rows,profile}; +} +export async function generateMetadata({params,searchParams}:Props):Promise{ + const {rows,profile:p}=await account(params),snapshot=await ledgerSnapshot(rows); + const canonical=new URL(p.path,siteOrigin).href; + const title=`${p.name} | ${p.status} · خزانه سایفوند انرژی`; + const description=`بالانس ${n(p.balance)} سایفوند انرژی · رتبه ${n(p.rank)} از ${n(p.members)} · ${n(p.count)} تراکنش · واریز لازم تا آمادگی: ${n(p.topUp)}`; + const timestamp=shareTimestamp((await searchParams).t); + let image=`${siteOrigin}/api/player-image?player=${encodeURIComponent(p.name)}&v=player-v1-${snapshot.revision}`; + if(timestamp!==null)image=withShareTimestamp(image,timestamp); + return {title,description,alternates:{canonical},openGraph:{type:'website',locale:'fa_IR',url:timestamp===null?canonical:withShareTimestamp(canonical,timestamp),title,description,images:[{url:image,width:playerCardWidth,height:playerCardHeight,alt:`وضعیت و آخرین تراکنش‌های ${p.name}`}]},twitter:{card:'summary_large_image',title,description,images:[{url:image,alt:`وضعیت و آخرین تراکنش‌های ${p.name}`}]}}; +} +export default async function Page({params}:Props){const {rows,profile}=await account(params);return ;} diff --git a/app/api/player-image/route.ts b/app/api/player-image/route.ts new file mode 100644 index 0000000..a726853 --- /dev/null +++ b/app/api/player-image/route.ts @@ -0,0 +1,16 @@ +import {ImageResponse} from 'next/og'; +import {createElement} from 'react'; +import {readLedger} from '../../../lib/server'; +import {playerSnapshot} from '../../../lib/player.mjs'; +import {PlayerCard,playerCardWidth,playerCardHeight} from '../../../lib/player-card'; +import {socialFonts} from '../../../lib/social-fonts'; +export const dynamic='force-dynamic'; +export async function GET(request:Request){ + const name=new URL(request.url).searchParams.get('player'); + if(!name||name.length>64)return new Response('Player not found',{status:404}); + try{ + const data=playerSnapshot(await readLedger(),name); + if(!data)return new Response('Player not found',{status:404}); + return new ImageResponse(createElement(PlayerCard,{data}),{width:playerCardWidth,height:playerCardHeight,fonts:[...socialFonts],headers:{'Cache-Control':'no-store'}}); + }catch{return new Response('تصویر حساب موقتاً در دسترس نیست.',{status:503,headers:{'Cache-Control':'no-store'}});} +} diff --git a/app/dashboard.tsx b/app/dashboard.tsx index 108c4e2..7e854de 100644 --- a/app/dashboard.tsx +++ b/app/dashboard.tsx @@ -1,6 +1,7 @@ 'use client'; import {useEffect,useState,useMemo} from 'react'; -import {Shield,ArrowUpRight,ArrowDownLeft,Search,ChevronLeft,Trophy,Flame,Coins,History,Lock,Upload,CheckCircle2,AlertTriangle,X,RefreshCw,Copy,Share2} from 'lucide-react'; +import {Shield,ArrowUpRight,ArrowDownLeft,Search,ChevronLeft,Trophy,Flame,Coins,History,Lock,Upload,AlertTriangle,RefreshCw,Share2} from 'lucide-react'; +import {playerPath} from '../lib/player.mjs'; import {withShareTimestamp} from '../lib/share-link.mjs'; import {seed,summarize,parseLog,identity,minimum} from '../lib/ledger.mjs'; type Row={id:string;date:string;player:string;reason:string;amount:number}; @@ -8,13 +9,11 @@ const num=(n:number)=>n.toLocaleString('fa-IR'); const digits=(s:string)=>s.replace(/[0-9]/g,n=>'۰۱۲۳۴۵۶۷۸۹'[Number(n)]); function status(n:number){return n<0?'بدهکار':n(seed as Row[]),[loading,setLoading]=useState(true),[error,setError]=useState(''),[query,setQuery]=useState(''),[tab,setTab]=useState('all'),[selected,setSelected]=useState(null),[log,setLog]=useState(''),[message,setMessage]=useState(''),[saving,setSaving]=useState(false),[admin,setAdmin]=useState(false),[view,setView]=useState('leaderboard'),[shareUrl,setShareUrl]=useState(''),[shareNotice,setShareNotice]=useState(''),[sharing,setSharing]=useState(false); + const [rows,setRows]=useState(seed as Row[]),[loading,setLoading]=useState(true),[error,setError]=useState(''),[query,setQuery]=useState(''),[tab,setTab]=useState('all'),[log,setLog]=useState(''),[message,setMessage]=useState(''),[saving,setSaving]=useState(false),[admin,setAdmin]=useState(false),[view,setView]=useState('leaderboard'),[shareUrl,setShareUrl]=useState(''),[shareNotice,setShareNotice]=useState(''),[sharing,setSharing]=useState(false); async function refresh(){setLoading(true);setError('');try{const r=await fetch('/api/ledger');const d=await r.json() as {error?:string;rows:Row[];admin:boolean;shareUrl:string};if(!r.ok)throw Error(d.error);setRows(d.rows);setAdmin(d.admin);setShareUrl(d.shareUrl);}catch(e){setError(e instanceof Error?e.message:'ارتباط برقرار نشد.');}finally{setLoading(false);}} useEffect(()=>{refresh();},[]); const players=useMemo(()=>summarize(rows),[rows]);const low=players.filter(p=>p.balances+p.balance,0);const deposits=rows.reduce((s,r)=>s+Math.max(r.amount,0),0);const withdrawals=rows.reduce((s,r)=>s+Math.max(-r.amount,0),0); const filtered=players.filter(p=>p.name.toLowerCase().includes(query.toLowerCase())&&(tab!=='low'||p.balance{if(!selected)return;const onKey=(e:KeyboardEvent)=>{if(e.key==='Escape')setSelected(null);};document.addEventListener('keydown',onKey);return()=>document.removeEventListener('keydown',onKey);},[selected]); - const profile=players.find(p=>p.name.toLowerCase()===selected?.toLowerCase()); const preview=useMemo(()=>{if(!log.trim())return null;try{const parsed=parseLog(log);const ids=new Set(rows.map(identity));let fresh=0;for(const r of parsed){const id=identity(r);if(!ids.has(id)){fresh++;ids.add(id);}}return {total:parsed.length,fresh,duplicates:parsed.length-fresh,error:''};}catch(e){return {error:(e as Error).message,total:0,fresh:0,duplicates:0};}},[log,rows]); async function shareLatest(){ setSharing(true);setShareNotice(''); @@ -32,9 +31,9 @@ export default function Dashboard({adminMode=false}:{adminMode?:boolean}){
بالانس خزانه
{num(total)}سایفوند انرژیخالص واریز و برداشت اعضا
کل واریزها
{num(deposits)}واریزسهم اعضا در قدرت گیلد
کل برداشت‌ها
{num(withdrawals)}برداشت{num(rows.length)} تراکنش ثبت‌شده
اعضای نیازمند اقدام
{num(low.length)}از {num(players.length)} عضوبالانس کمتر از {num(minimum)} سایفوند انرژی
{adminMode&&
خزانه را به‌روز نگه دار

ورود لاگ خزانه

خروجی بازی را همراه عنوان ستون‌ها اینجا پیست کن. پیش‌نمایش را بررسی و سپس ثبت کن.

+
فایلی انتخاب نشده
+
+

انتشار سایت

برای انتشار مستقیم، یک بار حساب کلودفلیر را متصل کنید. ورود و تأیید دسترسی در مرورگر خودتان انجام می‌شود.

بارگذاری از داشبورد کلودفلیر

بستهٔ آماده را دانلود کنید و در صفحهٔ بارگذاری قرار دهید.

باز کردن صفحهٔ بارگذاری
محیط «Production» را انتخاب کنید، فایل ZIP را بارگذاری کنید و «Save and deploy» را بزنید.
+
این ابزار فقط روی کامپیوتر شما اجرا می‌شود. داده‌های قبلی پیش از ادغام پشتیبان‌گیری می‌شوند.
diff --git a/cloudflare/tool/server.mjs b/cloudflare/tool/server.mjs new file mode 100644 index 0000000..634c930 --- /dev/null +++ b/cloudflare/tool/server.mjs @@ -0,0 +1,54 @@ +import http from 'node:http'; +import fs from 'node:fs/promises'; +import {randomBytes} from 'node:crypto'; +import {spawn} from 'node:child_process'; +import {fileURLToPath} from 'node:url'; +import {parseLog,merge,summarize} from '../../lib/ledger.mjs'; +const root=fileURLToPath(new URL('../../',import.meta.url)); +const ledgerPath=root+'cloudflare/migration/ledger.json'; +const token=randomBytes(24).toString('hex'); +const port=Number(process.env.SIPHONED_TOOL_PORT||5188),origin=`http://127.0.0.1:${port}`; +let busy=false,auth='idle'; +const env={...process.env,WRANGLER_SEND_METRICS:'false',CLOUDFLARE_ACCOUNT_ID:'1be1e22e71d56e01fe8fdbf449b341dc',WRANGLER_LOG_PATH:root+'cloudflare/.work/wrangler-logs'}; +function run(args){return new Promise((resolve,reject)=>{let output='';const child=spawn(process.execPath,args,{cwd:root,env});child.stdout.on('data',d=>output+=d);child.stderr.on('data',d=>output+=d);child.on('error',reject);child.on('close',code=>code===0?resolve(output):reject(Error('عملیات کامل نشد. اتصال اینترنت و ورود کلودفلیر را بررسی کنید.')));});} +async function readLedger(){return JSON.parse(await fs.readFile(ledgerPath,'utf8'));} +function stats(rows){const players=summarize(rows);return {transactions:rows.length,members:players.length,balance:players.reduce((n,p)=>n+p.balance,0)};} +function candidate(before,log){const incoming=parseLog(log),rows=merge([...before.rows,...incoming]),added=rows.length-before.rows.length;return {rows,...stats(rows),added,duplicates:incoming.length-added};} +const server=http.createServer(async(req,res)=>{ + const url=new URL(req.url,origin); + const send=(status,obj)=>{res.writeHead(status,{'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store'});res.end(JSON.stringify(obj));}; + if(req.headers.host!==`127.0.0.1:${port}`){send(403,{error:'دسترسی مجاز نیست.'});return;} + try{ + const assets={ + '/assets/Vazirmatn-Regular.ttf':['lib/fonts/Vazirmatn-Regular.ttf','font/ttf'], + '/assets/Vazirmatn-Bold.ttf':['lib/fonts/Vazirmatn-Bold.ttf','font/ttf'], + '/assets/favicon.svg':['public/favicon.svg','image/svg+xml'], + '/assets/siphoned-energy.svg':['public/siphoned-energy.svg','image/svg+xml'], + }; + if(req.method==='GET'&&assets[url.pathname]){const [path,type]=assets[url.pathname];res.writeHead(200,{'Content-Type':type,'Cache-Control':'no-cache'});res.end(await fs.readFile(root+path));return;} + if(req.method==='GET'&&url.pathname==='/'&&url.searchParams.get('key')===token){res.writeHead(200,{'Content-Type':'text/html; charset=utf-8','Cache-Control':'no-store','Referrer-Policy':'no-referrer'});res.end((await fs.readFile(root+'cloudflare/tool/index.html','utf8')).replace('__SESSION__',token));return;} + if(req.headers['x-session']!==token||(req.method==='POST'&&req.headers.origin!==origin)){send(403,{error:'ابزار را از میان‌بر محلی باز کنید.'});return;} + if(req.method==='GET'&&url.pathname==='/status'){send(200,{...stats((await readLedger()).rows),busy,auth});return;} + if(req.method==='GET'&&url.pathname==='/package'){res.writeHead(200,{'Content-Type':'application/zip','Content-Disposition':'attachment; filename="siphoned.zip"','Cache-Control':'no-store'});res.end(await fs.readFile(root+'cloudflare/siphoned.zip'));return;} + if(req.method!=='POST'){send(404,{error:'پیدا نشد.'});return;} + let body='';for await(const chunk of req){body+=chunk;if(body.length>2000000)throw Error('حجم لاگ بیش از حد مجاز است.');} + const data=JSON.parse(body||'{}'); + if(busy){send(409,{error:'عملیات قبلی هنوز در حال انجام است.'});return;} + if(url.pathname==='/preview'){const {rows,...result}=candidate(await readLedger(),data.log);send(200,result);return;} + if(url.pathname==='/connect'){ + auth='waiting';busy=true;send(200,{message:'پنجرهٔ ورود کلودفلیر باز می‌شود؛ تأیید دسترسی را خودتان انجام دهید.'}); + run([root+'node_modules/wrangler/bin/wrangler.js','login']).then(()=>auth='connected').catch(()=>auth='failed').finally(()=>busy=false);return; + } + if(url.pathname==='/build'){ + busy=true;const original=await fs.readFile(ledgerPath,'utf8'); + try{const {rows,...result}=candidate(JSON.parse(original),data.log);await fs.mkdir(root+'cloudflare/.work',{recursive:true});await fs.copyFile(ledgerPath,root+'cloudflare/migration/ledger.backup.json');await fs.writeFile(ledgerPath,JSON.stringify({rows},null,2));await run([root+'cloudflare/build.mjs']);send(200,{...result,message:'داده‌ها ادغام شدند و بستهٔ سایت و تصویر جدید آماده است.'});} + catch(error){await fs.writeFile(ledgerPath,original);throw error;}finally{busy=false;}return; + } + if(url.pathname==='/deploy'){ + busy=true;try{await run([root+'node_modules/wrangler/bin/wrangler.js','pages','deploy',root+'cloudflare/dist','--project-name','siphoned-energy','--branch','main','--commit-dirty=true']);send(200,{message:'نسخهٔ جدید منتشر شد.',url:'https://siphoned.oneup.megh.dad/?t='+Math.floor(Date.now()/1000)});}finally{busy=false;}return; + } + send(404,{error:'پیدا نشد.'}); + }catch(error){send(400,{error:error.message});} +}); +server.listen(port,'127.0.0.1',()=>{const url=origin+'/?key='+token;console.log('ابزار سایفوند انرژی آماده است: '+url);if(!process.env.SIPHONED_NO_OPEN)spawn('open',[url],{stdio:'ignore'});}); +server.on('error',()=>{console.error('ابزار قبلاً باز است یا این پورت در دسترس نیست. پنجرهٔ قبلی را ببندید و دوباره اجرا کنید.');process.exit(1);}); diff --git a/cloudflare/wrangler.json b/cloudflare/wrangler.json new file mode 100644 index 0000000..31fc770 --- /dev/null +++ b/cloudflare/wrangler.json @@ -0,0 +1,6 @@ +{ + "name": "siphoned-energy", + "pages_build_output_dir": "./dist", + "compatibility_date": "2026-05-15", + "account_id": "1be1e22e71d56e01fe8fdbf449b341dc" +} \ No newline at end of file diff --git a/components/player-page.tsx b/components/player-page.tsx new file mode 100644 index 0000000..39867ef --- /dev/null +++ b/components/player-page.tsx @@ -0,0 +1,38 @@ +'use client'; +/* Shared with the standalone Cloudflare client, which has no Next router or image runtime. */ +/* eslint-disable @next/next/no-html-link-for-pages, @next/next/no-img-element */ +import {useMemo, useState} from 'react'; +import {ArrowRight, ArrowDownLeft, ArrowUpRight, Trophy, Shield, Share2, Download, Search, CheckCircle2, AlertTriangle} from 'lucide-react'; +import {minimum} from '../lib/ledger.mjs'; +import {playerSnapshot} from '../lib/player.mjs'; +import {withShareTimestamp} from '../lib/share-link.mjs'; +import {persianNumber as n, persianDigits as digits} from '../lib/persian-text'; +export type PlayerRow = {date:string; player:string; reason:string; amount:number}; +type Profile = NonNullable>; +export function BalanceTimeline({profile:p}:{profile:Profile}) { + const points=[0,...p.history.slice().reverse().map(r=>r.balance)]; + const min=Math.min(0,...points),max=Math.max(minimum,...points),range=max-min||1; + const y=(v:number)=>160-(v-min)/range*130; + const line=points.map((v,i)=>`${20+i/(points.length-1)*760},${y(v)}`).join(' '); + return
روند بالانس بر اساس همهٔ لاگ‌های ثبت‌شده
شروع لاگ‌ها · {digits(p.first.slice(0,10))}خط‌چین: حداقل {n(minimum)}آخرین وضعیت · {digits(p.last.slice(0,10))}
; +} +export default function PlayerPage({rows,name,origin}:{rows:PlayerRow[];name:string;origin:string}) { + const p=useMemo(()=>playerSnapshot(rows,name),[rows,name]); + const [filter,setFilter]=useState('all'),[query,setQuery]=useState(''),[limit,setLimit]=useState(25),[notice,setNotice]=useState(''); + if(!p)return

بازیکن پیدا نشد

هنوز تراکنشی برای این نام ثبت نشده است.

بازگشت به خزانه
; + const history=p.history.filter(r=>(filter==='all'||(filter==='deposit'?r.amount>0:r.amount<0))&&`${r.date} ${digits(r.date)} ${r.amount} ${n(r.amount)}`.includes(query.trim())); + const tone=p.balance<0?'bad':p.balance[r.date,/^[=+@\-\t\r]/.test(r.player)?"'"+r.player:r.player,r.reason,r.amount,r.balance].map(v=>'"'+String(v).replaceAll('"','""')+'"').join(',')).join('\r\n'); + const url=URL.createObjectURL(new Blob([csv],{type:'text/csv;charset=utf-8'}));const a=document.createElement('a');a.href=url;a.download='player-transactions.csv';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000); + } + return
خزانهٔ گیلد سایفوند انرژی
+
کارنامهٔ عضو گیلد

@{p.name}

{p.status}
رتبهٔ {n(p.rank)} از {n(p.members)} عضو
+
{[{label:'بالانس فعلی',value:p.balance,color:p.balance<0?'red':'energy',sub:'خالص واریز و برداشت'},{label:'مجموع واریز',value:p.deposits,color:'green',sub:'سهم ثبت‌شده در خزانه'},{label:'مجموع برداشت',value:p.withdrawals,color:'',sub:'سایفوند انرژی مصرف‌شده'},{label:'تراکنش ثبت‌شده',value:p.count,color:'',sub:'از '+digits(p.first.slice(0,10))}].map(s=>
{s.label}
{n(s.value)}{s.sub}
)}
+
{p.topUp>0?:}

{p.topUp>0?'قدم بعدی: شارژ حساب':'برای نبرد بعدی آماده‌ای'}

{p.topUp>0?<>با واریز {n(p.topUp)} سایفوند انرژی به حداقل آمادگی {n(minimum)} می‌رسی.:<>بالانس تو {n(p.balance-minimum)} سایفوند انرژی بالاتر از حداقل آمادگی {n(minimum)} است.}

+
هر واریز و برداشت، یک قدم در مسیر

مسیر بالانس

{n(p.count)} تراکنش
+
شفاف، از اولین لاگ تا امروز

تاریخچهٔ کامل حساب

{[['all','همه'],['deposit','واریزها'],['withdrawal','برداشت‌ها']].map(([value,label])=>)}
+
{history.slice(0,limit).map((r,i)=>)}
زمان ثبت در بازینوع تراکنشمقداربالانس پس از تراکنش
{digits(r.date)}0?'green':'red')}>{r.amount>0?:} {r.amount>0?'واریز':'برداشت'}0?'green':'red'}>{r.amount>0?'+':''}{n(r.amount)}{n(r.balance)}
{!history.length&&

تراکنشی با این فیلتر پیدا نشد.

}
{n(Math.min(limit,history.length))} از {n(history.length)} تراکنش · جدیدترین در بالا{history.length>limit&&}
+
آخرین تراکنش این بازیکن: {digits(p.last)}

بالانس از صفر و بر اساس لاگ‌های ثبت‌شده محاسبه شده است؛ موجودی پیش از اولین لاگ لحاظ نشده است. زمان‌ها همان زمان ثبت‌شده در بازی هستند.

مشاهدهٔ همهٔ اعضا ←
{notice&&
setNotice('')}>{notice}
}
; +} diff --git a/lib/player-card.tsx b/lib/player-card.tsx new file mode 100644 index 0000000..f471610 --- /dev/null +++ b/lib/player-card.tsx @@ -0,0 +1,25 @@ +/* Satori renders plain image elements in social cards. */ +/* eslint-disable @next/next/no-img-element */ +import {playerSnapshot} from './player.mjs'; +import {fa, persianNumber as n, persianDigits} from './persian-text'; +import {energyArtDataUri} from './energy-art.mjs'; +export const playerCardWidth=1600, playerCardHeight=900; +type Profile=NonNullable>; +export function PlayerCard({data:p}:{data:Profile}) { + const color=p.balance<0?'#e47878':p.topUp>0?'#e19b58':'#80b6a0'; + const short=(s:string,max=34)=>s.length>max?s.slice(0,max-1)+'…':s; + return
+
{fa(`رتبهٔ ${n(p.rank)} از ${n(p.members)} عضو`)}
{fa('کارنامهٔ بازیکن · خزانهٔ گیلد')}
+
{fa(p.status)}
28?38:58,fontWeight:700}}>@{short(p.name)}
+
+
{fa('واریز لازم تا آمادگی')}
{n(p.topUp)}
{fa(p.topUp>0?`برای رسیدن به حداقل ${n(10)} سایفوند انرژی`:'حساب برای نبرد بعدی آماده است')}
+
{fa('بالانس فعلی · سایفوند انرژی')}
{n(p.balance)}
{fa('خالص واریز و برداشت در لاگ‌های ثبت‌شده')}
+
+
{fa(`${n(p.count)} تراکنش ثبت‌شده`)}{fa(`کل برداشت: ${n(p.withdrawals)}`)}{fa(`کل واریز: ${n(p.deposits)}`)}
+
+
{fa('بالانس پس از تراکنش')}
{fa('آخرین تراکنش‌های بازیکن')}
+ {p.history.slice(0,5).map((r,i)=>
{n(r.balance)}
0?'#80b6a0':'#e47878'}}>{r.amount>0?'+':''}{n(r.amount)}
0?'#80b6a0':'#e47878'}}>{fa(r.amount>0?'واریز':'برداشت')}
{persianDigits(r.date)}
)} +
+
{fa('بالانس بر اساس لاگ‌ها · تاریخچهٔ کامل در صفحهٔ بازیکن')}{fa('آخرین تراکنش: ')} {persianDigits(p.last)}
+
; +} diff --git a/lib/player.mjs b/lib/player.mjs new file mode 100644 index 0000000..44d0583 --- /dev/null +++ b/lib/player.mjs @@ -0,0 +1,24 @@ +import { merge, minimum, summarize } from './ledger.mjs'; + +export const playerPath = name => '/@' + encodeURIComponent(name.toLowerCase()); +export const playerImagePath = name => '/player-images/' + Array.from(new TextEncoder().encode(name.toLowerCase()), n => n.toString(16).padStart(2, '0')).join('') + '.png'; +export function playerFromPath(path) { + const match = /^\/@([^/]+)\/?$/.exec(path); + if (!match) return null; + try { const name = decodeURIComponent(match[1]); return name.length && name.length <= 64 && !/[\x00-\x1f]/.test(name) ? name : null; } catch { return null; } +} +export const playerStatus = balance => balance < 0 ? 'بدهکار' : balance < minimum ? 'نیازمند شارژ' : 'آمادهٔ نبرد'; +/** + * @param {{date:string, player:string, reason:string, amount:number}[]} rows + * @param {string} name + * @returns {{name:string, balance:number, deposits:number, withdrawals:number, count:number, last:string, rank:number, members:number, topUp:number, status:string, first:string, history:{date:string, player:string, reason:string, amount:number, balance:number}[], path:string, imagePath:string}|null} + */ +export function playerSnapshot(rows, name) { + const ordered = merge(rows), players = summarize(ordered); + const rank = players.findIndex(p => p.name.toLowerCase() === name.toLowerCase()); + if (rank < 0) return null; + const player = players[rank]; + let balance = 0; + const history = ordered.filter(r => r.player.toLowerCase() === name.toLowerCase()).reverse().map(row => ({...row, balance: balance += row.amount})); + return {...player, rank: rank + 1, members: players.length, topUp: Math.max(0, minimum - player.balance), status: playerStatus(player.balance), first: history[0].date, history: history.reverse(), path: playerPath(player.name), imagePath: playerImagePath(player.name)}; +} diff --git a/lib/player.test.mjs b/lib/player.test.mjs new file mode 100644 index 0000000..563e8c0 --- /dev/null +++ b/lib/player.test.mjs @@ -0,0 +1,25 @@ +import {test} from 'node:test'; +import assert from 'node:assert/strict'; +import {seed} from './ledger.mjs'; +import {playerSnapshot, playerPath, playerFromPath, playerImagePath} from './player.mjs'; +test('player lookup is case insensitive and running balances reconcile in unsorted history', () => { + const p = playerSnapshot([...seed].reverse(), 'BELGHEYS'); + assert.equal(p.balance,16); assert.equal(p.count,4); assert.equal(p.history[0].balance,p.balance); + assert.deepEqual(p.history.map(r=>r.balance),[16,26,0,10]); + assert.equal(p.deposits-p.withdrawals,p.balance); assert.equal(p.topUp,0); + assert.equal(p.path,'/@belgheys'); assert.equal(p.members,12); +}); +test('debt, low and ready statuses include the correct required top-up',()=>{ + for(const [balance,status,topUp] of [[-10,'بدهکار',20],[0,'نیازمند شارژ',10],[9,'نیازمند شارژ',1],[10,'آمادهٔ نبرد',0]]){ + const p=playerSnapshot([{date:'2026-10-12 19:30:40',player:'x',reason:'Deposit',amount:balance}],'x'); + assert.equal(p.status,status);assert.equal(p.topUp,topUp); + } + assert.equal(playerSnapshot(seed,'missing'),null); +}); +test('routes and image paths safely handle special names and malformed paths',()=>{ + for(const name of ['GODpori','a b','a/b','