Remove CustomerRepository and replace with direct API calls

- Remove `CustomerRepository` and its methods for customer management and caching.
- Refactor customer-related pages (`[id]/page.tsx`, `customers/page.tsx`) to use direct `fetch` API calls.
- Update breadcrumb resolver to fetch data directly from the API.
- Simplify `addCustomer` use case to avoid repository dependency.
This commit is contained in:
2025-07-11 18:38:44 +02:00
parent 328c0537ba
commit 2a95efb75f
5 changed files with 47 additions and 106 deletions

View File

@@ -11,7 +11,6 @@ import CustomerInformationContent from "@/components/customers/details/sub/Conta
import CustomerPhoneNumberContent from "@/components/customers/details/sub/CustomerPhoneNumberContent"; import CustomerPhoneNumberContent from "@/components/customers/details/sub/CustomerPhoneNumberContent";
import CustomerNotesContent from "@/components/customers/details/sub/CustomerNotesContent"; import CustomerNotesContent from "@/components/customers/details/sub/CustomerNotesContent";
import {Customer} from "@/services/customers/entities/customer"; import {Customer} from "@/services/customers/entities/customer";
import {CustomerRepository} from "@/services/customers/repositories/customerRepository";
export default function CustomerDetailPage() { export default function CustomerDetailPage() {
const router = useRouter(); const router = useRouter();
@@ -33,16 +32,22 @@ export default function CustomerDetailPage() {
setLoading(true); setLoading(true);
setError(null); setError(null);
CustomerRepository.getById(id) fetch(`/api/customers/${id}`)
.then((result) => { .then(async (response) => {
if (!isMounted) return; if (!isMounted) return;
if (!result) { if (response.status === 404) {
setError("Kunde nicht gefunden"); setError("Kunde nicht gefunden");
setCustomer(null); setCustomer(null);
} else { return;
setCustomer(result);
} }
if (!response.ok) {
throw new Error(`Failed to fetch customer: ${response.statusText}`);
}
const result = await response.json();
setCustomer(result);
}) })
.catch((error) => { .catch((error) => {
if (!isMounted) return; if (!isMounted) return;

View File

@@ -24,7 +24,6 @@ import {ArrowRight} from "lucide-react";
import {NewCustomerModal} from "@/components/customers/modal/NewCustomerModal"; import {NewCustomerModal} from "@/components/customers/modal/NewCustomerModal";
import {Customer} from "@/services/customers/entities/customer"; import {Customer} from "@/services/customers/entities/customer";
import Link from "next/link"; import Link from "next/link";
import {CustomerRepository} from "@/services/customers/repositories/customerRepository";
export default function CustomersPage() { export default function CustomersPage() {
const [customers, setCustomers] = useState<Customer[]>([]); const [customers, setCustomers] = useState<Customer[]>([]);
@@ -35,7 +34,13 @@ export default function CustomersPage() {
useEffect(() => { useEffect(() => {
setLoading(true); setLoading(true);
CustomerRepository.getAll() fetch('/api/customers')
.then(async (response) => {
if (!response.ok) {
throw new Error(`Failed to fetch customers: ${response.statusText}`);
}
return response.json();
})
.then((data) => { .then((data) => {
setCustomers(data); setCustomers(data);
}) })

View File

@@ -1,5 +1,3 @@
import {CustomerRepository} from "@/services/customers/repositories/customerRepository";
export const breadcrumbMap: Record<string, string> = { export const breadcrumbMap: Record<string, string> = {
'dashboard': 'Dashboard', 'dashboard': 'Dashboard',
'settings': 'Settings', 'settings': 'Settings',
@@ -10,11 +8,21 @@ export const breadcrumbMap: Record<string, string> = {
export const breadcrumbResolvers: Record<string, (id: string) => Promise<string>> = { export const breadcrumbResolvers: Record<string, (id: string) => Promise<string>> = {
"customers": async (id: string) => { "customers": async (id: string) => {
const customer = await CustomerRepository.getById(id); try {
const response = await fetch(`/api/customers/${id}`);
if (!response.ok) {
return `ID: ${id}`;
}
const customer = await response.json();
if (!customer) return `ID: ${id}`; if (!customer) return `ID: ${id}`;
if (customer.companyName) return `Firma: ${customer.companyName}`; if (customer.companyName) return `Firma: ${customer.companyName}`;
if (customer.name) return `Name: ${customer.name}`; if (customer.name) return `Name: ${customer.name}`;
return `ID: ${id}`; return `ID: ${id}`;
} catch (error) {
console.error('Error fetching customer for breadcrumb:', error);
return `ID: ${id}`;
}
}, },
}; };

View File

@@ -1,86 +0,0 @@
import {Customer} from "@/services/customers/entities/customer";
import {CreateCustomerDto} from "@/services/customers/dtos/createCustomer.dto";
export class CustomerRepository {
private static readonly customerCache: Map<string, Customer> = new Map();
private static lastFetchAll: number | null = null;
private static readonly CACHE_DURATION = 10 * 1000; // seconds in milliseconds
static async getAll(): Promise<Customer[]> {
const now = Date.now();
if (this.lastFetchAll && (now - this.lastFetchAll < this.CACHE_DURATION)) {
return Array.from(this.customerCache.values());
}
console.log('Cache expired or not initialized, fetching fresh data from API');
const response = await fetch('/api/customers');
if (!response.ok) {
console.error('Failed to fetch customers:', response.status, response.statusText);
return Promise.reject(new Error(`Failed to fetch customers: ${response.statusText}`));
}
const customers: Customer[] = await response.json();
this.customerCache.clear();
customers.forEach((customer: Customer) => this.customerCache.set(customer.id, customer));
this.lastFetchAll = now;
return customers;
}
static async getById(id: string): Promise<Customer | null> {
const cachedCustomer = this.customerCache.get(id);
if (cachedCustomer) {
return cachedCustomer;
}
console.log(`Cache miss for customer ${id}, fetching from API`);
try {
const response = await fetch(`/api/customers/${id}`);
if (!response.ok) {
if (response.status === 404) {
console.log(`Customer ${id} not found`);
return null;
}
console.error('Failed to fetch customer:', response.status, response.statusText);
return Promise.reject(new Error(`Failed to fetch customer: ${response.statusText}`));
}
const customer: Customer = await response.json();
this.customerCache.set(id, customer);
return customer;
} catch (error) {
console.error('Error fetching customer:', error);
return Promise.reject(error);
}
}
static async create(payload: CreateCustomerDto): Promise<void> {
const response = await fetch('/api/customers', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload)
});
if (!response.ok) {
console.error('Failed to create customer:', response.status, response.statusText);
return Promise.reject(new Error(`Failed to create customer: ${response.statusText}`));
}
console.log('Cache invalidated after creating new customer');
this.lastFetchAll = null; // Invalidate the cache after creating new customer
}
static clearCache(): void {
console.log('Cache manually cleared');
this.customerCache.clear();
this.lastFetchAll = null;
}
static updateCache(customer: Customer): void {
console.log(`Cache updated for customer ${customer.id}`);
this.customerCache.set(customer.id, customer);
}
}

View File

@@ -1,7 +1,6 @@
"use server"; "use server";
import {CreateCustomerDto} from "@/services/customers/dtos/createCustomer.dto"; import {CreateCustomerDto} from "@/services/customers/dtos/createCustomer.dto";
import {CustomerRepository} from "@/services/customers/repositories/customerRepository";
export async function addCustomer(params: CreateCustomerDto): Promise<void> { export async function addCustomer(params: CreateCustomerDto): Promise<void> {
const {email, name, companyName, street, zip, city, phoneNumbers, notes} = params; const {email, name, companyName, street, zip, city, phoneNumbers, notes} = params;
@@ -17,5 +16,15 @@ export async function addCustomer(params: CreateCustomerDto): Promise<void> {
notes: notes.map(({text}) => ({text})), notes: notes.map(({text}) => ({text})),
}; };
await CustomerRepository.create(payload); const response = await fetch('/api/customers', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload)
});
if (!response.ok) {
throw new Error(`Failed to create customer: ${response.statusText}`);
}
} }