614 lines
30 KiB
JavaScript
614 lines
30 KiB
JavaScript
'use client';
|
|
|
|
import React, { useState, useEffect } from 'react';
|
|
import { useRouter } from 'next/navigation';
|
|
import { Button, Card, Input, Select, Textarea } from '../../../shared/components';
|
|
import { useToast } from '@hykocx/zen/toast';
|
|
import { formatDateForInput, subtractDays, getTodayString } from '../../../shared/lib/dates.js';
|
|
|
|
/**
|
|
* Invoice Create Page Component
|
|
* Page for creating a new invoice
|
|
*/
|
|
const InvoiceCreatePage = ({ user }) => {
|
|
const router = useRouter();
|
|
const toast = useToast();
|
|
const today = getTodayString();
|
|
|
|
const [clients, setClients] = useState([]);
|
|
const [items, setItems] = useState([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [saving, setSaving] = useState(false);
|
|
|
|
const [formData, setFormData] = useState({
|
|
client_id: '',
|
|
due_date: '',
|
|
status: 'draft',
|
|
notes: '',
|
|
first_reminder_days: 30,
|
|
items: [{ name: '', description: '', quantity: 1, unit_price: 0 }]
|
|
});
|
|
|
|
const [errors, setErrors] = useState({});
|
|
const [selectedItemIds, setSelectedItemIds] = useState(['custom']); // Track selected item ID for each item row
|
|
const [timeInputModes, setTimeInputModes] = useState([false]); // Track if time input mode is enabled for each item
|
|
const [timeInputValues, setTimeInputValues] = useState([{ hours: '', minutes: '' }]); // Track hours/minutes for each item
|
|
|
|
// Convert hours and minutes to decimal quantity
|
|
const convertTimeToQuantity = (hours, minutes) => {
|
|
const h = parseFloat(hours) || 0;
|
|
const m = parseFloat(minutes) || 0;
|
|
const totalHours = h + (m / 60);
|
|
return parseFloat(totalHours.toFixed(4));
|
|
};
|
|
|
|
const statusOptions = [
|
|
{ value: 'draft', label: "Brouillon" },
|
|
{ value: 'sent', label: "Envoyée" },
|
|
{ value: 'paid', label: "Payée" },
|
|
{ value: 'overdue', label: "En retard" },
|
|
{ value: 'cancelled', label: "Annulée" }
|
|
];
|
|
|
|
const reminderOptions = [
|
|
{ value: 30, label: '30 jours' },
|
|
{ value: 14, label: '14 jours' },
|
|
{ value: 7, label: '7 jours' },
|
|
{ value: 3, label: '3 jours' }
|
|
];
|
|
|
|
useEffect(() => {
|
|
loadData();
|
|
}, []);
|
|
|
|
const loadData = async () => {
|
|
try {
|
|
setLoading(true);
|
|
|
|
// Load clients
|
|
const clientsResponse = await fetch('/zen/api/admin/clients?limit=1000', {
|
|
credentials: 'include'
|
|
});
|
|
const clientsData = await clientsResponse.json();
|
|
|
|
if (clientsData.success) {
|
|
setClients(clientsData.clients || []);
|
|
} else {
|
|
toast.error("Échec du chargement des clients");
|
|
}
|
|
|
|
// Load items (active only)
|
|
const itemsResponse = await fetch('/zen/api/admin/items?limit=1000&is_active=true', {
|
|
credentials: 'include'
|
|
});
|
|
const itemsData = await itemsResponse.json();
|
|
|
|
if (itemsData.success) {
|
|
setItems(itemsData.items || []);
|
|
}
|
|
} catch (error) {
|
|
console.error('Error loading data:', error);
|
|
toast.error("Échec du chargement des données");
|
|
} finally {
|
|
setLoading(false);
|
|
}
|
|
};
|
|
|
|
const calculateTotals = () => {
|
|
const subtotal = formData.items.reduce((sum, item) => {
|
|
return sum + (parseFloat(item.quantity || 0) * parseFloat(item.unit_price || 0));
|
|
}, 0);
|
|
|
|
const total = subtotal;
|
|
|
|
return {
|
|
subtotal: parseFloat(subtotal.toFixed(2)),
|
|
total: parseFloat(total.toFixed(2))
|
|
};
|
|
};
|
|
|
|
// Calculate issue date based on due date and first reminder days
|
|
const calculateIssueDate = (dueDate, reminderDays) => {
|
|
if (!dueDate || !reminderDays) return '';
|
|
|
|
const issueDate = subtractDays(dueDate, parseInt(reminderDays));
|
|
return formatDateForInput(issueDate);
|
|
};
|
|
|
|
const handleInputChange = (field, value) => {
|
|
setFormData(prev => ({
|
|
...prev,
|
|
[field]: value
|
|
}));
|
|
|
|
if (errors[field]) {
|
|
setErrors(prev => ({
|
|
...prev,
|
|
[field]: null
|
|
}));
|
|
}
|
|
};
|
|
|
|
const handleItemChange = (index, field, value) => {
|
|
const newItems = [...formData.items];
|
|
newItems[index] = { ...newItems[index], [field]: value };
|
|
setFormData(prev => ({ ...prev, items: newItems }));
|
|
|
|
if (errors[`item_${index}_${field}`]) {
|
|
setErrors(prev => ({
|
|
...prev,
|
|
[`item_${index}_${field}`]: null
|
|
}));
|
|
}
|
|
};
|
|
|
|
// Toggle between quantity and time input mode
|
|
const toggleTimeInputMode = (index) => {
|
|
const newModes = [...timeInputModes];
|
|
newModes[index] = !newModes[index];
|
|
setTimeInputModes(newModes);
|
|
|
|
// If switching to time mode, initialize with current quantity converted to time
|
|
if (newModes[index]) {
|
|
const currentQty = parseFloat(formData.items[index].quantity) || 0;
|
|
const hours = Math.floor(currentQty);
|
|
const minutes = Math.round((currentQty - hours) * 60);
|
|
const newTimeValues = [...timeInputValues];
|
|
newTimeValues[index] = { hours: hours || '', minutes: minutes || '' };
|
|
setTimeInputValues(newTimeValues);
|
|
}
|
|
};
|
|
|
|
// Handle time input changes (hours or minutes)
|
|
const handleTimeInputChange = (index, field, value) => {
|
|
const newTimeValues = [...timeInputValues];
|
|
newTimeValues[index] = { ...newTimeValues[index], [field]: value };
|
|
setTimeInputValues(newTimeValues);
|
|
|
|
// Convert to quantity and update the item
|
|
const hours = field === 'hours' ? value : newTimeValues[index].hours;
|
|
const minutes = field === 'minutes' ? value : newTimeValues[index].minutes;
|
|
const quantity = convertTimeToQuantity(hours, minutes);
|
|
handleItemChange(index, 'quantity', quantity);
|
|
};
|
|
|
|
const handleSelectItem = (index, itemId) => {
|
|
// Update the selected item ID for this row
|
|
const newSelectedItemIds = [...selectedItemIds];
|
|
newSelectedItemIds[index] = itemId;
|
|
setSelectedItemIds(newSelectedItemIds);
|
|
|
|
if (itemId === '' || itemId === 'custom') {
|
|
// Reset to custom/empty
|
|
handleItemChange(index, 'name', '');
|
|
handleItemChange(index, 'description', '');
|
|
handleItemChange(index, 'unit_price', 0);
|
|
return;
|
|
}
|
|
|
|
const selectedItem = items.find(item => item.id === parseInt(itemId));
|
|
if (selectedItem) {
|
|
// Build full item name with category hierarchy
|
|
let fullItemName = '';
|
|
if (selectedItem.parent_category_title) {
|
|
fullItemName = `${selectedItem.parent_category_title} - ${selectedItem.category_title} - ${selectedItem.name}`;
|
|
} else if (selectedItem.category_title) {
|
|
fullItemName = `${selectedItem.category_title} - ${selectedItem.name}`;
|
|
} else {
|
|
fullItemName = selectedItem.name;
|
|
}
|
|
|
|
// Pre-fill fields from selected item
|
|
const newItems = [...formData.items];
|
|
newItems[index] = {
|
|
...newItems[index],
|
|
name: fullItemName,
|
|
description: selectedItem.description || '',
|
|
unit_price: selectedItem.unit_price
|
|
};
|
|
setFormData(prev => ({ ...prev, items: newItems }));
|
|
}
|
|
};
|
|
|
|
const addItem = () => {
|
|
setFormData(prev => ({
|
|
...prev,
|
|
items: [...prev.items, { name: '', description: '', quantity: 1, unit_price: 0 }]
|
|
}));
|
|
setSelectedItemIds(prev => [...prev, 'custom']);
|
|
setTimeInputModes(prev => [...prev, false]);
|
|
setTimeInputValues(prev => [...prev, { hours: '', minutes: '' }]);
|
|
};
|
|
|
|
const removeItem = (index) => {
|
|
if (formData.items.length > 1) {
|
|
setFormData(prev => ({
|
|
...prev,
|
|
items: prev.items.filter((_, i) => i !== index)
|
|
}));
|
|
setSelectedItemIds(prev => prev.filter((_, i) => i !== index));
|
|
setTimeInputModes(prev => prev.filter((_, i) => i !== index));
|
|
setTimeInputValues(prev => prev.filter((_, i) => i !== index));
|
|
}
|
|
};
|
|
|
|
const validateForm = () => {
|
|
const newErrors = {};
|
|
|
|
if (!formData.client_id) {
|
|
newErrors.client_id = "Le client est requis";
|
|
}
|
|
|
|
if (!formData.due_date) {
|
|
newErrors.due_date = "La date d'échéance est requise";
|
|
}
|
|
|
|
formData.items.forEach((item, index) => {
|
|
if (!item.name.trim()) {
|
|
newErrors[`item_${index}_name`] = "Le nom de l'article est requis";
|
|
}
|
|
if (!item.quantity || item.quantity <= 0) {
|
|
newErrors[`item_${index}_quantity`] = "La quantité doit être supérieure à 0";
|
|
}
|
|
if (item.unit_price < 0) {
|
|
newErrors[`item_${index}_unit_price`] = "Le prix unitaire ne peut pas être négatif";
|
|
}
|
|
});
|
|
|
|
setErrors(newErrors);
|
|
return Object.keys(newErrors).length === 0;
|
|
};
|
|
|
|
const handleSubmit = async (e) => {
|
|
e.preventDefault();
|
|
|
|
if (!validateForm()) {
|
|
return;
|
|
}
|
|
|
|
try {
|
|
setSaving(true);
|
|
|
|
// Calculate issue_date before submitting
|
|
const issue_date = calculateIssueDate(formData.due_date, formData.first_reminder_days);
|
|
|
|
const invoiceDataToSubmit = {
|
|
...formData,
|
|
issue_date
|
|
};
|
|
|
|
const response = await fetch('/zen/api/admin/invoices', {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
credentials: 'include',
|
|
body: JSON.stringify({ invoice: invoiceDataToSubmit }),
|
|
});
|
|
|
|
const data = await response.json();
|
|
|
|
if (data.success) {
|
|
toast.success("Facture créée avec succès");
|
|
router.push('/admin/invoice/invoices');
|
|
} else {
|
|
toast.error(data.error || "Échec de la création de la facture");
|
|
}
|
|
} catch (error) {
|
|
console.error('Error creating invoice:', error);
|
|
toast.error("Échec de la création de la facture");
|
|
} finally {
|
|
setSaving(false);
|
|
}
|
|
};
|
|
|
|
const totals = calculateTotals();
|
|
|
|
return (
|
|
<div className="flex flex-col gap-4 sm:gap-6 lg:gap-8">
|
|
{/* Header */}
|
|
<div className="flex items-center justify-between">
|
|
<div>
|
|
<h1 className="text-lg sm:text-xl font-semibold text-neutral-900 dark:text-white">Créer une facture</h1>
|
|
<p className="mt-1 text-xs text-neutral-400">Remplissez les détails pour créer une nouvelle facture</p>
|
|
</div>
|
|
<Button
|
|
variant="secondary"
|
|
size="sm"
|
|
onClick={() => router.push('/admin/invoice/invoices')}
|
|
>
|
|
← Retour aux factures
|
|
</Button>
|
|
</div>
|
|
|
|
{/* Form */}
|
|
<form onSubmit={handleSubmit} className="space-y-6">
|
|
{/* Invoice Information */}
|
|
<Card>
|
|
<div className="space-y-4">
|
|
<h2 className="text-lg font-semibold text-neutral-900 dark:text-white">Informations de la facture</h2>
|
|
|
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
<Select
|
|
label="Client *"
|
|
value={formData.client_id}
|
|
onChange={(value) => handleInputChange('client_id', value)}
|
|
options={[
|
|
{ value: '', label: "Sélectionner un client" },
|
|
...clients.map(client => ({
|
|
value: client.id,
|
|
label: client.company_name || `${client.first_name} ${client.last_name}`
|
|
}))
|
|
]}
|
|
error={errors.client_id}
|
|
disabled={loading}
|
|
/>
|
|
|
|
<Select
|
|
label="Statut"
|
|
value={formData.status}
|
|
onChange={(value) => handleInputChange('status', value)}
|
|
options={statusOptions}
|
|
/>
|
|
|
|
<Input
|
|
label="Date d'échéance *"
|
|
type="date"
|
|
value={formData.due_date}
|
|
onChange={(value) => handleInputChange('due_date', value)}
|
|
error={errors.due_date}
|
|
/>
|
|
|
|
<Select
|
|
label="Premier rappel (jours avant l'échéance)"
|
|
value={formData.first_reminder_days}
|
|
onChange={(value) => handleInputChange('first_reminder_days', value)}
|
|
options={reminderOptions}
|
|
/>
|
|
</div>
|
|
|
|
{formData.due_date && formData.first_reminder_days && (
|
|
<div className="bg-blue-500/10 border border-blue-500/20 text-blue-400 px-4 py-3 rounded-lg">
|
|
<p className="text-sm">
|
|
<strong>Date d'émission calculée :</strong> {calculateIssueDate(formData.due_date, formData.first_reminder_days)}
|
|
<span className="ml-2 text-xs">(Date d'échéance moins les jours du premier rappel)</span>
|
|
</p>
|
|
</div>
|
|
)}
|
|
</div>
|
|
</Card>
|
|
|
|
{/* Items */}
|
|
<Card>
|
|
<div className="space-y-4">
|
|
<div className="flex justify-between items-center">
|
|
<h2 className="text-lg font-semibold text-neutral-900 dark:text-white">Articles</h2>
|
|
</div>
|
|
|
|
<div className="space-y-4">
|
|
{formData.items.map((item, index) => (
|
|
<div key={index} className="border border-neutral-200 dark:border-neutral-700/50 rounded-lg p-4 bg-neutral-50 dark:bg-neutral-900/20">
|
|
<div className="flex justify-between items-start mb-4">
|
|
<h3 className="text-sm font-medium text-neutral-700 dark:text-neutral-300">Article {index + 1}</h3>
|
|
{formData.items.length > 1 && (
|
|
<Button
|
|
type="button"
|
|
variant="danger"
|
|
size="sm"
|
|
onClick={() => removeItem(index)}
|
|
>
|
|
Supprimer
|
|
</Button>
|
|
)}
|
|
</div>
|
|
|
|
<div className="space-y-4">
|
|
<div className="grid gap-4 grid-cols-1 md:grid-cols-2">
|
|
<Select
|
|
label="Article *"
|
|
value={selectedItemIds[index] || 'custom'}
|
|
onChange={(value) => handleSelectItem(index, value)}
|
|
options={[
|
|
{ value: 'custom', label: "Personnalisé" },
|
|
...items.map(availableItem => {
|
|
// Build category hierarchy display
|
|
let categoryDisplay = '';
|
|
if (availableItem.parent_category_title) {
|
|
categoryDisplay = `${availableItem.parent_category_title} - ${availableItem.category_title} - `;
|
|
} else if (availableItem.category_title) {
|
|
categoryDisplay = `${availableItem.category_title} - `;
|
|
}
|
|
|
|
return {
|
|
value: availableItem.id,
|
|
label: `${categoryDisplay}${availableItem.name} - $${parseFloat(availableItem.unit_price).toFixed(2)}`
|
|
};
|
|
})
|
|
]}
|
|
/>
|
|
|
|
<Input
|
|
label="Nom de l'article *"
|
|
value={item.name}
|
|
onChange={(value) => handleItemChange(index, 'name', value)}
|
|
placeholder="Entrez le nom de l'article..."
|
|
error={errors[`item_${index}_name`]}
|
|
/>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
|
<div className="space-y-2">
|
|
<div className="flex items-center justify-between">
|
|
<label className="block text-sm font-medium text-neutral-700 dark:text-neutral-300">
|
|
Quantité *
|
|
</label>
|
|
<button
|
|
type="button"
|
|
onClick={() => toggleTimeInputMode(index)}
|
|
className={`text-xs px-2 py-1 rounded transition-colors ${
|
|
timeInputModes[index]
|
|
? 'bg-blue-500/20 text-blue-400 border border-blue-500/30'
|
|
: 'bg-neutral-100 dark:bg-neutral-700/50 text-neutral-600 dark:text-neutral-400 border border-neutral-200 dark:border-neutral-600/50 hover:bg-neutral-200 dark:hover:bg-neutral-700'
|
|
}`}
|
|
>
|
|
{timeInputModes[index] ? "Heures" : "Qté"}
|
|
</button>
|
|
</div>
|
|
|
|
{timeInputModes[index] ? (
|
|
<div className="space-y-2">
|
|
<div className="flex gap-2">
|
|
<div className="flex-1">
|
|
<Input
|
|
type="number"
|
|
min="0"
|
|
step="1"
|
|
value={timeInputValues[index]?.hours || ''}
|
|
onChange={(value) => handleTimeInputChange(index, 'hours', value)}
|
|
placeholder="0"
|
|
/>
|
|
<span className="text-xs text-neutral-500 mt-1 block">Heures</span>
|
|
</div>
|
|
<div className="flex-1">
|
|
<Input
|
|
type="number"
|
|
min="0"
|
|
max="59"
|
|
step="1"
|
|
value={timeInputValues[index]?.minutes || ''}
|
|
onChange={(value) => handleTimeInputChange(index, 'minutes', value)}
|
|
placeholder="0"
|
|
/>
|
|
<span className="text-xs text-neutral-500 mt-1 block">Minutes</span>
|
|
</div>
|
|
</div>
|
|
<div className="text-xs text-neutral-600 dark:text-neutral-400 bg-neutral-100 dark:bg-neutral-800/50 px-2 py-1 rounded">
|
|
= {item.quantity} unités
|
|
</div>
|
|
{errors[`item_${index}_quantity`] && (
|
|
<p className="text-sm text-red-600 dark:text-red-400">{errors[`item_${index}_quantity`]}</p>
|
|
)}
|
|
</div>
|
|
) : (
|
|
<Input
|
|
type="number"
|
|
step="0.01"
|
|
min="0"
|
|
value={item.quantity}
|
|
onChange={(value) => handleItemChange(index, 'quantity', value)}
|
|
error={errors[`item_${index}_quantity`]}
|
|
/>
|
|
)}
|
|
</div>
|
|
|
|
<Input
|
|
label="Prix unitaire *"
|
|
type="number"
|
|
step="0.01"
|
|
min="0"
|
|
value={item.unit_price}
|
|
onChange={(value) => handleItemChange(index, 'unit_price', value)}
|
|
error={errors[`item_${index}_unit_price`]}
|
|
/>
|
|
</div>
|
|
|
|
<Textarea
|
|
label="Description"
|
|
value={item.description}
|
|
onChange={(value) => handleItemChange(index, 'description', value)}
|
|
rows={2}
|
|
placeholder="Décrivez l'article ou le service..."
|
|
/>
|
|
|
|
<div className="text-right pt-2 border-t border-neutral-200 dark:border-neutral-700/50">
|
|
<span className="text-sm text-neutral-400">Total de l'article : </span>
|
|
<span className="text-lg font-semibold text-green-400">
|
|
${(parseFloat(item.quantity || 0) * parseFloat(item.unit_price || 0)).toLocaleString('en-US', {
|
|
minimumFractionDigits: 2,
|
|
maximumFractionDigits: 2
|
|
})}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
))}
|
|
|
|
<div className="flex justify-end items-center">
|
|
<Button
|
|
type="button"
|
|
variant="secondary"
|
|
size="sm"
|
|
onClick={addItem}
|
|
>
|
|
+ Ajouter un article
|
|
</Button>
|
|
</div>
|
|
</div>
|
|
|
|
{/* Totals */}
|
|
<div className="pt-4 border-t border-neutral-200 dark:border-neutral-700/50">
|
|
<div className="flex justify-end">
|
|
<div className="w-full sm:w-80 space-y-2">
|
|
<div className="flex justify-between text-neutral-600 dark:text-neutral-300">
|
|
<span>Sous-total :</span>
|
|
<span className="font-medium">
|
|
${totals.subtotal.toLocaleString('en-US', {
|
|
minimumFractionDigits: 2,
|
|
maximumFractionDigits: 2
|
|
})}
|
|
</span>
|
|
</div>
|
|
<div className="flex justify-between text-neutral-900 dark:text-white text-lg font-semibold pt-2 border-t border-neutral-200 dark:border-neutral-700/50">
|
|
<span>Total :</span>
|
|
<span>
|
|
${totals.total.toLocaleString('en-US', {
|
|
minimumFractionDigits: 2,
|
|
maximumFractionDigits: 2
|
|
})}
|
|
</span>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</Card>
|
|
|
|
{/* Notes */}
|
|
<Card>
|
|
<div className="space-y-4">
|
|
<h2 className="text-lg font-semibold text-neutral-900 dark:text-white">Notes</h2>
|
|
<Textarea
|
|
value={formData.notes}
|
|
onChange={(value) => handleInputChange('notes', value)}
|
|
rows={4}
|
|
placeholder="Ajoutez des notes supplémentaires ou des instructions de paiement..."
|
|
/>
|
|
</div>
|
|
</Card>
|
|
|
|
{/* Actions */}
|
|
<div className="flex items-center justify-end gap-3">
|
|
<Button
|
|
type="button"
|
|
variant="secondary"
|
|
onClick={() => router.push('/admin/invoice/invoices')}
|
|
disabled={saving}
|
|
>
|
|
Annuler
|
|
</Button>
|
|
<Button
|
|
type="submit"
|
|
variant="success"
|
|
loading={saving}
|
|
disabled={saving}
|
|
>
|
|
{saving ? "Création..." : "Créer une facture"}
|
|
</Button>
|
|
</div>
|
|
</form>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default InvoiceCreatePage;
|