Initial commit - ERP System
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
// /opt/erp-system/app/api/auth/[...nextauth]/route.ts
|
||||
import NextAuth from "next-auth";
|
||||
import CredentialsProvider from "next-auth/providers/credentials";
|
||||
import prisma from "../../../../lib/prisma";
|
||||
import bcrypt from "bcryptjs";
|
||||
|
||||
export const authOptions = {
|
||||
providers: [
|
||||
CredentialsProvider({
|
||||
name: "Credentials",
|
||||
credentials: {
|
||||
email: { label: "Email", type: "email" },
|
||||
password: { label: "Passwort", type: "password" }
|
||||
},
|
||||
async authorize(credentials) {
|
||||
if (!credentials?.email || !credentials?.password) return null;
|
||||
|
||||
const teamUser = await prisma.user.findUnique({
|
||||
where: { email: credentials.email },
|
||||
include: { role: true }
|
||||
});
|
||||
|
||||
if (teamUser) {
|
||||
const match = await bcrypt.compare(credentials.password, teamUser.passwordHash);
|
||||
if (match) {
|
||||
return {
|
||||
id: `TEAM_${teamUser.id}`, dbId: teamUser.id, email: teamUser.email,
|
||||
firstName: teamUser.firstName, lastName: teamUser.lastName,
|
||||
roleName: teamUser.role?.name || 'Keine Rolle', permissions: teamUser.role?.permissions || [],
|
||||
userType: 'TEAM', forcePasswordChange: false
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const customer = await prisma.customer.findUnique({ where: { email: credentials.email } });
|
||||
|
||||
if (customer && customer.passwordHash) {
|
||||
const match = await bcrypt.compare(credentials.password, customer.passwordHash);
|
||||
if (match) {
|
||||
return {
|
||||
id: `CUST_${customer.id}`, dbId: customer.id, email: customer.email,
|
||||
firstName: customer.firstName, lastName: customer.lastName,
|
||||
roleName: 'Kunde', permissions: [], userType: 'CUSTOMER',
|
||||
companyName: customer.companyName,
|
||||
forcePasswordChange: customer.forcePasswordChange // WICHTIG: Flag übergeben
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
})
|
||||
],
|
||||
callbacks: {
|
||||
async jwt({ token, user }: any) {
|
||||
if (user) {
|
||||
token.dbId = user.dbId; token.firstName = user.firstName; token.lastName = user.lastName;
|
||||
token.roleName = user.roleName; token.permissions = user.permissions;
|
||||
token.userType = user.userType; token.companyName = user.companyName;
|
||||
token.forcePasswordChange = user.forcePasswordChange;
|
||||
}
|
||||
return token;
|
||||
},
|
||||
async session({ session, token }: any) {
|
||||
if (token) {
|
||||
session.user.id = token.dbId; session.user.firstName = token.firstName;
|
||||
session.user.lastName = token.lastName; session.user.roleName = token.roleName;
|
||||
session.user.permissions = token.permissions || []; session.user.userType = token.userType;
|
||||
session.user.companyName = token.companyName;
|
||||
session.user.forcePasswordChange = token.forcePasswordChange;
|
||||
}
|
||||
return session;
|
||||
}
|
||||
},
|
||||
pages: { signIn: "/login" },
|
||||
secret: process.env.NEXTAUTH_SECRET,
|
||||
};
|
||||
|
||||
const handler = NextAuth(authOptions);
|
||||
export { handler as GET, handler as POST };
|
||||
@@ -0,0 +1,57 @@
|
||||
// /opt/erp-system/app/api/billing/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../lib/prisma';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../auth/[...nextauth]/route";
|
||||
|
||||
async function checkAccess() {
|
||||
const session = await getServerSession(authOptions);
|
||||
const perms = (session?.user as any)?.permissions || [];
|
||||
return perms.includes('TEAM_MANAGE'); // Wir nutzen vorerst dieses Recht für die Abrechnung
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
if (!await checkAccess()) return NextResponse.json({ error: 'Zugriff verweigert' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const unbilledEntries = await prisma.timeEntry.findMany({
|
||||
where: { isBilled: false },
|
||||
include: {
|
||||
user: { select: { firstName: true, lastName: true } },
|
||||
ticket: {
|
||||
include: { customer: true }
|
||||
}
|
||||
},
|
||||
orderBy: { createdAt: 'asc' }
|
||||
});
|
||||
|
||||
return NextResponse.json(unbilledEntries);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
if (!await checkAccess()) return NextResponse.json({ error: 'Zugriff verweigert' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const { entryIds } = body;
|
||||
|
||||
if (!Array.isArray(entryIds) || entryIds.length === 0) {
|
||||
return NextResponse.json({ error: 'Keine Einträge übergeben' }, { status: 400 });
|
||||
}
|
||||
|
||||
await prisma.timeEntry.updateMany({
|
||||
where: { id: { in: entryIds } },
|
||||
data: {
|
||||
isBilled: true,
|
||||
billedAt: new Date()
|
||||
}
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Fehler beim Speichern' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// /opt/erp-system/app/api/cron/imap/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../../lib/prisma';
|
||||
import { ImapFlow } from 'imapflow';
|
||||
import { simpleParser } from 'mailparser';
|
||||
import { writeFile } from 'fs/promises';
|
||||
import { join } from 'path';
|
||||
|
||||
export const dynamic = 'force-dynamic';
|
||||
const UPLOAD_DIR = join(process.cwd(), 'uploads');
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const settings = await prisma.systemSettings.findFirst({ where: { id: 1 } });
|
||||
if (!settings || !settings.imapHost || !settings.imapUser || !settings.imapPass) {
|
||||
return NextResponse.json({ error: 'IMAP Zugangsdaten fehlen.' }, { status: 400 });
|
||||
}
|
||||
|
||||
const client = new ImapFlow({
|
||||
host: settings.imapHost,
|
||||
port: settings.imapPort,
|
||||
secure: settings.imapPort === 993,
|
||||
auth: { user: settings.imapUser, pass: settings.imapPass },
|
||||
logger: false
|
||||
});
|
||||
|
||||
await client.connect();
|
||||
let lock = await client.getMailboxLock('INBOX');
|
||||
let processedCounter = 0;
|
||||
|
||||
try {
|
||||
for await (let message of client.fetch({ seen: false }, { source: true, uid: true })) {
|
||||
const parsed = await simpleParser(message.source);
|
||||
|
||||
const fromEmail = parsed.from?.value[0]?.address;
|
||||
const fromName = parsed.from?.value[0]?.name || 'Unbekannt';
|
||||
const subject = parsed.subject || 'Kein Betreff';
|
||||
const textContent = parsed.text || parsed.textAsHtml || '(Kein Inhalt)';
|
||||
|
||||
if (!fromEmail) continue;
|
||||
|
||||
// 1. Kunden-Matching (Haupt-Email, alternative E-Mails oder Mitarbeiter)
|
||||
let targetCustomerId = null;
|
||||
|
||||
const directCustomer = await prisma.customer.findFirst({
|
||||
where: {
|
||||
OR: [
|
||||
{ email: fromEmail },
|
||||
{ additionalEmails: { has: fromEmail } }
|
||||
]
|
||||
}
|
||||
});
|
||||
|
||||
if (directCustomer) {
|
||||
targetCustomerId = directCustomer.id;
|
||||
} else {
|
||||
const contact = await prisma.customerContact.findFirst({
|
||||
where: { email: fromEmail }
|
||||
});
|
||||
if (contact) {
|
||||
targetCustomerId = contact.customerId;
|
||||
}
|
||||
}
|
||||
|
||||
// Falls komplett unbekannt, neuen Kunden anlegen
|
||||
if (!targetCustomerId) {
|
||||
const newCustomer = await prisma.customer.create({
|
||||
data: {
|
||||
email: fromEmail,
|
||||
firstName: fromName,
|
||||
lastName: '(Auto-Erfasst)',
|
||||
companyName: 'Aus E-Mail Anfrage'
|
||||
}
|
||||
});
|
||||
targetCustomerId = newCustomer.id;
|
||||
}
|
||||
|
||||
// 2. Ticket Zuordnung
|
||||
const ticketMatch = subject.match(/Ticket #(\d+)/i);
|
||||
let ticketId = ticketMatch ? parseInt(ticketMatch[1]) : null;
|
||||
let activeTicketId = null;
|
||||
|
||||
if (ticketId) {
|
||||
const existingTicket = await prisma.ticket.findUnique({ where: { id: ticketId } });
|
||||
if (existingTicket) {
|
||||
activeTicketId = existingTicket.id;
|
||||
await prisma.ticketMessage.create({
|
||||
data: { content: textContent, isFromCustomer: true, ticketId: existingTicket.id }
|
||||
});
|
||||
|
||||
if (existingTicket.status !== 'OPEN' && existingTicket.status !== 'IN_PROGRESS') {
|
||||
await prisma.ticket.update({ where: { id: existingTicket.id }, data: { status: 'OPEN' } });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!activeTicketId) {
|
||||
const newTicket = await prisma.ticket.create({
|
||||
data: { title: subject, description: textContent, customerId: targetCustomerId, status: 'OPEN' }
|
||||
});
|
||||
activeTicketId = newTicket.id;
|
||||
}
|
||||
|
||||
// 3. Dateianhänge verarbeiten
|
||||
if (parsed.attachments && parsed.attachments.length > 0) {
|
||||
for (const att of parsed.attachments) {
|
||||
// Buffer in Datei schreiben
|
||||
const safeOriginalName = (att.filename || 'unbekannt.dat').replace(/[^a-zA-Z0-9.-]/g, '_');
|
||||
const savedName = `${Date.now()}-${safeOriginalName}`;
|
||||
const filepath = join(UPLOAD_DIR, savedName);
|
||||
|
||||
await writeFile(filepath, att.content);
|
||||
|
||||
// DB Eintrag
|
||||
await prisma.attachment.create({
|
||||
data: {
|
||||
fileName: att.filename || 'unbekannt.dat',
|
||||
savedName: savedName,
|
||||
fileSize: att.size || 0,
|
||||
fileType: att.contentType || 'application/octet-stream',
|
||||
ticketId: activeTicketId
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await client.messageFlagsAdd(message.uid, ['\\Seen'], { uid: true });
|
||||
processedCounter++;
|
||||
}
|
||||
} finally {
|
||||
lock.release();
|
||||
}
|
||||
await client.logout();
|
||||
return NextResponse.json({ success: true, processedTickets: processedCounter });
|
||||
|
||||
} catch (error: any) {
|
||||
console.error('IMAP Error:', error);
|
||||
return NextResponse.json({ error: 'Verarbeitungsfehler', details: error.message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// /opt/erp-system/app/api/customers/[id]/contacts/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../../../lib/prisma';
|
||||
|
||||
export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const params = await context.params;
|
||||
const body = await request.json();
|
||||
|
||||
const contact = await prisma.customerContact.create({
|
||||
data: {
|
||||
firstName: body.firstName,
|
||||
lastName: body.lastName,
|
||||
email: body.email,
|
||||
phone: body.phone || null,
|
||||
customerId: parseInt(params.id)
|
||||
}
|
||||
});
|
||||
|
||||
return NextResponse.json(contact, { status: 201 });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Fehler beim Erstellen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const contactId = searchParams.get('contactId');
|
||||
|
||||
if (!contactId) return NextResponse.json({ error: 'Kontakt-ID fehlt' }, { status: 400 });
|
||||
|
||||
await prisma.customerContact.delete({
|
||||
where: { id: parseInt(contactId) }
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Löschen fehlgeschlagen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../../../lib/prisma';
|
||||
|
||||
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const params = await context.params;
|
||||
const contracts = await prisma.contract.findMany({
|
||||
where: { customerId: parseInt(params.id) },
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
return NextResponse.json(contracts);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const params = await context.params;
|
||||
const data = await request.json();
|
||||
|
||||
const contract = await prisma.contract.create({
|
||||
data: {
|
||||
customerId: parseInt(params.id),
|
||||
title: data.title,
|
||||
description: data.description || '',
|
||||
startDate: new Date(data.startDate),
|
||||
endDate: data.endDate ? new Date(data.endDate) : null,
|
||||
monthlyPrice: parseFloat(data.monthlyPrice) || 0,
|
||||
status: data.status || 'ACTIVE'
|
||||
}
|
||||
});
|
||||
|
||||
return NextResponse.json(contract);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Erstellen fehlgeschlagen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const contractId = searchParams.get('contractId');
|
||||
if (!contractId) return NextResponse.json({ error: 'ID fehlt' }, { status: 400 });
|
||||
|
||||
await prisma.contract.delete({
|
||||
where: { id: parseInt(contractId) }
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Löschen fehlgeschlagen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../../../lib/prisma';
|
||||
|
||||
export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const params = await context.params;
|
||||
const data = await request.json();
|
||||
|
||||
const credential = await prisma.customerCredential.create({
|
||||
data: {
|
||||
customerId: parseInt(params.id),
|
||||
title: data.title,
|
||||
username: data.username,
|
||||
password: data.password
|
||||
}
|
||||
});
|
||||
|
||||
return NextResponse.json(credential);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Erstellen fehlgeschlagen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const credId = searchParams.get('credId');
|
||||
if (!credId) return NextResponse.json({ error: 'ID fehlt' }, { status: 400 });
|
||||
|
||||
await prisma.customerCredential.delete({
|
||||
where: { id: parseInt(credId) }
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Löschen fehlgeschlagen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../../../lib/prisma';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
|
||||
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const params = await context.params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const downloadId = searchParams.get('download');
|
||||
|
||||
if (downloadId) {
|
||||
const doc = await prisma.customerDocument.findUnique({
|
||||
where: { id: parseInt(downloadId) }
|
||||
});
|
||||
if (!doc) return new NextResponse('Not found', { status: 404 });
|
||||
|
||||
const filePath = path.join(process.cwd(), 'uploads', 'customers', params.id, doc.savedName);
|
||||
const fileBuffer = await fs.readFile(filePath);
|
||||
|
||||
return new NextResponse(fileBuffer, {
|
||||
headers: {
|
||||
'Content-Type': doc.fileType,
|
||||
'Content-Disposition': `attachment; filename="${doc.fileName}"`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const documents = await prisma.customerDocument.findMany({
|
||||
where: { customerId: parseInt(params.id) },
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
return NextResponse.json(documents);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const params = await context.params;
|
||||
const formData = await request.formData();
|
||||
const file = formData.get('file') as File;
|
||||
if (!file) return NextResponse.json({ error: 'No file uploaded' }, { status: 400 });
|
||||
|
||||
const buffer = Buffer.from(await file.arrayBuffer());
|
||||
const savedName = `${Date.now()}_${file.name.replace(/[^a-zA-Z0-9.-]/g, '_')}`;
|
||||
const uploadDir = path.join(process.cwd(), 'uploads', 'customers', params.id);
|
||||
|
||||
await fs.mkdir(uploadDir, { recursive: true });
|
||||
await fs.writeFile(path.join(uploadDir, savedName), buffer);
|
||||
|
||||
const doc = await prisma.customerDocument.create({
|
||||
data: {
|
||||
customerId: parseInt(params.id),
|
||||
fileName: file.name,
|
||||
savedName: savedName,
|
||||
fileSize: file.size,
|
||||
fileType: file.type
|
||||
}
|
||||
});
|
||||
|
||||
return NextResponse.json(doc);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return NextResponse.json({ error: 'Upload fehlgeschlagen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const params = await context.params;
|
||||
const { searchParams } = new URL(request.url);
|
||||
const docId = searchParams.get('docId');
|
||||
if (!docId) return NextResponse.json({ error: 'ID fehlt' }, { status: 400 });
|
||||
|
||||
const doc = await prisma.customerDocument.findUnique({
|
||||
where: { id: parseInt(docId) }
|
||||
});
|
||||
|
||||
if (doc) {
|
||||
const filePath = path.join(process.cwd(), 'uploads', 'customers', params.id, doc.savedName);
|
||||
try {
|
||||
await fs.unlink(filePath);
|
||||
} catch(e) {
|
||||
// ignore if file doesn't exist
|
||||
}
|
||||
await prisma.customerDocument.delete({ where: { id: parseInt(docId) } });
|
||||
}
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Löschen fehlgeschlagen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// /opt/erp-system/app/api/customers/[id]/reset-password/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../../../lib/prisma';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { sendEmail } from '../../../../../lib/email';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../../../auth/[...nextauth]/route";
|
||||
|
||||
export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session || (session.user as any).userType !== 'TEAM') {
|
||||
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const params = await context.params;
|
||||
const customerId = parseInt(params.id);
|
||||
|
||||
const customer = await prisma.customer.findUnique({ where: { id: customerId } });
|
||||
if (!customer) return NextResponse.json({ error: 'Kunde nicht gefunden' }, { status: 404 });
|
||||
|
||||
const tempPassword = Math.random().toString(36).slice(-8);
|
||||
const hash = await bcrypt.hash(tempPassword, 10);
|
||||
|
||||
await prisma.customer.update({
|
||||
where: { id: customerId },
|
||||
data: { passwordHash: hash, forcePasswordChange: true }
|
||||
});
|
||||
|
||||
await sendEmail({
|
||||
to: customer.email,
|
||||
subject: "Ihr Passwort wurde zurückgesetzt",
|
||||
text: `Hallo ${customer.firstName},\n\nIhr Passwort für das Kundenportal wurde durch unseren Support zurückgesetzt.\n\nIhr neues Start-Passwort lautet: ${tempPassword}\n\nBitte loggen Sie sich ein. Sie werden aufgefordert, sofort ein neues, eigenes Passwort zu vergeben.\n\nViele Grüße\nIhr Support-Team`
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Fehler beim Reset' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
// /opt/erp-system/app/api/customers/[id]/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../../lib/prisma';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||
|
||||
async function getPerms() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return null;
|
||||
return (session.user as any)?.permissions || [];
|
||||
}
|
||||
|
||||
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
const perms = await getPerms();
|
||||
if (!perms) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
|
||||
|
||||
try {
|
||||
const params = await context.params;
|
||||
const customer = await prisma.customer.findUnique({
|
||||
where: { id: parseInt(params.id) },
|
||||
include: {
|
||||
contacts: { orderBy: { createdAt: 'desc' } },
|
||||
tickets: { orderBy: { createdAt: 'desc' } },
|
||||
contracts: { orderBy: { createdAt: 'desc' } },
|
||||
documents: { orderBy: { createdAt: 'desc' } },
|
||||
credentials: { orderBy: { createdAt: 'desc' } }
|
||||
}
|
||||
});
|
||||
|
||||
if (!customer) return NextResponse.json({ error: 'Nicht gefunden' }, { status: 404 });
|
||||
return NextResponse.json(customer);
|
||||
} catch (error) {
|
||||
console.error('Customer GET Error:', error);
|
||||
return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
const perms = await getPerms();
|
||||
if (!perms || (!perms.includes('CUSTOMERS_MANAGE') && !perms.includes('CUSTOMERS_EDIT'))) {
|
||||
return NextResponse.json({ error: 'Keine Berechtigung zum Bearbeiten von Kundendaten' }, { status: 403 });
|
||||
}
|
||||
|
||||
try {
|
||||
const params = await context.params;
|
||||
const body = await request.json();
|
||||
|
||||
const updateData: any = {
|
||||
companyName: body.companyName,
|
||||
firstName: body.firstName,
|
||||
lastName: body.lastName,
|
||||
email: body.email,
|
||||
phone: body.phone,
|
||||
address: body.address,
|
||||
zipCode: body.zipCode,
|
||||
city: body.city,
|
||||
additionalEmails: body.additionalEmails || [],
|
||||
};
|
||||
|
||||
// Nur ein neues Passwort hashen und speichern, wenn das Feld ausgefüllt wurde
|
||||
if (body.password && body.password.trim() !== '') {
|
||||
updateData.passwordHash = await bcrypt.hash(body.password, 10);
|
||||
}
|
||||
|
||||
const customer = await prisma.customer.update({
|
||||
where: { id: parseInt(params.id) },
|
||||
data: updateData,
|
||||
include: { contacts: true }
|
||||
});
|
||||
|
||||
return NextResponse.json(customer);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return NextResponse.json({ error: 'Update fehlgeschlagen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
// /opt/erp-system/app/api/customers/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../lib/prisma';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { sendEmail } from '../../../lib/email';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../auth/[...nextauth]/route";
|
||||
|
||||
export async function GET() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
|
||||
|
||||
const customers = await prisma.customer.findMany({ orderBy: { companyName: 'asc' } });
|
||||
return NextResponse.json(customers);
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
|
||||
// 1. Zufälliges Start-Passwort generieren (8 Zeichen)
|
||||
const tempPassword = Math.random().toString(36).slice(-8);
|
||||
const hash = await bcrypt.hash(tempPassword, 10);
|
||||
|
||||
// 2. Kunde anlegen
|
||||
const customer = await prisma.customer.create({
|
||||
data: {
|
||||
companyName: body.companyName,
|
||||
firstName: body.firstName,
|
||||
lastName: body.lastName,
|
||||
email: body.email,
|
||||
phone: body.phone,
|
||||
passwordHash: hash,
|
||||
forcePasswordChange: true // Muss beim ersten Login geändert werden
|
||||
}
|
||||
});
|
||||
|
||||
// 3. Willkommens-E-Mail senden
|
||||
await sendEmail({
|
||||
to: customer.email,
|
||||
subject: "Willkommen im Kundenportal",
|
||||
text: `Hallo ${customer.firstName} ${customer.lastName},\n\nIhr Kundenkonto wurde erfolgreich eingerichtet.\n\nIhre Zugangsdaten lauten:\nLogin: ${customer.email}\nPasswort: ${tempPassword}\n\nBitte loggen Sie sich in unser Portal ein. Sie werden nach dem ersten Login aufgefordert, ein eigenes Passwort zu vergeben.\n\nViele Grüße\nIhr Support-Team`
|
||||
});
|
||||
|
||||
return NextResponse.json(customer, { status: 201 });
|
||||
} catch (error: any) {
|
||||
console.error(error);
|
||||
return NextResponse.json({ error: 'Fehler beim Erstellen des Kunden' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const perms = (session?.user as any)?.permissions || [];
|
||||
if (!perms.includes('DATA_DELETE')) return NextResponse.json({ error: 'Keine Löschberechtigung' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const id = searchParams.get('id');
|
||||
if (!id) return NextResponse.json({ error: 'ID fehlt' }, { status: 400 });
|
||||
|
||||
const customerId = parseInt(id);
|
||||
|
||||
// Delete all related data first (non-cascading relations)
|
||||
await prisma.ticketMessage.deleteMany({ where: { ticket: { customerId } } });
|
||||
await prisma.ticketNote.deleteMany({ where: { ticket: { customerId } } });
|
||||
await prisma.timeEntry.deleteMany({ where: { ticket: { customerId } } });
|
||||
await prisma.ticketSurvey.deleteMany({ where: { ticket: { customerId } } });
|
||||
await prisma.attachment.deleteMany({ where: { ticket: { customerId } } });
|
||||
await prisma.ticket.deleteMany({ where: { customerId } });
|
||||
|
||||
// Cascading relations (contacts, contracts, documents, credentials) are handled by onDelete: Cascade
|
||||
await prisma.customer.delete({ where: { id: customerId } });
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return NextResponse.json({ error: 'Löschen fehlgeschlagen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../../lib/prisma';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return NextResponse.json([], { status: 401 });
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const q = searchParams.get('q')?.trim();
|
||||
if (!q || q.length < 2) return NextResponse.json([]);
|
||||
|
||||
const customers = await prisma.customer.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ companyName: { contains: q, mode: 'insensitive' } },
|
||||
{ firstName: { contains: q, mode: 'insensitive' } },
|
||||
{ lastName: { contains: q, mode: 'insensitive' } },
|
||||
{ email: { contains: q, mode: 'insensitive' } },
|
||||
]
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
companyName: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
email: true,
|
||||
},
|
||||
take: 8,
|
||||
orderBy: { companyName: 'asc' }
|
||||
});
|
||||
|
||||
return NextResponse.json(customers);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
// /opt/erp-system/app/api/dashboard/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../lib/prisma';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../auth/[...nextauth]/route";
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
|
||||
|
||||
const userId = parseInt((session.user as any).id);
|
||||
const userType = (session.user as any).userType;
|
||||
|
||||
// ----------------------------------------------------
|
||||
// METRIKEN FÜR KUNDEN
|
||||
// ----------------------------------------------------
|
||||
if (userType === 'CUSTOMER') {
|
||||
const [openTicketsCount, closedTicketsCount, recentTickets] = await Promise.all([
|
||||
prisma.ticket.count({
|
||||
where: { customerId: userId, status: { in: ['OPEN', 'IN_PROGRESS', 'WAITING_FOR_CUSTOMER'] } }
|
||||
}),
|
||||
prisma.ticket.count({
|
||||
where: { customerId: userId, status: { in: ['RESOLVED', 'CLOSED'] } }
|
||||
}),
|
||||
prisma.ticket.findMany({
|
||||
where: { customerId: userId },
|
||||
take: 5,
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
include: { customer: { select: { companyName: true, firstName: true, lastName: true } } }
|
||||
})
|
||||
]);
|
||||
|
||||
return NextResponse.json({
|
||||
userType: 'CUSTOMER',
|
||||
openTickets: openTicketsCount,
|
||||
closedTickets: closedTicketsCount,
|
||||
recentTickets
|
||||
});
|
||||
}
|
||||
|
||||
// ----------------------------------------------------
|
||||
// METRIKEN FÜR TEAM-MITARBEITER
|
||||
// ----------------------------------------------------
|
||||
const [openTicketsCount, myTicketsCount, recentTickets, timeEntries] = await Promise.all([
|
||||
prisma.ticket.count({
|
||||
where: { status: { in: ['OPEN', 'IN_PROGRESS', 'WAITING_FOR_CUSTOMER'] } }
|
||||
}),
|
||||
prisma.ticket.count({
|
||||
where: { assignedToId: userId, status: { in: ['OPEN', 'IN_PROGRESS', 'WAITING_FOR_CUSTOMER'] } }
|
||||
}),
|
||||
prisma.ticket.findMany({
|
||||
take: 5,
|
||||
orderBy: { updatedAt: 'desc' },
|
||||
include: { customer: { select: { companyName: true, firstName: true, lastName: true } } }
|
||||
}),
|
||||
prisma.timeEntry.aggregate({
|
||||
_sum: { durationMins: true }
|
||||
})
|
||||
]);
|
||||
|
||||
const totalMinutes = timeEntries._sum.durationMins || 0;
|
||||
const totalHours = totalMinutes / 60;
|
||||
|
||||
return NextResponse.json({
|
||||
userType: 'TEAM',
|
||||
openTickets: openTicketsCount,
|
||||
myTickets: myTicketsCount,
|
||||
recentTickets,
|
||||
totalHours
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error("Dashboard Fehler:", error);
|
||||
return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// /opt/erp-system/app/api/portal/password/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../../lib/prisma';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session || (session.user as any).userType !== 'CUSTOMER') {
|
||||
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
if (!body.password || body.password.length < 6) {
|
||||
return NextResponse.json({ error: 'Passwort zu kurz' }, { status: 400 });
|
||||
}
|
||||
|
||||
const hash = await bcrypt.hash(body.password, 10);
|
||||
const customerId = parseInt((session.user as any).id);
|
||||
|
||||
await prisma.customer.update({
|
||||
where: { id: customerId },
|
||||
data: { passwordHash: hash, forcePasswordChange: false }
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Fehler beim Speichern' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { readFile } from 'fs/promises';
|
||||
import path from 'path';
|
||||
|
||||
export async function GET(request: Request, context: { params: Promise<{ name: string }> }) {
|
||||
try {
|
||||
const { name } = await context.params;
|
||||
const filePath = path.join(process.cwd(), 'uploads', 'products', name);
|
||||
const buffer = await readFile(filePath);
|
||||
const ext = name.split('.').pop()?.toLowerCase();
|
||||
const contentType = ext === 'png' ? 'image/png' : ext === 'webp' ? 'image/webp' : ext === 'gif' ? 'image/gif' : 'image/jpeg';
|
||||
return new NextResponse(buffer, { headers: { 'Content-Type': contentType, 'Cache-Control': 'public, max-age=86400' } });
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Bild nicht gefunden' }, { status: 404 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../lib/prisma';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../auth/[...nextauth]/route";
|
||||
import { writeFile, mkdir } from 'fs/promises';
|
||||
import path from 'path';
|
||||
|
||||
async function checkPerm(perm: string) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const perms = (session?.user as any)?.permissions || [];
|
||||
return perms.includes(perm);
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const products = await prisma.product.findMany({ orderBy: { name: 'asc' } });
|
||||
return NextResponse.json(products);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (!await checkPerm('PURCHASING_MANAGE')) return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
const name = formData.get('name') as string;
|
||||
const description = formData.get('description') as string || '';
|
||||
const sku = formData.get('sku') as string || null;
|
||||
const purchasePrice = parseFloat(formData.get('purchasePrice') as string || '0');
|
||||
const salePrice = parseFloat(formData.get('salePrice') as string || '0');
|
||||
const stock = parseInt(formData.get('stock') as string || '0');
|
||||
const unit = formData.get('unit') as string || 'Stk';
|
||||
const category = formData.get('category') as string || null;
|
||||
const trackStock = formData.get('trackStock') !== 'false';
|
||||
const image = formData.get('image') as File | null;
|
||||
|
||||
let imagePath = null;
|
||||
if (image && image.size > 0) {
|
||||
const uploadDir = path.join(process.cwd(), 'uploads', 'products');
|
||||
await mkdir(uploadDir, { recursive: true });
|
||||
const ext = image.name.split('.').pop();
|
||||
const savedName = `prod_${Date.now()}.${ext}`;
|
||||
const buffer = Buffer.from(await image.arrayBuffer());
|
||||
await writeFile(path.join(uploadDir, savedName), buffer);
|
||||
imagePath = `/api/products/image/${savedName}`;
|
||||
}
|
||||
|
||||
const product = await prisma.product.create({
|
||||
data: { name, description, sku, purchasePrice, salePrice, stock, unit, category, trackStock, imagePath }
|
||||
});
|
||||
|
||||
return NextResponse.json(product, { status: 201 });
|
||||
} catch (error: any) {
|
||||
if (error.code === 'P2002') return NextResponse.json({ error: 'Artikelnummer existiert bereits' }, { status: 400 });
|
||||
console.error(error);
|
||||
return NextResponse.json({ error: 'Fehler beim Erstellen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
if (!await checkPerm('PURCHASING_MANAGE')) return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
const id = parseInt(formData.get('id') as string);
|
||||
const data: any = {
|
||||
name: formData.get('name') as string,
|
||||
description: formData.get('description') as string || '',
|
||||
sku: formData.get('sku') as string || null,
|
||||
purchasePrice: parseFloat(formData.get('purchasePrice') as string || '0'),
|
||||
salePrice: parseFloat(formData.get('salePrice') as string || '0'),
|
||||
stock: parseInt(formData.get('stock') as string || '0'),
|
||||
unit: formData.get('unit') as string || 'Stk',
|
||||
category: formData.get('category') as string || null,
|
||||
active: formData.get('active') === 'true',
|
||||
trackStock: formData.get('trackStock') !== 'false',
|
||||
};
|
||||
|
||||
const image = formData.get('image') as File | null;
|
||||
if (image && image.size > 0) {
|
||||
const uploadDir = path.join(process.cwd(), 'uploads', 'products');
|
||||
await mkdir(uploadDir, { recursive: true });
|
||||
const ext = image.name.split('.').pop();
|
||||
const savedName = `prod_${Date.now()}.${ext}`;
|
||||
const buffer = Buffer.from(await image.arrayBuffer());
|
||||
await writeFile(path.join(uploadDir, savedName), buffer);
|
||||
data.imagePath = `/api/products/image/${savedName}`;
|
||||
}
|
||||
|
||||
const product = await prisma.product.update({ where: { id }, data });
|
||||
return NextResponse.json(product);
|
||||
} catch (error: any) {
|
||||
if (error.code === 'P2002') return NextResponse.json({ error: 'Artikelnummer existiert bereits' }, { status: 400 });
|
||||
console.error(error);
|
||||
return NextResponse.json({ error: 'Fehler beim Aktualisieren' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
if (!await checkPerm('PURCHASING_MANAGE')) return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 });
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const id = parseInt(searchParams.get('id') || '0');
|
||||
await prisma.product.delete({ where: { id } });
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Löschen fehlgeschlagen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
// /opt/erp-system/app/api/roles/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../lib/prisma';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../auth/[...nextauth]/route";
|
||||
|
||||
async function checkAccess() {
|
||||
const session = await getServerSession(authOptions);
|
||||
const perms = (session?.user as any)?.permissions || [];
|
||||
return perms.includes('TEAM_MANAGE');
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
if (!await checkAccess()) return NextResponse.json({ error: 'Access denied' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const roles = await prisma.role.findMany({
|
||||
include: { _count: { select: { users: true } } },
|
||||
orderBy: { id: 'asc' }
|
||||
});
|
||||
return NextResponse.json(roles);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Fehler beim Laden' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (!await checkAccess()) return NextResponse.json({ error: 'Access denied' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const newRole = await prisma.role.create({
|
||||
data: { name: body.name, permissions: body.permissions }
|
||||
});
|
||||
return NextResponse.json(newRole, { status: 201 });
|
||||
} catch (error: any) {
|
||||
if (error.code === 'P2002') return NextResponse.json({ error: 'Rollenname existiert bereits.' }, { status: 400 });
|
||||
return NextResponse.json({ error: 'Fehler beim Speichern' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
if (!await checkAccess()) return NextResponse.json({ error: 'Access denied' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const updatedRole = await prisma.role.update({
|
||||
where: { id: body.id },
|
||||
data: { name: body.name, permissions: body.permissions }
|
||||
});
|
||||
return NextResponse.json(updatedRole, { status: 200 });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Fehler beim Speichern' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const perms = (session?.user as any)?.permissions || [];
|
||||
if (!perms.includes('DATA_DELETE')) return NextResponse.json({ error: 'Keine Löschberechtigung' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const id = searchParams.get('id');
|
||||
if (!id) return NextResponse.json({ error: 'ID fehlt' }, { status: 400 });
|
||||
|
||||
const roleId = parseInt(id);
|
||||
|
||||
// Check if users are still assigned
|
||||
const usersWithRole = await prisma.user.count({ where: { roleId } });
|
||||
if (usersWithRole > 0) {
|
||||
return NextResponse.json({ error: `Diese Gruppe ist noch ${usersWithRole} Nutzer(n) zugeordnet. Bitte weise sie zuerst einer anderen Gruppe zu.` }, { status: 400 });
|
||||
}
|
||||
|
||||
await prisma.role.delete({ where: { id: roleId } });
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return NextResponse.json({ error: 'Löschen fehlgeschlagen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../../lib/prisma';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||
|
||||
const PREFIXES: Record<string, string> = {
|
||||
QUOTE: 'ANG', ORDER_CONFIRMATION: 'AB', DELIVERY_NOTE: 'LS', INVOICE: 'RE', CREDIT_NOTE: 'RK'
|
||||
};
|
||||
const NUMBER_FIELDS: Record<string, string> = {
|
||||
QUOTE: 'nextQuoteNumber', ORDER_CONFIRMATION: 'nextOrderNumber',
|
||||
DELIVERY_NOTE: 'nextDeliveryNumber', INVOICE: 'nextInvoiceNumber', CREDIT_NOTE: 'nextCreditNoteNumber'
|
||||
};
|
||||
|
||||
async function generateNumber(type: string) {
|
||||
const settings = await prisma.systemSettings.findFirst();
|
||||
if (!settings) throw new Error('SystemSettings not found');
|
||||
const year = new Date().getFullYear();
|
||||
const prefix = PREFIXES[type] || 'DOC';
|
||||
const field = NUMBER_FIELDS[type];
|
||||
const num = (settings as any)[field] || 1;
|
||||
await prisma.systemSettings.update({ where: { id: settings.id }, data: { [field]: num + 1 } });
|
||||
return `${prefix}-${year}-${num.toString().padStart(4, '0')}`;
|
||||
}
|
||||
|
||||
// Set status to ARCHIVED while preserving original status in previousStatus
|
||||
async function archiveDoc(docId: number) {
|
||||
const doc = await prisma.salesDocument.findUnique({ where: { id: docId }, select: { status: true } });
|
||||
if (!doc || doc.status === 'ARCHIVED' || doc.status === 'CANCELLED') return;
|
||||
await prisma.salesDocument.update({
|
||||
where: { id: docId },
|
||||
data: { previousStatus: doc.status, status: 'ARCHIVED' }
|
||||
});
|
||||
}
|
||||
|
||||
// Walk the chain back via sourceDocumentId and collect all related doc IDs
|
||||
async function getChainIds(docId: number): Promise<number[]> {
|
||||
const ids: number[] = [];
|
||||
let currentId: number | null = docId;
|
||||
while (currentId) {
|
||||
const doc = await prisma.salesDocument.findUnique({ where: { id: currentId }, select: { sourceDocumentId: true } });
|
||||
if (doc?.sourceDocumentId) {
|
||||
ids.push(doc.sourceDocumentId);
|
||||
currentId = doc.sourceDocumentId;
|
||||
} else {
|
||||
currentId = null;
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const { id } = await context.params;
|
||||
const doc = await prisma.salesDocument.findUnique({
|
||||
where: { id: parseInt(id) },
|
||||
include: {
|
||||
customer: true,
|
||||
items: { include: { product: true } },
|
||||
createdBy: { select: { firstName: true, lastName: true } }
|
||||
}
|
||||
});
|
||||
if (!doc) return NextResponse.json({ error: 'Nicht gefunden' }, { status: 404 });
|
||||
return NextResponse.json(doc);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const perms = (session?.user as any)?.permissions || [];
|
||||
if (!perms.includes('SALES_MANAGE')) return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const { id } = await context.params;
|
||||
const body = await request.json();
|
||||
const docId = parseInt(id);
|
||||
|
||||
// Handle signature (not for invoices/credit notes)
|
||||
if (body.signatureData) {
|
||||
const doc = await prisma.salesDocument.findUnique({ where: { id: docId } });
|
||||
if (doc?.type === 'INVOICE' || doc?.type === 'CREDIT_NOTE') {
|
||||
return NextResponse.json({ error: 'Kann nicht unterschrieben werden' }, { status: 400 });
|
||||
}
|
||||
const updated = await prisma.salesDocument.update({
|
||||
where: { id: docId },
|
||||
data: { signatureData: body.signatureData, signedAt: new Date(), status: 'ACCEPTED' }
|
||||
});
|
||||
return NextResponse.json(updated);
|
||||
}
|
||||
|
||||
// Handle "create follow-up document" action
|
||||
if (body.action === 'CREATE_FOLLOWUP') {
|
||||
const doc = await prisma.salesDocument.findUnique({ where: { id: docId }, include: { items: true } });
|
||||
if (!doc) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
let newType = '';
|
||||
if (doc.type === 'ORDER_CONFIRMATION') newType = 'DELIVERY_NOTE';
|
||||
else if (doc.type === 'DELIVERY_NOTE') newType = 'INVOICE';
|
||||
else if (doc.type === 'INVOICE') newType = 'CREDIT_NOTE';
|
||||
else return NextResponse.json({ error: 'Kein Folgebeleg möglich' }, { status: 400 });
|
||||
|
||||
const number = await generateNumber(newType);
|
||||
const followUp = await prisma.salesDocument.create({
|
||||
data: {
|
||||
type: newType as any,
|
||||
number,
|
||||
customerId: doc.customerId,
|
||||
createdById: (session?.user as any)?.id || null,
|
||||
sourceDocumentId: doc.id,
|
||||
subtotal: doc.subtotal, taxAmount: doc.taxAmount, total: doc.total,
|
||||
notes: newType === 'CREDIT_NOTE' ? `Rechnungskorrektur zu ${doc.number}` : doc.notes,
|
||||
items: {
|
||||
create: doc.items.map(i => ({
|
||||
description: i.description, quantity: i.quantity, unitPrice: i.unitPrice,
|
||||
taxRate: i.taxRate, total: i.total, productId: i.productId
|
||||
}))
|
||||
}
|
||||
},
|
||||
include: { items: true }
|
||||
});
|
||||
|
||||
// CREDIT_NOTE → cancel the original invoice
|
||||
if (newType === 'CREDIT_NOTE') {
|
||||
await prisma.salesDocument.update({
|
||||
where: { id: doc.id },
|
||||
data: { previousStatus: doc.status, status: 'CANCELLED' }
|
||||
});
|
||||
} else {
|
||||
// Archive the source document
|
||||
await archiveDoc(doc.id);
|
||||
}
|
||||
|
||||
// If creating an INVOICE → also archive all earlier docs in the chain
|
||||
if (newType === 'INVOICE') {
|
||||
const chainIds = await getChainIds(followUp.id);
|
||||
for (const cid of chainIds) { await archiveDoc(cid); }
|
||||
}
|
||||
|
||||
return NextResponse.json(followUp, { status: 201 });
|
||||
}
|
||||
|
||||
// Handle status changes
|
||||
if (body.status) {
|
||||
const doc = await prisma.salesDocument.findUnique({
|
||||
where: { id: docId },
|
||||
include: { items: { include: { product: true } } }
|
||||
});
|
||||
if (!doc) return NextResponse.json({ error: 'Not found' }, { status: 404 });
|
||||
|
||||
// QUOTE accepted → reserve stock + auto-create AB (SENT) + archive quote
|
||||
if (doc.type === 'QUOTE' && body.status === 'ACCEPTED') {
|
||||
for (const item of doc.items) {
|
||||
if (item.productId && item.product?.trackStock) {
|
||||
await prisma.product.update({
|
||||
where: { id: item.productId },
|
||||
data: { reservedStock: { increment: Math.ceil(item.quantity) } }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-create AB with status SENT
|
||||
const abNumber = await generateNumber('ORDER_CONFIRMATION');
|
||||
const ab = await prisma.salesDocument.create({
|
||||
data: {
|
||||
type: 'ORDER_CONFIRMATION',
|
||||
number: abNumber,
|
||||
status: 'SENT',
|
||||
customerId: doc.customerId,
|
||||
createdById: (session?.user as any)?.id || null,
|
||||
sourceDocumentId: doc.id,
|
||||
subtotal: doc.subtotal, taxAmount: doc.taxAmount, total: doc.total,
|
||||
notes: doc.notes,
|
||||
items: {
|
||||
create: doc.items.map(i => ({
|
||||
description: i.description, quantity: i.quantity, unitPrice: i.unitPrice,
|
||||
taxRate: i.taxRate, total: i.total, productId: i.productId
|
||||
}))
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Archive the quote (preserving ACCEPTED as previousStatus)
|
||||
await prisma.salesDocument.update({
|
||||
where: { id: docId },
|
||||
data: { previousStatus: 'ACCEPTED', status: 'ARCHIVED' }
|
||||
});
|
||||
|
||||
return NextResponse.json({ ...doc, status: 'ARCHIVED', followUpId: ab.id, followUpNumber: ab.number });
|
||||
}
|
||||
|
||||
// DELIVERY_NOTE delivered → reduce stock
|
||||
if (doc.type === 'DELIVERY_NOTE' && body.status === 'DELIVERED') {
|
||||
for (const item of doc.items) {
|
||||
if (item.productId && item.product?.trackStock) {
|
||||
await prisma.product.update({
|
||||
where: { id: item.productId },
|
||||
data: {
|
||||
stock: { decrement: Math.ceil(item.quantity) },
|
||||
reservedStock: { decrement: Math.ceil(item.quantity) }
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// INVOICE paid → mark as paid then archive
|
||||
if (doc.type === 'INVOICE' && body.status === 'PAID') {
|
||||
await prisma.salesDocument.update({
|
||||
where: { id: docId },
|
||||
data: { previousStatus: 'PAID', status: 'ARCHIVED' }
|
||||
});
|
||||
return NextResponse.json({ ...doc, status: 'ARCHIVED', previousStatus: 'PAID' });
|
||||
}
|
||||
}
|
||||
|
||||
const updated = await prisma.salesDocument.update({
|
||||
where: { id: docId },
|
||||
data: {
|
||||
status: body.status || undefined,
|
||||
notes: body.notes !== undefined ? body.notes : undefined,
|
||||
},
|
||||
include: { items: true, customer: true }
|
||||
});
|
||||
|
||||
return NextResponse.json(updated);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return NextResponse.json({ error: 'Fehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../lib/prisma';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../auth/[...nextauth]/route";
|
||||
|
||||
async function getSession() {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return null;
|
||||
return session;
|
||||
}
|
||||
|
||||
const PREFIXES: Record<string, string> = {
|
||||
QUOTE: 'ANG', ORDER_CONFIRMATION: 'AB', DELIVERY_NOTE: 'LS', INVOICE: 'RE', CREDIT_NOTE: 'RK'
|
||||
};
|
||||
const NUMBER_FIELDS: Record<string, string> = {
|
||||
QUOTE: 'nextQuoteNumber', ORDER_CONFIRMATION: 'nextOrderNumber',
|
||||
DELIVERY_NOTE: 'nextDeliveryNumber', INVOICE: 'nextInvoiceNumber', CREDIT_NOTE: 'nextCreditNoteNumber'
|
||||
};
|
||||
|
||||
async function generateNumber(type: string) {
|
||||
const settings = await prisma.systemSettings.findFirst();
|
||||
if (!settings) throw new Error('SystemSettings not found');
|
||||
const year = new Date().getFullYear();
|
||||
const prefix = PREFIXES[type] || 'DOC';
|
||||
const field = NUMBER_FIELDS[type];
|
||||
const num = (settings as any)[field] || 1;
|
||||
await prisma.systemSettings.update({ where: { id: settings.id }, data: { [field]: num + 1 } });
|
||||
return `${prefix}-${year}-${num.toString().padStart(4, '0')}`;
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const session = await getSession();
|
||||
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
||||
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const customerId = searchParams.get('customerId');
|
||||
|
||||
const where = customerId ? { customerId: parseInt(customerId) } : {};
|
||||
const docs = await prisma.salesDocument.findMany({
|
||||
where,
|
||||
include: {
|
||||
customer: { select: { companyName: true, firstName: true, lastName: true } },
|
||||
items: { include: { product: { select: { name: true } } } },
|
||||
createdBy: { select: { firstName: true, lastName: true } }
|
||||
},
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
return NextResponse.json(docs);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const session = await getSession();
|
||||
const perms = (session?.user as any)?.permissions || [];
|
||||
if (!perms.includes('SALES_MANAGE')) return NextResponse.json({ error: 'Keine Berechtigung' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const number = await generateNumber(body.type);
|
||||
|
||||
// Auto-set validity for quotes
|
||||
let validUntil = body.validUntil ? new Date(body.validUntil) : null;
|
||||
if (body.type === 'QUOTE' && !validUntil) {
|
||||
const settings = await prisma.systemSettings.findFirst();
|
||||
if (settings?.defaultQuoteValidityDays) {
|
||||
validUntil = new Date();
|
||||
validUntil.setDate(validUntil.getDate() + settings.defaultQuoteValidityDays);
|
||||
}
|
||||
}
|
||||
// Calculate totals
|
||||
let subtotal = 0;
|
||||
const items = (body.items || []).map((item: any) => {
|
||||
const total = item.quantity * item.unitPrice;
|
||||
subtotal += total;
|
||||
return { ...item, total, taxRate: 19 };
|
||||
});
|
||||
const taxAmount = subtotal * 0.19;
|
||||
const total = subtotal + taxAmount;
|
||||
|
||||
const doc = await prisma.salesDocument.create({
|
||||
data: {
|
||||
type: body.type,
|
||||
number,
|
||||
customerId: body.customerId,
|
||||
createdById: (session?.user as any)?.id || null,
|
||||
notes: body.notes || null,
|
||||
validUntil,
|
||||
subtotal, taxAmount, total,
|
||||
items: { create: items.map((i: any) => ({ description: i.description, quantity: i.quantity, unitPrice: i.unitPrice, taxRate: i.taxRate, total: i.total, productId: i.productId || null })) }
|
||||
},
|
||||
include: { items: true, customer: true }
|
||||
});
|
||||
|
||||
return NextResponse.json(doc, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return NextResponse.json({ error: 'Fehler beim Erstellen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// /opt/erp-system/app/api/search/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../lib/prisma';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../auth/[...nextauth]/route";
|
||||
|
||||
export async function GET(request: Request) {
|
||||
const session = await getServerSession(authOptions);
|
||||
|
||||
// Nur Team-Mitglieder dürfen die globale Suche nutzen
|
||||
if (!session || (session.user as any).userType !== 'TEAM') {
|
||||
return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const q = searchParams.get('q');
|
||||
|
||||
if (!q || q.length < 2) {
|
||||
return NextResponse.json({ tickets: [], customers: [] });
|
||||
}
|
||||
|
||||
// Prüfen, ob nach einer exakten Ticket-ID gesucht wird (z.B. "12")
|
||||
const isNumber = !isNaN(Number(q));
|
||||
|
||||
try {
|
||||
const [tickets, customers] = await Promise.all([
|
||||
prisma.ticket.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
isNumber ? { id: Number(q) } : {},
|
||||
{ title: { contains: q, mode: 'insensitive' } },
|
||||
{ description: { contains: q, mode: 'insensitive' } }
|
||||
].filter(condition => Object.keys(condition).length > 0)
|
||||
},
|
||||
take: 20, // Begrenzung für Performance
|
||||
include: { customer: { select: { firstName: true, lastName: true, companyName: true } } }
|
||||
}),
|
||||
prisma.customer.findMany({
|
||||
where: {
|
||||
OR: [
|
||||
{ firstName: { contains: q, mode: 'insensitive' } },
|
||||
{ lastName: { contains: q, mode: 'insensitive' } },
|
||||
{ companyName: { contains: q, mode: 'insensitive' } },
|
||||
{ email: { contains: q, mode: 'insensitive' } }
|
||||
]
|
||||
},
|
||||
take: 20
|
||||
})
|
||||
]);
|
||||
|
||||
return NextResponse.json({ tickets, customers });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Fehler bei der Suche' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// /opt/erp-system/app/api/settings/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../lib/prisma';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../auth/[...nextauth]/route";
|
||||
|
||||
async function checkAccess() {
|
||||
const session = await getServerSession(authOptions);
|
||||
const perms = (session?.user as any)?.permissions || [];
|
||||
return perms.includes('SYSTEM_SETTINGS');
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
let settings = await prisma.systemSettings.findFirst({ where: { id: 1 } });
|
||||
if (!settings) {
|
||||
settings = await prisma.systemSettings.create({ data: { id: 1 } });
|
||||
}
|
||||
|
||||
// Passwörter nicht ans Frontend senden
|
||||
const { smtpPass, imapPass, ...safeSettings } = settings;
|
||||
|
||||
return NextResponse.json({
|
||||
...safeSettings,
|
||||
hasSmtpPass: !!smtpPass,
|
||||
hasImapPass: !!imapPass
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
if (!await checkAccess()) return NextResponse.json({ error: 'Verweigert' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
|
||||
const updateData: any = {
|
||||
hourlyRate: parseFloat(body.hourlyRate),
|
||||
taxRate: parseFloat(body.taxRate),
|
||||
companyName: body.companyName,
|
||||
companyInfo: body.companyInfo,
|
||||
smtpHost: body.smtpHost,
|
||||
smtpPort: parseInt(body.smtpPort) || 587,
|
||||
smtpUser: body.smtpUser,
|
||||
smtpFrom: body.smtpFrom,
|
||||
imapHost: body.imapHost,
|
||||
imapPort: parseInt(body.imapPort) || 993,
|
||||
imapUser: body.imapUser,
|
||||
};
|
||||
|
||||
if (body.smtpPass && body.smtpPass.trim() !== '') updateData.smtpPass = body.smtpPass;
|
||||
if (body.imapPass && body.imapPass.trim() !== '') updateData.imapPass = body.imapPass;
|
||||
|
||||
const updated = await prisma.systemSettings.upsert({
|
||||
where: { id: 1 },
|
||||
update: updateData,
|
||||
create: { id: 1, ...updateData }
|
||||
});
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return NextResponse.json({ error: 'Update-Fehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// /opt/erp-system/app/api/setup-customer/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../lib/prisma';
|
||||
import bcrypt from 'bcryptjs';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const customer = await prisma.customer.findFirst({ orderBy: { id: 'asc' } });
|
||||
|
||||
if (!customer) {
|
||||
return NextResponse.json({ error: 'Kein Kunde im System gefunden.' }, { status: 404 });
|
||||
}
|
||||
|
||||
const hash = await bcrypt.hash('portal123', 10);
|
||||
|
||||
await prisma.customer.update({
|
||||
where: { id: customer.id },
|
||||
data: { passwordHash: hash }
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `Passwort für Kunde ${customer.email} (ID: ${customer.id}) erfolgreich auf 'portal123' gesetzt.`
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Fehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// /opt/erp-system/app/api/setup/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../lib/prisma';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
// 1. Sicherestellen, dass die Admin-Rolle existiert und alle Rechte hat
|
||||
const adminRole = await prisma.role.upsert({
|
||||
where: { name: 'Administrator' },
|
||||
update: {
|
||||
permissions: ['TICKETS_VIEW', 'TICKETS_EDIT', 'CUSTOMERS_MANAGE', 'TEAM_MANAGE', 'SYSTEM_SETTINGS']
|
||||
},
|
||||
create: {
|
||||
name: 'Administrator',
|
||||
permissions: ['TICKETS_VIEW', 'TICKETS_EDIT', 'CUSTOMERS_MANAGE', 'TEAM_MANAGE', 'SYSTEM_SETTINGS']
|
||||
}
|
||||
});
|
||||
|
||||
// 2. Den allerersten Nutzer im System finden (dein initialer Account)
|
||||
const firstUser = await prisma.user.findFirst({
|
||||
orderBy: { id: 'asc' }
|
||||
});
|
||||
|
||||
if (!firstUser) {
|
||||
return NextResponse.json({ error: 'Kein Nutzer im System gefunden. Bitte erstelle zuerst einen Nutzer.' }, { status: 404 });
|
||||
}
|
||||
|
||||
// 3. Diesem Nutzer die Admin-Rolle aufzwingen
|
||||
await prisma.user.update({
|
||||
where: { id: firstUser.id },
|
||||
data: { roleId: adminRole.id }
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: `Setup erfolgreich! Der Nutzer ${firstUser.email} (ID: ${firstUser.id}) ist jetzt Administrator. Bitte logge dich jetzt einmal aus und wieder ein.`
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
console.error("Setup Fehler:", error);
|
||||
return NextResponse.json({ error: 'Interner Fehler beim Setup. Siehe Terminal.' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// /opt/erp-system/app/api/tickets/[id]/attachments/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../../../lib/prisma';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../../../auth/[...nextauth]/route";
|
||||
import { writeFile, readFile } from 'fs/promises';
|
||||
import { join } from 'path';
|
||||
|
||||
const UPLOAD_DIR = join(process.cwd(), 'uploads');
|
||||
|
||||
// POST: Datei hochladen
|
||||
export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
|
||||
|
||||
try {
|
||||
const params = await context.params;
|
||||
const ticketId = parseInt(params.id);
|
||||
const formData = await request.formData();
|
||||
|
||||
const file = formData.get('file') as File;
|
||||
if (!file) return NextResponse.json({ error: 'Keine Datei gefunden' }, { status: 400 });
|
||||
|
||||
const bytes = await file.arrayBuffer();
|
||||
const buffer = Buffer.from(bytes);
|
||||
|
||||
// Dateinamen bereinigen und eindeutig machen
|
||||
const safeOriginalName = file.name.replace(/[^a-zA-Z0-9.-]/g, '_');
|
||||
const savedName = `${Date.now()}-${safeOriginalName}`;
|
||||
const filepath = join(UPLOAD_DIR, savedName);
|
||||
|
||||
await writeFile(filepath, buffer);
|
||||
|
||||
const attachment = await prisma.attachment.create({
|
||||
data: {
|
||||
fileName: file.name,
|
||||
savedName: savedName,
|
||||
fileSize: file.size,
|
||||
fileType: file.type,
|
||||
ticketId: ticketId
|
||||
}
|
||||
});
|
||||
|
||||
return NextResponse.json(attachment, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error("Upload Fehler:", error);
|
||||
return NextResponse.json({ error: 'Fehler beim Upload' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
// GET: Datei-Liste abrufen oder einzelne Datei herunterladen
|
||||
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return new NextResponse('Nicht autorisiert', { status: 401 });
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
const downloadId = searchParams.get('download');
|
||||
|
||||
try {
|
||||
const params = await context.params;
|
||||
const ticketId = parseInt(params.id);
|
||||
|
||||
// Modus 1: Einzelne Datei herunterladen
|
||||
if (downloadId) {
|
||||
const attachment = await prisma.attachment.findUnique({
|
||||
where: { id: parseInt(downloadId) }
|
||||
});
|
||||
|
||||
if (!attachment || attachment.ticketId !== ticketId) {
|
||||
return new NextResponse('Datei nicht gefunden', { status: 404 });
|
||||
}
|
||||
|
||||
const filepath = join(UPLOAD_DIR, attachment.savedName);
|
||||
const fileBuffer = await readFile(filepath);
|
||||
|
||||
return new NextResponse(fileBuffer, {
|
||||
headers: {
|
||||
'Content-Type': attachment.fileType,
|
||||
'Content-Disposition': `attachment; filename="${attachment.fileName}"`
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Modus 2: Liste aller Anhänge des Tickets zurückgeben
|
||||
const attachments = await prisma.attachment.findMany({
|
||||
where: { ticketId: ticketId },
|
||||
orderBy: { createdAt: 'desc' }
|
||||
});
|
||||
return NextResponse.json(attachments);
|
||||
|
||||
} catch (error) {
|
||||
return new NextResponse('Fehler beim Abrufen der Datei', { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// /opt/erp-system/app/api/tickets/[id]/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../../lib/prisma';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||
import { sendEmail } from '../../../../lib/email';
|
||||
|
||||
export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
|
||||
|
||||
const params = await context.params;
|
||||
const ticketId = parseInt(params.id);
|
||||
const userId = parseInt((session.user as any).id);
|
||||
const userType = (session.user as any).userType;
|
||||
|
||||
const ticket = await prisma.ticket.findUnique({
|
||||
where: { id: ticketId },
|
||||
include: {
|
||||
customer: true,
|
||||
assignedTo: { select: { id: true, firstName: true, lastName: true } },
|
||||
messages: { orderBy: { createdAt: 'asc' } },
|
||||
timeEntries: { orderBy: { createdAt: 'desc' }, include: { user: { select: { firstName: true, lastName: true } } } },
|
||||
notes: { orderBy: { createdAt: 'desc' }, include: { user: { select: { firstName: true, lastName: true } } } },
|
||||
}
|
||||
});
|
||||
|
||||
if (!ticket) return NextResponse.json({ error: 'Nicht gefunden' }, { status: 404 });
|
||||
|
||||
// Sicherheits-Prüfung: Kunden dürfen nur ihre eigenen Akten laden
|
||||
if (userType === 'CUSTOMER' && ticket.customerId !== userId) {
|
||||
return NextResponse.json({ error: 'Zugriff verweigert' }, { status: 403 });
|
||||
}
|
||||
|
||||
return NextResponse.json(ticket);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: Request, context: { params: Promise<{ id: string }> }) {
|
||||
try {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
|
||||
|
||||
const params = await context.params;
|
||||
const ticketId = parseInt(params.id);
|
||||
const body = await request.json();
|
||||
const userId = parseInt((session.user as any).id);
|
||||
const userType = (session.user as any).userType;
|
||||
|
||||
const ticket = await prisma.ticket.findUnique({
|
||||
where: { id: ticketId },
|
||||
include: { customer: true }
|
||||
});
|
||||
|
||||
if (!ticket) return NextResponse.json({ error: 'Ticket nicht gefunden' }, { status: 404 });
|
||||
|
||||
// Sicherheits-Prüfung für Schreibzugriffe
|
||||
if (userType === 'CUSTOMER' && ticket.customerId !== userId) {
|
||||
return NextResponse.json({ error: 'Zugriff verweigert' }, { status: 403 });
|
||||
}
|
||||
|
||||
if (body.action === 'assign') {
|
||||
if (userType === 'CUSTOMER') return NextResponse.json({ error: 'Aktion unzulässig' }, { status: 403 });
|
||||
await prisma.ticket.update({
|
||||
where: { id: ticketId },
|
||||
data: { assignedToId: body.userId ? parseInt(body.userId) : null }
|
||||
});
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
|
||||
if (body.action === 'changePriority') {
|
||||
if (userType === 'CUSTOMER') return NextResponse.json({ error: 'Aktion unzulässig' }, { status: 403 });
|
||||
await prisma.ticket.update({
|
||||
where: { id: ticketId },
|
||||
data: { priority: body.priority }
|
||||
});
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
|
||||
if (body.action === 'addMessage') {
|
||||
const isFromCustomer = userType === 'CUSTOMER';
|
||||
await prisma.ticketMessage.create({
|
||||
data: { content: body.content, ticketId, isFromCustomer }
|
||||
});
|
||||
|
||||
// Nur E-Mail senden, wenn der Mitarbeiter antwortet
|
||||
if (!isFromCustomer && ticket.customer.email) {
|
||||
await sendEmail({
|
||||
to: ticket.customer.email,
|
||||
subject: `Update zu Ticket #${ticket.id}: ${ticket.title}`,
|
||||
text: `Hallo ${ticket.customer.firstName},\n\nes gibt eine neue Nachricht zu deinem Ticket:\n\n${body.content}\n\nViele Grüße\nDein Support-Team`
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
|
||||
if (body.action === 'addTimeEntry') {
|
||||
if (userType === 'CUSTOMER') return NextResponse.json({ error: 'Aktion unzulässig' }, { status: 403 });
|
||||
await prisma.timeEntry.create({ data: { durationMins: parseInt(body.durationMins), description: body.description, ticketId, userId } });
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
|
||||
if (body.action === 'addNote') {
|
||||
if (userType === 'CUSTOMER') return NextResponse.json({ error: 'Aktion unzulässig' }, { status: 403 });
|
||||
await prisma.ticketNote.create({ data: { content: body.content, ticketId, userId } });
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
|
||||
if (body.action === 'closeTicket') {
|
||||
if (userType === 'CUSTOMER') return NextResponse.json({ error: 'Aktion unzulässig' }, { status: 403 });
|
||||
if (body.durationMins > 0) {
|
||||
await prisma.timeEntry.create({ data: { durationMins: parseInt(body.durationMins), description: body.description || 'Abschluss', ticketId, userId } });
|
||||
}
|
||||
await prisma.ticket.update({ where: { id: ticketId }, data: { status: 'RESOLVED' } });
|
||||
|
||||
if (ticket.customer.email) {
|
||||
await sendEmail({
|
||||
to: ticket.customer.email,
|
||||
subject: `Ticket #${ticket.id} gelöst: ${ticket.title}`,
|
||||
text: `Hallo ${ticket.customer.firstName},\n\ndein Ticket wurde als gelöst markiert.\n\nLösung/Hinweis:\n${body.description || 'Das Problem wurde behoben.'}\n\nViele Grüße\nDein Support-Team`
|
||||
});
|
||||
}
|
||||
return NextResponse.json({ success: true });
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: 'Ungültig' }, { status: 400 });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Fehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
// /opt/erp-system/app/api/tickets/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../lib/prisma';
|
||||
import { sendEmail } from '../../../lib/email';
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const tickets = await prisma.ticket.findMany({
|
||||
include: {
|
||||
customer: { select: { companyName: true, firstName: true, lastName: true } },
|
||||
assignedTo: { select: { id: true, firstName: true, lastName: true } }
|
||||
},
|
||||
orderBy: { updatedAt: 'desc' }
|
||||
});
|
||||
return NextResponse.json(tickets);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const body = await request.json();
|
||||
|
||||
const ticket = await prisma.ticket.create({
|
||||
data: {
|
||||
title: body.title,
|
||||
description: body.description,
|
||||
customerId: parseInt(body.customerId),
|
||||
priority: body.priority || 'MEDIUM'
|
||||
},
|
||||
include: { customer: true }
|
||||
});
|
||||
|
||||
// Automatischer E-Mail-Versand an den Kunden
|
||||
if (ticket.customer.email) {
|
||||
await sendEmail({
|
||||
to: ticket.customer.email,
|
||||
subject: `Ticket #${ticket.id} eröffnet: ${ticket.title}`,
|
||||
text: `Hallo ${ticket.customer.firstName},\n\ndein Ticket wurde erfolgreich in unserem System erfasst.\n\nBetreff: ${ticket.title}\nBeschreibung:\n${ticket.description}\n\nWir kümmern uns schnellstmöglich darum.\n\nViele Grüße\nDein Support-Team`
|
||||
});
|
||||
}
|
||||
|
||||
return NextResponse.json(ticket, { status: 201 });
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Fehler beim Erstellen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
// /opt/erp-system/app/api/time-entries/[id]/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../../lib/prisma';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../../auth/[...nextauth]/route";
|
||||
|
||||
export async function PUT(
|
||||
request: Request,
|
||||
context: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
const session = await getServerSession(authOptions);
|
||||
if (!session) return NextResponse.json({ error: 'Nicht autorisiert' }, { status: 401 });
|
||||
|
||||
try {
|
||||
const params = await context.params;
|
||||
const id = parseInt(params.id);
|
||||
const body = await request.json();
|
||||
|
||||
const updated = await prisma.timeEntry.update({
|
||||
where: { id },
|
||||
data: {
|
||||
description: body.description,
|
||||
durationMins: parseInt(body.durationMins)
|
||||
}
|
||||
});
|
||||
|
||||
return NextResponse.json(updated);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Fehler beim Update' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// /opt/erp-system/app/api/users/route.ts
|
||||
import { NextResponse } from 'next/server';
|
||||
import prisma from '../../../lib/prisma';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import { getServerSession } from "next-auth/next";
|
||||
import { authOptions } from "../auth/[...nextauth]/route";
|
||||
|
||||
async function checkAccess() {
|
||||
const session = await getServerSession(authOptions);
|
||||
const perms = (session?.user as any)?.permissions || [];
|
||||
return perms.includes('TEAM_MANAGE');
|
||||
}
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const users = await prisma.user.findMany({
|
||||
include: { role: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
});
|
||||
|
||||
const safeUsers = users.map(u => ({
|
||||
id: u.id, firstName: u.firstName, lastName: u.lastName, email: u.email, role: u.role, createdAt: u.createdAt, roleId: u.roleId
|
||||
}));
|
||||
return NextResponse.json(safeUsers);
|
||||
} catch (error) {
|
||||
return NextResponse.json({ error: 'Ladefehler' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (!await checkAccess()) return NextResponse.json({ error: 'Zugriff verweigert' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
const passwordHash = await bcrypt.hash(body.password, 10);
|
||||
|
||||
const newUser = await prisma.user.create({
|
||||
data: {
|
||||
firstName: body.firstName,
|
||||
lastName: body.lastName,
|
||||
email: body.email,
|
||||
passwordHash: passwordHash,
|
||||
roleId: parseInt(body.roleId),
|
||||
},
|
||||
include: { role: true }
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
id: newUser.id, firstName: newUser.firstName, email: newUser.email, role: newUser.role
|
||||
}, { status: 201 });
|
||||
} catch (error: any) {
|
||||
if (error.code === 'P2002') return NextResponse.json({ error: 'E-Mail wird bereits verwendet.' }, { status: 400 });
|
||||
return NextResponse.json({ error: 'Fehler beim Erstellen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
if (!await checkAccess()) return NextResponse.json({ error: 'Zugriff verweigert' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const body = await request.json();
|
||||
|
||||
// Basis-Daten für das Update
|
||||
const updateData: any = {
|
||||
firstName: body.firstName,
|
||||
lastName: body.lastName,
|
||||
email: body.email,
|
||||
roleId: parseInt(body.roleId)
|
||||
};
|
||||
|
||||
// Passwort nur aktualisieren, wenn ein neues eingegeben wurde
|
||||
if (body.password && body.password.trim() !== '') {
|
||||
updateData.passwordHash = await bcrypt.hash(body.password, 10);
|
||||
}
|
||||
|
||||
const updatedUser = await prisma.user.update({
|
||||
where: { id: body.id },
|
||||
data: updateData,
|
||||
include: { role: true }
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
id: updatedUser.id, firstName: updatedUser.firstName, email: updatedUser.email, role: updatedUser.role
|
||||
}, { status: 200 });
|
||||
} catch (error: any) {
|
||||
if (error.code === 'P2002') return NextResponse.json({ error: 'E-Mail wird bereits verwendet.' }, { status: 400 });
|
||||
return NextResponse.json({ error: 'Fehler beim Aktualisieren' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
const session = await getServerSession(authOptions);
|
||||
const perms = (session?.user as any)?.permissions || [];
|
||||
if (!perms.includes('DATA_DELETE')) return NextResponse.json({ error: 'Keine Löschberechtigung' }, { status: 403 });
|
||||
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const id = searchParams.get('id');
|
||||
if (!id) return NextResponse.json({ error: 'ID fehlt' }, { status: 400 });
|
||||
|
||||
const userId = parseInt(id);
|
||||
|
||||
// Unassign tickets instead of deleting them
|
||||
await prisma.ticket.updateMany({ where: { assignedToId: userId }, data: { assignedToId: null } });
|
||||
// Delete user's time entries and notes
|
||||
await prisma.timeEntry.deleteMany({ where: { userId } });
|
||||
await prisma.ticketNote.deleteMany({ where: { userId } });
|
||||
|
||||
await prisma.user.delete({ where: { id: userId } });
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return NextResponse.json({ error: 'Löschen fehlgeschlagen' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user