@flowselections/floriday-verkoop-module 1.0.11 → 1.0.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/dist-lib/components/verkoop/AutoFulfillmentStatusCard.d.ts +4 -0
  2. package/dist-lib/components/verkoop/AutoFulfillmentStatusCard.d.ts.map +1 -0
  3. package/dist-lib/components/verkoop/AutoFulfillmentStatusCard.js +95 -0
  4. package/dist-lib/components/verkoop/CartAssignmentWizard.d.ts +6 -0
  5. package/dist-lib/components/verkoop/CartAssignmentWizard.d.ts.map +1 -0
  6. package/dist-lib/components/verkoop/CartAssignmentWizard.js +194 -0
  7. package/dist-lib/components/verkoop/CreateOrderPage.d.ts.map +1 -1
  8. package/dist-lib/components/verkoop/CreateOrderPage.js +230 -192
  9. package/dist-lib/components/verkoop/OrderAfleverbrievenCard.d.ts +4 -0
  10. package/dist-lib/components/verkoop/OrderAfleverbrievenCard.d.ts.map +1 -0
  11. package/dist-lib/components/verkoop/OrderAfleverbrievenCard.js +44 -0
  12. package/dist-lib/components/verkoop/OrderKarindelingCard.d.ts +5 -0
  13. package/dist-lib/components/verkoop/OrderKarindelingCard.d.ts.map +1 -0
  14. package/dist-lib/components/verkoop/OrderKarindelingCard.js +160 -0
  15. package/dist-lib/components/verkoop/SalesOrderDetailView.d.ts.map +1 -1
  16. package/dist-lib/components/verkoop/SalesOrderDetailView.js +6 -3
  17. package/dist-lib/components/verkoop/SalesOrdersTable.d.ts.map +1 -1
  18. package/dist-lib/components/verkoop/SalesOrdersTable.js +3 -4
  19. package/dist-lib/components/verkoop/SearchableSelect.d.ts +19 -0
  20. package/dist-lib/components/verkoop/SearchableSelect.d.ts.map +1 -0
  21. package/dist-lib/components/verkoop/SearchableSelect.js +21 -0
  22. package/dist-lib/components/verkoop/VerkoopOrdersPage.d.ts.map +1 -1
  23. package/dist-lib/components/verkoop/VerkoopOrdersPage.js +39 -3
  24. package/dist-lib/integrations/supabase/auth-middleware.d.ts +1381 -86
  25. package/dist-lib/integrations/supabase/auth-middleware.d.ts.map +1 -1
  26. package/dist-lib/integrations/supabase/client.d.ts +1381 -86
  27. package/dist-lib/integrations/supabase/client.d.ts.map +1 -1
  28. package/dist-lib/integrations/supabase/client.server.d.ts +1381 -86
  29. package/dist-lib/integrations/supabase/client.server.d.ts.map +1 -1
  30. package/dist-lib/integrations/supabase/types.d.ts +1402 -79
  31. package/dist-lib/integrations/supabase/types.d.ts.map +1 -1
  32. package/dist-lib/lib/cart-lock.functions.d.ts +11225 -0
  33. package/dist-lib/lib/cart-lock.functions.d.ts.map +1 -0
  34. package/dist-lib/lib/cart-lock.functions.js +47 -0
  35. package/dist-lib/lib/cart-planner.d.ts +38 -0
  36. package/dist-lib/lib/cart-planner.d.ts.map +1 -0
  37. package/dist-lib/lib/cart-planner.js +217 -0
  38. package/dist-lib/lib/cart-replan.functions.d.ts +22467 -0
  39. package/dist-lib/lib/cart-replan.functions.d.ts.map +1 -0
  40. package/dist-lib/lib/cart-replan.functions.js +203 -0
  41. package/dist-lib/lib/create-order.functions.d.ts +100967 -0
  42. package/dist-lib/lib/create-order.functions.d.ts.map +1 -0
  43. package/dist-lib/lib/create-order.functions.js +343 -0
  44. package/dist-lib/lib/floriday-auto-fulfillment.functions.d.ts +33640 -0
  45. package/dist-lib/lib/floriday-auto-fulfillment.functions.d.ts.map +1 -0
  46. package/dist-lib/lib/floriday-auto-fulfillment.functions.js +65 -0
  47. package/dist-lib/lib/floriday-auto-fulfillment.server.d.ts +21 -0
  48. package/dist-lib/lib/floriday-auto-fulfillment.server.d.ts.map +1 -0
  49. package/dist-lib/lib/floriday-auto-fulfillment.server.js +352 -0
  50. package/dist-lib/lib/floriday-logistic-labels.functions.d.ts +11220 -0
  51. package/dist-lib/lib/floriday-logistic-labels.functions.d.ts.map +1 -0
  52. package/dist-lib/lib/floriday-logistic-labels.functions.js +171 -0
  53. package/dist-lib/lib/floriday-public.functions.d.ts +9067 -16
  54. package/dist-lib/lib/floriday-public.functions.d.ts.map +1 -1
  55. package/dist-lib/lib/floriday-public.functions.js +45 -47
  56. package/dist-lib/lib/floriday-writes.functions.d.ts +6475 -0
  57. package/dist-lib/lib/floriday-writes.functions.d.ts.map +1 -1
  58. package/dist-lib/lib/salesorders-mapping.d.ts +2 -0
  59. package/dist-lib/lib/salesorders-mapping.d.ts.map +1 -1
  60. package/dist-lib/lib/salesorders-mapping.js +46 -20
  61. package/dist-lib/lib/salesorders.functions.d.ts +4273 -388
  62. package/dist-lib/lib/salesorders.functions.d.ts.map +1 -1
  63. package/dist-lib/lib/salesorders.functions.js +8 -0
  64. package/dist-lib/lib/tradeitems.functions.d.ts +1381 -86
  65. package/dist-lib/lib/tradeitems.functions.d.ts.map +1 -1
  66. package/dist-lib/lib/useSalesOrdersQuery.d.ts +1 -0
  67. package/dist-lib/lib/useSalesOrdersQuery.d.ts.map +1 -1
  68. package/dist-lib/lib/useSalesOrdersQuery.js +130 -41
  69. package/package.json +1 -1
@@ -1,218 +1,256 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { useMemo, useState } from "react";
3
- import { Badge, Button, Input, Label, Popover, PopoverContent, PopoverTrigger, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, toast, } from "@flowselections/core";
2
+ // Handmatig aanmaken van een bestelling — gebruikt exact dezelfde workflow,
3
+ // server-fns en validaties als de Mailbox-module. Beide modules leunen op
4
+ // gedeelde queries (klanten, producten met voorraad, afleverlocaties,
5
+ // afhaallocaties, vervoerders, orderpicktijd) en dezelfde eerstmogelijke-
6
+ // leverdatum-berekening. Zie src/lib/create-order.functions.ts.
7
+ import { useEffect, useMemo, useRef, useState } from "react";
8
+ import { Button, Card, CardContent, CardHeader, CardTitle, Input, Label, Textarea, toast, } from "@flowselections/core";
4
9
  import { Link, useNavigate } from "@tanstack/react-router";
5
10
  import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
6
- import { ArrowLeft, ChevronDown, Plus, Search, Trash2, Truck, MapPin, } from "lucide-react";
7
- import { supabase } from "../../integrations/supabase/client";
11
+ import { ArrowLeft, Plus, Trash2 } from "lucide-react";
8
12
  import { useServerFn } from "@tanstack/react-start";
9
- import { getFlorydayCachedList } from "../../lib/floriday-public.functions";
10
- const eur = new Intl.NumberFormat("nl-NL", {
11
- style: "currency",
12
- currency: "EUR",
13
- });
14
- function pickStr(v) {
15
- if (v == null)
16
- return null;
17
- if (typeof v === "string")
18
- return v;
19
- if (typeof v === "number")
20
- return String(v);
21
- if (Array.isArray(v)) {
22
- for (const x of v) {
23
- const s = pickStr(x?.text ?? x?.value ?? x);
24
- if (s)
25
- return s;
26
- }
27
- return null;
28
- }
29
- if (typeof v === "object") {
30
- return (v.nl ?? v.NL ?? v.en ?? v.EN ?? v.text ?? v.value ??
31
- Object.values(v).find((x) => typeof x === "string") ??
32
- null);
33
- }
34
- return null;
13
+ import { SearchableSelect } from "./SearchableSelect";
14
+ import { CartAssignmentWizard } from "./CartAssignmentWizard";
15
+ import { listCustomersForCreateOrder, listProductsForCreateOrder, listDeliveryLocationsForCustomerCO, listPickupLocationsCO, listCarriersForCreateOrder, getOrderPickDaysCO, createManualOrder, } from "../../lib/create-order.functions";
16
+ function ReadOnlyField({ label, value }) {
17
+ return (_jsxs("div", { className: "space-y-0.5", children: [_jsx("div", { className: "text-[11px] uppercase tracking-wide text-muted-foreground", children: label }), _jsx("div", { className: "text-sm", children: value && String(value).trim() !== "" ? value : _jsx("span", { className: "text-muted-foreground", children: "\u2014" }) })] }));
35
18
  }
36
- function useCustomersForOrder() {
37
- return useQuery({
38
- queryKey: ["create-order", "customers"],
39
- queryFn: async () => {
40
- const { data, error } = await supabase
41
- .from("customers")
42
- .select("id, company_name, city, is_active")
43
- .or("is_active.is.null,is_active.eq.true")
44
- .order("company_name", { ascending: true })
45
- .limit(2000);
46
- if (error)
47
- throw error;
48
- return (data ?? []);
49
- },
50
- staleTime: 60000,
19
+ export function CreateOrderPage() {
20
+ const navigate = useNavigate();
21
+ const qc = useQueryClient();
22
+ const fetchCustomers = useServerFn(listCustomersForCreateOrder);
23
+ const fetchProducts = useServerFn(listProductsForCreateOrder);
24
+ const fetchDeliveryLocations = useServerFn(listDeliveryLocationsForCustomerCO);
25
+ const fetchPickupLocations = useServerFn(listPickupLocationsCO);
26
+ const fetchCarriers = useServerFn(listCarriersForCreateOrder);
27
+ const fetchPickDays = useServerFn(getOrderPickDaysCO);
28
+ const fetchCreate = useServerFn(createManualOrder);
29
+ const safe = async (fn) => {
30
+ try {
31
+ return await fn();
32
+ }
33
+ catch {
34
+ return { items: [] };
35
+ }
36
+ };
37
+ const customersQ = useQuery({ queryKey: ["co-customers"], queryFn: () => safe(() => fetchCustomers()) });
38
+ const productsQ = useQuery({ queryKey: ["co-products"], queryFn: () => safe(() => fetchProducts()) });
39
+ const pickupQ = useQuery({ queryKey: ["co-pickup"], queryFn: () => safe(() => fetchPickupLocations()) });
40
+ const carriersQ = useQuery({ queryKey: ["co-carriers"], queryFn: () => safe(() => fetchCarriers()) });
41
+ const pickDaysQ = useQuery({
42
+ queryKey: ["co-pickdays"],
43
+ queryFn: async () => { try {
44
+ return await fetchPickDays();
45
+ }
46
+ catch {
47
+ return { pickDays: 0 };
48
+ } },
51
49
  });
52
- }
53
- function useProductsForOrder() {
54
- const fetchCachedList = useServerFn(getFlorydayCachedList);
55
- return useQuery({
56
- queryKey: ["create-order", "products"],
50
+ const customers = customersQ.data?.items ?? [];
51
+ const products = productsQ.data?.items ?? [];
52
+ const pickupLocations = pickupQ.data?.items ?? [];
53
+ const carriers = carriersQ.data?.items ?? [];
54
+ const pickDays = Math.max(0, Number(pickDaysQ.data?.pickDays ?? 0));
55
+ const [customerId, setCustomerId] = useState(null);
56
+ const [deliveryLocationId, setDeliveryLocationId] = useState(null);
57
+ const [pickupLocationId, setPickupLocationId] = useState(null);
58
+ const [carrierId, setCarrierId] = useState(null);
59
+ const [deliveryDate, setDeliveryDate] = useState("");
60
+ const [notes, setNotes] = useState("");
61
+ const [lines, setLines] = useState([
62
+ { product_id: null, product_name: "", quantity: null, unit: "stuks", unit_price: null },
63
+ ]);
64
+ const [cartOrderId, setCartOrderId] = useState(null);
65
+ // Afleverlocaties van gekozen klant
66
+ const deliveryLocQ = useQuery({
67
+ queryKey: ["co-delivery-locations", customerId],
68
+ enabled: !!customerId,
57
69
  queryFn: async () => {
58
- const [localRes, floridayList] = await Promise.all([
59
- supabase
60
- .from("products")
61
- .select("id, product, sale_price, unit")
62
- .order("product", { ascending: true })
63
- .limit(2000),
64
- fetchCachedList({ data: { environment: "staging", entity: "trade-items", limit: 5000 } }),
65
- ]);
66
- if (localRes.error)
67
- throw localRes.error;
68
- const out = [];
69
- for (const r of localRes.data ?? []) {
70
- out.push({
71
- id: `local:${r.id}`,
72
- name: r.product ?? "Onbekend product",
73
- source: "local",
74
- price: r.sale_price != null ? Number(r.sale_price) : null,
75
- unit: r.unit ?? null,
76
- });
70
+ try {
71
+ return await fetchDeliveryLocations({ data: { customerId: customerId } });
77
72
  }
78
- for (const r of floridayList.rows ?? []) {
79
- const d = r.data ?? {};
80
- const name = pickStr(d.name) ??
81
- pickStr(d.productName) ??
82
- pickStr(d.tradeItemName) ??
83
- pickStr(d.tradeItemTexts) ??
84
- "Onbekend artikel";
85
- out.push({
86
- id: `floriday:${r.floriday_id}`,
87
- name,
88
- source: "floriday",
89
- price: null,
90
- });
73
+ catch {
74
+ return { items: [] };
91
75
  }
92
- return out;
93
76
  },
94
- staleTime: 60000,
95
77
  });
96
- }
97
- export function CreateOrderPage() {
98
- const navigate = useNavigate();
99
- const queryClient = useQueryClient();
100
- const customersQ = useCustomersForOrder();
101
- const productsQ = useProductsForOrder();
102
- const [customerId, setCustomerId] = useState("");
103
- const [deliveryDate, setDeliveryDate] = useState("");
104
- const [carrier, setCarrier] = useState("");
105
- const [country, setCountry] = useState("");
106
- const [productPickerOpen, setProductPickerOpen] = useState(false);
107
- const [productQuery, setProductQuery] = useState("");
108
- const [selectedProduct, setSelectedProduct] = useState(null);
109
- const [quantity, setQuantity] = useState("");
110
- const [unitPrice, setUnitPrice] = useState("");
111
- const [lines, setLines] = useState([]);
112
- const filteredProducts = useMemo(() => {
113
- const list = productsQ.data ?? [];
114
- const q = productQuery.trim().toLowerCase();
115
- const base = q
116
- ? list.filter((p) => p.name.toLowerCase().includes(q))
117
- : list;
118
- return base.slice(0, 100);
119
- }, [productsQ.data, productQuery]);
120
- const total = lines.reduce((s, l) => s + l.quantity * l.unitPrice, 0);
121
- const addLine = () => {
122
- if (!selectedProduct)
123
- return;
124
- const qty = Number(quantity);
125
- const price = Number(unitPrice);
126
- if (!Number.isFinite(qty) || qty <= 0) {
127
- toast.error("Vul een geldig aantal in");
128
- return;
78
+ const deliveryLocations = deliveryLocQ.data?.items ?? [];
79
+ const selectedLocation = deliveryLocations.find((l) => l.id === deliveryLocationId) ?? null;
80
+ // Reset delivery_location bij klantwissel
81
+ useEffect(() => {
82
+ if (deliveryLocationId && !deliveryLocations.some((l) => l.id === deliveryLocationId)) {
83
+ setDeliveryLocationId(null);
129
84
  }
130
- if (!Number.isFinite(price) || price < 0) {
131
- toast.error("Vul een geldige prijs in");
85
+ // eslint-disable-next-line react-hooks/exhaustive-deps
86
+ }, [customerId, deliveryLocQ.data]);
87
+ // Auto-fill vervoerder op basis van gekozen afleverlocatie (één keer per wissel)
88
+ const lastLocRef = useRef(null);
89
+ useEffect(() => {
90
+ if (deliveryLocationId !== lastLocRef.current) {
91
+ lastLocRef.current = deliveryLocationId;
92
+ const loc = deliveryLocations.find((l) => l.id === deliveryLocationId);
93
+ if (loc?.carrier_id)
94
+ setCarrierId(loc.carrier_id);
95
+ else if (deliveryLocationId === null)
96
+ setCarrierId(null);
97
+ }
98
+ // eslint-disable-next-line react-hooks/exhaustive-deps
99
+ }, [deliveryLocationId, deliveryLocations.length]);
100
+ // Eerst mogelijke leverdatum
101
+ const selectedCarrier = carriers.find((c) => c.id === carrierId) ?? null;
102
+ const carrierDeliveryDays = Math.max(0, Number(selectedCarrier?.delivery_days ?? 0));
103
+ const canPickDate = !!customerId && !!deliveryLocationId && !!pickupLocationId && !!carrierId;
104
+ const fmtISO = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
105
+ const earliestDate = useMemo(() => {
106
+ const base = new Date();
107
+ base.setHours(0, 0, 0, 0);
108
+ base.setDate(base.getDate() + pickDays + carrierDeliveryDays);
109
+ return base;
110
+ }, [pickDays, carrierDeliveryDays]);
111
+ const earliestISO = fmtISO(earliestDate);
112
+ const earliestLabel = earliestDate.toLocaleDateString("nl-NL", {
113
+ day: "numeric", month: "long", year: "numeric",
114
+ });
115
+ useEffect(() => {
116
+ if (!canPickDate)
132
117
  return;
118
+ if (!deliveryDate || deliveryDate < earliestISO) {
119
+ setDeliveryDate(earliestISO);
133
120
  }
134
- setLines((prev) => [
135
- ...prev,
136
- {
137
- key: `${selectedProduct.id}-${Date.now()}`,
138
- product: selectedProduct,
139
- quantity: qty,
140
- unitPrice: price,
141
- },
142
- ]);
143
- setSelectedProduct(null);
144
- setQuantity("");
145
- setUnitPrice("");
146
- setProductQuery("");
121
+ // eslint-disable-next-line react-hooks/exhaustive-deps
122
+ }, [canPickDate, earliestISO]);
123
+ const blockDecimal = (e) => {
124
+ if ([".", ",", "e", "E", "+", "-"].includes(e.key))
125
+ e.preventDefault();
147
126
  };
148
- const removeLine = (key) => setLines((prev) => prev.filter((l) => l.key !== key));
149
- const createMutation = useMutation({
127
+ const createMut = useMutation({
150
128
  mutationFn: async () => {
151
129
  if (!customerId)
152
130
  throw new Error("Selecteer een klant");
131
+ if (!deliveryLocationId)
132
+ throw new Error("Selecteer een afleverlocatie");
133
+ if (!pickupLocationId)
134
+ throw new Error("Selecteer een afhaallocatie (tuin)");
135
+ if (!carrierId)
136
+ throw new Error("Selecteer een vervoerder");
153
137
  if (!deliveryDate)
154
138
  throw new Error("Selecteer een leverdatum");
155
- if (lines.length === 0)
139
+ const validLines = lines.filter((l) => l.product_id && (l.quantity ?? 0) > 0);
140
+ if (validLines.length === 0)
156
141
  throw new Error("Voeg minimaal één product toe");
157
- const customer = customersQ.data?.find((c) => c.id === customerId);
158
- const orderNumber = `LOC-${new Date()
159
- .toISOString()
160
- .slice(0, 10)
161
- .replace(/-/g, "")}-${Math.floor(Math.random() * 9000 + 1000)}`;
162
- const { data: orderRow, error: orderErr } = await supabase
163
- .from("orders")
164
- .insert({
165
- order_number: orderNumber,
166
- customer_id: customerId,
167
- customer_name: customer?.company_name ?? "Onbekende klant",
168
- order_date: new Date().toISOString(),
169
- delivery_date: deliveryDate,
170
- status: "open",
171
- total: String(total.toFixed(2)),
172
- custom_fields: {
173
- source: "local",
174
- transporteur: carrier || null,
175
- land: country || null,
176
- },
177
- })
178
- .select("id")
179
- .single();
180
- if (orderErr)
181
- throw orderErr;
182
- const itemsPayload = lines.map((l) => ({
183
- order_id: orderRow.id,
184
- product_id: l.product.source === "local"
185
- ? l.product.id.replace(/^local:/, "")
186
- : undefined,
187
- product_name: l.product.name,
188
- quantity: Math.round(l.quantity),
189
- unit: l.product.unit ?? undefined,
190
- unit_price: l.unitPrice,
191
- }));
192
- const { error: itemsErr } = await supabase
193
- .from("order_items")
194
- .insert(itemsPayload);
195
- if (itemsErr)
196
- throw itemsErr;
142
+ for (const l of validLines) {
143
+ const p = products.find((x) => x.id === l.product_id);
144
+ const ppc = Math.max(1, Number(p?.plants_per_crate ?? 1));
145
+ const q = l.quantity ?? 0;
146
+ if (q < ppc || q % ppc !== 0) {
147
+ throw new Error(`"${p?.product ?? l.product_name}" moet per hele fust besteld worden (min. 1 fust = ${ppc} planten).`);
148
+ }
149
+ }
150
+ const customer = customers.find((c) => c.id === customerId);
151
+ const payload = {
152
+ customerId,
153
+ customerName: customer?.company_name ?? "Onbekende klant",
154
+ deliveryLocationId,
155
+ pickupLocationId,
156
+ carrierId,
157
+ deliveryDate,
158
+ notes: notes.trim() ? notes.trim() : null,
159
+ lines: validLines.map((l) => {
160
+ const p = products.find((x) => x.id === l.product_id);
161
+ return {
162
+ product_id: l.product_id,
163
+ product_name: p?.product ?? l.product_name ?? "Onbekend product",
164
+ quantity: l.quantity,
165
+ unit: l.unit ?? p?.unit ?? "stuks",
166
+ unit_price: l.unit_price ?? undefined,
167
+ };
168
+ }),
169
+ };
170
+ return await fetchCreate({ data: payload });
197
171
  },
198
- onSuccess: () => {
199
- toast.success("Bestelling aangemaakt");
200
- queryClient.invalidateQueries({ queryKey: ["floriday", "salesorders-cache"] });
201
- navigate({ to: "/floriday-verkoop/verkooporders" });
172
+ onSuccess: (res) => {
173
+ toast.success("Bestelling aangemaakt — deel nu de karren in");
174
+ qc.invalidateQueries({ queryKey: ["floriday", "salesorders-cache"] });
175
+ if (res?.orderId) {
176
+ setCartOrderId(res.orderId);
177
+ }
178
+ else {
179
+ navigate({ to: "/floriday-verkoop/verkooporders" });
180
+ }
202
181
  },
203
182
  onError: (e) => toast.error(e?.message ?? "Aanmaken mislukt"),
204
183
  });
205
- return (_jsxs("main", { className: "space-y-5 p-6", children: [_jsx("div", { children: _jsx(Button, { asChild: true, variant: "ghost", size: "sm", children: _jsxs(Link, { to: "/floriday-verkoop/verkooporders", children: [_jsx(ArrowLeft, { className: "mr-2 h-4 w-4" }), "Terug naar verkooporders"] }) }) }), _jsxs("div", { className: "rounded-lg border border-border bg-card p-6", children: [_jsx("h1", { className: "text-xl font-semibold text-foreground", children: "Nieuwe Bestelling" }), _jsx("p", { className: "mt-1 text-sm text-muted-foreground", children: "Maak een nieuwe bestelling aan door producten te zoeken en toe te voegen." }), _jsxs("div", { className: "mt-6 grid gap-5 md:grid-cols-2", children: [_jsxs("div", { className: "grid gap-1.5", children: [_jsxs(Label, { children: ["Klant ", _jsx("span", { className: "text-destructive", children: "*" })] }), _jsxs(Select, { value: customerId, onValueChange: setCustomerId, children: [_jsx(SelectTrigger, { children: _jsx(SelectValue, { placeholder: "Selecteer klant" }) }), _jsxs(SelectContent, { children: [(customersQ.data ?? []).map((c) => (_jsxs(SelectItem, { value: c.id, children: [c.company_name ?? "Onbekend", c.city ? ` — ${c.city}` : ""] }, c.id))), customersQ.data?.length === 0 && (_jsx("div", { className: "px-3 py-2 text-sm text-muted-foreground", children: "Geen klanten gevonden" }))] })] })] }), _jsxs("div", { className: "grid gap-1.5", children: [_jsxs(Label, { htmlFor: "delivery", children: ["Leverdatum ", _jsx("span", { className: "text-destructive", children: "*" })] }), _jsx(Input, { id: "delivery", type: "date", value: deliveryDate, onChange: (e) => setDeliveryDate(e.target.value) })] }), _jsxs("div", { className: "grid gap-1.5", children: [_jsx(Label, { htmlFor: "carrier", children: "Transporteur" }), _jsxs("div", { className: "relative", children: [_jsx(Truck, { className: "pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" }), _jsx(Input, { id: "carrier", className: "pl-9", placeholder: "Bv. DHL, PostNL", value: carrier, onChange: (e) => setCarrier(e.target.value) })] })] }), _jsxs("div", { className: "grid gap-1.5", children: [_jsx(Label, { htmlFor: "country", children: "Land" }), _jsxs("div", { className: "relative", children: [_jsx(MapPin, { className: "pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" }), _jsx(Input, { id: "country", className: "pl-9", placeholder: "Bv. Nederland", value: country, onChange: (e) => setCountry(e.target.value) })] })] })] }), _jsxs("div", { className: "mt-8", children: [_jsx(Label, { children: "Producten toevoegen" }), _jsxs("div", { className: "mt-2 flex flex-wrap items-stretch gap-2", children: [_jsx("div", { className: "min-w-[260px] flex-1", children: _jsxs(Popover, { open: productPickerOpen, onOpenChange: setProductPickerOpen, children: [_jsx(PopoverTrigger, { asChild: true, children: _jsxs(Button, { type: "button", variant: "outline", className: "w-full justify-between font-normal", children: [_jsx("span", { className: selectedProduct ? "" : "text-muted-foreground", children: selectedProduct ? selectedProduct.name : "Zoek product..." }), _jsx(ChevronDown, { className: "h-4 w-4 opacity-50" })] }) }), _jsxs(PopoverContent, { align: "start", className: "w-[--radix-popover-trigger-width] p-0", children: [_jsxs("div", { className: "flex items-center gap-2 border-b border-border px-3 py-2", children: [_jsx(Search, { className: "h-4 w-4 text-muted-foreground" }), _jsx("input", { autoFocus: true, placeholder: "Zoek product...", value: productQuery, onChange: (e) => setProductQuery(e.target.value), className: "h-8 w-full bg-transparent text-sm outline-none placeholder:text-muted-foreground" })] }), _jsxs("div", { className: "max-h-72 overflow-y-auto py-1", children: [productsQ.isLoading && (_jsx("div", { className: "px-3 py-6 text-center text-sm text-muted-foreground", children: "Laden\u2026" })), !productsQ.isLoading && filteredProducts.length === 0 && (_jsx("div", { className: "px-3 py-6 text-center text-sm text-muted-foreground", children: "Geen producten gevonden." })), filteredProducts.map((p) => (_jsxs("button", { type: "button", onClick: () => {
206
- setSelectedProduct(p);
207
- if (p.price != null && unitPrice === "")
208
- setUnitPrice(p.price);
209
- if (quantity === "")
210
- setQuantity(1);
211
- setProductPickerOpen(false);
212
- }, className: "flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-sm hover:bg-accent", children: [_jsx("span", { className: "truncate", children: p.name }), _jsx(Badge, { variant: "outline", className: p.source === "local"
213
- ? "border-primary/30 text-primary"
214
- : "border-emerald-500/30 text-emerald-600", children: p.source === "local" ? "Lokaal" : "Floriday" })] }, p.id)))] })] })] }) }), _jsx(Input, { type: "number", min: 1, placeholder: "Aantal", className: "w-28", value: quantity, onChange: (e) => setQuantity(e.target.value === "" ? "" : Number(e.target.value)) }), _jsx(Input, { type: "number", min: 0, step: "0.01", placeholder: "\u20AC Prijs", className: "w-32", value: unitPrice, onChange: (e) => setUnitPrice(e.target.value === "" ? "" : Number(e.target.value)) }), _jsx(Button, { type: "button", onClick: addLine, disabled: !selectedProduct, "aria-label": "Toevoegen", children: _jsx(Plus, { className: "h-4 w-4" }) })] }), _jsx("div", { className: "mt-3 rounded-lg border border-dashed border-border bg-muted/30", children: lines.length === 0 ? (_jsx("div", { className: "px-4 py-10 text-center text-sm text-muted-foreground", children: "Voeg producten toe aan de bestelling" })) : (_jsxs("div", { className: "divide-y divide-border", children: [lines.map((l) => (_jsxs("div", { className: "flex items-center gap-3 px-4 py-3 text-sm", children: [_jsxs("div", { className: "flex-1 min-w-0", children: [_jsx("div", { className: "truncate font-medium text-foreground", children: l.product.name }), _jsx("div", { className: "text-xs text-muted-foreground", children: l.product.source === "local" ? "Lokaal" : "Floriday" })] }), _jsxs("div", { className: "w-20 text-right", children: [l.quantity, " st."] }), _jsx("div", { className: "w-24 text-right", children: eur.format(l.unitPrice) }), _jsx("div", { className: "w-28 text-right font-medium", children: eur.format(l.quantity * l.unitPrice) }), _jsx(Button, { type: "button", variant: "ghost", size: "icon", onClick: () => removeLine(l.key), "aria-label": "Regel verwijderen", children: _jsx(Trash2, { className: "h-4 w-4 text-muted-foreground" }) })] }, l.key))), _jsxs("div", { className: "flex items-center justify-end gap-3 px-4 py-3 text-sm", children: [_jsx("span", { className: "text-muted-foreground", children: "Totaal" }), _jsx("span", { className: "text-base font-semibold text-foreground", children: eur.format(total) })] })] })) })] }), _jsxs("div", { className: "mt-8 flex items-center justify-end gap-2", children: [_jsx(Button, { variant: "outline", onClick: () => navigate({ to: "/floriday-verkoop/verkooporders" }), disabled: createMutation.isPending, children: "Annuleren" }), _jsx(Button, { onClick: () => createMutation.mutate(), disabled: createMutation.isPending ||
215
- !customerId ||
216
- !deliveryDate ||
217
- lines.length === 0, children: createMutation.isPending ? "Aanmaken…" : "Bestelling Aanmaken" })] })] })] }));
184
+ return (_jsxs("main", { className: "space-y-5 p-6", children: [_jsx("div", { children: _jsx(Button, { asChild: true, variant: "ghost", size: "sm", children: _jsxs(Link, { to: "/floriday-verkoop/verkooporders", children: [_jsx(ArrowLeft, { className: "mr-2 h-4 w-4" }), "Terug naar verkooporders"] }) }) }), _jsxs(Card, { children: [_jsxs(CardHeader, { children: [_jsx(CardTitle, { children: "Nieuwe Bestelling" }), _jsx("p", { className: "text-sm text-muted-foreground", children: "Doorloop de stappen: klant \u2192 afleverlocatie \u2192 afhaallocatie \u2192 vervoerder \u2192 leverdatum \u2192 producten." })] }), _jsxs(CardContent, { className: "space-y-5", children: [_jsxs("div", { className: "space-y-1", children: [_jsxs(Label, { className: "flex items-center gap-2", children: ["Klant ", _jsx("span", { className: "text-destructive", children: "*" })] }), _jsx(SearchableSelect, { value: customerId, placeholder: customersQ.isLoading ? "Laden..." : "Kies klant...", options: customers.map((c) => ({ value: c.id, label: c.company_name ?? "Onbekend", hint: c.email ?? undefined })), onChange: (v) => { setCustomerId(v); setDeliveryLocationId(null); }, allowClear: false })] }), _jsxs("div", { className: "space-y-1", children: [_jsxs(Label, { className: "flex items-center gap-2", children: ["Afleverlocatie ", _jsx("span", { className: "text-destructive", children: "*" })] }), _jsx(SearchableSelect, { value: deliveryLocationId, placeholder: !customerId ? "Selecteer eerst een klant"
185
+ : deliveryLocations.length ? "Kies locatie..."
186
+ : "Geen locaties bekend voor deze klant", disabled: !customerId || deliveryLocations.length === 0, allowClear: false, options: deliveryLocations.map((l) => {
187
+ const addr = [
188
+ l.address_line || [l.street, l.house_number].filter(Boolean).join(" "),
189
+ l.postal_code, l.city,
190
+ ].filter(Boolean).join(", ");
191
+ return {
192
+ value: l.id,
193
+ label: (l.name || addr || "Locatie") + (l.is_primary ? " ★" : ""),
194
+ hint: l.name && addr ? addr : undefined,
195
+ };
196
+ }), onChange: setDeliveryLocationId })] }), selectedLocation && (_jsxs("div", { className: "rounded-md border bg-muted/30 p-3 space-y-2", children: [_jsx("div", { className: "text-xs font-medium text-muted-foreground", children: "Adresgegevens" }), _jsxs("div", { className: "grid grid-cols-2 gap-2", children: [_jsx(ReadOnlyField, { label: "Straat", value: selectedLocation.street }), _jsx(ReadOnlyField, { label: "Huisnummer", value: selectedLocation.house_number }), _jsx(ReadOnlyField, { label: "Postcode", value: selectedLocation.postal_code }), _jsx(ReadOnlyField, { label: "Plaats", value: selectedLocation.city }), _jsx(ReadOnlyField, { label: "Provincie", value: selectedLocation.province }), _jsx(ReadOnlyField, { label: "Land", value: selectedLocation.country })] })] })), _jsxs("div", { className: "space-y-1", children: [_jsxs(Label, { className: "flex items-center gap-2", children: ["Afhaallocatie / Tuin ", _jsx("span", { className: "text-destructive", children: "*" })] }), _jsx(SearchableSelect, { value: pickupLocationId, placeholder: pickupLocations.length ? "Kies eigen locatie..." : "Geen eigen locaties bekend", disabled: pickupLocations.length === 0, allowClear: false, options: pickupLocations.map((l) => ({ value: l.id, label: l.name })), onChange: setPickupLocationId }), _jsx("div", { className: "text-xs text-muted-foreground", children: "Eigen locatie (tuin) van waaruit de bestelling wordt geleverd of opgehaald." })] }), _jsxs("div", { className: "space-y-1", children: [_jsxs(Label, { children: ["Vervoerder ", _jsx("span", { className: "text-destructive", children: "*" })] }), _jsx(SearchableSelect, { value: carrierId, placeholder: !customerId ? "Selecteer eerst een klant"
197
+ : !deliveryLocationId ? "Selecteer eerst een afleverlocatie"
198
+ : "Kies vervoerder...", disabled: !deliveryLocationId, allowClear: false, options: carriers.map((c) => ({
199
+ value: c.id,
200
+ label: c.name + (c.is_default ? " (standaard)" : ""),
201
+ })), onChange: setCarrierId }), selectedLocation?.carrier_id && carrierId && carrierId !== selectedLocation.carrier_id && (_jsx("div", { className: "text-xs text-muted-foreground", children: "Wijkt af van standaard vervoerder van deze locatie \u2014 geldt alleen voor deze bestelling." }))] }), _jsxs("div", { className: "space-y-1", children: [_jsxs(Label, { className: "flex items-center gap-2", children: ["Leverdatum ", _jsx("span", { className: "text-destructive", children: "*" })] }), _jsx(Input, { type: "date", value: canPickDate ? deliveryDate : "", min: canPickDate ? earliestISO : undefined, disabled: !canPickDate, onChange: (e) => {
202
+ const v = e.target.value || "";
203
+ if (v && v < earliestISO) {
204
+ toast.error(`Eerst mogelijke leverdatum is ${earliestLabel}.`);
205
+ setDeliveryDate(earliestISO);
206
+ return;
207
+ }
208
+ setDeliveryDate(v);
209
+ } }), !canPickDate ? (_jsx("div", { className: "text-xs text-muted-foreground", children: "Selecteer eerst klant, afleverlocatie, afhaallocatie en vervoerder." })) : (_jsxs("div", { className: "text-xs text-muted-foreground", children: ["Eerst beschikbare leverdatum is ", earliestLabel, ", o.b.v. orderpicktijd (", pickDays, "d) en levertijd vervoerder (", carrierDeliveryDays, "d)."] }))] }), _jsxs("div", { className: "space-y-2", children: [_jsx(Label, { children: "Bestelregels" }), _jsxs("div", { className: "grid grid-cols-12 gap-2 text-xs text-muted-foreground px-1", children: [_jsx("div", { className: "col-span-5", children: "Product" }), _jsx("div", { className: "col-span-2", children: "Planten" }), _jsx("div", { className: "col-span-2", children: "Fusten" }), _jsx("div", { className: "col-span-2", children: "Prijs" }), _jsx("div", { className: "col-span-1" })] }), lines.map((line, idx) => {
210
+ const product = line.product_id ? products.find((p) => p.id === line.product_id) : null;
211
+ const ppc = Math.max(1, Number(product?.plants_per_crate ?? 1));
212
+ const plants = line.quantity ?? null;
213
+ const cratesDisplay = plants === null ? "" : String(Math.ceil(plants / ppc));
214
+ return (_jsxs("div", { className: "grid grid-cols-12 gap-2 items-start", children: [_jsx("div", { className: "col-span-5", children: _jsx(SearchableSelect, { value: line.product_id, placeholder: "Kies product...", clearLabel: "\u2014 Handmatig \u2014", options: products.map((p) => ({ value: p.id, label: p.product, hint: p.unit })), onChange: (v) => {
215
+ const next = [...lines];
216
+ if (v === null)
217
+ next[idx] = { ...next[idx], product_id: null };
218
+ else {
219
+ const p = products.find((x) => x.id === v);
220
+ const newPpc = Math.max(1, Number(p?.plants_per_crate ?? 1));
221
+ const currentQ = Number(next[idx].quantity ?? 0);
222
+ const normalizedQ = currentQ > 0 ? Math.ceil(currentQ / newPpc) * newPpc : newPpc;
223
+ next[idx] = {
224
+ ...next[idx],
225
+ product_id: v,
226
+ product_name: p?.product ?? "",
227
+ unit: next[idx].unit ?? p?.unit ?? "stuks",
228
+ quantity: normalizedQ,
229
+ unit_price: next[idx].unit_price ?? (p?.sale_price != null ? Number(p.sale_price) : null),
230
+ };
231
+ }
232
+ setLines(next);
233
+ } }) }), _jsx(Input, { className: "col-span-2", type: "number", min: ppc, step: ppc, inputMode: "numeric", onKeyDown: blockDecimal, value: plants ?? "", onChange: (e) => {
234
+ const next = [...lines];
235
+ const raw = e.target.value.replace(/[.,]/g, "");
236
+ const v = raw ? Number(raw) : null;
237
+ const rounded = v === null ? null : Math.max(1, Math.ceil(v / ppc)) * ppc;
238
+ next[idx] = { ...next[idx], quantity: rounded };
239
+ setLines(next);
240
+ }, placeholder: "Planten", title: `Verkoop per hele fust van ${ppc} planten` }), _jsx(Input, { className: "col-span-2", type: "number", min: 1, step: 1, inputMode: "numeric", onKeyDown: blockDecimal, value: cratesDisplay, onChange: (e) => {
241
+ const next = [...lines];
242
+ const raw = e.target.value.replace(/[.,]/g, "");
243
+ const cr = raw ? Math.max(1, Math.floor(Number(raw))) : null;
244
+ next[idx] = { ...next[idx], quantity: cr === null ? null : cr * ppc };
245
+ setLines(next);
246
+ }, placeholder: "Fusten", title: `${ppc} planten per fust` }), _jsx(Input, { className: "col-span-2", type: "number", min: 0, step: "0.01", value: line.unit_price ?? "", onChange: (e) => {
247
+ const next = [...lines];
248
+ const v = e.target.value === "" ? null : Number(e.target.value);
249
+ next[idx] = { ...next[idx], unit_price: v };
250
+ setLines(next);
251
+ }, placeholder: "\u20AC prijs" }), _jsx(Button, { variant: "ghost", size: "icon", className: "col-span-1", onClick: () => setLines(lines.filter((_, i) => i !== idx)), "aria-label": "Regel verwijderen", children: _jsx(Trash2, { className: "h-4 w-4" }) })] }, idx));
252
+ }), _jsxs(Button, { variant: "outline", size: "sm", onClick: () => setLines([...lines, { product_id: null, product_name: "", quantity: null, unit: "stuks", unit_price: null }]), children: [_jsx(Plus, { className: "h-3 w-3 mr-1" }), " Regel toevoegen"] })] }), _jsxs("div", { className: "space-y-1", children: [_jsx(Label, { children: "Opmerkingen" }), _jsx(Textarea, { value: notes, onChange: (e) => setNotes(e.target.value), placeholder: "Optionele notities bij deze bestelling", rows: 3 })] }), _jsxs("div", { className: "flex items-center justify-end gap-2 pt-2", children: [_jsx(Button, { variant: "outline", onClick: () => navigate({ to: "/floriday-verkoop/verkooporders" }), disabled: createMut.isPending, children: "Annuleren" }), _jsx(Button, { onClick: () => createMut.mutate(), disabled: createMut.isPending, children: createMut.isPending ? "Bezig..." : "Bestelling Aanmaken" })] })] })] }), _jsx(CartAssignmentWizard, { orderId: cartOrderId, open: !!cartOrderId, onClose: () => {
253
+ setCartOrderId(null);
254
+ navigate({ to: "/floriday-verkoop/verkooporders" });
255
+ } })] }));
218
256
  }
@@ -0,0 +1,4 @@
1
+ export declare function OrderAfleverbrievenCard({ salesOrderId }: {
2
+ salesOrderId: string;
3
+ }): import("react/jsx-runtime").JSX.Element;
4
+ //# sourceMappingURL=OrderAfleverbrievenCard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OrderAfleverbrievenCard.d.ts","sourceRoot":"","sources":["../../../src/components/verkoop/OrderAfleverbrievenCard.tsx"],"names":[],"mappings":"AA+BA,wBAAgB,uBAAuB,CAAC,EAAE,YAAY,EAAE,EAAE;IAAE,YAAY,EAAE,MAAM,CAAA;CAAE,2CA4FjF"}
@@ -0,0 +1,44 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { useQuery } from "@tanstack/react-query";
3
+ import { useServerFn } from "@tanstack/react-start";
4
+ import { Badge, Button, Card, CardContent, CardHeader, CardTitle } from "@flowselections/core";
5
+ import { FileText, Printer, ExternalLink, RefreshCw } from "lucide-react";
6
+ import { listLogisticLabelsForOrder } from "../../lib/floriday-logistic-labels.functions";
7
+ const LC_SHORT = {
8
+ DANISH_TROLLEY: "DC",
9
+ DANISH_CONTAINER: "DC",
10
+ CC_CONTAINER: "CC",
11
+ CC_TROLLEY: "CC",
12
+ EURO_PALLET: "EP",
13
+ BLOCK_PALLET: "BP",
14
+ BOX: "BX",
15
+ };
16
+ function printPdf(url) {
17
+ const w = window.open(url, "_blank");
18
+ if (!w)
19
+ return;
20
+ // Kick off print dialog once loaded (browsers may block cross-origin, then user prints from tab)
21
+ const timer = setTimeout(() => {
22
+ try {
23
+ w.focus();
24
+ w.print();
25
+ }
26
+ catch {
27
+ /* ignore */
28
+ }
29
+ }, 1200);
30
+ w.addEventListener?.("beforeunload", () => clearTimeout(timer));
31
+ }
32
+ export function OrderAfleverbrievenCard({ salesOrderId }) {
33
+ const fetchLabels = useServerFn(listLogisticLabelsForOrder);
34
+ const { data, isLoading, error, refetch, isFetching } = useQuery({
35
+ queryKey: ["floriday-logistic-labels", salesOrderId],
36
+ queryFn: () => fetchLabels({ data: { salesOrderId } }),
37
+ staleTime: 60000,
38
+ });
39
+ const labels = data?.labels ?? [];
40
+ return (_jsxs(Card, { children: [_jsxs(CardHeader, { className: "flex flex-row items-center justify-between", children: [_jsx(CardTitle, { className: "text-base", children: "Afleverbrieven" }), _jsxs("div", { className: "flex items-center gap-2", children: [_jsxs(Badge, { variant: "secondary", children: [labels.length, " brief(en)"] }), _jsx(Button, { variant: "ghost", size: "sm", onClick: () => refetch(), disabled: isFetching, title: "Opnieuw ophalen bij Floriday", children: _jsx(RefreshCw, { className: `h-4 w-4 ${isFetching ? "animate-spin" : ""}` }) })] })] }), _jsxs(CardContent, { children: [isLoading && (_jsx("p", { className: "text-sm text-muted-foreground", children: "Afleverbrieven ophalen\u2026" })), error && (_jsx("p", { className: "text-sm text-destructive", children: error.message })), !isLoading && !error && labels.length === 0 && (_jsx("p", { className: "text-sm text-muted-foreground", children: "Nog geen afleverbrief beschikbaar (order nog niet vrijgegeven door Floriday)." })), labels.length > 0 && (_jsx("div", { className: "divide-y divide-border rounded-md border border-border", children: labels.map((l) => {
41
+ const lcShort = l.loadCarrierType ? LC_SHORT[l.loadCarrierType] ?? l.loadCarrierType.slice(0, 2) : "";
42
+ return (_jsxs("div", { className: "flex items-center justify-between gap-4 px-3 py-2 text-sm", children: [_jsxs("div", { className: "flex items-center gap-3 min-w-0", children: [_jsx(FileText, { className: "h-4 w-4 shrink-0 text-muted-foreground" }), _jsxs("div", { className: "min-w-0", children: [_jsxs("div", { className: "font-mono font-medium", children: [l.code, l.letter ? _jsxs("span", { className: "ml-1 text-primary", children: ["\u00B7", l.letter] }) : null] }), _jsxs("div", { className: "text-xs text-muted-foreground", children: ["Kar ", l.loadCarrierIndex, lcShort ? ` · ${lcShort}` : "", l.packages ? ` · ${l.packages} fusten` : ""] })] })] }), _jsx("div", { className: "flex items-center gap-2", children: l.hasPdf && l.signedUrl ? (_jsxs(_Fragment, { children: [_jsx(Button, { asChild: true, variant: "outline", size: "sm", children: _jsxs("a", { href: l.signedUrl, target: "_blank", rel: "noreferrer", children: [_jsx(ExternalLink, { className: "mr-1 h-3.5 w-3.5" }), "Openen"] }) }), _jsxs(Button, { variant: "default", size: "sm", onClick: () => printPdf(l.signedUrl), children: [_jsx(Printer, { className: "mr-1 h-3.5 w-3.5" }), "Printen"] })] })) : (_jsx("span", { className: "text-xs text-muted-foreground", children: "PDF nog niet vrijgegeven" })) })] }, `${l.fulfillmentOrderId}-${l.code}-${l.letter ?? ""}`));
43
+ }) }))] })] }));
44
+ }
@@ -0,0 +1,5 @@
1
+ import type { SalesOrderDTO } from "../../lib/salesorders-mapping";
2
+ export declare function OrderKarindelingCard({ order }: {
3
+ order: SalesOrderDTO;
4
+ }): import("react/jsx-runtime").JSX.Element;
5
+ //# sourceMappingURL=OrderKarindelingCard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OrderKarindelingCard.d.ts","sourceRoot":"","sources":["../../../src/components/verkoop/OrderKarindelingCard.tsx"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AA6F/D,wBAAgB,oBAAoB,CAAC,EAAE,KAAK,EAAE,EAAE;IAAE,KAAK,EAAE,aAAa,CAAA;CAAE,2CA+KvE"}