Have your say in Community Polls: What was/is your greatest motivation to start your own business?

Re: How can I calculate remaining trial days in a Remix app with GraphQL?

How can I calculate remaining trial days in a Remix app with GraphQL?

Ionuts1
Shopify Partner
24 1 4

Hi guys, I'm currently develop a small app for shopify using cli 3.0 remix, now and now i'm stuck at trialDays, how i can get how many days are left?
What i'm trying right now to find a solution, i don't know if its the best solution for getting the remaining days from trial:
1. I do a query after customer approve the app:

query {
  currentAppInstallation {
    id
    activeSubscriptions {
      id
      trialDays
      currentPeriodEnd
      createdAt
    }
  }
}

2. And is getting the response:

"activeSubscriptions": [
        {
          "id": "gid://shopify/AppSubscription/xxxxxx",
          "trialDays": 1,
          "currentPeriodEnd": "2024-03-06T23:15:42Z",
          "createdAt": "2024-02-04T23:15:31Z"
        }
      ]

3. Start calculate the difference between createAt and currentPeriodEnd, but its weird because i have only 1 day as a trial and on the code from above its saying 2 days from 04-02-2024 to 06-02-2024.

I did some investigation but i find only this answer which looks what i really need but i can't used because is with Rest api and not GraphQL. "The trial ends on calculated based on the RecurringApplicationCharge's activation time."


It is possible to use rest api inside of remix.js? 


Reply 1 (1)

appaza
Shopify Partner
34 2 3
export const CalculateTrialStatus = (currentAppInstallation: any): string => {
  if (
    !currentAppInstallation ||
    !currentAppInstallation.activeSubscriptions ||
    currentAppInstallation.activeSubscriptions.length === 0
  ) {
    return "No active subscriptions";
  }

  const subscription = currentAppInstallation.activeSubscriptions[0];
  const currentPeriodEnd = new Date(subscription.currentPeriodEnd);
  const createdAt = new Date(subscription.createdAt);
  const trialDays = subscription.trialDays;

  // Calculate the remaining trial days
  const now = new Date();
  const elapsedMilliseconds = now.getTime() - createdAt.getTime();
  const elapsedDays = elapsedMilliseconds / (1000 * 60 * 60 * 24);
  let remainingTrialDays = trialDays - elapsedDays;

  // Adjust remaining trial days if past the current period end
  if (now > currentPeriodEnd) {
    remainingTrialDays = 0;
  }

  // Ensure remaining trial days is not negative
  remainingTrialDays = Math.max(0, remainingTrialDays);

  // Round remaining trial days to the nearest whole number
  remainingTrialDays = Math.round(remainingTrialDays);

  // Return appropriate message based on remaining trial days
  if (remainingTrialDays === 0) {
    return "Upgrade Now";
  } else {
    return `${remainingTrialDays} days trial`;
  }
};
Collaboration creates new things