diff --git a/server/routes/businesses.js b/server/routes/businesses.js index 126b193..c46fe2e 100644 --- a/server/routes/businesses.js +++ b/server/routes/businesses.js @@ -70,11 +70,36 @@ async function findBusinessByApplicationId(merchantId, applicationId) { if (!normalizedApplicationId) return null; const businesses = await getIndex(merchantId); - return businesses.find((business) => { + const exactMatch = businesses.find((business) => { const storedApplicationId = normalizeScopeId(business.applicationId); const storedBusinessId = normalizeScopeId(business.businessId); return storedApplicationId === normalizedApplicationId || storedBusinessId === normalizedApplicationId; - }) || null; + }); + + if (exactMatch) return exactMatch; + + const normalizedBrandLookup = normalizedApplicationId.toLowerCase(); + const brandMatches = businesses.filter((business) => normalizeText(business.brandName).toLowerCase() === normalizedBrandLookup); + + if (brandMatches.length > 1) { + throw createHttpError( + 409, + 'Multiple businesses matched the provided applicationId brand fallback', + { + code: 'AMBIGUOUS_BUSINESS_MATCH', + details: { + companyId: merchantId, + applicationId: normalizedApplicationId, + matchedBusinesses: brandMatches.map((business) => ({ + businessId: business.businessId, + brandName: business.brandName, + })), + }, + } + ); + } + + return brandMatches[0] || null; } const PROVIDER_FIELDS = ['providerName', 'senderId', 'dltEntityId', 'authKey'];