Assemble QMS app + SQLite refactor + Unraid single-container deploy
Build and Push Docker Image / build (push) Successful in 1m12s
Build and Push Docker Image / build (push) Successful in 1m12s
Reconstruct the full app from init-source overlays (base + fix-1..6 + update-1..3, last-wins) at the repo root, complete the missing pieces so it builds and runs, and stage the Unraid deployment. App completion: - types/index.ts: former Prisma enums as string-literal unions + AppUser - pages/_app.tsx + styles/globals.css (mount AppProvider/ToastProvider) - API routes: auth/login, auth/me, users, submissions (+REVIEW_READY notify), forms (list/create), notifications - scripts/create-admin.js: idempotent first-admin bootstrap - 14 unbuilt nav targets stubbed via ComingSoon placeholder SQLite refactor (single-container, no external DB): - schema provider -> sqlite; enums -> String; Json -> String; FormField.options String[] -> JSON-encoded String - lib/forms.ts (de)serialises options at the DB boundary - drop mode:"insensitive" (unsupported on SQLite) - enum imports repointed from @prisma/client to @/types Deploy: - multi-stage Dockerfile (next build -> prod runner), docker-entrypoint.sh (prisma db push -> create-admin -> next start), .dockerignore - docker-compose.yml: br0 10.2.0.x, /mnt/user/appdata/qms -> /data volume - README rewritten for the Unraid/Gitea Actions flow; .env scrubbed of the live Supabase credential; vercel.json removed Verified: next build clean (41 routes); live SQLite round-trip of login/session, form options array, and submission -> REVIEW_READY. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
+108
@@ -0,0 +1,108 @@
|
||||
import { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { prisma } from './prisma'
|
||||
import { Role } from '@/types'
|
||||
import bcrypt from 'bcryptjs'
|
||||
import { v4 as uuid } from 'uuid'
|
||||
|
||||
export const SESSION_COOKIE = 'qms_session'
|
||||
export const SESSION_EXPIRY_DAYS = 7
|
||||
|
||||
export async function hashPassword(password: string) {
|
||||
return bcrypt.hash(password, 12)
|
||||
}
|
||||
|
||||
export async function verifyPassword(password: string, hash: string) {
|
||||
return bcrypt.compare(password, hash)
|
||||
}
|
||||
|
||||
export async function createSession(userId: string) {
|
||||
const token = uuid()
|
||||
const expiresAt = new Date()
|
||||
expiresAt.setDate(expiresAt.getDate() + SESSION_EXPIRY_DAYS)
|
||||
|
||||
await prisma.session.create({
|
||||
data: { userId, token, expiresAt },
|
||||
})
|
||||
|
||||
return token
|
||||
}
|
||||
|
||||
export async function getSessionUser(req: NextApiRequest) {
|
||||
const token = req.cookies[SESSION_COOKIE]
|
||||
if (!token) return null
|
||||
|
||||
const session = await prisma.session.findUnique({
|
||||
where: { token },
|
||||
include: { user: true },
|
||||
})
|
||||
|
||||
if (!session || session.expiresAt < new Date()) {
|
||||
if (session) await prisma.session.delete({ where: { token } })
|
||||
return null
|
||||
}
|
||||
|
||||
return session.user
|
||||
}
|
||||
|
||||
export async function requireAuth(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse,
|
||||
allowedRoles?: Role[]
|
||||
) {
|
||||
const user = await getSessionUser(req)
|
||||
|
||||
if (!user || !user.active) {
|
||||
res.status(401).json({ error: 'Unauthorised' })
|
||||
return null
|
||||
}
|
||||
|
||||
if (allowedRoles && !allowedRoles.includes(user.role as Role)) {
|
||||
res.status(403).json({ error: 'Forbidden' })
|
||||
return null
|
||||
}
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
export async function logAction(
|
||||
userId: string,
|
||||
action: string,
|
||||
entity: string,
|
||||
entityId: string,
|
||||
before?: unknown,
|
||||
after?: unknown
|
||||
) {
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
userId,
|
||||
action,
|
||||
entity,
|
||||
entityId,
|
||||
before: before === undefined ? null : JSON.stringify(before),
|
||||
after: after === undefined ? null : JSON.stringify(after),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function generateRef(prefix: string, count: number) {
|
||||
return `${prefix}-${String(count + 1).padStart(3, '0')}`
|
||||
}
|
||||
|
||||
// Role permission helpers
|
||||
export const ROLE_PERMISSIONS = {
|
||||
ADMIN: ['*'],
|
||||
QC: ['capa', 'audits', 'ncr', 'resolutions', 'documents', 'risk', 'suppliers', 'standards', 'shipping-standard', 'dashboard', 'reports', 'export'],
|
||||
PRODUCTION: ['fill', 'my-submissions', 'report-issue'],
|
||||
PRODUCTION_LEAD: ['fill', 'my-submissions', 'report-issue', 'shipments', 'escapes', 'shipping-standard', 'ncr', 'dashboard'],
|
||||
LOGISTICS_LEAD: ['shipments', 'escapes', 'shipping-standard', 'ncr', 'dashboard'],
|
||||
MANAGEMENT: ['dashboard', 'reports', 'export'],
|
||||
} as const
|
||||
|
||||
// Only these roles may batch-email a client release package
|
||||
export const SHIPMENT_SEND_ROLES: Role[] = ['ADMIN', 'PRODUCTION_LEAD', 'LOGISTICS_LEAD']
|
||||
|
||||
export function canAccess(role: string, module: string): boolean {
|
||||
const perms = ROLE_PERMISSIONS[role as Role] as readonly string[] | undefined
|
||||
if (!perms) return false
|
||||
return perms.includes('*') || perms.includes(module)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import React, { createContext, useContext, useState, useEffect, useCallback } from 'react'
|
||||
import { AppUser } from '@/types'
|
||||
|
||||
interface AppContextValue {
|
||||
user: AppUser | null
|
||||
loading: boolean
|
||||
login: (email: string, password: string) => Promise<string | null>
|
||||
logout: () => Promise<void>
|
||||
refreshUser: () => Promise<void>
|
||||
}
|
||||
|
||||
const AppContext = createContext<AppContextValue>({} as AppContextValue)
|
||||
|
||||
export function AppProvider({ children }: { children: React.ReactNode }) {
|
||||
const [user, setUser] = useState<AppUser | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
const refreshUser = useCallback(async () => {
|
||||
try {
|
||||
const res = await fetch('/api/auth/me')
|
||||
if (res.ok) {
|
||||
const { user } = await res.json()
|
||||
setUser(user)
|
||||
} else {
|
||||
setUser(null)
|
||||
}
|
||||
} catch {
|
||||
setUser(null)
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
refreshUser().finally(() => setLoading(false))
|
||||
}, [refreshUser])
|
||||
|
||||
const login = async (email: string, password: string): Promise<string | null> => {
|
||||
const res = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, password }),
|
||||
})
|
||||
const data = await res.json()
|
||||
if (res.ok) {
|
||||
setUser(data.user)
|
||||
return null
|
||||
}
|
||||
return data.error || 'Login failed'
|
||||
}
|
||||
|
||||
const logout = async () => {
|
||||
await fetch('/api/auth/me', { method: 'DELETE' })
|
||||
setUser(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<AppContext.Provider value={{ user, loading, login, logout, refreshUser }}>
|
||||
{children}
|
||||
</AppContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export const useApp = () => useContext(AppContext)
|
||||
@@ -0,0 +1,92 @@
|
||||
import nodemailer from 'nodemailer'
|
||||
import { prisma } from './prisma'
|
||||
import { NotifType } from '@/types'
|
||||
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: process.env.SMTP_HOST,
|
||||
port: Number(process.env.SMTP_PORT) || 587,
|
||||
secure: false,
|
||||
auth: {
|
||||
user: process.env.SMTP_USER,
|
||||
pass: process.env.SMTP_PASS,
|
||||
},
|
||||
})
|
||||
|
||||
const FROM = process.env.EMAIL_FROM || 'qms@acmequality.com'
|
||||
const APP_URL = process.env.NEXT_PUBLIC_APP_URL || 'http://localhost:3000'
|
||||
|
||||
export async function sendEmail(to: string, subject: string, html: string) {
|
||||
if (!process.env.SMTP_HOST) {
|
||||
console.log('[EMAIL SKIPPED - no SMTP config]', { to, subject })
|
||||
return
|
||||
}
|
||||
await transporter.sendMail({ from: FROM, to, subject, html })
|
||||
}
|
||||
|
||||
export async function createNotification(
|
||||
userId: string,
|
||||
type: NotifType,
|
||||
title: string,
|
||||
body: string,
|
||||
link?: string
|
||||
) {
|
||||
return prisma.notification.create({
|
||||
data: { userId, type, title, body, link },
|
||||
})
|
||||
}
|
||||
|
||||
export async function notifyCAPAOverdue(capaRef: string, capaTitle: string, ownerEmail: string, ownerId: string) {
|
||||
const link = `${APP_URL}/qc/capas`
|
||||
await createNotification(ownerId, 'CAPA_OVERDUE', `${capaRef} is overdue`, `${capaTitle} has passed its due date.`, link)
|
||||
await sendEmail(ownerEmail, `[V11 QMS] CAPA ${capaRef} overdue`, `
|
||||
<p>Hello,</p>
|
||||
<p>CAPA <strong>${capaRef}: ${capaTitle}</strong> has passed its due date and requires immediate attention.</p>
|
||||
<p><a href="${link}">View CAPA →</a></p>
|
||||
`)
|
||||
}
|
||||
|
||||
export async function notifyNCREscalated(ncrRef: string, ncrDesc: string, managerEmail: string, managerId: string) {
|
||||
const link = `${APP_URL}/qc/ncr`
|
||||
await createNotification(managerId, 'NCR_ESCALATED', `${ncrRef} escalated`, ncrDesc, link)
|
||||
await sendEmail(managerEmail, `[V11 QMS] NCR ${ncrRef} escalated`, `
|
||||
<p>NCR <strong>${ncrRef}</strong> has been escalated: ${ncrDesc}</p>
|
||||
<p><a href="${link}">View NCR →</a></p>
|
||||
`)
|
||||
}
|
||||
|
||||
export async function notifyFormReviewReady(formName: string, submissionCount: number, adminEmail: string, adminId: string) {
|
||||
const link = `${APP_URL}/admin/forms`
|
||||
await createNotification(adminId, 'FORM_REVIEW_READY', `${formName} ready for review`, `${submissionCount} submissions collected. QC review can begin.`, link)
|
||||
await sendEmail(adminEmail, `[V11 QMS] Form ready for QC review: ${formName}`, `
|
||||
<p><strong>${formName}</strong> has reached ${submissionCount} submissions and is ready for QC standard review.</p>
|
||||
<p><a href="${link}">Review now →</a></p>
|
||||
`)
|
||||
}
|
||||
|
||||
export async function notifySolutionConfirmed(ncrRef: string, ncrDesc: string, reporterEmail: string, reporterId: string) {
|
||||
const link = `${APP_URL}/qc/ncr`
|
||||
await createNotification(reporterId, 'SOLUTION_CONFIRMED', `Fix confirmed for ${ncrRef}`, `The issue you reported (${ncrDesc}) has been resolved. No action needed from you.`, link)
|
||||
await sendEmail(reporterEmail, `[V11 QMS] Fixed: ${ncrRef}`, `
|
||||
<p>Good news — the issue you reported has been resolved:</p>
|
||||
<p style="color:#666">${ncrDesc}</p>
|
||||
<p>No further action is needed from you.</p>
|
||||
`)
|
||||
}
|
||||
|
||||
export function emailTemplate(title: string, body: string) {
|
||||
return `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<head><meta charset="utf-8"><title>${title}</title></head>
|
||||
<body style="font-family:sans-serif;max-width:600px;margin:0 auto;padding:24px;color:#333">
|
||||
<div style="border-bottom:2px solid #534AB7;padding-bottom:12px;margin-bottom:20px">
|
||||
<span style="font-weight:600;font-size:16px;color:#534AB7">V11 QMS</span>
|
||||
</div>
|
||||
<h2 style="font-size:18px;font-weight:500;margin-bottom:12px">${title}</h2>
|
||||
${body}
|
||||
<div style="border-top:1px solid #eee;margin-top:32px;padding-top:12px;font-size:11px;color:#999">
|
||||
This is an automated message from V11 Enterprise QMS. Do not reply.
|
||||
</div>
|
||||
</body>
|
||||
</html>`
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// Helpers for the FormField.options column, which is stored as a JSON-encoded
|
||||
// string in SQLite (no native scalar lists). The client/API contract keeps
|
||||
// `options` as a real string[] — these convert at the DB boundary.
|
||||
|
||||
export function parseOptions(raw: unknown): string[] {
|
||||
if (Array.isArray(raw)) return raw as string[]
|
||||
if (typeof raw !== 'string' || raw.length === 0) return []
|
||||
try {
|
||||
const v = JSON.parse(raw)
|
||||
return Array.isArray(v) ? v.map(String) : []
|
||||
} catch {
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
export function serializeOptions(opts: unknown): string {
|
||||
return JSON.stringify(Array.isArray(opts) ? opts : [])
|
||||
}
|
||||
|
||||
// Returns a shallow copy of a form with each field's `options` parsed to string[].
|
||||
export function withParsedFields<T extends { fields?: any[] | null }>(form: T | null): T | null {
|
||||
if (!form) return form
|
||||
if (Array.isArray(form.fields)) {
|
||||
return {
|
||||
...form,
|
||||
fields: form.fields.map(f => ({ ...f, options: parseOptions(f.options) })),
|
||||
}
|
||||
}
|
||||
return form
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { PrismaClient } from '@prisma/client'
|
||||
|
||||
const globalForPrisma = globalThis as unknown as {
|
||||
prisma: PrismaClient | undefined
|
||||
}
|
||||
|
||||
export const prisma =
|
||||
globalForPrisma.prisma ??
|
||||
new PrismaClient({
|
||||
log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
|
||||
})
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma
|
||||
|
||||
export default prisma
|
||||
Reference in New Issue
Block a user