fix mail sand 2
This commit is contained in:
@@ -443,29 +443,34 @@ def get_eligible_users(assignment_id: str, db: Session = Depends(get_db), curren
|
||||
return result
|
||||
|
||||
|
||||
from typing import Optional
|
||||
from typing import Optional, Union
|
||||
|
||||
class TestEmailRequest(BaseModel):
|
||||
date: Optional[date] = None
|
||||
date: Optional[str] = None
|
||||
office_id: str
|
||||
bulk_send: bool = False # New flag
|
||||
|
||||
|
||||
@router.post("/test-email")
|
||||
def send_test_email_tool(data: TestEmailRequest, db: Session = Depends(get_db), current_user=Depends(require_manager_or_admin)):
|
||||
"""Send a test email to the current user (Test Tool)"""
|
||||
from services.notifications import send_email
|
||||
from database.models import OfficeClosingDay, OfficeWeeklyClosingDay
|
||||
from datetime import timedelta
|
||||
|
||||
"""Send a test email to the current user OR bulk reminder to all (Test Tool)"""
|
||||
from services.notifications import send_email, send_daily_parking_reminder
|
||||
from database.models import OfficeClosingDay, OfficeWeeklyClosingDay, User
|
||||
from datetime import timedelta, datetime
|
||||
|
||||
# Verify office access
|
||||
if current_user.role == UserRole.MANAGER and current_user.office_id != data.office_id:
|
||||
raise HTTPException(status_code=403, detail="Not authorized for this office")
|
||||
|
||||
target_date = data.date
|
||||
target_date = None
|
||||
if data.date:
|
||||
try:
|
||||
target_date = datetime.strptime(data.date, "%Y-%m-%d").date()
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=422, detail="Invalid date format. Use YYYY-MM-DD")
|
||||
|
||||
if not target_date:
|
||||
# Find next open day
|
||||
# Start from tomorrow (or today? Prompt says "dopo il giorno corrente" -> after today)
|
||||
# Find next open day logic (same as before)
|
||||
check_date = date.today() + timedelta(days=1)
|
||||
|
||||
# Load closing rules
|
||||
@@ -479,15 +484,11 @@ def send_test_email_tool(data: TestEmailRequest, db: Session = Depends(get_db),
|
||||
OfficeClosingDay.date >= check_date
|
||||
).all()
|
||||
|
||||
# Max lookahead 30 days to avoid infinite loop
|
||||
found = False
|
||||
for _ in range(30):
|
||||
# Check weekly
|
||||
if check_date.weekday() in weekly_closed_set:
|
||||
check_date += timedelta(days=1)
|
||||
continue
|
||||
|
||||
# Check specific
|
||||
is_specific = False
|
||||
for d in specific_closed:
|
||||
s = d.date
|
||||
@@ -495,31 +496,89 @@ def send_test_email_tool(data: TestEmailRequest, db: Session = Depends(get_db),
|
||||
if s <= check_date <= e:
|
||||
is_specific = True
|
||||
break
|
||||
|
||||
if is_specific:
|
||||
check_date += timedelta(days=1)
|
||||
continue
|
||||
|
||||
found = True
|
||||
break
|
||||
|
||||
if found:
|
||||
target_date = check_date
|
||||
else:
|
||||
# Fallback
|
||||
target_date = date.today() + timedelta(days=1)
|
||||
|
||||
# Send Email
|
||||
subject = f"Test Email - Parking System ({target_date})"
|
||||
target_date = check_date if found else date.today() + timedelta(days=1)
|
||||
|
||||
# BULK MODE
|
||||
if data.bulk_send:
|
||||
# Get all assignments for this date/office
|
||||
assignments = db.query(DailyParkingAssignment).filter(
|
||||
DailyParkingAssignment.office_id == data.office_id,
|
||||
DailyParkingAssignment.date == target_date,
|
||||
DailyParkingAssignment.user_id.isnot(None)
|
||||
).all()
|
||||
|
||||
count = 0
|
||||
failed = 0
|
||||
|
||||
# Convert date to datetime for the existing function signature if needed, or update function
|
||||
# send_daily_parking_reminder takes datetime
|
||||
target_datetime = datetime.combine(target_date, datetime.min.time().replace(hour=8)) # default 8am
|
||||
|
||||
for assignment in assignments:
|
||||
user = db.query(User).filter(User.id == assignment.user_id).first()
|
||||
if user:
|
||||
# Force send (bypass preference check? User said "invia mail uguale a quella di promemoria")
|
||||
# We'll use the existing function but maybe bypass checks?
|
||||
# send_daily_parking_reminder checks preferences & log.
|
||||
# Let's bypass log check by deleting log first? Or just implement direct send here.
|
||||
|
||||
# User wants to "accertarsi che il sistmea funziona", so using the real function is best.
|
||||
# BUT we must ensure it sends even if already sent?
|
||||
# Let's clean logs for this specific test run first to ensure send?
|
||||
# No, better just call send_email directly with the template logic to strictly test EMAIL sending,
|
||||
# or use the function to test full LOGIC.
|
||||
# "invia una mail uguale a quella di promemoria" -> Use logic.
|
||||
|
||||
# To force send, we can modify the function or just build the email here manually like the function does.
|
||||
# Manual build is safer for a "Test Tool" to avoid messing with production logs state.
|
||||
|
||||
spot_name = get_spot_display_name(assignment.spot_id, assignment.office_id, db)
|
||||
day_name = target_date.strftime("%d/%m/%Y")
|
||||
|
||||
subject = f"Promemoria Parcheggio - {day_name} (Test)"
|
||||
body_html = f"""
|
||||
<html>
|
||||
<body>
|
||||
<h2>Promemoria Parcheggio Giornaliero</h2>
|
||||
<p>Ciao {user.name},</p>
|
||||
<p>Hai un posto auto assegnato per il giorno {day_name}:</p>
|
||||
<p style="font-size: 18px; font-weight: bold;">Posto {spot_name}</p>
|
||||
<p>Cordiali saluti,<br>Team Parking Manager</p>
|
||||
<p><em>(Email di test inviata manualmente dall'amministrazione)</em></p>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
if send_email(user.email, subject, body_html):
|
||||
count += 1
|
||||
else:
|
||||
failed += 1
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"mode": "BULK",
|
||||
"count": count,
|
||||
"failed": failed,
|
||||
"date": target_date
|
||||
}
|
||||
|
||||
# SINGLE USER TEST MODE (Existing)
|
||||
formatted_date = target_date.strftime("%d/%m/%Y")
|
||||
subject = f"Test Email - Sistema Parcheggi ({formatted_date})"
|
||||
body_html = f"""
|
||||
<html>
|
||||
<body>
|
||||
<h2>Parking System Test Email</h2>
|
||||
<p>Hi {current_user.name},</p>
|
||||
<p>This is a test email triggered from the Parking Manager Test Tools.</p>
|
||||
<p><strong>Selected Date:</strong> {target_date}</p>
|
||||
<p><strong>SMTP Status:</strong> {'Enabled' if config.SMTP_ENABLED else 'Disabled (File Logging)'}</p>
|
||||
<p>If you received this, the notification system is working.</p>
|
||||
<h2>Email di Test - Sistema Parcheggi</h2>
|
||||
<p>Ciao {current_user.name},</p>
|
||||
<p>Questa è una email di test inviata dagli strumenti di amministrazione.</p>
|
||||
<p><strong>Data Selezionata:</strong> {formatted_date}</p>
|
||||
<p><strong>Stato SMTP:</strong> {'Abilitato' if config.SMTP_ENABLED else 'Disabilitato (File Logging)'}</p>
|
||||
<p>Se hai ricevuto questa email, il sistema di notifiche funziona correttamente.</p>
|
||||
</body>
|
||||
</html>
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user