connect api to stock page for get, patch and delete

This commit is contained in:
2025-11-29 23:14:04 +01:00
parent a76b184dc1
commit 0189fb0440
8 changed files with 255 additions and 78 deletions

View File

@@ -1,12 +1,12 @@
<form nz-form nzLayout="horizontal" [formGroup]="stockForm" (ngSubmit)="submitForm()"> <form nz-form nzLayout="horizontal" [formGroup]="stockForm">
<nz-form-item nz-flex> <nz-form-item nz-flex>
<nz-form-label nzSpan="15" nzRequired> <nz-form-label nzSpan="15" nzRequired>
Quantité minimale du produit Quantité minimale du produit
</nz-form-label> </nz-form-label>
<nz-form-control nzSpan="4" nzErrorTip="Ce champ est requis"> <nz-form-control nzSpan="4" nzErrorTip="Requis">
<input nz-input placeholder="12345" formControlName="minQuantity"> <input nz-input type="number" placeholder="12345" formControlName="minimalQuantity">
</nz-form-control> </nz-form-control>
</nz-form-item> </nz-form-item>
</form> </form>

View File

@@ -1,9 +1,10 @@
import { Component } from '@angular/core'; import {Component, effect, input} from '@angular/core';
import {FormControl, FormGroup, ReactiveFormsModule, Validators} from "@angular/forms"; import {FormControl, FormGroup, ReactiveFormsModule, Validators} from "@angular/forms";
import {NzFormControlComponent, NzFormDirective, NzFormItemComponent, NzFormLabelComponent} from "ng-zorro-antd/form"; import {NzFormControlComponent, NzFormDirective, NzFormItemComponent, NzFormLabelComponent} from "ng-zorro-antd/form";
import {NzInputDirective} from "ng-zorro-antd/input"; import {NzInputDirective} from "ng-zorro-antd/input";
import {NzColDirective} from "ng-zorro-antd/grid"; import {NzColDirective} from "ng-zorro-antd/grid";
import {NzFlexDirective} from "ng-zorro-antd/flex"; import {NzFlexDirective} from "ng-zorro-antd/flex";
import {GetProductDto} from "../../services/api";
@Component({ @Component({
selector: 'app-stock-form', selector: 'app-stock-form',
@@ -22,17 +23,19 @@ import {NzFlexDirective} from "ng-zorro-antd/flex";
}) })
export class StockForm { export class StockForm {
stockForm = new FormGroup({ stockForm = new FormGroup({
minQuantity: new FormControl<number>(null, [Validators.required]) id: new FormControl<number>(null),
minimalQuantity: new FormControl<number>(null, [Validators.required])
}) })
submitForm() { product= input<GetProductDto>();
// Pour annuler si le formulaire est invalide constructor() {
if (this.stockForm.invalid) return; effect(() => {
if (this.product()) {
// Pour obtenir la valeur du formulaire this.stockForm.patchValue({
console.log(this.stockForm.getRawValue()) id: this.product().id,
minimalQuantity: this.product().minimalQuantity,
// Pour vider le formulaire });
this.stockForm.reset() }
});
} }
} }

View File

@@ -1,6 +1,6 @@
<nz-table <nz-table
#rowSelectionTable [nzData]="products()"
[nzData]="listOfData" [nzFrontPagination]="false"
(nzCurrentPageDataChange)="onCurrentPageDataChange($event)" (nzCurrentPageDataChange)="onCurrentPageDataChange($event)"
> >
<thead> <thead>
@@ -26,36 +26,39 @@
</thead> </thead>
<tbody class="text-center"> <tbody class="text-center">
@for (data of rowSelectionTable.data; track data.id) { @for (product of products(); track product.id) {
<tr> <tr>
<td nzWidth="40px"> <td nzWidth="40px">
<label <label
nz-checkbox nz-checkbox
[ngModel]="setOfCheckedId.has(data.id)" [ngModel]="setOfCheckedId.has(product.id)"
(ngModelChange)="onItemChecked(data.id, $event)" (ngModelChange)="onItemChecked(product.id, $event)"
></label> ></label>
</td> </td>
<td>{{ data.product.name }}</td> <td>{{ product.name }}</td>
<td>{{ data.product.reference }}</td> <td>{{ product.references }}</td>
<td>{{ data.product.nec }}</td> <td>{{ product.nec }}</td>
<td>{{ data.product.caliber }}</td> <td>{{ product.caliber }}</td>
<td>{{ data.product.weight }}</td> <td>{{ product.weight }}</td>
<td>{{ data.product.duration }}</td> <td>{{ product.duration }}</td>
<td>{{ data.quantity }}</td> <td> Quantité totale ??? </td>
<td>{{ data.product.minimalQuantity }}</td> <td>{{ product.minimalQuantity }}</td>
<td> <td>
<div style="justify-content: center; display: flex"> <div style="justify-content: center; display: flex">
<app-modal-nav nameIcon="edit" name="Modification de la quantité minimale"> <nz-icon nzType="edit" nzTheme="outline" class="cursor-pointer" (click)="openEditModal(product)"></nz-icon>
<app-stock-form></app-stock-form>
</app-modal-nav>
<nz-divider nzType="vertical"></nz-divider> <nz-divider nzType="vertical"></nz-divider>
<nz-icon nzType="delete" (click)="delete()" nzTheme="outline" <nz-icon nzType="delete" nzTheme="outline" (click)="delete(product.id)" class="text-red-600 cursor-pointer"></nz-icon>
class="cursor-pointer text-red-700"/>
</div> </div>
</td> </td>
</tr> </tr>
} }
</tbody> </tbody>
</nz-table> </nz-table>
<div class="hidden">
<app-modal-nav #modalNav nameIcon="edit" [name]="'Modifier'" (ok)="onModalOk(selectedProduct.id, stockForm, modalNav)" (cancel)="onModalCancel(modalNav)">
<app-stock-form #stockForm [product]="selectedProduct"></app-stock-form>
</app-modal-nav>
</div>

View File

@@ -1,13 +1,14 @@
import {Component, output} from '@angular/core'; import {Component, inject, OnInit, output, signal, viewChild} from '@angular/core';
import {StockInfo} from "../../interfaces/stock.interface"; import {NzTableComponent, NzThMeasureDirective} from "ng-zorro-antd/table";
import {NzTableComponent} from "ng-zorro-antd/table";
import {ModalNav} from "../modal-nav/modal-nav"; import {ModalNav} from "../modal-nav/modal-nav";
import {NzIconDirective} from "ng-zorro-antd/icon"; import {NzIconDirective} from "ng-zorro-antd/icon";
import {StockForm} from "../stock-form/stock-form"; import {StockForm} from "../stock-form/stock-form";
import {NzDividerComponent} from "ng-zorro-antd/divider"; import {NzDividerComponent} from "ng-zorro-antd/divider";
import {ProductTable} from "../product-table/product-table";
import {FormsModule} from "@angular/forms"; import {FormsModule} from "@angular/forms";
import {NzCheckboxComponent} from "ng-zorro-antd/checkbox"; import {NzCheckboxComponent} from "ng-zorro-antd/checkbox";
import {GetProductDto, ProductsService} from "../../services/api";
import {NzNotificationService} from "ng-zorro-antd/notification";
import {firstValueFrom} from "rxjs";
@Component({ @Component({
selector: 'app-stock-table', selector: 'app-stock-table',
@@ -19,38 +20,30 @@ import {NzCheckboxComponent} from "ng-zorro-antd/checkbox";
NzDividerComponent, NzDividerComponent,
FormsModule, FormsModule,
NzCheckboxComponent, NzCheckboxComponent,
NzThMeasureDirective,
], ],
templateUrl: './stock-table.html', templateUrl: './stock-table.html',
styleUrl: './stock-table.css', styleUrl: './stock-table.css',
}) })
export class StockTable { export class StockTable implements OnInit {
listOfData: StockInfo[] = [ private productsService = inject(ProductsService);
{ id: 1, product: ProductTable.listOfProducts[0], quantity: 10 }, private notificationService = inject(NzNotificationService)
{ id: 2, product: ProductTable.listOfProducts[1], quantity: 5 }, products = signal<GetProductDto[]>([]);
{ id: 3, product: ProductTable.listOfProducts[2], quantity: 8 }, productsLoading = signal<boolean>(false);
{ id: 4, product: ProductTable.listOfProducts[3], quantity: 12 }, updateProduct = viewChild.required<StockForm>('stockForm');
{ id: 5, product: ProductTable.listOfProducts[4], quantity: 7 }, modal = viewChild.required<ModalNav>('modalNav');
{ id: 6, product: ProductTable.listOfProducts[5], quantity: 15 },
{ id: 7, product: ProductTable.listOfProducts[6], quantity: 9 },
{ id: 8, product: ProductTable.listOfProducts[7], quantity: 6 },
{ id: 9, product: ProductTable.listOfProducts[8], quantity: 11 },
{ id: 10, product: ProductTable.listOfProducts[9], quantity: 14 },
{ id: 11, product: ProductTable.listOfProducts[10], quantity: 7 },
{ id: 12, product: ProductTable.listOfProducts[11], quantity: 13 },
{ id: 13, product: ProductTable.listOfProducts[12], quantity: 10 },
{ id: 14, product: ProductTable.listOfProducts[13], quantity: 5 },
];
checked = false; checked = false;
indeterminate = false; indeterminate = false;
setOfCheckedId = new Set<number>(); setOfCheckedId = new Set<number>();
selectionChange = output<boolean>()
currentPageData: GetProductDto[] = [];
get hasSelection(): boolean { get hasSelection(): boolean {
return this.setOfCheckedId.size > 0; return this.setOfCheckedId.size > 0;
} }
updateCheckedSet(id: number, checked: boolean): void { updateCheckedSet(id: number, checked: boolean): void {
if (checked) this.setOfCheckedId.add(id); if (checked) this.setOfCheckedId.add(id);
else this.setOfCheckedId.delete(id); else this.setOfCheckedId.delete(id);
@@ -62,31 +55,109 @@ export class StockTable {
} }
onAllChecked(checked: boolean): void { onAllChecked(checked: boolean): void {
this.listOfData.forEach(item => this.updateCheckedSet(item.id, checked)); this.currentPageData.forEach(item =>
this.updateCheckedSet(item.id, checked)
);
this.refreshCheckedStatus();
}
onCurrentPageDataChange($event: GetProductDto[]): void {
this.currentPageData = $event;
this.refreshCheckedStatus(); this.refreshCheckedStatus();
} }
refreshCheckedStatus(): void { refreshCheckedStatus(): void {
const total = this.listOfData.length; const total = this.currentPageData.length;
const checkedCount = this.setOfCheckedId.size; const checkedCount = this.currentPageData.filter(p => this.setOfCheckedId.has(p.id)).length;
this.checked = checkedCount === total; this.checked = checkedCount === total;
this.indeterminate = checkedCount > 0 && checkedCount < total; this.indeterminate = checkedCount > 0 && checkedCount < total;
// 🔥 Émission asynchrone -> corrige le retard daffichage setTimeout(() => this.selectionChange.emit(this.hasSelection));
setTimeout(() => {
this.selectionChange.emit(this.hasSelection);
});
} }
get selectedIds() {
onCurrentPageDataChange($event: StockInfo[]): void { return Array.from(this.setOfCheckedId);
this.listOfData = $event;
this.refreshCheckedStatus();
} }
delete() { async ngOnInit() {
await this.fetchProducts();
}
async fetchProducts() {
this.productsLoading.set(true)
try {
const products = await firstValueFrom(this.productsService.getAllProductsEndpoint())
this.products.set(products);
} catch (e) {
this.notificationService.error(
'Erreur',
'Erreur de communication avec l\'API'
)
}
this.productsLoading.set(false)
}
async delete(productId:number) {
try {
await firstValueFrom(this.productsService.deleteProductEndpoint(productId))
this.notificationService.success(
'Success',
'Suppression effectuée'
)
} catch (e) {
this.notificationService.error(
'Erreur',
'Impossible de supprimer la ligne'
)
}
await this.fetchProducts();
}
async edit(id: number, updateProductComponent: StockForm) {
if (updateProductComponent.stockForm.invalid) {
this.notificationService.error(
'Erreur',
'Erreur d\'écriture dans le formulaire'
)
return; return;
} }
selectionChange = output<boolean>()
try {
const products = updateProductComponent.stockForm.getRawValue();
await firstValueFrom(this.productsService.patchProductMinimalStockEndpoint(id, products))
this.notificationService.success(
'Success',
'Limite de stock modifiée'
)
} catch (e) {
console.error(e);
this.notificationService.error(
'Erreur',
'Erreur lors de la modification'
)
}
}
selectedProduct: GetProductDto | null = null;
openEditModal(product: GetProductDto) {
this.selectedProduct = { ...product};
this.modal().showModal();
}
async onModalOk(productId: number, updateProductComponent: StockForm, modal: ModalNav) {
if (!this.selectedProduct) return;
await this.edit(productId, updateProductComponent);
updateProductComponent.stockForm.reset();
modal.isVisible = false;
await this.fetchProducts();
}
onModalCancel(modal: ModalNav) {
modal.isVisible = false;
}
} }

View File

@@ -1,11 +1,11 @@
<div class="flex mt-2"> <div class="flex mt-2">
@if (hasSelection) { @if (hasSelection) {
<app-modal-button type="default" name="Créer un bon de commande" class="ml-4"> <app-modal-button #modalButton type="default" name="Créer un bon de commande" class="ml-4">
<app-purchase-order-form></app-purchase-order-form> <app-purchase-order-form #purchaseOrderForm></app-purchase-order-form>
</app-modal-button> </app-modal-button>
<app-modal-button type="default" name="Créer un devis" class="ml-4"> <app-modal-button #modalButton type="default" name="Créer un devis" class="ml-4" (click)="test()">
<app-quotation-form></app-quotation-form> <app-quotation-form #quotationForm></app-quotation-form>
</app-modal-button> </app-modal-button>
} }
@@ -15,7 +15,5 @@
</div> </div>
<div class="mt-1"> <div class="mt-1">
<app-stock-table <app-stock-table #stockTable (selectionChange)="onSelectionChange($event)"></app-stock-table>
(selectionChange)="onSelectionChange($event)"
></app-stock-table>
</div> </div>

View File

@@ -1,9 +1,12 @@
import { Component } from '@angular/core'; import {Component, inject, viewChild} from '@angular/core';
import {StockTable} from "../../components/stock-table/stock-table"; import {StockTable} from "../../components/stock-table/stock-table";
import {Search} from "../../components/search/search"; import {Search} from "../../components/search/search";
import {ModalButton} from "../../components/modal-button/modal-button"; import {ModalButton} from "../../components/modal-button/modal-button";
import {PurchaseOrderForm} from "../../components/purchase-order-form/purchase-order-form"; import {PurchaseOrderForm} from "../../components/purchase-order-form/purchase-order-form";
import {QuotationForm} from "../../components/quotation-form/quotation-form"; import {QuotationForm} from "../../components/quotation-form/quotation-form";
import {ProductsService} from "../../services/api";
import {NzNotificationService} from "ng-zorro-antd/notification";
import {firstValueFrom} from "rxjs";
@Component({ @Component({
selector: 'app-stock', selector: 'app-stock',
@@ -19,10 +22,56 @@ import {QuotationForm} from "../../components/quotation-form/quotation-form";
}) })
export class Stock { export class Stock {
modal = viewChild.required<ModalButton>('modalButton');
createQuotation = viewChild.required<QuotationForm>('quotationForm');
createPurchaseOrder = viewChild.required<PurchaseOrderForm>('purchaseOrderForm');
productTable = viewChild.required<StockTable>('stockTable');
private productsService = inject(ProductsService);
private notificationService = inject(NzNotificationService)
// async onModalOk() {
// await this.addSupplier()
// this.createSupplier().supplierForm.reset();
// this.modal().isVisible = false;
// await this.supplierTable().fetchSuppliers()
// }
//
// onModalCancel() {
// this.modal().isVisible = false;
// }
//
// async addSupplier() {
// if (this.createSupplier().supplierForm.invalid)
// {
// this.notificationService.error(
// 'Erreur',
// 'Erreur d\'écriture dans le formulaire'
// )
// }
// try {
// const suppliers = this.createSupplier().supplierForm.getRawValue();
// await firstValueFrom(this.usersService.createSupplierEndpoint(suppliers))
//
// this.notificationService.success(
// 'Success',
// 'Fournisseur enregistré'
// )
// } catch (e) {
// this.notificationService.error(
// 'Erreur',
// 'Erreur d\'enregistrement'
// )
// }
// }
hasSelection = false; hasSelection = false;
onSelectionChange(value: boolean) { onSelectionChange(value: boolean) {
this.hasSelection = value; this.hasSelection = value;
} }
test(){
console.log(this.productTable().selectedIds);
}
} }

View File

@@ -22,7 +22,7 @@ export class Supplier {
modal = viewChild.required<ModalButton>('modalButton'); modal = viewChild.required<ModalButton>('modalButton');
createSupplier = viewChild.required<SupplierForm>('supplierForm'); createSupplier = viewChild.required<SupplierForm>('supplierForm');
supplierTable = viewChild.required<SupplierTable>('supplierTable'); supplierTable = viewChild.required<SupplierTable>('supplierTable');
private usersService = inject(SuppliersService); private suppliersService = inject(SuppliersService);
private notificationService = inject(NzNotificationService) private notificationService = inject(NzNotificationService)
async onModalOk() { async onModalOk() {
@@ -46,7 +46,7 @@ export class Supplier {
} }
try { try {
const suppliers = this.createSupplier().supplierForm.getRawValue(); const suppliers = this.createSupplier().supplierForm.getRawValue();
await firstValueFrom(this.usersService.createSupplierEndpoint(suppliers)) await firstValueFrom(this.suppliersService.createSupplierEndpoint(suppliers))
this.notificationService.success( this.notificationService.success(
'Success', 'Success',

View File

@@ -39,6 +39,59 @@ export class ProductsService extends BaseService {
super(basePath, configuration); super(basePath, configuration);
} }
/**
* @endpoint delete /API/products/{productId}
* @param productId
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public deleteProductEndpoint(productId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext, transferCache?: boolean}): Observable<any>;
public deleteProductEndpoint(productId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public deleteProductEndpoint(productId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public deleteProductEndpoint(productId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (productId === null || productId === undefined) {
throw new Error('Required parameter productId was null or undefined when calling deleteProductEndpoint.');
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/API/products/${this.configuration.encodeParam({name: "productId", value: productId, in: "path", style: "simple", explode: false, dataType: "number", dataFormat: "int32"})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('delete', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
}
/** /**
* @endpoint get /API/products * @endpoint get /API/products
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.