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\QuoteLineRepositoryInterface::class, \App\Repositories\QuoteLineRepository::class);
$this->app->bind(\App\Repositories\ClientActivityTimelineRepositoryInterface::class, \App\Repositories\ClientActivityTimelineRepository::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(DeceasedDocumentRepositoryInterface::class, DeceasedDocumentRepository::class);
$this->app->bind(InterventionRepositoryInterface::class, InterventionRepository::class); $this->app->bind(InterventionRepositoryInterface::class, InterventionRepository::class);
$this->app->bind(FileRepositoryInterface::class, FileRepository::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\FileAttachmentController;
use App\Http\Controllers\Api\QuoteController; use App\Http\Controllers\Api\QuoteController;
use App\Http\Controllers\Api\ClientActivityTimelineController; use App\Http\Controllers\Api\ClientActivityTimelineController;
use App\Http\Controllers\Api\PurchaseOrderController;
/* /*
@ -85,6 +86,7 @@ Route::middleware('auth:sanctum')->group(function () {
// Fournisseur management // Fournisseur management
Route::get('/fournisseurs/searchBy', [FournisseurController::class, 'searchBy']); Route::get('/fournisseurs/searchBy', [FournisseurController::class, 'searchBy']);
Route::apiResource('purchase-orders', PurchaseOrderController::class);
Route::apiResource('fournisseurs', FournisseurController::class); Route::apiResource('fournisseurs', FournisseurController::class);
Route::get('fournisseurs/{fournisseurId}/contacts', [ContactController::class, 'getContactsByFournisseur']); Route::get('fournisseurs/{fournisseurId}/contacts', [ContactController::class, 'getContactsByFournisseur']);

View File

@ -8,7 +8,7 @@
<div class="row"> <div class="row">
<div class="col-12"> <div class="col-12">
<avoir-table <avoir-table
:data="filteredAvoirs" :data="avoirs"
:loading="loading" :loading="loading"
@view="handleView" @view="handleView"
@delete="handleDelete" @delete="handleDelete"
@ -23,72 +23,18 @@ import { ref, onMounted, computed } from "vue";
import { useRouter } from "vue-router"; import { useRouter } from "vue-router";
import AvoirListControls from "@/components/molecules/Avoir/AvoirListControls.vue"; import AvoirListControls from "@/components/molecules/Avoir/AvoirListControls.vue";
import AvoirTable from "@/components/molecules/Tables/Avoirs/AvoirTable.vue"; import AvoirTable from "@/components/molecules/Tables/Avoirs/AvoirTable.vue";
import { useAvoirStore } from "@/stores/avoirStore";
import { storeToRefs } from "pinia";
const router = useRouter(); const router = useRouter();
const loading = ref(false); const avoirStore = useAvoirStore();
const { avoirs, loading, error } = storeToRefs(avoirStore);
const activeFilter = ref(null); const activeFilter = ref(null);
// Sample data for avoirs const handleFilter = (status) => {
const avoirs = ref([ activeFilter.value = status;
{ avoirStore.fetchAvoirs({ status: status || undefined });
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 openCreateModal = () => { const openCreateModal = () => {
router.push("/avoirs/new"); router.push("/avoirs/new");
@ -98,13 +44,8 @@ const handleView = (id) => {
router.push(`/avoirs/${id}`); router.push(`/avoirs/${id}`);
}; };
const handleFilter = (status) => {
activeFilter.value = status;
};
const handleExport = () => { const handleExport = () => {
// Export filtered avoirs to CSV const dataToExport = avoirs.value;
const dataToExport = filteredAvoirs.value;
const headers = [ const headers = [
"N° Avoir", "N° Avoir",
"Date", "Date",
@ -118,17 +59,16 @@ const handleExport = () => {
headers.join(","), headers.join(","),
...dataToExport.map((avoir) => ...dataToExport.map((avoir) =>
[ [
avoir.number, avoir.avoir_number,
avoir.date.toLocaleDateString("fr-FR"), new Date(avoir.avoir_date).toLocaleDateString("fr-FR"),
getStatusLabel(avoir.status), getStatusLabel(avoir.status),
avoir.clientName, avoir.client?.name || "N/A",
avoir.invoiceNumber, avoir.invoice?.invoice_number || "N/A",
avoir.amount.toFixed(2) + " EUR", (avoir.total_ttc || 0).toFixed(2) + " EUR",
].join(",") ].join(",")
), ),
].join("\n"); ].join("\n");
// Create blob and download
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" }); const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
const link = document.createElement("a"); const link = document.createElement("a");
const url = URL.createObjectURL(blob); const url = URL.createObjectURL(blob);
@ -154,12 +94,20 @@ const getStatusLabel = (status) => {
const handleDelete = async (id) => { const handleDelete = async (id) => {
if (confirm("Êtes-vous sûr de vouloir supprimer cet avoir ?")) { 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"); alert("Avoir supprimé avec succès");
} catch (err) {
alert("Erreur lors de la suppression de l'avoir");
}
} }
}; };
onMounted(() => { onMounted(async () => {
loading.value = false; try {
await avoirStore.fetchAvoirs();
} catch (err) {
console.error("Failed to fetch avoirs:", err);
}
}); });
</script> </script>

View File

@ -98,13 +98,15 @@
</template> </template>
<script setup> <script setup>
import { ref, defineProps } from "vue"; import { ref, defineProps, onMounted } from "vue";
import { useRouter } from "vue-router"; import { useRouter } from "vue-router";
import CommandeDetailTemplate from "@/components/templates/Commande/CommandeDetailTemplate.vue"; import CommandeDetailTemplate from "@/components/templates/Commande/CommandeDetailTemplate.vue";
import CommandeHeader from "@/components/molecules/Commande/CommandeHeader.vue"; import CommandeHeader from "@/components/molecules/Commande/CommandeHeader.vue";
import CommandeLinesTable from "@/components/molecules/Commande/CommandeLinesTable.vue"; import CommandeLinesTable from "@/components/molecules/Commande/CommandeLinesTable.vue";
import CommandeSummary from "@/components/molecules/Commande/CommandeSummary.vue"; import CommandeSummary from "@/components/molecules/Commande/CommandeSummary.vue";
import SoftButton from "@/components/SoftButton.vue"; import SoftButton from "@/components/SoftButton.vue";
import { PurchaseOrderService } from "@/services/purchaseOrder";
import { useNotificationStore } from "@/stores/notification";
const props = defineProps({ const props = defineProps({
commandeId: { commandeId: {
@ -114,51 +116,12 @@ const props = defineProps({
}); });
const router = useRouter(); const router = useRouter();
const notificationStore = useNotificationStore();
const commande = ref(null); const commande = ref(null);
const loading = ref(true); const loading = ref(true);
const error = ref(null); const error = ref(null);
const dropdownOpen = ref(false); 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 availableStatuses = ["brouillon", "confirmee", "livree", "facturee", "annulee"];
const formatDate = (dateString) => { const formatDate = (dateString) => {
@ -177,13 +140,66 @@ const getStatusLabel = (status) => {
return labels[status] || status; return labels[status] || status;
}; };
const changeStatus = (newStatus) => { const fetchCommande = async () => {
commande.value.status = newStatus; 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 const changeStatus = async (newStatus) => {
setTimeout(() => { try {
commande.value = sampleCommande; const payload = {
loading.value = false; id: props.commandeId,
}, 500); 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> </script>

View File

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

View File

@ -1,27 +1,58 @@
<template> <template>
<form @submit.prevent="submitForm"> <form @submit.prevent="submitForm" class="purchase-form">
<!-- Row 1: N° Commande, Fournisseur, Date --> <!-- Header Section -->
<div class="row g-3 mb-4"> <div class="form-section">
<div class="col-md-4"> <div class="section-title">
<label class="form-label">N° Commande</label> <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 <soft-input
v-model="formData.number" v-model="supplierSearchQuery"
type="text" type="text"
placeholder="Auto-généré" placeholder="Rechercher un fournisseur..."
:disabled="true" @input="handleSupplierSearch"
@focus="showSupplierResults = true"
required
class="search-input"
/> />
</div> </div>
<div class="col-md-4">
<label class="form-label">Fournisseur *</label> <!-- Search Results Dropdown -->
<select v-model="formData.supplierId" class="form-select" @change="updateSupplierInfo" required> <div
<option value="">-- Sélectionner un fournisseur --</option> v-if="showSupplierResults && (supplierSearchResults.length > 0 || isSearchingSuppliers)"
<option v-for="supplier in suppliers" :key="supplier.id" :value="supplier.id"> class="search-dropdown"
{{ supplier.name }} >
</option> <div v-if="isSearchingSuppliers" class="dropdown-loading">
</select> <div class="spinner-border spinner-border-sm text-primary" role="status">
<span class="visually-hidden">Chargement...</span>
</div> </div>
<div class="col-md-4"> </div>
<label class="form-label">Date commande *</label> <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 <soft-input
v-model="formData.date" v-model="formData.date"
type="date" type="date"
@ -30,75 +61,119 @@
</div> </div>
</div> </div>
<!-- Row 2: Statut, Adresse fournisseur --> <!-- Row 2: Statut, Adresse livraison -->
<div class="row g-3 mb-4"> <div class="row g-3 mb-3">
<div class="col-md-6"> <div class="col-md-6">
<label class="form-label">Statut</label> <label class="form-label">Statut</label>
<select v-model="formData.status" class="form-select"> <div class="select-wrapper">
<option value="brouillon">Brouillon</option> <select v-model="formData.status" class="form-select custom-select">
<option value="confirmee">Confirmée</option> <option value="brouillon">📝 Brouillon</option>
<option value="livree">Livrée</option> <option value="confirmee"> Confirmée</option>
<option value="facturee">Facturée</option> <option value="livree">🚚 Livrée</option>
<option value="annulee">Annulée</option> <option value="facturee">💳 Facturée</option>
<option value="annulee"> Annulée</option>
</select> </select>
<i class="fas fa-chevron-down select-arrow"></i>
</div>
</div> </div>
<div class="col-md-6"> <div class="col-md-6">
<label class="form-label">Adresse livraison</label> <label class="form-label">Adresse livraison</label>
<div class="search-input-wrapper">
<i class="fas fa-map-marker-alt search-icon"></i>
<soft-input <soft-input
v-model="formData.deliveryAddress" v-model="formData.deliveryAddress"
type="text" type="text"
placeholder="Adresse de livraison" placeholder="Adresse de livraison"
class="search-input"
/> />
</div> </div>
</div> </div>
</div>
<!-- Notes --> <!-- Notes -->
<div class="mb-4"> <div class="mb-0">
<label class="form-label">Notes de commande</label> <label class="form-label">Notes de commande</label>
<textarea <textarea
v-model="formData.notes" v-model="formData.notes"
class="form-control" class="form-control notes-textarea"
placeholder="Notes importantes..." placeholder="Notes importantes..."
rows="2" rows="2"
></textarea> ></textarea>
</div> </div>
</div>
<!-- Articles Section --> <!-- Articles Section -->
<div class="mb-4"> <div class="form-section">
<div class="d-flex justify-content-between align-items-center mb-3"> <div class="section-header">
<h6 class="mb-0">Articles</h6> <div class="section-title">
<i class="fas fa-boxes"></i>
Articles
</div>
<soft-button <soft-button
type="button" type="button"
color="primary" color="primary"
size="sm" size="sm"
@click="addLine" @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> </soft-button>
</div> </div>
<div class="space-y-3"> <div class="lines-container">
<div <div
v-for="(line, index) in formData.lines" v-for="(line, index) in formData.lines"
:key="index" :key="index"
class="row g-2 align-items-end bg-light p-3 rounded" class="line-item"
> >
<div class="col-md-4"> <div class="row g-2 align-items-end">
<label class="form-label text-xs mb-2">Article *</label> <div class="col-md-4 position-relative product-search-container">
<select <label class="form-label text-xs">Article <span class="text-danger">*</span></label>
v-model="line.productId" <div class="search-input-wrapper">
class="form-select form-select-sm" <i class="fas fa-search search-icon"></i>
@change="updateProductInfo(index)" <soft-input
v-model="line.searchQuery"
type="text"
placeholder="Rechercher un article..."
@input="handleProductSearch(index)"
@focus="activeLineIndex = index; showProductResults = true"
required required
> class="search-input"
<option value="">-- Choisir un article --</option> />
<option v-for="product in products" :key="product.id" :value="product.id">
{{ product.name }}
</option>
</select>
</div> </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 <soft-input
v-model="line.designation" v-model="line.designation"
type="text" type="text"
@ -106,8 +181,9 @@
required required
/> />
</div> </div>
<div class="col-md-2"> <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 <soft-input
v-model.number="line.quantity" v-model.number="line.quantity"
type="number" type="number"
@ -116,8 +192,9 @@
required required
/> />
</div> </div>
<div class="col-md-2"> <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 <soft-input
v-model.number="line.priceHt" v-model.number="line.priceHt"
type="number" type="number"
@ -126,93 +203,236 @@
required required
/> />
</div> </div>
<div class="col-md-1 text-end">
<div class="col-md-1 d-flex flex-column align-items-end gap-2">
<button <button
type="button" type="button"
class="btn btn-sm btn-danger" class="btn-delete"
@click="removeLine(index)" @click="removeLine(index)"
:disabled="formData.lines.length === 1" :disabled="formData.lines.length === 1"
title="Supprimer la ligne"
> >
<i class="fas fa-trash"></i> <i class="fas fa-trash-alt"></i>
</button> </button>
</div> <span class="line-total">
<div class="col-md-1 text-end">
<span class="text-sm font-weight-bold">
{{ formatCurrency(line.quantity * line.priceHt) }} {{ formatCurrency(line.quantity * line.priceHt) }}
</span> </span>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
</div>
<!-- Totaux --> <!-- Totals Section - Clean Design -->
<div class="row mb-4"> <div class="totals-section">
<div class="col-12"> <div class="totals-content">
<div class="alert alert-info"> <div class="total-row">
<div class="row text-end"> <span class="total-label">Total HT</span>
<div class="col-12"> <span class="total-value">{{ formatCurrency(calculateTotalHt()) }}</span>
<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>
</div> </div>
<div class="total-row">
<span class="total-label">TVA (20%)</span>
<span class="total-value">{{ formatCurrency(calculateTotalTva()) }}</span>
</div> </div>
<div class="total-row total-final">
<span class="total-label">Total TTC</span>
<span class="total-amount">{{ formatCurrency(calculateTotalTtc()) }}</span>
</div> </div>
</div> </div>
</div> </div>
<!-- Boutons d'action --> <!-- Action Buttons -->
<div class="d-flex justify-content-end gap-3"> <div class="action-buttons">
<soft-button <soft-button
type="button" type="button"
color="secondary" color="secondary"
variant="outline" variant="outline"
@click="cancelForm" @click="cancelForm"
class="btn-cancel"
> >
Annuler <i class="fas fa-times"></i> Annuler
</soft-button> </soft-button>
<soft-button <soft-button
type="submit" type="submit"
color="success" color="success"
class="btn-submit"
> >
Créer la commande <i class="fas fa-check"></i> Créer la commande
</soft-button> </soft-button>
</div> </div>
</form> </form>
</template> </template>
<script setup> <script setup>
import { ref, defineEmits } from "vue"; import { ref, defineEmits, onMounted, onUnmounted } from "vue";
import SoftInput from "@/components/SoftInput.vue"; import SoftInput from "@/components/SoftInput.vue";
import SoftButton from "@/components/SoftButton.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 emit = defineEmits(["submit"]);
const suppliers = [ // Supplier Search States
{ id: "1", name: "Produits Funéraires Pro" }, const supplierSearchQuery = ref("");
{ id: "2", name: "Thanatos Supply" }, const supplierSearchResults = ref([]);
{ id: "3", name: "ISOFROID" }, const isSearchingSuppliers = ref(false);
{ id: "4", name: "EEP Co EUROPE" }, const showSupplierResults = ref(false);
{ id: "5", name: "NEXTECH MEDICAL" }, let searchTimeout = null;
{ id: "6", name: "ACTION" },
{ id: "7", name: "E.LECLERC" },
];
const products = [ const handleSupplierSearch = () => {
{ id: "1", name: "Fluide artériel Premium 5L", price: 450.0 }, if (supplierSearchQuery.value.length < 3) {
{ id: "2", name: "Aiguilles de suture serpentine 10,80cm", price: 125.0 }, supplierSearchResults.value = [];
{ id: "3", name: "Trocar professionnel", price: 85.0 }, if (searchTimeout) clearTimeout(searchTimeout);
{ id: "4", name: "Pince à dissection 250mm", price: 65.0 }, isSearchingSuppliers.value = false;
{ id: "5", name: "Crème visage reconstructive", price: 32.0 }, return;
{ id: "6", name: "Fluide cavité 2L", price: 210.0 }, }
];
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({ const formData = ref({
number: "CMD-" + Date.now(), number: "CMD-" + Date.now(),
@ -226,6 +446,7 @@ const formData = ref({
lines: [ lines: [
{ {
productId: "", productId: "",
searchQuery: "",
designation: "", designation: "",
quantity: 1, quantity: 1,
priceHt: 0, 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) => { const formatCurrency = (value) => {
return new Intl.NumberFormat("fr-FR", { return new Intl.NumberFormat("fr-FR", {
style: "currency", style: "currency",
currency: "EUR", currency: "EUR",
}).format(value); }).format(value || 0);
}; };
const calculateTotalHt = () => { const calculateTotalHt = () => {
return formData.value.lines.reduce((sum, line) => { return formData.value.lines.reduce((sum, line) => {
return sum + line.quantity * line.priceHt; return sum + (line.quantity || 0) * (line.priceHt || 0);
}, 0); }, 0);
}; };
@ -273,6 +478,7 @@ const calculateTotalTtc = () => {
const addLine = () => { const addLine = () => {
formData.value.lines.push({ formData.value.lines.push({
productId: "", productId: "",
searchQuery: "",
designation: "", designation: "",
quantity: 1, quantity: 1,
priceHt: 0, priceHt: 0,
@ -285,12 +491,45 @@ const removeLine = (index) => {
} }
}; };
const submitForm = () => { const submitForm = async () => {
if (!formData.value.supplierId) { if (!formData.value.supplierId) {
alert("Veuillez sélectionner un fournisseur"); notificationStore.error("Champ requis", "Veuillez sélectionner un fournisseur.");
return; 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 = () => { const cancelForm = () => {
@ -299,17 +538,349 @@ const cancelForm = () => {
</script> </script>
<style scoped> <style scoped>
.space-y-3 > div + div { .purchase-form {
margin-top: 0.75rem; 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 { .form-label {
font-size: 0.875rem; font-size: 0.875rem;
font-weight: 500; font-weight: 500;
color: #495057;
margin-bottom: 0.5rem; 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; 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> </style>

View File

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

View File

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