One Pricing Plan per Member

For anyone wondering how to let your Members only have one Pricing Plan at a time: Here’s the code.

import { orders } from 'wix-pricing-plans-backend';

export async function wixPricingPlans_onOrderStarted(event) {
  const newPlanId = event.data.order._id;
  const memberId = event.data.order.buyer.memberId;

  console.log(`Neuer Plan gekauft: ${newPlanId} von Mitglied: ${memberId}`);

  try {
    const allOrders = await orders.listOrders();
    console.log(`Anzahl der Bestellungen insgesamt: ${allOrders.length}`);

    // Funktion zur Verarbeitung der Bestellungen
    const processOrders = async (ordersList) => {
      const activeMemberOrders = ordersList.filter(order => 
        order.buyer.memberId === memberId && order.status === 'ACTIVE'
      );
      
      console.log(`Anzahl der aktiven Bestellungen des Mitglieds: ${activeMemberOrders.length}`);
      
      for (const order of activeMemberOrders) {
        if (newPlanId !== order._id) {
          console.log(`Cancelle Bestellung: ${order._id}`);
          await orders.cancelOrder(order._id, 'IMMEDIATELY', { suppressAuth: true });
        } else {
          console.log(`Behalte Bestellung (neuer Plan): ${order._id}`);
        }
      }
    };

    
    await processOrders(allOrders);

  } catch (error) {
    console.error(`Fehler aufgetreten: ${error}`);
  }
}

→ Paste it into your events.js file and it should work just fine.

→ When a Member purchases a new Plan the code automatically cancels all existing (active) plans.

:bulb:This code is specifically for anyone, using the pricing plans app without additional code (using solely the regular pricing plan-pricing page)

3 Likes

Thanks for sharing!!!