chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session, api-gateway, mobile-api, services-auth, services-system, services-counter, services-member, services-log, services-email. solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal from tastefully 8bd93d15. Copied as tracked files only. Literal secrets replaced with environment placeholders: - services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY, MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default) - services-system: JUMIO_TOKEN, JUMIO_SECRET (optional) - services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed - core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default removed, ipgeolocation key read from IPGEOLOCATION_API_KEY - services-system EkycAppConfig: commented Jumio credentials removed Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
This commit is contained in:
1 parent
e396568cc3
commit
5ee51d1913
2918 files changed
+302373
-3
No files matched your search
+140
@@ -0,0 +1,140 @@
|
||||
package com.solvway.services.counter.controller;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import com.solvway.services.counter.configuration.PubSubConfig;
|
||||
import com.solvway.services.counter.model.CheckInBooth;
|
||||
import com.solvway.services.counter.model.EventAttendance;
|
||||
import com.solvway.services.counter.service.CheckInBoothService;
|
||||
import com.solvway.services.counter.service.EventBoothService;
|
||||
import com.solvway.services.counter.service.EventRedeemCodeService;
|
||||
import com.solvway.services.counter.service.EventService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.isA;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* One attendance per member per event per day, at any booth, whichever caller (merchant scan,
|
||||
* member scan, legacy portal) asks for it: the shared counter save must not record a repeat.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class CheckInBoothControllerSaveTest {
|
||||
|
||||
private static final long EVENT = 11L;
|
||||
private static final long MEMBER = 22L;
|
||||
private static final long BOOTH = 33L;
|
||||
private static final LocalDate DAY = LocalDate.of(2026, 11, 5);
|
||||
|
||||
@Mock private EventService eventService;
|
||||
@Mock private CheckInBoothService checkInBoothService;
|
||||
@Mock private EventBoothService eventBoothService;
|
||||
@Mock private EventRedeemCodeService eventRedeemCodeService;
|
||||
@Mock private ValidateUtil validateUtil;
|
||||
@Mock private PubSubUtil pubSubUtil;
|
||||
@Mock private PubSubConfig pubSubConfig;
|
||||
@Mock private PubSubTemplate pubSubTemplate;
|
||||
|
||||
private CheckInBoothController controller;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
controller = new CheckInBoothController(eventService, checkInBoothService, eventBoothService,
|
||||
eventRedeemCodeService, validateUtil, pubSubUtil, pubSubConfig, pubSubTemplate);
|
||||
}
|
||||
|
||||
private static CheckInBooth request() {
|
||||
CheckInBooth c = new CheckInBooth();
|
||||
c.setEventUuid(EVENT);
|
||||
c.setMemberUuid(MEMBER);
|
||||
c.setStockistUuid(BOOTH);
|
||||
c.setCheckInDate(DAY);
|
||||
c.setCreateBy("tastefully");
|
||||
c.setDoneBy("tastefully");
|
||||
return c;
|
||||
}
|
||||
|
||||
@Test
|
||||
void repeatSaveSameDayReturnsExistingAndRecordsNothing() {
|
||||
CheckInBooth existing = request();
|
||||
existing.setId(99L);
|
||||
when(checkInBoothService.findByEventUuidAndMemberUuidAndCheckInDate(
|
||||
EVENT, MEMBER, DAY)).thenReturn(Optional.of(existing));
|
||||
|
||||
CheckInBooth result = controller.save(request());
|
||||
|
||||
assertThat(result).isSameAs(existing);
|
||||
verify(checkInBoothService, never()).save(any());
|
||||
verifyNoInteractions(eventService, eventBoothService, eventRedeemCodeService, pubSubUtil);
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstSaveOfTheDayIsRecordedAndPublished() {
|
||||
CheckInBooth req = request();
|
||||
when(checkInBoothService.findByEventUuidAndMemberUuidAndCheckInDate(
|
||||
EVENT, MEMBER, DAY)).thenReturn(Optional.empty());
|
||||
when(checkInBoothService.lockDay(req)).thenReturn(true);
|
||||
when(eventBoothService.findByEventUuidAndStockistUuid(EVENT, BOOTH)).thenReturn(Optional.empty());
|
||||
when(checkInBoothService.save(req)).thenReturn(req);
|
||||
|
||||
CheckInBooth result = controller.save(req);
|
||||
|
||||
assertThat(result).isSameAs(req);
|
||||
verify(checkInBoothService).save(req);
|
||||
verify(pubSubUtil).publishMessage(any(), any(), isA(EventAttendance.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveAtAnotherBoothSameDayReturnsTheFirstBoothCheckIn() {
|
||||
CheckInBooth boothA = request();
|
||||
boothA.setStockistUuid(44L);
|
||||
when(checkInBoothService.findByEventUuidAndMemberUuidAndCheckInDate(
|
||||
EVENT, MEMBER, DAY)).thenReturn(Optional.of(boothA));
|
||||
|
||||
CheckInBooth result = controller.save(request());
|
||||
|
||||
assertThat(result).isSameAs(boothA);
|
||||
verify(checkInBoothService, never()).save(any());
|
||||
verifyNoInteractions(eventService, eventBoothService, eventRedeemCodeService, pubSubUtil);
|
||||
}
|
||||
|
||||
@Test
|
||||
void simultaneousSaveThatLosesTheLockReturnsTheWinnersCheckIn() {
|
||||
CheckInBooth req = request();
|
||||
CheckInBooth winner = request();
|
||||
when(checkInBoothService.findByEventUuidAndMemberUuidAndCheckInDate(EVENT, MEMBER, DAY))
|
||||
.thenReturn(Optional.empty(), Optional.of(winner));
|
||||
when(checkInBoothService.lockDay(req)).thenReturn(false);
|
||||
|
||||
CheckInBooth result = controller.save(req);
|
||||
|
||||
assertThat(result).isSameAs(winner);
|
||||
verify(checkInBoothService, never()).save(any());
|
||||
verifyNoInteractions(eventService, eventBoothService, eventRedeemCodeService, pubSubUtil);
|
||||
}
|
||||
|
||||
@Test
|
||||
void simultaneousSaveThatLosesTheLockBeforeTheWinnerSavedReturnsNothing() {
|
||||
CheckInBooth req = request();
|
||||
when(checkInBoothService.findByEventUuidAndMemberUuidAndCheckInDate(EVENT, MEMBER, DAY))
|
||||
.thenReturn(Optional.empty());
|
||||
when(checkInBoothService.lockDay(req)).thenReturn(false);
|
||||
|
||||
assertThat(controller.save(req)).isNull();
|
||||
verify(checkInBoothService, never()).save(any());
|
||||
verifyNoInteractions(eventService, eventBoothService, eventRedeemCodeService, pubSubUtil);
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.services.counter.model.CheckInBooth;
|
||||
import com.solvway.services.counter.repo.CheckInBoothRepository;
|
||||
import com.solvway.services.counter.util.redis.RedisUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The day lookup that guards one check-in per member per event per day: it must ignore the booth,
|
||||
* and its cache read must use the same key the save writes.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class CheckInBoothServiceDayLookupTest {
|
||||
|
||||
private static final long EVENT = 11L;
|
||||
private static final long MEMBER = 22L;
|
||||
private static final LocalDate DAY = LocalDate.of(2026, 11, 5);
|
||||
|
||||
@Mock private CheckInBoothRepository repository;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private RedisUtil<CheckInBooth> redisUtil;
|
||||
|
||||
private CheckInBoothService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
service = new CheckInBoothService(repository, dateTimeFormatterUtil, redisUtil);
|
||||
org.mockito.Mockito.lenient().when(dateTimeFormatterUtil.format(DAY)).thenReturn("2026-11-05");
|
||||
}
|
||||
|
||||
private static CheckInBooth checkIn(long booth) {
|
||||
CheckInBooth c = new CheckInBooth();
|
||||
c.setEventUuid(EVENT);
|
||||
c.setMemberUuid(MEMBER);
|
||||
c.setStockistUuid(booth);
|
||||
c.setCheckInDate(DAY);
|
||||
return c;
|
||||
}
|
||||
|
||||
@Test
|
||||
void saveDoesNotWriteTheCacheBeforeCommit() {
|
||||
CheckInBooth saved = checkIn(33L);
|
||||
when(repository.save(saved)).thenReturn(saved);
|
||||
|
||||
service.save(saved);
|
||||
|
||||
verifyNoInteractions(redisUtil);
|
||||
}
|
||||
|
||||
@Test
|
||||
void lookupCachesTheDbHitAndReadsItBackUnderTheSameKey() {
|
||||
CheckInBooth row = checkIn(33L);
|
||||
when(repository.findByEventUuidAndMemberUuidAndCheckInDate(EVENT, MEMBER, DAY)).thenReturn(List.of(row));
|
||||
service.findByEventUuidAndMemberUuidAndCheckInDate(EVENT, MEMBER, DAY);
|
||||
ArgumentCaptor<String> written = ArgumentCaptor.forClass(String.class);
|
||||
verify(redisUtil).putValueIfAbsent(written.capture(), eq(row));
|
||||
ArgumentCaptor<String> read = ArgumentCaptor.forClass(String.class);
|
||||
verify(redisUtil).getValue(read.capture());
|
||||
assertThat(read.getValue()).isEqualTo(written.getValue());
|
||||
|
||||
when(redisUtil.getValue(written.getValue())).thenReturn(row);
|
||||
assertThat(service.findByEventUuidAndMemberUuidAndCheckInDate(EVENT, MEMBER, DAY)).containsSame(row);
|
||||
verify(repository, org.mockito.Mockito.times(1)).findByEventUuidAndMemberUuidAndCheckInDate(EVENT, MEMBER, DAY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void lookupMissesCacheAndFindsCheckInAtAnyBooth() {
|
||||
CheckInBooth otherBooth = checkIn(44L);
|
||||
when(repository.findByEventUuidAndMemberUuidAndCheckInDate(EVENT, MEMBER, DAY))
|
||||
.thenReturn(List.of(otherBooth));
|
||||
|
||||
assertThat(service.findByEventUuidAndMemberUuidAndCheckInDate(EVENT, MEMBER, DAY))
|
||||
.containsSame(otherBooth);
|
||||
}
|
||||
|
||||
@Test
|
||||
void lockDayTakesAnExpiringLockPerEventMemberDay() {
|
||||
CheckInBooth req = checkIn(33L);
|
||||
when(redisUtil.putValueIfAbsentWithExpiredTime(anyString(), eq(req), eq(10L), eq(TimeUnit.SECONDS)))
|
||||
.thenReturn(true, false);
|
||||
|
||||
assertThat(service.lockDay(req)).isTrue();
|
||||
assertThat(service.lockDay(req)).isFalse();
|
||||
|
||||
ArgumentCaptor<String> key = ArgumentCaptor.forClass(String.class);
|
||||
verify(redisUtil, org.mockito.Mockito.times(2))
|
||||
.putValueIfAbsentWithExpiredTime(key.capture(), eq(req), eq(10L), eq(TimeUnit.SECONDS));
|
||||
assertThat(key.getValue()).isEqualTo("service:counter:check-in-day-lock:11:2026-11-05:22");
|
||||
verifyNoInteractions(repository);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.services.counter.model.EventProduct;
|
||||
import com.solvway.services.counter.repo.EventProductRepository;
|
||||
import com.solvway.services.counter.util.redis.RedisUtil;
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
/**
|
||||
* The store-facing reward feed must report each product's available stock as
|
||||
* ledger balance minus the frozen (in-flight) quantity.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class EventProductServiceAvailableBalanceTest {
|
||||
|
||||
private static final BigInteger EVENT_UUID = BigInteger.valueOf(77001);
|
||||
private static final BigInteger PRODUCT_UUID = BigInteger.valueOf(1001);
|
||||
|
||||
@Mock private EventProductRepository eventProductRepository;
|
||||
@Mock private EventRewardPlusService eventRewardPlusService;
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private PaymentService paymentService;
|
||||
@Mock private RedisUtil<Integer> freezeRedisUtil;
|
||||
@Mock private com.solvway.core.utils.PubSubUtil pubSubUtil;
|
||||
@Mock private com.solvway.services.counter.configuration.PubSubConfig pubSubConfig;
|
||||
@Mock private com.google.cloud.spring.pubsub.core.PubSubTemplate pubSubTemplate;
|
||||
|
||||
@InjectMocks private EventProductService eventProductService;
|
||||
|
||||
@Test
|
||||
void findByEventUuidWithAvailableBalance_setsStockToBalanceMinusFrozen() {
|
||||
EventProduct product = new EventProduct();
|
||||
product.setUuid(PRODUCT_UUID);
|
||||
product.setDisplayName("Towel");
|
||||
|
||||
when(eventProductRepository.findByEventUuidAndEnabledOrderByDisplayNameAsc(EVENT_UUID, GeneralEnum.FlagYesNo.Y))
|
||||
.thenReturn(List.of(product));
|
||||
// Ledger balance = 10, frozen (in-flight) = 3 → available = 7.
|
||||
when(paymentService.getEventProductBalance(PRODUCT_UUID)).thenReturn(10);
|
||||
when(freezeRedisUtil.getMapAsAll(anyString())).thenReturn(Map.of("order-1", 3));
|
||||
when(freezeRedisUtil.checkKeyExist(anyString())).thenReturn(true);
|
||||
|
||||
List<EventProduct> result = eventProductService.findByEventUuidWithAvailableBalance(EVENT_UUID);
|
||||
|
||||
assertThat(result).hasSize(1);
|
||||
assertThat(result.get(0).getStockBalance()).isEqualTo(7);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findByEventUuidWithAvailableBalance_zeroOrNegativeWhenFrozenExceedsBalance() {
|
||||
EventProduct product = new EventProduct();
|
||||
product.setUuid(PRODUCT_UUID);
|
||||
product.setDisplayName("Mug");
|
||||
|
||||
when(eventProductRepository.findByEventUuidAndEnabledOrderByDisplayNameAsc(EVENT_UUID, GeneralEnum.FlagYesNo.Y))
|
||||
.thenReturn(List.of(product));
|
||||
when(paymentService.getEventProductBalance(PRODUCT_UUID)).thenReturn(2);
|
||||
when(freezeRedisUtil.getMapAsAll(anyString())).thenReturn(Map.of("order-1", 2));
|
||||
when(freezeRedisUtil.checkKeyExist(anyString())).thenReturn(true);
|
||||
|
||||
List<EventProduct> result = eventProductService.findByEventUuidWithAvailableBalance(EVENT_UUID);
|
||||
|
||||
assertThat(result.get(0).getStockBalance()).isLessThanOrEqualTo(0);
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.solvway.core.dto.EventRedeemDto;
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.services.counter.model.EventProduct;
|
||||
import com.solvway.services.counter.repo.EventProductRepository;
|
||||
import com.solvway.services.counter.util.redis.RedisUtil;
|
||||
import java.math.BigInteger;
|
||||
import java.util.Optional;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
|
||||
/**
|
||||
* Regression test for the event-product redeem insufficient-balance bug
|
||||
* (member 80871554): the redeem authorization must read the authoritative
|
||||
* ledger balance (no-cache) rather than the stale cached balance.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class EventProductServiceRedeemBalanceTest {
|
||||
|
||||
private static final String BUYER_UUID = "123";
|
||||
private static final BigInteger PRODUCT_UUID = BigInteger.valueOf(1001);
|
||||
|
||||
@Mock private EventProductRepository eventProductRepository;
|
||||
@Mock private EventRewardPlusService eventRewardPlusService;
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private PaymentService paymentService;
|
||||
@Mock private RedisUtil<Integer> freezeRedisUtil;
|
||||
@Mock private com.solvway.core.utils.PubSubUtil pubSubUtil;
|
||||
@Mock private com.solvway.services.counter.configuration.PubSubConfig pubSubConfig;
|
||||
@Mock private com.google.cloud.spring.pubsub.core.PubSubTemplate pubSubTemplate;
|
||||
|
||||
@InjectMocks private EventProductService eventProductService;
|
||||
|
||||
@Test
|
||||
void redeem_usesAuthoritativeLedgerBalance_notStaleCache() {
|
||||
Member buyer = new Member();
|
||||
buyer.setUuid(BUYER_UUID);
|
||||
|
||||
EventProduct product = new EventProduct();
|
||||
product.setUuid(PRODUCT_UUID);
|
||||
product.setDisplayName("Towel");
|
||||
product.setCostAmount(800d);
|
||||
|
||||
EventRedeemDto request = new EventRedeemDto();
|
||||
request.setBuyerUuid(BUYER_UUID);
|
||||
request.setOrderUuid("9001");
|
||||
request.getRedeemList().put(PRODUCT_UUID, 1);
|
||||
|
||||
when(memberService.findByUuid(BUYER_UUID)).thenReturn(Optional.of(buyer));
|
||||
when(eventProductRepository.findByUuid(PRODUCT_UUID)).thenReturn(Optional.of(product));
|
||||
|
||||
// Stale cached balance is BELOW cost; authoritative ledger balance equals cost.
|
||||
lenient().when(paymentService.getTastefullyPointBalance(BUYER_UUID)).thenReturn(300d);
|
||||
lenient().when(paymentService.getTastefullyPointBalanceNoCache(BUYER_UUID)).thenReturn(800d);
|
||||
// Force the downstream stock-freeze step to stop execution deterministically,
|
||||
// so this test isolates the Tastefully Point affordability decision.
|
||||
lenient().when(paymentService.getEventProductBalance(PRODUCT_UUID)).thenReturn(0);
|
||||
|
||||
EventRedeemDto result = eventProductService.redeemEventProduct(request);
|
||||
|
||||
// With balance (800) == cost (800), the redeem MUST NOT be rejected for
|
||||
// insufficient Tastefully Point. Reading the stale cache (300) would reject it here.
|
||||
assertThat(result.getResponseMessage())
|
||||
.isNotEqualTo("Insufficient balance for Tastefully Point.");
|
||||
// The affordability check must consult the authoritative (no-cache) balance.
|
||||
verify(paymentService).getTastefullyPointBalanceNoCache(BUYER_UUID);
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import com.solvway.services.counter.model.EventRedeemCode;
|
||||
import com.solvway.services.counter.repo.EventRedeemCodeRepository;
|
||||
import com.solvway.services.counter.util.redis.RedisUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EventRedeemCodeServiceFindByMemberTest {
|
||||
|
||||
@Mock
|
||||
private EventRedeemCodeRepository eventRedeemCodeRepository;
|
||||
|
||||
@Mock
|
||||
private RedisUtil<EventRedeemCode> redisUtil;
|
||||
|
||||
private EventRedeemCodeService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new EventRedeemCodeService(eventRedeemCodeRepository, redisUtil);
|
||||
}
|
||||
|
||||
private static EventRedeemCode redeemCode(long uuid, String redeemCode, LocalDateTime createdAt) {
|
||||
EventRedeemCode code = new EventRedeemCode();
|
||||
code.setUuid(uuid);
|
||||
code.setRedeemCode(redeemCode);
|
||||
code.setCreateDateTime(createdAt);
|
||||
return code;
|
||||
}
|
||||
|
||||
@Test
|
||||
void findByMemberUuidReturnsTheRepositoryCodeListInOrder() {
|
||||
long memberUuid = 42L;
|
||||
EventRedeemCode newer = redeemCode(10L, "CODE-B", LocalDateTime.of(2025, 3, 1, 10, 0));
|
||||
EventRedeemCode older = redeemCode(9L, "CODE-A", LocalDateTime.of(2025, 2, 1, 10, 0));
|
||||
when(eventRedeemCodeRepository.findTop50ByMemberUuidOrderByCreateDateTimeDesc(memberUuid))
|
||||
.thenReturn(List.of(newer, older));
|
||||
|
||||
List<EventRedeemCode> result = service.findByMemberUuid(memberUuid);
|
||||
|
||||
assertThat(result).hasSize(2);
|
||||
assertThat(result.get(0).getRedeemCode()).isEqualTo("CODE-B");
|
||||
assertThat(result.get(1).getRedeemCode()).isEqualTo("CODE-A");
|
||||
verify(eventRedeemCodeRepository).findTop50ByMemberUuidOrderByCreateDateTimeDesc(memberUuid);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findByMemberUuidEmptyRepoResultGivesEmptyList() {
|
||||
long memberUuid = 42L;
|
||||
when(eventRedeemCodeRepository.findTop50ByMemberUuidOrderByCreateDateTimeDesc(memberUuid))
|
||||
.thenReturn(List.of());
|
||||
|
||||
List<EventRedeemCode> result = service.findByMemberUuid(memberUuid);
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
}
|
||||
+275
@@ -0,0 +1,275 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum.FlagYesNo;
|
||||
import com.solvway.core.model.MemberVoucherEligibility;
|
||||
import com.solvway.services.counter.model.MemberVoucher;
|
||||
import com.solvway.services.counter.model.MemberVoucherRedemption;
|
||||
import com.solvway.services.counter.repo.MemberVoucherRedemptionRepository;
|
||||
import com.solvway.services.counter.repo.MemberVoucherRedemptionRepository.VoucherRedeemedCount;
|
||||
import com.solvway.services.counter.repo.MemberVoucherRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The single eligibility rule. "Once per member, ever" is the ABSENCE of a redemption row —
|
||||
* vouchers are never materialised per member.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberVoucherServiceEligibilityTest {
|
||||
|
||||
private static final long MEMBER = 900L;
|
||||
|
||||
@Mock private MemberVoucherRepository voucherRepository;
|
||||
@Mock private MemberVoucherRedemptionRepository redemptionRepository;
|
||||
|
||||
private MemberVoucherService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new MemberVoucherService(voucherRepository, redemptionRepository);
|
||||
}
|
||||
|
||||
private static MemberVoucher voucher(long uuid) {
|
||||
MemberVoucher v = new MemberVoucher();
|
||||
v.setUuid(uuid);
|
||||
v.setName("New First-Time User");
|
||||
v.setCurrencySymbol("RM");
|
||||
v.setAmount(10d);
|
||||
v.setActive(FlagYesNo.Y);
|
||||
v.setRequireCompleteProfile(FlagYesNo.Y);
|
||||
return v;
|
||||
}
|
||||
|
||||
private MemberVoucherEligibility only(MemberVoucher v, boolean profileComplete) {
|
||||
when(voucherRepository.findAllByOrderByCreateDateTimeDesc()).thenReturn(List.of(v));
|
||||
List<MemberVoucherEligibility> result = service.findEligibilityForMember(MEMBER, profileComplete);
|
||||
assertThat(result).hasSize(1);
|
||||
return result.get(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeemableWhenActiveInWindowUnredeemedAndProfileComplete() {
|
||||
MemberVoucher v = voucher(1L);
|
||||
v.setEffectiveFrom(LocalDateTime.now().minusDays(1));
|
||||
v.setEffectiveTo(LocalDateTime.now().plusDays(1));
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(1L, MEMBER)).thenReturn(Optional.empty());
|
||||
|
||||
MemberVoucherEligibility e = only(v, true);
|
||||
|
||||
assertThat(e.isRedeemable()).isTrue();
|
||||
assertThat(e.getReason()).isNull();
|
||||
assertThat(e.getVoucher().getAmount()).isEqualTo(10d);
|
||||
}
|
||||
|
||||
@Test
|
||||
void openEndedDatesAreTreatedAsAlwaysInWindow() {
|
||||
MemberVoucher v = voucher(1L);
|
||||
v.setEffectiveFrom(null);
|
||||
v.setEffectiveTo(null);
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(1L, MEMBER)).thenReturn(Optional.empty());
|
||||
|
||||
assertThat(only(v, true).isRedeemable()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void notActive() {
|
||||
MemberVoucher v = voucher(1L);
|
||||
v.setActive(FlagYesNo.N);
|
||||
|
||||
MemberVoucherEligibility e = only(v, true);
|
||||
|
||||
assertThat(e.isRedeemable()).isFalse();
|
||||
assertThat(e.getReason()).isEqualTo("NOT_ACTIVE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void notStarted() {
|
||||
MemberVoucher v = voucher(1L);
|
||||
v.setEffectiveFrom(LocalDateTime.now().plusDays(1));
|
||||
|
||||
MemberVoucherEligibility e = only(v, true);
|
||||
|
||||
assertThat(e.isRedeemable()).isFalse();
|
||||
assertThat(e.getReason()).isEqualTo("NOT_STARTED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void expired() {
|
||||
MemberVoucher v = voucher(1L);
|
||||
v.setEffectiveTo(LocalDateTime.now().minusMinutes(1));
|
||||
|
||||
MemberVoucherEligibility e = only(v, true);
|
||||
|
||||
assertThat(e.isRedeemable()).isFalse();
|
||||
assertThat(e.getReason()).isEqualTo("EXPIRED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void alreadyRedeemedCarriesTheRedemptionTimestamp() {
|
||||
MemberVoucher v = voucher(1L);
|
||||
MemberVoucherRedemption r = new MemberVoucherRedemption();
|
||||
LocalDateTime when = LocalDateTime.now().minusDays(3);
|
||||
r.setRedeemedDateTime(when);
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(1L, MEMBER)).thenReturn(Optional.of(r));
|
||||
|
||||
MemberVoucherEligibility e = only(v, true);
|
||||
|
||||
assertThat(e.isRedeemable()).isFalse();
|
||||
assertThat(e.getReason()).isEqualTo("ALREADY_REDEEMED");
|
||||
assertThat(e.getRedeemedDateTime()).isEqualTo(when);
|
||||
}
|
||||
|
||||
@Test
|
||||
void profileIncompleteBlocksWhenTheVoucherRequiresIt() {
|
||||
MemberVoucher v = voucher(1L);
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(1L, MEMBER)).thenReturn(Optional.empty());
|
||||
|
||||
MemberVoucherEligibility e = only(v, false);
|
||||
|
||||
assertThat(e.isRedeemable()).isFalse();
|
||||
assertThat(e.getReason()).isEqualTo("PROFILE_INCOMPLETE");
|
||||
}
|
||||
|
||||
@Test
|
||||
void profileIncompleteIsIgnoredWhenTheVoucherDoesNotRequireIt() {
|
||||
MemberVoucher v = voucher(1L);
|
||||
v.setRequireCompleteProfile(FlagYesNo.N);
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(1L, MEMBER)).thenReturn(Optional.empty());
|
||||
|
||||
assertThat(only(v, false).isRedeemable()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void alreadyRedeemedOutranksProfileIncomplete() {
|
||||
MemberVoucher v = voucher(1L);
|
||||
MemberVoucherRedemption r = new MemberVoucherRedemption();
|
||||
r.setRedeemedDateTime(LocalDateTime.now().minusDays(1));
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(1L, MEMBER)).thenReturn(Optional.of(r));
|
||||
|
||||
// A member who already redeemed should be told that, not sent to fix their profile.
|
||||
assertThat(only(v, false).getReason()).isEqualTo("ALREADY_REDEEMED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void everyVoucherIsReturnedNotJustTheRedeemableOnes() {
|
||||
MemberVoucher ok = voucher(1L);
|
||||
MemberVoucher off = voucher(2L);
|
||||
off.setActive(FlagYesNo.N);
|
||||
when(voucherRepository.findAllByOrderByCreateDateTimeDesc()).thenReturn(List.of(ok, off));
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(anyLong(), anyLong())).thenReturn(Optional.empty());
|
||||
|
||||
List<MemberVoucherEligibility> result = service.findEligibilityForMember(MEMBER, true);
|
||||
|
||||
assertThat(result).hasSize(2);
|
||||
assertThat(result).extracting(MemberVoucherEligibility::isRedeemable).containsExactly(true, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* The grouped-count query returns one row per voucher that has redemptions. Vouchers with
|
||||
* none are simply absent, which the service reads as zero.
|
||||
*/
|
||||
private static VoucherRedeemedCount countRow(long voucherUuid, long redeemedCount) {
|
||||
return new VoucherRedeemedCount() {
|
||||
@Override public long getVoucherUuid() { return voucherUuid; }
|
||||
@Override public long getRedeemedCount() { return redeemedCount; }
|
||||
};
|
||||
}
|
||||
|
||||
private void redeemedSoFar(long voucherUuid, long count) {
|
||||
when(redemptionRepository.countGroupedByVoucherUuid()).thenReturn(List.of(countRow(voucherUuid, count)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeemableWhileTheRedemptionCountIsUnderTheLimit() {
|
||||
MemberVoucher v = voucher(1L);
|
||||
v.setRedemptionLimit(100);
|
||||
redeemedSoFar(1L, 99L);
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(1L, MEMBER)).thenReturn(Optional.empty());
|
||||
|
||||
MemberVoucherEligibility e = only(v, true);
|
||||
|
||||
assertThat(e.isRedeemable()).isTrue();
|
||||
assertThat(e.getReason()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullyRedeemedOnceTheCountReachesTheLimit() {
|
||||
MemberVoucher v = voucher(1L);
|
||||
v.setRedemptionLimit(100);
|
||||
redeemedSoFar(1L, 100L);
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(1L, MEMBER)).thenReturn(Optional.empty());
|
||||
|
||||
MemberVoucherEligibility e = only(v, true);
|
||||
|
||||
assertThat(e.isRedeemable()).isFalse();
|
||||
assertThat(e.getReason()).isEqualTo("FULLY_REDEEMED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullyRedeemedWhenAnAdminLowersTheLimitBelowWhatWasAlreadyTaken() {
|
||||
// Lowering the limit is allowed and is not an error; the voucher simply reads exhausted.
|
||||
// This is why the comparison is >= and not ==.
|
||||
MemberVoucher v = voucher(1L);
|
||||
v.setRedemptionLimit(5);
|
||||
redeemedSoFar(1L, 12L);
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(1L, MEMBER)).thenReturn(Optional.empty());
|
||||
|
||||
assertThat(only(v, true).getReason()).isEqualTo("FULLY_REDEEMED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVoucherWithNoLimitIsNeverFullyRedeemedNoMatterTheCount() {
|
||||
MemberVoucher v = voucher(1L);
|
||||
v.setRedemptionLimit(null);
|
||||
redeemedSoFar(1L, 5000L);
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(1L, MEMBER)).thenReturn(Optional.empty());
|
||||
|
||||
assertThat(only(v, true).isRedeemable()).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void alreadyRedeemedOutranksFullyRedeemed() {
|
||||
// A member holding one of the issued vouchers must be told they hold it, not that the
|
||||
// pool is gone — otherwise their own redemption disappears from the screen.
|
||||
MemberVoucher v = voucher(1L);
|
||||
v.setRedemptionLimit(100);
|
||||
redeemedSoFar(1L, 100L);
|
||||
MemberVoucherRedemption r = new MemberVoucherRedemption();
|
||||
r.setRedeemedDateTime(LocalDateTime.now().minusDays(1));
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(1L, MEMBER)).thenReturn(Optional.of(r));
|
||||
|
||||
assertThat(only(v, false).getReason()).isEqualTo("ALREADY_REDEEMED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void fullyRedeemedOutranksProfileIncomplete() {
|
||||
// Telling a member to complete their profile implies redemption would then succeed.
|
||||
// Once stock is gone that is a false promise, so exhaustion is reported instead.
|
||||
MemberVoucher v = voucher(1L);
|
||||
v.setRedemptionLimit(100);
|
||||
redeemedSoFar(1L, 100L);
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(1L, MEMBER)).thenReturn(Optional.empty());
|
||||
|
||||
assertThat(only(v, false).getReason()).isEqualTo("FULLY_REDEEMED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void theRedemptionLimitIsCarriedOntoTheCoreModelForCallers() {
|
||||
MemberVoucher v = voucher(1L);
|
||||
v.setRedemptionLimit(100);
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(1L, MEMBER)).thenReturn(Optional.empty());
|
||||
|
||||
assertThat(only(v, true).getVoucher().getRedemptionLimit()).isEqualTo(100);
|
||||
}
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import com.solvway.services.counter.model.MemberVoucher;
|
||||
import com.solvway.services.counter.repo.MemberVoucherRedemptionRepository;
|
||||
import com.solvway.services.counter.repo.MemberVoucherRedemptionRepository.VoucherRedeemedCount;
|
||||
import com.solvway.services.counter.repo.MemberVoucherRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* The listing needs to show how much of a limited voucher is gone. The tally rides along on the
|
||||
* findAll response rather than costing backoffice a second call — it is display-only and never
|
||||
* persisted.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberVoucherServiceFindAllTest {
|
||||
|
||||
@Mock private MemberVoucherRepository voucherRepository;
|
||||
@Mock private MemberVoucherRedemptionRepository redemptionRepository;
|
||||
|
||||
private MemberVoucherService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new MemberVoucherService(voucherRepository, redemptionRepository);
|
||||
}
|
||||
|
||||
private static MemberVoucher voucher(long uuid) {
|
||||
MemberVoucher v = new MemberVoucher();
|
||||
v.setUuid(uuid);
|
||||
v.setName("New First-Time User");
|
||||
return v;
|
||||
}
|
||||
|
||||
private static VoucherRedeemedCount countRow(long voucherUuid, long redeemedCount) {
|
||||
return new VoucherRedeemedCount() {
|
||||
@Override public long getVoucherUuid() { return voucherUuid; }
|
||||
@Override public long getRedeemedCount() { return redeemedCount; }
|
||||
};
|
||||
}
|
||||
|
||||
@Test
|
||||
void findAllTagsEachVoucherWithHowManyMembersHaveRedeemedIt() {
|
||||
when(voucherRepository.findAllByOrderByCreateDateTimeDesc())
|
||||
.thenReturn(List.of(voucher(1L), voucher(2L)));
|
||||
when(redemptionRepository.countGroupedByVoucherUuid())
|
||||
.thenReturn(List.of(countRow(1L, 47L), countRow(2L, 3L)));
|
||||
|
||||
List<MemberVoucher> result = service.findAll();
|
||||
|
||||
assertThat(result).extracting(MemberVoucher::getRedeemedCount).containsExactly(47, 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVoucherNobodyHasRedeemedReportsZeroRatherThanGoingMissing() {
|
||||
// The grouped query returns no row at all for a voucher with no redemptions.
|
||||
when(voucherRepository.findAllByOrderByCreateDateTimeDesc()).thenReturn(List.of(voucher(1L)));
|
||||
when(redemptionRepository.countGroupedByVoucherUuid()).thenReturn(List.of());
|
||||
|
||||
assertThat(service.findAll().get(0).getRedeemedCount()).isZero();
|
||||
}
|
||||
}
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import com.solvway.core.dto.MemberVoucherRedeemRequest;
|
||||
import com.solvway.core.dto.MemberVoucherRedeemResult;
|
||||
import com.solvway.core.enums.GeneralEnum.FlagYesNo;
|
||||
import com.solvway.services.counter.model.MemberVoucher;
|
||||
import com.solvway.services.counter.model.MemberVoucherRedemption;
|
||||
import com.solvway.services.counter.repo.MemberVoucherRedemptionRepository;
|
||||
import com.solvway.services.counter.repo.MemberVoucherRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyLong;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Redemption re-checks eligibility at write time (the voucher may have been deactivated while
|
||||
* the member held the QR open) and treats a unique-constraint violation as "already redeemed"
|
||||
* rather than an error — that constraint is what makes concurrent double-redeem impossible.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberVoucherServiceRedeemTest {
|
||||
|
||||
private static final long VOUCHER = 1L;
|
||||
private static final long MEMBER = 900L;
|
||||
|
||||
@Mock private MemberVoucherRepository voucherRepository;
|
||||
@Mock private MemberVoucherRedemptionRepository redemptionRepository;
|
||||
|
||||
private MemberVoucherService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new MemberVoucherService(voucherRepository, redemptionRepository);
|
||||
}
|
||||
|
||||
private static MemberVoucher activeVoucher() {
|
||||
MemberVoucher v = new MemberVoucher();
|
||||
v.setUuid(VOUCHER);
|
||||
v.setName("New First-Time User");
|
||||
v.setActive(FlagYesNo.Y);
|
||||
v.setRequireCompleteProfile(FlagYesNo.Y);
|
||||
return v;
|
||||
}
|
||||
|
||||
private static MemberVoucherRedeemRequest request(boolean profileComplete) {
|
||||
MemberVoucherRedeemRequest r = new MemberVoucherRedeemRequest();
|
||||
r.setVoucherUuid(VOUCHER);
|
||||
r.setMemberUuid(MEMBER);
|
||||
r.setProfileComplete(profileComplete);
|
||||
r.setDoneBy("counter.staff");
|
||||
r.setChannel("BACKOFFICE");
|
||||
return r;
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeemPersistsARedemptionAndReportsSuccess() {
|
||||
when(voucherRepository.findByUuidForUpdate(VOUCHER)).thenReturn(Optional.of(activeVoucher()));
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(VOUCHER, MEMBER)).thenReturn(Optional.empty());
|
||||
when(redemptionRepository.save(any(MemberVoucherRedemption.class)))
|
||||
.thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
MemberVoucherRedeemResult result = service.redeem(request(true));
|
||||
|
||||
assertThat(result.isSuccess()).isTrue();
|
||||
assertThat(result.getReason()).isNull();
|
||||
|
||||
ArgumentCaptor<MemberVoucherRedemption> saved = ArgumentCaptor.forClass(MemberVoucherRedemption.class);
|
||||
verify(redemptionRepository).save(saved.capture());
|
||||
assertThat(saved.getValue().getVoucherUuid()).isEqualTo(VOUCHER);
|
||||
assertThat(saved.getValue().getMemberUuid()).isEqualTo(MEMBER);
|
||||
assertThat(saved.getValue().getDoneBy()).isEqualTo("counter.staff");
|
||||
assertThat(saved.getValue().getChannel()).isEqualTo("BACKOFFICE");
|
||||
assertThat(saved.getValue().getRedeemedDateTime()).isNotNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeemIsRefusedWhenProfileIncompleteAndPersistsNothing() {
|
||||
when(voucherRepository.findByUuidForUpdate(VOUCHER)).thenReturn(Optional.of(activeVoucher()));
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(VOUCHER, MEMBER)).thenReturn(Optional.empty());
|
||||
|
||||
MemberVoucherRedeemResult result = service.redeem(request(false));
|
||||
|
||||
assertThat(result.isSuccess()).isFalse();
|
||||
assertThat(result.getReason()).isEqualTo("PROFILE_INCOMPLETE");
|
||||
verify(redemptionRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeemIsRefusedWhenTheVoucherWasDeactivatedWhileTheQrWasOpen() {
|
||||
MemberVoucher deactivated = activeVoucher();
|
||||
deactivated.setActive(FlagYesNo.N);
|
||||
when(voucherRepository.findByUuidForUpdate(VOUCHER)).thenReturn(Optional.of(deactivated));
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(VOUCHER, MEMBER)).thenReturn(Optional.empty());
|
||||
|
||||
MemberVoucherRedeemResult result = service.redeem(request(true));
|
||||
|
||||
assertThat(result.isSuccess()).isFalse();
|
||||
assertThat(result.getReason()).isEqualTo("NOT_ACTIVE");
|
||||
verify(redemptionRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeemIsRefusedWhenAlreadyRedeemed() {
|
||||
when(voucherRepository.findByUuidForUpdate(VOUCHER)).thenReturn(Optional.of(activeVoucher()));
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(VOUCHER, MEMBER))
|
||||
.thenReturn(Optional.of(new MemberVoucherRedemption()));
|
||||
|
||||
MemberVoucherRedeemResult result = service.redeem(request(true));
|
||||
|
||||
assertThat(result.isSuccess()).isFalse();
|
||||
assertThat(result.getReason()).isEqualTo("ALREADY_REDEEMED");
|
||||
verify(redemptionRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aConcurrentRedeemLosesToTheUniqueConstraintAndIsReportedAsAlreadyRedeemed() {
|
||||
when(voucherRepository.findByUuidForUpdate(VOUCHER)).thenReturn(Optional.of(activeVoucher()));
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(VOUCHER, MEMBER)).thenReturn(Optional.empty());
|
||||
// Two staff scanned at the same instant: both passed the pre-check, the DB rejects the loser.
|
||||
when(redemptionRepository.save(any(MemberVoucherRedemption.class)))
|
||||
.thenThrow(new DataIntegrityViolationException("uk_member_voucher_redemption_voucher_member"));
|
||||
|
||||
MemberVoucherRedeemResult result = service.redeem(request(true));
|
||||
|
||||
assertThat(result.isSuccess()).isFalse();
|
||||
assertThat(result.getReason()).isEqualTo("ALREADY_REDEEMED");
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeemIsRefusedWhenTheVoucherDoesNotExist() {
|
||||
when(voucherRepository.findByUuidForUpdate(VOUCHER)).thenReturn(Optional.empty());
|
||||
|
||||
MemberVoucherRedeemResult result = service.redeem(request(true));
|
||||
|
||||
assertThat(result.isSuccess()).isFalse();
|
||||
assertThat(result.getReason()).isEqualTo("NOT_ACTIVE");
|
||||
verify(redemptionRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeemIsRefusedWhenTheVoucherIsFullyRedeemed() {
|
||||
MemberVoucher exhausted = activeVoucher();
|
||||
exhausted.setRedemptionLimit(2);
|
||||
when(voucherRepository.findByUuidForUpdate(VOUCHER)).thenReturn(Optional.of(exhausted));
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(VOUCHER, MEMBER)).thenReturn(Optional.empty());
|
||||
when(redemptionRepository.countByVoucherUuid(VOUCHER)).thenReturn(2L);
|
||||
|
||||
MemberVoucherRedeemResult result = service.redeem(request(true));
|
||||
|
||||
assertThat(result.isSuccess()).isFalse();
|
||||
assertThat(result.getReason()).isEqualTo("FULLY_REDEEMED");
|
||||
verify(redemptionRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeemSucceedsOnTheLastRemainingRedemption() {
|
||||
MemberVoucher lastOne = activeVoucher();
|
||||
lastOne.setRedemptionLimit(2);
|
||||
when(voucherRepository.findByUuidForUpdate(VOUCHER)).thenReturn(Optional.of(lastOne));
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(VOUCHER, MEMBER)).thenReturn(Optional.empty());
|
||||
when(redemptionRepository.countByVoucherUuid(VOUCHER)).thenReturn(1L);
|
||||
when(redemptionRepository.save(any(MemberVoucherRedemption.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
MemberVoucherRedeemResult result = service.redeem(request(true));
|
||||
|
||||
assertThat(result.isSuccess()).isTrue();
|
||||
assertThat(result.getReason()).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void redeemReadsTheVoucherUnderALockRatherThanWithAPlainRead() {
|
||||
// The count-then-insert below is a read-modify-write. Without this lock two staff
|
||||
// scanning the last voucher at the same instant both pass the check and the limit is
|
||||
// exceeded. A plain findByUuid here would be silently wrong, and no unit test can
|
||||
// observe the race itself — so pin the call that prevents it.
|
||||
when(voucherRepository.findByUuidForUpdate(VOUCHER)).thenReturn(Optional.of(activeVoucher()));
|
||||
when(redemptionRepository.findByVoucherUuidAndMemberUuid(VOUCHER, MEMBER)).thenReturn(Optional.empty());
|
||||
when(redemptionRepository.save(any(MemberVoucherRedemption.class))).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
service.redeem(request(true));
|
||||
|
||||
verify(voucherRepository).findByUuidForUpdate(VOUCHER);
|
||||
verify(voucherRepository, never()).findByUuid(anyLong());
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package com.solvway.services.counter.service;
|
||||
|
||||
import com.solvway.services.counter.model.MemberVoucher;
|
||||
import com.solvway.services.counter.repo.MemberVoucherRedemptionRepository;
|
||||
import com.solvway.services.counter.repo.MemberVoucherRepository;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.times;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* A voucher created in backoffice crosses a REST boundary as com.solvway.core.model.MemberVoucher,
|
||||
* whose primitive uuid defaults to 0 and overwrites this entity's SnowflakeIdWorker field
|
||||
* initializer during deserialization. Counter-service owns the table and its unique key on uuid,
|
||||
* so it is the last place that can guarantee one before the insert.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberVoucherServiceSaveTest {
|
||||
|
||||
@Mock private MemberVoucherRepository voucherRepository;
|
||||
@Mock private MemberVoucherRedemptionRepository redemptionRepository;
|
||||
|
||||
private MemberVoucherService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new MemberVoucherService(voucherRepository, redemptionRepository);
|
||||
when(voucherRepository.save(any(MemberVoucher.class)))
|
||||
.thenAnswer(invocation -> invocation.getArgument(0));
|
||||
}
|
||||
|
||||
private static MemberVoucher incomingVoucher(long uuid) {
|
||||
MemberVoucher voucher = new MemberVoucher();
|
||||
voucher.setName("New First-Time User");
|
||||
voucher.setUuid(uuid);
|
||||
return voucher;
|
||||
}
|
||||
|
||||
@Test
|
||||
void assignsAUuidWhenTheIncomingVoucherHasNone() {
|
||||
MemberVoucher saved = service.save(incomingVoucher(0L));
|
||||
|
||||
assertThat(saved.getUuid()).isNotZero();
|
||||
}
|
||||
|
||||
/**
|
||||
* The reported defect: the first voucher inserted with uuid 0 succeeds, and the second
|
||||
* fails on Duplicate entry '0' for key 'member_voucher.uk_member_voucher_uuid'.
|
||||
*/
|
||||
@Test
|
||||
void assignsADistinctUuidToEachVoucherSavedWithoutOne() {
|
||||
service.save(incomingVoucher(0L));
|
||||
service.save(incomingVoucher(0L));
|
||||
|
||||
ArgumentCaptor<MemberVoucher> captor = ArgumentCaptor.forClass(MemberVoucher.class);
|
||||
verify(voucherRepository, times(2)).save(captor.capture());
|
||||
long first = captor.getAllValues().get(0).getUuid();
|
||||
long second = captor.getAllValues().get(1).getUuid();
|
||||
|
||||
assertThat(first).isNotZero();
|
||||
assertThat(second).isNotZero();
|
||||
assertThat(first).isNotEqualTo(second);
|
||||
}
|
||||
|
||||
/** The edit path saves a loaded entity; re-keying an existing row would orphan its redemptions. */
|
||||
@Test
|
||||
void preservesTheUuidOfAVoucherThatAlreadyHasOne() {
|
||||
MemberVoucher saved = service.save(incomingVoucher(123456789L));
|
||||
|
||||
assertThat(saved.getUuid()).isEqualTo(123456789L);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user