From d02fac8b348fa4f3d2dd2d7adf360cfb26992e83 Mon Sep 17 00:00:00 2001 From: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com> Date: Thu, 18 Jun 2026 12:24:45 +0200 Subject: [PATCH] refactor(zeitkarten/cleanup): relocate shared timecard UI out of app/admin; delete dead code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SoC: the timecard editor was imported by the dashboard from app/admin/timecards (dashboard → admin coupling). Moved the 9 shared editor files to neutral src/components/timecards/ (next to ShiftWidget + WeeklyScheduleEditor); both the admin and dashboard routes now import from there. No behaviour change. Dead-code removal (verified zero callers): - src/components/shop/ProductCard.tsx (no importers; ListingCard is the live tile) - src/lib/services/order-service.ts + test + barrel exports (legacy Medusa order path; live flow is marketplaceOrders/*; orders/order_items tables are empty — their drop is deferred to a deliberate migration as they have a dependent DB function). Co-Authored-By: Claude Opus 4.8 (1M context) --- src/app/admin/timecards/page.tsx | 2 +- src/app/dashboard/timecards/page.tsx | 2 +- src/components/shop/ProductCard.tsx | 67 ------ .../timecards/NoScheduleNotice.tsx | 0 .../timecards/TimecardBulkBar.tsx | 0 .../timecards/TimecardDayEditor.tsx | 0 .../timecards/TimecardHeader.tsx | 0 .../timecards/TimecardMonthGrid.tsx | 0 .../timecards/TimecardsClient.tsx | 0 .../timecards/draft-utils.ts | 0 .../admin => components}/timecards/types.ts | 0 .../timecards/useTimecardDraft.ts | 0 src/lib/services/__tests__/index.test.ts | 3 - .../services/__tests__/order-service.test.ts | 227 ------------------ src/lib/services/index.ts | 4 - src/lib/services/order-service.ts | 184 -------------- 16 files changed, 2 insertions(+), 487 deletions(-) delete mode 100644 src/components/shop/ProductCard.tsx rename src/{app/admin => components}/timecards/NoScheduleNotice.tsx (100%) rename src/{app/admin => components}/timecards/TimecardBulkBar.tsx (100%) rename src/{app/admin => components}/timecards/TimecardDayEditor.tsx (100%) rename src/{app/admin => components}/timecards/TimecardHeader.tsx (100%) rename src/{app/admin => components}/timecards/TimecardMonthGrid.tsx (100%) rename src/{app/admin => components}/timecards/TimecardsClient.tsx (100%) rename src/{app/admin => components}/timecards/draft-utils.ts (100%) rename src/{app/admin => components}/timecards/types.ts (100%) rename src/{app/admin => components}/timecards/useTimecardDraft.ts (100%) delete mode 100644 src/lib/services/__tests__/order-service.test.ts delete mode 100644 src/lib/services/order-service.ts diff --git a/src/app/admin/timecards/page.tsx b/src/app/admin/timecards/page.tsx index 1abb413e6..f850f41b5 100644 --- a/src/app/admin/timecards/page.tsx +++ b/src/app/admin/timecards/page.tsx @@ -6,7 +6,7 @@ import { db } from '@/db' import { teamProfiles } from '@/db/schema' import AdminPageWrapper from '@/components/admin/AdminPageWrapper' import { requireSection } from '@/lib/admin/guards' -import { TimecardsClient } from './TimecardsClient' +import { TimecardsClient } from '@/components/timecards/TimecardsClient' export const metadata: Metadata = { title: 'Zeitkarten', diff --git a/src/app/dashboard/timecards/page.tsx b/src/app/dashboard/timecards/page.tsx index de5105c3b..cb913cb72 100644 --- a/src/app/dashboard/timecards/page.tsx +++ b/src/app/dashboard/timecards/page.tsx @@ -27,7 +27,7 @@ import { auth } from '@/auth' import { db } from '@/db' import { teamProfiles, timecards as timecardsTable } from '@/db/schema' import Heading from '@/components/ui/Heading' -import { TimecardsClient } from '@/app/admin/timecards/TimecardsClient' +import { TimecardsClient } from '@/components/timecards/TimecardsClient' import { TimecardHistorySidebar } from '@/components/dashboard/timecards/TimecardHistorySidebar' import { WeeklyScheduleEditor } from '@/components/timecards/WeeklyScheduleEditor' diff --git a/src/components/shop/ProductCard.tsx b/src/components/shop/ProductCard.tsx deleted file mode 100644 index d77bbce47..000000000 --- a/src/components/shop/ProductCard.tsx +++ /dev/null @@ -1,67 +0,0 @@ -import Link from 'next/link' -import Image from 'next/image' -import { Package, Tag } from 'lucide-react' -import type { InventoryProduct } from '@/lib/services/inventory-service' -import { formatCHF } from '@/config/marketplace' -import { CO2Badge } from '@/components/marketplace/CO2Badge' - -interface Props { - product: InventoryProduct - stockOneLabel?: string -} - -export function ProductCard({ product, stockOneLabel }: Props) { - return ( - -
- {product.image_url ? ( - {product.title} - ) : ( -
- -
- )} - {stockOneLabel && product.quantity <= 1 && ( - - {stockOneLabel} - - )} -
-
-
-

{product.brand}

-

- {product.title} -

-
- {product.description && ( -

{product.description}

- )} - {/* CO₂ Badge — silently hides when category isn't a known KATEGORIEN - ID (shop inventory categories are sometimes free text from CSV - imports). Credibility-first: better empty than guessed. */} - {product.category && ( - - )} -
-
- - {formatCHF(product.price)} -
- - {product.condition} - -
-
- - ) -} diff --git a/src/app/admin/timecards/NoScheduleNotice.tsx b/src/components/timecards/NoScheduleNotice.tsx similarity index 100% rename from src/app/admin/timecards/NoScheduleNotice.tsx rename to src/components/timecards/NoScheduleNotice.tsx diff --git a/src/app/admin/timecards/TimecardBulkBar.tsx b/src/components/timecards/TimecardBulkBar.tsx similarity index 100% rename from src/app/admin/timecards/TimecardBulkBar.tsx rename to src/components/timecards/TimecardBulkBar.tsx diff --git a/src/app/admin/timecards/TimecardDayEditor.tsx b/src/components/timecards/TimecardDayEditor.tsx similarity index 100% rename from src/app/admin/timecards/TimecardDayEditor.tsx rename to src/components/timecards/TimecardDayEditor.tsx diff --git a/src/app/admin/timecards/TimecardHeader.tsx b/src/components/timecards/TimecardHeader.tsx similarity index 100% rename from src/app/admin/timecards/TimecardHeader.tsx rename to src/components/timecards/TimecardHeader.tsx diff --git a/src/app/admin/timecards/TimecardMonthGrid.tsx b/src/components/timecards/TimecardMonthGrid.tsx similarity index 100% rename from src/app/admin/timecards/TimecardMonthGrid.tsx rename to src/components/timecards/TimecardMonthGrid.tsx diff --git a/src/app/admin/timecards/TimecardsClient.tsx b/src/components/timecards/TimecardsClient.tsx similarity index 100% rename from src/app/admin/timecards/TimecardsClient.tsx rename to src/components/timecards/TimecardsClient.tsx diff --git a/src/app/admin/timecards/draft-utils.ts b/src/components/timecards/draft-utils.ts similarity index 100% rename from src/app/admin/timecards/draft-utils.ts rename to src/components/timecards/draft-utils.ts diff --git a/src/app/admin/timecards/types.ts b/src/components/timecards/types.ts similarity index 100% rename from src/app/admin/timecards/types.ts rename to src/components/timecards/types.ts diff --git a/src/app/admin/timecards/useTimecardDraft.ts b/src/components/timecards/useTimecardDraft.ts similarity index 100% rename from src/app/admin/timecards/useTimecardDraft.ts rename to src/components/timecards/useTimecardDraft.ts diff --git a/src/lib/services/__tests__/index.test.ts b/src/lib/services/__tests__/index.test.ts index 6a9f37f12..464c5f337 100644 --- a/src/lib/services/__tests__/index.test.ts +++ b/src/lib/services/__tests__/index.test.ts @@ -83,9 +83,6 @@ jest.mock('../inventory-service', () => ({ jest.mock('../seller-service', () => ({ getSellerDashboard: jest.fn(), })) -jest.mock('../order-service', () => ({ - createOrder: jest.fn(), -})) // --------------------------------------------------------------------------- // Imports (after mocks) diff --git a/src/lib/services/__tests__/order-service.test.ts b/src/lib/services/__tests__/order-service.test.ts deleted file mode 100644 index c2752238a..000000000 --- a/src/lib/services/__tests__/order-service.test.ts +++ /dev/null @@ -1,227 +0,0 @@ -/** - * Tests for order-service.ts - * - * Tests order creation with mocked Drizzle ORM (db.execute + db.transaction). - */ - -// --------------------------------------------------------------------------- -// Drizzle mock setup -// --------------------------------------------------------------------------- - -// Use an object container so we can reference it inside hoisted jest.mock factories. -// jest.mock is hoisted above const declarations, so direct references would hit TDZ. -const mocks = { - execute: jest.fn(), - txExecute: jest.fn(), - transaction: jest.fn(), -} - -// Wire up transaction to call the callback with a fake tx -mocks.transaction.mockImplementation(async (cb: (tx: { execute: jest.Mock }) => Promise) => { - return cb({ execute: mocks.txExecute }) -}) - -jest.mock('@/db', () => ({ - db: { - execute: (...args: unknown[]) => mocks.execute(...args), - transaction: (...args: unknown[]) => mocks.transaction(...args), - }, -})) - -jest.mock('drizzle-orm', () => ({ - sql: Object.assign( - (strings: TemplateStringsArray, ...values: unknown[]) => ({ strings, values }), - { - raw: (v: string) => v, - join: (items: unknown[], sep: unknown) => ({ items, sep }), - } - ), - getTableName: (table: unknown) => { - if (table && typeof table === 'object' && '_name' in table) return (table as { _name: string })._name - return 'mock_table' - }, -})) - -jest.mock('@/db/schema', () => ({ - inventoryItems: { _name: 'inventory_items' }, - aiExtractedProducts: { _name: 'ai_extracted_products' }, - orders: { _name: 'orders' }, - orderItems: { _name: 'order_items' }, -})) - -jest.mock('@/config/payment-status', () => ({ - PAYMENT_STATUS: { PENDING: 'pending' }, -})) - -jest.mock('@/lib/logger', () => ({ - logger: { - info: jest.fn(), - warn: jest.fn(), - error: jest.fn(), - }, -})) - -import { createOrder } from '../order-service' -import type { CreateOrderParams, ShippingAddress } from '../order-service' - -describe('createOrder', () => { - beforeEach(() => { - mocks.execute.mockReset() - mocks.transaction.mockClear() - mocks.transaction.mockImplementation(async (cb: (tx: { execute: jest.Mock }) => Promise) => { - return cb({ execute: mocks.txExecute }) - }) - mocks.txExecute.mockReset() - }) - - it('creates an order with inventory items and returns id + timestamp', async () => { - // All four SQL operations now live inside the transaction: - // 1) SELECT FOR UPDATE — inventory lookup - mocks.txExecute.mockResolvedValueOnce({ - rows: [{ - id: 'inv-1', - selling_price_chf: 50, - quantity_available: 10, - product_name: 'Test Product', - }], - }) - // 2) INSERT INTO orders RETURNING id, created_at - mocks.txExecute.mockResolvedValueOnce({ - rows: [{ id: 'order-1', created_at: '2024-01-15T10:00:00Z' }], - }) - // 3) INSERT INTO order_items (per item) - mocks.txExecute.mockResolvedValueOnce({ rows: [] }) - // 4) UPDATE inventory_items (decrement, per item) - mocks.txExecute.mockResolvedValueOnce({ rows: [] }) - - const params: CreateOrderParams = { - userId: 'user-1', - items: [{ inventoryItemId: 'inv-1', quantity: 1 }], - paymentTransactionId: 'txn_test123', - } - - const result = await createOrder(params) - expect(result.orderId).toBe('order-1') - expect(result.createdAt).toBe('2024-01-15T10:00:00Z') - - expect(mocks.transaction).toHaveBeenCalledTimes(1) - // Inside transaction: inventory lookup + order insert + order_item insert + decrement = 4 - expect(mocks.txExecute).toHaveBeenCalledTimes(4) - }) - - it('includes shipping address when provided', async () => { - // Inventory lookup - mocks.txExecute.mockResolvedValueOnce({ - rows: [{ - id: 'inv-1', - selling_price_chf: 50, - quantity_available: 10, - product_name: 'Test Product', - }], - }) - // Order INSERT (returns id+created_at), then order_item INSERT + decrement - mocks.txExecute.mockResolvedValueOnce({ - rows: [{ id: 'order-2', created_at: '2024-01-15' }], - }) - mocks.txExecute.mockResolvedValueOnce({ rows: [] }) - mocks.txExecute.mockResolvedValueOnce({ rows: [] }) - - const address: ShippingAddress = { - firstName: 'Hans', - lastName: 'Müller', - street: 'Bahnhofstrasse 1', - city: 'Zürich', - postalCode: '8001', - country: 'CH', - } - - await createOrder({ - userId: 'user-1', - items: [{ inventoryItemId: 'inv-1', quantity: 1 }], - paymentTransactionId: 'txn_test', - shippingAddress: address, - }) - - // The SECOND tx.execute call is the order INSERT (first is inventory lookup) - const orderInsertCall = mocks.txExecute.mock.calls[1][0] - expect(orderInsertCall.values).toContainEqual(JSON.stringify(address)) - }) - - it('passes null when no shipping address', async () => { - mocks.txExecute.mockResolvedValueOnce({ - rows: [{ - id: 'inv-1', - selling_price_chf: 50, - quantity_available: 10, - product_name: 'Test Product', - }], - }) - mocks.txExecute.mockResolvedValueOnce({ - rows: [{ id: 'order-3', created_at: '2024-01-15' }], - }) - mocks.txExecute.mockResolvedValueOnce({ rows: [] }) - mocks.txExecute.mockResolvedValueOnce({ rows: [] }) - - await createOrder({ - userId: 'user-1', - items: [{ inventoryItemId: 'inv-1', quantity: 1 }], - paymentTransactionId: 'txn_test', - }) - - // SECOND tx.execute call is the order INSERT — shipping_address should be null - const orderInsertCall = mocks.txExecute.mock.calls[1][0] - expect(orderInsertCall.values).toContainEqual(null) - }) - - it('throws when items array is empty', async () => { - await expect( - createOrder({ - userId: 'user-1', - items: [], - }) - ).rejects.toThrow('Warenkorb ist leer') - }) - - it('throws when inventory item is not found', async () => { - mocks.txExecute.mockResolvedValueOnce({ - rows: [], - }) - - await expect( - createOrder({ - userId: 'user-1', - items: [{ inventoryItemId: 'non-existent', quantity: 1 }], - }) - ).rejects.toThrow('Artikel nicht gefunden') - }) - - it('throws when insufficient inventory', async () => { - mocks.txExecute.mockResolvedValueOnce({ - rows: [{ - id: 'inv-1', - selling_price_chf: 50, - quantity_available: 1, - product_name: 'Test Product', - }], - }) - - await expect( - createOrder({ - userId: 'user-1', - items: [{ inventoryItemId: 'inv-1', quantity: 5 }], - }) - ).rejects.toThrow('Nicht genügend Lagerbestand') - }) - - it('throws on database error', async () => { - mocks.txExecute.mockRejectedValueOnce(new Error('DB connection failed')) - - await expect( - createOrder({ - userId: 'user-1', - items: [{ inventoryItemId: 'inv-1', quantity: 1 }], - paymentTransactionId: 'txn_test', - }) - ).rejects.toThrow('DB connection failed') - }) -}) diff --git a/src/lib/services/index.ts b/src/lib/services/index.ts index 299f53713..c639becc1 100644 --- a/src/lib/services/index.ts +++ b/src/lib/services/index.ts @@ -21,10 +21,6 @@ export type { InventoryFilters, InventoryProduct, InventoryResult } from './inve export { getSellerDashboard } from './seller-service' export type { SellerProduct, SellerStats, SellerDashboardData } from './seller-service' -// Order service -export { createOrder } from './order-service' -export type { CreateOrderParams, CreatedOrder, ShippingAddress } from './order-service' - // ============================================================================ // Unified Service Layer (Dienstleistungen) // ============================================================================ diff --git a/src/lib/services/order-service.ts b/src/lib/services/order-service.ts deleted file mode 100644 index efa8e6b2f..000000000 --- a/src/lib/services/order-service.ts +++ /dev/null @@ -1,184 +0,0 @@ -/** - * Order Service - * - * Business logic for order creation. - * Creates order records from local inventory items - * and decrements inventory. - */ - -import { db } from '@/db' -import { sql, getTableName } from 'drizzle-orm' -import { inventoryItems, aiExtractedProducts, orders, orderItems } from '@/db/schema' -import { PAYMENT_STATUS } from '@/config/payment-status' -import { logger } from '@/lib/logger' - -// Table name refs -const iiTable = getTableName(inventoryItems) -const aepTable = getTableName(aiExtractedProducts) -const ordersTable = getTableName(orders) -const oiTable = getTableName(orderItems) - -// ============================================================================ -// Types -// ============================================================================ - -export interface ShippingAddress { - firstName: string - lastName: string - street: string - city: string - postalCode: string - country: string -} - -export interface OrderItem { - inventoryItemId: string - quantity: number -} - -export interface CreateOrderParams { - userId: string - items: OrderItem[] - paymentTransactionId?: string - shippingAddress?: ShippingAddress -} - -interface OrderRow { - id: string - created_at: string -} - -export interface CreatedOrder { - orderId: string - createdAt: string -} - -interface InventoryRow { - id: string - selling_price_chf: number | null - quantity_available: number - product_name: string -} - -// ============================================================================ -// Public API -// ============================================================================ - -/** - * Create a new order from local inventory items. - * - * Looks up inventory items, creates order + order items - * with real totals, and decrements quantity_available. - */ -export async function createOrder(params: CreateOrderParams): Promise { - const { userId, items, paymentTransactionId = PAYMENT_STATUS.PENDING, shippingAddress } = params - - try { - if (!items || items.length === 0) { - throw new Error('Warenkorb ist leer') - } - - const itemIds = items.map(i => i.inventoryItemId) - - // Lock inventory rows, validate stock, calculate total, create order + - // items, decrement — all inside one transaction. Without the FOR UPDATE - // lock, two concurrent orders for the same last-N items both pass the - // stock check and oversell (GREATEST(...,0) hides the bug but the orders - // still exist with no inventory to fulfill them). - const result = await db.transaction(async (tx) => { - const inventoryResult = await tx.execute(sql` - SELECT ii.id, ii.selling_price_chf, ii.quantity_available, aep.product_name - FROM ${sql.raw(iiTable)} ii - JOIN ${sql.raw(aepTable)} aep ON aep.id = ii.ai_product_id - WHERE ii.id IN (${sql.join(itemIds.map(id => sql`${id}`), sql`, `)}) - FOR UPDATE OF ii - `) - - const inventoryMap = new Map( - (inventoryResult.rows as unknown as InventoryRow[]).map(r => [r.id, r]) - ) - - let totalCents = 0 - for (const item of items) { - const inv = inventoryMap.get(item.inventoryItemId) - if (!inv) { - throw new Error(`Artikel nicht gefunden: ${item.inventoryItemId}`) - } - if (inv.quantity_available < item.quantity) { - throw new Error(`Nicht genügend Lagerbestand für: ${inv.product_name}`) - } - totalCents += (inv.selling_price_chf || 0) * 100 * item.quantity - } - - const orderResult = await tx.execute(sql` - INSERT INTO ${sql.raw(ordersTable)} ( - user_id, - status, - total_amount_cents, - currency, - payment_intent_id, - shipping_address - ) VALUES ( - ${userId}, - 'confirmed', - ${totalCents}, - 'CHF', - ${paymentTransactionId}, - ${shippingAddress ? JSON.stringify(shippingAddress) : null} - ) - RETURNING id, created_at - `) - - const orderData = (orderResult.rows as unknown as OrderRow[])[0] - const orderId = orderData.id - - // Create order items and decrement inventory - for (const item of items) { - const inv = inventoryMap.get(item.inventoryItemId)! - - await tx.execute(sql` - INSERT INTO ${sql.raw(oiTable)} ( - order_id, - product_title, - quantity, - unit_price_cents, - total_price_cents, - inventory_item_id - ) VALUES ( - ${orderId}, - ${inv.product_name}, - ${item.quantity}, - ${(inv.selling_price_chf || 0) * 100}, - ${(inv.selling_price_chf || 0) * 100 * item.quantity}, - ${item.inventoryItemId} - ) - `) - - // Row is locked + stock validated above; safe to decrement without clamp - await tx.execute(sql` - UPDATE ${sql.raw(iiTable)} - SET quantity_available = quantity_available - ${item.quantity} - WHERE id = ${item.inventoryItemId} - `) - } - - return { orderId, createdAt: orderData.created_at, totalCents } - }) - - logger.info('Order created', { - orderId: result.orderId, - userId, - totalCents: result.totalCents, - itemCount: items.length, - }) - - return { orderId: result.orderId, createdAt: result.createdAt } - } catch (error) { - logger.error('Failed to create order', { - userId, - itemCount: items.length, - error, - }) - throw error - } -}