Files
AndymickandClaude Sonnet 5 396347b982 Move uploaded images to disk storage, fix Next 16 async params/searchParams
Homepage was rendering 71MB of HTML because every uploaded image (gallery,
products, proofs, custom requests, design previews, invoices, receipts) was
stored as base64 in Postgres and double-embedded via RSC hydration payloads.
Adds src/lib/storage.ts (sharp-based compression, disk storage under
public/uploads/) and a new /api/design-uploads endpoint for images added
inside the design tool, migrates existing rows, and drops the now-unused
base64 columns and the dead ProductImage table.

Also fixes a systemic bug from the Next.js 16 upgrade where dynamic pages
across the app still destructured params/searchParams synchronously instead
of awaiting them as Promises, which was silently breaking filters/params and
crashing /products/[slug] outright.

Updates README.md and SETUP_AND_BUILD.md to reflect Postgres + Next.js 16 and
document the new image storage architecture and backup requirements.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-22 20:56:40 +01:00

163 lines
7.4 KiB
Markdown

# Craft2Prints — Ink it. Print it. Love it.
A complete self-hosted e-commerce platform for personalized products (apparel, drinkware, phone cases) with an in-browser design tool, integrated accounting system, and real Stripe payments.
## Features
### Customer Experience
- **Design Tool** — In-browser tool to customize templates with text and images
- **Product Catalog** — Browse and filter by category, color, size, and price
- **Shopping Cart** — Persistent cart stored in IndexedDB
- **Customer Accounts** — Optional sign-up for order history and faster checkout
- **Dark Mode** — Full dark mode support with system preference detection
- **Mobile Responsive** — Works seamlessly on all devices
### Order Management
- **Real Payments** — Stripe integration for production-ready checkout
- **Order Tracking** — Customers see order history, status, and print files
- **Design Approvals** — Upload custom designs for customer review with built-in chat
- **Photo Requests** — Customers submit photos; you design them into products
- **Auto-Archiving** — Paid/failed orders auto-archive after 30 days
### Admin Dashboard
- **Product Management** — Add/edit/delete products with photos, colors, sizes
- **Category Management** — Organize products by customer-facing categories
- **Financial System** — Complete self-hosted accounting:
- 📊 **Reports & Analysis** — KPIs, profit trends, income breakdown, tax year summaries
- 🏦 **Bank Reconciliation** — Upload CSV statements, auto-match transactions, verify accuracy
- 📋 **Audit Trail** — Track all changes with IP addresses, timestamps, and reasons
- 📈 **Tax Compliance** — UK tax year (April-April) calculations and HMRC export
- **Admin Login Activity** — Track who logged in, when, from where
- **Customer Login Activity** — Monitor customer account access
- **Order Management** — View, approve, archive orders
- **Inbox** — Chat with customers about design changes
- **Promotions** — Create sales with per-product or site-wide discounts
### Security & Compliance
- **Admin Authentication** — Session-based login with automatic logout on page close
- **Customer Authentication** — Separate customer account system (optional)
- **Rate Limiting** — DB-backed rate limiting on login/checkout
- **CAPTCHA** — Cloudflare Turnstile on public forms
- **Audit Logging** — Full financial audit trail for compliance
- **Session Expiry** — Auto-logout when browser closes
### Technical Stack
- **Frontend** — Next.js 16 (App Router, Turbopack), React, Tailwind CSS
- **Backend** — Next.js server actions, API routes
- **Database** — PostgreSQL with Prisma ORM
- **File storage** — Uploaded images/documents are compressed with `sharp` and saved as files on disk (`public/uploads/`), not as base64 in the database — see [Image & File Storage](#image--file-storage) below
- **Payments** — Stripe (production-ready)
- **Email** — SMTP (Gmail, Outlook, SendGrid, etc.)
- **Design** — Fabric.js/Konva canvas for the design tool, SVG-based product mockups
## Quick Start
1. **Install Node.js 18+** — Check with `node -v`
2. **Install dependencies**
```bash
npm install
```
3. **Set up environment**
```bash
cp .env.example .env
# Edit .env with your configuration (see SETUP_AND_BUILD.md for details)
```
4. **Create database and load starter products**
```bash
npm run db:push
npm run db:seed
```
5. **Start dev server**
```bash
npm run dev
```
Open http://localhost:3000 — you'll see the homepage and catalog.
## Configuration
**Essential (.env):**
- `DATABASE_URL` — PostgreSQL connection string
- `ADMIN_USER` / `ADMIN_PASSWORD` — Admin login credentials (⚠️ change before deployment)
- `STRIPE_SECRET_KEY` / `STRIPE_WEBHOOK_SECRET` — Stripe payment keys
**Optional:**
- `SMTP_*` — Email configuration for order confirmations and password resets
- `NEXT_PUBLIC_TURNSTILE_SITE_KEY` / `TURNSTILE_SECRET_KEY` — CAPTCHA on forms
- `NEXT_PUBLIC_FACEBOOK_APP_ID` — Messenger sharing (WhatsApp always works)
See `.env.example` and [SETUP_AND_BUILD.md](./SETUP_AND_BUILD.md) for complete reference.
## Key Concepts
### Product Catalogs
- **Personalised Catalog** (`/made-to-order`) — Full design tool, customers customize templates
- **Products Catalog** (`/products`) — Buy as-is with color/size picker, no design tool
A product can appear on both catalogs simultaneously.
### Currency
Prices stored in **GBP pence** internally. Customer-facing header currency selector (£/$/€) changes display only — no actual conversion happens until checkout is configured for it.
### Cart Storage
Cart persists to **IndexedDB**, not localStorage, since it comfortably holds the design tool's cart items without the ~5-10MB ceiling localStorage imposes.
### Color Names
Colors display as friendly names to customers (Navy, Red, Forest Green) instead of hex codes. Admin still sees hex for reference.
### Image & File Storage
Every uploaded image or document (product photos, gallery photos, custom-request photos, design-approval previews, purchase invoices, expense receipts, images added inside the design tool) is saved as a real file on disk under `public/uploads/<category>/<yyyy>/<mm>/<uuid>.<ext>`, compressed and resized on the way in with `sharp`. Database columns only ever hold the resulting short URL (e.g. `/uploads/gallery/2026/07/<uuid>.jpeg`) — never a base64 data URL. PDFs (invoices/receipts) pass through untouched.
This matters operationally: `public/uploads/` is gitignored but lives permanently on the server's disk, so **backups must cover it alongside the database** (see [SETUP_AND_BUILD.md](./SETUP_AND_BUILD.md)). No web server config is needed to serve these files — Next.js serves everything under `public/` automatically.
See `src/lib/storage.ts` for the upload/compression helper and its per-category presets.
## Accounting Features
### Financial Reports
- **KPI Dashboard** — Year-to-date metrics, income source breakdown, growth rates
- **12-Month Trends** — Visual profit trends with best/worst month analysis
- **Income Breakdown** — Website sales vs manual sales comparison
- **Revenue vs Expenses** — Side-by-side trend analysis
- **Tax Year Summary** — UK April-April year calculations
- **HMRC Report** — Tax compliance format for self-assessment filing
### Bank Reconciliation
- Upload CSV bank statements from any UK bank
- Auto-matches transactions based on amount and date (95%+ accuracy)
- Manual matching for edge cases (transfers, fees, refunds)
- Discrepancy detection (amount mismatches flagged in orange)
- Reconciliation status tracking (PENDING → RECONCILED → ARCHIVED)
- Export reconciliation reports
### Audit Trail
- Logs all financial changes (create/update/delete)
- Tracks IP address, timestamp, and reason for each change
- Stores before/after values for data integrity
- Separate login activity logging (admin and customer)
## Deployment
See [SETUP_AND_BUILD.md](./SETUP_AND_BUILD.md) for detailed deployment instructions including:
- Production build process
- Environment setup
- Stripe live keys configuration
- Reverse proxy setup (nginx)
- Process management (pm2)
- Database backups
- Security hardening
## Support
- **Issues** — Check the GitHub issues for known problems
- **Docs** — See SETUP_AND_BUILD.md for comprehensive setup and deployment guide
- **Examples** — `.env.example` shows all available configuration options
## License
Built with ❤️ for small businesses and makers.