Cards and Their State

List every card of a subaccount with its last four digits, network, expiry and the state of its current card subscription, from one list of subscriptions.

For: developers

A card's state lives on its card subscription: active, pending, deactivated, expired and others. A card can have more than one subscription: enrolling a card again after its subscription was deactivated gives the same card a new subscription. So this recipe reads every subscription of the subaccount with its card embedded, one list and no call per card, and keeps one subscription per card: an active one first, then a pending one, else the newest.

Before you start

  • Scopes: card-subscriptions:read, and cards:read for the embedded card.
  • A subaccount with enrolled cards. In the sandbox, Testing Single Card Enrollment enrolls test cards.
  • Sandbox or production.

The code

States this code does not know, including ones newer than it, rank below pending, so a newer state never hides an active subscription.

/** One card, as your page shows it. */
export interface CardRow {
  cardId: string;
  /** Absent when the card itself could not be read (its key is then missing from `_embedded`). */
  last4?: string;
  network?: string | null;
  expiry?: string;
  state: string;
  subscriptionId: string;
  enrolledAt: string;
}

/** Higher wins when a card has several subscriptions. Other states, and states newer than this code, rank 0. */
function rank(state: string): number {
  if (state === 'active') return 2;
  if (state === 'pending') return 1;
  return 0;
}

function better(candidate: CardSubscription, current: CardSubscription): boolean {
  const byState = rank(candidate.state) - rank(current.state);
  if (byState !== 0) return byState > 0;
  return Date.parse(candidate.createdAt) > Date.parse(current.createdAt);
}
@dataclass
class CardRow:
    """One card, as your page shows it."""

    card_id: str
    # None when the card itself could not be read (its key is then missing from `_embedded`).
    last4: Optional[str]
    network: Optional[str]
    expiry: Optional[str]
    state: str
    subscription_id: str
    enrolled_at: str


def rank(state: str) -> int:
    """Higher wins when a card has several subscriptions. Other states, and states newer than
    this code, rank 0."""
    if state == "active":
        return 2
    if state == "pending":
        return 1
    return 0


def better(candidate: astrada.CardSubscription, current: astrada.CardSubscription) -> bool:
    by_state = rank(candidate.state) - rank(current.state)
    if by_state != 0:
        return by_state > 0
    return candidate.created_at > current.created_at
/** One card, as your page shows it. */
public static final class CardRow {
    public final UUID cardId;
    /** Null when the card itself could not be read (its key is then missing from {@code _embedded}). */
    public final String last4;
    public final String network;
    public final String expiry;
    public final String state;
    public final UUID subscriptionId;
    public final String enrolledAt;

    CardRow(UUID cardId, String last4, String network, String expiry, String state, UUID subscriptionId, String enrolledAt) {
        this.cardId = cardId;
        this.last4 = last4;
        this.network = network;
        this.expiry = expiry;
        this.state = state;
        this.subscriptionId = subscriptionId;
        this.enrolledAt = enrolledAt;
    }

    @Override
    public String toString() {
        return cardId + " " + last4 + " " + network + " " + expiry + " " + state + " " + subscriptionId + " " + enrolledAt;
    }
}

/** Higher wins when a card has several subscriptions. Other states, and states newer than this code, rank 0. */
static int rank(String state) {
    if ("active".equals(state)) {
        return 2;
    }
    if ("pending".equals(state)) {
        return 1;
    }
    return 0;
}

static boolean better(CardSubscription candidate, CardSubscription current) {
    int byState = rank(candidate.getStateRawValue()) - rank(current.getStateRawValue());
    if (byState != 0) {
        return byState > 0;
    }
    return candidate.getCreatedAt().isAfter(current.getCreatedAt());
}

The function that reads the subaccount's subscriptions and keeps one per card:

/** Every card of the subaccount with the state of its current subscription. */
export async function cardsWithState(astrada: Astrada, subaccountId: string): Promise<CardRow[]> {
  const byCard = new Map<string, CardSubscription>();
  for await (const subscription of astrada.cardSubscriptions.listAll({ subaccountId, expand: ['card'], limit: 100 })) {
    const current = byCard.get(subscription.cardId);
    if (current === undefined || better(subscription, current)) byCard.set(subscription.cardId, subscription);
  }
  return [...byCard.values()].map((subscription) => {
    const card = subscription._embedded?.card;
    return {
      cardId: subscription.cardId,
      last4: card?.last4digits,
      network: card?.network,
      expiry: card ? `${String(card.expiryMonth).padStart(2, '0')}/${card.expiryYear}` : undefined,
      state: subscription.state,
      subscriptionId: subscription.id,
      enrolledAt: subscription.createdAt,
    };
  });
}
def cards_with_state(client: astrada.Astrada, subaccount_id: str) -> List[CardRow]:
    """Every card of the subaccount with the state of its current subscription."""
    by_card: Dict[str, astrada.CardSubscription] = {}
    for subscription in client.card_subscriptions.list_all(
            subaccount_id=subaccount_id, expand=["card"], limit=100):
        current = by_card.get(str(subscription.card_id))
        if current is None or better(subscription, current):
            by_card[str(subscription.card_id)] = subscription
    rows = []
    for subscription in by_card.values():
        card = subscription.embedded.card if subscription.embedded else None
        rows.append(CardRow(
            card_id=str(subscription.card_id),
            last4=card.last4digits if card else None,
            network=card.network if card else None,
            expiry="%02d/%d" % (card.expiry_month, card.expiry_year) if card else None,
            state=subscription.state,
            subscription_id=str(subscription.id),
            enrolled_at=subscription.created_at.isoformat(),
        ))
    return rows
/** Every card of the subaccount with the state of its current subscription. */
public static List<CardRow> cardsWithState(ApiClient client, UUID subaccountId) {
    Map<UUID, CardSubscription> byCard = new LinkedHashMap<>();
    for (CardSubscription subscription : client.cardSubscriptions().listAll(ListCardSubscriptionsRequest.builder()
            .subaccountId(subaccountId).expand("card").limit(100).build())) {
        CardSubscription current = byCard.get(subscription.getCardId());
        if (current == null || better(subscription, current)) {
            byCard.put(subscription.getCardId(), subscription);
        }
    }
    List<CardRow> rows = new ArrayList<>();
    for (CardSubscription subscription : byCard.values()) {
        Card card = subscription.getEmbedded() == null ? null : subscription.getEmbedded().getCard();
        rows.add(new CardRow(
                subscription.getCardId(),
                card == null ? null : card.getLast4digits(),
                card == null || card.getNetwork() == null ? null : card.getNetwork().getValue(),
                card == null ? null : String.format("%02d/%d", card.getExpiryMonth(), card.getExpiryYear()),
                subscription.getStateRawValue(),
                subscription.getId(),
                subscription.getCreatedAt().toString()));
    }
    return rows;
}

Whole example files: TypeScript, Python, Java.

What to expect

You get one row per card, with its last four digits, network, expiry, the state of its current subscription, that subscription's id and when it was created. If a subscription comes back without its card under _embedded, the row has no last four digits, network or expiry.

Read more


Did this page help you?