contact.phonenumbers from TEXT to JSON

This commit is contained in:
Michael Hoennig 2024-04-29 17:32:42 +02:00
parent a7d30726a6
commit d28ac596a2
13 changed files with 144 additions and 58 deletions

View File

@ -14,6 +14,9 @@ import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBui
import java.util.List;
import java.util.UUID;
import java.util.function.BiConsumer;
import static net.hostsharing.hsadminng.mapper.KeyValueMap.from;
@RestController
@ -51,7 +54,7 @@ public class HsOfficeContactController implements HsOfficeContactsApi {
context.define(currentUser, assumedRoles);
final var entityToSave = mapper.map(body, HsOfficeContactEntity.class);
final var entityToSave = mapper.map(body, HsOfficeContactEntity.class, RESOURCE_TO_ENTITY_POSTMAPPER);
final var saved = contactRepo.save(entityToSave);
@ -108,10 +111,15 @@ public class HsOfficeContactController implements HsOfficeContactsApi {
final var current = contactRepo.findByUuid(contactUuid).orElseThrow();
new HsOfficeContactEntityPatch(current).apply(body);
new HsOfficeContactEntityPatcher(current).apply(body);
final var saved = contactRepo.save(current);
final var mapped = mapper.map(saved, HsOfficeContactResource.class);
return ResponseEntity.ok(mapped);
}
@SuppressWarnings("unchecked")
final BiConsumer<HsOfficeContactInsertResource, HsOfficeContactEntity> RESOURCE_TO_ENTITY_POSTMAPPER = (resource, entity) -> {
entity.putEmailAdresses(from(resource.getEmailAddresses()));
};
}

View File

@ -1,17 +1,22 @@
package net.hostsharing.hsadminng.hs.office.contact;
import io.hypersistence.utils.hibernate.type.json.JsonType;
import lombok.*;
import lombok.experimental.FieldNameConstants;
import net.hostsharing.hsadminng.errors.DisplayName;
import net.hostsharing.hsadminng.mapper.PatchableMapWrapper;
import net.hostsharing.hsadminng.rbac.rbacobject.RbacObject;
import net.hostsharing.hsadminng.rbac.rbacdef.RbacView;
import net.hostsharing.hsadminng.rbac.rbacdef.RbacView.SQL;
import net.hostsharing.hsadminng.stringify.Stringify;
import net.hostsharing.hsadminng.stringify.Stringifyable;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import jakarta.persistence.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static net.hostsharing.hsadminng.rbac.rbacdef.RbacView.GLOBAL;
@ -48,13 +53,27 @@ public class HsOfficeContactEntity implements Stringifyable, RbacObject {
private String label;
@Column(name = "postaladdress")
private String postalAddress; // TODO.spec: check if we really want multiple, if so: JSON-Array or Postgres-Array?
private String postalAddress; // multiline free-format text
@Column(name = "emailaddresses", columnDefinition = "json")
private String emailAddresses; // TODO.spec: check if we can really add multiple. format: ["eins@...", "zwei@..."]
@Builder.Default
@Setter(AccessLevel.NONE)
@Type(JsonType.class)
@Column(name = "emailaddresses")
private Map<String, String> emailAddresses = new HashMap<>();
@Transient
private PatchableMapWrapper<String> emailAddressesWrapper;
public PatchableMapWrapper<String> getEmailAdresses() {
return PatchableMapWrapper.of(emailAddressesWrapper, (newWrapper) -> {emailAddressesWrapper = newWrapper; }, emailAddresses );
}
public void putEmailAdresses(Map<String, String> newEmailAddresses) {
getEmailAdresses().assign(newEmailAddresses);
}
@Column(name = "phonenumbers", columnDefinition = "json")
private String phoneNumbers; // TODO.spec: check if we can really add multiple. format: { "office": "+49 40 12345-10", "fax": "+49 40 12345-05" }
private String phoneNumbers;
@Override
public String toString() {

View File

@ -1,14 +1,17 @@
package net.hostsharing.hsadminng.hs.office.contact;
import net.hostsharing.hsadminng.mapper.EntityPatcher;
import net.hostsharing.hsadminng.mapper.KeyValueMap;
import net.hostsharing.hsadminng.mapper.OptionalFromJson;
import net.hostsharing.hsadminng.hs.office.generated.api.v1.model.HsOfficeContactPatchResource;
class HsOfficeContactEntityPatch implements EntityPatcher<HsOfficeContactPatchResource> {
import java.util.Optional;
class HsOfficeContactEntityPatcher implements EntityPatcher<HsOfficeContactPatchResource> {
private final HsOfficeContactEntity entity;
HsOfficeContactEntityPatch(final HsOfficeContactEntity entity) {
HsOfficeContactEntityPatcher(final HsOfficeContactEntity entity) {
this.entity = entity;
}
@ -16,7 +19,8 @@ class HsOfficeContactEntityPatch implements EntityPatcher<HsOfficeContactPatchRe
public void apply(final HsOfficeContactPatchResource resource) {
OptionalFromJson.of(resource.getLabel()).ifPresent(entity::setLabel);
OptionalFromJson.of(resource.getPostalAddress()).ifPresent(entity::setPostalAddress);
OptionalFromJson.of(resource.getEmailAddresses()).ifPresent(entity::setEmailAddresses);
Optional.ofNullable(resource.getEmailAddresses())
.ifPresent(r -> entity.getEmailAdresses().patch(KeyValueMap.from(resource.getEmailAddresses())));
OptionalFromJson.of(resource.getPhoneNumbers()).ifPresent(entity::setPhoneNumbers);
}
}

View File

@ -5,9 +5,9 @@ import java.util.Map;
public class KeyValueMap {
@SuppressWarnings("unchecked")
public static Map<String, Object> from(final Object obj) {
public static <T> Map<String, T> from(final Object obj) {
if (obj instanceof Map<?, ?>) {
return (Map<String, Object>) obj;
return (Map<String, T>) obj;
}
throw new ClassCastException("Map expected, but got: " + obj);
}

View File

@ -12,19 +12,19 @@ import static java.util.Arrays.stream;
* This is a map which can take key-value-pairs where the value can be null
* thus JSON nullable object structures from HTTP PATCH can be represented.
*/
public class PatchMap extends TreeMap<String, Object> {
public class PatchMap<T> extends TreeMap<String, T> {
public PatchMap(final ImmutablePair<String, Object>[] entries) {
public PatchMap(final ImmutablePair<String, T>[] entries) {
stream(entries).forEach(r -> put(r.getKey(), r.getValue()));
}
@SafeVarargs
public static Map<String, Object> patchMap(final ImmutablePair<String, Object>... entries) {
public static <T> Map<String, T> patchMap(final ImmutablePair<String, Object>... entries) {
return new PatchMap(entries);
}
@NotNull
public static ImmutablePair<String, Object> entry(final String key, final Object value) {
public static <T> ImmutablePair<String, T> entry(final String key, final T value) {
return new ImmutablePair<>(key, value);
}
}

View File

@ -4,7 +4,9 @@ import net.hostsharing.hsadminng.errors.DisplayName;
import jakarta.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
@ -62,6 +64,7 @@ public final class Stringify<B> {
final var propValues = props.stream()
.map(prop -> PropertyValue.of(prop, prop.getter.apply(object)))
.filter(Objects::nonNull)
.filter(PropertyValue::nonEmpty)
.map(propVal -> {
if (propVal.rawValue instanceof Stringifyable stringifyable) {
return new PropertyValue<>(propVal.prop, propVal.rawValue, stringifyable.toShortString());
@ -110,5 +113,12 @@ public final class Stringify<B> {
static <B> PropertyValue<B> of(Property<B> prop, Object rawValue) {
return rawValue != null ? new PropertyValue<>(prop, rawValue, rawValue.toString()) : null;
}
boolean nonEmpty() {
return rawValue != null &&
(!(rawValue instanceof Collection<?> c) || !c.isEmpty()) &&
(!(rawValue instanceof Map<?,?> m) || !m.isEmpty()) &&
(!(rawValue instanceof String s) || !s.isEmpty());
}
}
}

View File

@ -14,7 +14,7 @@ components:
postalAddress:
type: string
emailAddresses:
type: string
$ref: '#/components/schemas/HsOfficeContactEmailAddresses'
phoneNumbers:
type: string
@ -26,7 +26,7 @@ components:
postalAddress:
type: string
emailAddresses:
type: string
$ref: '#/components/schemas/HsOfficeContactEmailAddresses'
phoneNumbers:
type: string
required:
@ -42,8 +42,13 @@ components:
type: string
nullable: true
emailAddresses:
type: string
nullable: true
$ref: '#/components/schemas/HsOfficeContactEmailAddresses'
phoneNumbers:
type: string
nullable: true
HsOfficeContactEmailAddresses:
# forces generating a java.lang.Object containing a Map, instead of class HsOfficeContactEmailAddresses
anyOf:
- type: object
additionalProperties: true

View File

@ -10,8 +10,8 @@ create table if not exists hs_office_contact
version int not null default 0,
label varchar(128) not null,
postalAddress text,
emailAddresses text, -- TODO.feat: change to json
phoneNumbers text -- TODO.feat: change to json
emailAddresses jsonb not null,
phoneNumbers text
);
--//

View File

@ -11,8 +11,9 @@
create or replace procedure createHsOfficeContactTestData(contLabel varchar)
language plpgsql as $$
declare
currentTask varchar;
emailAddr varchar;
currentTask varchar;
postalAddr varchar;
emailAddr varchar;
begin
currentTask = 'creating contact test-data ' || contLabel;
execute format('set local hsadminng.currentTask to %L', currentTask);
@ -22,14 +23,17 @@ begin
perform createRbacUser(emailAddr);
call defineContext(currentTask, null, emailAddr);
postalAddr := E'Vorname Nachname\nStraße Hnr\nPLZ Stadt';
raise notice 'creating test contact: %', contLabel;
insert
into hs_office_contact (label, postaladdress, emailaddresses, phonenumbers)
values (contLabel, $address$
Vorname Nachname
Straße Hnr
PLZ Stadt
$address$, emailAddr, '+49 123 1234567');
values (
contLabel,
postalAddr,
('{ "main": "' || emailAddr || '" }')::jsonb,
'+49 123 1234567'
);
end; $$;
--//

View File

@ -19,6 +19,7 @@ import org.springframework.transaction.annotation.Transactional;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import java.util.Map;
import java.util.UUID;
import static net.hostsharing.hsadminng.rbac.test.IsValidUuidMatcher.isUuidValid;
@ -103,7 +104,9 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu
.body("""
{
"label": "Temp Contact",
"emailAddresses": "test@example.org"
"emailAddresses": {
"main": "test@example.org"
}
}
""")
.port(port)
@ -114,7 +117,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu
.contentType(ContentType.JSON)
.body("uuid", isUuidValid())
.body("label", is("Temp Contact"))
.body("emailAddresses", is("test@example.org"))
.body("emailAddresses", is(Map.of("main", "test@example.org")))
.header("Location", startsWith("http://localhost"))
.extract().header("Location"); // @formatter:on
@ -180,9 +183,11 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu
.contentType("application/json")
.body("", lenientlyEquals("""
{
"label": "first contact",
"emailAddresses": "contact-admin@firstcontact.example.com",
"phoneNumbers": "+49 123 1234567"
"label": "first contact",
"emailAddresses": {
"main": "contact-admin@firstcontact.example.com"
},
"phoneNumbers": "+49 123 1234567"
}
""")); // @formatter:on
}
@ -204,7 +209,9 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu
.body("""
{
"label": "Temp patched contact",
"emailAddresses": "patched@example.org",
"emailAddresses": {
"main": "patched@example.org"
},
"postalAddress": "Patched Address",
"phoneNumbers": "+01 100 123456"
}
@ -217,7 +224,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu
.contentType(ContentType.JSON)
.body("uuid", isUuidValid())
.body("label", is("Temp patched contact"))
.body("emailAddresses", is("patched@example.org"))
.body("emailAddresses", is(Map.of("main", "patched@example.org")))
.body("postalAddress", is("Patched Address"))
.body("phoneNumbers", is("+01 100 123456"));
// @formatter:on
@ -227,7 +234,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu
assertThat(contactRepo.findByUuid(givenContact.getUuid())).isPresent().get()
.matches(person -> {
assertThat(person.getLabel()).isEqualTo("Temp patched contact");
assertThat(person.getEmailAddresses()).isEqualTo("patched@example.org");
assertThat(person.getEmailAddresses()).isEqualTo(Map.of("main", "patched@example.org"));
assertThat(person.getPostalAddress()).isEqualTo("Patched Address");
assertThat(person.getPhoneNumbers()).isEqualTo("+01 100 123456");
return true;
@ -246,7 +253,9 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu
.contentType(ContentType.JSON)
.body("""
{
"emailAddresses": "patched@example.org",
"emailAddresses": {
"main": "patched@example.org"
},
"phoneNumbers": "+01 100 123456"
}
""")
@ -258,7 +267,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu
.contentType(ContentType.JSON)
.body("uuid", isUuidValid())
.body("label", is(givenContact.getLabel()))
.body("emailAddresses", is("patched@example.org"))
.body("emailAddresses", is(Map.of("main", "patched@example.org")))
.body("postalAddress", is(givenContact.getPostalAddress()))
.body("phoneNumbers", is("+01 100 123456"));
// @formatter:on
@ -267,7 +276,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu
assertThat(contactRepo.findByUuid(givenContact.getUuid())).isPresent().get()
.matches(person -> {
assertThat(person.getLabel()).isEqualTo(givenContact.getLabel());
assertThat(person.getEmailAddresses()).isEqualTo("patched@example.org");
assertThat(person.getEmailAddresses()).isEqualTo(Map.of("main", "patched@example.org"));
assertThat(person.getPostalAddress()).isEqualTo(givenContact.getPostalAddress());
assertThat(person.getPhoneNumbers()).isEqualTo("+01 100 123456");
return true;
@ -340,7 +349,7 @@ class HsOfficeContactControllerAcceptanceTest extends ContextBasedTestWithCleanu
final var newContact = HsOfficeContactEntity.builder()
.uuid(UUID.randomUUID())
.label("Temp from " + Context.getCallerMethodNameFromStackFrame(1) )
.emailAddresses(RandomStringUtils.randomAlphabetic(10) + "@example.org")
.emailAddresses(Map.of("main", RandomStringUtils.randomAlphabetic(10) + "@example.org"))
.postalAddress("Postal Address " + RandomStringUtils.randomAlphabetic(10))
.phoneNumbers("+01 200 " + RandomStringUtils.randomNumeric(8))
.build();

View File

@ -4,9 +4,12 @@ import net.hostsharing.hsadminng.rbac.test.PatchUnitTestBase;
import net.hostsharing.hsadminng.hs.office.generated.api.v1.model.HsOfficeContactPatchResource;
import org.junit.jupiter.api.TestInstance;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Stream;
import static net.hostsharing.hsadminng.mapper.PatchMap.entry;
import static net.hostsharing.hsadminng.mapper.PatchMap.patchMap;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
@TestInstance(PER_CLASS)
@ -16,13 +19,26 @@ class HsOfficeContactEntityPatcherUnitTest extends PatchUnitTestBase<
> {
private static final UUID INITIAL_CONTACT_UUID = UUID.randomUUID();
private static final Map<String, String> PATCH_EMAIL_ADDRESSES = patchMap(
entry("main", "patched@example.com"),
entry("paul", null),
entry("suse", "suse@example.com")
);
private static final Map<String, String> PATCHED_EMAIL_ADDRESSES = patchMap(
entry("main", "patched@example.com"),
entry("suse", "suse@example.com"),
entry("mila", "mila@example.com")
);
@Override
protected HsOfficeContactEntity newInitialEntity() {
final var entity = new HsOfficeContactEntity();
entity.setUuid(INITIAL_CONTACT_UUID);
entity.setLabel("initial label");
entity.setEmailAddresses("initial@example.org");
entity.putEmailAdresses(Map.ofEntries(
entry("main", "initial@example.org"),
entry("paul", "paul@example.com"),
entry("mila", "mila@example.com")));
entity.setPhoneNumbers("initial postal address");
entity.setPostalAddress("+01 100 123456789");
return entity;
@ -34,8 +50,8 @@ class HsOfficeContactEntityPatcherUnitTest extends PatchUnitTestBase<
}
@Override
protected HsOfficeContactEntityPatch createPatcher(final HsOfficeContactEntity entity) {
return new HsOfficeContactEntityPatch(entity);
protected HsOfficeContactEntityPatcher createPatcher(final HsOfficeContactEntity entity) {
return new HsOfficeContactEntityPatcher(entity);
}
@Override
@ -46,11 +62,13 @@ class HsOfficeContactEntityPatcherUnitTest extends PatchUnitTestBase<
HsOfficeContactPatchResource::setLabel,
"patched label",
HsOfficeContactEntity::setLabel),
new JsonNullableProperty<>(
"emailAddresses",
new SimpleProperty<>(
"resources",
HsOfficeContactPatchResource::setEmailAddresses,
"patched trade name",
HsOfficeContactEntity::setEmailAddresses),
PATCH_EMAIL_ADDRESSES,
HsOfficeContactEntity::putEmailAdresses,
PATCHED_EMAIL_ADDRESSES)
.notNullable(),
new JsonNullableProperty<>(
"phoneNumbers",
HsOfficeContactPatchResource::setPhoneNumbers,

View File

@ -1,5 +1,6 @@
package net.hostsharing.hsadminng.hs.office.contact;
import java.util.Map;
public class TestHsOfficeContact {
@ -9,7 +10,7 @@ public class TestHsOfficeContact {
return HsOfficeContactEntity.builder()
.label(label)
.postalAddress("address of " + label)
.emailAddresses(emailAddr)
.emailAddresses(Map.of("main", emailAddr))
.build();
}
}

View File

@ -107,7 +107,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu
"mark": null,
"contact": {
"label": "first contact",
"emailAddresses": "contact-admin@firstcontact.example.com",
"emailAddresses": { "main": "contact-admin@firstcontact.example.com" },
"phoneNumbers": "+49 123 1234567"
}
},
@ -132,7 +132,7 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu
"mark": null,
"contact": {
"label": "first contact",
"emailAddresses": "contact-admin@firstcontact.example.com",
"emailAddresses": { "main": "contact-admin@firstcontact.example.com" },
"phoneNumbers": "+49 123 1234567"
}
},
@ -162,7 +162,9 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu
"anchor": {"tradeName": "Second e.K."},
"holder": {"tradeName": "Second e.K."},
"type": "DEBITOR",
"contact": {"emailAddresses": "contact-admin@secondcontact.example.com"}
"contact": {
"emailAddresses": { "main": "contact-admin@secondcontact.example.com" }
}
},
"debitorNumber": 1000212,
"debitorNumberSuffix": 12,
@ -172,7 +174,9 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu
"anchor": {"tradeName": "Hostsharing eG"},
"holder": {"tradeName": "Second e.K."},
"type": "PARTNER",
"contact": {"emailAddresses": "contact-admin@secondcontact.example.com"}
"contact": {
"emailAddresses": { "main": "contact-admin@secondcontact.example.com" }
}
},
"details": {
"registrationOffice": "Hamburg",
@ -192,7 +196,9 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu
"anchor": {"tradeName": "Third OHG"},
"holder": {"tradeName": "Third OHG"},
"type": "DEBITOR",
"contact": {"emailAddresses": "contact-admin@thirdcontact.example.com"}
"contact": {
"emailAddresses": { "main": "contact-admin@thirdcontact.example.com" }
}
},
"debitorNumber": 1000313,
"debitorNumberSuffix": 13,
@ -202,7 +208,9 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu
"anchor": {"tradeName": "Hostsharing eG"},
"holder": {"tradeName": "Third OHG"},
"type": "PARTNER",
"contact": {"emailAddresses": "contact-admin@thirdcontact.example.com"}
"contact": {
"emailAddresses": { "main": "contact-admin@thirdcontact.example.com" }
}
},
"details": {
"registrationOffice": "Hamburg",
@ -456,8 +464,8 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu
"type": "DEBITOR",
"contact": {
"label": "first contact",
"postalAddress": "\\nVorname Nachname\\nStraße Hnr\\nPLZ Stadt\\n",
"emailAddresses": "contact-admin@firstcontact.example.com",
"postalAddress": "Vorname Nachname\\nStraße Hnr\\nPLZ Stadt",
"emailAddresses": { "main": "contact-admin@firstcontact.example.com" },
"phoneNumbers": "+49 123 1234567"
}
},
@ -472,8 +480,8 @@ class HsOfficeDebitorControllerAcceptanceTest extends ContextBasedTestWithCleanu
"mark": null,
"contact": {
"label": "first contact",
"postalAddress": "\\nVorname Nachname\\nStraße Hnr\\nPLZ Stadt\\n",
"emailAddresses": "contact-admin@firstcontact.example.com",
"postalAddress": "Vorname Nachname\\nStraße Hnr\\nPLZ Stadt",
"emailAddresses": { "main": "contact-admin@firstcontact.example.com" },
"phoneNumbers": "+49 123 1234567"
}
},