|
8 | 8 |
|
9 | 9 | import jakarta.persistence.EntityNotFoundException;
|
10 | 10 | import lombok.RequiredArgsConstructor;
|
| 11 | +import org.apache.commons.lang3.tuple.Pair; |
11 | 12 | import org.gridsuite.studyconfig.server.dto.*;
|
12 | 13 | import org.gridsuite.studyconfig.server.entities.ColumnEntity;
|
13 | 14 | import org.gridsuite.studyconfig.server.entities.GlobalFilterEntity;
|
@@ -371,16 +372,45 @@ private static void reorderColumns(List<UUID> columnOrder, List<ColumnEntity> co
|
371 | 372 | columns.sort(Comparator.comparingInt(column -> columnOrder.indexOf(column.getUuid())));
|
372 | 373 | }
|
373 | 374 |
|
| 375 | + private String newCandidate(String base, int n) { |
| 376 | + return base + '(' + n + ')'; |
| 377 | + } |
| 378 | + |
| 379 | + private Pair<String, String> getDuplicateIdAndNameCandidate(SpreadsheetConfigEntity entity, String columnId, String columnName) { |
| 380 | + String newColumnId = columnId; |
| 381 | + String newColumnName = columnName; |
| 382 | + |
| 383 | + var existingColumnIds = entity.getColumns().stream().map(ColumnEntity::getId).collect(Collectors.toSet()); |
| 384 | + var existingColumnNames = entity.getColumns().stream().map(ColumnEntity::getName).collect(Collectors.toSet()); |
| 385 | + |
| 386 | + if (existingColumnIds.contains(columnId)) { |
| 387 | + int i = 1; |
| 388 | + while (existingColumnIds.contains(newCandidate(columnId, i))) { |
| 389 | + ++i; |
| 390 | + } |
| 391 | + newColumnId = newCandidate(columnId, i); |
| 392 | + } |
| 393 | + if (existingColumnNames.contains(columnName)) { |
| 394 | + int i = 1; |
| 395 | + while (existingColumnNames.contains(newCandidate(columnName, i))) { |
| 396 | + ++i; |
| 397 | + } |
| 398 | + newColumnName = newCandidate(columnName, i); |
| 399 | + } |
| 400 | + |
| 401 | + return Pair.of(newColumnId, newColumnName); |
| 402 | + } |
| 403 | + |
374 | 404 | @Transactional
|
375 | 405 | public void duplicateColumn(UUID id, UUID columnId) {
|
376 | 406 | SpreadsheetConfigEntity entity = findEntityById(id);
|
377 | 407 | ColumnEntity columnEntity = entity.getColumns().stream().filter(col -> col.getUuid().equals(columnId))
|
378 | 408 | .findFirst().orElseThrow(() -> new EntityNotFoundException(COLUMN_NOT_FOUND + columnId));
|
379 | 409 | ColumnEntity columnCopy = columnEntity.toBuilder().build();
|
380 | 410 | columnCopy.setUuid(UUID.randomUUID());
|
381 |
| - columnCopy.setId(columnCopy.getId() + "copy"); |
382 |
| - columnCopy.setName(columnCopy.getName() + "-copy"); |
383 |
| - |
| 411 | + Pair<String, String> idAndName = getDuplicateIdAndNameCandidate(entity, columnCopy.getId(), columnCopy.getName()); |
| 412 | + columnCopy.setId(idAndName.getLeft()); |
| 413 | + columnCopy.setName(idAndName.getRight()); |
384 | 414 | List<ColumnEntity> columns = entity.getColumns();
|
385 | 415 | columns.add(columns.indexOf(columnEntity) + 1, columnCopy);
|
386 | 416 | entity.setColumns(columns);
|
|
0 commit comments