├── phpstan.neon.dist ├── config └── config.php ├── src ├── Traits │ ├── BelongsToPlan.php │ └── HasPlanSubscriptions.php ├── Console │ └── Commands │ │ ├── PublishCommand.php │ │ ├── RollbackCommand.php │ │ └── MigrateCommand.php ├── Providers │ └── SubscriptionsServiceProvider.php ├── Services │ └── Period.php └── Models │ ├── PlanSubscriptionUsage.php │ ├── PlanFeature.php │ ├── Plan.php │ └── PlanSubscription.php ├── LICENSE ├── database └── migrations │ ├── 2020_01_01_000002_create_plan_features_table.php │ ├── 2020_01_01_000004_create_plan_subscription_usage_table.php │ ├── 2020_01_01_000003_create_plan_subscriptions_table.php │ └── 2020_01_01_000001_create_plans_table.php ├── CONTRIBUTING.md ├── composer.json ├── CODE_OF_CONDUCT.md ├── CHANGELOG.md └── README.md /phpstan.neon.dist: -------------------------------------------------------------------------------- 1 | includes: 2 | - ./vendor/nunomaduro/larastan/extension.neon 3 | parameters: 4 | level: 5 5 | paths: 6 | - src 7 | -------------------------------------------------------------------------------- /config/config.php: -------------------------------------------------------------------------------- 1 | true, 9 | 10 | // Subscriptions Database Tables 11 | 'tables' => [ 12 | 13 | 'plans' => 'plans', 14 | 'plan_features' => 'plan_features', 15 | 'plan_subscriptions' => 'plan_subscriptions', 16 | 'plan_subscription_usage' => 'plan_subscription_usage', 17 | 18 | ], 19 | 20 | // Subscriptions Models 21 | 'models' => [ 22 | 23 | 'plan' => \Rinvex\Subscriptions\Models\Plan::class, 24 | 'plan_feature' => \Rinvex\Subscriptions\Models\PlanFeature::class, 25 | 'plan_subscription' => \Rinvex\Subscriptions\Models\PlanSubscription::class, 26 | 'plan_subscription_usage' => \Rinvex\Subscriptions\Models\PlanSubscriptionUsage::class, 27 | 28 | ], 29 | 30 | ]; 31 | -------------------------------------------------------------------------------- /src/Traits/BelongsToPlan.php: -------------------------------------------------------------------------------- 1 | belongsTo(config('rinvex.subscriptions.models.plan'), 'plan_id', 'id', 'plan'); 20 | } 21 | 22 | /** 23 | * Scope models by plan id. 24 | * 25 | * @param \Illuminate\Database\Eloquent\Builder $builder 26 | * @param int $planId 27 | * 28 | * @return \Illuminate\Database\Eloquent\Builder 29 | */ 30 | public function scopeByPlanId(Builder $builder, int $planId): Builder 31 | { 32 | return $builder->where('plan_id', $planId); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016-2021, Rinvex LLC, 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/Console/Commands/PublishCommand.php: -------------------------------------------------------------------------------- 1 | alert($this->description); 33 | 34 | collect($this->option('resource') ?: ['config', 'migrations'])->each(function ($resource) { 35 | $this->call('vendor:publish', ['--tag' => "rinvex/subscriptions::{$resource}", '--force' => $this->option('force')]); 36 | }); 37 | 38 | $this->line(''); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/Console/Commands/RollbackCommand.php: -------------------------------------------------------------------------------- 1 | alert($this->description); 33 | 34 | $path = config('rinvex.subscriptions.autoload_migrations') ? 35 | 'vendor/rinvex/laravel-subscriptions/database/migrations' : 36 | 'database/migrations/rinvex/laravel-subscriptions'; 37 | 38 | if (file_exists($path)) { 39 | $this->call('migrate:reset', [ 40 | '--path' => $path, 41 | '--force' => $this->option('force'), 42 | ]); 43 | } else { 44 | $this->warn('No migrations found! Consider publish them first: php artisan rinvex:publish:subscriptions'); 45 | } 46 | 47 | $this->line(''); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/Console/Commands/MigrateCommand.php: -------------------------------------------------------------------------------- 1 | alert($this->description); 33 | 34 | $path = config('rinvex.subscriptions.autoload_migrations') ? 35 | 'vendor/rinvex/laravel-subscriptions/database/migrations' : 36 | 'database/migrations/rinvex/laravel-subscriptions'; 37 | 38 | if (file_exists($path)) { 39 | $this->call('migrate', [ 40 | '--step' => true, 41 | '--path' => $path, 42 | '--force' => $this->option('force'), 43 | ]); 44 | } else { 45 | $this->warn('No migrations found! Consider publish them first: php artisan rinvex:publish:subscriptions'); 46 | } 47 | 48 | $this->line(''); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /database/migrations/2020_01_01_000002_create_plan_features_table.php: -------------------------------------------------------------------------------- 1 | increments('id'); 20 | $table->integer('plan_id')->unsigned(); 21 | $table->string('slug'); 22 | $table->json('name'); 23 | $table->json('description')->nullable(); 24 | $table->string('value'); 25 | $table->smallInteger('resettable_period')->unsigned()->default(0); 26 | $table->string('resettable_interval')->default('month'); 27 | $table->mediumInteger('sort_order')->unsigned()->default(0); 28 | $table->timestamps(); 29 | $table->softDeletes(); 30 | 31 | // Indexes 32 | $table->unique(['plan_id', 'slug']); 33 | $table->foreign('plan_id')->references('id')->on(config('rinvex.subscriptions.tables.plans')) 34 | ->onDelete('cascade')->onUpdate('cascade'); 35 | }); 36 | } 37 | 38 | /** 39 | * Reverse the migrations. 40 | * 41 | * @return void 42 | */ 43 | public function down(): void 44 | { 45 | Schema::dropIfExists(config('rinvex.subscriptions.tables.plan_features')); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /database/migrations/2020_01_01_000004_create_plan_subscription_usage_table.php: -------------------------------------------------------------------------------- 1 | increments('id'); 19 | $table->integer('subscription_id')->unsigned(); 20 | $table->integer('feature_id')->unsigned(); 21 | $table->smallInteger('used')->unsigned(); 22 | $table->dateTime('valid_until')->nullable(); 23 | $table->string('timezone')->nullable(); 24 | $table->timestamps(); 25 | $table->softDeletes(); 26 | 27 | $table->unique(['subscription_id', 'feature_id']); 28 | $table->foreign('subscription_id')->references('id')->on(config('rinvex.subscriptions.tables.plan_subscriptions')) 29 | ->onDelete('cascade')->onUpdate('cascade'); 30 | $table->foreign('feature_id')->references('id')->on(config('rinvex.subscriptions.tables.plan_features')) 31 | ->onDelete('cascade')->onUpdate('cascade'); 32 | }); 33 | } 34 | 35 | /** 36 | * Reverse the migrations. 37 | * 38 | * @return void 39 | */ 40 | public function down(): void 41 | { 42 | Schema::dropIfExists(config('rinvex.subscriptions.tables.plan_subscription_usage')); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /database/migrations/2020_01_01_000003_create_plan_subscriptions_table.php: -------------------------------------------------------------------------------- 1 | increments('id'); 19 | $table->morphs('subscriber'); 20 | $table->integer('plan_id')->unsigned(); 21 | $table->string('slug'); 22 | $table->json('name'); 23 | $table->json('description')->nullable(); 24 | $table->dateTime('trial_ends_at')->nullable(); 25 | $table->dateTime('starts_at')->nullable(); 26 | $table->dateTime('ends_at')->nullable(); 27 | $table->dateTime('cancels_at')->nullable(); 28 | $table->dateTime('canceled_at')->nullable(); 29 | $table->string('timezone')->nullable(); 30 | $table->timestamps(); 31 | $table->softDeletes(); 32 | 33 | // Indexes 34 | $table->unique('slug'); 35 | $table->foreign('plan_id')->references('id')->on(config('rinvex.subscriptions.tables.plans')) 36 | ->onDelete('cascade')->onUpdate('cascade'); 37 | }); 38 | } 39 | 40 | /** 41 | * Reverse the migrations. 42 | * 43 | * @return void 44 | */ 45 | public function down(): void 46 | { 47 | Schema::dropIfExists(config('rinvex.subscriptions.tables.plan_subscriptions')); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /database/migrations/2020_01_01_000001_create_plans_table.php: -------------------------------------------------------------------------------- 1 | increments('id'); 20 | $table->string('slug'); 21 | $table->json('name'); 22 | $table->json('description')->nullable(); 23 | $table->boolean('is_active')->default(true); 24 | $table->decimal('price')->default('0.00'); 25 | $table->decimal('signup_fee')->default('0.00'); 26 | $table->string('currency', 3); 27 | $table->smallInteger('trial_period')->unsigned()->default(0); 28 | $table->string('trial_interval')->default('day'); 29 | $table->smallInteger('invoice_period')->unsigned()->default(0); 30 | $table->string('invoice_interval')->default('month'); 31 | $table->smallInteger('grace_period')->unsigned()->default(0); 32 | $table->string('grace_interval')->default('day'); 33 | $table->tinyInteger('prorate_day')->unsigned()->nullable(); 34 | $table->tinyInteger('prorate_period')->unsigned()->nullable(); 35 | $table->tinyInteger('prorate_extend_due')->unsigned()->nullable(); 36 | $table->smallInteger('active_subscribers_limit')->unsigned()->nullable(); 37 | $table->mediumInteger('sort_order')->unsigned()->default(0); 38 | $table->timestamps(); 39 | $table->softDeletes(); 40 | 41 | // Indexes 42 | $table->unique('slug'); 43 | }); 44 | } 45 | 46 | /** 47 | * Reverse the migrations. 48 | * 49 | * @return void 50 | */ 51 | public function down(): void 52 | { 53 | Schema::dropIfExists(config('rinvex.subscriptions.tables.plans')); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guide 2 | 3 | This project adheres to the following standards and practices. 4 | 5 | 6 | ## Versioning 7 | 8 | This project is versioned under the [Semantic Versioning](http://semver.org/) guidelines as much as possible. 9 | 10 | Releases will be numbered with the following format: 11 | 12 | - `..` 13 | - `..` 14 | 15 | And constructed with the following guidelines: 16 | 17 | - Breaking backward compatibility bumps the major and resets the minor and patch. 18 | - New additions without breaking backward compatibility bump the minor and reset the patch. 19 | - Bug fixes and misc changes bump the patch. 20 | 21 | 22 | ## Pull Requests 23 | 24 | The pull request process differs for new features and bugs. 25 | 26 | Pull requests for bugs may be sent without creating any proposal issue. If you believe that you know of a solution for a bug that has been filed, please leave a comment detailing your proposed fix or create a pull request with the fix mentioning that issue id. 27 | 28 | 29 | ## Coding Standards 30 | 31 | This project follows the FIG PHP Standards Recommendations compliant with the [PSR-1: Basic Coding Standard](http://www.php-fig.org/psr/psr-1/), [PSR-2: Coding Style Guide](http://www.php-fig.org/psr/psr-2/) and [PSR-4: Autoloader](http://www.php-fig.org/psr/psr-4/) to ensure a high level of interoperability between shared PHP code. If you notice any compliance oversights, please send a patch via pull request. 32 | 33 | 34 | ## Feature Requests 35 | 36 | If you have a proposal or a feature request, you may create an issue with `[Proposal]` in the title. 37 | 38 | The proposal should also describe the new feature, as well as implementation ideas. The proposal will then be reviewed and either approved or denied. Once a proposal is approved, a pull request may be created implementing the new feature. 39 | 40 | 41 | ## Git Flow 42 | 43 | This project follows [Git-Flow](http://nvie.com/posts/a-successful-git-branching-model/), and as such has `master` (latest stable releases), `develop` (latest WIP development) and X.Y support branches (when there's multiple major versions). 44 | 45 | Accordingly all pull requests MUST be sent to the `develop` branch. 46 | 47 | > **Note:** Pull requests which do not follow these guidelines will be closed without any further notice. 48 | -------------------------------------------------------------------------------- /src/Providers/SubscriptionsServiceProvider.php: -------------------------------------------------------------------------------- 1 | 'command.rinvex.subscriptions.migrate', 28 | PublishCommand::class => 'command.rinvex.subscriptions.publish', 29 | RollbackCommand::class => 'command.rinvex.subscriptions.rollback', 30 | ]; 31 | 32 | /** 33 | * Register the application services. 34 | * 35 | * @return void 36 | */ 37 | public function register(): void 38 | { 39 | $this->mergeConfigFrom(realpath(__DIR__.'/../../config/config.php'), 'rinvex.subscriptions'); 40 | 41 | // Bind eloquent models to IoC container 42 | $this->registerModels([ 43 | 'rinvex.subscriptions.plan' => Plan::class, 44 | 'rinvex.subscriptions.plan_feature' => PlanFeature::class, 45 | 'rinvex.subscriptions.plan_subscription' => PlanSubscription::class, 46 | 'rinvex.subscriptions.plan_subscription_usage' => PlanSubscriptionUsage::class, 47 | ]); 48 | 49 | // Register console commands 50 | $this->registerCommands($this->commands); 51 | } 52 | 53 | /** 54 | * Bootstrap the application services. 55 | * 56 | * @return void 57 | */ 58 | public function boot(): void 59 | { 60 | // Publish Resources 61 | $this->publishesConfig('rinvex/laravel-subscriptions'); 62 | $this->publishesMigrations('rinvex/laravel-subscriptions'); 63 | ! $this->autoloadMigrations('rinvex/laravel-subscriptions') || $this->loadMigrationsFrom(__DIR__.'/../../database/migrations'); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/Services/Period.php: -------------------------------------------------------------------------------- 1 | interval = $interval; 51 | 52 | if (empty($start)) { 53 | $this->start = Carbon::now(); 54 | } elseif (! $start instanceof Carbon) { 55 | $this->start = new Carbon($start); 56 | } else { 57 | $this->start = $start; 58 | } 59 | 60 | $this->period = $count; 61 | $start = clone $this->start; 62 | $method = 'add'.ucfirst($this->interval).'s'; 63 | $this->end = $start->{$method}($this->period); 64 | } 65 | 66 | /** 67 | * Get start date. 68 | * 69 | * @return \Carbon\Carbon 70 | */ 71 | public function getStartDate(): Carbon 72 | { 73 | return $this->start; 74 | } 75 | 76 | /** 77 | * Get end date. 78 | * 79 | * @return \Carbon\Carbon 80 | */ 81 | public function getEndDate(): Carbon 82 | { 83 | return $this->end; 84 | } 85 | 86 | /** 87 | * Get period interval. 88 | * 89 | * @return string 90 | */ 91 | public function getInterval(): string 92 | { 93 | return $this->interval; 94 | } 95 | 96 | /** 97 | * Get period interval count. 98 | * 99 | * @return int 100 | */ 101 | public function getIntervalCount(): int 102 | { 103 | return $this->period; 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rinvex/laravel-subscriptions", 3 | "description": "Rinvex Subscriptions is a flexible plans and subscription management system for Laravel, with the required tools to run your SAAS like services efficiently. It's simple architecture, accompanied by powerful underlying to afford solid platform for your business.", 4 | "type": "library", 5 | "keywords": [ 6 | "plan", 7 | "value", 8 | "laravel", 9 | "feature", 10 | "database", 11 | "recurring", 12 | "subscription" 13 | ], 14 | "license": "MIT", 15 | "homepage": "https://rinvex.com", 16 | "support": { 17 | "email": "help@rinvex.com", 18 | "issues": "https://github.com/rinvex/laravel-subscriptions/issues", 19 | "source": "https://github.com/rinvex/laravel-subscriptions", 20 | "docs": "https://github.com/rinvex/laravel-subscriptions/blob/master/README.md" 21 | }, 22 | "authors": [ 23 | { 24 | "name": "Rinvex LLC", 25 | "homepage": "https://rinvex.com", 26 | "email": "help@rinvex.com" 27 | }, 28 | { 29 | "name": "Abdelrahman Omran", 30 | "homepage": "https://omranic.com", 31 | "email": "me@omranic.com", 32 | "role": "Project Lead" 33 | }, 34 | { 35 | "name": "The Generous Laravel Community", 36 | "homepage": "https://github.com/rinvex/laravel-subscriptions/contributors" 37 | } 38 | ], 39 | "require": { 40 | "php": "^8.0.0", 41 | "illuminate/console": "^9.0.0 || ^10.0.0", 42 | "illuminate/database": "^9.0.0 || ^10.0.0", 43 | "illuminate/support": "^9.0.0 || ^10.0.0", 44 | "rinvex/laravel-support": "^6.0.0", 45 | "spatie/eloquent-sortable": "^4.0.0", 46 | "spatie/laravel-sluggable": "^3.3.0", 47 | "spatie/laravel-translatable": "^5.2.0" 48 | }, 49 | "require-dev": { 50 | "codedungeon/phpunit-result-printer": "^0.31.0", 51 | "illuminate/container": "^9.0.0 || ^10.0.0", 52 | "phpunit/phpunit": "^9.5.0" 53 | }, 54 | "autoload": { 55 | "psr-4": { 56 | "Rinvex\\Subscriptions\\": "src" 57 | } 58 | }, 59 | "autoload-dev": { 60 | "psr-4": { 61 | "Rinvex\\Subscriptions\\Tests\\": "tests" 62 | } 63 | }, 64 | "scripts": { 65 | "test": "vendor/bin/phpunit" 66 | }, 67 | "config": { 68 | "sort-packages": true, 69 | "preferred-install": "dist", 70 | "optimize-autoloader": true 71 | }, 72 | "extra": { 73 | "laravel": { 74 | "providers": [ 75 | "Rinvex\\Subscriptions\\Providers\\SubscriptionsServiceProvider" 76 | ] 77 | } 78 | }, 79 | "minimum-stability": "dev", 80 | "prefer-stable": true 81 | } 82 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, gender identity and expression, level of experience, 9 | nationality, personal appearance, race, religion, or sexual identity and 10 | orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at [help@rinvex.com](mailto:help@rinvex.com). All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at [http://contributor-covenant.org/version/1/4][version] 72 | 73 | [homepage]: http://contributor-covenant.org 74 | [version]: http://contributor-covenant.org/version/1/4/ 75 | -------------------------------------------------------------------------------- /src/Traits/HasPlanSubscriptions.php: -------------------------------------------------------------------------------- 1 | planSubscriptions()->delete(); 38 | }); 39 | } 40 | 41 | /** 42 | * The subscriber may have many plan subscriptions. 43 | * 44 | * @return \Illuminate\Database\Eloquent\Relations\MorphMany 45 | */ 46 | public function planSubscriptions(): MorphMany 47 | { 48 | return $this->morphMany(config('rinvex.subscriptions.models.plan_subscription'), 'subscriber', 'subscriber_type', 'subscriber_id'); 49 | } 50 | 51 | /** 52 | * A model may have many active plan subscriptions. 53 | * 54 | * @return \Illuminate\Database\Eloquent\Collection 55 | */ 56 | public function activePlanSubscriptions(): Collection 57 | { 58 | return $this->planSubscriptions->reject->inactive(); 59 | } 60 | 61 | /** 62 | * Get a plan subscription by slug. 63 | * 64 | * @param string $subscriptionSlug 65 | * 66 | * @return \Rinvex\Subscriptions\Models\PlanSubscription|null 67 | */ 68 | public function planSubscription(string $subscriptionSlug): ?PlanSubscription 69 | { 70 | return $this->planSubscriptions()->where('slug', $subscriptionSlug)->first(); 71 | } 72 | 73 | /** 74 | * Get subscribed plans. 75 | * 76 | * @return \Illuminate\Database\Eloquent\Collection 77 | */ 78 | public function subscribedPlans(): Collection 79 | { 80 | $planIds = $this->planSubscriptions->reject->inactive()->pluck('plan_id')->unique(); 81 | 82 | return app('rinvex.subscriptions.plan')->whereIn('id', $planIds)->get(); 83 | } 84 | 85 | /** 86 | * Check if the subscriber subscribed to the given plan. 87 | * 88 | * @param int $planId 89 | * 90 | * @return bool 91 | */ 92 | public function subscribedTo($planId): bool 93 | { 94 | $subscription = $this->planSubscriptions()->where('plan_id', $planId)->first(); 95 | 96 | return $subscription && $subscription->active(); 97 | } 98 | 99 | /** 100 | * Subscribe subscriber to a new plan. 101 | * 102 | * @param string $subscription 103 | * @param \Rinvex\Subscriptions\Models\Plan $plan 104 | * @param \Carbon\Carbon|null $startDate 105 | * 106 | * @return \Rinvex\Subscriptions\Models\PlanSubscription 107 | */ 108 | public function newPlanSubscription($subscription, Plan $plan, Carbon $startDate = null): PlanSubscription 109 | { 110 | $trial = new Period($plan->trial_interval, $plan->trial_period, $startDate ?? now()); 111 | $period = new Period($plan->invoice_interval, $plan->invoice_period, $trial->getEndDate()); 112 | 113 | return $this->planSubscriptions()->create([ 114 | 'name' => $subscription, 115 | 'plan_id' => $plan->getKey(), 116 | 'trial_ends_at' => $trial->getEndDate(), 117 | 'starts_at' => $period->getStartDate(), 118 | 'ends_at' => $period->getEndDate(), 119 | ]); 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/Models/PlanSubscriptionUsage.php: -------------------------------------------------------------------------------- 1 | 'integer', 61 | 'feature_id' => 'integer', 62 | 'used' => 'integer', 63 | 'valid_until' => 'datetime', 64 | 'deleted_at' => 'datetime', 65 | ]; 66 | 67 | /** 68 | * {@inheritdoc} 69 | */ 70 | protected $observables = [ 71 | 'validating', 72 | 'validated', 73 | ]; 74 | 75 | /** 76 | * The default rules that the model will validate against. 77 | * 78 | * @var array 79 | */ 80 | protected $rules = []; 81 | 82 | /** 83 | * Whether the model should throw a 84 | * ValidationException if it fails validation. 85 | * 86 | * @var bool 87 | */ 88 | protected $throwValidationExceptions = true; 89 | 90 | /** 91 | * Create a new Eloquent model instance. 92 | * 93 | * @param array $attributes 94 | */ 95 | public function __construct(array $attributes = []) 96 | { 97 | $this->setTable(config('rinvex.subscriptions.tables.plan_subscription_usage')); 98 | $this->mergeRules([ 99 | 'subscription_id' => 'required|integer|exists:'.config('rinvex.subscriptions.tables.plan_subscriptions').',id', 100 | 'feature_id' => 'required|integer|exists:'.config('rinvex.subscriptions.tables.plan_features').',id', 101 | 'used' => 'required|integer', 102 | 'valid_until' => 'nullable|date', 103 | ]); 104 | 105 | parent::__construct($attributes); 106 | } 107 | 108 | /** 109 | * Subscription usage always belongs to a plan feature. 110 | * 111 | * @return \Illuminate\Database\Eloquent\Relations\BelongsTo 112 | */ 113 | public function feature(): BelongsTo 114 | { 115 | return $this->belongsTo(config('rinvex.subscriptions.models.plan_feature'), 'feature_id', 'id', 'feature'); 116 | } 117 | 118 | /** 119 | * Subscription usage always belongs to a plan subscription. 120 | * 121 | * @return \Illuminate\Database\Eloquent\Relations\BelongsTo 122 | */ 123 | public function subscription(): BelongsTo 124 | { 125 | return $this->belongsTo(config('rinvex.subscriptions.models.plan_subscription'), 'subscription_id', 'id', 'subscription'); 126 | } 127 | 128 | /** 129 | * Scope subscription usage by feature slug. 130 | * 131 | * @param \Illuminate\Database\Eloquent\Builder $builder 132 | * @param string $featureSlug 133 | * 134 | * @return \Illuminate\Database\Eloquent\Builder 135 | */ 136 | public function scopeByFeatureSlug(Builder $builder, string $featureSlug): Builder 137 | { 138 | $feature = app('rinvex.subscriptions.plan_feature')->where('slug', $featureSlug)->first(); 139 | 140 | return $builder->where('feature_id', $feature ? $feature->getKey() : null); 141 | } 142 | 143 | /** 144 | * Check whether usage has been expired or not. 145 | * 146 | * @return bool 147 | */ 148 | public function expired(): bool 149 | { 150 | if (is_null($this->valid_until)) { 151 | return false; 152 | } 153 | 154 | return Carbon::now()->gte($this->valid_until); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/Models/PlanFeature.php: -------------------------------------------------------------------------------- 1 | 'integer', 84 | 'slug' => 'string', 85 | 'value' => 'string', 86 | 'resettable_period' => 'integer', 87 | 'resettable_interval' => 'string', 88 | 'sort_order' => 'integer', 89 | 'deleted_at' => 'datetime', 90 | ]; 91 | 92 | /** 93 | * {@inheritdoc} 94 | */ 95 | protected $observables = [ 96 | 'validating', 97 | 'validated', 98 | ]; 99 | 100 | /** 101 | * The attributes that are translatable. 102 | * 103 | * @var array 104 | */ 105 | public $translatable = [ 106 | 'name', 107 | 'description', 108 | ]; 109 | 110 | /** 111 | * The sortable settings. 112 | * 113 | * @var array 114 | */ 115 | public $sortable = [ 116 | 'order_column_name' => 'sort_order', 117 | ]; 118 | 119 | /** 120 | * The default rules that the model will validate against. 121 | * 122 | * @var array 123 | */ 124 | protected $rules = []; 125 | 126 | /** 127 | * Whether the model should throw a 128 | * ValidationException if it fails validation. 129 | * 130 | * @var bool 131 | */ 132 | protected $throwValidationExceptions = true; 133 | 134 | /** 135 | * Create a new Eloquent model instance. 136 | * 137 | * @param array $attributes 138 | */ 139 | public function __construct(array $attributes = []) 140 | { 141 | $this->setTable(config('rinvex.subscriptions.tables.plan_features')); 142 | $this->mergeRules([ 143 | 'plan_id' => 'required|integer|exists:'.config('rinvex.subscriptions.tables.plans').',id', 144 | 'slug' => 'required|alpha_dash|max:150|unique:'.config('rinvex.subscriptions.tables.plan_features').',slug', 145 | 'name' => 'required|string|strip_tags|max:150', 146 | 'description' => 'nullable|string|max:32768', 147 | 'value' => 'required|string', 148 | 'resettable_period' => 'sometimes|integer', 149 | 'resettable_interval' => 'sometimes|in:hour,day,week,month', 150 | 'sort_order' => 'nullable|integer|max:100000', 151 | ]); 152 | 153 | parent::__construct($attributes); 154 | } 155 | 156 | /** 157 | * {@inheritdoc} 158 | */ 159 | protected static function boot() 160 | { 161 | parent::boot(); 162 | 163 | static::deleted(function ($plan_feature) { 164 | $plan_feature->usage()->delete(); 165 | }); 166 | } 167 | 168 | /** 169 | * Get the options for generating the slug. 170 | * 171 | * @return \Spatie\Sluggable\SlugOptions 172 | */ 173 | public function getSlugOptions(): SlugOptions 174 | { 175 | return SlugOptions::create() 176 | ->doNotGenerateSlugsOnUpdate() 177 | ->generateSlugsFrom('name') 178 | ->saveSlugsTo('slug'); 179 | } 180 | 181 | /** 182 | * The plan feature may have many subscription usage. 183 | * 184 | * @return \Illuminate\Database\Eloquent\Relations\HasMany 185 | */ 186 | public function usage(): HasMany 187 | { 188 | return $this->hasMany(config('rinvex.subscriptions.models.plan_subscription_usage'), 'feature_id', 'id'); 189 | } 190 | 191 | /** 192 | * Get feature's reset date. 193 | * 194 | * @param string $dateFrom 195 | * 196 | * @return \Carbon\Carbon 197 | */ 198 | public function getResetDate(Carbon $dateFrom): Carbon 199 | { 200 | $period = new Period($this->resettable_interval, $this->resettable_period, $dateFrom ?? now()); 201 | 202 | return $period->getEndDate(); 203 | } 204 | } 205 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Rinvex Subscriptions Change Log 2 | 3 | All notable changes to this project will be documented in this file. 4 | 5 | This project adheres to [Semantic Versioning](CONTRIBUTING.md). 6 | 7 | 8 | ## [v6.1.0] - 2022-02-14 9 | - Update composer dependencies to Laravel v9 10 | - Add support for model HasFactory 11 | - Feature to find active subscriptions for a user (#173) 12 | 13 | ## [v6.0.1] - 2021-12-15 14 | - Soft deleting children models on soft deleting parent models 15 | - Update the required packages 16 | 17 | ## [v6.0.0] - 2021-08-22 18 | - Drop PHP v7 support, and upgrade rinvex package dependencies to next major version 19 | - Update composer dependencies 20 | - Merge rules instead of resetting, to allow adequate model override 21 | - Fix constructor initialization order (fill attributes should come next after merging fillables & rules) 22 | - Drop old MySQL versions support that doesn't support json columns 23 | - Upgrade to GitHub-native Dependabot 24 | 25 | ## [v5.0.3] - 2021-03-15 26 | - Changes in doc to reflect new ofSubscriber breaking change 27 | - Utilize `SoftDeletes` functionality (fix #142) 28 | - Update hardcoded model to use service container IoC 29 | - Add period regardless if it's 0 or more, this should be fine 30 | - Check if there's usage or not (fix #26 & #138) 31 | 32 | ## [v5.0.2] - 2021-02-19 33 | - Define morphMany parameters explicitly 34 | - Simplify service provider model registration into IoC 35 | - Add startDate optional parameter to new subscription creation (fix #79) 36 | - Fix FeatureSlug confused with FeatureName by mistake (fix #43 #48 #62 #65 #136 #137) 37 | - Breaking Change: Rename "User" to "Subscriber" for more generic naming convention (fix #63) 38 | 39 | ## [v5.0.1] - 2020-12-25 40 | - Add support for PHP v8 41 | 42 | ## [v5.0.0] - 2020-12-22 43 | - Upgrade to Laravel v8 44 | - Update validation rules 45 | 46 | ## [v4.1.0] - 2020-06-15 47 | - Update validation rules 48 | - Drop using rinvex/laravel-cacheable from core packages for more flexibility 49 | - Caching should be handled on the application layer, not enforced from the core packages 50 | - Drop PHP 7.2 & 7.3 support from travis 51 | 52 | ## [v4.0.6] - 2020-05-30 53 | - Remove default indent size config 54 | - Add strip_tags validation rule to string fields 55 | - Specify events queue 56 | - Explicitly specify relationship attributes 57 | - Add strip_tags validation rule 58 | - Explicitly define relationship name 59 | 60 | ## [v4.0.5] - 2020-04-12 61 | - Fix ServiceProvider registerCommands method compatibility 62 | 63 | ## [v4.0.4] - 2020-04-09 64 | - Tweak artisan command registration 65 | - Reverse commit "Convert database int fields into bigInteger" 66 | - Refactor publish command and allow multiple resource values 67 | 68 | ## [v4.0.3] - 2020-04-04 69 | - Fix namespace issue 70 | 71 | ## [v4.0.2] - 2020-04-04 72 | - Enforce consistent artisan command tag namespacing 73 | - Enforce consistent package namespace 74 | - Drop laravel/helpers usage as it's no longer used 75 | 76 | ## [v4.0.1] - 2020-03-20 77 | - Convert into bigInteger database fields 78 | - Add shortcut -f (force) for artisan publish commands 79 | - Fix migrations path 80 | 81 | ## [v4.0.0] - 2020-03-15 82 | - Upgrade to Laravel v7.1.x & PHP v7.4.x 83 | 84 | ## [v3.0.2] - 2020-03-13 85 | - Tweak TravisCI config 86 | - Add migrations autoload option to the package 87 | - Tweak service provider `publishesResources` 88 | - Remove indirect composer dependency 89 | - Drop using global helpers 90 | - Update StyleCI config 91 | 92 | ## [v3.0.1] - 2019-12-18 93 | - Fix `migrate:reset` args as it doesn't accept --step 94 | 95 | ## [v3.0.0] - 2019-09-23 96 | - Upgrade to Laravel v6 and update dependencies 97 | 98 | ## [v2.1.1] - 2019-06-03 99 | - Enforce latest composer package versions 100 | 101 | ## [v2.1.0] - 2019-06-02 102 | - Update composer deps 103 | - Drop PHP 7.1 travis test 104 | - Refactor migrations and artisan commands, and tweak service provider publishes functionality 105 | - Fix wrong container binding: 106 | - app('rinvex.subscriptions.plan_features') => app('rinvex.subscriptions.plan_feature') 107 | - app('rinvex.subscriptions.plan_subscriptions') => app('rinvex.subscriptions.plan_subscription') 108 | 109 | ## [v2.0.0] - 2019-03-03 110 | - Require PHP 7.2 & Laravel 5.8 111 | 112 | ## [v1.0.2] - 2018-12-30 113 | - Rinvex\Subscriptions\Services\Period: adding interval received as parameter in constructor to property ->interval 114 | 115 | ## [v1.0.1] - 2018-12-22 116 | - Update composer dependencies 117 | - Add PHP 7.3 support to travis 118 | - Fix MySQL / PostgreSQL json column compatibility 119 | 120 | ## [v1.0.0] - 2018-10-01 121 | - Enforce Consistency 122 | - Support Laravel 5.7+ 123 | - Rename package to rinvex/laravel-subscriptions 124 | 125 | ## [v0.0.4] - 2018-09-21 126 | - Update travis php versions 127 | - Define polymorphic relationship parameters explicitly 128 | - Fix fully qualified booking unit methods (fix #20) 129 | - Convert timestamps into datetime fields and add timezone 130 | - Tweak validation rules 131 | - Drop StyleCI multi-language support (paid feature now!) 132 | - Update composer dependencies 133 | - Prepare and tweak testing configuration 134 | - Update StyleCI options 135 | - Update PHPUnit options 136 | - Rename subscription model activation and deactivation methods 137 | 138 | ## [v0.0.3] - 2018-02-18 139 | - Add PublishCommand to artisan 140 | - Move slug auto generation to the custom HasSlug trait 141 | - Add Rollback Console Command 142 | - Add missing composer dependencies 143 | - Remove useless scopes 144 | - Add PHPUnitPrettyResultPrinter 145 | - Use Carbon global helper 146 | - Update composer dependencies 147 | - Update supplementary files 148 | - Use ->getKey() method instead of ->id 149 | - Typehint method returns 150 | - Drop useless model contracts (models already swappable through IoC) 151 | - Add Laravel v5.6 support 152 | - Simplify IoC binding 153 | - Add force option to artisan commands 154 | - Refactor user_id to a polymorphic relation 155 | - Rename PlanSubscriber trait to HasSubscriptions 156 | - Rename polymorphic relation customer to user 157 | - Rename polymorphic relation customer to user 158 | - Convert interval column data type into string from character 159 | 160 | ## [v0.0.2] - 2017-09-08 161 | - Fix many issues and apply many enhancements 162 | - Rename package rinvex/laravel-subscriptions from rinvex/subscribable 163 | 164 | ## v0.0.1 - 2017-06-29 165 | - Tag first release 166 | 167 | [v6.1.0]: https://github.com/rinvex/laravel-subscriptions/compare/v6.0.1...v6.1.0 168 | [v6.0.1]: https://github.com/rinvex/laravel-subscriptions/compare/v6.0.0...v6.0.1 169 | [v6.0.0]: https://github.com/rinvex/laravel-subscriptions/compare/v5.0.3...v6.0.0 170 | [v5.0.3]: https://github.com/rinvex/laravel-subscriptions/compare/v5.0.2...v5.0.3 171 | [v5.0.2]: https://github.com/rinvex/laravel-subscriptions/compare/v5.0.1...v5.0.2 172 | [v5.0.1]: https://github.com/rinvex/laravel-subscriptions/compare/v5.0.0...v5.0.1 173 | [v5.0.0]: https://github.com/rinvex/laravel-subscriptions/compare/v4.1.0...v5.0.0 174 | [v4.1.0]: https://github.com/rinvex/laravel-subscriptions/compare/v4.0.6...v4.1.0 175 | [v4.0.6]: https://github.com/rinvex/laravel-subscriptions/compare/v4.0.5...v4.0.6 176 | [v4.0.5]: https://github.com/rinvex/laravel-subscriptions/compare/v4.0.4...v4.0.5 177 | [v4.0.4]: https://github.com/rinvex/laravel-subscriptions/compare/v4.0.3...v4.0.4 178 | [v4.0.3]: https://github.com/rinvex/laravel-subscriptions/compare/v4.0.2...v4.0.3 179 | [v4.0.2]: https://github.com/rinvex/laravel-subscriptions/compare/v4.0.1...v4.0.2 180 | [v4.0.1]: https://github.com/rinvex/laravel-subscriptions/compare/v4.0.0...v4.0.1 181 | [v4.0.0]: https://github.com/rinvex/laravel-subscriptions/compare/v3.0.2...v4.0.0 182 | [v3.0.2]: https://github.com/rinvex/laravel-subscriptions/compare/v3.0.1...v3.0.2 183 | [v3.0.1]: https://github.com/rinvex/laravel-subscriptions/compare/v3.0.0...v3.0.1 184 | [v3.0.0]: https://github.com/rinvex/laravel-subscriptions/compare/v2.1.1...v3.0.0 185 | [v2.1.1]: https://github.com/rinvex/laravel-subscriptions/compare/v2.1.0...v2.1.1 186 | [v2.1.0]: https://github.com/rinvex/laravel-subscriptions/compare/v2.0.0...v2.1.0 187 | [v2.0.0]: https://github.com/rinvex/laravel-subscriptions/compare/v1.0.2...v2.0.0 188 | [v1.0.2]: https://github.com/rinvex/laravel-subscriptions/compare/v1.0.1...v1.0.2 189 | [v1.0.1]: https://github.com/rinvex/laravel-subscriptions/compare/v1.0.0...v1.0.1 190 | [v1.0.0]: https://github.com/rinvex/laravel-subscriptions/compare/v0.0.4...v1.0.0 191 | [v0.0.4]: https://github.com/rinvex/laravel-subscriptions/compare/v0.0.3...v0.0.4 192 | [v0.0.3]: https://github.com/rinvex/laravel-subscriptions/compare/v0.0.2...v0.0.3 193 | [v0.0.2]: https://github.com/rinvex/laravel-subscriptions/compare/v0.0.1...v0.0.2 194 | -------------------------------------------------------------------------------- /src/Models/Plan.php: -------------------------------------------------------------------------------- 1 | 'string', 109 | 'is_active' => 'boolean', 110 | 'price' => 'float', 111 | 'signup_fee' => 'float', 112 | 'currency' => 'string', 113 | 'trial_period' => 'integer', 114 | 'trial_interval' => 'string', 115 | 'invoice_period' => 'integer', 116 | 'invoice_interval' => 'string', 117 | 'grace_period' => 'integer', 118 | 'grace_interval' => 'string', 119 | 'prorate_day' => 'integer', 120 | 'prorate_period' => 'integer', 121 | 'prorate_extend_due' => 'integer', 122 | 'active_subscribers_limit' => 'integer', 123 | 'sort_order' => 'integer', 124 | 'deleted_at' => 'datetime', 125 | ]; 126 | 127 | /** 128 | * {@inheritdoc} 129 | */ 130 | protected $observables = [ 131 | 'validating', 132 | 'validated', 133 | ]; 134 | 135 | /** 136 | * The attributes that are translatable. 137 | * 138 | * @var array 139 | */ 140 | public $translatable = [ 141 | 'name', 142 | 'description', 143 | ]; 144 | 145 | /** 146 | * The sortable settings. 147 | * 148 | * @var array 149 | */ 150 | public $sortable = [ 151 | 'order_column_name' => 'sort_order', 152 | ]; 153 | 154 | /** 155 | * The default rules that the model will validate against. 156 | * 157 | * @var array 158 | */ 159 | protected $rules = []; 160 | 161 | /** 162 | * Whether the model should throw a 163 | * ValidationException if it fails validation. 164 | * 165 | * @var bool 166 | */ 167 | protected $throwValidationExceptions = true; 168 | 169 | /** 170 | * Create a new Eloquent model instance. 171 | * 172 | * @param array $attributes 173 | */ 174 | public function __construct(array $attributes = []) 175 | { 176 | $this->setTable(config('rinvex.subscriptions.tables.plans')); 177 | $this->mergeRules([ 178 | 'slug' => 'required|alpha_dash|max:150|unique:'.config('rinvex.subscriptions.tables.plans').',slug', 179 | 'name' => 'required|string|strip_tags|max:150', 180 | 'description' => 'nullable|string|max:32768', 181 | 'is_active' => 'sometimes|boolean', 182 | 'price' => 'required|numeric', 183 | 'signup_fee' => 'required|numeric', 184 | 'currency' => 'required|alpha|size:3', 185 | 'trial_period' => 'sometimes|integer|max:100000', 186 | 'trial_interval' => 'sometimes|in:hour,day,week,month', 187 | 'invoice_period' => 'sometimes|integer|max:100000', 188 | 'invoice_interval' => 'sometimes|in:hour,day,week,month', 189 | 'grace_period' => 'sometimes|integer|max:100000', 190 | 'grace_interval' => 'sometimes|in:hour,day,week,month', 191 | 'sort_order' => 'nullable|integer|max:100000', 192 | 'prorate_day' => 'nullable|integer|max:150', 193 | 'prorate_period' => 'nullable|integer|max:150', 194 | 'prorate_extend_due' => 'nullable|integer|max:150', 195 | 'active_subscribers_limit' => 'nullable|integer|max:100000', 196 | ]); 197 | 198 | parent::__construct($attributes); 199 | } 200 | 201 | /** 202 | * {@inheritdoc} 203 | */ 204 | protected static function boot() 205 | { 206 | parent::boot(); 207 | 208 | static::deleted(function ($plan) { 209 | $plan->features()->delete(); 210 | $plan->planSubscriptions()->delete(); 211 | }); 212 | } 213 | 214 | /** 215 | * Get the options for generating the slug. 216 | * 217 | * @return \Spatie\Sluggable\SlugOptions 218 | */ 219 | public function getSlugOptions(): SlugOptions 220 | { 221 | return SlugOptions::create() 222 | ->doNotGenerateSlugsOnUpdate() 223 | ->generateSlugsFrom('name') 224 | ->saveSlugsTo('slug'); 225 | } 226 | 227 | /** 228 | * The plan may have many features. 229 | * 230 | * @return \Illuminate\Database\Eloquent\Relations\HasMany 231 | */ 232 | public function features(): HasMany 233 | { 234 | return $this->hasMany(config('rinvex.subscriptions.models.plan_feature'), 'plan_id', 'id'); 235 | } 236 | 237 | /** 238 | * The plan may have many subscriptions. 239 | * 240 | * @return \Illuminate\Database\Eloquent\Relations\HasMany 241 | */ 242 | public function subscriptions(): HasMany 243 | { 244 | return $this->hasMany(config('rinvex.subscriptions.models.plan_subscription'), 'plan_id', 'id'); 245 | } 246 | 247 | /** 248 | * Check if plan is free. 249 | * 250 | * @return bool 251 | */ 252 | public function isFree(): bool 253 | { 254 | return (float) $this->price <= 0.00; 255 | } 256 | 257 | /** 258 | * Check if plan has trial. 259 | * 260 | * @return bool 261 | */ 262 | public function hasTrial(): bool 263 | { 264 | return $this->trial_period && $this->trial_interval; 265 | } 266 | 267 | /** 268 | * Check if plan has grace. 269 | * 270 | * @return bool 271 | */ 272 | public function hasGrace(): bool 273 | { 274 | return $this->grace_period && $this->grace_interval; 275 | } 276 | 277 | /** 278 | * Get plan feature by the given slug. 279 | * 280 | * @param string $featureSlug 281 | * 282 | * @return \Rinvex\Subscriptions\Models\PlanFeature|null 283 | */ 284 | public function getFeatureBySlug(string $featureSlug): ?PlanFeature 285 | { 286 | return $this->features()->where('slug', $featureSlug)->first(); 287 | } 288 | 289 | /** 290 | * Activate the plan. 291 | * 292 | * @return $this 293 | */ 294 | public function activate() 295 | { 296 | $this->update(['is_active' => true]); 297 | 298 | return $this; 299 | } 300 | 301 | /** 302 | * Deactivate the plan. 303 | * 304 | * @return $this 305 | */ 306 | public function deactivate() 307 | { 308 | $this->update(['is_active' => false]); 309 | 310 | return $this; 311 | } 312 | } 313 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rinvex Subscriptions 2 | 3 | ⚠️ This package is abandoned and no longer maintained. No replacement package was suggested. ⚠️ 4 | 5 | 👉 If you are interested to step on as the main maintainer of this package, please [reach out to me](https://twitter.com/omranic)! 6 | 7 | --- 8 | 9 | **Rinvex Subscriptions** is a flexible plans and subscription management system for Laravel, with the required tools to run your SAAS like services efficiently. It's simple architecture, accompanied by powerful underlying to afford solid platform for your business. 10 | 11 | [![Packagist](https://img.shields.io/packagist/v/rinvex/laravel-subscriptions.svg?label=Packagist&style=flat-square)](https://packagist.org/packages/rinvex/laravel-subscriptions) 12 | [![Scrutinizer Code Quality](https://img.shields.io/scrutinizer/g/rinvex/laravel-subscriptions.svg?label=Scrutinizer&style=flat-square)](https://scrutinizer-ci.com/g/rinvex/laravel-subscriptions/) 13 | [![Travis](https://img.shields.io/travis/rinvex/laravel-subscriptions.svg?label=TravisCI&style=flat-square)](https://travis-ci.org/rinvex/laravel-subscriptions) 14 | [![StyleCI](https://styleci.io/repos/93313402/shield)](https://styleci.io/repos/93313402) 15 | [![License](https://img.shields.io/packagist/l/rinvex/laravel-subscriptions.svg?label=License&style=flat-square)](https://github.com/rinvex/laravel-subscriptions/blob/develop/LICENSE) 16 | 17 | 18 | ## Considerations 19 | 20 | - Payments are out of scope for this package. 21 | - You may want to extend some of the core models, in case you need to override the logic behind some helper methods like `renew()`, `cancel()` etc. E.g.: when cancelling a subscription you may want to also cancel the recurring payment attached. 22 | 23 | 24 | ## Installation 25 | 26 | 1. Install the package via composer: 27 | ```shell 28 | composer require rinvex/laravel-subscriptions 29 | ``` 30 | 31 | 2. Publish resources (migrations and config files): 32 | ```shell 33 | php artisan rinvex:publish:subscriptions 34 | ``` 35 | 36 | 3. Execute migrations via the following command: 37 | ```shell 38 | php artisan rinvex:migrate:subscriptions 39 | ``` 40 | 41 | 4. Done! 42 | 43 | 44 | ## Usage 45 | 46 | ### Add Subscriptions to User model 47 | 48 | **Rinvex Subscriptions** has been specially made for Eloquent and simplicity has been taken very serious as in any other Laravel related aspect. To add Subscription functionality to your User model just use the `\Rinvex\Subscriptions\Traits\HasPlanSubscriptions` trait like this: 49 | 50 | ```php 51 | namespace App\Models; 52 | 53 | use Rinvex\Subscriptions\Traits\HasPlanSubscriptions; 54 | use Illuminate\Foundation\Auth\User as Authenticatable; 55 | 56 | class User extends Authenticatable 57 | { 58 | use HasPlanSubscriptions; 59 | } 60 | ``` 61 | 62 | That's it, we only have to use that trait in our User model! Now your users may subscribe to plans. 63 | 64 | > **Note:** you can use `HasPlanSubscriptions` trait on any subscriber model, it doesn't have to be the user model, in fact any model will do. 65 | 66 | ### Create a Plan 67 | 68 | ```php 69 | $plan = app('rinvex.subscriptions.plan')->create([ 70 | 'name' => 'Pro', 71 | 'description' => 'Pro plan', 72 | 'price' => 9.99, 73 | 'signup_fee' => 1.99, 74 | 'invoice_period' => 1, 75 | 'invoice_interval' => 'month', 76 | 'trial_period' => 15, 77 | 'trial_interval' => 'day', 78 | 'sort_order' => 1, 79 | 'currency' => 'USD', 80 | ]); 81 | 82 | // Create multiple plan features at once 83 | $plan->features()->saveMany([ 84 | new PlanFeature(['name' => 'listings', 'value' => 50, 'sort_order' => 1]), 85 | new PlanFeature(['name' => 'pictures_per_listing', 'value' => 10, 'sort_order' => 5]), 86 | new PlanFeature(['name' => 'listing_duration_days', 'value' => 30, 'sort_order' => 10, 'resettable_period' => 1, 'resettable_interval' => 'month']), 87 | new PlanFeature(['name' => 'listing_title_bold', 'value' => 'Y', 'sort_order' => 15]) 88 | ]); 89 | ``` 90 | 91 | ### Get Plan Details 92 | 93 | You can query the plan for further details, using the intuitive API as follows: 94 | 95 | ```php 96 | $plan = app('rinvex.subscriptions.plan')->find(1); 97 | 98 | // Get all plan features 99 | $plan->features; 100 | 101 | // Get all plan subscriptions 102 | $plan->planSubscriptions; 103 | 104 | // Check if the plan is free 105 | $plan->isFree(); 106 | 107 | // Check if the plan has trial period 108 | $plan->hasTrial(); 109 | 110 | // Check if the plan has grace period 111 | $plan->hasGrace(); 112 | ``` 113 | 114 | Both `$plan->features` and `$plan->planSubscriptions` are collections, driven from relationships, and thus you can query these relations as any normal Eloquent relationship. E.g. `$plan->features()->where('name', 'listing_title_bold')->first()`. 115 | 116 | ### Get Feature Value 117 | 118 | Say you want to show the value of the feature _pictures_per_listing_ from above. You can do so in many ways: 119 | 120 | ```php 121 | // Use the plan instance to get feature's value 122 | $amountOfPictures = $plan->getFeatureBySlug('pictures_per_listing')->value; 123 | 124 | // Query the feature itself directly 125 | $amountOfPictures = app('rinvex.subscriptions.plan_feature')->where('slug', 'pictures_per_listing')->first()->value; 126 | 127 | // Get feature value through the subscription instance 128 | $amountOfPictures = app('rinvex.subscriptions.plan_subscription')->find(1)->getFeatureValue('pictures_per_listing'); 129 | ``` 130 | 131 | ### Create a Subscription 132 | 133 | You can subscribe a user to a plan by using the `newSubscription()` function available in the `HasPlanSubscriptions` trait. First, retrieve an instance of your subscriber model, which typically will be your user model and an instance of the plan your user is subscribing to. Once you have retrieved the model instance, you may use the `newSubscription` method to create the model's subscription. 134 | 135 | ```php 136 | $user = User::find(1); 137 | $plan = app('rinvex.subscriptions.plan')->find(1); 138 | 139 | $user->newPlanSubscription('main', $plan); 140 | ``` 141 | 142 | The first argument passed to `newSubscription` method should be the title of the subscription. If your application offer a single subscription, you might call this `main` or `primary`, while the second argument is the plan instance your user is subscribing to, and there's an optional third parameter to specify custom start date as an instance of `Carbon\Carbon` (by default if not provided, it will start now). 143 | 144 | ### Change the Plan 145 | 146 | You can change subscription plan easily as follows: 147 | 148 | ```php 149 | $plan = app('rinvex.subscriptions.plan')->find(2); 150 | $subscription = app('rinvex.subscriptions.plan_subscription')->find(1); 151 | 152 | // Change subscription plan 153 | $subscription->changePlan($plan); 154 | ``` 155 | 156 | If both plans (current and new plan) have the same billing frequency (e.g., `invoice_period` and `invoice_interval`) the subscription will retain the same billing dates. If the plans don't have the same billing frequency, the subscription will have the new plan billing frequency, starting on the day of the change and _the subscription usage data will be cleared_. Also if the new plan has a trial period and it's a new subscription, the trial period will be applied. 157 | 158 | ### Feature Options 159 | 160 | Plan features are great for fine-tuning subscriptions, you can top-up certain feature for X times of usage, so users may then use it only for that amount. Features also have the ability to be resettable and then it's usage could be expired too. See the following examples: 161 | 162 | ```php 163 | // Find plan feature 164 | $feature = app('rinvex.subscriptions.plan_feature')->where('name', 'listing_duration_days')->first(); 165 | 166 | // Get feature reset date 167 | $feature->getResetDate(new \Carbon\Carbon()); 168 | ``` 169 | 170 | ### Subscription Feature Usage 171 | 172 | There's multiple ways to determine the usage and ability of a particular feature in the user subscription, the most common one is `canUseFeature`: 173 | 174 | The `canUseFeature` method returns `true` or `false` depending on multiple factors: 175 | 176 | - Feature _is enabled_. 177 | - Feature value isn't `0`/`false`/`NULL`. 178 | - Or feature has remaining uses available. 179 | 180 | ```php 181 | $user->planSubscription('main')->canUseFeature('listings'); 182 | ``` 183 | 184 | Other feature methods on the user subscription instance are: 185 | 186 | - `getFeatureUsage`: returns how many times the user has used a particular feature. 187 | - `getFeatureRemainings`: returns available uses for a particular feature. 188 | - `getFeatureValue`: returns the feature value. 189 | 190 | > All methods share the same signature: e.g. `$user->planSubscription('main')->getFeatureUsage('listings');`. 191 | 192 | ### Record Feature Usage 193 | 194 | In order to effectively use the ability methods you will need to keep track of every usage of each feature (or at least those that require it). You may use the `recordFeatureUsage` method available through the user `subscription()` method: 195 | 196 | ```php 197 | $user->planSubscription('main')->recordFeatureUsage('listings'); 198 | ``` 199 | 200 | The `recordFeatureUsage` method accept 3 parameters: the first one is the feature's name, the second one is the quantity of uses to add (default is `1`), and the third one indicates if the addition should be incremental (default behavior), when disabled the usage will be override by the quantity provided. E.g.: 201 | 202 | ```php 203 | // Increment by 2 204 | $user->planSubscription('main')->recordFeatureUsage('listings', 2); 205 | 206 | // Override with 9 207 | $user->planSubscription('main')->recordFeatureUsage('listings', 9, false); 208 | ``` 209 | 210 | ### Reduce Feature Usage 211 | 212 | Reducing the feature usage is _almost_ the same as incrementing it. Here we only _substract_ a given quantity (default is `1`) to the actual usage: 213 | 214 | ```php 215 | $user->planSubscription('main')->reduceFeatureUsage('listings', 2); 216 | ``` 217 | 218 | ### Clear The Subscription Usage Data 219 | 220 | ```php 221 | $user->planSubscription('main')->usage()->delete(); 222 | ``` 223 | 224 | ### Check Subscription Status 225 | 226 | For a subscription to be considered active _one of the following must be `true`_: 227 | 228 | - Subscription has an active trial. 229 | - Subscription `ends_at` is in the future. 230 | 231 | ```php 232 | $user->subscribedTo($planId); 233 | ``` 234 | 235 | Alternatively you can use the following methods available in the subscription model: 236 | 237 | ```php 238 | $user->planSubscription('main')->active(); 239 | $user->planSubscription('main')->canceled(); 240 | $user->planSubscription('main')->ended(); 241 | $user->planSubscription('main')->onTrial(); 242 | ``` 243 | 244 | > Canceled subscriptions with an active trial or `ends_at` in the future are considered active. 245 | 246 | ### Renew a Subscription 247 | 248 | To renew a subscription you may use the `renew` method available in the subscription model. This will set a new `ends_at` date based on the selected plan and _will clear the usage data_ of the subscription. 249 | 250 | ```php 251 | $user->planSubscription('main')->renew(); 252 | ``` 253 | 254 | _Canceled subscriptions with an ended period can't be renewed._ 255 | 256 | ### Cancel a Subscription 257 | 258 | To cancel a subscription, simply use the `cancel` method on the user's subscription: 259 | 260 | ```php 261 | $user->planSubscription('main')->cancel(); 262 | ``` 263 | 264 | By default the subscription will remain active until the end of the period, you may pass `true` to end the subscription _immediately_: 265 | 266 | ```php 267 | $user->planSubscription('main')->cancel(true); 268 | ``` 269 | 270 | ### Scopes 271 | 272 | #### Subscription Model 273 | 274 | ```php 275 | // Get subscriptions by plan 276 | $subscriptions = app('rinvex.subscriptions.plan_subscription')->byPlanId($plan_id)->get(); 277 | 278 | // Get bookings of the given user 279 | $user = \App\Models\User::find(1); 280 | $bookingsOfSubscriber = app('rinvex.subscriptions.plan_subscription')->ofSubscriber($user)->get(); 281 | 282 | // Get subscriptions with trial ending in 3 days 283 | $subscriptions = app('rinvex.subscriptions.plan_subscription')->findEndingTrial(3)->get(); 284 | 285 | // Get subscriptions with ended trial 286 | $subscriptions = app('rinvex.subscriptions.plan_subscription')->findEndedTrial()->get(); 287 | 288 | // Get subscriptions with period ending in 3 days 289 | $subscriptions = app('rinvex.subscriptions.plan_subscription')->findEndingPeriod(3)->get(); 290 | 291 | // Get subscriptions with ended period 292 | $subscriptions = app('rinvex.subscriptions.plan_subscription')->findEndedPeriod()->get(); 293 | ``` 294 | 295 | ### Models 296 | 297 | **Rinvex Subscriptions** uses 4 models: 298 | 299 | ```php 300 | Rinvex\Subscriptions\Models\Plan; 301 | Rinvex\Subscriptions\Models\PlanFeature; 302 | Rinvex\Subscriptions\Models\PlanSubscription; 303 | Rinvex\Subscriptions\Models\PlanSubscriptionUsage; 304 | ``` 305 | 306 | 307 | ## Roadmap 308 | 309 | **Looking for contributors!** 310 | 311 | The following are a set of limitations to be improved, or feature requests that's looking for contributors to implement, all PRs are welcome 🙂 312 | 313 | - [ ] Allow paying for multiple occurrences of the same plan (i.e. monthly plan, user can pay for 6 months of that plan) (#64) 314 | - [ ] Plan prorate fields in database isn't utilized, this should be implemented to consolidate extension dates, and prices (#68) 315 | - [ ] Change *features* to be in a many-to-many relationship with plans. Multiple plans can have the same feature, and many plans can have many features as well (#101) 316 | - [ ] Plan subscription timezone field in database isn't utilized, this should be implemented to respect timezone on date calculations (i.e. starts_at, ends_at, trial_ends_at) (#78) 317 | - [ ] Separate trial feature from the subscription periods and adjust subscriptions accordingly. Users should be able to have a trial period without having a subscription at all (#67) 318 | 319 | ## Changelog 320 | 321 | Refer to the [Changelog](CHANGELOG.md) for a full history of the project. 322 | 323 | 324 | ## Support 325 | 326 | The following support channels are available at your fingertips: 327 | 328 | - [Chat on Slack](https://bit.ly/rinvex-slack) 329 | - [Help on Email](mailto:help@rinvex.com) 330 | - [Follow on Twitter](https://twitter.com/rinvex) 331 | 332 | 333 | ## Contributing & Protocols 334 | 335 | Thank you for considering contributing to this project! The contribution guide can be found in [CONTRIBUTING.md](CONTRIBUTING.md). 336 | 337 | Bug reports, feature requests, and pull requests are very welcome. 338 | 339 | - [Versioning](CONTRIBUTING.md#versioning) 340 | - [Pull Requests](CONTRIBUTING.md#pull-requests) 341 | - [Coding Standards](CONTRIBUTING.md#coding-standards) 342 | - [Feature Requests](CONTRIBUTING.md#feature-requests) 343 | - [Git Flow](CONTRIBUTING.md#git-flow) 344 | 345 | 346 | ## Security Vulnerabilities 347 | 348 | If you discover a security vulnerability within this project, please send an e-mail to [help@rinvex.com](help@rinvex.com). All security vulnerabilities will be promptly addressed. 349 | 350 | 351 | ## About Rinvex 352 | 353 | Rinvex is a software solutions startup, specialized in integrated enterprise solutions for SMEs established in Alexandria, Egypt since June 2016. We believe that our drive The Value, The Reach, and The Impact is what differentiates us and unleash the endless possibilities of our philosophy through the power of software. We like to call it Innovation At The Speed Of Life. That’s how we do our share of advancing humanity. 354 | 355 | 356 | ## License 357 | 358 | This software is released under [The MIT License (MIT)](LICENSE). 359 | 360 | (c) 2016-2022 Rinvex LLC, Some rights reserved. 361 | -------------------------------------------------------------------------------- /src/Models/PlanSubscription.php: -------------------------------------------------------------------------------- 1 | 'integer', 99 | 'subscriber_type' => 'string', 100 | 'plan_id' => 'integer', 101 | 'slug' => 'string', 102 | 'trial_ends_at' => 'datetime', 103 | 'starts_at' => 'datetime', 104 | 'ends_at' => 'datetime', 105 | 'cancels_at' => 'datetime', 106 | 'canceled_at' => 'datetime', 107 | 'deleted_at' => 'datetime', 108 | ]; 109 | 110 | /** 111 | * {@inheritdoc} 112 | */ 113 | protected $observables = [ 114 | 'validating', 115 | 'validated', 116 | ]; 117 | 118 | /** 119 | * The attributes that are translatable. 120 | * 121 | * @var array 122 | */ 123 | public $translatable = [ 124 | 'name', 125 | 'description', 126 | ]; 127 | 128 | /** 129 | * The default rules that the model will validate against. 130 | * 131 | * @var array 132 | */ 133 | protected $rules = []; 134 | 135 | /** 136 | * Whether the model should throw a 137 | * ValidationException if it fails validation. 138 | * 139 | * @var bool 140 | */ 141 | protected $throwValidationExceptions = true; 142 | 143 | /** 144 | * Create a new Eloquent model instance. 145 | * 146 | * @param array $attributes 147 | */ 148 | public function __construct(array $attributes = []) 149 | { 150 | $this->setTable(config('rinvex.subscriptions.tables.plan_subscriptions')); 151 | $this->mergeRules([ 152 | 'name' => 'required|string|strip_tags|max:150', 153 | 'description' => 'nullable|string|max:32768', 154 | 'slug' => 'required|alpha_dash|max:150|unique:'.config('rinvex.subscriptions.tables.plan_subscriptions').',slug', 155 | 'plan_id' => 'required|integer|exists:'.config('rinvex.subscriptions.tables.plans').',id', 156 | 'subscriber_id' => 'required|integer', 157 | 'subscriber_type' => 'required|string|strip_tags|max:150', 158 | 'trial_ends_at' => 'nullable|date', 159 | 'starts_at' => 'required|date', 160 | 'ends_at' => 'required|date', 161 | 'cancels_at' => 'nullable|date', 162 | 'canceled_at' => 'nullable|date', 163 | ]); 164 | 165 | parent::__construct($attributes); 166 | } 167 | 168 | /** 169 | * {@inheritdoc} 170 | */ 171 | protected static function boot() 172 | { 173 | parent::boot(); 174 | 175 | static::validating(function (self $model) { 176 | if (! $model->starts_at || ! $model->ends_at) { 177 | $model->setNewPeriod(); 178 | } 179 | }); 180 | 181 | static::deleted(function ($subscription) { 182 | $subscription->usage()->delete(); 183 | }); 184 | } 185 | 186 | /** 187 | * Get the options for generating the slug. 188 | * 189 | * @return \Spatie\Sluggable\SlugOptions 190 | */ 191 | public function getSlugOptions(): SlugOptions 192 | { 193 | return SlugOptions::create() 194 | ->doNotGenerateSlugsOnUpdate() 195 | ->generateSlugsFrom('name') 196 | ->saveSlugsTo('slug'); 197 | } 198 | 199 | /** 200 | * Get the owning subscriber. 201 | * 202 | * @return \Illuminate\Database\Eloquent\Relations\MorphTo 203 | */ 204 | public function subscriber(): MorphTo 205 | { 206 | return $this->morphTo('subscriber', 'subscriber_type', 'subscriber_id', 'id'); 207 | } 208 | 209 | /** 210 | * The subscription may have many usage. 211 | * 212 | * @return \Illuminate\Database\Eloquent\Relations\HasMany 213 | */ 214 | public function usage(): hasMany 215 | { 216 | return $this->hasMany(config('rinvex.subscriptions.models.plan_subscription_usage'), 'subscription_id', 'id'); 217 | } 218 | 219 | /** 220 | * Check if subscription is active. 221 | * 222 | * @return bool 223 | */ 224 | public function active(): bool 225 | { 226 | return ! $this->ended() || $this->onTrial(); 227 | } 228 | 229 | /** 230 | * Check if subscription is inactive. 231 | * 232 | * @return bool 233 | */ 234 | public function inactive(): bool 235 | { 236 | return ! $this->active(); 237 | } 238 | 239 | /** 240 | * Check if subscription is currently on trial. 241 | * 242 | * @return bool 243 | */ 244 | public function onTrial(): bool 245 | { 246 | return $this->trial_ends_at ? Carbon::now()->lt($this->trial_ends_at) : false; 247 | } 248 | 249 | /** 250 | * Check if subscription is canceled. 251 | * 252 | * @return bool 253 | */ 254 | public function canceled(): bool 255 | { 256 | return $this->canceled_at ? Carbon::now()->gte($this->canceled_at) : false; 257 | } 258 | 259 | /** 260 | * Check if subscription period has ended. 261 | * 262 | * @return bool 263 | */ 264 | public function ended(): bool 265 | { 266 | return $this->ends_at ? Carbon::now()->gte($this->ends_at) : false; 267 | } 268 | 269 | /** 270 | * Cancel subscription. 271 | * 272 | * @param bool $immediately 273 | * 274 | * @return $this 275 | */ 276 | public function cancel($immediately = false) 277 | { 278 | $this->canceled_at = Carbon::now(); 279 | 280 | if ($immediately) { 281 | $this->ends_at = $this->canceled_at; 282 | } 283 | 284 | $this->save(); 285 | 286 | return $this; 287 | } 288 | 289 | /** 290 | * Change subscription plan. 291 | * 292 | * @param \Rinvex\Subscriptions\Models\Plan $plan 293 | * 294 | * @return $this 295 | */ 296 | public function changePlan(Plan $plan) 297 | { 298 | // If plans does not have the same billing frequency 299 | // (e.g., invoice_interval and invoice_period) we will update 300 | // the billing dates starting today, and sice we are basically creating 301 | // a new billing cycle, the usage data will be cleared. 302 | if ($this->plan->invoice_interval !== $plan->invoice_interval || $this->plan->invoice_period !== $plan->invoice_period) { 303 | $this->setNewPeriod($plan->invoice_interval, $plan->invoice_period); 304 | $this->usage()->delete(); 305 | } 306 | 307 | // Attach new plan to subscription 308 | $this->plan_id = $plan->getKey(); 309 | $this->save(); 310 | 311 | return $this; 312 | } 313 | 314 | /** 315 | * Renew subscription period. 316 | * 317 | * @throws \LogicException 318 | * 319 | * @return $this 320 | */ 321 | public function renew() 322 | { 323 | if ($this->ended() && $this->canceled()) { 324 | throw new LogicException('Unable to renew canceled ended subscription.'); 325 | } 326 | 327 | $subscription = $this; 328 | 329 | DB::transaction(function () use ($subscription) { 330 | // Clear usage data 331 | $subscription->usage()->delete(); 332 | 333 | // Renew period 334 | $subscription->setNewPeriod(); 335 | $subscription->canceled_at = null; 336 | $subscription->save(); 337 | }); 338 | 339 | return $this; 340 | } 341 | 342 | /** 343 | * Get bookings of the given subscriber. 344 | * 345 | * @param \Illuminate\Database\Eloquent\Builder $builder 346 | * @param \Illuminate\Database\Eloquent\Model $subscriber 347 | * 348 | * @return \Illuminate\Database\Eloquent\Builder 349 | */ 350 | public function scopeOfSubscriber(Builder $builder, Model $subscriber): Builder 351 | { 352 | return $builder->where('subscriber_type', $subscriber->getMorphClass())->where('subscriber_id', $subscriber->getKey()); 353 | } 354 | 355 | /** 356 | * Scope subscriptions with ending trial. 357 | * 358 | * @param \Illuminate\Database\Eloquent\Builder $builder 359 | * @param int $dayRange 360 | * 361 | * @return \Illuminate\Database\Eloquent\Builder 362 | */ 363 | public function scopeFindEndingTrial(Builder $builder, int $dayRange = 3): Builder 364 | { 365 | $from = Carbon::now(); 366 | $to = Carbon::now()->addDays($dayRange); 367 | 368 | return $builder->whereBetween('trial_ends_at', [$from, $to]); 369 | } 370 | 371 | /** 372 | * Scope subscriptions with ended trial. 373 | * 374 | * @param \Illuminate\Database\Eloquent\Builder $builder 375 | * 376 | * @return \Illuminate\Database\Eloquent\Builder 377 | */ 378 | public function scopeFindEndedTrial(Builder $builder): Builder 379 | { 380 | return $builder->where('trial_ends_at', '<=', now()); 381 | } 382 | 383 | /** 384 | * Scope subscriptions with ending periods. 385 | * 386 | * @param \Illuminate\Database\Eloquent\Builder $builder 387 | * @param int $dayRange 388 | * 389 | * @return \Illuminate\Database\Eloquent\Builder 390 | */ 391 | public function scopeFindEndingPeriod(Builder $builder, int $dayRange = 3): Builder 392 | { 393 | $from = Carbon::now(); 394 | $to = Carbon::now()->addDays($dayRange); 395 | 396 | return $builder->whereBetween('ends_at', [$from, $to]); 397 | } 398 | 399 | /** 400 | * Scope subscriptions with ended periods. 401 | * 402 | * @param \Illuminate\Database\Eloquent\Builder $builder 403 | * 404 | * @return \Illuminate\Database\Eloquent\Builder 405 | */ 406 | public function scopeFindEndedPeriod(Builder $builder): Builder 407 | { 408 | return $builder->where('ends_at', '<=', now()); 409 | } 410 | 411 | /** 412 | * Scope all active subscriptions for a user. 413 | * 414 | * @param \Illuminate\Database\Eloquent\Builder $builder 415 | * 416 | * @return \Illuminate\Database\Eloquent\Builder 417 | */ 418 | public function scopeFindActive(Builder $builder): Builder 419 | { 420 | return $builder->where('ends_at', '>', now()); 421 | } 422 | 423 | /** 424 | * Set new subscription period. 425 | * 426 | * @param string $invoice_interval 427 | * @param int $invoice_period 428 | * @param string $start 429 | * 430 | * @return $this 431 | */ 432 | protected function setNewPeriod($invoice_interval = '', $invoice_period = '', $start = '') 433 | { 434 | if (empty($invoice_interval)) { 435 | $invoice_interval = $this->plan->invoice_interval; 436 | } 437 | 438 | if (empty($invoice_period)) { 439 | $invoice_period = $this->plan->invoice_period; 440 | } 441 | 442 | $period = new Period($invoice_interval, $invoice_period, $start); 443 | 444 | $this->starts_at = $period->getStartDate(); 445 | $this->ends_at = $period->getEndDate(); 446 | 447 | return $this; 448 | } 449 | 450 | /** 451 | * Record feature usage. 452 | * 453 | * @param string $featureSlug 454 | * @param int $uses 455 | * 456 | * @return \Rinvex\Subscriptions\Models\PlanSubscriptionUsage 457 | */ 458 | public function recordFeatureUsage(string $featureSlug, int $uses = 1, bool $incremental = true): PlanSubscriptionUsage 459 | { 460 | $feature = $this->plan->features()->where('slug', $featureSlug)->first(); 461 | 462 | $usage = $this->usage()->firstOrNew([ 463 | 'subscription_id' => $this->getKey(), 464 | 'feature_id' => $feature->getKey(), 465 | ]); 466 | 467 | if ($feature->resettable_period) { 468 | // Set expiration date when the usage record is new or doesn't have one. 469 | if (is_null($usage->valid_until)) { 470 | // Set date from subscription creation date so the reset 471 | // period match the period specified by the subscription's plan. 472 | $usage->valid_until = $feature->getResetDate($this->created_at); 473 | } elseif ($usage->expired()) { 474 | // If the usage record has been expired, let's assign 475 | // a new expiration date and reset the uses to zero. 476 | $usage->valid_until = $feature->getResetDate($usage->valid_until); 477 | $usage->used = 0; 478 | } 479 | } 480 | 481 | $usage->used = ($incremental ? $usage->used + $uses : $uses); 482 | 483 | $usage->save(); 484 | 485 | return $usage; 486 | } 487 | 488 | /** 489 | * Reduce usage. 490 | * 491 | * @param string $featureSlug 492 | * @param int $uses 493 | * 494 | * @return \Rinvex\Subscriptions\Models\PlanSubscriptionUsage|null 495 | */ 496 | public function reduceFeatureUsage(string $featureSlug, int $uses = 1): ?PlanSubscriptionUsage 497 | { 498 | $usage = $this->usage()->byFeatureSlug($featureSlug)->first(); 499 | 500 | if (is_null($usage)) { 501 | return null; 502 | } 503 | 504 | $usage->used = max($usage->used - $uses, 0); 505 | 506 | $usage->save(); 507 | 508 | return $usage; 509 | } 510 | 511 | /** 512 | * Determine if the feature can be used. 513 | * 514 | * @param string $featureSlug 515 | * 516 | * @return bool 517 | */ 518 | public function canUseFeature(string $featureSlug): bool 519 | { 520 | $featureValue = $this->getFeatureValue($featureSlug); 521 | $usage = $this->usage()->byFeatureSlug($featureSlug)->first(); 522 | 523 | if ($featureValue === 'true') { 524 | return true; 525 | } 526 | 527 | // If the feature value is zero, let's return false since 528 | // there's no uses available. (useful to disable countable features) 529 | if (! $usage || $usage->expired() || is_null($featureValue) || $featureValue === '0' || $featureValue === 'false') { 530 | return false; 531 | } 532 | 533 | // Check for available uses 534 | return $this->getFeatureRemainings($featureSlug) > 0; 535 | } 536 | 537 | /** 538 | * Get how many times the feature has been used. 539 | * 540 | * @param string $featureSlug 541 | * 542 | * @return int 543 | */ 544 | public function getFeatureUsage(string $featureSlug): int 545 | { 546 | $usage = $this->usage()->byFeatureSlug($featureSlug)->first(); 547 | 548 | return (! $usage || $usage->expired()) ? 0 : $usage->used; 549 | } 550 | 551 | /** 552 | * Get the available uses. 553 | * 554 | * @param string $featureSlug 555 | * 556 | * @return int 557 | */ 558 | public function getFeatureRemainings(string $featureSlug): int 559 | { 560 | return $this->getFeatureValue($featureSlug) - $this->getFeatureUsage($featureSlug); 561 | } 562 | 563 | /** 564 | * Get feature value. 565 | * 566 | * @param string $featureSlug 567 | * 568 | * @return mixed 569 | */ 570 | public function getFeatureValue(string $featureSlug) 571 | { 572 | $feature = $this->plan->features()->where('slug', $featureSlug)->first(); 573 | 574 | return $feature->value ?? null; 575 | } 576 | } 577 | --------------------------------------------------------------------------------