mirror of
https://github.com/soconnor0919/beenvoice.git
synced 2026-05-08 17:48:55 -04:00
Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ad89ad001d | |||
| 4fd6772f2e | |||
| fbeca7cfee | |||
| b582b6c88e | |||
| 00e066ca4e | |||
| 4214a4b4de | |||
| af392e1bc9 | |||
| 74f9696023 | |||
| 1f76cf38a7 | |||
| e5242b37a4 | |||
| 38206f34fe | |||
| e950abd805 | |||
| 4c0eae4b11 |
+1
-3
@@ -6,14 +6,12 @@ Dockerfile*
|
||||
docker-compose*
|
||||
README.md
|
||||
*.log
|
||||
.DS_Store
|
||||
.env*
|
||||
!.env.example
|
||||
drizzle/*.sql
|
||||
drizzle/*-journal
|
||||
.vscode
|
||||
.idea
|
||||
coverage
|
||||
*.tsbuildinfo
|
||||
dist
|
||||
build
|
||||
|
||||
|
||||
+43
-35
@@ -1,43 +1,51 @@
|
||||
# Base application env
|
||||
NODE_ENV="development"
|
||||
PORT="3000"
|
||||
HOSTNAME="0.0.0.0"
|
||||
# Copy this file to .env before running Docker Compose:
|
||||
# cp .env.example .env
|
||||
|
||||
# Runtime
|
||||
NODE_ENV=production
|
||||
WEB_PORT=3000
|
||||
|
||||
# Auth
|
||||
# You can generate a new secret on the command line with:
|
||||
# openssl rand -base64 32
|
||||
AUTH_SECRET="your-auth-secret"
|
||||
BETTER_AUTH_URL="http://localhost:3000" # Set to your production URL in production
|
||||
# Generate with: openssl rand -base64 32
|
||||
AUTH_SECRET=change-me-generate-a-real-secret
|
||||
BETTER_AUTH_URL=http://localhost:3000
|
||||
|
||||
# App URL
|
||||
# Used for client-side redirects and base URLs
|
||||
NEXT_PUBLIC_APP_URL="http://localhost:3000"
|
||||
# Public app URL
|
||||
NEXT_PUBLIC_APP_URL=http://localhost:3000
|
||||
|
||||
# Database (Postgres)
|
||||
# These are required for Docker container initialization
|
||||
POSTGRES_USER="postgres"
|
||||
POSTGRES_PASSWORD="postgres"
|
||||
POSTGRES_DB="postgres"
|
||||
# Postgres used by docker-compose.yml
|
||||
POSTGRES_USER=postgres
|
||||
POSTGRES_PASSWORD=postgres
|
||||
POSTGRES_DB=postgres
|
||||
DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres
|
||||
DB_DISABLE_SSL=true
|
||||
|
||||
# Connect string for the app
|
||||
DATABASE_URL="postgres://postgres:postgres@localhost:5432/postgres"
|
||||
# Disable SSL for Docker local Postgres; set to false or remove for managed Postgres
|
||||
DB_DISABLE_SSL="true"
|
||||
# White-label defaults used at image build time.
|
||||
# Admin-managed platform branding in the app can override these after setup.
|
||||
NEXT_PUBLIC_BRAND_NAME="beenvoice"
|
||||
NEXT_PUBLIC_BRAND_TAGLINE="Simple and efficient invoicing for freelancers and small businesses"
|
||||
NEXT_PUBLIC_BRAND_LOGO_TEXT="beenvoice"
|
||||
NEXT_PUBLIC_BRAND_ICON="$"
|
||||
NEXT_PUBLIC_DEFAULT_INTERFACE_THEME="beenvoice"
|
||||
NEXT_PUBLIC_DEFAULT_FONT="brand"
|
||||
NEXT_PUBLIC_DEFAULT_BODY_FONT="brand"
|
||||
NEXT_PUBLIC_DEFAULT_HEADING_FONT="brand"
|
||||
NEXT_PUBLIC_DEFAULT_RADIUS="xl"
|
||||
NEXT_PUBLIC_DEFAULT_SIDEBAR_STYLE="floating"
|
||||
|
||||
# Email (Resend). Replace with real keys in production
|
||||
RESEND_API_KEY="your-resend-api-key"
|
||||
RESEND_DOMAIN=""
|
||||
# Email delivery via Resend (optional)
|
||||
# Leave blank to disable invoice/password-reset email delivery.
|
||||
RESEND_API_KEY=
|
||||
RESEND_DOMAIN=
|
||||
|
||||
# Analytics
|
||||
NEXT_PUBLIC_UMAMI_WEBSITE_ID="your-website-id-here"
|
||||
NEXT_PUBLIC_UMAMI_SCRIPT_URL="https://analytics.umami.is/script.js"
|
||||
# Build tweaks
|
||||
# SKIP_ENV_VALIDATION=1
|
||||
# Analytics via Umami (optional)
|
||||
# Leave website ID blank to disable analytics.
|
||||
NEXT_PUBLIC_UMAMI_WEBSITE_ID=
|
||||
NEXT_PUBLIC_UMAMI_SCRIPT_URL=https://analytics.umami.is/script.js
|
||||
|
||||
# SSO / Authentik (Optional - only needed if using SSO authentication)
|
||||
# Configure these if you want to enable Single Sign-On with Authentik OIDC
|
||||
# The issuer should be your Authentik application's OAuth2 provider URL
|
||||
# Example: https://auth.example.com/application/o/your-app-slug
|
||||
AUTHENTIK_ISSUER=""
|
||||
AUTHENTIK_CLIENT_ID=""
|
||||
AUTHENTIK_CLIENT_SECRET=""
|
||||
# SSO via Authentik OIDC (optional)
|
||||
NEXT_PUBLIC_AUTHENTIK_ENABLED=false
|
||||
AUTHENTIK_ISSUER=
|
||||
AUTHENTIK_CLIENT_ID=
|
||||
AUTHENTIK_CLIENT_SECRET=
|
||||
AUTHENTIK_ORIGIN=
|
||||
|
||||
+2
-1
@@ -34,6 +34,7 @@ yarn-error.log*
|
||||
# local env files
|
||||
# do not commit any .env files to git, except for the .env.example file. https://create.t3.gg/en/usage/env-variables#using-environment-variables
|
||||
.env
|
||||
.env.prod
|
||||
.env*.local
|
||||
.env*.production
|
||||
|
||||
@@ -41,4 +42,4 @@ yarn-error.log*
|
||||
*.tsbuildinfo
|
||||
|
||||
# idea files
|
||||
.idea
|
||||
.idea
|
||||
|
||||
+26
-49
@@ -1,59 +1,36 @@
|
||||
FROM oven/bun:1.2.19 as deps
|
||||
WORKDIR /app
|
||||
# syntax=docker/dockerfile:1
|
||||
FROM oven/bun:1 AS base
|
||||
WORKDIR /usr/src/app
|
||||
|
||||
# Install dependencies (only package manifests copied first for better caching)
|
||||
FROM base AS install
|
||||
COPY package.json bun.lock ./
|
||||
# Install minimal toolchain for native devDependencies (e.g., better-sqlite3) during build
|
||||
# Minimal toolchain (kept for safety, but we skip dev deps)
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends python3 make g++ \
|
||||
&& ln -sf /usr/bin/python3 /usr/bin/python \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
# Install all deps (including dev) for build tooling like @tailwindcss/postcss
|
||||
RUN bun install --frozen-lockfile --verbose
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
FROM oven/bun:1.2.19 as builder
|
||||
WORKDIR /app
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV SKIP_ENV_VALIDATION=1
|
||||
ENV NEXT_TELEMETRY_DISABLED=1
|
||||
|
||||
COPY --from=deps /app/node_modules ./node_modules
|
||||
FROM base AS build
|
||||
COPY --from=install /usr/src/app/node_modules node_modules
|
||||
COPY . .
|
||||
|
||||
# Build Next.js app (no memory constraints)
|
||||
RUN bun run build
|
||||
ENV NODE_ENV=production \
|
||||
SKIP_ENV_VALIDATION=1 \
|
||||
NODE_OPTIONS=--max-old-space-size=4096 \
|
||||
BETTER_AUTH_URL=http://localhost:3000 \
|
||||
AUTH_SECRET=docker-build-placeholder-secret-do-not-use \
|
||||
DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres
|
||||
RUN bun run build && bun build src/server/db/migrate.ts --target=bun --outfile=migrate.js
|
||||
|
||||
FROM oven/bun:1.2.19 as runner
|
||||
WORKDIR /app
|
||||
FROM base AS release
|
||||
ENV NODE_ENV=production \
|
||||
PORT=3000 \
|
||||
HOSTNAME=0.0.0.0
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
COPY --from=build /usr/src/app/.next/standalone ./
|
||||
COPY --from=build /usr/src/app/.next/static ./.next/static
|
||||
COPY --from=build /usr/src/app/public ./public
|
||||
COPY --from=build /usr/src/app/migrate.js ./migrate.js
|
||||
COPY --from=build /usr/src/app/drizzle ./drizzle
|
||||
|
||||
# Create non-root user and group
|
||||
RUN addgroup --system --gid 1001 beenvoice \
|
||||
&& adduser --system --uid 1001 --ingroup beenvoice beenvoice
|
||||
|
||||
# Copy runtime artifacts and install production deps
|
||||
COPY --from=builder /app/.next ./.next
|
||||
COPY --from=builder /app/public ./public
|
||||
COPY --from=builder /app/package.json ./package.json
|
||||
COPY --from=builder /app/bun.lock ./bun.lock
|
||||
RUN bun install --frozen-lockfile --production --verbose
|
||||
COPY --from=builder /app/start.sh ./start.sh
|
||||
COPY --from=builder /app/next.config.js ./next.config.js
|
||||
COPY --from=builder /app/src ./src
|
||||
COPY --from=builder /app/drizzle ./drizzle
|
||||
COPY --from=builder /app/drizzle.config.ts ./drizzle.config.ts
|
||||
COPY --from=builder /app/.env.example ./.env.example
|
||||
|
||||
RUN chmod +x ./start.sh
|
||||
|
||||
USER 1001
|
||||
RUN chmod -R a+rX drizzle migrate.js public
|
||||
|
||||
USER bun
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["./start.sh"]
|
||||
|
||||
|
||||
CMD ["sh", "-c", "bun migrate.js && bun server.js"]
|
||||
|
||||
+33
-9
@@ -1,21 +1,45 @@
|
||||
services:
|
||||
app:
|
||||
build:
|
||||
context: .
|
||||
image: beenvoice:local
|
||||
environment:
|
||||
NODE_ENV: production
|
||||
AUTH_SECRET: ${AUTH_SECRET:?Set AUTH_SECRET in .env}
|
||||
DATABASE_URL: postgres://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-postgres}@db:5432/${POSTGRES_DB:-postgres}
|
||||
DB_DISABLE_SSL: "true"
|
||||
BETTER_AUTH_URL: ${BETTER_AUTH_URL:-http://localhost:3000}
|
||||
NEXT_PUBLIC_APP_URL: ${NEXT_PUBLIC_APP_URL:-http://localhost:3000}
|
||||
RESEND_API_KEY: ${RESEND_API_KEY:-}
|
||||
RESEND_DOMAIN: ${RESEND_DOMAIN:-}
|
||||
NEXT_PUBLIC_UMAMI_WEBSITE_ID: ${NEXT_PUBLIC_UMAMI_WEBSITE_ID:-}
|
||||
NEXT_PUBLIC_UMAMI_SCRIPT_URL: ${NEXT_PUBLIC_UMAMI_SCRIPT_URL:-https://analytics.umami.is/script.js}
|
||||
NEXT_PUBLIC_AUTHENTIK_ENABLED: ${NEXT_PUBLIC_AUTHENTIK_ENABLED:-false}
|
||||
AUTHENTIK_ISSUER: ${AUTHENTIK_ISSUER:-}
|
||||
AUTHENTIK_CLIENT_ID: ${AUTHENTIK_CLIENT_ID:-}
|
||||
AUTHENTIK_CLIENT_SECRET: ${AUTHENTIK_CLIENT_SECRET:-}
|
||||
AUTHENTIK_ORIGIN: ${AUTHENTIK_ORIGIN:-}
|
||||
ports:
|
||||
- "${WEB_PORT:-3000}:3000"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
|
||||
db:
|
||||
image: postgres:17-alpine
|
||||
container_name: beenvoice-db
|
||||
env_file:
|
||||
- .env.local
|
||||
environment:
|
||||
POSTGRES_USER: ${POSTGRES_USER:-postgres}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-postgres}
|
||||
volumes:
|
||||
- beenvoice_pg_data:/var/lib/postgresql/data
|
||||
ports:
|
||||
- "5432:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres"]
|
||||
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 10
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
beenvoice_pg_data:
|
||||
driver: local
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE "beenvoice_expense" ADD COLUMN "taxDeductible" boolean DEFAULT false NOT NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
ALTER TABLE "beenvoice_user" ADD COLUMN "interfaceTheme" varchar(50) DEFAULT 'beenvoice' NOT NULL;
|
||||
ALTER TABLE "beenvoice_user" ADD COLUMN "fontPreference" varchar(50) DEFAULT 'brand' NOT NULL;
|
||||
@@ -0,0 +1,11 @@
|
||||
ALTER TABLE "beenvoice_user"
|
||||
ADD COLUMN "bodyFontPreference" varchar(50) DEFAULT 'brand' NOT NULL;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "beenvoice_user"
|
||||
ADD COLUMN "headingFontPreference" varchar(50) DEFAULT 'brand' NOT NULL;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "beenvoice_user"
|
||||
ADD COLUMN "radiusPreference" varchar(20) DEFAULT 'xl' NOT NULL;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "beenvoice_user"
|
||||
ADD COLUMN "sidebarStyle" varchar(20) DEFAULT 'floating' NOT NULL;
|
||||
@@ -0,0 +1,59 @@
|
||||
ALTER TABLE "beenvoice_user"
|
||||
ADD COLUMN "role" varchar(20) DEFAULT 'user' NOT NULL;
|
||||
--> statement-breakpoint
|
||||
UPDATE "beenvoice_user"
|
||||
SET "role" = 'admin'
|
||||
WHERE "id" = (
|
||||
SELECT "id"
|
||||
FROM "beenvoice_user"
|
||||
ORDER BY "createdAt" ASC
|
||||
LIMIT 1
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE IF NOT EXISTS "beenvoice_platform_setting" (
|
||||
"id" varchar(50) PRIMARY KEY DEFAULT 'global' NOT NULL,
|
||||
"brandName" varchar(100) DEFAULT 'beenvoice' NOT NULL,
|
||||
"brandTagline" varchar(255) DEFAULT 'Simple and efficient invoicing for freelancers and small businesses' NOT NULL,
|
||||
"brandLogoText" varchar(100) DEFAULT 'beenvoice' NOT NULL,
|
||||
"brandIcon" varchar(20) DEFAULT '$' NOT NULL,
|
||||
"colorTheme" varchar(50) DEFAULT 'slate' NOT NULL,
|
||||
"customColor" varchar(50),
|
||||
"theme" varchar(20) DEFAULT 'system' NOT NULL,
|
||||
"interfaceTheme" varchar(50) DEFAULT 'beenvoice' NOT NULL,
|
||||
"bodyFontPreference" varchar(50) DEFAULT 'brand' NOT NULL,
|
||||
"headingFontPreference" varchar(50) DEFAULT 'brand' NOT NULL,
|
||||
"radiusPreference" varchar(20) DEFAULT 'xl' NOT NULL,
|
||||
"sidebarStyle" varchar(20) DEFAULT 'floating' NOT NULL,
|
||||
"createdAt" timestamp DEFAULT now() NOT NULL,
|
||||
"updatedAt" timestamp DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
INSERT INTO "beenvoice_platform_setting" (
|
||||
"id",
|
||||
"brandName",
|
||||
"brandTagline",
|
||||
"brandLogoText",
|
||||
"brandIcon",
|
||||
"colorTheme",
|
||||
"customColor",
|
||||
"theme",
|
||||
"interfaceTheme",
|
||||
"bodyFontPreference",
|
||||
"headingFontPreference",
|
||||
"radiusPreference",
|
||||
"sidebarStyle"
|
||||
) VALUES (
|
||||
'global',
|
||||
'beenvoice',
|
||||
'Simple and efficient invoicing for freelancers and small businesses',
|
||||
'beenvoice',
|
||||
'$',
|
||||
'slate',
|
||||
NULL,
|
||||
'system',
|
||||
'beenvoice',
|
||||
'brand',
|
||||
'brand',
|
||||
'xl',
|
||||
'floating'
|
||||
) ON CONFLICT ("id") DO NOTHING;
|
||||
@@ -0,0 +1,14 @@
|
||||
ALTER TABLE "beenvoice_platform_setting"
|
||||
ADD COLUMN "pdfTemplate" varchar(20) DEFAULT 'classic' NOT NULL;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "beenvoice_platform_setting"
|
||||
ADD COLUMN "pdfAccentColor" varchar(50) DEFAULT '#111827' NOT NULL;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "beenvoice_platform_setting"
|
||||
ADD COLUMN "pdfFooterText" varchar(120) DEFAULT 'Professional Invoicing' NOT NULL;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "beenvoice_platform_setting"
|
||||
ADD COLUMN "pdfShowLogo" boolean DEFAULT true NOT NULL;
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "beenvoice_platform_setting"
|
||||
ADD COLUMN "pdfShowPageNumbers" boolean DEFAULT true NOT NULL;
|
||||
@@ -15,6 +15,41 @@
|
||||
"when": 1775356013998,
|
||||
"tag": "0001_supreme_the_enforcers",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 2,
|
||||
"version": "7",
|
||||
"when": 1775400000000,
|
||||
"tag": "0002_tax_deductible",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 3,
|
||||
"version": "7",
|
||||
"when": 1775600000000,
|
||||
"tag": "0003_appearance_preferences",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 4,
|
||||
"version": "7",
|
||||
"when": 1777336000000,
|
||||
"tag": "0004_platform_appearance_controls",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 5,
|
||||
"version": "7",
|
||||
"when": 1777337000000,
|
||||
"tag": "0005_platform_settings_and_roles",
|
||||
"breakpoints": true
|
||||
},
|
||||
{
|
||||
"idx": 6,
|
||||
"version": "7",
|
||||
"when": 1777338000000,
|
||||
"tag": "0006_pdf_generation_settings",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
+2
-1
@@ -6,7 +6,8 @@ import "./src/env.js";
|
||||
|
||||
/** @type {import("next").NextConfig} */
|
||||
const config = {
|
||||
serverExternalPackages: ['pg'],
|
||||
output: "standalone",
|
||||
serverExternalPackages: ["pg"],
|
||||
};
|
||||
|
||||
export default config;
|
||||
|
||||
+4
-4
@@ -7,12 +7,12 @@
|
||||
"build": "next build",
|
||||
"check": "eslint . && tsc --noEmit",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "bun src/server/db/migrate.ts",
|
||||
"db:migrate": "bun drizzle-kit migrate",
|
||||
"db:push": "drizzle-kit push",
|
||||
"db:studio": "drizzle-kit studio",
|
||||
"db:clone": "./scripts/clone-local.sh",
|
||||
"docker:up": "colima start && docker-compose up -d",
|
||||
"docker:down": "docker-compose down && colima stop",
|
||||
"docker:up": "colima start && docker compose up -d",
|
||||
"docker:down": "docker compose down && colima stop",
|
||||
"deploy": "drizzle-kit push && next build",
|
||||
"dev": "next dev --turbo",
|
||||
"format:check": "prettier --check \"**/*.{ts,tsx,js,jsx,mdx}\" --cache",
|
||||
@@ -64,6 +64,7 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"dotenv": "^17.2.3",
|
||||
"drizzle-orm": "^0.44.7",
|
||||
"file-saver": "^2.0.5",
|
||||
"framer-motion": "^12.23.26",
|
||||
@@ -92,7 +93,6 @@
|
||||
"@types/react": "^19.2.7",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"baseline-browser-mapping": "^2.9.6",
|
||||
"dotenv": "^17.2.3",
|
||||
"drizzle-kit": "^0.30.6",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-config-next": "^16.0.10",
|
||||
|
||||
@@ -55,6 +55,20 @@ export async function POST(request: NextRequest) {
|
||||
})
|
||||
.where(eq(users.id, user.id));
|
||||
|
||||
if (!env.RESEND_API_KEY) {
|
||||
console.warn(
|
||||
"Password reset requested, but RESEND_API_KEY is not configured.",
|
||||
);
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: true,
|
||||
message:
|
||||
"If an account with that email exists, password reset instructions have been sent.",
|
||||
},
|
||||
{ status: 200 },
|
||||
);
|
||||
}
|
||||
|
||||
// Send password reset email using Resend
|
||||
try {
|
||||
const resend = new Resend(env.RESEND_API_KEY);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { Label } from "~/components/ui/label";
|
||||
import { toast } from "sonner";
|
||||
import { Logo } from "~/components/branding/logo";
|
||||
import { LegalModal } from "~/components/ui/legal-modal";
|
||||
import { env } from "~/env";
|
||||
import {
|
||||
Mail,
|
||||
Lock,
|
||||
@@ -21,6 +22,7 @@ import {
|
||||
} from "lucide-react";
|
||||
|
||||
function SignInForm() {
|
||||
const authentikEnabled = env.NEXT_PUBLIC_AUTHENTIK_ENABLED === true;
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const callbackUrl = searchParams.get("callbackUrl") ?? "/dashboard";
|
||||
@@ -63,24 +65,27 @@ function SignInForm() {
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center relative overflow-hidden">
|
||||
<div className="relative flex min-h-screen items-center justify-center overflow-hidden">
|
||||
{/* Blob Background */}
|
||||
<div className="fixed inset-0 -z-10 overflow-hidden pointer-events-none flex items-center justify-center">
|
||||
<div className="pointer-events-none fixed inset-0 -z-10 flex items-center justify-center overflow-hidden">
|
||||
<div className="absolute inset-0 bg-[linear-gradient(to_right,#80808012_1px,transparent_1px),linear-gradient(to_bottom,#80808012_1px,transparent_1px)] bg-[size:24px_24px]"></div>
|
||||
<div className="w-[800px] h-[800px] bg-neutral-400/30 dark:bg-neutral-500/20 rounded-full blur-3xl animate-blob"></div>
|
||||
<div className="animate-blob h-[800px] w-[800px] rounded-full bg-neutral-400/30 blur-3xl dark:bg-neutral-500/20"></div>
|
||||
</div>
|
||||
|
||||
<Card className="mx-auto h-screen w-full overflow-hidden border-0 shadow-none md:h-auto md:max-w-6xl md:border md:shadow-2xl md:bg-background/80 md:backdrop-blur-xl md:border-border/50 md:rounded-3xl">
|
||||
<Card className="md:bg-background/80 md:border-border/50 mx-auto h-screen w-full overflow-hidden border-0 shadow-none md:h-auto md:max-w-6xl md:rounded-3xl md:border md:shadow-2xl md:backdrop-blur-xl">
|
||||
<CardContent className="grid h-full p-0 md:grid-cols-2">
|
||||
{/* Hero Section - Hidden on mobile */}
|
||||
<div className="bg-primary/5 relative hidden md:flex md:flex-col md:justify-center md:p-12 border-r border-border/50">
|
||||
<div className="bg-primary/5 border-border/50 relative hidden border-r md:flex md:flex-col md:justify-center md:p-12">
|
||||
<div className="space-y-8">
|
||||
<div className="space-y-4">
|
||||
<Logo size="xl" />
|
||||
<div className="space-y-3">
|
||||
<h1 className="text-3xl font-bold lg:text-4xl font-heading">
|
||||
<h1 className="font-heading text-3xl font-bold lg:text-4xl">
|
||||
Welcome back to your
|
||||
<span className="text-primary italic"> invoicing workspace</span>
|
||||
<span className="text-primary italic">
|
||||
{" "}
|
||||
invoicing workspace
|
||||
</span>
|
||||
</h1>
|
||||
<p className="text-muted-foreground text-lg">
|
||||
Continue managing your clients and creating professional
|
||||
@@ -95,7 +100,9 @@ function SignInForm() {
|
||||
<Users className="text-primary h-5 w-5" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h3 className="font-semibold text-foreground">Client Management</h3>
|
||||
<h3 className="text-foreground font-semibold">
|
||||
Client Management
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Organize and track all your clients in one place
|
||||
</p>
|
||||
@@ -107,7 +114,9 @@ function SignInForm() {
|
||||
<FileText className="text-primary h-5 w-5" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h3 className="font-semibold text-foreground">Professional Invoices</h3>
|
||||
<h3 className="text-foreground font-semibold">
|
||||
Professional Invoices
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Beautiful templates that get you paid faster
|
||||
</p>
|
||||
@@ -119,7 +128,9 @@ function SignInForm() {
|
||||
<TrendingUp className="text-primary h-5 w-5" />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<h3 className="font-semibold text-foreground">Payment Tracking</h3>
|
||||
<h3 className="text-foreground font-semibold">
|
||||
Payment Tracking
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
Monitor your income with real-time insights
|
||||
</p>
|
||||
@@ -138,35 +149,37 @@ function SignInForm() {
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 text-center md:text-left">
|
||||
<h1 className="text-3xl font-bold font-heading">Sign In</h1>
|
||||
<h1 className="font-heading text-3xl font-bold">Sign In</h1>
|
||||
<p className="text-muted-foreground">
|
||||
Enter your credentials to access your account
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
type="button"
|
||||
className="w-full h-11 relative rounded-xl"
|
||||
onClick={handleSocialSignIn}
|
||||
disabled={loading}
|
||||
>
|
||||
<Shield className="mr-2 h-4 w-4" />
|
||||
Sign in with Authentik
|
||||
</Button>
|
||||
{authentikEnabled && (
|
||||
<div className="space-y-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
type="button"
|
||||
className="relative h-11 w-full rounded-xl"
|
||||
onClick={handleSocialSignIn}
|
||||
disabled={loading}
|
||||
>
|
||||
<Shield className="mr-2 h-4 w-4" />
|
||||
Sign in with Authentik
|
||||
</Button>
|
||||
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="w-full border-t border-border/50" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-background px-2 text-muted-foreground">
|
||||
Or continue with
|
||||
</span>
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<span className="border-border/50 w-full border-t" />
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-background text-muted-foreground px-2">
|
||||
Or continue with
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<form onSubmit={handleSignIn} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
@@ -180,7 +193,7 @@ function SignInForm() {
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
autoFocus
|
||||
className="h-11 pl-10 bg-background/50 border-border/60 focus:bg-background transition-all"
|
||||
className="bg-background/50 border-border/60 focus:bg-background h-11 pl-10 transition-all"
|
||||
placeholder="m@example.com"
|
||||
/>
|
||||
</div>
|
||||
@@ -204,7 +217,7 @@ function SignInForm() {
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
className="h-11 pl-10 bg-background/50 border-border/60 focus:bg-background transition-all"
|
||||
className="bg-background/50 border-border/60 focus:bg-background h-11 pl-10 transition-all"
|
||||
placeholder="Enter your password"
|
||||
/>
|
||||
</div>
|
||||
@@ -212,7 +225,7 @@ function SignInForm() {
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="h-11 w-full rounded-xl text-base shadow-lg shadow-primary/20 hover:shadow-primary/30"
|
||||
className="shadow-primary/20 hover:shadow-primary/30 h-11 w-full rounded-xl text-base shadow-lg"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? (
|
||||
|
||||
@@ -29,7 +29,7 @@ import { NumberInput } from "~/components/ui/number-input";
|
||||
import { toast } from "sonner";
|
||||
import { Plus, Pencil, Trash2, Receipt } from "lucide-react";
|
||||
import { formatCurrency, SUPPORTED_CURRENCIES } from "~/lib/currency";
|
||||
import { EXPENSE_CATEGORIES } from "~/server/api/routers/expenses";
|
||||
import { EXPENSE_CATEGORIES } from "~/lib/expense-categories";
|
||||
|
||||
interface ExpenseFormData {
|
||||
date: Date;
|
||||
@@ -39,6 +39,7 @@ interface ExpenseFormData {
|
||||
category: string;
|
||||
billable: boolean;
|
||||
reimbursable: boolean;
|
||||
taxDeductible: boolean;
|
||||
notes: string;
|
||||
clientId: string;
|
||||
}
|
||||
@@ -51,6 +52,7 @@ const defaultForm: ExpenseFormData = {
|
||||
category: "",
|
||||
billable: false,
|
||||
reimbursable: false,
|
||||
taxDeductible: false,
|
||||
notes: "",
|
||||
clientId: "",
|
||||
};
|
||||
@@ -89,6 +91,7 @@ export default function ExpensesPage() {
|
||||
category: expense.category ?? "",
|
||||
billable: expense.billable,
|
||||
reimbursable: expense.reimbursable,
|
||||
taxDeductible: expense.taxDeductible ?? false,
|
||||
notes: expense.notes ?? "",
|
||||
clientId: expense.clientId ?? "",
|
||||
});
|
||||
@@ -97,13 +100,14 @@ export default function ExpensesPage() {
|
||||
const handleSubmit = () => {
|
||||
if (!form.description.trim()) { toast.error("Description is required"); return; }
|
||||
if (form.amount <= 0) { toast.error("Amount must be greater than 0"); return; }
|
||||
const payload = { ...form, clientId: form.clientId || undefined, category: form.category || undefined, notes: form.notes || undefined };
|
||||
const payload = { ...form, clientId: form.clientId || undefined, category: form.category || undefined, notes: form.notes || undefined, taxDeductible: form.taxDeductible };
|
||||
if (editId) update.mutate({ id: editId, ...payload });
|
||||
else create.mutate(payload);
|
||||
};
|
||||
|
||||
const totalExpenses = expenses.reduce((s, e) => s + e.amount, 0);
|
||||
const billableTotal = expenses.filter((e) => e.billable).reduce((s, e) => s + e.amount, 0);
|
||||
const deductibleTotal = expenses.filter((e) => e.taxDeductible).reduce((s, e) => s + e.amount, 0);
|
||||
|
||||
return (
|
||||
<div className="page-enter space-y-6 pb-6">
|
||||
@@ -114,7 +118,7 @@ export default function ExpensesPage() {
|
||||
</PageHeader>
|
||||
|
||||
{/* Summary cards */}
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3">
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">Total</p>
|
||||
@@ -127,7 +131,13 @@ export default function ExpensesPage() {
|
||||
<p className="text-primary mt-1 text-2xl font-bold">{formatCurrency(billableTotal)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card className="col-span-2 sm:col-span-1">
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">Deductible</p>
|
||||
<p className="mt-1 text-2xl font-bold text-green-600">{formatCurrency(deductibleTotal)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<p className="text-muted-foreground text-xs font-medium uppercase tracking-wide">Count</p>
|
||||
<p className="mt-1 text-2xl font-bold">{expenses.length}</p>
|
||||
@@ -159,6 +169,7 @@ export default function ExpensesPage() {
|
||||
<p className="font-medium">{expense.description}</p>
|
||||
{expense.billable && <Badge variant="secondary" className="text-xs">Billable</Badge>}
|
||||
{expense.reimbursable && <Badge variant="outline" className="text-xs">Reimbursable</Badge>}
|
||||
{expense.taxDeductible && <Badge variant="outline" className="text-xs text-green-600 border-green-300">Tax Deductible</Badge>}
|
||||
{expense.category && <Badge variant="outline" className="text-xs">{expense.category}</Badge>}
|
||||
</div>
|
||||
<p className="text-muted-foreground mt-0.5 text-xs">
|
||||
@@ -229,7 +240,7 @@ export default function ExpensesPage() {
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex gap-6">
|
||||
<div className="flex flex-wrap gap-6">
|
||||
<label className="flex cursor-pointer items-center gap-2">
|
||||
<Checkbox checked={form.billable} onCheckedChange={(v) => setForm((p) => ({ ...p, billable: !!v }))} />
|
||||
<span className="text-sm">Billable</span>
|
||||
@@ -238,6 +249,10 @@ export default function ExpensesPage() {
|
||||
<Checkbox checked={form.reimbursable} onCheckedChange={(v) => setForm((p) => ({ ...p, reimbursable: !!v }))} />
|
||||
<span className="text-sm">Reimbursable</span>
|
||||
</label>
|
||||
<label className="flex cursor-pointer items-center gap-2">
|
||||
<Checkbox checked={form.taxDeductible} onCheckedChange={(v) => setForm((p) => ({ ...p, taxDeductible: !!v }))} />
|
||||
<span className="text-sm">Tax Deductible</span>
|
||||
</label>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Notes (optional)</Label>
|
||||
|
||||
@@ -30,15 +30,15 @@ export function InvoiceDetailsSkeleton() {
|
||||
<Skeleton className="h-8 w-48" />
|
||||
<Skeleton className="h-6 w-24 rounded-full" />
|
||||
</div>
|
||||
<div className="space-y-1 sm:space-y-0 text-sm">
|
||||
<div className="space-y-1 text-sm sm:space-y-0">
|
||||
<div className="flex gap-2">
|
||||
<Skeleton className="h-4 w-32" />
|
||||
<Skeleton className="h-4 w-32 hidden sm:block" />
|
||||
<Skeleton className="hidden h-4 w-32 sm:block" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-shrink-0 text-left sm:text-right">
|
||||
<Skeleton className="h-4 w-24 mb-1 sm:ml-auto" />
|
||||
<Skeleton className="mb-1 h-4 w-24 sm:ml-auto" />
|
||||
<Skeleton className="h-9 w-32 sm:ml-auto" />
|
||||
</div>
|
||||
</div>
|
||||
@@ -118,7 +118,7 @@ export function InvoiceDetailsSkeleton() {
|
||||
<div className="space-y-3">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
|
||||
<div className="min-w-0 flex-1">
|
||||
<Skeleton className="h-5 w-3/4 mb-2" />
|
||||
<Skeleton className="mb-2 h-5 w-3/4" />
|
||||
<div className="flex gap-4">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-4 w-16" />
|
||||
@@ -156,7 +156,7 @@ export function InvoiceDetailsSkeleton() {
|
||||
|
||||
{/* Right Column - Actions */}
|
||||
<div className="space-y-6">
|
||||
<Card className="sticky top-20">
|
||||
<Card className="lg:sticky lg:top-6">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Skeleton className="h-5 w-5 rounded-full" />
|
||||
|
||||
@@ -25,6 +25,9 @@ export function PDFDownloadButton({
|
||||
{ id: invoiceId },
|
||||
{ enabled: false },
|
||||
);
|
||||
const { data: platformTheme } = api.settings.getTheme.useQuery(undefined, {
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
const handleDownloadPDF = async () => {
|
||||
if (isGenerating) return;
|
||||
@@ -39,7 +42,29 @@ export function PDFDownloadButton({
|
||||
throw new Error("Invoice not found");
|
||||
}
|
||||
|
||||
await generateInvoicePDF(invoiceData);
|
||||
// Map invoice to PDF format with currency support
|
||||
const pdfData = {
|
||||
invoiceNumber: invoiceData.invoiceNumber,
|
||||
invoicePrefix: invoiceData.invoicePrefix,
|
||||
issueDate: new Date(invoiceData.issueDate),
|
||||
dueDate: new Date(invoiceData.dueDate),
|
||||
status: invoiceData.status,
|
||||
totalAmount: invoiceData.totalAmount,
|
||||
taxRate: invoiceData.taxRate,
|
||||
currency: invoiceData.currency ?? "USD",
|
||||
notes: invoiceData.notes,
|
||||
business: invoiceData.business,
|
||||
client: invoiceData.client,
|
||||
items: invoiceData.items,
|
||||
};
|
||||
|
||||
await generateInvoicePDF(pdfData, {
|
||||
pdfTemplate: platformTheme?.pdfTemplate,
|
||||
pdfAccentColor: platformTheme?.pdfAccentColor,
|
||||
pdfFooterText: platformTheme?.pdfFooterText,
|
||||
pdfShowLogo: platformTheme?.pdfShowLogo,
|
||||
pdfShowPageNumbers: platformTheme?.pdfShowPageNumbers,
|
||||
});
|
||||
toast.success("PDF downloaded successfully");
|
||||
} catch (error) {
|
||||
console.error("PDF generation error:", error);
|
||||
|
||||
@@ -411,7 +411,7 @@ function InvoiceViewContent({ invoiceId }: { invoiceId: string }) {
|
||||
|
||||
{/* Right Column - Actions */}
|
||||
<div className="space-y-6">
|
||||
<Card className="sticky top-20">
|
||||
<Card className="lg:sticky lg:top-6">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Check className="h-5 w-5" />
|
||||
|
||||
+364
-166
@@ -1,10 +1,14 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import { useMemo, useState } from "react";
|
||||
import { api } from "~/trpc/react";
|
||||
import { PageHeader } from "~/components/layout/page-header";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { StatusBadge } from "~/components/data/status-badge";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "~/components/ui/select";
|
||||
import { Separator } from "~/components/ui/separator";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "~/components/ui/tabs";
|
||||
import { formatCurrency } from "~/lib/currency";
|
||||
import { getEffectiveInvoiceStatus } from "~/lib/invoice-status";
|
||||
import type { StoredInvoiceStatus } from "~/types/invoice";
|
||||
@@ -19,18 +23,28 @@ import {
|
||||
Tooltip,
|
||||
ResponsiveContainer,
|
||||
} from "recharts";
|
||||
import { TrendingUp, DollarSign, Clock, Users } from "lucide-react";
|
||||
import { TrendingUp, DollarSign, Clock, Users, Download, Receipt, FileText } from "lucide-react";
|
||||
|
||||
function toNumericChartValue(value: unknown) {
|
||||
const numericValue = typeof value === "number" ? value : Number(value ?? 0);
|
||||
return Number.isFinite(numericValue) ? numericValue : 0;
|
||||
}
|
||||
|
||||
export default function ReportsPage() {
|
||||
const { data: invoices = [], isLoading } = api.invoices.getAll.useQuery();
|
||||
const { data: invoices = [], isLoading: invoicesLoading } = api.invoices.getAll.useQuery();
|
||||
const { data: expenses = [], isLoading: expensesLoading } = api.expenses.getAll.useQuery();
|
||||
const { data: stats } = api.dashboard.getStats.useQuery();
|
||||
|
||||
const now = new Date();
|
||||
const isLoading = invoicesLoading || expensesLoading;
|
||||
|
||||
const reportData = useMemo(() => {
|
||||
const now = new Date();
|
||||
const currentYear = now.getFullYear();
|
||||
const [taxYear, setTaxYear] = useState(String(currentYear));
|
||||
|
||||
// Overview data (last 12 months)
|
||||
const overviewData = useMemo(() => {
|
||||
if (!invoices.length) return null;
|
||||
|
||||
// Revenue by month (last 12 months)
|
||||
const monthMap: Record<string, number> = {};
|
||||
for (let i = 11; i >= 0; i--) {
|
||||
const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
|
||||
@@ -41,7 +55,6 @@ export default function ReportsPage() {
|
||||
let totalRevenue = 0;
|
||||
let totalPending = 0;
|
||||
let totalHours = 0;
|
||||
let overdueCount = 0;
|
||||
|
||||
for (const inv of invoices) {
|
||||
const status = getEffectiveInvoiceStatus(inv.status as StoredInvoiceStatus, inv.dueDate);
|
||||
@@ -52,7 +65,6 @@ export default function ReportsPage() {
|
||||
} else if (status === "sent" || status === "overdue") {
|
||||
totalPending += inv.totalAmount;
|
||||
}
|
||||
if (status === "overdue") overdueCount++;
|
||||
totalHours += (inv.items ?? []).reduce((s, item) => s + item.hours, 0);
|
||||
}
|
||||
|
||||
@@ -61,35 +73,122 @@ export default function ReportsPage() {
|
||||
revenue,
|
||||
}));
|
||||
|
||||
// Top clients by revenue (paid only)
|
||||
const clientMap: Record<string, { name: string; revenue: number; count: number }> = {};
|
||||
const clientMap: Record<string, { name: string; revenue: number }> = {};
|
||||
for (const inv of invoices) {
|
||||
const status = getEffectiveInvoiceStatus(inv.status as StoredInvoiceStatus, inv.dueDate);
|
||||
if (status === "paid" && inv.client) {
|
||||
const id = inv.client.id;
|
||||
if (!clientMap[id]) clientMap[id] = { name: inv.client.name, revenue: 0, count: 0 };
|
||||
if (!clientMap[id]) clientMap[id] = { name: inv.client.name, revenue: 0 };
|
||||
clientMap[id]!.revenue += inv.totalAmount;
|
||||
clientMap[id]!.count += 1;
|
||||
}
|
||||
}
|
||||
const topClients = Object.values(clientMap)
|
||||
.sort((a, b) => b.revenue - a.revenue)
|
||||
.slice(0, 6);
|
||||
const topClients = Object.values(clientMap).sort((a, b) => b.revenue - a.revenue).slice(0, 6);
|
||||
|
||||
// Status breakdown
|
||||
const statusCount: Record<string, number> = { draft: 0, sent: 0, paid: 0, overdue: 0 };
|
||||
for (const inv of invoices) {
|
||||
const s = getEffectiveInvoiceStatus(inv.status as StoredInvoiceStatus, inv.dueDate);
|
||||
statusCount[s] = (statusCount[s] ?? 0) + 1;
|
||||
}
|
||||
|
||||
return { revenueByMonth, topClients, totalRevenue, totalPending, totalHours, overdueCount, statusCount };
|
||||
return { revenueByMonth, topClients, totalRevenue, totalPending, totalHours, statusCount };
|
||||
}, [invoices]);
|
||||
|
||||
// Tax summary for selected year
|
||||
const taxData = useMemo(() => {
|
||||
const year = parseInt(taxYear);
|
||||
|
||||
const yearInvoices = invoices.filter((inv) => {
|
||||
const status = getEffectiveInvoiceStatus(inv.status as StoredInvoiceStatus, inv.dueDate);
|
||||
return status === "paid" && new Date(inv.issueDate).getFullYear() === year;
|
||||
});
|
||||
const yearExpenses = expenses.filter((exp) => new Date(exp.date).getFullYear() === year);
|
||||
|
||||
const grossIncome = yearInvoices.reduce((s, inv) => s + inv.totalAmount, 0);
|
||||
const taxCollected = yearInvoices.reduce((s, inv) => s + inv.totalAmount * (inv.taxRate ?? 0), 0);
|
||||
const totalExpenses = yearExpenses.reduce((s, exp) => s + exp.amount, 0);
|
||||
const deductibleExpenses = yearExpenses
|
||||
.filter((exp) => (exp as typeof exp & { taxDeductible?: boolean }).taxDeductible)
|
||||
.reduce((s, exp) => s + exp.amount, 0);
|
||||
|
||||
const netProfit = grossIncome - deductibleExpenses;
|
||||
const seTaxBase = Math.max(0, netProfit) * 0.9235;
|
||||
const selfEmploymentTax = seTaxBase * 0.153;
|
||||
const taxableIncome = Math.max(0, netProfit - selfEmploymentTax / 2);
|
||||
const federalEstimate = taxableIncome * 0.22;
|
||||
const totalEstimated = selfEmploymentTax + federalEstimate;
|
||||
|
||||
const quarters = [1, 2, 3, 4].map((q) => {
|
||||
const qMonths = [(q - 1) * 3, (q - 1) * 3 + 1, (q - 1) * 3 + 2];
|
||||
return {
|
||||
label: `Q${q}`,
|
||||
income: yearInvoices.filter((inv) => qMonths.includes(new Date(inv.issueDate).getMonth())).reduce((s, inv) => s + inv.totalAmount, 0),
|
||||
expenses: yearExpenses.filter((exp) => qMonths.includes(new Date(exp.date).getMonth())).reduce((s, exp) => s + exp.amount, 0),
|
||||
};
|
||||
});
|
||||
|
||||
return { grossIncome, taxCollected, totalInvoiced: grossIncome + taxCollected, totalExpenses, deductibleExpenses, netProfit, selfEmploymentTax, federalEstimate, totalEstimated, quarters, yearInvoices, yearExpenses };
|
||||
}, [invoices, expenses, taxYear]);
|
||||
|
||||
const availableYears = useMemo(() => {
|
||||
const years = new Set<number>([currentYear, currentYear - 1]);
|
||||
for (const inv of invoices) years.add(new Date(inv.issueDate).getFullYear());
|
||||
for (const exp of expenses) years.add(new Date(exp.date).getFullYear());
|
||||
return Array.from(years).sort((a, b) => b - a);
|
||||
}, [invoices, expenses, currentYear]);
|
||||
|
||||
const avgInvoice = invoices.length > 0
|
||||
? (overviewData?.totalRevenue ?? 0) / (invoices.filter((i) => getEffectiveInvoiceStatus(i.status as StoredInvoiceStatus, i.dueDate) === "paid").length || 1)
|
||||
: 0;
|
||||
|
||||
function exportCSV() {
|
||||
const rows: string[] = [
|
||||
`Tax Year ${taxYear} - Income & Expense Report`,
|
||||
`Generated: ${new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" })}`,
|
||||
"",
|
||||
"INCOME (Paid Invoices)",
|
||||
"Date,Invoice #,Client,Subtotal,Tax Rate,Tax Amount,Total",
|
||||
...taxData.yearInvoices.map((inv) => {
|
||||
const taxAmt = inv.totalAmount * (inv.taxRate ?? 0);
|
||||
return [new Date(inv.issueDate).toLocaleDateString("en-US"), inv.invoiceNumber, `"${inv.client?.name ?? ""}"`, inv.totalAmount.toFixed(2), `${((inv.taxRate ?? 0) * 100).toFixed(1)}%`, taxAmt.toFixed(2), (inv.totalAmount + taxAmt).toFixed(2)].join(",");
|
||||
}),
|
||||
`,,Totals,${taxData.grossIncome.toFixed(2)},,${taxData.taxCollected.toFixed(2)},${taxData.totalInvoiced.toFixed(2)}`,
|
||||
"",
|
||||
"EXPENSES",
|
||||
"Date,Description,Category,Amount,Currency,Billable,Reimbursable,Tax Deductible",
|
||||
...taxData.yearExpenses.map((exp) => [
|
||||
new Date(exp.date).toLocaleDateString("en-US"),
|
||||
`"${exp.description}"`,
|
||||
`"${exp.category ?? ""}"`,
|
||||
exp.amount.toFixed(2),
|
||||
exp.currency,
|
||||
exp.billable ? "Yes" : "No",
|
||||
exp.reimbursable ? "Yes" : "No",
|
||||
(exp as typeof exp & { taxDeductible?: boolean }).taxDeductible ? "Yes" : "No",
|
||||
].join(",")),
|
||||
`,,Totals,${taxData.totalExpenses.toFixed(2)},,,,"Deductible: ${taxData.deductibleExpenses.toFixed(2)}"`,
|
||||
"",
|
||||
"TAX SUMMARY",
|
||||
`Gross Income,${taxData.grossIncome.toFixed(2)}`,
|
||||
`Tax Collected,${taxData.taxCollected.toFixed(2)}`,
|
||||
`Deductible Expenses,${taxData.deductibleExpenses.toFixed(2)}`,
|
||||
`Net Profit,${taxData.netProfit.toFixed(2)}`,
|
||||
`Est. Self-Employment Tax (15.3%),${taxData.selfEmploymentTax.toFixed(2)}`,
|
||||
`Est. Federal Income Tax (22%),${taxData.federalEstimate.toFixed(2)}`,
|
||||
`Total Estimated Tax,${taxData.totalEstimated.toFixed(2)}`,
|
||||
];
|
||||
const blob = new Blob([rows.join("\n")], { type: "text/csv;charset=utf-8;" });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = `tax-report-${taxYear}.csv`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
}
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="page-enter space-y-6">
|
||||
<PageHeader title="Reports" description="Revenue and invoice analytics" variant="gradient" />
|
||||
<PageHeader title="Reports" description="Revenue and tax analytics" variant="gradient" />
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
|
||||
{[...Array(4)].map((_, i) => <div key={i} className="bg-muted h-24 animate-pulse rounded-xl" />)}
|
||||
</div>
|
||||
@@ -97,165 +196,264 @@ export default function ReportsPage() {
|
||||
);
|
||||
}
|
||||
|
||||
const avgInvoice = invoices.length > 0 ? (reportData?.totalRevenue ?? 0) / invoices.filter((i) => getEffectiveInvoiceStatus(i.status as StoredInvoiceStatus, i.dueDate) === "paid").length || 0 : 0;
|
||||
|
||||
return (
|
||||
<div className="page-enter space-y-6 pb-6">
|
||||
<PageHeader title="Reports" description="Revenue and invoice analytics" variant="gradient" />
|
||||
<PageHeader title="Reports" description="Revenue and tax analytics" variant="gradient" />
|
||||
|
||||
{/* KPI cards */}
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-primary/10 rounded p-1.5">
|
||||
<DollarSign className="text-primary h-4 w-4" />
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs font-medium">Total Revenue</p>
|
||||
</div>
|
||||
<p className="mt-2 text-2xl font-bold">{formatCurrency(reportData?.totalRevenue ?? 0)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-yellow-500/10 rounded p-1.5">
|
||||
<Clock className="h-4 w-4 text-yellow-500" />
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs font-medium">Pending</p>
|
||||
</div>
|
||||
<p className="mt-2 text-2xl font-bold">{formatCurrency(reportData?.totalPending ?? 0)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-blue-500/10 rounded p-1.5">
|
||||
<TrendingUp className="h-4 w-4 text-blue-500" />
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs font-medium">Avg Invoice</p>
|
||||
</div>
|
||||
<p className="mt-2 text-2xl font-bold">{formatCurrency(isNaN(avgInvoice) ? 0 : avgInvoice)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-green-500/10 rounded p-1.5">
|
||||
<Users className="h-4 w-4 text-green-500" />
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs font-medium">Total Hours</p>
|
||||
</div>
|
||||
<p className="mt-2 text-2xl font-bold">{(reportData?.totalHours ?? 0).toFixed(1)}h</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<Tabs defaultValue="overview">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="overview"><TrendingUp className="mr-1.5 h-4 w-4" /> Overview</TabsTrigger>
|
||||
<TabsTrigger value="tax"><FileText className="mr-1.5 h-4 w-4" /> Tax Summary</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* Revenue trend chart */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<TrendingUp className="h-5 w-5" /> Revenue (Last 12 Months)
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="h-48 w-full md:h-64">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={reportData?.revenueByMonth ?? []}>
|
||||
<defs>
|
||||
<linearGradient id="revenueGrad" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="hsl(142, 76%, 36%)" stopOpacity={0.3} />
|
||||
<stop offset="95%" stopColor="hsl(142, 76%, 36%)" stopOpacity={0.02} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" className="stroke-border" />
|
||||
<XAxis dataKey="month" tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }} axisLine={false} tickLine={false} />
|
||||
<YAxis tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }} axisLine={false} tickLine={false} tickFormatter={(v: number) => `$${v >= 1000 ? `${(v / 1000).toFixed(0)}k` : v}`} />
|
||||
<Tooltip formatter={(v: number) => [formatCurrency(v), "Revenue"]} contentStyle={{ background: "hsl(var(--card))", border: "1px solid hsl(var(--border))", borderRadius: "8px", fontSize: 12 }} />
|
||||
<Area type="monotone" dataKey="revenue" stroke="hsl(142, 76%, 36%)" fill="url(#revenueGrad)" strokeWidth={2} dot={false} />
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
{/* ── OVERVIEW TAB ── */}
|
||||
<TabsContent value="overview" className="mt-4 space-y-6">
|
||||
<div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-primary/10 rounded p-1.5"><DollarSign className="text-primary h-4 w-4" /></div>
|
||||
<p className="text-muted-foreground text-xs font-medium">Total Revenue</p>
|
||||
</div>
|
||||
<p className="mt-2 text-2xl font-bold">{formatCurrency(overviewData?.totalRevenue ?? 0)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-yellow-500/10 rounded p-1.5"><Clock className="h-4 w-4 text-yellow-500" /></div>
|
||||
<p className="text-muted-foreground text-xs font-medium">Pending</p>
|
||||
</div>
|
||||
<p className="mt-2 text-2xl font-bold">{formatCurrency(overviewData?.totalPending ?? 0)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-blue-500/10 rounded p-1.5"><TrendingUp className="h-4 w-4 text-blue-500" /></div>
|
||||
<p className="text-muted-foreground text-xs font-medium">Avg Invoice</p>
|
||||
</div>
|
||||
<p className="mt-2 text-2xl font-bold">{formatCurrency(isNaN(avgInvoice) ? 0 : avgInvoice)}</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="p-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="bg-green-500/10 rounded p-1.5"><Users className="h-4 w-4 text-green-500" /></div>
|
||||
<p className="text-muted-foreground text-xs font-medium">Total Hours</p>
|
||||
</div>
|
||||
<p className="mt-2 text-2xl font-bold">{(overviewData?.totalHours ?? 0).toFixed(1)}h</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
{/* Top clients */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Users className="h-5 w-5" /> Top Clients by Revenue
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{!reportData?.topClients.length ? (
|
||||
<p className="text-muted-foreground py-6 text-center text-sm">No paid invoices yet.</p>
|
||||
) : (
|
||||
<div className="h-48 md:h-56">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2"><TrendingUp className="h-5 w-5" /> Revenue (Last 12 Months)</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="h-48 w-full md:h-64">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={reportData.topClients} layout="vertical">
|
||||
<XAxis type="number" tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }} axisLine={false} tickLine={false} tickFormatter={(v: number) => `$${v >= 1000 ? `${(v / 1000).toFixed(0)}k` : v}`} />
|
||||
<YAxis type="category" dataKey="name" tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }} axisLine={false} tickLine={false} width={80} />
|
||||
<Tooltip formatter={(v: number) => [formatCurrency(v), "Revenue"]} contentStyle={{ background: "hsl(var(--card))", border: "1px solid hsl(var(--border))", borderRadius: "8px", fontSize: 12 }} />
|
||||
<Bar dataKey="revenue" fill="hsl(142, 76%, 36%)" radius={[0, 4, 4, 0]} />
|
||||
<AreaChart data={overviewData?.revenueByMonth ?? []}>
|
||||
<defs>
|
||||
<linearGradient id="revenueGrad" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="5%" stopColor="hsl(142, 76%, 36%)" stopOpacity={0.3} />
|
||||
<stop offset="95%" stopColor="hsl(142, 76%, 36%)" stopOpacity={0.02} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid strokeDasharray="3 3" className="stroke-border" />
|
||||
<XAxis dataKey="month" tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }} axisLine={false} tickLine={false} />
|
||||
<YAxis tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }} axisLine={false} tickLine={false} tickFormatter={(v: number) => `$${v >= 1000 ? `${(v / 1000).toFixed(0)}k` : v}`} />
|
||||
<Tooltip formatter={(value) => [formatCurrency(toNumericChartValue(value)), "Revenue"]} contentStyle={{ background: "hsl(var(--card))", border: "1px solid hsl(var(--border))", borderRadius: "8px", fontSize: 12 }} />
|
||||
<Area type="monotone" dataKey="revenue" stroke="hsl(142, 76%, 36%)" fill="url(#revenueGrad)" strokeWidth={2} dot={false} />
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-2">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2"><Users className="h-5 w-5" /> Top Clients by Revenue</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{!overviewData?.topClients.length ? (
|
||||
<p className="text-muted-foreground py-6 text-center text-sm">No paid invoices yet.</p>
|
||||
) : (
|
||||
<div className="h-48 md:h-56">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={overviewData.topClients} layout="vertical">
|
||||
<XAxis type="number" tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }} axisLine={false} tickLine={false} tickFormatter={(v: number) => `$${v >= 1000 ? `${(v / 1000).toFixed(0)}k` : v}`} />
|
||||
<YAxis type="category" dataKey="name" tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }} axisLine={false} tickLine={false} width={80} />
|
||||
<Tooltip formatter={(value) => [formatCurrency(toNumericChartValue(value)), "Revenue"]} contentStyle={{ background: "hsl(var(--card))", border: "1px solid hsl(var(--border))", borderRadius: "8px", fontSize: 12 }} />
|
||||
<Bar dataKey="revenue" fill="hsl(142, 76%, 36%)" radius={[0, 4, 4, 0]} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader><CardTitle>Invoice Status Breakdown</CardTitle></CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{Object.entries(overviewData?.statusCount ?? {}).map(([status, count]) => (
|
||||
<div key={status} className="flex items-center justify-between">
|
||||
<StatusBadge status={status as never} />
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="bg-muted h-2 w-24 overflow-hidden rounded-full sm:w-32">
|
||||
<div className="bg-primary h-full rounded-full" style={{ width: `${invoices.length ? (count / invoices.length) * 100 : 0}%` }} />
|
||||
</div>
|
||||
<span className="text-muted-foreground w-8 text-right text-sm">{count}</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{invoices.length === 0 && <p className="text-muted-foreground py-6 text-center text-sm">No invoices yet.</p>}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{stats && (
|
||||
<Card>
|
||||
<CardHeader><CardTitle>Recent Activity</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
<div className="divide-y">
|
||||
{stats.recentInvoices.map((inv) => (
|
||||
<div key={inv.id} className="flex items-center justify-between py-3">
|
||||
<div>
|
||||
<p className="font-medium">{inv.client?.name ?? "—"}</p>
|
||||
<p className="text-muted-foreground text-xs">{new Date(inv.issueDate).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<StatusBadge status={getEffectiveInvoiceStatus(inv.status as StoredInvoiceStatus, inv.dueDate) as never} />
|
||||
<p className="font-semibold">{formatCurrency(inv.totalAmount)}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</TabsContent>
|
||||
|
||||
{/* ── TAX SUMMARY TAB ── */}
|
||||
<TabsContent value="tax" className="mt-4 space-y-6">
|
||||
<div className="flex items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<span className="text-sm font-medium">Tax Year</span>
|
||||
<Select value={taxYear} onValueChange={setTaxYear}>
|
||||
<SelectTrigger className="w-28"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
{availableYears.map((y) => <SelectItem key={y} value={String(y)}>{y}</SelectItem>)}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<Button variant="outline" onClick={exportCSV} className="gap-2">
|
||||
<Download className="h-4 w-4" /> Export CSV
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Income */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2"><DollarSign className="h-5 w-5" /> Income</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Gross Income (paid invoices)</span>
|
||||
<span className="font-medium">{formatCurrency(taxData.grossIncome)}</span>
|
||||
</div>
|
||||
{taxData.taxCollected > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Tax Collected from Clients</span>
|
||||
<span className="font-medium">{formatCurrency(taxData.taxCollected)}</span>
|
||||
</div>
|
||||
)}
|
||||
<Separator />
|
||||
<div className="flex justify-between font-medium">
|
||||
<span>Total Invoiced (inc. tax)</span>
|
||||
<span>{formatCurrency(taxData.totalInvoiced)}</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Expenses */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2"><Receipt className="h-5 w-5" /> Expenses & Deductions</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Total Expenses</span>
|
||||
<span className="font-medium">{formatCurrency(taxData.totalExpenses)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Tax-Deductible Expenses</span>
|
||||
<span className="font-medium text-green-600">{formatCurrency(taxData.deductibleExpenses)}</span>
|
||||
</div>
|
||||
{taxData.totalExpenses > 0 && taxData.deductibleExpenses === 0 && (
|
||||
<p className="text-muted-foreground text-xs">Mark expenses as "Tax Deductible" in the Expenses page to include them here.</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Estimated tax */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2"><FileText className="h-5 w-5" /> Estimated Tax Liability</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Net Profit (income − deductible expenses)</span>
|
||||
<span className="font-medium">{formatCurrency(taxData.netProfit)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Self-Employment Tax (15.3% on 92.35% of net)</span>
|
||||
<span className="font-medium">{formatCurrency(taxData.selfEmploymentTax)}</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Federal Income Tax (est. 22% bracket)</span>
|
||||
<span className="font-medium">{formatCurrency(taxData.federalEstimate)}</span>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex justify-between text-lg font-bold">
|
||||
<span>Total Estimated Tax</span>
|
||||
<span className="text-destructive">{formatCurrency(taxData.totalEstimated)}</span>
|
||||
</div>
|
||||
<p className="text-muted-foreground text-xs pt-1">
|
||||
Assumes US self-employment tax rules and the 22% federal bracket. Consult a tax professional for accurate filing.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Quarterly chart */}
|
||||
<Card>
|
||||
<CardHeader><CardTitle>Quarterly Breakdown</CardTitle></CardHeader>
|
||||
<CardContent>
|
||||
<div className="h-48 md:h-64">
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<BarChart data={taxData.quarters}>
|
||||
<CartesianGrid strokeDasharray="3 3" className="stroke-border" />
|
||||
<XAxis dataKey="label" tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }} axisLine={false} tickLine={false} />
|
||||
<YAxis tick={{ fontSize: 11, fill: "hsl(var(--muted-foreground))" }} axisLine={false} tickLine={false} tickFormatter={(v: number) => `$${v >= 1000 ? `${(v / 1000).toFixed(0)}k` : v}`} />
|
||||
<Tooltip
|
||||
formatter={(value, name) => [formatCurrency(toNumericChartValue(value)), name === "income" ? "Income" : "Expenses"]}
|
||||
contentStyle={{ background: "hsl(var(--card))", border: "1px solid hsl(var(--border))", borderRadius: "8px", fontSize: 12 }}
|
||||
/>
|
||||
<Bar dataKey="income" name="income" fill="hsl(142, 76%, 36%)" radius={[4, 4, 0, 0]} />
|
||||
<Bar dataKey="expenses" name="expenses" fill="hsl(0, 84%, 60%)" radius={[4, 4, 0, 0]} opacity={0.75} />
|
||||
</BarChart>
|
||||
</ResponsiveContainer>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Invoice status breakdown */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Invoice Status Breakdown</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{Object.entries(reportData?.statusCount ?? {}).map(([status, count]) => (
|
||||
<div key={status} className="flex items-center justify-between">
|
||||
<StatusBadge status={status as never} />
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="bg-muted h-2 w-24 overflow-hidden rounded-full sm:w-32">
|
||||
<div
|
||||
className="bg-primary h-full rounded-full"
|
||||
style={{ width: `${invoices.length ? (count / invoices.length) * 100 : 0}%` }}
|
||||
/>
|
||||
</div>
|
||||
<span className="text-muted-foreground w-8 text-right text-sm">{count}</span>
|
||||
</div>
|
||||
<div className="mt-2 flex justify-center gap-6 text-xs text-muted-foreground">
|
||||
<span className="flex items-center gap-1.5"><span className="inline-block h-2.5 w-2.5 rounded-sm bg-green-600" /> Income</span>
|
||||
<span className="flex items-center gap-1.5"><span className="inline-block h-2.5 w-2.5 rounded-sm bg-red-500/75" /> Expenses</span>
|
||||
</div>
|
||||
))}
|
||||
{invoices.length === 0 && (
|
||||
<p className="text-muted-foreground py-6 text-center text-sm">No invoices yet.</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Monthly stats table */}
|
||||
{stats && (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Recent Activity</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="divide-y">
|
||||
{stats.recentInvoices.map((inv) => (
|
||||
<div key={inv.id} className="flex items-center justify-between py-3">
|
||||
<div>
|
||||
<p className="font-medium">{inv.client?.name ?? "—"}</p>
|
||||
<p className="text-muted-foreground text-xs">{new Date(inv.issueDate).toLocaleDateString("en-US", { month: "short", day: "numeric", year: "numeric" })}</p>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
<StatusBadge status={getEffectiveInvoiceStatus(inv.status as StoredInvoiceStatus, inv.dueDate) as never} />
|
||||
<p className="font-semibold">{formatCurrency(inv.totalAmount)}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+63
-13
@@ -6,26 +6,34 @@ import { Inter, Playfair_Display, Geist_Mono } from "next/font/google";
|
||||
import { TRPCReactProvider } from "~/trpc/react";
|
||||
import { Toaster } from "~/components/ui/sonner";
|
||||
import { AnimationPreferencesProvider } from "~/components/providers/animation-preferences-provider";
|
||||
|
||||
import { AppearanceProvider } from "~/components/providers/appearance-provider";
|
||||
import {
|
||||
brand,
|
||||
defaultBodyFontPreference,
|
||||
defaultFontPreference,
|
||||
defaultHeadingFontPreference,
|
||||
defaultInterfaceTheme,
|
||||
defaultRadiusPreference,
|
||||
defaultSidebarStyle,
|
||||
} from "~/lib/branding";
|
||||
|
||||
import { UmamiScript } from "~/components/analytics/umami-script";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "beenvoice - Invoicing Made Simple",
|
||||
description:
|
||||
"Simple and efficient invoicing for freelancers and small businesses",
|
||||
title: `${brand.name} - Invoicing Made Simple`,
|
||||
description: brand.tagline,
|
||||
icons: [{ rel: "icon", url: "/favicon.ico" }],
|
||||
};
|
||||
|
||||
const inter = Inter({
|
||||
subsets: ["latin"],
|
||||
variable: "--font-sans",
|
||||
variable: "--font-inter",
|
||||
display: "swap",
|
||||
});
|
||||
|
||||
const playfair = Playfair_Display({
|
||||
subsets: ["latin"],
|
||||
variable: "--font-heading",
|
||||
variable: "--font-playfair",
|
||||
display: "swap",
|
||||
});
|
||||
|
||||
@@ -42,20 +50,62 @@ export default function RootLayout({
|
||||
<html
|
||||
suppressHydrationWarning
|
||||
lang="en"
|
||||
data-interface-theme={defaultInterfaceTheme}
|
||||
data-font={defaultFontPreference}
|
||||
data-body-font={defaultBodyFontPreference}
|
||||
data-heading-font={defaultHeadingFontPreference}
|
||||
data-radius={defaultRadiusPreference}
|
||||
data-sidebar-style={defaultSidebarStyle}
|
||||
data-color-mode="system"
|
||||
data-color-theme="slate"
|
||||
className={`${inter.variable} ${playfair.variable} ${geistMono.variable}`}
|
||||
>
|
||||
<head>
|
||||
<script
|
||||
id="appearance-init"
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `
|
||||
try {
|
||||
var defaults = {
|
||||
interfaceTheme: "${defaultInterfaceTheme}",
|
||||
fontPreference: "${defaultFontPreference}",
|
||||
bodyFontPreference: "${defaultBodyFontPreference}",
|
||||
headingFontPreference: "${defaultHeadingFontPreference}",
|
||||
radiusPreference: "${defaultRadiusPreference}",
|
||||
sidebarStyle: "${defaultSidebarStyle}",
|
||||
colorMode: "system",
|
||||
colorTheme: "slate"
|
||||
};
|
||||
var stored = JSON.parse(localStorage.getItem("bv.appearance") || "{}");
|
||||
var appearance = Object.assign(defaults, stored);
|
||||
var root = document.documentElement;
|
||||
root.dataset.interfaceTheme = appearance.interfaceTheme;
|
||||
root.dataset.font = appearance.fontPreference;
|
||||
root.dataset.bodyFont = appearance.bodyFontPreference || appearance.fontPreference;
|
||||
root.dataset.headingFont = appearance.headingFontPreference || appearance.fontPreference;
|
||||
root.dataset.radius = appearance.radiusPreference;
|
||||
root.dataset.sidebarStyle = appearance.sidebarStyle;
|
||||
root.dataset.colorMode = appearance.colorMode;
|
||||
root.dataset.colorTheme = appearance.colorTheme;
|
||||
if (appearance.colorMode === "dark") root.classList.add("dark");
|
||||
if (appearance.customColor) root.style.setProperty("--custom-primary", appearance.customColor);
|
||||
} catch {}
|
||||
`,
|
||||
}}
|
||||
/>
|
||||
</head>
|
||||
<body className="bg-background text-foreground relative min-h-screen overflow-x-hidden font-sans antialiased">
|
||||
<div className="fixed inset-0 -z-10 overflow-hidden pointer-events-none flex items-center justify-center">
|
||||
<div className="brand-background pointer-events-none fixed inset-0 -z-10 flex items-center justify-center overflow-hidden">
|
||||
<div className="absolute inset-0 bg-[linear-gradient(to_right,#80808012_1px,transparent_1px),linear-gradient(to_bottom,#80808012_1px,transparent_1px)] bg-[size:24px_24px]"></div>
|
||||
<div className="w-[800px] h-[800px] bg-neutral-400/40 dark:bg-neutral-500/30 rounded-full blur-3xl animate-blob"></div>
|
||||
<div className="animate-blob h-[800px] w-[800px] rounded-full bg-neutral-400/40 blur-3xl dark:bg-neutral-500/30"></div>
|
||||
</div>
|
||||
|
||||
<TRPCReactProvider>
|
||||
<AnimationPreferencesProvider>
|
||||
<div className="relative z-10">
|
||||
{children}
|
||||
</div>
|
||||
</AnimationPreferencesProvider>
|
||||
<AppearanceProvider>
|
||||
<AnimationPreferencesProvider>
|
||||
<div className="relative z-10">{children}</div>
|
||||
</AnimationPreferencesProvider>
|
||||
</AppearanceProvider>
|
||||
<Toaster />
|
||||
<UmamiScript />
|
||||
</TRPCReactProvider>
|
||||
|
||||
+85
-49
@@ -12,20 +12,21 @@ import {
|
||||
BarChart3,
|
||||
Rocket,
|
||||
} from "lucide-react";
|
||||
import { brand } from "~/lib/branding";
|
||||
|
||||
export default function HomePage() {
|
||||
return (
|
||||
<div className="min-h-screen relative overflow-x-hidden">
|
||||
<div className="relative min-h-screen overflow-x-hidden">
|
||||
<AuthRedirect />
|
||||
|
||||
{/* Blob Background for Homepage */}
|
||||
<div className="fixed inset-0 -z-10 overflow-hidden pointer-events-none flex items-center justify-center">
|
||||
<div className="pointer-events-none fixed inset-0 -z-10 flex items-center justify-center overflow-hidden">
|
||||
<div className="absolute inset-0 bg-[linear-gradient(to_right,#80808012_1px,transparent_1px),linear-gradient(to_bottom,#80808012_1px,transparent_1px)] bg-[size:24px_24px]"></div>
|
||||
<div className="w-[800px] h-[800px] bg-neutral-400/30 dark:bg-neutral-500/20 rounded-full blur-3xl animate-blob"></div>
|
||||
<div className="animate-blob h-[800px] w-[800px] rounded-full bg-neutral-400/30 blur-3xl dark:bg-neutral-500/20"></div>
|
||||
</div>
|
||||
|
||||
{/* Navigation */}
|
||||
<nav className="fixed top-4 left-4 right-4 z-50 m-4 rounded-2xl border border-border/60 bg-background/80 backdrop-blur-md">
|
||||
<nav className="border-border/60 bg-background/80 fixed top-4 right-4 left-4 z-50 m-4 rounded-2xl border backdrop-blur-md">
|
||||
<div className="mx-auto px-6">
|
||||
<div className="flex h-16 items-center justify-between">
|
||||
<Logo />
|
||||
@@ -67,25 +68,25 @@ export default function HomePage() {
|
||||
<section className="relative pt-48 pb-32">
|
||||
<div className="container mx-auto px-4 text-center">
|
||||
<div className="mx-auto max-w-4xl">
|
||||
<Badge className="bg-primary/10 text-primary border-primary/20 mb-8 border px-4 py-1 text-sm rounded-full">
|
||||
<Badge className="bg-primary/10 text-primary border-primary/20 mb-8 rounded-full border px-4 py-1 text-sm">
|
||||
<Zap className="mr-2 h-3.5 w-3.5" />
|
||||
Completely Free for Everyone
|
||||
</Badge>
|
||||
|
||||
<h1 className="text-foreground mb-8 text-6xl font-heading font-bold tracking-tight sm:text-7xl lg:text-8xl leading-tight">
|
||||
Invoicing Made <br />
|
||||
<h1 className="text-foreground font-heading mb-8 text-6xl leading-tight font-bold tracking-tight sm:text-7xl lg:text-8xl">
|
||||
{brand.name} <br />
|
||||
<span className="text-primary italic">Beautifully Simple.</span>
|
||||
</h1>
|
||||
|
||||
<p className="text-muted-foreground mx-auto mb-12 max-w-2xl text-xl leading-relaxed font-sans">
|
||||
Create professional invoices, manage clients, and track payments with a tool that feels as good as it looks.
|
||||
<p className="text-muted-foreground mx-auto mb-12 max-w-2xl font-sans text-xl leading-relaxed">
|
||||
{brand.tagline}
|
||||
</p>
|
||||
|
||||
<div className="flex flex-col items-center gap-6 sm:flex-row sm:justify-center">
|
||||
<Link href="/auth/register">
|
||||
<Button
|
||||
size="lg"
|
||||
className="h-14 px-10 text-lg rounded-2xl shadow-xl shadow-primary/20 hover:shadow-2xl hover:shadow-primary/30 transition-all duration-300"
|
||||
className="shadow-primary/20 hover:shadow-primary/30 h-14 rounded-2xl px-10 text-lg shadow-xl transition-all duration-300 hover:shadow-2xl"
|
||||
>
|
||||
Start For Free
|
||||
<ArrowRight className="ml-2 h-5 w-5" />
|
||||
@@ -95,14 +96,14 @@ export default function HomePage() {
|
||||
<Button
|
||||
variant="outline"
|
||||
size="lg"
|
||||
className="h-14 px-10 text-lg rounded-2xl border-border/50 bg-background/50 hover:bg-background/80 backdrop-blur-sm"
|
||||
className="border-border/50 bg-background/50 hover:bg-background/80 h-14 rounded-2xl px-10 text-lg backdrop-blur-sm"
|
||||
>
|
||||
Learn More
|
||||
</Button>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="mt-16 text-muted-foreground/80 flex flex-col items-center justify-center gap-2 text-sm sm:flex-row sm:gap-8">
|
||||
<div className="text-muted-foreground/80 mt-16 flex flex-col items-center justify-center gap-2 text-sm sm:flex-row sm:gap-8">
|
||||
<div className="flex items-center gap-2">
|
||||
<Check className="text-primary h-4 w-4" />
|
||||
<span>No credit card required</span>
|
||||
@@ -121,11 +122,12 @@ export default function HomePage() {
|
||||
</section>
|
||||
|
||||
{/* Features Section */}
|
||||
<section id="features" className="py-24 relative">
|
||||
<div className="container mx-auto px-4 relative z-10">
|
||||
<section id="features" className="relative py-24">
|
||||
<div className="relative z-10 container mx-auto px-4">
|
||||
<div className="mb-20 text-center">
|
||||
<h2 className="text-foreground mb-6 text-4xl font-heading font-bold sm:text-5xl">
|
||||
Everything you need to <span className="italic text-primary">thrive</span>
|
||||
<h2 className="text-foreground font-heading mb-6 text-4xl font-bold sm:text-5xl">
|
||||
Everything you need to{" "}
|
||||
<span className="text-primary italic">thrive</span>
|
||||
</h2>
|
||||
<p className="text-muted-foreground mx-auto max-w-2xl text-lg">
|
||||
Powerful features wrapped in a calm, focused interface.
|
||||
@@ -137,28 +139,46 @@ export default function HomePage() {
|
||||
{
|
||||
icon: Rocket,
|
||||
title: "Quick Setup",
|
||||
description: "Start creating invoices immediately. No complicated setup required.",
|
||||
items: ["Simple client management", "Professional templates", "Easy invoice sending"]
|
||||
description:
|
||||
"Start creating invoices immediately. No complicated setup required.",
|
||||
items: [
|
||||
"Simple client management",
|
||||
"Professional templates",
|
||||
"Easy invoice sending",
|
||||
],
|
||||
},
|
||||
{
|
||||
icon: BarChart3,
|
||||
title: "Payment Tracking",
|
||||
description: "Keep track of invoice status and monitor your payments effortlessly.",
|
||||
items: ["Invoice status tracking", "Payment history", "Overdue notifications"]
|
||||
description:
|
||||
"Keep track of invoice status and monitor your payments effortlessly.",
|
||||
items: [
|
||||
"Invoice status tracking",
|
||||
"Payment history",
|
||||
"Overdue notifications",
|
||||
],
|
||||
},
|
||||
{
|
||||
icon: Shield,
|
||||
title: "Professional Features",
|
||||
description: "Tools that make you look professional and get you paid faster.",
|
||||
items: ["PDF generation", "Custom tax rates", "Professional numbering"]
|
||||
}
|
||||
description:
|
||||
"Tools that make you look professional and get you paid faster.",
|
||||
items: [
|
||||
"PDF generation",
|
||||
"Custom tax rates",
|
||||
"Professional numbering",
|
||||
],
|
||||
},
|
||||
].map((feature, i) => (
|
||||
<Card key={i} className="group hover:-translate-y-2 transition-transform duration-500 border-border/40 bg-background/60 backdrop-blur-xl">
|
||||
<Card
|
||||
key={i}
|
||||
className="group border-border/40 bg-background/60 backdrop-blur-xl transition-transform duration-500 hover:-translate-y-2"
|
||||
>
|
||||
<CardContent className="p-8">
|
||||
<div className="bg-primary/10 text-primary mb-6 inline-flex rounded-2xl p-4">
|
||||
<feature.icon className="h-8 w-8" />
|
||||
</div>
|
||||
<h3 className="text-foreground mb-4 text-2xl font-bold font-heading">
|
||||
<h3 className="text-foreground font-heading mb-4 text-2xl font-bold">
|
||||
{feature.title}
|
||||
</h3>
|
||||
<p className="text-muted-foreground mb-6 leading-relaxed">
|
||||
@@ -166,8 +186,11 @@ export default function HomePage() {
|
||||
</p>
|
||||
<ul className="space-y-3">
|
||||
{feature.items.map((item, j) => (
|
||||
<li key={j} className="flex items-center gap-3 text-sm text-foreground/80">
|
||||
<div className="h-1.5 w-1.5 rounded-full bg-primary" />
|
||||
<li
|
||||
key={j}
|
||||
className="text-foreground/80 flex items-center gap-3 text-sm"
|
||||
>
|
||||
<div className="bg-primary h-1.5 w-1.5 rounded-full" />
|
||||
{item}
|
||||
</li>
|
||||
))}
|
||||
@@ -180,39 +203,45 @@ export default function HomePage() {
|
||||
</section>
|
||||
|
||||
{/* Pricing Section */}
|
||||
<section id="pricing" className="py-24 relative overflow-hidden">
|
||||
<div className="container mx-auto px-4 relative z-10">
|
||||
<div className="max-w-4xl mx-auto text-center mb-16">
|
||||
<h2 className="text-5xl font-heading font-bold mb-6">Simple Pricing</h2>
|
||||
<p className="text-xl text-muted-foreground">Focus on your work, not on fees.</p>
|
||||
<section id="pricing" className="relative overflow-hidden py-24">
|
||||
<div className="relative z-10 container mx-auto px-4">
|
||||
<div className="mx-auto mb-16 max-w-4xl text-center">
|
||||
<h2 className="font-heading mb-6 text-5xl font-bold">
|
||||
Simple Pricing
|
||||
</h2>
|
||||
<p className="text-muted-foreground text-xl">
|
||||
Focus on your work, not on fees.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="max-w-md mx-auto">
|
||||
<Card className="relative overflow-visible border-primary/50 shadow-2xl shadow-primary/5 bg-background/80 backdrop-blur-xl">
|
||||
<div className="absolute -top-4 left-1/2 -translate-x-1/2 bg-primary text-primary-foreground px-6 py-1.5 rounded-full text-sm font-medium shadow-lg">
|
||||
<div className="mx-auto max-w-md">
|
||||
<Card className="border-primary/50 shadow-primary/5 bg-background/80 relative overflow-visible shadow-2xl backdrop-blur-xl">
|
||||
<div className="bg-primary text-primary-foreground absolute -top-4 left-1/2 -translate-x-1/2 rounded-full px-6 py-1.5 text-sm font-medium shadow-lg">
|
||||
Forever Free
|
||||
</div>
|
||||
<CardContent className="p-10 text-center">
|
||||
<div className="mb-2 text-6xl font-bold font-heading">$0</div>
|
||||
<div className="text-muted-foreground mb-8">No credit card required.</div>
|
||||
<div className="font-heading mb-2 text-6xl font-bold">$0</div>
|
||||
<div className="text-muted-foreground mb-8">
|
||||
No credit card required.
|
||||
</div>
|
||||
|
||||
<div className="space-y-4 mb-10 text-left pl-8">
|
||||
<div className="mb-10 space-y-4 pl-8 text-left">
|
||||
{[
|
||||
"Unlimited Invoices",
|
||||
"Unlimited Clients",
|
||||
"PDF Downloads",
|
||||
"Payment Tracking",
|
||||
"Email Support"
|
||||
"Email Support",
|
||||
].map((item, i) => (
|
||||
<div key={i} className="flex items-center gap-3">
|
||||
<Check className="h-5 w-5 text-primary shrink-0" />
|
||||
<Check className="text-primary h-5 w-5 shrink-0" />
|
||||
<span className="text-foreground/90">{item}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<Link href="/auth/register" className="block">
|
||||
<Button size="lg" className="w-full text-lg h-12 rounded-xl">
|
||||
<Button size="lg" className="h-12 w-full rounded-xl text-lg">
|
||||
Get Started
|
||||
</Button>
|
||||
</Link>
|
||||
@@ -223,20 +252,27 @@ export default function HomePage() {
|
||||
</section>
|
||||
|
||||
{/* Footer */}
|
||||
<footer className="border-t border-border/40 bg-background/50 backdrop-blur-sm py-12 mt-12">
|
||||
<div className="container mx-auto px-6 flex flex-col md:flex-row items-center justify-between gap-6">
|
||||
<footer className="border-border/40 bg-background/50 mt-12 border-t py-12 backdrop-blur-sm">
|
||||
<div className="container mx-auto flex flex-col items-center justify-between gap-6 px-6 md:flex-row">
|
||||
<div className="flex items-center gap-3">
|
||||
<Logo size="sm" />
|
||||
<span className="text-sm text-muted-foreground">© 2024 beenvoice</span>
|
||||
<span className="text-muted-foreground text-sm">
|
||||
© 2024 beenvoice
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex gap-8 text-sm text-muted-foreground">
|
||||
<a href="#" className="hover:text-foreground transition-colors">Privacy</a>
|
||||
<a href="#" className="hover:text-foreground transition-colors">Terms</a>
|
||||
<a href="#" className="hover:text-foreground transition-colors">Contact</a>
|
||||
<div className="text-muted-foreground flex gap-8 text-sm">
|
||||
<a href="#" className="hover:text-foreground transition-colors">
|
||||
Privacy
|
||||
</a>
|
||||
<a href="#" className="hover:text-foreground transition-colors">
|
||||
Terms
|
||||
</a>
|
||||
<a href="#" className="hover:text-foreground transition-colors">
|
||||
Contact
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { motion } from "framer-motion";
|
||||
import { brand } from "~/lib/branding";
|
||||
import { useAppearance } from "~/components/providers/appearance-provider";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
interface LogoProps {
|
||||
@@ -10,6 +12,9 @@ interface LogoProps {
|
||||
}
|
||||
|
||||
export function Logo({ className, size = "md", animated = true }: LogoProps) {
|
||||
const appearance = useAppearance();
|
||||
const logoText = appearance.brandLogoText || brand.logoText;
|
||||
const icon = appearance.brandIcon || brand.icon;
|
||||
const sizeClasses = {
|
||||
sm: "text-base",
|
||||
md: "text-xl",
|
||||
@@ -19,7 +24,15 @@ export function Logo({ className, size = "md", animated = true }: LogoProps) {
|
||||
};
|
||||
|
||||
if (!animated) {
|
||||
return <LogoContent className={className} size={size} sizeClasses={sizeClasses} />;
|
||||
return (
|
||||
<LogoContent
|
||||
className={className}
|
||||
size={size}
|
||||
sizeClasses={sizeClasses}
|
||||
logoText={logoText}
|
||||
icon={icon}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -27,7 +40,11 @@ export function Logo({ className, size = "md", animated = true }: LogoProps) {
|
||||
initial={{ opacity: 0 }}
|
||||
animate={{ opacity: 1 }}
|
||||
transition={{ duration: 0.1, ease: "easeOut" }}
|
||||
className={cn("flex items-center font-mono", sizeClasses[size], className)}
|
||||
className={cn(
|
||||
"flex items-center font-mono",
|
||||
sizeClasses[size],
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<motion.span
|
||||
initial={{ opacity: 0 }}
|
||||
@@ -35,7 +52,7 @@ export function Logo({ className, size = "md", animated = true }: LogoProps) {
|
||||
transition={{ delay: 0.02, duration: 0.05, ease: "easeOut" }}
|
||||
className="text-primary font-bold tracking-tight"
|
||||
>
|
||||
$
|
||||
{icon}
|
||||
</motion.span>
|
||||
{size !== "icon" && (
|
||||
<>
|
||||
@@ -51,7 +68,7 @@ export function Logo({ className, size = "md", animated = true }: LogoProps) {
|
||||
transition={{ delay: 0.04, duration: 0.05, ease: "easeOut" }}
|
||||
className="text-foreground font-bold tracking-tight"
|
||||
>
|
||||
been
|
||||
{logoText.slice(0, Math.ceil(logoText.length / 2))}
|
||||
</motion.span>
|
||||
<motion.span
|
||||
initial={{ opacity: 0 }}
|
||||
@@ -59,7 +76,7 @@ export function Logo({ className, size = "md", animated = true }: LogoProps) {
|
||||
transition={{ delay: 0.06, duration: 0.05, ease: "easeOut" }}
|
||||
className="text-foreground/70 font-bold tracking-tight"
|
||||
>
|
||||
voice
|
||||
{logoText.slice(Math.ceil(logoText.length / 2))}
|
||||
</motion.span>
|
||||
</>
|
||||
)}
|
||||
@@ -71,19 +88,35 @@ function LogoContent({
|
||||
className,
|
||||
size,
|
||||
sizeClasses,
|
||||
logoText,
|
||||
icon,
|
||||
}: {
|
||||
className?: string;
|
||||
size: "sm" | "md" | "lg" | "xl" | "icon";
|
||||
sizeClasses: Record<string, string>;
|
||||
logoText: string;
|
||||
icon: string;
|
||||
}) {
|
||||
return (
|
||||
<div className={cn("flex items-center font-mono", sizeClasses[size], className)}>
|
||||
<span className="text-primary font-bold tracking-tight">$</span>
|
||||
<div
|
||||
className={cn(
|
||||
"flex items-center font-mono",
|
||||
sizeClasses[size],
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<span className="text-primary font-bold tracking-tight">
|
||||
{icon}
|
||||
</span>
|
||||
{size !== "icon" && (
|
||||
<>
|
||||
<span className="inline-block w-1"></span>
|
||||
<span className="text-foreground font-bold tracking-tight">been</span>
|
||||
<span className="text-foreground/70 font-bold tracking-tight">voice</span>
|
||||
<span className="text-foreground font-bold tracking-tight">
|
||||
{logoText.slice(0, Math.ceil(logoText.length / 2))}
|
||||
</span>
|
||||
<span className="text-foreground/70 font-bold tracking-tight">
|
||||
{logoText.slice(Math.ceil(logoText.length / 2))}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -108,10 +108,10 @@ export function InvoiceView({ invoiceId }: InvoiceViewProps) {
|
||||
}
|
||||
};
|
||||
|
||||
const formatCurrency = (amount: number) => {
|
||||
const formatCurrency = (amount: number, currency = "USD") => {
|
||||
return new Intl.NumberFormat("en-US", {
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
currency,
|
||||
}).format(amount);
|
||||
};
|
||||
|
||||
@@ -233,7 +233,7 @@ export function InvoiceView({ invoiceId }: InvoiceViewProps) {
|
||||
onClick={handlePDFExport}
|
||||
disabled={isExportingPDF}
|
||||
variant="default"
|
||||
className="transform-none flex-shrink-0"
|
||||
className="flex-shrink-0 transform-none"
|
||||
>
|
||||
{isExportingPDF ? (
|
||||
<>
|
||||
@@ -423,18 +423,30 @@ export function InvoiceView({ invoiceId }: InvoiceViewProps) {
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Subtotal</span>
|
||||
<span className="text-foreground font-medium">
|
||||
{formatCurrency(invoice.totalAmount)}
|
||||
{formatCurrency(invoice.totalAmount, invoice.currency)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">Tax</span>
|
||||
<span className="text-foreground font-medium">$0.00</span>
|
||||
</div>
|
||||
{(invoice.taxRate ?? 0) > 0 && (
|
||||
<div className="flex justify-between text-sm">
|
||||
<span className="text-muted-foreground">
|
||||
Tax ({((invoice.taxRate ?? 0) * 100).toFixed(1)}%)
|
||||
</span>
|
||||
<span className="text-foreground font-medium">
|
||||
{formatCurrency(
|
||||
invoice.totalAmount * (invoice.taxRate ?? 0),
|
||||
invoice.currency,
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<Separator />
|
||||
<div className="flex justify-between text-lg font-bold">
|
||||
<span className="text-foreground">Total</span>
|
||||
<span className="text-primary">
|
||||
{formatCurrency(invoice.totalAmount)}
|
||||
{formatCurrency(
|
||||
invoice.totalAmount * (1 + (invoice.taxRate ?? 0)),
|
||||
invoice.currency,
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -15,13 +15,24 @@ import {
|
||||
SelectValue,
|
||||
} from "~/components/ui/select";
|
||||
import { DatePicker } from "~/components/ui/date-picker";
|
||||
import { Input } from "~/components/ui/input";
|
||||
import { NumberInput } from "~/components/ui/number-input";
|
||||
import { PageHeader } from "~/components/layout/page-header";
|
||||
import { InvoiceLineItems } from "./invoice-line-items";
|
||||
import { InvoiceCalendarView } from "./invoice-calendar-view";
|
||||
import { EmailPreview } from "./email-preview";
|
||||
import { api } from "~/trpc/react";
|
||||
import { toast } from "sonner";
|
||||
import { Save, Calendar as CalendarIcon, Tag, User, List, FileText, ChevronDown } from "lucide-react";
|
||||
import {
|
||||
Save,
|
||||
Calendar as CalendarIcon,
|
||||
Tag,
|
||||
User,
|
||||
List,
|
||||
FileText,
|
||||
ChevronDown,
|
||||
Mail,
|
||||
} from "lucide-react";
|
||||
import { SUPPORTED_CURRENCIES } from "~/lib/currency";
|
||||
import { Textarea } from "~/components/ui/textarea";
|
||||
import {
|
||||
@@ -49,7 +60,7 @@ interface InvoiceFormProps {
|
||||
|
||||
function InvoiceFormSkeleton() {
|
||||
return (
|
||||
<div className="space-y-6 pb-32">
|
||||
<div className="space-y-6 pb-8">
|
||||
<PageHeader
|
||||
title="Loading..."
|
||||
description="Loading invoice form"
|
||||
@@ -72,6 +83,7 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
// State
|
||||
const [formData, setFormData] = useState<InvoiceFormData>({
|
||||
invoiceNumber: `INV-${new Date().toISOString().slice(0, 10).replace(/-/g, "")}-${Date.now().toString().slice(-6)}`,
|
||||
invoicePrefix: "#",
|
||||
businessId: "",
|
||||
clientId: "",
|
||||
issueDate: new Date(),
|
||||
@@ -101,7 +113,9 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
// Queries (Same as before)
|
||||
const { data: clients, isLoading: loadingClients } =
|
||||
api.clients.getAll.useQuery();
|
||||
const { data: noteTemplates } = api.invoiceTemplates.getByType.useQuery({ type: "notes" });
|
||||
const { data: noteTemplates } = api.invoiceTemplates.getByType.useQuery({
|
||||
type: "notes",
|
||||
});
|
||||
const { data: businesses, isLoading: loadingBusinesses } =
|
||||
api.businesses.getAll.useQuery();
|
||||
const { data: existingInvoice, isLoading: loadingInvoice } =
|
||||
@@ -140,6 +154,7 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
) || [];
|
||||
setFormData({
|
||||
invoiceNumber: existingInvoice.invoiceNumber,
|
||||
invoicePrefix: existingInvoice.invoicePrefix ?? "#",
|
||||
businessId: existingInvoice.businessId ?? "",
|
||||
clientId: existingInvoice.clientId,
|
||||
issueDate: new Date(existingInvoice.issueDate),
|
||||
@@ -186,6 +201,16 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
const total = subtotal + taxAmount;
|
||||
return { subtotal, taxAmount, total };
|
||||
}, [formData.items, formData.taxRate]);
|
||||
const selectedClient = React.useMemo(
|
||||
() => clients?.find((client) => client.id === formData.clientId),
|
||||
[clients, formData.clientId],
|
||||
);
|
||||
const selectedBusiness = React.useMemo(
|
||||
() =>
|
||||
businesses?.find((business) => business.id === formData.businessId) ??
|
||||
businesses?.find((business) => business.isDefault),
|
||||
[businesses, formData.businessId],
|
||||
);
|
||||
|
||||
// Handlers (addItem, updateItem etc. - same as before)
|
||||
const addItem = (date?: unknown) => {
|
||||
@@ -231,32 +256,6 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
}),
|
||||
}));
|
||||
};
|
||||
const moveItemUp = (idx: number) => {
|
||||
if (idx === 0) return;
|
||||
setFormData((prev) => {
|
||||
const newItems = [...prev.items];
|
||||
if (newItems[idx] && newItems[idx - 1]) {
|
||||
const temp = newItems[idx - 1]!;
|
||||
newItems[idx - 1] = newItems[idx];
|
||||
newItems[idx] = temp;
|
||||
}
|
||||
return { ...prev, items: newItems };
|
||||
});
|
||||
};
|
||||
const moveItemDown = (idx: number) => {
|
||||
if (idx === formData.items.length - 1) return;
|
||||
setFormData((prev) => {
|
||||
const newItems = [...prev.items];
|
||||
if (newItems[idx] && newItems[idx + 1]) {
|
||||
const temp = newItems[idx + 1]!;
|
||||
newItems[idx + 1] = newItems[idx];
|
||||
newItems[idx] = temp;
|
||||
}
|
||||
return { ...prev, items: newItems };
|
||||
});
|
||||
};
|
||||
const reorderItems = (newItems: InvoiceItem[]) =>
|
||||
setFormData((prev) => ({ ...prev, items: newItems }));
|
||||
|
||||
const createInvoice = api.invoices.create.useMutation({
|
||||
onSuccess: (inv) => {
|
||||
@@ -333,6 +332,7 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
try {
|
||||
const payload = {
|
||||
invoiceNumber: formData.invoiceNumber,
|
||||
invoicePrefix: formData.invoicePrefix,
|
||||
businessId: formData.businessId || "",
|
||||
clientId: formData.clientId,
|
||||
issueDate: formData.issueDate,
|
||||
@@ -382,7 +382,7 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="page-enter space-y-6 pb-32">
|
||||
<div className="page-enter space-y-6 pb-8">
|
||||
<PageHeader
|
||||
title={invoiceId !== "new" ? "Edit Invoice" : "Create Invoice"}
|
||||
description="Manage your invoice"
|
||||
@@ -405,7 +405,7 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
|
||||
<Tabs value={activeTab} className="w-full" onValueChange={setActiveTab}>
|
||||
{/* TAB SELECTOR: w-full, p-1, visible background */}
|
||||
<TabsList className="bg-muted grid h-auto w-full grid-cols-3 rounded-xl p-1">
|
||||
<TabsList className="bg-muted grid h-auto w-full grid-cols-4 rounded-xl p-1">
|
||||
<TabsTrigger
|
||||
value="details"
|
||||
className="data-[state=active]:bg-background rounded-lg py-2.5 data-[state=active]:shadow-sm"
|
||||
@@ -424,6 +424,12 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
>
|
||||
Timesheet
|
||||
</TabsTrigger>
|
||||
<TabsTrigger
|
||||
value="preview"
|
||||
className="data-[state=active]:bg-background rounded-lg py-2.5 data-[state=active]:shadow-sm"
|
||||
>
|
||||
Preview
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* DETAILS TAB */}
|
||||
@@ -431,7 +437,7 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
value="details"
|
||||
className="mt-6 grid grid-cols-1 gap-6 focus-visible:outline-none lg:grid-cols-2"
|
||||
>
|
||||
<Card className="h-fit">
|
||||
<Card className="h-full">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex gap-2 text-base">
|
||||
<User className="h-4 w-4" /> Client Details
|
||||
@@ -453,13 +459,24 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
? selectedClient.defaultHourlyRate
|
||||
: null;
|
||||
const businessRate =
|
||||
currentBusiness && "defaultHourlyRate" in currentBusiness
|
||||
currentBusiness &&
|
||||
"defaultHourlyRate" in currentBusiness
|
||||
? currentBusiness.defaultHourlyRate
|
||||
: null;
|
||||
updateField("defaultHourlyRate", (clientRate ?? businessRate ?? 0) as number);
|
||||
updateField(
|
||||
"defaultHourlyRate",
|
||||
(clientRate ?? businessRate ?? 0) as number,
|
||||
);
|
||||
// Auto-fill currency from client
|
||||
if (selectedClient && "currency" in selectedClient && selectedClient.currency) {
|
||||
updateField("currency", selectedClient.currency as string);
|
||||
if (
|
||||
selectedClient &&
|
||||
"currency" in selectedClient &&
|
||||
selectedClient.currency
|
||||
) {
|
||||
updateField(
|
||||
"currency",
|
||||
selectedClient.currency as string,
|
||||
);
|
||||
}
|
||||
}}
|
||||
>
|
||||
@@ -496,10 +513,10 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card className="h-fit">
|
||||
<Card className="h-full">
|
||||
<CardHeader>
|
||||
<CardTitle className="flex gap-2 text-base">
|
||||
<Tag className="h-4 w-4" /> Invoice Config
|
||||
<Tag className="h-4 w-4" /> Invoice Settings
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
@@ -525,6 +542,30 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-[96px_1fr] sm:gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Prefix</Label>
|
||||
<Input
|
||||
value={formData.invoicePrefix}
|
||||
onChange={(e) =>
|
||||
updateField("invoicePrefix", e.target.value)
|
||||
}
|
||||
placeholder="#"
|
||||
className="w-full"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label>Invoice Number</Label>
|
||||
<Input
|
||||
value={formData.invoiceNumber}
|
||||
onChange={(e) =>
|
||||
updateField("invoiceNumber", e.target.value)
|
||||
}
|
||||
placeholder="INV-20260428-000001"
|
||||
className="w-full font-mono"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Tax Rate</Label>
|
||||
@@ -599,7 +640,11 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
{noteTemplates && noteTemplates.length > 0 && (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="h-7 gap-1 text-xs">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 gap-1 text-xs"
|
||||
>
|
||||
Use template <ChevronDown className="h-3 w-3" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
@@ -674,9 +719,6 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
onAddItem={addItem}
|
||||
onRemoveItem={removeItem}
|
||||
onUpdateItem={updateItem}
|
||||
onMoveUp={moveItemUp}
|
||||
onMoveDown={moveItemDown}
|
||||
onReorderItems={reorderItems}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
@@ -704,6 +746,54 @@ export default function InvoiceForm({ invoiceId }: InvoiceFormProps) {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent
|
||||
value="preview"
|
||||
className="mt-6 focus-visible:outline-none"
|
||||
>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex gap-2">
|
||||
<Mail className="h-5 w-5" /> Email Preview
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<EmailPreview
|
||||
subject={`Invoice ${formData.invoiceNumber} from ${
|
||||
selectedBusiness?.name ?? "Your Business"
|
||||
}`}
|
||||
fromEmail={selectedBusiness?.email ?? ""}
|
||||
toEmail={selectedClient?.email ?? ""}
|
||||
content=""
|
||||
invoice={{
|
||||
invoiceNumber: formData.invoiceNumber,
|
||||
issueDate: formData.issueDate,
|
||||
dueDate: formData.dueDate,
|
||||
taxRate: formData.taxRate,
|
||||
status: formData.status,
|
||||
totalAmount: totals.total,
|
||||
client: selectedClient
|
||||
? {
|
||||
name: selectedClient.name,
|
||||
email: selectedClient.email,
|
||||
}
|
||||
: undefined,
|
||||
business: selectedBusiness
|
||||
? {
|
||||
name: selectedBusiness.name,
|
||||
email: selectedBusiness.email,
|
||||
}
|
||||
: undefined,
|
||||
items: formData.items.map((item) => ({
|
||||
id: item.id,
|
||||
hours: item.hours,
|
||||
rate: item.rate,
|
||||
})),
|
||||
}}
|
||||
/>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ChevronDown,
|
||||
ChevronUp,
|
||||
Plus,
|
||||
Trash2,
|
||||
} from "lucide-react";
|
||||
import { Plus, Trash2 } from "lucide-react";
|
||||
import * as React from "react";
|
||||
import { motion, AnimatePresence } from "framer-motion";
|
||||
import { Button } from "~/components/ui/button";
|
||||
@@ -33,9 +28,6 @@ interface InvoiceLineItemsProps {
|
||||
field: string,
|
||||
value: string | number | Date,
|
||||
) => void;
|
||||
onMoveUp: (index: number) => void;
|
||||
onMoveDown: (index: number) => void;
|
||||
onReorderItems: (items: InvoiceItem[]) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
@@ -49,130 +41,67 @@ interface LineItemRowProps {
|
||||
field: string,
|
||||
value: string | number | Date,
|
||||
) => void;
|
||||
onMoveUp: (index: number) => void;
|
||||
onMoveDown: (index: number) => void;
|
||||
isFirst: boolean;
|
||||
isLast: boolean;
|
||||
}
|
||||
|
||||
const LineItemCard = React.forwardRef<HTMLDivElement, LineItemRowProps>(
|
||||
(
|
||||
{
|
||||
item,
|
||||
index,
|
||||
canRemove,
|
||||
onRemove,
|
||||
onUpdate,
|
||||
onMoveUp,
|
||||
onMoveDown,
|
||||
isFirst,
|
||||
isLast,
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
({ item, index, canRemove, onRemove, onUpdate }, ref) => {
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"bg-card border hidden rounded-xl p-4 md:block transition-all shadow-sm group hover:border-primary/20",
|
||||
"group hover:bg-muted/40 hidden min-h-16 grid-cols-[140px_minmax(200px,1fr)_124px_136px_104px_32px] items-center gap-2 border-b px-3 py-2 transition-colors md:grid",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
{/* Arrow Controls */}
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onMoveUp(index)}
|
||||
className="h-6 w-6 p-0"
|
||||
disabled={isFirst}
|
||||
aria-label="Move up"
|
||||
>
|
||||
<ChevronUp className="h-3 w-3" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onMoveDown(index)}
|
||||
className="h-6 w-6 p-0"
|
||||
disabled={isLast}
|
||||
aria-label="Move down"
|
||||
>
|
||||
<ChevronDown className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<DatePicker
|
||||
date={item.date}
|
||||
onDateChange={(date) => onUpdate(index, "date", date ?? new Date())}
|
||||
size="sm"
|
||||
className="w-full"
|
||||
inputClassName="h-9"
|
||||
/>
|
||||
|
||||
{/* Main Content */}
|
||||
<div className="flex-1 space-y-3">
|
||||
{/* Description */}
|
||||
<div>
|
||||
<Input
|
||||
value={item.description}
|
||||
onChange={(e) => onUpdate(index, "description", e.target.value)}
|
||||
placeholder="Describe the work performed..."
|
||||
className="w-full text-sm font-medium"
|
||||
/>
|
||||
</div>
|
||||
<Input
|
||||
value={item.description}
|
||||
onChange={(e) => onUpdate(index, "description", e.target.value)}
|
||||
placeholder="Describe the work performed..."
|
||||
className="h-9 w-full text-sm font-medium"
|
||||
/>
|
||||
|
||||
{/* Controls Row */}
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
{/* Date */}
|
||||
<DatePicker
|
||||
date={item.date}
|
||||
onDateChange={(date) =>
|
||||
onUpdate(index, "date", date ?? new Date())
|
||||
}
|
||||
size="sm"
|
||||
className="w-full sm:w-[180px]"
|
||||
inputClassName="h-9"
|
||||
/>
|
||||
<NumberInput
|
||||
value={item.hours}
|
||||
onChange={(value) => onUpdate(index, "hours", value)}
|
||||
min={0}
|
||||
step={0.25}
|
||||
width="full"
|
||||
className="h-9 font-mono [&_button]:w-6 [&_input]:min-w-12"
|
||||
suffix="h"
|
||||
/>
|
||||
|
||||
{/* Hours */}
|
||||
<NumberInput
|
||||
value={item.hours}
|
||||
onChange={(value) => onUpdate(index, "hours", value)}
|
||||
min={0}
|
||||
step={0.25}
|
||||
width="auto"
|
||||
className="h-9 flex-1 min-w-[100px] font-mono"
|
||||
suffix="h"
|
||||
/>
|
||||
<NumberInput
|
||||
value={item.rate}
|
||||
onChange={(value) => onUpdate(index, "rate", value)}
|
||||
min={0}
|
||||
step={1}
|
||||
prefix="$"
|
||||
width="full"
|
||||
className="h-9 font-mono [&_button]:w-6 [&_input]:min-w-14"
|
||||
/>
|
||||
|
||||
{/* Rate */}
|
||||
<NumberInput
|
||||
value={item.rate}
|
||||
onChange={(value) => onUpdate(index, "rate", value)}
|
||||
min={0}
|
||||
step={1}
|
||||
prefix="$"
|
||||
width="auto"
|
||||
className="h-9 flex-1 min-w-[100px] font-mono"
|
||||
/>
|
||||
|
||||
{/* Amount */}
|
||||
<div className="ml-auto">
|
||||
<span className="text-primary font-semibold">
|
||||
${(item.hours * item.rate).toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onRemove(index)}
|
||||
className="text-muted-foreground hover:text-destructive h-8 w-8 p-0"
|
||||
disabled={!canRemove}
|
||||
aria-label="Remove item"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-primary text-right font-mono font-semibold">
|
||||
${(item.hours * item.rate).toFixed(2)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onRemove(index)}
|
||||
className="text-muted-foreground hover:text-destructive h-8 w-8 p-0"
|
||||
disabled={!canRemove}
|
||||
aria-label="Remove item"
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
},
|
||||
@@ -185,10 +114,6 @@ function MobileLineItem({
|
||||
canRemove,
|
||||
onRemove,
|
||||
onUpdate,
|
||||
onMoveUp,
|
||||
onMoveDown,
|
||||
isFirst,
|
||||
isLast,
|
||||
}: LineItemRowProps) {
|
||||
return (
|
||||
<motion.div
|
||||
@@ -253,28 +178,6 @@ function MobileLineItem({
|
||||
{/* Bottom section with controls, item name, and total */}
|
||||
<div className="border-border bg-muted/50 flex items-center justify-between border-t px-4 py-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onMoveUp(index)}
|
||||
className="h-8 w-8 p-0"
|
||||
disabled={isFirst}
|
||||
aria-label="Move up"
|
||||
>
|
||||
<ChevronUp className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => onMoveDown(index)}
|
||||
className="h-8 w-8 p-0"
|
||||
disabled={isLast}
|
||||
aria-label="Move down"
|
||||
>
|
||||
<ChevronDown className="h-4 w-4" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
@@ -310,8 +213,6 @@ export function InvoiceLineItems({
|
||||
onAddItem,
|
||||
onRemoveItem,
|
||||
onUpdateItem,
|
||||
onMoveUp,
|
||||
onMoveDown,
|
||||
className,
|
||||
}: InvoiceLineItemsProps) {
|
||||
const canRemoveItems = items.length > 1;
|
||||
@@ -319,7 +220,15 @@ export function InvoiceLineItems({
|
||||
return (
|
||||
<div className={cn("space-y-2", className)}>
|
||||
<AnimatePresence>
|
||||
<div className="space-y-2">
|
||||
<div className="space-y-2 md:space-y-0 md:overflow-hidden md:rounded-lg md:border">
|
||||
<div className="bg-muted/60 text-muted-foreground hidden grid-cols-[140px_minmax(200px,1fr)_124px_136px_104px_32px] gap-2 border-b px-3 py-2 text-xs font-medium md:grid">
|
||||
<span>Date</span>
|
||||
<span>Description</span>
|
||||
<span className="text-right">Hours</span>
|
||||
<span className="text-right">Rate</span>
|
||||
<span className="text-right">Amount</span>
|
||||
<span />
|
||||
</div>
|
||||
{items.map((item, index) => (
|
||||
<React.Fragment key={item.id}>
|
||||
{/* Desktop/Tablet Card */}
|
||||
@@ -337,10 +246,6 @@ export function InvoiceLineItems({
|
||||
canRemove={canRemoveItems}
|
||||
onRemove={onRemoveItem}
|
||||
onUpdate={onUpdateItem}
|
||||
onMoveUp={onMoveUp}
|
||||
onMoveDown={onMoveDown}
|
||||
isFirst={index === 0}
|
||||
isLast={index === items.length - 1}
|
||||
/>
|
||||
</motion.div>
|
||||
|
||||
@@ -351,10 +256,6 @@ export function InvoiceLineItems({
|
||||
canRemove={canRemoveItems}
|
||||
onRemove={onRemoveItem}
|
||||
onUpdate={onUpdateItem}
|
||||
onMoveUp={onMoveUp}
|
||||
onMoveDown={onMoveDown}
|
||||
isFirst={index === 0}
|
||||
isLast={index === items.length - 1}
|
||||
/>
|
||||
</React.Fragment>
|
||||
))}
|
||||
@@ -362,19 +263,15 @@ export function InvoiceLineItems({
|
||||
</AnimatePresence>
|
||||
|
||||
{/* Add Item Button */}
|
||||
<div className="px-3 pt-3">
|
||||
<div className="border-t pt-6">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onAddItem}
|
||||
className="w-full border-dashed border-border py-8 text-muted-foreground hover:text-primary hover:bg-accent/50 hover:border-primary/50 transition-all"
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Line Item
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={onAddItem}
|
||||
className="border-border text-muted-foreground hover:text-primary hover:bg-accent/50 hover:border-primary/50 mt-3 w-full border-dashed py-6 transition-all"
|
||||
>
|
||||
<Plus className="mr-2 h-4 w-4" />
|
||||
Add Line Item
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,98 +9,93 @@ import { InvoiceCalendarView } from "../invoice-calendar-view";
|
||||
import type { InvoiceFormData } from "./types";
|
||||
|
||||
interface InvoiceWorkspaceProps {
|
||||
formData: InvoiceFormData;
|
||||
viewMode: "list" | "calendar";
|
||||
setViewMode: (mode: "list" | "calendar") => void;
|
||||
addItem: (date?: Date) => void;
|
||||
removeItem: (index: number) => void;
|
||||
updateItem: (index: number, field: string, value: string | number | Date) => void;
|
||||
moveItemUp: (index: number) => void;
|
||||
moveItemDown: (index: number) => void;
|
||||
reorderItems: (items: InvoiceFormData['items']) => void;
|
||||
className?: string;
|
||||
formData: InvoiceFormData;
|
||||
viewMode: "list" | "calendar";
|
||||
setViewMode: (mode: "list" | "calendar") => void;
|
||||
addItem: (date?: Date) => void;
|
||||
removeItem: (index: number) => void;
|
||||
updateItem: (
|
||||
index: number,
|
||||
field: string,
|
||||
value: string | number | Date,
|
||||
) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function InvoiceWorkspace({
|
||||
formData,
|
||||
viewMode,
|
||||
setViewMode,
|
||||
addItem,
|
||||
removeItem,
|
||||
updateItem,
|
||||
moveItemUp,
|
||||
moveItemDown,
|
||||
reorderItems,
|
||||
className,
|
||||
formData,
|
||||
viewMode,
|
||||
setViewMode,
|
||||
addItem,
|
||||
removeItem,
|
||||
updateItem,
|
||||
className,
|
||||
}: InvoiceWorkspaceProps) {
|
||||
|
||||
return (
|
||||
<div className={cn("flex flex-col h-full", className)}>
|
||||
{/* Workspace Header / View Toggle */}
|
||||
<div className="flex items-center justify-between p-4 border-b bg-background/50 backdrop-blur-sm sticky top-0 z-10">
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 className="text-lg font-semibold tracking-tight">
|
||||
{viewMode === 'list' ? 'Line Items' : 'Timesheet'}
|
||||
</h2>
|
||||
<div className="text-sm text-muted-foreground ml-2">
|
||||
{formData.items.length} {formData.items.length === 1 ? 'entry' : 'entries'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center bg-secondary/50 p-1 rounded-lg">
|
||||
<Button
|
||||
variant={viewMode === 'list' ? 'secondary' : 'ghost'}
|
||||
size="sm"
|
||||
onClick={() => setViewMode('list')}
|
||||
className="h-8 gap-2 text-xs"
|
||||
>
|
||||
<List className="w-3.5 h-3.5" />
|
||||
List
|
||||
</Button>
|
||||
<Button
|
||||
variant={viewMode === 'calendar' ? 'secondary' : 'ghost'}
|
||||
size="sm"
|
||||
onClick={() => setViewMode('calendar')}
|
||||
className="h-8 gap-2 text-xs"
|
||||
>
|
||||
<CalendarIcon className="w-3.5 h-3.5" />
|
||||
Calendar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Workspace Content */}
|
||||
<div className="flex-1 overflow-hidden relative">
|
||||
<div className="absolute inset-0 overflow-y-auto p-6 md:p-8">
|
||||
{viewMode === 'list' ? (
|
||||
<div className="max-w-4xl mx-auto space-y-6">
|
||||
<div className="bg-background/40 backdrop-blur-md rounded-xl border border-white/10 p-1">
|
||||
<InvoiceLineItems
|
||||
items={formData.items}
|
||||
onAddItem={() => addItem()}
|
||||
onRemoveItem={removeItem}
|
||||
onUpdateItem={updateItem}
|
||||
onMoveUp={moveItemUp}
|
||||
onMoveDown={moveItemDown}
|
||||
onReorderItems={reorderItems}
|
||||
className="p-4"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-full">
|
||||
<InvoiceCalendarView
|
||||
items={formData.items}
|
||||
onAddItem={addItem}
|
||||
onRemoveItem={removeItem}
|
||||
onUpdateItem={updateItem}
|
||||
defaultHourlyRate={formData.defaultHourlyRate}
|
||||
className="h-full"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
return (
|
||||
<div className={cn("flex h-full flex-col", className)}>
|
||||
{/* Workspace Header / View Toggle */}
|
||||
<div className="bg-background/50 sticky top-0 z-10 flex items-center justify-between border-b p-4 backdrop-blur-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<h2 className="text-lg font-semibold tracking-tight">
|
||||
{viewMode === "list" ? "Line Items" : "Timesheet"}
|
||||
</h2>
|
||||
<div className="text-muted-foreground ml-2 text-sm">
|
||||
{formData.items.length}{" "}
|
||||
{formData.items.length === 1 ? "entry" : "entries"}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
<div className="bg-secondary/50 flex items-center rounded-lg p-1">
|
||||
<Button
|
||||
variant={viewMode === "list" ? "secondary" : "ghost"}
|
||||
size="sm"
|
||||
onClick={() => setViewMode("list")}
|
||||
className="h-8 gap-2 text-xs"
|
||||
>
|
||||
<List className="h-3.5 w-3.5" />
|
||||
List
|
||||
</Button>
|
||||
<Button
|
||||
variant={viewMode === "calendar" ? "secondary" : "ghost"}
|
||||
size="sm"
|
||||
onClick={() => setViewMode("calendar")}
|
||||
className="h-8 gap-2 text-xs"
|
||||
>
|
||||
<CalendarIcon className="h-3.5 w-3.5" />
|
||||
Calendar
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Workspace Content */}
|
||||
<div className="relative flex-1 overflow-hidden">
|
||||
<div className="absolute inset-0 overflow-y-auto p-6 md:p-8">
|
||||
{viewMode === "list" ? (
|
||||
<div className="mx-auto max-w-4xl space-y-6">
|
||||
<div className="bg-background/40 rounded-xl border border-white/10 p-1 backdrop-blur-md">
|
||||
<InvoiceLineItems
|
||||
items={formData.items}
|
||||
onAddItem={() => addItem()}
|
||||
onRemoveItem={removeItem}
|
||||
onUpdateItem={updateItem}
|
||||
className="p-4"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-full">
|
||||
<InvoiceCalendarView
|
||||
items={formData.items}
|
||||
onAddItem={addItem}
|
||||
onRemoveItem={removeItem}
|
||||
onUpdateItem={updateItem}
|
||||
defaultHourlyRate={formData.defaultHourlyRate}
|
||||
className="h-full"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -4,30 +4,31 @@ export type ClientType = RouterOutputs["clients"]["getAll"][number];
|
||||
export type BusinessType = RouterOutputs["businesses"]["getAll"][number];
|
||||
|
||||
export interface InvoiceItem {
|
||||
id: string;
|
||||
date: Date;
|
||||
description: string;
|
||||
hours: number;
|
||||
rate: number;
|
||||
amount: number;
|
||||
id: string;
|
||||
date: Date;
|
||||
description: string;
|
||||
hours: number;
|
||||
rate: number;
|
||||
amount: number;
|
||||
}
|
||||
|
||||
export interface InvoiceFormData {
|
||||
invoiceNumber: string;
|
||||
businessId: string;
|
||||
clientId: string;
|
||||
issueDate: Date;
|
||||
dueDate: Date;
|
||||
status: "draft" | "sent" | "paid";
|
||||
notes: string;
|
||||
taxRate: number;
|
||||
currency: string;
|
||||
defaultHourlyRate: number | null;
|
||||
items: InvoiceItem[];
|
||||
invoiceNumber: string;
|
||||
invoicePrefix: string;
|
||||
businessId: string;
|
||||
clientId: string;
|
||||
issueDate: Date;
|
||||
dueDate: Date;
|
||||
status: "draft" | "sent" | "paid";
|
||||
notes: string;
|
||||
taxRate: number;
|
||||
currency: string;
|
||||
defaultHourlyRate: number | null;
|
||||
items: InvoiceItem[];
|
||||
}
|
||||
|
||||
export const STATUS_OPTIONS = [
|
||||
{ value: "draft", label: "Draft" },
|
||||
{ value: "sent", label: "Sent" },
|
||||
{ value: "paid", label: "Paid" },
|
||||
{ value: "draft", label: "Draft" },
|
||||
{ value: "sent", label: "Sent" },
|
||||
{ value: "paid", label: "Paid" },
|
||||
] as const;
|
||||
|
||||
@@ -8,9 +8,11 @@ import { Menu } from "lucide-react";
|
||||
import { Logo } from "~/components/branding/logo";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Sheet, SheetContent, SheetTrigger } from "~/components/ui/sheet";
|
||||
import { useAppearance } from "~/components/providers/appearance-provider";
|
||||
|
||||
function DashboardContent({ children }: { children: React.ReactNode }) {
|
||||
const { isCollapsed } = useSidebar();
|
||||
const { sidebarStyle } = useAppearance();
|
||||
const [isMobileOpen, setIsMobileOpen] = React.useState(false);
|
||||
|
||||
return (
|
||||
@@ -21,7 +23,7 @@ function DashboardContent({ children }: { children: React.ReactNode }) {
|
||||
</div>
|
||||
|
||||
{/* Mobile Sidebar (Sheet) */}
|
||||
<div className="md:hidden fixed top-0 left-0 right-0 h-16 bg-background/80 backdrop-blur-md border-b z-50 px-4 flex items-center">
|
||||
<div className="fixed top-0 right-0 left-0 z-50 flex h-16 items-center border-b bg-background/80 px-4 backdrop-blur-md md:hidden">
|
||||
<Sheet open={isMobileOpen} onOpenChange={setIsMobileOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button variant="outline" size="icon" className="h-10 w-10 bg-background shadow-sm" suppressHydrationWarning>
|
||||
@@ -47,13 +49,14 @@ function DashboardContent({ children }: { children: React.ReactNode }) {
|
||||
suppressHydrationWarning
|
||||
className={cn(
|
||||
"flex-1 min-h-screen min-w-0 transition-all duration-300 ease-in-out",
|
||||
// Desktop margins based on collapsed state
|
||||
"md:ml-0",
|
||||
// Sidebar is fixed at left: 1rem (16px), width: 16rem (256px) or 4rem (64px)
|
||||
// We need margin-left = left + width + gap
|
||||
// Expanded: 16px + 256px + 16px (gap) = 288px (18rem)
|
||||
// Collapsed: 16px + 64px + 16px (gap) = 96px (6rem)
|
||||
isCollapsed ? "md:ml-24" : "md:ml-[18rem]"
|
||||
sidebarStyle === "floating"
|
||||
? isCollapsed
|
||||
? "md:ml-24"
|
||||
: "md:ml-[18rem]"
|
||||
: isCollapsed
|
||||
? "md:ml-16"
|
||||
: "md:ml-64",
|
||||
)}
|
||||
>
|
||||
<div className="p-4 pt-16 md:pt-4">
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useState } from "react";
|
||||
import React from "react";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Card, CardContent } from "~/components/ui/card";
|
||||
import { useAppearance } from "~/components/providers/appearance-provider";
|
||||
import { useSidebar } from "~/components/layout/sidebar-provider";
|
||||
|
||||
interface FloatingActionBarProps {
|
||||
/** Content to display on the left side */
|
||||
@@ -13,74 +15,38 @@ interface FloatingActionBarProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
import { useSidebar } from "~/components/layout/sidebar-provider";
|
||||
|
||||
export function FloatingActionBar({
|
||||
leftContent,
|
||||
children,
|
||||
className,
|
||||
}: FloatingActionBarProps) {
|
||||
const [isDocked, setIsDocked] = useState(false);
|
||||
const { isCollapsed } = useSidebar();
|
||||
|
||||
useEffect(() => {
|
||||
const handleScroll = () => {
|
||||
// Check if we're truly at the bottom of the page
|
||||
const scrollHeight = document.documentElement.scrollHeight;
|
||||
const scrollTop = document.documentElement.scrollTop;
|
||||
const clientHeight = document.documentElement.clientHeight;
|
||||
const distanceFromBottom = scrollHeight - (scrollTop + clientHeight);
|
||||
|
||||
// Only dock when we're within 50px of the actual bottom AND there's content to scroll
|
||||
const hasScrollableContent = scrollHeight > clientHeight;
|
||||
const shouldDock = hasScrollableContent && distanceFromBottom <= 50;
|
||||
|
||||
// If content is too small, keep it at bottom of viewport
|
||||
const contentTooSmall = scrollHeight <= clientHeight + 200;
|
||||
|
||||
setIsDocked(shouldDock && !contentTooSmall);
|
||||
};
|
||||
|
||||
window.addEventListener("scroll", handleScroll, { passive: true });
|
||||
handleScroll(); // Check initial state
|
||||
|
||||
return () => window.removeEventListener("scroll", handleScroll);
|
||||
}, []);
|
||||
const { sidebarStyle } = useAppearance();
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
// Base positioning - always at bottom
|
||||
"fixed right-0 z-50 transition-all duration-300 ease-in-out",
|
||||
// Safe area and sidebar adjustments
|
||||
"pb-safe-area-inset-bottom left-0",
|
||||
isCollapsed ? "md:left-24" : "md:left-[18rem]",
|
||||
// Conditional centering based on dock state
|
||||
isDocked ? "flex justify-center" : "",
|
||||
// Dynamic bottom positioning
|
||||
isDocked ? "bottom-4" : "bottom-0",
|
||||
// Add entrance animation
|
||||
"pb-safe-area-inset-bottom fixed right-0 bottom-4 left-0 z-50 transition-all duration-300 ease-in-out",
|
||||
sidebarStyle === "floating"
|
||||
? isCollapsed
|
||||
? "md:left-24"
|
||||
: "md:left-[18rem]"
|
||||
: isCollapsed
|
||||
? "md:left-16"
|
||||
: "md:left-64",
|
||||
"animate-slide-in-bottom",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{/* Content container - full width when floating, content width when docked */}
|
||||
<div
|
||||
className={cn(
|
||||
"w-full transition-transform duration-300",
|
||||
isDocked ? "mx-auto mb-0 px-4" : "mb-4 px-4",
|
||||
)}
|
||||
>
|
||||
<div className="w-full px-4 transition-transform duration-300">
|
||||
<Card className="hover-lift bg-card border-border border shadow-lg">
|
||||
<CardContent className="flex flex-col gap-3 p-3 sm:flex-row sm:items-center sm:justify-between sm:p-4">
|
||||
{/* Left content */}
|
||||
{leftContent && (
|
||||
<div className="text-card-foreground animate-fade-in flex flex-1 items-center gap-3">
|
||||
{leftContent}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Right actions */}
|
||||
<div className="animate-fade-in animate-delay-100 flex items-center gap-2 sm:gap-3">
|
||||
{children}
|
||||
</div>
|
||||
|
||||
@@ -42,9 +42,9 @@ export function PageHeader({
|
||||
return (
|
||||
<div className={`animate-fade-in-down mb-6 ${className}`}>
|
||||
{variant === "large-gradient" || variant === "gradient" ? (
|
||||
<div className="rounded-xl border bg-card text-card-foreground shadow-sm overflow-hidden relative">
|
||||
<div className="absolute inset-0 bg-gradient-to-br from-primary/5 via-transparent to-transparent pointer-events-none" />
|
||||
<div className="p-6 relative">
|
||||
<div className="platform-header-surface rounded-xl border bg-card text-card-foreground shadow-sm overflow-hidden relative">
|
||||
<div className="platform-header-gradient absolute inset-0 bg-gradient-to-br from-primary/5 via-transparent to-transparent pointer-events-none" />
|
||||
<div className="platform-header-content p-6 relative">
|
||||
<DashboardBreadcrumbs className="mb-4" />
|
||||
{/* UPDATED: flex-col on mobile to prevent squishing, row on sm+ */}
|
||||
<div className="flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4">
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
} from "~/components/ui/dropdown-menu";
|
||||
import { getGravatarUrl } from "~/lib/gravatar";
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "~/components/ui/avatar";
|
||||
import { useAppearance } from "~/components/providers/appearance-provider";
|
||||
|
||||
interface SidebarProps {
|
||||
mobile?: boolean;
|
||||
@@ -36,6 +37,7 @@ export function Sidebar({ mobile, onClose }: SidebarProps) {
|
||||
const { data: session, isPending } = authClient.useSession();
|
||||
// const session = { user: null } as any; const isPending = false;
|
||||
const { isCollapsed, toggleCollapse } = useSidebar();
|
||||
const { sidebarStyle } = useAppearance();
|
||||
|
||||
// If mobile, always expanded
|
||||
const collapsed = mobile ? false : isCollapsed;
|
||||
@@ -214,9 +216,11 @@ export function Sidebar({ mobile, onClose }: SidebarProps) {
|
||||
return (
|
||||
<aside
|
||||
className={cn(
|
||||
"fixed top-4 bottom-4 left-4 z-30 hidden md:flex flex-col",
|
||||
"bg-background/80 backdrop-blur-xl border-border/50 border shadow-xl rounded-3xl transition-all duration-300 ease-in-out",
|
||||
isCollapsed ? "w-16" : "w-64"
|
||||
"fixed z-30 hidden flex-col transition-all duration-300 ease-in-out md:flex",
|
||||
sidebarStyle === "floating"
|
||||
? "top-4 bottom-4 left-4 border-border/50 rounded-3xl border bg-background/80 shadow-xl backdrop-blur-xl"
|
||||
: "top-0 bottom-0 left-0 rounded-none border-r border-border bg-background shadow-none",
|
||||
isCollapsed ? "w-16" : "w-64",
|
||||
)}
|
||||
>
|
||||
{SidebarContent}
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from "react";
|
||||
import {
|
||||
defaultFontPreference,
|
||||
defaultBodyFontPreference,
|
||||
defaultHeadingFontPreference,
|
||||
defaultInterfaceTheme,
|
||||
defaultRadiusPreference,
|
||||
defaultSidebarStyle,
|
||||
brand as defaultBrand,
|
||||
type ColorMode,
|
||||
type ColorTheme,
|
||||
type FontPreference,
|
||||
type InterfaceTheme,
|
||||
type RadiusPreference,
|
||||
type SidebarStyle,
|
||||
} from "~/lib/branding";
|
||||
import { api } from "~/trpc/react";
|
||||
|
||||
type AppearancePreferences = {
|
||||
interfaceTheme: InterfaceTheme;
|
||||
fontPreference: FontPreference;
|
||||
bodyFontPreference: FontPreference;
|
||||
headingFontPreference: FontPreference;
|
||||
radiusPreference: RadiusPreference;
|
||||
sidebarStyle: SidebarStyle;
|
||||
colorMode: ColorMode;
|
||||
colorTheme: ColorTheme;
|
||||
customColor?: string;
|
||||
brandName: string;
|
||||
brandTagline: string;
|
||||
brandLogoText: string;
|
||||
brandIcon: string;
|
||||
pdfTemplate: "classic" | "minimal";
|
||||
pdfAccentColor: string;
|
||||
pdfFooterText: string;
|
||||
pdfShowLogo: boolean;
|
||||
pdfShowPageNumbers: boolean;
|
||||
};
|
||||
|
||||
type AppearancePatch = Partial<AppearancePreferences>;
|
||||
|
||||
type ServerAppearance = {
|
||||
interfaceTheme: InterfaceTheme;
|
||||
fontPreference: FontPreference;
|
||||
bodyFontPreference: FontPreference;
|
||||
headingFontPreference: FontPreference;
|
||||
radiusPreference: RadiusPreference;
|
||||
sidebarStyle: SidebarStyle;
|
||||
theme: ColorMode;
|
||||
colorTheme: ColorTheme;
|
||||
customColor?: string;
|
||||
brandName: string;
|
||||
brandTagline: string;
|
||||
brandLogoText: string;
|
||||
brandIcon: string;
|
||||
pdfTemplate: "classic" | "minimal";
|
||||
pdfAccentColor: string;
|
||||
pdfFooterText: string;
|
||||
pdfShowLogo: boolean;
|
||||
pdfShowPageNumbers: boolean;
|
||||
};
|
||||
|
||||
type AppearanceContextValue = AppearancePreferences & {
|
||||
updateAppearance: (patch: AppearancePatch) => void;
|
||||
isUpdating: boolean;
|
||||
};
|
||||
|
||||
const STORAGE_KEY = "bv.appearance";
|
||||
|
||||
const defaultAppearance: AppearancePreferences = {
|
||||
interfaceTheme: defaultInterfaceTheme,
|
||||
fontPreference: defaultFontPreference,
|
||||
bodyFontPreference: defaultBodyFontPreference,
|
||||
headingFontPreference: defaultHeadingFontPreference,
|
||||
radiusPreference: defaultRadiusPreference,
|
||||
sidebarStyle: defaultSidebarStyle,
|
||||
colorMode: "system",
|
||||
colorTheme: "slate",
|
||||
brandName: defaultBrand.name,
|
||||
brandTagline: defaultBrand.tagline,
|
||||
brandLogoText: defaultBrand.logoText,
|
||||
brandIcon: defaultBrand.icon,
|
||||
pdfTemplate: "classic",
|
||||
pdfAccentColor: "#111827",
|
||||
pdfFooterText: "Professional Invoicing",
|
||||
pdfShowLogo: true,
|
||||
pdfShowPageNumbers: true,
|
||||
};
|
||||
|
||||
const AppearanceContext = createContext<AppearanceContextValue | null>(null);
|
||||
|
||||
function getServerAppearancePatch(
|
||||
serverAppearance: ServerAppearance,
|
||||
): AppearancePatch {
|
||||
return {
|
||||
interfaceTheme: serverAppearance.interfaceTheme,
|
||||
fontPreference: serverAppearance.fontPreference,
|
||||
bodyFontPreference: serverAppearance.bodyFontPreference,
|
||||
headingFontPreference: serverAppearance.headingFontPreference,
|
||||
radiusPreference: serverAppearance.radiusPreference,
|
||||
sidebarStyle: serverAppearance.sidebarStyle,
|
||||
colorMode: serverAppearance.theme,
|
||||
colorTheme: serverAppearance.colorTheme,
|
||||
customColor: serverAppearance.customColor,
|
||||
brandName: serverAppearance.brandName,
|
||||
brandTagline: serverAppearance.brandTagline,
|
||||
brandLogoText: serverAppearance.brandLogoText,
|
||||
brandIcon: serverAppearance.brandIcon,
|
||||
pdfTemplate: serverAppearance.pdfTemplate,
|
||||
pdfAccentColor: serverAppearance.pdfAccentColor,
|
||||
pdfFooterText: serverAppearance.pdfFooterText,
|
||||
pdfShowLogo: serverAppearance.pdfShowLogo,
|
||||
pdfShowPageNumbers: serverAppearance.pdfShowPageNumbers,
|
||||
};
|
||||
}
|
||||
|
||||
function isInterfaceTheme(value: unknown): value is InterfaceTheme {
|
||||
return (
|
||||
value === "beenvoice" ||
|
||||
value === "shadcn" ||
|
||||
value === "minimal" ||
|
||||
value === "editorial"
|
||||
);
|
||||
}
|
||||
|
||||
function isFontPreference(value: unknown): value is FontPreference {
|
||||
return (
|
||||
value === "brand" ||
|
||||
value === "platform" ||
|
||||
value === "inter" ||
|
||||
value === "serif"
|
||||
);
|
||||
}
|
||||
|
||||
function isColorMode(value: unknown): value is ColorMode {
|
||||
return value === "light" || value === "dark" || value === "system";
|
||||
}
|
||||
|
||||
function isColorTheme(value: unknown): value is ColorTheme {
|
||||
return (
|
||||
value === "slate" ||
|
||||
value === "blue" ||
|
||||
value === "green" ||
|
||||
value === "rose" ||
|
||||
value === "orange" ||
|
||||
value === "custom"
|
||||
);
|
||||
}
|
||||
|
||||
function isRadiusPreference(value: unknown): value is RadiusPreference {
|
||||
return (
|
||||
value === "none" ||
|
||||
value === "sm" ||
|
||||
value === "md" ||
|
||||
value === "lg" ||
|
||||
value === "xl"
|
||||
);
|
||||
}
|
||||
|
||||
function isSidebarStyle(value: unknown): value is SidebarStyle {
|
||||
return value === "floating" || value === "docked";
|
||||
}
|
||||
|
||||
function readStoredAppearance(): Partial<AppearancePreferences> | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw) as Record<string, unknown>;
|
||||
return {
|
||||
interfaceTheme: isInterfaceTheme(parsed.interfaceTheme)
|
||||
? parsed.interfaceTheme
|
||||
: undefined,
|
||||
fontPreference: isFontPreference(parsed.fontPreference)
|
||||
? parsed.fontPreference
|
||||
: undefined,
|
||||
bodyFontPreference: isFontPreference(parsed.bodyFontPreference)
|
||||
? parsed.bodyFontPreference
|
||||
: isFontPreference(parsed.fontPreference)
|
||||
? parsed.fontPreference
|
||||
: undefined,
|
||||
headingFontPreference: isFontPreference(parsed.headingFontPreference)
|
||||
? parsed.headingFontPreference
|
||||
: isFontPreference(parsed.fontPreference)
|
||||
? parsed.fontPreference
|
||||
: undefined,
|
||||
radiusPreference: isRadiusPreference(parsed.radiusPreference)
|
||||
? parsed.radiusPreference
|
||||
: undefined,
|
||||
sidebarStyle: isSidebarStyle(parsed.sidebarStyle)
|
||||
? parsed.sidebarStyle
|
||||
: undefined,
|
||||
colorMode: isColorMode(parsed.colorMode) ? parsed.colorMode : undefined,
|
||||
colorTheme: isColorTheme(parsed.colorTheme)
|
||||
? parsed.colorTheme
|
||||
: undefined,
|
||||
customColor:
|
||||
typeof parsed.customColor === "string" ? parsed.customColor : undefined,
|
||||
brandName:
|
||||
typeof parsed.brandName === "string" ? parsed.brandName : undefined,
|
||||
brandTagline:
|
||||
typeof parsed.brandTagline === "string"
|
||||
? parsed.brandTagline
|
||||
: undefined,
|
||||
brandLogoText:
|
||||
typeof parsed.brandLogoText === "string"
|
||||
? parsed.brandLogoText
|
||||
: undefined,
|
||||
brandIcon:
|
||||
typeof parsed.brandIcon === "string" ? parsed.brandIcon : undefined,
|
||||
pdfTemplate:
|
||||
parsed.pdfTemplate === "classic" || parsed.pdfTemplate === "minimal"
|
||||
? parsed.pdfTemplate
|
||||
: undefined,
|
||||
pdfAccentColor:
|
||||
typeof parsed.pdfAccentColor === "string"
|
||||
? parsed.pdfAccentColor
|
||||
: undefined,
|
||||
pdfFooterText:
|
||||
typeof parsed.pdfFooterText === "string"
|
||||
? parsed.pdfFooterText
|
||||
: undefined,
|
||||
pdfShowLogo:
|
||||
typeof parsed.pdfShowLogo === "boolean"
|
||||
? parsed.pdfShowLogo
|
||||
: undefined,
|
||||
pdfShowPageNumbers:
|
||||
typeof parsed.pdfShowPageNumbers === "boolean"
|
||||
? parsed.pdfShowPageNumbers
|
||||
: undefined,
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function writeStoredAppearance(prefs: AppearancePreferences) {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(prefs));
|
||||
} catch {
|
||||
// Storage can be unavailable in private browsing or locked-down contexts.
|
||||
}
|
||||
}
|
||||
|
||||
function applyAppearance(prefs: AppearancePreferences) {
|
||||
if (typeof document === "undefined") return;
|
||||
|
||||
const root = document.documentElement;
|
||||
root.dataset.interfaceTheme = prefs.interfaceTheme;
|
||||
root.dataset.font = prefs.fontPreference;
|
||||
root.dataset.bodyFont = prefs.bodyFontPreference;
|
||||
root.dataset.headingFont = prefs.headingFontPreference;
|
||||
root.dataset.radius = prefs.radiusPreference;
|
||||
root.dataset.sidebarStyle = prefs.sidebarStyle;
|
||||
root.dataset.colorMode = prefs.colorMode;
|
||||
root.dataset.colorTheme = prefs.colorTheme;
|
||||
|
||||
root.classList.toggle("dark", prefs.colorMode === "dark");
|
||||
|
||||
if (prefs.customColor) {
|
||||
root.style.setProperty("--custom-primary", prefs.customColor);
|
||||
} else {
|
||||
root.style.removeProperty("--custom-primary");
|
||||
}
|
||||
}
|
||||
|
||||
export function AppearanceProvider({
|
||||
children,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const [appearance, setAppearance] =
|
||||
useState<AppearancePreferences>(defaultAppearance);
|
||||
const utils = api.useUtils();
|
||||
const updateMutation = api.settings.updateTheme.useMutation({
|
||||
onSuccess: async () => {
|
||||
await utils.settings.getTheme.invalidate();
|
||||
},
|
||||
onError: () => {
|
||||
const cachedAppearance = utils.settings.getTheme.getData();
|
||||
const fallback = cachedAppearance
|
||||
? {
|
||||
...defaultAppearance,
|
||||
...getServerAppearancePatch(cachedAppearance),
|
||||
}
|
||||
: defaultAppearance;
|
||||
|
||||
setAppearance(fallback);
|
||||
applyAppearance(fallback);
|
||||
writeStoredAppearance(fallback);
|
||||
},
|
||||
});
|
||||
|
||||
const { data: serverAppearance } = api.settings.getTheme.useQuery(undefined, {
|
||||
retry: false,
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 60_000,
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const storedAppearance = readStoredAppearance();
|
||||
if (!storedAppearance) return;
|
||||
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setAppearance((prev) => ({ ...prev, ...storedAppearance }));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!serverAppearance) return;
|
||||
const next = getServerAppearancePatch(serverAppearance);
|
||||
|
||||
// eslint-disable-next-line react-hooks/set-state-in-effect
|
||||
setAppearance((prev) => ({ ...prev, ...next }));
|
||||
}, [serverAppearance]);
|
||||
|
||||
useEffect(() => {
|
||||
applyAppearance(appearance);
|
||||
writeStoredAppearance(appearance);
|
||||
}, [appearance]);
|
||||
|
||||
const updateAppearance = useCallback(
|
||||
(patch: AppearancePatch) => {
|
||||
setAppearance((prev) => {
|
||||
const next = { ...prev, ...patch };
|
||||
applyAppearance(next);
|
||||
writeStoredAppearance(next);
|
||||
return next;
|
||||
});
|
||||
|
||||
updateMutation.mutate({
|
||||
interfaceTheme: patch.interfaceTheme,
|
||||
fontPreference: patch.fontPreference,
|
||||
bodyFontPreference: patch.bodyFontPreference,
|
||||
headingFontPreference: patch.headingFontPreference,
|
||||
radiusPreference: patch.radiusPreference,
|
||||
sidebarStyle: patch.sidebarStyle,
|
||||
theme: patch.colorMode,
|
||||
colorTheme: patch.colorTheme,
|
||||
customColor: patch.customColor,
|
||||
brandName: patch.brandName,
|
||||
brandTagline: patch.brandTagline,
|
||||
brandLogoText: patch.brandLogoText,
|
||||
brandIcon: patch.brandIcon,
|
||||
pdfTemplate: patch.pdfTemplate,
|
||||
pdfAccentColor: patch.pdfAccentColor,
|
||||
pdfFooterText: patch.pdfFooterText,
|
||||
pdfShowLogo: patch.pdfShowLogo,
|
||||
pdfShowPageNumbers: patch.pdfShowPageNumbers,
|
||||
});
|
||||
},
|
||||
[updateMutation],
|
||||
);
|
||||
|
||||
const value = useMemo<AppearanceContextValue>(
|
||||
() => ({
|
||||
...appearance,
|
||||
updateAppearance,
|
||||
isUpdating: updateMutation.isPending,
|
||||
}),
|
||||
[appearance, updateAppearance, updateMutation.isPending],
|
||||
);
|
||||
|
||||
return (
|
||||
<AppearanceContext.Provider value={value}>
|
||||
{children}
|
||||
</AppearanceContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAppearance() {
|
||||
const ctx = useContext(AppearanceContext);
|
||||
if (!ctx) {
|
||||
throw new Error("useAppearance must be used within an AppearanceProvider");
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
+38
-4
@@ -13,10 +13,7 @@ export const env = createEnv({
|
||||
: z.string().optional(),
|
||||
DATABASE_URL: z.string().url(),
|
||||
BETTER_AUTH_URL: z.string().url().optional(),
|
||||
RESEND_API_KEY:
|
||||
process.env.NODE_ENV === "production"
|
||||
? z.string().min(1)
|
||||
: z.string().min(1).optional(),
|
||||
RESEND_API_KEY: z.string().min(1).optional(),
|
||||
RESEND_DOMAIN: z.string().optional(),
|
||||
NODE_ENV: z
|
||||
.enum(["development", "test", "production"])
|
||||
@@ -26,6 +23,7 @@ export const env = createEnv({
|
||||
AUTHENTIK_ISSUER: z.string().url().optional(),
|
||||
AUTHENTIK_CLIENT_ID: z.string().optional(),
|
||||
AUTHENTIK_CLIENT_SECRET: z.string().optional(),
|
||||
AUTHENTIK_ORIGIN: z.string().url().optional(),
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -37,6 +35,27 @@ export const env = createEnv({
|
||||
NEXT_PUBLIC_APP_URL: z.string().url().optional(),
|
||||
NEXT_PUBLIC_UMAMI_WEBSITE_ID: z.string().optional(),
|
||||
NEXT_PUBLIC_UMAMI_SCRIPT_URL: z.string().url().optional(),
|
||||
NEXT_PUBLIC_AUTHENTIK_ENABLED: z.coerce.boolean().optional(),
|
||||
NEXT_PUBLIC_BRAND_NAME: z.string().optional(),
|
||||
NEXT_PUBLIC_BRAND_TAGLINE: z.string().optional(),
|
||||
NEXT_PUBLIC_BRAND_LOGO_TEXT: z.string().optional(),
|
||||
NEXT_PUBLIC_BRAND_ICON: z.string().optional(),
|
||||
NEXT_PUBLIC_DEFAULT_INTERFACE_THEME: z
|
||||
.enum(["beenvoice", "shadcn", "minimal", "editorial"])
|
||||
.optional(),
|
||||
NEXT_PUBLIC_DEFAULT_FONT: z
|
||||
.enum(["brand", "platform", "inter", "serif"])
|
||||
.optional(),
|
||||
NEXT_PUBLIC_DEFAULT_BODY_FONT: z
|
||||
.enum(["brand", "platform", "inter", "serif"])
|
||||
.optional(),
|
||||
NEXT_PUBLIC_DEFAULT_HEADING_FONT: z
|
||||
.enum(["brand", "platform", "inter", "serif"])
|
||||
.optional(),
|
||||
NEXT_PUBLIC_DEFAULT_RADIUS: z.enum(["none", "sm", "md", "lg", "xl"]).optional(),
|
||||
NEXT_PUBLIC_DEFAULT_SIDEBAR_STYLE: z
|
||||
.enum(["floating", "docked"])
|
||||
.optional(),
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -54,9 +73,24 @@ export const env = createEnv({
|
||||
AUTHENTIK_ISSUER: process.env.AUTHENTIK_ISSUER,
|
||||
AUTHENTIK_CLIENT_ID: process.env.AUTHENTIK_CLIENT_ID,
|
||||
AUTHENTIK_CLIENT_SECRET: process.env.AUTHENTIK_CLIENT_SECRET,
|
||||
AUTHENTIK_ORIGIN: process.env.AUTHENTIK_ORIGIN,
|
||||
NEXT_PUBLIC_APP_URL: process.env.NEXT_PUBLIC_APP_URL,
|
||||
NEXT_PUBLIC_UMAMI_WEBSITE_ID: process.env.NEXT_PUBLIC_UMAMI_WEBSITE_ID,
|
||||
NEXT_PUBLIC_UMAMI_SCRIPT_URL: process.env.NEXT_PUBLIC_UMAMI_SCRIPT_URL,
|
||||
NEXT_PUBLIC_AUTHENTIK_ENABLED: process.env.NEXT_PUBLIC_AUTHENTIK_ENABLED,
|
||||
NEXT_PUBLIC_BRAND_NAME: process.env.NEXT_PUBLIC_BRAND_NAME,
|
||||
NEXT_PUBLIC_BRAND_TAGLINE: process.env.NEXT_PUBLIC_BRAND_TAGLINE,
|
||||
NEXT_PUBLIC_BRAND_LOGO_TEXT: process.env.NEXT_PUBLIC_BRAND_LOGO_TEXT,
|
||||
NEXT_PUBLIC_BRAND_ICON: process.env.NEXT_PUBLIC_BRAND_ICON,
|
||||
NEXT_PUBLIC_DEFAULT_INTERFACE_THEME:
|
||||
process.env.NEXT_PUBLIC_DEFAULT_INTERFACE_THEME,
|
||||
NEXT_PUBLIC_DEFAULT_FONT: process.env.NEXT_PUBLIC_DEFAULT_FONT,
|
||||
NEXT_PUBLIC_DEFAULT_BODY_FONT: process.env.NEXT_PUBLIC_DEFAULT_BODY_FONT,
|
||||
NEXT_PUBLIC_DEFAULT_HEADING_FONT:
|
||||
process.env.NEXT_PUBLIC_DEFAULT_HEADING_FONT,
|
||||
NEXT_PUBLIC_DEFAULT_RADIUS: process.env.NEXT_PUBLIC_DEFAULT_RADIUS,
|
||||
NEXT_PUBLIC_DEFAULT_SIDEBAR_STYLE:
|
||||
process.env.NEXT_PUBLIC_DEFAULT_SIDEBAR_STYLE,
|
||||
},
|
||||
/**
|
||||
* Run `build` or `dev` with `SKIP_ENV_VALIDATION` to skip env validation. This is especially
|
||||
|
||||
+53
-45
@@ -5,55 +5,63 @@ import { genericOAuth } from "better-auth/plugins";
|
||||
import { db } from "~/server/db";
|
||||
import * as schema from "~/server/db/schema";
|
||||
|
||||
const authentikEnabled = Boolean(
|
||||
process.env.AUTHENTIK_ISSUER &&
|
||||
process.env.AUTHENTIK_CLIENT_ID &&
|
||||
process.env.AUTHENTIK_CLIENT_SECRET,
|
||||
);
|
||||
|
||||
export const auth = betterAuth({
|
||||
database: drizzleAdapter(db, {
|
||||
provider: "pg",
|
||||
schema: {
|
||||
user: schema.users,
|
||||
session: schema.sessions,
|
||||
account: schema.accounts,
|
||||
verification: schema.verificationTokens,
|
||||
ssoProvider: schema.ssoProviders,
|
||||
},
|
||||
}),
|
||||
trustedOrigins: [
|
||||
"https://beenvoice.soconnor.dev",
|
||||
"https://auth.soconnor.dev", // Authentik IdP for OIDC discovery
|
||||
],
|
||||
database: drizzleAdapter(db, {
|
||||
provider: "pg",
|
||||
schema: {
|
||||
user: schema.users,
|
||||
session: schema.sessions,
|
||||
account: schema.accounts,
|
||||
verification: schema.verificationTokens,
|
||||
ssoProvider: schema.ssoProviders,
|
||||
},
|
||||
}),
|
||||
trustedOrigins: [
|
||||
"https://beenvoice.soconnor.dev",
|
||||
...(process.env.AUTHENTIK_ORIGIN ? [process.env.AUTHENTIK_ORIGIN] : []),
|
||||
],
|
||||
...(authentikEnabled && {
|
||||
accountLinking: {
|
||||
enabled: true,
|
||||
trustedProviders: ["authentik"],
|
||||
enabled: true,
|
||||
trustedProviders: ["authentik"],
|
||||
},
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
password: {
|
||||
hash: async (password) => {
|
||||
const bcrypt = await import("bcryptjs");
|
||||
return bcrypt.hash(password, 12);
|
||||
},
|
||||
verify: async ({ hash, password }) => {
|
||||
const bcrypt = await import("bcryptjs");
|
||||
return bcrypt.compare(password, hash);
|
||||
},
|
||||
},
|
||||
}),
|
||||
emailAndPassword: {
|
||||
enabled: true,
|
||||
password: {
|
||||
hash: async (password) => {
|
||||
const bcrypt = await import("bcryptjs");
|
||||
return bcrypt.hash(password, 12);
|
||||
},
|
||||
verify: async ({ hash, password }) => {
|
||||
const bcrypt = await import("bcryptjs");
|
||||
return bcrypt.compare(password, hash);
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
nextCookies(),
|
||||
genericOAuth({
|
||||
},
|
||||
plugins: [
|
||||
nextCookies(),
|
||||
...(authentikEnabled
|
||||
? [
|
||||
genericOAuth({
|
||||
config: [
|
||||
{
|
||||
providerId: "authentik",
|
||||
clientId: process.env.AUTHENTIK_CLIENT_ID!,
|
||||
clientSecret: process.env.AUTHENTIK_CLIENT_SECRET!,
|
||||
discoveryUrl: `${process.env.AUTHENTIK_ISSUER}/.well-known/openid-configuration`,
|
||||
// Explicit endpoints to ensure correct routing in production
|
||||
authorizationUrl: "https://auth.soconnor.dev/application/o/authorize/",
|
||||
tokenUrl: "https://auth.soconnor.dev/application/o/token/",
|
||||
userInfoUrl: "https://auth.soconnor.dev/application/o/userinfo/",
|
||||
scopes: ["openid", "email", "profile"],
|
||||
pkce: true,
|
||||
},
|
||||
{
|
||||
providerId: "authentik",
|
||||
clientId: process.env.AUTHENTIK_CLIENT_ID!,
|
||||
clientSecret: process.env.AUTHENTIK_CLIENT_SECRET!,
|
||||
discoveryUrl: `${process.env.AUTHENTIK_ISSUER}/.well-known/openid-configuration`,
|
||||
scopes: ["openid", "email", "profile"],
|
||||
pkce: true,
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
]
|
||||
: []),
|
||||
],
|
||||
});
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import { env } from "~/env";
|
||||
|
||||
export type InterfaceTheme = "beenvoice" | "shadcn" | "minimal" | "editorial";
|
||||
export type FontPreference = "brand" | "platform" | "inter" | "serif";
|
||||
export type RadiusPreference = "none" | "sm" | "md" | "lg" | "xl";
|
||||
export type SidebarStyle = "floating" | "docked";
|
||||
export type ColorMode = "light" | "dark" | "system";
|
||||
export type ColorTheme =
|
||||
| "slate"
|
||||
| "blue"
|
||||
| "green"
|
||||
| "rose"
|
||||
| "orange"
|
||||
| "custom";
|
||||
|
||||
export const interfaceThemes: {
|
||||
value: InterfaceTheme;
|
||||
label: string;
|
||||
description: string;
|
||||
}[] = [
|
||||
{
|
||||
value: "beenvoice",
|
||||
label: "beenvoice",
|
||||
description: "Opinionated brand system with expressive headings.",
|
||||
},
|
||||
{
|
||||
value: "shadcn",
|
||||
label: "shadcn/ui",
|
||||
description: "A plain shadcn baseline for white-label starts.",
|
||||
},
|
||||
{
|
||||
value: "minimal",
|
||||
label: "Minimal",
|
||||
description: "Quiet surfaces, lower contrast, and restrained chrome.",
|
||||
},
|
||||
{
|
||||
value: "editorial",
|
||||
label: "Editorial",
|
||||
description: "A warmer presentation style for service-led brands.",
|
||||
},
|
||||
];
|
||||
|
||||
export const themePresets: Record<
|
||||
InterfaceTheme,
|
||||
{
|
||||
interfaceTheme: InterfaceTheme;
|
||||
bodyFontPreference: FontPreference;
|
||||
headingFontPreference: FontPreference;
|
||||
colorTheme: ColorTheme;
|
||||
radiusPreference: RadiusPreference;
|
||||
sidebarStyle: SidebarStyle;
|
||||
}
|
||||
> = {
|
||||
beenvoice: {
|
||||
interfaceTheme: "beenvoice",
|
||||
bodyFontPreference: "brand",
|
||||
headingFontPreference: "brand",
|
||||
colorTheme: "slate",
|
||||
radiusPreference: "xl",
|
||||
sidebarStyle: "floating",
|
||||
},
|
||||
shadcn: {
|
||||
interfaceTheme: "shadcn",
|
||||
bodyFontPreference: "inter",
|
||||
headingFontPreference: "inter",
|
||||
colorTheme: "slate",
|
||||
radiusPreference: "md",
|
||||
sidebarStyle: "docked",
|
||||
},
|
||||
minimal: {
|
||||
interfaceTheme: "minimal",
|
||||
bodyFontPreference: "platform",
|
||||
headingFontPreference: "platform",
|
||||
colorTheme: "slate",
|
||||
radiusPreference: "sm",
|
||||
sidebarStyle: "docked",
|
||||
},
|
||||
editorial: {
|
||||
interfaceTheme: "editorial",
|
||||
bodyFontPreference: "platform",
|
||||
headingFontPreference: "serif",
|
||||
colorTheme: "rose",
|
||||
radiusPreference: "lg",
|
||||
sidebarStyle: "floating",
|
||||
},
|
||||
};
|
||||
|
||||
export const fontPreferences: {
|
||||
value: FontPreference;
|
||||
label: string;
|
||||
description: string;
|
||||
}[] = [
|
||||
{
|
||||
value: "brand",
|
||||
label: "Brand",
|
||||
description: "Inter body with Playfair headings.",
|
||||
},
|
||||
{
|
||||
value: "platform",
|
||||
label: "Platform",
|
||||
description: "Native system fonts for the current OS.",
|
||||
},
|
||||
{
|
||||
value: "inter",
|
||||
label: "Inter",
|
||||
description: "Inter for both body and headings.",
|
||||
},
|
||||
{
|
||||
value: "serif",
|
||||
label: "Editorial",
|
||||
description: "Serif headings with system body text.",
|
||||
},
|
||||
];
|
||||
|
||||
export const bodyFontPreferences: {
|
||||
value: FontPreference;
|
||||
label: string;
|
||||
description: string;
|
||||
}[] = [
|
||||
{
|
||||
value: "brand",
|
||||
label: "Brand Sans",
|
||||
description: "Inter body text for a clean product feel.",
|
||||
},
|
||||
{
|
||||
value: "platform",
|
||||
label: "Platform",
|
||||
description: "Native system body text for the current OS.",
|
||||
},
|
||||
{
|
||||
value: "inter",
|
||||
label: "Inter",
|
||||
description: "Inter body text, explicitly selected.",
|
||||
},
|
||||
{
|
||||
value: "serif",
|
||||
label: "Serif",
|
||||
description: "Georgia-style body text for editorial deployments.",
|
||||
},
|
||||
];
|
||||
|
||||
export const headingFontPreferences: {
|
||||
value: FontPreference;
|
||||
label: string;
|
||||
description: string;
|
||||
}[] = [
|
||||
{
|
||||
value: "brand",
|
||||
label: "Brand Serif",
|
||||
description: "Playfair headings for the BeenVoice identity.",
|
||||
},
|
||||
{
|
||||
value: "platform",
|
||||
label: "Platform",
|
||||
description: "Native system headings for a neutral app feel.",
|
||||
},
|
||||
{
|
||||
value: "inter",
|
||||
label: "Inter",
|
||||
description: "Inter headings for a plain shadcn-style baseline.",
|
||||
},
|
||||
{
|
||||
value: "serif",
|
||||
label: "Editorial",
|
||||
description: "Playfair headings with a stronger editorial tone.",
|
||||
},
|
||||
];
|
||||
|
||||
export const radiusPreferences: {
|
||||
value: RadiusPreference;
|
||||
label: string;
|
||||
description: string;
|
||||
}[] = [
|
||||
{ value: "none", label: "Square", description: "No rounded corners." },
|
||||
{ value: "sm", label: "Small", description: "Subtle 4px rounding." },
|
||||
{ value: "md", label: "Medium", description: "Standard 8px rounding." },
|
||||
{ value: "lg", label: "Large", description: "Soft 12px rounding." },
|
||||
{
|
||||
value: "xl",
|
||||
label: "Extra Large",
|
||||
description: "Expressive 16px rounding.",
|
||||
},
|
||||
];
|
||||
|
||||
export const sidebarStyles: {
|
||||
value: SidebarStyle;
|
||||
label: string;
|
||||
description: string;
|
||||
}[] = [
|
||||
{
|
||||
value: "floating",
|
||||
label: "Floating",
|
||||
description: "Inset navigation with rounded edges and elevation.",
|
||||
},
|
||||
{
|
||||
value: "docked",
|
||||
label: "Flush",
|
||||
description: "Full-height navigation aligned to the viewport edge.",
|
||||
},
|
||||
];
|
||||
|
||||
export const colorThemes: {
|
||||
value: ColorTheme;
|
||||
label: string;
|
||||
swatch: string;
|
||||
}[] = [
|
||||
{ value: "slate", label: "Slate", swatch: "hsl(240 5.9% 10%)" },
|
||||
{ value: "blue", label: "Blue", swatch: "hsl(221.2 83.2% 53.3%)" },
|
||||
{ value: "green", label: "Green", swatch: "hsl(142.1 76.2% 36.3%)" },
|
||||
{ value: "rose", label: "Rose", swatch: "hsl(346.8 77.2% 49.8%)" },
|
||||
{ value: "orange", label: "Orange", swatch: "hsl(24.6 95% 53.1%)" },
|
||||
];
|
||||
|
||||
export const colorModes: {
|
||||
value: ColorMode;
|
||||
label: string;
|
||||
description: string;
|
||||
}[] = [
|
||||
{ value: "system", label: "System", description: "Follow device setting." },
|
||||
{ value: "light", label: "Light", description: "Always use light mode." },
|
||||
{ value: "dark", label: "Dark", description: "Always use dark mode." },
|
||||
];
|
||||
|
||||
export const defaultInterfaceTheme: InterfaceTheme =
|
||||
env.NEXT_PUBLIC_DEFAULT_INTERFACE_THEME ?? "beenvoice";
|
||||
|
||||
export const defaultFontPreference: FontPreference =
|
||||
env.NEXT_PUBLIC_DEFAULT_FONT ?? "brand";
|
||||
|
||||
export const defaultBodyFontPreference: FontPreference =
|
||||
env.NEXT_PUBLIC_DEFAULT_BODY_FONT ?? defaultFontPreference;
|
||||
|
||||
export const defaultHeadingFontPreference: FontPreference =
|
||||
env.NEXT_PUBLIC_DEFAULT_HEADING_FONT ?? defaultFontPreference;
|
||||
|
||||
export const defaultRadiusPreference: RadiusPreference =
|
||||
env.NEXT_PUBLIC_DEFAULT_RADIUS ?? "xl";
|
||||
|
||||
export const defaultSidebarStyle: SidebarStyle =
|
||||
env.NEXT_PUBLIC_DEFAULT_SIDEBAR_STYLE ?? "floating";
|
||||
|
||||
export const brand = {
|
||||
name: env.NEXT_PUBLIC_BRAND_NAME ?? "beenvoice",
|
||||
tagline:
|
||||
env.NEXT_PUBLIC_BRAND_TAGLINE ??
|
||||
"Simple and efficient invoicing for freelancers and small businesses",
|
||||
logoText: env.NEXT_PUBLIC_BRAND_LOGO_TEXT ?? "beenvoice",
|
||||
icon: env.NEXT_PUBLIC_BRAND_ICON ?? "$",
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
export const EXPENSE_CATEGORIES = [
|
||||
"Travel",
|
||||
"Meals & Entertainment",
|
||||
"Software & Subscriptions",
|
||||
"Hardware & Equipment",
|
||||
"Office Supplies",
|
||||
"Marketing",
|
||||
"Professional Services",
|
||||
"Utilities",
|
||||
"Other",
|
||||
] as const;
|
||||
+303
-272
@@ -5,11 +5,31 @@ import {
|
||||
View,
|
||||
Image,
|
||||
StyleSheet,
|
||||
Font,
|
||||
pdf,
|
||||
} from "@react-pdf/renderer";
|
||||
import { saveAs } from "file-saver";
|
||||
import React from "react";
|
||||
|
||||
Font.register({
|
||||
family: "Frutiger",
|
||||
fonts: [
|
||||
{
|
||||
src: "/fonts/frutiger/Frutiger.ttf",
|
||||
fontWeight: "normal",
|
||||
},
|
||||
{
|
||||
src: "/fonts/frutiger/Frutiger_bold.ttf",
|
||||
fontWeight: "bold",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
Font.register({
|
||||
family: "Frutiger-Bold",
|
||||
src: "/fonts/frutiger/Frutiger_bold.ttf",
|
||||
});
|
||||
|
||||
// Fallback download function for better browser compatibility
|
||||
function downloadBlob(blob: Blob, filename: string): void {
|
||||
try {
|
||||
@@ -56,11 +76,13 @@ function downloadBlob(blob: Blob, filename: string): void {
|
||||
|
||||
interface InvoiceData {
|
||||
invoiceNumber: string;
|
||||
invoicePrefix?: string | null;
|
||||
issueDate: Date;
|
||||
dueDate: Date;
|
||||
status: string;
|
||||
totalAmount: number;
|
||||
taxRate: number;
|
||||
currency?: string | null;
|
||||
notes?: string | null;
|
||||
business?: {
|
||||
name: string;
|
||||
@@ -96,11 +118,31 @@ interface InvoiceData {
|
||||
} | null> | null;
|
||||
}
|
||||
|
||||
export interface PDFGenerationSettings {
|
||||
pdfTemplate?: "classic" | "minimal";
|
||||
pdfAccentColor?: string;
|
||||
pdfFooterText?: string;
|
||||
pdfShowLogo?: boolean;
|
||||
pdfShowPageNumbers?: boolean;
|
||||
}
|
||||
|
||||
const defaultPDFSettings: Required<PDFGenerationSettings> = {
|
||||
pdfTemplate: "classic",
|
||||
pdfAccentColor: "#111827",
|
||||
pdfFooterText: "Professional Invoicing",
|
||||
pdfShowLogo: true,
|
||||
pdfShowPageNumbers: true,
|
||||
};
|
||||
|
||||
function resolvePDFSettings(settings?: PDFGenerationSettings) {
|
||||
return { ...defaultPDFSettings, ...settings };
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
page: {
|
||||
flexDirection: "column",
|
||||
backgroundColor: "#ffffff",
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
fontSize: 10,
|
||||
paddingTop: 40,
|
||||
paddingBottom: 80,
|
||||
@@ -127,7 +169,7 @@ const styles = StyleSheet.create({
|
||||
},
|
||||
|
||||
businessName: {
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
fontSize: 18,
|
||||
color: "#0f0f0f",
|
||||
marginBottom: 4,
|
||||
@@ -135,7 +177,7 @@ const styles = StyleSheet.create({
|
||||
|
||||
businessInfo: {
|
||||
fontSize: 10,
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
color: "#6b7280",
|
||||
lineHeight: 1.4,
|
||||
marginBottom: 3,
|
||||
@@ -143,7 +185,7 @@ const styles = StyleSheet.create({
|
||||
|
||||
businessAddress: {
|
||||
fontSize: 10,
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
color: "#6b7280",
|
||||
lineHeight: 1.4,
|
||||
marginTop: 4,
|
||||
@@ -156,14 +198,14 @@ const styles = StyleSheet.create({
|
||||
|
||||
invoiceTitle: {
|
||||
fontSize: 28,
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
color: "#0f0f0f",
|
||||
marginBottom: 8,
|
||||
},
|
||||
|
||||
invoiceNumber: {
|
||||
fontSize: 14,
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
color: "#374151",
|
||||
marginBottom: 4,
|
||||
},
|
||||
@@ -172,7 +214,7 @@ const styles = StyleSheet.create({
|
||||
paddingHorizontal: 8,
|
||||
paddingVertical: 4,
|
||||
fontSize: 11,
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
textAlign: "center",
|
||||
},
|
||||
|
||||
@@ -200,13 +242,13 @@ const styles = StyleSheet.create({
|
||||
|
||||
sectionTitle: {
|
||||
fontSize: 12,
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
color: "#0f0f0f",
|
||||
marginBottom: 12,
|
||||
},
|
||||
|
||||
clientName: {
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
fontSize: 12,
|
||||
color: "#0f0f0f",
|
||||
marginBottom: 2,
|
||||
@@ -214,7 +256,7 @@ const styles = StyleSheet.create({
|
||||
|
||||
clientInfo: {
|
||||
fontSize: 10,
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
color: "#6b7280",
|
||||
lineHeight: 1.4,
|
||||
marginBottom: 2,
|
||||
@@ -222,7 +264,7 @@ const styles = StyleSheet.create({
|
||||
|
||||
clientAddress: {
|
||||
fontSize: 10,
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
color: "#6b7280",
|
||||
lineHeight: 1.4,
|
||||
marginTop: 4,
|
||||
@@ -236,14 +278,14 @@ const styles = StyleSheet.create({
|
||||
|
||||
detailLabel: {
|
||||
fontSize: 11,
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
color: "#6b7280",
|
||||
flex: 1,
|
||||
},
|
||||
|
||||
detailValue: {
|
||||
fontSize: 10,
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
color: "#0f0f0f",
|
||||
flex: 1,
|
||||
textAlign: "right",
|
||||
@@ -259,21 +301,21 @@ const styles = StyleSheet.create({
|
||||
|
||||
notesTitle: {
|
||||
fontSize: 11,
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
color: "#0f0f0f",
|
||||
marginBottom: 6,
|
||||
},
|
||||
|
||||
notesContent: {
|
||||
fontSize: 10,
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
color: "#374151",
|
||||
lineHeight: 1.4,
|
||||
},
|
||||
|
||||
businessContact: {
|
||||
fontSize: 9,
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
color: "#6b7280",
|
||||
lineHeight: 1.4,
|
||||
},
|
||||
@@ -297,7 +339,7 @@ const styles = StyleSheet.create({
|
||||
|
||||
abridgedBusinessName: {
|
||||
fontSize: 12,
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
color: "#0f0f0f",
|
||||
},
|
||||
|
||||
@@ -309,13 +351,13 @@ const styles = StyleSheet.create({
|
||||
|
||||
abridgedInvoiceTitle: {
|
||||
fontSize: 14,
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
color: "#0f0f0f",
|
||||
},
|
||||
|
||||
abridgedInvoiceNumber: {
|
||||
fontSize: 12,
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
color: "#374151",
|
||||
},
|
||||
|
||||
@@ -335,7 +377,7 @@ const styles = StyleSheet.create({
|
||||
|
||||
tableHeaderCell: {
|
||||
fontSize: 10,
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
color: "#374151",
|
||||
paddingHorizontal: 4,
|
||||
},
|
||||
@@ -380,7 +422,7 @@ const styles = StyleSheet.create({
|
||||
color: "#0f0f0f",
|
||||
paddingHorizontal: 4,
|
||||
paddingVertical: 2,
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
},
|
||||
|
||||
tableCellDate: {
|
||||
@@ -396,7 +438,7 @@ const styles = StyleSheet.create({
|
||||
paddingHorizontal: 2,
|
||||
textAlign: "left",
|
||||
flexWrap: "wrap",
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
},
|
||||
|
||||
tableCellHours: {
|
||||
@@ -454,7 +496,7 @@ const styles = StyleSheet.create({
|
||||
totalLabel: {
|
||||
fontSize: 11,
|
||||
color: "#6b7280",
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
},
|
||||
|
||||
totalAmount: {
|
||||
@@ -472,7 +514,7 @@ const styles = StyleSheet.create({
|
||||
|
||||
finalTotalLabel: {
|
||||
fontSize: 12,
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
color: "#0f0f0f",
|
||||
},
|
||||
|
||||
@@ -484,7 +526,7 @@ const styles = StyleSheet.create({
|
||||
|
||||
itemCount: {
|
||||
fontSize: 9,
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
color: "#9ca3af",
|
||||
textAlign: "center",
|
||||
marginTop: 6,
|
||||
@@ -511,16 +553,16 @@ const styles = StyleSheet.create({
|
||||
|
||||
pageNumber: {
|
||||
fontSize: 10,
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
color: "#6b7280",
|
||||
},
|
||||
});
|
||||
|
||||
// Helper functions
|
||||
const formatCurrency = (amount: number) => {
|
||||
const formatCurrency = (amount: number, currency = "USD") => {
|
||||
return new Intl.NumberFormat("en-US", {
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
currency,
|
||||
}).format(amount);
|
||||
};
|
||||
|
||||
@@ -565,212 +607,95 @@ const getStatusStyle = (status: string) => {
|
||||
}
|
||||
};
|
||||
|
||||
// Helper function to estimate text height based on content and width
|
||||
function estimateTextHeight(
|
||||
text: string,
|
||||
maxWidth: number,
|
||||
fontSize = 10,
|
||||
lineHeight = 1.3,
|
||||
): number {
|
||||
if (!text) return fontSize * lineHeight;
|
||||
|
||||
// Rough character width estimation for Helvetica at given font size
|
||||
const avgCharWidth = fontSize * 0.6;
|
||||
const maxCharsPerLine = Math.floor(maxWidth / avgCharWidth);
|
||||
|
||||
if (maxCharsPerLine <= 0) return fontSize * lineHeight;
|
||||
|
||||
const lines = Math.ceil(text.length / maxCharsPerLine);
|
||||
return lines * fontSize * lineHeight;
|
||||
function pageContentBudget(isFirstPage: boolean, hasNotes: boolean): number {
|
||||
// 792pt page - 40pt paddingTop - 80pt paddingBottom = 672pt usable
|
||||
let h = 672;
|
||||
h -= isFirstPage ? 285 : 50; // dense vs abridged header
|
||||
h -= hasNotes ? 185 : 130; // totals box (+ notes section if present)
|
||||
h -= 28; // table header row
|
||||
return h;
|
||||
}
|
||||
|
||||
// Calculate estimated height for a table row based on actual content
|
||||
function calculateRowHeight(
|
||||
item: NonNullable<InvoiceData["items"]>[0],
|
||||
function estimateRowHeight(
|
||||
item: NonNullable<NonNullable<InvoiceData["items"]>[0]>,
|
||||
showRate: boolean,
|
||||
): number {
|
||||
if (!item) return 18; // fallback
|
||||
|
||||
const basePadding = 8; // Row padding
|
||||
const fontSize = 10;
|
||||
const lineHeight = 1.3;
|
||||
|
||||
// Description column is 40% of table width
|
||||
// Table width is roughly 512 points (letter width - margins)
|
||||
const descriptionWidth = 512 * 0.4;
|
||||
|
||||
const descriptionHeight = estimateTextHeight(
|
||||
item.description,
|
||||
descriptionWidth,
|
||||
fontSize,
|
||||
lineHeight,
|
||||
);
|
||||
|
||||
// Minimum row height for other columns
|
||||
const minRowHeight = fontSize * lineHeight;
|
||||
|
||||
// Row height is the maximum of description height and minimum height, plus padding
|
||||
// Ensure minimum row height of 24 points for readability
|
||||
return Math.max(descriptionHeight, minRowHeight, 24) + basePadding;
|
||||
// 532pt usable width (612 - 80pt horizontal padding); description takes 40% or 48%
|
||||
const descColWidth = 532 * (showRate ? 0.4 : 0.48);
|
||||
// Frutiger at 10pt: 0.45em gives ~47 chars/line, matching real wrap behaviour
|
||||
const charsPerLine = Math.max(1, Math.floor(descColWidth / (10 * 0.45)));
|
||||
const lines = Math.ceil((item.description.length || 1) / charsPerLine);
|
||||
// row paddingVertical:6 (×2=12) + cell paddingVertical:4 (×2=8) = 20pt overhead,
|
||||
// but react-pdf measures the line box at slightly under full lineHeight, so 16pt in practice
|
||||
return lines * 10 * 1.4 + 16;
|
||||
}
|
||||
|
||||
// Dynamic pagination calculation based on actual content
|
||||
function calculateItemsForPage(
|
||||
items: NonNullable<InvoiceData["items"]>,
|
||||
startIndex: number,
|
||||
isFirstPage: boolean,
|
||||
hasNotes: boolean,
|
||||
): number {
|
||||
// Estimate available space in points (1 point = 1/72 inch)
|
||||
const pageHeight = 792; // Letter size height in points
|
||||
const margins = 80; // Top + bottom margins
|
||||
const footerSpace = 60; // Footer space
|
||||
|
||||
let availableHeight = pageHeight - margins - footerSpace;
|
||||
|
||||
if (isFirstPage) {
|
||||
// Dense header takes significant space
|
||||
availableHeight -= 300; // Dense header space
|
||||
} else {
|
||||
// Abridged header is smaller
|
||||
availableHeight -= 60; // Abridged header space
|
||||
}
|
||||
|
||||
if (hasNotes) {
|
||||
// Last page needs space for totals and notes
|
||||
availableHeight -= 200; // Totals + notes space (much more conservative)
|
||||
} else {
|
||||
// Regular page just needs totals space
|
||||
availableHeight -= 150; // Totals space only (much more conservative)
|
||||
}
|
||||
|
||||
// Table header takes space
|
||||
availableHeight -= 30; // Table header
|
||||
|
||||
// Calculate how many items can fit based on actual row heights
|
||||
let usedHeight = 0;
|
||||
let itemCount = 0;
|
||||
|
||||
for (let i = startIndex; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
if (!item) continue;
|
||||
|
||||
const rowHeight = calculateRowHeight(item);
|
||||
|
||||
if (usedHeight + rowHeight > availableHeight) {
|
||||
break; // This item won't fit
|
||||
}
|
||||
|
||||
usedHeight += rowHeight;
|
||||
itemCount++;
|
||||
}
|
||||
|
||||
return Math.max(1, itemCount); // Always return at least 1 item
|
||||
}
|
||||
|
||||
// Fallback function for backward compatibility
|
||||
function calculateItemsPerPage(
|
||||
isFirstPage: boolean,
|
||||
hasNotes: boolean,
|
||||
): number {
|
||||
// Estimate available space in points (1 point = 1/72 inch)
|
||||
const pageHeight = 792; // Letter size height in points
|
||||
const margins = 80; // Top + bottom margins
|
||||
const footerSpace = 60; // Footer space
|
||||
|
||||
let availableHeight = pageHeight - margins - footerSpace;
|
||||
|
||||
if (isFirstPage) {
|
||||
// Dense header takes significant space
|
||||
availableHeight -= 300; // Dense header space
|
||||
} else {
|
||||
// Abridged header is smaller
|
||||
availableHeight -= 60; // Abridged header space
|
||||
}
|
||||
|
||||
if (hasNotes) {
|
||||
// Last page needs space for totals and notes
|
||||
availableHeight -= 200; // Totals + notes space (much more conservative)
|
||||
} else {
|
||||
// Regular page just needs totals space
|
||||
availableHeight -= 150; // Totals space only (much more conservative)
|
||||
}
|
||||
|
||||
// Table header takes space
|
||||
availableHeight -= 30; // Table header
|
||||
|
||||
// Conservative estimate using average row height
|
||||
const avgRowHeight = 24; // Increased from 18 to account for potential wrapping
|
||||
|
||||
return Math.max(1, Math.floor(availableHeight / avgRowHeight));
|
||||
}
|
||||
|
||||
// Dynamic pagination function
|
||||
function paginateItems(
|
||||
items: NonNullable<InvoiceData["items"]>,
|
||||
hasNotes = false,
|
||||
showRate = true,
|
||||
) {
|
||||
const validItems = items.filter(Boolean);
|
||||
const pages: Array<typeof validItems> = [];
|
||||
const validItems = items.filter(Boolean) as NonNullable<typeof items[0]>[];
|
||||
if (validItems.length === 0) return [[]];
|
||||
|
||||
if (validItems.length === 0) {
|
||||
return [[]];
|
||||
const rowHeights = validItems.map((item) => estimateRowHeight(item, showRate));
|
||||
|
||||
function pack(startIdx: number, budget: number): number {
|
||||
let used = 0, count = 0;
|
||||
for (let i = startIdx; i < validItems.length; i++) {
|
||||
if (used + rowHeights[i]! > budget) break;
|
||||
used += rowHeights[i]!;
|
||||
count++;
|
||||
}
|
||||
return Math.max(1, count);
|
||||
}
|
||||
|
||||
let currentIndex = 0;
|
||||
let pageIndex = 0;
|
||||
const pages: (typeof validItems)[] = [];
|
||||
let idx = 0;
|
||||
|
||||
while (currentIndex < validItems.length) {
|
||||
const isFirstPage = pageIndex === 0;
|
||||
const remainingItems = validItems.length - currentIndex;
|
||||
while (idx < validItems.length) {
|
||||
const isFirst = pages.length === 0;
|
||||
const countFull = pack(idx, pageContentBudget(isFirst, false));
|
||||
|
||||
// Determine if this could be the last page with simple calculation
|
||||
const maxPossibleItems = calculateItemsPerPage(isFirstPage, false);
|
||||
const wouldBeLastPage =
|
||||
currentIndex + maxPossibleItems >= validItems.length;
|
||||
|
||||
// Calculate items per page, accounting for notes space if this is likely the last page
|
||||
let itemsPerPage = calculateItemsForPage(
|
||||
validItems,
|
||||
currentIndex,
|
||||
isFirstPage,
|
||||
wouldBeLastPage && hasNotes,
|
||||
);
|
||||
|
||||
// Fallback to conservative calculation if dynamic fails
|
||||
if (itemsPerPage === 0) {
|
||||
itemsPerPage = calculateItemsPerPage(
|
||||
isFirstPage,
|
||||
wouldBeLastPage && hasNotes,
|
||||
);
|
||||
if (idx + countFull >= validItems.length) {
|
||||
// All remaining items fit — if there are notes, verify they also fit with the notes reservation
|
||||
if (hasNotes) {
|
||||
const countWithNotes = pack(idx, pageContentBudget(isFirst, true));
|
||||
if (idx + countWithNotes >= validItems.length) {
|
||||
pages.push(validItems.slice(idx));
|
||||
break;
|
||||
}
|
||||
// Notes don't fit alongside all items — push what fits, notes go on next page
|
||||
pages.push(validItems.slice(idx, idx + countWithNotes));
|
||||
idx += countWithNotes;
|
||||
} else {
|
||||
pages.push(validItems.slice(idx));
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
pages.push(validItems.slice(idx, idx + countFull));
|
||||
idx += countFull;
|
||||
}
|
||||
|
||||
// Ensure we don't have tiny orphan pages
|
||||
if (remainingItems > itemsPerPage && remainingItems - itemsPerPage < 2) {
|
||||
itemsPerPage = Math.max(1, itemsPerPage - 1);
|
||||
}
|
||||
|
||||
// Never take more items than we have
|
||||
itemsPerPage = Math.min(itemsPerPage, remainingItems);
|
||||
|
||||
const pageItems = validItems.slice(
|
||||
currentIndex,
|
||||
currentIndex + itemsPerPage,
|
||||
);
|
||||
|
||||
pages.push(pageItems);
|
||||
currentIndex += itemsPerPage;
|
||||
pageIndex++;
|
||||
}
|
||||
|
||||
return pages;
|
||||
}
|
||||
|
||||
function getColumnWidths(showRate: boolean) {
|
||||
return showRate
|
||||
? { date: "15%", description: "40%", hours: "12%", rate: "15%", amount: "18%" }
|
||||
: { date: "15%", description: "48%", hours: "14%", amount: "23%" };
|
||||
}
|
||||
|
||||
// Dense header component (first page)
|
||||
const DenseHeader: React.FC<{ invoice: InvoiceData }> = ({ invoice }) => (
|
||||
const DenseHeader: React.FC<{
|
||||
invoice: InvoiceData;
|
||||
settings: Required<PDFGenerationSettings>;
|
||||
}> = ({ invoice, settings }) => (
|
||||
<View style={styles.denseHeader}>
|
||||
<View style={styles.headerTop}>
|
||||
<View style={styles.businessSection}>
|
||||
<Text style={styles.businessName}>
|
||||
<Text style={[styles.businessName, { color: settings.pdfAccentColor }]}>
|
||||
{invoice.business?.name ?? "Your Business Name"}
|
||||
</Text>
|
||||
{invoice.business?.email && (
|
||||
@@ -806,8 +731,13 @@ const DenseHeader: React.FC<{ invoice: InvoiceData }> = ({ invoice }) => (
|
||||
</View>
|
||||
|
||||
<View style={styles.invoiceSection}>
|
||||
<Text style={styles.invoiceTitle}>INVOICE</Text>
|
||||
<Text style={styles.invoiceNumber}>#{invoice.invoiceNumber}</Text>
|
||||
<Text style={[styles.invoiceTitle, { color: settings.pdfAccentColor }]}>
|
||||
INVOICE
|
||||
</Text>
|
||||
<Text style={styles.invoiceNumber}>
|
||||
{invoice.invoicePrefix ?? "#"}
|
||||
{invoice.invoiceNumber}
|
||||
</Text>
|
||||
<View style={getStatusStyle(invoice.status)}>
|
||||
<Text>{getStatusLabel(invoice.status)}</Text>
|
||||
</View>
|
||||
@@ -866,32 +796,75 @@ const DenseHeader: React.FC<{ invoice: InvoiceData }> = ({ invoice }) => (
|
||||
);
|
||||
|
||||
// Abridged header component (other pages)
|
||||
const AbridgedHeader: React.FC<{ invoice: InvoiceData }> = ({ invoice }) => (
|
||||
const AbridgedHeader: React.FC<{
|
||||
invoice: InvoiceData;
|
||||
settings: Required<PDFGenerationSettings>;
|
||||
}> = ({ invoice, settings }) => (
|
||||
<View style={styles.abridgedHeader}>
|
||||
<Text style={styles.abridgedBusinessName}>
|
||||
<Text
|
||||
style={[styles.abridgedBusinessName, { color: settings.pdfAccentColor }]}
|
||||
>
|
||||
{invoice.business?.name ?? "Your Business Name"}
|
||||
</Text>
|
||||
<View style={styles.abridgedInvoiceInfo}>
|
||||
<Text style={styles.abridgedInvoiceTitle}>INVOICE</Text>
|
||||
<Text style={styles.abridgedInvoiceNumber}>#{invoice.invoiceNumber}</Text>
|
||||
<Text style={styles.abridgedInvoiceNumber}>
|
||||
{invoice.invoicePrefix ?? "#"}
|
||||
{invoice.invoiceNumber}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
|
||||
// Table header component
|
||||
const TableHeader: React.FC = () => (
|
||||
<View style={styles.tableHeader}>
|
||||
<Text style={[styles.tableHeaderCell, styles.tableHeaderDate]}>Date</Text>
|
||||
<Text style={[styles.tableHeaderCell, styles.tableHeaderDescription]}>
|
||||
Description
|
||||
</Text>
|
||||
<Text style={[styles.tableHeaderCell, styles.tableHeaderHours]}>Hours</Text>
|
||||
<Text style={[styles.tableHeaderCell, styles.tableHeaderRate]}>Rate</Text>
|
||||
<Text style={[styles.tableHeaderCell, styles.tableHeaderAmount]}>
|
||||
Amount
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
const TableHeader: React.FC<{
|
||||
settings: Required<PDFGenerationSettings>;
|
||||
showRate: boolean;
|
||||
}> = ({ settings, showRate }) => {
|
||||
const cols = getColumnWidths(showRate);
|
||||
return (
|
||||
<View
|
||||
style={[
|
||||
styles.tableHeader,
|
||||
settings.pdfTemplate === "minimal" ? { backgroundColor: "#ffffff" } : {},
|
||||
]}
|
||||
>
|
||||
<Text style={[styles.tableHeaderCell, { width: cols.date }]}>Date</Text>
|
||||
<Text style={[styles.tableHeaderCell, { width: cols.description }]}>
|
||||
Description
|
||||
</Text>
|
||||
<Text
|
||||
style={[
|
||||
styles.tableHeaderCell,
|
||||
styles.tableHeaderHours,
|
||||
{ width: cols.hours },
|
||||
]}
|
||||
>
|
||||
Hours
|
||||
</Text>
|
||||
{showRate && (
|
||||
<Text
|
||||
style={[
|
||||
styles.tableHeaderCell,
|
||||
styles.tableHeaderRate,
|
||||
{ width: cols.rate },
|
||||
]}
|
||||
>
|
||||
Rate
|
||||
</Text>
|
||||
)}
|
||||
<Text
|
||||
style={[
|
||||
styles.tableHeaderCell,
|
||||
styles.tableHeaderAmount,
|
||||
{ width: cols.amount },
|
||||
]}
|
||||
>
|
||||
Amount
|
||||
</Text>
|
||||
</View>
|
||||
);
|
||||
};
|
||||
|
||||
// Footer component
|
||||
const NotesSection: React.FC<{ invoice: InvoiceData }> = ({ invoice }) => {
|
||||
@@ -907,35 +880,40 @@ const NotesSection: React.FC<{ invoice: InvoiceData }> = ({ invoice }) => {
|
||||
);
|
||||
};
|
||||
|
||||
const Footer: React.FC = () => (
|
||||
const Footer: React.FC<{ settings: Required<PDFGenerationSettings> }> = ({
|
||||
settings,
|
||||
}) => (
|
||||
<View style={styles.footer} fixed>
|
||||
<View style={styles.footerLogo}>
|
||||
{/* eslint-disable-next-line jsx-a11y/alt-text */}
|
||||
<Image
|
||||
src="/beenvoice-logo.png"
|
||||
style={{
|
||||
width: 120,
|
||||
height: 18,
|
||||
marginRight: 8,
|
||||
}}
|
||||
/>
|
||||
{settings.pdfShowLogo && (
|
||||
<Image
|
||||
src="/beenvoice-logo.png"
|
||||
style={{
|
||||
width: 120,
|
||||
height: 18,
|
||||
marginRight: 8,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<Text
|
||||
style={{
|
||||
fontSize: 9,
|
||||
fontFamily: "Helvetica",
|
||||
fontFamily: "Frutiger",
|
||||
color: "#6b7280",
|
||||
marginLeft: 8,
|
||||
marginLeft: settings.pdfShowLogo ? 8 : 0,
|
||||
}}
|
||||
>
|
||||
Professional Invoicing
|
||||
{settings.pdfFooterText}
|
||||
</Text>
|
||||
</View>
|
||||
<Text
|
||||
style={styles.pageNumber}
|
||||
render={({ pageNumber, totalPages }) =>
|
||||
`Page ${pageNumber} of ${totalPages}`
|
||||
}
|
||||
/>
|
||||
{settings.pdfShowPageNumbers && (
|
||||
<Text
|
||||
style={styles.pageNumber}
|
||||
render={({ pageNumber, totalPages }) =>
|
||||
`Page ${pageNumber} of ${totalPages}`
|
||||
}
|
||||
/>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -943,17 +921,31 @@ const Footer: React.FC = () => (
|
||||
const TotalsSection: React.FC<{
|
||||
invoice: InvoiceData;
|
||||
items: Array<NonNullable<InvoiceData["items"]>[0]>;
|
||||
}> = ({ invoice, items }) => {
|
||||
settings: Required<PDFGenerationSettings>;
|
||||
}> = ({ invoice, items, settings }) => {
|
||||
const currency = invoice.currency ?? "USD";
|
||||
const subtotal = items.reduce((sum, item) => sum + (item?.amount ?? 0), 0);
|
||||
const taxAmount = (subtotal * invoice.taxRate) / 100;
|
||||
const total = subtotal + taxAmount;
|
||||
|
||||
return (
|
||||
<View style={styles.totalsContainer}>
|
||||
<View style={styles.totalsBox}>
|
||||
<View
|
||||
style={[
|
||||
styles.totalsBox,
|
||||
settings.pdfTemplate === "minimal"
|
||||
? {
|
||||
backgroundColor: "#ffffff",
|
||||
borderTop: "1px solid #e5e7eb",
|
||||
paddingHorizontal: 0,
|
||||
}
|
||||
: {},
|
||||
]}
|
||||
>
|
||||
<Text
|
||||
style={{
|
||||
fontSize: 11,
|
||||
fontFamily: "Helvetica-Bold",
|
||||
fontFamily: "Frutiger-Bold",
|
||||
color: "#0f0f0f",
|
||||
textAlign: "center",
|
||||
marginBottom: 8,
|
||||
@@ -965,20 +957,29 @@ const TotalsSection: React.FC<{
|
||||
|
||||
<View style={styles.totalRow}>
|
||||
<Text style={styles.totalLabel}>Subtotal:</Text>
|
||||
<Text style={styles.totalAmount}>{formatCurrency(subtotal)}</Text>
|
||||
<Text style={styles.totalAmount}>
|
||||
{formatCurrency(subtotal, currency)}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
{invoice.taxRate > 0 && (
|
||||
<View style={styles.totalRow}>
|
||||
<Text style={styles.totalLabel}>Tax ({invoice.taxRate}%):</Text>
|
||||
<Text style={styles.totalAmount}>{formatCurrency(taxAmount)}</Text>
|
||||
<Text style={styles.totalAmount}>
|
||||
{formatCurrency(taxAmount, currency)}
|
||||
</Text>
|
||||
</View>
|
||||
)}
|
||||
|
||||
<View style={styles.finalTotalRow}>
|
||||
<Text style={styles.finalTotalLabel}>TOTAL:</Text>
|
||||
<Text style={styles.finalTotalAmount}>
|
||||
{formatCurrency(invoice.totalAmount)}
|
||||
<Text
|
||||
style={[
|
||||
styles.finalTotalAmount,
|
||||
{ color: settings.pdfAccentColor },
|
||||
]}
|
||||
>
|
||||
{formatCurrency(total, currency)}
|
||||
</Text>
|
||||
</View>
|
||||
|
||||
@@ -991,9 +992,16 @@ const TotalsSection: React.FC<{
|
||||
};
|
||||
|
||||
// Main PDF component
|
||||
const InvoicePDF: React.FC<{ invoice: InvoiceData }> = ({ invoice }) => {
|
||||
const InvoicePDF: React.FC<{
|
||||
invoice: InvoiceData;
|
||||
settings?: PDFGenerationSettings;
|
||||
}> = ({ invoice, settings: inputSettings }) => {
|
||||
const settings = resolvePDFSettings(inputSettings);
|
||||
const items = invoice.items?.filter(Boolean) ?? [];
|
||||
const paginatedItems = paginateItems(items, Boolean(invoice.notes));
|
||||
const currency = invoice.currency ?? "USD";
|
||||
const showRate = new Set(items.map((item) => item?.rate)).size > 1;
|
||||
const cols = getColumnWidths(showRate);
|
||||
const paginatedItems = paginateItems(items, Boolean(invoice.notes), showRate);
|
||||
|
||||
return (
|
||||
<Document>
|
||||
@@ -1006,15 +1014,15 @@ const InvoicePDF: React.FC<{ invoice: InvoiceData }> = ({ invoice }) => {
|
||||
<Page key={`page-${pageIndex}`} size="LETTER" style={styles.page}>
|
||||
{/* Header */}
|
||||
{isFirstPage ? (
|
||||
<DenseHeader invoice={invoice} />
|
||||
<DenseHeader invoice={invoice} settings={settings} />
|
||||
) : (
|
||||
<AbridgedHeader invoice={invoice} />
|
||||
<AbridgedHeader invoice={invoice} settings={settings} />
|
||||
)}
|
||||
|
||||
{/* Table */}
|
||||
{hasItems && (
|
||||
<View style={styles.tableContainer}>
|
||||
<TableHeader />
|
||||
<TableHeader settings={settings} showRate={showRate} />
|
||||
{pageItems.map(
|
||||
(item, index) =>
|
||||
item && (
|
||||
@@ -1022,30 +1030,41 @@ const InvoicePDF: React.FC<{ invoice: InvoiceData }> = ({ invoice }) => {
|
||||
key={`${pageIndex}-${index}`}
|
||||
style={[
|
||||
styles.tableRow,
|
||||
index % 2 === 0 ? styles.tableRowAlt : {},
|
||||
settings.pdfTemplate === "classic" && index % 2 === 0
|
||||
? styles.tableRowAlt
|
||||
: {},
|
||||
]}
|
||||
>
|
||||
<Text style={[styles.tableCell, styles.tableCellDate]}>
|
||||
<Text style={[styles.tableCell, styles.tableCellDate, { width: cols.date }]}>
|
||||
{formatDate(item.date)}
|
||||
</Text>
|
||||
<Text
|
||||
style={[
|
||||
styles.tableCell,
|
||||
styles.tableCellDescription,
|
||||
{ width: cols.description },
|
||||
]}
|
||||
>
|
||||
{item.description}
|
||||
</Text>
|
||||
<Text style={[styles.tableCell, styles.tableCellHours]}>
|
||||
<Text style={[styles.tableCell, styles.tableCellHours, { width: cols.hours }]}>
|
||||
{item.hours}
|
||||
</Text>
|
||||
<Text style={[styles.tableCell, styles.tableCellRate]}>
|
||||
{formatCurrency(item.rate)}
|
||||
</Text>
|
||||
{showRate && (
|
||||
<Text
|
||||
style={[
|
||||
styles.tableCell,
|
||||
styles.tableCellRate,
|
||||
{ width: cols.rate },
|
||||
]}
|
||||
>
|
||||
{formatCurrency(item.rate, currency)}
|
||||
</Text>
|
||||
)}
|
||||
<Text
|
||||
style={[styles.tableCell, styles.tableCellAmount]}
|
||||
style={[styles.tableCell, styles.tableCellAmount, { width: cols.amount }]}
|
||||
>
|
||||
{formatCurrency(item.amount)}
|
||||
{formatCurrency(item.amount, currency)}
|
||||
</Text>
|
||||
</View>
|
||||
),
|
||||
@@ -1057,12 +1076,16 @@ const InvoicePDF: React.FC<{ invoice: InvoiceData }> = ({ invoice }) => {
|
||||
{isLastPage && (
|
||||
<View style={styles.bottomSection}>
|
||||
{invoice.notes && <NotesSection invoice={invoice} />}
|
||||
<TotalsSection invoice={invoice} items={items} />
|
||||
<TotalsSection
|
||||
invoice={invoice}
|
||||
items={items}
|
||||
settings={settings}
|
||||
/>
|
||||
</View>
|
||||
)}
|
||||
|
||||
{/* Footer */}
|
||||
<Footer />
|
||||
<Footer settings={settings} />
|
||||
</Page>
|
||||
);
|
||||
})}
|
||||
@@ -1071,7 +1094,10 @@ const InvoicePDF: React.FC<{ invoice: InvoiceData }> = ({ invoice }) => {
|
||||
};
|
||||
|
||||
// Export functions
|
||||
export async function generateInvoicePDF(invoice: InvoiceData): Promise<void> {
|
||||
export async function generateInvoicePDF(
|
||||
invoice: InvoiceData,
|
||||
settings?: PDFGenerationSettings,
|
||||
): Promise<void> {
|
||||
try {
|
||||
// Validate invoice data
|
||||
if (!invoice) {
|
||||
@@ -1087,7 +1113,9 @@ export async function generateInvoicePDF(invoice: InvoiceData): Promise<void> {
|
||||
}
|
||||
|
||||
// Generate PDF blob
|
||||
const originalBlob = await pdf(<InvoicePDF invoice={invoice} />).toBlob();
|
||||
const originalBlob = await pdf(
|
||||
<InvoicePDF invoice={invoice} settings={settings} />,
|
||||
).toBlob();
|
||||
|
||||
// Validate blob
|
||||
if (!originalBlob || originalBlob.size === 0) {
|
||||
@@ -1113,6 +1141,7 @@ export async function generateInvoicePDF(invoice: InvoiceData): Promise<void> {
|
||||
// Additional utility function for generating PDF without downloading
|
||||
export async function generateInvoicePDFBlob(
|
||||
invoice: InvoiceData,
|
||||
settings?: PDFGenerationSettings,
|
||||
): Promise<Blob> {
|
||||
try {
|
||||
// Validate invoice data
|
||||
@@ -1129,7 +1158,9 @@ export async function generateInvoicePDFBlob(
|
||||
}
|
||||
|
||||
// Generate PDF blob
|
||||
const originalBlob = await pdf(<InvoicePDF invoice={invoice} />).toBlob();
|
||||
const originalBlob = await pdf(
|
||||
<InvoicePDF invoice={invoice} settings={settings} />,
|
||||
).toBlob();
|
||||
|
||||
// Validate blob
|
||||
if (!originalBlob || originalBlob.size === 0) {
|
||||
|
||||
@@ -1,15 +1,12 @@
|
||||
import { z } from "zod";
|
||||
import { Resend } from "resend";
|
||||
import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
|
||||
import { invoices } from "~/server/db/schema";
|
||||
import { invoices, platformSettings } from "~/server/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { env } from "~/env";
|
||||
import { generateInvoicePDFBlob } from "~/lib/pdf-export";
|
||||
import { generateInvoiceEmailTemplate } from "~/lib/email-templates";
|
||||
|
||||
// Default Resend instance - will be overridden if business has custom API key
|
||||
const defaultResend = new Resend(env.RESEND_API_KEY);
|
||||
|
||||
export const emailRouter = createTRPCRouter({
|
||||
sendInvoice: protectedProcedure
|
||||
.input(
|
||||
@@ -56,7 +53,19 @@ export const emailRouter = createTRPCRouter({
|
||||
// Generate PDF for attachment
|
||||
let pdfBuffer: Buffer;
|
||||
try {
|
||||
const pdfBlob = await generateInvoicePDFBlob(invoice);
|
||||
const settings = await ctx.db.query.platformSettings.findFirst({
|
||||
where: eq(platformSettings.id, "global"),
|
||||
});
|
||||
const pdfBlob = await generateInvoicePDFBlob(invoice, {
|
||||
pdfTemplate: settings?.pdfTemplate as
|
||||
| "classic"
|
||||
| "minimal"
|
||||
| undefined,
|
||||
pdfAccentColor: settings?.pdfAccentColor,
|
||||
pdfFooterText: settings?.pdfFooterText,
|
||||
pdfShowLogo: settings?.pdfShowLogo,
|
||||
pdfShowPageNumbers: settings?.pdfShowPageNumbers,
|
||||
});
|
||||
pdfBuffer = Buffer.from(await pdfBlob.arrayBuffer());
|
||||
|
||||
// Validate PDF was generated successfully
|
||||
@@ -126,14 +135,17 @@ export const emailRouter = createTRPCRouter({
|
||||
: invoice.business.name) ??
|
||||
userName;
|
||||
fromEmail = `${fromName} <noreply@${invoice.business.resendDomain}>`;
|
||||
} else if (env.RESEND_DOMAIN) {
|
||||
} else if (env.RESEND_API_KEY && env.RESEND_DOMAIN) {
|
||||
// Use system Resend configuration
|
||||
resendInstance = defaultResend;
|
||||
resendInstance = new Resend(env.RESEND_API_KEY);
|
||||
fromEmail = `noreply@${env.RESEND_DOMAIN}`;
|
||||
} else if (env.RESEND_API_KEY) {
|
||||
resendInstance = new Resend(env.RESEND_API_KEY);
|
||||
fromEmail = invoice.business?.email ?? "noreply@example.com";
|
||||
} else {
|
||||
// Fallback to business email if no configured domains
|
||||
resendInstance = defaultResend;
|
||||
fromEmail = invoice.business?.email ?? "noreply@yourdomain.com";
|
||||
throw new Error(
|
||||
"Email delivery is not configured. Add a Resend API key globally or on this business.",
|
||||
);
|
||||
}
|
||||
|
||||
// Prepare CC and BCC lists
|
||||
|
||||
@@ -3,18 +3,9 @@ import { eq, and, desc } from "drizzle-orm";
|
||||
import { createTRPCRouter, protectedProcedure } from "../trpc";
|
||||
import { expenses, clients, businesses, invoices } from "~/server/db/schema";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { EXPENSE_CATEGORIES } from "~/lib/expense-categories";
|
||||
|
||||
export const EXPENSE_CATEGORIES = [
|
||||
"Travel",
|
||||
"Meals & Entertainment",
|
||||
"Software & Subscriptions",
|
||||
"Hardware & Equipment",
|
||||
"Office Supplies",
|
||||
"Marketing",
|
||||
"Professional Services",
|
||||
"Utilities",
|
||||
"Other",
|
||||
] as const;
|
||||
export { EXPENSE_CATEGORIES };
|
||||
|
||||
const createExpenseSchema = z.object({
|
||||
date: z.date(),
|
||||
@@ -24,6 +15,7 @@ const createExpenseSchema = z.object({
|
||||
category: z.string().optional().or(z.literal("")),
|
||||
billable: z.boolean().default(false),
|
||||
reimbursable: z.boolean().default(false),
|
||||
taxDeductible: z.boolean().default(false),
|
||||
notes: z.string().optional().or(z.literal("")),
|
||||
clientId: z.string().optional().or(z.literal("")),
|
||||
businessId: z.string().optional().or(z.literal("")),
|
||||
|
||||
@@ -18,6 +18,7 @@ const invoiceItemSchema = z.object({
|
||||
|
||||
const createInvoiceSchema = z.object({
|
||||
invoiceNumber: z.string().min(1, "Invoice number is required"),
|
||||
invoicePrefix: z.string().optional().default("#"),
|
||||
businessId: z
|
||||
.string()
|
||||
.min(1, "Business is required")
|
||||
@@ -416,11 +417,17 @@ export const invoicesRouter = createTRPCRouter({
|
||||
});
|
||||
|
||||
if (!invoice) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "Invoice not found" });
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "Invoice not found",
|
||||
});
|
||||
}
|
||||
|
||||
if (invoice.createdById !== ctx.session.user.id) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "You don't have permission to update this invoice" });
|
||||
throw new TRPCError({
|
||||
code: "FORBIDDEN",
|
||||
message: "You don't have permission to update this invoice",
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.db
|
||||
@@ -428,18 +435,27 @@ export const invoicesRouter = createTRPCRouter({
|
||||
.set({ status: input.status, updatedAt: new Date() })
|
||||
.where(eq(invoices.id, input.id));
|
||||
|
||||
return { success: true, message: `Invoice status updated to ${input.status}` };
|
||||
return {
|
||||
success: true,
|
||||
message: `Invoice status updated to ${input.status}`,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof TRPCError) throw error;
|
||||
throw new TRPCError({ code: "INTERNAL_SERVER_ERROR", message: "Failed to update invoice status", cause: error });
|
||||
throw new TRPCError({
|
||||
code: "INTERNAL_SERVER_ERROR",
|
||||
message: "Failed to update invoice status",
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}),
|
||||
|
||||
bulkUpdateStatus: protectedProcedure
|
||||
.input(z.object({
|
||||
ids: z.array(z.string()).min(1),
|
||||
status: z.enum(["draft", "sent", "paid"]),
|
||||
}))
|
||||
.input(
|
||||
z.object({
|
||||
ids: z.array(z.string()).min(1),
|
||||
status: z.enum(["draft", "sent", "paid"]),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
// Only update invoices owned by this user
|
||||
const owned = await ctx.db.query.invoices.findMany({
|
||||
@@ -452,7 +468,10 @@ export const invoicesRouter = createTRPCRouter({
|
||||
.map((inv) => inv.id);
|
||||
|
||||
if (ownedIds.length === 0) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "No matching invoices found" });
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "No matching invoices found",
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.db
|
||||
@@ -476,7 +495,10 @@ export const invoicesRouter = createTRPCRouter({
|
||||
.map((inv) => inv.id);
|
||||
|
||||
if (ownedIds.length === 0) {
|
||||
throw new TRPCError({ code: "NOT_FOUND", message: "No matching invoices found" });
|
||||
throw new TRPCError({
|
||||
code: "NOT_FOUND",
|
||||
message: "No matching invoices found",
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.db.delete(invoices).where(inArray(invoices.id, ownedIds));
|
||||
|
||||
@@ -1,14 +1,48 @@
|
||||
import { z } from "zod";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { createTRPCRouter, protectedProcedure, publicProcedure } from "~/server/api/trpc";
|
||||
import {
|
||||
createTRPCRouter,
|
||||
protectedProcedure,
|
||||
publicProcedure,
|
||||
} from "~/server/api/trpc";
|
||||
import {
|
||||
users,
|
||||
clients,
|
||||
businesses,
|
||||
invoices,
|
||||
invoiceItems,
|
||||
platformSettings,
|
||||
} from "~/server/db/schema";
|
||||
import {
|
||||
defaultBodyFontPreference,
|
||||
defaultFontPreference,
|
||||
defaultHeadingFontPreference,
|
||||
defaultInterfaceTheme,
|
||||
defaultRadiusPreference,
|
||||
defaultSidebarStyle,
|
||||
type ColorMode,
|
||||
type ColorTheme,
|
||||
type FontPreference,
|
||||
type InterfaceTheme,
|
||||
type RadiusPreference,
|
||||
type SidebarStyle,
|
||||
} from "~/lib/branding";
|
||||
|
||||
async function requireAdmin(ctx: {
|
||||
db: typeof import("~/server/db").db;
|
||||
session: { user: { id: string } };
|
||||
}) {
|
||||
const user = await ctx.db.query.users.findFirst({
|
||||
where: eq(users.id, ctx.session.user.id),
|
||||
columns: { role: true },
|
||||
});
|
||||
|
||||
if (user?.role !== "admin") {
|
||||
throw new TRPCError({ code: "FORBIDDEN" });
|
||||
}
|
||||
}
|
||||
|
||||
// Validation schemas for backup data
|
||||
const ClientBackupSchema = z.object({
|
||||
@@ -76,6 +110,37 @@ const BackupDataSchema = z.object({
|
||||
});
|
||||
|
||||
export const settingsRouter = createTRPCRouter({
|
||||
listAccounts: protectedProcedure.query(async ({ ctx }) => {
|
||||
await requireAdmin(ctx);
|
||||
return ctx.db.query.users.findMany({
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
email: true,
|
||||
role: true,
|
||||
emailVerified: true,
|
||||
createdAt: true,
|
||||
},
|
||||
orderBy: (users, { asc }) => [asc(users.createdAt)],
|
||||
});
|
||||
}),
|
||||
|
||||
updateAccountRole: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
userId: z.string().min(1),
|
||||
role: z.enum(["user", "admin"]),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await requireAdmin(ctx);
|
||||
await ctx.db
|
||||
.update(users)
|
||||
.set({ role: input.role })
|
||||
.where(eq(users.id, input.userId));
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
// Get user profile information
|
||||
getProfile: protectedProcedure.query(async ({ ctx }) => {
|
||||
const user = await ctx.db.query.users.findFirst({
|
||||
@@ -85,6 +150,7 @@ export const settingsRouter = createTRPCRouter({
|
||||
name: true,
|
||||
email: true,
|
||||
image: true,
|
||||
role: true,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -144,20 +210,41 @@ export const settingsRouter = createTRPCRouter({
|
||||
}),
|
||||
|
||||
// Get theme preferences
|
||||
getTheme: protectedProcedure.query(async ({ ctx }) => {
|
||||
const user = await ctx.db.query.users.findFirst({
|
||||
where: eq(users.id, ctx.session.user.id),
|
||||
columns: {
|
||||
colorTheme: true,
|
||||
customColor: true,
|
||||
theme: true,
|
||||
},
|
||||
getTheme: publicProcedure.query(async ({ ctx }) => {
|
||||
const settings = await ctx.db.query.platformSettings.findFirst({
|
||||
where: eq(platformSettings.id, "global"),
|
||||
});
|
||||
|
||||
return {
|
||||
colorTheme: (user?.colorTheme as "slate" | "blue" | "green" | "rose" | "orange" | "custom") ?? "slate",
|
||||
customColor: user?.customColor ?? undefined,
|
||||
theme: (user?.theme as "light" | "dark" | "system") ?? "system",
|
||||
colorTheme: (settings?.colorTheme as ColorTheme) ?? "slate",
|
||||
customColor: settings?.customColor ?? undefined,
|
||||
theme: (settings?.theme as ColorMode) ?? "system",
|
||||
interfaceTheme:
|
||||
(settings?.interfaceTheme as InterfaceTheme) ?? defaultInterfaceTheme,
|
||||
fontPreference: defaultFontPreference,
|
||||
bodyFontPreference:
|
||||
(settings?.bodyFontPreference as FontPreference) ??
|
||||
defaultBodyFontPreference,
|
||||
headingFontPreference:
|
||||
(settings?.headingFontPreference as FontPreference) ??
|
||||
defaultHeadingFontPreference,
|
||||
radiusPreference:
|
||||
(settings?.radiusPreference as RadiusPreference) ??
|
||||
defaultRadiusPreference,
|
||||
sidebarStyle:
|
||||
(settings?.sidebarStyle as SidebarStyle) ?? defaultSidebarStyle,
|
||||
brandName: settings?.brandName ?? "beenvoice",
|
||||
brandTagline:
|
||||
settings?.brandTagline ??
|
||||
"Simple and efficient invoicing for freelancers and small businesses",
|
||||
brandLogoText: settings?.brandLogoText ?? "beenvoice",
|
||||
brandIcon: settings?.brandIcon ?? "$",
|
||||
pdfTemplate:
|
||||
(settings?.pdfTemplate as "classic" | "minimal") ?? "classic",
|
||||
pdfAccentColor: settings?.pdfAccentColor ?? "#111827",
|
||||
pdfFooterText: settings?.pdfFooterText ?? "Professional Invoicing",
|
||||
pdfShowLogo: settings?.pdfShowLogo ?? true,
|
||||
pdfShowPageNumbers: settings?.pdfShowPageNumbers ?? true,
|
||||
};
|
||||
}),
|
||||
|
||||
@@ -165,20 +252,105 @@ export const settingsRouter = createTRPCRouter({
|
||||
updateTheme: protectedProcedure
|
||||
.input(
|
||||
z.object({
|
||||
colorTheme: z.enum(["slate", "blue", "green", "rose", "orange", "custom"]).optional(),
|
||||
colorTheme: z
|
||||
.enum(["slate", "blue", "green", "rose", "orange", "custom"])
|
||||
.optional(),
|
||||
customColor: z.string().optional(),
|
||||
theme: z.enum(["light", "dark", "system"]).optional(),
|
||||
interfaceTheme: z
|
||||
.enum(["beenvoice", "shadcn", "minimal", "editorial"])
|
||||
.optional(),
|
||||
fontPreference: z
|
||||
.enum(["brand", "platform", "inter", "serif"])
|
||||
.optional(),
|
||||
bodyFontPreference: z
|
||||
.enum(["brand", "platform", "inter", "serif"])
|
||||
.optional(),
|
||||
headingFontPreference: z
|
||||
.enum(["brand", "platform", "inter", "serif"])
|
||||
.optional(),
|
||||
radiusPreference: z.enum(["none", "sm", "md", "lg", "xl"]).optional(),
|
||||
sidebarStyle: z.enum(["floating", "docked"]).optional(),
|
||||
brandName: z.string().min(1).max(100).optional(),
|
||||
brandTagline: z.string().min(1).max(255).optional(),
|
||||
brandLogoText: z.string().min(1).max(100).optional(),
|
||||
brandIcon: z.string().min(1).max(20).optional(),
|
||||
pdfTemplate: z.enum(["classic", "minimal"]).optional(),
|
||||
pdfAccentColor: z.string().min(4).max(50).optional(),
|
||||
pdfFooterText: z.string().min(1).max(120).optional(),
|
||||
pdfShowLogo: z.boolean().optional(),
|
||||
pdfShowPageNumbers: z.boolean().optional(),
|
||||
}),
|
||||
)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await requireAdmin(ctx);
|
||||
await ctx.db
|
||||
.update(users)
|
||||
.set({
|
||||
...(input.colorTheme && { colorTheme: input.colorTheme }),
|
||||
...(input.customColor !== undefined && { customColor: input.customColor }),
|
||||
...(input.theme && { theme: input.theme }),
|
||||
.insert(platformSettings)
|
||||
.values({
|
||||
id: "global",
|
||||
brandName: input.brandName ?? "beenvoice",
|
||||
brandTagline:
|
||||
input.brandTagline ??
|
||||
"Simple and efficient invoicing for freelancers and small businesses",
|
||||
brandLogoText: input.brandLogoText ?? "beenvoice",
|
||||
brandIcon: input.brandIcon ?? "$",
|
||||
colorTheme: input.colorTheme ?? "slate",
|
||||
customColor: input.customColor,
|
||||
theme: input.theme ?? "system",
|
||||
interfaceTheme: input.interfaceTheme ?? defaultInterfaceTheme,
|
||||
bodyFontPreference:
|
||||
input.bodyFontPreference ?? defaultBodyFontPreference,
|
||||
headingFontPreference:
|
||||
input.headingFontPreference ?? defaultHeadingFontPreference,
|
||||
radiusPreference: input.radiusPreference ?? defaultRadiusPreference,
|
||||
sidebarStyle: input.sidebarStyle ?? defaultSidebarStyle,
|
||||
pdfTemplate: input.pdfTemplate ?? "classic",
|
||||
pdfAccentColor: input.pdfAccentColor ?? "#111827",
|
||||
pdfFooterText: input.pdfFooterText ?? "Professional Invoicing",
|
||||
pdfShowLogo: input.pdfShowLogo ?? true,
|
||||
pdfShowPageNumbers: input.pdfShowPageNumbers ?? true,
|
||||
})
|
||||
.where(eq(users.id, ctx.session.user.id));
|
||||
.onConflictDoUpdate({
|
||||
target: platformSettings.id,
|
||||
set: {
|
||||
...(input.brandName && { brandName: input.brandName }),
|
||||
...(input.brandTagline && { brandTagline: input.brandTagline }),
|
||||
...(input.brandLogoText && {
|
||||
brandLogoText: input.brandLogoText,
|
||||
}),
|
||||
...(input.brandIcon && { brandIcon: input.brandIcon }),
|
||||
...(input.colorTheme && { colorTheme: input.colorTheme }),
|
||||
...(input.customColor !== undefined && {
|
||||
customColor: input.customColor,
|
||||
}),
|
||||
...(input.theme && { theme: input.theme }),
|
||||
...(input.interfaceTheme && {
|
||||
interfaceTheme: input.interfaceTheme,
|
||||
}),
|
||||
...(input.bodyFontPreference && {
|
||||
bodyFontPreference: input.bodyFontPreference,
|
||||
}),
|
||||
...(input.headingFontPreference && {
|
||||
headingFontPreference: input.headingFontPreference,
|
||||
}),
|
||||
...(input.radiusPreference && {
|
||||
radiusPreference: input.radiusPreference,
|
||||
}),
|
||||
...(input.sidebarStyle && { sidebarStyle: input.sidebarStyle }),
|
||||
...(input.pdfTemplate && { pdfTemplate: input.pdfTemplate }),
|
||||
...(input.pdfAccentColor && {
|
||||
pdfAccentColor: input.pdfAccentColor,
|
||||
}),
|
||||
...(input.pdfFooterText && { pdfFooterText: input.pdfFooterText }),
|
||||
...(input.pdfShowLogo !== undefined && {
|
||||
pdfShowLogo: input.pdfShowLogo,
|
||||
}),
|
||||
...(input.pdfShowPageNumbers !== undefined && {
|
||||
pdfShowPageNumbers: input.pdfShowPageNumbers,
|
||||
}),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
}),
|
||||
|
||||
+226
-4
@@ -6,6 +6,10 @@
|
||||
* This applies any pending migrations from the drizzle/ directory to the
|
||||
* database specified by DATABASE_URL. It is safe to run multiple times —
|
||||
* Drizzle tracks applied migrations in the __drizzle_migrations table.
|
||||
*
|
||||
* If the database was previously set up via `db:push` (no migration history),
|
||||
* this script will baseline it: seed the migration history without re-running
|
||||
* the SQL, so only future migrations are applied.
|
||||
*/
|
||||
import * as dotenv from "dotenv";
|
||||
|
||||
@@ -17,7 +21,8 @@ import { Pool } from "pg";
|
||||
import { drizzle } from "drizzle-orm/node-postgres";
|
||||
import { migrate } from "drizzle-orm/node-postgres/migrator";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import fs from "fs";
|
||||
import crypto from "crypto";
|
||||
|
||||
const databaseUrl = process.env.DATABASE_URL;
|
||||
if (!databaseUrl) {
|
||||
@@ -25,20 +30,237 @@ if (!databaseUrl) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const migrationsFolder = path.resolve(__dirname, "../../../drizzle");
|
||||
const migrationsFolder = path.resolve(process.cwd(), "drizzle");
|
||||
|
||||
const pool = new Pool({
|
||||
connectionString: databaseUrl,
|
||||
ssl: process.env.DB_DISABLE_SSL === "true" ? false : { rejectUnauthorized: false },
|
||||
ssl:
|
||||
process.env.DB_DISABLE_SSL === "true"
|
||||
? false
|
||||
: { rejectUnauthorized: false },
|
||||
max: 1,
|
||||
});
|
||||
|
||||
const db = drizzle(pool);
|
||||
|
||||
/**
|
||||
* Verify and repair the migration tracking table:
|
||||
* 1. If no tracking table exists and DB has tables → baseline from db:push
|
||||
* 2. If tracking table exists → scan for any entries that are recorded as
|
||||
* applied but whose schema changes don't actually exist, and remove them
|
||||
* so migrate() will re-run those migrations.
|
||||
*/
|
||||
async function baselineIfNeeded(client: Pool) {
|
||||
const hasMigrationsTable = await tableExists(
|
||||
client,
|
||||
"drizzle",
|
||||
"__drizzle_migrations",
|
||||
);
|
||||
|
||||
// Always ensure the drizzle schema + table exist
|
||||
await client.query(`CREATE SCHEMA IF NOT EXISTS drizzle`);
|
||||
await client.query(`
|
||||
CREATE TABLE IF NOT EXISTS drizzle.__drizzle_migrations (
|
||||
id SERIAL PRIMARY KEY,
|
||||
hash text NOT NULL,
|
||||
created_at bigint
|
||||
)
|
||||
`);
|
||||
|
||||
const { rows: entryRows } = await client.query<{ count: string }>(
|
||||
`SELECT COUNT(*)::text AS count FROM drizzle.__drizzle_migrations`,
|
||||
);
|
||||
const hasEntries = parseInt(entryRows[0]?.count ?? "0") > 0;
|
||||
|
||||
if (!hasMigrationsTable || !hasEntries) {
|
||||
// No history at all — check if DB was previously set up via db:push
|
||||
const dbAlreadyExists = await tableExists(
|
||||
client,
|
||||
"public",
|
||||
"beenvoice_account",
|
||||
);
|
||||
if (!dbAlreadyExists) {
|
||||
return; // Fresh DB — let migrate() run everything normally
|
||||
}
|
||||
|
||||
console.log(
|
||||
"[migrate] Existing database detected without migration history — baselining...",
|
||||
);
|
||||
await seedMigrationHistory(client);
|
||||
return;
|
||||
}
|
||||
|
||||
// Migration history exists — validate that each recorded migration is
|
||||
// actually reflected in the schema. Remove any bogus entries.
|
||||
await removeBogusEntries(client);
|
||||
}
|
||||
|
||||
async function seedMigrationHistory(client: Pool) {
|
||||
const journal = JSON.parse(
|
||||
fs.readFileSync(path.join(migrationsFolder, "meta/_journal.json"), "utf8"),
|
||||
) as { entries: { idx: number; tag: string; when: number }[] };
|
||||
|
||||
for (const entry of journal.entries) {
|
||||
const applied = await isMigrationApplied(client, entry.tag);
|
||||
if (!applied) {
|
||||
console.log(`[migrate] Not yet in schema, will run: ${entry.tag}`);
|
||||
continue;
|
||||
}
|
||||
const sql = fs.readFileSync(
|
||||
path.join(migrationsFolder, `${entry.tag}.sql`),
|
||||
"utf8",
|
||||
);
|
||||
const hash = crypto.createHash("sha256").update(sql).digest("hex");
|
||||
await client.query(
|
||||
`INSERT INTO drizzle.__drizzle_migrations (hash, created_at) VALUES ($1, $2)`,
|
||||
[hash, entry.when],
|
||||
);
|
||||
console.log(`[migrate] Baselined: ${entry.tag}`);
|
||||
}
|
||||
console.log("[migrate] Baseline complete");
|
||||
}
|
||||
|
||||
async function removeBogusEntries(client: Pool) {
|
||||
// Get all recorded hashes
|
||||
const { rows } = await client.query<{ id: number; hash: string }>(
|
||||
`SELECT id, hash FROM drizzle.__drizzle_migrations ORDER BY id`,
|
||||
);
|
||||
|
||||
const journal = JSON.parse(
|
||||
fs.readFileSync(path.join(migrationsFolder, "meta/_journal.json"), "utf8"),
|
||||
) as { entries: { idx: number; tag: string; when: number }[] };
|
||||
|
||||
for (const entry of journal.entries) {
|
||||
const sql = fs.readFileSync(
|
||||
path.join(migrationsFolder, `${entry.tag}.sql`),
|
||||
"utf8",
|
||||
);
|
||||
const expectedHash = crypto.createHash("sha256").update(sql).digest("hex");
|
||||
const recorded = rows.find((r) => r.hash === expectedHash);
|
||||
if (!recorded) continue; // Not recorded yet — migrate() will run it
|
||||
|
||||
// It's recorded — verify it's actually applied in the schema
|
||||
const applied = await isMigrationApplied(client, entry.tag);
|
||||
if (!applied) {
|
||||
console.log(
|
||||
`[migrate] Removing bogus migration record for: ${entry.tag}`,
|
||||
);
|
||||
await client.query(
|
||||
`DELETE FROM drizzle.__drizzle_migrations WHERE id = $1`,
|
||||
[recorded.id],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function tableExists(
|
||||
client: Pool,
|
||||
schema: string,
|
||||
table: string,
|
||||
): Promise<boolean> {
|
||||
const { rows } = await client.query<{ count: string }>(
|
||||
`
|
||||
SELECT COUNT(*)::text AS count FROM information_schema.tables
|
||||
WHERE table_schema = $1 AND table_name = $2
|
||||
`,
|
||||
[schema, table],
|
||||
);
|
||||
return parseInt(rows[0]?.count ?? "0") > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a specific migration's schema changes already exist in the DB.
|
||||
*/
|
||||
async function isMigrationApplied(client: Pool, tag: string): Promise<boolean> {
|
||||
if (tag === "0000_glossy_magneto") {
|
||||
return tableExists(client, "public", "beenvoice_account");
|
||||
}
|
||||
if (tag === "0001_supreme_the_enforcers") {
|
||||
// 0001 adds currency to beenvoice_client
|
||||
const { rows } = await client.query<{ count: string }>(`
|
||||
SELECT COUNT(*)::text AS count FROM information_schema.columns
|
||||
WHERE table_schema = 'public'
|
||||
AND table_name = 'beenvoice_client'
|
||||
AND column_name = 'currency'
|
||||
`);
|
||||
return parseInt(rows[0]?.count ?? "0") > 0;
|
||||
}
|
||||
if (tag === "0002_tax_deductible") {
|
||||
// 0002 adds taxDeductible to beenvoice_expense
|
||||
const { rows } = await client.query<{ count: string }>(`
|
||||
SELECT COUNT(*)::text AS count FROM information_schema.columns
|
||||
WHERE table_schema = 'public'
|
||||
AND table_name = 'beenvoice_expense'
|
||||
AND column_name = 'taxDeductible'
|
||||
`);
|
||||
return parseInt(rows[0]?.count ?? "0") > 0;
|
||||
}
|
||||
if (tag === "0003_appearance_preferences") {
|
||||
// 0003 adds appearance preferences to beenvoice_user
|
||||
const { rows } = await client.query<{ count: string }>(`
|
||||
SELECT COUNT(*)::text AS count FROM information_schema.columns
|
||||
WHERE table_schema = 'public'
|
||||
AND table_name = 'beenvoice_user'
|
||||
AND column_name = 'interfaceTheme'
|
||||
`);
|
||||
return parseInt(rows[0]?.count ?? "0") > 0;
|
||||
}
|
||||
if (tag === "0004_platform_appearance_controls") {
|
||||
// 0004 adds platform-level appearance controls to beenvoice_user
|
||||
const { rows } = await client.query<{ count: string }>(`
|
||||
SELECT COUNT(*)::text AS count FROM information_schema.columns
|
||||
WHERE table_schema = 'public'
|
||||
AND table_name = 'beenvoice_user'
|
||||
AND column_name = 'sidebarStyle'
|
||||
`);
|
||||
return parseInt(rows[0]?.count ?? "0") > 0;
|
||||
}
|
||||
if (tag === "0005_platform_settings_and_roles") {
|
||||
const hasRole = await columnExists(
|
||||
client,
|
||||
"public",
|
||||
"beenvoice_user",
|
||||
"role",
|
||||
);
|
||||
const hasPlatformSettings = await tableExists(
|
||||
client,
|
||||
"public",
|
||||
"beenvoice_platform_setting",
|
||||
);
|
||||
return hasRole && hasPlatformSettings;
|
||||
}
|
||||
if (tag === "0006_pdf_generation_settings") {
|
||||
return columnExists(
|
||||
client,
|
||||
"public",
|
||||
"beenvoice_platform_setting",
|
||||
"pdfTemplate",
|
||||
);
|
||||
}
|
||||
// Unknown migration — assume not applied so it runs
|
||||
return false;
|
||||
}
|
||||
|
||||
async function columnExists(
|
||||
client: Pool,
|
||||
schema: string,
|
||||
table: string,
|
||||
column: string,
|
||||
): Promise<boolean> {
|
||||
const { rows } = await client.query<{ count: string }>(
|
||||
`
|
||||
SELECT COUNT(*)::text AS count FROM information_schema.columns
|
||||
WHERE table_schema = $1 AND table_name = $2 AND column_name = $3
|
||||
`,
|
||||
[schema, table, column],
|
||||
);
|
||||
return parseInt(rows[0]?.count ?? "0") > 0;
|
||||
}
|
||||
|
||||
console.log("[migrate] Running migrations from", migrationsFolder);
|
||||
|
||||
try {
|
||||
await baselineIfNeeded(pool);
|
||||
await migrate(db, { migrationsFolder });
|
||||
console.log("[migrate] All migrations applied successfully");
|
||||
} catch (err) {
|
||||
|
||||
+94
-15
@@ -1,7 +1,6 @@
|
||||
import { relations, sql } from "drizzle-orm";
|
||||
import { index, pgTableCreator } from "drizzle-orm/pg-core";
|
||||
|
||||
|
||||
/**
|
||||
* This is an example of how to use the multi-project schema feature of Drizzle ORM. Use the same
|
||||
* database instance for multiple projects.
|
||||
@@ -22,7 +21,11 @@ export const users = createTable("user", (d) => ({
|
||||
emailVerified: d.boolean().default(false).notNull(),
|
||||
image: d.varchar({ length: 255 }),
|
||||
createdAt: d.timestamp().notNull().defaultNow(),
|
||||
updatedAt: d.timestamp().notNull().defaultNow().$onUpdate(() => new Date()),
|
||||
updatedAt: d
|
||||
.timestamp()
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
password: d.varchar({ length: 255 }), // Matched DB: varchar(255)
|
||||
resetToken: d.varchar({ length: 255 }), // Matched DB: varchar(255)
|
||||
resetTokenExpiry: d.timestamp(),
|
||||
@@ -32,6 +35,48 @@ export const users = createTable("user", (d) => ({
|
||||
colorTheme: d.varchar({ length: 50 }).default("slate").notNull(),
|
||||
customColor: d.varchar({ length: 50 }),
|
||||
theme: d.varchar({ length: 20 }).default("system").notNull(),
|
||||
interfaceTheme: d.varchar({ length: 50 }).default("beenvoice").notNull(),
|
||||
fontPreference: d.varchar({ length: 50 }).default("brand").notNull(),
|
||||
bodyFontPreference: d.varchar({ length: 50 }).default("brand").notNull(),
|
||||
headingFontPreference: d.varchar({ length: 50 }).default("brand").notNull(),
|
||||
radiusPreference: d.varchar({ length: 20 }).default("xl").notNull(),
|
||||
sidebarStyle: d.varchar({ length: 20 }).default("floating").notNull(),
|
||||
role: d.varchar({ length: 20 }).default("user").notNull(),
|
||||
}));
|
||||
|
||||
export const platformSettings = createTable("platform_setting", (d) => ({
|
||||
id: d.varchar({ length: 50 }).notNull().primaryKey().default("global"),
|
||||
brandName: d.varchar({ length: 100 }).default("beenvoice").notNull(),
|
||||
brandTagline: d
|
||||
.varchar({ length: 255 })
|
||||
.default(
|
||||
"Simple and efficient invoicing for freelancers and small businesses",
|
||||
)
|
||||
.notNull(),
|
||||
brandLogoText: d.varchar({ length: 100 }).default("beenvoice").notNull(),
|
||||
brandIcon: d.varchar({ length: 20 }).default("$").notNull(),
|
||||
colorTheme: d.varchar({ length: 50 }).default("slate").notNull(),
|
||||
customColor: d.varchar({ length: 50 }),
|
||||
theme: d.varchar({ length: 20 }).default("system").notNull(),
|
||||
interfaceTheme: d.varchar({ length: 50 }).default("beenvoice").notNull(),
|
||||
bodyFontPreference: d.varchar({ length: 50 }).default("brand").notNull(),
|
||||
headingFontPreference: d.varchar({ length: 50 }).default("brand").notNull(),
|
||||
radiusPreference: d.varchar({ length: 20 }).default("xl").notNull(),
|
||||
sidebarStyle: d.varchar({ length: 20 }).default("floating").notNull(),
|
||||
pdfTemplate: d.varchar({ length: 20 }).default("classic").notNull(),
|
||||
pdfAccentColor: d.varchar({ length: 50 }).default("#111827").notNull(),
|
||||
pdfFooterText: d
|
||||
.varchar({ length: 120 })
|
||||
.default("Professional Invoicing")
|
||||
.notNull(),
|
||||
pdfShowLogo: d.boolean().default(true).notNull(),
|
||||
pdfShowPageNumbers: d.boolean().default(true).notNull(),
|
||||
createdAt: d.timestamp().notNull().defaultNow(),
|
||||
updatedAt: d
|
||||
.timestamp()
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
}));
|
||||
|
||||
export const usersRelations = relations(users, ({ many }) => ({
|
||||
@@ -47,7 +92,11 @@ export const usersRelations = relations(users, ({ many }) => ({
|
||||
export const accounts = createTable(
|
||||
"account",
|
||||
(d) => ({
|
||||
id: d.text().notNull().primaryKey().$defaultFn(() => crypto.randomUUID()), // Matched DB: text
|
||||
id: d
|
||||
.text()
|
||||
.notNull()
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()), // Matched DB: text
|
||||
userId: d
|
||||
.varchar({ length: 255 })
|
||||
.notNull()
|
||||
@@ -62,11 +111,13 @@ export const accounts = createTable(
|
||||
idToken: d.text(),
|
||||
password: d.text(), // Matched DB: text
|
||||
createdAt: d.timestamp().notNull().defaultNow(),
|
||||
updatedAt: d.timestamp().notNull().defaultNow().$onUpdate(() => new Date()),
|
||||
updatedAt: d
|
||||
.timestamp()
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
}),
|
||||
(t) => [
|
||||
index("account_userId_idx").on(t.userId),
|
||||
],
|
||||
(t) => [index("account_userId_idx").on(t.userId)],
|
||||
);
|
||||
|
||||
export const accountsRelations = relations(accounts, ({ one }) => ({
|
||||
@@ -76,7 +127,11 @@ export const accountsRelations = relations(accounts, ({ one }) => ({
|
||||
export const sessions = createTable(
|
||||
"session",
|
||||
(d) => ({
|
||||
id: d.text().notNull().primaryKey().$defaultFn(() => crypto.randomUUID()), // Matched DB: text
|
||||
id: d
|
||||
.text()
|
||||
.notNull()
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()), // Matched DB: text
|
||||
userId: d
|
||||
.varchar({ length: 255 })
|
||||
.notNull()
|
||||
@@ -86,7 +141,11 @@ export const sessions = createTable(
|
||||
ipAddress: d.text(), // Matched DB: text
|
||||
userAgent: d.text(), // Matched DB: text
|
||||
createdAt: d.timestamp().notNull().defaultNow(),
|
||||
updatedAt: d.timestamp().notNull().defaultNow().$onUpdate(() => new Date()),
|
||||
updatedAt: d
|
||||
.timestamp()
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
}),
|
||||
(t) => [index("session_userId_idx").on(t.userId)],
|
||||
);
|
||||
@@ -98,12 +157,20 @@ export const sessionsRelations = relations(sessions, ({ one }) => ({
|
||||
export const verificationTokens = createTable(
|
||||
"verification_token",
|
||||
(d) => ({
|
||||
id: d.text().notNull().primaryKey().$defaultFn(() => crypto.randomUUID()), // Matched DB: text
|
||||
id: d
|
||||
.text()
|
||||
.notNull()
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()), // Matched DB: text
|
||||
identifier: d.varchar({ length: 255 }).notNull(),
|
||||
value: d.varchar({ length: 255 }).notNull(),
|
||||
expiresAt: d.timestamp().notNull(),
|
||||
createdAt: d.timestamp().notNull().defaultNow(),
|
||||
updatedAt: d.timestamp().notNull().defaultNow().$onUpdate(() => new Date()),
|
||||
updatedAt: d
|
||||
.timestamp()
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
}),
|
||||
(t) => [index("verification_token_identifier_idx").on(t.identifier)],
|
||||
);
|
||||
@@ -111,14 +178,25 @@ export const verificationTokens = createTable(
|
||||
export const ssoProviders = createTable(
|
||||
"sso_provider",
|
||||
(d) => ({
|
||||
id: d.varchar({ length: 255 }).notNull().primaryKey().$defaultFn(() => crypto.randomUUID()),
|
||||
id: d
|
||||
.varchar({ length: 255 })
|
||||
.notNull()
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()),
|
||||
providerId: d.varchar({ length: 255 }).notNull().unique(),
|
||||
userId: d.varchar({ length: 255 }).notNull().references(() => users.id),
|
||||
userId: d
|
||||
.varchar({ length: 255 })
|
||||
.notNull()
|
||||
.references(() => users.id),
|
||||
redirectURI: d.varchar({ length: 255 }).notNull().default(""), // Added detailed fields
|
||||
oidcConfig: d.text(),
|
||||
samlConfig: d.text(),
|
||||
createdAt: d.timestamp().notNull().defaultNow(),
|
||||
updatedAt: d.timestamp().notNull().defaultNow().$onUpdate(() => new Date()),
|
||||
updatedAt: d
|
||||
.timestamp()
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdate(() => new Date()),
|
||||
}),
|
||||
(t) => [index("sso_provider_user_id_idx").on(t.userId)],
|
||||
);
|
||||
@@ -230,6 +308,7 @@ export const invoices = createTable(
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()),
|
||||
invoiceNumber: d.varchar({ length: 100 }).notNull(),
|
||||
invoicePrefix: d.varchar({ length: 20 }).default("#"),
|
||||
businessId: d.varchar({ length: 255 }).references(() => businesses.id),
|
||||
clientId: d
|
||||
.varchar({ length: 255 })
|
||||
@@ -334,6 +413,7 @@ export const expenses = createTable(
|
||||
category: d.varchar({ length: 100 }),
|
||||
billable: d.boolean().default(false).notNull(),
|
||||
reimbursable: d.boolean().default(false).notNull(),
|
||||
taxDeductible: d.boolean().default(false).notNull(),
|
||||
notes: d.varchar({ length: 500 }),
|
||||
createdById: d
|
||||
.varchar({ length: 255 })
|
||||
@@ -410,4 +490,3 @@ export const invoiceTemplatesRelations = relations(
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
+311
-5
@@ -34,8 +34,155 @@
|
||||
/* 16px Global Radius */
|
||||
}
|
||||
|
||||
:root[data-interface-theme="shadcn"] {
|
||||
--primary: 240 5.9% 10%;
|
||||
--primary-foreground: 0 0% 98%;
|
||||
--secondary: 240 4.8% 95.9%;
|
||||
--secondary-foreground: 240 5.9% 10%;
|
||||
--accent: 240 4.8% 95.9%;
|
||||
--accent-foreground: 240 5.9% 10%;
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="beenvoice"] {
|
||||
--secondary: 240 4.8% 90%;
|
||||
--secondary-foreground: 240 5.9% 10%;
|
||||
--radius: 1rem;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="minimal"] {
|
||||
--background: 0 0% 100%;
|
||||
--card: 0 0% 100%;
|
||||
--popover: 0 0% 100%;
|
||||
--primary: 240 5.9% 10%;
|
||||
--primary-foreground: 0 0% 98%;
|
||||
--secondary: 240 4.8% 96.5%;
|
||||
--secondary-foreground: 240 5.9% 10%;
|
||||
--muted: 240 4.8% 97%;
|
||||
--accent: 240 4.8% 96%;
|
||||
--accent-foreground: 240 5.9% 10%;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="editorial"] {
|
||||
--background: 36 33% 98%;
|
||||
--card: 36 33% 99%;
|
||||
--popover: 36 33% 99%;
|
||||
--primary: 346.8 77.2% 49.8%;
|
||||
--primary-foreground: 355.7 100% 97.3%;
|
||||
--secondary: 30 18% 91%;
|
||||
--secondary-foreground: 24 10% 10%;
|
||||
--muted: 30 20% 94%;
|
||||
--accent: 346.8 77.2% 49.8%;
|
||||
--accent-foreground: 355.7 100% 97.3%;
|
||||
--border: 30 15% 86%;
|
||||
--input: 30 15% 86%;
|
||||
}
|
||||
|
||||
:root[data-body-font="brand"],
|
||||
:root[data-body-font="inter"] {
|
||||
--app-font-sans: var(--font-inter), ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
:root[data-body-font="platform"] {
|
||||
--app-font-sans:
|
||||
ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
:root[data-body-font="serif"] {
|
||||
--app-font-sans:
|
||||
ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;
|
||||
}
|
||||
|
||||
:root[data-heading-font="brand"],
|
||||
:root[data-heading-font="serif"] {
|
||||
--app-font-heading: var(--font-playfair), ui-serif, Georgia, serif;
|
||||
}
|
||||
|
||||
:root[data-heading-font="platform"] {
|
||||
--app-font-heading:
|
||||
ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
:root[data-heading-font="inter"] {
|
||||
--app-font-heading: var(--font-inter), ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
:root[data-font="brand"]:not([data-body-font]) {
|
||||
--app-font-sans: var(--font-inter), ui-sans-serif, system-ui, sans-serif;
|
||||
--app-font-heading: var(--font-playfair), ui-serif, Georgia, serif;
|
||||
}
|
||||
|
||||
:root[data-font="platform"]:not([data-body-font]) {
|
||||
--app-font-sans:
|
||||
ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
|
||||
sans-serif;
|
||||
--app-font-heading:
|
||||
ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI",
|
||||
sans-serif;
|
||||
}
|
||||
|
||||
:root[data-font="inter"]:not([data-body-font]) {
|
||||
--app-font-sans: var(--font-inter), ui-sans-serif, system-ui, sans-serif;
|
||||
--app-font-heading: var(--font-inter), ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
:root[data-font="serif"]:not([data-body-font]) {
|
||||
--app-font-sans:
|
||||
ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;
|
||||
--app-font-heading: var(--font-playfair), ui-serif, Georgia, serif;
|
||||
}
|
||||
|
||||
:root[data-radius="none"] {
|
||||
--radius: 0rem;
|
||||
}
|
||||
|
||||
:root[data-radius="sm"] {
|
||||
--radius: 0.25rem;
|
||||
}
|
||||
|
||||
:root[data-radius="md"] {
|
||||
--radius: 0.5rem;
|
||||
}
|
||||
|
||||
:root[data-radius="lg"] {
|
||||
--radius: 0.75rem;
|
||||
}
|
||||
|
||||
:root[data-radius="xl"] {
|
||||
--radius: 1rem;
|
||||
}
|
||||
|
||||
:root[data-color-mode="dark"],
|
||||
:root.dark {
|
||||
--background: 240 10% 3.9%;
|
||||
/* #09090B */
|
||||
--foreground: 0 0% 98%;
|
||||
/* #FAFAFA */
|
||||
--card: 240 10% 3.9%;
|
||||
--card-foreground: 0 0% 98%;
|
||||
--popover: 240 10% 3.9%;
|
||||
--popover-foreground: 0 0% 98%;
|
||||
--primary: 0 0% 98%;
|
||||
--primary-foreground: 240 5.9% 10%;
|
||||
--secondary: 240 3.7% 20%;
|
||||
/* #27272A */
|
||||
--secondary-foreground: 0 0% 98%;
|
||||
--muted: 240 3.7% 15.9%;
|
||||
--muted-foreground: 240 5% 64.9%;
|
||||
--accent: 240 3.7% 15.9%;
|
||||
--accent-foreground: 0 0% 98%;
|
||||
--destructive: 0 62.8% 30.6%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 240 3.7% 15.9%;
|
||||
/* #27272A */
|
||||
--input: 240 3.7% 15.9%;
|
||||
--ring: 240 4.9% 83.9%;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
:root:not([data-color-mode="light"]) {
|
||||
--background: 240 10% 3.9%;
|
||||
/* #09090B */
|
||||
--foreground: 0 0% 98%;
|
||||
@@ -61,6 +208,65 @@
|
||||
--ring: 240 4.9% 83.9%;
|
||||
}
|
||||
}
|
||||
|
||||
:root[data-color-theme="slate"] {
|
||||
--primary: 240 5.9% 10%;
|
||||
--primary-foreground: 0 0% 98%;
|
||||
--accent: 240 4.8% 95.9%;
|
||||
--accent-foreground: 240 5.9% 10%;
|
||||
}
|
||||
|
||||
:root[data-color-theme="blue"] {
|
||||
--primary: 221.2 83.2% 53.3%;
|
||||
--primary-foreground: 210 40% 98%;
|
||||
--accent: 217.2 91.2% 59.8%;
|
||||
--accent-foreground: 210 40% 98%;
|
||||
}
|
||||
|
||||
:root[data-color-theme="green"] {
|
||||
--primary: 142.1 76.2% 36.3%;
|
||||
--primary-foreground: 355.7 100% 97.3%;
|
||||
--accent: 142.1 70.6% 45.3%;
|
||||
--accent-foreground: 355.7 100% 97.3%;
|
||||
}
|
||||
|
||||
:root[data-color-theme="rose"] {
|
||||
--primary: 346.8 77.2% 49.8%;
|
||||
--primary-foreground: 355.7 100% 97.3%;
|
||||
--accent: 346.8 77.2% 49.8%;
|
||||
--accent-foreground: 355.7 100% 97.3%;
|
||||
}
|
||||
|
||||
:root[data-color-theme="orange"] {
|
||||
--primary: 24.6 95% 53.1%;
|
||||
--primary-foreground: 60 9.1% 97.8%;
|
||||
--accent: 20.5 90.2% 48.2%;
|
||||
--accent-foreground: 60 9.1% 97.8%;
|
||||
}
|
||||
|
||||
:root[data-color-theme="custom"] {
|
||||
--primary: var(--custom-primary, 142.1 76.2% 36.3%);
|
||||
--primary-foreground: 355.7 100% 97.3%;
|
||||
--accent: var(--custom-primary, 142.1 76.2% 36.3%);
|
||||
--accent-foreground: 355.7 100% 97.3%;
|
||||
}
|
||||
|
||||
:root[data-color-mode="dark"][data-color-theme="slate"],
|
||||
:root.dark[data-color-theme="slate"] {
|
||||
--primary: 0 0% 98%;
|
||||
--primary-foreground: 240 5.9% 10%;
|
||||
--accent: 240 3.7% 15.9%;
|
||||
--accent-foreground: 0 0% 98%;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root:not([data-color-mode="light"])[data-color-theme="slate"] {
|
||||
--primary: 0 0% 98%;
|
||||
--primary-foreground: 240 5.9% 10%;
|
||||
--accent: 240 3.7% 15.9%;
|
||||
--accent-foreground: 0 0% 98%;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
@@ -84,9 +290,9 @@
|
||||
--color-input: hsl(var(--input));
|
||||
--color-ring: hsl(var(--ring));
|
||||
|
||||
--font-sans: var(--font-sans), sans-serif;
|
||||
--font-heading: var(--font-heading), serif;
|
||||
--font-mono: var(--font-geist-mono), monospace;
|
||||
--font-sans: var(--app-font-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
--font-heading: var(--app-font-heading), ui-serif, Georgia, serif;
|
||||
--font-mono: var(--font-geist-mono), ui-monospace, monospace;
|
||||
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
@@ -114,6 +320,87 @@
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
:root[data-interface-theme="shadcn"] .brand-background,
|
||||
:root[data-interface-theme="minimal"] .brand-background {
|
||||
display: none;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="minimal"] [data-slot="card"] {
|
||||
background-color: transparent;
|
||||
border-color: transparent;
|
||||
border-radius: 0;
|
||||
border-top-color: hsl(var(--border));
|
||||
box-shadow: none;
|
||||
backdrop-filter: none;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="minimal"] [data-slot="card"] + [data-slot="card"],
|
||||
:root[data-interface-theme="minimal"] .form-section + .form-section {
|
||||
border-top: 1px solid hsl(var(--border));
|
||||
padding-top: 1rem;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="minimal"] [data-slot="card-header"],
|
||||
:root[data-interface-theme="minimal"] [data-slot="card-content"],
|
||||
:root[data-interface-theme="minimal"] [data-slot="card-footer"] {
|
||||
padding-inline: 0;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="minimal"] [data-slot="card-header"] {
|
||||
padding-top: 0.75rem;
|
||||
padding-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="minimal"] [data-slot="card-content"] {
|
||||
padding-bottom: 0.75rem;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="minimal"] .page-enter,
|
||||
:root[data-interface-theme="minimal"] [class*="space-y-8"],
|
||||
:root[data-interface-theme="minimal"] [class*="space-y-6"] {
|
||||
row-gap: 1rem;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="minimal"]
|
||||
[class*="space-y-8"]
|
||||
> :not([hidden])
|
||||
~ :not([hidden]),
|
||||
:root[data-interface-theme="minimal"]
|
||||
[class*="space-y-6"]
|
||||
> :not([hidden])
|
||||
~ :not([hidden]) {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="minimal"] [class*="gap-6"] {
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="minimal"] .platform-header-surface {
|
||||
background-color: transparent;
|
||||
border-color: transparent;
|
||||
box-shadow: none;
|
||||
backdrop-filter: none;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="minimal"] .platform-header-content {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="minimal"] .platform-header-gradient {
|
||||
display: none;
|
||||
}
|
||||
|
||||
:root[data-interface-theme="minimal"] .bg-dashboard {
|
||||
background-color: hsl(var(--background));
|
||||
}
|
||||
|
||||
:root[data-interface-theme="editorial"] .brand-background {
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.animate-blob {
|
||||
animation: blob 7s infinite;
|
||||
}
|
||||
@@ -135,6 +422,25 @@
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 4px 12px -4px hsl(var(--foreground) / 0.1);
|
||||
}
|
||||
|
||||
:root[data-radius] .rounded-sm {
|
||||
border-radius: var(--radius-sm);
|
||||
}
|
||||
|
||||
:root[data-radius] .rounded,
|
||||
:root[data-radius] .rounded-md {
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
:root[data-radius] .rounded-lg {
|
||||
border-radius: var(--radius-lg);
|
||||
}
|
||||
|
||||
:root[data-radius] .rounded-xl,
|
||||
:root[data-radius] .rounded-2xl,
|
||||
:root[data-radius] .rounded-3xl {
|
||||
border-radius: var(--radius-xl);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes blob {
|
||||
@@ -153,4 +459,4 @@
|
||||
100% {
|
||||
transform: translate(0px, 0px) scale(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+4
-4
@@ -7,7 +7,6 @@ import { type inferRouterInputs, type inferRouterOutputs } from "@trpc/server";
|
||||
import { useState } from "react";
|
||||
import SuperJSON from "superjson";
|
||||
|
||||
import { type AppRouter } from "~/server/api/root";
|
||||
import { createQueryClient } from "./query-client";
|
||||
|
||||
let clientQueryClientSingleton: QueryClient | undefined = undefined;
|
||||
@@ -22,21 +21,22 @@ const getQueryClient = () => {
|
||||
return clientQueryClientSingleton;
|
||||
};
|
||||
|
||||
export const api = createTRPCReact<AppRouter>();
|
||||
// Use inline import() type to avoid pulling server modules into the client bundle
|
||||
export const api = createTRPCReact<import("~/server/api/root").AppRouter>();
|
||||
|
||||
/**
|
||||
* Inference helper for inputs.
|
||||
*
|
||||
* @example type HelloInput = RouterInputs['example']['hello']
|
||||
*/
|
||||
export type RouterInputs = inferRouterInputs<AppRouter>;
|
||||
export type RouterInputs = inferRouterInputs<import("~/server/api/root").AppRouter>;
|
||||
|
||||
/**
|
||||
* Inference helper for outputs.
|
||||
*
|
||||
* @example type HelloOutput = RouterOutputs['example']['hello']
|
||||
*/
|
||||
export type RouterOutputs = inferRouterOutputs<AppRouter>;
|
||||
export type RouterOutputs = inferRouterOutputs<import("~/server/api/root").AppRouter>;
|
||||
|
||||
export function TRPCReactProvider(props: { children: React.ReactNode }) {
|
||||
const queryClient = getQueryClient();
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
echo "[start.sh] Starting beenvoice in production mode"
|
||||
|
||||
# Detect if running inside a Docker container
|
||||
IS_DOCKER=false
|
||||
if [ -f /\.dockerenv ]; then
|
||||
IS_DOCKER=true
|
||||
fi
|
||||
|
||||
if [ "$IS_DOCKER" = false ]; then
|
||||
## Host mode: prepare env, then run containers
|
||||
if [ ! -f ./.env ] && { [ -f ./.env.example ] || [ -f ./env.example ]; }; then
|
||||
echo "[start.sh] No .env detected. Creating from env.example with generated secrets..."
|
||||
GEN_AUTH_SECRET=$(openssl rand -hex 32 || cat /proc/sys/kernel/random/uuid)
|
||||
GEN_DB_PASSWORD=$(openssl rand -hex 16 || cat /proc/sys/kernel/random/uuid)
|
||||
tmp_env=$(mktemp)
|
||||
ENV_TEMPLATE="./.env.example"
|
||||
if [ -f ./env.example ]; then ENV_TEMPLATE="./env.example"; fi
|
||||
sed \
|
||||
-e "s/^AUTH_SECRET=__GENERATE__/AUTH_SECRET=${GEN_AUTH_SECRET}/" \
|
||||
-e "s/^POSTGRES_PASSWORD=__GENERATE__/POSTGRES_PASSWORD=${GEN_DB_PASSWORD}/" \
|
||||
"$ENV_TEMPLATE" > "$tmp_env"
|
||||
mv "$tmp_env" ./.env
|
||||
echo "[start.sh] Created .env. Please review and edit it as needed, then run this script again."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Auto-generate missing placeholders in existing .env
|
||||
if [ -f ./.env ]; then
|
||||
set -a; . ./.env; set +a
|
||||
updated_env=false
|
||||
if [ -z "${AUTH_SECRET:-}" ] || grep -qE '^AUTH_SECRET=($|__GENERATE__)' ./.env; then
|
||||
new_auth_secret=$(openssl rand -hex 32 || cat /proc/sys/kernel/random/uuid)
|
||||
sed -i.bak -e "s/^AUTH_SECRET=.*/AUTH_SECRET=${new_auth_secret}/" ./.env || echo "AUTH_SECRET=${new_auth_secret}" >> ./.env
|
||||
updated_env=true
|
||||
fi
|
||||
if [ -z "${POSTGRES_PASSWORD:-}" ] || grep -qE '^POSTGRES_PASSWORD=($|__GENERATE__)' ./.env; then
|
||||
new_db_pw=$(openssl rand -hex 16 || cat /proc/sys/kernel/random/uuid)
|
||||
sed -i.bak -e "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=${new_db_pw}/" ./.env || echo "POSTGRES_PASSWORD=${new_db_pw}" >> ./.env
|
||||
updated_env=true
|
||||
fi
|
||||
if [ "$updated_env" = true ]; then rm -f ./.env.bak || true; fi
|
||||
fi
|
||||
|
||||
# Ensure docker is available
|
||||
if ! command -v docker >/dev/null 2>&1; then
|
||||
echo "[start.sh] ERROR: docker is not installed or not in PATH." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "[start.sh] Bringing up containers with docker compose..."
|
||||
docker compose up -d
|
||||
echo "[start.sh] Containers started. View logs with: docker compose logs -f app"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Container mode: continue to runtime checks and start app
|
||||
|
||||
# If .env exists but secrets are missing or placeholders, auto-generate and update file
|
||||
updated_env=false
|
||||
if [ -f ./.env ]; then
|
||||
if [ -z "${AUTH_SECRET:-}" ] || grep -qE '^AUTH_SECRET=($|__GENERATE__)' ./.env; then
|
||||
new_auth_secret=$(openssl rand -hex 32 || cat /proc/sys/kernel/random/uuid)
|
||||
sed -i.bak -e "s/^AUTH_SECRET=.*/AUTH_SECRET=${new_auth_secret}/" ./.env || echo "AUTH_SECRET=${new_auth_secret}" >> ./.env
|
||||
AUTH_SECRET=${new_auth_secret}
|
||||
updated_env=true
|
||||
fi
|
||||
if [ -z "${POSTGRES_PASSWORD:-}" ] || grep -qE '^POSTGRES_PASSWORD=($|__GENERATE__)' ./.env; then
|
||||
new_db_pw=$(openssl rand -hex 16 || cat /proc/sys/kernel/random/uuid)
|
||||
sed -i.bak -e "s/^POSTGRES_PASSWORD=.*/POSTGRES_PASSWORD=${new_db_pw}/" ./.env || echo "POSTGRES_PASSWORD=${new_db_pw}" >> ./.env
|
||||
POSTGRES_PASSWORD=${new_db_pw}
|
||||
updated_env=true
|
||||
fi
|
||||
# Compose DATABASE_URL if missing but POSTGRES_* present
|
||||
if [ -z "${DATABASE_URL:-}" ] && [ -n "${POSTGRES_USER:-}" ] && [ -n "${POSTGRES_PASSWORD:-}" ] && [ -n "${POSTGRES_DB:-}" ]; then
|
||||
DATABASE_URL="postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}"
|
||||
echo "DATABASE_URL=${DATABASE_URL}" >> ./.env
|
||||
updated_env=true
|
||||
fi
|
||||
# Reload env if we updated it
|
||||
if [ "$updated_env" = true ]; then
|
||||
set -a
|
||||
# shellcheck disable=SC1091
|
||||
. ./.env
|
||||
set +a
|
||||
rm -f ./.env.bak || true
|
||||
fi
|
||||
fi
|
||||
|
||||
# Ensure required env vars are present (fail fast for critical ones)
|
||||
if [ -z "${DATABASE_URL:-}" ]; then
|
||||
echo "[start.sh] ERROR: DATABASE_URL must be set (in .env or environment)." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -z "${AUTH_SECRET:-}" ]; then
|
||||
echo "[start.sh] ERROR: AUTH_SECRET must be set (in .env or environment)." >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -z "${RESEND_API_KEY:-}" ]; then
|
||||
echo "[start.sh] ERROR: RESEND_API_KEY must be set (in .env or environment)." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Optional: allow skipping migrations with SKIP_DB_MIGRATION=true
|
||||
SKIP_DB_MIGRATION=${SKIP_DB_MIGRATION:-false}
|
||||
|
||||
if [ "$SKIP_DB_MIGRATION" != "true" ]; then
|
||||
echo "[start.sh] Applying database migrations"
|
||||
SKIP_ENV_VALIDATION=1 bun src/server/db/migrate.ts
|
||||
else
|
||||
echo "[start.sh] Skipping DB migration due to SKIP_DB_MIGRATION=${SKIP_DB_MIGRATION}"
|
||||
fi
|
||||
|
||||
PORT=${PORT:-3000}
|
||||
HOSTNAME_ENV=${HOSTNAME:-0.0.0.0}
|
||||
|
||||
echo "[start.sh] Starting Next.js server on ${HOSTNAME_ENV}:${PORT}"
|
||||
exec bun run start -p "${PORT}" -H "${HOSTNAME_ENV}"
|
||||
|
||||
|
||||
Reference in New Issue
Block a user