use api in front

This commit is contained in:
2025-10-29 02:57:10 +01:00
parent 07dd1bc0ff
commit 52723b200a
14 changed files with 900 additions and 263 deletions
+3
View File
@@ -60,6 +60,8 @@ def create_submission(
if len(files) < len(data.responses):
return 400, {"detail": "Not enough files for all responses"}
print(data, files)
try:
with transaction.atomic():
# Create the submission
@@ -135,6 +137,7 @@ def create_submission(
return submission
except Exception as e:
print(e)
return 500, {"detail": f"Error creating submission: {str(e)}"}
@@ -0,0 +1,18 @@
# Generated by Django 5.2.7 on 2025-10-29 01:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('submissions', '0004_submission_puzzleresponse_submissionfile'),
]
operations = [
migrations.AlterField(
model_name='submission',
name='notes',
field=models.TextField(blank=True, help_text='Optional notes about the submission', null=True),
),
]
+83 -125
View File
@@ -10,65 +10,63 @@ User = get_user_model()
class SteamAPIKey(models.Model):
"""Model to store Steam API key configuration - Admin only"""
name = models.CharField(
max_length=100,
max_length=100,
unique=True,
help_text="Descriptive name for this API key (e.g., 'Production Key', 'Development Key')"
help_text="Descriptive name for this API key (e.g., 'Production Key', 'Development Key')",
)
api_key = models.CharField(
max_length=64,
help_text="Steam Web API key from https://steamcommunity.com/dev/apikey"
help_text="Steam Web API key from https://steamcommunity.com/dev/apikey",
)
is_active = models.BooleanField(
default=True,
help_text="Whether this API key should be used"
default=True, help_text="Whether this API key should be used"
)
description = models.TextField(
blank=True,
help_text="Optional description or notes about this API key"
blank=True, help_text="Optional description or notes about this API key"
)
# Metadata
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
last_used = models.DateTimeField(
null=True,
blank=True,
help_text="When this API key was last used"
null=True, blank=True, help_text="When this API key was last used"
)
class Meta:
verbose_name = "Steam API Key"
verbose_name_plural = "Steam API Keys"
ordering = ['-is_active', 'name']
ordering = ["-is_active", "name"]
def __str__(self):
status = "Active" if self.is_active else "Inactive"
return f"{self.name} ({status})"
def clean(self):
"""Validate the API key format"""
if self.api_key:
# Steam API keys are typically 32 characters of hexadecimal
if len(self.api_key) != 32:
raise ValidationError("Steam API key should be 32 characters long")
# Check if it's hexadecimal
try:
int(self.api_key, 16)
except ValueError:
raise ValidationError("Steam API key should contain only hexadecimal characters (0-9, A-F)")
raise ValidationError(
"Steam API key should contain only hexadecimal characters (0-9, A-F)"
)
def save(self, *args, **kwargs):
self.full_clean()
super().save(*args, **kwargs)
@classmethod
def get_active_key(cls):
"""Get the currently active API key"""
return cls.objects.filter(is_active=True).first()
@property
def masked_key(self):
"""Return a masked version of the API key for display"""
@@ -202,69 +200,67 @@ class SteamCollectionItem(models.Model):
def submission_file_upload_path(instance, filename):
"""Generate upload path for submission files"""
# Create path: submissions/{submission_id}/{uuid}_{filename}
ext = filename.split('.')[-1] if '.' in filename else ''
ext = filename.split(".")[-1] if "." in filename else ""
new_filename = f"{uuid.uuid4()}_{filename}" if ext else str(uuid.uuid4())
return f"submissions/{instance.response.submission.id}/{new_filename}"
class Submission(models.Model):
"""Model representing a submission containing multiple puzzle responses"""
# Identification
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
# User information (optional for anonymous submissions)
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
null=True,
User,
on_delete=models.CASCADE,
null=True,
blank=True,
help_text="User who made the submission (null for anonymous)"
help_text="User who made the submission (null for anonymous)",
)
# Submission metadata
notes = models.TextField(
null=True,
blank=True,
help_text="Optional notes about the submission"
help_text="Optional notes about the submission",
)
# Status tracking
is_validated = models.BooleanField(
default=False,
help_text="Whether this submission has been manually validated"
default=False, help_text="Whether this submission has been manually validated"
)
validated_by = models.ForeignKey(
User,
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name='validated_submissions',
help_text="Admin user who validated this submission"
related_name="validated_submissions",
help_text="Admin user who validated this submission",
)
validated_at = models.DateTimeField(
null=True,
blank=True,
help_text="When this submission was validated"
null=True, blank=True, help_text="When this submission was validated"
)
# Timestamps
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
ordering = ["-created_at"]
verbose_name = "Submission"
verbose_name_plural = "Submissions"
def __str__(self):
user_info = f"by {self.user.username}" if self.user else "anonymous"
return f"Submission {self.id} {user_info}"
@property
def total_responses(self):
"""Get total number of puzzle responses in this submission"""
return self.responses.count()
@property
def needs_validation(self):
"""Check if any response needs manual validation"""
@@ -273,167 +269,129 @@ class Submission(models.Model):
class PuzzleResponse(models.Model):
"""Model representing a response/solution for a specific puzzle"""
# Relationships
submission = models.ForeignKey(
Submission,
on_delete=models.CASCADE,
related_name='responses'
Submission, on_delete=models.CASCADE, related_name="responses"
)
puzzle = models.ForeignKey(
SteamCollectionItem,
on_delete=models.CASCADE,
related_name='responses',
help_text="The puzzle this response is for"
related_name="responses",
help_text="The puzzle this response is for",
)
# OCR extracted data
puzzle_name = models.CharField(
max_length=255,
help_text="Puzzle name as detected by OCR"
)
cost = models.CharField(
max_length=20,
blank=True,
help_text="Cost value from OCR"
max_length=255, help_text="Puzzle name as detected by OCR"
)
cost = models.CharField(max_length=20, blank=True, help_text="Cost value from OCR")
cycles = models.CharField(
max_length=20,
blank=True,
help_text="Cycles value from OCR"
max_length=20, blank=True, help_text="Cycles value from OCR"
)
area = models.CharField(
max_length=20,
blank=True,
help_text="Area value from OCR"
)
area = models.CharField(max_length=20, blank=True, help_text="Area value from OCR")
# Validation flags
needs_manual_validation = models.BooleanField(
default=False,
help_text="Whether OCR failed and manual validation is needed"
default=False, help_text="Whether OCR failed and manual validation is needed"
)
ocr_confidence_score = models.FloatField(
null=True,
blank=True,
help_text="OCR confidence score (0.0 to 1.0)"
null=True, blank=True, help_text="OCR confidence score (0.0 to 1.0)"
)
# Manual validation overrides
validated_cost = models.CharField(
max_length=20,
blank=True,
help_text="Manually validated cost value"
max_length=20, blank=True, help_text="Manually validated cost value"
)
validated_cycles = models.CharField(
max_length=20,
blank=True,
help_text="Manually validated cycles value"
max_length=20, blank=True, help_text="Manually validated cycles value"
)
validated_area = models.CharField(
max_length=20,
blank=True,
help_text="Manually validated area value"
max_length=20, blank=True, help_text="Manually validated area value"
)
# Timestamps
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['submission', 'puzzle__order_index']
unique_together = ['submission', 'puzzle']
ordering = ["submission", "puzzle__order_index"]
unique_together = ["submission", "puzzle"]
verbose_name = "Puzzle Response"
verbose_name_plural = "Puzzle Responses"
def __str__(self):
return f"Response for {self.puzzle_name} in {self.submission}"
@property
def final_cost(self):
"""Get the final cost value (validated if available, otherwise OCR)"""
return self.validated_cost or self.cost
@property
def final_cycles(self):
"""Get the final cycles value (validated if available, otherwise OCR)"""
return self.validated_cycles or self.cycles
@property
def final_area(self):
"""Get the final area value (validated if available, otherwise OCR)"""
return self.validated_area or self.area
def mark_for_validation(self, reason="OCR failed"):
"""Mark this response as needing manual validation"""
self.needs_manual_validation = True
self.save(update_fields=['needs_manual_validation'])
self.save(update_fields=["needs_manual_validation"])
class SubmissionFile(models.Model):
"""Model representing files uploaded with a puzzle response"""
# Relationships
response = models.ForeignKey(
PuzzleResponse,
on_delete=models.CASCADE,
related_name='files'
PuzzleResponse, on_delete=models.CASCADE, related_name="files"
)
# File information
file = models.FileField(
upload_to=submission_file_upload_path,
help_text="Uploaded file (image/gif)"
upload_to=submission_file_upload_path, help_text="Uploaded file (image/gif)"
)
original_filename = models.CharField(
max_length=255,
help_text="Original filename as uploaded by user"
max_length=255, help_text="Original filename as uploaded by user"
)
file_size = models.PositiveIntegerField(
help_text="File size in bytes"
)
content_type = models.CharField(
max_length=100,
help_text="MIME type of the file"
)
file_size = models.PositiveIntegerField(help_text="File size in bytes")
content_type = models.CharField(max_length=100, help_text="MIME type of the file")
# OCR metadata
ocr_processed = models.BooleanField(
default=False,
help_text="Whether OCR has been processed for this file"
default=False, help_text="Whether OCR has been processed for this file"
)
ocr_raw_data = models.JSONField(
null=True,
blank=True,
help_text="Raw OCR data as JSON"
null=True, blank=True, help_text="Raw OCR data as JSON"
)
ocr_error = models.TextField(
blank=True,
help_text="OCR processing error message"
)
ocr_error = models.TextField(blank=True, help_text="OCR processing error message")
# Timestamps
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['response', 'created_at']
ordering = ["response", "created_at"]
verbose_name = "Submission File"
verbose_name_plural = "Submission Files"
def __str__(self):
return f"{self.original_filename} for {self.response}"
@property
def file_url(self):
"""Get the URL for the uploaded file"""
if self.file:
return self.file.url
return None
def save(self, *args, **kwargs):
# Set file metadata on save
if self.file and not self.file_size:
self.file_size = self.file.size
super().save(*args, **kwargs)