Document deed settlement recovery and link patronage offers to checkout

This commit is contained in:
unimatrixgit 2026-11-20 22:49:58 +01:00
commit 0d2fd3a065
3 changed files with 50 additions and 2 deletions

View file

@ -0,0 +1,48 @@
# Deed offers and purchases
The clan/company Patronage form publishes an existing `entity-transfer` (XFR)
instruction through `relations.transfer`, then publishes that instruction in the
existing Exchange listing register. Political and protected organisation deeds
are excluded. The offer captures the current entity/deed versions and price in
integer DM minor units. Publishing does not transfer control or charge a buyer.
Exchange links to `/deed-purchase?listing=<listing UUID>`. The authenticated buyer
reviews the current price, seller payment account, purchasing Original/Royal
organisation and its authorised payment account. The existing CP session,
game-access and same-origin write checks apply. Quotes and purchase status are
private; a status request is visible only to its buyer.
Confirmation reserves existing Postbank funds and the scoped XFR instruction.
The existing central scheduler processes it at the ordinary bank window. No
additional worker, balance store or payment ledger is introduced. Execution
revalidates both deeds and calls `setEntityParent`; the local owner, roster and
personal voting rights remain unchanged. This is patronage/control acquisition.
Durable purchase states are `preparing`, `funded`, `applied`, `posted` and `failed`.
The request reference, quoted revision, price, purchaser and accounts are fixed.
Replays use the same reference. The bank order uses mode `deed`, state `escrow`,
so ordinary payment queue processing cannot release it prematurely.
Before the key is consumed, a permanent validation failure releases the bank
reservation and reconciles the unexecuted key. After consumption, a payment
failure retains the escrow and retries the existing Postbank posting operation.
It does not silently undo the deed or charge again. A crash between central key
commit and bank acknowledgement is recovered from the existing key receipt.
Proof readers reuse the held bank transaction connection.
Personal acquisition quests count a deed only when its consumed XFR dossier,
buyer/target/request bindings, posted bank order and balanced debit/credit legs
agree. An offer, reserved payment or self-founded organisation does not count.
Company acquisitions use `purchase`; a voluntarily sold clan uses the existing
`bend-the-knee` quest category. Repeated collection counts each entity once.
The existing conquest producer remains separate.
Bank startup adds `jarvis_deed_purchases` using the normal schema initializer.
Purchasing is unavailable when Postbank is disabled. No reset, old offer
conversion, Minecraft plugin change or real purchase is performed by deployment.
Local integration tests cover retries, changed deeds, withdrawn bank authority,
held payouts, interrupted acknowledgement, private status/origin checks and
verified quest credit. Form tests cover unchanged-intent retries and reopening a
purchase status link. Production publication is not evidence that a real sale
or transfer has executed; record that separately if the owner tests one.

View file

@ -29,7 +29,7 @@ export function mountPatronage(host,{kind='clan',record=null,fetcher=fetch,sellD
requestAnimationFrame(()=>{if(!root.isConnected)return;const probe=el('article');probe.style.cssText='position:absolute;visibility:hidden;box-sizing:border-box;width:'+seeking.getBoundingClientRect().width+'px';probe.append(el('h3','Seeking Patronage'),el('p','Smaller clans will be able to publish a voluntary petition to join a larger household.'));grid.append(probe);const maximum=Math.floor(probe.getBoundingClientRect().height*1.25);probe.remove();if(maximum>0)for(const card of [seeking,offering])card.style.height=maximum+'px';});
const controller=new AbortController();if(sellDeed===null)sellDeed=async input=>{const response=await fetcher('/api/jarvis/publish',{method:'POST',credentials:'same-origin',headers:{'Content-Type':'application/json'},signal:controller.signal,body:JSON.stringify({type:'entity-transfer',...input})});const data=await response.json();if(!response.ok)throw Error(data.message||'Deed publication could not be confirmed.');return data;};let active=true,current=null,busy=false;const requestId=crypto.randomUUID();
async function read(url){const response=await fetcher(url,{credentials:'same-origin',cache:'no-store',signal:controller.signal});const data=await response.json();if(!response.ok)throw Error(data.message||'Service unavailable.');return data;}
void Promise.allSettled([read('/api/exchange/listings?view=all'),read('/api/jarvis/listings')]).then(results=>{if(!active)return;if(results.every(r=>r.status==='rejected'))throw Error('Deed listings are temporarily unavailable.');const records=results.filter(r=>r.status==='fulfilled').flatMap(r=>Array.isArray(r.value)?r.value:r.value.listings||[]);const rows=deedPreviewRows(records,{kind});list.replaceChildren();for(const row of rows){const line=el('a',undefined,'patronage-deed-row');line.href=exchange+'&listing='+encodeURIComponent(row.id);line.target='_top';const icon=el('img');icon.width=icon.height=24;icon.alt='';icon.src=patronageEmblem(row.emblem)||assets+'organisation-deed-keys-v1.png';const copy=el('span',row.displayName||row.title||'Organisation deed'),amount=el('small',Number(row.price).toFixed(2)+' DM');line.append(icon,copy,amount);list.append(line);}state.textContent=rows.length?'':'No '+noun+' deeds currently listed.';}).catch(error=>{if(active)state.textContent=error.message;});
void Promise.allSettled([read('/api/exchange/listings?view=all'),read('/api/jarvis/listings')]).then(results=>{if(!active)return;if(results.every(r=>r.status==='rejected'))throw Error('Deed listings are temporarily unavailable.');const records=results.filter(r=>r.status==='fulfilled').flatMap(r=>Array.isArray(r.value)?r.value:r.value.listings||[]);const rows=deedPreviewRows(records,{kind});list.replaceChildren();for(const row of rows){const line=el('a',undefined,'patronage-deed-row');line.href=row.purchaseAvailable?'https://cp.dunerealms.com/deed-purchase?listing='+encodeURIComponent(row.id):exchange+'&listing='+encodeURIComponent(row.id);line.target='_top';const icon=el('img');icon.width=icon.height=24;icon.alt='';icon.src=patronageEmblem(row.emblem)||assets+'organisation-deed-keys-v1.png';const copy=el('span',row.displayName||row.title||'Organisation deed'),amount=el('small',Number(row.price).toFixed(2)+' DM');line.append(icon,copy,amount);list.append(line);}state.textContent=rows.length?'':'No '+noun+' deeds currently listed.';}).catch(error=>{if(active)state.textContent=error.message;});
async function ownership(){let value=record;if(!company){const registry=await read('/api/clans');if(registry.membership?.clan_role!=='owner')throw Error('Only the clan owner can list its deed.');value=await read('/api/clans/'+encodeURIComponent(registry.membership.clan_id));value={...value.clan,role:value.role,protected:!!value.clan?.institution};}else{if(!record?.id)throw Error('Select your company.');value=await read('/api/companies/deeds/'+encodeURIComponent(record.id));}if(value.role!=='owner'||value.protected||value.institution||value.organisationType==='passive-order')throw Error('Only an ordinary '+noun+' owner can list its deed.');if(!active)return;current=value;name.textContent=value.name;logo.src=patronageEmblem(value.emblem||record?.emblem)||'https://cp.dunerealms.com/api/'+(company?'company':'clan')+'-emblems/'+encodeURIComponent(value.id);submit.disabled=typeof sellDeed!=='function';notice.textContent=submit.disabled?'Deed publication is not connected yet. No key or listing has been created.':'Your deed-key offer will be listed on Exchange for review and purchase.';}
void ownership().catch(error=>{if(active){name.textContent='Your '+noun;notice.textContent=error.message;}});
form.onsubmit=async event=>{event.preventDefault();if(busy||!current||typeof sellDeed!=='function'||!form.reportValidity())return;if(!await confirmAction('Sell '+noun+' deed?','List '+current.name+' for '+Number(price.value).toFixed(2)+' DM on Exchange? This publishes your transfer-key offer; ownership does not change now.'))return;if(!active)return;busy=true;submit.disabled=true;try{const result=await sellDeed({kind,entityId:current.id,version:current.version,price:price.value,message:message.value.trim(),requestId,confirmed:true});if(result?.ok!==true)throw Error('Listing was not confirmed. Check Exchange before retrying.');if(active)notice.textContent='Deed listed on Exchange.';}catch(error){if(active){notice.textContent=error.message;submit.disabled=false;}}finally{busy=false;}};

View file

@ -12,7 +12,7 @@ const accountSQL='SELECT a.*,c.entity_id,e.kind,e.external_key,e.active AS entit
const fail=(message,status=409)=>{throw new JarvisError(message,status);};
const paymentInput=j=>({keyId:j.key_id,listingId:j.listing_id,requestId:j.id,actorId:j.actor_id,sellerId:j.seller_id,parentKind:j.parent_kind,parentId:j.parent_id,sourceAccount:String(j.source_account),recipientAccount:String(j.recipient_account),priceMinor:Number(j.price_minor)});
const matches=(j,p)=>j&&j.id===p.requestId&&j.actor_id===p.buyerId&&j.seller_id===p.sellerId&&j.key_id===p.keyId&&j.listing_id===p.listingId&&j.parent_kind===p.parent.kind&&j.parent_id===p.parent.id&&String(j.source_account)===p.sourceAccount&&String(j.recipient_account)===p.recipientAccount&&Number(j.price_minor)===p.priceMinor;
const receipt=j=>({purchaseId:j.id,listingId:j.listing_id,state:j.state,nextProcessingAt:Number(j.due_at),paymentReference:j.id,complete:j.state==='posted',message:j.state==='posted'?'Deed acquisition and payment completed.':j.state==='failed'?'The deed or payment authority changed. No purchase was completed.':'Purchase reserved for the ordinary bank processing window.'});
const receipt=j=>({purchaseId:j.id,listingId:j.listing_id,state:j.state,nextProcessingAt:Number(j.due_at),paymentReference:j.id,complete:j.state==='posted',message:j.state==='posted'?'Deed acquisition and payment completed.':j.state==='failed'?'The deed or payment authority changed. No purchase was completed.':j.state==='applied'?'Deed transfer recorded. The reserved payment is awaiting bank reconciliation.':'Purchase reserved for the ordinary bank processing window.'});
export function createDeedPurchases(central,bank,keys,{authority,clock=Date.now,resolveActor=async id=>(await central.query("SELECT id,username,role FROM site_accounts WHERE id=? AND password_hash NOT LIKE '!%'",[id]))[0]||null}={}){
if(typeof authority!=='function')throw TypeError('Current bank authority adapter required');
const bankScope=new AsyncLocalStorage(),reader=()=>bankScope.getStore()||bank;