80 lines
2.5 KiB
TypeScript
80 lines
2.5 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import {
|
|
getSuppliersFromAppwrite,
|
|
createSupplierInAppwrite,
|
|
updateSupplierInAppwrite,
|
|
deleteSupplierInAppwrite,
|
|
} from '@/lib/server-appwrite';
|
|
import { dataService } from '@/lib/data-service';
|
|
|
|
export async function GET(request: Request) {
|
|
try {
|
|
const { searchParams } = new URL(request.url);
|
|
const includeAll = searchParams.get('all') === 'true';
|
|
|
|
const suppliers = await getSuppliersFromAppwrite();
|
|
const result = includeAll ? suppliers : suppliers.filter((s) => s.isActive !== false);
|
|
|
|
return NextResponse.json({ success: true, suppliers: result });
|
|
} catch (error: any) {
|
|
const fallback = dataService.getSuppliers(true);
|
|
return NextResponse.json({ success: true, suppliers: fallback });
|
|
}
|
|
}
|
|
|
|
export async function POST(request: Request) {
|
|
try {
|
|
const body = await request.json();
|
|
const created = await createSupplierInAppwrite(body);
|
|
dataService.addSupplier(created);
|
|
return NextResponse.json({ success: true, supplier: created });
|
|
} catch (error: any) {
|
|
return NextResponse.json({ success: false, error: error.message }, { status: 400 });
|
|
}
|
|
}
|
|
|
|
export async function PUT(request: Request) {
|
|
try {
|
|
const body = await request.json();
|
|
const { id, updates, ...rest } = body;
|
|
const targetId = id || rest.id;
|
|
|
|
if (!targetId) {
|
|
return NextResponse.json({ success: false, error: 'ID de proveedor requerido' }, { status: 400 });
|
|
}
|
|
|
|
const payload = updates || rest;
|
|
const updated = await updateSupplierInAppwrite(targetId, payload);
|
|
dataService.updateSupplier(targetId, payload);
|
|
|
|
return NextResponse.json({ success: true, supplier: updated || payload });
|
|
} catch (error: any) {
|
|
return NextResponse.json({ success: false, error: error.message }, { status: 400 });
|
|
}
|
|
}
|
|
|
|
export async function DELETE(request: Request) {
|
|
try {
|
|
const { searchParams } = new URL(request.url);
|
|
let id = searchParams.get('id');
|
|
|
|
if (!id) {
|
|
try {
|
|
const body = await request.json();
|
|
id = body?.id;
|
|
} catch (_) {}
|
|
}
|
|
|
|
if (!id) {
|
|
return NextResponse.json({ success: false, error: 'ID de proveedor requerido' }, { status: 400 });
|
|
}
|
|
|
|
const deleted = await deleteSupplierInAppwrite(id);
|
|
dataService.deleteSupplier(id);
|
|
|
|
return NextResponse.json({ success: true, message: 'Proveedor desactivado/eliminado correctamente' });
|
|
} catch (error: any) {
|
|
return NextResponse.json({ success: false, error: error.message }, { status: 500 });
|
|
}
|
|
}
|