@apptimate/ui 1.8.0 → 1.9.0

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apptimate/ui",
3
- "version": "1.8.0",
3
+ "version": "1.9.0",
4
4
  "main": "src/index.tsx",
5
5
  "types": "src/index.tsx",
6
6
  "dependencies": {
@@ -65,16 +65,31 @@ export function DashboardLayout({
65
65
  const [isOrgModalOpen, setIsOrgModalOpen] = useState(false);
66
66
  const pathname = usePathname() || "";
67
67
 
68
- // Find which main menu should be active based on current path, or default to first
68
+ // Find which main menu should be active based on current path.
69
+ // When basePath is set, prefer the menu whose items are mostly within basePath.
69
70
  const fullPath = basePath + (pathname === "/" && basePath ? "" : pathname);
70
-
71
- const currentMainMenu = menus.find(menu =>
72
- menu.groups.some(group => group.items.some(item =>
73
- fullPath === item.path ||
74
- fullPath.startsWith(item.path + "/") ||
75
- item.path.startsWith(fullPath + "/")
76
- ))
77
- ) || menus[0];
71
+ const currentMainMenu = (() => {
72
+ let bestMenu = menus[0];
73
+ let bestScore = -1;
74
+ let bestInternalCount = -1;
75
+ for (const menu of menus) {
76
+ for (const group of menu.groups) {
77
+ for (const item of group.items) {
78
+ if (fullPath === item.path || fullPath.startsWith(item.path + "/")) {
79
+ const internalCount = basePath
80
+ ? menu.groups.reduce((sum, g) => sum + g.items.filter(i => i.path.startsWith(basePath)).length, 0)
81
+ : 0;
82
+ if (item.path.length > bestScore || (item.path.length === bestScore && internalCount > bestInternalCount)) {
83
+ bestScore = item.path.length;
84
+ bestInternalCount = internalCount;
85
+ bestMenu = menu;
86
+ }
87
+ }
88
+ }
89
+ }
90
+ }
91
+ return bestMenu;
92
+ })();
78
93
 
79
94
  const [activeMenuId, setActiveMenuId] = useState(currentMainMenu?.id || "");
80
95
 
@@ -158,7 +173,7 @@ export function DashboardLayout({
158
173
 
159
174
  {/* Desktop Secondary Sidebar */}
160
175
  {activeMenu && activeMenu.groups.length > 0 && (
161
- <aside className="hidden md:flex w-[240px] bg-white border-gray-200 flex-col py-8 shrink-0 z-10">
176
+ <aside className="hidden md:flex w-[210px] bg-white border-gray-200 flex-col py-8 shrink-0 z-10">
162
177
  <h2 className="px-6 text-xl font-bold text-[#2D3142]/80 mb-6">{activeMenu.label}</h2>
163
178
  <div className="flex-1 overflow-y-auto px-4 space-y-6">
164
179
  {activeMenu.groups.map((group) => (
@@ -1,335 +1,336 @@
1
- "use client";
2
-
3
- import React, { useState, useEffect, useCallback, useMemo } from "react";
4
- import { cn } from "@apptimate/core-lib";
5
- import { CreditCard, Banknote, Building, Trash2, Loader2, Split, Check, AlertCircle } from "lucide-react";
6
-
7
- /* ── Types (mirroring sales POS types) ── */
8
-
9
- export interface PaymentModeField {
10
- key: string;
11
- label: string;
12
- type: "text" | "number" | "date" | "bank_account_select";
13
- required: boolean;
14
- }
15
-
16
- export interface PaymentMode {
17
- id: number;
18
- code: string;
19
- name: string;
20
- is_active: boolean;
21
- requires_reference: boolean;
22
- field_config: { fields: PaymentModeField[] };
23
- sort_order: number;
24
- }
25
-
26
- export interface PaymentEntry {
27
- mode_id: number;
28
- mode_code: string;
29
- mode_name: string;
30
- amount: number;
31
- metadata: Record<string, string | number>;
32
- }
33
-
34
- export interface BankAccount {
35
- id: number;
36
- account_name: string;
37
- bank_name: string;
38
- branch?: string;
39
- account_number: string;
40
- account_type: string;
41
- currency: string;
42
- }
43
-
44
- /* ── Props ── */
45
-
46
- export interface PaymentSectionProps {
47
- /** The total amount to collect */
48
- totalAmount: number;
49
- /** Current payment entries */
50
- payments: PaymentEntry[];
51
- /** Callback when payments change */
52
- onPaymentsChange: (payments: PaymentEntry[]) => void;
53
- /** Optional: show compact variant */
54
- compact?: boolean;
55
- /** Fetcher for payment modes */
56
- fetchPaymentModes: () => Promise<{ is_success: boolean; result?: any }>;
57
- /** Fetcher for bank accounts */
58
- fetchBankAccounts: () => Promise<{ is_success: boolean; result?: any }>;
59
- }
60
-
61
- /* ── Component ── */
62
-
63
- export function PaymentSection({ totalAmount, payments, onPaymentsChange, compact, fetchPaymentModes, fetchBankAccounts }: PaymentSectionProps) {
64
- const [paymentModes, setPaymentModes] = useState<PaymentMode[]>([]);
65
- const [bankAccounts, setBankAccounts] = useState<BankAccount[]>([]);
66
- const [isLoading, setIsLoading] = useState(false);
67
- const [selectionMode, setSelectionMode] = useState<"single" | "split">("single");
68
-
69
- // ── Load payment modes on mount ──
70
- useEffect(() => {
71
- const load = async () => {
72
- setIsLoading(true);
73
- try {
74
- const [modesRes, bankRes] = await Promise.all([fetchPaymentModes(), fetchBankAccounts()]);
75
- const modes: PaymentMode[] = modesRes.is_success ? (modesRes.result || []) : [];
76
- setPaymentModes(modes);
77
- if (bankRes.is_success) setBankAccounts(bankRes.result || []);
78
-
79
- // Auto-select cash if no payments yet
80
- if (payments.length === 0 && modes.length > 0) {
81
- const cashMode = modes.find((m) => m.code === "cash" && m.is_active);
82
- if (cashMode) {
83
- onPaymentsChange([{
84
- mode_id: cashMode.id, mode_code: cashMode.code, mode_name: cashMode.name,
85
- amount: totalAmount, metadata: {},
86
- }]);
87
- }
88
- }
89
- } finally { setIsLoading(false); }
90
- };
91
- load();
92
- }, []);
93
-
94
- // ── Calculations ──
95
- const totalPaid = useMemo(() => payments.reduce((s, p) => s + p.amount, 0), [payments]);
96
- const balance = useMemo(() => totalAmount - totalPaid, [totalAmount, totalPaid]);
97
- const formatCurrency = (v: number) => v.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
98
-
99
- // ── Mode icon ──
100
- const getModeIcon = useCallback((code: string, size = 14) => {
101
- switch (code) {
102
- case "cash": return <Banknote size={size} />;
103
- case "card": return <CreditCard size={size} />;
104
- case "bank_transfer": return <Building size={size} />;
105
- default: return <CreditCard size={size} />;
106
- }
107
- }, []);
108
-
109
- // ── Payment management ──
110
- const selectSingleMode = useCallback((mode: PaymentMode) => {
111
- setSelectionMode("single");
112
- onPaymentsChange([{
113
- mode_id: mode.id, mode_code: mode.code, mode_name: mode.name,
114
- amount: totalAmount, metadata: {},
115
- }]);
116
- }, [totalAmount, onPaymentsChange]);
117
-
118
- const updatePayment = useCallback((index: number, updates: Partial<PaymentEntry>) => {
119
- const next = [...payments];
120
- next[index] = { ...next[index], ...updates };
121
- onPaymentsChange(next);
122
- }, [payments, onPaymentsChange]);
123
-
124
- // ── Auto-sync single mode amount ──
125
- useEffect(() => {
126
- if (selectionMode === "single" && payments.length === 1 && payments[0].amount !== totalAmount) {
127
- updatePayment(0, { amount: totalAmount });
128
- }
129
- }, [totalAmount, selectionMode, payments, updatePayment]);
130
-
131
- const activateSplitMode = useCallback(() => {
132
- setSelectionMode("split");
133
- if (payments.length <= 1) onPaymentsChange([]);
134
- }, [payments.length, onPaymentsChange]);
135
-
136
- const addPayment = useCallback((mode: PaymentMode) => {
137
- const entry: PaymentEntry = {
138
- mode_id: mode.id, mode_code: mode.code, mode_name: mode.name,
139
- amount: Math.max(0, balance), metadata: {},
140
- };
141
- onPaymentsChange([...payments, entry]);
142
- }, [payments, balance, onPaymentsChange]);
143
-
144
- const removePayment = useCallback((index: number) => {
145
- onPaymentsChange(payments.filter((_, i) => i !== index));
146
- }, [payments, onPaymentsChange]);
147
-
148
- if (isLoading) {
149
- return (
150
- <div className="flex items-center justify-center py-4">
151
- <Loader2 size={18} className="animate-spin text-primary" />
152
- </div>
153
- );
154
- }
155
-
156
- return (
157
- <div className="space-y-3">
158
- {/* ── Mode Selection Buttons ── */}
159
- <div className="flex flex-wrap gap-2">
160
- {paymentModes
161
- .filter((m) => m.is_active)
162
- .map((mode) => {
163
- const isActive = selectionMode === "single" && payments.length === 1 && payments[0].mode_id === mode.id;
164
- return (
165
- <button key={mode.id} onClick={() => selectSingleMode(mode)}
166
- className={cn(
167
- "inline-flex items-center gap-2 px-4 py-2.5 text-[12px] font-semibold rounded-[10px] border transition-all",
168
- isActive
169
- ? "bg-primary text-primary-foreground border-primary shadow-sm"
170
- : "bg-surface-0 border-border-subtle text-foreground-1 hover:border-primary/40 hover:bg-primary/5 hover:text-primary"
171
- )}>
172
- {getModeIcon(mode.code)}
173
- {mode.name}
174
- </button>
175
- );
176
- })}
177
- {/* Split Button */}
178
- <button onClick={activateSplitMode}
179
- className={cn(
180
- "inline-flex items-center gap-2 px-4 py-2.5 text-[12px] font-semibold rounded-[10px] border transition-all",
181
- selectionMode === "split"
182
- ? "bg-primary text-primary-foreground border-primary shadow-sm"
183
- : "bg-surface-0 border-border-subtle text-foreground-1 hover:border-primary/40 hover:bg-primary/5 hover:text-primary"
184
- )}>
185
- <Split size={14} />
186
- Multiple Methods
187
- </button>
188
- </div>
189
-
190
- {/* ── Single Mode: Entry with fields (no delete) ── */}
191
- {selectionMode === "single" && payments.length === 1 && (
192
- <PaymentEntryRow entry={payments[0]} mode={paymentModes.find((m) => m.id === payments[0].mode_id)}
193
- bankAccounts={bankAccounts} onUpdate={(updates) => updatePayment(0, updates)} onRemove={() => {}} showRemove={false} />
194
- )}
195
-
196
- {/* ── Split Mode: Multi-entry UI ── */}
197
- {selectionMode === "split" && (
198
- <div className="space-y-2.5">
199
- {payments.map((entry, idx) => {
200
- const mode = paymentModes.find((m) => m.id === entry.mode_id);
201
- return (
202
- <PaymentEntryRow key={idx} entry={entry} mode={mode} bankAccounts={bankAccounts}
203
- onUpdate={(updates) => updatePayment(idx, updates)} onRemove={() => removePayment(idx)} />
204
- );
205
- })}
206
- {/* Add split mode buttons */}
207
- <div className="flex flex-wrap gap-1.5 pt-1">
208
- {paymentModes
209
- .filter((m) => m.is_active && !payments.some(p => p.mode_id === m.id))
210
- .map((mode) => (
211
- <button key={mode.id} onClick={() => addPayment(mode)}
212
- className="inline-flex items-center gap-1.5 px-3 py-1.5 text-[11px] font-semibold rounded-[8px] bg-surface-0 border border-border-subtle text-foreground-subtle hover:border-primary/40 hover:text-primary transition-all">
213
- {getModeIcon(mode.code, 12)}
214
- + {mode.name}
215
- </button>
216
- ))}
217
- </div>
218
- </div>
219
- )}
220
-
221
- {/* ── Totals ── */}
222
- {payments.length > 0 && (
223
- <div className="bg-surface-0 rounded-[12px] border border-border-subtle p-4 space-y-2">
224
- <TotalRow label="Amount to Pay" value={formatCurrency(totalAmount)} bold />
225
- <div className="border-t border-border-subtle my-2" />
226
- <TotalRow label="Total Paid" value={formatCurrency(totalPaid)} />
227
- <TotalRow
228
- label={balance > 0.01 ? "Balance Due" : balance < -0.01 ? "Change Due" : "Settled"}
229
- value={formatCurrency(Math.abs(balance))}
230
- className={balance > 0.01 ? "text-danger-alt" : "text-green-600"}
231
- bold
232
- />
233
- {balance < -0.01 && (
234
- <div className="flex items-center gap-1.5 mt-1 text-[11px] text-amber-600 font-medium">
235
- <AlertCircle size={12} /><span>Change: {formatCurrency(Math.abs(balance))}</span>
236
- </div>
237
- )}
238
- {Math.abs(balance) < 0.01 && (
239
- <div className="flex items-center gap-1.5 mt-1 text-[11px] text-green-600 font-medium">
240
- <Check size={12} /><span>Fully paid</span>
241
- </div>
242
- )}
243
- </div>
244
- )}
245
- </div>
246
- );
247
- }
248
-
249
- /* ── TotalRow ── */
250
-
251
- function TotalRow({ label, value, bold, className }: { label: string; value: string; bold?: boolean; className?: string }) {
252
- return (
253
- <div className="flex items-center justify-between">
254
- <span className={cn("text-[12px]", bold ? "font-bold text-foreground-1" : "text-foreground-subtle")}>{label}</span>
255
- <span className={cn("text-[12px]", bold ? "font-bold text-foreground-0 text-[14px]" : "text-foreground-1 font-medium", className)}>{value}</span>
256
- </div>
257
- );
258
- }
259
-
260
- /* ── PaymentEntryRow (mirrors sales POS exactly) ── */
261
-
262
- interface PaymentEntryRowProps {
263
- entry: PaymentEntry;
264
- mode?: PaymentMode;
265
- bankAccounts: BankAccount[];
266
- onUpdate: (updates: Partial<PaymentEntry>) => void;
267
- onRemove: () => void;
268
- showRemove?: boolean;
269
- }
270
-
271
- function PaymentEntryRow({ entry, mode, bankAccounts, onUpdate, onRemove, showRemove = true }: PaymentEntryRowProps) {
272
- const fields = mode?.field_config?.fields || [];
273
-
274
- const getModeIcon = () => {
275
- switch (entry.mode_code) {
276
- case "cash": return <Banknote size={13} />;
277
- case "card": return <CreditCard size={13} />;
278
- case "bank_transfer": return <Building size={13} />;
279
- default: return <CreditCard size={13} />;
280
- }
281
- };
282
-
283
- return (
284
- <div className="bg-surface-0 border-[1.5px] border-border-subtle rounded-[10px] p-4 space-y-3">
285
- {/* Header */}
286
- <div className="flex items-center justify-between">
287
- <div className="flex items-center gap-1.5 text-[12px] font-bold text-foreground-1">
288
- {getModeIcon()}
289
- {entry.mode_name}
290
- </div>
291
- {showRemove && (
292
- <button onClick={onRemove}
293
- className="w-7 h-7 rounded-[6px] flex items-center justify-center text-foreground-disabled hover:text-danger-alt hover:bg-danger-alt/10 transition-all">
294
- <Trash2 size={13} />
295
- </button>
296
- )}
297
- </div>
298
-
299
- {/* Amount */}
300
- <div className="flex flex-col gap-1">
301
- <label className="text-[11px] text-foreground-subtle font-bold uppercase tracking-wider">Amount</label>
302
- <input type="number" value={entry.amount || ""} onChange={(e) => onUpdate({ amount: Number(e.target.value) || 0 })}
303
- className="w-full bg-surface-1 border-[1.5px] border-border-subtle rounded-[8px] px-3 py-2.5 text-[13px] font-medium text-foreground-1 outline-none focus:border-primary/40 transition-all [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
304
- step="0.01" min={0} />
305
- </div>
306
-
307
- {/* Dynamic sub-fields from field_config */}
308
- {fields.length > 0 && (
309
- <div className="grid grid-cols-2 gap-2.5">
310
- {fields.map((field: PaymentModeField) => (
311
- <div key={field.key} className="flex flex-col gap-1">
312
- <label className="text-[11px] text-foreground-subtle font-bold uppercase tracking-wider">
313
- {field.label}
314
- {field.required && <span className="text-danger-alt ml-0.5">*</span>}
315
- </label>
316
- {field.type === "bank_account_select" ? (
317
- <select value={entry.metadata[field.key] || ""}
318
- onChange={(e) => onUpdate({ metadata: { ...entry.metadata, [field.key]: e.target.value ? Number(e.target.value) : "" } })}
319
- className="w-full bg-surface-1 border-[1.5px] border-border-subtle rounded-[8px] px-2.5 py-2.5 text-[12px] text-foreground-1 outline-none focus:border-primary/40 transition-all">
320
- <option value="">Select...</option>
321
- {bankAccounts.map((b) => (<option key={b.id} value={b.id}>{b.bank_name} - {b.account_number}</option>))}
322
- </select>
323
- ) : (
324
- <input type={field.type === "number" ? "number" : field.type === "date" ? "date" : "text"}
325
- value={entry.metadata[field.key] || ""}
326
- onChange={(e) => onUpdate({ metadata: { ...entry.metadata, [field.key]: e.target.value } })}
327
- className="w-full bg-surface-1 border-[1.5px] border-border-subtle rounded-[8px] px-2.5 py-2.5 text-[12px] text-foreground-1 outline-none focus:border-primary/40 transition-all [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none" />
328
- )}
329
- </div>
330
- ))}
331
- </div>
332
- )}
333
- </div>
334
- );
335
- }
1
+ "use client";
2
+
3
+ import React, { useState, useEffect, useCallback, useMemo } from "react";
4
+ import { cn } from "@apptimate/core-lib";
5
+ import { CreditCard, Banknote, Building, Trash2, Loader2, Split, Check, AlertCircle } from "lucide-react";
6
+
7
+ /* ── Types (mirroring sales POS types) ── */
8
+
9
+ export interface PaymentModeField {
10
+ key: string;
11
+ label: string;
12
+ type: "text" | "number" | "date" | "bank_account_select";
13
+ required: boolean;
14
+ }
15
+
16
+ export interface PaymentMode {
17
+ id: number;
18
+ code: string;
19
+ name: string;
20
+ is_active: boolean;
21
+ requires_reference: boolean;
22
+ field_config: { fields: PaymentModeField[] };
23
+ sort_order: number;
24
+ }
25
+
26
+ export interface PaymentEntry {
27
+ mode_id: number;
28
+ mode_code: string;
29
+ mode_name: string;
30
+ amount: number;
31
+ metadata: Record<string, string | number>;
32
+ }
33
+
34
+ export interface BankAccount {
35
+ id: number;
36
+ account_name: string;
37
+ bank_name: string;
38
+ branch?: string;
39
+ account_number: string;
40
+ account_type: string;
41
+ currency: string;
42
+ }
43
+
44
+ /* ── Props ── */
45
+
46
+ export interface PaymentSectionProps {
47
+ /** The total amount to collect */
48
+ totalAmount: number;
49
+ /** Current payment entries */
50
+ payments: PaymentEntry[];
51
+ /** Callback when payments change */
52
+ onPaymentsChange: (payments: PaymentEntry[]) => void;
53
+ /** Optional: show compact variant */
54
+ compact?: boolean;
55
+ /** Fetcher for payment modes */
56
+ fetchPaymentModes: () => Promise<{ is_success: boolean; result?: any }>;
57
+ /** Fetcher for bank accounts */
58
+ fetchBankAccounts: () => Promise<{ is_success: boolean; result?: any }>;
59
+ }
60
+
61
+ /* ── Component ── */
62
+
63
+ export function PaymentSection({ totalAmount, payments, onPaymentsChange, compact, fetchPaymentModes, fetchBankAccounts }: PaymentSectionProps) {
64
+ const [paymentModes, setPaymentModes] = useState<PaymentMode[]>([]);
65
+ const [bankAccounts, setBankAccounts] = useState<BankAccount[]>([]);
66
+ const [isLoading, setIsLoading] = useState(false);
67
+ const [selectionMode, setSelectionMode] = useState<"single" | "split">("single");
68
+
69
+ // ── Load payment modes on mount ──
70
+ useEffect(() => {
71
+ const load = async () => {
72
+ setIsLoading(true);
73
+ try {
74
+ const [modesRes, bankRes] = await Promise.all([fetchPaymentModes(), fetchBankAccounts()]);
75
+ const modes: PaymentMode[] = modesRes.is_success ? (modesRes.result || []) : [];
76
+ setPaymentModes(modes);
77
+ if (bankRes.is_success) setBankAccounts(bankRes.result || []);
78
+
79
+ // Auto-select cash if no payments yet
80
+ if (payments.length === 0 && modes.length > 0) {
81
+ const cashMode = modes.find((m) => m.code === "cash" && m.is_active);
82
+ if (cashMode) {
83
+ onPaymentsChange([{
84
+ mode_id: cashMode.id, mode_code: cashMode.code, mode_name: cashMode.name,
85
+ amount: totalAmount, metadata: {},
86
+ }]);
87
+ }
88
+ }
89
+ } finally { setIsLoading(false); }
90
+ };
91
+ load();
92
+ }, []);
93
+
94
+ // ── Calculations ──
95
+ const totalPaid = useMemo(() => payments.reduce((s, p) => s + p.amount, 0), [payments]);
96
+ const balance = useMemo(() => totalAmount - totalPaid, [totalAmount, totalPaid]);
97
+ const formatCurrency = (v: number) => v.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
98
+
99
+ // ── Mode icon ──
100
+ const getModeIcon = useCallback((code: string, size = 14) => {
101
+ switch (code) {
102
+ case "cash": return <Banknote size={size} />;
103
+ case "card": return <CreditCard size={size} />;
104
+ case "bank_transfer": return <Building size={size} />;
105
+ default: return <CreditCard size={size} />;
106
+ }
107
+ }, []);
108
+
109
+ // ── Payment management ──
110
+ const selectSingleMode = useCallback((mode: PaymentMode) => {
111
+ setSelectionMode("single");
112
+ onPaymentsChange([{
113
+ mode_id: mode.id, mode_code: mode.code, mode_name: mode.name,
114
+ amount: totalAmount, metadata: {},
115
+ }]);
116
+ }, [totalAmount, onPaymentsChange]);
117
+
118
+ const updatePayment = useCallback((index: number, updates: Partial<PaymentEntry>) => {
119
+ const next = [...payments];
120
+ next[index] = { ...next[index], ...updates };
121
+ onPaymentsChange(next);
122
+ }, [payments, onPaymentsChange]);
123
+
124
+ // ── Auto-sync single mode amount when totalAmount changes ──
125
+ useEffect(() => {
126
+ if (selectionMode === "single" && payments.length === 1) {
127
+ updatePayment(0, { amount: totalAmount });
128
+ }
129
+ // eslint-disable-next-line react-hooks/exhaustive-deps
130
+ }, [totalAmount, selectionMode]); // intentionally omitting `payments` to allow manual partial payments
131
+
132
+ const activateSplitMode = useCallback(() => {
133
+ setSelectionMode("split");
134
+ if (payments.length <= 1) onPaymentsChange([]);
135
+ }, [payments.length, onPaymentsChange]);
136
+
137
+ const addPayment = useCallback((mode: PaymentMode) => {
138
+ const entry: PaymentEntry = {
139
+ mode_id: mode.id, mode_code: mode.code, mode_name: mode.name,
140
+ amount: Math.max(0, balance), metadata: {},
141
+ };
142
+ onPaymentsChange([...payments, entry]);
143
+ }, [payments, balance, onPaymentsChange]);
144
+
145
+ const removePayment = useCallback((index: number) => {
146
+ onPaymentsChange(payments.filter((_, i) => i !== index));
147
+ }, [payments, onPaymentsChange]);
148
+
149
+ if (isLoading) {
150
+ return (
151
+ <div className="flex items-center justify-center py-4">
152
+ <Loader2 size={18} className="animate-spin text-primary" />
153
+ </div>
154
+ );
155
+ }
156
+
157
+ return (
158
+ <div className="space-y-3">
159
+ {/* ── Mode Selection Buttons ── */}
160
+ <div className="flex flex-wrap gap-2">
161
+ {paymentModes
162
+ .filter((m) => m.is_active)
163
+ .map((mode) => {
164
+ const isActive = selectionMode === "single" && payments.length === 1 && payments[0].mode_id === mode.id;
165
+ return (
166
+ <button key={mode.id} onClick={() => selectSingleMode(mode)}
167
+ className={cn(
168
+ "inline-flex items-center gap-2 px-4 py-2.5 text-[12px] font-semibold rounded-[10px] border transition-all",
169
+ isActive
170
+ ? "bg-primary text-primary-foreground border-primary shadow-sm"
171
+ : "bg-surface-0 border-border-subtle text-foreground-1 hover:border-primary/40 hover:bg-primary/5 hover:text-primary"
172
+ )}>
173
+ {getModeIcon(mode.code)}
174
+ {mode.name}
175
+ </button>
176
+ );
177
+ })}
178
+ {/* Split Button */}
179
+ <button onClick={activateSplitMode}
180
+ className={cn(
181
+ "inline-flex items-center gap-2 px-4 py-2.5 text-[12px] font-semibold rounded-[10px] border transition-all",
182
+ selectionMode === "split"
183
+ ? "bg-primary text-primary-foreground border-primary shadow-sm"
184
+ : "bg-surface-0 border-border-subtle text-foreground-1 hover:border-primary/40 hover:bg-primary/5 hover:text-primary"
185
+ )}>
186
+ <Split size={14} />
187
+ Multiple Methods
188
+ </button>
189
+ </div>
190
+
191
+ {/* ── Single Mode: Entry with fields (no delete) ── */}
192
+ {selectionMode === "single" && payments.length === 1 && (
193
+ <PaymentEntryRow entry={payments[0]} mode={paymentModes.find((m) => m.id === payments[0].mode_id)}
194
+ bankAccounts={bankAccounts} onUpdate={(updates) => updatePayment(0, updates)} onRemove={() => {}} showRemove={false} />
195
+ )}
196
+
197
+ {/* ── Split Mode: Multi-entry UI ── */}
198
+ {selectionMode === "split" && (
199
+ <div className="space-y-2.5">
200
+ {payments.map((entry, idx) => {
201
+ const mode = paymentModes.find((m) => m.id === entry.mode_id);
202
+ return (
203
+ <PaymentEntryRow key={idx} entry={entry} mode={mode} bankAccounts={bankAccounts}
204
+ onUpdate={(updates) => updatePayment(idx, updates)} onRemove={() => removePayment(idx)} />
205
+ );
206
+ })}
207
+ {/* Add split mode buttons */}
208
+ <div className="flex flex-wrap gap-1.5 pt-1">
209
+ {paymentModes
210
+ .filter((m) => m.is_active && !payments.some(p => p.mode_id === m.id))
211
+ .map((mode) => (
212
+ <button key={mode.id} onClick={() => addPayment(mode)}
213
+ className="inline-flex items-center gap-1.5 px-3 py-1.5 text-[11px] font-semibold rounded-[8px] bg-surface-0 border border-border-subtle text-foreground-subtle hover:border-primary/40 hover:text-primary transition-all">
214
+ {getModeIcon(mode.code, 12)}
215
+ + {mode.name}
216
+ </button>
217
+ ))}
218
+ </div>
219
+ </div>
220
+ )}
221
+
222
+ {/* ── Totals ── */}
223
+ {payments.length > 0 && (
224
+ <div className="bg-surface-0 rounded-[12px] border border-border-subtle p-4 space-y-2">
225
+ <TotalRow label="Amount to Pay" value={formatCurrency(totalAmount)} bold />
226
+ <div className="border-t border-border-subtle my-2" />
227
+ <TotalRow label="Total Paid" value={formatCurrency(totalPaid)} />
228
+ <TotalRow
229
+ label={balance > 0.01 ? "Balance Due" : balance < -0.01 ? "Change Due" : "Settled"}
230
+ value={formatCurrency(Math.abs(balance))}
231
+ className={balance > 0.01 ? "text-danger-alt" : "text-green-600"}
232
+ bold
233
+ />
234
+ {balance < -0.01 && (
235
+ <div className="flex items-center gap-1.5 mt-1 text-[11px] text-amber-600 font-medium">
236
+ <AlertCircle size={12} /><span>Change: {formatCurrency(Math.abs(balance))}</span>
237
+ </div>
238
+ )}
239
+ {Math.abs(balance) < 0.01 && (
240
+ <div className="flex items-center gap-1.5 mt-1 text-[11px] text-green-600 font-medium">
241
+ <Check size={12} /><span>Fully paid</span>
242
+ </div>
243
+ )}
244
+ </div>
245
+ )}
246
+ </div>
247
+ );
248
+ }
249
+
250
+ /* ── TotalRow ── */
251
+
252
+ function TotalRow({ label, value, bold, className }: { label: string; value: string; bold?: boolean; className?: string }) {
253
+ return (
254
+ <div className="flex items-center justify-between">
255
+ <span className={cn("text-[12px]", bold ? "font-bold text-foreground-1" : "text-foreground-subtle")}>{label}</span>
256
+ <span className={cn("text-[12px]", bold ? "font-bold text-foreground-0 text-[14px]" : "text-foreground-1 font-medium", className)}>{value}</span>
257
+ </div>
258
+ );
259
+ }
260
+
261
+ /* ── PaymentEntryRow (mirrors sales POS exactly) ── */
262
+
263
+ interface PaymentEntryRowProps {
264
+ entry: PaymentEntry;
265
+ mode?: PaymentMode;
266
+ bankAccounts: BankAccount[];
267
+ onUpdate: (updates: Partial<PaymentEntry>) => void;
268
+ onRemove: () => void;
269
+ showRemove?: boolean;
270
+ }
271
+
272
+ function PaymentEntryRow({ entry, mode, bankAccounts, onUpdate, onRemove, showRemove = true }: PaymentEntryRowProps) {
273
+ const fields = mode?.field_config?.fields || [];
274
+
275
+ const getModeIcon = () => {
276
+ switch (entry.mode_code) {
277
+ case "cash": return <Banknote size={13} />;
278
+ case "card": return <CreditCard size={13} />;
279
+ case "bank_transfer": return <Building size={13} />;
280
+ default: return <CreditCard size={13} />;
281
+ }
282
+ };
283
+
284
+ return (
285
+ <div className="bg-surface-0 border-[1.5px] border-border-subtle rounded-[10px] p-4 space-y-3">
286
+ {/* Header */}
287
+ <div className="flex items-center justify-between">
288
+ <div className="flex items-center gap-1.5 text-[12px] font-bold text-foreground-1">
289
+ {getModeIcon()}
290
+ {entry.mode_name}
291
+ </div>
292
+ {showRemove && (
293
+ <button onClick={onRemove}
294
+ className="w-7 h-7 rounded-[6px] flex items-center justify-center text-foreground-disabled hover:text-danger-alt hover:bg-danger-alt/10 transition-all">
295
+ <Trash2 size={13} />
296
+ </button>
297
+ )}
298
+ </div>
299
+
300
+ {/* Amount */}
301
+ <div className="flex flex-col gap-1">
302
+ <label className="text-[11px] text-foreground-subtle font-bold uppercase tracking-wider">Amount</label>
303
+ <input type="number" value={entry.amount || ""} onChange={(e) => onUpdate({ amount: Number(e.target.value) || 0 })}
304
+ className="w-full bg-surface-1 border-[1.5px] border-border-subtle rounded-[8px] px-3 py-2.5 text-[13px] font-medium text-foreground-1 outline-none focus:border-primary/40 transition-all [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"
305
+ step="0.01" min={0} />
306
+ </div>
307
+
308
+ {/* Dynamic sub-fields from field_config */}
309
+ {fields.length > 0 && (
310
+ <div className="grid grid-cols-2 gap-2.5">
311
+ {fields.map((field: PaymentModeField) => (
312
+ <div key={field.key} className="flex flex-col gap-1">
313
+ <label className="text-[11px] text-foreground-subtle font-bold uppercase tracking-wider">
314
+ {field.label}
315
+ {field.required && <span className="text-danger-alt ml-0.5">*</span>}
316
+ </label>
317
+ {field.type === "bank_account_select" ? (
318
+ <select value={entry.metadata[field.key] || ""}
319
+ onChange={(e) => onUpdate({ metadata: { ...entry.metadata, [field.key]: e.target.value ? Number(e.target.value) : "" } })}
320
+ className="w-full bg-surface-1 border-[1.5px] border-border-subtle rounded-[8px] px-2.5 py-2.5 text-[12px] text-foreground-1 outline-none focus:border-primary/40 transition-all">
321
+ <option value="">Select...</option>
322
+ {bankAccounts.map((b) => (<option key={b.id} value={b.id}>{b.bank_name} - {b.account_number}</option>))}
323
+ </select>
324
+ ) : (
325
+ <input type={field.type === "number" ? "number" : field.type === "date" ? "date" : "text"}
326
+ value={entry.metadata[field.key] || ""}
327
+ onChange={(e) => onUpdate({ metadata: { ...entry.metadata, [field.key]: e.target.value } })}
328
+ className="w-full bg-surface-1 border-[1.5px] border-border-subtle rounded-[8px] px-2.5 py-2.5 text-[12px] text-foreground-1 outline-none focus:border-primary/40 transition-all [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none" />
329
+ )}
330
+ </div>
331
+ ))}
332
+ </div>
333
+ )}
334
+ </div>
335
+ );
336
+ }