diff --git a/scripts/db/migrations/004_ai_inventory_system.sql b/scripts/db/migrations/004_ai_inventory_system.sql new file mode 100644 index 000000000..d3bfc8d49 --- /dev/null +++ b/scripts/db/migrations/004_ai_inventory_system.sql @@ -0,0 +1,402 @@ +-- Migration: 004_ai_inventory_system +-- Description: AI-powered inventory management system with automated data extraction + +-- ============================================================================ +-- AI PRODUCT EXTRACTION SYSTEM +-- ============================================================================ + +-- Create table for AI-extracted product data +CREATE TABLE IF NOT EXISTS ai_extracted_products ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + original_image_url TEXT, + extracted_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + + -- Basic product information + product_name TEXT, + product_name_confidence DECIMAL(3,2) CHECK (product_name_confidence >= 0 AND product_name_confidence <= 1), + brand TEXT, + brand_confidence DECIMAL(3,2) CHECK (brand_confidence >= 0 AND brand_confidence <= 1), + model TEXT, + model_confidence DECIMAL(3,2) CHECK (model_confidence >= 0 AND model_confidence <= 1), + + -- Categorization + category TEXT, + category_confidence DECIMAL(3,2) CHECK (category_confidence >= 0 AND category_confidence <= 1), + subcategory TEXT, + subcategory_confidence DECIMAL(3,2) CHECK (subcategory_confidence >= 0 AND subcategory_confidence <= 1), + + -- Pricing and condition + estimated_price_chf DECIMAL(10,2), + price_confidence DECIMAL(3,2) CHECK (price_confidence >= 0 AND price_confidence <= 1), + condition TEXT CHECK (condition IN ('new', 'like_new', 'good', 'fair', 'poor', 'damaged')), + condition_confidence DECIMAL(3,2) CHECK (condition_confidence >= 0 AND condition_confidence <= 1), + + -- Technical specifications + specifications JSONB DEFAULT '{}', + specs_confidence DECIMAL(3,2) CHECK (specs_confidence >= 0 AND specs_confidence <= 1), + + -- Additional metadata + color TEXT, + color_confidence DECIMAL(3,2) CHECK (color_confidence >= 0 AND color_confidence <= 1), + material TEXT, + material_confidence DECIMAL(3,2) CHECK (material_confidence >= 0 AND material_confidence <= 1), + dimensions JSONB DEFAULT '{}', -- {width: 10, height: 20, depth: 5, unit: 'cm'} + weight_grams INTEGER, + weight_confidence DECIMAL(3,2) CHECK (weight_confidence >= 0 AND weight_confidence <= 1), + + -- AI processing metadata + ai_provider TEXT DEFAULT 'openai', -- 'openai', 'anthropic', 'google', etc. + ai_model TEXT DEFAULT 'gpt-4-vision-preview', + processing_time_ms INTEGER, + total_confidence DECIMAL(3,2) CHECK (total_confidence >= 0 AND total_confidence <= 1), + + -- Raw AI response for debugging/analysis + raw_ai_response JSONB DEFAULT '{}', + + -- User and processing status + created_by UUID REFERENCES users(id), + status TEXT DEFAULT 'pending_review' CHECK (status IN ('pending_review', 'approved', 'rejected', 'processed')), + reviewed_by UUID REFERENCES users(id), + reviewed_at TIMESTAMP WITH TIME ZONE, + review_notes TEXT, + + -- Integration fields + kivitendo_article_number TEXT, + medusa_product_id TEXT, + marketplace_listing_id TEXT, + + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +-- ============================================================================ +-- SUSTAINABILITY SCORING SYSTEM +-- ============================================================================ + +-- Create sustainability scoring table +CREATE TABLE IF NOT EXISTS sustainability_scores ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + product_id UUID REFERENCES ai_extracted_products(id) ON DELETE CASCADE, + + -- Overall sustainability score (0-100) + overall_score INTEGER CHECK (overall_score >= 0 AND overall_score <= 100), + + -- Component scores + environmental_score INTEGER CHECK (environmental_score >= 0 AND environmental_score <= 100), + social_score INTEGER CHECK (social_score >= 0 AND social_score <= 100), + economic_score INTEGER CHECK (economic_score >= 0 AND economic_score <= 100), + + -- Detailed factors + factors JSONB DEFAULT '{}', -- {recyclability: 85, energy_efficiency: 70, fair_trade: 60, ...} + + -- AI analysis + ai_analysis JSONB DEFAULT '{}', + ai_provider TEXT DEFAULT 'openai', + ai_model TEXT, + + -- Recommendations + recommendations TEXT[], + improvement_suggestions TEXT[], + + -- Metadata + assessed_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + assessed_by TEXT DEFAULT 'ai', -- 'ai', 'expert', 'user' + + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +-- ============================================================================ +-- PRODUCT CATEGORIES AND ATTRIBUTES +-- ============================================================================ + +-- Enhanced product categories table +CREATE TABLE IF NOT EXISTS product_categories ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + slug VARCHAR(100) NOT NULL UNIQUE, + name VARCHAR(150) NOT NULL, + description TEXT, + parent_id UUID REFERENCES product_categories(id), + level INTEGER DEFAULT 1, -- 1 = main category, 2 = subcategory, etc. + + -- Display and SEO + icon TEXT, + color VARCHAR(7), -- hex color + seo_title TEXT, + seo_description TEXT, + + -- Metadata + is_active BOOLEAN DEFAULT true, + sort_order INTEGER DEFAULT 0, + ai_detection_keywords TEXT[], -- Keywords for AI recognition + + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +-- Product attributes (for structured data) +CREATE TABLE IF NOT EXISTS product_attributes ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + category_id UUID REFERENCES product_categories(id), + name VARCHAR(100) NOT NULL, + display_name VARCHAR(150), + data_type VARCHAR(20) DEFAULT 'text' CHECK (data_type IN ('text', 'number', 'boolean', 'select', 'multiselect', 'date')), + unit VARCHAR(20), -- 'cm', 'kg', 'GB', etc. + is_required BOOLEAN DEFAULT false, + is_filterable BOOLEAN DEFAULT false, + options TEXT[] DEFAULT '{}', -- For select/multiselect types + + -- AI extraction + ai_extraction_prompt TEXT, + ai_confidence_threshold DECIMAL(3,2) DEFAULT 0.7, + + -- Display + sort_order INTEGER DEFAULT 0, + is_active BOOLEAN DEFAULT true, + + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + + UNIQUE(category_id, name) +); + +-- ============================================================================ +-- INVENTORY MANAGEMENT +-- ============================================================================ + +-- Inventory items table (links AI extraction to physical inventory) +CREATE TABLE IF NOT EXISTS inventory_items ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + ai_product_id UUID REFERENCES ai_extracted_products(id), + + -- Legacy system integration + kivitendo_article_number TEXT UNIQUE, + legacy_csv_data JSONB DEFAULT '{}', + + -- Physical inventory tracking + location TEXT, -- Warehouse location + quantity_available INTEGER DEFAULT 0, + quantity_reserved INTEGER DEFAULT 0, + quantity_sold INTEGER DEFAULT 0, + + -- Status tracking + status TEXT DEFAULT 'available' CHECK (status IN ('available', 'reserved', 'sold', 'damaged', 'missing')), + condition_override TEXT CHECK (condition_override IN ('new', 'like_new', 'good', 'fair', 'poor', 'damaged')), + condition_notes TEXT, + + -- Pricing + acquisition_cost_chf DECIMAL(10,2), + selling_price_chf DECIMAL(10,2), + min_selling_price_chf DECIMAL(10,2), + + -- Marketplace integration + medusa_product_id TEXT UNIQUE, + marketplace_status TEXT DEFAULT 'draft' CHECK (marketplace_status IN ('draft', 'published', 'sold', 'archived')), + + -- User assignments + assigned_to UUID REFERENCES users(id), -- Who is responsible for this item + assigned_at TIMESTAMP WITH TIME ZONE, + assignment_notes TEXT, + + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +-- ============================================================================ +-- PRODUCT IMAGES AND MEDIA +-- ============================================================================ + +-- Enhanced product images table +CREATE TABLE IF NOT EXISTS product_images ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + product_id UUID REFERENCES ai_extracted_products(id) ON DELETE CASCADE, + + -- File information + filename TEXT NOT NULL, + original_filename TEXT, + file_path TEXT NOT NULL, + file_size_bytes INTEGER, + mime_type TEXT, + + -- AI analysis + ai_description TEXT, + ai_tags TEXT[], + is_primary BOOLEAN DEFAULT false, + + -- Image metadata + width INTEGER, + height INTEGER, + dominant_colors TEXT[], -- ['#FF0000', '#00FF00', etc.] + image_quality DECIMAL(3,2), -- AI-assessed quality score + + -- Processing status + upload_status TEXT DEFAULT 'processing' CHECK (upload_status IN ('uploading', 'processing', 'ready', 'failed')), + processed_at TIMESTAMP WITH TIME ZONE, + + -- User and permissions + uploaded_by UUID REFERENCES users(id), + is_public BOOLEAN DEFAULT true, + + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +-- ============================================================================ +-- AI PROCESSING LOGS AND ANALYTICS +-- ============================================================================ + +-- AI processing logs for debugging and improvement +CREATE TABLE IF NOT EXISTS ai_processing_logs ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + product_id UUID REFERENCES ai_extracted_products(id), + + -- Request details + request_type TEXT NOT NULL, -- 'image_analysis', 'text_extraction', 'sustainability_scoring' + provider TEXT NOT NULL, + model TEXT NOT NULL, + input_data JSONB DEFAULT '{}', + + -- Response details + response_data JSONB DEFAULT '{}', + processing_time_ms INTEGER, + tokens_used INTEGER, + cost_cents DECIMAL(8,4), + + -- Quality metrics + confidence_score DECIMAL(3,2), + accuracy_rating DECIMAL(3,2), -- User-provided feedback + error_message TEXT, + + -- Metadata + user_id UUID REFERENCES users(id), + ip_address INET, + user_agent TEXT, + + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +-- ============================================================================ +-- MARKETPLACE INTEGRATION +-- ============================================================================ + +-- Marketplace listings table +CREATE TABLE IF NOT EXISTS marketplace_listings ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + inventory_item_id UUID REFERENCES inventory_items(id) ON DELETE CASCADE, + + -- Listing details + title TEXT NOT NULL, + description TEXT, + price_chf DECIMAL(10,2) NOT NULL, + + -- Platform integration + platform TEXT NOT NULL, -- 'medusa', 'external_api', etc. + platform_listing_id TEXT, + platform_url TEXT, + + -- Status and visibility + status TEXT DEFAULT 'draft' CHECK (status IN ('draft', 'published', 'sold', 'paused', 'expired')), + is_featured BOOLEAN DEFAULT false, + views_count INTEGER DEFAULT 0, + favorites_count INTEGER DEFAULT 0, + + -- Sales tracking + sold_at TIMESTAMP WITH TIME ZONE, + sold_price_chf DECIMAL(10,2), + buyer_info JSONB DEFAULT '{}', -- Anonymized buyer data + + -- Metadata + published_at TIMESTAMP WITH TIME ZONE, + expires_at TIMESTAMP WITH TIME ZONE, + created_by UUID REFERENCES users(id), + + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +-- ============================================================================ +-- INDEXES FOR PERFORMANCE +-- ============================================================================ + +-- AI extracted products indexes +CREATE INDEX IF NOT EXISTS idx_ai_products_status ON ai_extracted_products(status); +CREATE INDEX IF NOT EXISTS idx_ai_products_brand ON ai_extracted_products(brand); +CREATE INDEX IF NOT EXISTS idx_ai_products_category ON ai_extracted_products(category); +CREATE INDEX IF NOT EXISTS idx_ai_products_created_by ON ai_extracted_products(created_by); +CREATE INDEX IF NOT EXISTS idx_ai_products_kivitendo ON ai_extracted_products(kivitendo_article_number); + +-- Inventory items indexes +CREATE INDEX IF NOT EXISTS idx_inventory_status ON inventory_items(status); +CREATE INDEX IF NOT EXISTS idx_inventory_location ON inventory_items(location); +CREATE INDEX IF NOT EXISTS idx_inventory_kivitendo ON inventory_items(kivitendo_article_number); +CREATE INDEX IF NOT EXISTS idx_inventory_assigned_to ON inventory_items(assigned_to); + +-- Product categories indexes +CREATE INDEX IF NOT EXISTS idx_categories_parent ON product_categories(parent_id); +CREATE INDEX IF NOT EXISTS idx_categories_level ON product_categories(level); +CREATE INDEX IF NOT EXISTS idx_categories_active ON product_categories(is_active); + +-- Marketplace listings indexes +CREATE INDEX IF NOT EXISTS idx_listings_status ON marketplace_listings(status); +CREATE INDEX IF NOT EXISTS idx_listings_platform ON marketplace_listings(platform); +CREATE INDEX IF NOT EXISTS idx_listings_created_by ON marketplace_listings(created_by); + +-- ============================================================================ +-- UPDATED AT TRIGGERS +-- ============================================================================ + +-- Add updated_at triggers for new tables +DO $$ +DECLARE + tbl_name text; + trigger_name text; +BEGIN + -- List of tables that need updated_at triggers + FOR tbl_name IN + SELECT unnest(ARRAY[ + 'ai_extracted_products', 'sustainability_scores', 'product_categories', + 'product_attributes', 'inventory_items', 'product_images', + 'ai_processing_logs', 'marketplace_listings' + ]) + LOOP + trigger_name := 'update_' || tbl_name || '_updated_at'; + + IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = tbl_name) AND + EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = tbl_name AND column_name = 'updated_at') THEN + IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = trigger_name) THEN + EXECUTE format('CREATE TRIGGER %I BEFORE UPDATE ON %I FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();', trigger_name, tbl_name); + END IF; + END IF; + END LOOP; +END $$; + +-- ============================================================================ +-- DEFAULT DATA INSERTION +-- ============================================================================ + +-- Insert default product categories +INSERT INTO product_categories (slug, name, description, level, icon, color, ai_detection_keywords) VALUES + ('electronics', 'Elektronik', 'Computer, Smartphones, Tablets und Zubehör', 1, 'computer', '#3B82F6', ARRAY['computer', 'laptop', 'smartphone', 'tablet', 'elektronik', 'electronic']), + ('components', 'Computer-Komponenten', 'CPUs, RAM, Festplatten, Mainboards', 2, 'cpu', '#10B981', ARRAY['ram', 'cpu', 'motherboard', 'ssd', 'hdd', 'grafikkarte', 'graphics card']), + ('peripherals', 'Peripheriegeräte', 'Monitore, Tastaturen, Mäuse, Drucker', 2, 'monitor', '#F59E0B', ARRAY['monitor', 'keyboard', 'mouse', 'printer', 'tastatur', 'maus', 'bildschirm']), + ('networking', 'Netzwerk', 'Router, Switches, Netzwerkkarten', 2, 'wifi', '#8B5CF6', ARRAY['router', 'switch', 'network', 'netzwerk', 'wifi', 'ethernet']), + ('audio', 'Audio', 'Lautsprecher, Kopfhörer, Mikrofone', 2, 'headphones', '#EF4444', ARRAY['speaker', 'headphone', 'microphone', 'audio', 'lautsprecher', 'kopfhörer']), + ('office', 'Büroartikel', 'Büromaterial, Organisation, Büroelektronik', 1, 'briefcase', '#6B7280', ARRAY['office', 'büro', 'printer', 'scanner', 'kopierer']) +ON CONFLICT (slug) DO NOTHING; + +-- Insert default product attributes for electronics category +INSERT INTO product_attributes (category_id, name, display_name, data_type, unit, is_required, is_filterable, options, ai_extraction_prompt) VALUES + ((SELECT id FROM product_categories WHERE slug = 'electronics'), 'brand', 'Marke', 'text', NULL, true, true, '{}', 'Extract the brand/manufacturer name from the product image and text'), + ((SELECT id FROM product_categories WHERE slug = 'electronics'), 'model', 'Modell', 'text', NULL, false, true, '{}', 'Extract the model number or name from the product'), + ((SELECT id FROM product_categories WHERE slug = 'electronics'), 'color', 'Farbe', 'text', NULL, false, true, '{}', 'Identify the primary color of the product'), + ((SELECT id FROM product_categories WHERE slug = 'electronics'), 'condition', 'Zustand', 'select', NULL, true, true, ARRAY['new', 'like_new', 'good', 'fair', 'poor'], 'Assess the physical condition of the product'), + ((SELECT id FROM product_categories WHERE slug = 'electronics'), 'weight_grams', 'Gewicht', 'number', 'g', false, false, '{}', 'Estimate the weight of the product in grams') +ON CONFLICT (category_id, name) DO NOTHING; + +-- Insert attributes for computer components +INSERT INTO product_attributes (category_id, name, display_name, data_type, unit, is_required, is_filterable, ai_extraction_prompt) VALUES + ((SELECT id FROM product_categories WHERE slug = 'components'), 'capacity', 'Kapazität', 'number', 'GB', false, true, 'Extract storage capacity for drives or memory size for RAM'), + ((SELECT id FROM product_categories WHERE slug = 'components'), 'speed', 'Geschwindigkeit', 'text', NULL, false, true, 'Extract speed specifications (MHz, GHz, etc.)'), + ((SELECT id FROM product_categories WHERE slug = 'components'), 'interface', 'Schnittstelle', 'text', NULL, false, true, 'Extract interface type (SATA, PCIe, DDR4, etc.)'), + ((SELECT id FROM product_categories WHERE slug = 'components'), 'form_factor', 'Formfaktor', 'text', NULL, false, false, 'Identify the physical form factor (2.5", DIMM, etc.)') +ON CONFLICT (category_id, name) DO NOTHING; \ No newline at end of file diff --git a/scripts/db/migrations/005_messaging_system.sql b/scripts/db/migrations/005_messaging_system.sql new file mode 100644 index 000000000..90d66caf1 --- /dev/null +++ b/scripts/db/migrations/005_messaging_system.sql @@ -0,0 +1,298 @@ +-- Migration: 005_messaging_system +-- Description: Real-time messaging system for buyer-seller and customer-repairer communication + +-- ============================================================================ +-- MESSAGING SYSTEM +-- ============================================================================ + +-- Conversations table - represents a conversation thread +CREATE TABLE IF NOT EXISTS conversations ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + title TEXT, -- Optional title for the conversation + type TEXT NOT NULL CHECK (type IN ('direct', 'appointment', 'marketplace', 'service')), + context_id TEXT, -- ID of related entity (appointment_id, marketplace_listing_id, etc.) + + -- Participants + participant_1 UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + participant_2 UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + + -- Metadata + last_message_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + last_message_preview TEXT, + unread_count_1 INTEGER DEFAULT 0, -- Unread messages for participant_1 + unread_count_2 INTEGER DEFAULT 0, -- Unread messages for participant_2 + + -- Status + is_active BOOLEAN DEFAULT true, + archived_by_1 BOOLEAN DEFAULT false, + archived_by_2 BOOLEAN DEFAULT false, + + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + + -- Ensure participants are different and ordered consistently + CONSTRAINT different_participants CHECK (participant_1 != participant_2), + CONSTRAINT ordered_participants CHECK (participant_1 < participant_2), + + UNIQUE(participant_1, participant_2, type, context_id) +); + +-- Messages table - individual messages within conversations +CREATE TABLE IF NOT EXISTS messages ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + conversation_id UUID NOT NULL REFERENCES conversations(id) ON DELETE CASCADE, + + sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + recipient_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + + content TEXT NOT NULL, + message_type TEXT DEFAULT 'text' CHECK (message_type IN ('text', 'image', 'file', 'system')), + + -- Attachments (optional) + attachment_url TEXT, + attachment_name TEXT, + attachment_size INTEGER, + + -- Status + is_read BOOLEAN DEFAULT false, + read_at TIMESTAMP WITH TIME ZONE, + + -- Delivery status + delivery_status TEXT DEFAULT 'sent' CHECK (delivery_status IN ('sent', 'delivered', 'read', 'failed')), + + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +-- Message reactions (optional feature) +CREATE TABLE IF NOT EXISTS message_reactions ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + message_id UUID NOT NULL REFERENCES messages(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + reaction TEXT NOT NULL, -- emoji or reaction type + + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + + UNIQUE(message_id, user_id, reaction) +); + +-- ============================================================================ +-- NOTIFICATION SYSTEM INTEGRATION +-- ============================================================================ + +-- Notification preferences for users +CREATE TABLE IF NOT EXISTS user_notification_preferences ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + + -- Email notifications + email_new_messages BOOLEAN DEFAULT true, + email_appointment_updates BOOLEAN DEFAULT true, + email_marketplace_updates BOOLEAN DEFAULT true, + + -- In-app notifications + in_app_messages BOOLEAN DEFAULT true, + in_app_appointments BOOLEAN DEFAULT true, + in_app_marketplace BOOLEAN DEFAULT true, + + -- SMS notifications (for urgent matters) + sms_urgent_messages BOOLEAN DEFAULT false, + sms_appointment_reminders BOOLEAN DEFAULT false, + + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + + UNIQUE(user_id) +); + +-- Notification history +CREATE TABLE IF NOT EXISTS notifications ( + id UUID PRIMARY KEY DEFAULT uuid_generate_v4(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + + type TEXT NOT NULL CHECK (type IN ('message', 'appointment', 'marketplace', 'system', 'marketing')), + title TEXT NOT NULL, + content TEXT NOT NULL, + + -- Related entity + related_type TEXT, -- 'conversation', 'appointment', 'marketplace_listing', etc. + related_id TEXT, + + -- Delivery methods + sent_email BOOLEAN DEFAULT false, + sent_sms BOOLEAN DEFAULT false, + sent_in_app BOOLEAN DEFAULT false, + + -- Status + is_read BOOLEAN DEFAULT false, + read_at TIMESTAMP WITH TIME ZONE, + + -- Scheduling (for delayed notifications) + scheduled_for TIMESTAMP WITH TIME ZONE, + + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +-- ============================================================================ +-- INDEXES FOR PERFORMANCE +-- ============================================================================ + +-- Conversation indexes +CREATE INDEX IF NOT EXISTS idx_conversations_participants ON conversations(participant_1, participant_2); +CREATE INDEX IF NOT EXISTS idx_conversations_type_context ON conversations(type, context_id); +CREATE INDEX IF NOT EXISTS idx_conversations_last_message ON conversations(last_message_at DESC); +CREATE INDEX IF NOT EXISTS idx_conversations_active ON conversations(is_active); + +-- Message indexes +CREATE INDEX IF NOT EXISTS idx_messages_conversation ON messages(conversation_id); +CREATE INDEX IF NOT EXISTS idx_messages_sender ON messages(sender_id); +CREATE INDEX IF NOT EXISTS idx_messages_recipient ON messages(recipient_id); +CREATE INDEX IF NOT EXISTS idx_messages_created ON messages(created_at DESC); +CREATE INDEX IF NOT EXISTS idx_messages_unread ON messages(recipient_id, is_read) WHERE is_read = false; + +-- Notification indexes +CREATE INDEX IF NOT EXISTS idx_notifications_user ON notifications(user_id); +CREATE INDEX IF NOT EXISTS idx_notifications_type ON notifications(type); +CREATE INDEX IF NOT EXISTS idx_notifications_read ON notifications(is_read); +CREATE INDEX IF NOT EXISTS idx_notifications_scheduled ON notifications(scheduled_for) WHERE scheduled_for IS NOT NULL; + +-- ============================================================================ +-- UPDATED AT TRIGGERS +-- ============================================================================ + +-- Add updated_at triggers for new tables +DO $$ +DECLARE + tbl_name text; + trigger_name text; +BEGIN + -- List of tables that need updated_at triggers + FOR tbl_name IN + SELECT unnest(ARRAY[ + 'conversations', 'messages', 'message_reactions', + 'user_notification_preferences', 'notifications' + ]) + LOOP + trigger_name := 'update_' || tbl_name || '_updated_at'; + + IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = tbl_name) AND + EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name = tbl_name AND column_name = 'updated_at') THEN + IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname = trigger_name) THEN + EXECUTE format('CREATE TRIGGER %I BEFORE UPDATE ON %I FOR EACH ROW EXECUTE FUNCTION update_updated_at_column();', trigger_name, tbl_name); + END IF; + END IF; + END LOOP; +END $$; + +-- ============================================================================ +-- DEFAULT NOTIFICATION PREFERENCES +-- ============================================================================ + +-- Insert default notification preferences for existing users +INSERT INTO user_notification_preferences ( + user_id, email_new_messages, email_appointment_updates, email_marketplace_updates, + in_app_messages, in_app_appointments, in_app_marketplace +) +SELECT + id, + true, true, true, -- email preferences + true, true, true -- in-app preferences +FROM users +ON CONFLICT (user_id) DO NOTHING; + +-- ============================================================================ +-- SYSTEM CONVERSATIONS FOR EXISTING APPOINTMENTS +-- ============================================================================ + +-- Create conversations for existing service appointments +INSERT INTO conversations ( + title, + type, + context_id, + participant_1, + participant_2, + last_message_at, + last_message_preview +) +SELECT + CONCAT('Service: ', st.name), + 'appointment', + sa.id::text, + -- Ensure consistent ordering of participants + CASE WHEN sa.user_id < '00000000-0000-0000-0000-000000000000'::uuid THEN sa.user_id ELSE '00000000-0000-0000-0000-000000000000'::uuid END, + CASE WHEN sa.user_id < '00000000-0000-0000-0000-000000000000'::uuid THEN '00000000-0000-0000-0000-000000000000'::uuid ELSE sa.user_id END, + sa.created_at, + COALESCE(sa.description, 'Neue Service-Anfrage') +FROM service_appointments sa +JOIN service_types st ON sa.service_type_id = st.id +-- Only create if participants are different (avoid self-conversations) +WHERE sa.user_id != '00000000-0000-0000-0000-000000000000'::uuid +ON CONFLICT (participant_1, participant_2, type, context_id) DO NOTHING; + +-- ============================================================================ +-- HELPER FUNCTIONS +-- ============================================================================ + +-- Function to update conversation metadata when a new message is added +CREATE OR REPLACE FUNCTION update_conversation_on_message() +RETURNS TRIGGER AS $$ +BEGIN + -- Update conversation's last message info + UPDATE conversations + SET + last_message_at = NEW.created_at, + last_message_preview = LEFT(NEW.content, 100), + -- Update unread counts + unread_count_1 = CASE + WHEN participant_1 = NEW.recipient_id THEN unread_count_1 + 1 + ELSE unread_count_1 + END, + unread_count_2 = CASE + WHEN participant_2 = NEW.recipient_id THEN unread_count_2 + 1 + ELSE unread_count_2 + END, + updated_at = CURRENT_TIMESTAMP + WHERE id = NEW.conversation_id; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- Trigger to automatically update conversation when messages are added +CREATE TRIGGER trigger_update_conversation_on_message + AFTER INSERT ON messages + FOR EACH ROW + EXECUTE FUNCTION update_conversation_on_message(); + +-- Function to reset unread count when messages are marked as read +CREATE OR REPLACE FUNCTION reset_unread_count() +RETURNS TRIGGER AS $$ +BEGIN + IF NEW.is_read = true AND OLD.is_read = false THEN + UPDATE conversations + SET + unread_count_1 = CASE + WHEN participant_1 = NEW.recipient_id THEN GREATEST(unread_count_1 - 1, 0) + ELSE unread_count_1 + END, + unread_count_2 = CASE + WHEN participant_2 = NEW.recipient_id THEN GREATEST(unread_count_2 - 1, 0) + ELSE unread_count_2 + END, + updated_at = CURRENT_TIMESTAMP + WHERE id = NEW.conversation_id; + END IF; + + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +-- Trigger to reset unread count when messages are read +CREATE TRIGGER trigger_reset_unread_count + AFTER UPDATE OF is_read ON messages + FOR EACH ROW + EXECUTE FUNCTION reset_unread_count(); + + + diff --git a/src/app/about/impact/content.tsx b/src/app/about/impact/content.tsx new file mode 100644 index 000000000..af3245060 --- /dev/null +++ b/src/app/about/impact/content.tsx @@ -0,0 +1,512 @@ +'use client' + +import { useState } from 'react' +import Image from 'next/image' +import { ResponsiveHero } from '@/components/layout/ResponsiveHero' +import AboutSubNav from '@/components/about/AboutSubNav' +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' +import { Button } from '@/components/ui/button' +import { IMPACT_METRICS, getEnvironmentalSummary, getSocialSummary, type ImpactMetric } from '@/data/impact-metrics' +import { getDefaultValue, getDefaultNumeric } from '@/lib/org-numbers.defaults' +// Simple Badge component replacement +const Badge = ({ children, className = "" }: { children: React.ReactNode, className?: string }) => ( + + {children} + +) + +// Simple Tabs replacement using state +const SimpleTabs = ({ + tabs, + defaultValue, + children +}: { + tabs: { value: string, label: string, icon?: React.ReactNode }[], + defaultValue: string, + children: (value: string) => React.ReactNode +}) => { + const [activeTab, setActiveTab] = useState(defaultValue) + + return ( +
+
+ {tabs.map((tab) => ( + + ))} +
+
+ {children(activeTab)} +
+
+ ) +} +import { + Heart, + Leaf, + Users, + TrendingUp, + Award, + Target, + CheckCircle, + ArrowRight, + Download, + Calendar, + MapPin +} from 'lucide-react' +import { + EWasteProblemSection, + ZeroWasteSolutionSection, + CommunitySpaceSection +} from '@/components/impact' + +interface DonationMethod { + id: string + name: string + description: string + amount?: string + icon: React.ReactNode + benefits: string[] + ctaText: string + popular?: boolean +} + +export default function ImpactPageContent() { + const [selectedDonationMethod, setSelectedDonationMethod] = useState(null) + const envSummary = getEnvironmentalSummary() + const socialSummary = getSocialSummary() + + const donationMethods: DonationMethod[] = [ + { + id: 'monthly', + name: 'Monatliche Spende', + description: 'Regelmässige Unterstützung für nachhaltige Wirkung', + amount: 'Ab CHF 20/Monat', + icon: , + benefits: [ + 'Kontinuierliche Finanzierung unserer Programme', + 'Planbare Ressourcen für langfristige Projekte', + 'Exklusive Updates über unsere Wirkung', + 'Einladungen zu besonderen Veranstaltungen' + ], + ctaText: 'Monatlich spenden', + popular: true + }, + { + id: 'one-time', + name: 'Einmalige Spende', + description: 'Direkte Unterstützung für spezifische Projekte', + amount: 'Frei wählbar', + icon: , + benefits: [ + 'Sofortige Wirkung für laufende Projekte', + 'Flexibilität bei der Spendenhöhe', + 'Spendenbescheinigung für Steuerzwecke', + 'Möglichkeit zur Projektbindung' + ], + ctaText: 'Jetzt spenden' + }, + { + id: 'corporate', + name: 'Unternehmenspartnerschaft', + description: 'Strategische Partnerschaft für nachhaltige IT', + amount: 'Ab CHF 5000/Jahr', + icon: , + benefits: [ + 'Nachhaltigkeitsbericht für Ihr Unternehmen', + 'Mitarbeiter-Workshops zu nachhaltiger IT', + 'Logo-Platzierung auf unserer Website', + 'Jährlicher Impact-Report' + ], + ctaText: 'Partner werden' + }, + { + id: 'equipment', + name: 'Geräte-Spende', + description: 'Spenden Sie funktionsfähige IT-Geräte', + icon: , + benefits: [ + 'Steuerliche Absetzbarkeit der Geräte', + 'Professionelle Datenlöschung garantiert', + 'Nachhaltigkeitszertifikat für Ihr Unternehmen', + 'Sichtbare Wirkung durch Geräte-Tracking' + ], + ctaText: 'Geräte spenden' + } + ] + + const getCategoryIcon = (category: ImpactMetric['category']) => { + switch (category) { + case 'environmental': return + case 'social': return + case 'economic': return + } + } + + const getCategoryColor = (category: ImpactMetric['category']) => { + switch (category) { + case 'environmental': return 'bg-green-50 border-green-200' + case 'social': return 'bg-blue-50 border-blue-200' + case 'economic': return 'bg-purple-50 border-purple-200' + } + } + + return ( +
+ {/* Hero Section */} + + + {/* Sub Navigation */} + + + {/* E-Waste Problem Section */} + + + {/* Zero-Waste Solution Section */} + + + {/* Community Space Section */} + + + {/* Impact Overview */} +
+
+

Warum Transparenz wichtig ist

+

+ Als gemeinnütziger Verein legen wir grössten Wert auf Transparenz. Jede unserer Zahlen ist nachvollziehbar dokumentiert, + damit Sie als Spender:in genau verstehen, wie Ihre Unterstützung wirkt. +

+
+ + {/* Key Metrics Cards */} +
+ {IMPACT_METRICS.map((metric) => ( + + +
+ {getCategoryIcon(metric.category)} + {metric.verified && ( + + + Verifiziert + + )} +
+ {metric.value} + {metric.title} +
+ +

{metric.description}

+
+ Methodik & Berechnung +

{metric.methodology}

+

Letzte Aktualisierung: {metric.lastUpdated}

+
+
+
+ ))} +
+ + {/* Impact Stories */} +
+

Wirkung in Zahlen verstehen

+ }, + { value: 'social', label: 'Sozial', icon: }, + { value: 'economic', label: 'Wirtschaftlich', icon: } + ]} + > + {(activeTab) => ( + <> + {activeTab === 'environmental' && ( +
+
+

Umweltwirkung im Detail

+
    +
  • + + Jedes gerettete Gerät spart durchschnittlich {envSummary.co2PerDevice}kg CO₂-Emissionen +
  • +
  • + + Wir vermeiden {envSummary.ewastePreventedTons.toFixed(1)} Tonnen Elektronikschrott pro Jahr +
  • +
  • + + {Math.round(envSummary.reuseRate * 100)}% unserer Geräte werden wiederverwendet statt recycelt +
  • +
+
+
+
Vergleich mit Neugeräten
+
+
+ Herstellung eines neuen Laptops: + {envSummary.co2ProductionKg}kg CO₂ +
+
+ Refurbishment eines Geräts: + {envSummary.co2RefurbishmentKg}kg CO₂ +
+
+ CO₂-Einsparung pro Gerät: + {envSummary.co2PerDevice}kg +
+
+
+
+ )} + + {activeTab === 'social' && ( +
+
+

Soziale Wirkung im Detail

+
    +
  • + + ~{Math.round(socialSummary.internshipSuccessRate * 100)}% unserer Praktikant:innen finden IT-Jobs oder Weiterbildung +
  • +
  • + + ~{socialSummary.careerReentries} berufliche Wiedereinstiege pro Jahr durch unser Programm +
  • +
  • + + {getDefaultValue('people_helped_total')} Menschen in nachhaltiger IT begleitet seit 2003 +
  • +
+
+
+
Erfolgsgeschichten
+
+

"Dank RevampIT habe ich nach 3 Jahren Arbeitslosigkeit wieder Fuss gefasst in der IT-Branche."

+

- Sarah M., ehemalige Praktikantin

+
+
+
+ )} + + {activeTab === 'economic' && ( +
+
+

Wirtschaftliche Wirkung

+
    +
  • + + Kunden sparen durchschnittlich CHF {getDefaultNumeric('customer_savings_chf')} pro repariertem Gerät +
  • +
  • + + KMU profitieren von günstigen Open Source-Lösungen +
  • +
  • + + {getDefaultValue('team_size_community')} sinnvolle Arbeitsplätze in der Schweiz +
  • +
+
+
+
Wirtschaftlicher Impact
+
+
+ Durchschnittliche Reparaturkosten: + CHF {getDefaultNumeric('avg_repair_cost_chf')} +
+
+ Neugerät-Preis (vergleichbar): + CHF {getDefaultNumeric('new_device_comparison_chf')} +
+
+ Einsparung pro Kunde: + CHF {getDefaultNumeric('customer_savings_chf')} +
+
+
+
+ )} + + )} +
+
+
+ + {/* Donation Methods */} +
+
+
+

Wie Sie uns unterstützen können

+

+ Jede Unterstützung zählt und trägt direkt zu unserer Mission bei. Wählen Sie die für Sie passende Art der Unterstützung. +

+
+ +
+ {donationMethods.map((method) => ( + setSelectedDonationMethod(method.id)} + > + +
+
+ {method.icon} + {method.name} +
+ {method.popular && ( + Beliebt + )} +
+ {method.description} + {method.amount && ( +

{method.amount}

+ )} +
+ +
    + {method.benefits.map((benefit, index) => ( +
  • + + {benefit} +
  • + ))} +
+ +
+
+ ))} +
+ + {/* Donation Impact Calculator */} + + + Ihre Spenden-Wirkung berechnen + + Sehen Sie sofort, welche Wirkung Ihre Spende haben kann + + + +
+
+

CHF {getDefaultNumeric('donation_impact_laptop_chf')}

+

Reparatur eines Laptops für eine Familie

+
+
+

CHF {getDefaultNumeric('donation_impact_internship_chf')}

+

Ein Monat Praktikumsstelle für Wiedereinsteiger:in

+
+
+

CHF {getDefaultNumeric('donation_impact_data_recovery_chf')}

+

Vollständige Datenrettung für KMU-Kunde

+
+
+
+
+
+
+ + {/* Transparency & Reports */} +
+
+

Transparenz & Berichterstattung

+

+ Wir berichten regelmässig über unsere Aktivitäten und Wirkung. Alle Dokumente sind öffentlich zugänglich. +

+
+ +
+ + + + + Jahresbericht 2023 + + + +

+ Vollständiger Tätigkeitsbericht mit allen Kennzahlen und Aktivitäten des Jahres 2023. +

+ +
+
+ + + + + + Wirkungsbericht + + + +

+ Detaillierte Analyse unserer sozialen und ökologischen Wirkung mit Methodik-Erläuterungen. +

+ +
+
+ + + + + + Transparenz-Register + + + +

+ Öffentliches Register aller Spenden und wie diese verwendet wurden. +

+ +
+
+
+
+ + {/* Call to Action */} +
+
+

Gemeinsam mehr erreichen

+

+ Ihre Unterstützung macht den Unterschied. Jeder Beitrag, ob gross oder klein, hilft uns dabei, + die Schweizer IT-Landschaft nachhaltiger zu gestalten und Menschen neue Chancen zu geben. +

+
+ + +
+
+
+
+ ) +} diff --git a/src/app/admin/layout.tsx b/src/app/admin/layout.tsx index a2d9bd12f..a3a97fe3b 100644 --- a/src/app/admin/layout.tsx +++ b/src/app/admin/layout.tsx @@ -9,9 +9,6 @@ import { redirect } from 'next/navigation' import { auth } from '@/auth' import { getAccessibleSections, isSuperAdmin, type AdminSection } from '@/lib/permissions' import { AdminLayoutClient } from './AdminLayoutClient' -import AppShell from '@/components/layout/AppShell' -import { NextIntlClientProvider } from 'next-intl' -import { getMessages, getLocale } from 'next-intl/server' export default async function AdminLayout({ children, @@ -43,24 +40,17 @@ export default async function AdminLayout({ redirect('/?error=no_admin_access') } - const messages = await getMessages() - const locale = await getLocale() - return ( - - - - {children} - - - + + {children} + ) } diff --git a/src/app/admin/services/page.tsx b/src/app/admin/services/page.tsx index 6ed882c5c..29fb9b1c0 100644 --- a/src/app/admin/services/page.tsx +++ b/src/app/admin/services/page.tsx @@ -10,16 +10,19 @@ import { auth } from '@/auth' import { redirect } from 'next/navigation' import { query } from '@/lib/auth/db' import { TABLE_NAMES } from '@/config/database' -import { REPAIRER_PROFILE_TIER } from '@/config/repairer-status' +import { CATEGORY_LABELS } from '@/config/service-categories' +import { formatPriceCents } from '@/config/marketplace' import { Plus, Wrench, Users, + Edit, + Eye, CheckCircle, + Star, + Calendar, } from 'lucide-react' import AdminPageWrapper from '@/components/admin/AdminPageWrapper' -import { ServiceListClient } from './ServiceListClient' -import Heading from '@/components/admin/AdminHeading' export const metadata: Metadata = { title: 'Dienstleistungen verwalten | RevampIT Admin', @@ -79,7 +82,7 @@ async function getServiceStats(): Promise { try { const techResult = await query<{ count: string }>( - `SELECT COUNT(*) as count FROM ${TABLE_NAMES.IT_HILFE_TECHNICIAN_PROFILES} WHERE is_active = true AND profile_tier = '${REPAIRER_PROFILE_TIER.COMMUNITY}'` + `SELECT COUNT(*) as count FROM ${TABLE_NAMES.IT_HILFE_TECHNICIAN_PROFILES} WHERE is_active = true` ) totalTechnicians = parseInt(techResult.rows[0]?.count || '0') } catch { @@ -107,6 +110,16 @@ async function getServices(): Promise { } } +const formatPrice = formatPriceCents + +function formatDuration(minutes: number | null): string { + if (minutes === null) return '-' + if (minutes < 60) return `${minutes} Min.` + const hours = Math.floor(minutes / 60) + const mins = minutes % 60 + if (mins === 0) return `${hours} Std.` + return `${hours} Std. ${mins} Min.` +} export default async function AdminServicesPage() { const session = await auth() @@ -123,7 +136,7 @@ export default async function AdminServicesPage() { return ( - {/* Services Table with Search/Filters */} - + {/* Services Table */} +
+ {services.length > 0 ? ( +
+ + + + + + + + + + + + {services.map((service) => ( + + + + + + + + ))} + +
+ Dienstleistung + + Kategorie + + Preis + + Flags + + Aktionen +
+
+
+ {service.name} +
+
+ /{service.slug} +
+
+
+ + {service.category ? CATEGORY_LABELS[service.category as keyof typeof CATEGORY_LABELS] || service.category : '-'} + + +
+ {formatPrice(service.price_cents)} +
+
+ {formatDuration(service.duration_minutes)} +
+
+
+ + {service.is_active ? 'Aktiv' : 'Inaktiv'} + + {service.is_featured && ( + + + + )} + {service.is_bookable && ( + + + + )} +
+
+
+ {service.is_featured && ( + + + + )} + + + +
+
+
+ ) : ( +
+ +

+ Noch keine Dienstleistungen +

+

+ Erstellen Sie Ihre erste Dienstleistung, um Service-Termine anzubieten. +

+ + + Erste Dienstleistung erstellen + +
+ )} +
- {/* Info Box */} + {/* Quick Actions */}
- +

Dienstleistungs-Verwaltung - -

- Dienstleistungen sind die Kernkompetenz von RevampIT. Biete Reparaturen, Installationen, +

+

+ Dienstleistungen sind die Kernkompetenz von RevampIT. Bieten Sie Reparaturen, Installationen, Beratungen und andere technische Services an. Kunden können online Termine buchen.

+
+ + Dienstleistung erstellen + +
diff --git a/src/app/ai-cms/page.tsx b/src/app/ai-cms/page.tsx new file mode 100644 index 000000000..f7345c0c4 --- /dev/null +++ b/src/app/ai-cms/page.tsx @@ -0,0 +1,32 @@ +import { Metadata } from 'next' +import { HeroSection } from './sections/HeroSection' +import { ProblemSection } from './sections/ProblemSection' +import { WorkflowSection } from './sections/WorkflowSection' +import { AccessControlSection } from './sections/AccessControlSection' +import { FeaturesSection } from './sections/FeaturesSection' +import { SuggestionTypesSection } from './sections/SuggestionTypesSection' +import { ComparisonSection } from './sections/ComparisonSection' +import { StatusSection } from './sections/StatusSection' +import { CTASection } from './sections/CTASection' + +export const metadata: Metadata = { + title: 'Kontextuelle Website-Verbesserungen | RevampIT', + description: 'Unser Verbesserungssystem ermöglicht es Nutzern, direkt auf jeder Seite Feedback zu geben. Eine moderne Alternative zu herkömmlichen Content-Management-Systemen.', + keywords: ['Website Feedback', 'Content Management', 'User Feedback', 'Website Verbesserung', 'Community-driven Development'], +} + +export default function AICMSPage() { + return ( +
+ + + + + + + + + +
+ ) +} diff --git a/src/app/ai-cms/sections/AccessControlSection.tsx b/src/app/ai-cms/sections/AccessControlSection.tsx new file mode 100644 index 000000000..f25dc797e --- /dev/null +++ b/src/app/ai-cms/sections/AccessControlSection.tsx @@ -0,0 +1,41 @@ +export function AccessControlSection() { + const roles = [ + { role: 'Alle Nutzer', can: ['Vorschläge einreichen', 'Eigene Vorschläge verfolgen'], color: 'blue' }, + { role: 'Registrierte Mitglieder', can: ['Vorschläge bewerten', 'Kommentare hinzufügen'], color: 'green' }, + { role: 'Redaktion / Staff', can: ['Alle Vorschläge verwalten', 'Status setzen', 'Änderungen umsetzen'], color: 'purple' }, + ] + + const colorMap: Record = { + blue: 'bg-blue-50 border-blue-100 text-blue-900', + green: 'bg-green-50 border-green-100 text-green-900', + purple: 'bg-purple-50 border-purple-100 text-purple-900', + } + + return ( +
+
+

+ Zugangskontrolle +

+

+ Das System funktioniert für alle — anonym oder eingeloggt. Mehr Rechte erhalten Mitglieder und Staff. +

+
+ {roles.map((r) => ( +
+

{r.role}

+
    + {r.can.map((item) => ( +
  • + ✓ + {item} +
  • + ))} +
+
+ ))} +
+
+
+ ) +} diff --git a/src/app/ai-cms/sections/CTASection.tsx b/src/app/ai-cms/sections/CTASection.tsx new file mode 100644 index 000000000..480cf2141 --- /dev/null +++ b/src/app/ai-cms/sections/CTASection.tsx @@ -0,0 +1,30 @@ +import Link from 'next/link' + +export function CTASection() { + return ( +
+
+

+ Machen Sie Ihre Website besser — gemeinsam +

+

+ Registrieren Sie sich kostenlos und helfen Sie mit, revamp-it.ch kontinuierlich zu verbessern. +

+
+ + Kostenlos registrieren + + + Kontakt aufnehmen + +
+
+
+ ) +} diff --git a/src/app/ai-cms/sections/ComparisonSection.tsx b/src/app/ai-cms/sections/ComparisonSection.tsx new file mode 100644 index 000000000..52fb23f21 --- /dev/null +++ b/src/app/ai-cms/sections/ComparisonSection.tsx @@ -0,0 +1,40 @@ +export function ComparisonSection() { + const rows = [ + { feature: 'Kontext beim Feedback', classic: '❌ Manuell', new: '✅ Automatisch (URL, Screenshot)' }, + { feature: 'Einreichung für Nutzer', classic: '❌ E-Mail / Formular', new: '✅ Direkt auf der Seite' }, + { feature: 'Redaktioneller Aufwand', classic: '❌ Hoch', new: '✅ Niedrig (KI-Gruppierung)' }, + { feature: 'Anonyme Einreichungen', classic: '✅ Möglich', new: '✅ Möglich' }, + { feature: 'Benachrichtigungen', classic: '❌ Manuell', new: '✅ Automatisch' }, + { feature: 'Datenschutz', classic: '✅ DSGVO-konform', new: '✅ DSGVO-konform' }, + ] + + return ( +
+
+

+ Klassisches CMS vs. Kontextuelles System +

+
+ + + + + + + + + + {rows.map((r, i) => ( + + + + + + ))} + +
FunktionKlassischUnser System
{r.feature}{r.classic}{r.new}
+
+
+
+ ) +} diff --git a/src/app/ai-cms/sections/FeaturesSection.tsx b/src/app/ai-cms/sections/FeaturesSection.tsx new file mode 100644 index 000000000..9172d3968 --- /dev/null +++ b/src/app/ai-cms/sections/FeaturesSection.tsx @@ -0,0 +1,29 @@ +export function FeaturesSection() { + const features = [ + { icon: '🗺️', title: 'Seitenkontext automatisch', description: 'URL, Screenshot und Seitentitel werden beim Einreichen automatisch erfasst.' }, + { icon: '🏷️', title: 'Kategorisierung', description: 'Vorschläge nach Typ: Fehler, Inhalt, Idee, Rechtschreibung, Barrierefreiheit.' }, + { icon: '🔔', title: 'Benachrichtigungen', description: 'Nutzer werden informiert, wenn ihr Vorschlag umgesetzt oder kommentiert wird.' }, + { icon: '🤖', title: 'KI-Zusammenfassung', description: 'Ähnliche Vorschläge werden automatisch gruppiert, um Duplikate zu reduzieren.' }, + { icon: '📊', title: 'Auswertung', description: 'Das Staff-Dashboard zeigt Trends und häufig gemeldete Bereiche.' }, + { icon: '🔒', title: 'Datenschutzkonform', description: 'Anonyme Einreichungen möglich — keine Pflichtangaben.' }, + ] + + return ( +
+
+

+ Funktionen +

+
+ {features.map((f) => ( +
+
{f.icon}
+

{f.title}

+

{f.description}

+
+ ))} +
+
+
+ ) +} diff --git a/src/app/ai-cms/sections/HeroSection.tsx b/src/app/ai-cms/sections/HeroSection.tsx new file mode 100644 index 000000000..e3cda076d --- /dev/null +++ b/src/app/ai-cms/sections/HeroSection.tsx @@ -0,0 +1,34 @@ +import Link from 'next/link' + +export function HeroSection() { + return ( +
+
+ + Kontextuelles Feedback-System + +

+ Website-Verbesserungen direkt auf der Seite +

+

+ Unser Verbesserungssystem ermöglicht es Nutzern, Feedback direkt auf jeder Seite zu geben — + ohne E-Mail, ohne Ticket, ohne Umwege. Eine moderne Alternative zu herkömmlichen CMS-Workflows. +

+
+ + Jetzt mitmachen + + + So funktioniert es + +
+
+
+ ) +} diff --git a/src/app/ai-cms/sections/ProblemSection.tsx b/src/app/ai-cms/sections/ProblemSection.tsx new file mode 100644 index 000000000..c8435484f --- /dev/null +++ b/src/app/ai-cms/sections/ProblemSection.tsx @@ -0,0 +1,38 @@ +export function ProblemSection() { + const problems = [ + { + title: 'Feedback geht verloren', + description: 'Nutzer finden einen Fehler, öffnen aber keine E-Mail. Der Fehler bleibt unbemerkt.', + }, + { + title: 'Fehlender Kontext', + description: 'Bug-Reports ohne Screenshot oder URL sind kaum verwertbar.', + }, + { + title: 'Langsame Redaktionszyklen', + description: 'Inhaltliche Änderungen brauchen Wochen, bis sie jemand einpflegt.', + }, + ] + + return ( +
+
+

+ Das Problem mit klassischem Feedback +

+

+ Traditionelle Rückmeldewege — E-Mail, Kontaktformular, Ticket-System — haben alle denselben + Nachteil: sie trennen Kontext vom Problem. +

+
+ {problems.map((p) => ( +
+

{p.title}

+

{p.description}

+
+ ))} +
+
+
+ ) +} diff --git a/src/app/ai-cms/sections/StatusSection.tsx b/src/app/ai-cms/sections/StatusSection.tsx new file mode 100644 index 000000000..0d41c3e76 --- /dev/null +++ b/src/app/ai-cms/sections/StatusSection.tsx @@ -0,0 +1,32 @@ +export function StatusSection() { + return ( +
+
+

+ Aktueller Status +

+
+ + In Entwicklung — Beta +
+

+ Das Verbesserungssystem wird schrittweise auf revamp-it.ch eingeführt. Zuerst auf ausgewählten + Seiten, dann auf der gesamten Plattform. +

+
+ {[ + { phase: 'Phase 1', label: 'Abgeschlossen', detail: 'Backend, Datenbank, Admin-Verwaltung', done: true }, + { phase: 'Phase 2', label: 'Aktiv', detail: 'Frontend-Widget auf ausgewählten Seiten', done: false }, + { phase: 'Phase 3', label: 'Geplant', detail: 'KI-Gruppierung, öffentliche Übersicht', done: false }, + ].map((p) => ( +
+
{p.phase}
+
{p.label}
+
{p.detail}
+
+ ))} +
+
+
+ ) +} diff --git a/src/app/ai-cms/sections/SuggestionTypesSection.tsx b/src/app/ai-cms/sections/SuggestionTypesSection.tsx new file mode 100644 index 000000000..f8b37a965 --- /dev/null +++ b/src/app/ai-cms/sections/SuggestionTypesSection.tsx @@ -0,0 +1,34 @@ +export function SuggestionTypesSection() { + const types = [ + { label: 'Fehler', emoji: '🐛', description: 'Etwas funktioniert nicht oder zeigt falsche Informationen an.' }, + { label: 'Inhalt', emoji: '✏️', description: 'Text ist veraltet, unvollständig oder missverständlich.' }, + { label: 'Idee', emoji: '💡', description: 'Neue Funktion oder Verbesserungsvorschlag.' }, + { label: 'Rechtschreibung', emoji: '🔤', description: 'Schreibfehler, Grammatik oder Formatierungsprobleme.' }, + { label: 'Barrierefreiheit', emoji: '♿', description: 'Problem mit Screenreader, Kontrast oder Tastaturnavigation.' }, + { label: 'Sonstiges', emoji: '📌', description: 'Allgemeines Feedback, das in keine Kategorie passt.' }, + ] + + return ( +
+
+

+ Arten von Vorschlägen +

+

+ Jede Einreichung wird einem Typ zugeordnet, damit das Team Prioritäten setzen kann. +

+
+ {types.map((t) => ( +
+ {t.emoji} +
+
{t.label}
+
{t.description}
+
+
+ ))} +
+
+
+ ) +} diff --git a/src/app/ai-cms/sections/WorkflowSection.tsx b/src/app/ai-cms/sections/WorkflowSection.tsx new file mode 100644 index 000000000..d34a6e1e4 --- /dev/null +++ b/src/app/ai-cms/sections/WorkflowSection.tsx @@ -0,0 +1,34 @@ +export function WorkflowSection() { + const steps = [ + { step: '1', title: 'Verbesserung entdecken', description: 'Nutzer klickt auf das Feedback-Symbol auf einer beliebigen Seite.' }, + { step: '2', title: 'Vorschlag einreichen', description: 'Kurze Beschreibung, Typ (Fehler, Inhalt, Idee) und Screenshot werden automatisch erfasst.' }, + { step: '3', title: 'Prüfung durch Redaktion', description: 'Das Team bewertet Vorschläge im Admin-Bereich und entscheidet über Umsetzung.' }, + { step: '4', title: 'Umsetzung & Bestätigung', description: 'Umgesetzte Vorschläge werden als erledigt markiert — der Einreichende erhält eine Benachrichtigung.' }, + ] + + return ( +
+
+

+ So funktioniert das System +

+
+
+
+ {steps.map((s) => ( +
+
+ {s.step} +
+
+

{s.title}

+

{s.description}

+
+
+ ))} +
+
+
+
+ ) +} diff --git a/src/app/dashboard/page.tsx b/src/app/dashboard/page.tsx index db038570d..c3cb3aa2a 100644 --- a/src/app/dashboard/page.tsx +++ b/src/app/dashboard/page.tsx @@ -2,209 +2,265 @@ import { Metadata } from 'next' import { auth } from '@/auth' import { redirect } from 'next/navigation' import Link from 'next/link' -import { AlertCircle } from 'lucide-react' -import { EmailVerificationBanner } from '@/components/dashboard/EmailVerificationBanner' -import { DashboardCard } from '@/components/dashboard/DashboardCard' -import { - getAllDashboardCards, - groupCardsByCategory, - DASHBOARD_CATEGORIES, -} from '@/config/dashboard' -import Heading from '@/components/ui/Heading' -import { query } from '@/lib/auth/db' -import { TABLE_NAMES } from '@/config/database' -import { BOOKING_STATUS } from '@/config/booking-status' -import { formatDate } from '@/lib/date-formats' -import { logger } from '@/lib/logger' -import { cn } from '@/lib/utils' +import { ROLES } from '@/lib/constants' +import { getCurrentUserRole } from '@/middleware/admin' import { getTextColor } from '@/lib/design-system' -import { getTranslations, getLocale } from 'next-intl/server' -import { ORG } from '@/config/org' +import { cn } from '@/lib/utils' +import { EmailVerificationBanner } from '@/components/dashboard/EmailVerificationBanner' +import { OnboardingChecklist } from '@/components/dashboard/OnboardingChecklist' +import { isStaffEmail } from '@/lib/permissions' -export async function generateMetadata(): Promise { - const locale = await getLocale() - const t = await getTranslations({ locale, namespace: 'dashboard.meta' }) - return { - title: `${t('dashboardTitle')} | ${ORG.name}`, - description: t('dashboardDesc'), - } -} - -interface MemberStatus { - isMember: boolean - memberSince: string | null - memberType: string | null -} - -interface ActivityCounts { - activeAppointments: number - pendingQuotes: number -} - - -async function getMemberStatus(userId: string): Promise { - try { - const result = await query<{ - is_member: boolean - member_since: string | null - member_type: string | null - }>( - `SELECT is_member, member_since, member_type - FROM ${TABLE_NAMES.USERS} - WHERE id = $1`, - [userId] - ) - const row = result.rows[0] - return { - isMember: row?.is_member ?? false, - memberSince: row?.member_since ?? null, - memberType: row?.member_type ?? null, - } - } catch (error) { - logger.error('Failed to fetch member status', { userId, error }) - return { isMember: false, memberSince: null, memberType: null } - } -} - -async function getActivityCounts(userId: string): Promise { - try { - const result = await query<{ - active_appointments: string - pending_quotes: string - }>( - `SELECT - COUNT(CASE WHEN status NOT IN ('${BOOKING_STATUS.COMPLETED}', '${BOOKING_STATUS.CANCELLED}', '${BOOKING_STATUS.REJECTED}') THEN 1 END) AS active_appointments, - COUNT(CASE WHEN status = '${BOOKING_STATUS.QUOTED}' THEN 1 END) AS pending_quotes - FROM ${TABLE_NAMES.SERVICE_APPOINTMENTS} - WHERE user_id = $1`, - [userId] - ) - return { - activeAppointments: parseInt(result.rows[0]?.active_appointments ?? '0', 10), - pendingQuotes: parseInt(result.rows[0]?.pending_quotes ?? '0', 10), - } - } catch (error) { - logger.error('Failed to fetch activity counts', { userId, error }) - return { activeAppointments: 0, pendingQuotes: 0 } - } +export const metadata: Metadata = { + title: 'Dashboard | RevampIT', + description: 'Verwalten Sie Ihr RevampIT-Konto, Workshops, Bestellungen und mehr.', } export default async function DashboardPage() { - const t = await getTranslations('dashboard.home') const session = await auth() if (!session?.user) { redirect('/auth/login?callbackUrl=/dashboard') } - const [memberStatus, counts] = await Promise.all([ - getMemberStatus(session.user.id!), - getActivityCounts(session.user.id!), - ]) - - const allCards = getAllDashboardCards({ - role: session.user.role ?? null, - isStaff: session.user.isStaff, - isSuperAdmin: false, - }) - - // Inject live count badges on relevant cards - const cardsWithBadges = allCards.map(card => { - if (card.id === 'appointments' && counts.activeAppointments > 0) - return { ...card, badge: t('activeBadge', { count: counts.activeAppointments }) } - if (card.id === 'bookings' && counts.activeAppointments > 0) - return { ...card, badge: t('activeBadge', { count: counts.activeAppointments }) } - return card - }) - - const grouped = groupCardsByCategory(cardsWithBadges) - - const userName = session.user.name || session.user.email || t('unknownUser') + const userRole = await getCurrentUserRole() return (
- {/* Email Verification Banner */} {!session.user.emailVerified && session.user.email && ( )} - {/* Header */} -
-
- - {t('welcomeBack', { name: userName })} - -

- {t('subtitle')} -

-
+ {/* Onboarding Checklist */} + - {/* Member status — inline badge, not full banner */} - {memberStatus.isMember ? ( -
- 🏅 - - {memberStatus.memberType === 'regular' ? t('memberTypeRegular') - : memberStatus.memberType === 'reduced' ? t('memberTypeReduced') - : memberStatus.memberType === 'honorary' ? t('memberTypeHonorary') - : t('memberFallback')} - {memberStatus.memberSince && ( - · {t('memberSince', { date: formatDate(memberStatus.memberSince) })} - )} - -
- ) : ( - - {t('becomeMember')} - - )} +
+

+ Willkommen zurück, {session.user.name || session.user.email}! +

+

+ Verwalten Sie Ihr Konto und entdecken Sie alle verfügbaren Funktionen. +

- {/* Pending quotes alert */} - {counts.pendingQuotes > 0 && ( -
- - {t('pendingQuotes', { count: counts.pendingQuotes })} - - {t('viewAlerts')} - -
- )} - - {/* Grouped card sections */} - {Array.from(grouped.entries()).map(([category, cards]) => { - if (cards.length === 0) return null - const categoryConfig = DASHBOARD_CATEGORIES[category] - return ( -
-

- {categoryConfig.title} -

-
- {cards.map(card => ( - - ))} +
+ {/* Profile Card */} + +
+
+ + {session.user.name?.charAt(0) || session.user.email?.charAt(0) || 'U'} +
-
- ) - })} +
+

+ Mein Profil +

+

+ Persönliche Daten verwalten +

+
+
+ + {/* Workshops Card */} + +
+
+ 🎓 +
+
+

+ Meine Workshops +

+

+ Angemeldete Kurse verwalten +

+
+
+ + + {/* Appointments Card */} + +
+
+ 📅 +
+
+

+ Termine +

+

+ Service-Termin buchen +

+
+
+ + + {/* Role-specific cards */} + {userRole === ROLES.SELLER && ( + +
+
+ 🏪 +
+
+

+ Seller Dashboard +

+

+ Produkte und Verkäufe +

+
+
+ + )} + + {userRole === ROLES.REPAIRER && ( + +
+
+ 🔧 +
+
+

+ Repairer Dashboard +

+

+ Reparaturen verwalten +

+
+
+ + )} + + {/* Upsell cards for capabilities (visible if user doesn't have role yet) */} + {userRole !== ROLES.SELLER && ( + +
+
+ 🏪 +
+
+

+ Auf Revamp‑IT verkaufen +

+

+ Eigene Produkte anbieten – Versand direkt an Käufer +

+
+
+ + )} + + {userRole !== ROLES.REPAIRER && ( + +
+
+ 🔧 +
+
+

+ Reparaturen anbieten +

+

+ Dienstleistungen publizieren und Anfragen erhalten +

+
+
+ + )} + + {/* Show admin card for staff users */} + {(session.user.isStaff || isStaffEmail(session.user.email || '')) && ( + +
+
+ ⚙️ +
+
+

+ Admin-Bereich +

+

+ System verwalten +

+
+
+ + )} + + {/* Workshop Proposal Card */} + +
+
+ 🎓 +
+
+

+ Workshop vorschlagen +

+

+ Eigene Workshops anbieten +

+
+
+ + + + {/* Blog Submit Card */} + +
+
+ ✍️ +
+
+

+ Beitrag verfassen +

+

+ Idee teilen oder Tutorial schreiben +

+
+
+ +
) -} +} \ No newline at end of file diff --git a/src/app/dashboard/seller/page.tsx b/src/app/dashboard/seller/page.tsx index 53c138348..deb96153b 100644 --- a/src/app/dashboard/seller/page.tsx +++ b/src/app/dashboard/seller/page.tsx @@ -1,9 +1,8 @@ 'use client' -import { useState, useEffect, useCallback } from 'react' +import { useState, useEffect } from 'react' import { useSession } from 'next-auth/react' import { useRouter } from 'next/navigation' -import { apiFetch } from '@/lib/api/client' import Link from 'next/link' import { Package, @@ -19,9 +18,6 @@ import { RefreshCw } from 'lucide-react' import { ListingImage } from '@/components/marketplace/ListingImage' -import { useTranslations } from 'next-intl' -import Heading from '@/components/ui/Heading' -import { Button } from '@/components/ui/button' import { ROLES } from '@/lib/constants' import { LISTING_STATUS_CONFIG } from '@/config/marketplace' import type { ListingStatus } from '@/config/marketplace' @@ -55,7 +51,6 @@ interface DashboardData { } export default function SellerDashboard() { - const t = useTranslations('dashboard.seller') const { data: session, status } = useSession() const router = useRouter() const [data, setData] = useState(null) @@ -67,23 +62,6 @@ export default function SellerDashboard() { document.title = 'Seller Dashboard | RevampIT' }, []) - const fetchDashboardData = useCallback(async () => { - setIsLoading(true) - setError(null) - try { - const result = await apiFetch('/api/seller/dashboard') - if (result.success && result.data) { - setData(result.data) - } else { - throw new Error(result.error || t('loadErrorGeneric')) - } - } catch (err) { - setError(err instanceof Error ? err.message : t('unexpectedError')) - } finally { - setIsLoading(false) - } - }, [t]) - useEffect(() => { if (status === 'loading') return @@ -106,33 +84,53 @@ export default function SellerDashboard() { } fetchDashboardData() - }, [session, status, router, fetchDashboardData]) + }, [session, status, router]) + + const fetchDashboardData = async () => { + setIsLoading(true) + setError(null) + + try { + const response = await fetch('/api/seller/dashboard') + const result = await response.json() + + if (result.success && result.data) { + setData(result.data) + } else { + throw new Error(result.error || 'Fehler beim Laden des Dashboards') + } + } catch (err) { + setError(err instanceof Error ? err.message : 'Ein unerwarteter Fehler ist aufgetreten') + } finally { + setIsLoading(false) + } + } const quickActions = [ { - title: t('quickNewProduct'), - description: t('quickNewProductDesc'), + title: 'Neues Produkt', + description: 'Produkt zum Marketplace hinzufügen', href: '/marketplace/sell', icon: Plus, color: 'bg-green-500', }, { - title: t('quickMyProducts'), - description: t('quickMyProductsDesc'), + title: 'Meine Produkte', + description: 'Alle Ihre Produkte verwalten', href: '/dashboard/listings', icon: Package, color: 'bg-blue-500', }, { - title: t('quickSales'), - description: t('quickSalesDesc'), + title: 'Verkäufe', + description: 'Bestellungen und Verkäufe anzeigen', href: '/dashboard/orders', icon: TrendingUp, color: 'bg-purple-500', }, { - title: t('quickMarketplace'), - description: t('quickMarketplaceDesc'), + title: 'Marketplace', + description: 'Marketplace ansehen', href: '/marketplace', icon: BarChart3, color: 'bg-orange-500', @@ -149,7 +147,7 @@ export default function SellerDashboard() { return (
- {t('loading')} + Dashboard wird geladen...
) } @@ -158,14 +156,17 @@ export default function SellerDashboard() { return (
- - {t('loadErrorTitle')} - +

+ Fehler beim Laden +

{error}

- + Erneut versuchen +
) } @@ -188,17 +189,17 @@ export default function SellerDashboard() {
- +

Seller Dashboard - +

- {t('pageSubtitle')} + Verwalten Sie Ihre Produkte im RevampIT Marketplace und verfolgen Sie Ihre Verkäufe.

@@ -210,9 +211,9 @@ export default function SellerDashboard() {
-

{t('statsProducts')}

+

Meine Produkte

{stats.totalProducts}

-

{t('statsActive', { count: stats.activeProducts })}

+

{stats.activeProducts} aktiv

@@ -221,13 +222,13 @@ export default function SellerDashboard() {
-

{t('statsRevenue')}

+

Umsatz

CHF {stats.totalRevenue.toLocaleString('de-CH')}

- {t('statsTotalRevenue')} + Gesamtumsatz

@@ -237,9 +238,9 @@ export default function SellerDashboard() {
-

{t('statsViews')}

+

Produkt-Aufrufe

{stats.totalViews.toLocaleString()}

-

{t('statsFavorites', { count: stats.totalFavorites })}

+

{stats.totalFavorites} Favoriten

@@ -248,9 +249,9 @@ export default function SellerDashboard() {
-

{t('statsOrders')}

+

Bestellungen

{stats.totalOrders}

-

{t('statsPending', { count: stats.pendingOrders })}

+

ausstehend: {stats.pendingOrders}

@@ -261,11 +262,11 @@ export default function SellerDashboard() { {/* Recent Products */}
- - {t('recentTitle')} - +

+ Meine Produkte +

- {t('recentSubtitle')} + Übersicht Ihrer Produkte

@@ -274,14 +275,14 @@ export default function SellerDashboard() {

- {t('noProducts')} + Sie haben noch keine Produkte erstellt.

- {t('createFirst')} + Erstes Produkt erstellen
) : ( @@ -294,11 +295,11 @@ export default function SellerDashboard() {
- +

{product.title} - +

- CHF {product.price} • {t('viewCount', { count: product.viewsCount })} + CHF {product.price} • {product.viewsCount} Aufrufe

@@ -318,7 +319,7 @@ export default function SellerDashboard() { href="/dashboard/listings" className="text-sm text-green-600 hover:text-green-700 dark:text-green-400 font-medium flex items-center gap-1" > - {t('manageAll')} + Alle Produkte verwalten
@@ -329,11 +330,11 @@ export default function SellerDashboard() { {/* Quick Actions */}
- - {t('quickActionsTitle')} - +

+ Schnellzugriff +

- {t('quickActionsSubtitle')} + Häufig verwendete Seller-Funktionen

@@ -349,9 +350,9 @@ export default function SellerDashboard() {
- +

{action.title} - +

{action.description} @@ -370,24 +371,26 @@ export default function SellerDashboard() {

- - {t('infoTitle')} - +

+ RevampIT Marketplace +

- {t('infoDesc')} + Als Seller können Sie Ihre eigenen refurbished Produkte im RevampIT Marketplace verkaufen. + Ihre Produkte erscheinen neben den offiziellen RevampIT Produkten und helfen dabei, + die Kreislaufwirtschaft zu fördern.

- {t('viewMarketplace')} + Marketplace ansehen - {t('addProduct')} + Produkt hinzufügen
diff --git a/src/app/dashboard/workshops/page.tsx b/src/app/dashboard/workshops/page.tsx index ce2a45b22..c31a166c7 100644 --- a/src/app/dashboard/workshops/page.tsx +++ b/src/app/dashboard/workshops/page.tsx @@ -2,18 +2,12 @@ import { useSession } from 'next-auth/react' import { useEffect, useState } from 'react' -import { useRouter, useSearchParams } from 'next/navigation' -import { apiFetch } from '@/lib/api/client' -import { Calendar, Clock, MapPin, Users, CheckCircle, XCircle, AlertCircle, ArrowLeft, LogIn } from 'lucide-react' -import { EmptyState } from '@/components/ui/EmptyState' +import { Calendar, Clock, MapPin, Users, CheckCircle, XCircle, AlertCircle, ArrowLeft } from 'lucide-react' import { WORKSHOP_REGISTRATION_STATUS } from '@/config/workshop-registration-status' import Link from 'next/link' import { getTextColor, getStatusColors } from '@/lib/design-system' import { cn } from '@/lib/utils' -import { useTranslations } from 'next-intl' import { formatDate } from '@/lib/date-formats' -import { Modal } from '@/components/ui/Modal' -import Heading from '@/components/ui/Heading' interface WorkshopRegistration { id: string @@ -32,54 +26,35 @@ interface WorkshopRegistration { } export default function WorkshopsDashboard() { - const tDates = useTranslations('dashboard.dates') - const t = useTranslations('dashboard.workshops') const { data: session, status } = useSession() - const router = useRouter() - const searchParams = useSearchParams() const [registrations, setRegistrations] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState('') - const [paymentSuccess, setPaymentSuccess] = useState( - () => searchParams.get('payment') === 'success' - ) const [editingId, setEditingId] = useState(null) const [editRating, setEditRating] = useState(5) const [editFeedback, setEditFeedback] = useState('') const [saving, setSaving] = useState(false) - // Strip the ?payment=success param from the URL after we've captured it into state useEffect(() => { - if (searchParams.get('payment') === 'success') { - router.replace('/dashboard/workshops') + if (session?.user) { + fetchRegistrations() } - }, [searchParams, router]) - - useEffect(() => { - if (!session?.user) return - let cancelled = false - async function load() { - const result = await apiFetch<{ registrations: WorkshopRegistration[] }>('/api/user/workshop-registrations') - if (cancelled) return - if (result.success && result.data) { - setRegistrations(result.data.registrations || []) - } else { - setError(result.error || t('loadError')) - } - setLoading(false) - } - load() - return () => { cancelled = true } - }, [session, t]) + }, [session]) const fetchRegistrations = async () => { - const result = await apiFetch<{ registrations: WorkshopRegistration[] }>('/api/user/workshop-registrations') - if (result.success && result.data) { - setRegistrations(result.data.registrations || []) - } else { - setError(result.error || t('loadError')) + try { + const response = await fetch('/api/user/workshop-registrations') + if (response.ok) { + const data = await response.json() + setRegistrations(data.data?.registrations || []) + } else { + setError('Fehler beim Laden der Workshop-Anmeldungen') + } + } catch (error) { + setError('Netzwerkfehler beim Laden der Daten') + } finally { + setLoading(false) } - setLoading(false) } const openEdit = (reg: WorkshopRegistration) => { @@ -91,17 +66,23 @@ export default function WorkshopsDashboard() { const saveEdit = async () => { if (!editingId) return setSaving(true) - const result = await apiFetch(`/api/workshops/registrations/${editingId}`, { - method: 'PATCH', - body: { rating: editRating, feedback: editFeedback } - }) - if (result.success) { - setEditingId(null) - fetchRegistrations() - } else { - setError(result.error || t('saveFailed')) + try { + const resp = await fetch(`/api/workshops/registrations/${editingId}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ rating: editRating, feedback: editFeedback }) + }) + if (resp.ok) { + setEditingId(null) + fetchRegistrations() + } else { + alert('Speichern fehlgeschlagen') + } + } catch { + alert('Netzwerkfehler beim Speichern') + } finally { + setSaving(false) } - setSaving(false) } const getStatusIcon = (status: string) => { @@ -120,11 +101,11 @@ export default function WorkshopsDashboard() { const getStatusText = (status: string) => { switch (status) { case WORKSHOP_REGISTRATION_STATUS.CONFIRMED: - return t('statusConfirmed') + return 'Bestätigt' case WORKSHOP_REGISTRATION_STATUS.PENDING: - return t('statusPending') + return 'Ausstehend' case WORKSHOP_REGISTRATION_STATUS.CANCELLED: - return t('statusCancelled') + return 'Storniert' default: return status } @@ -154,19 +135,18 @@ export default function WorkshopsDashboard() { return (
- - {t('login')} - - } - /> +
+

Anmeldung erforderlich

+

+ Bitte melden Sie sich an, um Ihre Workshop-Anmeldungen zu sehen. +

+ + Anmelden + +
) @@ -182,31 +162,14 @@ export default function WorkshopsDashboard() { className={cn('inline-flex items-center mb-4', getTextColor('neutral', 'muted'), 'hover:text-primary-600')} > - {t('backToDashboard')} + Zurück zum Dashboard - {t('pageTitle')} +

Meine Workshops

- {t('pageSubtitle')} + Übersicht Ihrer Workshop-Anmeldungen und Teilnahmen

- {/* Payment success banner (shown after Payrexx redirect) */} - {paymentSuccess && ( -
-
- -

{t('paymentSuccess')}

-
- -
- )} - {/* Error Message */} {error && (
@@ -221,9 +184,9 @@ export default function WorkshopsDashboard() {
- +

{registration.workshop_title} - +

{getStatusIcon(registration.status)} @@ -231,7 +194,7 @@ export default function WorkshopsDashboard() {
- {tDates('registeredOn', { date: formatDate(registration.created_at) })} + Angemeldet am {formatDate(registration.created_at)}
@@ -242,10 +205,10 @@ export default function WorkshopsDashboard() {
- {t('confirmedTitle')} + Ihre Anmeldung wurde bestätigt!

- {t('confirmedDesc')} + Sie erhalten in Kürze weitere Informationen zu Datum und Ort.

)} @@ -254,10 +217,10 @@ export default function WorkshopsDashboard() {
- {t('pendingTitle')} + Anmeldung ausstehend

- {t('pendingDesc')} + Ihre Anmeldung wird von unserem Team geprüft. Sie erhalten eine Bestätigung per E-Mail.

)} @@ -266,11 +229,11 @@ export default function WorkshopsDashboard() {
- {t('cancelledTitle')} + Anmeldung storniert
{registration.cancelled_at && (

- {t('cancelledOn', { date: formatDate(registration.cancelled_at) })} + Storniert am {formatDate(registration.cancelled_at)}

)}
@@ -281,26 +244,31 @@ export default function WorkshopsDashboard() {
)} @@ -308,58 +276,75 @@ export default function WorkshopsDashboard() { ))}
) : ( - - {t('discoverWorkshops')} - - } - /> +
+ +

+ Noch keine Workshop-Anmeldungen +

+

+ Sie haben sich noch für keine Workshops angemeldet. +

+ + Workshops entdecken + +
)}
- setEditingId(null)} title={t('modalTitle')}> -
-
- - setEditRating(Math.max(1, Math.min(5, Number(e.target.value))))} - className="w-24 px-3 py-2 border border-gray-300 rounded-lg" - /> + setEditingId(null)}> +
+

Feedback bearbeiten

+
+
+ + setEditRating(Math.max(1, Math.min(5, Number(e.target.value))))} + className="w-24 px-3 py-2 border border-gray-300 rounded-lg" + /> +
+
+ +