hisham-cmd commited on
Commit
e415ee9
·
verified ·
1 Parent(s): 03998fa

Update backend with high-quality catalog and fixes

Browse files
app/api/orders.py CHANGED
@@ -366,23 +366,26 @@ def upload_payment_receipt(
366
  if not payment:
367
  raise HTTPException(status_code=404, detail="Payment record not found")
368
 
369
- # Ensure directory exists in DATA_DIR
370
- uploads_dir = os.path.join(settings.DATA_DIR, "uploads", "receipts")
371
- os.makedirs(uploads_dir, exist_ok=True)
372
 
373
- # Generate unique filename
374
- ext = os.path.splitext(file.filename)[1]
375
- filename = f"receipt_{order.id}_{uuid.uuid4().hex[:8]}{ext}"
376
- file_path = os.path.join(uploads_dir, filename)
377
-
378
- # Save the file
379
- with open(file_path, "wb") as buffer:
380
- import shutil
381
- shutil.copyfileobj(file.file, buffer)
 
 
382
 
 
 
 
383
  # Update payment record
384
- receipt_url = f"/uploads/receipts/{filename}"
385
- payment.receipt_url = receipt_url
386
  payment.status = PaymentStatus.PENDING # Awaiting admin approval
387
 
388
  # 5. Finally Clear Cart (if requested via bank transfer follow-up)
@@ -399,7 +402,7 @@ def upload_payment_receipt(
399
 
400
  return {
401
  "isSuccess": True,
402
- "value": {"message": "Receipt uploaded successfully", "receipt_url": receipt_url},
403
  "statusCode": 200
404
  }
405
 
 
366
  if not payment:
367
  raise HTTPException(status_code=404, detail="Payment record not found")
368
 
369
+ # Convert file to base64 string
370
+ file_bytes = file.file.read()
 
371
 
372
+ import base64
373
+ ext = os.path.splitext(file.filename)[1].lower()
374
+ mime_type = "image/jpeg"
375
+ if ext in [".png"]:
376
+ mime_type = "image/png"
377
+ elif ext in [".gif"]:
378
+ mime_type = "image/gif"
379
+ elif ext in [".webp"]:
380
+ mime_type = "image/webp"
381
+ elif ext in [".pdf"]:
382
+ mime_type = "application/pdf"
383
 
384
+ b64_encoded = base64.b64encode(file_bytes).decode('utf-8')
385
+ receipt_data_uri = f"data:{mime_type};base64,{b64_encoded}"
386
+
387
  # Update payment record
388
+ payment.receipt_url = receipt_data_uri
 
389
  payment.status = PaymentStatus.PENDING # Awaiting admin approval
390
 
391
  # 5. Finally Clear Cart (if requested via bank transfer follow-up)
 
402
 
403
  return {
404
  "isSuccess": True,
405
+ "value": {"message": "Receipt uploaded successfully", "receipt_url": receipt_data_uri},
406
  "statusCode": 200
407
  }
408
 
app/api/settings.py CHANGED
@@ -57,20 +57,24 @@ def upload_settings_image(
57
  db: Session = Depends(get_db),
58
  current_admin=Depends(get_current_admin_user)
59
  ) -> Any:
60
- # 1. Create directory if not exists
61
- settings_uploads = os.path.join(app_settings.DATA_DIR, "uploads", "settings")
62
- os.makedirs(settings_uploads, exist_ok=True)
63
 
64
- # 2. Save file
65
- file_ext = os.path.splitext(file.filename)[1]
66
- filename = f"settings_{int(datetime.now().timestamp())}{file_ext}"
67
- file_path = os.path.join(settings_uploads, filename)
68
-
69
- with open(file_path, "wb") as buffer:
70
- shutil.copyfileobj(file.file, buffer)
 
 
71
 
 
 
 
72
  return APIResponse(
73
  isSuccess=True,
74
- value={"url": f"/uploads/settings/{filename}"},
75
  statusCode=200
76
  )
 
57
  db: Session = Depends(get_db),
58
  current_admin=Depends(get_current_admin_user)
59
  ) -> Any:
60
+ # Convert file to base64 string
61
+ file_bytes = file.file.read()
 
62
 
63
+ import base64
64
+ ext = os.path.splitext(file.filename)[1].lower()
65
+ mime_type = "image/jpeg"
66
+ if ext in [".png"]:
67
+ mime_type = "image/png"
68
+ elif ext in [".gif"]:
69
+ mime_type = "image/gif"
70
+ elif ext in [".webp"]:
71
+ mime_type = "image/webp"
72
 
73
+ b64_encoded = base64.b64encode(file_bytes).decode('utf-8')
74
+ data_uri = f"data:{mime_type};base64,{b64_encoded}"
75
+
76
  return APIResponse(
77
  isSuccess=True,
78
+ value={"url": data_uri},
79
  statusCode=200
80
  )
app/core/config.py CHANGED
@@ -8,6 +8,7 @@ class Settings(BaseSettings):
8
  # Base directory for persistent data (e.g., /data for Hugging Face persistent storage)
9
  DATA_DIR: str = os.getenv("DATA_DIR", ".")
10
  DATABASE_URL: str = os.getenv("DATABASE_URL", f"sqlite:///{os.path.join(os.getenv('DATA_DIR', '.'), 'vortex.db')}")
 
11
 
12
  JWT_SECRET: str = "change-me-in-production"
13
  JWT_ALGORITHM: str = "HS256"
 
8
  # Base directory for persistent data (e.g., /data for Hugging Face persistent storage)
9
  DATA_DIR: str = os.getenv("DATA_DIR", ".")
10
  DATABASE_URL: str = os.getenv("DATABASE_URL", f"sqlite:///{os.path.join(os.getenv('DATA_DIR', '.'), 'vortex.db')}")
11
+ TURSO_AUTH_TOKEN: str = os.getenv("TURSO_AUTH_TOKEN", "")
12
 
13
  JWT_SECRET: str = "change-me-in-production"
14
  JWT_ALGORITHM: str = "HS256"
app/db/base.py CHANGED
@@ -3,9 +3,20 @@ from sqlalchemy.orm import sessionmaker, DeclarativeBase
3
 
4
  from app.core.config import settings
5
 
 
 
 
 
 
 
 
 
 
 
 
6
  engine = create_engine(
7
  settings.DATABASE_URL,
8
- connect_args={"check_same_thread": False} if "sqlite" in settings.DATABASE_URL else {},
9
  echo=False,
10
  )
11
 
 
3
 
4
  from app.core.config import settings
5
 
6
+ # Create connection args dynamically based on the URL type
7
+ connect_args = {}
8
+ if "sqlite" in settings.DATABASE_URL or "libsql" in settings.DATABASE_URL:
9
+ connect_args["check_same_thread"] = False
10
+
11
+ # Add Turso Auth Token if connecting remotely
12
+ if settings.TURSO_AUTH_TOKEN and "turso.io" in settings.DATABASE_URL:
13
+ # Ensure URL uses sqlite+libsql if it's a bare libsql://
14
+ if settings.DATABASE_URL.startswith("libsql://"):
15
+ settings.DATABASE_URL = settings.DATABASE_URL.replace("libsql://", "sqlite+libsql://", 1)
16
+
17
  engine = create_engine(
18
  settings.DATABASE_URL,
19
+ connect_args=connect_args,
20
  echo=False,
21
  )
22
 
requirements.txt CHANGED
@@ -12,6 +12,8 @@ google-api-python-client==2.118.0
12
  python-multipart==0.0.9
13
  httpx==0.27.0
14
  aiosqlite==0.20.0
 
 
15
  python-dotenv==1.0.1
16
  reportlab==4.0.9
17
  email-validator==2.1.0.post1
 
12
  python-multipart==0.0.9
13
  httpx==0.27.0
14
  aiosqlite==0.20.0
15
+ libsql-client==0.1.4
16
+ sqlalchemy-libsql==0.1.1
17
  python-dotenv==1.0.1
18
  reportlab==4.0.9
19
  email-validator==2.1.0.post1
test_turso.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ def test_uri():
4
+ db_url = "libsql://ofoq-ofoq.aws-ap-northeast-1.turso.io"
5
+ token = "eyJhbGciOiJFZERTQSIsInR5cCI6IkpXVCJ9..."
6
+
7
+ # Normally we do:
8
+ if db_url.startswith("libsql://"):
9
+ db_url = db_url.replace("libsql://", "sqlite+libsql://", 1)
10
+
11
+ # And we append the token as a query parameter
12
+ if "?" in db_url:
13
+ db_url += f"&authToken={token}"
14
+ else:
15
+ db_url += f"?authToken={token}"
16
+
17
+ print("FINAL URL:", db_url)
18
+
19
+ if __name__ == "__main__":
20
+ test_uri()