Files
xbcr/rental_mail.py
T

453 lines
20 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""租车提醒邮件与无登录还车能力链接。"""
import datetime as dt
import hashlib
import html
import json
import os
import secrets
from pathlib import Path
from db import get_db, get_user_rental_settings
from email_utils import send_email
TOKEN_TTL_HOURS = 24
CONFIG_PATH = Path(__file__).parent / "server_config.json"
def _utc_now():
return dt.datetime.now(dt.timezone.utc)
def _time_str(value):
return value.astimezone(dt.timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
def _token_hash(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()
def _public_base_url() -> str:
env_url = os.environ.get("XBNEW_PUBLIC_BASE_URL", "").strip()
if env_url:
return env_url.rstrip("/")
try:
data = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
return str(data.get("public_base_url") or "").strip().rstrip("/")
except (OSError, ValueError, TypeError):
return ""
def create_return_token(rental_id: int) -> str:
"""创建一个短期能力令牌;数据库中只存摘要。"""
token = secrets.token_urlsafe(32)
expires_at = _utc_now() + dt.timedelta(hours=TOKEN_TTL_HOURS)
conn = get_db()
conn.execute("""
INSERT INTO rental_return_tokens (rental_id, token_hash, expires_at)
VALUES (?, ?, ?)
""", (rental_id, _token_hash(token), _time_str(expires_at)))
conn.commit()
conn.close()
return token
def resolve_return_token(token: str):
"""验证 token,返回 (status, rental)。status: valid/used/expired/finished/invalid。"""
if not token or len(token) > 200:
return "invalid", None
conn = get_db()
row = conn.execute("""
SELECT t.used_at, t.expires_at, r.*
FROM rental_return_tokens t
JOIN rentals r ON r.id = t.rental_id
WHERE t.token_hash = ?
LIMIT 1
""", (_token_hash(token),)).fetchone()
conn.close()
if not row:
return "invalid", None
rental = dict(row)
if row["used_at"]:
return "used", rental
try:
expires = dt.datetime.strptime(row["expires_at"], "%Y-%m-%d %H:%M:%S").replace(
tzinfo=dt.timezone.utc
)
except (TypeError, ValueError):
return "invalid", None
if expires <= _utc_now():
return "expired", rental
if rental.get("expired"):
return "finished", rental
return "valid", rental
def mark_return_tokens_used(rental_id: int):
"""还车成功后作废该订单所有历史邮件链接。"""
conn = get_db()
conn.execute("""
UPDATE rental_return_tokens
SET used_at = COALESCE(used_at, ?)
WHERE rental_id = ?
""", (_time_str(_utc_now()), rental_id))
conn.commit()
conn.close()
def _display_name(email: str) -> str:
if not email:
return "未知用户"
return email.split("@", 1)[0] or email
def get_rental_mail_context(rental_id: int):
conn = get_db()
row = conn.execute("""
SELECT r.*, owner.email AS owner_email, rider.email AS rider_email
FROM rentals r
LEFT JOIN users owner ON owner.id = r.user_id
LEFT JOIN users rider ON rider.id = r.rider_user_id
WHERE r.id = ?
""", (rental_id,)).fetchone()
if not row:
conn.close()
return None
result = dict(row)
result["owner_remark"] = ""
result["rider_remark"] = ""
if result.get("rider_user_id") and result.get("rider_user_id") != result.get("user_id"):
share = conn.execute("""
SELECT owner_remark, rider_remark FROM shares
WHERE owner_user_id = ? AND rider_user_id = ?
ORDER BY id DESC LIMIT 1
""", (result["user_id"], result["rider_user_id"])).fetchone()
if share:
result["owner_remark"] = share["owner_remark"] or ""
result["rider_remark"] = share["rider_remark"] or ""
conn.close()
return result
def _render_html(title: str, lead: str, details, button_url: str, urgent=False):
accent = "#dc2626" if urgent else "#2563eb"
rows = "".join(
'<tr><td style="padding:8px 0;color:#64748b;width:92px;vertical-align:top">{}</td>'
'<td style="padding:8px 0;color:#0f172a;font-weight:600">{}</td></tr>'.format(
html.escape(str(label)), html.escape(str(value))
)
for label, value in details
)
button = ""
if button_url:
safe_url = html.escape(button_url, quote=True)
button = f"""
<div style="margin:28px 0 12px;text-align:center">
<a href="{safe_url}" style="display:inline-block;background:{accent};color:#fff;text-decoration:none;
padding:13px 34px;border-radius:10px;font-weight:700;font-size:16px">立即还车</a>
</div>
<p style="margin:10px 0 0;color:#94a3b8;font-size:12px;line-height:1.7">
链接含有一次性还车凭证,24 小时内有效。请勿转发给他人。点击后仍需手动确认,不会直接还车。
</p>"""
return f"""<!doctype html>
<html><body style="margin:0;background:#f1f5f9;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Microsoft YaHei',sans-serif">
<div style="max-width:600px;margin:0 auto;padding:30px 14px">
<div style="background:#fff;border-radius:18px;overflow:hidden;box-shadow:0 8px 30px rgba(15,23,42,.08)">
<div style="height:6px;background:{accent}"></div>
<div style="padding:30px">
<div style="font-size:13px;color:{accent};font-weight:800;letter-spacing:.08em">小白超人·用车提醒</div>
<h1 style="margin:10px 0 12px;font-size:25px;line-height:1.35;color:#0f172a">{html.escape(title)}</h1>
<p style="margin:0 0 22px;color:#475569;font-size:15px;line-height:1.8">{html.escape(lead)}</p>
<table role="presentation" style="width:100%;border-collapse:collapse;background:#f8fafc;border-radius:12px;padding:12px">
{rows}
</table>
{button}
</div>
</div>
<p style="text-align:center;color:#94a3b8;font-size:12px;margin:18px 0">这是系统自动发送的用车通知。</p>
</div>
</body></html>"""
def send_rental_notification(rental_id: int, reminder_type: str, return_result=None):
"""按订单关系生成个性化邮件;共享订单分别发给双方。"""
rental = get_rental_mail_context(rental_id)
if not rental:
return []
owner_email = rental.get("owner_email") or rental.get("email")
rider_email = rental.get("rider_email")
is_shared = bool(rider_email and rental.get("rider_user_id") != rental.get("user_id"))
owner_name = _display_name(owner_email)
rider_name = _display_name(rider_email)
bike_code = rental.get("bike_code") or "--"
order_id = rental.get("order_id") or rental_id
recipients = []
if is_shared:
recipients.append({
"email": owner_email,
"user_id": rental.get("user_id"),
"role": "owner",
"subject_identity": rental.get("owner_remark") or rider_name,
"lead": f"{rental.get('owner_remark') or rider_name} 正在骑行你的共享车。",
"details": [("车辆归属", f"你({owner_email})"),
("当前骑行人", f"{rental.get('owner_remark') or rider_name}({rider_email})")],
})
recipients.append({
"email": rider_email,
"user_id": rental.get("rider_user_id"),
"role": "rider",
"subject_identity": rental.get("rider_remark") or owner_name,
"lead": f"你正在骑行 {rental.get('rider_remark') or owner_name} 的共享车。",
"details": [("车辆归属", f"{rental.get('rider_remark') or owner_name}({owner_email})"),
("当前骑行人", f"你({rider_email})")],
})
else:
recipients.append({
"email": owner_email,
"user_id": rental.get("user_id"),
"role": "rider",
"subject_identity": "",
"lead": "你当前的用车订单即将到期,请及时安排还车。",
"details": [("当前骑行人", f"你({owner_email})")],
})
results = []
base_url = _public_base_url()
auto_success = bool(return_result and return_result.get("success"))
auto_attempted = bool(return_result is not None and return_result.get("attempted", True))
for recipient in recipients:
if not recipient["email"]:
continue
settings = get_user_rental_settings(recipient.get("user_id"))
try:
reminder_minute = int(reminder_type)
except (TypeError, ValueError):
reminder_minute = None
if (not settings["reminder_enabled"] or
reminder_minute not in settings["reminder_minutes"]):
continue
details = list(recipient["details"])
details.extend([("车辆编号", f"#{bike_code}"), ("订单编号", str(order_id))])
can_remote_return = bool(rental.get("order_id") and rental.get("source") != "reminder")
if reminder_type == "0":
if auto_success:
title = "已自动还车"
lead = recipient["lead"] + " 免费时长到期,系统已确认还车成功。"
subject = f"【小白超人】车辆 #{bike_code} 已自动还车"
urgent = False
button_url = ""
elif auto_attempted:
title = "自动还车失败"
error = (return_result or {}).get("message") or "上游还车接口未确认成功"
lead = recipient["lead"] + " 免费时长已到期,系统自动还车失败,请立即处理。"
details.append(("失败原因", error))
subject = f"【小白超人·紧急】车辆 #{bike_code} 自动还车失败"
urgent = True
token = create_return_token(rental_id) if can_remote_return else ""
button_url = f"{base_url}/rental/email-return#token={token}" if base_url and token else ""
else:
title = "免费时长已到期"
reason = (return_result or {}).get("message") or "未执行自动还车"
if reason == "用户未开启自动还车":
action_text = "你未开启自动还车,请及时手动还车。"
else:
action_text = "该计时未关联可自动还车的微信订单,请及时手动还车。"
lead = recipient["lead"] + " 免费时长已到期," + action_text
subject = f"【小白超人】车辆 #{bike_code} 免费时长已到期,请手动还车"
urgent = True
token = create_return_token(rental_id) if can_remote_return else ""
button_url = f"{base_url}/rental/email-return#token={token}" if base_url and token else ""
else:
minutes = int(reminder_type)
title = f"免费时长还剩 {minutes} 分钟"
lead = recipient["lead"] + f" 免费时长还剩 {minutes} 分钟。"
identity = f"·{recipient['subject_identity']}" if recipient["subject_identity"] else ""
subject = f"【小白超人】共享用车{identity}还剩 {minutes} 分钟" if is_shared \
else f"【小白超人】用车还剩 {minutes} 分钟"
urgent = minutes <= 3
token = create_return_token(rental_id) if can_remote_return else ""
button_url = f"{base_url}/rental/email-return#token={token}" if base_url and token else ""
plain_details = "\n".join(f"{k}:{v}" for k, v in details)
plain = f"{title}\n\n{lead}\n\n{plain_details}"
if button_url:
plain += f"\n\n立即还车(点击后需再确认):\n{button_url}\n\n请勿转发此链接。"
html_body = _render_html(title, lead, details, button_url, urgent)
results.append(send_email(recipient["email"], subject, plain, html_body))
return results
# =====================================================================
# 共享/订阅等通用通知邮件
# =====================================================================
def _render_notice_html(kicker, title, lead, details, button_url="", accent="#2563eb"):
"""通用通知邮件模板(申请/开始使用/还车播报共用)。"""
rows = "".join(
'<tr><td style="padding:8px 0;color:#64748b;width:110px;vertical-align:top">{}</td>'
'<td style="padding:8px 0;color:#0f172a;font-weight:600">{}</td></tr>'.format(
html.escape(str(label)), html.escape(str(value)))
for label, value in details)
button = ""
if button_url:
safe_url = html.escape(button_url, quote=True)
button = f"""
<div style="margin:28px 0 12px;text-align:center">
<a href="{safe_url}" style="display:inline-block;background:{accent};color:#fff;text-decoration:none;
padding:13px 34px;border-radius:10px;font-weight:700;font-size:16px">打开处理</a>
</div>"""
return f"""<!doctype html>
<html><body style="margin:0;background:#f1f5f9;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI','Microsoft YaHei',sans-serif">
<div style="max-width:600px;margin:0 auto;padding:30px 14px">
<div style="background:#fff;border-radius:18px;overflow:hidden;box-shadow:0 8px 30px rgba(15,23,42,.08)">
<div style="height:6px;background:{accent}"></div>
<div style="padding:30px">
<div style="font-size:13px;color:{accent};font-weight:800;letter-spacing:.08em">{html.escape(kicker)}</div>
<h1 style="margin:10px 0 12px;font-size:24px;line-height:1.35;color:#0f172a">{html.escape(title)}</h1>
<p style="margin:0 0 22px;color:#475569;font-size:15px;line-height:1.8">{html.escape(lead)}</p>
<table role="presentation" style="width:100%;border-collapse:collapse;background:#f8fafc;border-radius:12px;padding:12px">
{rows}
</table>
{button}
</div>
</div>
<p style="text-align:center;color:#94a3b8;font-size:12px;margin:18px 0">这是系统自动发送的通知邮件。</p>
</div>
</body></html>"""
def _send_notice(to_email, subject, title, lead, details, button_url="", accent="#2563eb"):
if not to_email:
return False
plain = f"{title}\n\n{lead}\n\n" + "\n".join(f"{k}:{v}" for k, v in details)
if button_url:
plain += f"\n\n打开处理:\n{button_url}"
return send_email(to_email, subject, plain,
_render_notice_html("小白超人 · 共享电动车", title, lead,
details, button_url, accent))
def send_share_request_email(owner_user_id: int, from_name: str, from_email: str):
"""P1.7 共享申请离线通知:有人申请共享你的电动车。"""
from db import get_user_alert_email
to_email = get_user_alert_email(owner_user_id)
if not to_email:
return False
base_url = _public_base_url()
title = f"{from_name} 申请共享你的电动车"
lead = "对方接受后即可在你不在用车时,用你的共享额度开锁用车(受每日次数与优惠卡规则约束)。"
details = [("申请人", f"{from_name}({from_email})"),
("通知时间", dt.datetime.now(dt.timezone(dt.timedelta(hours=8))).strftime("%Y-%m-%d %H:%M"))]
button_url = f"{base_url}/#profile" if base_url else ""
return _send_notice(to_email, f"【小白超人】{title}", title, lead, details, button_url)
def send_share_started_email(rental_id: int, owner_user_id: int, rider_user_id: int,
bike_code: str, latitude, longitude,
duration_minutes: int, used_today: int, daily_limit: int):
"""P1.8 被使用提醒(发给车主):昵称(邮箱)已开始使用你的电动车 + 车辆位置。"""
from db import (get_user_alert_email, get_user_display_name)
rider_email = _display_name_owner_email(owner_user_id, rider_user_id)
if not rider_email:
return False
# 车主给骑行者起的私密备注优先
owner_remark = ""
conn = get_db()
shr = conn.execute("""
SELECT owner_remark FROM shares
WHERE owner_user_id = ? AND rider_user_id = ?
ORDER BY id DESC LIMIT 1
""", (owner_user_id, rider_user_id)).fetchone()
if shr and shr["owner_remark"]:
owner_remark = shr["owner_remark"]
conn.close()
rider_display = get_user_display_name(rider_user_id)
rider_label = owner_remark or rider_display
from campus import resolve_location_label
location = resolve_location_label(latitude, longitude) or "位置未知(坐标已记录)"
tz = dt.timezone(dt.timedelta(hours=8))
now_str = dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M")
title = f"{rider_label}({rider_email})已开始使用你的电动车"
lead = "共享开锁成功,本次用车时长按骑行者设置计时,到期会自动还车并用你的优惠卡支付。"
details = [("车辆编号", f"#{bike_code}"),
("当前骑行人", f"{rider_label}({rider_email})"),
("开锁位置", location),
("本轮时长", f"{duration_minutes} 分钟"),
("今日已用", f"{used_today} 次" + (f" / 上限 {daily_limit}" if daily_limit else "")),
("开始时间", now_str)]
to_email = get_user_alert_email(owner_user_id)
return _send_notice(to_email, f"【小白超人】{title}", title, lead, details)
def send_share_returned_email(rental_id: int, order_id, owner_user_id: int,
rider_user_id, bike_code: str,
latitude, longitude):
"""P1.8 还车播报(双方):从哪里骑到哪里 + 实际用时。"""
from db import (get_user_alert_email, get_user_display_name)
ctx = get_rental_mail_context(rental_id) or {}
owner_email = ctx.get("owner_email") or _display_name_owner_email(owner_user_id, owner_user_id)
rider_email = ctx.get("rider_email") or (
_display_name_owner_email(owner_user_id, rider_user_id) if rider_user_id else "")
owner_remark = ctx.get("owner_remark") or ""
rider_remark = ctx.get("rider_remark") or ""
from campus import resolve_location_label
end_location = resolve_location_label(latitude, longitude)
start_location = ctx.get("start_label") or None
if not end_location and latitude is not None:
end_location = "位置未知(坐标已记录)"
tz = dt.timezone(dt.timedelta(hours=8))
end_str = ctx.get("returned_at") or dt.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
duration_text = "--"
if ctx.get("start_time"):
try:
s = dt.datetime.strptime(ctx["start_time"], "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz)
e = dt.datetime.strptime(end_str, "%Y-%m-%d %H:%M:%S").replace(tzinfo=tz)
total_min = max(int((e - s).total_seconds() // 60), 0)
duration_text = f"{total_min // 60} 小时 {total_min % 60} 分钟" if total_min >= 60 \
else f"{total_min} 分钟"
except (TypeError, ValueError):
pass
route = f"{start_location or '起点未知'} → {end_location or '终点未知'}"
title = f"车辆 #{bike_code} 已还车"
lead = f"本次骑行路线:{route}。"
base_details = [("车辆编号", f"#{bike_code}"),
("骑行路线", route),
("实际用时", duration_text),
("还车时间", end_str),
("订单编号", str(order_id or rental_id))]
results = []
owner_to = get_user_alert_email(owner_user_id)
if owner_to:
details = list(base_details)
details.insert(1, ("骑行人", f"{owner_remark or get_user_display_name(rider_user_id) or '--'}({rider_email or '--'})"))
results.append(_send_notice(owner_to, f"【小白超人】共享车辆 {title}:{route}",
title, lead, details))
if rider_user_id and rider_email:
rider_to = get_user_alert_email(rider_user_id)
if rider_to:
details = list(base_details)
details.insert(1, ("车辆归属", f"{rider_remark or get_user_display_name(owner_user_id) or '--'}({owner_email or '--'})"))
results.append(_send_notice(rider_to, f"【小白超人】{title}:{route}",
title, lead, details))
return results
def _display_name_owner_email(owner_user_id: int, target_user_id: int):
"""查某用户邮箱(查询失败返回 None)。"""
if not target_user_id:
return None
conn = get_db()
row = conn.execute("SELECT email FROM users WHERE id = ?", (target_user_id,)).fetchone()
conn.close()
return row["email"] if row else None