Production

This commit is contained in:
Shubhankar45
2026-09-22 06:23:46 +00:00
commit 8fdd20b29f
217 changed files with 31212 additions and 0 deletions
+56
View File
@@ -0,0 +1,56 @@
import type { DcrStatus, Role } from "../types";
export const STATUS_LABEL: Record<DcrStatus, string> = {
DRAFT: "Draft",
PENDING_AM: "With Area Manager",
RETURNED: "Returned",
APPROVED: "Approved",
};
export const ROLE_LABEL: Record<Role, string> = {
MR: "Medical Representative",
AM: "Area Manager",
GM: "General Manager",
ADMIN: "Administrator",
};
/** Today's date in the user's own timezone (toISOString would give the UTC date). */
export const todayISO = () => {
const d = new Date();
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
};
/** The current local time as HH:MM, for time inputs. */
export const nowHHMM = () => {
const d = new Date();
return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
};
export function formatDate(value: string | null | undefined): string {
if (!value) return "—";
const date = new Date(value.length === 10 ? `${value}T00:00:00` : value);
return Number.isNaN(date.getTime())
? value
: date.toLocaleDateString(undefined, { day: "2-digit", month: "short", year: "numeric" });
}
export function formatDateTime(value: string | null | undefined): string {
if (!value) return "—";
const date = new Date(value);
return Number.isNaN(date.getTime())
? value
: date.toLocaleString(undefined, { day: "2-digit", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" });
}
export const initials = (name: string) =>
name.split(/\s+/).filter(Boolean).slice(0, 2).map((part) => part[0]!.toUpperCase()).join("") || "?";
const ACRONYMS = new Set(["pob", "pts", "km", "kms", "pds", "id"]);
export const humanize = (key: string) =>
key
.split("_")
.map((word) => (ACRONYMS.has(word) ? word.toUpperCase() : word.charAt(0).toUpperCase() + word.slice(1)))
.join(" ");
export const errorMessage = (error: unknown, fallback = "Something went wrong") =>
error instanceof Error ? error.message : fallback;
+11
View File
@@ -0,0 +1,11 @@
import type { AreaManagerMapping, Headquarters, User } from "../types";
/** Headquarters a person works in: an MR has one, an AM has any number, GM and Admin cover all. */
export function headquartersOf(user: User, hqs: Headquarters[], mappings: AreaManagerMapping[]): { all: boolean; items: Headquarters[] } {
if (user.role === "GM" || user.role === "ADMIN") return { all: true, items: [] };
const ids = user.role === "MR"
? (user.headquarters_id ? [user.headquarters_id] : [])
: mappings.filter((m) => m.area_manager_user_id === user.id).map((m) => m.headquarters_id);
const wanted = new Set(ids);
return { all: false, items: hqs.filter((h) => wanted.has(h.id)) };
}
+62
View File
@@ -0,0 +1,62 @@
import type { IconName } from "../components/ui/Icon";
import type { Role } from "../types";
export interface NavItem {
to: string;
label: string;
icon: IconName;
roles?: Role[];
}
export interface NavSection {
title: string;
items: NavItem[];
}
/** Sidebar structure. `roles` limits an item to those roles; omitted means everyone. */
export const NAVIGATION: NavSection[] = [
{
title: "Workspace",
items: [
{ to: "/", label: "Dashboard", icon: "dashboard" },
{ to: "/reports", label: "Daily Call Reports", icon: "file", roles: ["MR", "AM", "GM"] },
],
},
{
title: "Field data",
items: [
{ to: "/directory", label: "Doctors & Chemists", icon: "stethoscope" },
{ to: "/products", label: "Products", icon: "box" },
{ to: "/forms", label: "Company forms", icon: "table", roles: ["MR", "AM", "ADMIN"] },
],
},
{
title: "Administration",
items: [
{ to: "/admin", label: "Setup", icon: "settings", roles: ["ADMIN"] },
{ to: "/users", label: "Users", icon: "users", roles: ["ADMIN", "GM"] },
],
},
];
export function navigationFor(role: Role): NavSection[] {
return NAVIGATION.map((section) => ({
...section,
items: section.items.filter((item) => !item.roles || item.roles.includes(role)),
})).filter((section) => section.items.length > 0);
}
/** Title shown in the top bar for the current path. */
export function titleFor(path: string): string {
if (path === "/") return "Dashboard";
if (path === "/reports/new") return "New report";
if (path.startsWith("/reports/")) return "Report";
if (path.startsWith("/reports")) return "Daily Call Reports";
if (path.startsWith("/forms")) return "Company forms";
if (path.startsWith("/directory")) return "Doctors & Chemists";
if (path.startsWith("/products")) return "Products";
if (path.startsWith("/admin")) return "Setup";
if (path.startsWith("/users")) return "Users";
if (path.startsWith("/profile")) return "Profile";
return "Not found";
}
+38
View File
@@ -0,0 +1,38 @@
import { type AnchorHTMLAttributes, useEffect, useState } from "react";
/**
* Minimal hash router. Hash URLs work behind any static file server (no server-side
* fallback needed), give every screen a shareable address and keep the back button working.
*/
const read = () => (window.location.hash.replace(/^#/, "").split("?")[0] || "/").replace(/\/+$/, "") || "/";
export function useLocation(): string {
const [path, setPath] = useState(read);
useEffect(() => {
const update = () => setPath(read());
window.addEventListener("hashchange", update);
return () => window.removeEventListener("hashchange", update);
}, []);
return path;
}
export function navigate(to: string): void {
if (read() !== to) window.location.hash = to;
}
/** Match "/reports/:id" against "/reports/42" → { id: "42" }, or null. */
export function matchPath(pattern: string, path: string): Record<string, string> | null {
const want = pattern.split("/").filter(Boolean);
const have = path.split("/").filter(Boolean);
if (want.length !== have.length) return null;
const params: Record<string, string> = {};
for (let i = 0; i < want.length; i++) {
if (want[i].startsWith(":")) params[want[i].slice(1)] = decodeURIComponent(have[i]);
else if (want[i] !== have[i]) return null;
}
return params;
}
export function Link({ to, ...rest }: { to: string } & Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href">) {
return <a href={`#${to}`} {...rest} />;
}
+54
View File
@@ -0,0 +1,54 @@
import { createContext, type ReactNode, useCallback, useContext, useEffect, useMemo, useState } from "react";
import { api, auth } from "../api";
import type { User } from "../types";
interface Session {
user: User | null;
loading: boolean;
signIn: (email: string, password: string) => Promise<void>;
signOut: () => void;
}
const SessionContext = createContext<Session | null>(null);
export function SessionProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(Boolean(auth.token));
const signOut = useCallback(() => {
auth.clear();
setUser(null);
window.location.hash = "/";
}, []);
useEffect(() => {
auth.onSignedOut(() => setUser(null));
if (!auth.token) return;
api
.me()
.then(setUser)
.catch(() => auth.clear())
.finally(() => setLoading(false));
}, []);
const signIn = useCallback(async (email: string, password: string) => {
setUser(await api.login(email, password));
window.location.hash = "/";
}, []);
const value = useMemo(() => ({ user, loading, signIn, signOut }), [user, loading, signIn, signOut]);
return <SessionContext.Provider value={value}>{children}</SessionContext.Provider>;
}
export function useSession(): Session {
const ctx = useContext(SessionContext);
if (!ctx) throw new Error("useSession must be used inside SessionProvider");
return ctx;
}
/** The signed-in user; only call below the authentication gate. */
export function useUser(): User {
const { user } = useSession();
if (!user) throw new Error("No signed-in user");
return user;
}
+96
View File
@@ -0,0 +1,96 @@
/** Small, dependency-free form validation shared by every form. Each rule returns an error message or null. */
import { useState } from "react";
export type Rule = (value: string) => string | null;
export type Errors = Record<string, string>;
const blank = (v: string) => v.trim() === "";
export const required = (label: string): Rule => (v) => (blank(v) ? `${label} is required` : null);
export const minLength = (n: number, label: string): Rule => (v) => (!blank(v) && v.trim().length < n ? `${label} must be at least ${n} characters` : null);
export const maxLength = (n: number, label: string): Rule => (v) => (v.trim().length > n ? `${label} must be ${n} characters or fewer` : null);
export const pattern = (re: RegExp, message: string): Rule => (v) => (blank(v) || re.test(v.trim()) ? null : message);
export const email: Rule = pattern(/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/, "Enter a valid email address, like name@company.com");
/** 7–15 digits, optionally with a leading + and spaces, dashes or brackets. */
export const phone: Rule = (v) => {
if (blank(v)) return null;
const digits = v.replace(/\D/g, "").length;
return /^\+?[0-9\s()-]+$/.test(v.trim()) && digits >= 7 && digits <= 15 ? null : "Enter a valid phone number (7–15 digits)";
};
export const code = (label: string): Rule => pattern(/^[A-Za-z0-9][A-Za-z0-9._/-]*$/, `${label} may only contain letters, numbers and . _ / -`);
export const password: Rule = (v) => {
if (v === "") return null;
if (v.length < 8) return "Password must be at least 8 characters";
if (v.length > 128) return "Password must be 128 characters or fewer";
return /[A-Za-z]/.test(v) && /\d/.test(v) ? null : "Password needs at least one letter and one number";
};
/** Whole or decimal number, thousands commas allowed ("12,500.50"). */
export const numeric = (label: string): Rule => pattern(/^-?\d[\d,]*(\.\d+)?$/, `${label} must be a number`);
/** An amount of money: optional ₹ / Rs prefix, digits with commas, up to 2 decimals. */
export const amount = (label: string): Rule => pattern(/^(₹|rs\.?)?\s?\d[\d,]*(\.\d{1,2})?$/i, `${label} must be an amount, like 12500 or 12,500.50`);
const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
export const isoDate = (label: string): Rule => (v) => {
if (blank(v)) return null;
const valid = ISO_DATE.test(v) && !Number.isNaN(Date.parse(v));
return valid ? null : `${label} must be a valid date`;
};
export const notAfter = (limit: string, label: string, what = "today"): Rule => (v) => (!blank(v) && v > limit ? `${label} cannot be after ${what}` : null);
/** The first failing rule's message, or null. */
export function firstError(value: string, rules: Rule[] = []): string | null {
for (const rule of rules) {
const message = rule(value);
if (message) return message;
}
return null;
}
export function validateValues(values: Record<string, string>, spec: Record<string, Rule[]>): Errors {
const errors: Errors = {};
for (const [name, rules] of Object.entries(spec)) {
const message = firstError(values[name] ?? "", rules);
if (message) errors[name] = message;
}
return errors;
}
/** Move the cursor to the first invalid control once the errors have rendered. */
export function focusFirstError(root: ParentNode | null): void {
requestAnimationFrame(() => {
root?.querySelector<HTMLElement>(".field-invalid input, .field-invalid select, .field-invalid textarea")?.focus();
});
}
/**
* Validation state for a controlled form. `check` validates everything (on submit);
* `touch` validates one field (on blur, and on change once it has shown an error).
*/
export function useValidation(spec: Record<string, Rule[]>) {
const [errors, setErrors] = useState<Errors>({});
return {
errors,
check(values: Record<string, string>, form?: ParentNode | null): boolean {
const found = validateValues(values, spec);
setErrors(found);
const ok = Object.keys(found).length === 0;
if (!ok) focusFirstError(form ?? document);
return ok;
},
touch(name: string, value: string) {
const message = firstError(value, spec[name]);
setErrors((prev) => {
if ((prev[name] ?? null) === message) return prev;
const next = { ...prev };
if (message) next[name] = message; else delete next[name];
return next;
});
},
/** Live re-check while typing, but only for a field that is already showing an error. */
retouch(name: string, value: string) {
if (errors[name]) this.touch(name, value);
},
clear: () => setErrors({}),
};
}