Spaces:
Running

File size: 8,404 Bytes
477fc03
 
 
 
 
 
 
 
 
 
 
9a26894
477fc03
5097468
477fc03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e024ada
 
477fc03
 
 
 
 
 
 
 
 
 
e024ada
 
477fc03
 
 
 
 
 
 
 
 
 
 
 
e024ada
 
477fc03
 
 
 
 
 
 
 
 
 
 
 
b93d6f8
477fc03
 
 
 
 
 
 
 
 
 
 
 
 
b93d6f8
477fc03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a26894
 
5097468
 
 
477fc03
 
 
 
b93d6f8
477fc03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b93d6f8
477fc03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a26894
 
5097468
 
 
477fc03
 
 
 
b93d6f8
477fc03
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a26894
5097468
 
 
9a26894
477fc03
 
 
b93d6f8
477fc03
 
 
 
 
 
 
 
 
 
 
 
 
72d27f1
 
 
477fc03
72d27f1
 
477fc03
 
72d27f1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94f3647
 
 
 
 
 
31b64b4
94f3647
 
 
 
72d27f1
 
94f3647
72d27f1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, status
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from typing import List
from uuid import UUID
from datetime import datetime

from app.core.database import get_session
from app.models.product import Product
from app.models.user import User
from app.api.deps import get_current_user
from app.services.ai_memory_manager import get_memory_manager
from pydantic import BaseModel
from app.models.tenant import Tenant

router = APIRouter(prefix="/products", tags=["Products"])


# ============================================================================
# Request/Response Models
# ============================================================================

class ProductCreate(BaseModel):
    """Schema for creating a new product."""
    name: str
    description: str | None = None
    price: float
    currency: str = "USD"
    category: str
    image_url: str | None = None  # Legacy: single image
    image_urls: List[str] | None = None  # NEW: Multiple images
    in_stock: bool = True


class ProductUpdate(BaseModel):
    """Schema for updating an existing product."""
    name: str | None = None
    description: str | None = None
    price: float | None = None
    currency: str | None = None
    category: str | None = None
    image_url: str | None = None  # Legacy: single image
    image_urls: List[str] | None = None  # NEW: Multiple images
    in_stock: bool | None = None


class ProductResponse(BaseModel):
    """Schema for product response."""
    id: UUID
    tenant_id: UUID
    name: str
    description: str | None
    price: float
    currency: str
    category: str
    image_url: str | None  # Legacy: single image
    image_urls: List[str] | None  # NEW: Multiple images
    in_stock: bool
    created_at: datetime
    updated_at: datetime

    class Config:
        from_attributes = True


# ============================================================================
# Endpoints
# ============================================================================

@router.get("/", response_model=List[ProductResponse])
async def get_products(
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    """
    Get all products for the current tenant.
    """
    statement = select(Product).where(Product.tenant_id == current_user.tenant_id)
    result = await session.execute(statement)
    products = result.scalars().all()
    return products


@router.post("/", response_model=ProductResponse, status_code=status.HTTP_201_CREATED)
async def create_product(
    product_data: ProductCreate,
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    """
    Create a new product for the current tenant.
    """
    product = Product(
        **product_data.model_dump(),
        tenant_id=current_user.tenant_id
    )
    
    session.add(product)
    await session.commit()
    await session.refresh(product)

    # SIGNAL: Invalidate AI Memory
    tenant = await session.get(Tenant, current_user.tenant_id)
    if tenant:
        await get_memory_manager().invalidate_memory(session, tenant)
    
    return product


@router.get("/{product_id}", response_model=ProductResponse)
async def get_product(
    product_id: UUID,
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    """
    Get a specific product by ID.
    """
    statement = select(Product).where(
        Product.id == product_id,
        Product.tenant_id == current_user.tenant_id
    )
    result = await session.execute(statement)
    product = result.scalar_one_or_none()
    
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    
    return product


@router.patch("/{product_id}", response_model=ProductResponse)
async def update_product(
    product_id: UUID,
    product_data: ProductUpdate,
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    """
    Update an existing product.
    """
    statement = select(Product).where(
        Product.id == product_id,
        Product.tenant_id == current_user.tenant_id
    )
    result = await session.execute(statement)
    product = result.scalar_one_or_none()
    
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    
    # Update only provided fields
    update_data = product_data.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(product, field, value)
    
    product.updated_at = datetime.utcnow()
    
    session.add(product)
    await session.commit()
    await session.refresh(product)

    # SIGNAL: Invalidate AI Memory
    tenant = await session.get(Tenant, current_user.tenant_id)
    if tenant:
        await get_memory_manager().invalidate_memory(session, tenant)
    
    return product


@router.delete("/{product_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_product(
    product_id: UUID,
    session: AsyncSession = Depends(get_session),
    current_user: User = Depends(get_current_user)
):
    """
    Delete a product.
    """
    statement = select(Product).where(
        Product.id == product_id,
        Product.tenant_id == current_user.tenant_id
    )
    result = await session.execute(statement)
    product = result.scalar_one_or_none()
    
    if not product:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Product not found"
        )
    
    await session.delete(product)
    await session.commit()
    
    # SIGNAL: Invalidate AI Memory
    tenant = await session.get(Tenant, current_user.tenant_id)
    if tenant:
        await get_memory_manager().invalidate_memory(session, tenant)
    
    return None


@router.post("/upload-image")
async def upload_product_image(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user)
):
    """
    Upload a product image.
    Returns the URL of the uploaded image.
    
    For now, returns a placeholder. In production, integrate with:
    - AWS S3
    - Cloudinary
    - Supabase Storage
    """
    # 1. Initialize Supabase
    from app.core.supabase import supabase_client
    if not supabase_client:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Supabase Storage not configured"
        )
    
    # 2. Sanitize filename & Rename to avoid collisions
    # Format: {tenant_id}/{timestamp}_{safe_filename}
    import re
    import time
    
    timestamp = int(time.time())
    safe_filename = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', file.filename)
    if len(safe_filename) > 50:
        safe_filename = safe_filename[-50:]
        
    # Tenant isolation folder
    storage_path = f"{current_user.tenant_id}/{timestamp}_{safe_filename}"
    
    # 3. Read file content
    file_content = await file.read()
    
    try:
        # 4. Upload to Supabase 'products' bucket
        res = supabase_client.storage.from_("products").upload(
            path=storage_path,
            file=file_content,
            file_options={"content-type": file.content_type}
        )
        
        # 5. Get Public URL
        public_url = supabase_client.storage.from_("products").get_public_url(storage_path)
        
        return {
            "url": public_url,
            "filename": safe_filename,
            "content_type": file.content_type
        }
        
    except Exception as e:
        error_msg = str(e)
        print(f"❌ Storage Upload Error: {error_msg}")
        
        # Check for common Supabase Storage errors
        if "Bucket not found" in error_msg:
            detail = "Storage bucket 'products' not found. Please create it in Supabase Dashboard."
        elif "new row violates row-level security policy" in error_msg:
             detail = "Storage permission denied. Check RLS policies on 'products' bucket."
        else:
            detail = f"Upload failed: {error_msg}"
            
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=detail
        )