Initial commit - ERP System

This commit is contained in:
root
2026-05-20 18:58:23 +00:00
commit e174936997
2697 changed files with 1628427 additions and 0 deletions
+41
View File
@@ -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 });
}
}
+54
View File
@@ -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 });
}
}
+95
View File
@@ -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 });
}
}
+78
View File
@@ -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 });
}
}
+83
View File
@@ -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 });
}
}
+35
View File
@@ -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);
}