/*
=====================================================
CSAVE ONLINE LLC
AUTOMATIC NOTIFICATIONS + RENTAL EMAIL HISTORY
COMPLETE SUPABASE EDGE FUNCTION REPLACEMENT
Keep the existing Edge Function name and trigger.
Existing features:
- Marketplace submission notifications
- Rental submission notifications
- Admin alerts
- Customer status notifications
- Verified account email lookup
- Secure webhook authentication
- Csave branded email design
New features:
- Rental email history
- Email provider acceptance tracking
- Failed / skipped attempt tracking
- Duplicate-event protection
- Resend idempotency keys
Required existing secrets:
- CSAVE_WEBHOOK_SECRET
- RESEND_API_KEY
- SUPABASE_URL
- SUPABASE_SERVICE_ROLE_KEY
Required existing table:
- public.csave_rental_email_history
IMPORTANT:
"accepted" means Resend accepted the email request.
It does not guarantee final inbox delivery.
=====================================================
*/
const FROM_EMAIL =
"Csave Notifications ";
const ADMIN_EMAIL = "info@csave.online";
type WebhookRecord = Record;
type EmailResult = {
id?: string;
[key: string]: unknown;
};
function respond(
data: unknown,
status = 200,
): Response {
return new Response(
JSON.stringify(data),
{
status,
headers: {
"Content-Type": "application/json",
},
},
);
}
/* -----------------------------------------
SAFE TEXT AND FORMATTING
----------------------------------------- */
function safe(value: unknown): string {
return String(value ?? "")
.replace(/&/g, "&")
.replace(//g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function display(value: unknown): string {
return (
value === null ||
value === undefined ||
value === ""
)
? "Not provided"
: safe(value);
}
function validEmail(value: unknown): string | null {
if (typeof value !== "string") {
return null;
}
const email = value.trim();
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)
? email
: null;
}
function formatPrice(value: unknown): string {
if (
value === null ||
value === undefined ||
value === ""
) {
return "Not provided";
}
const amount = Number(value);
if (!Number.isFinite(amount)) {
return String(value);
}
return new Intl.NumberFormat(
"en-US",
{
style: "currency",
currency: "USD",
},
).format(amount);
}
/* -----------------------------------------
SECURE WEBHOOK AUTHENTICATION
----------------------------------------- */
async function sameSecret(
a: string,
b: string,
): Promise {
const encoder = new TextEncoder();
const left = new Uint8Array(
await crypto.subtle.digest(
"SHA-256",
encoder.encode(a),
),
);
const right = new Uint8Array(
await crypto.subtle.digest(
"SHA-256",
encoder.encode(b),
),
);
let difference = 0;
for (
let i = 0;
i < left.length;
i++
) {
difference |= left[i] ^ right[i];
}
return difference === 0;
}
/* -----------------------------------------
SERVER-ONLY SUPABASE CONNECTION
----------------------------------------- */
function getServerCredentials() {
const url = Deno.env.get("SUPABASE_URL");
const key = Deno.env.get(
"SUPABASE_SERVICE_ROLE_KEY",
);
if (!url || !key) {
throw new Error(
"Supabase server credentials missing",
);
}
return { url, key };
}
function serverHeaders(
key: string,
extra: Record = {},
) {
return {
apikey: key,
Authorization: `Bearer ${key}`,
"Content-Type": "application/json",
...extra,
};
}
/* -----------------------------------------
MEMBER EMAIL LOOKUP
Customer status emails go only to the
submitting member's verified account.
----------------------------------------- */
async function getMemberEmail(
memberId: unknown,
): Promise {
if (typeof memberId !== "string") {
return null;
}
if (
!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
.test(memberId)
) {
return null;
}
const { url, key } = getServerCredentials();
const response = await fetch(
`${url}/auth/v1/admin/users/${
encodeURIComponent(memberId)
}`,
{
headers: serverHeaders(key),
},
);
if (response.status === 404) {
return null;
}
if (!response.ok) {
throw new Error(
`Member lookup failed: ${response.status}`,
);
}
const user = await response.json();
if (!user.email_confirmed_at) {
return null;
}
return validEmail(user.email);
}
/* -----------------------------------------
CSAVE BRANDED HTML EMAIL
----------------------------------------- */
function htmlEmail(
heading: string,
subtitle: string,
message: string,
rows: [string, unknown][],
status: string,
footerMessage: string,
): string {
const details = rows
.map(
([label, value]) => `
${safe(label)}
${display(value)}
`,
)
.join("");
return `
`;
}
/* -----------------------------------------
RESEND EMAIL DELIVERY
Idempotency-Key reduces duplicate
sends during supported retry windows.
----------------------------------------- */
async function sendEmail(
resendKey: string,
recipient: string,
subject: string,
html: string,
idempotencyKey?: string,
): Promise {
const headers: Record = {
Authorization: `Bearer ${resendKey}`,
"Content-Type": "application/json",
};
if (idempotencyKey) {
headers["Idempotency-Key"] =
idempotencyKey;
}
const response = await fetch(
"https://api.resend.com/emails",
{
method: "POST",
headers,
body: JSON.stringify({
from: FROM_EMAIL,
to: [recipient],
reply_to: ADMIN_EMAIL,
subject,
html,
}),
},
);
if (!response.ok) {
console.error(
"Resend rejected notification:",
response.status,
);
throw new Error(
`Email sending request failed: ${
response.status
}`,
);
}
return await response.json();
}
/* -----------------------------------------
STABLE EVENT IDENTIFIER
Hash the webhook event contents so
the same repeated webhook can be
recognized.
Different status transitions normally
produce different event keys.
----------------------------------------- */
function canonicalJson(value: unknown): string {
if (
value === null ||
typeof value !== "object"
) {
return JSON.stringify(value) ?? "null";
}
if (Array.isArray(value)) {
return "[" +
value.map(canonicalJson).join(",") +
"]";
}
const object = value as Record;
return "{" +
Object.keys(object)
.sort()
.map(
key =>
JSON.stringify(key) +
":" +
canonicalJson(object[key]),
)
.join(",") +
"}";
}
async function eventHash(
type: string,
table: string,
record: WebhookRecord,
oldRecord: WebhookRecord | null,
): Promise {
const input = canonicalJson({
type,
table,
record,
old_record: oldRecord,
});
const digest = await crypto.subtle.digest(
"SHA-256",
new TextEncoder().encode(input),
);
return Array.from(
new Uint8Array(digest),
)
.map(
byte =>
byte.toString(16).padStart(2, "0"),
)
.join("");
}
/* -----------------------------------------
RENTAL EMAIL HISTORY STORAGE
The table is private.
Customer email history is written
only by this server-side function.
----------------------------------------- */
type HistoryInput = {
event_key: string;
rental_request_id: string;
customer_email: string | null;
notification_type: string;
request_status: string;
email_subject: string;
delivery_status: string;
provider_email_id?: string | null;
error_message?: string | null;
};
async function claimHistory(
entry: HistoryInput,
): Promise<{
claimed: boolean;
existingStatus?: string;
}> {
const { url, key } = getServerCredentials();
const response = await fetch(
`${url}/rest/v1/csave_rental_email_history`,
{
method: "POST",
headers: serverHeaders(key, {
Prefer: "return=representation",
}),
body: JSON.stringify(entry),
},
);
if (response.ok) {
return { claimed: true };
}
if (response.status === 409) {
const existing = await fetch(
`${url}/rest/v1/csave_rental_email_history` +
`?event_key=eq.${
encodeURIComponent(entry.event_key)
}` +
"&select=delivery_status",
{
headers: serverHeaders(key),
},
);
if (!existing.ok) {
throw new Error(
"Could not verify duplicate email event",
);
}
const rows = await existing.json();
if (!Array.isArray(rows) || !rows.length) {
throw new Error(
"Duplicate email history record unavailable",
);
}
return {
claimed: false,
existingStatus: rows[0].delivery_status,
};
}
console.error(
"Email history insert failed:",
response.status,
(await response.text()).slice(0, 500),
);
throw new Error(
`Unable to record email attempt: ${
response.status
}`,
);
}
async function updateHistory(
eventKey: string,
updates: {
delivery_status: string;
provider_email_id?: string | null;
error_message?: string | null;
},
): Promise {
const { url, key } = getServerCredentials();
const response = await fetch(
`${url}/rest/v1/csave_rental_email_history` +
`?event_key=eq.${
encodeURIComponent(eventKey)
}`,
{
method: "PATCH",
headers: serverHeaders(key, {
Prefer: "return=representation",
}),
body: JSON.stringify(updates),
},
);
if (!response.ok) {
console.error(
"Email history update failed:",
response.status,
);
throw new Error(
"Email history could not be finalized",
);
}
const rows = await response.json();
if (!Array.isArray(rows) || rows.length !== 1) {
throw new Error(
"Email history update was not verified",
);
}
}
/* -----------------------------------------
SERVER ENTRY POINT
----------------------------------------- */
Deno.serve(async (req: Request) => {
if (req.method !== "POST") {
return respond(
{ error: "Method not allowed" },
405,
);
}
const webhookSecret = Deno.env.get(
"CSAVE_WEBHOOK_SECRET",
);
const resendKey = Deno.env.get(
"RESEND_API_KEY",
);
if (!webhookSecret || !resendKey) {
console.error("Required secret is missing");
return respond(
{
error: "Notification service not configured",
},
503,
);
}
/* AUTHENTICATE THE EXISTING WEBHOOK */
const suppliedSecret =
req.headers.get(
"x-csave-webhook-secret",
) || "";
if (
!suppliedSecret ||
!(await sameSecret(
suppliedSecret,
webhookSecret,
))
) {
return respond(
{ error: "Unauthorized webhook" },
401,
);
}
/* VALIDATE PAYLOAD */
let payload: any;
try {
payload = await req.json();
} catch {
return respond(
{ error: "Invalid JSON" },
400,
);
}
const event = payload?.type;
const table = payload?.table;
const record = payload?.record;
const oldRecord = payload?.old_record;
if (
payload?.schema !== "public" ||
!record?.id ||
!["INSERT", "UPDATE"].includes(event)
) {
return respond(
{ error: "Invalid webhook event" },
400,
);
}
if (
table !== "marketplace_listings" &&
table !== "rental_requests"
) {
return respond(
{ error: "Unsupported table" },
400,
);
}
const isMarketplace =
table === "marketplace_listings";
const isRental =
table === "rental_requests";
const status = String(
record.status ?? "pending",
).toLowerCase();
const statusLabels: Record = {
pending: "Pending Review",
reviewing: "Under Review",
approved: "Approved",
rejected: "Not Approved",
};
const statusLabel =
statusLabels[status] || status;
const serviceName = isMarketplace
? "Marketplace Listing"
: "Rental Request";
/* SKIP UNCHANGED STATUS UPDATES */
if (event === "UPDATE") {
if (!oldRecord) {
return respond(
{ error: "Previous record missing" },
400,
);
}
if (oldRecord.status === record.status) {
return respond({
success: true,
skipped: true,
reason: "Status unchanged",
});
}
if (
![
"pending",
"reviewing",
"approved",
"rejected",
].includes(status)
) {
return respond({
success: true,
skipped: true,
reason: "Unsupported notification status",
});
}
}
/* BUILD EVENT KEY */
const hash = await eventHash(
event,
table,
record,
oldRecord ?? null,
);
const adminIdempotencyKey =
`csave-admin-${hash}`;
const customerIdempotencyKey =
`csave-customer-${hash}`;
/* ADMINISTRATOR EMAIL DETAILS */
const adminRows: [string, unknown][] =
isMarketplace
? [
["Category", record.category],
["Title", record.title],
["Description", record.description],
["City", record.city],
["State", record.state],
[
"Price",
formatPrice(record.asking_price),
],
["Status", status],
["Submission ID", record.id],
]
: [
["Customer", record.contact_name],
["Email", record.contact_email],
["Phone", record.contact_phone],
[
"Vehicle Listing ID",
record.vehicle_listing_id,
],
["Pickup Date", record.pickup_date],
["Return Date", record.return_date],
[
"Pickup Location",
record.pickup_location,
],
["Notes", record.notes],
["Status", status],
["Submission ID", record.id],
];
/* CUSTOMER EMAIL DETAILS */
const customerRows: [string, unknown][] =
isMarketplace
? [
["Listing Title", record.title],
["Category", record.category],
[
"Asking Price",
formatPrice(record.asking_price),
],
["Submission ID", record.id],
]
: [
["Pickup Date", record.pickup_date],
["Return Date", record.return_date],
[
"Pickup Location",
record.pickup_location,
],
["Submission ID", record.id],
];
const results: Record = {};
let failed = false;
/* ---------------------------------------
NEW SUBMISSION: ADMINISTRATOR ALERT
--------------------------------------- */
if (event === "INSERT") {
const adminHeading = isMarketplace
? "New Marketplace Listing"
: "New Community Car Rental Request";
const adminSubject = isMarketplace
? "Csave - New Marketplace Listing"
: "Csave - New Rental Request";
try {
results.admin = await sendEmail(
resendKey,
ADMIN_EMAIL,
adminSubject,
htmlEmail(
adminHeading,
"Administrator Notification",
"A new submission requires review.",
adminRows,
statusLabel,
"Sign in to your private Csave Admin Dashboard to review this submission.",
),
adminIdempotencyKey,
);
} catch (error) {
failed = true;
results.admin = "Failed";
console.error(
"Administrator notification failed:",
error instanceof Error
? error.message
: "Unknown error",
);
}
}
/* ---------------------------------------
VERIFIED CUSTOMER EMAIL
--------------------------------------- */
let customerEmail: string | null = null;
try {
customerEmail = await getMemberEmail(
record.member_id,
);
} catch (error) {
failed = true;
console.error(
"Customer email lookup failed:",
error instanceof Error
? error.message
: "Unknown error",
);
results.customer =
"Email lookup failed";
}
/* ---------------------------------------
CUSTOMER EMAIL CONTENT
--------------------------------------- */
let heading = "";
let message = "";
let subject = "";
if (event === "INSERT") {
heading = `${serviceName} Received`;
subject =
`Csave Online - ${serviceName} Received`;
message = isMarketplace
? "Thank you for submitting your listing to Csave Online Marketplace.\n\nWe received your submission and it is awaiting administrator review."
: "Thank you for submitting your Community Car Rental request.\n\nCsave Online has received your information and will review it.";
}
if (event === "UPDATE") {
if (status === "approved") {
heading =
`${serviceName} Approved`;
subject =
`Csave Online - ${serviceName} Approved`;
message = isMarketplace
? "Good news! Your Marketplace listing has been approved by Csave Online.\n\nYou can sign in to your account to check your listing status."
: "Good news! Your rental request has been approved for further booking arrangements.\n\nOur team will contact you regarding vehicle availability, pricing, eligibility and next steps.\n\nThis approval is not a confirmed vehicle reservation.";
}
if (status === "rejected") {
heading =
`${serviceName} Not Approved`;
subject =
`Csave Online - ${serviceName} Update`;
message = isMarketplace
? "Thank you for submitting your Marketplace listing.\n\nAfter review, your listing was not approved at this time. You may contact Csave Online for assistance or clarification."
: "Thank you for submitting your rental request.\n\nUnfortunately, your request was not approved at this time. Please contact Csave Online if you would like assistance with other rental options.";
}
if (status === "reviewing") {
heading =
`${serviceName} Under Review`;
subject =
`Csave Online - ${serviceName} Under Review`;
message =
"Your submission is currently being reviewed by the Csave Online team.\n\nWe will notify you when there is another update. Thank you for your patience.";
}
if (status === "pending") {
heading =
`${serviceName} Status Updated`;
subject =
`Csave Online - ${serviceName} Pending Review`;
message =
"Your submission has been returned to pending review.\n\nCsave Online will review your information again and notify you when a new decision has been made.";
}
}
/* ---------------------------------------
RENTAL HISTORY: CLAIM EVENT BEFORE SEND
If the same rental webhook is received
again, do not send the customer email
a second time.
An unresolved "pending" claim needs
administrator review rather than an
automatic duplicate send.
--------------------------------------- */
let rentalHistoryKey: string | null = null;
let duplicateEvent = false;
if (isRental && subject) {
rentalHistoryKey =
`rental-${hash}`;
try {
const claim = await claimHistory({
event_key: rentalHistoryKey,
rental_request_id: record.id,
customer_email: customerEmail,
notification_type:
event === "INSERT"
? "received"
: status,
request_status: status,
email_subject: subject,
delivery_status:
customerEmail
? "pending"
: "skipped",
provider_email_id: null,
error_message:
customerEmail
? null
: "Verified member email unavailable",
});
if (!claim.claimed) {
duplicateEvent = true;
results.customer =
"Skipped: event previously recorded (" +
(claim.existingStatus || "unknown") +
")";
console.log(
"Duplicate rental notification skipped:",
record.id,
status,
);
}
} catch (error) {
/*
Fail closed:
Do not send an untracked rental
notification if history cannot
be safely recorded.
*/
console.error(
"Rental email history unavailable:",
error instanceof Error
? error.message
: "Unknown error",
);
return respond(
{
success: false,
error:
"Rental notification history could not be recorded",
results,
},
502,
);
}
}
/* ---------------------------------------
SEND CUSTOMER EMAIL
--------------------------------------- */
if (
customerEmail &&
subject &&
!duplicateEvent
) {
try {
const delivery = await sendEmail(
resendKey,
customerEmail,
subject,
htmlEmail(
heading,
event === "INSERT"
? "Submission Confirmation"
: "Submission Status Update",
message,
customerRows,
statusLabel,
"Thank you for being part of the Csave Online community.",
),
customerIdempotencyKey,
);
results.customer = delivery;
/* Save accepted delivery information */
if (rentalHistoryKey) {
await updateHistory(
rentalHistoryKey,
{
delivery_status: "accepted",
provider_email_id:
delivery.id || null,
error_message: null,
},
);
}
console.log(
"Customer notification accepted:",
table,
event,
status,
);
} catch (error) {
failed = true;
const reason =
error instanceof Error
? error.message
: "Unknown error";
results.customer = "Failed";
console.error(
"Customer notification failed:",
table,
status,
reason,
);
if (rentalHistoryKey) {
try {
await updateHistory(
rentalHistoryKey,
{
delivery_status: "failed",
error_message: reason,
},
);
} catch (historyError) {
console.error(
"Unable to save failure status:",
historyError instanceof Error
? historyError.message
: "Unknown error",
);
}
}
}
} else if (
!results.customer &&
!duplicateEvent
) {
results.customer =
"Skipped: verified member email unavailable";
}
console.log(
"Csave notification processed:",
table,
event,
status,
);
return respond(
{
success: !failed,
table,
event,
status,
results,
},
failed ? 502 : 200,
);
});
CSAVE ONLINE
PRIVATE ADMIN DASHBOARD
Marketplace, Community Car Rentals & Careers
Administrator Sign In
Authorized administrators only.
0
Marketplace
0
Rental Requests
0
Career Applications
0
Pending Review
0
Approved
0
Reviewing
0
Rejected
CSAVE ONLINE
PRIVATE RENTAL ADMINISTRATION
VERSION 17 — RENTAL PROVIDER VERIFICATION
Business • Insurance • Authorization • Review
Verification requires independent review of
authentic business and insurance documents.
Checking a box only records an administrator's
review. It does not prove coverage or authorize
a vehicle to be rented.
This dashboard does not confirm bookings.
Administrator Sign In
0
Provider Applications
0
Approved Applications
0
Currently Verified
0
Needs Review / Attention
Find a Rental Provider
CSAVE ONLINE
PRIVATE RENTAL ADMINISTRATION
VERSION 17 — RENTAL PROVIDER VERIFICATION
& PRIVATE DOCUMENT MANAGEMENT
Business • Insurance • Authorization • Documents • Review
Verification requires independent review
of authentic business, insurance, and
vehicle authorization documents.
Uploading a file or checking a box does
not independently prove insurance coverage,
ownership, authorization, or rental eligibility.
This dashboard does not confirm bookings.
Administrator Sign In
0
Provider Applications
0
Approved Applications
0
Currently Verified
0
Needs Review / Attention
Find a Rental Provider
CSAVE ONLINE LLC
WELCOME TO
TREASURE CITY
Discover a new world of community, opportunities, rewards and connections. Your journey starts here.
🧰💰
EXPLORE YOUR CITY
One community. Multiple opportunities. Discover what Csave Online has to offer.
Marketplace
Discover items, vehicles, jobs, services and entertainment listings.
Explore MarketplaceCsave Rewards
Turn Your Time Into Rewards. Integration and testing in progress.
COMING SOONVehicle Rentals
Explore vehicle rental opportunities through participating providers.
Explore Rentals
MEMBERSHIP NOTICE
Csave Online is intended for adults aged 18 and older. Availability of features may vary. Csave Online is not a bank, does not offer FDIC-insured deposits, and does not guarantee earnings or financial returns.
Csave Online is intended for adults aged 18 and older. Availability of features may vary. Csave Online is not a bank, does not offer FDIC-insured deposits, and does not guarantee earnings or financial returns.