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
+20
@@ -0,0 +1,20 @@
|
||||
package com.solvway.mobile.api;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
|
||||
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
|
||||
@EnableCaching
|
||||
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
|
||||
@SpringBootApplication(scanBasePackages = {"com.solvway"})
|
||||
public class SolvwayMobileApiApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(SolvwayMobileApiApplication.class, args);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.solvway.mobile.api.cache;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Component
|
||||
public class MessageLabelCache {
|
||||
|
||||
static final Duration TTL = Duration.ofMinutes(10);
|
||||
|
||||
private final Clock clock;
|
||||
private final ConcurrentHashMap<String, Entry> entries = new ConcurrentHashMap<>();
|
||||
|
||||
public MessageLabelCache() {
|
||||
this(Clock.systemUTC());
|
||||
}
|
||||
|
||||
public MessageLabelCache(Clock clock) {
|
||||
this.clock = clock;
|
||||
}
|
||||
|
||||
public Optional<String> get(String code, String locale) {
|
||||
String k = key(code, locale);
|
||||
Entry entry = entries.get(k);
|
||||
if (entry == null) return Optional.empty();
|
||||
if (clock.millis() > entry.expiresAtMillis) {
|
||||
entries.remove(k, entry);
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(entry.label);
|
||||
}
|
||||
|
||||
public void put(String code, String locale, String label) {
|
||||
entries.put(key(code, locale), new Entry(label, clock.millis() + TTL.toMillis()));
|
||||
}
|
||||
|
||||
private static String key(String code, String locale) {
|
||||
return code + "::" + locale;
|
||||
}
|
||||
|
||||
private record Entry(String label, long expiresAtMillis) {}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.solvway.mobile.api.config;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum.CmsPlatform;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "auth.api-key")
|
||||
@Slf4j
|
||||
public class AuthAppKeyConfig {
|
||||
|
||||
/** Raw tokens from AUTH_API_KEYS: "<key>" or "<key>:<PLATFORM>". */
|
||||
private List<String> list = new ArrayList<>();
|
||||
|
||||
/** Parsed key -> platform, rebuilt whenever the list is set. */
|
||||
private final Map<String, CmsPlatform> resolved = new LinkedHashMap<>();
|
||||
|
||||
public List<String> getList() {
|
||||
return list;
|
||||
}
|
||||
|
||||
public void setList(List<String> list) {
|
||||
this.list = list != null ? list : new ArrayList<>();
|
||||
parse();
|
||||
}
|
||||
|
||||
private void parse() {
|
||||
resolved.clear();
|
||||
for (String token : list) {
|
||||
if (token == null || token.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String trimmed = token.trim();
|
||||
// Platform is an optional trailing ":<CmsPlatform>" suffix. Split on the LAST colon so
|
||||
// an api-key value that itself contains a colon is preserved; only treat the suffix as
|
||||
// a platform when it is a recognised CmsPlatform, otherwise the whole token is the key.
|
||||
String key = trimmed;
|
||||
CmsPlatform platform = null;
|
||||
int sep = trimmed.lastIndexOf(':');
|
||||
if (sep >= 0) {
|
||||
CmsPlatform suffix = tryParsePlatform(trimmed.substring(sep + 1).trim());
|
||||
if (suffix != null) {
|
||||
key = trimmed.substring(0, sep).trim();
|
||||
platform = suffix;
|
||||
}
|
||||
}
|
||||
if (key.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
if (platform == null) {
|
||||
platform = CmsPlatform.APP;
|
||||
log.warn("[AuthAppKeyConfig] api-key {} has no valid platform suffix, defaulting to APP",
|
||||
maskKey(key));
|
||||
}
|
||||
resolved.put(key, platform);
|
||||
}
|
||||
}
|
||||
|
||||
private CmsPlatform tryParsePlatform(String value) {
|
||||
if (value.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return CmsPlatform.valueOf(value);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public boolean contains(String apiKey) {
|
||||
return apiKey != null && resolved.containsKey(apiKey);
|
||||
}
|
||||
|
||||
/** True when at least one token parsed to a non-empty key (a token like ":CP" does not). */
|
||||
public boolean hasKeys() {
|
||||
return !resolved.isEmpty();
|
||||
}
|
||||
|
||||
public CmsPlatform resolvePlatform(String apiKey) {
|
||||
return resolved.getOrDefault(apiKey, CmsPlatform.APP);
|
||||
}
|
||||
|
||||
private String maskKey(String key) {
|
||||
if (key == null) return "null";
|
||||
if (key.length() <= 8) return "****";
|
||||
return key.substring(0, 8) + "****(len=" + key.length() + ")";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package com.solvway.mobile.api.config;
|
||||
|
||||
import com.google.cloud.pubsub.v1.SubscriptionAdminClient;
|
||||
import com.google.cloud.spring.pubsub.PubSubAdmin;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
@Configuration
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class PubSubConfig {
|
||||
private final PubSubAdmin pubSubAdmin;
|
||||
|
||||
private final SubscriptionAdminClient subscriptionAdminClient;
|
||||
|
||||
private final PubSubUtil pubSubUtil;
|
||||
|
||||
@Value("${spring.cloud.gcp.project-id}")
|
||||
public String projectId;
|
||||
|
||||
@Value("${pubsub.response-time-log.topic}")
|
||||
public String responseTimeLogTopic;
|
||||
|
||||
@Value("${pubsub.email.save-request.topic}")
|
||||
public String emailSaveRequestTopic;
|
||||
|
||||
@PostConstruct
|
||||
public void newTopic() {
|
||||
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
|
||||
executor.submit(() -> pubSubUtil.createTopicIfNotExists(pubSubAdmin, responseTimeLogTopic));
|
||||
executor.submit(() -> pubSubUtil.createTopicIfNotExists(pubSubAdmin, emailSaveRequestTopic));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.solvway.mobile.api.config;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.cache.RedisCacheConfiguration;
|
||||
import org.springframework.data.redis.cache.RedisCacheManager;
|
||||
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
|
||||
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.serializer.GenericToStringSerializer;
|
||||
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.RedisSerializationContext.SerializationPair;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
|
||||
@Value("${cache.time-to-live}")
|
||||
private int defaultTtl;
|
||||
|
||||
@Value("${spring.data.redis.host}")
|
||||
public String hostname;
|
||||
|
||||
@Value("${spring.data.redis.port}")
|
||||
public int port;
|
||||
|
||||
@Bean
|
||||
JedisConnectionFactory jedisConnectionFactory() {
|
||||
return new JedisConnectionFactory(new RedisStandaloneConfiguration(hostname, port));
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedisTemplate<String,Object> redisTemplate() {
|
||||
final RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
|
||||
redisTemplate.setKeySerializer(new StringRedisSerializer());
|
||||
redisTemplate.setHashKeySerializer(new GenericToStringSerializer<>(Object.class));
|
||||
redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
|
||||
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
|
||||
redisTemplate.setConnectionFactory(jedisConnectionFactory());
|
||||
return redisTemplate;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedisCacheConfiguration cacheConfiguration() {
|
||||
ClassLoader loader = Thread.currentThread().getContextClassLoader();
|
||||
JdkSerializationRedisSerializer jdkSerializer = new JdkSerializationRedisSerializer(loader);
|
||||
SerializationPair<Object> pair = SerializationPair.fromSerializer(jdkSerializer);
|
||||
|
||||
return RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(Duration.ofSeconds(defaultTtl))
|
||||
.disableCachingNullValues().serializeValuesWith(pair);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedisCacheManager cacheManager() {
|
||||
return RedisCacheManager.builder(jedisConnectionFactory())
|
||||
.cacheDefaults(cacheConfiguration())
|
||||
.transactionAware()
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
package com.solvway.mobile.api.config;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Fails application startup when a security-critical property is missing or too weak.
|
||||
* Replaces the previous silent fallbacks (empty JWT signing key, committed API-key literals).
|
||||
*/
|
||||
@Component
|
||||
public class StartupSecurityConfigValidator {
|
||||
|
||||
static final int MIN_JWT_SECRET_LENGTH = 32;
|
||||
|
||||
private final String jwtSecret;
|
||||
private final String outboundApiKey;
|
||||
private final AuthAppKeyConfig authAppKeyConfig;
|
||||
|
||||
StartupSecurityConfigValidator(@Value("${jwt.secret:}") String jwtSecret,
|
||||
@Value("${app.api-key:}") String outboundApiKey,
|
||||
AuthAppKeyConfig authAppKeyConfig) {
|
||||
this.jwtSecret = jwtSecret;
|
||||
this.outboundApiKey = outboundApiKey;
|
||||
this.authAppKeyConfig = authAppKeyConfig;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void validate() {
|
||||
validateJwtSecret();
|
||||
validateOutboundApiKey();
|
||||
validateInboundApiKeys();
|
||||
}
|
||||
|
||||
private void validateJwtSecret() {
|
||||
String value = normalise(jwtSecret);
|
||||
if (value.isEmpty()) {
|
||||
throw new IllegalStateException(
|
||||
"jwt.secret is not configured. Set the JWT_SECRET environment variable.");
|
||||
}
|
||||
if (value.length() < MIN_JWT_SECRET_LENGTH) {
|
||||
throw new IllegalStateException(
|
||||
"jwt.secret is too short. JWT_SECRET must be at least " + MIN_JWT_SECRET_LENGTH + " characters.");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateOutboundApiKey() {
|
||||
if (normalise(outboundApiKey).isEmpty()) {
|
||||
throw new IllegalStateException(
|
||||
"app.api-key is not configured. Set the APIKEY environment variable.");
|
||||
}
|
||||
}
|
||||
|
||||
private void validateInboundApiKeys() {
|
||||
List<String> keys = authAppKeyConfig == null ? null : authAppKeyConfig.getList();
|
||||
boolean hasUsableKey = keys != null && keys.stream().anyMatch(key -> !normalise(key).isEmpty())
|
||||
&& authAppKeyConfig.hasKeys();
|
||||
if (!hasUsableKey) {
|
||||
throw new IllegalStateException(
|
||||
"auth.api-key.list is empty. Set the AUTH_API_KEYS environment variable "
|
||||
+ "to a comma-separated list of inbound client API keys.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Trims the value and collapses Spring's quoted-empty placeholder defaults ({@code ''} and {@code ""})
|
||||
* to the empty string, so they are treated as "not configured" rather than as a two-character secret.
|
||||
*/
|
||||
private String normalise(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
if ("''".equals(trimmed) || "\"\"".equals(trimmed)) {
|
||||
return "";
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.solvway.mobile.api.constant.api;
|
||||
|
||||
public class RestApiAuthServiceConstants {
|
||||
|
||||
private RestApiAuthServiceConstants() {}
|
||||
|
||||
public static final String API_REST_AUTHENTICATION= "/auth/webMemberAuthenticate";
|
||||
public static final String API_REST_AUTHENTICATION_AUTO_LOGIN_UPDATE= "/auth/memberAutoLoginUpdate";
|
||||
public static final String API_REST_AUTHENTICATION_FINGER_PRINT_LOGIN= "/auth/fingerPrintLoginWithToken/{token}/{memberCode}";
|
||||
public static final String API_REST_REFRESH_TOKEN = "/auth/refreshToken/{token}";
|
||||
public static final String API_REST_SYSTEM_GET_USER_BYTOKEN = "/auth/findUserByToken/{area}/{token}";
|
||||
public static final String API_REST_LOGOUT_TOKEN= "/auth/logoutToken/{token}";
|
||||
public static final String API_REST_AES_ENCRYPT="/auth/aes/encrypt";
|
||||
public static final String API_REST_AES_DECRYPT="/auth/aes/decrypt";
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.solvway.mobile.api.constant.api;
|
||||
|
||||
public class RestApiCounterServiceConstants {
|
||||
|
||||
private RestApiCounterServiceConstants() {}
|
||||
|
||||
//Event
|
||||
public static final String API_REST_COUNTER_EVENT_FIND_CURRENT_EVENT = "/counter/event/findCurrentEvent";
|
||||
|
||||
//Check in booth
|
||||
public static final String API_REST_COUNTER_EVENT_CHECK_IN_BOOTH = "/counter/checkInBooth/save";
|
||||
public static final String API_REST_COUNTER_EVENT_CHECK_IN_BOOTH_DIRECT_REDEEM_CODE = "/counter/checkInBooth/directGetRedeemCode";
|
||||
public static final String API_REST_COUNTER_EVENT_CHECK_IN_BOOTH_FIND_EXISTED = "/counter/checkInBooth/findCheckInExisted";
|
||||
public static final String API_REST_COUNTER_EVENT_CHECK_IN_BOOTH_FIND_BY_MEMBER_UUID = "/counter/checkInBooth/findByMemberUuid/{memberUuid}";
|
||||
|
||||
//Event Receipt
|
||||
public static final String API_REST_COUNTER_EVENT_RECEIPT_SAVE="/counter/eventReceipt/save";
|
||||
public static final String API_REST_COUNTER_EVENT_RECEIPT_FIND_BY_UUID="/counter/eventReceipt/findByUuid/{uuid}";
|
||||
public static final String API_REST_COUNTER_EVENT_RECEIPT_FIND_BY_EVENT_UUID_AND_MEMBER_UUID="/counter/eventReceipt/findByEventUuidAndMemberUuid/{eventUuid}/{memberUuid}";
|
||||
|
||||
//Event Lucky Draw Ticket
|
||||
public static final String API_REST_COUNTER_EVENT_LUCKY_DRAW_TICKET_FIND_BY_EVENT_UUID_AND_MEMBER_UUID="/counter/eventLuckyDrawTicket/findByEventUuidAndMemberUuid/{eventUuid}/{memberUuid}";
|
||||
public static final String API_REST_COUNTER_EVENT_LUCKY_DRAW_TICKET_FIND_BY_EVENT_UUID_AND_RECEIPT_UUID="/counter/eventLuckyDrawTicket/findByEventUuidAndReceiptUuid/{eventUuid}/{receiptUuid}";
|
||||
|
||||
//Event Gift With Purchase
|
||||
public static final String API_REST_COUNTER_EVENT_GIFT_WITH_PURCHASE_FIND_BY_EVENT_UUID_AND_MEMBER_UUID = "/counter/eventGiftWithPurchase/findByEventUuidAndMemberUuid/{eventUuid}/{memberUuid}";
|
||||
|
||||
//Event Redeem Code
|
||||
public static final String API_REST_COUNTER_EVENT_REDEEM_CODE_FIND_BY_UUID="/counter/eventRedeemCode/findByUuid/{uuid}";
|
||||
public static final String API_REST_COUNTER_EVENT_REDEEM_CODE_FIND_BY_EVENT_UUID_AND_MEMBER_UUID="/counter/eventRedeemCode/findByEventUuidAndMemberUuid";
|
||||
public static final String API_REST_COUNTER_EVENT_REDEEM_CODE_FIND_BY_EVENT_UUID_AND_STOCKIST_UUID_AND_MEMBER_UUID="/counter/eventRedeemCode/findByEventUuidAndStockistUuidAndMemberUuid";
|
||||
public static final String API_REST_COUNTER_EVENT_REDEEM_CODE_FIND_BY_MEMBER_UUID="/counter/eventRedeemCode/findByMemberUuid/{memberUuid}";
|
||||
public static final String API_REST_COUNTER_EVENT_FIND_BY_UUID="/counter/event/findByUuid/{uuid}";
|
||||
|
||||
//Event Product
|
||||
public static final String API_REST_COUNTER_EVENT_PRODUCT_FIND_BY_EVENT_UUID = "/counter/eventProduct/findByEventUuid/{eventUuid}";
|
||||
|
||||
//Member Voucher
|
||||
public static final String API_REST_COUNTER_MEMBER_VOUCHER_FIND_ELIGIBILITY="/counter/memberVoucher/findEligibility";
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package com.solvway.mobile.api.constant.api;
|
||||
|
||||
public class RestApiDriveServiceConstants {
|
||||
|
||||
private RestApiDriveServiceConstants() {}
|
||||
|
||||
public static final String API_REST_DRIVE_UPLOAD = "/storage/upload";
|
||||
public static final String API_REST_DRIVE_PRIVATE_FILE_V2 = "/storage/loadPrivateFileV2";
|
||||
public static final String API_REST_DRIVE_GET_PRESIGNED_URL = "/storage/getPresignedUrl";
|
||||
public static final String API_REST_DRIVE_GET_PRESIGNED_URL_PUBLIC = "/storage/getPresignedUrl/public";
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.solvway.mobile.api.constant.api;
|
||||
|
||||
public class RestApiEmailServiceConstants {
|
||||
|
||||
private RestApiEmailServiceConstants() {}
|
||||
|
||||
public static final String API_REST_EMAIL_SEND = "/email/send";
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.solvway.mobile.api.constant.api;
|
||||
|
||||
public class RestApiMemberServiceConstants {
|
||||
|
||||
private RestApiMemberServiceConstants() {}
|
||||
|
||||
public static final String API_REST_MEMBER_MEMBER_FIND_BY_ID = "/member/findById/{id}";
|
||||
public static final String API_REST_MEMBER_REPLICATED_URL = "/member/replicatedUrl/{memberCode}";
|
||||
public static final String API_REST_MEMBER_MEMBER_FIND_BY_USERNAME = "/member/findByUsername/{username}";
|
||||
public static final String API_REST_MEMBER_MEMBER_FIND_BY_MEMBER_CODE= "/member/findByMemberCode/{memberCode}";
|
||||
public static final String API_REST_MEMBER_MEMBER_EXISTS_ACTIVE_BY_MEMBER_CODE = "/member/existsActiveByMemberCode/{memberCode}";
|
||||
public static final String API_REST_MEMBER_REQUEST_DELETION ="/member/requestDeletion";
|
||||
public static final String API_REST_MEMBER_FORGET_PASSWORD = "/member/forgetPassword/{email}";
|
||||
public static final String API_REST_MEMBER_MEMBER_SAVE = "/member/save";
|
||||
public static final String API_REST_MEMBER_MEMBER_REG_NEW_MEMBER = "/member/registerNewMember";
|
||||
public static final String API_REST_MEMBER_MEMBER_REG_NEW_MEMBER_SELF_SERVICE = "/member/registerNewMemberSelfService";
|
||||
public static final String API_REST_MEMBER_MEMBER_FIND_BY_PHONE_NO_AND_PHONE_PREFIX_ID_NOT = "/member/findByPhoneNoAndPhoneNoPrefixAndIdNot/{phoneNo}/{phoneNoPrefix}/{id}";
|
||||
public static final String API_REST_MEMBER_COUNT_REFERRALS_BY_SPONSOR = "/member/countReferralsBySponsor/{memberCode}";
|
||||
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package com.solvway.mobile.api.constant.api;
|
||||
|
||||
public class RestApiPaymentServiceConstants {
|
||||
|
||||
private RestApiPaymentServiceConstants() {}
|
||||
|
||||
//Tastefully Point
|
||||
public static final String API_REST_TASTEFULLY_POINT_FIND_WALLET_BY_UUID = "/payment/tastefullyPoint/findWalletByUuid/{uuid}";
|
||||
public static final String API_REST_TASTEFULLY_POINT_GET_WALLET = "/payment/tastefullyPoint/getWallet/{ownerUuid}";
|
||||
public static final String API_REST_TASTEFULLY_POINT_TRXN_FIND_ALL_PAGEABLE = "/payment/tastefullyPoint/trxn/findByPropertyAndPageable";
|
||||
public static final String API_REST_TASTEFULLY_POINT_GET_BALANCE_NO_CACHE = "/payment/tastefullyPoint/getBalanceNoCache/{memberUuid}";
|
||||
public static final String API_REST_TASTEFULLY_POINT_GET_BALANCE_CACHE = "/payment/tastefullyPoint/getBalanceCache/{memberUuid}";
|
||||
public static final String API_REST_TASTEFULLY_POINT_TRXN_FIND_BY_UUID = "/payment/tastefullyPoint/trxn/findByUuid/{uuid}";
|
||||
public static final String API_REST_TASTEFULLY_POINT_SUM_REFERRAL_EARNED = "/payment/tastefullyPoint/sumReferralEarned/{ownerUuid}";
|
||||
|
||||
//QRPayment
|
||||
public static final String API_REST_PAYMENT_QR_SCAN_GET_QR_TEXT_FOR_MERCHANT_SCAN = "/payment/qrScan/getQrTextForMerchantScan";
|
||||
public static final String API_REST_PAYMENT_QR_SCAN_FIND_QR_SCAN_TRAN_BY_UUID = "/payment/qrScan/findQrScanTranByUuid/{uuid}";
|
||||
public static final String API_REST_PAYMENT_QR_SCAN_USER_SCAN_QR = "/payment/qrScan/userScanQr";
|
||||
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.solvway.mobile.api.constant.api;
|
||||
|
||||
public class RestApiStockistServiceConstants {
|
||||
|
||||
private RestApiStockistServiceConstants() {}
|
||||
|
||||
//Stockist CMS Profile
|
||||
public static final String API_REST_STOCKIST_CMS_PROFILE_FIND_TOP_DISPLAY = "/stockist/stockistCmsProfile/findTopForDisplay";
|
||||
public static final String API_REST_STOCKIST_CMS_PROFILE_FIND_ALL_DISPLAY = "/stockist/stockistCmsProfile/findAllForDisplay";
|
||||
public static final String API_REST_STOCKIST_CMS_PROFILE_FIND_BY_STOCKIST_UUID = "/stockist/stockistCmsProfile/findByStockistUuid/{stockistUuid}";
|
||||
|
||||
//Stockist CMS Product
|
||||
public static final String API_REST_STOCKIST_CMS_PRODUCT_FIND_BY_STOCKIST_UUID = "/stockist/stockistCmsProduct/findByStockistUuid/{stockistUuid}";
|
||||
|
||||
//Stockist Category Tag
|
||||
public static final String API_REST_STOCKIST_CATEGORY_TAG_FIND_ALL = "/stockist/stockistCategoryTag/findAll";
|
||||
public static final String API_REST_STOCKIST_CATEGORY_TAG_FIND_BY_UUID = "/stockist/stockistCategoryTag/findByUuid/{uuid}";
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.solvway.mobile.api.constant.api;
|
||||
|
||||
public class RestApiSystemServiceConstants {
|
||||
|
||||
private RestApiSystemServiceConstants() {}
|
||||
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_USERNAME = "/user/findByUsername/{username}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_EXIST_BY_USERNAME = "/user/findExistByUsername/{username}";
|
||||
public static final String API_REST_SYSTEM_USER_FIND_BY_USERNAME_WITH_PASSWORD = "/user/findByUsernameWithPassword/{username}";
|
||||
public static final String API_REST_SYSTEM_USER_UPDATE_MEMBER_PHONE_VERIFIED = "/user/updatePhoneVerified";
|
||||
public static final String API_REST_SYSTEM_USER_UPDATE_MEMBER_PASSWORD = "/user/updateMemberPassword";
|
||||
public static final String API_REST_SYSTEM_USER_GET_ENCRYPTED_STRING="/user/getEncryptedStringForPassword";
|
||||
public static final String API_REST_SYSTEM_USER_CHECK_ENCRYPTED_STRING_MATCHED="/user/checkEncryptedStringMatched";
|
||||
public static final String API_REST_SYSTEM_USER_FIRST_TIME_LOGIN="/user/memberFirstTimeLogin";
|
||||
public static final String API_REST_SYSTEM_USER_VALIDATE_PASSWORD_RULES="/user/validatePasswordFromRulesForMember";
|
||||
|
||||
//OneTimePassword
|
||||
public static final String API_REST_SYSTEM_OTP_GENERATE_OTP_EMAIL = "/system/oneTimePassword/generateOneTimePasswordEmail";
|
||||
public static final String API_REST_SYSTEM_OTP_GENERATE_OTP_SMS = "/system/oneTimePassword/generateOneTimePasswordSms";
|
||||
public static final String API_REST_SYSTEM_OTP_VERIFY_OTP="/system/oneTimePassword/verifyOneTimePassword";
|
||||
public static final String API_REST_SYSTEM_OTP_FIND_BY_CODE="/system/oneTimePassword/findByCode/{code}";
|
||||
public static final String API_REST_SYSTEM_OTP_FIND_VALID_BY_IDENTITY_REF="/system/oneTimePassword/findValidByIdentityRef/{identityRef}";
|
||||
|
||||
//AppInitialize
|
||||
public static final String API_REST_SYSTEM_APP_INITIALIZE = "/appInitialize/init";
|
||||
|
||||
//LocationHierarchy
|
||||
public static final String API_REST_SYSTEM_LOCATION_HIERARCHY_FIND_BYCODE = "/locationHierarchy/findByCode/{code}";
|
||||
public static final String API_REST_SYSTEM_LOCATION_HIERARCHY_FIND_CONFIG_BY_CTRY = "/locationHierarchy/findConfigByCountry/{countryCode}";
|
||||
//GeoLocationHierarchy
|
||||
public static final String API_REST_GEOLOCATION_HIERARCHY_FIND_BYID = "/geoLocationHierarchy/findById/{id}";
|
||||
public static final String API_REST_SYSTEM_GEO_LOCATION_HIERARCHY_FIND_FIRST_LEVEL="/geoLocationHierarchy/findByFirstLevelLocation";
|
||||
public static final String API_REST_SYSTEM_GEO_LOCATION_HIERARCHY_FIND_NEXT_LEVEL="/geoLocationHierarchy/findAllByParentId/{parentId}";
|
||||
public static final String API_REST_GEOLOCATION_HIERARCHY_VALIDATE_ID = "/geoLocationHierarchy/validateGeoLocationById/{id}";
|
||||
public static final String API_REST_GEOLOCATION_HIERARCHY_GENERATE_ADDRESS="/geoLocationHierarchy/generateAddress/{id}/{locale}";
|
||||
//CountryConfig
|
||||
|
||||
//Race
|
||||
|
||||
//Message
|
||||
public static final String API_REST_SYSTEM_MESSAGE_JSON_BY_AREA_AND_LOCALE = "/message/getMessageJsonByAreaAndLocale/{area}/{locale}";
|
||||
|
||||
//Nationality
|
||||
public static final String API_REST_NATIONALITY_FIND_BYCODE = "/nationality/findByCode/{code}";
|
||||
|
||||
//Bulletin
|
||||
public static final String API_REST_BULLETIN_FIND_ACTIVE_BY_TYPE = "/bulletin/findActiveBulletinsByType/{type}";
|
||||
|
||||
//AppBanner (global announcement banner)
|
||||
public static final String API_REST_APP_BANNER_FIND_ACTIVE = "/system/appBanner/findActive";
|
||||
|
||||
//AppPromo (home promo carousel)
|
||||
public static final String API_REST_APP_PROMO_FIND_ACTIVE = "/system/appPromo/findActive";
|
||||
|
||||
//Article
|
||||
public static final String API_REST_ARTICLE_FIND_BY_UUID = "/system/article/findByUuid/{uuid}";
|
||||
public static final String API_REST_ARTICLE_FIND_BY_TYPE_AND_STATUS_ORDER_ID_DESC = "/system/article/findByTypeAndStatusOrderByIdDesc/{type}/{status}";
|
||||
|
||||
//Album
|
||||
public static final String API_REST_ALBUM_FIND_BY_UUID = "/system/album/findByUuid/{uuid}";
|
||||
public static final String API_REST_ALBUM_FIND_BY_ENABLED = "/system/album/findByEnabled/{enabled}";
|
||||
public static final String API_REST_ALBUM_DETAIL_FIND_BY_ALBUM_UUID = "/system/album/detail/findByAlbumUuid/{albumUuid}";
|
||||
public static final String API_REST_ALBUM_DETAIL_FIND_DETAIL_FIRST_BY_ALBUM_UUID = "/system/album/detail/findDetailFirstByAlbumUuid/{albumUuid}";
|
||||
|
||||
//EventSchedule
|
||||
public static final String API_REST_EVENT_SCHEDULE_FIND_ENABLED_DISPLAY = "/system/eventSchedule/findEnabledForDisplay";
|
||||
|
||||
//GenericHierarchy
|
||||
public static final String API_REST_GENERIC_HIERARCHY_FIND_BY_UUID = "/system/genericHierarchy/findByUuid/{uuid}";
|
||||
public static final String API_REST_GENERIC_HIERARCHY_FIND_FULL_BY_TYPE_AND_UUID = "/system/genericHierarchy/findFullHierarchyByHierarchyTypeAndUuid/{hierarchyType}/{uuid}";
|
||||
public static final String API_REST_GENERIC_HIERARCHY_FIND_ROOT_BY_TYPE = "/system/genericHierarchy/findRootByHierarchyType/{hierarchyType}";
|
||||
|
||||
//HelpCenterPost
|
||||
public static final String API_REST_HELP_CENTER_POST_FIND_BY_HIERARCHY_UUID = "/system/helpCenterPost/findByGenericHierarchyUuid/{genericHierarchyUuid}";
|
||||
|
||||
//GenericPost
|
||||
public static final String API_REST_GENERIC_POST_FIND_BY_UUID = "/system/genericPost/findByUuid/{uuid}";
|
||||
public static final String API_REST_GENERIC_POST_CONTENT_FIND_BY_UUID_AND_LOCALE = "/system/genericPost/content/findByPostUuidAndLocale/{uuid}/{locale}";
|
||||
|
||||
//Message
|
||||
public static final String API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE = "/message/findByCodeAndLocale/{code}/{locale}";
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.model.AppInit;
|
||||
import com.solvway.mobile.api.service.SystemService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/app")
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class AppController {
|
||||
private final SystemService systemService;
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/initialize")
|
||||
public ResponseEntity<Map<String, Object>> initialize(@RequestBody AppInit appInit) {
|
||||
return ResponseEntity.ok(systemService.appInitialize(appInit));
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import com.solvway.mobile.api.model.AuthRequest;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/auth")
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class AuthController {
|
||||
private static final String RESULT_KEY = "result";
|
||||
private final AuthenticationService authenticationService;
|
||||
private final MemberService memberService;
|
||||
private final ValidateUtil validateUtil;
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/login")
|
||||
public ResponseEntity<Map<String, String>> login(@RequestBody AuthRequest request){
|
||||
String username = request.getUsername();
|
||||
//[START TASTEFULLY USERNAME] Allow to have email or phone number, so need to massage 601xxx
|
||||
username = username.replaceAll("\\s", "");
|
||||
if(username.startsWith("+6")){
|
||||
username = username.substring(1);
|
||||
}
|
||||
if(validateUtil.isNumeric(username)) {
|
||||
if(username.startsWith("0")){
|
||||
username = "6"+username;
|
||||
}
|
||||
if(username.startsWith("600")){
|
||||
username = username.replaceFirst("600", "60");
|
||||
}
|
||||
}
|
||||
//[END TASTEFULLY USERNAME] Allow to have email or phone number, so need to massage 601xxx
|
||||
request.setUsername(username);
|
||||
Map<String, String> response = new HashMap<>();
|
||||
String token = authenticationService.getToken(request);
|
||||
if(StringUtils.hasLength(token)){
|
||||
User u = authenticationService.loadUserByToken(token);
|
||||
if(u==null){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
response.put(RESULT_KEY, "true");
|
||||
response.put("token", token);
|
||||
response.put("memberCode", u.getMemberCode());
|
||||
response.put("name", u.getName());
|
||||
response.put("phoneNoPrefix", u.getPhoneNoPrefix());
|
||||
response.put("phoneNo", u.getPhoneNo());
|
||||
response.put("resetPasswordRequired", u.getLogin().equals(GeneralEnum.LoginStatus.N)? "true": "false");
|
||||
response.put("phoneVerificationRequired", u.getPhoneVerified() != GeneralEnum.FlagYesNo.Y && u.getEmailVerified() != GeneralEnum.FlagYesNo.Y ? "true" : "false");
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
response.put(RESULT_KEY, "false");
|
||||
response.put("message", "Invalid username or password");
|
||||
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(response);
|
||||
}
|
||||
@PostMapping("/memberAutoLoginUpdate")
|
||||
public ResponseEntity<Map<String, String>> memberAutoLoginUpdate(@RequestBody Map<String, String> param){
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(token);
|
||||
if(!StringUtils.hasLength(memberCode)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Map<String, String> response = new HashMap<>();
|
||||
response.put(RESULT_KEY, String.valueOf(authenticationService.memberAutoLoginUpdate(param)));
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
@PostMapping("/fingerPrintLogin")
|
||||
public ResponseEntity<Map<String, String>> fingerPrintLogin(@RequestBody Map<String, String> param){
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(token);
|
||||
if(!StringUtils.hasLength(memberCode)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
String memberCodeFromRequest = param.get("memberCode");
|
||||
if(!StringUtils.hasLength(memberCodeFromRequest)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
if(!memberCode.equals(memberCodeFromRequest)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Map<String, String> response = new HashMap<>();
|
||||
response.put(RESULT_KEY, String.valueOf(authenticationService.fingerPrintLogin(memberCode, memberCodeFromRequest)));
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
}
|
||||
+542
@@ -0,0 +1,542 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.OrderEnum;
|
||||
import com.solvway.core.enums.PaymentEnum;
|
||||
import com.solvway.core.model.CheckInBooth;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.EventProduct;
|
||||
import com.solvway.core.model.EventReceipt;
|
||||
import com.solvway.core.model.EventRedeemCode;
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.model.StockistCmsProfile;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.NumberFormatterUtil;
|
||||
import com.solvway.core.utils.QrScanUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.DriveService;
|
||||
import com.solvway.mobile.api.service.EventService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.StockistCmsService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping("/api/event")
|
||||
@RequiredArgsConstructor
|
||||
public class EventController {
|
||||
private final EventService eventService;
|
||||
private final DriveService driveService;
|
||||
private final DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
private final NumberFormatterUtil numberFormatterUtil;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final QrScanUtil qrScanUtil;
|
||||
private final StockistCmsService stockistCmsService;
|
||||
private final MemberService memberService;
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/upcomingEvent")
|
||||
public ResponseEntity<String> getUpcomingEvent() {
|
||||
//Ensure it synced with member-portal EventController
|
||||
return ResponseEntity.ok("https://s3-storage.containerverse.dev/tastefully-public-prd/UPCOMING_EVENT/upcoming-2026.jpg");
|
||||
}
|
||||
|
||||
@GetMapping("/currentEventConfig")
|
||||
public ResponseEntity<Map<String, Object>> getCurrentEventConfig() {
|
||||
Optional<Event> currentEventOptional = eventService.findCurrentEvent();
|
||||
if (currentEventOptional.isEmpty()) {
|
||||
return ResponseEntity.ok(null);
|
||||
}
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
Event currentEvent = currentEventOptional.get();
|
||||
if (StringUtils.hasLength(currentEvent.getUploadFloorPlan())) {
|
||||
response.put("currentEventFloorPlan",
|
||||
driveService.getPresignedUrl(currentEvent.getUploadFloorPlan(), 24, TimeUnit.HOURS));
|
||||
}
|
||||
if (StringUtils.hasLength(currentEvent.getUploadStageActivities())) {
|
||||
response.put("currentEventStageActivities",
|
||||
driveService.getPresignedUrl(currentEvent.getUploadStageActivities(), 24, TimeUnit.HOURS));
|
||||
}
|
||||
if (StringUtils.hasLength(currentEvent.getUploadLuckyDraw())) {
|
||||
response.put("currentEventLuckyDraw",
|
||||
driveService.getPresignedUrl(currentEvent.getUploadLuckyDraw(), 24, TimeUnit.HOURS));
|
||||
}
|
||||
if (StringUtils.hasLength(currentEvent.getUploadTasteRewards())) {
|
||||
response.put("currentEventTasteRewards",
|
||||
driveService.getPresignedUrl(currentEvent.getUploadTasteRewards(), 24, TimeUnit.HOURS));
|
||||
}
|
||||
// Products are sent whether or not the "How to redeem" document is uploaded:
|
||||
// customer-portal unlocks the Taste Rewards+ tile on products alone.
|
||||
List<EventProduct> eventProducts = eventService.findEventProductByEventUuid(currentEvent.getUuid());
|
||||
List<EventProduct> eventProductList = (eventProducts == null ? List.<EventProduct>of() : eventProducts)
|
||||
.parallelStream()
|
||||
.map(ep -> {
|
||||
ep.setPriceDisplay(numberFormatterUtil.format(ep.getCostAmount(), NumberFormatterUtil.wholeFormatter) + " Points");
|
||||
if (StringUtils.hasLength(ep.getAddOnCostLabel())) {
|
||||
ep.setPriceDisplay(ep.getPriceDisplay() + " " + ep.getAddOnCostLabel());
|
||||
}
|
||||
return ep;
|
||||
})
|
||||
.sorted(Comparator.comparing(EventProduct::getCostAmount))
|
||||
.toList();
|
||||
response.put("currentEventTasteRewardsProductList", eventProductList);
|
||||
Map<String, String> eventMap = new HashMap<>();
|
||||
eventMap.put("uuid", String.valueOf(currentEvent.getUuid()));
|
||||
eventMap.put("name", currentEvent.getName());
|
||||
eventMap.put("location", currentEvent.getLocation());
|
||||
try{
|
||||
eventMap.put("dateStart", dateTimeFormatterUtil.format(currentEvent.getDateStart()));
|
||||
eventMap.put("dateEnd", dateTimeFormatterUtil.format(currentEvent.getDateEnd()));
|
||||
} catch (Exception ignored) {
|
||||
log.debug("Date formatting failed for event: {}", currentEvent.getUuid(), ignored);
|
||||
}
|
||||
response.put("currentEvent", eventMap);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
@PostMapping("/checkIn")
|
||||
public ResponseEntity<Map<String, Object>> checkIn(@RequestBody Map<String, String> requestBody) {
|
||||
String qrText = requestBody.get("qrText");
|
||||
if (!StringUtils.hasLength(qrText)) {
|
||||
return ResponseEntity.ok(Map.of("status", "INVALID_QR"));
|
||||
}
|
||||
PaymentEnum.QrScanCodeAction action = qrScanUtil.getQrScanCodeAction(qrText);
|
||||
if (action != PaymentEnum.QrScanCodeAction.CI) {
|
||||
return ResponseEntity.ok(Map.of("status", "WRONG_QR_TYPE"));
|
||||
}
|
||||
qrText = qrScanUtil.extractQrTextExcludeActionPrefix(qrText);
|
||||
|
||||
Optional<Event> currentEventOptional = eventService.findCurrentEvent();
|
||||
if (currentEventOptional.isEmpty()) {
|
||||
log.warn("checkIn: no active event");
|
||||
return ResponseEntity.ok(Map.of("status", "NO_ACTIVE_EVENT"));
|
||||
}
|
||||
Event currentEvent = currentEventOptional.get();
|
||||
|
||||
String stockistUuid = authenticationService.decrypt(qrText);
|
||||
if (!StringUtils.hasLength(stockistUuid)) {
|
||||
log.warn("checkIn: decrypt returned blank for qrText");
|
||||
return ResponseEntity.ok(Map.of("status", "INVALID_QR"));
|
||||
}
|
||||
long stockistUuidLong;
|
||||
try {
|
||||
stockistUuidLong = Long.parseLong(stockistUuid);
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("checkIn: stockist uuid not numeric: {}", stockistUuid);
|
||||
return ResponseEntity.ok(Map.of("status", "INVALID_QR"));
|
||||
}
|
||||
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberUuidStr = authenticationService.getMemberUuidFromToken(token);
|
||||
if (!StringUtils.hasLength(memberUuidStr)) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||
}
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(token);
|
||||
|
||||
CheckInBooth checkInBooth = new CheckInBooth();
|
||||
checkInBooth.setEventUuid(currentEvent.getUuid());
|
||||
checkInBooth.setStockistUuid(stockistUuidLong);
|
||||
checkInBooth.setMemberUuid(Long.parseLong(memberUuidStr));
|
||||
checkInBooth.setCreateBy(memberCode);
|
||||
checkInBooth.setDoneBy(memberCode);
|
||||
|
||||
// Idempotency: one check-in per member per event per day, at any booth. checkInBooth.checkInDate
|
||||
// defaults to today, so this matches on (event, member, today).
|
||||
if (eventService.findCheckInExisted(checkInBooth)) {
|
||||
log.info("checkIn: already checked in today for stockist={} member={}", stockistUuid, memberUuidStr);
|
||||
Map<String, Object> alreadyResponse = new HashMap<>();
|
||||
alreadyResponse.put("status", "ALREADY_CHECKED_IN");
|
||||
alreadyResponse.put("eventName", currentEvent.getName());
|
||||
return ResponseEntity.ok(alreadyResponse);
|
||||
}
|
||||
|
||||
CheckInBooth saved = eventService.saveCheckInBooth(checkInBooth);
|
||||
if (saved == null) {
|
||||
log.error("checkIn: saveCheckInBooth returned null for stockist={} member={}", stockistUuid, memberUuidStr);
|
||||
return ResponseEntity.ok(Map.of("status", "CHECK_IN_FAILED"));
|
||||
}
|
||||
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("status", "CHECKED_IN");
|
||||
response.put("eventName", currentEvent.getName());
|
||||
try {
|
||||
stockistCmsService.findByStockistUuid(stockistUuid).ifPresent(profile -> {
|
||||
if (StringUtils.hasLength(profile.getStockistName())) {
|
||||
response.put("stockistName", profile.getStockistName());
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
log.warn("checkIn: stockist name lookup failed, omitting: {}", e.getMessage());
|
||||
}
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
// Authenticated: JWT is validated by AppAccessAspect (no @AppAuth(skipValidate=true) = auth required).
|
||||
@GetMapping("/checkIns")
|
||||
public ResponseEntity<List<Map<String, Object>>> getCheckIns() {
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberUuidStr = authenticationService.getMemberUuidFromToken(token);
|
||||
if (!StringUtils.hasLength(memberUuidStr)) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||
}
|
||||
long memberUuid;
|
||||
try {
|
||||
memberUuid = Long.parseLong(memberUuidStr);
|
||||
} catch (NumberFormatException e) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||
}
|
||||
|
||||
List<CheckInBooth> checkIns = new ArrayList<>(eventService.findCheckInBoothByMemberUuid(memberUuid));
|
||||
checkIns.sort(Comparator.comparing(CheckInBooth::getCheckInDateTime,
|
||||
Comparator.nullsLast(Comparator.reverseOrder())));
|
||||
|
||||
Map<Long, String> nameCache = new HashMap<>();
|
||||
List<Map<String, Object>> response = new ArrayList<>();
|
||||
for (CheckInBooth ci : checkIns) {
|
||||
long stockistUuid = ci.getStockistUuid();
|
||||
String name;
|
||||
if (nameCache.containsKey(stockistUuid)) {
|
||||
name = nameCache.get(stockistUuid);
|
||||
} else {
|
||||
name = null;
|
||||
try {
|
||||
name = stockistCmsService.findByStockistUuid(String.valueOf(stockistUuid))
|
||||
.map(StockistCmsProfile::getStockistName)
|
||||
.filter(StringUtils::hasLength)
|
||||
.orElse(null);
|
||||
} catch (Exception e) {
|
||||
log.warn("getCheckIns: stockist name lookup failed for {}: {}", stockistUuid, e.getMessage());
|
||||
}
|
||||
nameCache.put(stockistUuid, name);
|
||||
}
|
||||
|
||||
Map<String, Object> item = new HashMap<>();
|
||||
item.put("stockistUuid", stockistUuid);
|
||||
item.put("eventUuid", ci.getEventUuid());
|
||||
if (name != null) {
|
||||
item.put("stockistName", name);
|
||||
}
|
||||
if (ci.getCheckInDateTime() != null) {
|
||||
item.put("checkInDateTime", ci.getCheckInDateTime().toString());
|
||||
}
|
||||
if (ci.getCheckInDate() != null) {
|
||||
item.put("checkInDate", ci.getCheckInDate().toString());
|
||||
}
|
||||
response.add(item);
|
||||
}
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
// Authenticated: JWT is validated by AppAccessAspect (no @AppAuth(skipValidate=true) = auth required).
|
||||
@GetMapping("/luckyDraw")
|
||||
public ResponseEntity<Map<String, Object>> getLuckyDraw() {
|
||||
Optional<EventMember> resolved = resolveCurrentEventAndMember();
|
||||
if (resolved.isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Event event = resolved.get().event();
|
||||
long memberUuid = resolved.get().memberUuid();
|
||||
LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
|
||||
|
||||
double totalSpent = eventService.findEventReceiptByEventUuidAndMemberUuid(event.getUuid(), memberUuid)
|
||||
.stream()
|
||||
.filter(r -> r.getUploadDateTime() != null && r.getUploadDateTime().isAfter(startOfDay))
|
||||
// Non-pending (Approved + Rejected) counts toward amount spent — mirrors member-portal's totalSpent.
|
||||
.filter(r -> r.getReviewStatus() != OrderEnum.EventReceiptReviewStatus.P)
|
||||
.mapToDouble(EventReceipt::getPurchaseAmount)
|
||||
.sum();
|
||||
|
||||
int ticketCount = (int) eventService.findEventLuckyDrawTicketByEventUuidAndMemberUuid(event.getUuid(), memberUuid)
|
||||
.stream()
|
||||
.filter(t -> t.getCreateDateTime() != null && t.getCreateDateTime().isAfter(startOfDay))
|
||||
.count();
|
||||
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("ticketCount", ticketCount);
|
||||
response.put("totalSpent", totalSpent);
|
||||
if (StringUtils.hasLength(event.getUploadLuckyDraw())) {
|
||||
response.put("posterUrl", driveService.getPresignedUrl(event.getUploadLuckyDraw(), 24, TimeUnit.HOURS));
|
||||
}
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
// Authenticated: JWT is validated by AppAccessAspect (no @AppAuth(skipValidate=true) = auth required).
|
||||
@GetMapping("/luckyDrawHistory")
|
||||
public ResponseEntity<List<Map<String, Object>>> getLuckyDrawHistory() {
|
||||
Optional<EventMember> resolved = resolveCurrentEventAndMember();
|
||||
if (resolved.isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Event event = resolved.get().event();
|
||||
long memberUuid = resolved.get().memberUuid();
|
||||
LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
|
||||
|
||||
List<Map<String, Object>> response = eventService.findEventReceiptByEventUuidAndMemberUuid(event.getUuid(), memberUuid)
|
||||
.stream()
|
||||
.filter(r -> r.getUploadDateTime() != null && r.getUploadDateTime().isAfter(startOfDay))
|
||||
.sorted(Comparator.comparing(EventReceipt::getUploadDateTime).reversed())
|
||||
.map(r -> {
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
try {
|
||||
row.put("uploadDateTime", dateTimeFormatterUtil.format(r.getUploadDateTime()));
|
||||
} catch (Exception ex) {
|
||||
row.put("uploadDateTime", r.getUploadDateTime().toString());
|
||||
}
|
||||
row.put("reviewStatus", r.getReviewStatus().name());
|
||||
row.put("reviewStatusLabel", r.getReviewStatus().getName());
|
||||
int ticketCount = 0;
|
||||
// Remote call per approved receipt — acceptable: today-scoped list is small (typically 1-3).
|
||||
if (r.getReviewStatus() == OrderEnum.EventReceiptReviewStatus.A) {
|
||||
ticketCount = eventService.findEventLuckyDrawTicketByEventUuidAndReceiptUuid(event.getUuid(), r.getUuid()).size();
|
||||
}
|
||||
row.put("ticketCount", ticketCount);
|
||||
List<String> receiptUrls = r.getUploadPath() == null ? List.of()
|
||||
: r.getUploadPath().stream()
|
||||
.filter(StringUtils::hasLength)
|
||||
.map(p -> driveService.getPresignedUrl(p, 24, TimeUnit.HOURS))
|
||||
.toList();
|
||||
row.put("receiptUrls", receiptUrls);
|
||||
return row;
|
||||
})
|
||||
.toList();
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
// Authenticated: JWT is validated by AppAccessAspect (no @AppAuth(skipValidate=true) = auth required).
|
||||
@GetMapping("/redeemCodes")
|
||||
public ResponseEntity<List<Map<String, Object>>> getRedeemCodes() {
|
||||
Optional<EventMember> resolved = resolveCurrentEventAndMember();
|
||||
if (resolved.isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Event event = resolved.get().event();
|
||||
long memberUuid = resolved.get().memberUuid();
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
List<Map<String, Object>> response = eventService.findEventRedeemCodeByEventUuidAndMemberUuid(event.getUuid(), memberUuid)
|
||||
.stream()
|
||||
.filter(c -> c.getExpiryDateTime() != null && c.getExpiryDateTime().isAfter(now))
|
||||
.sorted(Comparator.comparing(EventRedeemCode::getCreateDateTime).reversed())
|
||||
.map(this::toRedeemCodeSummary)
|
||||
.toList();
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
// Authenticated: JWT is validated by AppAccessAspect (no @AppAuth(skipValidate=true) = auth required).
|
||||
@GetMapping("/redeemCodes/history")
|
||||
public ResponseEntity<List<Map<String, Object>>> getRedeemCodeHistory() {
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberUuidStr = authenticationService.getMemberUuidFromToken(token);
|
||||
if (!StringUtils.hasLength(memberUuidStr)) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||
}
|
||||
long memberUuid;
|
||||
try {
|
||||
memberUuid = Long.parseLong(memberUuidStr);
|
||||
} catch (NumberFormatException e) {
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
|
||||
}
|
||||
|
||||
List<EventRedeemCode> codes = eventService.findEventRedeemCodeByMemberUuid(memberUuid);
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
// Keep only past codes: redeemed OR expired (or never expires)
|
||||
List<EventRedeemCode> filtered = new ArrayList<>();
|
||||
for (EventRedeemCode code : codes) {
|
||||
if (code.getRedeemStatus() == OrderEnum.EventRedeemCodeStatus.R
|
||||
|| code.getExpiryDateTime() == null
|
||||
|| code.getExpiryDateTime().isBefore(now)) {
|
||||
filtered.add(code);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by createDateTime descending, nulls last
|
||||
filtered.sort(Comparator.comparing(
|
||||
EventRedeemCode::getCreateDateTime,
|
||||
Comparator.nullsLast(Comparator.reverseOrder())));
|
||||
|
||||
Map<Long, String> stockistNameCache = new HashMap<>();
|
||||
Map<Long, String> eventNameCache = new HashMap<>();
|
||||
List<Map<String, Object>> response = new ArrayList<>();
|
||||
for (EventRedeemCode code : filtered) {
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
row.put("uuid", code.getUuid());
|
||||
row.put("eventUuid", code.getEventUuid());
|
||||
row.put("redeemStatus", code.getRedeemStatus().name());
|
||||
|
||||
// expiryDateTime — same formatting as toRedeemCodeSummary
|
||||
try {
|
||||
row.put("expiryDateTime", code.getExpiryDateTime() == null ? null
|
||||
: dateTimeFormatterUtil.format(code.getExpiryDateTime()));
|
||||
} catch (Exception ex) {
|
||||
row.put("expiryDateTime", code.getExpiryDateTime() == null ? null
|
||||
: code.getExpiryDateTime().toString());
|
||||
}
|
||||
|
||||
row.put("redeemedDateTime", code.getRedeemedDateTime());
|
||||
row.put("createDateTime", code.getCreateDateTime() == null ? null
|
||||
: code.getCreateDateTime().toString());
|
||||
|
||||
// stockistName — cache per request
|
||||
long stockistUuid = code.getStockistUuid();
|
||||
if (!stockistNameCache.containsKey(stockistUuid)) {
|
||||
String name = null;
|
||||
try {
|
||||
name = stockistCmsService.findByStockistUuid(String.valueOf(stockistUuid))
|
||||
.map(StockistCmsProfile::getStockistName)
|
||||
.filter(StringUtils::hasLength)
|
||||
.orElse(null);
|
||||
} catch (Exception e) {
|
||||
log.warn("getRedeemCodeHistory: stockist name lookup failed for {}: {}", stockistUuid, e.getMessage());
|
||||
}
|
||||
stockistNameCache.put(stockistUuid, name);
|
||||
}
|
||||
if (stockistNameCache.get(stockistUuid) != null) {
|
||||
row.put("stockistName", stockistNameCache.get(stockistUuid));
|
||||
}
|
||||
|
||||
// eventName — cache per request
|
||||
long eventUuid = code.getEventUuid();
|
||||
if (!eventNameCache.containsKey(eventUuid)) {
|
||||
String name = null;
|
||||
try {
|
||||
name = eventService.findEventByUuid(eventUuid)
|
||||
.map(Event::getName)
|
||||
.filter(StringUtils::hasLength)
|
||||
.orElse(null);
|
||||
} catch (Exception e) {
|
||||
log.warn("getRedeemCodeHistory: event name lookup failed for {}: {}", eventUuid, e.getMessage());
|
||||
}
|
||||
eventNameCache.put(eventUuid, name);
|
||||
}
|
||||
if (eventNameCache.get(eventUuid) != null) {
|
||||
row.put("eventName", eventNameCache.get(eventUuid));
|
||||
}
|
||||
|
||||
response.add(row);
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
// Authenticated: JWT is validated by AppAccessAspect (no @AppAuth(skipValidate=true) = auth required).
|
||||
@GetMapping("/redeemCode/{uuid}")
|
||||
public ResponseEntity<Map<String, Object>> getRedeemCode(@PathVariable("uuid") long uuid) {
|
||||
Optional<EventMember> resolved = resolveCurrentEventAndMember();
|
||||
if (resolved.isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Event event = resolved.get().event();
|
||||
long memberUuid = resolved.get().memberUuid();
|
||||
|
||||
Optional<EventRedeemCode> codeOptional = eventService.findEventRedeemCodeByUuid(uuid);
|
||||
if (codeOptional.isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
EventRedeemCode code = codeOptional.get();
|
||||
if (code.getMemberUuid() != memberUuid) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
if (code.getEventUuid() != event.getUuid()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
Map<String, Object> response = toRedeemCodeSummary(code);
|
||||
boolean redeemable = code.getRedeemStatus() == OrderEnum.EventRedeemCodeStatus.Y
|
||||
&& code.getExpiryDateTime() != null && code.getExpiryDateTime().isAfter(LocalDateTime.now());
|
||||
if (redeemable) {
|
||||
String qrText = qrScanUtil.generateQrText(authenticationService.encrypt(code.getRedeemCode()), PaymentEnum.QrScanCodeAction.RC);
|
||||
response.put("qrText", qrText);
|
||||
}
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
// Authenticated: JWT is validated by AppAccessAspect (no @AppAuth(skipValidate=true) = auth required).
|
||||
@GetMapping("/redeemCode/{uuid}/status")
|
||||
public ResponseEntity<Map<String, Object>> getRedeemCodeStatus(@PathVariable("uuid") long uuid) {
|
||||
Optional<EventMember> resolved = resolveCurrentEventAndMember();
|
||||
if (resolved.isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
long memberUuid = resolved.get().memberUuid();
|
||||
|
||||
Optional<EventRedeemCode> codeOptional = eventService.findEventRedeemCodeByUuid(uuid);
|
||||
if (codeOptional.isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
EventRedeemCode code = codeOptional.get();
|
||||
if (code.getMemberUuid() != memberUuid) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
|
||||
return ResponseEntity.ok(Map.of("redeemed", code.getRedeemStatus() == OrderEnum.EventRedeemCodeStatus.R));
|
||||
}
|
||||
|
||||
/** Common fields shared by the redeem-code list and detail responses; stockist name resolved where available. */
|
||||
private Map<String, Object> toRedeemCodeSummary(EventRedeemCode code) {
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
row.put("uuid", code.getUuid());
|
||||
try {
|
||||
stockistCmsService.findByStockistUuid(String.valueOf(code.getStockistUuid()))
|
||||
.ifPresent(profile -> {
|
||||
if (StringUtils.hasLength(profile.getStockistName())) {
|
||||
row.put("stockistName", profile.getStockistName());
|
||||
}
|
||||
});
|
||||
} catch (Exception e) {
|
||||
log.warn("redeemCode: stockist name lookup failed, omitting: {}", e.getMessage());
|
||||
}
|
||||
row.put("redeemStatus", code.getRedeemStatus().name());
|
||||
try {
|
||||
row.put("expiryDateTime", code.getExpiryDateTime() == null ? null : dateTimeFormatterUtil.format(code.getExpiryDateTime()));
|
||||
} catch (Exception ex) {
|
||||
row.put("expiryDateTime", code.getExpiryDateTime() == null ? null : code.getExpiryDateTime().toString());
|
||||
}
|
||||
row.put("redeemedDateTime", code.getRedeemedDateTime());
|
||||
return row;
|
||||
}
|
||||
|
||||
/** Resolved current event + authenticated member uuid. */
|
||||
private record EventMember(Event event, long memberUuid) {}
|
||||
|
||||
/** Resolve the current event and the authenticated member; empty when any precondition fails (→ 404). */
|
||||
private Optional<EventMember> resolveCurrentEventAndMember() {
|
||||
Optional<Event> eventOptional = eventService.findCurrentEvent();
|
||||
if (eventOptional.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(HttpReqRespUtils.getJwtToken());
|
||||
if (!StringUtils.hasLength(memberCode)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Member member = memberService.findByMemberCode(memberCode);
|
||||
if (member == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String memberUuidStr = member.getUuid();
|
||||
if (!StringUtils.hasLength(memberUuidStr)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
return Optional.of(new EventMember(eventOptional.get(), Long.parseLong(memberUuidStr)));
|
||||
} catch (NumberFormatException ex) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.model.GeoLocationHierarchy;
|
||||
import com.solvway.mobile.api.service.GeoLocationHierarchyService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
// Serves geo nodes including their postCode (#66/#77); redeploy marker 2026-09-23.
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping("/api/geoLocationHierarchy")
|
||||
@RequiredArgsConstructor
|
||||
public class GeoLocationController {
|
||||
private final GeoLocationHierarchyService geoLocationHierarchyService;
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/findFirstLevel")
|
||||
public List<GeoLocationHierarchy> findFirstLevel() {
|
||||
return geoLocationHierarchyService.findFirstLevel();
|
||||
}
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/findByParentId/{parentId}")
|
||||
public List<GeoLocationHierarchy> findByParentId(@PathVariable("parentId") Long parentId) {
|
||||
return geoLocationHierarchyService.findByParentId(parentId);
|
||||
}
|
||||
}
|
||||
+851
@@ -0,0 +1,851 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.enums.HierarchyEnum;
|
||||
import com.solvway.core.enums.MemberEnum;
|
||||
import com.solvway.core.model.*;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import com.solvway.mobile.api.model.AuthRequest;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
import com.solvway.mobile.api.useraccess.PhoneVerificationExempt;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping("/api/member")
|
||||
@RequiredArgsConstructor
|
||||
public class MemberController {
|
||||
private static final String RESULT_KEY = "result";
|
||||
private static final String ERROR_MESSAGE_KEY = "errorMessage";
|
||||
private static final String FALSE_STRING = "false";
|
||||
private static final String TRUE_STRING = "true";
|
||||
private static final String SUCCESS_KEY = "success";
|
||||
private static final String FIELD_NAME = "name";
|
||||
private static final String FIELD_SURNAME = "surname";
|
||||
private static final String FIELD_PHONE_NO_PREFIX = "phoneNoPrefix";
|
||||
private static final String FIELD_PHONE_NO = "phoneNo";
|
||||
private static final String FIELD_EMAIL = "email";
|
||||
private static final String FIELD_PASSWORD = "password";
|
||||
private static final String FIELD_CONFIRM_PASSWORD = "confirmPassword";
|
||||
private static final String MSG_PARAM_CONFIRM_PASSWORD_REQUIRED = "Param 'confirmPassword' is required. ";
|
||||
private static final String MSG_PARAM_CODE_INVALID = "Param 'code' is invalid. ";
|
||||
private static final String MSG_REGISTRATION_FAILED = "Registration failed. ";
|
||||
private static final String FIELD_CODE = "code";
|
||||
|
||||
private final MemberService memberService;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final UserService userService;
|
||||
private final DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
private final GeoLocationHierarchyService geoLocationHierarchyService;
|
||||
private final LocationHierarchyService locationHierarchyService;
|
||||
private final OneTimePasswordService oneTimePasswordService;
|
||||
private final SystemService systemService;
|
||||
private final ValidateUtil validateUtil;
|
||||
private final TastefullyPointService tastefullyPointService;
|
||||
|
||||
@Value("${app.customer-portal-base-url}")
|
||||
private String customerPortalBaseUrl;
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/findDocumentsForRegistration")
|
||||
public ResponseEntity<Map<String, String>> findDocumentsForRegistration(){
|
||||
Map<String, String> response = new HashMap<>();
|
||||
response.put("termsAndConditions","https://s3-storage.containerverse.dev/tastefully-public-prd/DOCUMENTS/TermsAndConditions_20250115.pdf");
|
||||
response.put("privacyPolicy","https://s3-storage.containerverse.dev/tastefully-public-prd/DOCUMENTS/PrivacyPolicy.pdf");
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/registerNewMember")
|
||||
public ResponseEntity<Map<String, String>> registerNewMember(@RequestBody Map<String, String> requestBody) {
|
||||
Map<String, String> response = new HashMap<>();
|
||||
String name = requestBody.get(FIELD_NAME);
|
||||
String surname = requestBody.get(FIELD_SURNAME);
|
||||
String phoneNoPrefix = requestBody.get(FIELD_PHONE_NO_PREFIX);
|
||||
String phoneNo = requestBody.get(FIELD_PHONE_NO);
|
||||
String email = requestBody.get(FIELD_EMAIL);
|
||||
String password = requestBody.get(FIELD_PASSWORD);
|
||||
String confirmPassword = requestBody.get(FIELD_CONFIRM_PASSWORD);
|
||||
String nationality = requestBody.get("nationality");
|
||||
Nationality nationalityBean = null;
|
||||
String sponsorId = requestBody.get("sponsorId");
|
||||
|
||||
if (!validateRequiredFields(name, surname, phoneNoPrefix, phoneNo, nationality, response)) {
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
|
||||
Optional<String[]> phoneNoResult = validateRegistrationPhoneNo(phoneNoPrefix, phoneNo, response);
|
||||
if (phoneNoResult.isEmpty()) {
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
phoneNoPrefix = phoneNoResult.get()[0];
|
||||
phoneNo = phoneNoResult.get()[1];
|
||||
|
||||
nationalityBean = systemService.findNationalityByCode(nationality)
|
||||
.orElseGet(() -> systemService.findNationalityByCode("MY").orElse(null));
|
||||
|
||||
if (!validateRegistrationPassword(password, confirmPassword, response)) {
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
|
||||
email = validateRegistrationEmail(email, response);
|
||||
if (FALSE_STRING.equals(response.get(RESULT_KEY))) {
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
|
||||
sponsorId = validateAndNormalizeSponsorId(sponsorId, response);
|
||||
if (sponsorId == null) {
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
|
||||
Member m = new Member();
|
||||
m.setName(name);
|
||||
m.setSurname(surname);
|
||||
m.setEmail(email);
|
||||
m.setNationality(nationalityBean);
|
||||
m.setPhoneNoPrefix(phoneNoPrefix);
|
||||
m.setPhoneNo(phoneNo);
|
||||
m.setSponsorId(sponsorId);
|
||||
m.setPhoneNo(canonicalLocalPhoneNo(m.getPhoneNo()));
|
||||
//Use PhoneNo as Username for Login
|
||||
m.setUsername(m.getPhoneNoPrefix() + m.getPhoneNo());
|
||||
m.setPrefix("MY");
|
||||
m.setSponsorId(sponsorId);
|
||||
m.setDoneBy(sponsorId);
|
||||
m.setCreateBy(sponsorId);
|
||||
|
||||
m.setAgreePdpa(GeneralEnum.FlagYesNo.N);
|
||||
m.setAgreeRandr(GeneralEnum.FlagYesNo.N);
|
||||
m.setPayeeName(m.getName());
|
||||
m.setSkipPurchase(true);
|
||||
m.setPassword(password);
|
||||
m.setSecurityPin(password);
|
||||
Map<String, Object> regResult = memberService.registerNewMemberSelfService(m);
|
||||
if (!Boolean.TRUE.equals(regResult.get("success"))) {
|
||||
String errorCode = (String) regResult.get("errorCode");
|
||||
log.warn("Registration failed for username {} with code {}", m.getUsername(), errorCode);
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, friendlyRegistrationMessage(errorCode));
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
log.info("Start wait for user account creation: {}", m.getUsername());
|
||||
if (!waitForUserAccountCreation(m.getUsername())) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, MSG_REGISTRATION_FAILED);
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
log.info("End wait for user account creation: {}", m.getUsername());
|
||||
|
||||
//Direct login
|
||||
AuthRequest request = new AuthRequest();
|
||||
request.setUsername(m.getUsername());
|
||||
request.setPassword(password);
|
||||
response = new HashMap<>();
|
||||
String token = authenticationService.getToken(request);
|
||||
if (StringUtils.hasLength(token)) {
|
||||
User u = authenticationService.loadUserByToken(token);
|
||||
if (u == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
response.put(RESULT_KEY, TRUE_STRING);
|
||||
response.put("token", token);
|
||||
response.put("memberCode", u.getMemberCode());
|
||||
response.put("name", u.getName());
|
||||
response.put(FIELD_PHONE_NO_PREFIX, u.getPhoneNoPrefix());
|
||||
response.put(FIELD_PHONE_NO, u.getPhoneNo());
|
||||
response.put("resetPasswordRequired", u.getLogin().equals(GeneralEnum.LoginStatus.N) ? TRUE_STRING : FALSE_STRING);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
@GetMapping("/otpRequired")
|
||||
@PhoneVerificationExempt
|
||||
public ResponseEntity<Map<String, Object>> getOtpRequired(){
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String username = authenticationService.getUsernameFromToken(token);
|
||||
if(!StringUtils.hasLength(username)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
//Try to check
|
||||
User u = userService.findByUsername(username);
|
||||
if(u==null){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
if (u.getPhoneVerified().equals(GeneralEnum.FlagYesNo.Y)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
//Allow to pass if email verified previously to reduce cost
|
||||
if(u.getEmailVerified().equals(GeneralEnum.FlagYesNo.Y)){
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
response.put(RESULT_KEY,"true");
|
||||
Member member = memberService.findByUsername(username);
|
||||
OneTimePassword oneTimePassword = oneTimePasswordService.getOneTimePasswordByMember(member, true);
|
||||
String phoneNumber = member.getPhoneNoCombined();
|
||||
|
||||
Map<String, Object> otp = new HashMap<>();
|
||||
otp.put("maskedPhone", validateUtil.maskPhoneNo(phoneNumber));
|
||||
otp.put("identityRef", oneTimePassword.getIdentityRef());
|
||||
otp.put("shortRef", oneTimePassword.getShortRef());
|
||||
otp.put("code", oneTimePassword.getCode());
|
||||
response.put("otpBean", otp);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
@PostMapping("/otpVerification")
|
||||
@PhoneVerificationExempt
|
||||
public ResponseEntity<Map<String, Object>> postOtpVerification(@RequestBody Map<String, String> requestBody){
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String username = authenticationService.getUsernameFromToken(token);
|
||||
if(!StringUtils.hasLength(username)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
//Try to check
|
||||
User u = userService.findByUsername(username);
|
||||
if(u==null){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
String password = requestBody.get(FIELD_PASSWORD);
|
||||
String code = requestBody.get(FIELD_CODE);
|
||||
if(!StringUtils.hasLength(password)){
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'password' is required. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
if(!StringUtils.hasLength(code)){
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'code' is required. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
|
||||
OneTimePassword otp = oneTimePasswordService.findByCode(code);
|
||||
if(otp==null){
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, MSG_PARAM_CODE_INVALID);
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
if(otp.getStatus().equals(GeneralEnum.FlagYesNo.N)){
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, MSG_PARAM_CODE_INVALID);
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
if(otp.getExpiryTime().isBefore(LocalDateTime.now())){
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'code' is expired. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
Member member = memberService.findByUsername(username);
|
||||
if(!member.getUuid().equals(otp.getIdentityRef())){
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, MSG_PARAM_CODE_INVALID);
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
otp.setPassword(password);
|
||||
otp = oneTimePasswordService.verifyOneTimePassword(otp);
|
||||
if(otp==null){
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'code' or 'password' does not match. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
response.put(RESULT_KEY,String.valueOf(userService.updatePhoneVerified(u.getId(), GeneralEnum.FlagYesNo.Y)));
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
@GetMapping("/referralLink")
|
||||
public ResponseEntity<String> getReferralLink(){
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(token);
|
||||
if(!StringUtils.hasLength(memberCode)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(customerPortalBaseUrl + "/register?ref=" + memberCode);
|
||||
}
|
||||
@GetMapping("/referralStats")
|
||||
public ResponseEntity<Map<String, Object>> getReferralStats() {
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(token);
|
||||
String memberUuid = authenticationService.getMemberUuidFromToken(token);
|
||||
if (!StringUtils.hasLength(memberCode)) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
long joined = 0;
|
||||
double earned = 0.0d;
|
||||
try { joined = memberService.countReferralsBySponsor(memberCode); }
|
||||
catch (Exception ex) { log.error("referralStats joined lookup failed for {}", memberCode, ex); }
|
||||
try { if (StringUtils.hasLength(memberUuid)) earned = tastefullyPointService.sumReferralEarned(memberUuid); }
|
||||
catch (Exception ex) { log.error("referralStats earned lookup failed for {}", memberCode, ex); }
|
||||
Map<String, Object> body = new HashMap<>();
|
||||
body.put("joined", joined);
|
||||
body.put("earned", earned);
|
||||
return ResponseEntity.ok(body);
|
||||
}
|
||||
@GetMapping("/editProfileInitialize")
|
||||
public ResponseEntity<Map<String, Object>> getEditProfileInitialize(){
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(token);
|
||||
if(!StringUtils.hasLength(memberCode)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Member m = memberService.findByMemberCode(memberCode);
|
||||
if(m==null){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
String prefix = m.getPrefix();
|
||||
List<ConfigCountry> configList = locationHierarchyService
|
||||
.findConfigByCountryCode(prefix);
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
populateConfigCountryLists(configList, response);
|
||||
if(StringUtils.hasLength(m.getAddressLocation())){
|
||||
Optional<GeoLocationHierarchy> gh = geoLocationHierarchyService.findById(Long.parseLong(m.getAddressLocation()));
|
||||
if(gh.isPresent()) {
|
||||
String traceKey = gh.get().getTraceKey();
|
||||
String[] traceKeyId = traceKey.split("/");
|
||||
for(int i=0;i<traceKeyId.length;i++) {
|
||||
response.put("geoLocationLevel"+i,traceKeyId[i]);
|
||||
GeoLocationHierarchy glh = geoLocationHierarchyService.findById(Long.parseLong(traceKeyId[i])).orElse(null);
|
||||
if(glh!=null && glh.getParentId()!=null && glh.getParentId().intValue()>0){
|
||||
List<GeoLocationHierarchy> list = geoLocationHierarchyService.findByParentId(glh.getParentId());
|
||||
response.put("geoLocationLevel"+i+"List",list);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ResponseEntity.ok(response);
|
||||
|
||||
}
|
||||
@GetMapping("/profile")
|
||||
public ResponseEntity<Map<String, Object>> getProfile(){
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(token);
|
||||
if(!StringUtils.hasLength(memberCode)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Member m = memberService.findByMemberCode(memberCode);
|
||||
if(m==null){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("uuid", m.getUuid());
|
||||
response.put("memberCode", m.getMemberCode());
|
||||
response.put("name", m.getName());
|
||||
response.put(FIELD_SURNAME, m.getSurname());
|
||||
response.put(FIELD_EMAIL, StringUtils.hasLength(m.getEmail())?m.getEmail():"");
|
||||
response.put("nationality", m.getNationality()!=null && StringUtils.hasLength(m.getNationality().getCode())? m.getNationality(): null);
|
||||
response.put("gender", m.getGender().toString());
|
||||
response.put(FIELD_PHONE_NO, m.getPhoneNo());
|
||||
response.put(FIELD_PHONE_NO_PREFIX, m.getPhoneNoPrefix());
|
||||
response.put("phoneNoCombined", m.getPhoneNoCombined());
|
||||
response.put("postCode", StringUtils.hasLength(m.getPostCode())? m.getPostCode():"");
|
||||
response.put("addressDetails", StringUtils.hasLength(m.getAddressDetails())?m.getAddressDetails():"");
|
||||
response.put("addressLocation", StringUtils.hasLength( m.getAddressLocation())? m.getAddressLocation():"");
|
||||
String fullAddress = StringUtils.hasLength(m.getAddressDetails()) ? m.getAddressDetails() : "";
|
||||
if (StringUtils.hasLength(m.getPostCode())) {
|
||||
fullAddress += ", " + m.getPostCode();
|
||||
}
|
||||
String addressString = geoLocationHierarchyService.generateAddress(m.getAddressLocation(),"en_US");
|
||||
if (StringUtils.hasLength(addressString)) {
|
||||
fullAddress += ", " + addressString;
|
||||
}
|
||||
response.put("fullAddress", fullAddress);
|
||||
response.put("dob", m.getDob()!=null? m.getDob().toString():"");
|
||||
response.put("emrmProfileUpdate",
|
||||
m.getEmrmProfileUpdate() != null ? m.getEmrmProfileUpdate().name() : "N");
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
@PostMapping("/editProfile")
|
||||
public ResponseEntity<Map<String, String>> editProfile(@RequestBody Map<String, String> requestBody){
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(token);
|
||||
if(!StringUtils.hasLength(memberCode)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Member m = memberService.findByMemberCode(memberCode);
|
||||
if(m==null){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Map<String, String> response = new HashMap<>();
|
||||
String name= requestBody.get("name");
|
||||
String surname = requestBody.get(FIELD_SURNAME);
|
||||
String email= requestBody.get(FIELD_EMAIL);
|
||||
String dobStr = requestBody.get("dob");
|
||||
String addressDetails = requestBody.get("addressDetails");
|
||||
String postCode = requestBody.get("postCode");
|
||||
String addressLocation = requestBody.get("addressLocation");
|
||||
String genderStr = requestBody.get("gender");
|
||||
if(!StringUtils.hasLength(name)){
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'name' is required. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
if (!StringUtils.hasLength(surname)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'surname' is required. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
if(!StringUtils.hasLength(email)){
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'email' is required. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
|
||||
LocalDate dob = validateEditProfileDob(dobStr, response);
|
||||
if (dob == null) {
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
|
||||
if (!validateEditProfileAddress(addressLocation, response)) {
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
|
||||
postCode = validateEditProfilePostCode(postCode, m.getPrefix(), response);
|
||||
if (postCode == null) {
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
|
||||
Optional<MemberEnum.Gender> genderResult = parseAndValidateGender(genderStr, response);
|
||||
if (genderResult.isEmpty()) {
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
MemberEnum.Gender gender = genderResult.get();
|
||||
m.setName(name);
|
||||
m.setSurname(surname);
|
||||
m.setEmail(email);
|
||||
m.setDob(dob);
|
||||
m.setAddressDetails(addressDetails);
|
||||
m.setPostCode(postCode);
|
||||
m.setAddressLocation(addressLocation);
|
||||
m.setAddressDetails(addressDetails);
|
||||
m.setGender(gender);
|
||||
m.setEmrmProfileUpdate(GeneralEnum.FlagYesNo.Y);
|
||||
response.put(RESULT_KEY, String.valueOf(memberService.save(m)));
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
@GetMapping("/requestDeletion")
|
||||
public ResponseEntity<Map<String, String>> requestDeletion() {
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(token);
|
||||
if(!StringUtils.hasLength(memberCode)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Member m = memberService.findByMemberCode(memberCode);
|
||||
if(m==null){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Map<String, String> response = new HashMap<>();
|
||||
m.setDoneBy(m.getUsername());
|
||||
response.put(RESULT_KEY,String.valueOf(memberService.requestDeletion(m)));
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
@PostMapping("/validatePasswordRules")
|
||||
public ResponseEntity<String> validatePasswordRules(@RequestBody Map<String, String> requestBody) {
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(token);
|
||||
if(!StringUtils.hasLength(memberCode)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Member m = memberService.findByMemberCode(memberCode);
|
||||
if(m==null){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
User u = userService.findByUsernameWithPassword(m.getUsername());
|
||||
if(u==null){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
String password = requestBody.get(FIELD_PASSWORD);
|
||||
String passwordResult = userService.validatePasswordFromRules(password);
|
||||
return ResponseEntity.ok(passwordResult);
|
||||
}
|
||||
@PostMapping("/firstTimePassword")
|
||||
@PhoneVerificationExempt
|
||||
public ResponseEntity<Map<String, String>> firstTimePassword(@RequestBody Map<String, String> requestBody) {
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(token);
|
||||
if(!StringUtils.hasLength(memberCode)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Member m = memberService.findByMemberCode(memberCode);
|
||||
if(m==null){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
User u = userService.findByUsernameWithPassword(m.getUsername());
|
||||
if(u==null){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
String newPassword = requestBody.get("newPassword");
|
||||
String confirmPassword = requestBody.get(FIELD_CONFIRM_PASSWORD);
|
||||
Map<String, String> response = new HashMap<>();
|
||||
if(!StringUtils.hasLength(newPassword)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'newPassword' is required. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
if(!StringUtils.hasLength(confirmPassword)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, MSG_PARAM_CONFIRM_PASSWORD_REQUIRED);
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
if(!newPassword.equals(confirmPassword)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "New password and confirm password does not match. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
String validationResult = userService.validatePasswordFromRules(newPassword);
|
||||
if(StringUtils.hasLength(validationResult) && !"[]".equals(validationResult)){
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Password format does not match. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
FirstTimeLogin loginChangePassword = new FirstTimeLogin();
|
||||
loginChangePassword.setUserId(String.valueOf(u.getId()));
|
||||
loginChangePassword.setNewPassword(newPassword);
|
||||
loginChangePassword.setRepeatPassword(confirmPassword);
|
||||
boolean result = userService.firstTimeLogin(loginChangePassword);
|
||||
if(!result){
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Failed to submit. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
response.put(RESULT_KEY, TRUE_STRING);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
@PostMapping("/changePassword")
|
||||
public ResponseEntity<Map<String, String>> changePassword(@RequestBody Map<String, String> requestBody) {
|
||||
String token = HttpReqRespUtils.getJwtToken();
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(token);
|
||||
if(!StringUtils.hasLength(memberCode)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Member m = memberService.findByMemberCode(memberCode);
|
||||
if(m==null){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
User u = userService.findByUsernameWithPassword(m.getUsername());
|
||||
if(u==null){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
String oldPassword = requestBody.get("oldPassword");
|
||||
String newPassword = requestBody.get("newPassword");
|
||||
String confirmPassword = requestBody.get(FIELD_CONFIRM_PASSWORD);
|
||||
|
||||
Map<String, String> response = new HashMap<>();
|
||||
|
||||
if(!StringUtils.hasLength(oldPassword)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'oldPassword' is required. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
if(!Boolean.TRUE.equals(userService.checkEncryptedStringMatched(oldPassword, u.getPassword()))) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Old password does not match. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
if(!StringUtils.hasLength(newPassword)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'newPassword' is required. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
if(!StringUtils.hasLength(confirmPassword)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, MSG_PARAM_CONFIRM_PASSWORD_REQUIRED);
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
if(!newPassword.equals(confirmPassword)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "New password and confirm password does not match. ");
|
||||
return ResponseEntity.badRequest().body(response);
|
||||
}
|
||||
|
||||
int result = userService.changePassword(u.getId(), newPassword);
|
||||
response.put(RESULT_KEY, result>0?TRUE_STRING:FALSE_STRING);
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/forgetPassword")
|
||||
public ResponseEntity<Map<String, Object>> forgetPassword(@RequestBody Map<String, String> requestBody){
|
||||
String username = requestBody.get(FIELD_PHONE_NO);
|
||||
//[START TASTEFULLY USERNAME] Allow to have email or phone number, so need to massage 601xxx
|
||||
username = username.replaceAll("\\s", "");
|
||||
if(username.startsWith("+6")){
|
||||
username = username.substring(1);
|
||||
}
|
||||
if(username.startsWith("0")){
|
||||
username = "6"+username;
|
||||
}
|
||||
if(username.startsWith("600")){
|
||||
username = username.replaceFirst("600", "60");
|
||||
}
|
||||
//[END TASTEFULLY USERNAME] Allow to have email or phone number, so need to massage 601xxx
|
||||
String result = memberService.forgetPassword(username);
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
if("resetMemberPasswordSuccess".equalsIgnoreCase(result)) {
|
||||
response.put(SUCCESS_KEY, true);
|
||||
}else if("multipleEmailDetected".equalsIgnoreCase(result)) {
|
||||
response.put(SUCCESS_KEY, false);
|
||||
response.put("multipleEmailDetected", true);
|
||||
}else {
|
||||
response.put(SUCCESS_KEY, false);
|
||||
}
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
private boolean waitForUserAccountCreation(String username) {
|
||||
try (ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1)) {
|
||||
CompletableFuture<Boolean> userFuture = new CompletableFuture<>();
|
||||
ScheduledFuture<?> scheduledTask = scheduler.scheduleAtFixedRate(() -> {
|
||||
boolean userCreated = userService.findExistByUsername(username);
|
||||
if (userCreated) {
|
||||
log.info("User account created: {}", username);
|
||||
userFuture.complete(true);
|
||||
}
|
||||
}, 0, 1, TimeUnit.SECONDS);
|
||||
userFuture.get();
|
||||
scheduledTask.cancel(true);
|
||||
return true;
|
||||
} catch (InterruptedException ex) {
|
||||
Thread.currentThread().interrupt();
|
||||
StackTraceUtil.printStackTrace(log, ex);
|
||||
return false;
|
||||
} catch (Exception ex) {
|
||||
StackTraceUtil.printStackTrace(log, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
String validateAndNormalizeSponsorId(String sponsorId, Map<String, String> response) {
|
||||
if (StringUtils.hasLength(sponsorId)) {
|
||||
if (!memberService.existsActiveByMemberCode(sponsorId)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Invalid sponsor code. ");
|
||||
return null;
|
||||
}
|
||||
return sponsorId;
|
||||
} else {
|
||||
return "00000000";
|
||||
}
|
||||
}
|
||||
|
||||
private void populateConfigCountryLists(List<ConfigCountry> configList, Map<String, Object> response) {
|
||||
for (ConfigCountry c : configList) {
|
||||
if (c.getType().equals(HierarchyEnum.ConfigCountryType.RM)) {
|
||||
response.put("marritalStatusList", c.getMarritalStatusList());
|
||||
} else if (c.getType().equals(HierarchyEnum.ConfigCountryType.RR)) {
|
||||
response.put("raceList", c.getRaceList());
|
||||
} else if (c.getType().equals(HierarchyEnum.ConfigCountryType.RS)) {
|
||||
response.put("salutationList", c.getSalutationList());
|
||||
} else if (c.getType().equals(HierarchyEnum.ConfigCountryType.RP)) {
|
||||
response.put("preferredLanguageList", c.getPreferredLanguageList());
|
||||
} else if (c.getType().equals(HierarchyEnum.ConfigCountryType.RN)) {
|
||||
response.put("nationalityList", c.getNationalityList().stream()
|
||||
.sorted(Comparator.comparing(Nationality::getName))
|
||||
.toList());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<MemberEnum.Gender> parseAndValidateGender(String genderStr, Map<String, String> response) {
|
||||
try {
|
||||
return Optional.of(MemberEnum.Gender.valueOf(genderStr));
|
||||
} catch (Exception e) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'gender' is invalid. Only 'M' or 'F' allowed. ");
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private boolean validateRequiredFields(String name, String surname, String phoneNoPrefix, String phoneNo, String nationality, Map<String, String> response) {
|
||||
if (!StringUtils.hasLength(name)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'name' is required. ");
|
||||
return false;
|
||||
}
|
||||
if (!StringUtils.hasLength(surname)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'surname' is required. ");
|
||||
return false;
|
||||
}
|
||||
if (!StringUtils.hasLength(phoneNoPrefix)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'phoneNoPrefix' is required. ");
|
||||
return false;
|
||||
}
|
||||
if (!StringUtils.hasLength(phoneNo)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'phoneNo' is required. ");
|
||||
return false;
|
||||
}
|
||||
if (!StringUtils.hasLength(nationality)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'nationality' is required. ");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private Optional<String[]> validateRegistrationPhoneNo(String phoneNoPrefix, String phoneNo, Map<String, String> response) {
|
||||
if (phoneNoPrefix.startsWith("+")) {
|
||||
phoneNoPrefix = phoneNoPrefix.substring(1);
|
||||
}
|
||||
phoneNo = phoneNo.trim().replaceAll("\\D", "");
|
||||
if (!validateUtil.isNumeric(phoneNo)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'phoneNo' is invalid. Only numeric allowed");
|
||||
return Optional.empty();
|
||||
}
|
||||
// The number is persisted in its canonical form (leading 60/0 stripped), so the
|
||||
// duplicate check must query that same form or duplicates entered with those
|
||||
// prefixes slip past here and only fail later as an opaque username collision.
|
||||
List<Member> phoneNoAlreadyExists =
|
||||
memberService.findByPhoneNoAndPhoneNoPrefixAndIdNot(canonicalLocalPhoneNo(phoneNo), phoneNoPrefix, 0L);
|
||||
if (phoneNoAlreadyExists != null && !phoneNoAlreadyExists.isEmpty()) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "This phone no already registered. ");
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new String[]{phoneNoPrefix, phoneNo});
|
||||
}
|
||||
|
||||
private boolean validateRegistrationPassword(String password, String confirmPassword, Map<String, String> response) {
|
||||
if (!StringUtils.hasLength(password)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'password' is required. ");
|
||||
return false;
|
||||
}
|
||||
if (!StringUtils.hasLength(confirmPassword)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, MSG_PARAM_CONFIRM_PASSWORD_REQUIRED);
|
||||
return false;
|
||||
}
|
||||
if (!password.equals(confirmPassword)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Password and confirm password does not match. ");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private String validateRegistrationEmail(String email, Map<String, String> response) {
|
||||
if (!StringUtils.hasLength(email)) {
|
||||
return null;
|
||||
}
|
||||
email = email.trim();
|
||||
String emailPattern = "^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+$";
|
||||
if (!email.matches(emailPattern)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Invalid email format. ");
|
||||
return null;
|
||||
}
|
||||
return email;
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical local phone number as persisted by services-member: a leading "60"
|
||||
* (country code typed into the local part) and then a single leading "0" are
|
||||
* stripped. Kept in one place so the duplicate pre-check and the stored value
|
||||
* cannot drift.
|
||||
*/
|
||||
static String canonicalLocalPhoneNo(String phoneNo) {
|
||||
if (phoneNo == null) {
|
||||
return null;
|
||||
}
|
||||
String canonical = phoneNo;
|
||||
if (canonical.startsWith("60")) {
|
||||
canonical = canonical.substring(1);
|
||||
}
|
||||
if (canonical.startsWith("0")) {
|
||||
canonical = canonical.substring(1);
|
||||
}
|
||||
return canonical;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a services-member registration failure code to a member-facing message.
|
||||
* Unknown codes fall back to the generic message (the specific code is logged by
|
||||
* the caller for diagnosis).
|
||||
*/
|
||||
static String friendlyRegistrationMessage(String errorCode) {
|
||||
if (errorCode == null) {
|
||||
return MSG_REGISTRATION_FAILED;
|
||||
}
|
||||
switch (errorCode) {
|
||||
case "DUPLICATE_USERNAME_ERROR":
|
||||
return "This phone number is already registered. ";
|
||||
case "NAME_ONLY_ALPHA":
|
||||
return "Name contains invalid characters. ";
|
||||
case "PHONE_NUMBER_ONLY_NUMERIC":
|
||||
return "Phone number must contain digits only. ";
|
||||
case "FIELD_FORMAT_EXCEPTION":
|
||||
return "One or more details are invalid. Please review and try again. ";
|
||||
default:
|
||||
return MSG_REGISTRATION_FAILED;
|
||||
}
|
||||
}
|
||||
|
||||
private LocalDate validateEditProfileDob(String dobStr, Map<String, String> response) {
|
||||
if (!StringUtils.hasLength(dobStr)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'dob' is required. ");
|
||||
return null;
|
||||
}
|
||||
LocalDate dob;
|
||||
try {
|
||||
dob = LocalDate.parse(dobStr);
|
||||
} catch (Exception e) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'dob' is invalid. ");
|
||||
return null;
|
||||
}
|
||||
if (validateUtil.periodBtwLocalDate(dob, LocalDate.now()).getYears() < 18) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Age should be greater than 18 years. ");
|
||||
return null;
|
||||
}
|
||||
return dob;
|
||||
}
|
||||
|
||||
private boolean validateEditProfileAddress(String addressLocation, Map<String, String> response) {
|
||||
if (!StringUtils.hasLength(addressLocation)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'addressLocation' is required. ");
|
||||
return false;
|
||||
}
|
||||
JSONObject json = geoLocationHierarchyService.validateGeoLocationById(addressLocation);
|
||||
if (json == null || !(boolean) json.get("valid")) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'addressLocation' is invalid. ");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private String validateEditProfilePostCode(String postCode, String countryCode, Map<String, String> response) {
|
||||
LocationHierarchy country = locationHierarchyService.findByCode(countryCode);
|
||||
if (country != null && country.getPostCode().equals(GeneralEnum.FlagYesNo.Y)) {
|
||||
if (!validateUtil.validatePostCode(countryCode, postCode)) {
|
||||
response.put(RESULT_KEY, FALSE_STRING);
|
||||
response.put(ERROR_MESSAGE_KEY, "Param 'postCode' is invalid. ");
|
||||
return null;
|
||||
}
|
||||
return postCode;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.BulletinEnum;
|
||||
import com.solvway.core.model.*;
|
||||
import com.solvway.mobile.api.dto.HelpCenterContentResponse;
|
||||
import com.solvway.mobile.api.dto.HelpCenterTreeResponse;
|
||||
import com.solvway.mobile.api.model.AppBanner;
|
||||
import com.solvway.mobile.api.model.AppPromo;
|
||||
import com.solvway.mobile.api.model.Bulletin;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping("/api/public")
|
||||
@RequiredArgsConstructor
|
||||
public class PublicContentController {
|
||||
private final BulletinService bulletinService;
|
||||
private final AppBannerService appBannerService;
|
||||
private final AppPromoService appPromoService;
|
||||
private final EventScheduleService eventScheduleService;
|
||||
private final ArticleService articleService;
|
||||
private final AlbumService albumService;
|
||||
private final StockistCmsService stockistCmsService;
|
||||
private final HelpCenterService helpCenterService;
|
||||
private final SystemService systemService;
|
||||
|
||||
// --- Bulletins ---
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/bulletins/{type}")
|
||||
public ResponseEntity<List<Bulletin>> getBulletins(@PathVariable BulletinEnum.BulletinType type) {
|
||||
return ResponseEntity.ok(bulletinService.findActiveBulletinsByType(type));
|
||||
}
|
||||
|
||||
// --- Announcement Banner ---
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/banner")
|
||||
public ResponseEntity<List<AppBanner>> getBanners() {
|
||||
return ResponseEntity.ok(appBannerService.findActive());
|
||||
}
|
||||
|
||||
// --- Home Promo Carousel ---
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/promos")
|
||||
public ResponseEntity<List<AppPromo>> getPromos() {
|
||||
return ResponseEntity.ok(appPromoService.findActive());
|
||||
}
|
||||
|
||||
// --- Event Schedules ---
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/eventSchedules")
|
||||
public ResponseEntity<List<EventSchedule>> getEventSchedules() {
|
||||
return ResponseEntity.ok(eventScheduleService.findEnabledForDisplay());
|
||||
}
|
||||
|
||||
// --- Articles (Blog) ---
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/articles")
|
||||
public ResponseEntity<List<Article>> getArticles() {
|
||||
return ResponseEntity.ok(articleService.findPublishedArticles());
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/articles/{uuid}")
|
||||
public ResponseEntity<Article> getArticle(@PathVariable BigInteger uuid) {
|
||||
Article article = articleService.findByUuid(uuid);
|
||||
if (article == null) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(article);
|
||||
}
|
||||
|
||||
// --- Albums (Gallery) ---
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/albums")
|
||||
public ResponseEntity<List<Album>> getAlbums() {
|
||||
return ResponseEntity.ok(albumService.findEnabledAlbums());
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/albums/{uuid}")
|
||||
public ResponseEntity<Map<String, Object>> getAlbumDetail(@PathVariable BigInteger uuid) {
|
||||
Optional<Album> albumOpt = albumService.findByUuid(uuid);
|
||||
if (albumOpt.isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("album", albumOpt.get());
|
||||
response.put("details", albumService.findDetailByAlbumUuid(uuid));
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
// --- Merchants ---
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/merchants/featured")
|
||||
public ResponseEntity<List<StockistCmsProfile>> getFeaturedMerchants() {
|
||||
return ResponseEntity.ok(stockistCmsService.findTopForDisplay());
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/merchants")
|
||||
public ResponseEntity<Map<String, Object>> getAllMerchants() {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("profiles", stockistCmsService.findAllForDisplay());
|
||||
response.put("categories", stockistCmsService.findAllCategoryTags());
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/merchants/{stockistUuid}")
|
||||
public ResponseEntity<Map<String, Object>> getMerchantDetail(@PathVariable String stockistUuid) {
|
||||
Optional<StockistCmsProfile> profileOpt = stockistCmsService.findByStockistUuid(stockistUuid);
|
||||
if (profileOpt.isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("profile", profileOpt.get());
|
||||
response.put("products", stockistCmsService.findProductsByStockistUuid(stockistUuid));
|
||||
return ResponseEntity.ok(response);
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/merchantCategories")
|
||||
public ResponseEntity<List<StockistCategoryTag>> getMerchantCategories() {
|
||||
return ResponseEntity.ok(stockistCmsService.findAllCategoryTags());
|
||||
}
|
||||
|
||||
// --- Help Center ---
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/helpCenter")
|
||||
public ResponseEntity<HelpCenterTreeResponse> getHelpCenterTree(
|
||||
@RequestParam(defaultValue = "en_US") String locale) {
|
||||
return ResponseEntity.ok(helpCenterService.getTree(locale));
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/helpCenter/{uuid}/content")
|
||||
public ResponseEntity<HelpCenterContentResponse> getHelpCenterContent(
|
||||
@PathVariable BigInteger uuid,
|
||||
@RequestParam(defaultValue = "en_US") String locale) {
|
||||
return helpCenterService.getLeafContent(uuid, locale)
|
||||
.map(ResponseEntity::ok)
|
||||
.orElseGet(() -> ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
// --- Messages ---
|
||||
|
||||
// Customer-portal UI labels live in the shared Area A (aligned with member-portal).
|
||||
private static final String MESSAGE_AREA = "A";
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@GetMapping("/messages/{locale}")
|
||||
public ResponseEntity<Map<String, String>> getMessages(@PathVariable String locale) {
|
||||
return ResponseEntity.ok(systemService.findMessageCatalog(MESSAGE_AREA, locale));
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.EmailEnum;
|
||||
import com.solvway.core.model.Email;
|
||||
import com.solvway.core.model.Recipient;
|
||||
import com.solvway.mobile.api.model.form.AffiliateRequest;
|
||||
import com.solvway.mobile.api.model.form.ContactUsRequest;
|
||||
import com.solvway.mobile.api.model.form.DistributorRequest;
|
||||
import com.solvway.mobile.api.service.EmailService;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.util.HtmlUtils;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping("/api/public")
|
||||
@RequiredArgsConstructor
|
||||
public class PublicFormController {
|
||||
private final EmailService emailService;
|
||||
|
||||
private static final String RECIPIENT_EMAIL = "bhchng@containerverse.dev";
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/contactUs")
|
||||
public ResponseEntity<JSONObject> contactUs(@Valid @RequestBody ContactUsRequest request) {
|
||||
String body = "<p>Dear Tastefully Team,</p>"
|
||||
+ "<p>There is a customer leave a message, below is the detail of the message.</p>"
|
||||
+ "<p>Name : " + escape(request.getName()) + " </p>"
|
||||
+ "<p>Email : " + escape(request.getEmail()) + " </p>"
|
||||
+ "<p>Message : " + escape(request.getMessage()) + " </p>"
|
||||
+ "<p>Thank you.</p>";
|
||||
|
||||
return sendEmail(body, "Customer Feedback From " + escape(request.getName()));
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/affiliate")
|
||||
public ResponseEntity<JSONObject> affiliate(@Valid @RequestBody AffiliateRequest request) {
|
||||
String body = "<p>Dear info@tastefullyexpo.com,</p>"
|
||||
+ "<p>There is a new affiliate registration. Below are the details:</p>"
|
||||
+ "<p>Name: " + escape(request.getName()) + " </p>"
|
||||
+ "<p>Email: " + escape(request.getEmail()) + " </p>"
|
||||
+ "<p>Phone Number: " + escape(request.getPhoneNo()) + " </p>"
|
||||
+ "<p>Instagram: " + escape(request.getInstagram()) + " </p>"
|
||||
+ "<p>Facebook: " + escape(request.getFacebook()) + " </p>"
|
||||
+ "<p>TikTok: " + escape(request.getTiktok()) + " </p>"
|
||||
+ "<p>Xiaohongshu: " + escape(request.getXiaohongshu()) + " </p>"
|
||||
+ "<p>Other Social Media Links: " + escape(request.getOtherSocial()) + " </p>"
|
||||
+ "<p>Comment: " + escape(request.getComment()) + " </p>"
|
||||
+ "<p>Thank you.</p>";
|
||||
|
||||
return sendEmail(body, "New Affiliate Registration: " + escape(request.getName()));
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
@PostMapping("/distributor")
|
||||
public ResponseEntity<JSONObject> distributor(@Valid @RequestBody DistributorRequest request) {
|
||||
String body = "<p>Dear info@tastefullyexpo.com,</p>"
|
||||
+ "<p>There is a new distributor registration. Below are the details:</p>"
|
||||
+ "<p>Name: " + escape(request.getName()) + " </p>"
|
||||
+ "<p>Email: " + escape(request.getEmail()) + " </p>"
|
||||
+ "<p>Phone Number: " + escape(request.getPhoneNo()) + " </p>"
|
||||
+ "<p>Company Name: " + escape(request.getCompanyName()) + " </p>"
|
||||
+ "<p>Company SSM: " + escape(request.getCompanySsm()) + " </p>"
|
||||
+ "<p>Company Address: " + escape(request.getCompanyAddress()) + " </p>"
|
||||
+ "<p>Social Media: " + escape(request.getSocial()) + " </p>"
|
||||
+ "<p>Thank you.</p>";
|
||||
|
||||
return sendEmail(body, "New Distributor Registration: " + escape(request.getName()));
|
||||
}
|
||||
|
||||
private String escape(String value) {
|
||||
return value == null ? "" : HtmlUtils.htmlEscape(value);
|
||||
}
|
||||
|
||||
private ResponseEntity<JSONObject> sendEmail(String body, String subject) {
|
||||
Recipient recipient = new Recipient();
|
||||
recipient.setRecipient(RECIPIENT_EMAIL);
|
||||
recipient.setStatus(EmailEnum.RecipientStatusType.Y);
|
||||
recipient.setType(EmailEnum.RecipientType.R);
|
||||
|
||||
Email email = new Email();
|
||||
email.setBody(body);
|
||||
email.setDatetime(LocalDateTime.now());
|
||||
email.setSubject(subject);
|
||||
email.setStatus(EmailEnum.StatusType.P);
|
||||
email.setRecipients(List.of(recipient));
|
||||
|
||||
JSONObject result = new JSONObject();
|
||||
Optional<Email> emailOpt = emailService.send(email);
|
||||
result.put("success", emailOpt.isPresent() ? "Y" : "N");
|
||||
return ResponseEntity.ok(result);
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.model.DynamicWalletTrxn;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.TastefullyPointService;
|
||||
import com.solvway.mobile.api.util.paging.InitialPagingSizes;
|
||||
import com.solvway.mobile.api.util.paging.PageableRest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@RestController
|
||||
@Slf4j
|
||||
@RequestMapping("/api/tastefullyPoint")
|
||||
@RequiredArgsConstructor
|
||||
public class TastefullyPointController {
|
||||
private final TastefullyPointService tastefullyPointService;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@GetMapping("/getBalance")
|
||||
public ResponseEntity<Double> getBalance() {
|
||||
try{
|
||||
String memberUuid = authenticationService.getMemberUuidFromToken(HttpReqRespUtils.getJwtToken());
|
||||
return ResponseEntity.ok(tastefullyPointService.getBalance(memberUuid));
|
||||
}catch (Exception ex){
|
||||
StackTraceUtil.printStackTrace(log, ex);
|
||||
return ResponseEntity.internalServerError().build();
|
||||
}
|
||||
}
|
||||
@GetMapping("/getBalanceCache")
|
||||
public ResponseEntity<Double> getBalanceCache() {
|
||||
try{
|
||||
String memberUuid = authenticationService.getMemberUuidFromToken(HttpReqRespUtils.getJwtToken());
|
||||
return ResponseEntity.ok(tastefullyPointService.getBalanceCache(memberUuid));
|
||||
}catch (Exception ex){
|
||||
StackTraceUtil.printStackTrace(log, ex);
|
||||
return ResponseEntity.internalServerError().build();
|
||||
}
|
||||
}
|
||||
@GetMapping("/getTodayEarned")
|
||||
public ResponseEntity<Double> getTodayEarned() {
|
||||
try{
|
||||
String memberUuid = authenticationService.getMemberUuidFromToken(HttpReqRespUtils.getJwtToken());
|
||||
List<DynamicWalletTrxn> todayTransactions = tastefullyPointService.getTodayTransaction(Long.parseLong(memberUuid));
|
||||
double todayEarned = todayTransactions.stream().mapToDouble(DynamicWalletTrxn::getAmountIn).sum();
|
||||
return ResponseEntity.ok(todayEarned);
|
||||
}catch (Exception ex){
|
||||
StackTraceUtil.printStackTrace(log, ex);
|
||||
return ResponseEntity.internalServerError().build();
|
||||
}
|
||||
}
|
||||
@PostMapping("/getTransactions")
|
||||
public ResponseEntity<Map<String, Object>> getTransactions(@RequestBody Map<String, String> requestBody) {
|
||||
try{
|
||||
int selectedPageSize = InitialPagingSizes.INITIAL_PAGE_SIZE;
|
||||
int selectedPage =InitialPagingSizes.INITIAL_PAGE;
|
||||
if(requestBody.containsKey("pageSize")){
|
||||
selectedPageSize = Integer.parseInt(requestBody.get("pageSize"));
|
||||
}
|
||||
if(requestBody.containsKey("page")){
|
||||
selectedPage = Integer.parseInt(requestBody.get("page"));
|
||||
}
|
||||
String memberUuid = authenticationService.getMemberUuidFromToken(HttpReqRespUtils.getJwtToken());
|
||||
Sort sort = Sort.by(Sort.Order.desc("transactionDateTime"));
|
||||
PageableRest pageableRest = new PageableRest(PageRequest.of(selectedPage, selectedPageSize, sort));
|
||||
HashMap<String, String> inputs = new HashMap<>();
|
||||
inputs.put("ownerUuid", memberUuid);
|
||||
Page<DynamicWalletTrxn> walletTrxn = tastefullyPointService.findAllTrxn(inputs, pageableRest);
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("hasNext", walletTrxn.hasNext());
|
||||
response.put("totalElements", walletTrxn.getTotalElements());
|
||||
response.put("totalPages", walletTrxn.getTotalPages());
|
||||
List<Map<String, String>> transactionMapList = walletTrxn.getContent().stream().map(dynamicWalletTrxn -> {
|
||||
|
||||
try {
|
||||
Map<String, String> transactionMap = new HashMap<>();
|
||||
transactionMap.put("uuid", String.valueOf(dynamicWalletTrxn.getUuid()));
|
||||
transactionMap.put("transactionDateTime", dateTimeFormatterUtil.format(dynamicWalletTrxn.getTransactionDateTime()));
|
||||
transactionMap.put("refNo", dynamicWalletTrxn.getRefNo());
|
||||
transactionMap.put("amountIn", String.valueOf(dynamicWalletTrxn.getAmountIn()));
|
||||
transactionMap.put("amountOut", String.valueOf(dynamicWalletTrxn.getAmountOut()));
|
||||
transactionMap.put("finalAmount", String.valueOf(dynamicWalletTrxn.getFinalAmount()));
|
||||
transactionMap.put("description", dynamicWalletTrxn.getDescription());
|
||||
transactionMap.put("remarks", dynamicWalletTrxn.getRemarks());
|
||||
transactionMap.put("trxnType", dynamicWalletTrxn.getTrxnType().toString());
|
||||
transactionMap.put("enabled", dynamicWalletTrxn.getEnabled().toString());
|
||||
transactionMap.put("doneBy", dynamicWalletTrxn.getDoneBy());
|
||||
transactionMap.put("createBy", dynamicWalletTrxn.getCreateBy());
|
||||
transactionMap.put("createDate", dateTimeFormatterUtil.format(dynamicWalletTrxn.getCreateDate()));
|
||||
|
||||
return transactionMap;
|
||||
} catch (ParseException e) {
|
||||
StackTraceUtil.printStackTrace(log, e, "MemberUUID: "+memberUuid);
|
||||
}
|
||||
return null;
|
||||
}).filter(Objects::nonNull).toList();
|
||||
response.put("content", transactionMapList);
|
||||
return ResponseEntity.ok(response);
|
||||
}catch (Exception ex){
|
||||
StackTraceUtil.printStackTrace(log, ex);
|
||||
}
|
||||
return ResponseEntity.badRequest().build();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.model.MemberVoucherEligibility;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.MemberVoucherService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Member-facing read API for vouchers. Ownership always comes from the JWT: the caller is
|
||||
* resolved from the token, never from the request, so a member cannot see another member's
|
||||
* voucher by guessing a uuid.
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/voucher")
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class VoucherController {
|
||||
|
||||
private final MemberVoucherService memberVoucherService;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final MemberService memberService;
|
||||
|
||||
// Authenticated: JWT is validated by AppAccessAspect (no @AppAuth(skipValidate=true) = auth required).
|
||||
@GetMapping("/list")
|
||||
public ResponseEntity<List<Map<String, Object>>> getVouchers() {
|
||||
Optional<Member> member = resolveMember();
|
||||
if (member.isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return ResponseEntity.ok(eligibilities(member.get()).stream().map(this::toRow).toList());
|
||||
}
|
||||
|
||||
@GetMapping("/{uuid}")
|
||||
public ResponseEntity<Map<String, Object>> getVoucher(@PathVariable("uuid") long uuid) {
|
||||
Optional<Member> member = resolveMember();
|
||||
if (member.isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
return eligibilities(member.get()).stream()
|
||||
.filter(e -> e.getVoucher() != null && e.getVoucher().getUuid() == uuid)
|
||||
.findFirst()
|
||||
.map(e -> ResponseEntity.ok(toRow(e)))
|
||||
.orElseGet(() -> ResponseEntity.notFound().build());
|
||||
}
|
||||
|
||||
@GetMapping("/{uuid}/status")
|
||||
public ResponseEntity<Map<String, Object>> getVoucherStatus(@PathVariable("uuid") long uuid) {
|
||||
Optional<Member> member = resolveMember();
|
||||
if (member.isEmpty()) {
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
// Same eligibility entry drives both keys: "redeemed" keeps its original, narrower
|
||||
// meaning (reason == ALREADY_REDEEMED) so existing callers see no behavior change;
|
||||
// "redeemable"/"reason" carry the full eligibility so a member holding an open QR can be
|
||||
// told the voucher is no longer redeemable (e.g. deactivated/expired) rather than being
|
||||
// left polling a dead redeemed=false forever. Unmatched uuid keeps returning 200 with the
|
||||
// same defaults as before this change — no new notFound path is introduced here.
|
||||
Optional<MemberVoucherEligibility> match = eligibilities(member.get()).stream()
|
||||
.filter(e -> e.getVoucher() != null && e.getVoucher().getUuid() == uuid)
|
||||
.findFirst();
|
||||
boolean redeemed = match.map(e -> "ALREADY_REDEEMED".equals(e.getReason())).orElse(false);
|
||||
Map<String, Object> body = new HashMap<>();
|
||||
body.put("redeemed", redeemed);
|
||||
body.put("redeemable", match.map(MemberVoucherEligibility::isRedeemable).orElse(false));
|
||||
body.put("reason", match.map(MemberVoucherEligibility::getReason).orElse(null));
|
||||
return ResponseEntity.ok(body);
|
||||
}
|
||||
|
||||
private List<MemberVoucherEligibility> eligibilities(Member member) {
|
||||
boolean profileComplete = GeneralEnum.FlagYesNo.Y.equals(member.getEmrmProfileUpdate());
|
||||
try {
|
||||
return memberVoucherService.findEligibility(Long.parseLong(member.getUuid()), profileComplete);
|
||||
} catch (NumberFormatException ex) {
|
||||
log.warn("Unparseable member uuid {}, returning no vouchers", member.getUuid());
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private Map<String, Object> toRow(MemberVoucherEligibility e) {
|
||||
Map<String, Object> row = new HashMap<>();
|
||||
// As a string, not a number: Snowflake uuids are ~3e18 and JavaScript's
|
||||
// Number.MAX_SAFE_INTEGER is ~9e15, so JSON.parse in the browser silently rounds a
|
||||
// numeric uuid and the id the member app puts back in a URL is a voucher that does not
|
||||
// exist. The long @PathVariable parses the string back with no change on the way in.
|
||||
row.put("uuid", String.valueOf(e.getVoucher().getUuid()));
|
||||
row.put("name", e.getVoucher().getName());
|
||||
row.put("description", e.getVoucher().getDescription());
|
||||
row.put("currencySymbol", e.getVoucher().getCurrencySymbol());
|
||||
row.put("amount", e.getVoucher().getAmount());
|
||||
row.put("redeemable", e.isRedeemable());
|
||||
row.put("reason", e.getReason());
|
||||
row.put("imageUrl", resolveImageUrl(e.getVoucher().getUploadPath()));
|
||||
return row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Voucher images are uploaded from backoffice with isPrivate=false, so MinioStorageService
|
||||
* already returns a full public URL (publicUrlPrefix + bucket + filename), not a storage key
|
||||
* — unlike the private-asset case in EventScheduleService/StockistCmsService, this needs no
|
||||
* presigning. member-portal's tasteRewards template renders EventProduct.uploadPath the same
|
||||
* way: raw, as an img src. The image is optional: a blank path yields null.
|
||||
*/
|
||||
private String resolveImageUrl(String uploadPath) {
|
||||
return StringUtils.hasText(uploadPath) ? uploadPath : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the authenticated member from the JWT. Mirrors EventController.resolveCurrentEventAndMember
|
||||
* (EventController.java:421-443) minus the event lookup — vouchers are not event-scoped.
|
||||
* Note mobile-api's MemberService.findByMemberCode returns Member directly, not Optional.
|
||||
*/
|
||||
private Optional<Member> resolveMember() {
|
||||
String memberCode = authenticationService.getMemberCodeFromToken(HttpReqRespUtils.getJwtToken());
|
||||
if (!StringUtils.hasLength(memberCode)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Member member = memberService.findByMemberCode(memberCode);
|
||||
if (member == null || !StringUtils.hasLength(member.getUuid())) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(member);
|
||||
}
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package com.solvway.mobile.api.dto;
|
||||
|
||||
import java.math.BigInteger;
|
||||
|
||||
public record HelpCenterContentResponse(
|
||||
BigInteger uuid,
|
||||
String locale,
|
||||
String redirectUrl,
|
||||
String content
|
||||
) {}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.solvway.mobile.api.dto;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
public record HelpCenterNode(
|
||||
BigInteger uuid,
|
||||
BigInteger parentUuid,
|
||||
String label,
|
||||
int sortIndex,
|
||||
List<HelpCenterNode> children
|
||||
) {}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package com.solvway.mobile.api.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record HelpCenterTreeResponse(
|
||||
String locale,
|
||||
List<HelpCenterNode> categories
|
||||
) {}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.solvway.mobile.api.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
/**
|
||||
* Client-facing view of a global announcement banner message. Only the fields
|
||||
* the customer-portal marquee needs are carried; other services-system columns
|
||||
* (dates, enabled, audit) are intentionally omitted and ignored on deserialize.
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class AppBanner {
|
||||
private Long id;
|
||||
private String message;
|
||||
private String linkUrl;
|
||||
private String style;
|
||||
private int sortIndex;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.solvway.mobile.api.model;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* Client-facing view of a home promo carousel slide (image/video). Only the
|
||||
* fields the customer-portal carousel needs are carried; services-system
|
||||
* audit columns (createBy, createDateTime, doneBy, lastModify) are
|
||||
* intentionally omitted and ignored on deserialize.
|
||||
*/
|
||||
@Setter
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class AppPromo {
|
||||
private Long id;
|
||||
private String mediaType;
|
||||
private String mediaUrl;
|
||||
private String linkUrl;
|
||||
private String caption;
|
||||
private String altText;
|
||||
private LocalDateTime dateFrom;
|
||||
private LocalDateTime dateTo;
|
||||
private boolean enabled;
|
||||
private int sortIndex;
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.solvway.mobile.api.model;
|
||||
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
public class AuthRequest {
|
||||
private String username;
|
||||
private String password;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.solvway.mobile.api.model;
|
||||
|
||||
import com.solvway.core.enums.BulletinEnum;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class Bulletin {
|
||||
private Long id;
|
||||
private String title;
|
||||
private LocalDateTime dateFrom;
|
||||
private LocalDateTime dateTo;
|
||||
private String imageUrl;
|
||||
private String content;
|
||||
private BulletinEnum.BulletinStatus status;
|
||||
private BulletinEnum.BulletinType type;
|
||||
private int sortIndex;
|
||||
private String s3Link;
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.solvway.mobile.api.model.form;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class AffiliateRequest {
|
||||
|
||||
@NotBlank
|
||||
@Size(max = 100)
|
||||
private String name;
|
||||
|
||||
@NotBlank
|
||||
@Email
|
||||
@Size(max = 254)
|
||||
private String email;
|
||||
|
||||
@Size(max = 30)
|
||||
private String phoneNo;
|
||||
|
||||
@Size(max = 200)
|
||||
private String instagram;
|
||||
|
||||
@Size(max = 200)
|
||||
private String facebook;
|
||||
|
||||
@Size(max = 200)
|
||||
private String tiktok;
|
||||
|
||||
@Size(max = 200)
|
||||
private String xiaohongshu;
|
||||
|
||||
@Size(max = 500)
|
||||
private String otherSocial;
|
||||
|
||||
@Size(max = 2000)
|
||||
private String comment;
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.solvway.mobile.api.model.form;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class ContactUsRequest {
|
||||
|
||||
@NotBlank
|
||||
@Size(max = 100)
|
||||
private String name;
|
||||
|
||||
@NotBlank
|
||||
@Email
|
||||
@Size(max = 254)
|
||||
private String email;
|
||||
|
||||
@NotBlank
|
||||
@Size(max = 2000)
|
||||
private String message;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.solvway.mobile.api.model.form;
|
||||
|
||||
import jakarta.validation.constraints.Email;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class DistributorRequest {
|
||||
|
||||
@NotBlank
|
||||
@Size(max = 100)
|
||||
private String name;
|
||||
|
||||
@NotBlank
|
||||
@Email
|
||||
@Size(max = 254)
|
||||
private String email;
|
||||
|
||||
@Size(max = 30)
|
||||
private String phoneNo;
|
||||
|
||||
@Size(max = 200)
|
||||
private String companyName;
|
||||
|
||||
@Size(max = 100)
|
||||
private String companySsm;
|
||||
|
||||
@Size(max = 500)
|
||||
private String companyAddress;
|
||||
|
||||
@Size(max = 500)
|
||||
private String social;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.Album;
|
||||
import com.solvway.core.model.AlbumDetail;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AlbumService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
public List<Album> findEnabledAlbums() {
|
||||
ResponseEntity<List<Album>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_ALBUM_FIND_BY_ENABLED),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, GeneralEnum.FlagYesNo.Y);
|
||||
List<Album> albums = ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
albums.forEach(album -> {
|
||||
Optional<AlbumDetail> firstDetail = findDetailFirstByAlbumUuid(album.getUuid());
|
||||
String imageUrl = firstDetail.map(AlbumDetail::getUploadPath).orElse("");
|
||||
album.setFirstImage(imageUrl);
|
||||
});
|
||||
return albums.stream()
|
||||
.sorted(Comparator.comparing(Album::getSortIndex).reversed())
|
||||
.toList();
|
||||
}
|
||||
|
||||
public Optional<Album> findByUuid(BigInteger uuid) {
|
||||
ResponseEntity<Album> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_ALBUM_FIND_BY_UUID),
|
||||
Album.class, uuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? Optional.ofNullable(ent.getBody()) : Optional.empty();
|
||||
}
|
||||
|
||||
public List<AlbumDetail> findDetailByAlbumUuid(BigInteger uuid) {
|
||||
ResponseEntity<List<AlbumDetail>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_ALBUM_DETAIL_FIND_BY_ALBUM_UUID),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, uuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
|
||||
private Optional<AlbumDetail> findDetailFirstByAlbumUuid(BigInteger uuid) {
|
||||
ResponseEntity<AlbumDetail> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_ALBUM_DETAIL_FIND_DETAIL_FIRST_BY_ALBUM_UUID),
|
||||
AlbumDetail.class, uuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? Optional.ofNullable(ent.getBody()) : Optional.empty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.model.AppBanner;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AppBannerService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
/** Active (enabled + in-window) announcement banners, in display order. */
|
||||
public List<AppBanner> findActive() {
|
||||
ResponseEntity<List<AppBanner>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_APP_BANNER_FIND_ACTIVE),
|
||||
new ParameterizedTypeReference<>() {
|
||||
});
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.model.AppPromo;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AppPromoService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
/** Active (enabled + in-window) home promo carousel slides, in display order. */
|
||||
public List<AppPromo> findActive() {
|
||||
ResponseEntity<List<AppPromo>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_APP_PROMO_FIND_ACTIVE),
|
||||
new ParameterizedTypeReference<>() {
|
||||
});
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.ArticleEnum;
|
||||
import com.solvway.core.model.Article;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class ArticleService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
public List<Article> findPublishedArticles() {
|
||||
ResponseEntity<List<Article>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_ARTICLE_FIND_BY_TYPE_AND_STATUS_ORDER_ID_DESC),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, ArticleEnum.ArticleType.M, ArticleEnum.Status.Y);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
|
||||
public Article findByUuid(BigInteger uuid) {
|
||||
ResponseEntity<Article> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_ARTICLE_FIND_BY_UUID),
|
||||
Article.class, uuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
}
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum.Area;
|
||||
import com.solvway.core.model.AesEncryptionHolder;
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.mobile.api.constant.api.RestApiAuthServiceConstants;
|
||||
import com.solvway.mobile.api.model.AuthRequest;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import com.solvway.mobile.api.util.redis.RedisUtil;
|
||||
import com.solvway.mobile.api.util.redis.TokenCacheKeyUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AuthenticationService {
|
||||
private final MemberService memberService;
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final RedisUtil<String> redisUtil;
|
||||
private static final String CACHE_KEY_TOKEN_USERNAME_PREFIX ="mobile-api:auth:token-username:";
|
||||
private static final String CACHE_KEY_TOKEN_MEMBER_CODE_PREFIX ="mobile-api:auth:token-member-code:";
|
||||
private static final String CACHE_KEY_TOKEN_MEMBER_UUID_PREFIX ="mobile-api:auth:token-member-uuid:";
|
||||
public String getToken(AuthRequest authRequest){
|
||||
ResponseEntity<String> ent = restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(RestApiAuthServiceConstants.API_REST_AUTHENTICATION), String.class, authRequest);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
public Boolean memberAutoLoginUpdate(Map<String, String> params){
|
||||
ResponseEntity<Boolean> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiAuthServiceConstants.API_REST_AUTHENTICATION_AUTO_LOGIN_UPDATE), Boolean.class, params);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
public String fingerPrintLogin(String token, String memberCode){
|
||||
ResponseEntity<String> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiAuthServiceConstants.API_REST_AUTHENTICATION_FINGER_PRINT_LOGIN), String.class, token, memberCode);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
public User loadUserByToken(String token) {
|
||||
ResponseEntity<User> ent = restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(RestApiAuthServiceConstants.API_REST_SYSTEM_GET_USER_BYTOKEN), User.class, Area.M, token);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public String refreshToken(String token){
|
||||
ResponseEntity<String> ent = restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(RestApiAuthServiceConstants.API_REST_REFRESH_TOKEN), String.class, token);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
public String logoutToken(String token) {
|
||||
ResponseEntity<String> ent = restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(RestApiAuthServiceConstants.API_REST_LOGOUT_TOKEN), String.class, token);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
public String encrypt(String plainText){
|
||||
AesEncryptionHolder holder = new AesEncryptionHolder();
|
||||
holder.setPlainText(plainText);
|
||||
ResponseEntity<AesEncryptionHolder> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiAuthServiceConstants.API_REST_AES_ENCRYPT),
|
||||
AesEncryptionHolder.class, holder);
|
||||
if (ent.getBody() == null) {
|
||||
return null;
|
||||
}
|
||||
AesEncryptionHolder body = ent.getBody();
|
||||
return ent.getStatusCode() == HttpStatus.OK && body != null ? body.getEncryptedText() : null;
|
||||
}
|
||||
public String decrypt(String encryptedText) {
|
||||
AesEncryptionHolder holder = new AesEncryptionHolder();
|
||||
holder.setEncryptedText(encryptedText);
|
||||
ResponseEntity<AesEncryptionHolder> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiAuthServiceConstants.API_REST_AES_DECRYPT),
|
||||
AesEncryptionHolder.class, holder);
|
||||
AesEncryptionHolder body = ent.getBody();
|
||||
if (body == null) {
|
||||
return null;
|
||||
}
|
||||
return ent.getStatusCode() == HttpStatus.OK ? body.getPlainText() : null;
|
||||
}
|
||||
public String getUsernameFromToken(String token){
|
||||
String redisKey = CACHE_KEY_TOKEN_USERNAME_PREFIX + TokenCacheKeyUtil.hashToken(token);
|
||||
if(redisUtil.checkKeyExist(redisKey)){
|
||||
return redisUtil.getValue(redisKey);
|
||||
}
|
||||
User u = loadUserByToken(token);
|
||||
if(u != null){
|
||||
redisUtil.putValueWithExpireTime(redisKey, u.getUsername(), 1, TimeUnit.HOURS);
|
||||
return u.getUsername();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
public String getMemberCodeFromToken(String token){
|
||||
String redisKey = CACHE_KEY_TOKEN_MEMBER_CODE_PREFIX + TokenCacheKeyUtil.hashToken(token);
|
||||
if(redisUtil.checkKeyExist(redisKey)){
|
||||
return redisUtil.getValue(redisKey);
|
||||
}
|
||||
String username = getUsernameFromToken(token);
|
||||
if(!StringUtils.hasLength(username)){
|
||||
return "";
|
||||
}
|
||||
Member m = memberService.findByUsername(username);
|
||||
if(m==null){
|
||||
return "";
|
||||
}
|
||||
redisUtil.putValueWithExpireTime(redisKey, m.getMemberCode(), 1, TimeUnit.HOURS);
|
||||
return m.getMemberCode();
|
||||
}
|
||||
public String getMemberUuidFromToken(String token){
|
||||
String redisKey = CACHE_KEY_TOKEN_MEMBER_UUID_PREFIX + TokenCacheKeyUtil.hashToken(token);
|
||||
if(redisUtil.checkKeyExist(redisKey)){
|
||||
return redisUtil.getValue(redisKey);
|
||||
}
|
||||
String memberCode = getMemberCodeFromToken(token);
|
||||
if(!StringUtils.hasLength(memberCode)){
|
||||
return "";
|
||||
}
|
||||
Member m = memberService.findByMemberCode(memberCode);
|
||||
if(m==null){
|
||||
return "";
|
||||
}
|
||||
redisUtil.putValueWithExpireTime(redisKey, m.getUuid(), 1, TimeUnit.HOURS);
|
||||
return m.getUuid();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.BulletinEnum;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.model.Bulletin;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class BulletinService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
public List<Bulletin> findActiveBulletinsByType(BulletinEnum.BulletinType type) {
|
||||
ResponseEntity<List<Bulletin>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_BULLETIN_FIND_ACTIVE_BY_TYPE),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, type);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.constant.api.RestApiDriveServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class DriveService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
public String getPresignedUrlPublic(String filename, int duration, TimeUnit timeUnit) {
|
||||
HashMap<String, Object> param = new HashMap<>();
|
||||
param.put("filename", filename);
|
||||
param.put("duration", duration);
|
||||
param.put("timeUnit", timeUnit);
|
||||
|
||||
ResponseEntity<String> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiDriveServiceConstants.API_REST_DRIVE_GET_PRESIGNED_URL_PUBLIC),
|
||||
String.class, param);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : "";
|
||||
}
|
||||
|
||||
public String getPresignedUrl(String filename, int duration, TimeUnit timeUnit) {
|
||||
HashMap<String, Object> param = new HashMap<>();
|
||||
param.put("filename", filename);
|
||||
param.put("duration", duration);
|
||||
param.put("timeUnit", timeUnit);
|
||||
|
||||
ResponseEntity<String> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiDriveServiceConstants.API_REST_DRIVE_GET_PRESIGNED_URL),
|
||||
String.class, param);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : "";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.model.Email;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class EmailService {
|
||||
|
||||
private final PubSubTemplate pubSubTemplate;
|
||||
private final PubSubUtil pubSubUtil;
|
||||
|
||||
@Value("${pubsub.email.save-request.topic}")
|
||||
private String emailSaveRequestTopic;
|
||||
|
||||
public Optional<Email> send(Email email) {
|
||||
try {
|
||||
pubSubUtil.publishMessageWithCustomObjectMapper(pubSubTemplate, emailSaveRequestTopic, email);
|
||||
return Optional.of(email);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.EventSchedule;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class EventScheduleService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final DriveService driveService;
|
||||
|
||||
public List<EventSchedule> findEnabledForDisplay() {
|
||||
String url = restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_EVENT_SCHEDULE_FIND_ENABLED_DISPLAY);
|
||||
log.info("[EventScheduleService] calling downstream url={}", url);
|
||||
ResponseEntity<List<EventSchedule>> ent = restTemplateUtil.getForEntity(
|
||||
url,
|
||||
new ParameterizedTypeReference<>() {
|
||||
});
|
||||
log.info("[EventScheduleService] downstream response status={}", ent.getStatusCode());
|
||||
List<EventSchedule> schedules = ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
schedules.forEach(s -> {
|
||||
if (StringUtils.hasLength(s.getUploadPath())) {
|
||||
s.setUploadPath(driveService.getPresignedUrlPublic(s.getUploadPath(), 24, TimeUnit.HOURS));
|
||||
}
|
||||
});
|
||||
return schedules;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.*;
|
||||
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class EventService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
public Optional<Event> findCurrentEvent() {
|
||||
ResponseEntity<Event> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_CURRENT_EVENT),
|
||||
Event.class);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? Optional.ofNullable(ent.getBody()) : Optional.empty();
|
||||
}
|
||||
|
||||
public CheckInBooth saveCheckInBooth(CheckInBooth checkInBooth) {
|
||||
ResponseEntity<CheckInBooth> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_CHECK_IN_BOOTH),
|
||||
CheckInBooth.class, checkInBooth);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the member already has a check-in for this event on the request's date, at any booth.
|
||||
* The counter service matches on (eventUuid, memberUuid, checkInDate);
|
||||
* an empty match serializes to a null body.
|
||||
*/
|
||||
public boolean findCheckInExisted(CheckInBooth checkInBooth) {
|
||||
ResponseEntity<CheckInBooth> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_CHECK_IN_BOOTH_FIND_EXISTED),
|
||||
CheckInBooth.class, checkInBooth);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null;
|
||||
}
|
||||
public List<CheckInBooth> findCheckInBoothByMemberUuid(long memberUuid) {
|
||||
ResponseEntity<List<CheckInBooth>> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_CHECK_IN_BOOTH_FIND_BY_MEMBER_UUID),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, memberUuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
|
||||
public CheckInBooth directGetRedeemCode(CheckInBooth checkInBooth) {
|
||||
ResponseEntity<CheckInBooth> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_CHECK_IN_BOOTH_DIRECT_REDEEM_CODE),
|
||||
CheckInBooth.class, checkInBooth);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public EventReceipt saveEventReceipt(EventReceipt eventReceipt) {
|
||||
ResponseEntity<EventReceipt> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_RECEIPT_SAVE),
|
||||
EventReceipt.class, eventReceipt);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public Optional<EventReceipt> findEventReceiptByUuid(long uuid) {
|
||||
ResponseEntity<EventReceipt> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_RECEIPT_FIND_BY_UUID),
|
||||
EventReceipt.class, uuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? Optional.ofNullable(ent.getBody()) : Optional.empty();
|
||||
}
|
||||
|
||||
public List<EventReceipt> findEventReceiptByEventUuidAndMemberUuid(long eventUuid, long memberUuid) {
|
||||
ResponseEntity<List<EventReceipt>> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_RECEIPT_FIND_BY_EVENT_UUID_AND_MEMBER_UUID),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, eventUuid, memberUuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
|
||||
public List<EventLuckyDrawTicket> findEventLuckyDrawTicketByEventUuidAndMemberUuid(long eventUuid, long memberUuid) {
|
||||
ResponseEntity<List<EventLuckyDrawTicket>> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LUCKY_DRAW_TICKET_FIND_BY_EVENT_UUID_AND_MEMBER_UUID),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, eventUuid, memberUuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
|
||||
public List<EventLuckyDrawTicket> findEventLuckyDrawTicketByEventUuidAndReceiptUuid(long eventUuid, long receiptUuid) {
|
||||
ResponseEntity<List<EventLuckyDrawTicket>> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_LUCKY_DRAW_TICKET_FIND_BY_EVENT_UUID_AND_RECEIPT_UUID),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, eventUuid, receiptUuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
|
||||
public List<EventGiftWithPurchase> findEventGiftWithPurchaseByEventUuidAndMemberUuid(long eventUuid, long memberUuid) {
|
||||
ResponseEntity<List<EventGiftWithPurchase>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_GIFT_WITH_PURCHASE_FIND_BY_EVENT_UUID_AND_MEMBER_UUID),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, eventUuid, memberUuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public Optional<EventRedeemCode> findEventRedeemCodeByUuid(long uuid) {
|
||||
ResponseEntity<EventRedeemCode> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_REDEEM_CODE_FIND_BY_UUID),
|
||||
EventRedeemCode.class, uuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? Optional.ofNullable(ent.getBody()) : Optional.empty();
|
||||
}
|
||||
|
||||
public List<EventRedeemCode> findEventRedeemCodeByEventUuidAndStockistUuidAndMemberUuid(long eventUuid, long stockistUuid, long memberUuid) {
|
||||
EventRedeemCode requestBody = new EventRedeemCode();
|
||||
requestBody.setEventUuid(eventUuid);
|
||||
requestBody.setStockistUuid(stockistUuid);
|
||||
requestBody.setMemberUuid(memberUuid);
|
||||
ResponseEntity<List<EventRedeemCode>> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_REDEEM_CODE_FIND_BY_EVENT_UUID_AND_STOCKIST_UUID_AND_MEMBER_UUID),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, requestBody);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
|
||||
public List<EventRedeemCode> findEventRedeemCodeByEventUuidAndMemberUuid(long eventUuid, long memberUuid) {
|
||||
EventRedeemCode requestBody = new EventRedeemCode();
|
||||
requestBody.setEventUuid(eventUuid);
|
||||
requestBody.setMemberUuid(memberUuid);
|
||||
ResponseEntity<List<EventRedeemCode>> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_REDEEM_CODE_FIND_BY_EVENT_UUID_AND_MEMBER_UUID),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, requestBody);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
|
||||
public List<EventProduct> findEventProductByEventUuid(long eventUuid) {
|
||||
ResponseEntity<List<EventProduct>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_PRODUCT_FIND_BY_EVENT_UUID),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, eventUuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public List<EventRedeemCode> findEventRedeemCodeByMemberUuid(long memberUuid) {
|
||||
ResponseEntity<List<EventRedeemCode>> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_REDEEM_CODE_FIND_BY_MEMBER_UUID),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, memberUuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
|
||||
public Optional<Event> findEventByUuid(long uuid) {
|
||||
ResponseEntity<Event> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_EVENT_FIND_BY_UUID),
|
||||
Event.class, uuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? Optional.ofNullable(ent.getBody()) : Optional.empty();
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.GeoLocationHierarchy;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class GeoLocationHierarchyService {
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
public Optional<GeoLocationHierarchy> findById(Long id) {
|
||||
ResponseEntity<GeoLocationHierarchy> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_GEOLOCATION_HIERARCHY_FIND_BYID),
|
||||
GeoLocationHierarchy.class, id);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? Optional.ofNullable(ent.getBody()) : Optional.empty();
|
||||
}
|
||||
|
||||
public List<GeoLocationHierarchy> findFirstLevel() {
|
||||
ResponseEntity<List<GeoLocationHierarchy> > ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_GEO_LOCATION_HIERARCHY_FIND_FIRST_LEVEL),
|
||||
new ParameterizedTypeReference<>() {
|
||||
});
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
|
||||
public List<GeoLocationHierarchy> findByParentId(Long parentId) {
|
||||
ResponseEntity<List<GeoLocationHierarchy> > ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_GEO_LOCATION_HIERARCHY_FIND_NEXT_LEVEL),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, parentId);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
public JSONObject validateGeoLocationById(String id) {
|
||||
ResponseEntity<JSONObject> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_GEOLOCATION_HIERARCHY_VALIDATE_ID),
|
||||
JSONObject.class, id);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public String generateAddress(String id, String locale) {
|
||||
if(!StringUtils.hasLength(id)){
|
||||
return "";
|
||||
}
|
||||
ResponseEntity<String> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_GEOLOCATION_HIERARCHY_GENERATE_ADDRESS),
|
||||
String.class, id, locale);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.GenericHierarchy;
|
||||
import com.solvway.core.model.GenericPostContent;
|
||||
import com.solvway.core.model.HelpCenterPost;
|
||||
import com.solvway.mobile.api.cache.MessageLabelCache;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.HelpCenterContentResponse;
|
||||
import com.solvway.mobile.api.dto.HelpCenterNode;
|
||||
import com.solvway.mobile.api.dto.HelpCenterTreeResponse;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.*;
|
||||
import java.util.Comparator;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class HelpCenterService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final MessageLabelCache messageLabelCache;
|
||||
|
||||
public Optional<HelpCenterContentResponse> getLeafContent(BigInteger uuid, String locale) {
|
||||
ResponseEntity<HelpCenterPost> postEnt = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_HELP_CENTER_POST_FIND_BY_HIERARCHY_UUID),
|
||||
HelpCenterPost.class, uuid);
|
||||
|
||||
if (postEnt.getStatusCode() != HttpStatus.OK || postEnt.getBody() == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
HelpCenterPost post = postEnt.getBody();
|
||||
|
||||
if (StringUtils.hasLength(post.getRedirectUrl())) {
|
||||
return Optional.of(new HelpCenterContentResponse(uuid, locale, post.getRedirectUrl(), null));
|
||||
}
|
||||
|
||||
ResponseEntity<GenericPostContent> contentEnt = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_GENERIC_POST_CONTENT_FIND_BY_UUID_AND_LOCALE),
|
||||
GenericPostContent.class, post.getGenericPostUuid(), locale);
|
||||
|
||||
if (contentEnt.getStatusCode() != HttpStatus.OK || contentEnt.getBody() == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
return Optional.of(new HelpCenterContentResponse(uuid, locale, null, contentEnt.getBody().getContent()));
|
||||
}
|
||||
|
||||
public HelpCenterTreeResponse getTree(String locale) {
|
||||
ResponseEntity<GenericHierarchy> rootEnt = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_GENERIC_HIERARCHY_FIND_ROOT_BY_TYPE),
|
||||
GenericHierarchy.class, GeneralEnum.GenericHierarchyType.HC);
|
||||
|
||||
if (rootEnt.getStatusCode() != HttpStatus.OK || rootEnt.getBody() == null) {
|
||||
return new HelpCenterTreeResponse(locale, List.of());
|
||||
}
|
||||
BigInteger rootUuid = rootEnt.getBody().getUuid();
|
||||
|
||||
ResponseEntity<GenericHierarchy> fullEnt = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_GENERIC_HIERARCHY_FIND_FULL_BY_TYPE_AND_UUID),
|
||||
GenericHierarchy.class, GeneralEnum.GenericHierarchyType.HC, rootUuid);
|
||||
|
||||
if (fullEnt.getStatusCode() != HttpStatus.OK || fullEnt.getBody() == null) {
|
||||
return new HelpCenterTreeResponse(locale, List.of());
|
||||
}
|
||||
|
||||
List<GenericHierarchy> activeTopLevel = filterActive(fullEnt.getBody().getChildList());
|
||||
|
||||
List<HelpCenterNode> categories = activeTopLevel.stream()
|
||||
.sorted(Comparator.comparingInt(GenericHierarchy::getSortIndex))
|
||||
.map(gh -> toNode(gh, locale))
|
||||
.toList();
|
||||
|
||||
return new HelpCenterTreeResponse(locale, categories);
|
||||
}
|
||||
|
||||
private List<GenericHierarchy> filterActive(List<GenericHierarchy> nodes) {
|
||||
if (nodes == null) return List.of();
|
||||
List<GenericHierarchy> out = new ArrayList<>();
|
||||
for (GenericHierarchy n : nodes) {
|
||||
if (GeneralEnum.FlagYesNo.Y != n.getStatus()) continue;
|
||||
n.setChildList(filterActive(n.getChildList()));
|
||||
out.add(n);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private HelpCenterNode toNode(GenericHierarchy gh, String locale) {
|
||||
String label = resolveLabel(gh.getMessageTag(), locale);
|
||||
if (!StringUtils.hasLength(label)) {
|
||||
label = gh.getName();
|
||||
}
|
||||
List<HelpCenterNode> children = gh.getChildList() == null ? List.of()
|
||||
: gh.getChildList().stream()
|
||||
.sorted(Comparator.comparingInt(GenericHierarchy::getSortIndex))
|
||||
.map(c -> toNode(c, locale))
|
||||
.toList();
|
||||
return new HelpCenterNode(gh.getUuid(), gh.getParentUuid(), label, gh.getSortIndex(), children);
|
||||
}
|
||||
|
||||
private String resolveLabel(String code, String locale) {
|
||||
if (!StringUtils.hasLength(code)) return null;
|
||||
|
||||
Optional<String> cached = messageLabelCache.get(code, locale);
|
||||
if (cached.isPresent()) return cached.get();
|
||||
|
||||
try {
|
||||
ResponseEntity<String> resp = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE),
|
||||
String.class, code, locale);
|
||||
|
||||
if (resp.getStatusCode() != HttpStatus.OK || !StringUtils.hasLength(resp.getBody())) {
|
||||
return null;
|
||||
}
|
||||
String label = resp.getBody();
|
||||
messageLabelCache.put(code, locale, label);
|
||||
return label;
|
||||
} catch (org.springframework.web.client.HttpClientErrorException.NotFound e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.ConfigCountry;
|
||||
import com.solvway.core.model.LocationHierarchy;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class LocationHierarchyService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
public LocationHierarchy findByCode(String code) {
|
||||
ResponseEntity<LocationHierarchy> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_LOCATION_HIERARCHY_FIND_BYCODE),
|
||||
LocationHierarchy.class, code);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public List<ConfigCountry> findConfigByCountryCode(String countryCode) {
|
||||
ResponseEntity<List<ConfigCountry>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_LOCATION_HIERARCHY_FIND_CONFIG_BY_CTRY),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, countryCode);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.mobile.api.constant.api.RestApiMemberServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class MemberService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
public String getReplicatedUrl(String memberCode) {
|
||||
ResponseEntity<String> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiMemberServiceConstants.API_REST_MEMBER_REPLICATED_URL),
|
||||
String.class, memberCode);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
public Member findByUsername(String username) {
|
||||
ResponseEntity<Member> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_FIND_BY_USERNAME),
|
||||
Member.class, username);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public Member findByMemberCode(String memberCode) {
|
||||
ResponseEntity<Member> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_FIND_BY_MEMBER_CODE),
|
||||
Member.class, memberCode);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public boolean existsActiveByMemberCode(String memberCode) {
|
||||
ResponseEntity<Boolean> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_EXISTS_ACTIVE_BY_MEMBER_CODE),
|
||||
Boolean.class, memberCode);
|
||||
return ent.getStatusCode() == HttpStatus.OK && Boolean.TRUE.equals(ent.getBody());
|
||||
}
|
||||
|
||||
public int countReferralsBySponsor(String memberCode) {
|
||||
ResponseEntity<Integer> ent = restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiMemberServiceConstants.API_REST_MEMBER_COUNT_REFERRALS_BY_SPONSOR),
|
||||
Integer.class, memberCode);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : 0;
|
||||
}
|
||||
|
||||
public List<Member> findByPhoneNoAndPhoneNoPrefixAndIdNot(String phoneNo, String phoneNoPrefix, Long id) {
|
||||
ResponseEntity<List<Member>> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_FIND_BY_PHONE_NO_AND_PHONE_PREFIX_ID_NOT),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, phoneNo, phoneNoPrefix, id);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
public Boolean requestDeletion(Member member){
|
||||
ResponseEntity<Boolean> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiMemberServiceConstants.API_REST_MEMBER_REQUEST_DELETION),
|
||||
Boolean.class, member);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
public String forgetPassword(String email) {
|
||||
ResponseEntity<String> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiMemberServiceConstants.API_REST_MEMBER_FORGET_PASSWORD),
|
||||
String.class, email);
|
||||
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : "";
|
||||
}
|
||||
|
||||
|
||||
public Optional<Member> findById(Long id) {
|
||||
ResponseEntity<Member> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_FIND_BY_ID),
|
||||
Member.class, id);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? Optional.ofNullable(ent.getBody()) : Optional.empty();
|
||||
}
|
||||
public boolean save(Member member) {
|
||||
ResponseEntity<Void> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_SAVE),
|
||||
Void.class, member);
|
||||
|
||||
return ent.getStatusCode() == HttpStatus.OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reason-bearing self-service registration. Returns the services-member result map
|
||||
* { success, id?, errorCode?, errorMessage? } so the caller can surface a specific
|
||||
* failure message instead of a generic one. Never returns null.
|
||||
*/
|
||||
public Map<String, Object> registerNewMemberSelfService(Member member) {
|
||||
ResponseEntity<Map<String, Object>> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_REG_NEW_MEMBER_SELF_SERVICE),
|
||||
new ParameterizedTypeReference<Map<String, Object>>() {}, member);
|
||||
if (ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null) {
|
||||
return ent.getBody();
|
||||
}
|
||||
Map<String, Object> fallback = new HashMap<>();
|
||||
fallback.put("success", false);
|
||||
fallback.put("errorCode", "REGISTRATION_FAILED");
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.dto.MemberVoucherEligibilityRequest;
|
||||
import com.solvway.core.model.MemberVoucherEligibility;
|
||||
import com.solvway.mobile.api.constant.api.RestApiCounterServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class MemberVoucherService {
|
||||
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
public List<MemberVoucherEligibility> findEligibility(long memberUuid, boolean profileComplete) {
|
||||
MemberVoucherEligibilityRequest request = new MemberVoucherEligibilityRequest();
|
||||
request.setMemberUuid(memberUuid);
|
||||
request.setProfileComplete(profileComplete);
|
||||
ResponseEntity<List<MemberVoucherEligibility>> ent = restTemplateUtil.postForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiCounterServiceConstants.API_REST_COUNTER_MEMBER_VOUCHER_FIND_ELIGIBILITY),
|
||||
new ParameterizedTypeReference<>() {}, request);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.model.OneTimePassword;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class OneTimePasswordService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
public OneTimePassword generateOneTimePasswordEmail(OneTimePassword otp) {
|
||||
ResponseEntity<OneTimePassword> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_OTP_GENERATE_OTP_EMAIL),
|
||||
OneTimePassword.class, otp);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
public OneTimePassword generateOneTimePasswordPhoneSms(OneTimePassword otp){
|
||||
ResponseEntity<OneTimePassword> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_OTP_GENERATE_OTP_SMS),
|
||||
OneTimePassword.class, otp);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public OneTimePassword verifyOneTimePassword(OneTimePassword otp) {
|
||||
ResponseEntity<OneTimePassword> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_OTP_VERIFY_OTP),
|
||||
OneTimePassword.class, otp);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public OneTimePassword findByCode(String code) {
|
||||
ResponseEntity<OneTimePassword> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_OTP_FIND_BY_CODE),
|
||||
OneTimePassword.class, code);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public List<OneTimePassword> findValidByIdentityRef(String identityRef) {
|
||||
if(!StringUtils.hasLength(identityRef)){
|
||||
return List.of();
|
||||
}
|
||||
ResponseEntity<List<OneTimePassword>> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_OTP_FIND_VALID_BY_IDENTITY_REF),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, identityRef);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
public OneTimePassword getOneTimePasswordByMember(Member member){
|
||||
return getOneTimePasswordByMember(member, false);
|
||||
}
|
||||
public OneTimePassword getOneTimePasswordByMember(Member member, boolean bySms){
|
||||
List<OneTimePassword> validOtp = findValidByIdentityRef(member.getUuid());
|
||||
if(!validOtp.isEmpty()){
|
||||
return validOtp.getFirst();
|
||||
}
|
||||
OneTimePassword oneTimePassword = new OneTimePassword();
|
||||
oneTimePassword.setIdentityRef(member.getUuid());
|
||||
if(bySms){
|
||||
return generateOneTimePasswordPhoneSms(oneTimePassword);
|
||||
}
|
||||
return generateOneTimePasswordEmail(oneTimePassword);
|
||||
}
|
||||
}
|
||||
+121
@@ -0,0 +1,121 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.StockistCategoryTag;
|
||||
import com.solvway.core.model.StockistCmsProduct;
|
||||
import com.solvway.core.model.StockistCmsProfile;
|
||||
import com.solvway.mobile.api.constant.api.RestApiStockistServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class StockistCmsService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final DriveService driveService;
|
||||
|
||||
public List<StockistCmsProfile> findTopForDisplay() {
|
||||
ResponseEntity<List<StockistCmsProfile>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiStockistServiceConstants.API_REST_STOCKIST_CMS_PROFILE_FIND_TOP_DISPLAY),
|
||||
new ParameterizedTypeReference<>() {
|
||||
});
|
||||
List<StockistCmsProfile> profiles = ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
profiles.forEach(this::resolveLogoPath);
|
||||
return profiles;
|
||||
}
|
||||
|
||||
public List<StockistCmsProfile> findAllForDisplay() {
|
||||
ResponseEntity<List<StockistCmsProfile>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiStockistServiceConstants.API_REST_STOCKIST_CMS_PROFILE_FIND_ALL_DISPLAY),
|
||||
new ParameterizedTypeReference<>() {
|
||||
});
|
||||
List<StockistCmsProfile> profiles = ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
profiles.forEach(p -> {
|
||||
resolveLogoPath(p);
|
||||
resolveProfileTags(p);
|
||||
});
|
||||
return profiles;
|
||||
}
|
||||
|
||||
public Optional<StockistCmsProfile> findByStockistUuid(String stockistUuid) {
|
||||
ResponseEntity<StockistCmsProfile> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiStockistServiceConstants.API_REST_STOCKIST_CMS_PROFILE_FIND_BY_STOCKIST_UUID),
|
||||
StockistCmsProfile.class, stockistUuid);
|
||||
if (ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null) {
|
||||
StockistCmsProfile profile = ent.getBody();
|
||||
resolveLogoPath(profile);
|
||||
resolveProfileTags(profile);
|
||||
return Optional.of(profile);
|
||||
}
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
public List<StockistCmsProduct> findProductsByStockistUuid(String stockistUuid) {
|
||||
ResponseEntity<List<StockistCmsProduct>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiStockistServiceConstants.API_REST_STOCKIST_CMS_PRODUCT_FIND_BY_STOCKIST_UUID),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, stockistUuid);
|
||||
List<StockistCmsProduct> products = ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
products.forEach(p -> {
|
||||
if (StringUtils.hasLength(p.getUploadPath())) {
|
||||
p.setUploadPath(driveService.getPresignedUrlPublic(p.getUploadPath(), 24, TimeUnit.HOURS));
|
||||
}
|
||||
});
|
||||
return products;
|
||||
}
|
||||
|
||||
public List<StockistCategoryTag> findAllCategoryTags() {
|
||||
ResponseEntity<List<StockistCategoryTag>> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiStockistServiceConstants.API_REST_STOCKIST_CATEGORY_TAG_FIND_ALL),
|
||||
new ParameterizedTypeReference<>() {
|
||||
});
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : List.of();
|
||||
}
|
||||
|
||||
private void resolveLogoPath(StockistCmsProfile profile) {
|
||||
if (StringUtils.hasLength(profile.getLogoPath())) {
|
||||
profile.setLogoPath(driveService.getPresignedUrlPublic(profile.getLogoPath(), 24, TimeUnit.HOURS));
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<StockistCategoryTag> findCategoryTagByUuid(BigInteger uuid) {
|
||||
ResponseEntity<StockistCategoryTag> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiStockistServiceConstants.API_REST_STOCKIST_CATEGORY_TAG_FIND_BY_UUID),
|
||||
StockistCategoryTag.class, uuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? Optional.ofNullable(ent.getBody()) : Optional.empty();
|
||||
}
|
||||
|
||||
private void resolveProfileTags(StockistCmsProfile profile) {
|
||||
if (profile.getTagList() == null || profile.getTagList().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
profile.setDisplayTagList(
|
||||
profile.getTagList().stream()
|
||||
.map(s -> findCategoryTagByUuid(new BigInteger(s)))
|
||||
.filter(Optional::isPresent)
|
||||
.map(Optional::get)
|
||||
.filter(t -> GeneralEnum.FlagYesNo.Y.equals(t.getEnabled()))
|
||||
.sorted(Comparator.comparing(StockistCategoryTag::getName))
|
||||
.toList()
|
||||
);
|
||||
profile.setDisplayTagClassList(
|
||||
profile.getDisplayTagList().stream()
|
||||
.map(StockistCategoryTag::getName)
|
||||
.collect(Collectors.joining(" "))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.AppInit;
|
||||
import com.solvway.core.model.Nationality;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class SystemService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
public Map<String, Object> appInitialize(AppInit appInit) {
|
||||
ResponseEntity<Map<String, Object>> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_APP_INITIALIZE),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, appInit);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : Map.of();
|
||||
}
|
||||
|
||||
public Map<String, String> findMessageCatalog(String area, String locale) {
|
||||
ResponseEntity<Map<String, String>> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_MESSAGE_JSON_BY_AREA_AND_LOCALE),
|
||||
new ParameterizedTypeReference<>() {
|
||||
}, area, locale);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : Map.of();
|
||||
}
|
||||
|
||||
public Optional<Nationality> findNationalityByCode(String code) {
|
||||
ResponseEntity<Nationality> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_NATIONALITY_FIND_BYCODE),
|
||||
Nationality.class, code);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? Optional.ofNullable(ent.getBody()) : Optional.empty();
|
||||
}
|
||||
}
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.model.DynamicWallet;
|
||||
import com.solvway.core.model.DynamicWalletTrxn;
|
||||
import com.solvway.core.model.QrScanTran;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.mobile.api.constant.api.RestApiPaymentServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import com.solvway.mobile.api.util.paging.PageableRest;
|
||||
import com.solvway.mobile.api.util.paging.ResponsePageRest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class TastefullyPointService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
private final MemberService memberService;
|
||||
private final DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
public Page<DynamicWalletTrxn> findAllTrxn(Map<String, String> property, PageableRest pageableRest) {
|
||||
Map<String, Object> param= new HashMap<>();
|
||||
param.put("property", property);
|
||||
param.put("pageableRest", pageableRest);
|
||||
|
||||
ResponseEntity<ResponsePageRest<DynamicWalletTrxn>> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiPaymentServiceConstants.API_REST_TASTEFULLY_POINT_TRXN_FIND_ALL_PAGEABLE),
|
||||
new ParameterizedTypeReference<ResponsePageRest<DynamicWalletTrxn>>() {}, param);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public double getBalance(String memberUuid) {
|
||||
ResponseEntity<Double> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiPaymentServiceConstants.API_REST_TASTEFULLY_POINT_GET_BALANCE_NO_CACHE),
|
||||
Double.class, memberUuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : 0.0d;
|
||||
}
|
||||
public double getBalanceCache(String memberUuid) {
|
||||
ResponseEntity<Double> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiPaymentServiceConstants.API_REST_TASTEFULLY_POINT_GET_BALANCE_CACHE),
|
||||
Double.class, memberUuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : 0.0d;
|
||||
}
|
||||
|
||||
public double sumReferralEarned(String memberUuid) {
|
||||
ResponseEntity<Double> ent = restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiPaymentServiceConstants.API_REST_TASTEFULLY_POINT_SUM_REFERRAL_EARNED),
|
||||
Double.class, memberUuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : 0.0d;
|
||||
}
|
||||
|
||||
public DynamicWalletTrxn findTrxnByUuid(String uuid) {
|
||||
ResponseEntity<DynamicWalletTrxn> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiPaymentServiceConstants.API_REST_TASTEFULLY_POINT_TRXN_FIND_BY_UUID),
|
||||
DynamicWalletTrxn.class, uuid);
|
||||
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null;
|
||||
}
|
||||
public DynamicWallet findWalletByOwnerUuid(String uuid) {
|
||||
ResponseEntity<DynamicWallet> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiPaymentServiceConstants.API_REST_TASTEFULLY_POINT_GET_WALLET),
|
||||
DynamicWallet.class, uuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null;
|
||||
}
|
||||
public DynamicWallet findWalletByUuid(long uuid) {
|
||||
ResponseEntity<DynamicWallet> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiPaymentServiceConstants.API_REST_TASTEFULLY_POINT_FIND_WALLET_BY_UUID),
|
||||
DynamicWallet.class, uuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK ? ent.getBody() : null;
|
||||
}
|
||||
public List<DynamicWalletTrxn> getTodayTransaction(long memberUuid) {
|
||||
try {
|
||||
PageableRest pageable = new PageableRest(PageRequest.of(0, Integer.MAX_VALUE, Sort.by(Sort.Order.desc("id"))));
|
||||
Map<String, String> property = new HashMap<>();
|
||||
property.put("ownerUuid", String.valueOf(memberUuid));
|
||||
property.put("transactionDateTimeFrom", dateTimeFormatterUtil.format(LocalDate.now()));
|
||||
Page<DynamicWalletTrxn> page = findAllTrxn(property, pageable);
|
||||
return page.stream().toList();
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
return List.of();
|
||||
}
|
||||
public Optional<QrScanTran> findQrScanTranByUuid(long uuid){
|
||||
ResponseEntity<QrScanTran> ent =
|
||||
restTemplateUtil.getForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiPaymentServiceConstants.API_REST_PAYMENT_QR_SCAN_FIND_QR_SCAN_TRAN_BY_UUID),
|
||||
QrScanTran.class, uuid);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody()!=null ? Optional.of(ent.getBody()) : Optional.empty();
|
||||
}
|
||||
public Optional<QrScanTran> getQrScanTranQrTextForMerchantScan(QrScanTran bean){
|
||||
ResponseEntity<QrScanTran> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiPaymentServiceConstants.API_REST_PAYMENT_QR_SCAN_GET_QR_TEXT_FOR_MERCHANT_SCAN),
|
||||
QrScanTran.class, bean);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody()!=null ? Optional.of(ent.getBody()) : Optional.empty();
|
||||
}
|
||||
public Optional<QrScanTran> userScanQr(QrScanTran bean){
|
||||
ResponseEntity<QrScanTran> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiPaymentServiceConstants.API_REST_PAYMENT_QR_SCAN_USER_SCAN_QR),
|
||||
QrScanTran.class, bean);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody()!=null ? Optional.of(ent.getBody()) : Optional.empty();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.FirstTimeLogin;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class UserService {
|
||||
private final RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
public User findByUsername(String username) {
|
||||
ResponseEntity<User> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_USERNAME),
|
||||
User.class, username);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public Boolean findExistByUsername(String username) {
|
||||
ResponseEntity<Boolean> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_EXIST_BY_USERNAME),
|
||||
Boolean.class, username);
|
||||
return ent.getStatusCode() == HttpStatus.OK && Boolean.TRUE.equals(ent.getBody());
|
||||
}
|
||||
public User findByUsernameWithPassword(String username) {
|
||||
ResponseEntity<User> ent = restTemplateUtil.getForEntity(
|
||||
restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIND_BY_USERNAME_WITH_PASSWORD),
|
||||
User.class, username);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : null;
|
||||
}
|
||||
|
||||
public Boolean updatePhoneVerified(Long userId, GeneralEnum.FlagYesNo phoneVerified) {
|
||||
HashMap<String, Object> param= new HashMap<>();
|
||||
param.put("userId", userId);
|
||||
param.put("phoneVerified", phoneVerified.toString());
|
||||
ResponseEntity<Boolean> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_USER_UPDATE_MEMBER_PHONE_VERIFIED),
|
||||
Boolean.class, param);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null && ent.getBody();
|
||||
}
|
||||
public String getEncryptedString(String plainText) {
|
||||
Map<String, String> requestBody=new HashMap<>();
|
||||
requestBody.put("plainText", plainText);
|
||||
ResponseEntity<String> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_USER_GET_ENCRYPTED_STRING),
|
||||
String.class, requestBody);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : "";
|
||||
}
|
||||
public Boolean checkEncryptedStringMatched(String plainText, String encrypted) {
|
||||
Map<String, String> requestBody=new HashMap<>();
|
||||
requestBody.put("plainText", plainText);
|
||||
requestBody.put("encryptedText", encrypted);
|
||||
ResponseEntity<Boolean> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_USER_CHECK_ENCRYPTED_STRING_MATCHED),
|
||||
Boolean.class, requestBody);
|
||||
return ent.getStatusCode() == HttpStatus.OK && Boolean.TRUE.equals(ent.getBody());
|
||||
}
|
||||
public Integer changePassword(Long userId, String password) {
|
||||
Map<String, String> requestBody=new HashMap<>();
|
||||
requestBody.put("userId", userId.toString());
|
||||
requestBody.put("password", password);
|
||||
ResponseEntity<Integer> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_USER_UPDATE_MEMBER_PASSWORD),
|
||||
Integer.class, requestBody);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : 0;
|
||||
}
|
||||
public String validatePasswordFromRules(String password) {
|
||||
Map<String, String> requestBody=new HashMap<>();
|
||||
requestBody.put("password", password);
|
||||
ResponseEntity<String> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_USER_VALIDATE_PASSWORD_RULES),
|
||||
String.class, requestBody);
|
||||
return ent.getStatusCode() == HttpStatus.OK && ent.getBody() != null ? ent.getBody() : "";
|
||||
}
|
||||
public Boolean firstTimeLogin(FirstTimeLogin firstTimeLogin) {
|
||||
ResponseEntity<Boolean> ent =
|
||||
restTemplateUtil.postForEntity(restTemplateUtil.getURLforApiService(
|
||||
RestApiSystemServiceConstants.API_REST_SYSTEM_USER_FIRST_TIME_LOGIN),
|
||||
Boolean.class, firstTimeLogin);
|
||||
return ent.getStatusCode() == HttpStatus.OK;
|
||||
}
|
||||
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.GeneralEnum.CmsPlatform;
|
||||
import com.solvway.core.enums.GeneralEnum.FlagYesNo;
|
||||
import com.solvway.core.model.ResponseTime;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.JwtTokenUtil;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.core.utils.SnowflakeIdWorker;
|
||||
import com.solvway.core.utils.StackTraceUtil;
|
||||
import com.solvway.mobile.api.config.AuthAppKeyConfig;
|
||||
import com.solvway.mobile.api.config.PubSubConfig;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.UserService;
|
||||
import com.solvway.mobile.api.util.HeaderRedactionUtil;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
|
||||
@Aspect
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AppAccessAspect {
|
||||
|
||||
private final MemberService memberService;
|
||||
private final UserService userService;
|
||||
private final PubSubConfig pubSubConfig;
|
||||
private final PubSubTemplate pubSubTemplate;
|
||||
private final PubSubUtil pubSubUtil;
|
||||
private final AuthAppKeyConfig authAppKey;
|
||||
private final AuthenticationService authenticationService;
|
||||
private final JwtTokenUtil jwtTokenUtil;
|
||||
@Around("execution(* com.solvway.mobile.api.controller.*.*(..))")
|
||||
public Object appAccessAuthCheck(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
long start = System.currentTimeMillis();
|
||||
String methodSig = joinPoint.getSignature().toShortString();
|
||||
String apiKey = HttpReqRespUtils.getHeaderValues("api-key");
|
||||
if(!StringUtils.hasLength(apiKey)){
|
||||
log.warn("[AppAccessAspect] REJECT: missing 'api-key' header for method={}", methodSig);
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing header 'api-key'");
|
||||
}
|
||||
if(!authAppKey.contains(apiKey)) {
|
||||
// Never log the allowed keys, even masked: a short key plus its ":PLATFORM" suffix outlives the mask.
|
||||
log.warn("[AppAccessAspect] REJECT: api-key not in allowed list. received={} allowedKeyCount={}",
|
||||
maskKey(apiKey), authAppKey.getList().size());
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid header 'api-key'");
|
||||
}
|
||||
try {
|
||||
if(!shouldSkipAuth(joinPoint)){
|
||||
validateJwt();
|
||||
requireVerifiedPhoneForCp(joinPoint, apiKey);
|
||||
}
|
||||
return joinPoint.proceed();
|
||||
} catch (ResponseStatusException ex) {
|
||||
log.warn("[AppAccessAspect] REJECT: {} for method={}", ex.getReason(), methodSig);
|
||||
throw ex;
|
||||
} catch (Exception ex) {
|
||||
log.error(StackTraceUtil.getStackTraceAsJsonString(ex));
|
||||
throw ex;
|
||||
} finally {
|
||||
long executionTime = System.currentTimeMillis() - start;
|
||||
long uuid = SnowflakeIdWorker.getUUID();
|
||||
String username = getUsernameFromJwt();
|
||||
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
|
||||
ResponseTime logBean = buildResponseTimeLog(uuid, apiKey, username, executionTime, methodSignature);
|
||||
publishLogSafely(logBean);
|
||||
}
|
||||
}
|
||||
|
||||
private String getUsernameFromJwt() {
|
||||
String username = "APP_PUBLIC";
|
||||
String jwt = HttpReqRespUtils.getJwtToken();
|
||||
if (StringUtils.hasLength(jwt)) {
|
||||
try {
|
||||
username = authenticationService.getUsernameFromToken(jwt);
|
||||
} catch (Exception ex) {
|
||||
log.error("Invalid JWT");
|
||||
}
|
||||
}
|
||||
return username;
|
||||
}
|
||||
|
||||
private void publishLogSafely(ResponseTime logBean) {
|
||||
try {
|
||||
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
|
||||
.getRequest();
|
||||
logBean.setMethod(request.getMethod());
|
||||
logBean.setUrl(request.getRequestURI());
|
||||
logBean.setUserAgent(HttpReqRespUtils.getUserAgent());
|
||||
logBean.setHttpHeaders(HeaderRedactionUtil.redact(HttpReqRespUtils.getAllHeaders()));
|
||||
publishLogMessage(logBean);
|
||||
} catch (Exception ignore) {
|
||||
log.debug("Failed to publish response time log", ignore);
|
||||
}
|
||||
}
|
||||
|
||||
private ResponseTime buildResponseTimeLog(long uuid, String apiKey, String username, long executionTime, MethodSignature methodSignature) {
|
||||
ResponseTime logBean = new ResponseTime();
|
||||
logBean.setSourcePlatform(authAppKey.resolvePlatform(apiKey));
|
||||
logBean.setId(uuid);
|
||||
logBean.setTimeUsedMs(uuid);
|
||||
logBean.setFunctionCalled(methodSignature.toString());
|
||||
logBean.setUsername(username);
|
||||
logBean.setTimeUsedMs(executionTime);
|
||||
logBean.setRequestTime(LocalDateTime.now());
|
||||
return logBean;
|
||||
}
|
||||
|
||||
private boolean shouldSkipAuth(ProceedingJoinPoint joinPoint) {
|
||||
try {
|
||||
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
|
||||
AppAuth annotation = methodSignature.getMethod().getAnnotation(AppAuth.class);
|
||||
return annotation != null && annotation.skipValidate();
|
||||
} catch (Exception ex) {
|
||||
StackTraceUtil.printStackTrace(log, ex);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void requireVerifiedPhoneForCp(ProceedingJoinPoint joinPoint, String apiKey) {
|
||||
if (authAppKey.resolvePlatform(apiKey) != CmsPlatform.CP) {
|
||||
return;
|
||||
}
|
||||
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
|
||||
if (methodSignature.getMethod().isAnnotationPresent(PhoneVerificationExempt.class)) {
|
||||
return;
|
||||
}
|
||||
boolean verified;
|
||||
try {
|
||||
// ponytail: one system-service call per authenticated CP request; cache verified usernames
|
||||
// (flag only moves N->Y) if latency matters.
|
||||
User user = userService.findByUsername(
|
||||
authenticationService.getUsernameFromToken(HttpReqRespUtils.getJwtToken()));
|
||||
if (user == null) {
|
||||
log.warn("[AppAccessAspect] phone-verification lookup returned no user");
|
||||
}
|
||||
verified = user != null
|
||||
&& (user.getPhoneVerified() == FlagYesNo.Y || user.getEmailVerified() == FlagYesNo.Y);
|
||||
} catch (Exception ex) {
|
||||
log.error("[AppAccessAspect] phone-verification lookup failed, failing closed: {}", ex.getClass().getSimpleName());
|
||||
verified = false;
|
||||
}
|
||||
if (!verified) {
|
||||
throw phoneVerificationRequired();
|
||||
}
|
||||
}
|
||||
|
||||
static ResponseStatusException phoneVerificationRequired() {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("X-Phone-Verification-Required", "true");
|
||||
return new ResponseStatusException(HttpStatus.FORBIDDEN, "Phone verification required.") {
|
||||
@Override
|
||||
public HttpHeaders getHeaders() {
|
||||
return headers;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private void validateJwt() {
|
||||
String jwt = HttpReqRespUtils.getJwtToken();
|
||||
if (!StringUtils.hasLength(jwt)) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Missing header 'Authorization'");
|
||||
}
|
||||
boolean isTokenExpired;
|
||||
try {
|
||||
isTokenExpired = Boolean.TRUE.equals(jwtTokenUtil.isTokenExpired(jwt));
|
||||
} catch (Exception ex) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Invalid Token");
|
||||
}
|
||||
if (isTokenExpired) {
|
||||
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Expired Token");
|
||||
}
|
||||
}
|
||||
|
||||
private String maskKey(String key) {
|
||||
if (key == null) return "null";
|
||||
if (key.length() <= 8) return "****";
|
||||
return key.substring(0, 8) + "****(len=" + key.length() + ")";
|
||||
}
|
||||
|
||||
private void publishLogMessage(ResponseTime logBean) {
|
||||
try {
|
||||
String topic = pubSubConfig.responseTimeLogTopic;
|
||||
pubSubUtil.publishMessage(pubSubTemplate, topic, logBean);
|
||||
} catch (Exception e) {
|
||||
log.error(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/** Endpoints a customer-portal user may call before verifying their phone (the OTP endpoints and the first-login password reset). */
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Target(ElementType.METHOD)
|
||||
public @interface PhoneVerificationExempt {
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.solvway.mobile.api.util;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonObject;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Removes credential-bearing header values from the JSON header blob before it is logged
|
||||
* or published to Pub/Sub. Fails closed: unparseable input yields an empty object rather
|
||||
* than the original string.
|
||||
*/
|
||||
public final class HeaderRedactionUtil {
|
||||
|
||||
private static final Set<String> SENSITIVE_HEADERS = Set.of(
|
||||
"authorization",
|
||||
"proxy-authorization",
|
||||
"api-key",
|
||||
"cookie",
|
||||
"set-cookie");
|
||||
|
||||
private static final String REDACTED = "[REDACTED]";
|
||||
private static final Gson GSON = new Gson();
|
||||
|
||||
private HeaderRedactionUtil() {
|
||||
}
|
||||
|
||||
public static String redact(String headersJson) {
|
||||
if (headersJson == null || headersJson.isEmpty()) {
|
||||
return headersJson;
|
||||
}
|
||||
try {
|
||||
JsonObject source = GSON.fromJson(headersJson, JsonObject.class);
|
||||
if (source == null) {
|
||||
return "{}";
|
||||
}
|
||||
JsonObject result = new JsonObject();
|
||||
for (String key : source.keySet()) {
|
||||
if (SENSITIVE_HEADERS.contains(key.toLowerCase(Locale.ROOT))) {
|
||||
result.addProperty(key, REDACTED);
|
||||
} else {
|
||||
result.add(key, source.get(key));
|
||||
}
|
||||
}
|
||||
return GSON.toJson(result);
|
||||
} catch (Exception ex) {
|
||||
return "{}";
|
||||
}
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.solvway.mobile.api.util;
|
||||
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.MultiValueMap;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class RestTemplateCustomUtil {
|
||||
|
||||
private final RestTemplate restTemplate;
|
||||
|
||||
@Value("${app.api-key:''}")
|
||||
private String apiKey;
|
||||
|
||||
@Value("${app.api-gateway-url}")
|
||||
private String apiUrl;
|
||||
|
||||
public String getURLforApiService(String apinameparam) {
|
||||
return getURLforApiService(apinameparam,"");
|
||||
}
|
||||
|
||||
public String getURLforApiService(String apinameparam, String prefix) {
|
||||
String name = apinameparam.startsWith("/") ? apinameparam.substring(1) : apinameparam;
|
||||
return apiUrl + "/" + prefix + name;
|
||||
}
|
||||
|
||||
public HttpEntity<Object> entity(Object request) {
|
||||
return new HttpEntity<>(request, getCommonHeaders());
|
||||
}
|
||||
public HttpHeaders getCommonHeaders() {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("api-key", apiKey);
|
||||
headers.add("CV-Source-Platform", "mobile-api");
|
||||
String jwt = HttpReqRespUtils.getJwtTokenRaw();
|
||||
if(StringUtils.hasLength(jwt)){
|
||||
headers.add("Authorization", jwt);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
public String getJwtFromHeader(){
|
||||
return HttpReqRespUtils.getHeaderValues("Authorization");
|
||||
}
|
||||
public <T> ResponseEntity<T> getForEntity(String url, ParameterizedTypeReference<T> responseType, Object... uriVariables) throws RestClientException {
|
||||
log.info("[RestTemplateCustomUtil] GET {}", url);
|
||||
return restTemplate.exchange(url,HttpMethod.GET, entity(null), responseType, uriVariables);
|
||||
}
|
||||
|
||||
public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables) throws RestClientException {
|
||||
log.info("[RestTemplateCustomUtil] GET {}", url);
|
||||
return restTemplate.exchange(url,HttpMethod.GET, entity(null), responseType, uriVariables);
|
||||
}
|
||||
|
||||
public <T> ResponseEntity<T> postForEntity(String url, ParameterizedTypeReference<T> responseType, Object request) throws RestClientException {
|
||||
return restTemplate.exchange(url,HttpMethod.POST, entity(request), responseType);
|
||||
}
|
||||
|
||||
public <T> ResponseEntity<T> postForEntity(String url, Class<T> responseType, Object request) throws RestClientException {
|
||||
return restTemplate.exchange(url,HttpMethod.POST, entity(request), responseType);
|
||||
}
|
||||
|
||||
public <T> ResponseEntity<T> postForEntity(String url,
|
||||
HttpEntity<MultiValueMap<String, Object>> requestEntity, ParameterizedTypeReference<T> responseType) throws RestClientException {
|
||||
return restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType);
|
||||
}
|
||||
|
||||
public <T> ResponseEntity<T> postForEntity(String url,
|
||||
HttpEntity<MultiValueMap<String, Object>> requestEntity, Class<T> responseType) throws RestClientException {
|
||||
return restTemplate.exchange(url, HttpMethod.POST, requestEntity, responseType);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package com.solvway.mobile.api.util.paging;
|
||||
|
||||
public final class InitialPagingSizes {
|
||||
|
||||
private InitialPagingSizes() { }
|
||||
|
||||
public static final int BUTTONS_TO_SHOW = 5;
|
||||
public static final int INITIAL_PAGE = 0;
|
||||
public static final int INITIAL_PAGE_SIZE = 100;
|
||||
protected static final int[] PAGE_SIZES = {100,200,300,400,500,600,700,800,900,1000};
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.solvway.mobile.api.util.paging;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Sort.Order;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
public class PageableRest{
|
||||
|
||||
@Setter
|
||||
@Getter
|
||||
public static class SortRest {
|
||||
|
||||
private String direction;
|
||||
private String property;
|
||||
|
||||
public SortRest(String direction, String property){
|
||||
this.direction = direction;
|
||||
this.property = property;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private int number;
|
||||
private int size;
|
||||
private PageRequest pageRequest;
|
||||
private ArrayList<SortRest> sorts;
|
||||
|
||||
public PageableRest(PageRequest pageRequest){
|
||||
this.number = pageRequest.getPageNumber();
|
||||
this.size = pageRequest.getPageSize();
|
||||
this.pageRequest = pageRequest;
|
||||
sorts = new ArrayList<>();
|
||||
|
||||
Iterator<Order> it = pageRequest.getSort().iterator();
|
||||
while (it.hasNext()) {
|
||||
Order o = it.next();
|
||||
sorts.add(new SortRest(o.getDirection().name(), o.getProperty()));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.solvway.mobile.api.util.paging;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Getter
|
||||
public class Pager {
|
||||
|
||||
private int buttonsToShow = 5;
|
||||
|
||||
@Setter
|
||||
private int startPage;
|
||||
|
||||
@Setter
|
||||
private int endPage;
|
||||
|
||||
private List<Integer> pageSizesToShow = new ArrayList<>();
|
||||
|
||||
public static final int PAGE_SIZE_ALL= Integer.MAX_VALUE;
|
||||
|
||||
public Pager(int totalPages, int currentPage, int buttonsToShow, long totalSize) {
|
||||
|
||||
setButtonsToShow(buttonsToShow);
|
||||
setPageSizesToShow(totalSize);
|
||||
|
||||
int halfPagesToShow = getButtonsToShow() / 2;
|
||||
|
||||
if (totalPages <= getButtonsToShow()) {
|
||||
setStartPage(1);
|
||||
setEndPage(totalPages);
|
||||
|
||||
} else if (currentPage - halfPagesToShow <= 0) {
|
||||
setStartPage(1);
|
||||
setEndPage(getButtonsToShow());
|
||||
|
||||
} else if (currentPage + halfPagesToShow == totalPages) {
|
||||
setStartPage(currentPage - halfPagesToShow);
|
||||
setEndPage(totalPages);
|
||||
|
||||
} else if (currentPage + halfPagesToShow > totalPages) {
|
||||
setStartPage(totalPages - getButtonsToShow() + 1);
|
||||
setEndPage(totalPages);
|
||||
|
||||
} else {
|
||||
setStartPage(currentPage - halfPagesToShow);
|
||||
setEndPage(currentPage + halfPagesToShow);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public void setButtonsToShow(int buttonsToShow) {
|
||||
if (buttonsToShow % 2 != 0) {
|
||||
this.buttonsToShow = buttonsToShow;
|
||||
} else {
|
||||
throw new IllegalArgumentException("Must be an odd value!");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return "Pager [startPage=" + startPage + ", endPage=" + endPage + "]";
|
||||
}
|
||||
|
||||
public String getPageSizesToShowInJSON() {
|
||||
Gson gson = new GsonBuilder().create();
|
||||
return gson.toJson(pageSizesToShow);
|
||||
}
|
||||
|
||||
public void setPageSizesToShow(long totalSize) {
|
||||
this.pageSizesToShow = Arrays.stream(InitialPagingSizes.PAGE_SIZES).boxed()
|
||||
.filter(pageSize -> totalSize > pageSize)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
//Add in one more option for showing all results but not showing all page sizes
|
||||
Optional<Integer> size = Arrays.stream(InitialPagingSizes.PAGE_SIZES).boxed()
|
||||
.filter(pageSize -> pageSize > totalSize).findFirst();
|
||||
if(size.isPresent()) {
|
||||
this.pageSizesToShow.add(size.get());
|
||||
}
|
||||
this.pageSizesToShow.addFirst(PAGE_SIZE_ALL);
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.solvway.mobile.api.util.paging;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class ResponsePageRest<T> extends PageImpl<T> {
|
||||
/**
|
||||
*
|
||||
*/
|
||||
private static final long serialVersionUID = 3917858643301137470L;
|
||||
|
||||
@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
|
||||
public ResponsePageRest(@JsonProperty("content") List<T> content,
|
||||
@JsonProperty("number") int number,
|
||||
@JsonProperty("size") int size,
|
||||
@JsonProperty("totalElements") Long totalElements,
|
||||
@JsonProperty("pageable") JsonNode pageable,
|
||||
@JsonProperty("last") boolean last,
|
||||
@JsonProperty("totalPages") int totalPages,
|
||||
@JsonProperty("sort") JsonNode sort,
|
||||
@JsonProperty("first") boolean first,
|
||||
@JsonProperty("numberOfElements") int numberOfElements) {
|
||||
|
||||
super(content, PageRequest.of(number, size), totalElements);
|
||||
}
|
||||
|
||||
public ResponsePageRest(List<T> content, Pageable pageable, long total) {
|
||||
super(content, pageable, total);
|
||||
}
|
||||
|
||||
public ResponsePageRest(List<T> content) {
|
||||
super(content);
|
||||
}
|
||||
|
||||
public ResponsePageRest() {
|
||||
super(new ArrayList<>());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.solvway.mobile.api.util.redis;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.data.redis.core.HashOperations;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.ValueOperations;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Component
|
||||
public class RedisUtil<T> {
|
||||
|
||||
@Getter
|
||||
private final RedisTemplate<String, T> redisTemplate;
|
||||
|
||||
private final HashOperations<String, Object, T> hashOperation;
|
||||
|
||||
private final ValueOperations<String, T> valueOperations;
|
||||
|
||||
RedisUtil(RedisTemplate<String, T> redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
this.hashOperation = redisTemplate.opsForHash();
|
||||
this.valueOperations = redisTemplate.opsForValue();
|
||||
}
|
||||
|
||||
|
||||
|
||||
public void putMap(String redisKey, Object key, T data) {
|
||||
hashOperation.put(redisKey, key, data);
|
||||
}
|
||||
|
||||
public T getMapAsSingleEntry(String redisKey, Object key) {
|
||||
return hashOperation.get(redisKey, key);
|
||||
}
|
||||
|
||||
public Map<Object, T> getMapAsAll(String redisKey) {
|
||||
return hashOperation.entries(redisKey);
|
||||
}
|
||||
|
||||
public void putValue(String key, T value) {
|
||||
valueOperations.set(key, value);
|
||||
}
|
||||
|
||||
public void putValueWithExpireTime(String key, T value, long timeout, TimeUnit unit) {
|
||||
valueOperations.set(key, value, timeout, unit);
|
||||
}
|
||||
|
||||
public T getValue(String key) {
|
||||
return valueOperations.get(key);
|
||||
}
|
||||
|
||||
public void setExpire(String key, long timeout, TimeUnit unit) {
|
||||
redisTemplate.expire(key, timeout, unit);
|
||||
}
|
||||
|
||||
public void delete(String key) {
|
||||
redisTemplate.delete(key);
|
||||
}
|
||||
|
||||
public boolean checkKeyExist(String key) {
|
||||
if (key == null) {
|
||||
return false;
|
||||
}
|
||||
Boolean exists = redisTemplate.hasKey(key);
|
||||
return Boolean.TRUE.equals(exists);
|
||||
}
|
||||
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.solvway.mobile.api.util.redis;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.HexFormat;
|
||||
|
||||
/**
|
||||
* Derives Redis cache keys from bearer tokens without storing the token itself,
|
||||
* so live credentials are not recoverable by scanning Redis key names.
|
||||
*/
|
||||
public final class TokenCacheKeyUtil {
|
||||
|
||||
private TokenCacheKeyUtil() {
|
||||
}
|
||||
|
||||
public static String hashToken(String token) {
|
||||
if (token == null || token.isEmpty()) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
return HexFormat.of().formatHex(digest.digest(token.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch (NoSuchAlgorithmException ex) {
|
||||
throw new IllegalStateException("SHA-256 is required but unavailable", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
app:
|
||||
api-key: ${APIKEY:}
|
||||
api-gateway-url: ${APIGATEWAYURL}
|
||||
# TODO: confirm real customer-portal host
|
||||
customer-portal-base-url: ${CUSTOMER_PORTAL_BASE_URL:https://user.tastefullyexpo.com}
|
||||
system:
|
||||
format:
|
||||
date: dd-MM-yyyy
|
||||
time: HH:mm:ss
|
||||
dateTime: dd-MM-yyyy HH:mm:ss
|
||||
decimal-point: 2
|
||||
decimal-point-bv: 0
|
||||
decimal-point-currency: 4
|
||||
decimal-point-bonus: 4
|
||||
server:
|
||||
port: 80
|
||||
spring:
|
||||
cloud:
|
||||
gcp:
|
||||
project-id: ${GCP_PROJECT}
|
||||
credentials:
|
||||
location: ${GCP_CREDENTIAL_FILE}
|
||||
data:
|
||||
redis:
|
||||
host: ${REDISHOST}
|
||||
port: 6379
|
||||
database: 3
|
||||
threads:
|
||||
virtual:
|
||||
enabled: true
|
||||
cache:
|
||||
time-to-live: 14400 # Seconds; 4hrs * 60minutes * 60seconds = 14400seconds
|
||||
time-to-live-public: 1800 #30min
|
||||
auth:
|
||||
api-key:
|
||||
# Comma-separated inbound client API keys, supplied by the AUTH_API_KEYS environment variable.
|
||||
# Each token is "<key>" or "<key>:<PLATFORM>" where PLATFORM is a CmsPlatform name
|
||||
# (APP=mobile app, CP=customer portal). The resolved platform is stamped on every
|
||||
# response-time log; a bare key defaults to APP. Never commit key material here.
|
||||
list: ${AUTH_API_KEYS:}
|
||||
jwt:
|
||||
# HS512 signing secret, supplied by the JWT_SECRET environment variable (minimum 32 characters).
|
||||
secret: ${JWT_SECRET:}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
package com.solvway.mobile.api.cache;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class MessageLabelCacheTest {
|
||||
|
||||
private static class MutableClock extends Clock {
|
||||
private Instant now = Instant.parse("2026-04-24T00:00:00Z");
|
||||
@Override public ZoneId getZone() { return ZoneId.of("UTC"); }
|
||||
@Override public Clock withZone(ZoneId zone) { return this; }
|
||||
@Override public Instant instant() { return now; }
|
||||
void advance(Duration d) { now = now.plus(d); }
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_returnsEmpty_whenNothingCached() {
|
||||
MessageLabelCache cache = new MessageLabelCache(Clock.systemUTC());
|
||||
assertThat(cache.get("CODE", "en_US")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_returnsValue_whenWithinTtl() {
|
||||
MutableClock clock = new MutableClock();
|
||||
MessageLabelCache cache = new MessageLabelCache(clock);
|
||||
cache.put("CODE", "en_US", "Hello");
|
||||
clock.advance(Duration.ofMinutes(9));
|
||||
|
||||
assertThat(cache.get("CODE", "en_US")).contains("Hello");
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_returnsEmpty_afterTtlExpiry() {
|
||||
MutableClock clock = new MutableClock();
|
||||
MessageLabelCache cache = new MessageLabelCache(clock);
|
||||
cache.put("CODE", "en_US", "Hello");
|
||||
clock.advance(Duration.ofMinutes(11));
|
||||
|
||||
assertThat(cache.get("CODE", "en_US")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void get_respectsLocaleBoundary() {
|
||||
MessageLabelCache cache = new MessageLabelCache(Clock.systemUTC());
|
||||
cache.put("CODE", "en_US", "Hello");
|
||||
cache.put("CODE", "zh_CN", "Nihao");
|
||||
|
||||
assertThat(cache.get("CODE", "en_US")).contains("Hello");
|
||||
assertThat(cache.get("CODE", "zh_CN")).contains("Nihao");
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package com.solvway.mobile.api.config;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum.CmsPlatform;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class AuthAppKeyConfigTest {
|
||||
|
||||
@Test
|
||||
void resolvesConfiguredPlatformPerKey() {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(List.of("customerKey:CP", "appKey:APP"));
|
||||
|
||||
assertThat(config.contains("customerKey")).isTrue();
|
||||
assertThat(config.resolvePlatform("customerKey")).isEqualTo(CmsPlatform.CP);
|
||||
assertThat(config.resolvePlatform("appKey")).isEqualTo(CmsPlatform.APP);
|
||||
}
|
||||
|
||||
@Test
|
||||
void bareKeyWithoutPlatformDefaultsToApp() {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(List.of("legacyKey"));
|
||||
|
||||
assertThat(config.contains("legacyKey")).isTrue();
|
||||
assertThat(config.resolvePlatform("legacyKey")).isEqualTo(CmsPlatform.APP);
|
||||
}
|
||||
|
||||
@Test
|
||||
void unrecognisedPlatformSuffixTreatsWholeTokenAsKeyAndDefaultsToApp() {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(List.of("k:NOPE"));
|
||||
|
||||
// "NOPE" is not a CmsPlatform, so the whole token is the key (not "k").
|
||||
assertThat(config.contains("k:NOPE")).isTrue();
|
||||
assertThat(config.contains("k")).isFalse();
|
||||
assertThat(config.resolvePlatform("k:NOPE")).isEqualTo(CmsPlatform.APP);
|
||||
}
|
||||
|
||||
@Test
|
||||
void keyContainingColonResolvesTrailingPlatformSuffix() {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(List.of("ab:cd:CP"));
|
||||
|
||||
assertThat(config.contains("ab:cd")).isTrue();
|
||||
assertThat(config.resolvePlatform("ab:cd")).isEqualTo(CmsPlatform.CP);
|
||||
}
|
||||
|
||||
@Test
|
||||
void suffixedTokenIsNotItselfAKey() {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(List.of("cpKey:CP"));
|
||||
|
||||
assertThat(config.contains("cpKey:CP")).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownKeyIsNotContainedAndResolvesToAppDefault() {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(List.of("k:CP"));
|
||||
|
||||
assertThat(config.contains("missing")).isFalse();
|
||||
assertThat(config.contains(null)).isFalse();
|
||||
assertThat(config.resolvePlatform("missing")).isEqualTo(CmsPlatform.APP);
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package com.solvway.mobile.api.config;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class StartupSecurityConfigValidatorTest {
|
||||
|
||||
private static final String VALID_SECRET = "0123456789abcdef0123456789abcdef";
|
||||
private static final String VALID_OUTBOUND_KEY = "outbound-key";
|
||||
|
||||
private static AuthAppKeyConfig keysOf(List<String> keys) {
|
||||
AuthAppKeyConfig config = new AuthAppKeyConfig();
|
||||
config.setList(keys);
|
||||
return config;
|
||||
}
|
||||
|
||||
private static StartupSecurityConfigValidator validator(String secret, String outboundKey, List<String> inboundKeys) {
|
||||
return new StartupSecurityConfigValidator(secret, outboundKey, keysOf(inboundKeys));
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsFullyConfiguredEnvironment() {
|
||||
assertThatCode(validator(VALID_SECRET, VALID_OUTBOUND_KEY, List.of("client-key"))::validate)
|
||||
.doesNotThrowAnyException();
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMissingJwtSecret() {
|
||||
assertThatThrownBy(validator("", VALID_OUTBOUND_KEY, List.of("client-key"))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("JWT_SECRET");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsSpringQuotedEmptyDefaultForJwtSecret() {
|
||||
assertThatThrownBy(validator("''", VALID_OUTBOUND_KEY, List.of("client-key"))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("JWT_SECRET");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsShortJwtSecret() {
|
||||
assertThatThrownBy(validator("tooshort", VALID_OUTBOUND_KEY, List.of("client-key"))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("at least 32");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsEmptyInboundApiKeyList() {
|
||||
assertThatThrownBy(validator(VALID_SECRET, VALID_OUTBOUND_KEY, List.of())::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("AUTH_API_KEYS");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInboundApiKeyListWhoseTokensHaveNoKey() {
|
||||
// ":CP" is non-blank but parses to an empty key, so it would authorise nothing.
|
||||
assertThatThrownBy(validator(VALID_SECRET, VALID_OUTBOUND_KEY, List.of(":CP"))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("AUTH_API_KEYS");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInboundApiKeyListOfBlanks() {
|
||||
assertThatThrownBy(validator(VALID_SECRET, VALID_OUTBOUND_KEY, List.of("", " "))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("AUTH_API_KEYS");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMissingOutboundApiKey() {
|
||||
assertThatThrownBy(validator(VALID_SECRET, "", List.of("client-key"))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.hasMessageContaining("APIKEY");
|
||||
}
|
||||
|
||||
@Test
|
||||
void errorMessageNeverLeaksTheSecretValue() {
|
||||
String secret = "supersecretvalue";
|
||||
assertThatThrownBy(validator(secret, VALID_OUTBOUND_KEY, List.of("client-key"))::validate)
|
||||
.isInstanceOf(IllegalStateException.class)
|
||||
.satisfies(ex -> assertThat(ex.getMessage()).doesNotContain(secret));
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import com.solvway.mobile.api.model.AuthRequest;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
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.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AuthControllerPhoneVerificationTest {
|
||||
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private ValidateUtil validateUtil;
|
||||
|
||||
@InjectMocks private AuthController controller;
|
||||
|
||||
private ResponseEntity<Map<String, String>> loginAs(GeneralEnum.FlagYesNo phone, GeneralEnum.FlagYesNo email) {
|
||||
User u = new User();
|
||||
u.setMemberCode("M1");
|
||||
u.setName("Alice");
|
||||
u.setPhoneNoPrefix("60");
|
||||
u.setPhoneNo("123456789");
|
||||
u.setLogin(GeneralEnum.LoginStatus.Y);
|
||||
u.setPhoneVerified(phone);
|
||||
u.setEmailVerified(email);
|
||||
when(authenticationService.getToken(any())).thenReturn("tok");
|
||||
when(authenticationService.loadUserByToken("tok")).thenReturn(u);
|
||||
AuthRequest req = new AuthRequest();
|
||||
req.setUsername("alice@example.com");
|
||||
return controller.login(req);
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginReportsPhoneVerificationRequiredWhenNeitherVerified() {
|
||||
Map<String, String> body = loginAs(GeneralEnum.FlagYesNo.N, GeneralEnum.FlagYesNo.N).getBody();
|
||||
assertThat(body).containsEntry("phoneVerificationRequired", "true");
|
||||
assertThat(body).containsEntry("token", "tok").containsEntry("memberCode", "M1")
|
||||
.containsEntry("name", "Alice").containsEntry("phoneNoPrefix", "60")
|
||||
.containsEntry("phoneNo", "123456789").containsEntry("resetPasswordRequired", "false");
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginReportsNotRequiredWhenPhoneVerified() {
|
||||
Map<String, String> body = loginAs(GeneralEnum.FlagYesNo.Y, GeneralEnum.FlagYesNo.N).getBody();
|
||||
assertThat(body).containsEntry("phoneVerificationRequired", "false");
|
||||
}
|
||||
|
||||
@Test
|
||||
void loginReportsNotRequiredWhenEmailVerified() {
|
||||
Map<String, String> body = loginAs(GeneralEnum.FlagYesNo.N, GeneralEnum.FlagYesNo.Y).getBody();
|
||||
assertThat(body).containsEntry("phoneVerificationRequired", "false");
|
||||
}
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.model.CheckInBooth;
|
||||
import com.solvway.core.model.StockistCmsProfile;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.NumberFormatterUtil;
|
||||
import com.solvway.core.utils.QrScanUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.DriveService;
|
||||
import com.solvway.mobile.api.service.EventService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.StockistCmsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EventControllerAttendanceTest {
|
||||
|
||||
@Mock private EventService eventService;
|
||||
@Mock private DriveService driveService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private NumberFormatterUtil numberFormatterUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private QrScanUtil qrScanUtil;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
@Mock private MemberService memberService;
|
||||
|
||||
@InjectMocks private EventController controller;
|
||||
|
||||
private static final long MEMBER_UUID = 12345L;
|
||||
|
||||
private CheckInBooth checkIn(long stockistUuid, long eventUuid, LocalDateTime dt) {
|
||||
CheckInBooth c = new CheckInBooth();
|
||||
c.setStockistUuid(stockistUuid);
|
||||
c.setEventUuid(eventUuid);
|
||||
c.setCheckInDateTime(dt);
|
||||
c.setCheckInDate(dt == null ? null : dt.toLocalDate());
|
||||
return c;
|
||||
}
|
||||
|
||||
private StockistCmsProfile profile(String name) {
|
||||
StockistCmsProfile p = new StockistCmsProfile();
|
||||
p.setStockistName(name);
|
||||
return p;
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_unresolvedMember_returns401() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn("");
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
verify(eventService, never()).findCheckInBoothByMemberUuid(anyLong());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_sortsDescAndEnrichesBoothName() {
|
||||
LocalDateTime older = LocalDateTime.of(2026, 7, 1, 10, 0);
|
||||
LocalDateTime newer = LocalDateTime.of(2026, 7, 3, 15, 30);
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findCheckInBoothByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(checkIn(101L, 900L, older), checkIn(202L, 901L, newer)));
|
||||
when(stockistCmsService.findByStockistUuid("101")).thenReturn(Optional.of(profile("Booth Alpha")));
|
||||
when(stockistCmsService.findByStockistUuid("202")).thenReturn(Optional.of(profile("Booth Beta")));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
List<Map<String, Object>> body = res.getBody();
|
||||
assertThat(body).hasSize(2);
|
||||
// most recent first
|
||||
assertThat(body.get(0)).containsEntry("stockistName", "Booth Beta");
|
||||
assertThat(body.get(0)).containsEntry("stockistUuid", 202L);
|
||||
assertThat(body.get(1)).containsEntry("stockistName", "Booth Alpha");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_repeatedBooth_lookedUpOnce() {
|
||||
LocalDateTime t1 = LocalDateTime.of(2026, 7, 1, 10, 0);
|
||||
LocalDateTime t2 = LocalDateTime.of(2026, 7, 2, 10, 0);
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findCheckInBoothByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(checkIn(101L, 900L, t1), checkIn(101L, 901L, t2)));
|
||||
when(stockistCmsService.findByStockistUuid("101")).thenReturn(Optional.of(profile("Booth Alpha")));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getBody()).hasSize(2);
|
||||
verify(stockistCmsService, times(1)).findByStockistUuid("101");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_unresolvedBoothName_recordStillReturnedWithoutName() {
|
||||
LocalDateTime t1 = LocalDateTime.of(2026, 7, 1, 10, 0);
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findCheckInBoothByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(checkIn(101L, 900L, t1)));
|
||||
when(stockistCmsService.findByStockistUuid("101")).thenReturn(Optional.empty());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getBody()).hasSize(1);
|
||||
assertThat(res.getBody().get(0)).doesNotContainKey("stockistName");
|
||||
assertThat(res.getBody().get(0)).containsEntry("stockistUuid", 101L);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_empty_returnsEmptyList() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findCheckInBoothByMemberUuid(MEMBER_UUID)).thenReturn(List.of());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_nullCheckInDateTime_sortsLast() {
|
||||
LocalDateTime newer = LocalDateTime.of(2026, 7, 3, 15, 30);
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findCheckInBoothByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(checkIn(101L, 900L, null), checkIn(202L, 901L, newer)));
|
||||
when(stockistCmsService.findByStockistUuid("101")).thenReturn(Optional.of(profile("Booth Null")));
|
||||
when(stockistCmsService.findByStockistUuid("202")).thenReturn(Optional.of(profile("Booth Beta")));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
List<Map<String, Object>> body = res.getBody();
|
||||
assertThat(body).hasSize(2);
|
||||
// Non-null timestamp first, null timestamp sorts last.
|
||||
assertThat(body.get(0)).containsEntry("stockistUuid", 202L);
|
||||
assertThat(body.get(1)).containsEntry("stockistUuid", 101L);
|
||||
assertThat(body.get(1)).doesNotContainKey("checkInDateTime");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_repeatedBoothWithNullName_lookedUpOnce() {
|
||||
LocalDateTime t1 = LocalDateTime.of(2026, 7, 1, 10, 0);
|
||||
LocalDateTime t2 = LocalDateTime.of(2026, 7, 2, 10, 0);
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findCheckInBoothByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(checkIn(101L, 900L, t1), checkIn(101L, 901L, t2)));
|
||||
when(stockistCmsService.findByStockistUuid("101")).thenReturn(Optional.empty());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getBody()).hasSize(2);
|
||||
assertThat(res.getBody().get(0)).doesNotContainKey("stockistName");
|
||||
assertThat(res.getBody().get(1)).doesNotContainKey("stockistName");
|
||||
// A null-resolving name is cached too: the repeated booth is looked up only once.
|
||||
verify(stockistCmsService, times(1)).findByStockistUuid("101");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCheckIns_nonNumericMemberUuid_returns401() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn("not-a-number");
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getCheckIns();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
verify(eventService, never()).findCheckInBoothByMemberUuid(anyLong());
|
||||
}
|
||||
}
|
||||
}
|
||||
+264
@@ -0,0 +1,264 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.PaymentEnum;
|
||||
import com.solvway.core.model.CheckInBooth;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.StockistCmsProfile;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.NumberFormatterUtil;
|
||||
import com.solvway.core.utils.QrScanUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.DriveService;
|
||||
import com.solvway.mobile.api.service.EventService;
|
||||
import com.solvway.mobile.api.service.StockistCmsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Spy;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EventControllerCheckInTest {
|
||||
|
||||
// Real QrScanUtil — pure/stateless; exercises actual prefix routing
|
||||
@Spy private QrScanUtil qrScanUtil = new QrScanUtil();
|
||||
|
||||
@Mock private EventService eventService;
|
||||
@Mock private DriveService driveService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private NumberFormatterUtil numberFormatterUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
|
||||
@InjectMocks
|
||||
private EventController controller;
|
||||
|
||||
// CI prefix from PaymentEnum.QrScanCodeAction.CI → "xFS86OG395iCIPch_"
|
||||
private static final String CI_PREFIX = PaymentEnum.QrScanCodeAction.CI.getPrefix();
|
||||
private static final String PT_PREFIX = PaymentEnum.QrScanCodeAction.PT.getPrefix();
|
||||
|
||||
private static final String ENCRYPTED_STOCKIST = "encryptedStockistPayload";
|
||||
private static final String STOCKIST_UUID_STR = "999001";
|
||||
private static final long STOCKIST_UUID = 999001L;
|
||||
private static final String MEMBER_UUID_STR = "12345";
|
||||
private static final long MEMBER_UUID = 12345L;
|
||||
private static final long EVENT_UUID = 77001L;
|
||||
private static final String MEMBER_CODE = "MC001";
|
||||
|
||||
private Event buildEvent() {
|
||||
Event e = new Event();
|
||||
e.setName("Tastefully 2026");
|
||||
e.setUuid(EVENT_UUID);
|
||||
return e;
|
||||
}
|
||||
|
||||
// ── 1. Happy path ────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_happyPath_returnsCheckedIn() {
|
||||
Event event = buildEvent();
|
||||
CheckInBooth saved = new CheckInBooth();
|
||||
|
||||
StockistCmsProfile profile = new StockistCmsProfile();
|
||||
profile.setStockistName("Booth Alpha");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(MEMBER_UUID_STR);
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn(MEMBER_CODE);
|
||||
when(authenticationService.decrypt(ENCRYPTED_STOCKIST)).thenReturn(STOCKIST_UUID_STR);
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event));
|
||||
when(eventService.saveCheckInBooth(any())).thenReturn(saved);
|
||||
when(stockistCmsService.findByStockistUuid(STOCKIST_UUID_STR)).thenReturn(Optional.of(profile));
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "CHECKED_IN");
|
||||
assertThat(res.getBody()).containsEntry("eventName", "Tastefully 2026");
|
||||
assertThat(res.getBody()).containsEntry("stockistName", "Booth Alpha");
|
||||
|
||||
// Verify saveCheckInBooth called with correct field values
|
||||
ArgumentCaptor<CheckInBooth> captor = ArgumentCaptor.forClass(CheckInBooth.class);
|
||||
verify(eventService).saveCheckInBooth(captor.capture());
|
||||
CheckInBooth recorded = captor.getValue();
|
||||
assertThat(recorded.getEventUuid()).isEqualTo(EVENT_UUID);
|
||||
assertThat(recorded.getStockistUuid()).isEqualTo(STOCKIST_UUID);
|
||||
assertThat(recorded.getMemberUuid()).isEqualTo(MEMBER_UUID);
|
||||
assertThat(recorded.getCreateBy()).isEqualTo(MEMBER_CODE);
|
||||
assertThat(recorded.getDoneBy()).isEqualTo(MEMBER_CODE);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 1b. Already checked in today at this booth ───────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_alreadyCheckedInToday_returnsAlreadyCheckedInAndDoesNotSave() {
|
||||
Event event = buildEvent();
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(MEMBER_UUID_STR);
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn(MEMBER_CODE);
|
||||
when(authenticationService.decrypt(ENCRYPTED_STOCKIST)).thenReturn(STOCKIST_UUID_STR);
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event));
|
||||
// A check-in already exists for this (event, member, booth, today).
|
||||
when(eventService.findCheckInExisted(any())).thenReturn(true);
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "ALREADY_CHECKED_IN");
|
||||
assertThat(res.getBody()).containsEntry("eventName", "Tastefully 2026");
|
||||
// The dedup check ran against the correct booth/member/event...
|
||||
ArgumentCaptor<CheckInBooth> captor = ArgumentCaptor.forClass(CheckInBooth.class);
|
||||
verify(eventService).findCheckInExisted(captor.capture());
|
||||
CheckInBooth probed = captor.getValue();
|
||||
assertThat(probed.getEventUuid()).isEqualTo(EVENT_UUID);
|
||||
assertThat(probed.getStockistUuid()).isEqualTo(STOCKIST_UUID);
|
||||
assertThat(probed.getMemberUuid()).isEqualTo(MEMBER_UUID);
|
||||
// ...and no duplicate was persisted.
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
}
|
||||
|
||||
// ── 2. Wrong QR type ─────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_wrongQrType_returnsWrongQrType() {
|
||||
Map<String, String> body = Map.of("qrText", PT_PREFIX + "somePayload");
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "WRONG_QR_TYPE");
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
|
||||
// ── 3. No active event ───────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_noActiveEvent_returnsNoActiveEvent() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.empty());
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "NO_ACTIVE_EVENT");
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
|
||||
// ── 4. Invalid stockist uuid ─────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_emptyDecryptResult_returnsInvalidQr() {
|
||||
Event event = buildEvent();
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event));
|
||||
// decrypt returns empty → INVALID_QR
|
||||
when(authenticationService.decrypt(ENCRYPTED_STOCKIST)).thenReturn("");
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "INVALID_QR");
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkIn_nonNumericStockistUuid_returnsInvalidQr() {
|
||||
Event event = buildEvent();
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event));
|
||||
// decrypt returns non-numeric value
|
||||
when(authenticationService.decrypt(ENCRYPTED_STOCKIST)).thenReturn("not-a-number");
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "INVALID_QR");
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
|
||||
// ── 5. Unresolved member → HTTP 401 ─────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_unresolvedMember_returns401() {
|
||||
Event event = buildEvent();
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event));
|
||||
when(authenticationService.decrypt(ENCRYPTED_STOCKIST)).thenReturn(STOCKIST_UUID_STR);
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn("");
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
}
|
||||
|
||||
// ── 6. Persistence failure ────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_persistenceFailure_returnsCheckInFailed() {
|
||||
Event event = buildEvent();
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event));
|
||||
when(authenticationService.decrypt(ENCRYPTED_STOCKIST)).thenReturn(STOCKIST_UUID_STR);
|
||||
when(eventService.saveCheckInBooth(any())).thenReturn(null);
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(MEMBER_UUID_STR);
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn(MEMBER_CODE);
|
||||
|
||||
Map<String, String> body = Map.of("qrText", CI_PREFIX + ENCRYPTED_STOCKIST);
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "CHECK_IN_FAILED");
|
||||
verify(eventService).saveCheckInBooth(any());
|
||||
}
|
||||
}
|
||||
|
||||
// ── 7. Blank/empty qrText ────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_blankQrText_returnsInvalidQr() {
|
||||
Map<String, String> body = Map.of("qrText", "");
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "INVALID_QR");
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
|
||||
// ── 8. Unrecognized/NA prefix ────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void checkIn_unrecognizedPrefix_returnsWrongQrType() {
|
||||
Map<String, String> body = Map.of("qrText", "totally-unrecognized-prefix-payload");
|
||||
ResponseEntity<Map<String, Object>> res = controller.checkIn(body);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("status", "WRONG_QR_TYPE");
|
||||
verify(eventService, never()).saveCheckInBooth(any());
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.EventProduct;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.NumberFormatterUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.DriveService;
|
||||
import com.solvway.mobile.api.service.EventService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
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;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyInt;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class EventControllerCurrentConfigTest {
|
||||
|
||||
@Mock private EventService eventService;
|
||||
@Mock private DriveService driveService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private NumberFormatterUtil numberFormatterUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private MemberService memberService;
|
||||
|
||||
@InjectMocks private EventController controller;
|
||||
|
||||
private Event event(String tasteRewardsDoc) {
|
||||
Event e = new Event();
|
||||
e.setUuid(100L);
|
||||
e.setName("Wonderfood");
|
||||
e.setUploadTasteRewards(tasteRewardsDoc);
|
||||
return e;
|
||||
}
|
||||
|
||||
private EventProduct product(String name, double cost) {
|
||||
EventProduct p = new EventProduct();
|
||||
p.setDisplayName(name);
|
||||
p.setCostAmount(cost);
|
||||
return p;
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void returnsProductsWhenNoTasteRewardsDocument() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event("")));
|
||||
when(eventService.findEventProductByEventUuid(100L)).thenReturn(List.of(
|
||||
product("Massage Mat", 1000), product("Magnet", 800)));
|
||||
|
||||
Map<String, Object> body = controller.getCurrentEventConfig().getBody();
|
||||
|
||||
assertThat(body).doesNotContainKey("currentEventTasteRewards");
|
||||
List<EventProduct> products = (List<EventProduct>) body.get("currentEventTasteRewardsProductList");
|
||||
assertThat(products).extracting(EventProduct::getDisplayName).containsExactly("Magnet", "Massage Mat");
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsProductsAndDocumentWhenBothExist() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event("/EVENT_TASTE_REWARDS/x.png")));
|
||||
when(driveService.getPresignedUrl(any(), anyInt(), any(TimeUnit.class))).thenReturn("https://signed/x.png");
|
||||
when(eventService.findEventProductByEventUuid(100L)).thenReturn(List.of(product("Magnet", 800)));
|
||||
|
||||
Map<String, Object> body = controller.getCurrentEventConfig().getBody();
|
||||
|
||||
assertThat(body).containsEntry("currentEventTasteRewards", "https://signed/x.png");
|
||||
assertThat((List<?>) body.get("currentEventTasteRewardsProductList")).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void nullProductLookupReturnsEmptyList() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event(null)));
|
||||
when(eventService.findEventProductByEventUuid(100L)).thenReturn(null);
|
||||
|
||||
Map<String, Object> body = controller.getCurrentEventConfig().getBody();
|
||||
|
||||
assertThat((List<?>) body.get("currentEventTasteRewardsProductList")).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void noCurrentEventReturnsEmptyBody() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.empty());
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getCurrentEventConfig();
|
||||
|
||||
assertThat(response.getBody()).isNull();
|
||||
}
|
||||
}
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.OrderEnum;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.EventLuckyDrawTicket;
|
||||
import com.solvway.core.model.EventReceipt;
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.NumberFormatterUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.DriveService;
|
||||
import com.solvway.mobile.api.service.EventService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.mockito.ArgumentMatchers;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EventControllerLuckyDrawTest {
|
||||
|
||||
@Mock private EventService eventService;
|
||||
@Mock private DriveService driveService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private NumberFormatterUtil numberFormatterUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private MemberService memberService;
|
||||
|
||||
@InjectMocks private EventController controller;
|
||||
|
||||
private Event event() {
|
||||
Event e = new Event();
|
||||
e.setUuid(100L);
|
||||
e.setUploadLuckyDraw("ld/poster.png");
|
||||
return e;
|
||||
}
|
||||
|
||||
private Member member() {
|
||||
Member m = new Member();
|
||||
m.setUuid("200");
|
||||
return m;
|
||||
}
|
||||
|
||||
private EventReceipt receipt(LocalDateTime when, OrderEnum.EventReceiptReviewStatus status, double amount) {
|
||||
EventReceipt r = new EventReceipt();
|
||||
r.setUploadDateTime(when);
|
||||
r.setReviewStatus(status);
|
||||
r.setPurchaseAmount(amount);
|
||||
return r;
|
||||
}
|
||||
|
||||
private EventLuckyDrawTicket ticket(LocalDateTime when) {
|
||||
EventLuckyDrawTicket t = new EventLuckyDrawTicket();
|
||||
t.setCreateDateTime(when);
|
||||
return t;
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsTodayTicketCountNonPendingSpentAndPresignedPoster() {
|
||||
Event e = event();
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(e));
|
||||
when(eventService.findEventReceiptByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of(
|
||||
receipt(LocalDateTime.now(), OrderEnum.EventReceiptReviewStatus.A, 500.0),
|
||||
receipt(LocalDateTime.now(), OrderEnum.EventReceiptReviewStatus.R, 350.0),
|
||||
receipt(LocalDateTime.now(), OrderEnum.EventReceiptReviewStatus.P, 999.0),
|
||||
receipt(LocalDateTime.now().minusDays(1), OrderEnum.EventReceiptReviewStatus.A, 123.0)
|
||||
));
|
||||
when(eventService.findEventLuckyDrawTicketByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of(
|
||||
ticket(LocalDateTime.now()),
|
||||
ticket(LocalDateTime.now()),
|
||||
ticket(LocalDateTime.now().minusDays(1))
|
||||
));
|
||||
when(driveService.getPresignedUrl("ld/poster.png", 24, TimeUnit.HOURS)).thenReturn("https://signed/poster");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(member());
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getLuckyDraw();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("ticketCount", 2);
|
||||
assertThat(res.getBody()).containsEntry("totalSpent", 850.0);
|
||||
assertThat(res.getBody()).containsEntry("posterUrl", "https://signed/poster");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void returns404WhenNoCurrentEvent() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.empty());
|
||||
ResponseEntity<Map<String, Object>> res = controller.getLuckyDraw();
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returns404WhenMemberNotFound() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(null);
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getLuckyDraw();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void omitsPosterUrlWhenEventHasNoPoster() {
|
||||
Event e = event();
|
||||
e.setUploadLuckyDraw(null);
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(e));
|
||||
when(eventService.findEventReceiptByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of());
|
||||
when(eventService.findEventLuckyDrawTicketByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of());
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(member());
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getLuckyDraw();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).doesNotContainKey("posterUrl");
|
||||
assertThat(res.getBody()).containsEntry("ticketCount", 0);
|
||||
assertThat(res.getBody()).containsEntry("totalSpent", 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyReturnsRowsNewestFirstWithApprovedTicketsAndPresignedReceiptUrls() throws Exception {
|
||||
Event e = event();
|
||||
|
||||
EventReceipt pendingOlder = new EventReceipt();
|
||||
pendingOlder.setUuid(1L);
|
||||
pendingOlder.setUploadDateTime(java.time.LocalDateTime.now().minusHours(2));
|
||||
pendingOlder.setReviewStatus(OrderEnum.EventReceiptReviewStatus.P);
|
||||
pendingOlder.setUploadPath(List.of("r/1a.png"));
|
||||
|
||||
EventReceipt approvedNewer = new EventReceipt();
|
||||
approvedNewer.setUuid(2L);
|
||||
approvedNewer.setUploadDateTime(java.time.LocalDateTime.now().minusHours(1));
|
||||
approvedNewer.setReviewStatus(OrderEnum.EventReceiptReviewStatus.A);
|
||||
approvedNewer.setUploadPath(List.of("r/2a.png", "r/2b.png"));
|
||||
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(e));
|
||||
when(eventService.findEventReceiptByEventUuidAndMemberUuid(100L, 200L))
|
||||
.thenReturn(List.of(pendingOlder, approvedNewer));
|
||||
when(eventService.findEventLuckyDrawTicketByEventUuidAndReceiptUuid(100L, 2L))
|
||||
.thenReturn(List.of(ticket(java.time.LocalDateTime.now()), ticket(java.time.LocalDateTime.now())));
|
||||
when(driveService.getPresignedUrl("r/1a.png", 24, TimeUnit.HOURS)).thenReturn("https://s/1a");
|
||||
when(driveService.getPresignedUrl("r/2a.png", 24, TimeUnit.HOURS)).thenReturn("https://s/2a");
|
||||
when(driveService.getPresignedUrl("r/2b.png", 24, TimeUnit.HOURS)).thenReturn("https://s/2b");
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(java.time.LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(member());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getLuckyDrawHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
List<Map<String, Object>> body = res.getBody();
|
||||
assertThat(body).hasSize(2);
|
||||
assertThat(body.get(0)).containsEntry("reviewStatus", "A");
|
||||
assertThat(body.get(0)).containsEntry("reviewStatusLabel", "Approved");
|
||||
assertThat(body.get(0)).containsEntry("ticketCount", 2);
|
||||
assertThat(body.get(0).get("receiptUrls")).isEqualTo(List.of("https://s/2a", "https://s/2b"));
|
||||
assertThat(body.get(1)).containsEntry("reviewStatus", "P");
|
||||
assertThat(body.get(1)).containsEntry("reviewStatusLabel", "Pending");
|
||||
assertThat(body.get(1)).containsEntry("ticketCount", 0);
|
||||
assertThat(body.get(1).get("receiptUrls")).isEqualTo(List.of("https://s/1a"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyReturns404WhenNoCurrentEvent() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.empty());
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getLuckyDrawHistory();
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyReturnsEmptyListWhenNoReceiptsToday() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
when(eventService.findEventReceiptByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of());
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(member());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getLuckyDrawHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void historyRowHasEmptyReceiptUrlsWhenUploadPathNull() throws Exception {
|
||||
EventReceipt r = new EventReceipt();
|
||||
r.setUuid(5L);
|
||||
r.setUploadDateTime(java.time.LocalDateTime.now());
|
||||
r.setReviewStatus(OrderEnum.EventReceiptReviewStatus.P);
|
||||
r.setUploadPath(null);
|
||||
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
when(eventService.findEventReceiptByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of(r));
|
||||
when(dateTimeFormatterUtil.format(org.mockito.ArgumentMatchers.any(java.time.LocalDateTime.class))).thenReturn("formatted");
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(member());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getLuckyDrawHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).hasSize(1);
|
||||
assertThat(res.getBody().get(0).get("receiptUrls")).isEqualTo(List.of());
|
||||
assertThat(res.getBody().get(0)).containsEntry("ticketCount", 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.OrderEnum;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.EventRedeemCode;
|
||||
import com.solvway.core.model.StockistCmsProfile;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.NumberFormatterUtil;
|
||||
import com.solvway.core.utils.QrScanUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.DriveService;
|
||||
import com.solvway.mobile.api.service.EventService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.StockistCmsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EventControllerRedeemCodeHistoryTest {
|
||||
|
||||
@Mock private EventService eventService;
|
||||
@Mock private DriveService driveService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private NumberFormatterUtil numberFormatterUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private QrScanUtil qrScanUtil;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
@Mock private MemberService memberService;
|
||||
|
||||
@InjectMocks private EventController controller;
|
||||
|
||||
private static final long MEMBER_UUID = 12345L;
|
||||
|
||||
private StockistCmsProfile profile(String name) {
|
||||
StockistCmsProfile p = new StockistCmsProfile();
|
||||
p.setStockistName(name);
|
||||
return p;
|
||||
}
|
||||
|
||||
private Event event(long uuid, String name) {
|
||||
Event e = new Event();
|
||||
e.setUuid(uuid);
|
||||
e.setName(name);
|
||||
return e;
|
||||
}
|
||||
|
||||
private EventRedeemCode redeemCode(long uuid, long eventUuid, long memberUuid, long stockistUuid,
|
||||
OrderEnum.EventRedeemCodeStatus status,
|
||||
LocalDateTime expiry, LocalDateTime redeemedDateTime,
|
||||
LocalDateTime createDateTime) {
|
||||
EventRedeemCode c = new EventRedeemCode();
|
||||
c.setUuid(uuid);
|
||||
c.setEventUuid(eventUuid);
|
||||
c.setMemberUuid(memberUuid);
|
||||
c.setStockistUuid(stockistUuid);
|
||||
c.setRedeemStatus(status);
|
||||
c.setExpiryDateTime(expiry);
|
||||
c.setRedeemedDateTime(redeemedDateTime);
|
||||
c.setCreateDateTime(createDateTime);
|
||||
c.setRedeemCode("REDEEM-" + uuid);
|
||||
return c;
|
||||
}
|
||||
|
||||
// ---------- Test 1: unresolved member ("" uuid) -> 401 ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_unresolvedMember_returns401() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn("");
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodeHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED);
|
||||
verify(eventService, never()).findEventRedeemCodeByMemberUuid(anyLong());
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Test 2: returns only redeemed or expired codes ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_filtersToRedeemedOrExpired() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
// R code (redeemed) — should be included
|
||||
EventRedeemCode redeemed = redeemCode(1L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.R, now.plusDays(1), now, now.minusDays(2));
|
||||
// Y code expired yesterday — should be included
|
||||
EventRedeemCode expired = redeemCode(2L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.Y, now.minusDays(1), null, now.minusDays(1));
|
||||
// Y code expiring tomorrow — should be excluded
|
||||
EventRedeemCode valid = redeemCode(3L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.Y, now.plusDays(1), null, now);
|
||||
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(profile("Acme")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findEventRedeemCodeByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(redeemed, expired, valid));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodeHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
List<Map<String, Object>> body = res.getBody();
|
||||
assertThat(body).hasSize(2);
|
||||
// The tomorrow code is absent
|
||||
assertThat(body).extracting("uuid").containsOnly(1L, 2L);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Test 3: newest first by createDateTime ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_sortedByCreateDateTimeDesc() {
|
||||
LocalDateTime older = LocalDateTime.now().minusDays(3);
|
||||
LocalDateTime newer = LocalDateTime.now().minusDays(1);
|
||||
|
||||
EventRedeemCode oldCode = redeemCode(1L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.R, null, LocalDateTime.now(), older);
|
||||
EventRedeemCode newCode = redeemCode(2L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.R, null, LocalDateTime.now(), newer);
|
||||
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(profile("Acme")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findEventRedeemCodeByMemberUuid(MEMBER_UUID))
|
||||
.thenReturn(List.of(oldCode, newCode));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodeHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
List<Map<String, Object>> body = res.getBody();
|
||||
assertThat(body).hasSize(2);
|
||||
assertThat(body.get(0)).containsEntry("uuid", 2L);
|
||||
assertThat(body.get(1)).containsEntry("uuid", 1L);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Test 4: rows carry stockistName and eventName, no qrText ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_includesStockistNameAndEventNameWithoutQrText() throws Exception {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
EventRedeemCode code = redeemCode(1L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.R, now.minusDays(1), now, now.minusDays(2));
|
||||
|
||||
when(eventService.findEventRedeemCodeByMemberUuid(MEMBER_UUID)).thenReturn(List.of(code));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(profile("Acme Stockist")));
|
||||
when(eventService.findEventByUuid(100L)).thenReturn(Optional.of(event(100L, "Summer Fest 2026")));
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodeHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
Map<String, Object> row = res.getBody().get(0);
|
||||
assertThat(row).containsEntry("stockistName", "Acme Stockist");
|
||||
assertThat(row).containsEntry("eventName", "Summer Fest 2026");
|
||||
assertThat(row).doesNotContainKey("qrText");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Test 5: same stockist and event -> looked up once each ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_cachesStockistAndEventLookups() throws Exception {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
EventRedeemCode code1 = redeemCode(1L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.R, now.minusDays(1), now, now.minusDays(2));
|
||||
EventRedeemCode code2 = redeemCode(2L, 100L, MEMBER_UUID, 300L,
|
||||
OrderEnum.EventRedeemCodeStatus.Y, now.minusDays(2), null, now.minusDays(3));
|
||||
|
||||
when(eventService.findEventRedeemCodeByMemberUuid(MEMBER_UUID)).thenReturn(List.of(code1, code2));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(profile("Acme Stockist")));
|
||||
when(eventService.findEventByUuid(100L)).thenReturn(Optional.of(event(100L, "Summer Fest 2026")));
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodeHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
verify(stockistCmsService, times(1)).findByStockistUuid("300");
|
||||
verify(eventService, times(1)).findEventByUuid(100L);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Test 6: empty list from service -> 200 with empty body ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_emptyList_returns200WithEmptyBody() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findEventRedeemCodeByMemberUuid(MEMBER_UUID)).thenReturn(List.of());
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodeHistory();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- Test 7: never calls findCurrentEvent ----------
|
||||
|
||||
@Test
|
||||
void getRedeemCodeHistory_neverCallsFindCurrentEvent() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn(String.valueOf(MEMBER_UUID));
|
||||
when(eventService.findEventRedeemCodeByMemberUuid(MEMBER_UUID)).thenReturn(List.of());
|
||||
|
||||
controller.getRedeemCodeHistory();
|
||||
|
||||
verify(eventService, never()).findCurrentEvent();
|
||||
}
|
||||
}
|
||||
}
|
||||
+360
@@ -0,0 +1,360 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.OrderEnum;
|
||||
import com.solvway.core.enums.PaymentEnum;
|
||||
import com.solvway.core.model.Event;
|
||||
import com.solvway.core.model.EventRedeemCode;
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.model.StockistCmsProfile;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.NumberFormatterUtil;
|
||||
import com.solvway.core.utils.QrScanUtil;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.DriveService;
|
||||
import com.solvway.mobile.api.service.EventService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.StockistCmsService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentMatchers;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EventControllerRedeemCodeTest {
|
||||
|
||||
@Mock private EventService eventService;
|
||||
@Mock private DriveService driveService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private NumberFormatterUtil numberFormatterUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private QrScanUtil qrScanUtil;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
@Mock private MemberService memberService;
|
||||
|
||||
@InjectMocks private EventController controller;
|
||||
|
||||
private Event event() {
|
||||
Event e = new Event();
|
||||
e.setUuid(100L);
|
||||
return e;
|
||||
}
|
||||
|
||||
private Member member() {
|
||||
Member m = new Member();
|
||||
m.setUuid("200");
|
||||
return m;
|
||||
}
|
||||
|
||||
private EventRedeemCode redeemCode(long uuid, long eventUuid, long memberUuid, long stockistUuid,
|
||||
OrderEnum.EventRedeemCodeStatus status,
|
||||
LocalDateTime expiry, LocalDateTime createDateTime) {
|
||||
EventRedeemCode c = new EventRedeemCode();
|
||||
c.setUuid(uuid);
|
||||
c.setEventUuid(eventUuid);
|
||||
c.setMemberUuid(memberUuid);
|
||||
c.setStockistUuid(stockistUuid);
|
||||
c.setRedeemStatus(status);
|
||||
c.setExpiryDateTime(expiry);
|
||||
c.setCreateDateTime(createDateTime);
|
||||
c.setRedeemCode("REDEEM-" + uuid);
|
||||
return c;
|
||||
}
|
||||
|
||||
private void stubAuthenticatedMember() {
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(member());
|
||||
}
|
||||
|
||||
private StockistCmsProfile stockistProfile(String name) {
|
||||
StockistCmsProfile p = new StockistCmsProfile();
|
||||
p.setStockistUuid(BigInteger.valueOf(300L));
|
||||
p.setStockistName(name);
|
||||
return p;
|
||||
}
|
||||
|
||||
// ---------- GET /api/event/redeemCodes ----------
|
||||
|
||||
@Test
|
||||
void listReturnsNonExpiredCodesNewestFirstWithStockistName() throws Exception {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode older = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now().minusHours(2));
|
||||
EventRedeemCode newer = redeemCode(2L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.R,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now().minusHours(1));
|
||||
EventRedeemCode expired = redeemCode(3L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().minusHours(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByEventUuidAndMemberUuid(100L, 200L))
|
||||
.thenReturn(List.of(older, newer, expired));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(stockistProfile("Acme Stockist")));
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodes();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
List<Map<String, Object>> body = res.getBody();
|
||||
assertThat(body).hasSize(2);
|
||||
assertThat(body.get(0)).containsEntry("uuid", 2L);
|
||||
assertThat(body.get(0)).containsEntry("redeemStatus", "R");
|
||||
assertThat(body.get(0)).containsEntry("stockistName", "Acme Stockist");
|
||||
assertThat(body.get(1)).containsEntry("uuid", 1L);
|
||||
assertThat(body.get(1)).containsEntry("redeemStatus", "Y");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void listReturns404WhenNoCurrentEvent() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.empty());
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodes();
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listReturnsEmptyListWhenNoCodes() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
when(eventService.findEventRedeemCodeByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of());
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodes();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).isEmpty();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void listOmitsStockistNameWhenLookupFails() throws Exception {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByEventUuidAndMemberUuid(100L, 200L)).thenReturn(List.of(code));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.empty());
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> res = controller.getRedeemCodes();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody().get(0)).doesNotContainKey("stockistName");
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- GET /api/event/redeemCode/{uuid} ----------
|
||||
|
||||
@Test
|
||||
void detailIncludesQrTextWhenActiveAndNotExpired() throws Exception {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(stockistProfile("Acme Stockist")));
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
when(authenticationService.encrypt("REDEEM-1")).thenReturn("encrypted-1");
|
||||
when(qrScanUtil.generateQrText("encrypted-1", PaymentEnum.QrScanCodeAction.RC)).thenReturn("RC_encrypted-1");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("uuid", 1L);
|
||||
assertThat(res.getBody()).containsEntry("stockistName", "Acme Stockist");
|
||||
assertThat(res.getBody()).containsEntry("redeemStatus", "Y");
|
||||
assertThat(res.getBody()).containsEntry("qrText", "RC_encrypted-1");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailOmitsQrTextWhenRedeemed() throws Exception {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.R,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(stockistProfile("Acme Stockist")));
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("redeemStatus", "R");
|
||||
assertThat(res.getBody()).doesNotContainKey("qrText");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailOmitsQrTextWhenExpired() throws Exception {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().minusHours(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
when(stockistCmsService.findByStockistUuid("300")).thenReturn(Optional.of(stockistProfile("Acme Stockist")));
|
||||
when(dateTimeFormatterUtil.format(ArgumentMatchers.any(LocalDateTime.class))).thenReturn("formatted");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).doesNotContainKey("qrText");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailReturns404WhenCodeNotFound() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.empty());
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailReturns404WhenNotOwnedByMember() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 999L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailReturns404WhenNotBelongingToCurrentEvent() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 999L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailReturns404WhenNoCurrentEvent() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.empty());
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCode(1L);
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
|
||||
// ---------- GET /api/event/redeemCode/{uuid}/status ----------
|
||||
|
||||
@Test
|
||||
void statusReturnsTrueWhenRedeemed() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.R,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCodeStatus(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("redeemed", true);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusReturnsFalseWhenActive() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 200L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCodeStatus(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("redeemed", false);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusReturns404WhenNotFound() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.empty());
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCodeStatus(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusReturns404WhenNotOwnedByMember() {
|
||||
when(eventService.findCurrentEvent()).thenReturn(Optional.of(event()));
|
||||
EventRedeemCode code = redeemCode(1L, 100L, 999L, 300L, OrderEnum.EventRedeemCodeStatus.Y,
|
||||
LocalDateTime.now().plusDays(1), LocalDateTime.now());
|
||||
when(eventService.findEventRedeemCodeByUuid(1L)).thenReturn(Optional.of(code));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getRedeemCodeStatus(1L);
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.NOT_FOUND);
|
||||
}
|
||||
}
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
/**
|
||||
* Unit tests for the registration helper logic: canonical phone normalization
|
||||
* (duplicate-detection consistency) and failure-code → message mapping.
|
||||
*/
|
||||
class MemberControllerHelperTest {
|
||||
|
||||
@Test
|
||||
void canonicalLocalPhoneNo_stripsLeading60ThenZero() {
|
||||
assertThat(MemberController.canonicalLocalPhoneNo("123456789")).isEqualTo("123456789");
|
||||
assertThat(MemberController.canonicalLocalPhoneNo("0123456789")).isEqualTo("123456789");
|
||||
assertThat(MemberController.canonicalLocalPhoneNo("60123456789")).isEqualTo("123456789");
|
||||
}
|
||||
|
||||
@Test
|
||||
void canonicalLocalPhoneNo_nullSafe() {
|
||||
assertThat(MemberController.canonicalLocalPhoneNo(null)).isNull();
|
||||
}
|
||||
|
||||
@Test
|
||||
void friendlyRegistrationMessage_mapsKnownCodes() {
|
||||
assertThat(MemberController.friendlyRegistrationMessage("DUPLICATE_USERNAME_ERROR"))
|
||||
.isEqualTo("This phone number is already registered. ");
|
||||
assertThat(MemberController.friendlyRegistrationMessage("NAME_ONLY_ALPHA"))
|
||||
.isEqualTo("Name contains invalid characters. ");
|
||||
assertThat(MemberController.friendlyRegistrationMessage("PHONE_NUMBER_ONLY_NUMERIC"))
|
||||
.isEqualTo("Phone number must contain digits only. ");
|
||||
}
|
||||
|
||||
@Test
|
||||
void friendlyRegistrationMessage_unknownOrNull_fallsBackToGeneric() {
|
||||
assertThat(MemberController.friendlyRegistrationMessage("SOMETHING_UNMAPPED"))
|
||||
.isEqualTo("Registration failed. ");
|
||||
assertThat(MemberController.friendlyRegistrationMessage(null))
|
||||
.isEqualTo("Registration failed. ");
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.model.OneTimePassword;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyBoolean;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberControllerOtpTest {
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private UserService userService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private GeoLocationHierarchyService geoLocationHierarchyService;
|
||||
@Mock private LocationHierarchyService locationHierarchyService;
|
||||
@Mock private OneTimePasswordService oneTimePasswordService;
|
||||
@Mock private SystemService systemService;
|
||||
@Mock private ValidateUtil validateUtil;
|
||||
|
||||
@InjectMocks private MemberController controller;
|
||||
|
||||
private OneTimePassword otpWithCode() {
|
||||
OneTimePassword otp = new OneTimePassword();
|
||||
otp.setCode("987654321");
|
||||
otp.setPassword("246810");
|
||||
otp.setIdentityRef("member-uuid");
|
||||
otp.setShortRef("SR1");
|
||||
return otp;
|
||||
}
|
||||
|
||||
private User unverifiedUser() {
|
||||
User user = new User();
|
||||
user.setPhoneVerified(GeneralEnum.FlagYesNo.N);
|
||||
user.setEmailVerified(GeneralEnum.FlagYesNo.N);
|
||||
return user;
|
||||
}
|
||||
|
||||
private Member member() {
|
||||
Member member = new Member();
|
||||
member.setUuid("member-uuid");
|
||||
return member;
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void otpRequiredResponseExposesCodeReferenceButNotPasscode() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getUsernameFromToken("tok")).thenReturn("alice");
|
||||
when(userService.findByUsername("alice")).thenReturn(unverifiedUser());
|
||||
when(memberService.findByUsername("alice")).thenReturn(member());
|
||||
when(oneTimePasswordService.getOneTimePasswordByMember(any(), anyBoolean())).thenReturn(otpWithCode());
|
||||
when(validateUtil.maskPhoneNo(any())).thenReturn("***1234");
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getOtpRequired();
|
||||
|
||||
Map<String, Object> otpBean = (Map<String, Object>) response.getBody().get("otpBean");
|
||||
assertThat(otpBean).containsEntry("code", "987654321");
|
||||
assertThat(otpBean).containsEntry("identityRef", "member-uuid");
|
||||
assertThat(otpBean).containsEntry("shortRef", "SR1");
|
||||
assertThat(otpBean).doesNotContainKeys("password", "passwordPlain");
|
||||
assertThat(otpBean.toString()).doesNotContain("246810");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@SuppressWarnings("unchecked")
|
||||
void otpRequiredResponseStillExposesNonSecretReferences() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getUsernameFromToken("tok")).thenReturn("alice");
|
||||
when(userService.findByUsername("alice")).thenReturn(unverifiedUser());
|
||||
when(memberService.findByUsername("alice")).thenReturn(member());
|
||||
when(oneTimePasswordService.getOneTimePasswordByMember(any(), anyBoolean())).thenReturn(otpWithCode());
|
||||
when(validateUtil.maskPhoneNo(any())).thenReturn("***1234");
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getOtpRequired();
|
||||
|
||||
Map<String, Object> otpBean = (Map<String, Object>) response.getBody().get("otpBean");
|
||||
assertThat(otpBean).containsEntry("maskedPhone", "***1234");
|
||||
assertThat(otpBean).containsEntry("shortRef", "SR1");
|
||||
}
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.enums.MemberEnum;
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
import org.json.simple.JSONObject;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.time.Period;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberControllerProfileFlagTest {
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private UserService userService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private GeoLocationHierarchyService geoLocationHierarchyService;
|
||||
@Mock private LocationHierarchyService locationHierarchyService;
|
||||
@Mock private OneTimePasswordService oneTimePasswordService;
|
||||
@Mock private SystemService systemService;
|
||||
@Mock private ValidateUtil validateUtil;
|
||||
|
||||
@InjectMocks
|
||||
private MemberController controller;
|
||||
|
||||
@Test
|
||||
void getProfileIncludesEmrmProfileUpdateFlag() {
|
||||
Member m = new Member();
|
||||
m.setGender(MemberEnum.Gender.M);
|
||||
m.setEmrmProfileUpdate(GeneralEnum.FlagYesNo.N);
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(m);
|
||||
when(geoLocationHierarchyService.generateAddress(any(), any())).thenReturn("");
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getProfile();
|
||||
|
||||
assertThat(res.getBody()).containsEntry("emrmProfileUpdate", "N");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getProfileDefaultsFlagToNWhenUnset() {
|
||||
Member m = new Member();
|
||||
m.setGender(MemberEnum.Gender.M);
|
||||
// emrmProfileUpdate left null
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(m);
|
||||
when(geoLocationHierarchyService.generateAddress(any(), any())).thenReturn("");
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getProfile();
|
||||
|
||||
assertThat(res.getBody()).containsEntry("emrmProfileUpdate", "N");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void editProfileSetsEmrmProfileUpdateToYOnSave() {
|
||||
Member m = new Member();
|
||||
m.setPrefix("MY");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(memberService.findByMemberCode("M1")).thenReturn(m);
|
||||
when(validateUtil.periodBtwLocalDate(any(), any())).thenReturn(Period.ofYears(30));
|
||||
JSONObject geo = new JSONObject();
|
||||
geo.put("valid", true);
|
||||
when(geoLocationHierarchyService.validateGeoLocationById(any())).thenReturn(geo);
|
||||
when(locationHierarchyService.findByCode(any())).thenReturn(null);
|
||||
|
||||
Map<String, String> body = new HashMap<>();
|
||||
body.put("name", "Jane");
|
||||
body.put("surname", "Doe");
|
||||
body.put("email", "jane@example.com");
|
||||
body.put("dob", "1990-01-01");
|
||||
body.put("gender", "M");
|
||||
body.put("addressLocation", "loc1");
|
||||
body.put("addressDetails", "1 Main St");
|
||||
body.put("postCode", "");
|
||||
|
||||
controller.editProfile(body);
|
||||
|
||||
ArgumentCaptor<Member> saved = ArgumentCaptor.forClass(Member.class);
|
||||
verify(memberService).save(saved.capture());
|
||||
assertThat(saved.getValue().getEmrmProfileUpdate()).isEqualTo(GeneralEnum.FlagYesNo.Y);
|
||||
}
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberControllerReferralTest {
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private UserService userService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private GeoLocationHierarchyService geoLocationHierarchyService;
|
||||
@Mock private LocationHierarchyService locationHierarchyService;
|
||||
@Mock private OneTimePasswordService oneTimePasswordService;
|
||||
@Mock private SystemService systemService;
|
||||
@Mock private ValidateUtil validateUtil;
|
||||
@Mock private TastefullyPointService tastefullyPointService;
|
||||
|
||||
@InjectMocks
|
||||
private MemberController controller;
|
||||
|
||||
@Test
|
||||
void getReferralLinkReturnsAppRegisterUrl() {
|
||||
ReflectionTestUtils.setField(controller, "customerPortalBaseUrl", "https://app.example.com");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
|
||||
ResponseEntity<String> res = controller.getReferralLink();
|
||||
|
||||
assertThat(res.getStatusCode().is2xxSuccessful()).isTrue();
|
||||
assertThat(res.getBody()).isEqualTo("https://app.example.com/register?ref=M1");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getReferralLinkReturnsNotFoundWhenMemberCodeBlank() {
|
||||
ReflectionTestUtils.setField(controller, "customerPortalBaseUrl", "https://app.example.com");
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("");
|
||||
|
||||
ResponseEntity<String> res = controller.getReferralLink();
|
||||
|
||||
assertThat(res.getStatusCode().is4xxClientError()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getReferralStatsReturnsJoinedAndEarnedWhenBothSubCallsSucceed() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn("UUID1");
|
||||
when(memberService.countReferralsBySponsor("M1")).thenReturn(4);
|
||||
when(tastefullyPointService.sumReferralEarned("UUID1")).thenReturn(150.0d);
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getReferralStats();
|
||||
|
||||
assertThat(res.getStatusCode().is2xxSuccessful()).isTrue();
|
||||
assertThat(res.getBody()).containsEntry("joined", 4L).containsEntry("earned", 150.0d);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void getReferralStatsDegradesGracefullyWhenJoinedLookupThrows() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M1");
|
||||
when(authenticationService.getMemberUuidFromToken("tok")).thenReturn("UUID1");
|
||||
when(memberService.countReferralsBySponsor("M1")).thenThrow(new RuntimeException("boom"));
|
||||
when(tastefullyPointService.sumReferralEarned("UUID1")).thenReturn(150.0d);
|
||||
|
||||
ResponseEntity<Map<String, Object>> res = controller.getReferralStats();
|
||||
|
||||
assertThat(res.getStatusCode().is2xxSuccessful()).isTrue();
|
||||
assertThat(res.getBody()).containsEntry("joined", 0L).containsEntry("earned", 150.0d);
|
||||
}
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.utils.DateTimeFormatterUtil;
|
||||
import com.solvway.core.utils.ValidateUtil;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
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 java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberControllerSponsorValidationTest {
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private UserService userService;
|
||||
@Mock private DateTimeFormatterUtil dateTimeFormatterUtil;
|
||||
@Mock private GeoLocationHierarchyService geoLocationHierarchyService;
|
||||
@Mock private LocationHierarchyService locationHierarchyService;
|
||||
@Mock private OneTimePasswordService oneTimePasswordService;
|
||||
@Mock private SystemService systemService;
|
||||
@Mock private ValidateUtil validateUtil;
|
||||
@Mock private TastefullyPointService tastefullyPointService;
|
||||
|
||||
@InjectMocks
|
||||
private MemberController controller;
|
||||
|
||||
@Test
|
||||
void validSponsorReturnsSponsorId() {
|
||||
when(memberService.existsActiveByMemberCode("M1")).thenReturn(true);
|
||||
Map<String, String> response = new HashMap<>();
|
||||
|
||||
String result = controller.validateAndNormalizeSponsorId("M1", response);
|
||||
|
||||
assertThat(result).isEqualTo("M1");
|
||||
assertThat(response).doesNotContainKey("errorMessage");
|
||||
}
|
||||
|
||||
@Test
|
||||
void unknownOrInactiveSponsorReturnsNullWithError() {
|
||||
when(memberService.existsActiveByMemberCode("M1")).thenReturn(false);
|
||||
Map<String, String> response = new HashMap<>();
|
||||
|
||||
String result = controller.validateAndNormalizeSponsorId("M1", response);
|
||||
|
||||
assertThat(result).isNull();
|
||||
assertThat(response).containsEntry("result", "false");
|
||||
assertThat(response).containsEntry("errorMessage", "Invalid sponsor code. ");
|
||||
}
|
||||
|
||||
@Test
|
||||
void blankSponsorReturnsDefaultCodeWithoutLookup() {
|
||||
Map<String, String> response = new HashMap<>();
|
||||
|
||||
String result = controller.validateAndNormalizeSponsorId("", response);
|
||||
|
||||
assertThat(result).isEqualTo("00000000");
|
||||
assertThat(response).isEmpty();
|
||||
verifyNoInteractions(memberService);
|
||||
}
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.mobile.api.model.AppBanner;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
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.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PublicContentControllerBannerTest {
|
||||
|
||||
@Mock private BulletinService bulletinService;
|
||||
@Mock private AppBannerService appBannerService;
|
||||
@Mock private EventScheduleService eventScheduleService;
|
||||
@Mock private ArticleService articleService;
|
||||
@Mock private AlbumService albumService;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
@Mock private HelpCenterService helpCenterService;
|
||||
@Mock private SystemService systemService;
|
||||
|
||||
@InjectMocks
|
||||
private PublicContentController controller;
|
||||
|
||||
@Test
|
||||
void getBannersReturnsActiveBanners() {
|
||||
when(appBannerService.findActive())
|
||||
.thenReturn(List.of(new AppBanner(1L, "Grand sale", "/store", "PROMO", 0)));
|
||||
|
||||
ResponseEntity<List<AppBanner>> res = controller.getBanners();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).extracting(AppBanner::getMessage).containsExactly("Grand sale");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getBannersReturnsEmptyWhenNoneActive() {
|
||||
when(appBannerService.findActive()).thenReturn(List.of());
|
||||
|
||||
ResponseEntity<List<AppBanner>> res = controller.getBanners();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).isEmpty();
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.mobile.api.dto.HelpCenterContentResponse;
|
||||
import com.solvway.mobile.api.dto.HelpCenterNode;
|
||||
import com.solvway.mobile.api.dto.HelpCenterTreeResponse;
|
||||
import com.solvway.mobile.api.service.AlbumService;
|
||||
import com.solvway.mobile.api.service.AppBannerService;
|
||||
import com.solvway.mobile.api.service.AppPromoService;
|
||||
import com.solvway.mobile.api.service.ArticleService;
|
||||
import com.solvway.mobile.api.service.BulletinService;
|
||||
import com.solvway.mobile.api.service.EventScheduleService;
|
||||
import com.solvway.mobile.api.service.HelpCenterService;
|
||||
import com.solvway.mobile.api.service.StockistCmsService;
|
||||
import com.solvway.mobile.api.service.SystemService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
@WebMvcTest(controllers = PublicContentController.class)
|
||||
class PublicContentControllerHelpCenterTest {
|
||||
|
||||
@Autowired MockMvc mockMvc;
|
||||
|
||||
@MockBean HelpCenterService helpCenterService;
|
||||
@MockBean BulletinService bulletinService;
|
||||
@MockBean AppBannerService appBannerService;
|
||||
@MockBean AppPromoService appPromoService;
|
||||
@MockBean EventScheduleService eventScheduleService;
|
||||
@MockBean ArticleService articleService;
|
||||
@MockBean AlbumService albumService;
|
||||
@MockBean StockistCmsService stockistCmsService;
|
||||
@MockBean SystemService systemService;
|
||||
|
||||
@Test
|
||||
void getHelpCenterTree_returns200WithCategories() throws Exception {
|
||||
HelpCenterNode n = new HelpCenterNode(
|
||||
BigInteger.valueOf(10), BigInteger.valueOf(1), "Account", 1, List.of());
|
||||
when(helpCenterService.getTree(eq("en_US")))
|
||||
.thenReturn(new HelpCenterTreeResponse("en_US", List.of(n)));
|
||||
|
||||
mockMvc.perform(get("/api/public/helpCenter").param("locale", "en_US"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.locale").value("en_US"))
|
||||
.andExpect(jsonPath("$.categories[0].label").value("Account"))
|
||||
.andExpect(jsonPath("$.categories[0].uuid").value(10))
|
||||
.andExpect(jsonPath("$.categories[0].sortIndex").value(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHelpCenterTree_defaultsLocaleToEnUs_whenOmitted() throws Exception {
|
||||
when(helpCenterService.getTree(eq("en_US")))
|
||||
.thenReturn(new HelpCenterTreeResponse("en_US", List.of()));
|
||||
|
||||
mockMvc.perform(get("/api/public/helpCenter"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.locale").value("en_US"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHelpCenterContent_returns200WhenContentPresent() throws Exception {
|
||||
when(helpCenterService.getLeafContent(eq(BigInteger.valueOf(42)), eq("en_US")))
|
||||
.thenReturn(Optional.of(new HelpCenterContentResponse(
|
||||
BigInteger.valueOf(42), "en_US", null, "<p>Hi</p>")));
|
||||
|
||||
mockMvc.perform(get("/api/public/helpCenter/42/content").param("locale", "en_US"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.content").value("<p>Hi</p>"))
|
||||
.andExpect(jsonPath("$.redirectUrl").value(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHelpCenterContent_returns200WhenRedirectPresent() throws Exception {
|
||||
when(helpCenterService.getLeafContent(eq(BigInteger.valueOf(42)), eq("en_US")))
|
||||
.thenReturn(Optional.of(new HelpCenterContentResponse(
|
||||
BigInteger.valueOf(42), "en_US", "https://example.com", null)));
|
||||
|
||||
mockMvc.perform(get("/api/public/helpCenter/42/content").param("locale", "en_US"))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.redirectUrl").value("https://example.com"))
|
||||
.andExpect(jsonPath("$.content").value(nullValue()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getHelpCenterContent_returns404WhenServiceReturnsEmpty() throws Exception {
|
||||
when(helpCenterService.getLeafContent(any(), any())).thenReturn(Optional.empty());
|
||||
|
||||
mockMvc.perform(get("/api/public/helpCenter/42/content"))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.mobile.api.service.*;
|
||||
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.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PublicContentControllerMessagesTest {
|
||||
|
||||
@Mock private BulletinService bulletinService;
|
||||
@Mock private EventScheduleService eventScheduleService;
|
||||
@Mock private ArticleService articleService;
|
||||
@Mock private AlbumService albumService;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
@Mock private HelpCenterService helpCenterService;
|
||||
@Mock private SystemService systemService;
|
||||
|
||||
@InjectMocks
|
||||
private PublicContentController controller;
|
||||
|
||||
@Test
|
||||
void getMessagesReturnsCatalogForLocale() {
|
||||
when(systemService.findMessageCatalog("A", "en_US"))
|
||||
.thenReturn(Map.of("FirstName", "First Name"));
|
||||
|
||||
ResponseEntity<Map<String, String>> res = controller.getMessages("en_US");
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).containsEntry("FirstName", "First Name");
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.mobile.api.model.AppPromo;
|
||||
import com.solvway.mobile.api.service.*;
|
||||
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.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PublicContentControllerPromoTest {
|
||||
|
||||
@Mock private BulletinService bulletinService;
|
||||
@Mock private AppBannerService appBannerService;
|
||||
@Mock private AppPromoService appPromoService;
|
||||
@Mock private EventScheduleService eventScheduleService;
|
||||
@Mock private ArticleService articleService;
|
||||
@Mock private AlbumService albumService;
|
||||
@Mock private StockistCmsService stockistCmsService;
|
||||
@Mock private HelpCenterService helpCenterService;
|
||||
@Mock private SystemService systemService;
|
||||
|
||||
@InjectMocks
|
||||
private PublicContentController controller;
|
||||
|
||||
@Test
|
||||
void getPromosReturnsActivePromos() {
|
||||
when(appPromoService.findActive())
|
||||
.thenReturn(List.of(new AppPromo(1L, "IMAGE", "https://cdn/app-promo/a.jpg", "/store",
|
||||
"Grand sale", "Grand sale banner", null, null, true, 0)));
|
||||
|
||||
ResponseEntity<List<AppPromo>> res = controller.getPromos();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).extracting(AppPromo::getCaption).containsExactly("Grand sale");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getPromosReturnsEmptyWhenNoneActive() {
|
||||
when(appPromoService.findActive()).thenReturn(List.of());
|
||||
|
||||
ResponseEntity<List<AppPromo>> res = controller.getPromos();
|
||||
|
||||
assertThat(res.getStatusCode()).isEqualTo(HttpStatus.OK);
|
||||
assertThat(res.getBody()).isEmpty();
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.model.Email;
|
||||
import com.solvway.mobile.api.model.form.ContactUsRequest;
|
||||
import com.solvway.mobile.api.service.EmailService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PublicFormControllerEscapingTest {
|
||||
|
||||
@Mock private EmailService emailService;
|
||||
|
||||
@InjectMocks private PublicFormController controller;
|
||||
|
||||
@Test
|
||||
void contactUsEscapesHtmlInUserSuppliedFields() {
|
||||
when(emailService.send(any())).thenReturn(Optional.of(new Email()));
|
||||
|
||||
ContactUsRequest request = new ContactUsRequest();
|
||||
request.setName("<script>alert(1)</script>");
|
||||
request.setEmail("attacker@example.com");
|
||||
request.setMessage("<img src=x onerror=alert(2)>");
|
||||
|
||||
controller.contactUs(request);
|
||||
|
||||
ArgumentCaptor<Email> captor = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emailService).send(captor.capture());
|
||||
String body = captor.getValue().getBody();
|
||||
|
||||
assertThat(body).doesNotContain("<script>");
|
||||
assertThat(body).doesNotContain("<img src=x");
|
||||
assertThat(body).contains("<script>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void contactUsEscapesHtmlInTheSubjectLine() {
|
||||
when(emailService.send(any())).thenReturn(Optional.of(new Email()));
|
||||
|
||||
ContactUsRequest request = new ContactUsRequest();
|
||||
request.setName("<b>bold</b>");
|
||||
request.setEmail("user@example.com");
|
||||
request.setMessage("hello");
|
||||
|
||||
controller.contactUs(request);
|
||||
|
||||
ArgumentCaptor<Email> captor = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emailService).send(captor.capture());
|
||||
|
||||
assertThat(captor.getValue().getSubject()).doesNotContain("<b>");
|
||||
}
|
||||
|
||||
@Test
|
||||
void contactUsStillDeliversTheLegibleMessageText() {
|
||||
when(emailService.send(any())).thenReturn(Optional.of(new Email()));
|
||||
|
||||
ContactUsRequest request = new ContactUsRequest();
|
||||
request.setName("Alice");
|
||||
request.setEmail("alice@example.com");
|
||||
request.setMessage("Please call me");
|
||||
|
||||
controller.contactUs(request);
|
||||
|
||||
ArgumentCaptor<Email> captor = ArgumentCaptor.forClass(Email.class);
|
||||
verify(emailService).send(captor.capture());
|
||||
String body = captor.getValue().getBody();
|
||||
|
||||
assertThat(body).contains("Alice");
|
||||
assertThat(body).contains("Please call me");
|
||||
}
|
||||
}
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
package com.solvway.mobile.api.controller;
|
||||
|
||||
import com.solvway.core.model.Member;
|
||||
import com.solvway.core.model.MemberVoucher;
|
||||
import com.solvway.core.model.MemberVoucherEligibility;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.mobile.api.service.MemberVoucherService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* Ownership always comes from the token, never the request. Ineligible vouchers are still
|
||||
* returned, carrying a reason, so the member sees why rather than an empty list.
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class VoucherControllerTest {
|
||||
|
||||
@Mock private MemberVoucherService memberVoucherService;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private MemberService memberService;
|
||||
|
||||
@InjectMocks private VoucherController controller;
|
||||
|
||||
/** Token -> memberCode -> Member, exactly as EventControllerRedeemCodeTest does it. */
|
||||
private void stubAuthenticatedMember() {
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn("M001");
|
||||
when(memberService.findByMemberCode("M001")).thenReturn(member());
|
||||
}
|
||||
|
||||
private static MemberVoucherEligibility eligibility(long uuid, boolean redeemable, String reason) {
|
||||
return eligibility(uuid, redeemable, reason, null);
|
||||
}
|
||||
|
||||
private static MemberVoucherEligibility eligibility(long uuid, boolean redeemable, String reason, String uploadPath) {
|
||||
MemberVoucher v = new MemberVoucher();
|
||||
v.setUuid(uuid);
|
||||
v.setName("New First-Time User");
|
||||
v.setCurrencySymbol("RM");
|
||||
v.setAmount(10d);
|
||||
v.setUploadPath(uploadPath);
|
||||
MemberVoucherEligibility e = new MemberVoucherEligibility();
|
||||
e.setVoucher(v);
|
||||
e.setRedeemable(redeemable);
|
||||
e.setReason(reason);
|
||||
return e;
|
||||
}
|
||||
|
||||
private static Member member() {
|
||||
Member m = new Member();
|
||||
m.setUuid("900");
|
||||
m.setMemberCode("M001");
|
||||
m.setEmrmProfileUpdate(GeneralEnum.FlagYesNo.Y);
|
||||
return m;
|
||||
}
|
||||
|
||||
@Test
|
||||
void listReturnsEveryVoucherWithItsRedeemableFlagAndReason() {
|
||||
when(memberVoucherService.findEligibility(900L, true)).thenReturn(List.of(
|
||||
eligibility(1L, true, null),
|
||||
eligibility(2L, false, "ALREADY_REDEEMED")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> response = controller.getVouchers();
|
||||
|
||||
assertThat(response.getBody()).hasSize(2);
|
||||
assertThat(response.getBody().get(0)).containsEntry("redeemable", true);
|
||||
assertThat(response.getBody().get(0)).containsEntry("amount", 10d);
|
||||
assertThat(response.getBody().get(1)).containsEntry("reason", "ALREADY_REDEEMED");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void anUnauthenticatedRequestGetsNotFoundAndNeverQueriesVouchers() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
when(authenticationService.getMemberCodeFromToken("tok")).thenReturn(null);
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> response = controller.getVouchers();
|
||||
|
||||
assertThat(response.getStatusCode().is4xxClientError()).isTrue();
|
||||
assertThat(response.getBody()).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusReportsRedeemedWhenTheVoucherIsNoLongerRedeemableBecauseItWasRedeemed() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, false, "ALREADY_REDEEMED")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getVoucherStatus(1L);
|
||||
|
||||
assertThat(response.getBody()).containsEntry("redeemed", true);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusIsNotRedeemedWhileTheVoucherIsStillRedeemable() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, true, null)));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getVoucherStatus(1L);
|
||||
|
||||
assertThat(response.getBody()).containsEntry("redeemed", false);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusReportsRedeemableTrueAndNoReasonWhileStillRedeemable() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, true, null)));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getVoucherStatus(1L);
|
||||
|
||||
assertThat(response.getBody()).containsEntry("redeemable", true);
|
||||
assertThat(response.getBody()).containsKey("reason");
|
||||
assertThat(response.getBody().get("reason")).isNull();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void statusReportsNotRedeemableWithReasonWhenExpired() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, false, "EXPIRED")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getVoucherStatus(1L);
|
||||
|
||||
assertThat(response.getBody()).containsEntry("redeemed", false);
|
||||
assertThat(response.getBody()).containsEntry("redeemable", false);
|
||||
assertThat(response.getBody()).containsEntry("reason", "EXPIRED");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVoucherThatIsNotTheMembersReturnsNotFound() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, true, null)));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getVoucher(999L);
|
||||
|
||||
assertThat(response.getStatusCode().is4xxClientError()).isTrue();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVoucherWithAnUploadPathReturnsItVerbatimAsImageUrl() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, true, null, "https://cdn.example.com/member-voucher/image.png")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> response = controller.getVouchers();
|
||||
|
||||
assertThat(response.getBody().get(0))
|
||||
.containsEntry("imageUrl", "https://cdn.example.com/member-voucher/image.png");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVoucherWithANullUploadPathReturnsNullImageUrl() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, true, null, null)));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> response = controller.getVouchers();
|
||||
|
||||
assertThat(response.getBody().get(0)).containsEntry("imageUrl", null);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aVoucherWithABlankUploadPathReturnsNullImageUrl() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(1L, true, null, " ")));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> response = controller.getVouchers();
|
||||
|
||||
assertThat(response.getBody().get(0)).containsEntry("imageUrl", null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Snowflake uuids are ~3e18, far past JavaScript's Number.MAX_SAFE_INTEGER (~9e15). Serialised
|
||||
* as a JSON number, the browser's JSON.parse silently rounds it, and the id the customer-portal
|
||||
* then puts in a URL is a voucher that does not exist. Emitting a string is what keeps the id
|
||||
* intact across the wire; the long @PathVariable parses it back without any change.
|
||||
*/
|
||||
private static final long SNOWFLAKE_UUID = 3271922645582381056L;
|
||||
|
||||
@Test
|
||||
void listEmitsTheVoucherUuidAsAStringSoLargeIdsSurviveJsonParse() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(SNOWFLAKE_UUID, true, null)));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<List<Map<String, Object>>> response = controller.getVouchers();
|
||||
|
||||
assertThat(response.getBody().get(0)).containsEntry("uuid", "3271922645582381056");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void detailEmitsTheVoucherUuidAsAStringSoLargeIdsSurviveJsonParse() {
|
||||
when(memberVoucherService.findEligibility(900L, true))
|
||||
.thenReturn(List.of(eligibility(SNOWFLAKE_UUID, true, null)));
|
||||
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("tok");
|
||||
stubAuthenticatedMember();
|
||||
|
||||
ResponseEntity<Map<String, Object>> response = controller.getVoucher(SNOWFLAKE_UUID);
|
||||
|
||||
assertThat(response.getBody()).containsEntry("uuid", "3271922645582381056");
|
||||
}
|
||||
}
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.model.AppBanner;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
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 org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AppBannerServiceTest {
|
||||
|
||||
@Mock
|
||||
private RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
private AppBannerService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new AppBannerService(restTemplateUtil);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findActiveReturnsBannerList() {
|
||||
AppBanner banner = new AppBanner(1L, "Grand sale", "/store", "PROMO", 0);
|
||||
when(restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_APP_BANNER_FIND_ACTIVE))
|
||||
.thenReturn("http://system/appBanner/findActive");
|
||||
when(restTemplateUtil.<List<AppBanner>>getForEntity(eq("http://system/appBanner/findActive"), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(ResponseEntity.ok(List.of(banner)));
|
||||
|
||||
List<AppBanner> result = service.findActive();
|
||||
|
||||
assertThat(result).extracting(AppBanner::getMessage).containsExactly("Grand sale");
|
||||
assertThat(result).extracting(AppBanner::getStyle).containsExactly("PROMO");
|
||||
}
|
||||
|
||||
@Test
|
||||
void findActiveReturnsEmptyOnNonOkResponse() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_APP_BANNER_FIND_ACTIVE))
|
||||
.thenReturn("http://system/appBanner/findActive");
|
||||
when(restTemplateUtil.<List<AppBanner>>getForEntity(any(String.class), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
|
||||
|
||||
List<AppBanner> result = service.findActive();
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.model.AppPromo;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
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 org.springframework.core.ParameterizedTypeReference;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AppPromoServiceTest {
|
||||
|
||||
@Mock
|
||||
private RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
private AppPromoService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new AppPromoService(restTemplateUtil);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findActiveReturnsPromoList() {
|
||||
AppPromo promo = new AppPromo(1L, "IMAGE", "https://cdn/app-promo/a.jpg", "/store", "Grand sale",
|
||||
"Grand sale banner", LocalDateTime.now().minusDays(1), LocalDateTime.now().plusDays(1), true, 0);
|
||||
when(restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_APP_PROMO_FIND_ACTIVE))
|
||||
.thenReturn("http://system/appPromo/findActive");
|
||||
when(restTemplateUtil.<List<AppPromo>>getForEntity(eq("http://system/appPromo/findActive"), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(ResponseEntity.ok(List.of(promo)));
|
||||
|
||||
List<AppPromo> result = service.findActive();
|
||||
|
||||
assertThat(result).extracting(AppPromo::getMediaUrl).containsExactly("https://cdn/app-promo/a.jpg");
|
||||
assertThat(result).extracting(AppPromo::getCaption).containsExactly("Grand sale");
|
||||
}
|
||||
|
||||
@Test
|
||||
void findActiveReturnsEmptyOnNonOkResponse() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_APP_PROMO_FIND_ACTIVE))
|
||||
.thenReturn("http://system/appPromo/findActive");
|
||||
when(restTemplateUtil.<List<AppPromo>>getForEntity(any(String.class), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
|
||||
|
||||
List<AppPromo> result = service.findActive();
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void findActiveReturnsEmptyOnNullBody() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiSystemServiceConstants.API_REST_APP_PROMO_FIND_ACTIVE))
|
||||
.thenReturn("http://system/appPromo/findActive");
|
||||
when(restTemplateUtil.<List<AppPromo>>getForEntity(any(String.class), any(ParameterizedTypeReference.class)))
|
||||
.thenReturn(ResponseEntity.ok(null));
|
||||
|
||||
List<AppPromo> result = service.findActive();
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
import com.solvway.mobile.api.util.redis.RedisUtil;
|
||||
import com.solvway.mobile.api.util.redis.TokenCacheKeyUtil;
|
||||
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 static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class AuthenticationServiceCacheKeyTest {
|
||||
|
||||
private static final String TOKEN = "eyJhbGciOiJIUzUxMiJ9.payload.signature";
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private RestTemplateCustomUtil restTemplateUtil;
|
||||
@Mock private RedisUtil<String> redisUtil;
|
||||
|
||||
@InjectMocks private AuthenticationService authenticationService;
|
||||
|
||||
@Test
|
||||
void usernameLookupUsesHashedTokenAsCacheKey() {
|
||||
String expectedKey = "mobile-api:auth:token-username:" + TokenCacheKeyUtil.hashToken(TOKEN);
|
||||
when(redisUtil.checkKeyExist(expectedKey)).thenReturn(true);
|
||||
when(redisUtil.getValue(expectedKey)).thenReturn("alice");
|
||||
|
||||
assertThat(authenticationService.getUsernameFromToken(TOKEN)).isEqualTo("alice");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cacheKeyNeverContainsTheRawToken() {
|
||||
String key = "mobile-api:auth:token-username:" + TokenCacheKeyUtil.hashToken(TOKEN);
|
||||
assertThat(key).doesNotContain(TOKEN);
|
||||
}
|
||||
|
||||
@Test
|
||||
void memberCodeLookupUsesHashedTokenAsCacheKey() {
|
||||
String expectedKey = "mobile-api:auth:token-member-code:" + TokenCacheKeyUtil.hashToken(TOKEN);
|
||||
when(redisUtil.checkKeyExist(expectedKey)).thenReturn(true);
|
||||
when(redisUtil.getValue(expectedKey)).thenReturn("M001");
|
||||
|
||||
assertThat(authenticationService.getMemberCodeFromToken(TOKEN)).isEqualTo("M001");
|
||||
}
|
||||
|
||||
@Test
|
||||
void memberUuidLookupUsesHashedTokenAsCacheKey() {
|
||||
String expectedKey = "mobile-api:auth:token-member-uuid:" + TokenCacheKeyUtil.hashToken(TOKEN);
|
||||
when(redisUtil.checkKeyExist(expectedKey)).thenReturn(true);
|
||||
when(redisUtil.getValue(expectedKey)).thenReturn("uuid-1");
|
||||
|
||||
assertThat(authenticationService.getMemberUuidFromToken(TOKEN)).isEqualTo("uuid-1");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.model.Email;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
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.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class EmailServiceTest {
|
||||
|
||||
@Mock
|
||||
private PubSubTemplate pubSubTemplate;
|
||||
|
||||
@Mock
|
||||
private PubSubUtil pubSubUtil;
|
||||
|
||||
@InjectMocks
|
||||
private EmailService emailService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ReflectionTestUtils.setField(emailService, "emailSaveRequestTopic", "email-save-request-topic");
|
||||
}
|
||||
|
||||
@Test
|
||||
void send_publishesEmailToSaveRequestTopicAndReturnsEmail() {
|
||||
Email email = new Email();
|
||||
email.setSubject("Test Subject");
|
||||
|
||||
Optional<Email> result = emailService.send(email);
|
||||
|
||||
assertTrue(result.isPresent());
|
||||
verify(pubSubUtil).publishMessageWithCustomObjectMapper(
|
||||
eq(pubSubTemplate), eq("email-save-request-topic"), eq(email));
|
||||
}
|
||||
|
||||
@Test
|
||||
void send_returnsEmptyWhenPublishThrows() {
|
||||
Email email = new Email();
|
||||
doThrow(new RuntimeException("publish failed"))
|
||||
.when(pubSubUtil).publishMessageWithCustomObjectMapper(any(), any(), any());
|
||||
|
||||
Optional<Email> result = emailService.send(email);
|
||||
|
||||
assertFalse(result.isPresent());
|
||||
}
|
||||
}
|
||||
+370
@@ -0,0 +1,370 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.core.enums.GeneralEnum;
|
||||
import com.solvway.core.model.GenericHierarchy;
|
||||
import com.solvway.core.model.GenericPostContent;
|
||||
import com.solvway.core.model.HelpCenterPost;
|
||||
import com.solvway.mobile.api.cache.MessageLabelCache;
|
||||
import com.solvway.mobile.api.constant.api.RestApiSystemServiceConstants;
|
||||
import com.solvway.mobile.api.dto.HelpCenterContentResponse;
|
||||
import com.solvway.mobile.api.dto.HelpCenterNode;
|
||||
import com.solvway.mobile.api.dto.HelpCenterTreeResponse;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
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.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import java.math.BigInteger;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class HelpCenterServiceTest {
|
||||
|
||||
@Mock
|
||||
RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
@Mock
|
||||
MessageLabelCache messageLabelCache;
|
||||
|
||||
@InjectMocks
|
||||
HelpCenterService helpCenterService;
|
||||
|
||||
private static final BigInteger UUID = BigInteger.valueOf(42);
|
||||
private static final String LOCALE = "en";
|
||||
|
||||
@Test
|
||||
void getLeafContent_returnsContent_whenLocalizedPostContentExists() {
|
||||
when(restTemplateUtil.getURLforApiService(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
HelpCenterPost post = new HelpCenterPost();
|
||||
post.setGenericPostUuid(BigInteger.valueOf(99));
|
||||
post.setRedirectUrl(null);
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_HELP_CENTER_POST_FIND_BY_HIERARCHY_UUID),
|
||||
eq(HelpCenterPost.class), eq(UUID)))
|
||||
.thenReturn(ResponseEntity.ok(post));
|
||||
|
||||
GenericPostContent content = new GenericPostContent();
|
||||
content.setContent("Some help content");
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_GENERIC_POST_CONTENT_FIND_BY_UUID_AND_LOCALE),
|
||||
eq(GenericPostContent.class), eq(BigInteger.valueOf(99)), eq(LOCALE)))
|
||||
.thenReturn(ResponseEntity.ok(content));
|
||||
|
||||
Optional<HelpCenterContentResponse> result = helpCenterService.getLeafContent(UUID, LOCALE);
|
||||
|
||||
assertThat(result).isPresent();
|
||||
assertThat(result.get().content()).isEqualTo("Some help content");
|
||||
assertThat(result.get().redirectUrl()).isNull();
|
||||
assertThat(result.get().uuid()).isEqualTo(UUID);
|
||||
assertThat(result.get().locale()).isEqualTo(LOCALE);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getLeafContent_returnsRedirectUrl_whenPostHasRedirect() {
|
||||
when(restTemplateUtil.getURLforApiService(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
HelpCenterPost post = new HelpCenterPost();
|
||||
post.setRedirectUrl("https://example.com/redirect");
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_HELP_CENTER_POST_FIND_BY_HIERARCHY_UUID),
|
||||
eq(HelpCenterPost.class), eq(UUID)))
|
||||
.thenReturn(ResponseEntity.ok(post));
|
||||
|
||||
Optional<HelpCenterContentResponse> result = helpCenterService.getLeafContent(UUID, LOCALE);
|
||||
|
||||
assertThat(result).isPresent();
|
||||
assertThat(result.get().redirectUrl()).isEqualTo("https://example.com/redirect");
|
||||
assertThat(result.get().content()).isNull();
|
||||
|
||||
verify(restTemplateUtil, never()).getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_GENERIC_POST_CONTENT_FIND_BY_UUID_AND_LOCALE),
|
||||
eq(GenericPostContent.class), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getLeafContent_returnsEmpty_whenPostNotFound() {
|
||||
when(restTemplateUtil.getURLforApiService(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_HELP_CENTER_POST_FIND_BY_HIERARCHY_UUID),
|
||||
eq(HelpCenterPost.class), eq(UUID)))
|
||||
.thenReturn(ResponseEntity.ok().build());
|
||||
|
||||
Optional<HelpCenterContentResponse> result = helpCenterService.getLeafContent(UUID, LOCALE);
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getLeafContent_returnsEmpty_whenPostNotOk() {
|
||||
when(restTemplateUtil.getURLforApiService(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_HELP_CENTER_POST_FIND_BY_HIERARCHY_UUID),
|
||||
eq(HelpCenterPost.class), eq(UUID)))
|
||||
.thenReturn(ResponseEntity.status(HttpStatus.NOT_FOUND).build());
|
||||
|
||||
Optional<HelpCenterContentResponse> result = helpCenterService.getLeafContent(UUID, LOCALE);
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getLeafContent_returnsEmpty_whenNoLocalizedContent() {
|
||||
when(restTemplateUtil.getURLforApiService(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
|
||||
HelpCenterPost post = new HelpCenterPost();
|
||||
post.setGenericPostUuid(BigInteger.valueOf(99));
|
||||
post.setRedirectUrl(null);
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_HELP_CENTER_POST_FIND_BY_HIERARCHY_UUID),
|
||||
eq(HelpCenterPost.class), eq(UUID)))
|
||||
.thenReturn(ResponseEntity.ok(post));
|
||||
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_GENERIC_POST_CONTENT_FIND_BY_UUID_AND_LOCALE),
|
||||
eq(GenericPostContent.class), eq(BigInteger.valueOf(99)), eq(LOCALE)))
|
||||
.thenReturn(ResponseEntity.ok().build());
|
||||
|
||||
Optional<HelpCenterContentResponse> result = helpCenterService.getLeafContent(UUID, LOCALE);
|
||||
|
||||
assertThat(result).isEmpty();
|
||||
}
|
||||
|
||||
// ─── getTree helpers ───────────────────────────────────────────────────────
|
||||
|
||||
private static GenericHierarchy node(long uuid, long parentUuid, String name, String tag,
|
||||
int sortIndex, String status, String sysManaged,
|
||||
List<GenericHierarchy> children) {
|
||||
GenericHierarchy gh = new GenericHierarchy();
|
||||
gh.setUuid(BigInteger.valueOf(uuid));
|
||||
gh.setParentUuid(BigInteger.valueOf(parentUuid));
|
||||
gh.setName(name);
|
||||
gh.setMessageTag(tag);
|
||||
gh.setSortIndex(sortIndex);
|
||||
gh.setStatus(GeneralEnum.FlagYesNo.valueOf(status));
|
||||
gh.setSysManaged(GeneralEnum.FlagYesNo.valueOf(sysManaged));
|
||||
gh.setHierarchyType(GeneralEnum.GenericHierarchyType.HC);
|
||||
gh.setChildList(children);
|
||||
return gh;
|
||||
}
|
||||
|
||||
private void stubUrlPassthrough() {
|
||||
when(restTemplateUtil.getURLforApiService(anyString())).thenAnswer(inv -> inv.getArgument(0));
|
||||
}
|
||||
|
||||
private void stubRoot(GenericHierarchy root) {
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_GENERIC_HIERARCHY_FIND_ROOT_BY_TYPE),
|
||||
eq(GenericHierarchy.class), eq(GeneralEnum.GenericHierarchyType.HC)))
|
||||
.thenReturn(ResponseEntity.ok(root));
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_GENERIC_HIERARCHY_FIND_FULL_BY_TYPE_AND_UUID),
|
||||
eq(GenericHierarchy.class), eq(GeneralEnum.GenericHierarchyType.HC), eq(root.getUuid())))
|
||||
.thenReturn(ResponseEntity.ok(root));
|
||||
}
|
||||
|
||||
private void stubLabel(String code, String locale, String label) {
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE),
|
||||
eq(String.class), eq(code), eq(locale)))
|
||||
.thenReturn(ResponseEntity.ok(label));
|
||||
}
|
||||
|
||||
private void stubLabelNotFound(String code, String locale) {
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE),
|
||||
eq(String.class), eq(code), eq(locale)))
|
||||
.thenReturn(ResponseEntity.status(HttpStatus.NOT_FOUND).build());
|
||||
}
|
||||
|
||||
// ─── getTree tests ─────────────────────────────────────────────────────────
|
||||
|
||||
@Test
|
||||
void getTree_returnsEmptyCategories_whenNoHcRoot() {
|
||||
stubUrlPassthrough();
|
||||
when(restTemplateUtil.getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_GENERIC_HIERARCHY_FIND_ROOT_BY_TYPE),
|
||||
eq(GenericHierarchy.class), eq(GeneralEnum.GenericHierarchyType.HC)))
|
||||
.thenReturn(ResponseEntity.ok(null));
|
||||
|
||||
HelpCenterTreeResponse result = helpCenterService.getTree("en_US");
|
||||
|
||||
assertThat(result.locale()).isEqualTo("en_US");
|
||||
assertThat(result.categories()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTree_stripsRoot_returnsTopLevelChildrenSortedBySortIndex() {
|
||||
stubUrlPassthrough();
|
||||
|
||||
GenericHierarchy leaf1 = node(11, 1, "Cat B", "TAG.CAT_B", 2, "Y", "N", List.of());
|
||||
GenericHierarchy leaf2 = node(12, 1, "Cat A", "TAG.CAT_A", 1, "Y", "N", List.of());
|
||||
GenericHierarchy root = node(1, 0, "HC Root", null, 0, "Y", "Y", List.of(leaf1, leaf2));
|
||||
|
||||
stubRoot(root);
|
||||
|
||||
when(messageLabelCache.get("TAG.CAT_B", "en_US")).thenReturn(Optional.empty());
|
||||
when(messageLabelCache.get("TAG.CAT_A", "en_US")).thenReturn(Optional.empty());
|
||||
|
||||
stubLabel("TAG.CAT_B", "en_US", "Category B");
|
||||
stubLabel("TAG.CAT_A", "en_US", "Category A");
|
||||
|
||||
HelpCenterTreeResponse result = helpCenterService.getTree("en_US");
|
||||
|
||||
assertThat(result.locale()).isEqualTo("en_US");
|
||||
assertThat(result.categories()).hasSize(2);
|
||||
// sorted by sortIndex: leaf2 (1) before leaf1 (2)
|
||||
assertThat(result.categories().get(0).label()).isEqualTo("Category A");
|
||||
assertThat(result.categories().get(1).label()).isEqualTo("Category B");
|
||||
|
||||
verify(messageLabelCache).put("TAG.CAT_A", "en_US", "Category A");
|
||||
verify(messageLabelCache).put("TAG.CAT_B", "en_US", "Category B");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTree_recursesArbitraryDepth() {
|
||||
stubUrlPassthrough();
|
||||
|
||||
GenericHierarchy leaf = node(30, 20, "Leaf", "TAG.LEAF", 1, "Y", "N", List.of());
|
||||
GenericHierarchy mid = node(20, 10, "Mid", "TAG.MID", 1, "Y", "N", List.of(leaf));
|
||||
GenericHierarchy top = node(10, 1, "Top", "TAG.TOP", 1, "Y", "N", List.of(mid));
|
||||
GenericHierarchy root = node(1, 0, "HC Root", null, 0, "Y", "Y", List.of(top));
|
||||
|
||||
stubRoot(root);
|
||||
|
||||
when(messageLabelCache.get("TAG.TOP", "en_US")).thenReturn(Optional.empty());
|
||||
when(messageLabelCache.get("TAG.MID", "en_US")).thenReturn(Optional.empty());
|
||||
when(messageLabelCache.get("TAG.LEAF", "en_US")).thenReturn(Optional.empty());
|
||||
|
||||
stubLabel("TAG.TOP", "en_US", "Top Category");
|
||||
stubLabel("TAG.MID", "en_US", "Mid Category");
|
||||
stubLabel("TAG.LEAF", "en_US", "Leaf Article");
|
||||
|
||||
HelpCenterTreeResponse result = helpCenterService.getTree("en_US");
|
||||
|
||||
assertThat(result.categories()).hasSize(1);
|
||||
HelpCenterNode topNode = result.categories().get(0);
|
||||
assertThat(topNode.label()).isEqualTo("Top Category");
|
||||
assertThat(topNode.children()).hasSize(1);
|
||||
|
||||
HelpCenterNode midNode = topNode.children().get(0);
|
||||
assertThat(midNode.label()).isEqualTo("Mid Category");
|
||||
assertThat(midNode.children()).hasSize(1);
|
||||
|
||||
HelpCenterNode leafNode = midNode.children().get(0);
|
||||
assertThat(leafNode.label()).isEqualTo("Leaf Article");
|
||||
assertThat(leafNode.children()).isEmpty();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTree_excludesInactiveNodesAndTheirDescendants() {
|
||||
stubUrlPassthrough();
|
||||
|
||||
GenericHierarchy activeLeaf = node(21, 10, "Active Leaf", "TAG.ACTIVE_LEAF", 1, "Y", "N", List.of());
|
||||
GenericHierarchy activeCat = node(10, 1, "Active Cat", "TAG.ACTIVE_CAT", 1, "Y", "N", List.of(activeLeaf));
|
||||
|
||||
GenericHierarchy hiddenChild = node(31, 20, "Hidden Child", "TAG.HIDDEN_CHILD", 1, "Y", "N", List.of());
|
||||
GenericHierarchy hiddenCat = node(20, 1, "Hidden Cat", "TAG.HIDDEN_CAT", 2, "N", "N", List.of(hiddenChild));
|
||||
|
||||
GenericHierarchy root = node(1, 0, "HC Root", null, 0, "Y", "Y", List.of(activeCat, hiddenCat));
|
||||
|
||||
stubRoot(root);
|
||||
|
||||
when(messageLabelCache.get("TAG.ACTIVE_CAT", "en_US")).thenReturn(Optional.empty());
|
||||
when(messageLabelCache.get("TAG.ACTIVE_LEAF", "en_US")).thenReturn(Optional.empty());
|
||||
|
||||
stubLabel("TAG.ACTIVE_CAT", "en_US", "Active Category");
|
||||
stubLabel("TAG.ACTIVE_LEAF", "en_US", "Active Leaf");
|
||||
|
||||
HelpCenterTreeResponse result = helpCenterService.getTree("en_US");
|
||||
|
||||
assertThat(result.categories()).hasSize(1);
|
||||
assertThat(result.categories().get(0).label()).isEqualTo("Active Category");
|
||||
assertThat(result.categories().get(0).children()).hasSize(1);
|
||||
assertThat(result.categories().get(0).children().get(0).label()).isEqualTo("Active Leaf");
|
||||
|
||||
verify(restTemplateUtil, never()).getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE),
|
||||
eq(String.class), eq("TAG.HIDDEN_CAT"), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTree_fallsBackToName_whenMessageTagMissingOrUnresolved() {
|
||||
stubUrlPassthrough();
|
||||
|
||||
GenericHierarchy blankTag = node(11, 1, "Blank Tag Name", "", 1, "Y", "N", List.of());
|
||||
GenericHierarchy nullTag = node(12, 1, "Null Tag Name", null, 2, "Y", "N", List.of());
|
||||
GenericHierarchy notFoundTag = node(13, 1, "Not Found Name", "TAG.NOT_FOUND", 3, "Y", "N", List.of());
|
||||
GenericHierarchy root = node(1, 0, "HC Root", null, 0, "Y", "Y", List.of(blankTag, nullTag, notFoundTag));
|
||||
|
||||
stubRoot(root);
|
||||
|
||||
when(messageLabelCache.get("TAG.NOT_FOUND", "en_US")).thenReturn(Optional.empty());
|
||||
stubLabelNotFound("TAG.NOT_FOUND", "en_US");
|
||||
|
||||
HelpCenterTreeResponse result = helpCenterService.getTree("en_US");
|
||||
|
||||
assertThat(result.categories()).hasSize(3);
|
||||
assertThat(result.categories().get(0).label()).isEqualTo("Blank Tag Name");
|
||||
assertThat(result.categories().get(1).label()).isEqualTo("Null Tag Name");
|
||||
assertThat(result.categories().get(2).label()).isEqualTo("Not Found Name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void getTree_usesCacheForHits_andCachesFreshFetches() {
|
||||
stubUrlPassthrough();
|
||||
|
||||
GenericHierarchy catA = node(11, 1, "Cat A Name", "TAG.A", 1, "Y", "N", List.of());
|
||||
GenericHierarchy catB = node(12, 1, "Cat B Name", "TAG.B", 2, "Y", "N", List.of());
|
||||
GenericHierarchy root = node(1, 0, "HC Root", null, 0, "Y", "Y", List.of(catA, catB));
|
||||
|
||||
stubRoot(root);
|
||||
|
||||
// TAG.A is a cache hit
|
||||
when(messageLabelCache.get("TAG.A", "en_US")).thenReturn(Optional.of("Cached A Label"));
|
||||
// TAG.B is a cache miss
|
||||
when(messageLabelCache.get("TAG.B", "en_US")).thenReturn(Optional.empty());
|
||||
|
||||
// Only stub TAG.B label endpoint
|
||||
stubLabel("TAG.B", "en_US", "Fresh B Label");
|
||||
|
||||
HelpCenterTreeResponse result = helpCenterService.getTree("en_US");
|
||||
|
||||
assertThat(result.categories()).hasSize(2);
|
||||
assertThat(result.categories().get(0).label()).isEqualTo("Cached A Label");
|
||||
assertThat(result.categories().get(1).label()).isEqualTo("Fresh B Label");
|
||||
|
||||
// TAG.A should never hit the REST endpoint
|
||||
verify(restTemplateUtil, never()).getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE),
|
||||
eq(String.class), eq("TAG.A"), anyString());
|
||||
|
||||
// TAG.B should be fetched and cached
|
||||
verify(restTemplateUtil).getForEntity(
|
||||
eq(RestApiSystemServiceConstants.API_REST_MESSAGE_FIND_BY_CODE_AND_LOCALE),
|
||||
eq(String.class), eq("TAG.B"), eq("en_US"));
|
||||
verify(messageLabelCache).put("TAG.B", "en_US", "Fresh B Label");
|
||||
|
||||
// TAG.A should NOT be put in cache (it was a hit)
|
||||
verify(messageLabelCache, never()).put(eq("TAG.A"), anyString(), anyString());
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package com.solvway.mobile.api.service;
|
||||
|
||||
import com.solvway.mobile.api.constant.api.RestApiMemberServiceConstants;
|
||||
import com.solvway.mobile.api.util.RestTemplateCustomUtil;
|
||||
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 org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class MemberServiceTest {
|
||||
|
||||
@Mock
|
||||
private RestTemplateCustomUtil restTemplateUtil;
|
||||
|
||||
private MemberService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
service = new MemberService(restTemplateUtil);
|
||||
}
|
||||
|
||||
@Test
|
||||
void existsActiveByMemberCodeReturnsTrueWhenOkAndBodyTrue() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_EXISTS_ACTIVE_BY_MEMBER_CODE))
|
||||
.thenReturn("http://member/member/existsActiveByMemberCode");
|
||||
when(restTemplateUtil.getForEntity(eq("http://member/member/existsActiveByMemberCode"), eq(Boolean.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(true));
|
||||
|
||||
boolean result = service.existsActiveByMemberCode("M1");
|
||||
|
||||
assertThat(result).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void existsActiveByMemberCodeReturnsFalseWhenOkAndBodyFalse() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_EXISTS_ACTIVE_BY_MEMBER_CODE))
|
||||
.thenReturn("http://member/member/existsActiveByMemberCode");
|
||||
when(restTemplateUtil.getForEntity(eq("http://member/member/existsActiveByMemberCode"), eq(Boolean.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(false));
|
||||
|
||||
boolean result = service.existsActiveByMemberCode("M1");
|
||||
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void existsActiveByMemberCodeReturnsFalseWhenOkAndBodyNull() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_EXISTS_ACTIVE_BY_MEMBER_CODE))
|
||||
.thenReturn("http://member/member/existsActiveByMemberCode");
|
||||
when(restTemplateUtil.getForEntity(eq("http://member/member/existsActiveByMemberCode"), eq(Boolean.class), any()))
|
||||
.thenReturn(ResponseEntity.ok(null));
|
||||
|
||||
boolean result = service.existsActiveByMemberCode("M1");
|
||||
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
|
||||
@Test
|
||||
void existsActiveByMemberCodeReturnsFalseOnNonOkStatus() {
|
||||
when(restTemplateUtil.getURLforApiService(RestApiMemberServiceConstants.API_REST_MEMBER_MEMBER_EXISTS_ACTIVE_BY_MEMBER_CODE))
|
||||
.thenReturn("http://member/member/existsActiveByMemberCode");
|
||||
when(restTemplateUtil.getForEntity(eq("http://member/member/existsActiveByMemberCode"), eq(Boolean.class), any()))
|
||||
.thenReturn(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
|
||||
|
||||
boolean result = service.existsActiveByMemberCode("M1");
|
||||
|
||||
assertThat(result).isFalse();
|
||||
}
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.JwtTokenUtil;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.mobile.api.config.AuthAppKeyConfig;
|
||||
import com.solvway.mobile.api.config.PubSubConfig;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.UserService;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
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.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class AppAccessAspectAuthTest {
|
||||
|
||||
private static final String VALID_API_KEY = "valid-api-key";
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private UserService userService;
|
||||
@Mock private PubSubConfig pubSubConfig;
|
||||
@Mock private PubSubTemplate pubSubTemplate;
|
||||
@Mock private PubSubUtil pubSubUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private JwtTokenUtil jwtTokenUtil;
|
||||
@Mock private ProceedingJoinPoint joinPoint;
|
||||
@Mock private MethodSignature methodSignature;
|
||||
|
||||
private AppAccessAspect aspect;
|
||||
|
||||
static class Target {
|
||||
@AppAuth
|
||||
public void secured() {
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
AuthAppKeyConfig authAppKeyConfig = new AuthAppKeyConfig();
|
||||
authAppKeyConfig.setList(List.of(VALID_API_KEY));
|
||||
aspect = new AppAccessAspect(memberService, userService, pubSubConfig, pubSubTemplate,
|
||||
pubSubUtil, authAppKeyConfig, authenticationService, jwtTokenUtil);
|
||||
|
||||
Method secured = Target.class.getMethod("secured");
|
||||
when(joinPoint.getSignature()).thenReturn(methodSignature);
|
||||
when(methodSignature.getMethod()).thenReturn(secured);
|
||||
when(methodSignature.toShortString()).thenReturn("Target.secured()");
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingApiKeyIsUnauthorized() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn("");
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("");
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode())
|
||||
.isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void invalidApiKeyIsUnauthorized() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn("wrong-key");
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("");
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode())
|
||||
.isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingAuthorizationHeaderIsUnauthorizedNotBadRequest() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(VALID_API_KEY);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("");
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode())
|
||||
.isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void expiredTokenIsUnauthorizedNotServerError() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(VALID_API_KEY);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("expired-token");
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
when(jwtTokenUtil.isTokenExpired("expired-token")).thenReturn(true);
|
||||
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode())
|
||||
.isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void malformedTokenIsUnauthorizedNotServerError() {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(VALID_API_KEY);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("garbage");
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
when(jwtTokenUtil.isTokenExpired("garbage")).thenThrow(new RuntimeException("bad signature"));
|
||||
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> assertThat(((ResponseStatusException) ex).getStatusCode())
|
||||
.isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void validTokenProceedsToController() throws Throwable {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(VALID_API_KEY);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn("good-token");
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
when(jwtTokenUtil.isTokenExpired("good-token")).thenReturn(false);
|
||||
when(authenticationService.getUsernameFromToken("good-token")).thenReturn("alice");
|
||||
when(joinPoint.proceed()).thenReturn("controller-result");
|
||||
|
||||
Object result = aspect.appAccessAuthCheck(joinPoint);
|
||||
|
||||
assertThat(result).isEqualTo("controller-result");
|
||||
}
|
||||
}
|
||||
}
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.GeneralEnum.FlagYesNo;
|
||||
import com.solvway.core.model.User;
|
||||
import com.solvway.core.utils.HttpReqRespUtils;
|
||||
import com.solvway.core.utils.JwtTokenUtil;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.mobile.api.config.AuthAppKeyConfig;
|
||||
import com.solvway.mobile.api.config.PubSubConfig;
|
||||
import com.solvway.mobile.api.controller.MemberController;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.UserService;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
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.MockedStatic;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.mockStatic;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class AppAccessAspectPhoneVerificationTest {
|
||||
|
||||
private static final String CP_KEY = "cp-key";
|
||||
private static final String APP_KEY = "app-key";
|
||||
private static final String JWT = "good-token";
|
||||
|
||||
@Mock private MemberService memberService;
|
||||
@Mock private UserService userService;
|
||||
@Mock private PubSubConfig pubSubConfig;
|
||||
@Mock private PubSubTemplate pubSubTemplate;
|
||||
@Mock private PubSubUtil pubSubUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
@Mock private JwtTokenUtil jwtTokenUtil;
|
||||
@Mock private ProceedingJoinPoint joinPoint;
|
||||
@Mock private MethodSignature methodSignature;
|
||||
|
||||
private AppAccessAspect aspect;
|
||||
|
||||
static class Target {
|
||||
@AppAuth
|
||||
public void secured() {
|
||||
}
|
||||
|
||||
@AppAuth
|
||||
@PhoneVerificationExempt
|
||||
public void exempt() {
|
||||
}
|
||||
|
||||
@AppAuth(skipValidate = true)
|
||||
public void open() {
|
||||
}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Throwable {
|
||||
AuthAppKeyConfig cfg = new AuthAppKeyConfig();
|
||||
cfg.setList(List.of(CP_KEY + ":CP", APP_KEY + ":APP"));
|
||||
aspect = new AppAccessAspect(memberService, userService, pubSubConfig, pubSubTemplate,
|
||||
pubSubUtil, cfg, authenticationService, jwtTokenUtil);
|
||||
when(joinPoint.getSignature()).thenReturn(methodSignature);
|
||||
when(methodSignature.toShortString()).thenReturn("Target.m()");
|
||||
when(jwtTokenUtil.isTokenExpired(JWT)).thenReturn(false);
|
||||
when(authenticationService.getUsernameFromToken(JWT)).thenReturn("alice");
|
||||
when(joinPoint.proceed()).thenReturn("result");
|
||||
}
|
||||
|
||||
private void useMethod(String name) throws Exception {
|
||||
when(methodSignature.getMethod()).thenReturn(Target.class.getMethod(name));
|
||||
}
|
||||
|
||||
private static User user(FlagYesNo phone, FlagYesNo email) {
|
||||
User u = new User();
|
||||
u.setPhoneVerified(phone);
|
||||
u.setEmailVerified(email);
|
||||
return u;
|
||||
}
|
||||
|
||||
private Object call(String apiKey) throws Throwable {
|
||||
try (MockedStatic<HttpReqRespUtils> http = mockStatic(HttpReqRespUtils.class)) {
|
||||
http.when(() -> HttpReqRespUtils.getHeaderValues("api-key")).thenReturn(apiKey);
|
||||
http.when(HttpReqRespUtils::getJwtToken).thenReturn(JWT);
|
||||
http.when(HttpReqRespUtils::getAllHeaders).thenReturn("{}");
|
||||
return aspect.appAccessAuthCheck(joinPoint);
|
||||
}
|
||||
}
|
||||
|
||||
private void assertForbidden(String apiKey) throws Throwable {
|
||||
assertThatThrownBy(() -> call(apiKey))
|
||||
.isInstanceOf(ResponseStatusException.class)
|
||||
.satisfies(ex -> {
|
||||
ResponseStatusException r = (ResponseStatusException) ex;
|
||||
assertThat(r.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN);
|
||||
assertThat(r.getReason()).isEqualTo("Phone verification required.");
|
||||
assertThat(r.getHeaders().getFirst("X-Phone-Verification-Required")).isEqualTo("true");
|
||||
});
|
||||
verify(joinPoint, never()).proceed();
|
||||
}
|
||||
|
||||
@Test
|
||||
void cpUnverifiedIsForbiddenAndControllerNotRun() throws Throwable {
|
||||
useMethod("secured");
|
||||
when(userService.findByUsername("alice")).thenReturn(user(FlagYesNo.N, FlagYesNo.N));
|
||||
assertForbidden(CP_KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cpPhoneVerifiedProceeds() throws Throwable {
|
||||
useMethod("secured");
|
||||
when(userService.findByUsername("alice")).thenReturn(user(FlagYesNo.Y, FlagYesNo.N));
|
||||
assertThat(call(CP_KEY)).isEqualTo("result");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cpEmailVerifiedProceeds() throws Throwable {
|
||||
useMethod("secured");
|
||||
when(userService.findByUsername("alice")).thenReturn(user(FlagYesNo.N, FlagYesNo.Y));
|
||||
assertThat(call(CP_KEY)).isEqualTo("result");
|
||||
}
|
||||
|
||||
@Test
|
||||
void cpExemptMethodProceedsWhenUnverified() throws Throwable {
|
||||
useMethod("exempt");
|
||||
when(userService.findByUsername("alice")).thenReturn(user(FlagYesNo.N, FlagYesNo.N));
|
||||
assertThat(call(CP_KEY)).isEqualTo("result");
|
||||
}
|
||||
|
||||
@Test
|
||||
void appPlatformUnverifiedProceedsWithoutLookup() throws Throwable {
|
||||
useMethod("secured");
|
||||
when(userService.findByUsername("alice")).thenReturn(user(FlagYesNo.N, FlagYesNo.N));
|
||||
assertThat(call(APP_KEY)).isEqualTo("result");
|
||||
verify(userService, never()).findByUsername(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void skipValidateMethodDoesNoUserLookup() throws Throwable {
|
||||
useMethod("open");
|
||||
assertThat(call(CP_KEY)).isEqualTo("result");
|
||||
verify(userService, never()).findByUsername(anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void cpNullUserIsForbidden() throws Throwable {
|
||||
useMethod("secured");
|
||||
when(userService.findByUsername("alice")).thenReturn(null);
|
||||
assertForbidden(CP_KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void cpLookupThrowingIsForbidden() throws Throwable {
|
||||
useMethod("secured");
|
||||
when(userService.findByUsername("alice")).thenThrow(new RuntimeException("system-service down"));
|
||||
assertForbidden(CP_KEY);
|
||||
}
|
||||
|
||||
@Test
|
||||
void otpEndpointsCarryPhoneVerificationExempt() throws Exception {
|
||||
Method required = MemberController.class.getMethod("getOtpRequired");
|
||||
Method verify = MemberController.class.getMethod("postOtpVerification", Map.class);
|
||||
assertThat(required.isAnnotationPresent(PhoneVerificationExempt.class)).isTrue();
|
||||
assertThat(verify.isAnnotationPresent(PhoneVerificationExempt.class)).isTrue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void firstTimePasswordCarriesPhoneVerificationExempt() throws Exception {
|
||||
Method m = MemberController.class.getMethod("firstTimePassword", Map.class);
|
||||
assertThat(m.isAnnotationPresent(PhoneVerificationExempt.class)).isTrue();
|
||||
}
|
||||
}
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.spi.ILoggingEvent;
|
||||
import ch.qos.logback.core.read.ListAppender;
|
||||
import com.google.cloud.spring.pubsub.core.PubSubTemplate;
|
||||
import com.solvway.core.annotation.AppAuth;
|
||||
import com.solvway.core.enums.GeneralEnum.CmsPlatform;
|
||||
import com.solvway.core.model.ResponseTime;
|
||||
import com.solvway.core.utils.JwtTokenUtil;
|
||||
import com.solvway.core.utils.PubSubUtil;
|
||||
import com.solvway.mobile.api.config.AuthAppKeyConfig;
|
||||
import com.solvway.mobile.api.config.PubSubConfig;
|
||||
import com.solvway.mobile.api.service.AuthenticationService;
|
||||
import com.solvway.mobile.api.service.MemberService;
|
||||
import com.solvway.mobile.api.service.UserService;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
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.mockito.junit.jupiter.MockitoSettings;
|
||||
import org.mockito.quality.Strictness;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doThrow;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/** add-response-time-platform-attribution: rows carry the platform of the api-key that authorised the call. */
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
@MockitoSettings(strictness = Strictness.LENIENT)
|
||||
class AppAccessAspectResponseTimeTest {
|
||||
|
||||
private static final String TOPIC = "response-time-log-topic";
|
||||
|
||||
@Mock private ProceedingJoinPoint joinPoint;
|
||||
@Mock private MethodSignature methodSignature;
|
||||
@Mock private PubSubTemplate pubSubTemplate;
|
||||
@Mock private PubSubUtil pubSubUtil;
|
||||
@Mock private JwtTokenUtil jwtTokenUtil;
|
||||
@Mock private AuthenticationService authenticationService;
|
||||
|
||||
private AppAccessAspect aspect;
|
||||
|
||||
static class Target {
|
||||
@AppAuth(skipValidate = true) public void publicEndpoint() {}
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Throwable {
|
||||
AuthAppKeyConfig keys = new AuthAppKeyConfig();
|
||||
keys.setList(List.of("cpKey:CP", "legacyKey", "abcd1234:CP"));
|
||||
PubSubConfig pubSubConfig = mock(PubSubConfig.class);
|
||||
pubSubConfig.responseTimeLogTopic = TOPIC;
|
||||
aspect = new AppAccessAspect(mock(MemberService.class), mock(UserService.class), pubSubConfig,
|
||||
pubSubTemplate, pubSubUtil, keys, authenticationService, jwtTokenUtil);
|
||||
|
||||
when(joinPoint.getSignature()).thenReturn(methodSignature);
|
||||
when(methodSignature.getMethod()).thenReturn(Target.class.getMethod("publicEndpoint"));
|
||||
when(methodSignature.toShortString()).thenReturn("Target.publicEndpoint()");
|
||||
when(joinPoint.proceed()).thenReturn("ok");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void tearDown() {
|
||||
RequestContextHolder.resetRequestAttributes();
|
||||
}
|
||||
|
||||
private void requestWithApiKey(String apiKey) {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/api/public/banner");
|
||||
request.addHeader("api-key", apiKey);
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request));
|
||||
}
|
||||
|
||||
private ResponseTime published() {
|
||||
ArgumentCaptor<ResponseTime> captor = ArgumentCaptor.forClass(ResponseTime.class);
|
||||
verify(pubSubUtil).publishMessage(eq(pubSubTemplate), eq(TOPIC), captor.capture());
|
||||
return captor.getValue();
|
||||
}
|
||||
|
||||
@Test
|
||||
void customerPortalKeyPassesGateAndPublishesCp() throws Throwable {
|
||||
requestWithApiKey("cpKey");
|
||||
|
||||
assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok");
|
||||
|
||||
ResponseTime rt = published();
|
||||
assertThat(rt.getSourcePlatform()).isEqualTo(CmsPlatform.CP);
|
||||
assertThat(rt.getUrl()).isEqualTo("/api/public/banner");
|
||||
assertThat(rt.getMethod()).isEqualTo("GET");
|
||||
}
|
||||
|
||||
@Test
|
||||
void bareKeyPublishesApp() throws Throwable {
|
||||
requestWithApiKey("legacyKey");
|
||||
|
||||
aspect.appAccessAuthCheck(joinPoint);
|
||||
|
||||
assertThat(published().getSourcePlatform()).isEqualTo(CmsPlatform.APP);
|
||||
}
|
||||
|
||||
@Test
|
||||
void rawSuffixedTokenIsRejectedAndNotPublished() {
|
||||
requestWithApiKey("cpKey:CP");
|
||||
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint))
|
||||
.isInstanceOfSatisfying(ResponseStatusException.class,
|
||||
ex -> assertThat(ex.getStatusCode()).isEqualTo(HttpStatus.UNAUTHORIZED));
|
||||
verify(pubSubUtil, never()).publishMessage(any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void publisherFailureDoesNotBreakSuccessfulResponse() throws Throwable {
|
||||
requestWithApiKey("cpKey");
|
||||
doThrow(new RuntimeException("pubsub down")).when(pubSubUtil).publishMessage(any(), any(), any());
|
||||
|
||||
assertThat(aspect.appAccessAuthCheck(joinPoint)).isEqualTo("ok");
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectLogNeverPrintsAConfiguredKey() {
|
||||
requestWithApiKey("wrong-key");
|
||||
Logger logger = (Logger) LoggerFactory.getLogger(AppAccessAspect.class);
|
||||
ListAppender<ILoggingEvent> appender = new ListAppender<>();
|
||||
appender.start();
|
||||
logger.addAppender(appender);
|
||||
try {
|
||||
assertThatThrownBy(() -> aspect.appAccessAuthCheck(joinPoint)).isInstanceOf(ResponseStatusException.class);
|
||||
} finally {
|
||||
logger.detachAppender(appender);
|
||||
}
|
||||
|
||||
// An 8-character key with a platform suffix used to be printed in full by the masked allow-list.
|
||||
assertThat(appender.list).isNotEmpty()
|
||||
.allSatisfy(event -> assertThat(event.getFormattedMessage())
|
||||
.doesNotContain("abcd1234").doesNotContain("cpKey").doesNotContain("legacyKey"));
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package com.solvway.mobile.api.useraccess;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
class PhoneVerificationHeaderMvcTest {
|
||||
|
||||
@RestController
|
||||
static class ThrowingController {
|
||||
@GetMapping("/gated")
|
||||
public String gated() {
|
||||
throw AppAccessAspect.phoneVerificationRequired();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void gateExceptionBecomes403WithHeaderOnTheHttpResponse() throws Exception {
|
||||
MockMvc mvc = MockMvcBuilders.standaloneSetup(new ThrowingController()).build();
|
||||
mvc.perform(get("/gated"))
|
||||
.andExpect(status().isForbidden())
|
||||
.andExpect(header().string("X-Phone-Verification-Required", "true"));
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
package com.solvway.mobile.api.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class HeaderRedactionUtilTest {
|
||||
|
||||
@Test
|
||||
void redactsAuthorizationHeaderValue() {
|
||||
String headers = "{\"Authorization\":\"Bearer secret-token\",\"User-Agent\":\"junit\"}";
|
||||
|
||||
String redacted = HeaderRedactionUtil.redact(headers);
|
||||
|
||||
assertThat(redacted).doesNotContain("secret-token");
|
||||
assertThat(redacted).contains("[REDACTED]");
|
||||
}
|
||||
|
||||
@Test
|
||||
void preservesNonSensitiveHeaders() {
|
||||
String headers = "{\"Authorization\":\"Bearer secret-token\",\"User-Agent\":\"junit\"}";
|
||||
|
||||
String redacted = HeaderRedactionUtil.redact(headers);
|
||||
|
||||
assertThat(redacted).contains("junit");
|
||||
}
|
||||
|
||||
@Test
|
||||
void redactsRegardlessOfHeaderNameCasing() {
|
||||
String headers = "{\"authorization\":\"Bearer secret-token\"}";
|
||||
|
||||
assertThat(HeaderRedactionUtil.redact(headers)).doesNotContain("secret-token");
|
||||
}
|
||||
|
||||
@Test
|
||||
void redactsApiKeyAndCookieHeaders() {
|
||||
String headers = "{\"api-key\":\"k123\",\"Cookie\":\"session=abc\"}";
|
||||
|
||||
String redacted = HeaderRedactionUtil.redact(headers);
|
||||
|
||||
assertThat(redacted).doesNotContain("k123");
|
||||
assertThat(redacted).doesNotContain("session=abc");
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsEmptyObjectForUnparseableInput() {
|
||||
assertThat(HeaderRedactionUtil.redact("not-json")).isEqualTo("{}");
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlesNullAndEmptyInput() {
|
||||
assertThat(HeaderRedactionUtil.redact(null)).isNull();
|
||||
assertThat(HeaderRedactionUtil.redact("")).isEmpty();
|
||||
}
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.solvway.mobile.api.util.redis;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class TokenCacheKeyUtilTest {
|
||||
|
||||
@Test
|
||||
void hashesTokenToLowercaseHexSha256() {
|
||||
assertThat(TokenCacheKeyUtil.hashToken("abc"))
|
||||
.isEqualTo("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
|
||||
}
|
||||
|
||||
@Test
|
||||
void producesStableHashForSameToken() {
|
||||
assertThat(TokenCacheKeyUtil.hashToken("token-1"))
|
||||
.isEqualTo(TokenCacheKeyUtil.hashToken("token-1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void producesDifferentHashesForDifferentTokens() {
|
||||
assertThat(TokenCacheKeyUtil.hashToken("token-1"))
|
||||
.isNotEqualTo(TokenCacheKeyUtil.hashToken("token-2"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void neverReturnsTheRawToken() {
|
||||
String token = "eyJhbGciOiJIUzUxMiJ9.payload.signature";
|
||||
assertThat(TokenCacheKeyUtil.hashToken(token)).doesNotContain(token);
|
||||
}
|
||||
|
||||
@Test
|
||||
void returnsEmptyStringForNullOrEmptyToken() {
|
||||
assertThat(TokenCacheKeyUtil.hashToken(null)).isEmpty();
|
||||
assertThat(TokenCacheKeyUtil.hashToken("")).isEmpty();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user