Feat purchase order

This commit is contained in:
kevin 2026-01-28 14:26:20 +03:00
parent 0009eb8c86
commit ed5181d290
17 changed files with 1423 additions and 399 deletions

View File

@ -0,0 +1,156 @@
<?php
declare(strict_types=1);
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Http\Requests\StorePurchaseOrderRequest;
use App\Http\Requests\UpdatePurchaseOrderRequest;
use App\Http\Resources\Fournisseur\PurchaseOrderResource;
use App\Repositories\PurchaseOrderRepositoryInterface;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Facades\Log;
class PurchaseOrderController extends Controller
{
public function __construct(
protected PurchaseOrderRepositoryInterface $purchaseOrderRepository
) {
}
/**
* Display a listing of purchase orders.
*/
public function index(): AnonymousResourceCollection|JsonResponse
{
try {
$purchaseOrders = $this->purchaseOrderRepository->all();
return PurchaseOrderResource::collection($purchaseOrders);
} catch (\Exception $e) {
Log::error('Error fetching purchase orders: ' . $e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
]);
return response()->json([
'message' => 'Une erreur est survenue lors de la récupération des commandes fournisseurs.',
'error' => config('app.debug') ? $e->getMessage() : null,
], 500);
}
}
/**
* Store a newly created purchase order.
*/
public function store(StorePurchaseOrderRequest $request): PurchaseOrderResource|JsonResponse
{
try {
$purchaseOrder = $this->purchaseOrderRepository->create($request->validated());
return new PurchaseOrderResource($purchaseOrder);
} catch (\Exception $e) {
Log::error('Error creating purchase order: ' . $e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'data' => $request->validated(),
]);
return response()->json([
'message' => 'Une erreur est survenue lors de la création de la commande fournisseur.',
'error' => config('app.debug') ? $e->getMessage() : null,
], 500);
}
}
/**
* Display the specified purchase order.
*/
public function show(string $id): PurchaseOrderResource|JsonResponse
{
try {
$purchaseOrder = $this->purchaseOrderRepository->find($id);
if (!$purchaseOrder) {
return response()->json([
'message' => 'Commande fournisseur non trouvée.',
], 404);
}
return new PurchaseOrderResource($purchaseOrder);
} catch (\Exception $e) {
Log::error('Error fetching purchase order: ' . $e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'purchase_order_id' => $id,
]);
return response()->json([
'message' => 'Une erreur est survenue lors de la récupération de la commande fournisseur.',
'error' => config('app.debug') ? $e->getMessage() : null,
], 500);
}
}
/**
* Update the specified purchase order.
*/
public function update(UpdatePurchaseOrderRequest $request, string $id): PurchaseOrderResource|JsonResponse
{
try {
$updated = $this->purchaseOrderRepository->update($id, $request->validated());
if (!$updated) {
return response()->json([
'message' => 'Commande fournisseur non trouvée ou échec de la mise à jour.',
], 404);
}
$purchaseOrder = $this->purchaseOrderRepository->find($id);
return new PurchaseOrderResource($purchaseOrder);
} catch (\Exception $e) {
Log::error('Error updating purchase order: ' . $e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'purchase_order_id' => $id,
'data' => $request->validated(),
]);
return response()->json([
'message' => 'Une erreur est survenue lors de la mise à jour de la commande fournisseur.',
'error' => config('app.debug') ? $e->getMessage() : null,
], 500);
}
}
/**
* Remove the specified purchase order.
*/
public function destroy(string $id): JsonResponse
{
try {
$deleted = $this->purchaseOrderRepository->delete($id);
if (!$deleted) {
return response()->json([
'message' => 'Commande fournisseur non trouvée ou échec de la suppression.',
], 404);
}
return response()->json([
'message' => 'Commande fournisseur supprimée avec succès.',
], 200);
} catch (\Exception $e) {
Log::error('Error deleting purchase order: ' . $e->getMessage(), [
'exception' => $e,
'trace' => $e->getTraceAsString(),
'purchase_order_id' => $id,
]);
return response()->json([
'message' => 'Une erreur est survenue lors de la suppression de la commande fournisseur.',
'error' => config('app.debug') ? $e->getMessage() : null,
], 500);
}
}
}

View File

@ -0,0 +1,80 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class StorePurchaseOrderRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'fournisseur_id' => ['required', 'exists:fournisseurs,id'],
'po_number' => ['nullable', 'string', 'max:191', 'unique:purchase_orders,po_number'],
'status' => ['nullable', 'in:brouillon,confirmee,livree,facturee,annulee'],
'order_date' => ['nullable', 'date'],
'expected_date' => ['nullable', 'date'],
'currency' => ['nullable', 'string', 'size:3'],
'total_ht' => ['required', 'numeric', 'min:0'],
'total_tva' => ['required', 'numeric', 'min:0'],
'total_ttc' => ['required', 'numeric', 'min:0'],
'notes' => ['nullable', 'string'],
'delivery_address' => ['nullable', 'string'],
'lines' => ['required', 'array', 'min:1'],
'lines.*.product_id' => ['nullable', 'exists:products,id'],
'lines.*.description' => ['required', 'string'],
'lines.*.quantity' => ['required', 'numeric', 'min:0.001'],
'lines.*.unit_price' => ['required', 'numeric', 'min:0'],
'lines.*.tva_rate' => ['required', 'numeric', 'min:0'],
'lines.*.discount_pct' => ['nullable', 'numeric', 'min:0', 'max:100'],
'lines.*.total_ht' => ['required', 'numeric', 'min:0'],
];
}
/**
* Get the error messages for the defined validation rules.
*
* @return array<string, string>
*/
public function messages(): array
{
return [
'fournisseur_id.required' => 'Le fournisseur est obligatoire.',
'fournisseur_id.exists' => 'Le fournisseur sélectionné est invalide.',
'po_number.unique' => 'Ce numéro de commande existe déjà.',
'order_date.date' => 'La date de commande n\'est pas valide.',
'expected_date.date' => 'La date de livraison prévue n\'est pas valide.',
'status.in' => 'Le statut sélectionné est invalide.',
'total_ht.required' => 'Le total HT est obligatoire.',
'total_tva.required' => 'Le total TVA est obligatoire.',
'total_ttc.required' => 'Le total TTC est obligatoire.',
'lines.required' => 'Au moins une ligne d\'article est requise.',
'lines.array' => 'Les lignes doivent être un tableau.',
'lines.min' => 'Vous devez ajouter au moins une ligne d\'article.',
'lines.*.description.required' => 'La désignation est obligatoire pour toutes les lignes.',
'lines.*.quantity.required' => 'La quantité est obligatoire.',
'lines.*.quantity.numeric' => 'La quantité doit être un nombre.',
'lines.*.quantity.min' => 'La quantité doit être supérieure à 0.',
'lines.*.unit_price.required' => 'Le prix unitaire est obligatoire.',
'lines.*.unit_price.numeric' => 'Le prix unitaire doit être un nombre.',
'lines.*.unit_price.min' => 'Le prix unitaire doit être positif.',
'lines.*.tva_rate.required' => 'Le taux de TVA est obligatoire.',
'lines.*.total_ht.required' => 'Le total HT de la ligne est obligatoire.',
];
}
}

View File

@ -0,0 +1,48 @@
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UpdatePurchaseOrderRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'fournisseur_id' => ['nullable', 'exists:fournisseurs,id'],
'po_number' => ['nullable', 'string', 'max:191', 'unique:purchase_orders,po_number,' . $this->route('purchase_order')],
'status' => ['nullable', 'in:brouillon,confirmee,livree,facturee,annulee'],
'order_date' => ['nullable', 'date'],
'expected_date' => ['nullable', 'date'],
'currency' => ['nullable', 'string', 'size:3'],
'total_ht' => ['nullable', 'numeric', 'min:0'],
'total_tva' => ['nullable', 'numeric', 'min:0'],
'total_ttc' => ['nullable', 'numeric', 'min:0'],
'notes' => ['nullable', 'string'],
'delivery_address' => ['nullable', 'string'],
'lines' => ['nullable', 'array', 'min:1'],
'lines.*.product_id' => ['nullable', 'exists:products,id'],
'lines.*.description' => ['required', 'string'],
'lines.*.quantity' => ['required', 'numeric', 'min:0.001'],
'lines.*.unit_price' => ['required', 'numeric', 'min:0'],
'lines.*.tva_rate' => ['required', 'numeric', 'min:0'],
'lines.*.discount_pct' => ['nullable', 'numeric', 'min:0', 'max:100'],
'lines.*.total_ht' => ['required', 'numeric', 'min:0'],
];
}
}

View File

@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace App\Http\Resources\Fournisseur;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
class PurchaseOrderResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @return array<string, mixed>
*/
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'fournisseur_id' => $this->fournisseur_id,
'fournisseur' => $this->whenLoaded('fournisseur'),
'po_number' => $this->po_number,
'status' => $this->status,
'order_date' => $this->order_date ? $this->order_date->format('Y-m-d') : null,
'expected_date' => $this->expected_date ? $this->expected_date->format('Y-m-d') : null,
'currency' => $this->currency,
'total_ht' => $this->total_ht,
'total_tva' => $this->total_tva,
'total_ttc' => $this->total_ttc,
'notes' => $this->notes,
'delivery_address' => $this->delivery_address,
'lines' => $this->whenLoaded('lines'),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}

View File

@ -0,0 +1,69 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class PurchaseOrder extends Model
{
use HasFactory;
protected static function booted()
{
static::creating(function ($purchaseOrder) {
// Auto-generate PO number if not provided
if (empty($purchaseOrder->po_number)) {
$prefix = 'CMD-' . now()->format('Ym') . '-';
$lastOrder = self::where('po_number', 'like', $prefix . '%')
->orderBy('po_number', 'desc')
->first();
if ($lastOrder) {
$lastNumber = intval(substr($lastOrder->po_number, -4));
$newNumber = $lastNumber + 1;
} else {
$newNumber = 1;
}
$purchaseOrder->po_number = $prefix . str_pad((string)$newNumber, 4, '0', STR_PAD_LEFT);
}
});
}
protected $fillable = [
'fournisseur_id',
'po_number',
'status',
'order_date',
'expected_date',
'currency',
'total_ht',
'total_tva',
'total_ttc',
'notes',
'delivery_address',
];
protected $casts = [
'order_date' => 'date',
'expected_date' => 'date',
'total_ht' => 'decimal:2',
'total_tva' => 'decimal:2',
'total_ttc' => 'decimal:2',
];
public function fournisseur(): BelongsTo
{
return $this->belongsTo(Fournisseur::class);
}
public function lines(): HasMany
{
return $this->hasMany(PurchaseOrderLine::class);
}
}

View File

@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class PurchaseOrderLine extends Model
{
use HasFactory;
protected $fillable = [
'purchase_order_id',
'product_id',
'description',
'quantity',
'unit_price',
'tva_rate',
'discount_pct',
'total_ht',
];
protected $casts = [
'quantity' => 'decimal:3',
'unit_price' => 'decimal:2',
'tva_rate' => 'decimal:2',
'discount_pct' => 'decimal:2',
'total_ht' => 'decimal:2',
];
public function purchaseOrder(): BelongsTo
{
return $this->belongsTo(PurchaseOrder::class);
}
public function product(): BelongsTo
{
return $this->belongsTo(Product::class);
}
}

View File

@ -105,6 +105,9 @@ class AppServiceProvider extends ServiceProvider
$this->app->bind(\App\Repositories\QuoteLineRepositoryInterface::class, \App\Repositories\QuoteLineRepository::class);
$this->app->bind(\App\Repositories\ClientActivityTimelineRepositoryInterface::class, \App\Repositories\ClientActivityTimelineRepository::class);
$this->app->bind(\App\Repositories\PurchaseOrderRepositoryInterface::class, \App\Repositories\PurchaseOrderRepository::class);
$this->app->bind(\App\Repositories\DeceasedDocumentRepositoryInterface::class, \App\Repositories\DeceasedDocumentRepository::class);
}

View File

@ -23,6 +23,7 @@ class RepositoryServiceProvider extends ServiceProvider
$this->app->bind(DeceasedDocumentRepositoryInterface::class, DeceasedDocumentRepository::class);
$this->app->bind(InterventionRepositoryInterface::class, InterventionRepository::class);
$this->app->bind(FileRepositoryInterface::class, FileRepository::class);
$this->app->bind(\App\Repositories\PurchaseOrderRepositoryInterface::class, \App\Repositories\PurchaseOrderRepository::class);
}

View File

@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace App\Repositories;
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderLine;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Collection;
class PurchaseOrderRepository extends BaseRepository implements PurchaseOrderRepositoryInterface
{
public function __construct(PurchaseOrder $model)
{
parent::__construct($model);
}
public function all(array $columns = ['*']): Collection
{
return $this->model->with(['fournisseur', 'lines.product'])->get($columns);
}
public function find(int|string $id, array $columns = ['*']): ?PurchaseOrder
{
return $this->model->with(['fournisseur', 'lines.product'])->find($id, $columns);
}
public function create(array $attributes): PurchaseOrder
{
return DB::transaction(function () use ($attributes) {
try {
$lines = $attributes['lines'] ?? [];
unset($attributes['lines']);
$purchaseOrder = parent::create($attributes);
foreach ($lines as $line) {
$purchaseOrder->lines()->create($line);
}
return $purchaseOrder->load('lines.product');
} catch (\Exception $e) {
Log::error('Error creating PurchaseOrder with lines: ' . $e->getMessage(), [
'attributes' => $attributes,
'exception' => $e
]);
throw $e;
}
});
}
public function update(int|string $id, array $attributes): bool
{
return DB::transaction(function () use ($id, $attributes) {
try {
$purchaseOrder = $this->find($id);
if (!$purchaseOrder) {
return false;
}
$lines = $attributes['lines'] ?? null;
unset($attributes['lines']);
$updated = parent::update($id, $attributes);
if ($lines !== null && $updated) {
$purchaseOrder->lines()->delete();
foreach ($lines as $line) {
$purchaseOrder->lines()->create($line);
}
}
return $updated;
} catch (\Exception $e) {
Log::error('Error updating PurchaseOrder with lines: ' . $e->getMessage(), [
'id' => $id,
'attributes' => $attributes,
'exception' => $e
]);
throw $e;
}
});
}
}

View File

@ -0,0 +1,9 @@
<?php
declare(strict_types=1);
namespace App\Repositories;
interface PurchaseOrderRepositoryInterface extends BaseRepositoryInterface
{
}

View File

@ -20,6 +20,7 @@ use App\Http\Controllers\Api\FileController;
use App\Http\Controllers\Api\FileAttachmentController;
use App\Http\Controllers\Api\QuoteController;
use App\Http\Controllers\Api\ClientActivityTimelineController;
use App\Http\Controllers\Api\PurchaseOrderController;
/*
@ -85,6 +86,7 @@ Route::middleware('auth:sanctum')->group(function () {
// Fournisseur management
Route::get('/fournisseurs/searchBy', [FournisseurController::class, 'searchBy']);
Route::apiResource('purchase-orders', PurchaseOrderController::class);
Route::apiResource('fournisseurs', FournisseurController::class);
Route::get('fournisseurs/{fournisseurId}/contacts', [ContactController::class, 'getContactsByFournisseur']);

View File

@ -8,7 +8,7 @@
<div class="row">
<div class="col-12">
<avoir-table
:data="filteredAvoirs"
:data="avoirs"
:loading="loading"
@view="handleView"
@delete="handleDelete"
@ -23,72 +23,18 @@ import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import AvoirListControls from "@/components/molecules/Avoir/AvoirListControls.vue";
import AvoirTable from "@/components/molecules/Tables/Avoirs/AvoirTable.vue";
import { useAvoirStore } from "@/stores/avoirStore";
import { storeToRefs } from "pinia";
const router = useRouter();
const loading = ref(false);
const avoirStore = useAvoirStore();
const { avoirs, loading, error } = storeToRefs(avoirStore);
const activeFilter = ref(null);
// Sample data for avoirs
const avoirs = ref([
{
id: "1",
number: "AV-2026-00001",
invoiceNumber: "F-2026-00001",
clientName: "Caroline Lepetit thanatopraxie",
amount: 168.0,
status: "emis",
date: new Date(2026, 0, 15),
reason: "Erreur de facturation",
},
{
id: "2",
number: "AV-2026-00002",
invoiceNumber: "FAC-202512-0002",
clientName: "Hygiène Funéraire 50",
amount: 84.0,
status: "applique",
date: new Date(2026, 0, 18),
reason: "Retour de marchandise",
},
{
id: "3",
number: "AV-2026-00003",
invoiceNumber: "FAC-202512-0005",
clientName: "Pompes Funèbres Martin",
amount: 54.0,
status: "brouillon",
date: new Date(2026, 0, 20),
reason: "Geste commercial",
},
{
id: "4",
number: "AV-2026-00004",
invoiceNumber: "FAC-202512-0007",
clientName: "Pompes Funèbres Martin",
amount: 108.0,
status: "emis",
date: new Date(2026, 0, 22),
reason: "Annulation de prestation",
},
{
id: "5",
number: "AV-2026-00005",
invoiceNumber: "FACT-2024-003",
clientName: "PF Premium",
amount: 72.0,
status: "annule",
date: new Date(2025, 11, 28),
reason: "Erreur de facturation",
},
]);
// Computed property for filtered avoirs
const filteredAvoirs = computed(() => {
if (!activeFilter.value) {
return avoirs.value;
}
return avoirs.value.filter(avoir => avoir.status === activeFilter.value);
});
const handleFilter = (status) => {
activeFilter.value = status;
avoirStore.fetchAvoirs({ status: status || undefined });
};
const openCreateModal = () => {
router.push("/avoirs/new");
@ -98,13 +44,8 @@ const handleView = (id) => {
router.push(`/avoirs/${id}`);
};
const handleFilter = (status) => {
activeFilter.value = status;
};
const handleExport = () => {
// Export filtered avoirs to CSV
const dataToExport = filteredAvoirs.value;
const dataToExport = avoirs.value;
const headers = [
"N° Avoir",
"Date",
@ -118,17 +59,16 @@ const handleExport = () => {
headers.join(","),
...dataToExport.map((avoir) =>
[
avoir.number,
avoir.date.toLocaleDateString("fr-FR"),
avoir.avoir_number,
new Date(avoir.avoir_date).toLocaleDateString("fr-FR"),
getStatusLabel(avoir.status),
avoir.clientName,
avoir.invoiceNumber,
avoir.amount.toFixed(2) + " EUR",
avoir.client?.name || "N/A",
avoir.invoice?.invoice_number || "N/A",
(avoir.total_ttc || 0).toFixed(2) + " EUR",
].join(",")
),
].join("\n");
// Create blob and download
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
const link = document.createElement("a");
const url = URL.createObjectURL(blob);
@ -154,12 +94,20 @@ const getStatusLabel = (status) => {
const handleDelete = async (id) => {
if (confirm("Êtes-vous sûr de vouloir supprimer cet avoir ?")) {
avoirs.value = avoirs.value.filter((a) => a.id !== id);
try {
await avoirStore.deleteAvoir(id);
alert("Avoir supprimé avec succès");
} catch (err) {
alert("Erreur lors de la suppression de l'avoir");
}
}
};
onMounted(() => {
loading.value = false;
onMounted(async () => {
try {
await avoirStore.fetchAvoirs();
} catch (err) {
console.error("Failed to fetch avoirs:", err);
}
});
</script>

View File

@ -98,13 +98,15 @@
</template>
<script setup>
import { ref, defineProps } from "vue";
import { ref, defineProps, onMounted } from "vue";
import { useRouter } from "vue-router";
import CommandeDetailTemplate from "@/components/templates/Commande/CommandeDetailTemplate.vue";
import CommandeHeader from "@/components/molecules/Commande/CommandeHeader.vue";
import CommandeLinesTable from "@/components/molecules/Commande/CommandeLinesTable.vue";
import CommandeSummary from "@/components/molecules/Commande/CommandeSummary.vue";
import SoftButton from "@/components/SoftButton.vue";
import { PurchaseOrderService } from "@/services/purchaseOrder";
import { useNotificationStore } from "@/stores/notification";
const props = defineProps({
commandeId: {
@ -114,51 +116,12 @@ const props = defineProps({
});
const router = useRouter();
const notificationStore = useNotificationStore();
const commande = ref(null);
const loading = ref(true);
const error = ref(null);
const dropdownOpen = ref(false);
// Sample commande data
const sampleCommande = {
id: props.commandeId,
number: "CMD-2026-001",
supplierName: "Produits Funéraires Pro",
supplierAddress: "123 rue de Paris, 75001 Paris",
supplierContact: "contact@pfpro.fr",
status: "confirmee",
date: new Date(2026, 0, 15),
total_ht: 2500.0,
total_tva: 500.0,
total_ttc: 3000.0,
lines: [
{
id: 1,
designation: "Fluide artériel Premium 5L",
quantity: 5,
price_ht: 450.0,
total_ht: 2250.0,
},
{
id: 2,
designation: "Aiguilles de suture serpentine 10,80cm",
quantity: 2,
price_ht: 125.0,
total_ht: 250.0,
},
],
history: [
{
changed_at: new Date(2026, 0, 15),
comment: "Commande créée",
},
{
changed_at: new Date(2026, 0, 15, 10, 30),
comment: "Commande confirmée par le fournisseur",
},
],
};
const availableStatuses = ["brouillon", "confirmee", "livree", "facturee", "annulee"];
const formatDate = (dateString) => {
@ -177,13 +140,66 @@ const getStatusLabel = (status) => {
return labels[status] || status;
};
const changeStatus = (newStatus) => {
commande.value.status = newStatus;
const fetchCommande = async () => {
loading.value = true;
error.value = null;
try {
const response = await PurchaseOrderService.getPurchaseOrder(props.commandeId);
const data = response.data;
// Map backend data to frontend structure
commande.value = {
id: data.id,
number: data.po_number,
status: data.status,
date: data.order_date,
total_ht: data.total_ht,
total_tva: data.total_tva,
total_ttc: data.total_ttc,
notes: data.notes,
deliveryAddress: data.delivery_address,
// Supplier mapping
supplierName: data.fournisseur?.name || "Inconnu",
supplierAddress: data.fournisseur ?
`${data.fournisseur.billing_address_line1 || ''} ${data.fournisseur.billing_city || ''}` :
"Non spécifiée",
supplierContact: data.fournisseur?.email || data.fournisseur?.phone || "Indisponible",
// Lines mapping: translation between backend (description, unit_price) and frontend (designation, price_ht)
lines: (data.lines || []).map(line => ({
id: line.id,
designation: line.description,
quantity: line.quantity,
price_ht: line.unit_price,
total_ht: line.total_ht
}))
};
} catch (err) {
console.error("Error fetching commande:", err);
error.value = "Impossible de charger les détails de la commande.";
notificationStore.error("Erreur", error.value);
} finally {
loading.value = false;
}
};
// Load sample data on mount
setTimeout(() => {
commande.value = sampleCommande;
loading.value = false;
}, 500);
const changeStatus = async (newStatus) => {
try {
const payload = {
id: props.commandeId,
status: newStatus
};
await PurchaseOrderService.updatePurchaseOrder(payload);
commande.value.status = newStatus;
notificationStore.success("Succès", `Statut mis à jour : ${getStatusLabel(newStatus)}`);
} catch (err) {
console.error("Error updating status:", err);
notificationStore.error("Erreur", "Échec de la mise à jour du statut.");
}
};
onMounted(() => {
fetchCommande();
});
</script>

View File

@ -8,7 +8,7 @@
<div class="row">
<div class="col-12">
<commande-table
:data="filteredCommandes"
:data="purchaseOrders"
:loading="loading"
@view="handleView"
@delete="handleDelete"
@ -23,67 +23,19 @@ import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router";
import CommandeListControls from "@/components/molecules/Fournisseur/CommandeListControls.vue";
import CommandeTable from "@/components/molecules/Tables/Fournisseurs/CommandeTable.vue";
import { usePurchaseOrderStore } from "@/stores/purchaseOrderStore";
import { storeToRefs } from "pinia";
const router = useRouter();
const loading = ref(false);
const purchaseOrderStore = usePurchaseOrderStore();
const { purchaseOrders, loading, error } = storeToRefs(purchaseOrderStore);
const activeFilter = ref(null);
// Sample data for commandes
const commandes = ref([
{
id: "1",
number: "CMD-2026-001",
date: new Date(2026, 0, 15),
supplier: "Produits Funéraires Pro",
status: "confirmee",
amount: 2500.0,
items_count: 5,
},
{
id: "2",
number: "CMD-2026-002",
date: new Date(2026, 0, 18),
supplier: "Thanatos Supply",
status: "livree",
amount: 1850.5,
items_count: 3,
},
{
id: "3",
number: "CMD-2026-003",
date: new Date(2026, 0, 20),
supplier: "ISOFROID",
status: "brouillon",
amount: 3200.0,
items_count: 8,
},
{
id: "4",
number: "CMD-2026-004",
date: new Date(2026, 0, 22),
supplier: "EEP Co EUROPE",
status: "confirmee",
amount: 1520.75,
items_count: 4,
},
{
id: "5",
number: "CMD-2026-005",
date: new Date(2025, 11, 28),
supplier: "NEXTECH MEDICAL",
status: "annulee",
amount: 890.0,
items_count: 2,
},
]);
// Computed property for filtered commandes
const filteredCommandes = computed(() => {
if (!activeFilter.value) {
return commandes.value;
}
return commandes.value.filter(cmd => cmd.status === activeFilter.value);
});
const handleFilter = (status) => {
activeFilter.value = status;
// If backend supports filtering, we can call fetchPurchaseOrders({ status })
purchaseOrderStore.fetchPurchaseOrders({ status: status || undefined });
};
const openCreateModal = () => {
router.push("/fournisseurs/commandes/new");
@ -93,19 +45,14 @@ const handleView = (id) => {
router.push(`/fournisseurs/commandes/${id}`);
};
const handleFilter = (status) => {
activeFilter.value = status;
};
const handleExport = () => {
// Export filtered commandes to CSV
const dataToExport = filteredCommandes.value;
const dataToExport = purchaseOrders.value;
const headers = [
"N° Commande",
"Date",
"Fournisseur",
"Statut",
"Montant",
"Montant TTC",
"Articles",
];
@ -113,17 +60,16 @@ const handleExport = () => {
headers.join(","),
...dataToExport.map((cmd) =>
[
cmd.number,
cmd.date.toLocaleDateString("fr-FR"),
cmd.supplier,
cmd.po_number,
new Date(cmd.order_date).toLocaleDateString("fr-FR"),
cmd.fournisseur?.name || "N/A",
getStatusLabel(cmd.status),
cmd.amount.toFixed(2) + " EUR",
cmd.items_count,
(cmd.total_ttc || 0).toFixed(2) + " EUR",
cmd.lines?.length || 0,
].join(",")
),
].join("\n");
// Create blob and download
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
const link = document.createElement("a");
const url = URL.createObjectURL(blob);
@ -150,12 +96,20 @@ const getStatusLabel = (status) => {
const handleDelete = async (id) => {
if (confirm("Êtes-vous sûr de vouloir supprimer cette commande ?")) {
commandes.value = commandes.value.filter((c) => c.id !== id);
try {
await purchaseOrderStore.deletePurchaseOrder(id);
alert("Commande supprimée avec succès");
} catch (err) {
alert("Erreur lors de la suppression de la commande");
}
}
};
onMounted(() => {
loading.value = false;
onMounted(async () => {
try {
await purchaseOrderStore.fetchPurchaseOrders();
} catch (err) {
console.error("Failed to fetch purchase orders:", err);
}
});
</script>

View File

@ -1,27 +1,58 @@
<template>
<form @submit.prevent="submitForm">
<!-- Row 1: N° Commande, Fournisseur, Date -->
<div class="row g-3 mb-4">
<div class="col-md-4">
<label class="form-label">N° Commande</label>
<form @submit.prevent="submitForm" class="purchase-form">
<!-- Header Section -->
<div class="form-section">
<div class="section-title">
<i class="fas fa-file-invoice"></i>
Informations générales
</div>
<!-- Row 1: Fournisseur, Date -->
<div class="row g-3 mb-3">
<div class="col-md-6 position-relative supplier-search-container">
<label class="form-label">Fournisseur <span class="text-danger">*</span></label>
<div class="search-input-wrapper">
<i class="fas fa-search search-icon"></i>
<soft-input
v-model="formData.number"
v-model="supplierSearchQuery"
type="text"
placeholder="Auto-généré"
:disabled="true"
placeholder="Rechercher un fournisseur..."
@input="handleSupplierSearch"
@focus="showSupplierResults = true"
required
class="search-input"
/>
</div>
<div class="col-md-4">
<label class="form-label">Fournisseur *</label>
<select v-model="formData.supplierId" class="form-select" @change="updateSupplierInfo" required>
<option value="">-- Sélectionner un fournisseur --</option>
<option v-for="supplier in suppliers" :key="supplier.id" :value="supplier.id">
{{ supplier.name }}
</option>
</select>
<!-- Search Results Dropdown -->
<div
v-if="showSupplierResults && (supplierSearchResults.length > 0 || isSearchingSuppliers)"
class="search-dropdown"
>
<div v-if="isSearchingSuppliers" class="dropdown-loading">
<div class="spinner-border spinner-border-sm text-primary" role="status">
<span class="visually-hidden">Chargement...</span>
</div>
<div class="col-md-4">
<label class="form-label">Date commande *</label>
</div>
<template v-else>
<button
v-for="supplier in supplierSearchResults"
:key="supplier.id"
type="button"
class="dropdown-item"
@click="selectSupplier(supplier)"
>
<span class="item-name">{{ supplier.name }}</span>
<span class="item-details">
{{ supplier.email || 'Pas d\'email' }} {{ supplier.billing_address?.city || 'Ville non spécifiée' }}
</span>
</button>
</template>
</div>
</div>
<div class="col-md-6">
<label class="form-label">Date commande <span class="text-danger">*</span></label>
<soft-input
v-model="formData.date"
type="date"
@ -30,75 +61,119 @@
</div>
</div>
<!-- Row 2: Statut, Adresse fournisseur -->
<div class="row g-3 mb-4">
<!-- Row 2: Statut, Adresse livraison -->
<div class="row g-3 mb-3">
<div class="col-md-6">
<label class="form-label">Statut</label>
<select v-model="formData.status" class="form-select">
<option value="brouillon">Brouillon</option>
<option value="confirmee">Confirmée</option>
<option value="livree">Livrée</option>
<option value="facturee">Facturée</option>
<option value="annulee">Annulée</option>
<div class="select-wrapper">
<select v-model="formData.status" class="form-select custom-select">
<option value="brouillon">📝 Brouillon</option>
<option value="confirmee"> Confirmée</option>
<option value="livree">🚚 Livrée</option>
<option value="facturee">💳 Facturée</option>
<option value="annulee"> Annulée</option>
</select>
<i class="fas fa-chevron-down select-arrow"></i>
</div>
</div>
<div class="col-md-6">
<label class="form-label">Adresse livraison</label>
<div class="search-input-wrapper">
<i class="fas fa-map-marker-alt search-icon"></i>
<soft-input
v-model="formData.deliveryAddress"
type="text"
placeholder="Adresse de livraison"
class="search-input"
/>
</div>
</div>
</div>
<!-- Notes -->
<div class="mb-4">
<div class="mb-0">
<label class="form-label">Notes de commande</label>
<textarea
v-model="formData.notes"
class="form-control"
class="form-control notes-textarea"
placeholder="Notes importantes..."
rows="2"
></textarea>
</div>
</div>
<!-- Articles Section -->
<div class="mb-4">
<div class="d-flex justify-content-between align-items-center mb-3">
<h6 class="mb-0">Articles</h6>
<div class="form-section">
<div class="section-header">
<div class="section-title">
<i class="fas fa-boxes"></i>
Articles
</div>
<soft-button
type="button"
color="primary"
size="sm"
@click="addLine"
class="add-btn"
>
<i class="fas fa-plus me-1"></i> Ajouter ligne
<i class="fas fa-plus"></i> Ajouter ligne
</soft-button>
</div>
<div class="space-y-3">
<div class="lines-container">
<div
v-for="(line, index) in formData.lines"
:key="index"
class="row g-2 align-items-end bg-light p-3 rounded"
class="line-item"
>
<div class="col-md-4">
<label class="form-label text-xs mb-2">Article *</label>
<select
v-model="line.productId"
class="form-select form-select-sm"
@change="updateProductInfo(index)"
<div class="row g-2 align-items-end">
<div class="col-md-4 position-relative product-search-container">
<label class="form-label text-xs">Article <span class="text-danger">*</span></label>
<div class="search-input-wrapper">
<i class="fas fa-search search-icon"></i>
<soft-input
v-model="line.searchQuery"
type="text"
placeholder="Rechercher un article..."
@input="handleProductSearch(index)"
@focus="activeLineIndex = index; showProductResults = true"
required
>
<option value="">-- Choisir un article --</option>
<option v-for="product in products" :key="product.id" :value="product.id">
{{ product.name }}
</option>
</select>
class="search-input"
/>
</div>
<div class="col-md-2">
<label class="form-label text-xs mb-2">Désignation *</label>
<!-- Product Search Results Dropdown -->
<div
v-show="showProductResults && activeLineIndex === index"
class="search-dropdown product-dropdown"
>
<div v-if="isSearchingProducts" class="dropdown-loading">
<div class="spinner-border spinner-border-sm text-primary" role="status">
<span class="visually-hidden">Chargement...</span>
</div>
</div>
<div v-else-if="productSearchResults.length === 0" class="dropdown-empty">
Aucun produit trouvé
</div>
<template v-else>
<button
v-for="product in productSearchResults"
:key="product.id"
type="button"
class="dropdown-item"
@mousedown.prevent="selectProduct(index, product)"
>
<span class="item-name">{{ product.nom }}</span>
<span class="item-details">
Réf: {{ product.reference }} Stock: {{ product.stock_actuel }} {{ product.unite }} {{ formatCurrency(product.prix_unitaire) }}
</span>
</button>
</template>
</div>
</div>
<div class="col-md-3">
<label class="form-label text-xs">Désignation <span class="text-danger">*</span></label>
<soft-input
v-model="line.designation"
type="text"
@ -106,8 +181,9 @@
required
/>
</div>
<div class="col-md-2">
<label class="form-label text-xs mb-2">Quantité *</label>
<label class="form-label text-xs">Qté <span class="text-danger">*</span></label>
<soft-input
v-model.number="line.quantity"
type="number"
@ -116,8 +192,9 @@
required
/>
</div>
<div class="col-md-2">
<label class="form-label text-xs mb-2">Prix HT *</label>
<label class="form-label text-xs">Prix HT <span class="text-danger">*</span></label>
<soft-input
v-model.number="line.priceHt"
type="number"
@ -126,93 +203,236 @@
required
/>
</div>
<div class="col-md-1 text-end">
<div class="col-md-1 d-flex flex-column align-items-end gap-2">
<button
type="button"
class="btn btn-sm btn-danger"
class="btn-delete"
@click="removeLine(index)"
:disabled="formData.lines.length === 1"
title="Supprimer la ligne"
>
<i class="fas fa-trash"></i>
<i class="fas fa-trash-alt"></i>
</button>
</div>
<div class="col-md-1 text-end">
<span class="text-sm font-weight-bold">
<span class="line-total">
{{ formatCurrency(line.quantity * line.priceHt) }}
</span>
</div>
</div>
</div>
</div>
</div>
<!-- Totaux -->
<div class="row mb-4">
<div class="col-12">
<div class="alert alert-info">
<div class="row text-end">
<div class="col-12">
<p class="mb-2">
<strong>Total HT :</strong>
<span>{{ formatCurrency(calculateTotalHt()) }}</span>
</p>
<p class="mb-2">
<strong>TVA (20%) :</strong>
<span>{{ formatCurrency(calculateTotalTva()) }}</span>
</p>
<h5 class="mb-0 text-info">
<strong>Total TTC : {{ formatCurrency(calculateTotalTtc()) }}</strong>
</h5>
<!-- Totals Section - Clean Design -->
<div class="totals-section">
<div class="totals-content">
<div class="total-row">
<span class="total-label">Total HT</span>
<span class="total-value">{{ formatCurrency(calculateTotalHt()) }}</span>
</div>
<div class="total-row">
<span class="total-label">TVA (20%)</span>
<span class="total-value">{{ formatCurrency(calculateTotalTva()) }}</span>
</div>
<div class="total-row total-final">
<span class="total-label">Total TTC</span>
<span class="total-amount">{{ formatCurrency(calculateTotalTtc()) }}</span>
</div>
</div>
</div>
<!-- Boutons d'action -->
<div class="d-flex justify-content-end gap-3">
<!-- Action Buttons -->
<div class="action-buttons">
<soft-button
type="button"
color="secondary"
variant="outline"
@click="cancelForm"
class="btn-cancel"
>
Annuler
<i class="fas fa-times"></i> Annuler
</soft-button>
<soft-button
type="submit"
color="success"
class="btn-submit"
>
Créer la commande
<i class="fas fa-check"></i> Créer la commande
</soft-button>
</div>
</form>
</template>
<script setup>
import { ref, defineEmits } from "vue";
import { ref, defineEmits, onMounted, onUnmounted } from "vue";
import SoftInput from "@/components/SoftInput.vue";
import SoftButton from "@/components/SoftButton.vue";
import { FournisseurService } from "@/services/fournisseur";
import ProductService from "@/services/product";
import { PurchaseOrderService } from "@/services/purchaseOrder";
import { useNotificationStore } from "@/stores/notification";
const productService = new ProductService();
const notificationStore = useNotificationStore();
const emit = defineEmits(["submit"]);
const suppliers = [
{ id: "1", name: "Produits Funéraires Pro" },
{ id: "2", name: "Thanatos Supply" },
{ id: "3", name: "ISOFROID" },
{ id: "4", name: "EEP Co EUROPE" },
{ id: "5", name: "NEXTECH MEDICAL" },
{ id: "6", name: "ACTION" },
{ id: "7", name: "E.LECLERC" },
];
// Supplier Search States
const supplierSearchQuery = ref("");
const supplierSearchResults = ref([]);
const isSearchingSuppliers = ref(false);
const showSupplierResults = ref(false);
let searchTimeout = null;
const products = [
{ id: "1", name: "Fluide artériel Premium 5L", price: 450.0 },
{ id: "2", name: "Aiguilles de suture serpentine 10,80cm", price: 125.0 },
{ id: "3", name: "Trocar professionnel", price: 85.0 },
{ id: "4", name: "Pince à dissection 250mm", price: 65.0 },
{ id: "5", name: "Crème visage reconstructive", price: 32.0 },
{ id: "6", name: "Fluide cavité 2L", price: 210.0 },
];
const handleSupplierSearch = () => {
if (supplierSearchQuery.value.length < 3) {
supplierSearchResults.value = [];
if (searchTimeout) clearTimeout(searchTimeout);
isSearchingSuppliers.value = false;
return;
}
if (searchTimeout) clearTimeout(searchTimeout);
searchTimeout = setTimeout(async () => {
// Check if the query is still the same before starting
if (supplierSearchQuery.value.trim() === "") return;
isSearchingSuppliers.value = true;
showSupplierResults.value = true;
try {
const results = await FournisseurService.searchFournisseurs(supplierSearchQuery.value);
// Handle both direct array or paginated object with data property
let actualResults = [];
if (Array.isArray(results)) {
actualResults = results;
} else if (results && Array.isArray(results.data)) {
actualResults = results.data;
}
supplierSearchResults.value = actualResults.filter(s => s && s.id);
} catch (error) {
console.error("Error searching suppliers:", error);
} finally {
isSearchingSuppliers.value = false;
}
}, 300);
};
const selectSupplier = (supplier) => {
if (!supplier || !supplier.id) return;
if (searchTimeout) clearTimeout(searchTimeout);
formData.value.supplierId = supplier.id;
formData.value.supplierName = supplier.name;
formData.value.supplierAddress = supplier.billing_address ?
`${supplier.billing_address.line1 || ''} ${supplier.billing_address.postal_code || ''} ${supplier.billing_address.city || ''}` :
"À déterminer";
supplierSearchQuery.value = supplier.name;
showSupplierResults.value = false;
};
// Product Search States
const productSearchResults = ref([]);
const isSearchingProducts = ref(false);
const showProductResults = ref(false);
const activeLineIndex = ref(null);
let productSearchTimeout = null;
const handleProductSearch = (index) => {
activeLineIndex.value = index;
const query = formData.value.lines[index].searchQuery;
console.log(query.length);
if (query.length < 2) {
productSearchResults.value = [];
if (productSearchTimeout) clearTimeout(productSearchTimeout);
isSearchingProducts.value = false;
return;
}
if (productSearchTimeout) clearTimeout(productSearchTimeout);
productSearchTimeout = setTimeout(async () => {
// Check if the query is still the same before starting
if (formData.value.lines[index].searchQuery !== query) return;
isSearchingProducts.value = true;
showProductResults.value = true;
try {
const response = await productService.searchProducts(query);
// Double check if this is still the active line and query, and line still exists
if (activeLineIndex.value === index &&
formData.value.lines[index] &&
formData.value.lines[index].searchQuery === query) {
// Handle paginated response: the array is in response.data.data
// Handle non-paginated: the array is in response.data
let results = [];
if (response && response.data) {
if (Array.isArray(response.data)) {
results = response.data;
} else if (response.data.data && Array.isArray(response.data.data)) {
results = response.data.data;
}
}
productSearchResults.value = results.filter(p => p && p.id);
}
} catch (error) {
console.error("Error searching products:", error);
} finally {
// Only set to false if this was the last triggered search
if (activeLineIndex.value === index) {
isSearchingProducts.value = false;
}
}
}, 300);
};
const selectProduct = (index, product) => {
if (!product || !product.id) return;
if (productSearchTimeout) clearTimeout(productSearchTimeout);
const line = formData.value.lines[index];
if (!line) return;
line.productId = product.id;
line.searchQuery = product.nom;
line.designation = product.nom;
line.priceHt = product.prix_unitaire;
showProductResults.value = false;
activeLineIndex.value = null;
};
// Close dropdowns on click outside
const handleClickOutside = (event) => {
const supplierContainer = document.querySelector('.supplier-search-container');
if (supplierContainer && !supplierContainer.contains(event.target)) {
showSupplierResults.value = false;
}
const productContainers = document.querySelectorAll('.product-search-container');
let clickedInsideAnyProduct = false;
productContainers.forEach(container => {
if (container.contains(event.target)) {
clickedInsideAnyProduct = true;
}
});
if (!clickedInsideAnyProduct) {
showProductResults.value = false;
}
};
onMounted(() => {
document.addEventListener('click', handleClickOutside);
});
onUnmounted(() => {
document.removeEventListener('click', handleClickOutside);
});
const formData = ref({
number: "CMD-" + Date.now(),
@ -226,6 +446,7 @@ const formData = ref({
lines: [
{
productId: "",
searchQuery: "",
designation: "",
quantity: 1,
priceHt: 0,
@ -233,32 +454,16 @@ const formData = ref({
],
});
const updateSupplierInfo = () => {
const supplier = suppliers.find(s => s.id === formData.value.supplierId);
if (supplier) {
formData.value.supplierName = supplier.name;
formData.value.supplierAddress = "À déterminer";
}
};
const updateProductInfo = (index) => {
const product = products.find(p => p.id === formData.value.lines[index].productId);
if (product) {
formData.value.lines[index].designation = product.name;
formData.value.lines[index].priceHt = product.price;
}
};
const formatCurrency = (value) => {
return new Intl.NumberFormat("fr-FR", {
style: "currency",
currency: "EUR",
}).format(value);
}).format(value || 0);
};
const calculateTotalHt = () => {
return formData.value.lines.reduce((sum, line) => {
return sum + line.quantity * line.priceHt;
return sum + (line.quantity || 0) * (line.priceHt || 0);
}, 0);
};
@ -273,6 +478,7 @@ const calculateTotalTtc = () => {
const addLine = () => {
formData.value.lines.push({
productId: "",
searchQuery: "",
designation: "",
quantity: 1,
priceHt: 0,
@ -285,12 +491,45 @@ const removeLine = (index) => {
}
};
const submitForm = () => {
const submitForm = async () => {
if (!formData.value.supplierId) {
alert("Veuillez sélectionner un fournisseur");
notificationStore.error("Champ requis", "Veuillez sélectionner un fournisseur.");
return;
}
emit("submit", formData.value);
try {
const payload = {
fournisseur_id: formData.value.supplierId,
po_number: formData.value.number,
order_date: formData.value.date,
status: formData.value.status,
delivery_address: formData.value.deliveryAddress,
notes: formData.value.notes,
total_ht: calculateTotalHt(),
total_tva: calculateTotalTva(),
total_ttc: calculateTotalTtc(),
lines: formData.value.lines.map(line => ({
product_id: line.productId || null,
description: line.designation,
quantity: line.quantity,
unit_price: line.priceHt,
tva_rate: 20, // Default 20%
total_ht: line.quantity * line.priceHt
}))
};
console.log("Submitting purchase order:", payload);
const response = await PurchaseOrderService.createPurchaseOrder(payload);
console.log("Purchase order created:", response);
emit("submit", response.data);
notificationStore.success("Succès", "Commande créée avec succès !");
} catch (error) {
console.error("Error creating purchase order:", error);
const message = error.response?.data?.message || "Une erreur est survenue lors de la création de la commande.";
notificationStore.error("Erreur", message);
}
};
const cancelForm = () => {
@ -299,17 +538,349 @@ const cancelForm = () => {
</script>
<style scoped>
.space-y-3 > div + div {
margin-top: 0.75rem;
.purchase-form {
max-width: 1200px;
margin: 0 auto;
}
/* Form Sections */
.form-section {
background: #fff;
border-radius: 12px;
padding: 1.5rem;
margin-bottom: 1.5rem;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
border: 1px solid #e9ecef;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
}
.section-title {
font-size: 1rem;
font-weight: 600;
color: #2c3e50;
display: flex;
align-items: center;
gap: 0.5rem;
}
.section-title i {
color: #6c757d;
font-size: 0.9rem;
}
/* Form Labels */
.form-label {
font-size: 0.875rem;
font-weight: 500;
color: #495057;
margin-bottom: 0.5rem;
}
.text-xs {
.form-label.text-xs {
font-size: 0.8rem;
}
/* Search Input with Icon */
.search-input-wrapper {
position: relative;
display: flex;
align-items: center;
}
.search-icon {
position: absolute;
left: 12px;
color: #6c757d;
font-size: 0.9rem;
z-index: 10;
pointer-events: none;
}
.search-input :deep(input) {
padding-left: 2.5rem !important;
}
/* Custom Select */
.select-wrapper {
position: relative;
}
.custom-select {
appearance: none;
padding-right: 2.5rem;
cursor: pointer;
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 0.5rem 1rem;
font-size: 0.875rem;
background: #fff;
transition: border-color 0.2s, box-shadow 0.2s;
}
.custom-select:focus {
border-color: #86b7fe;
box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.15);
outline: none;
}
.select-arrow {
position: absolute;
right: 12px;
top: 50%;
transform: translateY(-50%);
color: #6c757d;
font-size: 0.75rem;
pointer-events: none;
}
/* Search Dropdown */
.search-dropdown {
position: absolute;
top: 100%;
left: 0;
right: 0;
background: #fff;
border: 1px solid #dee2e6;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
max-height: 250px;
overflow-y: auto;
z-index: 9999;
margin-top: 4px;
}
.product-dropdown {
z-index: 10000;
}
.dropdown-item {
display: flex;
flex-direction: column;
padding: 0.75rem 1rem;
border-bottom: 1px solid #f1f3f5;
background: none;
border-left: none;
border-right: none;
border-top: none;
width: 100%;
text-align: left;
cursor: pointer;
transition: background-color 0.15s;
}
.dropdown-item:last-child {
border-bottom: none;
}
.dropdown-item:hover {
background-color: #f8f9fa;
}
.item-name {
font-weight: 600;
color: #212529;
font-size: 0.9rem;
}
.item-details {
font-size: 0.75rem;
color: #6c757d;
margin-top: 2px;
}
.dropdown-loading {
padding: 1rem;
text-align: center;
}
.dropdown-empty {
padding: 1rem;
text-align: center;
color: #6c757d;
font-style: italic;
font-size: 0.875rem;
}
/* Notes Textarea */
.notes-textarea {
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 0.75rem 1rem;
font-size: 0.875rem;
resize: vertical;
transition: border-color 0.2s, box-shadow 0.2s;
}
.notes-textarea:focus {
border-color: #86b7fe;
box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.15);
outline: none;
}
/* Lines Container */
.lines-container {
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.line-item {
background: #f8f9fa;
border-radius: 10px;
padding: 1rem;
border: 1px solid #e9ecef;
transition: box-shadow 0.2s, border-color 0.2s;
}
.line-item:hover {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
border-color: #dee2e6;
}
/* Delete Button */
.btn-delete {
width: 32px;
height: 32px;
border-radius: 6px;
border: none;
background: #dc3545;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
transition: background-color 0.2s, transform 0.1s;
}
.btn-delete:hover:not(:disabled) {
background: #c82333;
transform: scale(1.05);
}
.btn-delete:disabled {
background: #e9ecef;
color: #adb5bd;
cursor: not-allowed;
}
.line-total {
font-weight: 600;
color: #28a745;
font-size: 0.85rem;
white-space: nowrap;
}
/* Add Button */
.add-btn {
display: flex;
align-items: center;
gap: 0.4rem;
padding: 0.4rem 0.875rem;
font-size: 0.85rem;
}
/* Totals Section - Clean Design */
.totals-section {
background: #fff;
border-radius: 12px;
padding: 1.5rem;
margin-bottom: 1.5rem;
border: 1px solid #e9ecef;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
.totals-content {
max-width: 350px;
margin-left: auto;
}
.total-row {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem 0;
border-bottom: 1px solid #e9ecef;
}
.total-row:last-child {
border-bottom: none;
}
.total-label {
font-size: 0.9rem;
color: #6c757d;
}
.total-value {
font-size: 0.95rem;
font-weight: 500;
color: #495057;
}
.total-final {
padding-top: 0.75rem;
margin-top: 0.5rem;
}
.total-final .total-label {
font-size: 1rem;
font-weight: 600;
color: #212529;
}
.total-amount {
font-size: 1.35rem;
font-weight: 700;
color: #212529;
}
/* Action Buttons */
.action-buttons {
display: flex;
justify-content: flex-end;
gap: 0.75rem;
padding-top: 0.5rem;
}
.btn-cancel,
.btn-submit {
display: flex;
align-items: center;
gap: 0.5rem;
padding: 0.625rem 1.25rem;
font-size: 0.9rem;
}
/* Responsive */
@media (max-width: 768px) {
.form-section {
padding: 1rem;
}
.section-header {
flex-direction: column;
align-items: flex-start;
gap: 0.75rem;
}
.totals-content {
max-width: 100%;
}
.action-buttons {
flex-direction: column-reverse;
}
.btn-cancel,
.btn-submit {
width: 100%;
justify-content: center;
}
}
</style>

View File

@ -20,7 +20,7 @@
<div class="d-flex align-items-center">
<soft-checkbox class="me-2" />
<p class="text-xs font-weight-bold ms-2 mb-0">
{{ avoir.number }}
{{ avoir.avoir_number || avoir.number }}
</p>
</div>
</td>
@ -28,7 +28,7 @@
<!-- Date -->
<td class="font-weight-bold">
<span class="my-2 text-xs">{{
formatDate(avoir.date)
formatDate(avoir.avoir_date || avoir.date)
}}</span>
</td>
@ -60,7 +60,7 @@
circular
/>
<span>{{
avoir.clientName || "Client Inconnu"
avoir.client?.name || avoir.clientName || "Client Inconnu"
}}</span>
</div>
</td>
@ -68,14 +68,14 @@
<!-- Invoice Reference -->
<td class="text-xs font-weight-bold">
<span class="my-2 text-xs">
{{ avoir.invoiceNumber }}
{{ avoir.invoice?.invoice_number || avoir.invoiceNumber }}
</span>
</td>
<!-- Amount (Total) -->
<td class="text-xs font-weight-bold">
<span class="my-2 text-xs">{{
formatCurrency(avoir.amount)
formatCurrency(avoir.total_ttc || avoir.amount)
}}</span>
</td>

View File

@ -20,7 +20,7 @@
<div class="d-flex align-items-center">
<soft-checkbox class="me-2" />
<p class="text-xs font-weight-bold ms-2 mb-0">
{{ commande.number }}
{{ commande.po_number || commande.number }}
</p>
</div>
</td>
@ -28,7 +28,7 @@
<!-- Date -->
<td class="font-weight-bold">
<span class="my-2 text-xs">{{
formatDate(commande.date)
formatDate(commande.order_date || commande.date)
}}</span>
</td>
@ -42,7 +42,7 @@
alt="supplier image"
circular
/>
<span>{{ commande.supplier }}</span>
<span>{{ commande.fournisseur?.name || commande.supplier }}</span>
</div>
</td>
@ -66,13 +66,13 @@
<!-- Amount -->
<td class="text-xs font-weight-bold">
<span class="my-2 text-xs">{{
formatCurrency(commande.amount)
formatCurrency(commande.total_ttc || commande.amount)
}}</span>
</td>
<!-- Items Count -->
<td class="text-xs font-weight-bold">
<span class="badge bg-secondary">{{ commande.items_count }}</span>
<span class="badge bg-secondary">{{ commande.lines?.length || commande.items_count || 0 }}</span>
</td>
<!-- Actions -->