feat: marketplace, économie à crédits, perks temps réel & pubs réelles

Transforme XIP en réseau social satirique complet : monnaie fictive,
marketplace, cosmétiques visibles de tous, messages riches sandboxés,
pubs pilotées par les données, et tous les compteurs mock rendus réels.

Backend (Bun + Hono + Prisma + Redis)
- Économie par IP : modèles Wallet/Purchase/Entitlement, lib/wallet.ts
  avec spend() atomique (point unique du paywall) + recharge gratuite.
- isLocalhost() → mode gratuit (README « si localhost: pas de paywall »).
- Marketplace : lib/catalog.ts (achat transactionnel, stock limité,
  limites par IP) + routes/shop.ts ; 10 produits seedés (idempotent).
- Perks : lib/perks.ts (cache Redis busté à l'achat) ; authorPerks
  injecté dans les payloads messages + endpoint batch /api/perks ;
  frame WS « perks » global pour MAJ live des messages déjà affichés.
- Messages riches : Message.richMode/richContent, gating par entitlement.
- Pubs réelles : modèle Ad seedé avec les 4 pubs (ex-hardcodées),
  rotation par API, comptage d'impressions réel + réconciliation.
- WebSocket : IP capturée par connexion → broadcastToIp / broadcast ;
  frames wallet/perks/ads/alert.
- Pièces jointes : lib/storage.ts (UUID, jamais exécuté) + routes/uploads.ts
  (limite 1 Mo sauf déblocage/localhost, Content-Disposition: attachment).
- Alerte audio : routes/alert.ts (cooldown serveur Redis NX, clamp durée).
- Compteur « argent extorqué » réel : impressions×CPM + crédits dépensés.

Frontend (Vue 3 + Vite)
- /shop : ShopPage + ProductCard fidèles aux maquettes ; composables
  useWallet/useShop/usePerks/useAds/useAttachments/useAlert.
- UI de réponse (bannière + sous-threads), solde + lien Shop dans le header.
- Perks rendus : Style Doré (or), Pets autour de l'IP, NoAds masque les pubs.
- RichContent.vue : iframe sandbox verrouillée (htmlcss sans script ;
  js allow-scripts seul, jamais allow-same-origin) + CSP.
- AdBand/InlineCasinoAd pilotés par l'API ; barre de saisie avec 📎,
  compteur de caractères, composer riche et bouton alerte.

Infra
- Migration economy_ads_attachments_rich ; seed idempotent (produits+pubs).
- vite.config : usePolling (HMR fiable sur /mnt/c via WSL).
- backend/.gitignore : uploads/.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-30 22:47:23 +02:00
parent 97f6fdaeae
commit cf239ab95f
46 changed files with 4080 additions and 198 deletions

View File

@@ -0,0 +1,123 @@
import { ref } from 'vue';
import { useWallet } from './useWallet';
/** Marketplace client: catalogue, my entitlements, purchase flow. */
export interface Product {
id: string;
category: string;
name: string;
subtitle?: string | null;
kind: string;
basePrice: number; // centi-credits
promoPrice?: number | null;
badge?: string | null;
stockLimit?: number | null;
stockSold: number;
sortOrder: number;
metaJson?: string | null;
}
export interface Entitlement {
id: string;
ip: string;
kind: string;
active: boolean;
expiresAt?: string | null;
metaJson?: string | null;
createdAt: string;
}
export interface PurchaseOptions {
plan?: 'monthly' | 'annual';
durationDays?: number;
format?: 'static' | 'gif';
url?: string;
petDesign?: string;
petChar?: string;
petPosition?: 'left' | 'right' | 'both';
}
const API_URL = import.meta.env.VITE_API_URL ?? 'http://localhost:3000';
export function useShop() {
const products = ref<Product[]>([]);
const entitlements = ref<Entitlement[]>([]);
const loading = ref(false);
const buying = ref<string | null>(null); // productId currently being purchased
const lastError = ref<string | null>(null);
const lastSuccess = ref<string | null>(null);
const { fetchWallet } = useWallet();
async function fetchProducts(): Promise<void> {
loading.value = true;
try {
const res = await fetch(`${API_URL}/api/shop/products`);
if (res.ok) products.value = (await res.json()) as Product[];
} finally {
loading.value = false;
}
}
async function fetchMe(): Promise<void> {
try {
const res = await fetch(`${API_URL}/api/shop/me`);
if (res.ok) {
const data = await res.json();
entitlements.value = data.entitlements ?? [];
}
} catch {
/* ignore */
}
}
function owns(kind: string): boolean {
return entitlements.value.some((e) => e.kind === kind && e.active);
}
function petCount(): number {
return entitlements.value.filter((e) => e.kind === 'pet' && e.active).length;
}
async function purchase(productId: string, options: PurchaseOptions = {}): Promise<boolean> {
buying.value = productId;
lastError.value = null;
lastSuccess.value = null;
try {
const res = await fetch(`${API_URL}/api/shop/purchase`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ productId, options }),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
lastError.value = data.error || 'Achat impossible';
return false;
}
lastSuccess.value = `Acheté : ${productId}`;
// Refresh wallet + my entitlements (WS also pushes wallet, this is belt-and-braces).
await Promise.all([fetchWallet(), fetchMe(), fetchProducts()]);
return true;
} catch {
lastError.value = 'Réseau indisponible';
return false;
} finally {
buying.value = null;
}
}
return {
products,
entitlements,
loading,
buying,
lastError,
lastSuccess,
fetchProducts,
fetchMe,
owns,
petCount,
purchase,
};
}