diff --git a/website/control-panel/public/cp-v2/cp-v2-mentat-embed.css b/website/control-panel/public/cp-v2/cp-v2-mentat-embed.css new file mode 100644 index 00000000..6b532fc3 --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-mentat-embed.css @@ -0,0 +1,2 @@ +html,body{margin:0;padding:0;background:transparent;color:#eee3c7;font:13px/1.5 system-ui,sans-serif}main,#sidebar-right{width:100%;min-width:0;box-sizing:border-box}.mentat-report{box-sizing:border-box;margin:0;width:100%;padding:18px;border:1px solid #ac8f49;border-radius:12px}.mentat-report h3{font-family:Georgia,serif;font-size:25px}.mentat-report a{color:#eed495}.progression-journal-menu,.progression-directory-menu{display:none!important}#report-host:empty,#content:has(#report-host:empty){display:none}.mentat-guest{padding:20px;border:1px solid #9e8546;border-radius:12px;background:#15352a}.mentat-guest a{color:#eed495} +.mentat-report{border:24px solid transparent;border-image:url('https://www.dunerealms.com/assets/imperial-panel-frame-v1.png') 230 fill / 24px / 0 stretch;border-radius:0;padding:14px;background-clip:padding-box;background-image:linear-gradient(180deg,#0b261b95,#102c22ed 65%),url('https://www.dunerealms.com/assets/political-imperial-chamber-v1.png');background-position:center top;background-size:auto 430px;background-repeat:no-repeat}.mentat-report header{padding-top:14px}.mentat-adviser .mentat-portrait{box-shadow:0 0 0 5px #0b231a,0 0 0 7px #c5a557,0 0 24px #c5a55755}.mentat-report h3{text-shadow:0 2px 5px #000}.mentat-xp{background:#0b251b88;border:1px solid #ab945344;padding:10px;border-radius:6px} diff --git a/website/control-panel/public/cp-v2/cp-v2-mentat-embed.html b/website/control-panel/public/cp-v2/cp-v2-mentat-embed.html new file mode 100644 index 00000000..c8346494 --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-mentat-embed.html @@ -0,0 +1 @@ +Your Mentat Report

Opening your personal briefing…

\ No newline at end of file diff --git a/website/control-panel/public/cp-v2/cp-v2-mentat-embed.mjs b/website/control-panel/public/cp-v2/cp-v2-mentat-embed.mjs new file mode 100644 index 00000000..f448c22a --- /dev/null +++ b/website/control-panel/public/cp-v2/cp-v2-mentat-embed.mjs @@ -0,0 +1,5 @@ +import {createProgressionSidebar} from './cp-v2-progression-sidebar.mjs'; +const host=document.querySelector('#report-host');let report=null;const controller=new AbortController(); +function resize(){const height=Math.ceil(document.documentElement.getBoundingClientRect().height);if(height>=100&&height<=1800)for(const origin of ['https://www.dunerealms.com','https://dunerealms.com'])window.parent.postMessage({type:'dune:mentat-size',height},origin);} +async function load(){try{const response=await fetch('/api/progression',{credentials:'same-origin',cache:'no-store',signal:controller.signal});if(response.status===401||response.status===403){host.replaceChildren();host.className='mentat-guest';const h=document.createElement('h2'),p=document.createElement('p'),a=document.createElement('a');h.textContent='Mentat Report';p.textContent='Sign in to see your House adviser, personal level and reputation.';a.textContent='Sign in →';a.href='https://cp.dunerealms.com/';a.target='_top';host.append(h,p,a);resize();return;}if(!response.ok)throw Error('Your briefing is temporarily unavailable.');const data=await response.json();host.replaceChildren();report=createProgressionSidebar(host,{onNavigate:(kind,view)=>{window.top.location.href='https://clans.dunerealms.com/#quests/quests?'+new URLSearchParams({xp:kind,view});}});report.setJournal('personal',data);report.setNavigation('personal','missions');report.showBranches(false);resize();}catch(error){host.textContent=error.message||'Your briefing is temporarily unavailable.';resize();}} +new ResizeObserver(resize).observe(document.body);window.addEventListener('pagehide',()=>{controller.abort();report?.dispose();},{once:true});void load(); diff --git a/website/control-panel/server.mjs b/website/control-panel/server.mjs index 80bf679f..fcbb5bc4 100644 --- a/website/control-panel/server.mjs +++ b/website/control-panel/server.mjs @@ -423,6 +423,7 @@ export function createPanel(db,settings={},dependencies={}){ if(path.startsWith('/v2/vendor/fullcalendar/')&&['GET','HEAD'].includes(request.method)){const file=path.slice('/v2/vendor/fullcalendar/'.length);if(!calendarVendorFiles.has(file))return new Response('Not found',{status:404});const type=file.endsWith('.js')?'text/javascript':file.endsWith('.css')?'text/css':file.endsWith('.json')?'application/json':'text/plain';return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/vendor/fullcalendar/'+file,import.meta.url)),{headers:{'Content-Type':type+'; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});} // All authored cp-v2 browser modules share this bounded public directory. // New components must not require a second, manually maintained route list. + if(path==='/mentat-report')return new Response(request.method==='HEAD'?null:await readFile(new URL('./public/cp-v2/cp-v2-mentat-embed.html',import.meta.url)),{headers:{'Content-Type':'text/html; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff','Content-Security-Policy':PANEL_CSP.replace("img-src 'self' data:;","img-src 'self' data: https://www.dunerealms.com;")}}); if(/^\/(?:v2|cp-v2)\/cp-v2-[a-z0-9-]+\.(?:mjs|css)$/.test(path)){ try{const bytes=await readFile(new URL('./public/cp-v2/'+path.slice(path.lastIndexOf('/')+1),import.meta.url));return new Response(request.method==='HEAD'?null:bytes,{headers:{'Content-Type':path.endsWith('.css')?'text/css; charset=utf-8':'text/javascript; charset=utf-8','Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff'}});}catch(error){if(error.code==='ENOENT')return new Response('Not found',{status:404});throw error;} } diff --git a/website/node/server.mjs b/website/node/server.mjs index 70baa77d..4fb0380b 100644 --- a/website/node/server.mjs +++ b/website/node/server.mjs @@ -1,3 +1,4 @@ +import {createShopSales} from './shop-sales.mjs'; import {initializePassiveOrders} from './political-passive-orders.mjs'; import {POLITICAL_APPOINTMENT_SCHEMA} from './political-appointments.mjs'; import {NETWORK_LAYOUT_SCHEMA} from './organisation-network.mjs'; @@ -35,7 +36,7 @@ import {createMenuBadges} from './menu-badges.mjs'; import {createSearchVisibility} from './search-visibility.mjs'; const root=new URL('./public/',import.meta.url); const servingCommit=releaseCommitFromModuleUrl(import.meta.url); -const security={'X-Content-Type-Options':'nosniff','Referrer-Policy':'strict-origin-when-cross-origin','Content-Security-Policy':"default-src 'self'; frame-src https://cp.dunerealms.com; img-src 'self' https://www.dunerealms.com https://cp.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com data:; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; script-src 'self'; connect-src 'self' https://cp.dunerealms.com; base-uri 'self'; object-src 'none'; frame-ancestors 'self'"}; +const security={'X-Content-Type-Options':'nosniff','Referrer-Policy':'strict-origin-when-cross-origin','Content-Security-Policy':"default-src 'self'; frame-src https://cp.dunerealms.com; img-src 'self' https://shop.dunerealms.com https://www.dunerealms.com https://cp.dunerealms.com https://support.dunerealms.com https://forums.dunerealms.com data:; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; script-src 'self'; connect-src 'self' https://cp.dunerealms.com; base-uri 'self'; object-src 'none'; frame-ancestors 'self'"}; export function createApplication(db,settings={}) { const origin=new URL(settings.PUBLIC_ORIGIN||'https://dunerealms.com').origin; const auth=createAuth(db,origin),publicClans=createPublicClans(db),publicOrganisations=createPublicOrganisations(db); @@ -47,10 +48,12 @@ export function createApplication(db,settings={}) { const gameLink=createGameLink(db,settings,origin); const rewards=createCommunityRewards(db,settings,origin); const publicNews=createPublicNews(db);const publicExchange=createPublicExchange(db,settings); + const shopSales=createShopSales(); const searchVisibility=createSearchVisibility(db);const menuBadges=createMenuBadges(db,settings); return async function handle(request) { const url=new URL(request.url); if(url.pathname==='/ci-build.json'&&servingCommit)return ['GET','HEAD'].includes(request.method)?new Response(request.method==='HEAD'?null:JSON.stringify({commit:servingCommit}),{headers:{'Content-Type':'application/json; charset=utf-8','Cache-Control':'no-store'}}):new Response('Method not allowed',{status:405}); + if(url.pathname==='/api/shop-sales')return shopSales(request); if(url.pathname==='/api/menu-badges')return menuBadges(request); // Discord publishes canonical /news/:slug-:id links. Route these before // static assets so published articles cannot fall through to a Worker 404. diff --git a/website/node/shop-sales.mjs b/website/node/shop-sales.mjs new file mode 100644 index 00000000..f728b86a --- /dev/null +++ b/website/node/shop-sales.mjs @@ -0,0 +1,14 @@ +const SHOP='https://shop.dunerealms.com'; +const FEED=SHOP+'/catalog/dune-shop/sales-feed?currency=EUR'; +const cleanText=(v,max)=>typeof v==='string'&&v.length>0&&v.length<=max&&!/[\x00-\x1f\x7f]/.test(v); +function shopURL(value,{product=false}={}){if(typeof value!=='string'||value.length>1800)return null;try{const url=new URL(value,SHOP+'/catalog/');if(url.hostname!=='shop.dunerealms.com'||!['https:','http:'].includes(url.protocol)||url.username||url.password||url.port||product&&!url.pathname.startsWith('/catalog/'))return null;url.protocol='https:';return url.href;}catch{return null;}} +export function projectShopSales(data){ + if(data?.source!=='oscommerce'||data.currency!=='EUR'||!Array.isArray(data.items)||data.items.length>24)throw Error('Invalid osCommerce promotion feed'); + const items=[];for(const row of data.items){const url=shopURL(row.url,{product:true}),image=shopURL(row.image);if(!Number.isSafeInteger(row.id)||row.id<1||!cleanText(row.name,240)||!cleanText(row.regularPrice,80)||!cleanText(row.salePrice,80)||!Number.isInteger(row.savingPercent)||row.savingPercent<1||row.savingPercent>100||!url)continue;items.push({id:row.id,name:row.name,url,image,regularPrice:row.regularPrice,salePrice:row.salePrice,savingPercent:row.savingPercent});if(items.length===3)break;} + return {source:'oscommerce',brand:'Imperial Heralds',currency:'EUR',items}; +} +export function createShopSales({fetcher=fetch,clock=Date.now}={}){ + let cached=null,expires=0,pending=null; + const read=()=>{if(cached&&clock(){const response=await fetcher(FEED,{redirect:'error',signal:AbortSignal.timeout(8000),headers:{Accept:'application/json'}});if(!response.ok)throw Error('Shop offers unavailable');const text=await response.text();if(text.length>131072)throw Error('Shop offer response too large');const data=projectShopSales(JSON.parse(text));cached=data;expires=clock()+60000;return data;})().finally(()=>pending=null);return pending;}; + return async request=>{if(request.method!=='GET')return Response.json({message:'Read-only shop offers.'},{status:405,headers:{Allow:'GET'}});if(new URL(request.url).search)return Response.json({message:'Unknown shop offer filter.'},{status:400});try{return Response.json(await read(),{headers:{'Cache-Control':'public, max-age=30','X-Content-Type-Options':'nosniff'}});}catch{return Response.json({source:'oscommerce',message:'Shop offers are temporarily unavailable.'},{status:503,headers:{'Cache-Control':'no-store'}});}}; +} diff --git a/website/ops/oscommerce/DuneShopController.php b/website/ops/oscommerce/DuneShopController.php index 283e94c3..d2ca3d76 100644 --- a/website/ops/oscommerce/DuneShopController.php +++ b/website/ops/oscommerce/DuneShopController.php @@ -3,14 +3,29 @@ namespace frontend\controllers; use Yii; use yii\helpers\Html; final class DuneShopController extends Sceleton { + public function actionSalesFeed() { + Yii::$app->response->format=\yii\web\Response::FORMAT_JSON; + Yii::$app->response->headers->set('Cache-Control','public, max-age=60'); + if(!Yii::$app->request->isGet){Yii::$app->response->statusCode=405;return ['message'=>'Read-only shop offers.'];} + $rows=Yii::$app->db->createCommand("SELECT DISTINCT p.products_id,p.products_price,p.products_tax_class_id,pd.products_name FROM products p JOIN platforms_products pp ON pp.products_id=p.products_id AND pp.platform_id=7 JOIN products_description pd ON pd.products_id=p.products_id AND pd.language_id=1 AND pd.platform_id=7 JOIN specials s ON s.products_id=p.products_id WHERE p.products_status=1 AND p.products_price>0 AND s.status=1 AND s.specials_new_products_price>=0 AND s.specials_new_products_priceNOW()) ORDER BY p.products_id DESC LIMIT 12")->queryAll(); + $currencies=Yii::$container->get('currencies');$items=[]; + foreach($rows as $p){ + $id=(int)$p['products_id'];$normal=\common\helpers\Product::get_products_price($id,1,$p['products_price']);$special=\common\helpers\Product::get_products_special_price($id,1); + if(!is_numeric($normal)||!is_numeric($special)||(float)$normal<=0||(float)$special<0||(float)$special>=(float)$normal)continue; + $tax=\common\helpers\Tax::get_tax_rate($p['products_tax_class_id']); + $price=fn($value)=>html_entity_decode(strip_tags($currencies->format($currencies->getPriceTaxable($value,$tax,1),true,'EUR','',false,false)),ENT_QUOTES|ENT_HTML5,'UTF-8'); + $items[]=['id'=>$id,'name'=>$p['products_name'],'url'=>\yii\helpers\Url::to(['catalog/product','products_id'=>$id],true),'image'=>\common\classes\Images::getImageUrl($id,'Small',1),'regularPrice'=>$price($normal),'salePrice'=>$price($special),'savingPercent'=>max(1,(int)round((1-(float)$special/(float)$normal)*100))]; + } + return ['source'=>'oscommerce','brand'=>'Imperial Heralds','currency'=>'EUR','items'=>$items]; + } public function actionIndex() { - $this->view->title='DuneRealms Shop'; + $this->view->title='Imperial Heralds · DuneRealms'; $rows=Yii::$app->db->createCommand("SELECT p.products_id,p.products_price,p.products_tax_class_id,pd.products_name,pd.products_description_short,d.kind FROM products p JOIN platforms_products pp ON pp.products_id=p.products_id AND pp.platform_id=7 JOIN products_description pd ON pd.products_id=p.products_id AND pd.language_id=1 AND pd.platform_id=7 LEFT JOIN dune_catalog_import d ON d.products_id=p.products_id WHERE p.products_status=1 ORDER BY p.products_date_added DESC,p.products_id DESC")->queryAll(); $saleIds=Yii::$app->db->createCommand("SELECT DISTINCT products_id FROM specials WHERE EXISTS(SELECT 1 FROM products active JOIN platforms_products pp ON pp.products_id=active.products_id AND pp.platform_id=7 WHERE active.products_id=specials.products_id AND active.products_status=1 AND specials.specials_new_products_priceNOW())")->queryColumn(); $featuredIds=Yii::$app->db->createCommand("SELECT DISTINCT products_id FROM featured WHERE EXISTS(SELECT 1 FROM products active JOIN platforms_products pp ON pp.products_id=active.products_id AND pp.platform_id=7 WHERE active.products_id=featured.products_id AND active.products_status=1) AND status=1 AND (start_date IS NULL OR start_date='0000-00-00 00:00:00' OR start_date<=NOW()) AND (expires_date IS NULL OR expires_date='0000-00-00 00:00:00' OR expires_date>NOW())")->queryColumn(); $sashes=count(array_filter($rows,fn($r)=>$r['kind']==='sash'));$ranks=count(array_filter($rows,fn($r)=>$r['kind']==='rank')); $base=fn($route)=>Html::encode(\yii\helpers\Url::to([$route])); - $out='
THE DUNEREALMS EMPORIUM

Carry a piece of the realms.

Ceremonial sashes, personal keepsakes and ways to support the community.

Browse the collection
'; + $out='
IMPERIAL HERALDS · DUNEREALMS

Carry a piece of the realms.

Ceremonial sashes, personal keepsakes and ways to support the community.

Browse the collection
'; $tiles=[['Sale',count($saleIds)?'Explore current offers':'No sales active right now','catalog/sales','nav-exchange-v2.webp',''],['Ceremonial sashes',$sashes.' designs · made to order','catalog/all-products','nav-clan-v2.webp','sash'],['Donor ranks',$ranks.' ways to support the realms','catalog/all-products','nav-account-v2.webp','rank']]; $out.='