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 {
alert("Avoir supprimé avec succès"); await avoirStore.deleteAvoir(id);
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 {
alert("Commande supprimée avec succès"); await purchaseOrderStore.deletePurchaseOrder(id);
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

@ -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 -->