MC/website/control-panel/public/kit-market.mjs
2026-11-27 23:43:05 +00:00

105 lines
23 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import {createKitGenerator,createEnchantmentProfile} from './kit-generator.mjs';
import {createKitCart} from './kit-cart.mjs';
import {kitReceiptStatus,groupKitReceipts,kitReceiptMetadata} from './kit-receipt-status.mjs';
const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n;};
export async function kitApi(path,body){const r=await fetch('/api/kits/'+path,{cache:'no-store',...(body?{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)}:{})});let d;try{d=await r.json();}catch{throw Error('The kit service returned an unreadable response. Check your receipts before retrying a payment.');}if(!d||typeof d!=='object'||Array.isArray(d))throw Error('The kit service returned an invalid response.');if(!r.ok)throw Error(typeof d.message==='string'&&d.message?d.message:'The kit service is unavailable.');return d;}
export async function mountPersonalKitArc(host){host.replaceChildren(el('p','Loading your kit story…'));try{const d=await kitApi('arc');if(!host.isConnected)return;host.replaceChildren(el('h3',d.title),el('p',d.salesRule),el('p','Rewards are funded by the existing server bank. A reward stays pending if that bank cannot fund it.'));const grid=el('div',undefined,'kit-market-grid');for(const chapter of d.chapters){const card=el('article',undefined,'kit-arc-card'),badge=el('small',chapter.claimed?'COMPLETED':chapter.unlocked?'ACTIVE':'LOCKED');card.append(badge,el('h4',(chapter.index+1)+'. '+chapter.title),el('p',chapter.description||''),el('p',chapter.sales+' / '+chapter.target+' qualifying sales'),el('p','Reward: '+chapter.rewardDunemarks+' DM · Minimum sale: '+chapter.minimumPriceDunemarks+' DM'));const bar=el('progress');bar.max=chapter.target;bar.value=chapter.sales;bar.setAttribute('aria-label','Qualifying sales progress');const button=el('button',chapter.claimed?'Reward Claimed':'Claim Reward');button.type='button';button.disabled=!chapter.canClaim;button.onclick=async()=>{button.disabled=true;try{const result=await kitApi('arc/claim',{index:chapter.index});if(result.pending){const note=el('p','The reward is waiting for server-bank funding.');card.append(note);}else await mountPersonalKitArc(host);}catch(e){card.append(el('p',e.message));button.disabled=!chapter.canClaim;}};card.append(bar,button);grid.append(card);}host.append(grid);}catch(e){if(host.isConnected)host.replaceChildren(el('p',e.message));}}
const dashboard=document.getElementById('dashboard');let actor=null,generation=0;
function mountCart(section){const owner=actor?.username;if(!owner)throw Error('Sign in first.');const cart=createKitCart({uuid:()=>crypto.randomUUID(),storage:sessionStorage,key:'dune-kit-cart-v1:'+owner});const box=el('aside',undefined,'kit-cart'),status=el('p');status.role='status';section.append(box);function render(){box.replaceChildren(el('h3','Your Kit Cart'),el('p','Pay with Dunemarks. Purchased kits produce private redeem codes; no real-money payment is taken here.'));const snap=cart.snapshot();for(const line of snap.lines){const row=el('div',undefined,'kit-cart-line'),remove=el('button','Remove');remove.type='button';remove.disabled=cart.busy;remove.onclick=()=>{try{cart.remove(line.orderLineId);render();}catch(e){status.textContent=e.message;}};row.append(el('span',line.name+' · '+(line.priceCents/100).toFixed(2)+' DM'),remove);box.append(row);}if(!snap.lines.length)box.append(el('p','Your cart is empty.'));box.append(el('strong','Total: '+(cart.total()/100).toFixed(2)+' DM'));const review=el('label'),check=el('input');check.type='checkbox';check.disabled=cart.busy;review.append(check,document.createTextNode(' I have reviewed these kits and the Dunemarks total.'));const pay=el('button',cart.busy?'Processing…':'Pay with Dunemarks');pay.type='button';pay.disabled=true;check.onchange=()=>pay.disabled=cart.busy||!check.checked||!snap.lines.length;pay.onclick=async()=>{if(actor?.username!==owner)return;status.textContent='Processing this cart…';const pending=cart.checkout(async payload=>{const fresh=await kitApi('catalogue');cart.validateCatalogue(fresh.listings);return kitApi('cart/checkout',payload);});render();try{await pending;if(actor?.username!==owner)return;status.replaceChildren(document.createTextNode('Purchase confirmed. '));const receipts=el('a','View your private codes and delivery receipts →');receipts.href=document.body.dataset.service==='tailor'?'#kit-receipts':'#rewards-redeem';status.append(receipts);}catch(e){if(actor?.username!==owner)return;status.textContent=e.message+' Your cart reference has been kept. Retry the same cart if the connection failed; check receipts before changing its contents.';}finally{if(actor?.username===owner)render();}};box.append(review,pay,status);}render();return{has(id){return typeof id==='string'&&cart.snapshot().lines.some(l=>l.listingId.toLowerCase()===id.toLowerCase())},add(listing){if(actor?.username!==owner)return;try{cart.add(listing);status.textContent='Kit added to your cart.';render();}catch(e){status.textContent=e.message;}}};}
function enchantmentBlock(quality,kind){return createEnchantmentProfile(quality,kind);}
async function mountKitStudio(host,{serverMode=false,selectedQuality=null,initialKind=null}={}){
const owner=actor?.username,g=generation,path=serverMode?'server-studio':'studio';host.replaceChildren(el('p','Checking your workshop…'));try{
const data=await kitApi(path);if(owner!==actor?.username||g!==generation||!host.isConnected)return;
host.replaceChildren(el('h3',serverMode?'Network Kit Workshop':'Your Stillsuit Workshop'),el('p','Design your kit and publish it with one action. Draft saves withdraw the previous revision from sale. Archiving is reversible; paid receipts stay unchanged.'));
const kindLabels={personal_sale:'Player Kits',official_sale:'Official Kits',faction_sale:'Faction Kits',server_sale:'Server Kits'},policy={personal_sale:'75% to the seller · 25% to the server bank.',official_sale:'80% to the officeholder · 20% to the server bank.',faction_sale:'25% to the faction bank · 60% to the designer’s personal bank · 15% to the server bank.',server_sale:'100% to the server bank.'};
const kinds=serverMode?['server_sale']:['personal_sale',...(data.offices?.length?['official_sale']:[]),...(data.offices?.some(o=>o.office.startsWith('house-leader:'))?['faction_sale']:[])];
const leaveDesign=()=>!detail.querySelector('.kit-generator-form[data-dirty=true]')||window.confirm('Discard your unsaved design changes?');
let selectedKind=kinds.includes(initialKind)?initialKind:kinds[0];const kindMenu=el('div',undefined,'kit-studio-tiers'),tiers=el('div',undefined,'kit-studio-tiers'),detail=el('div');host.append(kindMenu,tiers,detail);
function show(tier){for(const b of tiers.children)b.setAttribute('aria-pressed',String(b.dataset.quality===tier.quality));detail.replaceChildren();const kind=selectedKind,design=data.designs.find(d=>d.quality===tier.quality&&(d.commerce_kind||'personal_sale')===kind),minimumCents=kind==='personal_sale'?tier.minimumPriceCents:1;
detail.append(el('h4',tier.quality.replaceAll('_',' ').replace(/\b\w/g,c=>c.toUpperCase())),el('p',policy[kind]));if(kind==='personal_sale')detail.append(el('p','Minimum sale price: '+(minimumCents/100).toFixed(2)+' DM'));
const profile=el('details',undefined,'kit-profile-disclosure');profile.append(el('summary','View '+tier.quality.replaceAll('_',' ')+' enchantment profile'),enchantmentBlock(tier.quality,kind));detail.append(profile);
if(kind==='personal_sale'&&!tier.unlocked){detail.append(el('p','Complete the previous chapter in The Loom of the Desert to unlock this rarity.'));return;}
const refresh=()=>mountKitStudio(host,{serverMode,selectedQuality:tier.quality,initialKind:kind});
const status=el('p');status.role='status';
async function lifecycle(action,button){if(owner!==actor?.username)return;button.disabled=true;status.textContent=action==='archive'?'Archiving…':'Restoring…';try{await kitApi(path,{action,kind,quality:tier.quality,version:design.version});await refresh();}catch(e){status.textContent=e.message;button.disabled=false;}}
if(design&&Number(design.active)===0){const restore=el('button','Restore draft');restore.type='button';restore.onclick=()=>lifecycle('restore',restore);detail.append(el('h4',design.name+' · Archived'),el('p','Restore this design to reuse this quality slot. Listings stay unpublished until you review and publish them.'),restore,status);return;}
const shopTypes=kind==='personal_sale'?['player',...(data.clan?['clan']:[])]:[({official_sale:'official',faction_sale:'faction',server_sale:'server'})[kind]];
const listingFields=el('fieldset');listingFields.className='kit-publish-form';listingFields.append(el('legend','Publication'));
const destination=el('select'),destinationLabel=el('label','Shop destination');for(const type of shopTypes){const option=el('option',type==='clan'?data.clan.name+' · Clan Shop':kindLabels[kind]);option.value=type;destination.append(option);}destinationLabel.append(destination);listingFields.append(destinationLabel);
let officeSelect;if(['official_sale','faction_sale'].includes(kind)){const label=el('label','Current office');officeSelect=el('select');for(const o of data.offices.filter(o=>kind!=='faction_sale'||o.office.startsWith('house-leader:'))){const option=el('option',o.office.replaceAll(':',' · '));option.value=o.office;officeSelect.append(option);}label.append(officeSelect);listingFields.append(label);}
const price=el('input'),priceLabel=el('label','Sale price (Dunemarks)');price.type='number';price.step='0.01';price.min=String(minimumCents/100);price.max='1000000';price.required=true;priceLabel.append(price);const listingState=el('p');listingFields.append(priceLabel,listingState);
let listing;function selectDestination(){listing=data.listings.find(l=>l.blueprint_id===design?.id&&l.shop_type===destination.value&&(destination.value!=='clan'||l.clan_id===data.clan?.id));price.value=String((listing?.price_cents||minimumCents)/100);listingState.textContent=listing?.published&&listing.active&&listing.blueprint_version===design?.version?'Published · available in the Kit Exchange.':'Draft · not currently published.';if(officeSelect&&listing?.office_key)officeSelect.value=listing.office_key;}destination.onchange=selectDestination;selectDestination();
if(data.listings.filter(l=>l.blueprint_id===design?.id&&l.published&&l.active).length>1)listingFields.append(el('p','Publishing a revised design updates this destination. Review and republish other destinations for the new revision.'));
const generator=createKitGenerator({kind,submitLabel:'Save & Publish',successMessage:'Design saved and published.',onUpgrade:async code=>{if(owner!==actor?.username)throw Error('Sign in again before using a token.');const result=await kitApi('upgrade-tokens',{action:'roll',code,blueprintId:design.id,version:Number(design.version)});await refresh();return result;},context:kindLabels[kind],initial:design||tier.template||{},quality:tier.quality.replaceAll('_',' '),art:kind==='official_sale'||kind==='server_sale'?'imperial-atelier-v1.webp':'clan-atelier-v1.webp',onSave:async values=>{
if(owner!==actor?.username)throw Error('Sign in again before saving.');const amount=price.value.trim();if(!/^\d{1,7}(?:\.\d{1,2})?$/.test(amount))throw Error('Enter a price with up to two decimal places.');const[whole,fraction='']=amount.split('.');await kitApi(path,{action:'save_publish',kind,quality:tier.quality,version:design?.version||0,...values,listingVersion:listing?.version||0,shopType:destination.value,priceCents:Number(whole)*100+Number(fraction.padEnd(2,'0')),...(officeSelect?{officeKey:officeSelect.value}:{})});await refresh();
}});
generator.form.insertBefore(listingFields,generator.submitButton);
const pending=kind!=='personal_sale'&&!data.nonPersonalPublishingEnabled;generator.submitButton.disabled=pending;if(pending)generator.status.textContent='Save a draft while this category awaits its game-side rollout.';
const draft=el('button','Save draft');draft.type='button';draft.onclick=async()=>{if(owner!==actor?.username||!generator.form.reportValidity())return;draft.disabled=generator.submitButton.disabled=true;generator.status.textContent='Saving draft…';try{await kitApi(path,{action:'save',kind,quality:tier.quality,version:design?.version||0,...generator.value()});await refresh();}catch(e){generator.status.textContent=e.message;draft.disabled=false;generator.submitButton.disabled=pending;}};generator.form.append(draft);
const publicationActions=el('div',undefined,'kit-publication-actions');
const publishExisting=el('button',listing?.published?'Withdraw listing':'Publish saved design');publishExisting.type='button';publishExisting.disabled=!design||(!listing?.published&&pending);publicationActions.append(publishExisting);
publishExisting.onclick=async()=>{if(owner!==actor?.username)return;if(generator.isDirty()){generator.status.textContent='Save your design before changing its publication.';return;}const action=listing?.published?'unpublish':'publish';if(action==='unpublish'&&!window.confirm('Withdraw this listing from the Kit Exchange? Existing paid receipts are retained.'))return;if(action==='publish'&&!price.reportValidity())return;const amount=action==='unpublish'?listing.price_cents:Math.round(Number(price.value)*100);if(!Number.isSafeInteger(amount)||amount<1){generator.status.textContent='Enter a valid sale price.';return;}publishExisting.disabled=true;try{await kitApi(path,{action,kind,quality:tier.quality,blueprintVersion:design.version,listingVersion:listing?.version||0,shopType:destination.value,priceCents:amount,...(officeSelect?{officeKey:officeSelect.value}:{})});await refresh();}catch(error){generator.status.textContent=error.message;publishExisting.disabled=false;}};
listingFields.append(publicationActions);
const actions=el('div',undefined,'kit-studio-tiers');if(design){const edit=el('button','Edit design');edit.type='button';edit.onclick=()=>{generator.form.querySelector('input').focus();generator.element.scrollIntoView({block:'nearest'});};const archive=el('button','Archive design');archive.type='button';const confirmation=el('div');confirmation.hidden=true;confirmation.append(el('p','Remove this design and all its listings from sale? You can restore the draft later. Paid receipts are retained.'));const confirm=el('button','Confirm archive'),cancel=el('button','Cancel');confirm.type=cancel.type='button';confirm.onclick=()=>lifecycle('archive',confirm);cancel.onclick=()=>{confirmation.hidden=true;archive.focus();};archive.onclick=()=>{confirmation.hidden=false;confirm.focus();};confirmation.append(confirm,cancel);actions.append(edit,archive);detail.append(actions,confirmation);}
detail.append(generator.element,status);
}
function chooseKind(kind){selectedKind=kind;for(const b of kindMenu.children)b.setAttribute('aria-pressed',String(b.dataset.kind===kind));tiers.replaceChildren();for(const tier of data.tiers){const locked=kind==='personal_sale'&&!tier.unlocked,b=el('button',tier.quality.replaceAll('_',' ')+(locked?' · Locked':''));b.type='button';b.dataset.quality=tier.quality;b.onclick=()=>{if(leaveDesign())show(tier);};tiers.append(b);}const existing=serverMode?data.designs.find(d=>d.commerce_kind==='server_sale'):null;show(data.tiers.find(t=>t.quality===(selectedQuality||existing?.quality))||data.tiers.find(t=>t.unlocked)||data.tiers[0]);}
for(const kind of kinds){const b=el('button',kindLabels[kind]);b.type='button';b.dataset.kind=kind;b.onclick=()=>{if(leaveDesign())chooseKind(kind);};kindMenu.append(b);}chooseKind(selectedKind);
}catch(e){if(g===generation&&host.isConnected)host.replaceChildren(el('h3',serverMode?'Network Kit Workshop':'Your Stillsuit Workshop'),el('p',e.message));}
}
async function catalogue(){const section=document.getElementById('kits-exchange');if(!actor||!section)return;section.replaceChildren(el('h2','Imperial Tailor'));const browse=el('a','Browse the Kit Exchange →');browse.href='https://www.dunerealms.com/kits.html';const tools=el('nav',undefined,'kit-workshop-links');tools.setAttribute('aria-label','Your kit workshop');tools.append(browse);for(const[label,href]of [['My progression','#kit-story'],['Receipts & delivery','#kit-receipts']]){const a=el('a',label);a.href=href;tools.append(a);}section.append(tools);const host=el('div');section.append(host);await mountKitStudio(host);}
const storySection=el('section'),receiptSection=el('section');storySection.id='kit-story';receiptSection.id='kit-receipts';storySection.hidden=receiptSection.hidden=true;dashboard?.append(storySection,receiptSection);
let checkoutSerial=0;const checkoutSection=el('section');checkoutSection.id='kit-checkout';checkoutSection.hidden=true;checkoutSection.append(el('h2','Kit Checkout'));dashboard?.append(checkoutSection);
async function checkout(){if(!actor)return;const g=generation,serial=++checkoutSerial;checkoutSection.replaceChildren(el('h2','Kit Checkout'),el('p','Checking current listings and your saved cart…'));try{const data=await kitApi('catalogue');if(g!==generation||serial!==checkoutSerial)return;if(!Array.isArray(data?.listings))throw Error('The kit catalogue is unavailable. Your saved cart has been kept.');checkoutSection.replaceChildren(el('h2','Kit Checkout'),el('p','Review the current price and confirm payment. Kit purchases issue private, one-use delivery codes.'));const back=el('a','Continue browsing kits →');back.href='https://www.dunerealms.com/kits.html';checkoutSection.append(back);const cart=mountCart(checkoutSection),url=new URL(location.href),id=url.searchParams.get('kit-listing');if(id){const matches=data.listings.filter(r=>r?.listingId?.toLowerCase()===id.toLowerCase());const listing=matches.length===1?matches[0]:null;if(!listing)checkoutSection.append(el('p','That kit is no longer available. Your existing cart has been kept.'));else if(listing.purchaseAvailable!==true&&!(listing.purchaseAvailable===undefined&&listing.commerceKind==='personal_sale'))checkoutSection.append(el('p','This kit is displayed for browsing but is not yet available to purchase. Your existing cart has been kept.'));else if(!cart.has(id))cart.add(listing);url.searchParams.delete('kit-listing');history.replaceState(null,'',url);}}catch(e){if(g===generation&&serial===checkoutSerial)checkoutSection.replaceChildren(el('h2','Kit Checkout'),el('p',e.message));}}
async function redemption(){
if(!actor)return;
const host=document.querySelector('#rewards-codes>.commerce-placeholder-note')||document.querySelector('#kit-receipts');if(!host)return;
const g=generation,owner=actor.username;
host.replaceChildren(el('h3','Redeem Kit Code'),el('p','Redeeming queues delivery; only the game confirms that your kit has arrived.'));
const form=el('form'),label=el('label','Private kit code'),input=el('input'),submit=el('button','Queue Kit Delivery'),status=el('p');
input.placeholder='DRK-…';input.autocomplete='off';input.required=true;input.maxLength=36;
submit.type='submit';status.role='status';label.append(input);form.append(label,submit,status);host.append(form);
const receipts=el('section'),heading=el('h3','Your Kit Receipts'),refresh=el('button','Refresh receipts'),orders=el('div');
refresh.type='button';receipts.append(heading,refresh,orders);host.append(receipts);
let refreshSerial=0;
async function refreshOrders(){
const serial=++refreshSerial;refresh.disabled=true;orders.replaceChildren(el('p','Loading your receipts…'));
try{
const d=await kitApi('orders');if(g!==generation||owner!==actor?.username||serial!==refreshSerial)return;
const groups=groupKitReceipts(d.orders);orders.replaceChildren();
for(const [title,items] of [['Purchases',groups.purchases],['Sales',groups.sales]]){
const section=el('section');section.append(el('h4',title));
if(!items.length)section.append(el('p',title==='Purchases'?'No kit purchases yet.':'No kit sales yet.'));
for(const order of items){
const row=el('article',undefined,'kit-order-card'),receipt=kitReceiptStatus(order);
row.append(el('h4',order.name||'Kit'),el('p',String(order.grossDunemarks??'—')+' DM · '+receipt.label),el('p',receipt.description));for(const detail of kitReceiptMetadata(order))row.append(el('p',detail));
if(title==='Purchases'&&typeof order.code==='string'&&/^DRK-[A-Z2-7]{32}$/.test(order.code)&&receipt.canRedeem){
const details=el('details'),summary=el('summary','Show Your Private Redeem Code');details.append(summary,el('code',order.code));row.append(details);
}
section.append(row);
}
orders.append(section);
}
}catch(e){if(g===generation&&owner===actor?.username&&serial===refreshSerial)orders.replaceChildren(el('p',e.message));}
finally{if(g===generation&&owner===actor?.username&&serial===refreshSerial)refresh.disabled=false;}
}
refresh.onclick=refreshOrders;
form.onsubmit=async e=>{
e.preventDefault();if(submit.disabled)return;submit.disabled=true;
try{
const d=await kitApi('redeem',{code:input.value.trim().toUpperCase()});if(g!==generation||owner!==actor?.username)return;
status.textContent=d.status==='delivered'?'This kit has already been delivered.':'Delivery queued. Join a planetary server with four empty inventory slots. The game confirms delivery.';
input.value='';await refreshOrders();
}catch(e){if(g===generation&&owner===actor?.username)status.textContent=e.message;}
finally{if(g===generation&&owner===actor?.username)submit.disabled=false;}
};
await refreshOrders();
}
const serverSection=el('section');serverSection.id='server-kits';serverSection.hidden=true;serverSection.append(el('h2','Network Kits'));dashboard?.append(serverSection);const serverLink=el('a','Network Kits');serverLink.href='#server-kits';let serverMenuActor=null;function serverStudio(){if(!actor)return;const protectedAccess=[actor.rank,...(actor.ranks||[])].some(r=>['owners','official_account','corestaff','web_net_admin','network_admin'].includes(r));serverSection.replaceChildren(el('h2','Network Kits'));if(!protectedAccess){serverSection.append(el('p','Protected network rank required.'));return;}if(serverMenuActor!==actor.username){serverMenuActor=actor.username;dashboard.querySelector('nav')?.append(serverLink);}const host=el('div');serverSection.append(host);mountKitStudio(host,{serverMode:true});}window.addEventListener('dune:session',e=>{const u=e.detail;if([u?.rank,...(u?.ranks||[])].some(r=>['owners','official_account','corestaff','web_net_admin','network_admin'].includes(r)))dashboard?.querySelector('nav')?.append(serverLink);else serverLink.remove();});
function load(){checkoutSection.hidden=!actor;serverSection.hidden=!actor||![actor.rank,...(actor.ranks||[])].some(r=>['owners','official_account','corestaff','web_net_admin','network_admin'].includes(r));if(actor&&[actor.rank,...(actor.ranks||[])].some(r=>['owners','official_account','corestaff','web_net_admin','network_admin'].includes(r))&&!serverLink.isConnected)dashboard?.querySelector('nav')?.append(serverLink);const page=location.hash;if(page==='#kit-story')mountPersonalKitArc(storySection);if(page==='#kit-receipts')redemption();if(page==='#kits-exchange')catalogue();if(page==='#server-kits')serverStudio();if(page==='#kit-checkout')checkout();if(['#rewards-redeem','#redeem-code'].includes(page))redemption();}
if(dashboard){const css=el('link');css.rel='stylesheet';css.href='/kit-market.css';document.head.append(css);window.addEventListener('dune:session',e=>{generation++;actor=e.detail;load();});window.addEventListener('dune:page',load);window.addEventListener('hashchange',load);const initial=generation;fetch('/api/auth/session',{cache:'no-store'}).then(r=>r.json()).then(d=>{if(initial===generation){actor=d.user;load();}}).catch(()=>{});}