feat: grid layout, global claim/qty toggles, admin access link, swaddle image
- Public wishlist now renders as responsive 3-col grid instead of list - Subtitle supports line breaks (whitespace-pre-line) - claimingEnabled and showQuantity moved to global site settings (not per-item); toggled in admin Configurações panel; claim API enforces server-side - Admin dashboard shows admin access link with copy button - Settings API exposes and persists the two new boolean settings Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
60
.planning/debug/resolved/items-reorder-async-transaction.md
Normal file
60
.planning/debug/resolved/items-reorder-async-transaction.md
Normal file
@@ -0,0 +1,60 @@
|
||||
---
|
||||
status: resolved
|
||||
trigger: "Investigate why reordering items fails with 'Failed to reorder item' in the wishlist app"
|
||||
created: 2026-05-03T00:00:00Z
|
||||
updated: 2026-05-03T00:00:00Z
|
||||
---
|
||||
|
||||
## Current Focus
|
||||
|
||||
hypothesis: confirmed — async transaction callback used with synchronous better-sqlite3 driver
|
||||
test: docker logs showed exact error
|
||||
expecting: fix converts async transaction to synchronous
|
||||
next_action: done
|
||||
|
||||
## Symptoms
|
||||
|
||||
expected: Dragging/reordering items in admin UI saves new order
|
||||
actual: "Failed to reorder item" error appears on every reorder attempt
|
||||
errors: TypeError: Transaction function cannot return a promise
|
||||
reproduction: Attempt to reorder any wishlist item in /admin
|
||||
started: unknown
|
||||
|
||||
## Eliminated
|
||||
|
||||
- hypothesis: HTTP method mismatch
|
||||
evidence: route exports POST, frontend calls POST
|
||||
timestamp: 2026-05-03
|
||||
|
||||
- hypothesis: auth issue
|
||||
evidence: error occurs inside the transaction, not at auth check
|
||||
timestamp: 2026-05-03
|
||||
|
||||
- hypothesis: body parsing / missing newSortOrder
|
||||
evidence: error occurs after body is parsed and validated
|
||||
timestamp: 2026-05-03
|
||||
|
||||
## Evidence
|
||||
|
||||
- timestamp: 2026-05-03
|
||||
checked: docker logs chadomartin --tail=50
|
||||
found: "TypeError: Transaction function cannot return a promise" in items reorder route
|
||||
implication: better-sqlite3 is synchronous; async callbacks to db.transaction() throw
|
||||
|
||||
- timestamp: 2026-05-03
|
||||
checked: app/api/wishlists/[id]/reorder/route.ts
|
||||
found: uses synchronous pattern — db.transaction((tx) => { ... .run() ... .all() })
|
||||
implication: this is the correct pattern for better-sqlite3
|
||||
|
||||
- timestamp: 2026-05-03
|
||||
checked: app/api/items/[id]/reorder/route.ts
|
||||
found: uses async pattern — await db.transaction(async (tx) => { await tx.update()... })
|
||||
implication: this is the bug — async callback is rejected by better-sqlite3
|
||||
|
||||
## Resolution
|
||||
|
||||
root_cause: app/api/items/[id]/reorder/route.ts used `await db.transaction(async (tx) => { ... })` — an async callback. better-sqlite3 is a synchronous driver and throws "Transaction function cannot return a promise" when given one.
|
||||
fix: Replaced the async transaction with the synchronous pattern (matching the working wishlists reorder route): `db.transaction((tx) => { ... .run() ... .all() })` with no async/await inside.
|
||||
verification: Code matches the working pattern in the wishlists route; docker logs showed the exact error which this change directly addresses.
|
||||
files_changed:
|
||||
- app/api/items/[id]/reorder/route.ts
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useParams } from 'next/navigation';
|
||||
import DOMPurify from 'dompurify';
|
||||
import { authApi, wishlistsApi, itemsApi, claimingApi, type Wishlist, type Item } from '@/lib/api';
|
||||
import { authApi, wishlistsApi, itemsApi, claimingApi, settingsApi, type Wishlist, type Item, type Settings } from '@/lib/api';
|
||||
import Header from '@/components/header';
|
||||
import GuestGuard from '@/components/guest-guard';
|
||||
|
||||
@@ -19,6 +19,7 @@ function PublicWishlistContent() {
|
||||
const params = useParams();
|
||||
const [wishlist, setWishlist] = useState<Wishlist | null>(null);
|
||||
const [items, setItems] = useState<Item[]>([]);
|
||||
const [siteSettings, setSiteSettings] = useState<Settings>({ siteTitle: '', homepageSubtext: '', claimingEnabled: true, showQuantity: true });
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
|
||||
@@ -54,6 +55,7 @@ function PublicWishlistContent() {
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
settingsApi.getSettings().then(setSiteSettings).catch(() => {});
|
||||
fetchWishlist();
|
||||
}, [params.slug]);
|
||||
|
||||
@@ -192,176 +194,175 @@ function PublicWishlistContent() {
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{filteredItems.map((item) => {
|
||||
const myClaim = myClaimFor(item);
|
||||
const maxForMe = item.remainingQuantity + (myClaim?.quantity ?? 0);
|
||||
const showQuantitySummary = item.quantity > 1;
|
||||
const showQuantitySummary = item.quantity > 1 && siteSettings.showQuantity;
|
||||
const sold = item.remainingQuantity === 0 && !myClaim;
|
||||
const canClaim = siteSettings.claimingEnabled;
|
||||
|
||||
return (
|
||||
<div
|
||||
key={item.id}
|
||||
className="bg-white dark:bg-gray-800 rounded-lg shadow hover:shadow-lg transition-all duration-300 overflow-hidden"
|
||||
className="bg-white dark:bg-gray-800 rounded-lg shadow hover:shadow-lg transition-all duration-300 overflow-hidden flex flex-col"
|
||||
>
|
||||
<div className="flex flex-col md:flex-row">
|
||||
{/* Left: Image */}
|
||||
{item.imageUrl && (
|
||||
<div className="md:w-48 md:flex-shrink-0">
|
||||
<img
|
||||
src={item.imageUrl}
|
||||
alt={item.name}
|
||||
className="w-full h-48 md:h-full object-cover"
|
||||
/>
|
||||
{/* Top: Image */}
|
||||
{item.imageUrl && (
|
||||
<div className="flex-shrink-0">
|
||||
<img
|
||||
src={item.imageUrl}
|
||||
alt={item.name}
|
||||
className="w-full h-48 object-cover"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Middle: Item Details */}
|
||||
<div className="flex-1 p-5">
|
||||
<h3 className="text-xl font-bold text-gray-900 dark:text-white mb-1">
|
||||
{item.name}
|
||||
</h3>
|
||||
{item.price != null && (
|
||||
<p className="text-base font-semibold text-indigo-600 dark:text-indigo-400 mb-1">
|
||||
{new Intl.NumberFormat('pt-BR', { style: 'currency', currency: item.currency || 'BRL' }).format(item.price)}
|
||||
</p>
|
||||
)}
|
||||
{showQuantitySummary && (
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 mb-2">
|
||||
{item.claimedQuantity} de {item.quantity} reservados
|
||||
</p>
|
||||
)}
|
||||
{item.description && (
|
||||
<p className="text-sm text-gray-600 dark:text-gray-300 mb-3">
|
||||
{item.description}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Existing claims list */}
|
||||
{item.claims.length > 0 && (
|
||||
<ul className="text-sm text-gray-700 dark:text-gray-300 space-y-1 mt-3 border-t border-gray-200 dark:border-gray-700 pt-3">
|
||||
{item.claims.map((c) => {
|
||||
const isMine = c.guest.id === currentGuestId;
|
||||
const canCancel = isMine || isAdmin;
|
||||
return (
|
||||
<li key={c.id} className="flex items-center justify-between gap-2">
|
||||
<div>
|
||||
<span className="font-medium">{isMine ? 'Você' : 'Reservado'}</span>
|
||||
{item.quantity > 1 && (
|
||||
<span className="text-gray-500"> · {c.quantity} un.</span>
|
||||
)}
|
||||
{c.note && isMine && (
|
||||
<span className="block text-xs italic text-gray-500">
|
||||
"{c.note}"
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{canCancel && (
|
||||
<button
|
||||
onClick={() => handleUnclaim(item.id, isMine ? undefined : c.guest.id)}
|
||||
disabled={isUnclaiming}
|
||||
className="text-xs text-red-600 hover:underline disabled:opacity-50 cursor-pointer"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Bottom: Action Area */}
|
||||
<div className="p-5 bg-gray-50 dark:bg-gray-900/50 border-t border-gray-200 dark:border-gray-700 flex flex-col gap-3">
|
||||
{item.purchaseUrls && item.purchaseUrls.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{item.purchaseUrls.map((url, idx) => (
|
||||
<a
|
||||
key={idx}
|
||||
href={url.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center justify-between text-sm px-3 py-2 rounded-lg hover:bg-indigo-50 dark:hover:bg-indigo-900/20 transition-colors cursor-pointer border border-gray-200 dark:border-gray-700"
|
||||
>
|
||||
<span className="text-indigo-600 dark:text-indigo-400 hover:text-indigo-800 dark:hover:text-indigo-300 font-medium">
|
||||
{url.label}
|
||||
</span>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Middle: Item Details */}
|
||||
<div className="flex-1 p-6">
|
||||
<h3 className="text-2xl font-bold text-gray-900 dark:text-white mb-1">
|
||||
{item.name}
|
||||
</h3>
|
||||
{item.price != null && (
|
||||
<p className="text-lg font-semibold text-indigo-600 dark:text-indigo-400 mb-1">
|
||||
{new Intl.NumberFormat('pt-BR', { style: 'currency', currency: item.currency || 'BRL' }).format(item.price)}
|
||||
</p>
|
||||
)}
|
||||
{showQuantitySummary && (
|
||||
<p className="text-sm text-gray-500 dark:text-gray-400 mb-3">
|
||||
{item.claimedQuantity} de {item.quantity} reservados
|
||||
</p>
|
||||
)}
|
||||
{item.description && (
|
||||
<p className="text-base text-gray-600 dark:text-gray-300 mb-4">
|
||||
{item.description}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{/* Existing claims list */}
|
||||
{item.claims.length > 0 && (
|
||||
<ul className="text-sm text-gray-700 dark:text-gray-300 space-y-1 mt-4 border-t border-gray-200 dark:border-gray-700 pt-3">
|
||||
{item.claims.map((c) => {
|
||||
const isMine = c.guest.id === currentGuestId;
|
||||
const canCancel = isMine || isAdmin;
|
||||
return (
|
||||
<li key={c.id} className="flex items-center justify-between gap-2">
|
||||
<div>
|
||||
<span className="font-medium">{isMine ? 'Você' : 'Reservado'}</span>
|
||||
{item.quantity > 1 && (
|
||||
<span className="text-gray-500"> · {c.quantity} un.</span>
|
||||
)}
|
||||
{c.note && isMine && (
|
||||
<span className="block text-xs italic text-gray-500">
|
||||
"{c.note}"
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{canCancel && (
|
||||
<button
|
||||
onClick={() => handleUnclaim(item.id, isMine ? undefined : c.guest.id)}
|
||||
disabled={isUnclaiming}
|
||||
className="text-xs text-red-600 hover:underline disabled:opacity-50 cursor-pointer"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Right: Action Area */}
|
||||
<div className="md:w-80 md:flex-shrink-0 p-6 bg-gray-50 dark:bg-gray-900/50 border-t md:border-t-0 md:border-l border-gray-200 dark:border-gray-700 flex flex-col">
|
||||
<div className="mb-4">
|
||||
{item.purchaseUrls && item.purchaseUrls.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{item.purchaseUrls.map((url, idx) => (
|
||||
<a
|
||||
key={idx}
|
||||
href={url.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex items-center justify-between text-base px-4 py-3 rounded-lg hover:bg-indigo-50 dark:hover:bg-indigo-900/20 transition-colors cursor-pointer border border-gray-200 dark:border-gray-700"
|
||||
>
|
||||
<span className="text-indigo-600 dark:text-indigo-400 hover:text-indigo-800 dark:hover:text-indigo-300 font-medium">
|
||||
{url.label}
|
||||
</span>
|
||||
</a>
|
||||
))}
|
||||
{!canClaim ? (
|
||||
<div className="bg-gray-100 dark:bg-gray-700 rounded p-3 text-center text-sm text-gray-500 dark:text-gray-400">
|
||||
Reservas desativadas
|
||||
</div>
|
||||
) : sold ? (
|
||||
<div className="bg-gray-100 dark:bg-gray-700 rounded p-3 text-center text-sm text-gray-700 dark:text-gray-300">
|
||||
Esgotado
|
||||
</div>
|
||||
) : claimingItemId === item.id ? (
|
||||
<form onSubmit={(e) => handleSubmitClaim(e, item.id)} className="space-y-3">
|
||||
{claimError && (
|
||||
<div className="p-2 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-400 rounded text-xs">
|
||||
{claimError}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="mt-auto">
|
||||
{sold ? (
|
||||
<div className="bg-gray-100 dark:bg-gray-700 rounded p-3 text-center text-sm text-gray-700 dark:text-gray-300">
|
||||
Esgotado
|
||||
{item.quantity > 1 && siteSettings.showQuantity && (
|
||||
<div>
|
||||
<label htmlFor={`claim-qty-${item.id}`} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Quantidade (máx {maxForMe}):
|
||||
</label>
|
||||
<input
|
||||
id={`claim-qty-${item.id}`}
|
||||
type="number"
|
||||
min={1}
|
||||
max={maxForMe}
|
||||
value={claimQty}
|
||||
onChange={(e) => setClaimQty(Math.max(1, Math.min(maxForMe, Number(e.target.value) || 1)))}
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-gray-700 dark:text-white"
|
||||
/>
|
||||
</div>
|
||||
) : claimingItemId === item.id ? (
|
||||
<form onSubmit={(e) => handleSubmitClaim(e, item.id)} className="space-y-3">
|
||||
{claimError && (
|
||||
<div className="p-2 bg-red-50 dark:bg-red-900/20 text-red-800 dark:text-red-400 rounded text-xs">
|
||||
{claimError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{item.quantity > 1 && (
|
||||
<div>
|
||||
<label htmlFor={`claim-qty-${item.id}`} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Quantidade (máx {maxForMe}):
|
||||
</label>
|
||||
<input
|
||||
id={`claim-qty-${item.id}`}
|
||||
type="number"
|
||||
min={1}
|
||||
max={maxForMe}
|
||||
value={claimQty}
|
||||
onChange={(e) => setClaimQty(Math.max(1, Math.min(maxForMe, Number(e.target.value) || 1)))}
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-gray-700 dark:text-white"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label htmlFor={`claim-note-${item.id}`} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Deixe uma nota (opcional):
|
||||
</label>
|
||||
<textarea
|
||||
id={`claim-note-${item.id}`}
|
||||
rows={3}
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-gray-700 dark:text-white resize-none"
|
||||
value={claimNote}
|
||||
onChange={(e) => setClaimNote(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isClaiming}
|
||||
className="w-full px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 font-medium disabled:opacity-50 transition-colors cursor-pointer"
|
||||
>
|
||||
{isClaiming ? 'Reservando...' : (myClaim ? 'Atualizar reserva' : 'Confirmar reserva')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setClaimingItemId(null)}
|
||||
className="w-full px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => handleStartClaim(item)}
|
||||
className="w-full px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 font-medium transition-colors cursor-pointer"
|
||||
>
|
||||
{myClaim ? 'Atualizar reserva' : 'Reservar'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label htmlFor={`claim-note-${item.id}`} className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Deixe uma nota (opcional):
|
||||
</label>
|
||||
<textarea
|
||||
id={`claim-note-${item.id}`}
|
||||
rows={3}
|
||||
className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-green-500 dark:bg-gray-700 dark:text-white resize-none"
|
||||
value={claimNote}
|
||||
onChange={(e) => setClaimNote(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isClaiming}
|
||||
className="w-full px-4 py-2 bg-green-500 text-white rounded-md hover:bg-green-600 font-medium disabled:opacity-50 transition-colors cursor-pointer"
|
||||
>
|
||||
{isClaiming ? 'Reservando...' : (myClaim ? 'Atualizar reserva' : 'Confirmar reserva')}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setClaimingItemId(null)}
|
||||
className="w-full px-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-md text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 cursor-pointer"
|
||||
>
|
||||
Cancelar
|
||||
</button>
|
||||
</form>
|
||||
) : (
|
||||
<button
|
||||
onClick={() => handleStartClaim(item)}
|
||||
className="w-full px-4 py-2 bg-indigo-600 text-white rounded-md hover:bg-indigo-700 font-medium transition-colors cursor-pointer"
|
||||
>
|
||||
{myClaim ? 'Atualizar reserva' : 'Reservar'}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -39,7 +39,11 @@ function AdminPageContent() {
|
||||
const [settings, setSettings] = useState<Settings>({
|
||||
siteTitle: 'Wishlist',
|
||||
homepageSubtext: '',
|
||||
claimingEnabled: true,
|
||||
showQuantity: true,
|
||||
});
|
||||
const [adminToken, setAdminToken] = useState<string | null>(null);
|
||||
const [linkCopied, setLinkCopied] = useState(false);
|
||||
|
||||
// Unified config edit state
|
||||
const [isEditingWishlist, setIsEditingWishlist] = useState(false);
|
||||
@@ -52,6 +56,8 @@ function AdminPageContent() {
|
||||
isPublic: true,
|
||||
siteTitle: '',
|
||||
homepageSubtext: '',
|
||||
claimingEnabled: true,
|
||||
showQuantity: true,
|
||||
});
|
||||
const [editError, setEditError] = useState('');
|
||||
const [isWishlistImageUploading, setIsWishlistImageUploading] = useState(false);
|
||||
@@ -68,8 +74,27 @@ function AdminPageContent() {
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
fetchAdminToken();
|
||||
}, []);
|
||||
|
||||
const fetchAdminToken = async () => {
|
||||
try {
|
||||
const res = await fetch('/api/admin/access-link', { credentials: 'include' });
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
setAdminToken(data.token);
|
||||
}
|
||||
} catch { /* ignore */ }
|
||||
};
|
||||
|
||||
const copyAdminLink = async () => {
|
||||
if (!adminToken) return;
|
||||
const url = `${window.location.origin}/?adm=${adminToken}`;
|
||||
await navigator.clipboard.writeText(url);
|
||||
setLinkCopied(true);
|
||||
setTimeout(() => setLinkCopied(false), 2000);
|
||||
};
|
||||
|
||||
const fetchData = async () => {
|
||||
try {
|
||||
const [lists, settingsData] = await Promise.all([
|
||||
@@ -108,6 +133,8 @@ function AdminPageContent() {
|
||||
isPublic: wishlist.isPublic,
|
||||
siteTitle: settings.siteTitle,
|
||||
homepageSubtext: settings.homepageSubtext,
|
||||
claimingEnabled: settings.claimingEnabled,
|
||||
showQuantity: settings.showQuantity,
|
||||
});
|
||||
setEditError('');
|
||||
setIsEditingWishlist(true);
|
||||
@@ -118,13 +145,13 @@ function AdminPageContent() {
|
||||
if (!wishlist) return;
|
||||
setEditError('');
|
||||
try {
|
||||
const { siteTitle, homepageSubtext, ...wishlistFields } = editForm;
|
||||
const { siteTitle, homepageSubtext, claimingEnabled, showQuantity, ...wishlistFields } = editForm;
|
||||
const [updated] = await Promise.all([
|
||||
wishlistsApi.update(wishlist.id, wishlistFields),
|
||||
settingsApi.updateSettings({ siteTitle, homepageSubtext }),
|
||||
settingsApi.updateSettings({ siteTitle, homepageSubtext, claimingEnabled, showQuantity }),
|
||||
]);
|
||||
setWishlist(updated);
|
||||
setSettings({ siteTitle, homepageSubtext });
|
||||
setSettings({ siteTitle, homepageSubtext, claimingEnabled, showQuantity });
|
||||
setIsEditingWishlist(false);
|
||||
} catch (error: any) {
|
||||
setEditError(error.message || 'Failed to update settings');
|
||||
@@ -292,6 +319,26 @@ function AdminPageContent() {
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex gap-6">
|
||||
<label className="flex items-center gap-2 cursor-pointer select-none">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="w-4 h-4 rounded accent-indigo-600"
|
||||
checked={editForm.claimingEnabled}
|
||||
onChange={(e) => setEditForm((prev) => ({ ...prev, claimingEnabled: e.target.checked }))}
|
||||
/>
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300">Permitir reservas</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2 cursor-pointer select-none">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="w-4 h-4 rounded accent-indigo-600"
|
||||
checked={editForm.showQuantity}
|
||||
onChange={(e) => setEditForm((prev) => ({ ...prev, showQuantity: e.target.checked }))}
|
||||
/>
|
||||
<span className="text-sm text-gray-700 dark:text-gray-300">Mostrar quantidade</span>
|
||||
</label>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">
|
||||
Descrição da lista
|
||||
@@ -370,6 +417,30 @@ function AdminPageContent() {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-4 mt-1">
|
||||
<span className={`text-xs px-2 py-0.5 rounded-full font-medium ${settings.claimingEnabled ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400' : 'bg-red-100 dark:bg-red-900/30 text-red-700 dark:text-red-400'}`}>
|
||||
Reservas {settings.claimingEnabled ? 'ativas' : 'desativadas'}
|
||||
</span>
|
||||
<span className={`text-xs px-2 py-0.5 rounded-full font-medium ${settings.showQuantity ? 'bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-400' : 'bg-yellow-100 dark:bg-yellow-900/30 text-yellow-700 dark:text-yellow-400'}`}>
|
||||
Quantidade {settings.showQuantity ? 'visível' : 'oculta'}
|
||||
</span>
|
||||
</div>
|
||||
{adminToken && (
|
||||
<div className="mt-4 pt-4 border-t border-gray-200 dark:border-gray-700">
|
||||
<p className="text-xs font-medium text-gray-500 dark:text-gray-400 mb-2">Link de acesso admin</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="flex-1 text-xs bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300 px-3 py-2 rounded truncate">
|
||||
{`${typeof window !== 'undefined' ? window.location.origin : ''}/?adm=${adminToken}`}
|
||||
</code>
|
||||
<button
|
||||
onClick={copyAdminLink}
|
||||
className="flex-shrink-0 px-3 py-2 text-xs font-medium rounded border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors cursor-pointer"
|
||||
>
|
||||
{linkCopied ? 'Copiado!' : 'Copiar'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
9
app/api/admin/access-link/route.ts
Normal file
9
app/api/admin/access-link/route.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { verifyAdminToken, getAdminToken } from '@/lib/auth/tokens';
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
if (!verifyAdminToken(request)) {
|
||||
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
}
|
||||
return NextResponse.json({ token: getAdminToken() });
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import { and, eq, ne, sql } from 'drizzle-orm';
|
||||
import { db, wishlistItems, wishlists, itemClaims, guests } from '@/lib/db';
|
||||
import { db, wishlistItems, wishlists, itemClaims, guests, settings } from '@/lib/db';
|
||||
import { getGuestFromRequest } from '@/lib/auth/tokens';
|
||||
|
||||
export async function POST(
|
||||
@@ -26,6 +26,11 @@ export async function POST(
|
||||
if (wl.length === 0) return NextResponse.json({ error: 'Wishlist not found' }, { status: 404 });
|
||||
if (!wl[0].isPublic) return NextResponse.json({ error: 'This wishlist is private' }, { status: 403 });
|
||||
|
||||
const claimingSetting = await db.select().from(settings).where(eq(settings.key, 'claimingEnabled')).limit(1);
|
||||
if (claimingSetting[0]?.value === 'false') {
|
||||
return NextResponse.json({ error: 'Reservas desativadas' }, { status: 403 });
|
||||
}
|
||||
|
||||
// Atomically check remaining quantity and upsert the claim inside a synchronous
|
||||
// transaction to prevent race conditions (better-sqlite3 is synchronous).
|
||||
type TxResult = { ok: true } | { ok: false; remaining: number };
|
||||
|
||||
@@ -13,18 +13,18 @@ export async function GET() {
|
||||
return acc;
|
||||
}, {} as Record<string, string>);
|
||||
|
||||
if (!settingsObj.siteTitle) {
|
||||
settingsObj.siteTitle = 'Wishlist';
|
||||
}
|
||||
if (!settingsObj.homepageSubtext) {
|
||||
settingsObj.homepageSubtext = 'Browse and explore available wishlists';
|
||||
}
|
||||
if (!settingsObj.siteTitle) settingsObj.siteTitle = 'Wishlist';
|
||||
if (!settingsObj.homepageSubtext) settingsObj.homepageSubtext = 'Browse and explore available wishlists';
|
||||
if (settingsObj.claimingEnabled === undefined) settingsObj.claimingEnabled = 'true';
|
||||
if (settingsObj.showQuantity === undefined) settingsObj.showQuantity = 'true';
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
settings: {
|
||||
siteTitle: settingsObj.siteTitle,
|
||||
homepageSubtext: settingsObj.homepageSubtext,
|
||||
claimingEnabled: settingsObj.claimingEnabled !== 'false',
|
||||
showQuantity: settingsObj.showQuantity !== 'false',
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -44,7 +44,7 @@ export async function PUT(request: NextRequest) {
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { siteTitle, homepageSubtext } = body;
|
||||
const { siteTitle, homepageSubtext, claimingEnabled, showQuantity } = body;
|
||||
|
||||
if (siteTitle !== undefined) {
|
||||
const existing = await db
|
||||
@@ -86,6 +86,18 @@ export async function PUT(request: NextRequest) {
|
||||
}
|
||||
}
|
||||
|
||||
for (const [key, val] of [['claimingEnabled', claimingEnabled], ['showQuantity', showQuantity]] as const) {
|
||||
if (val !== undefined) {
|
||||
const strVal = val ? 'true' : 'false';
|
||||
const existing = await db.select().from(settings).where(eq(settings.key, key)).limit(1);
|
||||
if (existing.length > 0) {
|
||||
await db.update(settings).set({ value: strVal, updatedAt: new Date() }).where(eq(settings.key, key));
|
||||
} else {
|
||||
await db.insert(settings).values({ key, value: strVal });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Settings updated successfully',
|
||||
|
||||
@@ -40,7 +40,7 @@ export default function Header({ title, subtitle, imageUrl, actions, maxWidth =
|
||||
{title}
|
||||
</h1>
|
||||
{subtitle && (
|
||||
<p className={`text-xl sm:text-2xl text-[color:var(--ink-soft)] mb-6 ${imageUrl ? '' : 'max-w-3xl mx-auto'}`}>
|
||||
<p className={`text-xl sm:text-2xl text-[color:var(--ink-soft)] mb-6 whitespace-pre-line ${imageUrl ? '' : 'max-w-3xl mx-auto'}`}>
|
||||
{subtitle}
|
||||
</p>
|
||||
)}
|
||||
|
||||
@@ -354,6 +354,8 @@ export const scrapingApi = {
|
||||
export interface Settings {
|
||||
siteTitle: string;
|
||||
homepageSubtext: string;
|
||||
claimingEnabled: boolean;
|
||||
showQuantity: boolean;
|
||||
}
|
||||
|
||||
export const settingsApi = {
|
||||
|
||||
Reference in New Issue
Block a user