Checking access…

Skip to main content
Audience: CCG Platform Engineers

Customer Lookup Logic (CCG Database)

Platform engineers tracing customer lookup logic against the CCG database. See Customer Lookup Logic (EIMP) for the EIMP-side counterpart.

Legend: Class / Handler Method Field / Config Key Event API Endpoint DB Table / Column

When a customer cannot be resolved through direct identifiers (walletCustomerId, enterpriseId, or hsid), the system falls back to a metadata-based CCG database lookup that also leverages the enterprise settings configuration.

When Does This Run?

The CCG DB metadata lookup is the final fallback in the customer resolution chain. It runs after all direct identifier lookups have been exhausted β€” not as a replacement for EIMP, but as a complementary database-level search that reuses the same enterprise settings configuration.

Resolution Chain β€” Where CCG DB Lookup Fits​

Customer Resolution Priority Order

The customer resolution order in CustomerQueryHandler.findCustomer():

PriorityStrategyLookup TargetMethod
1stDirect IDcustomer table by walletCustomerIdfindById()
2ndEnterprise IDenterprise_customer table by enterpriseIdgetCustomerByEnterpriseId()
3rdHSIDenterprise_customer table by hsidgetCustomerByHsid()
4thMetadata and demographics (Enterprise Settings)merchant_customer_metadata and merchant_customer tablesgetCustomerByMetadataAndDemographics()
5thBase HSIDmerchant_customer tablegetCustomerByBaseHsid()

CCG DB Lookup Algorithm​

Step-by-Step Process

The lookup is implemented in CustomerQueryHandler.getCustomerByMetadataAndDemographics(). It uses merchantMetadataKey to find candidates in the database, then the matched criteria's merchantSearchKey fields to validate their demographics:

  1. Guard check β€” If the query has no metadata, skip directly to getCustomerByBaseHsid()

  2. Load merchant and verify enterprise settings

    • Retrieve the Merchant entity using merchantRepository.findByMerchantId()
    • Confirm orderedCustomerSearchCriteria is non-empty; if empty, skip to fallback
  3. Expand search to the entire merchant group

    • Retrieve the merchantGroupId from the requesting merchant
    • Load all merchants in that group via merchantRepository.findByMerchantGroupId()
    • This enables cross-merchant customer discovery within the same merchant group
  4. For each merchant in the group:

    • Sort OrderedCustomerSearchCriteria by outer precedence (ascending)
    • Sort each inner CustomerSearchCriteria list by inner precedence (ascending)
  5. Validate metadata completeness β€” isMetadataContains()

    • Extract all merchantMetadataKey values marked required:true from the criteria
    • Verify the request metadata contains all required keys
    • If no criteria are marked required, at least one configured key must be present
    • If validation fails, skip this criteria set
  6. Filter metadata to configured keys β€” filterMetadata()

    • From the request metadata, keep only entries whose key matches a merchantMetadataKey in the criteria
    • Uses a LinkedHashMap to preserve insertion order (respects inner precedence)
    • Example: Request {"subscriberId": "ABC", "dependentCode": "01", "phone": "555-1234"} with criteria keys ["subscriberId", "dependentCode"] β†’ filtered to {"subscriberId": "ABC", "dependentCode": "01"}
  7. Execute SQL query against merchant_customer_metadata

    • Call merchantCustomerMetadataRepository.findAllCustomerIdsByMetadataAndMerchantId(filteredMetadata, merchantId)
    • Collect all matching customer_id values for each merchant and criteria set
  8. Load candidate customers β€” For each customer_id, load the active Customer via customerRepository.findOptionalCustomerById(), retaining the matched criteria and merchant ID

  9. Validate demographics β€” For each candidate, load its merchant_customer record for the matched merchant. Compare the required demographic fields from the matched criteria (such as ZIP code or date of birth) against that record. If no demographic fields are configured, the metadata-matched candidate passes this check.

  10. Resolve a unique match β€” Deduplicate passing candidates by customer ID. Return the customer only if exactly one distinct customer passes.

  11. Final fallback β€” If no metadata candidates are found, or zero or multiple distinct customers pass demographics validation, call getCustomerByBaseHsid()

SQL Query Construction​

Dynamic Query Building

The SQL is built dynamically by MerchantCustomerMetadataRepository.buildMetadataQuery() using nested subqueries for multi-key intersection:

Single metadata key (e.g., {"subscriberId": "ABC123"}):

SELECT customer_id FROM merchant_customer_metadata mcm
JOIN customer cus ON cus.id = mcm.customer_id
WHERE mcm.metadata_key = 'subscriberId'
AND mcm.metadata_value = 'ABC123'
AND mcm.merchant_id = '<merchant-uuid>'
AND (cus.inactive IS NULL OR cus.inactive = false)

Multiple metadata keys (e.g., {"subscriberId": "ABC123", "dependentCode": "01"}):

SELECT customer_id FROM merchant_customer_metadata mcm
JOIN customer cus ON cus.id = mcm.customer_id
WHERE mcm.metadata_key = 'subscriberId'
AND mcm.metadata_value = 'ABC123'
AND mcm.merchant_id = '<merchant-uuid>'
AND (cus.inactive IS NULL OR cus.inactive = false)
AND customer_id IN (
SELECT customer_id FROM merchant_customer_metadata mcm
JOIN customer cus ON cus.id = mcm.customer_id
WHERE mcm.metadata_key = 'dependentCode'
AND mcm.metadata_value = '01'
AND mcm.merchant_id = '<merchant-uuid>'
AND (cus.inactive IS NULL OR cus.inactive = false)
)

Each additional metadata key adds another nested AND customer_id IN (...) subquery, forming an intersection β€” the customer must have matching rows for every filtered metadata key.

Database Tables and Schema​

Tables Involved
TableColumns UsedRole
merchantenterprise_settings (JSONB), merchant_group_idStores enterprise settings config; groups merchants
merchant_customer_metadatacustomer_id, merchant_id, metadata_key, metadata_valueKey-value pairs linking customers to merchant-specific identifiers
merchant_customercustomer_id, merchant_id, configured demographic fieldsValidates metadata-matched candidates against the merchant's customer record
customerid, inactiveJOIN filter to exclude inactive customers

The merchant_customer_metadata entity:

@Entity
@Table(name = "merchant_customer_metadata")
public class MerchantCustomerMetadata {
UUID id;
UUID customerId; // β†’ customer.id
UUID merchantId; // β†’ merchant.wallet_merchant_id
String key; // metadata_key (e.g., "subscriberId")
String value; // metadata_value (e.g., "ABC123")
}

Sequence Diagram​

CCG DB Metadata Lookup Flow

merchantMetadataKey β€” EIMP vs CCG DB Usage​

Dual Purpose of merchantMetadataKey

The merchantMetadataKey field serves different purposes in different lookup phases:

PhaseHow merchantMetadataKey Is UsedOther Keys Used
EIMP Lookup❌ Not usedmerchantSearchKey (JSONPath extraction), enterpriseSearchKey, enterpriseValueKey
CCG DB Lookupβœ… Matches request metadata keys to DB query keysmerchantSearchKey identifies fields for subsequent demographic validation
Wallet Upgradeβœ… Maps EIMP response values (via enterpriseResponseSearchPath) to metadata storage keys in merchant_customer_metadataenterpriseResponseSearchPath

During EIMP lookups, the system uses merchantSearchKey (a JSONPath) to extract values from the full customer request object. During CCG DB lookups, the system uses merchantMetadataKey to match against the flat metadata map that was passed in the request, then uses required merchantSearchKey fields from the matched criteria to validate candidate demographics.

Example:

Enterprise Settings:
merchantSearchKey: "$.metadata.subscriberId" ← used by EIMP lookup (JSONPath on full request)
merchantMetadataKey: "subscriberId" ← used by CCG DB lookup (key match on metadata map)

Request:
{ "metadata": { "subscriberId": "ABC123" } }

EIMP: extracts "ABC123" via JSONPath "$.metadata.subscriberId"
CCG DB: filters metadata map to {"subscriberId": "ABC123"}, queries merchant_customer_metadata table

Merchant Group Cross-Lookup​

Cross-Merchant Customer Discovery

A key feature of the CCG DB lookup is that it searches across all merchants in the same merchant group, not only the requesting merchant. This enables scenarios where a customer was originally created under one merchant but needs to be discovered when accessing through another merchant in the same group.

Merchant Group "Healthcare Corp" (merchantGroupId: MG-001)
β”œβ”€β”€ Merchant A (walletMerchantId: M-001) β€” customer created here
β”‚ └── merchant_customer_metadata: {subscriberId: "ABC123"} β†’ customer_id: C-001
β”œβ”€β”€ Merchant B (walletMerchantId: M-002) β€” customer requests here
β”‚ └── merchant_customer_metadata: (no entry for this customer)
└── Merchant C (walletMerchantId: M-003)

When a request arrives at Merchant B with metadata: {"subscriberId": "ABC123"}:

  1. System loads Merchant B β†’ gets merchantGroupId: MG-001
  2. Loads all merchants in group: A, B, C
  3. For each merchant, runs the metadata query against merchant_customer_metadata
  4. Finds C-001 as a candidate under Merchant A and validates its configured demographics against Merchant A's merchant_customer record
  5. Returns C-001 only if it is the sole distinct customer that passes; otherwise falls back to base HSID

Local Customer Lookup During Payment Method Transfer​

Reuse in Wallet Merge Flow

The same metadata and demographics lookup is reused by CustomerQueryHandler.findLocalCustomer(), called during the Local to Enterprise Wallet Merge process:

public Mono<MerchantCustomer> findLocalCustomer(CreateCustomerForMerchantCommand command) {
String merchantId = command.getWalletMerchantId();
return merchantId.equals(eiClaimsMerchantId) ? Mono.empty()
: getCustomerByMetadataAndDemographics(buildCustomerQuery(command))
.flatMap(localCustomer -> merchantCustomerRepo
.findByMerchantIdAndCustomerIdAndNotEnterpriseCustomer(
UUID.fromString(merchantId), localCustomer.getId()));
}

This adds an extra filter: the found customer must not already be an enterprise customer (verified via NOT EXISTS against the enterprise_customer table). This ensures only genuinely local customers are identified for migration.