Find subscription with an ending trial.

@return \Illuminate\Database\Eloquent\Builder
979643
public function scopeFindEndingTrial($query, $dayRange = 3)
    {
        $from = Carbon::now();
        $to = Carbon::now()->addDays($dayRange);

        $query->whereBetween('trial_ends_at', [$from, $to]);
    }
1104440
private function _cancel_trial() {
            $this->_logger->entrance();

            if ( ! $this->is_trial() ) {
                return (object) array(
                    'error' => (object) array(
                        'message' => $this->get_text_inline( 'It looks like you are not in trial mode anymore so there\'s nothing to cancel :)', 'trial-cancel-no-trial-message' )
                    )
                );
            }

            $trial_plan = $this->get_trial_plan();

            $api  = $this->get_api_site_scope();
            $site = $api->call( 'trials.json', 'delete' );

            $trial_cancelled = false;

            if ( $this->is_api_result_entity( $site ) ) {
                $prev_trial_ends = $this->_site->trial_ends;

                if ( $this->is_paid_trial() ) {
                    $this->_license->expiration   = $site->trial_ends;
                    $this->_license->is_cancelled = true;
                    $this->_update_site_license( $this->_license );
                    $this->_store_licenses();

                    // Clear subscription reference.
                    $this->_sync_site_subscription( null );
                }

                // Update site info.
                $this->_site = new FS_Site( $site );

                $trial_cancelled = ( $prev_trial_ends != $site->trial_ends );
            } else {
                // @todo handle different error cases.
            }

            if ( ! $trial_cancelled ) {
                return (object) array(
                    'error' => (object) array(
                        'message' => $this->get_text_inline( 'Seems like we are having some temporary issue with your trial cancellation. Please try again in few minutes.', 'trial-cancel-failure-message' )
                    )
                );
            }

            // Remove previous sticky messages about upgrade or trial (if exist).
            $this->_admin_notices->remove_sticky( array(
                'trial_started',
                'trial_promotion',
                'plan_upgraded',
            ) );

            // Store site updates.
            $this->_store_site();

            if ( ! $this->is_addon() ||
                 ! $this->deactivate_premium_only_addon_without_license( true )
            ) {
                $this->_admin_notices->add(
                    sprintf( $this->get_text_inline( 'Your %s free trial was successfully cancelled.', 'trial-cancel-message' ), $trial_plan->title )
                );
            }

            return $site;
        }
1335799
public function onGracePeriod()
	{
		if (! is_null($endsAt = $this->getSubscriptionEndDate())) {
			return Carbon::now()->lt(Carbon::instance($endsAt));
		} else {
			return false;
		}
	}
322759
public function onTrial($subscription = 'default', $plan = null)
    {
        if (func_num_args() === 0 && $this->onGenericTrial()) {
            return true;
        }

        $subscription = $this->subscription($subscription);

        if (is_null($plan)) {
            return $subscription && $subscription->onTrial();
        }

        return $subscription && $subscription->onTrial() &&
               $subscription->stripe_plan === $plan;
    }
280230
private function findLastRoute()
    {
        $method = $this->lastRouteMethod;
        $index = count($this->routes[$method])-1;

        return $this->routes[$method][$index];
    }
1065487
public function onGenericTrial(): bool
    {
        return $this->trial_ends_at && Carbon::now()->lt(Carbon::createFromFormat('Y-m-d H:i:s', $this->trial_ends_at));
    }
1044156
public function findOne() {
        $this->statementContext->setLimit(1);

        $statement = new SelectStatement();
        $statement->setStatementContext($this->statementContext);
        $statement->setCondition($this->condition);
        $sql = $statement->parse();

        $row = $this->connection->query($sql, $this->statementContext->getParameters());

        $this->clear();

        return $row;
    }
439761
public function swap($plan)
    {
        $subscription = $this->asStripeSubscription();

        $subscription->plan = $plan;

        $subscription->prorate = $this->prorate;

        $subscription->cancel_at_period_end = false;

        if (! is_null($this->billingCycleAnchor)) {
            $subscription->billing_cycle_anchor = $this->billingCycleAnchor;
        }

        // If no specific trial end date has been set, the default behavior should be
        // to maintain the current trial state, whether that is "active" or to run
        // the swap out with the exact number of days left on this current plan.
        if ($this->onTrial()) {
            $subscription->trial_end = $this->trial_ends_at->getTimestamp();
        } else {
            $subscription->trial_end = 'now';
        }

        // Again, if no explicit quantity was set, the default behaviors should be to
        // maintain the current quantity onto the new plan. This is a sensible one
        // that should be the expected behavior for most developers with Stripe.
        if ($this->quantity) {
            $subscription->quantity = $this->quantity;
        }

        $subscription->save();

        try {
            $this->user->invoice(['subscription' => $subscription->id]);
        } catch (StripeCard $exception) {
            // When the payment for the plan swap fails, we continue to let the user swap to the
            // new plan. This is because Stripe may attempt to retry the payment later on. If
            // all attempts to collect payment fail, webhooks will handle any update to it.
        }

        $this->fill([
            'stripe_plan' => $plan,
            'ends_at' => null,
        ])->save();

        return $this;
    }
1207869
protected function getLastMonth() {
        if (!$this->_lastMonth) {
            $this->_lastMonth = new LastMonthList($this->version, $this->solution['accountSid']);
        }

        return $this->_lastMonth;
    }
57954
private function buildFindFirst() {
        $method = new Object\Method();
        $method->setAccess('public');
        $method->setName('findFirst');
        $method->setDescription('Override parent so we have completion');
        $method->setStatic(true);
        $method->setReturnType('ChildModel|false');
        $parameter = new Object\Parameter();
        $parameter->setName('parameters');
        $parameter->setDefaultValue('null');
        $parameter->setDescription("Array of conditions or primary key.");
        $parameter->setType('array|int');
        $method->addParameter($parameter);
        $method->setContent('return parent::findFirst($parameters);');
        $this->getAbstractClass()->addMethod($method);

        $method = new Object\Method();
        $method->setAccess('public');
        $method->setName('findFirstInstance');
        $method->setDescription('This calls the findFirst method and is used for unit testing so that it is not a static method');
        $method->setReturnType('ChildModel|false');
        $parameter = new Object\Parameter();
        $parameter->setName('parameters');
        $parameter->setDefaultValue('null');
        $parameter->setDescription("Array of conditions or primary key.");
        $parameter->setType('array|int');
        $method->addParameter($parameter);
        $method->setContent('return $this->findFirst($parameters);');
        $this->getAbstractClass()->addMethod($method);
    }
745620
public function findLastPaper(Exercise $exercise, User $user)
    {
        return $this->createQueryBuilder('p')
            ->where('p.user = :user')
            ->andWhere('p.exercise = :exercise')
            ->orderBy('p.number', 'DESC')
            ->setMaxResults(1)
            ->setParameters([
                'user' => $user,
                'exercise' => $exercise,
            ])
            ->getQuery()
            ->getOneOrNullResult();
    }
783621
public function subscriptionEndsAt($ends = null)
    {
        if ($ends === null) {
            return $this->subscription_ends_at;
        } else {
            $this->subscription_ends_at = $ends;
            return $this;
        }
    }
213609
protected function GetReturnToLastStepURL()
    {
        $sLink = false;
        $oBackItem = $this->GetPreviousStep();
        if (!is_null($oBackItem)) {
            $sLink = $oBackItem->GetStepURL();
        }

        return $sLink;
    }
1289635
function is_paid_trial() {
            $this->_logger->entrance();

            if ( ! $this->is_trial() ) {
                return false;
            }

            return $this->has_active_valid_license() && ( $this->_site->trial_plan_id == $this->_license->plan_id );
        }
733247
public function getSubscription()
    {
        if (null === $this->_subscription) {
            $this->_subscription = Subscription::find()->id($this->subscriptionId)->one();
        }

        return $this->_subscription;
    }
449160
public function resume()
    {
        if (!$this->onGracePeriod()) {
            throw new LogicException('Unable to resume subscription that is not within grace period.');
        }

        $subscription = $this->asStripeSubscription();

        // To resume the subscription we need to set the plan parameter on the Stripe
        // subscription object. This will force Stripe to resume this subscription
        // where we left off. Then, we'll set the proper trial ending timestamp.
        $subscription->plan = $this->stripe_plan;

        if ($this->onTrial()) {
            $subscription->trial_end = $this->trial_ends_at->getTimestamp();
        } else {
            $subscription->trial_end = 'now';
        }

        $subscription->save();

        // Finally, we will remove the ending timestamp from the user's record in the
        // local database to indicate that the subscription is active again and is
        // no longer "cancelled". Then we will save this record in the database.
        $this->ends_at = null;
        $this->save();

        return $this;
    }
197337
public function finalReviewStepAction()
    {
        $request = $this->getCurrentRequest();
        $basket = $this->get('sonata.basket');

        $violations = $this
            ->get('validator')
            ->validate($basket, ['elements', 'delivery', 'payment']);

        if ($violations->count() > 0) {
            // basket not valid

            // todo : add flash message rendering in template
            foreach ($violations as $violation) {
                $this->get('session')->getFlashBag()->add('error', 'Error: '.$violation->getMessage());
            }

            return new RedirectResponse($this->generateUrl('sonata_basket_index'));
        }

        if ('POST' === $request->getMethod()) {
            if ($request->get('tac')) {
                // send the basket to the payment callback
                return $this->forward('SonataPaymentBundle:Payment:sendbank');
            }
        }

        $this->get('sonata.seo.page')->setTitle($this->get('translator')->trans('basket_review_title', [], 'SonataBasketBundle'));

        return $this->render('SonataBasketBundle:Basket:final_review_step.html.twig', [
            'basket' => $basket,
            'tac_error' => 'POST' === $request->getMethod(),
        ]);
    }