Create monorepo from known-good production state
This commit is contained in:
commit
c034824338
651 changed files with 120469 additions and 0 deletions
102
app/lib/auth-cookies.ts
Normal file
102
app/lib/auth-cookies.ts
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
// app/lib/auth-cookies.ts
|
||||
import { NextResponse } from "next/server";
|
||||
|
||||
export type TokenBundle = {
|
||||
access_token: string;
|
||||
refresh_token?: string;
|
||||
/** seconds until expiration (Directus style) */
|
||||
expires?: number;
|
||||
};
|
||||
|
||||
export type PublicUser = {
|
||||
id: string;
|
||||
email: string;
|
||||
username: string;
|
||||
};
|
||||
|
||||
const ACCESS_COOKIE = "ma_at";
|
||||
const REFRESH_COOKIE = "ma_rt";
|
||||
const USER_COOKIE = "ma_user";
|
||||
|
||||
/** Derive cookie maxAge (in seconds) for access token */
|
||||
function accessMaxAgeSec(expires?: number) {
|
||||
// If Directus gave us seconds-until-expiration, use that (clamped)
|
||||
if (typeof expires === "number" && Number.isFinite(expires)) {
|
||||
return Math.max(60, Math.min(expires, 60 * 60 * 24)); // 1 min .. 1 day
|
||||
}
|
||||
// Fallback: 1 hour
|
||||
return 60 * 60;
|
||||
}
|
||||
|
||||
/** Refresh token lifetime: default ~30 days if present */
|
||||
function refreshMaxAgeSec() {
|
||||
return 60 * 60 * 24 * 30;
|
||||
}
|
||||
|
||||
/** Shared secure cookie options (override per cookie when needed) */
|
||||
function baseOpts(maxAge: number) {
|
||||
return {
|
||||
httpOnly: true as const,
|
||||
sameSite: "lax" as const,
|
||||
secure: true,
|
||||
path: "/",
|
||||
maxAge,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Set auth cookies on the provided response.
|
||||
* Returns the SAME response instance with cookies set (typed generically).
|
||||
*/
|
||||
export function setAuthCookies<T>(
|
||||
res: NextResponse<T>,
|
||||
tokens: TokenBundle,
|
||||
user?: PublicUser
|
||||
): NextResponse<T> {
|
||||
// Access token (httpOnly)
|
||||
const atAge = accessMaxAgeSec(tokens.expires);
|
||||
res.cookies.set(ACCESS_COOKIE, tokens.access_token, baseOpts(atAge));
|
||||
|
||||
// Refresh token (httpOnly) if present
|
||||
if (tokens.refresh_token) {
|
||||
res.cookies.set(REFRESH_COOKIE, tokens.refresh_token, baseOpts(refreshMaxAgeSec()));
|
||||
}
|
||||
|
||||
// Small readable user stub (NOT httpOnly) so client can reflect UI state if desired
|
||||
if (user) {
|
||||
const safeStub = JSON.stringify({
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
});
|
||||
res.cookies.set(USER_COOKIE, safeStub, {
|
||||
...baseOpts(atAge),
|
||||
httpOnly: false, // readable on client
|
||||
});
|
||||
}
|
||||
|
||||
return res;
|
||||
}
|
||||
|
||||
/** Clear all auth cookies (returns the SAME response instance) */
|
||||
export function clearAuthCookies<T>(res: NextResponse<T>): NextResponse<T> {
|
||||
const opts = {
|
||||
httpOnly: true as const,
|
||||
sameSite: "lax" as const,
|
||||
secure: true,
|
||||
path: "/",
|
||||
maxAge: 0,
|
||||
};
|
||||
res.cookies.set(ACCESS_COOKIE, "", opts);
|
||||
res.cookies.set(REFRESH_COOKIE, "", opts);
|
||||
// Also clear public user stub
|
||||
res.cookies.set(USER_COOKIE, "", { ...opts, httpOnly: false });
|
||||
return res;
|
||||
}
|
||||
|
||||
/** (Optional) Simple helpers if you ever want the names elsewhere */
|
||||
export const AUTH_COOKIE_KEYS = {
|
||||
access: ACCESS_COOKIE,
|
||||
refresh: REFRESH_COOKIE,
|
||||
user: USER_COOKIE,
|
||||
};
|
||||
250
app/lib/directus.ts
Normal file
250
app/lib/directus.ts
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
// lib/directus.ts
|
||||
// Central Directus helpers used by API routes. (user bearer only)
|
||||
|
||||
// ⚠️ NOTE: Do NOT import `headers()` / `cookies()` from "next/headers" here.
|
||||
// Next 15's types can make those async and break build-time type checks in shared libs.
|
||||
|
||||
const BASE = (process.env.DIRECTUS_URL || "").replace(/\/$/, "");
|
||||
const TOKEN_ADMIN_REGISTER = process.env.DIRECTUS_TOKEN_ADMIN_REGISTER || ""; // server-only
|
||||
const ROLE_MEMBER_NAME = process.env.DIRECTUS_ROLE_MEMBER_NAME || "Users";
|
||||
const PROJECTS_COLLECTION = process.env.DIRECTUS_PROJECTS_COLLECTION || "projects";
|
||||
|
||||
if (!BASE) console.warn("[directus] Missing DIRECTUS_URL");
|
||||
if (!TOKEN_ADMIN_REGISTER)
|
||||
console.warn("[directus] Missing DIRECTUS_TOKEN_ADMIN_REGISTER (used for registration)");
|
||||
|
||||
export function bytesFromMB(mb: number) {
|
||||
return Math.round(mb * 1024 * 1024);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the user's Directus bearer token from the **incoming Request**.
|
||||
* Looks at:
|
||||
* 1) Authorization: Bearer ...
|
||||
* 2) Raw Cookie header for ma_at / ma_at_beta / ma_session
|
||||
*
|
||||
* We intentionally avoid `next/headers` helpers here to keep this library
|
||||
* compatible with Next 15's stricter type checks.
|
||||
*/
|
||||
export function getUserBearerFromRequest(req?: Request): string | null {
|
||||
if (!req) return null;
|
||||
|
||||
// 1) Authorization header (supports server-to-server/proxy calls)
|
||||
const hAuth = req.headers.get("authorization");
|
||||
if (hAuth?.startsWith("Bearer ")) return hAuth.slice(7);
|
||||
|
||||
// 2) Raw Cookie header (plain Request)
|
||||
const raw = req.headers.get("cookie") ?? "";
|
||||
if (raw) {
|
||||
const map = Object.fromEntries(
|
||||
raw.split(/;\s*/).map((p) => {
|
||||
const [k, ...v] = p.split("=");
|
||||
return [decodeURIComponent(k), decodeURIComponent(v.join("=") || "")];
|
||||
})
|
||||
);
|
||||
const t = map["ma_at"] || map["ma_at_beta"] || map["ma_session"];
|
||||
if (t) return String(t);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// Low-level helpers (bearer REQUIRED; no fallbacks)
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
|
||||
function authHeaders(bearer: string, extra?: HeadersInit): HeadersInit {
|
||||
return { Accept: "application/json", Authorization: `Bearer ${bearer}`, ...extra };
|
||||
}
|
||||
|
||||
async function parseJsonSafe(res: Response) {
|
||||
const text = await res.text();
|
||||
let json: any = null;
|
||||
try {
|
||||
json = text ? JSON.parse(text) : null;
|
||||
} catch {}
|
||||
return { json, text };
|
||||
}
|
||||
|
||||
async function throwIfNotOk(res: Response) {
|
||||
const { json, text } = await parseJsonSafe(res);
|
||||
if (!res.ok) {
|
||||
const err: any = new Error(`Directus ${res.status}: ${text || res.statusText}`);
|
||||
err.status = res.status;
|
||||
err.detail = json ?? text;
|
||||
throw err;
|
||||
}
|
||||
return json;
|
||||
}
|
||||
|
||||
export async function dxGET<T = any>(path: string, bearer: string): Promise<T> {
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
headers: authHeaders(bearer),
|
||||
cache: "no-store",
|
||||
});
|
||||
return (await throwIfNotOk(res)) as T;
|
||||
}
|
||||
|
||||
export async function dxPOST<T = any>(path: string, bearer: string, body: any): Promise<T> {
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
method: "POST",
|
||||
headers: authHeaders(bearer, { "content-type": "application/json" }),
|
||||
body: JSON.stringify(body),
|
||||
cache: "no-store",
|
||||
});
|
||||
return (await throwIfNotOk(res)) as T;
|
||||
}
|
||||
|
||||
export async function dxPATCH<T = any>(path: string, bearer: string, body: any): Promise<T> {
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
method: "PATCH",
|
||||
headers: authHeaders(bearer, { "content-type": "application/json" }),
|
||||
body: JSON.stringify(body),
|
||||
cache: "no-store",
|
||||
});
|
||||
return (await throwIfNotOk(res)) as T;
|
||||
}
|
||||
|
||||
export async function dxDELETE<T = any>(path: string, bearer: string): Promise<T> {
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
method: "DELETE",
|
||||
headers: authHeaders(bearer),
|
||||
cache: "no-store",
|
||||
});
|
||||
return (await throwIfNotOk(res)) as T;
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// Server-only admin fetch (registration flows, etc.)
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function directusAdminFetch<T = any>(path: string, init?: RequestInit): Promise<T> {
|
||||
if (!TOKEN_ADMIN_REGISTER) throw new Error("Missing DIRECTUS_TOKEN_ADMIN_REGISTER");
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
...init,
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${TOKEN_ADMIN_REGISTER}`,
|
||||
...(init?.headers || {}),
|
||||
},
|
||||
cache: "no-store",
|
||||
});
|
||||
return (await throwIfNotOk(res)) as T;
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
// Files & items — user bearer ONLY (no folder listing/browsing)
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function uploadFile(
|
||||
file: Blob | File,
|
||||
filename: string,
|
||||
bearer: string,
|
||||
options?: { folderId?: string; title?: string }
|
||||
): Promise<{ id: string }> {
|
||||
const form = new FormData();
|
||||
form.set("file", file, filename);
|
||||
form.set("filename_download", filename);
|
||||
if (options?.title) form.set("title", options.title);
|
||||
if (options?.folderId) form.set("folder", options.folderId); // user-scoped
|
||||
|
||||
const res = await fetch(`${BASE}/files`, {
|
||||
method: "POST",
|
||||
headers: authHeaders(bearer),
|
||||
body: form,
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
const json = await throwIfNotOk(res);
|
||||
const id = json?.data?.id ?? json?.id;
|
||||
if (!id) throw new Error("File upload succeeded but no id returned");
|
||||
return { id: String(id) };
|
||||
}
|
||||
|
||||
export async function createSettingsItem(
|
||||
collection: string,
|
||||
payload: any,
|
||||
bearer: string
|
||||
): Promise<{ data: { id: string } }> {
|
||||
// Note: callers are already using { data: ... } patterns when needed.
|
||||
return dxPOST<{ data: { id: string } }>(`/items/${collection}`, bearer, payload);
|
||||
}
|
||||
|
||||
export async function createProjectRow(
|
||||
payload: any,
|
||||
bearer: string
|
||||
): Promise<{ data: { id: string } }> {
|
||||
return dxPOST<{ data: { id: string } }>(`/items/${PROJECTS_COLLECTION}`, bearer, payload);
|
||||
}
|
||||
|
||||
export async function patchProject(
|
||||
id: string | number,
|
||||
payload: any,
|
||||
bearer: string
|
||||
): Promise<{ data: { id: string } }> {
|
||||
return dxPATCH<{ data: { id: string } }>(`/items/${PROJECTS_COLLECTION}/${id}`, bearer, payload);
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
/** Auth helpers (registration / login support) */
|
||||
// ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function resolveMemberRoleId(): Promise<string> {
|
||||
const name = ROLE_MEMBER_NAME;
|
||||
const q = `/roles?filter[name][_eq]=${encodeURIComponent(name)}&fields=id,name&limit=1`;
|
||||
const { data } = await directusAdminFetch<{ data: Array<{ id: string }> }>(q);
|
||||
const hit = data?.[0]?.id;
|
||||
if (!hit) throw new Error(`Role not found: ${name}`);
|
||||
return hit;
|
||||
}
|
||||
|
||||
/** Registrations always create a 'Users' role account. No overrides. */
|
||||
export async function createDirectusUser(input: {
|
||||
username: string;
|
||||
password: string;
|
||||
email?: string;
|
||||
}): Promise<{ id: string }> {
|
||||
const role = await resolveMemberRoleId();
|
||||
|
||||
// If email is omitted, create a stable placeholder so login can still work.
|
||||
const email =
|
||||
input.email && input.email.trim()
|
||||
? input.email.trim()
|
||||
: `${input.username}@noemail.local`;
|
||||
|
||||
// System endpoint `/users` expects raw fields (no { data } wrapper).
|
||||
const res = await directusAdminFetch<{ data?: { id?: string } }>(`/users`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
status: "active",
|
||||
role,
|
||||
username: input.username,
|
||||
email,
|
||||
password: input.password,
|
||||
}),
|
||||
});
|
||||
|
||||
const id = res?.data?.id as string | undefined;
|
||||
if (!id) throw new Error("User create succeeded but no id returned");
|
||||
return { id: String(id) };
|
||||
}
|
||||
|
||||
export async function emailForUsername(username: string): Promise<string | null> {
|
||||
const q = `/users?filter[username][_eq]=${encodeURIComponent(username)}&fields=email&limit=1`;
|
||||
const { data } = await directusAdminFetch<{ data: Array<{ email?: string }> }>(q);
|
||||
const em = data?.[0]?.email;
|
||||
return em ? String(em) : null;
|
||||
}
|
||||
|
||||
export async function loginDirectus(email: string, password: string) {
|
||||
const res = await fetch(`${BASE}/auth/login`, {
|
||||
method: "POST",
|
||||
headers: { Accept: "application/json", "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ email, password }),
|
||||
cache: "no-store",
|
||||
});
|
||||
const json = await throwIfNotOk(res);
|
||||
// Directus typically returns { data: { access_token, refresh_token, expires } }
|
||||
return json?.data ?? json;
|
||||
}
|
||||
15
app/lib/jwt.ts
Normal file
15
app/lib/jwt.ts
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
// lib/jwt.ts
|
||||
export function jwtExp(token?: string | null): number | null {
|
||||
if (!token) return null;
|
||||
try {
|
||||
const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64").toString("utf8"));
|
||||
return typeof payload?.exp === "number" ? payload.exp : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function isJwtValid(token?: string | null): boolean {
|
||||
const exp = jwtExp(token);
|
||||
return !!exp && exp * 1000 > Date.now();
|
||||
}
|
||||
187
app/lib/laser-finder.ts
Normal file
187
app/lib/laser-finder.ts
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
// lib/laser-finder.ts
|
||||
export type LaserType = "fiber" | "co2_gantry" | "co2_galvo" | "uv";
|
||||
|
||||
export const LASER_LABEL: Record<LaserType, string> = {
|
||||
fiber: "Fiber (MOPA/QR)",
|
||||
co2_gantry: "CO₂ Gantry",
|
||||
co2_galvo: "CO₂ Galvo",
|
||||
uv: "UV (355 nm)",
|
||||
};
|
||||
|
||||
export const TYPE_INFO: Record<
|
||||
LaserType,
|
||||
{
|
||||
summary: string;
|
||||
bestFor: string[]; // show as tags
|
||||
materials: string[]; // show as tags
|
||||
cautions: string[]; // negatives / limits
|
||||
learnLink: string; // link to your settings pages
|
||||
}
|
||||
> = {
|
||||
fiber: {
|
||||
summary:
|
||||
"Best for marking/engraving bare metals, color marking on stainless (MOPA), and high-throughput galvo jobs.",
|
||||
bestFor: [
|
||||
"Bare metal marking",
|
||||
"Deep engraving on metals",
|
||||
"Color marking stainless",
|
||||
"Serials/QR/codes on parts",
|
||||
],
|
||||
materials: ["Steel", "Stainless", "Aluminum", "Brass", "Titanium"],
|
||||
cautions: [
|
||||
"Not for cutting wood/acrylic",
|
||||
"Limited on organics/plastics (unless additives/coatings)",
|
||||
],
|
||||
learnLink: "/fiber-settings",
|
||||
},
|
||||
co2_gantry: {
|
||||
summary:
|
||||
"Large work area; best for cutting & engraving non-metals (wood, acrylic, leather, textiles).",
|
||||
bestFor: ["Thick acrylic cuts", "Wood cutting/engraving", "Signage", "Textiles"],
|
||||
materials: ["Wood", "Acrylic", "Leather", "Paper", "Textiles", "Rubber"],
|
||||
cautions: [
|
||||
"Poor on bare metals without coatings",
|
||||
"Slower for fine micro-engraving",
|
||||
],
|
||||
learnLink: "/co2-gantry-settings",
|
||||
},
|
||||
co2_galvo: {
|
||||
summary:
|
||||
"High-speed CO₂ marking/engraving on organics/non-metals with small scan fields.",
|
||||
bestFor: ["Fast marking on organics", "Photo engraving on wood/leather", "High throughput"],
|
||||
materials: ["Wood", "Leather", "Paper/Card", "Anodized/painted items"],
|
||||
cautions: [
|
||||
"Small scan field vs gantry",
|
||||
"Not for cutting thick sheets",
|
||||
"Poor on bare metals",
|
||||
],
|
||||
learnLink: "/co2-galvo-settings",
|
||||
},
|
||||
uv: {
|
||||
summary:
|
||||
"Ultra-fine marking/engraving on plastics, glass, ceramics; low heat-affected zone for micro features.",
|
||||
bestFor: ["Micro text/logos", "Fine plastic marking", "Glass/ceramic marking"],
|
||||
materials: ["Plastics", "Glass", "Ceramics", "PCB/silicon (marking)"],
|
||||
cautions: [
|
||||
"Typically lower power; not for thick cutting",
|
||||
"Higher $/W, smaller working areas",
|
||||
],
|
||||
learnLink: "/uv-settings",
|
||||
},
|
||||
};
|
||||
|
||||
export type Answers = {
|
||||
materials: Array<
|
||||
| "metals_bare"
|
||||
| "metals_coated"
|
||||
| "plastics"
|
||||
| "wood_paper_leather"
|
||||
| "glass_ceramic"
|
||||
| "stone"
|
||||
| "textiles"
|
||||
>;
|
||||
operations: Array<
|
||||
| "deep_mark_metal"
|
||||
| "color_mark_stainless"
|
||||
| "fine_engraving"
|
||||
| "photo_engrave"
|
||||
| "cut_nonmetals_thick"
|
||||
| "cut_nonmetals_thin"
|
||||
| "mark_coated"
|
||||
>;
|
||||
part_size: "small" | "medium" | "large"; // ~ scan field or bed
|
||||
detail: "low" | "medium" | "high" | "micro";
|
||||
throughput: "low" | "medium" | "high";
|
||||
budget: "low" | "mid" | "high";
|
||||
};
|
||||
|
||||
type Score = Record<LaserType, number>;
|
||||
const bump = (s: Score, k: LaserType, n: number) => (s[k] += n);
|
||||
|
||||
export function scoreAnswers(a: Answers): {
|
||||
score: Score;
|
||||
ranked: LaserType[];
|
||||
why: Record<LaserType, string[]>;
|
||||
} {
|
||||
const s: Score = { fiber: 0, co2_gantry: 0, co2_galvo: 0, uv: 0 };
|
||||
const why: Record<LaserType, string[]> = {
|
||||
fiber: [],
|
||||
co2_gantry: [],
|
||||
co2_galvo: [],
|
||||
uv: [],
|
||||
};
|
||||
|
||||
// Materials
|
||||
if (a.materials.includes("metals_bare")) {
|
||||
bump(s, "fiber", 6); why.fiber.push("Bare metals benefit from fiber.");
|
||||
bump(s, "uv", 2); why.uv.push("UV can mark some metals with fine detail.");
|
||||
bump(s, "co2_gantry", -3);
|
||||
bump(s, "co2_galvo", -3);
|
||||
}
|
||||
if (a.materials.includes("metals_coated")) {
|
||||
bump(s, "fiber", 3); why.fiber.push("Coated metals are fiber-friendly.");
|
||||
bump(s, "uv", 2); why.uv.push("UV works well on coatings and labels.");
|
||||
bump(s, "co2_galvo", 1); why.co2_galvo.push("CO₂ galvo can mark coated items quickly.");
|
||||
}
|
||||
if (a.materials.includes("plastics") || a.materials.includes("wood_paper_leather")) {
|
||||
bump(s, "co2_gantry", 3); why.co2_gantry.push("Organics & plastics suit CO₂ gantry cutting/engraving.");
|
||||
bump(s, "co2_galvo", 3); why.co2_galvo.push("CO₂ galvo is fast for organic marking.");
|
||||
bump(s, "uv", 1); why.uv.push("UV excels at fine marking plastics.");
|
||||
}
|
||||
if (a.materials.includes("glass_ceramic")) {
|
||||
bump(s, "uv", 4); why.uv.push("Glass/ceramic: UV has low HAZ for crisp marks.");
|
||||
bump(s, "co2_galvo", 1);
|
||||
}
|
||||
if (a.materials.includes("textiles")) {
|
||||
bump(s, "co2_gantry", 3); why.co2_gantry.push("Textiles: CO₂ gantry handles larger panels.");
|
||||
}
|
||||
if (a.materials.includes("stone")) {
|
||||
bump(s, "co2_gantry", 1); bump(s, "co2_galvo", 1);
|
||||
}
|
||||
|
||||
// Operations
|
||||
if (a.operations.includes("deep_mark_metal")) { bump(s, "fiber", 5); why.fiber.push("Deep metal marking favors fiber."); }
|
||||
if (a.operations.includes("color_mark_stainless")) { bump(s, "fiber", 5); why.fiber.push("Color marking stainless = MOPA fiber."); }
|
||||
if (a.operations.includes("fine_engraving")) {
|
||||
bump(s, "uv", 4); why.uv.push("Micro features need UV’s small spot.");
|
||||
bump(s, "fiber", 2); why.fiber.push("Fiber can achieve fine detail on metals.");
|
||||
bump(s, "co2_galvo", 2);
|
||||
}
|
||||
if (a.operations.includes("photo_engrave")) {
|
||||
bump(s, "uv", 3); why.uv.push("UV gives clean dithers on many materials.");
|
||||
bump(s, "co2_galvo", 2); why.co2_galvo.push("CO₂ galvo is common for photo engraving organics.");
|
||||
}
|
||||
if (a.operations.includes("cut_nonmetals_thick")) { bump(s, "co2_gantry", 6); why.co2_gantry.push("Thick cutting needs gantry CO₂."); }
|
||||
if (a.operations.includes("cut_nonmetals_thin")) {
|
||||
bump(s, "co2_gantry", 3); why.co2_gantry.push("Thin cutting works well on gantry CO₂.");
|
||||
bump(s, "co2_galvo", 2);
|
||||
}
|
||||
if (a.operations.includes("mark_coated")) {
|
||||
bump(s, "fiber", 2); why.fiber.push("Coated marks are straightforward on fiber.");
|
||||
bump(s, "uv", 2); why.uv.push("UV marks coatings with low HAZ.");
|
||||
bump(s, "co2_galvo", 1);
|
||||
}
|
||||
|
||||
// Part size & throughput
|
||||
if (a.part_size === "large") { bump(s, "co2_gantry", 5); why.co2_gantry.push("Large work area points to gantry CO₂."); }
|
||||
if (a.part_size === "small") { bump(s, "co2_galvo", 2); }
|
||||
if (a.throughput === "high") {
|
||||
bump(s, "co2_galvo", 3); why.co2_galvo.push("High throughput favors galvo systems.");
|
||||
bump(s, "fiber", 2); why.fiber.push("Fiber galvos are fast on metals.");
|
||||
}
|
||||
|
||||
// Detail requirement
|
||||
if (a.detail === "micro") {
|
||||
bump(s, "uv", 5); why.uv.push("Micro detail → UV’s spot and short wavelength.");
|
||||
bump(s, "fiber", 2);
|
||||
} else if (a.detail === "high") {
|
||||
bump(s, "uv", 3); bump(s, "fiber", 2); bump(s, "co2_galvo", 1);
|
||||
}
|
||||
|
||||
// Budget (very soft tie-breaker)
|
||||
if (a.budget === "low") bump(s, "co2_gantry", 1);
|
||||
if (a.budget === "high") { bump(s, "fiber", 1); bump(s, "uv", 1); }
|
||||
|
||||
const ranked = (Object.keys(s) as LaserType[]).sort((x, y) => s[y] - s[x]);
|
||||
return { score: s, ranked, why };
|
||||
}
|
||||
109
app/lib/memberships.ts
Normal file
109
app/lib/memberships.ts
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
// /lib/support/memberships.ts
|
||||
|
||||
export type MembershipRow = {
|
||||
id: string | number;
|
||||
provider: "kofi" | "patreon" | "mighty" | string;
|
||||
status: "active" | "one_time" | "canceled" | "inactive" | string;
|
||||
tier?: string | null;
|
||||
started_at?: string | null;
|
||||
renews_at?: string | null;
|
||||
email?: string | null;
|
||||
username?: string | null;
|
||||
app_user?: string | null;
|
||||
};
|
||||
|
||||
export type SupportBadge = {
|
||||
provider: "kofi" | "patreon" | "mighty" | string;
|
||||
active: boolean; // true if currently entitled (status==="active" && renews_at >= now)
|
||||
kind: "member" | "one_time" | "inactive";
|
||||
label: string; // e.g., "Ko-fi • Bronze" or "Ko-fi Supporter"
|
||||
tier?: string | null;
|
||||
renews_at?: string | null;
|
||||
started_at?: string | null;
|
||||
};
|
||||
|
||||
const DIRECTUS = (process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, "");
|
||||
|
||||
/** Active if status==="active" and renews_at >= now */
|
||||
function computeActive(row: MembershipRow): boolean {
|
||||
if (row.status !== "active") return false;
|
||||
if (!row.renews_at) return false;
|
||||
const due = new Date(row.renews_at).getTime();
|
||||
return Number.isFinite(due) && due >= Date.now();
|
||||
}
|
||||
|
||||
function providerLabel(p: string) {
|
||||
if (p === "kofi") return "Ko-fi";
|
||||
if (p === "patreon") return "Patreon";
|
||||
if (p === "mighty") return "Mighty";
|
||||
return p[0]?.toUpperCase() + p.slice(1);
|
||||
}
|
||||
|
||||
/** Convert a membership row → displayable badge */
|
||||
function rowToBadge(row: MembershipRow): SupportBadge {
|
||||
const active = computeActive(row);
|
||||
const prov = providerLabel(row.provider);
|
||||
let kind: SupportBadge["kind"] = "inactive";
|
||||
let label = prov;
|
||||
|
||||
if (active) {
|
||||
kind = "member";
|
||||
label = row.tier ? `${prov} • ${row.tier}` : `${prov} Member`;
|
||||
} else if (row.status === "one_time") {
|
||||
kind = "one_time";
|
||||
label = `${prov} Supporter`;
|
||||
} else {
|
||||
kind = "inactive";
|
||||
label = `${prov} (inactive)`;
|
||||
}
|
||||
|
||||
return {
|
||||
provider: row.provider,
|
||||
active,
|
||||
kind,
|
||||
label,
|
||||
tier: row.tier ?? null,
|
||||
renews_at: row.renews_at ?? null,
|
||||
started_at: row.started_at ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all memberships for a user by app_user (preferred) or by email.
|
||||
* Pass either/both: { userId?, email? }
|
||||
*/
|
||||
export async function fetchMembershipBadges(opts: { userId?: string; email?: string }): Promise<SupportBadge[]> {
|
||||
const clauses: any[] = [{ provider: { _in: ["kofi", "patreon", "mighty"] } }];
|
||||
if (opts.userId) clauses.push({ app_user: { _eq: opts.userId } });
|
||||
if (opts.email) clauses.push({ email: { _eq: opts.email.toLowerCase() } });
|
||||
|
||||
// Build filter: provider IN (...) AND (app_user = userId OR email = email)
|
||||
const filter = encodeURIComponent(
|
||||
JSON.stringify({
|
||||
_and: [
|
||||
clauses[0],
|
||||
{ _or: clauses.slice(1).length ? clauses.slice(1) : [{ id: { _neq: null } }] },
|
||||
],
|
||||
})
|
||||
);
|
||||
|
||||
const res = await fetch(`${DIRECTUS}/items/user_memberships?filter=${filter}&limit=500`, { cache: "no-store" });
|
||||
const json = await res.json().catch(() => ({} as any));
|
||||
const rows: MembershipRow[] = json?.data || [];
|
||||
|
||||
const badges = rows.map(rowToBadge);
|
||||
|
||||
// Sort: active first, then provider name asc
|
||||
badges.sort((a, b) => {
|
||||
if (a.active !== b.active) return a.active ? -1 : 1;
|
||||
return a.provider.localeCompare(b.provider);
|
||||
});
|
||||
|
||||
return badges;
|
||||
}
|
||||
|
||||
/** Quick boolean if any active membership exists */
|
||||
export async function hasActiveMembership(opts: { userId?: string; email?: string }): Promise<boolean> {
|
||||
const list = await fetchMembershipBadges(opts);
|
||||
return list.some(b => b.kind === "member" && b.active);
|
||||
}
|
||||
7
app/lib/utils.ts
Normal file
7
app/lib/utils.ts
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
// utils.ts
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue