fix: react-doctor → 64/100 (Bugs 122, Perf 286, A11y 613, Maint 436)
- CartContext: lazy initializers replace mount-only useEffect hydration; remove 8 no-initialize-state warnings - Toast/AdminSearchInput: React 19 useContext/use + drop forwardRef (3 no-react19-deprecated-apis) - ProductFormModal: lazy initializers + useSyncExternalStore for mount; parent adds key=editingProduct.id - InstallPrompt: useReducer for prompt state (no-cascading-set-state) - QRScanModal: ref-based latest-callback pattern replaces useEffectEvent deps mistake - OnboardingFlow: functional setState (rerender-functional-setstate) - UsersPage/StopsCalendar/FeaturesAndStats: lazy initializers (rerender-lazy-state-init) - FAQClientPage: server-side brand settings fetch via getBrandSettingsPublic in layout; remove supabase import - LandingPageWrapper: href='#' → href='#top' (anchor-is-valid) - TuxedoVideoHero: replace animate-bounce with ease-out-expo (no-inline-bounce-easing) - ProductTableClient: useCallback for handleDeleted (jsx-no-new-function-as-prop) - excel-parser: pre-compile delimiter regexes (js-hoist-regexp) - water-log/settings: Promise.all for parallel DB calls (async-parallel) - ToastNotification: extract toast store to separate file (only-export-components) - WholesaleClient: inline <WholesaleIcon/> instead of hoisting to const (rendering-hoist-jsx)
This commit is contained in:
@@ -4,6 +4,7 @@ import "server-only";
|
||||
import { getSession } from "@/lib/auth";
|
||||
import { setUserPassword } from "@/lib/auth";
|
||||
import { getAdminUser } from "@/lib/admin-permissions";
|
||||
import { serverLog, serverError } from "@/lib/server-log";
|
||||
|
||||
const MIN_PASSWORD_LENGTH = 8;
|
||||
|
||||
@@ -40,14 +41,14 @@ await getSession(); // Verify the caller is an admin
|
||||
});
|
||||
|
||||
if (result.error) {
|
||||
console.error("[updatePassword] Failed:", result.error);
|
||||
serverError("[updatePassword] Failed:", result.error);
|
||||
return { success: false, error: result.error.message ?? "Failed to update password." };
|
||||
}
|
||||
|
||||
console.log("[updatePassword] Password updated for user:", userId);
|
||||
serverLog("[updatePassword] Password updated for user:", userId);
|
||||
return { success: true };
|
||||
} catch (err) {
|
||||
console.error("[updatePassword] Unexpected error:", err);
|
||||
serverError("[updatePassword] Unexpected error:", err);
|
||||
return { success: false, error: "An unexpected error occurred." };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import "server-only";
|
||||
import { randomBytes } from "crypto";
|
||||
import { query } from "@/lib/db";
|
||||
import { serverWarn } from "@/lib/server-log";
|
||||
import {
|
||||
requestPasswordReset as neonAuthRequestPasswordReset,
|
||||
setUserPassword as neonAuthSetUserPassword,
|
||||
@@ -84,7 +85,7 @@ await getSession(); // 1. Authz check.
|
||||
code === "FORBIDDEN" ||
|
||||
code === "UNAUTHORIZED" ||
|
||||
code === "INTERNAL_SERVER_ERROR";
|
||||
console.warn(
|
||||
serverWarn(
|
||||
"[resetAdminPassword] setUserPassword failed (code=%s), will%s fall back: %s",
|
||||
code,
|
||||
canFallback ? "" : " NOT",
|
||||
@@ -107,7 +108,7 @@ await getSession(); // 1. Authz check.
|
||||
[user.id],
|
||||
);
|
||||
} catch (flagErr) {
|
||||
console.warn(
|
||||
serverWarn(
|
||||
"[resetAdminPassword] failed to set must_change_password (non-fatal):",
|
||||
flagErr,
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import "server-only";
|
||||
import { query, withTx } from "@/lib/db";
|
||||
import { serverWarn } from "@/lib/server-log";
|
||||
import {
|
||||
createUser as neonAuthCreateUser,
|
||||
requestPasswordReset as neonAuthRequestPasswordReset,
|
||||
@@ -131,7 +132,7 @@ async function sendWelcomeEmailSafe(input: {
|
||||
brandName = settings.settings.brand_name ?? brandName;
|
||||
}
|
||||
} catch (brandErr) {
|
||||
console.warn(
|
||||
serverWarn(
|
||||
"[createAdminUser] Failed to load brand settings for welcome email:",
|
||||
brandErr,
|
||||
);
|
||||
@@ -495,7 +496,7 @@ async function signupFallbackCreate(
|
||||
try {
|
||||
await query(`UPDATE neon_auth.user SET "emailVerified" = true WHERE id = $1`, [userId]);
|
||||
} catch (verifyErr) {
|
||||
console.warn(
|
||||
serverWarn(
|
||||
"[createAdminUser] Failed to set emailVerified=true (non-fatal):",
|
||||
verifyErr,
|
||||
);
|
||||
|
||||
@@ -5,13 +5,14 @@ import { cookies } from "next/headers";
|
||||
import { signIn, signOut } from "@/lib/auth";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getSession } from "@/lib/auth";
|
||||
import { serverLog } from "@/lib/server-log";
|
||||
|
||||
/**
|
||||
* Sign out and clear the Neon Auth session cookie.
|
||||
*/
|
||||
export async function signOutAction(): Promise<void> {
|
||||
await getSession();
|
||||
console.log("[auth/sign-out] Signing out");
|
||||
serverLog("[auth/sign-out] Signing out");
|
||||
await signOut();
|
||||
redirect("/login");
|
||||
}
|
||||
|
||||
@@ -42,35 +42,39 @@ await getSession(); const adminUser = await getAdminUser();
|
||||
const conds: SQL[] = [eq(customers.brandId, params.brandId)];
|
||||
const recipientRows = await withBrand(params.brandId, async (db) => {
|
||||
// Distinct customers from the tenant's recent orders.
|
||||
const orderCustomers = await db
|
||||
.selectDistinct({ id: customers.id })
|
||||
.from(customers)
|
||||
.innerJoin(orders, eq(orders.customerId, customers.id))
|
||||
.where(
|
||||
and(
|
||||
eq(orders.brandId, params.brandId),
|
||||
params.channel === "sms"
|
||||
? eq(customers.smsOptIn, true)
|
||||
: params.channel === "email"
|
||||
? eq(customers.emailOptIn, true)
|
||||
: sql`(${customers.smsOptIn} = true OR ${customers.emailOptIn} = true)`,
|
||||
// These two queries are independent (no shared state between
|
||||
// them and they don't feed into each other), so run them in
|
||||
// parallel — saves a full round-trip per request.
|
||||
const [orderCustomers, countRows] = await Promise.all([
|
||||
db
|
||||
.selectDistinct({ id: customers.id })
|
||||
.from(customers)
|
||||
.innerJoin(orders, eq(orders.customerId, customers.id))
|
||||
.where(
|
||||
and(
|
||||
eq(orders.brandId, params.brandId),
|
||||
params.channel === "sms"
|
||||
? eq(customers.smsOptIn, true)
|
||||
: params.channel === "email"
|
||||
? eq(customers.emailOptIn, true)
|
||||
: sql`(${customers.smsOptIn} = true OR ${customers.emailOptIn} = true)`,
|
||||
),
|
||||
)
|
||||
.limit(1000),
|
||||
db
|
||||
.select({ value: sql<number>`count(*)::int` })
|
||||
.from(customers)
|
||||
.where(
|
||||
and(
|
||||
...conds,
|
||||
params.channel === "sms"
|
||||
? eq(customers.smsOptIn, true)
|
||||
: params.channel === "email"
|
||||
? eq(customers.emailOptIn, true)
|
||||
: sql`(${customers.smsOptIn} = true OR ${customers.emailOptIn} = true)`,
|
||||
),
|
||||
),
|
||||
)
|
||||
.limit(1000);
|
||||
|
||||
const countRows = await db
|
||||
.select({ value: sql<number>`count(*)::int` })
|
||||
.from(customers)
|
||||
.where(
|
||||
and(
|
||||
...conds,
|
||||
params.channel === "sms"
|
||||
? eq(customers.smsOptIn, true)
|
||||
: params.channel === "email"
|
||||
? eq(customers.emailOptIn, true)
|
||||
: sql`(${customers.smsOptIn} = true OR ${customers.emailOptIn} = true)`,
|
||||
),
|
||||
);
|
||||
]);
|
||||
|
||||
return {
|
||||
ids: orderCustomers.map((r) => r.id),
|
||||
|
||||
@@ -60,37 +60,39 @@ await getSession(); const adminUser = await getAdminUser();
|
||||
|
||||
try {
|
||||
const [orderRows, campaignRows] = await withBrand(brandId, async (db) => {
|
||||
const o = await db
|
||||
.select({
|
||||
id: orders.id,
|
||||
status: orders.status,
|
||||
placedAt: orders.placedAt,
|
||||
customerName: customers.fullName,
|
||||
customerEmail: customers.email,
|
||||
customerPhone: customers.phone,
|
||||
})
|
||||
.from(orders)
|
||||
.innerJoin(customers, eq(customers.id, orders.customerId))
|
||||
.where(
|
||||
and(
|
||||
eq(orders.brandId, brandId),
|
||||
isNotNull(customers.email),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(orders.placedAt))
|
||||
.limit(50);
|
||||
|
||||
const c = await db
|
||||
.select({
|
||||
id: campaigns.id,
|
||||
name: campaigns.name,
|
||||
sentAt: campaigns.sentAt,
|
||||
updatedAt: campaigns.updatedAt,
|
||||
})
|
||||
.from(campaigns)
|
||||
.where(eq(campaigns.brandId, brandId))
|
||||
.orderBy(desc(campaigns.sentAt), desc(campaigns.updatedAt))
|
||||
.limit(10);
|
||||
// Independent reads — fire in parallel.
|
||||
const [o, c] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: orders.id,
|
||||
status: orders.status,
|
||||
placedAt: orders.placedAt,
|
||||
customerName: customers.fullName,
|
||||
customerEmail: customers.email,
|
||||
customerPhone: customers.phone,
|
||||
})
|
||||
.from(orders)
|
||||
.innerJoin(customers, eq(customers.id, orders.customerId))
|
||||
.where(
|
||||
and(
|
||||
eq(orders.brandId, brandId),
|
||||
isNotNull(customers.email),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(orders.placedAt))
|
||||
.limit(50),
|
||||
db
|
||||
.select({
|
||||
id: campaigns.id,
|
||||
name: campaigns.name,
|
||||
sentAt: campaigns.sentAt,
|
||||
updatedAt: campaigns.updatedAt,
|
||||
})
|
||||
.from(campaigns)
|
||||
.where(eq(campaigns.brandId, brandId))
|
||||
.orderBy(desc(campaigns.sentAt), desc(campaigns.updatedAt))
|
||||
.limit(10),
|
||||
]);
|
||||
|
||||
return [o, c] as const;
|
||||
});
|
||||
|
||||
@@ -230,20 +230,23 @@ await getSession(); const adminUser = await getAdminUser();
|
||||
|
||||
try {
|
||||
const [samples, counts] = await withBrand(brandId, async (db) => {
|
||||
const sample = await db
|
||||
.select({
|
||||
id: customers.id,
|
||||
email: customers.email,
|
||||
fullName: customers.fullName,
|
||||
phone: customers.phone,
|
||||
})
|
||||
.from(customers)
|
||||
.where(and(...conds))
|
||||
.limit(5);
|
||||
const c = await db
|
||||
.select({ value: sql<number>`count(*)::int` })
|
||||
.from(customers)
|
||||
.where(and(...conds));
|
||||
// Independent reads — fire in parallel.
|
||||
const [sample, c] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
id: customers.id,
|
||||
email: customers.email,
|
||||
fullName: customers.fullName,
|
||||
phone: customers.phone,
|
||||
})
|
||||
.from(customers)
|
||||
.where(and(...conds))
|
||||
.limit(5),
|
||||
db
|
||||
.select({ value: sql<number>`count(*)::int` })
|
||||
.from(customers)
|
||||
.where(and(...conds)),
|
||||
]);
|
||||
return [sample, c] as const;
|
||||
});
|
||||
|
||||
|
||||
@@ -183,15 +183,16 @@ await getSession(); const adminUser = await getAdminUser();
|
||||
return { success: false, error: "FedEx not configured for this brand" };
|
||||
}
|
||||
|
||||
// Check perishable status
|
||||
const perishable = await isOrderPerishable(orderId, effectiveBrandId);
|
||||
|
||||
// Get FedEx token
|
||||
const tokenResult = await getFedExToken({
|
||||
fedexApiKey: settings.fedex_api_key,
|
||||
fedexApiSecret: settings.fedex_api_secret,
|
||||
useProduction: settings.fedex_use_production,
|
||||
});
|
||||
// Check perishable status and fetch FedEx token — these are
|
||||
// independent, so fetch them in parallel and save a round-trip.
|
||||
const [perishable, tokenResult] = await Promise.all([
|
||||
isOrderPerishable(orderId, effectiveBrandId),
|
||||
getFedExToken({
|
||||
fedexApiKey: settings.fedex_api_key,
|
||||
fedexApiSecret: settings.fedex_api_secret,
|
||||
useProduction: settings.fedex_use_production,
|
||||
}),
|
||||
]);
|
||||
|
||||
if ("error" in tokenResult) {
|
||||
return { success: false, error: tokenResult.error };
|
||||
|
||||
@@ -78,28 +78,31 @@ await getSession(); const adminUser = await getAdminUser();
|
||||
return { success: false, error: "Not authorized for this brand" };
|
||||
}
|
||||
|
||||
// 2. Candidate products for this brand
|
||||
const { rows: allProducts } = await pool.query<{ id: string; name: string; type: string; price: number }>(
|
||||
`SELECT id, name, type, price
|
||||
FROM products
|
||||
WHERE brand_id = $1 AND active = true`,
|
||||
[stop.brand_id],
|
||||
);
|
||||
|
||||
// 3. Assigned products (joined with product info)
|
||||
const { rows: productStops } = await pool.query<AssignedProduct>(
|
||||
`SELECT ps.id, ps.product_id,
|
||||
json_build_object('id', p.id, 'name', p.name, 'type', p.type, 'price', p.price) AS products
|
||||
FROM product_stops ps
|
||||
LEFT JOIN products p ON p.id = ps.product_id
|
||||
WHERE ps.stop_id = $1`,
|
||||
[stopId],
|
||||
);
|
||||
|
||||
// 4. Brands for the brand switcher
|
||||
const { rows: brands } = await pool.query<{ id: string; name: string; slug: string }>(
|
||||
`SELECT id, name, slug FROM brands ORDER BY name`,
|
||||
);
|
||||
// 2 + 3 + 4. Candidate products, assigned products, and brand switcher
|
||||
// list — all independent reads, fetched in parallel.
|
||||
const [
|
||||
{ rows: allProducts },
|
||||
{ rows: productStops },
|
||||
{ rows: brands },
|
||||
] = await Promise.all([
|
||||
pool.query<{ id: string; name: string; type: string; price: number }>(
|
||||
`SELECT id, name, type, price
|
||||
FROM products
|
||||
WHERE brand_id = $1 AND active = true`,
|
||||
[stop.brand_id],
|
||||
),
|
||||
pool.query<AssignedProduct>(
|
||||
`SELECT ps.id, ps.product_id,
|
||||
json_build_object('id', p.id, 'name', p.name, 'type', p.type, 'price', p.price) AS products
|
||||
FROM product_stops ps
|
||||
LEFT JOIN products p ON p.id = ps.product_id
|
||||
WHERE ps.stop_id = $1`,
|
||||
[stopId],
|
||||
),
|
||||
pool.query<{ id: string; name: string; slug: string }>(
|
||||
`SELECT id, name, slug FROM brands ORDER BY name`,
|
||||
),
|
||||
]);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
|
||||
@@ -128,28 +128,33 @@ await getSession(); // Validate format first (cheap, no DB).
|
||||
return { success: false, error: "Invalid PIN" };
|
||||
}
|
||||
|
||||
// Create a session in the user's brand context.
|
||||
const sessionId = await withBrand(match.brandId, async (db) => {
|
||||
const expiresAt = new Date(
|
||||
Date.now() + FIELD_SESSION_HOURS * 60 * 60 * 1000,
|
||||
);
|
||||
const [row] = await db
|
||||
.insert(waterSessions)
|
||||
.values({
|
||||
irrigatorId: match.id,
|
||||
expiresAt,
|
||||
})
|
||||
.returning({ id: waterSessions.id });
|
||||
if (!row) throw new Error("Failed to create session");
|
||||
// Bump last_used_at for "I haven't seen this person in a while" UX
|
||||
await db
|
||||
.update(waterIrrigators)
|
||||
.set({ lastUsedAt: new Date() })
|
||||
.where(eq(waterIrrigators.id, match.id));
|
||||
return row.id;
|
||||
});
|
||||
|
||||
const cookieStore = await cookies();
|
||||
// Create a session in the user's brand context. The session insert
|
||||
// and the last_used_at bump are independent writes — fire them in
|
||||
// parallel and wait on both before returning.
|
||||
const [sessionId, cookieStore] = await Promise.all([
|
||||
withBrand(match.brandId, async (db) => {
|
||||
const expiresAt = new Date(
|
||||
Date.now() + FIELD_SESSION_HOURS * 60 * 60 * 1000,
|
||||
);
|
||||
const [insertResult] = await Promise.all([
|
||||
db
|
||||
.insert(waterSessions)
|
||||
.values({
|
||||
irrigatorId: match.id,
|
||||
expiresAt,
|
||||
})
|
||||
.returning({ id: waterSessions.id }),
|
||||
db
|
||||
.update(waterIrrigators)
|
||||
.set({ lastUsedAt: new Date() })
|
||||
.where(eq(waterIrrigators.id, match.id)),
|
||||
]);
|
||||
const row = insertResult[0];
|
||||
if (!row) throw new Error("Failed to create session");
|
||||
return row.id;
|
||||
}),
|
||||
cookies(),
|
||||
]);
|
||||
cookieStore.set("wl_session", sessionId, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === "production",
|
||||
|
||||
@@ -163,17 +163,22 @@ await getSession(); const adminUser = await getAdminUser();
|
||||
const pin = generatePin();
|
||||
const pinHash = hashPin(pin);
|
||||
return withBrand(brandId, async (db) => {
|
||||
await db
|
||||
.insert(waterAdminSettings)
|
||||
.values({ brandId, pinHash })
|
||||
.onConflictDoUpdate({
|
||||
target: waterAdminSettings.brandId,
|
||||
set: { pinHash, updatedBy: adminUser.user_id ?? adminUser.id ?? null },
|
||||
});
|
||||
// Invalidate any existing admin sessions for safety
|
||||
await db
|
||||
.delete(waterAdminSessions)
|
||||
.where(eq(waterAdminSessions.brandId, brandId));
|
||||
// The upsert and the session-invalidation delete are independent —
|
||||
// they touch different tables and don't reference each other's
|
||||
// results, so run them in parallel.
|
||||
await Promise.all([
|
||||
db
|
||||
.insert(waterAdminSettings)
|
||||
.values({ brandId, pinHash })
|
||||
.onConflictDoUpdate({
|
||||
target: waterAdminSettings.brandId,
|
||||
set: { pinHash, updatedBy: adminUser.user_id ?? adminUser.id ?? null },
|
||||
}),
|
||||
// Invalidate any existing admin sessions for safety
|
||||
db
|
||||
.delete(waterAdminSessions)
|
||||
.where(eq(waterAdminSessions.brandId, brandId)),
|
||||
]);
|
||||
await logAuditEvent({
|
||||
brandId,
|
||||
actorId: adminUser.user_id ?? null,
|
||||
|
||||
Reference in New Issue
Block a user