Feat purchase order
This commit is contained in:
parent
0009eb8c86
commit
ed5181d290
@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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.',
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -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'],
|
||||
];
|
||||
}
|
||||
}
|
||||
@ -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,
|
||||
];
|
||||
}
|
||||
}
|
||||
69
thanasoft-back/app/Models/PurchaseOrder.php
Normal file
69
thanasoft-back/app/Models/PurchaseOrder.php
Normal 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);
|
||||
}
|
||||
}
|
||||
43
thanasoft-back/app/Models/PurchaseOrderLine.php
Normal file
43
thanasoft-back/app/Models/PurchaseOrderLine.php
Normal 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);
|
||||
}
|
||||
}
|
||||
@ -105,6 +105,9 @@ class AppServiceProvider extends ServiceProvider
|
||||
$this->app->bind(\App\Repositories\QuoteLineRepositoryInterface::class, \App\Repositories\QuoteLineRepository::class);
|
||||
|
||||
$this->app->bind(\App\Repositories\ClientActivityTimelineRepositoryInterface::class, \App\Repositories\ClientActivityTimelineRepository::class);
|
||||
|
||||
$this->app->bind(\App\Repositories\PurchaseOrderRepositoryInterface::class, \App\Repositories\PurchaseOrderRepository::class);
|
||||
$this->app->bind(\App\Repositories\DeceasedDocumentRepositoryInterface::class, \App\Repositories\DeceasedDocumentRepository::class);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@ -23,6 +23,7 @@ class RepositoryServiceProvider extends ServiceProvider
|
||||
$this->app->bind(DeceasedDocumentRepositoryInterface::class, DeceasedDocumentRepository::class);
|
||||
$this->app->bind(InterventionRepositoryInterface::class, InterventionRepository::class);
|
||||
$this->app->bind(FileRepositoryInterface::class, FileRepository::class);
|
||||
$this->app->bind(\App\Repositories\PurchaseOrderRepositoryInterface::class, \App\Repositories\PurchaseOrderRepository::class);
|
||||
|
||||
}
|
||||
|
||||
|
||||
86
thanasoft-back/app/Repositories/PurchaseOrderRepository.php
Normal file
86
thanasoft-back/app/Repositories/PurchaseOrderRepository.php
Normal 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;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Repositories;
|
||||
|
||||
interface PurchaseOrderRepositoryInterface extends BaseRepositoryInterface
|
||||
{
|
||||
}
|
||||
@ -20,6 +20,7 @@ use App\Http\Controllers\Api\FileController;
|
||||
use App\Http\Controllers\Api\FileAttachmentController;
|
||||
use App\Http\Controllers\Api\QuoteController;
|
||||
use App\Http\Controllers\Api\ClientActivityTimelineController;
|
||||
use App\Http\Controllers\Api\PurchaseOrderController;
|
||||
|
||||
|
||||
/*
|
||||
@ -85,6 +86,7 @@ Route::middleware('auth:sanctum')->group(function () {
|
||||
|
||||
// Fournisseur management
|
||||
Route::get('/fournisseurs/searchBy', [FournisseurController::class, 'searchBy']);
|
||||
Route::apiResource('purchase-orders', PurchaseOrderController::class);
|
||||
Route::apiResource('fournisseurs', FournisseurController::class);
|
||||
Route::get('fournisseurs/{fournisseurId}/contacts', [ContactController::class, 'getContactsByFournisseur']);
|
||||
|
||||
|
||||
@ -8,7 +8,7 @@
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<avoir-table
|
||||
:data="filteredAvoirs"
|
||||
:data="avoirs"
|
||||
:loading="loading"
|
||||
@view="handleView"
|
||||
@delete="handleDelete"
|
||||
@ -23,72 +23,18 @@ import { ref, onMounted, computed } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import AvoirListControls from "@/components/molecules/Avoir/AvoirListControls.vue";
|
||||
import AvoirTable from "@/components/molecules/Tables/Avoirs/AvoirTable.vue";
|
||||
import { useAvoirStore } from "@/stores/avoirStore";
|
||||
import { storeToRefs } from "pinia";
|
||||
|
||||
const router = useRouter();
|
||||
const loading = ref(false);
|
||||
const avoirStore = useAvoirStore();
|
||||
const { avoirs, loading, error } = storeToRefs(avoirStore);
|
||||
const activeFilter = ref(null);
|
||||
|
||||
// Sample data for avoirs
|
||||
const avoirs = ref([
|
||||
{
|
||||
id: "1",
|
||||
number: "AV-2026-00001",
|
||||
invoiceNumber: "F-2026-00001",
|
||||
clientName: "Caroline Lepetit thanatopraxie",
|
||||
amount: 168.0,
|
||||
status: "emis",
|
||||
date: new Date(2026, 0, 15),
|
||||
reason: "Erreur de facturation",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
number: "AV-2026-00002",
|
||||
invoiceNumber: "FAC-202512-0002",
|
||||
clientName: "Hygiène Funéraire 50",
|
||||
amount: 84.0,
|
||||
status: "applique",
|
||||
date: new Date(2026, 0, 18),
|
||||
reason: "Retour de marchandise",
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
number: "AV-2026-00003",
|
||||
invoiceNumber: "FAC-202512-0005",
|
||||
clientName: "Pompes Funèbres Martin",
|
||||
amount: 54.0,
|
||||
status: "brouillon",
|
||||
date: new Date(2026, 0, 20),
|
||||
reason: "Geste commercial",
|
||||
},
|
||||
{
|
||||
id: "4",
|
||||
number: "AV-2026-00004",
|
||||
invoiceNumber: "FAC-202512-0007",
|
||||
clientName: "Pompes Funèbres Martin",
|
||||
amount: 108.0,
|
||||
status: "emis",
|
||||
date: new Date(2026, 0, 22),
|
||||
reason: "Annulation de prestation",
|
||||
},
|
||||
{
|
||||
id: "5",
|
||||
number: "AV-2026-00005",
|
||||
invoiceNumber: "FACT-2024-003",
|
||||
clientName: "PF Premium",
|
||||
amount: 72.0,
|
||||
status: "annule",
|
||||
date: new Date(2025, 11, 28),
|
||||
reason: "Erreur de facturation",
|
||||
},
|
||||
]);
|
||||
|
||||
// Computed property for filtered avoirs
|
||||
const filteredAvoirs = computed(() => {
|
||||
if (!activeFilter.value) {
|
||||
return avoirs.value;
|
||||
}
|
||||
return avoirs.value.filter(avoir => avoir.status === activeFilter.value);
|
||||
});
|
||||
const handleFilter = (status) => {
|
||||
activeFilter.value = status;
|
||||
avoirStore.fetchAvoirs({ status: status || undefined });
|
||||
};
|
||||
|
||||
const openCreateModal = () => {
|
||||
router.push("/avoirs/new");
|
||||
@ -98,13 +44,8 @@ const handleView = (id) => {
|
||||
router.push(`/avoirs/${id}`);
|
||||
};
|
||||
|
||||
const handleFilter = (status) => {
|
||||
activeFilter.value = status;
|
||||
};
|
||||
|
||||
const handleExport = () => {
|
||||
// Export filtered avoirs to CSV
|
||||
const dataToExport = filteredAvoirs.value;
|
||||
const dataToExport = avoirs.value;
|
||||
const headers = [
|
||||
"N° Avoir",
|
||||
"Date",
|
||||
@ -118,17 +59,16 @@ const handleExport = () => {
|
||||
headers.join(","),
|
||||
...dataToExport.map((avoir) =>
|
||||
[
|
||||
avoir.number,
|
||||
avoir.date.toLocaleDateString("fr-FR"),
|
||||
avoir.avoir_number,
|
||||
new Date(avoir.avoir_date).toLocaleDateString("fr-FR"),
|
||||
getStatusLabel(avoir.status),
|
||||
avoir.clientName,
|
||||
avoir.invoiceNumber,
|
||||
avoir.amount.toFixed(2) + " EUR",
|
||||
avoir.client?.name || "N/A",
|
||||
avoir.invoice?.invoice_number || "N/A",
|
||||
(avoir.total_ttc || 0).toFixed(2) + " EUR",
|
||||
].join(",")
|
||||
),
|
||||
].join("\n");
|
||||
|
||||
// Create blob and download
|
||||
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
|
||||
const link = document.createElement("a");
|
||||
const url = URL.createObjectURL(blob);
|
||||
@ -154,12 +94,20 @@ const getStatusLabel = (status) => {
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (confirm("Êtes-vous sûr de vouloir supprimer cet avoir ?")) {
|
||||
avoirs.value = avoirs.value.filter((a) => a.id !== id);
|
||||
alert("Avoir supprimé avec succès");
|
||||
try {
|
||||
await avoirStore.deleteAvoir(id);
|
||||
alert("Avoir supprimé avec succès");
|
||||
} catch (err) {
|
||||
alert("Erreur lors de la suppression de l'avoir");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
loading.value = false;
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await avoirStore.fetchAvoirs();
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch avoirs:", err);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
@ -98,13 +98,15 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, defineProps } from "vue";
|
||||
import { ref, defineProps, onMounted } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import CommandeDetailTemplate from "@/components/templates/Commande/CommandeDetailTemplate.vue";
|
||||
import CommandeHeader from "@/components/molecules/Commande/CommandeHeader.vue";
|
||||
import CommandeLinesTable from "@/components/molecules/Commande/CommandeLinesTable.vue";
|
||||
import CommandeSummary from "@/components/molecules/Commande/CommandeSummary.vue";
|
||||
import SoftButton from "@/components/SoftButton.vue";
|
||||
import { PurchaseOrderService } from "@/services/purchaseOrder";
|
||||
import { useNotificationStore } from "@/stores/notification";
|
||||
|
||||
const props = defineProps({
|
||||
commandeId: {
|
||||
@ -114,51 +116,12 @@ const props = defineProps({
|
||||
});
|
||||
|
||||
const router = useRouter();
|
||||
const notificationStore = useNotificationStore();
|
||||
const commande = ref(null);
|
||||
const loading = ref(true);
|
||||
const error = ref(null);
|
||||
const dropdownOpen = ref(false);
|
||||
|
||||
// Sample commande data
|
||||
const sampleCommande = {
|
||||
id: props.commandeId,
|
||||
number: "CMD-2026-001",
|
||||
supplierName: "Produits Funéraires Pro",
|
||||
supplierAddress: "123 rue de Paris, 75001 Paris",
|
||||
supplierContact: "contact@pfpro.fr",
|
||||
status: "confirmee",
|
||||
date: new Date(2026, 0, 15),
|
||||
total_ht: 2500.0,
|
||||
total_tva: 500.0,
|
||||
total_ttc: 3000.0,
|
||||
lines: [
|
||||
{
|
||||
id: 1,
|
||||
designation: "Fluide artériel Premium 5L",
|
||||
quantity: 5,
|
||||
price_ht: 450.0,
|
||||
total_ht: 2250.0,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
designation: "Aiguilles de suture serpentine 10,80cm",
|
||||
quantity: 2,
|
||||
price_ht: 125.0,
|
||||
total_ht: 250.0,
|
||||
},
|
||||
],
|
||||
history: [
|
||||
{
|
||||
changed_at: new Date(2026, 0, 15),
|
||||
comment: "Commande créée",
|
||||
},
|
||||
{
|
||||
changed_at: new Date(2026, 0, 15, 10, 30),
|
||||
comment: "Commande confirmée par le fournisseur",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const availableStatuses = ["brouillon", "confirmee", "livree", "facturee", "annulee"];
|
||||
|
||||
const formatDate = (dateString) => {
|
||||
@ -177,13 +140,66 @@ const getStatusLabel = (status) => {
|
||||
return labels[status] || status;
|
||||
};
|
||||
|
||||
const changeStatus = (newStatus) => {
|
||||
commande.value.status = newStatus;
|
||||
const fetchCommande = async () => {
|
||||
loading.value = true;
|
||||
error.value = null;
|
||||
try {
|
||||
const response = await PurchaseOrderService.getPurchaseOrder(props.commandeId);
|
||||
const data = response.data;
|
||||
|
||||
// Map backend data to frontend structure
|
||||
commande.value = {
|
||||
id: data.id,
|
||||
number: data.po_number,
|
||||
status: data.status,
|
||||
date: data.order_date,
|
||||
total_ht: data.total_ht,
|
||||
total_tva: data.total_tva,
|
||||
total_ttc: data.total_ttc,
|
||||
notes: data.notes,
|
||||
deliveryAddress: data.delivery_address,
|
||||
|
||||
// Supplier mapping
|
||||
supplierName: data.fournisseur?.name || "Inconnu",
|
||||
supplierAddress: data.fournisseur ?
|
||||
`${data.fournisseur.billing_address_line1 || ''} ${data.fournisseur.billing_city || ''}` :
|
||||
"Non spécifiée",
|
||||
supplierContact: data.fournisseur?.email || data.fournisseur?.phone || "Indisponible",
|
||||
|
||||
// Lines mapping: translation between backend (description, unit_price) and frontend (designation, price_ht)
|
||||
lines: (data.lines || []).map(line => ({
|
||||
id: line.id,
|
||||
designation: line.description,
|
||||
quantity: line.quantity,
|
||||
price_ht: line.unit_price,
|
||||
total_ht: line.total_ht
|
||||
}))
|
||||
};
|
||||
} catch (err) {
|
||||
console.error("Error fetching commande:", err);
|
||||
error.value = "Impossible de charger les détails de la commande.";
|
||||
notificationStore.error("Erreur", error.value);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
};
|
||||
|
||||
// Load sample data on mount
|
||||
setTimeout(() => {
|
||||
commande.value = sampleCommande;
|
||||
loading.value = false;
|
||||
}, 500);
|
||||
const changeStatus = async (newStatus) => {
|
||||
try {
|
||||
const payload = {
|
||||
id: props.commandeId,
|
||||
status: newStatus
|
||||
};
|
||||
await PurchaseOrderService.updatePurchaseOrder(payload);
|
||||
commande.value.status = newStatus;
|
||||
notificationStore.success("Succès", `Statut mis à jour : ${getStatusLabel(newStatus)}`);
|
||||
} catch (err) {
|
||||
console.error("Error updating status:", err);
|
||||
notificationStore.error("Erreur", "Échec de la mise à jour du statut.");
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
fetchCommande();
|
||||
});
|
||||
</script>
|
||||
|
||||
@ -8,7 +8,7 @@
|
||||
<div class="row">
|
||||
<div class="col-12">
|
||||
<commande-table
|
||||
:data="filteredCommandes"
|
||||
:data="purchaseOrders"
|
||||
:loading="loading"
|
||||
@view="handleView"
|
||||
@delete="handleDelete"
|
||||
@ -23,67 +23,19 @@ import { ref, onMounted, computed } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import CommandeListControls from "@/components/molecules/Fournisseur/CommandeListControls.vue";
|
||||
import CommandeTable from "@/components/molecules/Tables/Fournisseurs/CommandeTable.vue";
|
||||
import { usePurchaseOrderStore } from "@/stores/purchaseOrderStore";
|
||||
import { storeToRefs } from "pinia";
|
||||
|
||||
const router = useRouter();
|
||||
const loading = ref(false);
|
||||
const purchaseOrderStore = usePurchaseOrderStore();
|
||||
const { purchaseOrders, loading, error } = storeToRefs(purchaseOrderStore);
|
||||
const activeFilter = ref(null);
|
||||
|
||||
// Sample data for commandes
|
||||
const commandes = ref([
|
||||
{
|
||||
id: "1",
|
||||
number: "CMD-2026-001",
|
||||
date: new Date(2026, 0, 15),
|
||||
supplier: "Produits Funéraires Pro",
|
||||
status: "confirmee",
|
||||
amount: 2500.0,
|
||||
items_count: 5,
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
number: "CMD-2026-002",
|
||||
date: new Date(2026, 0, 18),
|
||||
supplier: "Thanatos Supply",
|
||||
status: "livree",
|
||||
amount: 1850.5,
|
||||
items_count: 3,
|
||||
},
|
||||
{
|
||||
id: "3",
|
||||
number: "CMD-2026-003",
|
||||
date: new Date(2026, 0, 20),
|
||||
supplier: "ISOFROID",
|
||||
status: "brouillon",
|
||||
amount: 3200.0,
|
||||
items_count: 8,
|
||||
},
|
||||
{
|
||||
id: "4",
|
||||
number: "CMD-2026-004",
|
||||
date: new Date(2026, 0, 22),
|
||||
supplier: "EEP Co EUROPE",
|
||||
status: "confirmee",
|
||||
amount: 1520.75,
|
||||
items_count: 4,
|
||||
},
|
||||
{
|
||||
id: "5",
|
||||
number: "CMD-2026-005",
|
||||
date: new Date(2025, 11, 28),
|
||||
supplier: "NEXTECH MEDICAL",
|
||||
status: "annulee",
|
||||
amount: 890.0,
|
||||
items_count: 2,
|
||||
},
|
||||
]);
|
||||
|
||||
// Computed property for filtered commandes
|
||||
const filteredCommandes = computed(() => {
|
||||
if (!activeFilter.value) {
|
||||
return commandes.value;
|
||||
}
|
||||
return commandes.value.filter(cmd => cmd.status === activeFilter.value);
|
||||
});
|
||||
const handleFilter = (status) => {
|
||||
activeFilter.value = status;
|
||||
// If backend supports filtering, we can call fetchPurchaseOrders({ status })
|
||||
purchaseOrderStore.fetchPurchaseOrders({ status: status || undefined });
|
||||
};
|
||||
|
||||
const openCreateModal = () => {
|
||||
router.push("/fournisseurs/commandes/new");
|
||||
@ -93,19 +45,14 @@ const handleView = (id) => {
|
||||
router.push(`/fournisseurs/commandes/${id}`);
|
||||
};
|
||||
|
||||
const handleFilter = (status) => {
|
||||
activeFilter.value = status;
|
||||
};
|
||||
|
||||
const handleExport = () => {
|
||||
// Export filtered commandes to CSV
|
||||
const dataToExport = filteredCommandes.value;
|
||||
const dataToExport = purchaseOrders.value;
|
||||
const headers = [
|
||||
"N° Commande",
|
||||
"Date",
|
||||
"Fournisseur",
|
||||
"Statut",
|
||||
"Montant",
|
||||
"Montant TTC",
|
||||
"Articles",
|
||||
];
|
||||
|
||||
@ -113,17 +60,16 @@ const handleExport = () => {
|
||||
headers.join(","),
|
||||
...dataToExport.map((cmd) =>
|
||||
[
|
||||
cmd.number,
|
||||
cmd.date.toLocaleDateString("fr-FR"),
|
||||
cmd.supplier,
|
||||
cmd.po_number,
|
||||
new Date(cmd.order_date).toLocaleDateString("fr-FR"),
|
||||
cmd.fournisseur?.name || "N/A",
|
||||
getStatusLabel(cmd.status),
|
||||
cmd.amount.toFixed(2) + " EUR",
|
||||
cmd.items_count,
|
||||
(cmd.total_ttc || 0).toFixed(2) + " EUR",
|
||||
cmd.lines?.length || 0,
|
||||
].join(",")
|
||||
),
|
||||
].join("\n");
|
||||
|
||||
// Create blob and download
|
||||
const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" });
|
||||
const link = document.createElement("a");
|
||||
const url = URL.createObjectURL(blob);
|
||||
@ -150,12 +96,20 @@ const getStatusLabel = (status) => {
|
||||
|
||||
const handleDelete = async (id) => {
|
||||
if (confirm("Êtes-vous sûr de vouloir supprimer cette commande ?")) {
|
||||
commandes.value = commandes.value.filter((c) => c.id !== id);
|
||||
alert("Commande supprimée avec succès");
|
||||
try {
|
||||
await purchaseOrderStore.deletePurchaseOrder(id);
|
||||
alert("Commande supprimée avec succès");
|
||||
} catch (err) {
|
||||
alert("Erreur lors de la suppression de la commande");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
loading.value = false;
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await purchaseOrderStore.fetchPurchaseOrders();
|
||||
} catch (err) {
|
||||
console.error("Failed to fetch purchase orders:", err);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -20,7 +20,7 @@
|
||||
<div class="d-flex align-items-center">
|
||||
<soft-checkbox class="me-2" />
|
||||
<p class="text-xs font-weight-bold ms-2 mb-0">
|
||||
{{ avoir.number }}
|
||||
{{ avoir.avoir_number || avoir.number }}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
@ -28,7 +28,7 @@
|
||||
<!-- Date -->
|
||||
<td class="font-weight-bold">
|
||||
<span class="my-2 text-xs">{{
|
||||
formatDate(avoir.date)
|
||||
formatDate(avoir.avoir_date || avoir.date)
|
||||
}}</span>
|
||||
</td>
|
||||
|
||||
@ -60,7 +60,7 @@
|
||||
circular
|
||||
/>
|
||||
<span>{{
|
||||
avoir.clientName || "Client Inconnu"
|
||||
avoir.client?.name || avoir.clientName || "Client Inconnu"
|
||||
}}</span>
|
||||
</div>
|
||||
</td>
|
||||
@ -68,14 +68,14 @@
|
||||
<!-- Invoice Reference -->
|
||||
<td class="text-xs font-weight-bold">
|
||||
<span class="my-2 text-xs">
|
||||
{{ avoir.invoiceNumber }}
|
||||
{{ avoir.invoice?.invoice_number || avoir.invoiceNumber }}
|
||||
</span>
|
||||
</td>
|
||||
|
||||
<!-- Amount (Total) -->
|
||||
<td class="text-xs font-weight-bold">
|
||||
<span class="my-2 text-xs">{{
|
||||
formatCurrency(avoir.amount)
|
||||
formatCurrency(avoir.total_ttc || avoir.amount)
|
||||
}}</span>
|
||||
</td>
|
||||
|
||||
|
||||
@ -20,7 +20,7 @@
|
||||
<div class="d-flex align-items-center">
|
||||
<soft-checkbox class="me-2" />
|
||||
<p class="text-xs font-weight-bold ms-2 mb-0">
|
||||
{{ commande.number }}
|
||||
{{ commande.po_number || commande.number }}
|
||||
</p>
|
||||
</div>
|
||||
</td>
|
||||
@ -28,7 +28,7 @@
|
||||
<!-- Date -->
|
||||
<td class="font-weight-bold">
|
||||
<span class="my-2 text-xs">{{
|
||||
formatDate(commande.date)
|
||||
formatDate(commande.order_date || commande.date)
|
||||
}}</span>
|
||||
</td>
|
||||
|
||||
@ -42,7 +42,7 @@
|
||||
alt="supplier image"
|
||||
circular
|
||||
/>
|
||||
<span>{{ commande.supplier }}</span>
|
||||
<span>{{ commande.fournisseur?.name || commande.supplier }}</span>
|
||||
</div>
|
||||
</td>
|
||||
|
||||
@ -66,13 +66,13 @@
|
||||
<!-- Amount -->
|
||||
<td class="text-xs font-weight-bold">
|
||||
<span class="my-2 text-xs">{{
|
||||
formatCurrency(commande.amount)
|
||||
formatCurrency(commande.total_ttc || commande.amount)
|
||||
}}</span>
|
||||
</td>
|
||||
|
||||
<!-- Items Count -->
|
||||
<td class="text-xs font-weight-bold">
|
||||
<span class="badge bg-secondary">{{ commande.items_count }}</span>
|
||||
<span class="badge bg-secondary">{{ commande.lines?.length || commande.items_count || 0 }}</span>
|
||||
</td>
|
||||
|
||||
<!-- Actions -->
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user