Boilerplate yield and back and forth

This commit is contained in:
KenwoodFox 2025-12-03 13:31:25 -05:00
parent c12aedeb20
commit 4cdd902b2e
7 changed files with 374 additions and 84 deletions

View File

@ -5,6 +5,7 @@ name = "pypi"
[packages] [packages]
django = "<5.0,>=4.2" django = "<5.0,>=4.2"
whitenoise = "<7.0,>=6.0"
[dev-packages] [dev-packages]

29
Pipfile.lock generated
View File

@ -1,7 +1,7 @@
{ {
"_meta": { "_meta": {
"hash": { "hash": {
"sha256": "bd4cb91114d0c833ac47abdad00410896c666f4553053870c3c7655342c703a0" "sha256": "faf9d6b8d73f937fa430b92dadbef77a6921f9675d5e8e3131b663391e308135"
}, },
"pipfile-spec": 6, "pipfile-spec": 6,
"requires": { "requires": {
@ -18,28 +18,37 @@
"default": { "default": {
"asgiref": { "asgiref": {
"hashes": [ "hashes": [
"sha256:aef8a81283a34d0ab31630c9b7dfe70c812c95eba78171367ca8745e88124734", "sha256:13acff32519542a1736223fb79a715acdebe24286d98e8b164a73085f40da2c4",
"sha256:d89f2d8cd8b56dada7d52fa7dc8075baa08fb836560710d38c292a7a3f78c04e" "sha256:1db9021efadb0d9512ce8ffaf72fcef601c7b73a8807a1bb2ef143dc6b14846d"
], ],
"markers": "python_version >= '3.9'", "markers": "python_version >= '3.9'",
"version": "==3.10.0" "version": "==3.11.0"
}, },
"django": { "django": {
"hashes": [ "hashes": [
"sha256:9398e487bcb55e3f142cb56d19fbd9a83e15bb03a97edc31f408361ee76d9d7a", "sha256:b865fbe0f4a3d1ee36594c5efa42b20db3c8bbb10dff0736face1c6e4bda5b92",
"sha256:c96e64fc3c359d051a6306871bd26243db1bd02317472a62ffdbe6c3cae14280" "sha256:f393a394053713e7d213984555c5b7d3caeee78b2ccb729888a0774dff6c11a8"
], ],
"index": "pypi", "index": "pypi",
"markers": "python_version >= '3.8'", "markers": "python_version >= '3.8'",
"version": "==4.2.26" "version": "==4.2.27"
}, },
"sqlparse": { "sqlparse": {
"hashes": [ "hashes": [
"sha256:09f67787f56a0b16ecdbde1bfc7f5d9c3371ca683cfeaa8e6ff60b4807ec9272", "sha256:4396a7d3cf1cd679c1be976cf3dc6e0a51d0111e87787e7a8d780e7d5a998f9e",
"sha256:cf2196ed3418f3ba5de6af7e82c694a9fbdbfecccdfc72e281548517081f16ca" "sha256:99a9f0314977b76d776a0fcb8554de91b9bb8a18560631d6bc48721d07023dcb"
], ],
"markers": "python_version >= '3.8'", "markers": "python_version >= '3.8'",
"version": "==0.5.3" "version": "==0.5.4"
},
"whitenoise": {
"hashes": [
"sha256:0f5bfce6061ae6611cd9396a8231e088722e4fc67bc13a111be74c738d99375f",
"sha256:b2aeb45950597236f53b5342b3121c5de69c8da0109362aee506ce88e022d258"
],
"index": "pypi",
"markers": "python_version >= '3.9'",
"version": "==6.11.0"
} }
}, },
"develop": {} "develop": {}

View File

@ -0,0 +1,81 @@
import json
import time
from pathlib import Path
from django.http import StreamingHttpResponse, JsonResponse
from django.conf import settings
from django.views.decorators.clickjacking import xframe_options_exempt
from django.views.decorators.csrf import csrf_exempt
def send_progress_update(step, message, progress):
"""Helper to send a progress update as JSON"""
return json.dumps({"step": step, "message": message, "progress": progress}) + "\n"
@xframe_options_exempt
@csrf_exempt
def submit_quote(request):
"""
Handle quote submission with progress updates.
Steps:
1. Upload files
2. Save files
3. Send email
4. Verify email sent
"""
if request.method != "POST":
return JsonResponse({"error": "Method not allowed"}, status=405)
# Read form data first (files need to be read from request)
email = request.POST.get("email", "").strip()
notes = request.POST.get("notes", "").strip()
files = request.FILES.getlist("files")
def process_quote():
try:
# Step 1: Upload files
yield send_progress_update(1, "Uploading files...", 25)
# Files are already uploaded at this point, just acknowledge
uploaded_files = []
for file in files:
uploaded_files.append({"name": file.name, "size": file.size})
# Step 2: Save files
yield send_progress_update(2, "Saving files...", 50)
# Save files to disk/storage
saved_paths = []
for file in files:
# Create store directory if it doesn't exist
store_dir = Path(settings.MEDIA_ROOT) / "uploads"
store_dir.mkdir(parents=True, exist_ok=True)
# Save file
file_path = store_dir / file.name
with open(file_path, "wb") as f:
for chunk in file.chunks():
f.write(chunk)
saved_paths.append(str(file_path))
# Step 3: Send emails
yield send_progress_update(3, "Sending emails 1/2...", 70)
time.sleep(0.5)
# TODO: Actually send emails
yield send_progress_update(4, "Sending emails 2/2...", 75)
time.sleep(0.5)
# TODO: Actually send emails
emails_sent = True # Placeholder
# Complete
yield send_progress_update(
5,
"Quote request submitted successfully! Check your email for confirmation.",
100,
)
except Exception as e:
yield send_progress_update("error", f"An error occurred: {str(e)}", 0)
response = StreamingHttpResponse(process_quote(), content_type="text/event-stream")
response["Cache-Control"] = "no-cache"
response["X-Accel-Buffering"] = "no"
return response

View File

@ -4,11 +4,13 @@ URL configuration for seduttomotorsports project.
from django.urls import path from django.urls import path
from . import views from . import views
from . import quote_submit
from django.conf import settings from django.conf import settings
from django.conf.urls.static import static from django.conf.urls.static import static
urlpatterns = [ urlpatterns = [
path("", views.quote_upload, name="quote_upload"), path("", views.quote_upload, name="quote_upload"),
path("submit-quote/", quote_submit.submit_quote, name="submit_quote"),
] ]
if settings.DEBUG: if settings.DEBUG:

View File

@ -30,6 +30,47 @@ h2 {
color: #333; color: #333;
} }
.form-field {
margin-bottom: 20px;
}
.form-field label {
display: block;
margin-bottom: 8px;
color: #333;
font-weight: 500;
font-size: 14px;
}
.form-field input[type="email"],
.form-field textarea {
width: 100%;
padding: 12px;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 14px;
font-family: Arial, sans-serif;
transition: border-color 0.3s;
}
.form-field input[type="email"]:focus,
.form-field textarea:focus {
outline: none;
border-color: #0066cc;
}
.form-field input[type="email"]:disabled,
.form-field textarea:disabled {
background: #f5f5f5;
cursor: not-allowed;
opacity: 0.7;
}
.form-field textarea {
resize: vertical;
min-height: 80px;
}
.drop-area { .drop-area {
border: 2px dashed #ccc; border: 2px dashed #ccc;
border-radius: 4px; border-radius: 4px;
@ -49,6 +90,11 @@ h2 {
background: #e6f2ff; background: #e6f2ff;
} }
.drop-area.disabled {
opacity: 0.6;
cursor: not-allowed;
}
.drop-area p + p { .drop-area p + p {
font-size: 14px; font-size: 14px;
color: #666; color: #666;
@ -96,14 +142,34 @@ button:disabled {
cursor: not-allowed; cursor: not-allowed;
} }
.todo { .progress-container {
margin-top: 20px; margin-top: 20px;
padding: 10px; padding: 16px;
background: #fff3cd; background: #f9f9f9;
border: 1px solid #ffc107;
border-radius: 4px; border-radius: 4px;
}
.progress-bar {
width: 100%;
height: 24px;
background: #e0e0e0;
border-radius: 12px;
overflow: hidden;
margin-bottom: 10px;
}
.progress-fill {
height: 100%;
background: #0066cc;
border-radius: 12px;
transition: width 0.3s ease;
width: 0%;
}
.progress-message {
font-size: 14px; font-size: 14px;
color: #856404; color: #666;
text-align: center;
} }
footer { footer {

181
static/js/quote_upload.js Normal file
View File

@ -0,0 +1,181 @@
const dropArea = document.getElementById('dropArea');
const fileInput = document.getElementById('fileInput');
const fileList = document.getElementById('fileList');
const submitBtn = document.getElementById('submitBtn');
const emailInput = document.getElementById('emailInput');
const notesInput = document.getElementById('notesInput');
let selectedFiles = [];
function checkCanSubmit() {
const hasEmail = emailInput.value.trim().length > 0;
const hasNotes = notesInput.value.trim().length > 0;
const hasFiles = selectedFiles.length > 0;
submitBtn.disabled = !(hasEmail || hasNotes || hasFiles);
}
emailInput.addEventListener('input', checkCanSubmit);
notesInput.addEventListener('input', checkCanSubmit);
dropArea.addEventListener('click', () => fileInput.click());
dropArea.addEventListener('dragover', (e) => {
e.preventDefault();
dropArea.classList.add('dragover');
});
dropArea.addEventListener('dragleave', () => {
dropArea.classList.remove('dragover');
});
dropArea.addEventListener('drop', (e) => {
e.preventDefault();
dropArea.classList.remove('dragover');
handleFiles(e.dataTransfer.files);
});
fileInput.addEventListener('change', (e) => {
handleFiles(e.target.files);
});
function handleFiles(files) {
selectedFiles = Array.from(files);
displayFiles();
checkCanSubmit();
}
function displayFiles() {
if (selectedFiles.length === 0) {
fileList.classList.remove('show');
return;
}
fileList.classList.add('show');
fileList.innerHTML = selectedFiles.map(file =>
`<div class="file-item">${file.name} (${(file.size / 1024).toFixed(1)} KB)</div>`
).join('');
}
submitBtn.addEventListener('click', async () => {
const email = emailInput.value.trim();
const notes = notesInput.value.trim();
// Validate at least one field
if (!email && !notes && selectedFiles.length === 0) {
return;
}
// Disable form during submission
submitBtn.disabled = true;
emailInput.disabled = true;
notesInput.disabled = true;
fileInput.disabled = true;
dropArea.style.pointerEvents = 'none';
dropArea.classList.add('disabled');
// Show progress bar
const progressContainer = document.getElementById('progressContainer');
const progressFill = document.getElementById('progressFill');
const progressMessage = document.getElementById('progressMessage');
progressContainer.style.display = 'block';
progressFill.style.width = '0%';
progressMessage.textContent = 'Starting...';
try {
// Create FormData
const formData = new FormData();
if (email) formData.append('email', email);
if (notes) formData.append('notes', notes);
selectedFiles.forEach(file => {
formData.append('files', file);
});
// Submit and read streaming response
const response = await fetch('/submit-quote/', {
method: 'POST',
body: formData
});
if (!response.ok) {
throw new Error(`Server error: ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || ''; // Keep incomplete line in buffer
for (const line of lines) {
if (line.trim()) {
try {
const update = JSON.parse(line);
progressFill.style.width = update.progress + '%';
progressMessage.textContent = update.message;
if (update.step === 5 || update.step === 'error') {
// Complete or error
if (update.step === 5) {
setTimeout(() => {
// Reset form after success
emailInput.value = '';
notesInput.value = '';
selectedFiles = [];
displayFiles();
checkCanSubmit();
// Re-enable form (but keep progress bar visible)
emailInput.disabled = false;
notesInput.disabled = false;
fileInput.disabled = false;
dropArea.style.pointerEvents = 'auto';
dropArea.classList.remove('disabled');
}, 2000);
} else {
// Error - re-enable form
emailInput.disabled = false;
notesInput.disabled = false;
fileInput.disabled = false;
dropArea.style.pointerEvents = 'auto';
dropArea.classList.remove('disabled');
submitBtn.disabled = false;
}
}
} catch (e) {
console.error('Error parsing progress update:', e);
}
}
}
}
} catch (error) {
progressMessage.textContent = `Error: ${error.message}`;
progressFill.style.width = '0%';
// Re-enable form
emailInput.disabled = false;
notesInput.disabled = false;
fileInput.disabled = false;
dropArea.style.pointerEvents = 'auto';
dropArea.classList.remove('disabled');
submitBtn.disabled = false;
}
});
// Attempt to auto-resize the iframe height (if parent allows)
function postHeight() {
const height = document.documentElement.scrollHeight;
try {
parent.postMessage({ type: 'sedutto-ifr-height', height }, '*');
} catch (e) {
// ignore if cross-origin restrictions apply
}
}
window.addEventListener('load', postHeight);
window.addEventListener('resize', postHeight);
const mo = new MutationObserver(postHeight);
mo.observe(document.body, { childList: true, subtree: true });

View File

@ -11,87 +11,37 @@
<body> <body>
<div class="upload-box"> <div class="upload-box">
<h2>Request a Quote</h2> <div class="form-field">
<label for="emailInput">Email</label>
<input type="email" id="emailInput" placeholder="your.email@example.com">
</div>
<div class="form-field">
<label for="notesInput">Notes / Comments</label>
<textarea id="notesInput" rows="4" placeholder="Additional information, comments or questions!"></textarea>
</div>
<div class="drop-area" id="dropArea"> <div class="drop-area" id="dropArea">
<p>Drag & drop files here</p> <p>Drag & drop drawings, CAD models, images or anything else here</p>
<p>or click to browse</p> <p>or click to browse</p>
<input type="file" id="fileInput" multiple> <input type="file" id="fileInput" multiple>
</div> </div>
<div class="file-list" id="fileList"></div> <div class="file-list" id="fileList"></div>
<button id="submitBtn" disabled>Submit</button> <button id="submitBtn" disabled>Submit</button>
<div class="todo">
<strong>TODO:</strong> Implement file upload functionality <div class="progress-container" id="progressContainer" style="display: none;">
<div class="progress-bar">
<div class="progress-fill" id="progressFill"></div>
</div>
<div class="progress-message" id="progressMessage"></div>
</div> </div>
<footer> <footer>
Hosted by <a href="https://kitsunehosting.net" target="_blank" Hosted by <a href="https://kitsunehosting.net" target="_blank"
rel="noopener noreferrer">kitsunehosting.net</a> rel="noopener noreferrer">kitsunehosting.net</a>
</footer> </footer>
</div> </div>
<script src="{% static 'js/quote_upload.js' %}"></script>
<script>
const dropArea = document.getElementById('dropArea');
const fileInput = document.getElementById('fileInput');
const fileList = document.getElementById('fileList');
const submitBtn = document.getElementById('submitBtn');
let selectedFiles = [];
dropArea.addEventListener('click', () => fileInput.click());
dropArea.addEventListener('dragover', (e) => {
e.preventDefault();
dropArea.classList.add('dragover');
});
dropArea.addEventListener('dragleave', () => {
dropArea.classList.remove('dragover');
});
dropArea.addEventListener('drop', (e) => {
e.preventDefault();
dropArea.classList.remove('dragover');
handleFiles(e.dataTransfer.files);
});
fileInput.addEventListener('change', (e) => {
handleFiles(e.target.files);
});
function handleFiles(files) {
selectedFiles = Array.from(files);
displayFiles();
submitBtn.disabled = selectedFiles.length === 0;
}
function displayFiles() {
if (selectedFiles.length === 0) {
fileList.classList.remove('show');
return;
}
fileList.classList.add('show');
fileList.innerHTML = selectedFiles.map(file =>
`<div class="file-item">${file.name} (${(file.size / 1024).toFixed(1)} KB)</div>`
).join('');
}
submitBtn.addEventListener('click', () => {
// TODO: Submit files to backend
alert('Upload functionality - TODO');
});
// Attempt to auto-resize the iframe height (if parent allows)
function postHeight() {
const height = document.documentElement.scrollHeight;
try {
parent.postMessage({ type: 'sedutto-ifr-height', height }, '*');
} catch (e) {
// ignore if cross-origin restrictions apply
}
}
window.addEventListener('load', postHeight);
window.addEventListener('resize', postHeight);
const mo = new MutationObserver(postHeight);
mo.observe(document.body, { childList: true, subtree: true });
</script>
</body> </body>
</html> </html>