feat: mobile-first refactor for BottleDetails & RLS security/performance optimizations

This commit is contained in:
2025-12-26 23:58:35 +01:00
parent 20f7436e66
commit 20659567fd
9 changed files with 734 additions and 282 deletions

62
performance_indexing.sql Normal file
View File

@@ -0,0 +1,62 @@
-- ============================================
-- Database Performance Optimization: Indexing
-- ============================================
-- Addresses "unindexed_foreign_keys" and "unused_index" linter warnings
-- ============================================
-- ============================================
-- 1. Missing Indexes for Foreign Keys
-- ============================================
-- bottles
CREATE INDEX IF NOT EXISTS idx_bottles_user_id ON public.bottles(user_id);
-- buddies
CREATE INDEX IF NOT EXISTS idx_buddies_user_id ON public.buddies(user_id);
CREATE INDEX IF NOT EXISTS idx_buddies_buddy_profile_id ON public.buddies(buddy_profile_id);
-- credit_transactions
CREATE INDEX IF NOT EXISTS idx_credit_transactions_admin_id ON public.credit_transactions(admin_id);
-- session_participants
CREATE INDEX IF NOT EXISTS idx_session_participants_session_id ON public.session_participants(session_id);
CREATE INDEX IF NOT EXISTS idx_session_participants_buddy_id ON public.session_participants(buddy_id);
CREATE INDEX IF NOT EXISTS idx_session_participants_user_id ON public.session_participants(user_id);
-- tags
CREATE INDEX IF NOT EXISTS idx_tags_created_by ON public.tags(created_by);
-- tasting_buddies
CREATE INDEX IF NOT EXISTS idx_tasting_buddies_tasting_id ON public.tasting_buddies(tasting_id);
CREATE INDEX IF NOT EXISTS idx_tasting_buddies_buddy_id ON public.tasting_buddies(buddy_id);
CREATE INDEX IF NOT EXISTS idx_tasting_buddies_user_id ON public.tasting_buddies(user_id);
-- tasting_sessions
CREATE INDEX IF NOT EXISTS idx_tasting_sessions_user_id ON public.tasting_sessions(user_id);
-- tasting_tags (aroma tags)
CREATE INDEX IF NOT EXISTS idx_tasting_tags_tasting_id ON public.tasting_tags(tasting_id);
CREATE INDEX IF NOT EXISTS idx_tasting_tags_tag_id ON public.tasting_tags(tag_id);
CREATE INDEX IF NOT EXISTS idx_tasting_tags_user_id ON public.tasting_tags(user_id);
-- tastings
CREATE INDEX IF NOT EXISTS idx_tastings_bottle_id ON public.tastings(bottle_id);
CREATE INDEX IF NOT EXISTS idx_tastings_user_id ON public.tastings(user_id);
-- ============================================
-- 2. Cleanup of Unused Indexes
-- ============================================
-- These were flagged by the linter as "never used".
-- Use with caution, but removal helps with insert/update performance.
-- DROP INDEX IF EXISTS idx_global_products_search_vector;
-- DROP INDEX IF EXISTS idx_buddy_invites_code;
-- DROP INDEX IF EXISTS idx_buddy_invites_expires_at;
-- DROP INDEX IF EXISTS idx_split_participants_status;
-- DROP INDEX IF EXISTS idx_tastings_tasted_at;
-- DROP INDEX IF EXISTS idx_credit_transactions_created_at;
-- DROP INDEX IF EXISTS idx_credit_transactions_type;
-- DROP INDEX IF EXISTS idx_subscription_plans_active;
-- DROP INDEX IF EXISTS idx_subscription_plans_sort_order;
-- DROP INDEX IF EXISTS idx_user_subscriptions_plan_id;

75
rls_buddy_access.sql Normal file
View File

@@ -0,0 +1,75 @@
-- ============================================
-- Buddy Access Logic Migration
-- Run AFTER rls_policy_performance_fixes.sql
-- ============================================
-- Adds read-only access for buddies to see sessions/tastings they participate in
-- ============================================
-- ============================================
-- Fix: tasting_sessions - Add consolidated buddy read access
-- ============================================
-- Drop all previous policies for this table
DROP POLICY IF EXISTS "tasting_sessions_policy" ON tasting_sessions;
DROP POLICY IF EXISTS "tasting_sessions_owner_policy" ON tasting_sessions;
DROP POLICY IF EXISTS "tasting_sessions_buddy_select_policy" ON tasting_sessions;
-- Consolidated SELECT: owner OR participant
CREATE POLICY "tasting_sessions_select_policy" ON tasting_sessions
FOR SELECT USING (
(SELECT auth.uid()) = user_id OR
id IN (
SELECT sp.session_id
FROM session_participants sp
JOIN buddies b ON b.id = sp.buddy_id
WHERE b.buddy_profile_id = (SELECT auth.uid())
)
);
-- Owner-only for other actions
CREATE POLICY "tasting_sessions_insert_policy" ON tasting_sessions
FOR INSERT WITH CHECK ((SELECT auth.uid()) = user_id);
CREATE POLICY "tasting_sessions_update_policy" ON tasting_sessions
FOR UPDATE USING ((SELECT auth.uid()) = user_id);
CREATE POLICY "tasting_sessions_delete_policy" ON tasting_sessions
FOR DELETE USING ((SELECT auth.uid()) = user_id);
-- ============================================
-- Fix: tastings - Add consolidated buddy read access
-- ============================================
-- Drop all previous policies for this table
DROP POLICY IF EXISTS "tastings_policy" ON tastings;
DROP POLICY IF EXISTS "tastings_owner_policy" ON tastings;
DROP POLICY IF EXISTS "tastings_buddy_select_policy" ON tastings;
-- Consolidated SELECT: owner OR tagged buddy
CREATE POLICY "tastings_select_policy" ON tastings
FOR SELECT USING (
(SELECT auth.uid()) = user_id OR
id IN (
SELECT tb.tasting_id
FROM tasting_buddies tb
JOIN buddies b ON b.id = tb.buddy_id
WHERE b.buddy_profile_id = (SELECT auth.uid())
)
);
-- Owner-only for other actions
CREATE POLICY "tastings_insert_policy" ON tastings
FOR INSERT WITH CHECK ((SELECT auth.uid()) = user_id);
CREATE POLICY "tastings_update_policy" ON tastings
FOR UPDATE USING ((SELECT auth.uid()) = user_id);
CREATE POLICY "tastings_delete_policy" ON tastings
FOR DELETE USING ((SELECT auth.uid()) = user_id);
-- ============================================
-- Note: bottles stays owner-only for now
-- The original logic was complex and could cause RLS recursion
-- If you need buddies to see bottles, we can add it separately
-- ============================================

View File

@@ -0,0 +1,248 @@
-- ============================================
-- RLS Policy Performance Fixes Migration
-- Run this in Supabase SQL Editor
-- ============================================
-- Fixes two types of issues:
-- 1. auth_rls_initplan: Ensures auth.uid() is wrapped in (SELECT ...)
-- 2. multiple_permissive_policies: Consolidates overlapping policies
-- ============================================
-- ============================================
-- Fix 1: user_subscriptions
-- Issues: Multiple permissive policies for INSERT and SELECT
-- ============================================
-- Drop existing policies
DROP POLICY IF EXISTS "user_subscriptions_select_policy" ON user_subscriptions;
DROP POLICY IF EXISTS "user_subscriptions_admin_policy" ON user_subscriptions;
DROP POLICY IF EXISTS "user_subscriptions_insert_self" ON user_subscriptions;
-- Consolidated SELECT policy: user can see own OR admin can see all
CREATE POLICY "user_subscriptions_select_policy" ON user_subscriptions
FOR SELECT USING (
(SELECT auth.uid()) = user_id OR
EXISTS (SELECT 1 FROM admin_users WHERE admin_users.user_id = (SELECT auth.uid()))
);
-- Consolidated INSERT policy: user can insert own OR admin can insert any
CREATE POLICY "user_subscriptions_insert_policy" ON user_subscriptions
FOR INSERT WITH CHECK (
(SELECT auth.uid()) = user_id OR
EXISTS (SELECT 1 FROM admin_users WHERE admin_users.user_id = (SELECT auth.uid()))
);
-- Admin UPDATE/DELETE policy
CREATE POLICY "user_subscriptions_admin_modify_policy" ON user_subscriptions
FOR UPDATE USING (
EXISTS (SELECT 1 FROM admin_users WHERE admin_users.user_id = (SELECT auth.uid()))
);
CREATE POLICY "user_subscriptions_admin_delete_policy" ON user_subscriptions
FOR DELETE USING (
EXISTS (SELECT 1 FROM admin_users WHERE admin_users.user_id = (SELECT auth.uid()))
);
-- ============================================
-- Fix 2: bottle_splits
-- Issues: bottle_splits_host_policy (ALL) and bottle_splits_public_view (SELECT) overlap
-- ============================================
DROP POLICY IF EXISTS "bottle_splits_host_policy" ON bottle_splits;
DROP POLICY IF EXISTS "bottle_splits_public_view" ON bottle_splits;
-- Consolidated SELECT: host can see all own, everyone can see active
CREATE POLICY "bottle_splits_select_policy" ON bottle_splits
FOR SELECT USING (
(SELECT auth.uid()) = host_id OR is_active = true
);
-- Host-only for INSERT/UPDATE/DELETE
CREATE POLICY "bottle_splits_host_insert_policy" ON bottle_splits
FOR INSERT WITH CHECK ((SELECT auth.uid()) = host_id);
CREATE POLICY "bottle_splits_host_update_policy" ON bottle_splits
FOR UPDATE USING ((SELECT auth.uid()) = host_id);
CREATE POLICY "bottle_splits_host_delete_policy" ON bottle_splits
FOR DELETE USING ((SELECT auth.uid()) = host_id);
-- ============================================
-- Fix 3: bottles
-- Issues: bottles_owner_policy (ALL) and bottles_session_select_policy (SELECT) overlap
-- Strategy: Just keep owner policy because the session_select_policy doesn't exist in schema
-- ============================================
DROP POLICY IF EXISTS "bottles_owner_policy" ON bottles;
DROP POLICY IF EXISTS "bottles_session_select_policy" ON bottles;
-- Owner-only policy for all operations (simple and performant)
CREATE POLICY "bottles_policy" ON bottles
FOR ALL USING ((SELECT auth.uid()) = user_id);
-- ============================================
-- Fix 4: buddy_invites
-- Issues: buddy_invites_creator_policy (ALL) and buddy_invites_redeem_policy (SELECT) overlap
-- ============================================
DROP POLICY IF EXISTS "buddy_invites_creator_policy" ON buddy_invites;
DROP POLICY IF EXISTS "buddy_invites_redeem_policy" ON buddy_invites;
-- Consolidated SELECT: creator can see own, anyone can see non-expired (for redemption)
CREATE POLICY "buddy_invites_select_policy" ON buddy_invites
FOR SELECT USING (
(SELECT auth.uid()) = creator_id OR expires_at > now()
);
-- Creator-only for INSERT/UPDATE/DELETE
CREATE POLICY "buddy_invites_creator_insert_policy" ON buddy_invites
FOR INSERT WITH CHECK ((SELECT auth.uid()) = creator_id);
CREATE POLICY "buddy_invites_creator_update_policy" ON buddy_invites
FOR UPDATE USING ((SELECT auth.uid()) = creator_id);
CREATE POLICY "buddy_invites_creator_delete_policy" ON buddy_invites
FOR DELETE USING ((SELECT auth.uid()) = creator_id);
-- ============================================
-- Fix 5: global_products
-- Issues: "Enable Admin Insert/Update" (ALL) and "Enable Read Access for all users" (SELECT) overlap
-- ============================================
DROP POLICY IF EXISTS "Enable Admin Insert/Update" ON global_products;
DROP POLICY IF EXISTS "Enable Read Access for all users" ON global_products;
-- Everyone can SELECT
CREATE POLICY "global_products_select_policy" ON global_products
FOR SELECT USING (true);
-- Admin-only for INSERT/UPDATE/DELETE
CREATE POLICY "global_products_admin_insert_policy" ON global_products
FOR INSERT WITH CHECK (
EXISTS (SELECT 1 FROM admin_users WHERE admin_users.user_id = (SELECT auth.uid()))
);
CREATE POLICY "global_products_admin_update_policy" ON global_products
FOR UPDATE USING (
EXISTS (SELECT 1 FROM admin_users WHERE admin_users.user_id = (SELECT auth.uid()))
);
CREATE POLICY "global_products_admin_delete_policy" ON global_products
FOR DELETE USING (
EXISTS (SELECT 1 FROM admin_users WHERE admin_users.user_id = (SELECT auth.uid()))
);
-- ============================================
-- Fix 6: session_participants
-- Issues: session_participants_manage_policy and session_participants_read_policy overlap
-- ============================================
DROP POLICY IF EXISTS "session_participants_owner_policy" ON session_participants;
DROP POLICY IF EXISTS "session_participants_manage_policy" ON session_participants;
DROP POLICY IF EXISTS "session_participants_read_policy" ON session_participants;
-- Single unified policy: owner can do all
CREATE POLICY "session_participants_policy" ON session_participants
FOR ALL USING ((SELECT auth.uid()) = user_id);
-- ============================================
-- Fix 7: split_participants
-- Issues: Multiple overlapping policies for different actions
-- ============================================
DROP POLICY IF EXISTS "split_participants_own_policy" ON split_participants;
DROP POLICY IF EXISTS "split_participants_host_policy" ON split_participants;
DROP POLICY IF EXISTS "split_participants_public_view" ON split_participants;
-- Consolidated SELECT: own participation OR host of split OR public active split
CREATE POLICY "split_participants_select_policy" ON split_participants
FOR SELECT USING (
(SELECT auth.uid()) = user_id OR
split_id IN (SELECT id FROM bottle_splits WHERE host_id = (SELECT auth.uid())) OR
split_id IN (SELECT id FROM bottle_splits WHERE is_active = true)
);
-- INSERT: own participation OR host of split
CREATE POLICY "split_participants_insert_policy" ON split_participants
FOR INSERT WITH CHECK (
(SELECT auth.uid()) = user_id OR
split_id IN (SELECT id FROM bottle_splits WHERE host_id = (SELECT auth.uid()))
);
-- UPDATE: own participation OR host of split
CREATE POLICY "split_participants_update_policy" ON split_participants
FOR UPDATE USING (
(SELECT auth.uid()) = user_id OR
split_id IN (SELECT id FROM bottle_splits WHERE host_id = (SELECT auth.uid()))
);
-- DELETE: own participation OR host of split
CREATE POLICY "split_participants_delete_policy" ON split_participants
FOR DELETE USING (
(SELECT auth.uid()) = user_id OR
split_id IN (SELECT id FROM bottle_splits WHERE host_id = (SELECT auth.uid()))
);
-- ============================================
-- Fix 8: subscription_plans
-- Issues: subscription_plans_admin_policy (ALL) and subscription_plans_select_policy (SELECT) overlap
-- ============================================
DROP POLICY IF EXISTS "subscription_plans_select_policy" ON subscription_plans;
DROP POLICY IF EXISTS "subscription_plans_admin_policy" ON subscription_plans;
-- Consolidated SELECT: active plans OR admin can see all
CREATE POLICY "subscription_plans_select_policy" ON subscription_plans
FOR SELECT USING (
is_active = true OR
EXISTS (SELECT 1 FROM admin_users WHERE admin_users.user_id = (SELECT auth.uid()))
);
-- Admin-only for INSERT/UPDATE/DELETE
CREATE POLICY "subscription_plans_admin_insert_policy" ON subscription_plans
FOR INSERT WITH CHECK (
EXISTS (SELECT 1 FROM admin_users WHERE admin_users.user_id = (SELECT auth.uid()))
);
CREATE POLICY "subscription_plans_admin_update_policy" ON subscription_plans
FOR UPDATE USING (
EXISTS (SELECT 1 FROM admin_users WHERE admin_users.user_id = (SELECT auth.uid()))
);
CREATE POLICY "subscription_plans_admin_delete_policy" ON subscription_plans
FOR DELETE USING (
EXISTS (SELECT 1 FROM admin_users WHERE admin_users.user_id = (SELECT auth.uid()))
);
-- ============================================
-- Fix 9: tasting_sessions
-- Issues: sessions_access_policy (ALL) and sessions_modification_policy overlap
-- Strategy: Keep it simple - owner-only for modifications, no complex buddy joins
-- ============================================
DROP POLICY IF EXISTS "sessions_access_policy" ON tasting_sessions;
DROP POLICY IF EXISTS "sessions_modification_policy" ON tasting_sessions;
-- Owner-only policy for all operations
CREATE POLICY "tasting_sessions_policy" ON tasting_sessions
FOR ALL USING ((SELECT auth.uid()) = user_id);
-- ============================================
-- Fix 10: tastings
-- Issues: tastings_modify_policy (ALL) and tastings_select_policy (SELECT) overlap
-- Strategy: Keep it simple - owner-only for all operations
-- ============================================
DROP POLICY IF EXISTS "tastings_select_policy" ON tastings;
DROP POLICY IF EXISTS "tastings_modify_policy" ON tastings;
-- Owner-only policy for all operations
CREATE POLICY "tastings_policy" ON tastings
FOR ALL USING ((SELECT auth.uid()) = user_id);
-- ============================================
-- Verification Query (run after migration)
-- ============================================
-- SELECT tablename, policyname, roles, cmd
-- FROM pg_policies
-- WHERE schemaname = 'public'
-- ORDER BY tablename, cmd, roles;

View File

@@ -0,0 +1,31 @@
-- ============================================
-- Database Security Optimization: Search Path
-- ============================================
-- Addresses "function_search_path_mutable" security warnings
-- ============================================
-- Fix for handle_new_user
ALTER FUNCTION public.handle_new_user() SET search_path = '';
-- Fix for generate_buddy_code
-- If this function exists, update its search_path
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_proc WHERE proname = 'generate_buddy_code') THEN
ALTER FUNCTION public.generate_buddy_code() SET search_path = '';
END IF;
END $$;
-- Fix for check_session_access
-- If this function exists, update its search_path
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM pg_proc WHERE proname = 'check_session_access') THEN
BEGIN
ALTER FUNCTION public.check_session_access(uuid) SET search_path = '';
-- Note: If it has different arguments, you might need to adjust the signature above
EXCEPTION WHEN OTHERS THEN
RAISE NOTICE 'Could not set search_path for check_session_access: %', SQLERRM;
END;
END IF;
END $$;

View File

@@ -82,186 +82,202 @@ export default function BottleDetails({ bottleId, sessionId, userId }: BottleDet
if (!bottle) return null; // Should not happen due to check above
return (
<div className="max-w-4xl mx-auto space-y-6 md:space-y-12">
<div className="max-w-2xl mx-auto px-4 pb-12 space-y-8">
{/* Back Button */}
<Link
href={`/${sessionId ? `?session_id=${sessionId}` : ''}`}
className="inline-flex items-center gap-2 text-zinc-500 hover:text-orange-600 transition-colors font-bold mb-4"
>
<ChevronLeft size={20} />
Zurück zur Sammlung
</Link>
<div className="pt-4">
<Link
href={`/${sessionId ? `?session_id=${sessionId}` : ''}`}
className="inline-flex items-center gap-2 text-zinc-500 hover:text-zinc-300 transition-colors font-bold text-sm tracking-tight"
>
<ChevronLeft size={18} />
Zurück
</Link>
</div>
{isOffline && (
<div className="bg-orange-600/10 border border-orange-600/20 p-3 rounded-2xl flex items-center gap-3 animate-in fade-in slide-in-from-top-2">
<WifiOff size={16} className="text-orange-600" />
<p className="text-[10px] font-bold uppercase tracking-widest text-orange-500">Offline-Modus: Daten aus dem Cache</p>
<p className="text-[10px] font-bold uppercase tracking-widest text-orange-500">Offline-Modus</p>
</div>
)}
{/* Hero Section */}
<section className="grid grid-cols-1 md:grid-cols-2 gap-8 items-start">
<div className="aspect-[4/5] rounded-3xl overflow-hidden shadow-2xl border border-zinc-800 bg-zinc-900">
{/* Header & Hero Section */}
<div className="space-y-6">
{/* 1. Header (Title at top) */}
<div className="text-center md:text-left">
<h1 className="text-3xl md:text-5xl font-black text-white tracking-tighter uppercase leading-none">
{bottle.name}
</h1>
<h2 className="text-lg md:text-xl text-orange-600 font-bold mt-2 uppercase tracking-[0.2em]">
{bottle.distillery}
</h2>
</div>
{/* 2. Image (Below title) */}
<div className="relative aspect-video w-full max-h-[280px] rounded-3xl overflow-hidden bg-radial-dark border border-zinc-800/50 flex items-center justify-center p-4">
<div className="absolute inset-0 bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] from-zinc-800/20 via-transparent to-transparent opacity-50" />
<img
src={getStorageUrl(bottle.image_url)}
alt={bottle.name}
className="w-full h-full object-cover"
className="max-h-full max-w-full object-contain drop-shadow-[0_20px_50px_rgba(0,0,0,0.5)] z-10"
/>
</div>
{/* 3. Metadata Consolidation (Info Row) */}
<div className="flex flex-wrap items-center justify-center md:justify-start gap-2 pt-2">
<div className="flex items-center gap-1.5 px-3 py-1.5 bg-zinc-900/80 border border-zinc-800 rounded-full">
<Wine size={14} className="text-orange-500" />
<span className="text-[11px] font-black uppercase tracking-wider text-zinc-300">{bottle.category || 'Whisky'}</span>
</div>
<div className="flex items-center gap-1.5 px-3 py-1.5 bg-zinc-900/80 border border-zinc-800 rounded-full">
<Droplets size={14} className="text-blue-400" />
<span className="text-[11px] font-black uppercase tracking-wider text-zinc-300">{bottle.abv}%</span>
</div>
{bottle.age && (
<div className="flex items-center gap-1.5 px-3 py-1.5 bg-zinc-900/80 border border-zinc-800 rounded-full">
<Calendar size={14} className="text-zinc-500" />
<span className="text-[11px] font-black uppercase tracking-wider text-zinc-300">{bottle.age}J.</span>
</div>
)}
{bottle.distilled_at && (
<div className="flex items-center gap-1.5 px-3 py-1.5 bg-zinc-900/80 border border-zinc-800 rounded-full">
<Calendar size={12} className="text-zinc-500" />
<span className="text-[10px] font-black uppercase tracking-wider text-zinc-400">Dist. {bottle.distilled_at}</span>
</div>
)}
{bottle.bottled_at && (
<div className="flex items-center gap-1.5 px-3 py-1.5 bg-zinc-900/80 border border-zinc-800 rounded-full">
<Package size={12} className="text-zinc-500" />
<span className="text-[10px] font-black uppercase tracking-wider text-zinc-400">Bott. {bottle.bottled_at}</span>
</div>
)}
{bottle.batch_info && (
<div className="flex items-center gap-1.5 px-3 py-1.5 bg-zinc-900/80 border border-zinc-800 rounded-full">
<Info size={12} className="text-zinc-500" />
<span className="text-[10px] font-black uppercase tracking-wider text-zinc-400">{bottle.batch_info}</span>
</div>
)}
{bottle.whiskybase_id && (
<a
href={`https://www.whiskybase.com/whiskies/whisky/${bottle.whiskybase_id}`}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1.5 px-3 py-1.5 bg-zinc-900/80 border border-zinc-800 rounded-full hover:border-orange-600/50 transition-colors"
>
<ExternalLink size={12} className="text-zinc-600" />
<span className="text-[10px] font-black uppercase tracking-wider text-zinc-500">WB {bottle.whiskybase_id}</span>
</a>
)}
</div>
</div>
{/* 4. Inventory Section (Cohesive Container) */}
<section className="bg-zinc-900/30 border border-zinc-800/50 rounded-[32px] p-6 space-y-6">
<div className="flex items-center justify-between mb-2">
<h3 className="text-[10px] font-black uppercase tracking-[0.2em] text-zinc-500">My Bottle</h3>
<Package size={14} className="text-zinc-700" />
</div>
<div className="space-y-6">
<div>
<h1 className="text-2xl md:text-4xl font-bold text-zinc-50 tracking-tighter leading-tight uppercase">
{bottle.name}
</h1>
<p className="text-sm md:text-xl text-orange-600 font-bold mt-1 uppercase tracking-widest">{bottle.distillery}</p>
{bottle.whiskybase_id && (
<div className="mt-4">
<a
href={`https://www.whiskybase.com/whiskies/whisky/${bottle.whiskybase_id}`}
target="_blank"
rel="noopener noreferrer"
className="inline-flex items-center gap-2 px-4 py-2 bg-zinc-900 text-zinc-400 border border-zinc-800 rounded-xl text-xs font-bold hover:text-orange-600 transition-colors"
{/* Segmented Control for Status */}
<div className="space-y-2">
<label className="text-[10px] font-bold uppercase text-zinc-600 ml-1">Status</label>
<div className="grid grid-cols-3 bg-zinc-950 p-1 rounded-2xl border border-zinc-800/50">
{['sealed', 'open', 'empty'].map((s) => (
<button
key={s}
disabled={isOffline}
onClick={() => handleQuickUpdate(undefined, s)}
className={`py-2.5 rounded-xl text-[10px] font-black uppercase tracking-widest transition-all ${status === s
? 'bg-orange-600 text-white shadow-lg'
: 'text-zinc-600 hover:text-zinc-400'
}`}
>
<ExternalLink size={14} />
Whiskybase ID: {bottle.whiskybase_id}
</a>
</div>
)}
{s === 'sealed' ? 'Sealed' : s === 'open' ? 'Open' : 'Empty'}
</button>
))}
</div>
</div>
<div className="grid grid-cols-2 md:grid-cols-3 gap-4">
<div className="p-4 bg-zinc-900 rounded-2xl border border-zinc-800 shadow-sm flex flex-col justify-between">
<div>
<div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
<Tag size={12} /> Kategorie
</div>
<div className="font-bold text-sm text-zinc-200">{bottle.category || '-'}</div>
</div>
</div>
<div className="p-4 bg-zinc-900 rounded-2xl border border-zinc-800 shadow-sm">
<div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
<Droplets size={12} /> Alkoholgehalt
</div>
<div className="font-bold text-sm text-zinc-200">{bottle.abv}% Vol.</div>
</div>
<div className="p-4 bg-zinc-900 rounded-2xl border border-zinc-800 shadow-sm">
<div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
<Award size={12} /> Alter
</div>
<div className="font-bold text-sm text-zinc-200">{bottle.age ? `${bottle.age} J.` : '-'}</div>
</div>
{bottle.distilled_at && (
<div className="p-4 bg-zinc-900 rounded-2xl border border-zinc-800 shadow-sm">
<div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
<Calendar size={12} /> Destilliert
</div>
<div className="font-bold text-sm text-zinc-200">{bottle.distilled_at}</div>
</div>
)}
{bottle.bottled_at && (
<div className="p-4 bg-zinc-900 rounded-2xl border border-zinc-800 shadow-sm">
<div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
<Package size={12} /> Abgefüllt
</div>
<div className="font-bold text-sm text-zinc-200">{bottle.bottled_at}</div>
</div>
)}
{/* Quick Collection Card */}
<div className="md:col-span-2 p-5 bg-orange-600/5 rounded-3xl border border-orange-600/20 shadow-xl space-y-4">
<div className="flex items-center justify-between">
<h3 className="text-[10px] font-black uppercase tracking-[0.2em] text-orange-600 flex items-center gap-2">
<Package size={14} /> Sammlungs-Status
</h3>
{isUpdating && <Loader2 size={12} className="animate-spin text-orange-600" />}
</div>
<div className="grid grid-cols-2 gap-4">
{/* Price */}
<div className="space-y-1.5">
<label className="text-[9px] font-bold uppercase text-zinc-500 ml-1">Einkaufspreis</label>
<div className="relative">
<input
type="number"
step="0.01"
value={price}
onChange={(e) => setPrice(e.target.value)}
onBlur={() => handleQuickUpdate(price)}
placeholder="0.00"
className="w-full bg-zinc-950 border border-zinc-800 rounded-xl pl-3 pr-8 py-2 text-sm font-bold text-orange-500 focus:outline-none focus:border-orange-600 transition-all"
/>
<div className="absolute right-3 top-1/2 -translate-y-1/2 text-[10px] font-bold text-zinc-700"></div>
</div>
</div>
{/* Status */}
<div className="space-y-1.5">
<label className="text-[9px] font-bold uppercase text-zinc-500 ml-1">Flaschenstatus</label>
<select
value={status}
onChange={(e) => {
setStatus(e.target.value);
handleQuickUpdate(undefined, e.target.value);
}}
className="w-full bg-zinc-950 border border-zinc-800 rounded-xl px-3 py-2 text-sm font-bold text-zinc-200 focus:outline-none focus:border-orange-600 appearance-none transition-all"
>
<option value="sealed">Versiegelt</option>
<option value="open">Offen</option>
<option value="sampled">Sample</option>
<option value="empty">Leer</option>
</select>
</div>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<label className="text-[10px] font-bold uppercase text-zinc-600 ml-1">Price</label>
<div className="relative">
<input
type="number"
inputMode="decimal"
step="0.01"
value={price}
onChange={(e) => setPrice(e.target.value)}
onBlur={() => handleQuickUpdate(price)}
placeholder="0.00"
className="w-full bg-zinc-950 border border-zinc-800 rounded-2xl pl-4 pr-8 py-3 text-sm font-bold text-zinc-100 focus:outline-none focus:border-orange-600"
/>
<div className="absolute right-4 top-1/2 -translate-y-1/2 text-[10px] font-bold text-zinc-700"></div>
</div>
</div>
{bottle.batch_info && (
<div className="p-4 bg-zinc-800/30 rounded-2xl border border-dashed border-zinc-700/50 md:col-span-1">
<div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
<Info size={12} /> Batch / Code
</div>
<div className="font-mono text-xs text-zinc-300 truncate" title={bottle.batch_info}>{bottle.batch_info}</div>
</div>
)}
<div className="p-4 bg-zinc-900 rounded-2xl border border-zinc-800 shadow-sm">
<div className="flex items-center gap-2 text-zinc-500 text-[10px] font-bold uppercase mb-1">
<Calendar size={12} /> Letzter Dram
</div>
<div className="font-bold text-sm text-zinc-200">
<div className="space-y-2">
<label className="text-[10px] font-bold uppercase text-zinc-600 ml-1">Last Dram</label>
<div className="w-full bg-zinc-950 border border-zinc-800 rounded-2xl px-4 py-3 text-sm font-bold text-zinc-400 flex items-center gap-2">
<Calendar size={14} className="text-zinc-700" />
{tastings && tastings.length > 0
? new Date(tastings[0].created_at).toLocaleDateString('de-DE')
: 'Noch nie'}
? new Date(tastings[0].created_at).toLocaleDateString(locale === 'de' ? 'de-DE' : 'en-US', { day: '2-digit', month: '2-digit' })
: '-'}
</div>
</div>
</div>
<div className="pt-2 flex flex-wrap gap-4">
{isOffline ? (
<div className="w-full p-4 bg-zinc-900 border border-dashed border-zinc-800 rounded-2xl flex items-center justify-center gap-2">
<Info size={14} className="text-zinc-500" />
<span className="text-[10px] font-bold uppercase text-zinc-500 tracking-widest">Bearbeiten & Löschen nur online möglich</span>
</div>
) : (
<>
<EditBottleForm bottle={bottle as any} />
<Link
href={`/splits/create?bottle=${bottle.id}`}
className="px-5 py-3 bg-zinc-800 hover:bg-zinc-700 text-white rounded-2xl text-xs font-black uppercase tracking-widest flex items-center gap-2 transition-all border border-zinc-700 hover:border-orange-600/50"
>
<Share2 size={16} className="text-orange-500" />
Split starten
</Link>
<DeleteBottleButton bottleId={bottle.id} />
</>
)}
</div>
</div>
</section>
{/* 5. Editing Form (Accordion) */}
<section>
<button
onClick={() => setIsFormVisible(!isFormVisible)}
className="w-full px-6 py-4 bg-zinc-900/50 border border-zinc-800/80 rounded-2xl flex items-center justify-between text-zinc-400 hover:text-orange-500 transition-all group"
>
<div className="flex items-center gap-3">
<Circle size={14} className={isFormVisible ? 'text-orange-600 fill-orange-600' : 'text-zinc-700'} />
<span className="text-xs font-black uppercase tracking-widest">Details korrigieren</span>
</div>
<ChevronDown size={18} className={`transition-transform duration-300 ${isFormVisible ? 'rotate-180 text-orange-600' : ''}`} />
</button>
<AnimatePresence>
{isFormVisible && (
<motion.div
initial={{ opacity: 0, height: 0 }}
animate={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.3, ease: 'circOut' }}
className="overflow-hidden"
>
<div className="pt-4 px-2">
<EditBottleForm
bottle={bottle as any}
onComplete={() => setIsFormVisible(false)}
/>
</div>
</motion.div>
)}
</AnimatePresence>
{!isOffline && (
<div className="flex gap-2 pt-6">
<Link
href={`/splits/create?bottle=${bottle.id}`}
className="flex-1 py-4 bg-zinc-900 hover:bg-zinc-800 text-white rounded-2xl text-[10px] font-black uppercase tracking-[0.2em] flex items-center justify-center gap-2 border border-zinc-800 transition-all"
>
<Share2 size={14} className="text-orange-500" />
Split starten
</Link>
<div className="flex-none">
<DeleteBottleButton bottleId={bottle.id} />
</div>
</div>
)}
</section>
<hr className="border-zinc-800" />
{/* Tasting Notes Section */}

View File

@@ -102,188 +102,189 @@ export default function EditBottleForm({ bottle, onComplete }: EditBottleFormPro
}
};
if (!isEditing) {
return (
<div className="flex flex-col gap-2">
<button
onClick={() => setIsEditing(true)}
className="flex items-center gap-2 px-4 py-2 bg-zinc-800 hover:bg-zinc-700 text-zinc-400 rounded-xl text-sm font-bold transition-all w-fit border border-zinc-700"
>
<Edit2 size={16} />
{t('bottle.editDetails')}
</button>
{bottle.purchase_price && (
<div className="flex items-center gap-2 px-4 py-2 bg-green-900/10 text-green-400 rounded-xl text-sm font-bold border border-green-900/30 w-fit">
<CircleDollarSign size={16} />
{t('bottle.priceLabel')}: {parseFloat(bottle.purchase_price.toString()).toLocaleString(locale === 'de' ? 'de-DE' : 'en-US', { style: 'currency', currency: 'EUR' })}
</div>
)}
</div>
);
}
return (
<div className="p-6 bg-zinc-900 border border-orange-500/20 rounded-3xl shadow-2xl space-y-4 animate-in zoom-in-95 duration-200">
<div className="flex justify-between items-center mb-2">
<h3 className="text-lg font-black text-orange-600 uppercase tracking-widest flex items-center gap-2">
<Info size={18} /> {t('bottle.editTitle')}
</h3>
<button
onClick={() => setIsEditing(false)}
className="text-zinc-400 hover:text-zinc-600 p-1"
>
<X size={20} />
</button>
</div>
<div className="space-y-6 animate-in fade-in slide-in-from-top-4 duration-300">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="space-y-1">
<label className="text-[10px] font-black uppercase text-zinc-400 ml-1">{t('bottle.nameLabel')}</label>
{/* Full Width Inputs */}
<div className="space-y-1.5 md:col-span-2">
<label className="text-[10px] font-black uppercase text-zinc-500 ml-1">{t('bottle.nameLabel')}</label>
<input
type="text"
value={formData.name}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200"
className="w-full px-4 py-3 bg-zinc-950 border border-zinc-800 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200 text-sm font-bold"
/>
</div>
<div className="space-y-1">
<label className="text-[10px] font-black uppercase text-zinc-400 ml-1">{t('bottle.distilleryLabel')}</label>
<div className="space-y-1.5 md:col-span-2">
<label className="text-[10px] font-black uppercase text-zinc-500 ml-1">{t('bottle.distilleryLabel')}</label>
<input
type="text"
value={formData.distillery}
onChange={(e) => setFormData({ ...formData, distillery: e.target.value })}
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200"
className="w-full px-4 py-3 bg-zinc-950 border border-zinc-800 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200 text-sm font-bold"
/>
</div>
<div className="space-y-1">
<label className="text-[10px] font-black uppercase text-zinc-400 ml-1">{t('bottle.categoryLabel')}</label>
{/* Compact Row: Category */}
<div className="space-y-1.5">
<label className="text-[10px] font-black uppercase text-zinc-500 ml-1">{t('bottle.categoryLabel')}</label>
<input
type="text"
value={formData.category}
onChange={(e) => setFormData({ ...formData, category: e.target.value })}
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200"
className="w-full px-4 py-3 bg-zinc-950 border border-zinc-800 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200 text-sm font-bold"
/>
</div>
<div className="grid grid-cols-2 gap-2">
<div className="space-y-1">
<label className="text-[10px] font-black uppercase text-zinc-400 ml-1">{t('bottle.abvLabel')}</label>
{/* Row A: ABV + Age */}
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<label className="text-[10px] font-black uppercase text-zinc-500 ml-1">{t('bottle.abvLabel')}</label>
<input
type="number"
inputMode="decimal"
step="0.1"
value={formData.abv}
onChange={(e) => setFormData({ ...formData, abv: parseFloat(e.target.value) })}
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200"
className="w-full px-4 py-3 bg-zinc-950 border border-zinc-800 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200 text-sm font-bold"
/>
</div>
<div className="space-y-1">
<label className="text-[10px] font-black uppercase text-zinc-400 ml-1">{t('bottle.ageLabel')}</label>
<div className="space-y-1.5">
<label className="text-[10px] font-black uppercase text-zinc-500 ml-1">{t('bottle.ageLabel')}</label>
<input
type="number"
inputMode="numeric"
value={formData.age}
onChange={(e) => setFormData({ ...formData, age: parseInt(e.target.value) })}
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200"
className="w-full px-4 py-3 bg-zinc-950 border border-zinc-800 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200 text-sm font-bold"
/>
</div>
</div>
<div className="space-y-1">
<label className="text-[10px] font-black uppercase text-zinc-400 ml-1 flex justify-between items-center">
{/* Row B: Distilled + Bottled */}
<div className="grid grid-cols-2 gap-3">
<div className="space-y-1.5">
<label className="text-[10px] font-black uppercase text-zinc-500 ml-1">{t('bottle.distilledLabel')}</label>
<input
type="text"
inputMode="numeric"
placeholder="YYYY"
value={formData.distilled_at}
onChange={(e) => setFormData({ ...formData, distilled_at: e.target.value })}
className="w-full px-4 py-3 bg-zinc-950 border border-zinc-800 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200 text-sm font-bold"
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black uppercase text-zinc-500 ml-1">{t('bottle.bottledLabel')}</label>
<input
type="text"
inputMode="numeric"
placeholder="YYYY"
value={formData.bottled_at}
onChange={(e) => setFormData({ ...formData, bottled_at: e.target.value })}
className="w-full px-4 py-3 bg-zinc-950 border border-zinc-800 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200 text-sm font-bold"
/>
</div>
</div>
{/* Price and WB ID Row */}
<div className="space-y-1.5">
<label className="text-[10px] font-black uppercase text-zinc-500 ml-1">{t('bottle.priceLabel')} ()</label>
<input
type="number"
inputMode="decimal"
step="0.01"
placeholder="0.00"
value={formData.purchase_price}
onChange={(e) => setFormData({ ...formData, purchase_price: e.target.value })}
className="w-full px-4 py-3 bg-zinc-950 border border-zinc-800 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 font-bold text-orange-500 text-sm"
/>
</div>
<div className="space-y-1.5">
<label className="text-[10px] font-black uppercase text-zinc-500 ml-1 flex justify-between items-center">
<span>Whiskybase ID</span>
<button
type="button"
onClick={handleDiscover}
disabled={isSearching}
className="text-orange-600 hover:text-orange-700 flex items-center gap-1 normal-case font-bold"
className="text-orange-600 hover:text-orange-700 flex items-center gap-1 normal-case font-bold text-[10px]"
>
{isSearching ? <Loader2 size={10} className="animate-spin" /> : <Search size={10} />}
{t('bottle.autoSearch')}
</button>
</label>
<input
type="text"
value={formData.whiskybase_id}
onChange={(e) => setFormData({ ...formData, whiskybase_id: e.target.value })}
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200"
/>
{discoveryResult && (
<div className="mt-2 p-3 bg-zinc-950 border border-orange-500/20 rounded-xl animate-in fade-in slide-in-from-top-2">
<p className="text-[10px] text-zinc-500 mb-2">Treffer gefunden:</p>
<p className="text-[11px] font-bold text-zinc-200 mb-2 truncate">{discoveryResult.title}</p>
<div className="flex gap-2">
<button
type="button"
onClick={applyDiscovery}
className="px-3 py-1.5 bg-orange-600 text-white text-[10px] font-black uppercase rounded-lg hover:bg-orange-700 transition-colors"
>
{t('bottle.applyId')}
</button>
<a
href={discoveryResult.url}
target="_blank"
rel="noopener noreferrer"
className="px-3 py-1.5 bg-zinc-800 text-zinc-400 text-[10px] font-black uppercase rounded-lg hover:bg-zinc-700 transition-colors flex items-center gap-1 border border-zinc-700"
>
<ExternalLink size={10} /> {t('common.check')}
</a>
<div className="relative">
<input
type="text"
inputMode="numeric"
value={formData.whiskybase_id}
onChange={(e) => setFormData({ ...formData, whiskybase_id: e.target.value })}
className="w-full px-4 py-3 bg-zinc-950 border border-zinc-800 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200 text-sm font-mono"
/>
{discoveryResult && (
<div className="absolute top-full left-0 right-0 z-50 mt-2 p-3 bg-zinc-900 border border-orange-500/30 rounded-2xl shadow-2xl animate-in zoom-in-95">
<p className="text-[10px] text-zinc-500 mb-1">Empfehlung:</p>
<p className="text-[11px] font-bold text-zinc-200 mb-2 truncate">{discoveryResult.title}</p>
<div className="flex gap-2">
<button
type="button"
onClick={applyDiscovery}
className="flex-1 py-2 bg-orange-600 text-white text-[10px] font-black uppercase rounded-xl"
>
ID übernehmen
</button>
<a
href={discoveryResult.url}
target="_blank"
rel="noopener noreferrer"
className="px-3 py-2 bg-zinc-800 text-zinc-400 rounded-xl flex items-center justify-center border border-zinc-700"
>
<ExternalLink size={12} />
</a>
</div>
</div>
</div>
)}
</div>
<div className="space-y-1">
<label className="text-[10px] font-black uppercase text-zinc-400 ml-1">{t('bottle.priceLabel')} ()</label>
<input
type="number"
step="0.01"
placeholder="0.00"
value={formData.purchase_price}
onChange={(e) => setFormData({ ...formData, purchase_price: e.target.value })}
className="w-full px-4 py-2 bg-zinc-950 border border-zinc-800 rounded-xl outline-none focus:ring-2 focus:ring-orange-600/50 font-bold text-zinc-100"
/>
)}
</div>
</div>
<div className="space-y-1">
<label className="text-[10px] font-black uppercase text-zinc-400 ml-1">{t('bottle.distilledLabel')}</label>
<input
type="text"
placeholder="z.B. 2010"
value={formData.distilled_at}
onChange={(e) => setFormData({ ...formData, distilled_at: e.target.value })}
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200"
/>
</div>
<div className="space-y-1">
<label className="text-[10px] font-black uppercase text-zinc-400 ml-1">{t('bottle.bottledLabel')}</label>
<input
type="text"
placeholder="z.B. 2022"
value={formData.bottled_at}
onChange={(e) => setFormData({ ...formData, bottled_at: e.target.value })}
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200"
/>
</div>
<div className="space-y-1 md:col-span-2">
<label className="text-[10px] font-black uppercase text-zinc-400 ml-1">{t('bottle.batchLabel')}</label>
{/* Batch Info */}
<div className="space-y-1.5 md:col-span-2">
<label className="text-[10px] font-black uppercase text-zinc-500 ml-1">{t('bottle.batchLabel')}</label>
<input
type="text"
placeholder="z.B. Batch 12 oder L-Code"
value={formData.batch_info}
onChange={(e) => setFormData({ ...formData, batch_info: e.target.value })}
className="w-full px-4 py-2 bg-zinc-800 border border-zinc-700 rounded-xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200"
className="w-full px-4 py-3 bg-zinc-950 border border-zinc-800 rounded-2xl outline-none focus:ring-2 focus:ring-orange-600/50 text-zinc-200 text-sm font-bold"
/>
</div>
</div>
{error && <p className="text-red-500 text-xs italic">{error}</p>}
{error && (
<div className="p-3 bg-red-500/10 border border-red-500/20 rounded-xl flex items-center gap-2 text-red-500 text-[10px] font-bold">
<Info size={14} />
{error}
</div>
)}
<button
onClick={handleSave}
disabled={isSaving}
className="w-full py-4 bg-orange-600 hover:bg-orange-700 text-white rounded-2xl font-black uppercase tracking-widest transition-all flex items-center justify-center gap-2 shadow-xl shadow-orange-950/20 disabled:opacity-50"
>
{isSaving ? <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div> : <Save size={20} />}
{t('bottle.saveChanges')}
</button>
<div className="flex gap-3 pt-2">
<button
onClick={() => onComplete?.()}
className="flex-1 py-4 bg-zinc-800 hover:bg-zinc-700 text-zinc-400 rounded-2xl font-black uppercase tracking-widest text-xs transition-all"
>
{t('common.cancel')}
</button>
<button
onClick={handleSave}
disabled={isSaving}
className="flex-[2] py-4 bg-orange-600 hover:bg-orange-700 text-white rounded-2xl font-black uppercase tracking-widest text-xs transition-all flex items-center justify-center gap-2 shadow-xl shadow-orange-950/20 disabled:opacity-50"
>
{isSaving ? <Loader2 size={16} className="animate-spin" /> : <Save size={16} />}
{t('bottle.saveChanges')}
</button>
</div>
</div>
);
}

View File

@@ -107,10 +107,29 @@ export async function updateUserCredits(
const isAdmin = await checkIsAdmin(user.id);
if (!isAdmin) return { success: false, error: 'Not authorized' };
// Get current credits
const currentCredits = await getUserCredits(validated.userId);
// Get current credits - if not found, create entry first
let currentCredits = await getUserCredits(validated.userId);
if (!currentCredits) {
return { success: false, error: 'User credits not found' };
// Create credits entry for user who doesn't have one
console.log(`[updateUserCredits] Creating credits entry for user ${validated.userId}`);
const { data: newCredits, error: insertError } = await supabase
.from('user_credits')
.insert({
user_id: validated.userId,
balance: 0,
total_purchased: 0,
total_used: 0
})
.select()
.single();
if (insertError) {
console.error('Error creating user credits:', insertError);
return { success: false, error: 'Failed to create user credits' };
}
currentCredits = newCredits;
}
const difference = validated.newBalance - currentCredits.balance;

View File

@@ -21,7 +21,7 @@ BEGIN
ON CONFLICT (id) DO NOTHING;
RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = '';
-- Manual sync for existing users (Run this once)
-- INSERT INTO public.profiles (id)

View File

@@ -41,7 +41,7 @@ EXCEPTION WHEN OTHERS THEN
RAISE WARNING 'handle_new_user failed: %', SQLERRM;
RETURN new;
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;
$$ LANGUAGE plpgsql SECURITY DEFINER SET search_path = '';
-- RLS Policy for user_subscriptions insert (for client-side fallback)
DO $$