mirror of
https://github.com/bitbaum/evig.git
synced 2026-12-04 18:37:57 +01:00
refactor(zeitkarten/cleanup): relocate shared timecard UI out of app/admin; delete dead code
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) <noreply@anthropic.com>
This commit is contained in:
1 parent
f9856627f5
commit
d02fac8b34
16 files changed
+2
-487
No files matched your search
@@ -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',
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -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 (
|
||||
<Link
|
||||
href="/marketplace"
|
||||
className="group card-shell hover:border-strong transition-all overflow-hidden flex flex-col"
|
||||
>
|
||||
<div className="relative aspect-4/3 bg-surface-raised">
|
||||
{product.image_url ? (
|
||||
<Image
|
||||
src={product.image_url}
|
||||
alt={product.title}
|
||||
fill
|
||||
className="object-contain p-4 group-hover:scale-105 transition-transform duration-300"
|
||||
sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<Package className="w-12 h-12 text-text-muted" />
|
||||
</div>
|
||||
)}
|
||||
{stockOneLabel && product.quantity <= 1 && (
|
||||
<span className="absolute top-2 right-2 text-xs bg-warning-100 dark:bg-warning-900/30 text-warning-700 dark:text-warning-400 font-medium px-2 py-0.5 rounded-full">
|
||||
{stockOneLabel}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="p-4 flex flex-col gap-2 flex-1">
|
||||
<div>
|
||||
<p className="text-xs text-text-tertiary font-medium uppercase tracking-wide">{product.brand}</p>
|
||||
<h3 className="font-medium text-text-primary group-hover:text-action transition-colors line-clamp-2 leading-snug">
|
||||
{product.title}
|
||||
</h3>
|
||||
</div>
|
||||
{product.description && (
|
||||
<p className="text-sm text-text-tertiary line-clamp-2">{product.description}</p>
|
||||
)}
|
||||
{/* 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 && (
|
||||
<CO2Badge category={product.category} className="text-xs" />
|
||||
)}
|
||||
<div className="mt-auto flex items-center justify-between pt-2">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Tag className="w-3.5 h-3.5 text-action" />
|
||||
<span className="font-bold text-action">{formatCHF(product.price)}</span>
|
||||
</div>
|
||||
<span className="text-xs bg-surface-raised text-text-secondary px-2 py-0.5 rounded-full capitalize">
|
||||
{product.condition}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</Link>
|
||||
)
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -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)
|
||||
|
||||
@@ -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<unknown>) => {
|
||||
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<unknown>) => {
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -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)
|
||||
// ============================================================================
|
||||
|
||||
@@ -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<CreatedOrder> {
|
||||
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
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user