Compare commits

...

49 Commits

Author SHA1 Message Date
b79068623f Update jenkinsfile 2025-12-05 14:27:59 +00:00
Vincent Guillet
3eed3d251f Refactor CORS configuration to use allowed origins and enhance header handling 2025-12-05 15:14:16 +01:00
7dcc85ac95 Update api/src/main/java/fr/gameovergne/api/controller/auth/AuthController.java 2025-12-05 13:57:42 +00:00
ec9eb0dc7d Update api/src/main/java/fr/gameovergne/api/config/SecurityConfig.java 2025-12-05 13:40:48 +00:00
01cafd5904 Update docker-compose.prod.yml 2025-12-05 13:35:48 +00:00
321e2fd546 Update jenkinsfile 2025-12-05 13:27:16 +00:00
3026f0a13f Update jenkinsfile 2025-12-05 13:23:58 +00:00
52d17e5ad8 Update jenkinsfile 2025-12-05 12:56:15 +00:00
2803e910bd Add docker-compose.prod.yml 2025-12-05 12:54:54 +00:00
653ce83c33 Add docker-compose.dev.yml 2025-12-05 12:54:08 +00:00
ce618deecf Update docker-compose.yml.OLD 2025-12-05 12:53:06 +00:00
5331ce7866 Update docker-compose.yml 2025-12-04 09:19:07 +00:00
Vincent Guillet
6f6d033be3 Center align items in main navbar container for improved layout 2025-12-03 22:48:26 +01:00
Vincent Guillet
ff8536b448 Update SecurityConfig to require authentication for /api/app/** endpoints 2025-12-03 22:47:14 +01:00
Vincent Guillet
60593f6c11 Update base URL in index.html for proper routing in Game Over'gne app 2025-12-03 22:46:34 +01:00
Vincent Guillet
1708c1bead Update base URL in index.html for proper routing in Game Over'gne app 2025-12-03 22:11:33 +01:00
Vincent Guillet
dc33d762a1 Refactor app configuration to use hrefBase for base URL and improve provider imports 2025-12-03 21:59:42 +01:00
Vincent Guillet
e04cac3345 Enhance main navbar styles for better overflow handling and safe area support 2025-12-03 21:49:52 +01:00
Vincent Guillet
00f45ae6c7 Add loading indicators to product CRUD and dialog components 2025-12-03 21:46:18 +01:00
Vincent Guillet
1a5d3a570a Add image deletion functionality to product dialog carousel 2025-12-03 21:21:50 +01:00
Vincent Guillet
9763289c2f Export resizeImage function and integrate it into Prestashop service 2025-12-03 19:48:19 +01:00
Vincent Guillet
fd6c730ae3 Add image resizing utility and integrate it into product image upload process 2025-12-03 19:46:31 +01:00
Vincent Guillet
eb94697955 Refactor application.properties to set maximum file and request sizes for multipart uploads 2025-12-03 16:40:57 +01:00
Vincent Guillet
a72957648e Refactor PrestashopClient to improve image upload response handling and enhance error reporting 2025-12-03 15:47:12 +01:00
Vincent Guillet
b15c331295 Refactor PrestashopClient to store basic auth header for improved readability and maintainability 2025-12-03 15:32:44 +01:00
Vincent Guillet
503cbee641 Refactor PrestashopClient to enhance manual multipart image upload handling and improve error logging 2025-12-03 15:19:26 +01:00
Vincent Guillet
078cef0585 Refactor PrestashopClient to enhance image upload logging and improve filename handling 2025-12-03 15:06:53 +01:00
Vincent Guillet
48f7e84ef9 Refactor PrestashopClient to improve multipart image upload construction and enhance header management 2025-12-03 14:53:39 +01:00
Vincent Guillet
f975e57110 Refactor PrestashopClient to improve multipart image upload handling and logging 2025-12-03 14:46:32 +01:00
Vincent Guillet
389beca604 Refactor PrestashopClient to construct absolute URL for image uploads and improve logging 2025-12-03 14:36:40 +01:00
Vincent Guillet
fa7a1c2f26 Refactor PrestashopClient to streamline image upload process and enhance error handling 2025-12-03 14:30:34 +01:00
Vincent Guillet
df98dfe38e Refactor PrestashopClient to enhance image upload handling and improve error logging 2025-12-03 14:22:47 +01:00
Vincent Guillet
65559bbb48 Refactor PrestashopProxyController to simplify image upload API path 2025-12-03 13:51:54 +01:00
Vincent Guillet
f317d15ac5 Refactor PrestashopProxyController to simplify image upload API path 2025-12-03 13:43:29 +01:00
Vincent Guillet
68ccb164e2 Refactor PrestashopProxyController to improve path extraction and enhance logging for proxy requests 2025-12-03 13:33:56 +01:00
Vincent Guillet
a8f9c5f49a Refactor PrestashopProxyController to unify API path handling and enhance error logging for proxy requests 2025-12-03 13:22:43 +01:00
Vincent Guillet
ff331e1630 Refactor PrestashopProxyController to streamline API endpoint handling and improve code readability 2025-12-03 12:28:22 +01:00
Vincent Guillet
d076286728 Add image upload functionality to PrestashopClient and PrestashopProxyController 2025-12-03 12:00:48 +01:00
Vincent Guillet
de942e0d96 Enhance PrestashopClient to use UTF-8 encoding for XML body in POST and PUT methods 2025-12-03 11:39:55 +01:00
Vincent Guillet
ce3389f2e6 Enhance PrestashopClient and PrestashopProxyController to add error handling for POST, PUT, and DELETE methods 2025-12-03 11:26:23 +01:00
Vincent Guillet
8680b2fc92 Enhance PrestashopProxyController and PrestashopClient to support POST, PUT, and DELETE methods with raw query handling 2025-12-03 11:03:26 +01:00
Vincent Guillet
5068390a14 Refactor package structure for Prestashop components and enhance raw query handling in PrestashopProxyController 2025-12-03 10:25:59 +01:00
Vincent Guillet
4fe16b0cb1 restore previous version 2025-12-03 10:04:22 +01:00
Vincent Guillet
42c1e655f1 Refactor PrestashopClient to normalize base URL, enhance URL building, and improve raw query handling 2025-12-03 09:33:30 +01:00
Vincent Guillet
fdb6c40bb9 Refactor PrestashopClient to normalize base URL, enhance URL building, and improve raw query handling 2025-12-02 17:48:27 +01:00
Vincent Guillet
72f3791616 Refactor PrestashopClient and PrestashopProxyController to support raw query handling and simplify proxy GET requests 2025-12-02 17:35:53 +01:00
Vincent Guillet
db8085c0aa Refactor PrestashopClient to enhance header configuration and improve query parameter encoding 2025-12-02 17:23:31 +01:00
Vincent Guillet
177eb2eb5c Refactor URI building in PrestashopClient to simplify query parameter encoding 2025-12-02 16:54:49 +01:00
Vincent Guillet
bceedc8620 Add support for raw query handling in PrestashopClient and update response handling in PrestashopProxyController 2025-12-02 16:35:42 +01:00
33 changed files with 2467 additions and 1967 deletions

View File

@@ -46,7 +46,7 @@ public class SecurityConfig {
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll() // autoriser les preflight
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/users/**").authenticated()
.requestMatchers("/api/app/**").permitAll()
.requestMatchers("/api/app/**").authenticated()
.anyRequest().permitAll()
)
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
@@ -61,16 +61,26 @@ public class SecurityConfig {
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOriginPatterns(Arrays.asList(
// IMPORTANT : origins explicites, sans path
config.setAllowedOrigins(Arrays.asList(
"http://localhost:4200",
"http://127.0.0.1:4200",
"https://dev.vincent-guillet.fr"
"https://dev.vincent-guillet.fr",
"https://projets.vincent-guillet.fr"
));
config.setAllowedMethods(Arrays.asList("GET","POST","PUT","DELETE","OPTIONS"));
config.setAllowedHeaders(Arrays.asList("Authorization","Content-Type","Accept"));
config.setExposedHeaders(Arrays.asList("Authorization"));
config.setAllowCredentials(true);
// Autoriser tous les headers côté requête (plus robuste)
config.setAllowedHeaders(Arrays.asList("*"));
// Autoriser les méthodes classiques
config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
// Headers que le client *voit* dans la réponse
config.setExposedHeaders(Arrays.asList("Authorization", "Content-Type"));
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
return source;

View File

@@ -1,4 +1,4 @@
package fr.gameovergne.api.config;
package fr.gameovergne.api.config.prestashop;
import lombok.Getter;
import lombok.Setter;

View File

@@ -1,78 +0,0 @@
package fr.gameovergne.api.controller;
import fr.gameovergne.api.dto.ps.*;
import fr.gameovergne.api.model.ps.SimpleResource;
import fr.gameovergne.api.service.PrestashopAdminService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/ps-admin")
@RequiredArgsConstructor
public class PrestashopAdminController {
private final PrestashopAdminService service;
// --- Simple resources ---
@GetMapping("/{resource}")
public List<PsItemDto> listSimple(@PathVariable SimpleResource resource) {
return service.listSimple(resource);
}
@PostMapping("/{resource}")
public long createSimple(@PathVariable SimpleResource resource,
@RequestParam String name) {
return service.createSimple(resource, name);
}
@PutMapping("/{resource}/{id}")
public void updateSimple(@PathVariable SimpleResource resource,
@PathVariable long id,
@RequestParam String name) {
service.updateSimple(resource, id, name);
}
@DeleteMapping("/{resource}/{id}")
public void deleteSimple(@PathVariable SimpleResource resource,
@PathVariable long id) {
service.deleteSimple(resource, id);
}
// --- Produits liste + flags + condition values ---
@GetMapping("/products")
public List<ProductListItemDto> listProducts(@RequestParam(required = false) String q) {
return service.listProducts(q);
}
@GetMapping("/products/{id}/flags")
public ProductFlagsDto getProductFlags(@PathVariable long id) {
return service.getProductFlags(id);
}
@GetMapping("/meta/condition-values")
public List<String> getConditionValues() {
return service.getConditionValues();
}
// --- Create / update / delete produit ---
@PostMapping("/products")
public long createProduct(@RequestBody PsProductDto dto) {
return service.createProduct(dto);
}
@PutMapping("/products/{id}")
public void updateProduct(@PathVariable long id,
@RequestBody PsProductDto dto) {
service.updateProduct(id, dto);
}
@DeleteMapping("/products/{id}")
public void deleteProduct(@PathVariable long id) {
service.deleteProduct(id);
}
}

View File

@@ -1,54 +0,0 @@
// File: src/main/java/fr/gameovergne/api/controller/PrestashopProxyController.java
package fr.gameovergne.api.controller;
import fr.gameovergne.api.service.PrestashopClient;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.HandlerMapping;
@RestController
@RequestMapping("/api/ps")
public class PrestashopProxyController {
private final PrestashopClient prestashopClient;
public PrestashopProxyController(PrestashopClient prestashopClient) {
this.prestashopClient = prestashopClient;
}
@GetMapping("/**")
public ResponseEntity<String> proxyGet(HttpServletRequest request) {
// Ex: fullPath = /api/ps/categories
String fullPath = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String) request.getAttribute(
HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
String relativePath = new AntPathMatcher()
.extractPathWithinPattern(bestMatchPattern, fullPath);
// Path Presta : "/categories" ou "/manufacturers/3" etc.
String path = relativePath.isEmpty() ? "/" : "/" + relativePath;
// Query string brute, déjà encodée (display=%5Bid,name,active%5D&output_format=JSON)
String rawQuery = request.getQueryString();
var prestaResponse = prestashopClient.getWithRawQuery(path, rawQuery);
// On propage le status + body, et on garde le Content-Type renvoyé par Presta
MediaType contentType = prestaResponse.getHeaders().getContentType();
if (contentType == null) {
contentType = MediaType.APPLICATION_JSON;
}
return ResponseEntity
.status(prestaResponse.getStatusCode())
.contentType(contentType)
.body(prestaResponse.getBody());
}
}

View File

@@ -17,12 +17,6 @@ import java.util.Arrays;
@RestController
@RequestMapping("/api/auth")
@CrossOrigin(
origins = "https://dev.vincent-guillet.fr",
allowCredentials = "true",
allowedHeaders = "*",
methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS}
)
public class AuthController {
private final AuthService authService;

View File

@@ -0,0 +1,143 @@
package fr.gameovergne.api.controller.prestashop;
import fr.gameovergne.api.service.prestashop.PrestashopClient;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
@RestController
@RequestMapping("/api/ps")
public class PrestashopProxyController {
Logger log = LoggerFactory.getLogger(PrestashopProxyController.class);
private final PrestashopClient prestashopClient;
public PrestashopProxyController(PrestashopClient prestashopClient) {
this.prestashopClient = prestashopClient;
}
// --- Helpers communs ---
private String extractPath(HttpServletRequest request) {
String fullPath = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE
);
String bestMatchPattern = (String) request.getAttribute(
HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE
);
String relativePath = new AntPathMatcher()
.extractPathWithinPattern(bestMatchPattern, fullPath);
// On renvoie toujours avec un "/" devant
return "/" + relativePath;
}
private String extractDecodedQuery(HttpServletRequest request) {
String rawQuery = request.getQueryString();
if (rawQuery != null) {
rawQuery = URLDecoder.decode(rawQuery, StandardCharsets.UTF_8);
}
return rawQuery;
}
// ---------- GET ----------
@GetMapping("/**")
public ResponseEntity<String> proxyGet(HttpServletRequest request) {
String path = extractPath(request);
String rawQuery = extractDecodedQuery(request);
ResponseEntity<String> prestaResponse =
prestashopClient.getWithRawQuery(path, rawQuery);
return ResponseEntity
.status(prestaResponse.getStatusCode())
.contentType(MediaType.APPLICATION_JSON)
.body(prestaResponse.getBody());
}
// ---------- POST ----------
@PostMapping("/**")
public ResponseEntity<String> proxyPost(HttpServletRequest request,
@RequestBody String xmlBody) {
String path = extractPath(request);
String rawQuery = extractDecodedQuery(request);
log.info("XML envoyé à Presta:\n{}", xmlBody);
ResponseEntity<String> prestaResponse =
prestashopClient.postWithRawQuery(path, rawQuery, xmlBody);
return ResponseEntity
.status(prestaResponse.getStatusCode())
.contentType(MediaType.APPLICATION_XML)
.body(prestaResponse.getBody());
}
// ---------- PUT ----------
@PutMapping("/**")
public ResponseEntity<String> proxyPut(HttpServletRequest request,
@RequestBody String xmlBody) {
String path = extractPath(request);
String rawQuery = extractDecodedQuery(request);
log.info("XML envoyé à Presta:\n{}", xmlBody);
ResponseEntity<String> prestaResponse =
prestashopClient.putWithRawQuery(path, rawQuery, xmlBody);
return ResponseEntity
.status(prestaResponse.getStatusCode())
.contentType(MediaType.APPLICATION_XML)
.body(prestaResponse.getBody());
}
// ---------- DELETE ----------
@DeleteMapping("/**")
public ResponseEntity<String> proxyDelete(HttpServletRequest request) {
String path = extractPath(request);
String rawQuery = extractDecodedQuery(request);
ResponseEntity<String> prestaResponse =
prestashopClient.deleteWithRawQuery(path, rawQuery);
return ResponseEntity
.status(prestaResponse.getStatusCode())
.contentType(MediaType.APPLICATION_XML)
.body(prestaResponse.getBody());
}
/**
* Upload d'une image produit :
* Front → (multipart/form-data) → /api/ps/images/products/{productId}
* Backend → (bytes) → https://shop.gameovergne.fr/api/images/products/{productId}
*/
@PostMapping(
path = "/images/products/{productId}",
consumes = MediaType.MULTIPART_FORM_DATA_VALUE,
produces = MediaType.APPLICATION_XML_VALUE
)
public ResponseEntity<String> uploadProductImage(
jakarta.servlet.http.HttpServletRequest request,
@PathVariable("productId") String productId,
@RequestPart("image") MultipartFile imageFile
) {
String rawQuery = request.getQueryString(); // si jamais tu ajoutes des options côté Presta
log.info("[Proxy] Upload image produit {} (size={} bytes, ct={})",
productId, imageFile.getSize(), imageFile.getContentType());
return prestashopClient.uploadProductImage(productId, rawQuery, imageFile);
}
}

View File

@@ -1,12 +0,0 @@
package fr.gameovergne.api.dto.ps;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class ProductFlagsDto {
boolean complete;
boolean hasManual;
String conditionLabel;
}

View File

@@ -1,16 +0,0 @@
package fr.gameovergne.api.dto.ps;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class ProductListItemDto {
Long id;
String name;
Long manufacturerId;
Long supplierId;
Long categoryId;
Double priceHt;
Integer quantity;
}

View File

@@ -1,12 +0,0 @@
package fr.gameovergne.api.dto.ps;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class PsItemDto {
Long id;
String name;
Boolean active;
}

View File

@@ -1,26 +0,0 @@
package fr.gameovergne.api.dto.ps;
import lombok.Builder;
import lombok.Value;
@Value
@Builder
public class PsProductDto {
Long id; // optionnel pour update
String name;
Long manufacturerId;
Long supplierId;
Long categoryId;
Double priceTtc;
Double vatRate;
Integer quantity;
Boolean complete; // Complet: Oui/Non
Boolean hasManual; // Notice: Avec/Sans
String conditionLabel; // État: libellé
String description; // description libre
}

View File

@@ -1,19 +0,0 @@
package fr.gameovergne.api.model.ps;
public enum SimpleResource {
categories("categories", "category", true, true),
manufacturers("manufacturers", "manufacturer", false, false),
suppliers("suppliers", "supplier", false, false);
public final String path;
public final String root;
public final boolean needsDefaultLang;
public final boolean nameIsMultilang;
SimpleResource(String path, String root, boolean needsDefaultLang, boolean nameIsMultilang) {
this.path = path;
this.root = root;
this.needsDefaultLang = needsDefaultLang;
this.nameIsMultilang = nameIsMultilang;
}
}

View File

@@ -1,149 +0,0 @@
// File: src/main/java/fr/gameovergne/api/service/PrestashopClient.java
package fr.gameovergne.api.service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClient;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
@Service
@Slf4j
public class PrestashopClient {
private final RestClient client;
private final String baseUrl;
public PrestashopClient(
@Value("${prestashop.base-url}") String baseUrl,
@Value("${prestashop.api-key}") String apiKey
) {
this.baseUrl = baseUrl;
String basicAuth = java.util.Base64.getEncoder()
.encodeToString((apiKey + ":").getBytes(StandardCharsets.UTF_8));
this.client = RestClient.builder()
.defaultHeader(HttpHeaders.AUTHORIZATION, "Basic " + basicAuth)
.build();
log.info("[PrestaShop] Base URL = {}", baseUrl);
log.info("[PrestaShop] API key length = {}", apiKey.length());
}
/**
* Construit lURL complète en encodant proprement les query params
* (y compris les crochets utilisés par PrestaShop : [id,name,...]).
*/
private String buildUri(String path, MultiValueMap<String, String> params) {
StringBuilder sb = new StringBuilder();
// baseUrl (ex: https://shop.gameovergne.fr/api)
sb.append(baseUrl);
// path (on gère proprement le /)
if (path != null && !path.isEmpty()) {
if (path.charAt(0) == '/') {
sb.append(path);
} else {
sb.append('/').append(path);
}
}
// query params
if (params != null && !params.isEmpty()) {
boolean first = true;
for (Map.Entry<String, List<String>> entry : params.entrySet()) {
String key = entry.getKey();
List<String> values = entry.getValue();
if (values == null || values.isEmpty()) {
continue;
}
// encode la clé
String encodedKey = URLEncoder.encode(key, StandardCharsets.UTF_8);
for (String rawValue : values) {
if (first) {
sb.append('?');
first = false;
} else {
sb.append('&');
}
// encode la valeur (crochets, %, espaces, etc.)
String encodedValue = rawValue == null
? ""
: URLEncoder.encode(rawValue, StandardCharsets.UTF_8);
sb.append(encodedKey)
.append('=')
.append(encodedValue);
}
}
}
String finalUri = sb.toString();
log.info("[PrestaShop] built URI = {}", finalUri);
return finalUri;
}
public String getJson(String path, MultiValueMap<String, String> params) {
String uri = buildUri(path, params);
log.info("[PrestaShop] GET JSON {}", uri);
return client.get()
.uri(uri)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.body(String.class);
}
public String getXml(String path, MultiValueMap<String, String> params) {
String uri = buildUri(path, params);
log.info("[PrestaShop] GET XML {}", uri);
return client.get()
.uri(uri)
.accept(MediaType.APPLICATION_XML)
.retrieve()
.body(String.class);
}
public String postXml(String path, MultiValueMap<String, String> params, String xmlBody) {
String uri = buildUri(path, params);
log.info("[PrestaShop] POST XML {}", uri);
return client.post()
.uri(uri)
.contentType(MediaType.APPLICATION_XML)
.body(xmlBody)
.retrieve()
.body(String.class);
}
public String putXml(String path, MultiValueMap<String, String> params, String xmlBody) {
String uri = buildUri(path, params);
log.info("[PrestaShop] PUT XML {}", uri);
return client.put()
.uri(uri)
.contentType(MediaType.APPLICATION_XML)
.body(xmlBody)
.retrieve()
.body(String.class);
}
public void delete(String path, MultiValueMap<String, String> params) {
String uri = buildUri(path, params);
log.info("[PrestaShop] DELETE {}", uri);
client.delete()
.uri(uri)
.retrieve()
.toBodilessEntity();
}
}

View File

@@ -0,0 +1,366 @@
package fr.gameovergne.api.service.prestashop;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
@Service
@Slf4j
public class PrestashopClient {
private static final MediaType APPLICATION_XML_UTF8 =
new MediaType("application", "xml", StandardCharsets.UTF_8);
private final RestClient client;
private final String baseUrl;
private final String basicAuthHeader;
public PrestashopClient(
@Value("${prestashop.base-url}") String baseUrl,
@Value("${prestashop.api-key}") String apiKey
) {
this.baseUrl = baseUrl;
String basicAuth = Base64.getEncoder()
.encodeToString((apiKey + ":").getBytes(StandardCharsets.UTF_8));
this.basicAuthHeader = "Basic " + basicAuth; // <--- mémorisé pour HttpURLConnection
this.client = RestClient.builder()
.defaultHeader(HttpHeaders.AUTHORIZATION, basicAuthHeader)
.build();
log.info("[PrestaShop] Base URL = {}", baseUrl);
log.info("[PrestaShop] API key length = {}", apiKey.length());
}
private String buildUri(String path, MultiValueMap<String, String> params) {
UriComponentsBuilder builder = UriComponentsBuilder
.fromHttpUrl(baseUrl + path);
if (params != null && !params.isEmpty()) {
builder.queryParams(params);
}
return builder.build(true).toUriString();
}
// -------- Méthodes "typed" JSON / XML utilisées par ps-admin --------
public String getJson(String path, MultiValueMap<String, String> params) {
String uri = buildUri(path, params);
log.info("[PrestaShop] GET JSON {}", uri);
return client.get()
.uri(uri)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.body(String.class);
}
public String getXml(String path, MultiValueMap<String, String> params) {
String uri = buildUri(path, params);
log.info("[PrestaShop] GET XML {}", uri);
return client.get()
.uri(uri)
.accept(MediaType.APPLICATION_XML)
.retrieve()
.body(String.class);
}
public String postXml(String path, MultiValueMap<String, String> params, String xmlBody) {
String uri = buildUri(path, params);
log.info("[PrestaShop] POST XML {}", uri);
byte[] bodyBytes = xmlBody.getBytes(StandardCharsets.UTF_8);
return client.post()
.uri(uri)
.contentType(APPLICATION_XML_UTF8)
.body(bodyBytes)
.retrieve()
.body(String.class);
}
public String putXml(String path, MultiValueMap<String, String> params, String xmlBody) {
String uri = buildUri(path, params);
log.info("[PrestaShop] PUT XML {}", uri);
byte[] bodyBytes = xmlBody.getBytes(StandardCharsets.UTF_8);
return client.put()
.uri(uri)
.contentType(APPLICATION_XML_UTF8)
.body(bodyBytes)
.retrieve()
.body(String.class);
}
public void delete(String path, MultiValueMap<String, String> params) {
String uri = buildUri(path, params);
log.info("[PrestaShop] DELETE {}", uri);
client.delete()
.uri(uri)
.retrieve()
.toBodilessEntity();
}
// -------- Méthodes génériques utilisées par le proxy /api/ps/** --------
public ResponseEntity<String> getWithRawQuery(String path, String rawQuery) {
String uri = baseUrl + path;
if (rawQuery != null && !rawQuery.isBlank()) {
uri = uri + "?" + rawQuery;
}
log.info("[PrestaShop] GET (proxy) {}", uri);
return client.get()
.uri(uri)
.accept(MediaType.APPLICATION_JSON)
.retrieve()
.toEntity(String.class);
}
public ResponseEntity<String> postWithRawQuery(String path, String rawQuery, String xmlBody) {
String uri = baseUrl + path;
if (rawQuery != null && !rawQuery.isBlank()) {
uri = uri + "?" + rawQuery;
}
log.info("[PrestaShop] POST (proxy) {}", uri);
log.info("[PrestaShop] XML envoyé (proxy POST):\n{}", xmlBody);
byte[] bodyBytes = xmlBody.getBytes(StandardCharsets.UTF_8);
try {
return client.post()
.uri(uri)
.contentType(APPLICATION_XML_UTF8)
.body(bodyBytes)
.retrieve()
.toEntity(String.class);
} catch (RestClientResponseException ex) {
// On propage tel quel le status + le body XML renvoyé par Presta
log.error("[PrestaShop] POST error {} : {}", ex.getRawStatusCode(), ex.getResponseBodyAsString());
return ResponseEntity
.status(ex.getRawStatusCode())
.contentType(MediaType.APPLICATION_XML)
.body(ex.getResponseBodyAsString());
} catch (RestClientException ex) {
// Cas réseau, timeout, etc.
log.error("[PrestaShop] POST technical error", ex);
return ResponseEntity
.status(502)
.contentType(MediaType.TEXT_PLAIN)
.body("Error while calling PrestaShop WebService");
}
}
public ResponseEntity<String> putWithRawQuery(String path, String rawQuery, String xmlBody) {
String uri = baseUrl + path;
if (rawQuery != null && !rawQuery.isBlank()) {
uri = uri + "?" + rawQuery;
}
log.info("[PrestaShop] PUT (proxy) {}", uri);
log.info("[PrestaShop] XML envoyé (proxy PUT):\n{}", xmlBody);
byte[] bodyBytes = xmlBody.getBytes(StandardCharsets.UTF_8);
try {
return client.put()
.uri(uri)
.contentType(APPLICATION_XML_UTF8)
.body(bodyBytes)
.retrieve()
.toEntity(String.class);
} catch (RestClientResponseException ex) {
// On propage tel quel le status + le body XML renvoyé par Presta
log.error("[PrestaShop] PUT error {} : {}", ex.getRawStatusCode(), ex.getResponseBodyAsString());
return ResponseEntity
.status(ex.getRawStatusCode())
.contentType(MediaType.APPLICATION_XML)
.body(ex.getResponseBodyAsString());
} catch (RestClientException ex) {
// Cas réseau, timeout, etc.
log.error("[PrestaShop] PUT technical error", ex);
return ResponseEntity
.status(502)
.contentType(MediaType.TEXT_PLAIN)
.body("Error while calling PrestaShop WebService");
}
}
public ResponseEntity<String> deleteWithRawQuery(String path, String rawQuery) {
String uri = baseUrl + path;
if (rawQuery != null && !rawQuery.isBlank()) {
uri = uri + "?" + rawQuery;
}
log.info("[PrestaShop] DELETE (proxy) {}", uri);
try {
return client.delete()
.uri(uri)
.retrieve()
.toEntity(String.class);
} catch (RestClientResponseException ex) {
// On propage tel quel le status + le body XML renvoyé par Presta
log.error("[PrestaShop] DELETE error {} : {}", ex.getRawStatusCode(), ex.getResponseBodyAsString());
return ResponseEntity
.status(ex.getRawStatusCode())
.contentType(MediaType.APPLICATION_XML)
.body(ex.getResponseBodyAsString());
} catch (RestClientException ex) {
// Cas réseau, timeout, etc.
log.error("[PrestaShop] DELETE technical error", ex);
return ResponseEntity
.status(502)
.contentType(MediaType.TEXT_PLAIN)
.body("Error while calling PrestaShop WebService");
}
}
/**
* Upload d'une image produit vers PrestaShop :
* POST /api/images/products/{productId}
*/
public ResponseEntity<String> uploadProductImage(
String productId,
String rawQuery,
MultipartFile imageFile
) {
try {
// Construire lURL Presta (comme avant)
StringBuilder urlBuilder = new StringBuilder(baseUrl)
.append("/images/products/")
.append(productId);
if (rawQuery != null && !rawQuery.isBlank()) {
urlBuilder.append('?').append(rawQuery);
}
String url = urlBuilder.toString();
byte[] fileBytes = imageFile.getBytes();
String originalFilename = imageFile.getOriginalFilename();
if (originalFilename == null || originalFilename.isBlank()) {
originalFilename = "image.jpg";
}
String contentType = imageFile.getContentType();
if (contentType == null || contentType.isBlank()) {
contentType = "application/octet-stream";
}
log.info(
"[PrestaShop] POST (image multipart - manual) {} (size={} bytes, contentType={}, filename={})",
url, fileBytes.length, contentType, originalFilename
);
// -------- Construction du multipart "à la main" --------
String boundary = "----PrestashopBoundary" + System.currentTimeMillis();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(baos, StandardCharsets.UTF_8);
PrintWriter writer = new PrintWriter(osw, true);
// Début de la part "image"
writer.append("--").append(boundary).append("\r\n");
writer.append("Content-Disposition: form-data; name=\"image\"; filename=\"")
.append(originalFilename)
.append("\"\r\n");
writer.append("Content-Type: ").append(contentType).append("\r\n");
writer.append("\r\n");
writer.flush();
// Données binaires du fichier
baos.write(fileBytes);
baos.write("\r\n".getBytes(StandardCharsets.UTF_8));
// Fin du multipart
writer.append("--").append(boundary).append("--").append("\r\n");
writer.flush();
byte[] multipartBytes = baos.toByteArray();
// -------- Envoi via HttpURLConnection --------
URL targetUrl = URI.create(url).toURL();
HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
conn.setRequestProperty("Accept", "application/xml, text/xml, */*;q=0.1");
conn.setRequestProperty("Authorization", basicAuthHeader);
// Important : pas de chunked, on envoie une taille fixe
conn.setFixedLengthStreamingMode(multipartBytes.length);
try (OutputStream os = conn.getOutputStream()) {
os.write(multipartBytes);
}
int status = conn.getResponseCode();
InputStream is = (status >= 200 && status < 300)
? conn.getInputStream()
: conn.getErrorStream();
String responseBody;
if (is != null) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
responseBody = sb.toString();
}
} else {
responseBody = "";
}
log.info("[PrestaShop] Image upload response status={}, body={}", status, responseBody);
// ---------- Mapping vers une réponse propre pour le front ----------
if (status >= 200 && status < 300) {
// Succès : on renvoie un petit JSON que Angular sait lire
return ResponseEntity
.ok()
.contentType(MediaType.APPLICATION_JSON)
.body("{\"success\":true}");
}
HttpStatus springStatus = HttpStatus.resolve(status);
if (springStatus == null) {
springStatus = HttpStatus.INTERNAL_SERVER_ERROR;
}
// En cas derreur Presta, on propage lXML pour debug
return ResponseEntity
.status(springStatus)
.contentType(MediaType.APPLICATION_XML)
.body(responseBody);
} catch (IOException e) {
log.error("[PrestaShop] Erreur lors de l'upload d'image", e);
return ResponseEntity
.status(HttpStatus.BAD_GATEWAY)
.contentType(MediaType.TEXT_PLAIN)
.body("Erreur lors de l'upload d'image vers PrestaShop");
}
}
}

View File

@@ -10,6 +10,9 @@ spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true
spring.servlet.multipart.max-file-size=15MB
spring.servlet.multipart.max-request-size=15MB
jwt.secret=a23ac96ce968bf13099d99410b951dd498118851bdfc996a3f844bd68b1b2afd
prestashop.base-url=https://shop.gameovergne.fr/api

View File

@@ -1,32 +1,41 @@
import {APP_INITIALIZER, ApplicationConfig, inject, provideZoneChangeDetection} from '@angular/core';
import {
APP_INITIALIZER,
ApplicationConfig,
inject,
provideZoneChangeDetection,
importProvidersFrom
} from '@angular/core';
import {provideRouter} from '@angular/router';
import {BrowserModule} from '@angular/platform-browser';
import {APP_BASE_HREF} from '@angular/common';
import {routes} from './app.routes';
import {provideHttpClient, withInterceptors} from '@angular/common/http';
import {provideAnimationsAsync} from '@angular/platform-browser/animations/async';
import {authTokenInterceptor} from './interceptors/auth-token.interceptor';
import {AuthService} from './services/auth.service';
import {catchError, firstValueFrom, of} from 'rxjs';
import {environment} from '../environments/environment';
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({eventCoalescing: true}),
importProvidersFrom(BrowserModule),
{provide: APP_BASE_HREF, useValue: environment.hrefBase},
provideRouter(routes),
provideAnimationsAsync(),
provideHttpClient(withInterceptors([
authTokenInterceptor
])
),
provideHttpClient(withInterceptors([authTokenInterceptor])),
{
provide: APP_INITIALIZER,
multi: true,
useFactory: () => {
const auth = inject(AuthService);
return () => firstValueFrom(auth.bootstrapSession().pipe(
catchError(err => of(null))
return () =>
firstValueFrom(
auth.bootstrapSession().pipe(
catchError(() => of(null))
)
);
}
}, provideAnimationsAsync()
}
]
};

View File

@@ -5,7 +5,7 @@ import {LoginComponent} from './pages/auth/login/login.component';
import {ProfileComponent} from './pages/profile/profile.component';
import {guestOnlyCanActivate, guestOnlyCanMatch} from './guards/guest-only.guard';
import {adminOnlyCanActivate, adminOnlyCanMatch} from './guards/admin-only.guard';
import {authOnlyCanMatch} from './guards/auth-only.guard';
import {authOnlyCanActivate, authOnlyCanMatch} from './guards/auth-only.guard';
import {PsAdminComponent} from './pages/admin/ps-admin/ps-admin.component';
import {ProductsComponent} from './pages/products/products.component';
@@ -40,13 +40,13 @@ export const routes: Routes = [
path: 'profile',
component: ProfileComponent,
canMatch: [authOnlyCanMatch],
canActivate: [authOnlyCanMatch]
canActivate: [authOnlyCanActivate]
},
{
path: 'products',
component: ProductsComponent,
canMatch: [authOnlyCanMatch],
canActivate: [authOnlyCanMatch]
canMatch: [adminOnlyCanMatch],
canActivate: [adminOnlyCanActivate]
},
{
path: 'admin',

View File

@@ -1,3 +1,16 @@
/* src/app/components/main-navbar/main-navbar.component.css */
/* Ajout prise en charge safe-area et meilleure gestion des overflow */
.mat-toolbar {
/* protège contre les zones sensibles (notch / status bar) */
padding-top: constant(safe-area-inset-top);
padding-top: env(safe-area-inset-top);
position: relative;
z-index: 1000;
box-sizing: border-box;
}
/* wrapper principal */
.container {
max-width: 1200px;
margin: 0 auto;
@@ -8,19 +21,22 @@
gap: 12px;
padding: 0 12px;
box-sizing: border-box;
min-height: 56px; /* assure une hauteur minimale utile sur mobile */
}
/* marque / titre */
.brand {
font-weight: bold;
font-size: 1.2rem;
cursor: pointer;
min-width: 0;
min-width: 0; /* autorise le shrink */
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1 1 auto;
}
/* actions (boutons, menu utilisateur) */
.nav-actions {
display: flex;
gap: 0.5rem;
@@ -28,16 +44,47 @@
flex: 0 1 auto;
justify-content: flex-end;
flex-wrap: nowrap;
min-width: 0; /* important pour permettre la réduction des enfants */
overflow: visible;
}
/* icône dans mat-menu */
.mat-menu-item mat-icon {
margin-right: 8px;
}
/* Empêcher les boutons de dépasser et couper le texte avec ellipsis */
.nav-actions button {
min-width: 0;
max-width: 100%;
display: inline-flex;
align-items: center;
gap: 8px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Angular Material place le texte dans .mat-button-wrapper — on le tronque proprement */
.nav-actions button .mat-button-wrapper {
display: inline-block;
max-width: calc(100% - 56px); /* espace pour icônes + padding */
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
vertical-align: middle;
}
/* Ajustements spécifiques pour petits écrans */
@media (max-width: 720px) {
.mat-toolbar {
padding-top: env(safe-area-inset-top);
}
.container {
flex-wrap: wrap;
align-items: center;
justify-content: center;
padding: 8px;
}
@@ -55,6 +102,7 @@
gap: 8px;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
padding-bottom: 4px; /* espace pour le scroll horizontal */
}
.nav-actions button {
@@ -62,6 +110,11 @@
font-size: 0.95rem;
min-width: 0;
white-space: nowrap;
max-width: 100%;
}
.nav-actions button .mat-button-wrapper {
max-width: calc(100% - 40px);
}
.nav-actions mat-icon {

View File

@@ -47,6 +47,21 @@ th, td {
flex-shrink: 0;
}
.product-list-root {
position: relative;
}
.product-list-loading-overlay {
position: absolute;
inset: 0;
background: rgba(255, 255, 255, 0.6);
display: flex;
align-items: center;
justify-content: center;
z-index: 10;
pointer-events: all;
}
mat-paginator {
width: 100%;
overflow: hidden;

View File

@@ -1,16 +1,27 @@
<section class="crud">
<div class="toolbar">
<button mat-raised-button color="primary" (click)="create()">
<button mat-raised-button
color="primary"
(click)="create()"
[disabled]="isLoading">
<mat-icon>add</mat-icon>&nbsp;Nouveau produit
</button>
<mat-form-field appearance="outline" class="filter">
<mat-label>Filtrer</mat-label>
<input matInput [formControl]="filterCtrl" placeholder="Nom, ID, catégorie, marque, fournisseur…">
<input matInput
[formControl]="filterCtrl"
placeholder="Nom, ID, catégorie, marque, fournisseur…"
[disabled]="isLoading">
</mat-form-field>
</div>
<div class="mat-elevation-z2">
<div class="mat-elevation-z2 product-list-root">
<!-- Overlay de chargement -->
<div class="product-list-loading-overlay" *ngIf="isLoading">
<mat-spinner diameter="48"></mat-spinner>
</div>
<table mat-table [dataSource]="dataSource" matSort>
<ng-container matColumnDef="id">
@@ -51,8 +62,19 @@
<ng-container matColumnDef="actions">
<th mat-header-cell *matHeaderCellDef>Actions</th>
<td mat-cell *matCellDef="let el">
<button mat-icon-button (click)="edit(el)" aria-label="edit"><mat-icon>edit</mat-icon></button>
<button mat-icon-button color="warn" (click)="remove(el)" aria-label="delete"><mat-icon>delete</mat-icon></button>
<button mat-icon-button
aria-label="edit"
(click)="edit(el)"
[disabled]="isLoading">
<mat-icon>edit</mat-icon>
</button>
<button mat-icon-button
color="warn"
aria-label="delete"
(click)="remove(el)"
[disabled]="isLoading">
<mat-icon>delete</mat-icon>
</button>
</td>
</ng-container>
@@ -60,10 +82,17 @@
<tr mat-row *matRowDef="let row; columns: displayed;"></tr>
<tr class="mat-row" *matNoDataRow>
<td class="mat-cell" [attr.colspan]="displayed.length">Aucune donnée.</td>
<td class="mat-cell" [attr.colspan]="displayed.length">
Aucune donnée.
</td>
</tr>
</table>
<mat-paginator [pageSizeOptions]="[5,10,25,100]" [pageSize]="10" aria-label="Pagination"></mat-paginator>
<mat-paginator
[pageSizeOptions]="[5,10,25,100]"
[pageSize]="10"
aria-label="Pagination"
[disabled]="isLoading">
</mat-paginator>
</div>
</section>

View File

@@ -13,7 +13,8 @@ import {MatButton, MatIconButton} from '@angular/material/button';
import {MatIcon} from '@angular/material/icon';
import {FormBuilder, ReactiveFormsModule} from '@angular/forms';
import {MatDialog, MatDialogModule} from '@angular/material/dialog';
import {forkJoin} from 'rxjs';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import {forkJoin, finalize} from 'rxjs';
import {PsItem} from '../../interfaces/ps-item';
import {ProductListItem} from '../../interfaces/product-list-item';
@@ -32,7 +33,8 @@ import {ProductDialogData, PsProductDialogComponent} from '../ps-product-dialog/
MatSortModule, MatPaginatorModule,
MatFormField, MatLabel, MatInput,
MatButton, MatIconButton, MatIcon,
MatDialogModule
MatDialogModule,
MatProgressSpinnerModule
]
})
export class PsProductCrudComponent implements OnInit {
@@ -40,26 +42,24 @@ export class PsProductCrudComponent implements OnInit {
private readonly ps = inject(PrestashopService);
private readonly dialog = inject(MatDialog);
// référentiels
categories: PsItem[] = [];
manufacturers: PsItem[] = [];
suppliers: PsItem[] = [];
// maps daffichage
private catMap = new Map<number, string>();
private manMap = new Map<number, string>();
private supMap = new Map<number, string>();
// table
displayed: string[] = ['id', 'name', 'category', 'manufacturer', 'supplier', 'priceTtc', 'quantity', 'actions'];
dataSource = new MatTableDataSource<any>([]);
@ViewChild(MatPaginator) paginator!: MatPaginator;
@ViewChild(MatSort) sort!: MatSort;
@ViewChild(MatTable) table!: MatTable<any>;
// filtre
filterCtrl = this.fb.control<string>('');
isLoading = false;
ngOnInit(): void {
forkJoin({
cats: this.ps.list('categories'),
@@ -73,6 +73,7 @@ export class PsProductCrudComponent implements OnInit {
this.manMap = new Map(this.manufacturers.map(x => [x.id, x.name]));
this.suppliers = sups ?? [];
this.supMap = new Map(this.suppliers.map(x => [x.id, x.name]));
this.reload();
},
error: err => {
@@ -80,7 +81,6 @@ export class PsProductCrudComponent implements OnInit {
}
});
// filtre client
this.filterCtrl.valueChanges.subscribe(v => {
this.dataSource.filter = (v ?? '').toString().trim().toLowerCase();
if (this.paginator) this.paginator.firstPage();
@@ -133,10 +133,24 @@ export class PsProductCrudComponent implements OnInit {
}
reload() {
this.ps.listProducts().subscribe(p => this.bindProducts(p));
this.isLoading = true;
this.ps.listProducts()
.pipe(
finalize(() => {
this.isLoading = false;
})
)
.subscribe({
next: p => this.bindProducts(p),
error: err => {
console.error('Erreur lors du chargement des produits', err);
}
});
}
create() {
if (this.isLoading) return;
const data: ProductDialogData = {
mode: 'create',
refs: {
@@ -145,12 +159,16 @@ export class PsProductCrudComponent implements OnInit {
suppliers: this.suppliers
}
};
this.dialog.open(PsProductDialogComponent, {width: '900px', data}).afterClosed().subscribe(ok => {
this.dialog.open(PsProductDialogComponent, {width: '900px', data})
.afterClosed()
.subscribe(ok => {
if (ok) this.reload();
});
}
edit(row: ProductListItem & { priceHt?: number }) {
if (this.isLoading) return;
const data: ProductDialogData = {
mode: 'edit',
productRow: row,
@@ -160,16 +178,29 @@ export class PsProductCrudComponent implements OnInit {
suppliers: this.suppliers
}
};
this.dialog.open(PsProductDialogComponent, {width: '900px', data}).afterClosed().subscribe(ok => {
this.dialog.open(PsProductDialogComponent, {width: '900px', data})
.afterClosed()
.subscribe(ok => {
if (ok) this.reload();
});
}
remove(row: ProductListItem) {
if (this.isLoading) return;
if (!confirm(`Supprimer le produit "${row.name}" (#${row.id}) ?`)) return;
this.ps.deleteProduct(row.id).subscribe({
this.isLoading = true;
this.ps.deleteProduct(row.id)
.pipe(
finalize(() => {
})
)
.subscribe({
next: () => this.reload(),
error: (e: unknown) => alert('Erreur: ' + (e instanceof Error ? e.message : String(e)))
error: (e: unknown) => {
this.isLoading = false;
alert('Erreur: ' + (e instanceof Error ? e.message : String(e)));
}
});
}
}

View File

@@ -76,6 +76,24 @@
font-size: 40px;
}
/* Bouton de suppression (croix rouge) */
.carousel-delete-btn {
position: absolute;
top: 6px;
right: 6px;
background: rgba(255, 255, 255, 0.9);
border-radius: 4px;
padding: 2px;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.25);
}
.carousel-delete-btn mat-icon {
font-size: 20px;
width: 20px;
height: 20px;
color: #e53935;
}
/* Bandeau de vignettes */
.carousel-thumbs {
@@ -85,15 +103,42 @@
}
.thumb-item {
position: relative;
width: 64px;
height: 64px;
border-radius: 4px;
overflow: hidden;
overflow: hidden; /* tu peux laisser comme ça */
border: 2px solid transparent;
flex: 0 0 auto;
cursor: pointer;
}
/* Bouton de suppression sur les vignettes */
.thumb-delete-btn {
position: absolute;
top: 2px;
right: 2px;
width: 18px;
height: 18px;
min-width: 18px;
padding: 0;
line-height: 18px;
background: transparent;
border-radius: 0;
box-shadow: none;
}
.thumb-delete-btn mat-icon {
font-size: 16px;
width: 16px;
height: 16px;
color: #e53935; /* rouge discret mais lisible */
}
.thumb-item.active {
border-color: #1976d2;
}
@@ -118,3 +163,19 @@
.thumb-placeholder mat-icon {
font-size: 28px;
}
.dialog-root {
position: relative;
}
/* Overlay plein écran dans le dialog pendant la sauvegarde */
.dialog-loading-overlay {
position: absolute;
inset: 0;
background: rgba(255, 255, 255, 0.6);
display: flex;
align-items: center;
justify-content: center;
z-index: 50;
pointer-events: all;
}

View File

@@ -1,5 +1,13 @@
<h2 mat-dialog-title>{{ mode === 'create' ? 'Nouveau produit' : 'Modifier le produit' }}</h2>
<div class="dialog-root">
<!-- Overlay de chargement -->
@if (isSaving) {
<div class="dialog-loading-overlay">
<mat-spinner diameter="48"></mat-spinner>
</div>
}
<div mat-dialog-content class="grid" [formGroup]="form">
<!-- CARROUSEL IMAGES -->
@@ -31,6 +39,23 @@
[disabled]="carouselItems.length <= 1">
<mat-icon>chevron_right</mat-icon>
</button>
<!-- Bouton de suppression (croix rouge) -->
@if (carouselItems.length && !carouselItems[currentIndex].isPlaceholder) {
<button mat-icon-button
class="carousel-delete-btn"
(click)="onDeleteCurrentImage()">
<mat-icon>delete</mat-icon>
</button>
}
<!-- Bouton suivant -->
<button mat-icon-button
class="carousel-nav-btn right"
(click)="next()"
[disabled]="carouselItems.length <= 1">
<mat-icon>chevron_right</mat-icon>
</button>
</div>
<!-- Bandeau de vignettes -->
@@ -40,6 +65,14 @@
[class.active]="i === currentIndex"
(click)="onThumbClick(i)">
@if (!item.isPlaceholder) {
<!-- Bouton suppression vignette -->
<button mat-icon-button
class="thumb-delete-btn"
(click)="onDeleteThumb(i, $event)">
<mat-icon>close</mat-icon>
</button>
<img class="thumb-img" [src]="item.src" alt="Vignette produit">
} @else {
<div class="thumb-placeholder" (click)="fileInput.click()">
@@ -127,11 +160,24 @@
<input matInput type="number" step="1" min="0" formControlName="quantity">
</mat-form-field>
</div>
</div>
<!-- Actions -->
<div mat-dialog-actions>
<button mat-button (click)="close()">Annuler</button>
<button mat-raised-button color="primary" (click)="save()" [disabled]="form.invalid">
{{ mode === 'create' ? 'Créer' : 'Enregistrer' }}
<mat-dialog-actions align="end">
<button mat-button
(click)="close()"
[disabled]="isSaving">
Annuler
</button>
</div>
<button mat-raised-button
color="primary"
(click)="save()"
[disabled]="form.invalid || isSaving">
@if (!isSaving) {
Enregistrer
} @else {
Enregistrement...
}
</button>
</mat-dialog-actions>

View File

@@ -1,4 +1,3 @@
// File: src/app/components/ps-product-dialog/ps-product-dialog.component.ts
import {Component, Inject, OnInit, inject, OnDestroy} from '@angular/core';
import {CommonModule} from '@angular/common';
import {FormBuilder, ReactiveFormsModule, Validators} from '@angular/forms';
@@ -16,12 +15,12 @@ import {
} from '@angular/material/dialog';
import {MatIcon} from '@angular/material/icon';
import { catchError, forkJoin, of, Observable } from 'rxjs';
import {catchError, forkJoin, of, Observable, finalize} from 'rxjs';
import {PsItem} from '../../interfaces/ps-item';
import {ProductListItem} from '../../interfaces/product-list-item';
import {PrestashopService} from '../../services/prestashop.serivce';
import { PsProduct } from '../../interfaces/ps-product'; // si tu as une interface dédiée
import {MatProgressSpinner} from '@angular/material/progress-spinner';
export type ProductDialogData = {
mode: 'create' | 'edit';
@@ -40,7 +39,7 @@ type CarouselItem = { src: string; isPlaceholder: boolean };
CommonModule, ReactiveFormsModule,
MatFormField, MatLabel, MatInput, MatSelectModule, MatCheckbox,
MatButton, MatDialogActions, MatDialogContent, MatDialogTitle,
MatIcon, MatIconButton
MatIcon, MatIconButton, MatProgressSpinner
]
})
export class PsProductDialogComponent implements OnInit, OnDestroy {
@@ -50,7 +49,10 @@ export class PsProductDialogComponent implements OnInit, OnDestroy {
constructor(
@Inject(MAT_DIALOG_DATA) public data: ProductDialogData,
private readonly dialogRef: MatDialogRef<PsProductDialogComponent>
) {}
) {
}
isSaving = false;
mode!: 'create' | 'edit';
categories: PsItem[] = [];
@@ -89,7 +91,6 @@ export class PsProductDialogComponent implements OnInit, OnDestroy {
// ---------- Helpers locaux ----------
// utilisé seulement pour pré-afficher un TTC approximatif à partir du HT de la liste
private toTtc(ht: number) {
return Math.round(((ht * 1.2) + Number.EPSILON) * 100) / 100;
}
@@ -151,7 +152,6 @@ export class PsProductDialogComponent implements OnInit, OnDestroy {
if (this.mode === 'edit' && this.productRow) {
const r = this.productRow;
// pré-remplissage rapide avec la ligne de liste (HT -> TTC approximatif)
const immediateTtc = r.priceHt == null ? 0 : this.toTtc(r.priceHt);
this.form.patchValue({
name: r.name,
@@ -162,7 +162,11 @@ export class PsProductDialogComponent implements OnInit, OnDestroy {
});
const details$ = this.ps.getProductDetails(r.id).pipe(
catchError(() => of<PsProduct | null>(null))
catchError(() => of({
id: r.id, name: r.name, description: '',
id_manufacturer: r.id_manufacturer, id_supplier: r.id_supplier,
id_category_default: r.id_category_default, priceHt: r.priceHt ?? 0
}))
);
const qty$ = this.ps.getProductQuantity(r.id).pipe(catchError(() => of(0)));
const imgs$ = this.ps.getProductImageUrls(r.id).pipe(catchError(() => of<string[]>([])));
@@ -172,23 +176,20 @@ export class PsProductDialogComponent implements OnInit, OnDestroy {
forkJoin({details: details$, qty: qty$, imgs: imgs$, flags: flags$})
.subscribe(({details, qty, imgs, flags}) => {
const baseDesc = this.cleanForTextarea(details?.description ?? '');
const ttc = this.toTtc(details.priceHt ?? 0);
const baseDesc = this.cleanForTextarea(details.description ?? '');
this.lastLoadedDescription = baseDesc;
this.form.patchValue({
// description depuis le backend (déjà propre / nettoyée normalement)
description: baseDesc,
// flags
complete: flags.complete,
hasManual: flags.hasManual,
conditionLabel: flags.conditionLabel || '',
// TTC "réel" calculé par le backend (si dispo) sinon on garde la valeur actuelle
priceTtc: (details?.priceTtc ?? this.form.value.priceTtc ?? 0),
priceTtc: (ttc || this.form.value.priceTtc || 0),
quantity: qty,
// ids de ref issus du DTO backend
categoryId: (details?.categoryId ?? this.form.value.categoryId) ?? null,
manufacturerId: (details?.manufacturerId ?? this.form.value.manufacturerId) ?? null,
supplierId: (details?.supplierId ?? this.form.value.supplierId) ?? null
categoryId: (details.id_category_default ?? this.form.value.categoryId) ?? null,
manufacturerId: (details.id_manufacturer ?? this.form.value.manufacturerId) ?? null,
supplierId: (details.id_supplier ?? this.form.value.supplierId) ?? null
});
this.existingImageUrls = imgs;
@@ -267,18 +268,21 @@ export class PsProductDialogComponent implements OnInit, OnDestroy {
// -------- Save / close --------
save() {
if (this.form.invalid) return;
if (this.form.invalid || this.isSaving) return;
this.isSaving = true;
this.dialogRef.disableClose = true;
const v = this.form.getRawValue();
const effectiveDescription = (v.description ?? '').trim() || this.lastLoadedDescription;
const dto: PsProduct = {
const dto = {
name: v.name!,
description: effectiveDescription,
categoryId: +v.categoryId!,
manufacturerId: +v.manufacturerId!,
supplierId: +v.supplierId!,
images: this.images, // toujours les fichiers sélectionnés
images: this.images,
complete: !!v.complete,
hasManual: !!v.hasManual,
conditionLabel: v.conditionLabel || undefined,
@@ -294,13 +298,99 @@ export class PsProductDialogComponent implements OnInit, OnDestroy {
op$ = this.ps.updateProduct(this.productRow.id, dto) as Observable<unknown>;
}
op$.subscribe({
op$
.pipe(
finalize(() => {
// si la boîte de dialogue est encore ouverte, on réactive tout
this.isSaving = false;
this.dialogRef.disableClose = false;
})
)
.subscribe({
next: () => this.dialogRef.close(true),
error: (e: unknown) => alert('Erreur: ' + (e instanceof Error ? e.message : String(e)))
error: (e: unknown) =>
alert('Erreur: ' + (e instanceof Error ? e.message : String(e)))
});
}
/** Extrait l'id_image depuis une URL FO Presta (.../img/p/.../<id>.jpg) */
private extractImageIdFromUrl(url: string): number | null {
const m = /\/(\d+)\.(?:jpg|jpeg|png|gif)$/i.exec(url);
if (!m) return null;
const id = Number(m[1]);
return Number.isFinite(id) ? id : null;
}
/** Suppression générique d'une image à l'index donné (carrousel + vignettes) */
private deleteImageAtIndex(idx: number) {
if (!this.carouselItems.length) return;
const item = this.carouselItems[idx];
if (!item || item.isPlaceholder) return;
const existingCount = this.existingImageUrls.length;
// --- Cas 1 : image existante (déjà chez Presta) ---
if (idx < existingCount) {
if (!this.productRow) return; // sécurité
const url = this.existingImageUrls[idx];
const imageId = this.extractImageIdFromUrl(url);
if (!imageId) {
alert('Impossible de déterminer lID de limage à supprimer.');
return;
}
if (!confirm('Supprimer cette image du produit ?')) return;
this.ps.deleteProductImage(this.productRow.id, imageId).subscribe({
next: () => {
// On la retire du tableau local et on reconstruit le carrousel
this.existingImageUrls.splice(idx, 1);
this.buildCarousel();
// Repositionnement de lindex si nécessaire
if (this.currentIndex >= this.carouselItems.length - 1) {
this.currentIndex = Math.max(0, this.carouselItems.length - 2);
}
},
error: (e: unknown) => {
alert('Erreur lors de la suppression de limage : ' + (e instanceof Error ? e.message : String(e)));
}
});
return;
}
// --- Cas 2 : image locale (nouvelle) ---
const localIdx = idx - existingCount;
if (localIdx >= 0 && localIdx < this.previewUrls.length) {
if (!confirm('Retirer cette image de la sélection ?')) return;
this.previewUrls.splice(localIdx, 1);
this.images.splice(localIdx, 1);
this.buildCarousel();
if (this.currentIndex >= this.carouselItems.length - 1) {
this.currentIndex = Math.max(0, this.carouselItems.length - 2);
}
}
}
// utilisée par la grande image
onDeleteCurrentImage() {
if (!this.carouselItems.length) return;
this.deleteImageAtIndex(this.currentIndex);
}
// utilisée par la croix sur une vignette
onDeleteThumb(index: number, event: MouseEvent) {
event.stopPropagation();
this.deleteImageAtIndex(index);
}
close() {
if (this.isSaving) return;
this.dialogRef.close(false);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,45 @@
export function resizeImage(
file: File,
maxWidth = 1600,
maxHeight = 1600,
quality = 0.8
): Promise<File> {
return new Promise((resolve, reject) => {
const img = new Image();
const reader = new FileReader();
reader.onload = e => {
if (!e.target?.result) return reject('Cannot load file');
img.onload = () => {
let { width, height } = img;
const ratio = Math.min(maxWidth / width, maxHeight / height, 1);
const newW = Math.round(width * ratio);
const newH = Math.round(height * ratio);
const canvas = document.createElement('canvas');
canvas.width = newW;
canvas.height = newH;
const ctx = canvas.getContext('2d');
if (!ctx) return reject('Cannot get canvas context');
ctx.drawImage(img, 0, 0, newW, newH);
canvas.toBlob(
blob => {
if (!blob) return reject('Compression failed');
resolve(new File([blob], file.name.replace(/\.[^.]+$/, '.jpg'), { type: 'image/jpeg' }));
},
'image/jpeg',
quality
);
};
img.src = e.target.result as string;
};
reader.readAsDataURL(file);
});
}

View File

@@ -2,4 +2,5 @@ export const environment = {
production: true,
apiUrl: '/gameovergne-api/api',
psUrl: '/gameovergne-api/api/ps',
hrefBase: '/gameovergne/',
};

View File

@@ -2,4 +2,5 @@ export const environment = {
production: false,
apiUrl: 'http://localhost:3000/api',
psUrl: '/ps',
hrefBase: '/',
};

View File

@@ -1,5 +1,4 @@
version: "3.9"
# docker-compose.dev.yml
services:
mysql:
image: mysql:8.4
@@ -9,11 +8,10 @@ services:
MYSQL_DATABASE: gameovergne_app
MYSQL_USER: gameovergne
MYSQL_PASSWORD: gameovergne
# 🔒 Persistant + accessible depuis l'extérieur
volumes:
- ./mysql-data:/var/lib/mysql
ports:
- "3366:3306" # pour te connecter depuis ton Mac / un client SQL
- "3366:3306"
networks:
- gameovergne
restart: unless-stopped
@@ -35,16 +33,14 @@ services:
SPRING_DATASOURCE_PASSWORD: gameovergne
PRESTASHOP_API_KEY: 2AQPG13MJ8X117U6FJ5NGHPS93HE34AB
SERVER_PORT: 3000
# pense bien à avoir prestashop.base-url / prestashop.basic-auth dans application.properties ou via env si besoin
networks:
- gameovergne
- traefik
- gameovergne
restart: unless-stopped
labels:
- traefik.enable=true
- traefik.docker.network=traefik
# API sous /gameovergne-api
- traefik.http.routers.gameovergne-api.rule=Host(`dev.vincent-guillet.fr`) && PathPrefix(`/gameovergne-api`)
- traefik.http.routers.gameovergne-api.entrypoints=edge
- traefik.http.routers.gameovergne-api.service=gameovergne-api
@@ -65,24 +61,19 @@ services:
- traefik.enable=true
- traefik.docker.network=traefik
# FRONT sous /gameovergne (avec et sans slash final)
- traefik.http.routers.gameovergne-client.rule=Host(`dev.vincent-guillet.fr`) && (Path(`/gameovergne`) || PathPrefix(`/gameovergne/`))
- traefik.http.routers.gameovergne-client.entrypoints=edge
- traefik.http.routers.gameovergne-client.service=gameovergne-client
- traefik.http.routers.gameovergne-client.middlewares=gameovergne-slash,gameovergne-client-stripprefix
# Redirige /gameovergne vers /gameovergne/
- traefik.http.middlewares.gameovergne-slash.redirectregex.regex=^https?://([^/]+)/gameovergne$$
- traefik.http.middlewares.gameovergne-slash.redirectregex.replacement=https://$${1}/gameovergne/
- traefik.http.middlewares.gameovergne-slash.redirectregex.permanent=true
# Enlève /gameovergne avant d'envoyer vers Nginx (le conteneur Angular)
- traefik.http.middlewares.gameovergne-client-stripprefix.stripprefix.prefixes=/gameovergne
# Service vers Nginx (port 80 dans le conteneur)
- traefik.http.services.gameovergne-client.loadbalancer.server.port=80
# Proxy Presta via /gameovergne/ps -> même service, même StripPrefix
- traefik.http.routers.gameovergne-ps.rule=Host(`dev.vincent-guillet.fr`) && PathPrefix(`/gameovergne/ps`)
- traefik.http.routers.gameovergne-ps.entrypoints=edge
- traefik.http.routers.gameovergne-ps.service=gameovergne-client
@@ -92,4 +83,4 @@ networks:
traefik:
external: true
gameovergne:
driver: bridge
external: true

86
docker-compose.prod.yml Normal file
View File

@@ -0,0 +1,86 @@
# docker-compose.prod.yml
services:
mysql:
image: mysql:8.4
container_name: gameovergne-mysql-prod
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: gameovergne_app
MYSQL_USER: gameovergne
MYSQL_PASSWORD: gameovergne
volumes:
- ./mysql-data-prod:/var/lib/mysql
ports:
- "3366:3306"
networks:
- gameovergne
restart: unless-stopped
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-u", "root", "-proot"]
interval: 10s
timeout: 5s
retries: 10
spring:
image: registry.vincent-guillet.fr/gameovergne-api:prod-latest
container_name: gameovergne-api-prod
depends_on:
mysql:
condition: service_healthy
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://mysql:3306/gameovergne_app?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
SPRING_DATASOURCE_USERNAME: gameovergne
SPRING_DATASOURCE_PASSWORD: gameovergne
PRESTASHOP_API_KEY: 2AQPG13MJ8X117U6FJ5NGHPS93HE34AB
SERVER_PORT: 3000
networks:
- traefik
- gameovergne
restart: unless-stopped
labels:
- traefik.enable=true
- traefik.docker.network=traefik
- traefik.http.routers.gameovergne-api.rule=Host(`projets.vincent-guillet.fr`) && PathPrefix(`/gameovergne-api`)
- traefik.http.routers.gameovergne-api.entrypoints=edge
- traefik.http.routers.gameovergne-api.service=gameovergne-api
- traefik.http.services.gameovergne-api.loadbalancer.server.port=3000
- traefik.http.routers.gameovergne-api.middlewares=gameovergne-api-stripprefix
- traefik.http.middlewares.gameovergne-api-stripprefix.stripprefix.prefixes=/gameovergne-api
angular:
image: registry.vincent-guillet.fr/gameovergne-client:prod-latest
container_name: gameovergne-client-prod
depends_on:
- spring
networks:
- gameovergne
- traefik
restart: unless-stopped
labels:
- traefik.enable=true
- traefik.docker.network=traefik
- traefik.http.routers.gameovergne-client.rule=Host(`projets.vincent-guillet.fr`) && (Path(`/gameovergne`) || PathPrefix(`/gameovergne/`))
- traefik.http.routers.gameovergne-client.entrypoints=edge
- traefik.http.routers.gameovergne-client.service=gameovergne-client
- traefik.http.routers.gameovergne-client.middlewares=gameovergne-slash,gameovergne-client-stripprefix
- traefik.http.middlewares.gameovergne-slash.redirectregex.regex=^https?://([^/]+)/gameovergne$$
- traefik.http.middlewares.gameovergne-slash.redirectregex.replacement=https://$${1}/gameovergne/
- traefik.http.middlewares.gameovergne-slash.redirectregex.permanent=true
- traefik.http.middlewares.gameovergne-client-stripprefix.stripprefix.prefixes=/gameovergne
- traefik.http.services.gameovergne-client.loadbalancer.server.port=80
- traefik.http.routers.gameovergne-ps.rule=Host(`projets.vincent-guillet.fr`) && PathPrefix(`/gameovergne/ps`)
- traefik.http.routers.gameovergne-ps.entrypoints=edge
- traefik.http.routers.gameovergne-ps.service=gameovergne-client
- traefik.http.routers.gameovergne-ps.middlewares=gameovergne-client-stripprefix
networks:
traefik:
external: true
gameovergne:
external: true

85
docker-compose.yml.OLD Normal file
View File

@@ -0,0 +1,85 @@
services:
mysql:
image: mysql:8.4
container_name: gameovergne-mysql
environment:
MYSQL_ROOT_PASSWORD: root
MYSQL_DATABASE: gameovergne_app
MYSQL_USER: gameovergne
MYSQL_PASSWORD: gameovergne
volumes:
- ./mysql-data:/var/lib/mysql
ports:
- "3366:3306"
networks:
- gameovergne
restart: unless-stopped
healthcheck:
test: ["CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-u", "root", "-proot"]
interval: 10s
timeout: 5s
retries: 10
spring:
image: registry.vincent-guillet.fr/gameovergne-api:dev-latest
container_name: gameovergne-api
depends_on:
mysql:
condition: service_healthy
environment:
SPRING_DATASOURCE_URL: jdbc:mysql://mysql:3306/gameovergne_app?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC
SPRING_DATASOURCE_USERNAME: gameovergne
SPRING_DATASOURCE_PASSWORD: gameovergne
PRESTASHOP_API_KEY: 2AQPG13MJ8X117U6FJ5NGHPS93HE34AB
SERVER_PORT: 3000
networks:
- traefik
- gameovergne
restart: unless-stopped
labels:
- traefik.enable=true
- traefik.docker.network=traefik
- traefik.http.routers.gameovergne-api.rule=Host(`dev.vincent-guillet.fr`) && PathPrefix(`/gameovergne-api`)
- traefik.http.routers.gameovergne-api.entrypoints=edge
- traefik.http.routers.gameovergne-api.service=gameovergne-api
- traefik.http.services.gameovergne-api.loadbalancer.server.port=3000
- traefik.http.routers.gameovergne-api.middlewares=gameovergne-api-stripprefix
- traefik.http.middlewares.gameovergne-api-stripprefix.stripprefix.prefixes=/gameovergne-api
angular:
image: registry.vincent-guillet.fr/gameovergne-client:dev-latest
container_name: gameovergne-client
depends_on:
- spring
networks:
- gameovergne
- traefik
restart: unless-stopped
labels:
- traefik.enable=true
- traefik.docker.network=traefik
- traefik.http.routers.gameovergne-client.rule=Host(`dev.vincent-guillet.fr`) && (Path(`/gameovergne`) || PathPrefix(`/gameovergne/`))
- traefik.http.routers.gameovergne-client.entrypoints=edge
- traefik.http.routers.gameovergne-client.service=gameovergne-client
- traefik.http.routers.gameovergne-client.middlewares=gameovergne-slash,gameovergne-client-stripprefix
- traefik.http.middlewares.gameovergne-slash.redirectregex.regex=^https?://([^/]+)/gameovergne$$
- traefik.http.middlewares.gameovergne-slash.redirectregex.replacement=https://$${1}/gameovergne/
- traefik.http.middlewares.gameovergne-slash.redirectregex.permanent=true
- traefik.http.middlewares.gameovergne-client-stripprefix.stripprefix.prefixes=/gameovergne
- traefik.http.services.gameovergne-client.loadbalancer.server.port=80
- traefik.http.routers.gameovergne-ps.rule=Host(`dev.vincent-guillet.fr`) && PathPrefix(`/gameovergne/ps`)
- traefik.http.routers.gameovergne-ps.entrypoints=edge
- traefik.http.routers.gameovergne-ps.service=gameovergne-client
- traefik.http.routers.gameovergne-ps.middlewares=gameovergne-client-stripprefix
networks:
traefik:
external: true
gameovergne:
external: true

View File

@@ -1,72 +1,119 @@
pipeline {
agent any
tools {
maven 'mvn'
nodejs 'npm'
}
agent none
environment {
JAVA_HOME = '/opt/java/openjdk'
PATH = "${JAVA_HOME}/bin:${env.PATH}"
SPRING_IMAGE_NAME = 'spring-jenkins'
ANGULAR_IMAGE_NAME = 'angular-jenkins'
IMAGE_TAG = 'latest'
REGISTRY = 'registry.vincent-guillet.fr'
API_IMAGE_DEV = "${REGISTRY}/gameovergne-api:dev-latest"
CLIENT_IMAGE_DEV = "${REGISTRY}/gameovergne-client:dev-latest"
API_IMAGE_PROD = "${REGISTRY}/gameovergne-api:prod-latest"
CLIENT_IMAGE_PROD = "${REGISTRY}/gameovergne-client:prod-latest"
COMPOSE_PROJECT = 'gameovergne-app'
}
stages {
stage('Checkout sur la branche dev') {
// Build & push images (toujours sur ct-home-dev)
stage('Build & Push Docker Images') {
agent { label 'ct-home-dev' }
steps {
git branch: 'dev', url: 'https://gitea.vincent-guillet.fr/vincentguillet/gameovergne-app.git'
// Multi-branch friendly : Jenkins fait le checkout de la branche courante
checkout scm
script {
// Choix des tags selon la branche
if (env.BRANCH_NAME == 'main') {
env.API_IMAGE = API_IMAGE_PROD
env.CLIENT_IMAGE = CLIENT_IMAGE_PROD
} else {
env.API_IMAGE = API_IMAGE_DEV
env.CLIENT_IMAGE = CLIENT_IMAGE_DEV
}
}
stage('Maven Build') {
steps {
// ----- Build API -----
dir('api') {
sh 'mvn clean package -DskipTests'
}
}
sh """
echo "=== Build image API ${API_IMAGE} ==="
docker build -t ${API_IMAGE} .
"""
}
stage('Angular Build') {
steps {
// ----- Build Client -----
dir('client') {
sh 'npm install'
sh 'npm run build'
sh """
echo "=== Build image CLIENT ${CLIENT_IMAGE} ==="
docker build -t ${CLIENT_IMAGE} .
"""
}
// ----- Push vers registry -----
sh """
echo "=== Push images vers ${REGISTRY} ==="
docker push ${API_IMAGE}
docker push ${CLIENT_IMAGE}
"""
}
}
stage('Spring Docker Build') {
steps {
sh 'docker build -t registry.vincent-guillet.fr/gameovergne-api:dev-latest ./api'
}
// Déploiement DEV (ct-home-dev, branche dev)
stage('Deploy DEV') {
when {
branch 'dev'
}
agent { label 'ct-home-dev' }
stage('Angular Docker Build') {
steps {
sh 'docker build -t registry.vincent-guillet.fr/gameovergne-client:dev-latest ./client'
}
}
checkout scm
stage('Deployment') {
steps {
withEnv([
"DOCKER_HOST=unix:///var/run/docker.sock",
"COMPOSE_PROJECT_NAME=${env.COMPOSE_PROJECT}"
]) {
sh '''
echo "=== Nettoyage des anciens conteneurs nommés ==="
sh """
echo "=== [DEV] Nettoyage anciens conteneurs ==="
docker rm -f gameovergne-api gameovergne-client 2>/dev/null || true
echo "=== docker-compose down sur le projet courant ==="
docker-compose down -v || true
echo "=== [DEV] docker compose down ==="
docker compose -f docker-compose.dev.yml down -v || true
echo "=== (Re)création de la stack MySQL + Spring + Angular ==="
docker-compose up -d mysql spring angular
'''
echo "=== [DEV] docker compose pull ==="
docker compose -f docker-compose.dev.yml pull
echo "=== [DEV] docker compose up (force recreate) ==="
docker compose -f docker-compose.dev.yml up -d --force-recreate mysql spring angular
"""
}
}
}
// Déploiement PROD (ct-home-projets, branche main)
stage('Deploy PROD') {
when {
branch 'main'
}
agent { label 'ct-home-projets' }
steps {
checkout scm
withEnv([
"DOCKER_HOST=unix:///var/run/docker.sock",
"COMPOSE_PROJECT_NAME=${env.COMPOSE_PROJECT}"
]) {
sh """
echo "=== [PROD] Nettoyage anciens conteneurs ==="
docker rm -f gameovergne-api-prod gameovergne-client-prod 2>/dev/null || true
echo "=== [PROD] docker compose down ==="
docker compose -f docker-compose.prod.yml down || true
echo "=== [PROD] docker compose pull ==="
docker compose -f docker-compose.prod.yml pull
echo "=== [PROD] docker compose up (force recreate) ==="
docker compose -f docker-compose.prod.yml up -d --force-recreate mysql spring angular
"""
}
}
}