update: Major Overhaul to all subsystems

This commit is contained in:
2026-03-07 11:32:18 +02:00
parent 810e81b323
commit c62188fda6
107 changed files with 20414 additions and 929 deletions

View File

@@ -0,0 +1,293 @@
import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import api from "../../api/client";
import { useAuth } from "../../auth/AuthContext";
const STATUS_COLORS = {
draft: { bg: "var(--bg-card-hover)", color: "var(--text-secondary)" },
confirmed: { bg: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" },
in_production: { bg: "#fff7ed", color: "#9a3412" },
shipped: { bg: "#f5f3ff", color: "#6d28d9" },
delivered: { bg: "var(--success-bg)", color: "var(--success-text)" },
cancelled: { bg: "var(--danger-bg)", color: "var(--danger-text)" },
};
const PAYMENT_COLORS = {
pending: { bg: "#fef9c3", color: "#854d0e" },
partial: { bg: "#fff7ed", color: "#9a3412" },
paid: { bg: "var(--success-bg)", color: "var(--success-text)" },
};
const labelStyle = {
display: "block",
marginBottom: 4,
fontSize: 12,
color: "var(--text-secondary)",
fontWeight: 500,
};
function ReadField({ label, value }) {
return (
<div>
<div style={labelStyle}>{label}</div>
<div className="text-sm" style={{ color: "var(--text-primary)" }}>
{value || <span style={{ color: "var(--text-muted)" }}></span>}
</div>
</div>
);
}
function SectionCard({ title, children }) {
return (
<div className="ui-section-card mb-4">
<h2 className="ui-section-card__header-title mb-4">{title}</h2>
{children}
</div>
);
}
export default function OrderDetail() {
const { id } = useParams();
const navigate = useNavigate();
const { hasPermission } = useAuth();
const canEdit = hasPermission("crm", "edit");
const [order, setOrder] = useState(null);
const [customer, setCustomer] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
useEffect(() => {
api.get(`/crm/orders/${id}`)
.then((data) => {
setOrder(data);
if (data.customer_id) {
api.get(`/crm/customers/${data.customer_id}`)
.then(setCustomer)
.catch(() => {});
}
})
.catch((err) => setError(err.message))
.finally(() => setLoading(false));
}, [id]);
if (loading) {
return <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>;
}
if (error) {
return (
<div className="text-sm rounded-md p-3 border" style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}>
{error}
</div>
);
}
if (!order) return null;
const statusStyle = STATUS_COLORS[order.status] || STATUS_COLORS.draft;
const payStyle = PAYMENT_COLORS[order.payment_status] || PAYMENT_COLORS.pending;
const shipping = order.shipping || {};
const subtotal = (order.items || []).reduce((sum, item) => {
return sum + (Number(item.quantity) || 0) * (Number(item.unit_price) || 0);
}, 0);
const discount = order.discount || {};
const discountAmount =
discount.type === "percentage"
? subtotal * ((Number(discount.value) || 0) / 100)
: Number(discount.value) || 0;
const total = Number(order.total_price || 0);
return (
<div style={{ maxWidth: 900 }}>
{/* Header */}
<div className="flex items-start justify-between mb-6">
<div>
<div className="flex items-center gap-3 mb-1">
<h1 className="text-2xl font-bold font-mono" style={{ color: "var(--text-heading)" }}>
{order.order_number}
</h1>
<span
className="px-2 py-0.5 text-xs rounded-full capitalize"
style={{ backgroundColor: statusStyle.bg, color: statusStyle.color }}
>
{(order.status || "draft").replace("_", " ")}
</span>
</div>
{customer ? (
<button
onClick={() => navigate(`/crm/customers/${customer.id}`)}
className="text-sm hover:underline"
style={{ color: "var(--accent)", background: "none", border: "none", cursor: "pointer", padding: 0 }}
>
{customer.organization ? `${customer.name} / ${customer.organization}` : customer.name}
</button>
) : (
<span className="text-sm" style={{ color: "var(--text-muted)" }}>{order.customer_id}</span>
)}
<p className="text-xs mt-1" style={{ color: "var(--text-muted)" }}>
Created {order.created_at ? new Date(order.created_at).toLocaleDateString() : "—"}
{order.updated_at && order.updated_at !== order.created_at && (
<span> · Updated {new Date(order.updated_at).toLocaleDateString()}</span>
)}
</p>
</div>
<div className="flex gap-2">
{customer && (
<button
onClick={() => navigate(`/crm/customers/${customer.id}`)}
className="px-3 py-1.5 text-sm rounded-md border cursor-pointer hover:opacity-80"
style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)" }}
>
Back to Customer
</button>
)}
{canEdit && (
<button
onClick={() => navigate(`/crm/orders/${id}/edit`)}
className="px-4 py-1.5 text-sm rounded-md cursor-pointer hover:opacity-90"
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
>
Edit
</button>
)}
</div>
</div>
{/* Items */}
<SectionCard title="Items">
{(order.items || []).length === 0 ? (
<p className="text-sm" style={{ color: "var(--text-muted)" }}>No items.</p>
) : (
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr style={{ borderBottom: "1px solid var(--border-primary)" }}>
<th className="pb-2 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Item</th>
<th className="pb-2 text-right font-medium" style={{ color: "var(--text-secondary)" }}>Qty</th>
<th className="pb-2 text-right font-medium" style={{ color: "var(--text-secondary)" }}>Unit Price</th>
<th className="pb-2 text-right font-medium" style={{ color: "var(--text-secondary)" }}>Line Total</th>
</tr>
</thead>
<tbody>
{order.items.map((item, idx) => {
const lineTotal = (Number(item.quantity) || 0) * (Number(item.unit_price) || 0);
const label =
item.type === "product"
? item.product_name || item.product_id || "Product"
: item.type === "console_device"
? `${item.device_id || ""}${item.label ? ` (${item.label})` : ""}`
: item.description || "—";
return (
<tr
key={idx}
style={{ borderBottom: idx < order.items.length - 1 ? "1px solid var(--border-secondary)" : "none" }}
>
<td className="py-2 pr-4">
<span style={{ color: "var(--text-primary)" }}>{label}</span>
<span className="ml-2 text-xs px-1.5 py-0.5 rounded-full" style={{ backgroundColor: "var(--bg-primary)", color: "var(--text-muted)" }}>
{item.type.replace("_", " ")}
</span>
{Array.isArray(item.serial_numbers) && item.serial_numbers.length > 0 && (
<div className="text-xs mt-0.5 font-mono" style={{ color: "var(--text-muted)" }}>
SN: {item.serial_numbers.join(", ")}
</div>
)}
</td>
<td className="py-2 text-right" style={{ color: "var(--text-primary)" }}>{item.quantity}</td>
<td className="py-2 text-right" style={{ color: "var(--text-primary)" }}>
{order.currency} {Number(item.unit_price || 0).toFixed(2)}
</td>
<td className="py-2 text-right font-medium" style={{ color: "var(--text-heading)" }}>
{order.currency} {lineTotal.toFixed(2)}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
)}
</SectionCard>
{/* Pricing Summary */}
<SectionCard title="Pricing">
<div style={{ display: "flex", flexDirection: "column", gap: 8, maxWidth: 300, marginLeft: "auto" }}>
<div className="flex justify-between text-sm">
<span style={{ color: "var(--text-secondary)" }}>Subtotal</span>
<span style={{ color: "var(--text-primary)" }}>{order.currency} {subtotal.toFixed(2)}</span>
</div>
{discountAmount > 0 && (
<div className="flex justify-between text-sm">
<span style={{ color: "var(--text-secondary)" }}>
Discount
{discount.type === "percentage" && ` (${discount.value}%)`}
{discount.reason && `${discount.reason}`}
</span>
<span style={{ color: "var(--danger-text)" }}>{order.currency} {discountAmount.toFixed(2)}</span>
</div>
)}
<div
className="flex justify-between text-sm font-semibold pt-2"
style={{ borderTop: "1px solid var(--border-primary)" }}
>
<span style={{ color: "var(--text-heading)" }}>Total</span>
<span style={{ color: "var(--text-heading)" }}>{order.currency} {total.toFixed(2)}</span>
</div>
</div>
</SectionCard>
{/* Payment */}
<SectionCard title="Payment">
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
<div>
<div style={labelStyle}>Payment Status</div>
<span
className="px-2 py-0.5 text-xs rounded-full capitalize"
style={{ backgroundColor: payStyle.bg, color: payStyle.color }}
>
{order.payment_status || "pending"}
</span>
</div>
<div>
<div style={labelStyle}>Invoice</div>
{order.invoice_path ? (
<span className="text-sm font-mono" style={{ color: "var(--text-primary)" }}>
{order.invoice_path}
</span>
) : (
<span style={{ color: "var(--text-muted)", fontSize: 14 }}></span>
)}
</div>
</div>
</SectionCard>
{/* Shipping */}
<SectionCard title="Shipping">
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
<ReadField label="Method" value={shipping.method} />
<ReadField label="Carrier" value={shipping.carrier} />
<ReadField label="Tracking Number" value={shipping.tracking_number} />
<ReadField label="Destination" value={shipping.destination} />
<ReadField
label="Shipped At"
value={shipping.shipped_at ? new Date(shipping.shipped_at).toLocaleDateString() : null}
/>
<ReadField
label="Delivered At"
value={shipping.delivered_at ? new Date(shipping.delivered_at).toLocaleDateString() : null}
/>
</div>
</SectionCard>
{/* Notes */}
{order.notes && (
<SectionCard title="Notes">
<p className="text-sm whitespace-pre-wrap" style={{ color: "var(--text-primary)" }}>{order.notes}</p>
</SectionCard>
)}
</div>
);
}

View File

@@ -0,0 +1,662 @@
import { useState, useEffect } from "react";
import { useNavigate, useParams, useSearchParams } from "react-router-dom";
import api from "../../api/client";
import { useAuth } from "../../auth/AuthContext";
const ORDER_STATUSES = ["draft", "confirmed", "in_production", "shipped", "delivered", "cancelled"];
const PAYMENT_STATUSES = ["pending", "partial", "paid"];
const CURRENCIES = ["EUR", "USD", "GBP"];
const ITEM_TYPES = ["product", "console_device", "freetext"];
const inputClass = "w-full px-3 py-2 text-sm rounded-md border";
const inputStyle = {
backgroundColor: "var(--bg-input)",
borderColor: "var(--border-primary)",
color: "var(--text-primary)",
};
const labelStyle = {
display: "block",
marginBottom: 4,
fontSize: 12,
color: "var(--text-secondary)",
fontWeight: 500,
};
function Field({ label, children, style }) {
return (
<div style={style}>
<label style={labelStyle}>{label}</label>
{children}
</div>
);
}
function SectionCard({ title, children }) {
return (
<div className="ui-section-card mb-4">
<h2 className="ui-section-card__header-title mb-4">{title}</h2>
{children}
</div>
);
}
const emptyItem = () => ({
type: "product",
product_id: "",
product_name: "",
description: "",
device_id: "",
label: "",
quantity: 1,
unit_price: 0,
serial_numbers: "",
});
export default function OrderForm() {
const { id } = useParams();
const isEdit = Boolean(id);
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { hasPermission } = useAuth();
const canEdit = hasPermission("crm", "edit");
const [form, setForm] = useState({
customer_id: searchParams.get("customer_id") || "",
order_number: "",
status: "draft",
currency: "EUR",
items: [],
discount: { type: "percentage", value: 0, reason: "" },
payment_status: "pending",
invoice_path: "",
shipping: {
method: "",
carrier: "",
tracking_number: "",
destination: "",
shipped_at: "",
delivered_at: "",
},
notes: "",
});
const [customers, setCustomers] = useState([]);
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(isEdit);
const [saving, setSaving] = useState(false);
const [error, setError] = useState("");
const [customerSearch, setCustomerSearch] = useState("");
const [showCustomerDropdown, setShowCustomerDropdown] = useState(false);
// Load customers and products
useEffect(() => {
api.get("/crm/customers").then((d) => setCustomers(d.customers || [])).catch(() => {});
api.get("/crm/products").then((d) => setProducts(d.products || [])).catch(() => {});
}, []);
// Load order for edit
useEffect(() => {
if (!isEdit) return;
api.get(`/crm/orders/${id}`)
.then((data) => {
const shipping = data.shipping || {};
setForm({
customer_id: data.customer_id || "",
order_number: data.order_number || "",
status: data.status || "draft",
currency: data.currency || "EUR",
items: (data.items || []).map((item) => ({
...emptyItem(),
...item,
serial_numbers: Array.isArray(item.serial_numbers)
? item.serial_numbers.join(", ")
: item.serial_numbers || "",
})),
discount: data.discount || { type: "percentage", value: 0, reason: "" },
payment_status: data.payment_status || "pending",
invoice_path: data.invoice_path || "",
shipping: {
method: shipping.method || "",
carrier: shipping.carrier || "",
tracking_number: shipping.tracking_number || "",
destination: shipping.destination || "",
shipped_at: shipping.shipped_at ? shipping.shipped_at.slice(0, 10) : "",
delivered_at: shipping.delivered_at ? shipping.delivered_at.slice(0, 10) : "",
},
notes: data.notes || "",
});
})
.catch((err) => setError(err.message))
.finally(() => setLoading(false));
}, [id, isEdit]);
// Set customer search label when customer_id loads
useEffect(() => {
if (form.customer_id && customers.length > 0) {
const c = customers.find((x) => x.id === form.customer_id);
if (c) setCustomerSearch(c.organization ? `${c.name} / ${c.organization}` : c.name);
}
}, [form.customer_id, customers]);
const setField = (key, value) => setForm((f) => ({ ...f, [key]: value }));
const setShipping = (key, value) => setForm((f) => ({ ...f, shipping: { ...f.shipping, [key]: value } }));
const setDiscount = (key, value) => setForm((f) => ({ ...f, discount: { ...f.discount, [key]: value } }));
const addItem = () => setForm((f) => ({ ...f, items: [...f.items, emptyItem()] }));
const removeItem = (idx) => setForm((f) => ({ ...f, items: f.items.filter((_, i) => i !== idx) }));
const setItem = (idx, key, value) =>
setForm((f) => ({
...f,
items: f.items.map((item, i) => (i === idx ? { ...item, [key]: value } : item)),
}));
const onProductSelect = (idx, productId) => {
const product = products.find((p) => p.id === productId);
setForm((f) => ({
...f,
items: f.items.map((item, i) =>
i === idx
? { ...item, product_id: productId, product_name: product?.name || "", unit_price: product?.price || 0 }
: item
),
}));
};
// Computed pricing
const subtotal = form.items.reduce((sum, item) => {
return sum + (Number(item.quantity) || 0) * (Number(item.unit_price) || 0);
}, 0);
const discountAmount =
form.discount.type === "percentage"
? subtotal * ((Number(form.discount.value) || 0) / 100)
: Number(form.discount.value) || 0;
const total = Math.max(0, subtotal - discountAmount);
const filteredCustomers = customerSearch
? customers.filter((c) => {
const q = customerSearch.toLowerCase();
return c.name.toLowerCase().includes(q) || (c.organization || "").toLowerCase().includes(q);
})
: customers.slice(0, 20);
const handleSave = async () => {
if (!form.customer_id) { setError("Please select a customer."); return; }
setSaving(true);
setError("");
try {
const payload = {
customer_id: form.customer_id,
order_number: form.order_number || undefined,
status: form.status,
currency: form.currency,
items: form.items.map((item) => ({
type: item.type,
product_id: item.product_id || null,
product_name: item.product_name || null,
description: item.description || null,
device_id: item.device_id || null,
label: item.label || null,
quantity: Number(item.quantity) || 1,
unit_price: Number(item.unit_price) || 0,
serial_numbers: item.serial_numbers
? item.serial_numbers.split(",").map((s) => s.trim()).filter(Boolean)
: [],
})),
subtotal,
discount: {
type: form.discount.type,
value: Number(form.discount.value) || 0,
reason: form.discount.reason || "",
},
total_price: total,
payment_status: form.payment_status,
invoice_path: form.invoice_path || "",
shipping: {
method: form.shipping.method || "",
carrier: form.shipping.carrier || "",
tracking_number: form.shipping.tracking_number || "",
destination: form.shipping.destination || "",
shipped_at: form.shipping.shipped_at || null,
delivered_at: form.shipping.delivered_at || null,
},
notes: form.notes || "",
};
if (isEdit) {
await api.put(`/crm/orders/${id}`, payload);
navigate(`/crm/orders/${id}`);
} else {
const result = await api.post("/crm/orders", payload);
navigate(`/crm/orders/${result.id}`);
}
} catch (err) {
setError(err.message);
} finally {
setSaving(false);
}
};
const handleDelete = async () => {
if (!window.confirm("Delete this order? This cannot be undone.")) return;
try {
await api.delete(`/crm/orders/${id}`);
navigate("/crm/orders");
} catch (err) {
setError(err.message);
}
};
if (loading) {
return <div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>;
}
if (!canEdit) {
return <div className="text-sm p-3" style={{ color: "var(--danger-text)" }}>No permission to edit orders.</div>;
}
return (
<div style={{ maxWidth: 900 }}>
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>
{isEdit ? "Edit Order" : "New Order"}
</h1>
<button
onClick={() => navigate(isEdit ? `/crm/orders/${id}` : "/crm/orders")}
className="px-3 py-1.5 text-sm rounded-md border cursor-pointer hover:opacity-80"
style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)" }}
>
Cancel
</button>
</div>
{error && (
<div
className="text-sm rounded-md p-3 mb-4 border"
style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}
>
{error}
</div>
)}
{/* 1. Customer */}
<SectionCard title="Customer">
<div style={{ position: "relative" }}>
<label style={labelStyle}>Customer *</label>
<input
className={inputClass}
style={inputStyle}
placeholder="Search by name or organization..."
value={customerSearch}
onChange={(e) => {
setCustomerSearch(e.target.value);
setShowCustomerDropdown(true);
if (!e.target.value) setField("customer_id", "");
}}
onFocus={() => setShowCustomerDropdown(true)}
onBlur={() => setTimeout(() => setShowCustomerDropdown(false), 150)}
/>
{showCustomerDropdown && filteredCustomers.length > 0 && (
<div
className="absolute z-10 w-full mt-1 rounded-md border shadow-lg"
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", maxHeight: 200, overflowY: "auto" }}
>
{filteredCustomers.map((c) => (
<div
key={c.id}
className="px-3 py-2 text-sm cursor-pointer hover:opacity-80"
style={{ color: "var(--text-primary)", borderBottom: "1px solid var(--border-secondary)" }}
onMouseDown={() => {
setField("customer_id", c.id);
setCustomerSearch(c.organization ? `${c.name} / ${c.organization}` : c.name);
setShowCustomerDropdown(false);
}}
>
<span style={{ color: "var(--text-heading)" }}>{c.name}</span>
{c.organization && (
<span className="ml-2 text-xs" style={{ color: "var(--text-muted)" }}>{c.organization}</span>
)}
</div>
))}
</div>
)}
</div>
</SectionCard>
{/* 2. Order Info */}
<SectionCard title="Order Info">
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16 }}>
<Field label="Order Number">
<input
className={inputClass}
style={inputStyle}
placeholder="Auto-generated if empty"
value={form.order_number}
onChange={(e) => setField("order_number", e.target.value)}
/>
</Field>
<Field label="Status">
<select className={inputClass} style={inputStyle} value={form.status}
onChange={(e) => setField("status", e.target.value)}>
{ORDER_STATUSES.map((s) => (
<option key={s} value={s}>{s.replace("_", " ")}</option>
))}
</select>
</Field>
<Field label="Currency">
<select className={inputClass} style={inputStyle} value={form.currency}
onChange={(e) => setField("currency", e.target.value)}>
{CURRENCIES.map((c) => <option key={c} value={c}>{c}</option>)}
</select>
</Field>
</div>
</SectionCard>
{/* 3. Items */}
<SectionCard title="Items">
{form.items.length === 0 ? (
<p className="text-sm mb-4" style={{ color: "var(--text-muted)" }}>No items yet.</p>
) : (
<div className="space-y-3 mb-4">
{form.items.map((item, idx) => (
<div
key={idx}
className="rounded-md border p-4"
style={{ backgroundColor: "var(--bg-primary)", borderColor: "var(--border-secondary)" }}
>
<div style={{ display: "grid", gridTemplateColumns: "140px 1fr 100px 120px auto", gap: 12, alignItems: "end" }}>
<Field label="Type">
<select
className={inputClass}
style={inputStyle}
value={item.type}
onChange={(e) => setItem(idx, "type", e.target.value)}
>
{ITEM_TYPES.map((t) => <option key={t} value={t}>{t.replace("_", " ")}</option>)}
</select>
</Field>
{item.type === "product" && (
<Field label="Product">
<select
className={inputClass}
style={inputStyle}
value={item.product_id}
onChange={(e) => onProductSelect(idx, e.target.value)}
>
<option value="">Select product...</option>
{products.map((p) => (
<option key={p.id} value={p.id}>{p.name}</option>
))}
</select>
</Field>
)}
{item.type === "console_device" && (
<Field label="Device ID + Label">
<div style={{ display: "flex", gap: 8 }}>
<input
className={inputClass}
style={inputStyle}
placeholder="Device UID"
value={item.device_id}
onChange={(e) => setItem(idx, "device_id", e.target.value)}
/>
<input
className={inputClass}
style={inputStyle}
placeholder="Label"
value={item.label}
onChange={(e) => setItem(idx, "label", e.target.value)}
/>
</div>
</Field>
)}
{item.type === "freetext" && (
<Field label="Description">
<input
className={inputClass}
style={inputStyle}
placeholder="Description..."
value={item.description}
onChange={(e) => setItem(idx, "description", e.target.value)}
/>
</Field>
)}
<Field label="Qty">
<input
type="number"
min="1"
className={inputClass}
style={inputStyle}
value={item.quantity}
onChange={(e) => setItem(idx, "quantity", e.target.value)}
/>
</Field>
<Field label="Unit Price">
<input
type="number"
min="0"
step="0.01"
className={inputClass}
style={inputStyle}
value={item.unit_price}
onChange={(e) => setItem(idx, "unit_price", e.target.value)}
/>
</Field>
<div style={{ paddingBottom: 2 }}>
<button
type="button"
onClick={() => removeItem(idx)}
className="px-3 py-2 text-sm rounded-md border cursor-pointer hover:opacity-80"
style={{ borderColor: "var(--danger)", color: "var(--danger-text)", whiteSpace: "nowrap" }}
>
Remove
</button>
</div>
</div>
<div className="mt-3">
<Field label="Serial Numbers (comma-separated)">
<input
className={inputClass}
style={inputStyle}
placeholder="SN001, SN002..."
value={item.serial_numbers}
onChange={(e) => setItem(idx, "serial_numbers", e.target.value)}
/>
</Field>
</div>
</div>
))}
</div>
)}
<button
type="button"
onClick={addItem}
className="px-3 py-1.5 text-sm rounded-md border cursor-pointer hover:opacity-80"
style={{ borderColor: "var(--border-primary)", color: "var(--text-secondary)" }}
>
+ Add Item
</button>
</SectionCard>
{/* 4. Pricing */}
<SectionCard title="Pricing">
<div className="flex gap-8 mb-4">
<div>
<div style={labelStyle}>Subtotal</div>
<div className="text-lg font-semibold" style={{ color: "var(--text-heading)" }}>
{form.currency} {subtotal.toFixed(2)}
</div>
</div>
<div>
<div style={labelStyle}>Total</div>
<div className="text-lg font-semibold" style={{ color: "var(--text-heading)" }}>
{form.currency} {total.toFixed(2)}
</div>
</div>
</div>
<div style={{ display: "grid", gridTemplateColumns: "140px 160px 1fr", gap: 16 }}>
<Field label="Discount Type">
<select
className={inputClass}
style={inputStyle}
value={form.discount.type}
onChange={(e) => setDiscount("type", e.target.value)}
>
<option value="percentage">Percentage (%)</option>
<option value="fixed">Fixed Amount</option>
</select>
</Field>
<Field label={form.discount.type === "percentage" ? "Discount %" : "Discount Amount"}>
<input
type="number"
min="0"
step="0.01"
className={inputClass}
style={inputStyle}
value={form.discount.value}
onChange={(e) => setDiscount("value", e.target.value)}
/>
</Field>
<Field label="Discount Reason">
<input
className={inputClass}
style={inputStyle}
placeholder="Optional reason..."
value={form.discount.reason}
onChange={(e) => setDiscount("reason", e.target.value)}
/>
</Field>
</div>
{Number(form.discount.value) > 0 && (
<p className="text-xs mt-2" style={{ color: "var(--text-muted)" }}>
Discount: {form.currency} {discountAmount.toFixed(2)}
</p>
)}
</SectionCard>
{/* 5. Payment */}
<SectionCard title="Payment">
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
<Field label="Payment Status">
<select
className={inputClass}
style={inputStyle}
value={form.payment_status}
onChange={(e) => setField("payment_status", e.target.value)}
>
{PAYMENT_STATUSES.map((s) => <option key={s} value={s}>{s}</option>)}
</select>
</Field>
<Field label="Invoice Path (Nextcloud)">
<input
className={inputClass}
style={inputStyle}
placeholder="05_Customers/FOLDER/invoice.pdf"
value={form.invoice_path}
onChange={(e) => setField("invoice_path", e.target.value)}
/>
</Field>
</div>
</SectionCard>
{/* 6. Shipping */}
<SectionCard title="Shipping">
<div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16, marginBottom: 16 }}>
<Field label="Method">
<input
className={inputClass}
style={inputStyle}
placeholder="e.g. courier, pickup"
value={form.shipping.method}
onChange={(e) => setShipping("method", e.target.value)}
/>
</Field>
<Field label="Carrier">
<input
className={inputClass}
style={inputStyle}
placeholder="e.g. ACS, DHL"
value={form.shipping.carrier}
onChange={(e) => setShipping("carrier", e.target.value)}
/>
</Field>
<Field label="Tracking Number">
<input
className={inputClass}
style={inputStyle}
value={form.shipping.tracking_number}
onChange={(e) => setShipping("tracking_number", e.target.value)}
/>
</Field>
<Field label="Destination" style={{ gridColumn: "1 / -1" }}>
<input
className={inputClass}
style={inputStyle}
placeholder="City, Country"
value={form.shipping.destination}
onChange={(e) => setShipping("destination", e.target.value)}
/>
</Field>
<Field label="Shipped At">
<input
type="date"
className={inputClass}
style={inputStyle}
value={form.shipping.shipped_at}
onChange={(e) => setShipping("shipped_at", e.target.value)}
/>
</Field>
<Field label="Delivered At">
<input
type="date"
className={inputClass}
style={inputStyle}
value={form.shipping.delivered_at}
onChange={(e) => setShipping("delivered_at", e.target.value)}
/>
</Field>
</div>
</SectionCard>
{/* 7. Notes */}
<SectionCard title="Notes">
<textarea
className={inputClass}
style={{ ...inputStyle, resize: "vertical", minHeight: 100 }}
placeholder="Internal notes..."
value={form.notes}
onChange={(e) => setField("notes", e.target.value)}
/>
</SectionCard>
{/* Actions */}
<div className="flex items-center gap-3">
<button
onClick={handleSave}
disabled={saving}
className="px-5 py-2 text-sm rounded-md cursor-pointer hover:opacity-90"
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)", opacity: saving ? 0.7 : 1 }}
>
{saving ? "Saving..." : isEdit ? "Save Changes" : "Create Order"}
</button>
{isEdit && (
<button
onClick={handleDelete}
className="px-4 py-2 text-sm rounded-md border cursor-pointer hover:opacity-80"
style={{ borderColor: "var(--danger)", color: "var(--danger-text)" }}
>
Delete Order
</button>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,207 @@
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import api from "../../api/client";
import { useAuth } from "../../auth/AuthContext";
const STATUS_COLORS = {
draft: { bg: "var(--bg-card-hover)", color: "var(--text-secondary)" },
confirmed: { bg: "var(--badge-blue-bg)", color: "var(--badge-blue-text)" },
in_production: { bg: "#fff7ed", color: "#9a3412" },
shipped: { bg: "#f5f3ff", color: "#6d28d9" },
delivered: { bg: "var(--success-bg)", color: "var(--success-text)" },
cancelled: { bg: "var(--danger-bg)", color: "var(--danger-text)" },
};
const PAYMENT_COLORS = {
pending: { bg: "#fef9c3", color: "#854d0e" },
partial: { bg: "#fff7ed", color: "#9a3412" },
paid: { bg: "var(--success-bg)", color: "var(--success-text)" },
};
const inputStyle = {
backgroundColor: "var(--bg-input)",
borderColor: "var(--border-primary)",
color: "var(--text-primary)",
};
const ORDER_STATUSES = ["draft", "confirmed", "in_production", "shipped", "delivered", "cancelled"];
const PAYMENT_STATUSES = ["pending", "partial", "paid"];
export default function OrderList() {
const [orders, setOrders] = useState([]);
const [customerMap, setCustomerMap] = useState({});
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [statusFilter, setStatusFilter] = useState("");
const [paymentFilter, setPaymentFilter] = useState("");
const [hoveredRow, setHoveredRow] = useState(null);
const navigate = useNavigate();
const { hasPermission } = useAuth();
const canEdit = hasPermission("crm", "edit");
useEffect(() => {
api.get("/crm/customers")
.then((data) => {
const map = {};
(data.customers || []).forEach((c) => { map[c.id] = c; });
setCustomerMap(map);
})
.catch(() => {});
}, []);
const fetchOrders = async () => {
setLoading(true);
setError("");
try {
const params = new URLSearchParams();
if (statusFilter) params.set("status", statusFilter);
if (paymentFilter) params.set("payment_status", paymentFilter);
const qs = params.toString();
const data = await api.get(`/crm/orders${qs ? `?${qs}` : ""}`);
setOrders(data.orders || []);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchOrders();
}, [statusFilter, paymentFilter]);
return (
<div>
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold" style={{ color: "var(--text-heading)" }}>Orders</h1>
{canEdit && (
<button
onClick={() => navigate("/crm/orders/new")}
className="px-4 py-2 text-sm rounded-md hover:opacity-90 transition-colors cursor-pointer"
style={{ backgroundColor: "var(--btn-primary)", color: "var(--text-white)" }}
>
New Order
</button>
)}
</div>
<div className="flex gap-3 mb-4">
<select
value={statusFilter}
onChange={(e) => setStatusFilter(e.target.value)}
className="px-3 py-2 text-sm rounded-md border"
style={inputStyle}
>
<option value="">All Statuses</option>
{ORDER_STATUSES.map((s) => (
<option key={s} value={s}>{s.replace("_", " ")}</option>
))}
</select>
<select
value={paymentFilter}
onChange={(e) => setPaymentFilter(e.target.value)}
className="px-3 py-2 text-sm rounded-md border"
style={inputStyle}
>
<option value="">All Payment Statuses</option>
{PAYMENT_STATUSES.map((s) => (
<option key={s} value={s}>{s}</option>
))}
</select>
</div>
{error && (
<div
className="text-sm rounded-md p-3 mb-4 border"
style={{ backgroundColor: "var(--danger-bg)", borderColor: "var(--danger)", color: "var(--danger-text)" }}
>
{error}
</div>
)}
{loading ? (
<div className="text-center py-8" style={{ color: "var(--text-muted)" }}>Loading...</div>
) : orders.length === 0 ? (
<div
className="rounded-lg p-8 text-center text-sm border"
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)", color: "var(--text-muted)" }}
>
No orders found.
</div>
) : (
<div
className="rounded-lg overflow-hidden border"
style={{ backgroundColor: "var(--bg-card)", borderColor: "var(--border-primary)" }}
>
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr style={{ backgroundColor: "var(--bg-primary)", borderBottom: "1px solid var(--border-primary)" }}>
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Order #</th>
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Customer</th>
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Status</th>
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Total</th>
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Payment</th>
<th className="px-4 py-3 text-left font-medium" style={{ color: "var(--text-secondary)" }}>Date</th>
</tr>
</thead>
<tbody>
{orders.map((o, index) => {
const statusStyle = STATUS_COLORS[o.status] || STATUS_COLORS.draft;
const payStyle = PAYMENT_COLORS[o.payment_status] || PAYMENT_COLORS.pending;
const customer = customerMap[o.customer_id];
const customerName = customer
? customer.organization
? `${customer.name} / ${customer.organization}`
: customer.name
: o.customer_id || "—";
return (
<tr
key={o.id}
onClick={() => navigate(`/crm/orders/${o.id}`)}
className="cursor-pointer"
style={{
borderBottom: index < orders.length - 1 ? "1px solid var(--border-secondary)" : "none",
backgroundColor: hoveredRow === o.id ? "var(--bg-card-hover)" : "transparent",
}}
onMouseEnter={() => setHoveredRow(o.id)}
onMouseLeave={() => setHoveredRow(null)}
>
<td className="px-4 py-3 font-mono text-xs font-medium" style={{ color: "var(--text-heading)" }}>
{o.order_number}
</td>
<td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>{customerName}</td>
<td className="px-4 py-3">
<span
className="px-2 py-0.5 text-xs rounded-full capitalize"
style={{ backgroundColor: statusStyle.bg, color: statusStyle.color }}
>
{(o.status || "draft").replace("_", " ")}
</span>
</td>
<td className="px-4 py-3" style={{ color: "var(--text-primary)" }}>
{o.currency || "EUR"} {Number(o.total_price || 0).toFixed(2)}
</td>
<td className="px-4 py-3">
<span
className="px-2 py-0.5 text-xs rounded-full capitalize"
style={{ backgroundColor: payStyle.bg, color: payStyle.color }}
>
{o.payment_status || "pending"}
</span>
</td>
<td className="px-4 py-3 text-xs" style={{ color: "var(--text-muted)" }}>
{o.created_at ? new Date(o.created_at).toLocaleDateString() : "—"}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,3 @@
export { default as OrderList } from "./OrderList";
export { default as OrderForm } from "./OrderForm";
export { default as OrderDetail } from "./OrderDetail";