RJBULK-APP/actions/settings.ts
SJCoetz b92a5b2817 feat: send statements through Gmail SMTP
Co-Authored-By: Claude <noreply@anthropic.com>

Co-authored-by: Orca <help@stably.ai>
2026-08-03 01:06:27 +02:00

81 lines
2.7 KiB
TypeScript

"use server";
import { revalidatePath } from "next/cache";
import { z } from "zod";
import PocketBase from "pocketbase";
import { sendEmail } from "@/lib/email";
import { getAuth } from "@/lib/auth";
import { PB_URL } from "@/lib/pocketbase";
export type ActionResult = { ok: true } | { ok: false; error: string };
export async function sendTestEmail(to: string): Promise<ActionResult> {
if (!to) return { ok: false, error: "Recipient email required" };
try {
await sendEmail({
to,
subject: "RJ Bulk test email",
html: "<p>This is a test email from your RJ Bulk back-office. If you got this, email is working correctly.</p>",
});
} catch (err: any) {
return { ok: false, error: err?.message || "Send failed" };
}
return { ok: true };
}
const addUserSchema = z.object({
name: z.string().min(1, "Name is required"),
username: z.string().min(3, "Username min 3 chars"),
email: z.string().email("Valid email"),
password: z.string().min(8, "Password min 8 chars"),
});
export async function addUser(_: unknown, formData: FormData): Promise<ActionResult> {
const { token } = await getAuth();
if (!token) return { ok: false, error: "Not signed in" };
const parsed = addUserSchema.safeParse({
name: formData.get("name"),
username: formData.get("username"),
email: formData.get("email"),
password: formData.get("password"),
});
if (!parsed.success) return { ok: false, error: parsed.error.issues[0]?.message ?? "Invalid input" };
try {
// Use superuser auth for creating new auth users (PocketBase limitation)
const pb = new PocketBase(PB_URL);
await pb.admins.authWithPassword(
process.env.PB_ADMIN_EMAIL || "David.els1@outlook.com",
process.env.PB_ADMIN_PASS || "1234567890",
);
await pb.collection("users").create({
email: parsed.data.email,
username: parsed.data.username,
password: parsed.data.password,
passwordConfirm: parsed.data.password,
name: parsed.data.name,
emailVisibility: true,
verified: true,
});
} catch (err: any) {
return { ok: false, error: err?.message || "Failed to create user" };
}
revalidatePath("/settings");
return { ok: true };
}
export async function deleteUser(userId: string): Promise<ActionResult> {
const { token } = await getAuth();
if (!token) return { ok: false, error: "Not signed in" };
try {
const pb = new PocketBase(PB_URL);
await pb.admins.authWithPassword(
process.env.PB_ADMIN_EMAIL || "David.els1@outlook.com",
process.env.PB_ADMIN_PASS || "1234567890",
);
await pb.collection("users").delete(userId);
} catch (err: any) {
return { ok: false, error: err?.message || "Failed to delete" };
}
revalidatePath("/settings");
return { ok: true };
}