Skip to content

Commit 49b07a4

Browse files
committed
Merge branch 'main' of github.com:lucoenergia/conluz into main
2 parents 489b74b + 37c174b commit 49b07a4

File tree

15 files changed

+459
-74
lines changed

15 files changed

+459
-74
lines changed

build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ plugins {
55
}
66

77
group = 'org.lucoenergia'
8-
version = "1.0.16"
8+
version = "1.0.17"
99

1010
java {
1111
toolchain {

src/main/java/org/lucoenergia/conluz/domain/admin/supply/Supply.java

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import jakarta.validation.constraints.NotBlank;
44
import jakarta.validation.constraints.NotNull;
5+
import jakarta.validation.constraints.PositiveOrZero;
56
import org.lucoenergia.conluz.domain.admin.user.User;
67
import org.lucoenergia.conluz.infrastructure.shared.uuid.ValidUUID;
78

@@ -18,10 +19,12 @@ public class Supply {
1819
private String code;
1920
@NotNull
2021
private User user;
22+
@NotBlank
2123
private String name;
2224
@NotBlank
2325
private String address;
2426
@NotNull
27+
@PositiveOrZero
2528
private Float partitionCoefficient;
2629
@NotNull
2730
private Boolean enabled;
@@ -265,4 +268,4 @@ public boolean equals(Object o) {
265268
public int hashCode() {
266269
return Objects.hash(getId(), getCode(), getUser());
267270
}
268-
}
271+
}

src/main/java/org/lucoenergia/conluz/infrastructure/admin/supply/SupplyExceptionHandler.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
package org.lucoenergia.conluz.infrastructure.admin.supply;
22

3+
import org.lucoenergia.conluz.domain.admin.supply.SupplyAlreadyExistsException;
34
import org.lucoenergia.conluz.domain.admin.supply.SupplyNotFoundException;
5+
import org.lucoenergia.conluz.domain.admin.user.UserAlreadyExistsException;
46
import org.lucoenergia.conluz.infrastructure.shared.web.error.RestError;
57
import org.springframework.context.MessageSource;
68
import org.springframework.context.i18n.LocaleContextHolder;
@@ -10,6 +12,7 @@
1012
import org.springframework.web.bind.annotation.RestControllerAdvice;
1113

1214
import java.util.Collections;
15+
import java.util.List;
1316

1417
@RestControllerAdvice
1518
public class SupplyExceptionHandler {
@@ -32,4 +35,15 @@ public ResponseEntity<RestError> handleException(SupplyNotFoundException e) {
3235
);
3336
return new ResponseEntity<>(new RestError(HttpStatus.BAD_REQUEST.value(), message), HttpStatus.BAD_REQUEST);
3437
}
38+
39+
@ExceptionHandler(SupplyAlreadyExistsException.class)
40+
public ResponseEntity<RestError> handleException(SupplyAlreadyExistsException e) {
41+
42+
String message = messageSource.getMessage(
43+
"error.supply.already.exists",
44+
List.of(e.getCode().getCode()).toArray(),
45+
LocaleContextHolder.getLocale()
46+
);
47+
return new ResponseEntity<>(new RestError(HttpStatus.BAD_REQUEST.value(), message), HttpStatus.BAD_REQUEST);
48+
}
3549
}

src/main/java/org/lucoenergia/conluz/infrastructure/admin/supply/create/CreateSupplyAssembler.java

Lines changed: 0 additions & 19 deletions
This file was deleted.

src/main/java/org/lucoenergia/conluz/infrastructure/admin/supply/create/CreateSupplyBody.java

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@
66
import org.lucoenergia.conluz.domain.admin.supply.Supply;
77
import org.lucoenergia.conluz.domain.admin.user.User;
88

9-
import java.util.UUID;
10-
119
@Schema(requiredProperties = {
1210
"code", "personalId", "address", "partitionCoefficient"
1311
})
@@ -21,6 +19,7 @@ public class CreateSupplyBody {
2119
private String address;
2220
@Positive
2321
private Float partitionCoefficient;
22+
private String name;
2423

2524
public String getCode() {
2625
return code;
@@ -54,12 +53,25 @@ public void setPersonalId(String personalId) {
5453
this.personalId = personalId;
5554
}
5655

56+
public String getName() {
57+
return name;
58+
}
59+
60+
public void setName(String name) {
61+
this.name = name;
62+
}
63+
5764
public Supply mapToSupply() {
5865
Supply.Builder builder = new Supply.Builder();
59-
builder.withCode(code)
60-
.withAddress(address)
66+
builder.withCode(code.trim())
67+
.withAddress(address.trim())
6168
.withPartitionCoefficient(partitionCoefficient)
62-
.withUser(new User.Builder().personalId(personalId).build());
69+
.withUser(new User.Builder().personalId(personalId.trim()).build());
70+
71+
if (name != null && !name.isBlank()) {
72+
builder.withName(name.trim());
73+
}
74+
6375
return builder.build();
6476
}
6577
}
Lines changed: 23 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
package org.lucoenergia.conluz.infrastructure.admin.supply.create;
22

33
import io.swagger.v3.oas.annotations.Operation;
4-
import io.swagger.v3.oas.annotations.media.Content;
5-
import io.swagger.v3.oas.annotations.media.ExampleObject;
64
import io.swagger.v3.oas.annotations.responses.ApiResponse;
75
import io.swagger.v3.oas.annotations.responses.ApiResponses;
8-
import org.lucoenergia.conluz.domain.admin.supply.create.CreateSupplyService;
6+
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
7+
import jakarta.validation.Valid;
98
import org.lucoenergia.conluz.domain.admin.supply.Supply;
9+
import org.lucoenergia.conluz.domain.admin.supply.create.CreateSupplyService;
1010
import org.lucoenergia.conluz.domain.shared.UserPersonalId;
1111
import org.lucoenergia.conluz.infrastructure.admin.supply.SupplyResponse;
1212
import org.lucoenergia.conluz.infrastructure.shared.web.apidocs.ApiTag;
@@ -15,6 +15,7 @@
1515
import org.lucoenergia.conluz.infrastructure.shared.web.apidocs.response.InternalServerErrorResponse;
1616
import org.lucoenergia.conluz.infrastructure.shared.web.apidocs.response.UnauthorizedErrorResponse;
1717
import org.springframework.http.MediaType;
18+
import org.springframework.security.access.prepost.PreAuthorize;
1819
import org.springframework.web.bind.annotation.PostMapping;
1920
import org.springframework.web.bind.annotation.RequestBody;
2021
import org.springframework.web.bind.annotation.RequestMapping;
@@ -31,59 +32,45 @@
3132
)
3233
public class CreateSupplyController {
3334

34-
private final CreateSupplyAssembler assembler;
3535
private final CreateSupplyService service;
3636

37-
public CreateSupplyController(CreateSupplyAssembler assembler, CreateSupplyService service) {
38-
this.assembler = assembler;
37+
public CreateSupplyController(CreateSupplyService service) {
3938
this.service = service;
4039
}
4140

4241
@PostMapping
4342
@Operation(
4443
summary = "Creates a new supply within the system.",
45-
description = "This endpoint is designed to create a new supply within the system. To utilize this endpoint, a client sends a request containing essential details such as the supply's address, partition coefficient, and any relevant parameters. Proper authentication, through authentication tokens, is required to access this endpoint. Upon successful creation, the server responds with a status code of 200, providing comprehensive details about the newly created supply, including its unique identifier. In case of failure, the server returns an appropriate error status code along with a descriptive error message, aiding the client in diagnosing and addressing the issue. This endpoint plays a pivotal role in dynamically expanding the system's repertoire of energy supplies.",
44+
description = """
45+
This endpoint is designed to create a new supply within the system.
46+
47+
To utilize this endpoint, a client sends a request containing essential details such as the supply's address, partition coefficient, and any relevant parameters.
48+
49+
Proper authentication, through authentication tokens, is required to access this endpoint.
50+
**Required Role: ADMIN**
51+
52+
Upon successful creation, the server responds with a status code of 200, providing comprehensive details about the newly created supply, including its unique identifier.
53+
54+
In case of failure, the server returns an appropriate error status code along with a descriptive error message, aiding the client in diagnosing and addressing the issue. This endpoint plays a pivotal role in dynamically expanding the system's repertoire of energy supplies.
55+
""",
4656
tags = ApiTag.SUPPLIES,
47-
operationId = "createSupply"
57+
operationId = "createSupply",
58+
security = @SecurityRequirement(name = "bearerToken", scopes = {"ADMIN"})
4859
)
4960
@ApiResponses(value = {
5061
@ApiResponse(
5162
responseCode = "200",
5263
description = "The supply has been successfully created.",
53-
content = @Content(
54-
mediaType = MediaType.APPLICATION_JSON_VALUE,
55-
examples = @ExampleObject(
56-
value = """
57-
{
58-
"id":"785de77b-8c22-4d2f-9d12-f172113f9aa4",
59-
"code":"ES0033333333333333AA0A",
60-
"user":{
61-
"id":"e7ab39cd-9250-40a9-b829-f11f65aae27d",
62-
"personalId":"rAtjrSXAU",
63-
"number":646650705,
64-
"fullName":"John Doe",
65-
"address":"Fake Street 123",
66-
"email":"[email protected]",
67-
"phoneNumber":"+34666333111",
68-
"enabled":true,
69-
"role":"PARTNER"
70-
},
71-
"name":null,
72-
"address":"Fake Street 123",
73-
"partitionCoefficient":3.0763,
74-
"enabled":true
75-
}
76-
"""
77-
)
78-
)
64+
useReturnTypeSchema = true
7965
)
8066
})
8167
@BadRequestErrorResponse
8268
@InternalServerErrorResponse
8369
@UnauthorizedErrorResponse
8470
@ForbiddenErrorResponse
85-
public SupplyResponse createSupply(@RequestBody CreateSupplyBody body) {
86-
Supply newSupply = service.create(assembler.assemble(body), UserPersonalId.of(body.getPersonalId()));
71+
@PreAuthorize("hasRole('ADMIN')")
72+
public SupplyResponse createSupply(@Valid @RequestBody CreateSupplyBody body) {
73+
Supply newSupply = service.create(body.mapToSupply(), UserPersonalId.of(body.getPersonalId()));
8774
return new SupplyResponse(newSupply);
8875
}
8976
}

src/main/java/org/lucoenergia/conluz/infrastructure/admin/supply/create/CreateSupplyServiceImpl.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,32 @@ public CreateSupplyServiceImpl(CreateSupplyRepository repository, GetUserReposit
2626
this.getUserRepository = getUserRepository;
2727
}
2828

29+
@Override
2930
public Supply create(Supply supply, UserId id) {
3031
supply.enable();
3132
supply.initializeUuid();
33+
34+
// If name is not provided, use the ID as the default name
35+
if (supply.getName() == null) {
36+
supply = new Supply.Builder()
37+
.withId(supply.getId())
38+
.withCode(supply.getCode())
39+
.withUser(supply.getUser())
40+
.withName(supply.getAddress())
41+
.withAddress(supply.getAddress())
42+
.withPartitionCoefficient(supply.getPartitionCoefficient())
43+
.withEnabled(supply.getEnabled())
44+
.withValidDateFrom(supply.getValidDateFrom())
45+
.withDistributor(supply.getDistributor())
46+
.withDistributorCode(supply.getDistributorCode())
47+
.withPointType(supply.getPointType())
48+
.withThirdParty(supply.isThirdParty())
49+
.withShellyMac(supply.getShellyMac())
50+
.withShellyId(supply.getShellyId())
51+
.withShellyMqttPrefix(supply.getShellyMqttPrefix())
52+
.build();
53+
}
54+
3255
return repository.create(supply, id);
3356
}
3457

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<databaseChangeLog
3+
xmlns="http://www.liquibase.org/xml/ns/dbchangelog"
4+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
5+
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog
6+
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.24.xsd">
7+
8+
<!-- Update existing null names to use ID as name -->
9+
<changeSet id="update_null_supply_names" author="Víctor Cañizares">
10+
<sql>
11+
UPDATE supplies
12+
SET name = id::text
13+
WHERE name IS NULL;
14+
</sql>
15+
</changeSet>
16+
17+
<!-- Make name column not nullable -->
18+
<changeSet id="make_supply_name_not_null" author="Víctor Cañizares">
19+
<addNotNullConstraint
20+
tableName="supplies"
21+
columnName="name"
22+
columnDataType="VARCHAR(250)"/>
23+
</changeSet>
24+
25+
</databaseChangeLog>

src/main/resources/db/liquibase/db.changelog-main.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,5 @@ http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-4.9.xsd">
1717
<include file="changelogs/rename_datadis_supplies_fields.xml" relativeToChangelogFile="true" />
1818
<include file="changelogs/create_table_sharing_agreements.xml" relativeToChangelogFile="true" />
1919
<include file="changelogs/create_table_supplies_partitions.xml" relativeToChangelogFile="true" />
20+
<include file="changelogs/make_supply_name_not_null.xml" relativeToChangelogFile="true" />
2021
</databaseChangeLog>

src/test/java/org/lucoenergia/conluz/domain/admin/supply/CreateSupplyServiceTest.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,4 +84,38 @@ void testCreateSupplyWithUserPersonalIdWhenUserNotExistThrowUserNotFoundExceptio
8484
// act & assert
8585
assertThrows(UserNotFoundException.class, () -> createSupplyService.create(supply, UserPersonalId.of("123")));
8686
}
87+
88+
@Test
89+
void testCreateSupplyWhenNameIsNotProvidedThenAddressIsUsedAsName() {
90+
// arrange
91+
String address = "Test Address 123";
92+
Supply supply = new Supply.Builder()
93+
.withId(UUID.randomUUID())
94+
.withCode("code")
95+
.withAddress(address)
96+
.withPartitionCoefficient(1.0F)
97+
.withEnabled(Boolean.TRUE)
98+
.build();
99+
UserId userId = UserId.of(UUID.randomUUID());
100+
101+
Supply expectedSupply = new Supply.Builder()
102+
.withId(supply.getId())
103+
.withCode(supply.getCode())
104+
.withAddress(address)
105+
.withName(address)
106+
.withPartitionCoefficient(supply.getPartitionCoefficient())
107+
.withEnabled(supply.getEnabled())
108+
.build();
109+
110+
when(supplyRepository.create(any(Supply.class), any(UserId.class))).thenReturn(expectedSupply);
111+
112+
// act
113+
Supply actualSupply = createSupplyService.create(supply, userId);
114+
115+
// assert
116+
assertNotNull(actualSupply);
117+
assertEquals(address, actualSupply.getName());
118+
}
119+
120+
87121
}

0 commit comments

Comments
 (0)