Giter Site home page Giter Site logo

spatie / laravel-stats Goto Github PK

View Code? Open in Web Editor NEW
391.0 11.0 33.0 142 KB

Easily track application stats like orders, subscriptions and users and their change over time

Home Page: https://freek.dev/1957-a-lightweight-laravel-package-to-track-changes-over-time

License: MIT License

PHP 100.00%

laravel-stats's Introduction

Track application stat changes over time

Latest Version on Packagist Tests Total Downloads

This package is a lightweight solution to summarize changes in your database over time. Here's a quick example where we are going to track the number of subscriptions and cancellations over time.

First, you should create a stats class.

use Spatie\Stats\BaseStats;

class SubscriptionStats extends BaseStats {}

Next, you can call increase on it when somebody subscribes, and decrease when somebody cancels their plan.

SubscriptionStats::increase(); // execute whenever somebody subscribes
SubscriptionStats::decrease() // execute whenever somebody cancels the subscription;

With this in place, you can query the stats. Here's how you can get the subscription stats for the past two months, grouped by week.

use Spatie\Stats\StatsQuery;

$stats = SubscriptionStats::query()
    ->start(now()->subMonths(2))
    ->end(now()->subSecond())
    ->groupByWeek()
    ->get();

This will return an array like this one:

[
    [
        'start' => '2020-01-01',
        'end' => '2020-01-08',
        'value' => 102,
        'increments' => 32,
        'decrements' => 20,
        'difference' => 12,
    ],
    [
        'start' => '2020-01-08',
        'end' => '2020-01-15',
        'value' => 114,
        'increments' => 63,
        'decrements' => 30,
        'difference' => 33,
    ],
]

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-stats

You must publish and run the migrations with:

php artisan vendor:publish --provider="Spatie\Stats\StatsServiceProvider" --tag="stats-migrations"
php artisan migrate

Usage

Step 1: create a stats class

First, you should create a stats class. This class is responsible for configuration how a particular statistic is stored. By default, it needs no configuration at all.

use Spatie\Stats\BaseStats;

class SubscriptionStats extends BaseStats {}

By default, the name of the class will be used to store the statistics in the database. To customize the used key, use getName

use Spatie\Stats\BaseStats;

class SubscriptionStats extends BaseStats
{
    public function getName() : string{
        return 'my-custom-name'; // stats will be stored with using name `my-custom-name`
    }
}

Step 2: call increase and decrease or set a fixed value

Next, you can call increase, decrease when the stat should change. In this particular case, you should call increase on it when somebody subscribes, and decrease when somebody cancels their plan.

SubscriptionStats::increase(); // execute whenever somebody subscribes
SubscriptionStats::decrease(); // execute whenever somebody cancels the subscription;

Instead of manually increasing and decreasing the stat, you can directly set it. This is useful when your particular stat does not get calculated by your own app, but lives elsewhere. Using the subscription example, let's image that subscriptions live elsewhere, and that there's an API call to get the count.

$count = AnAPi::getSubscriptionCount(); 

SubscriptionStats::set($count);

By default, that increase, decrease and set methods assume that the event that caused your stats to change, happened right now. Optionally, you can pass a date time as a second parameter to these methods. Your stat change will be recorded as if it happened on that moment.

SubscriptionStats::increase(1, $subscription->created_at); 

Step 3: query the stats

With this in place, you can query the stats. You can fetch stats for a certain period and group them by minute, hour, day, week, month, or year.

Here's how you can get the subscription stats for the past two months, grouped by week.

$stats = SubscriptionStats::query()
    ->start(now()->subMonths(2))
    ->end(now()->subSecond())
    ->groupByWeek()
    ->get();

This will return an array containing arrayable Spatie\Stats\DataPoint objects. These objects can be cast to arrays like this:

// output of $stats->toArray():
[
    [
        'start' => '2020-01-01',
        'end' => '2020-01-08',
        'value' => 102,
        'increments' => 32,
        'decrements' => 20,
        'difference' => 12,
    ],
    [
        'start' => '2020-01-08',
        'end' => '2020-01-15',
        'value' => 114,
        'increments' => 63,
        'decrements' => 30,
        'difference' => 33,
    ],
]

Extended Use-Cases

Read and Write from a custom Model

  • Create a new table with type (string), value (bigInt), created_at, updated_at fields
  • Create a model and add HasStats-trait
StatsWriter::for(MyCustomModel::class)->set(123)
StatsWriter::for(MyCustomModel::class, ['custom_column' => '123'])->increase(1)
StatsWriter::for(MyCustomModel::class, ['another_column' => '234'])->decrease(1, now()->subDay())

$stats = StatsQuery::for(MyCustomModel::class)
    ->start(now()->subMonths(2))
    ->end(now()->subSecond())
    ->groupByWeek()
    ->get();
    
// OR

$stats = StatsQuery::for(MyCustomModel::class, ['additional_column' => '123'])
    ->start(now()->subMonths(2))
    ->end(now()->subSecond())
    ->groupByWeek()
    ->get(); 

Read and Write from a HasMany-Relationship

$tenant = Tenant::find(1) 

StatsWriter::for($tenant->orderStats(), ['payment_type_column' => 'recurring'])->increment(1)

$stats = StatsQuery::for($tenant->orderStats(), , ['payment_type_column' => 'recurring'])
    ->start(now()->subMonths(2))
    ->end(now()->subSecond())
    ->groupByWeek()
    ->get();

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

laravel-stats's People

Contributors

abenerd avatar abishekrsrikaanth avatar adrianmrn avatar alexvanderbist avatar bumbummen99 avatar christoph-kluge avatar dexterharrison avatar digitalkreativ avatar finndev avatar freekmurze avatar fsamapoor avatar gauravmak avatar manojkirana avatar noamanahmed avatar patinthehat avatar rubenvanassche avatar sachinganesh avatar skollro avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-stats's Issues

Feature Request: Group or similar "Tenant" for stats?

Hi Team,

I've already added the task on my project to incorporate this and remove the stats library I dreamt up!

Would you consider adding some sort of grouping column/attribute? For example, to set the stats per tenant, user, project or similar?

E.

Changing value in DB won't update stats

Hi,
I implemented an increase event every time a URL is hit. So far so good. Results are correct.
Now, to test daily stats, I changed manually (created_at, updated_at) the first entry in the DB, to a day previous to the original one

Then, when I execute

App\Stats\PropertyHitsStats::query()
    ->start(now()->subDays(1))
    ->end(now()->subSecond())
    ->groupByDay()
    ->get();

I get (erroneously)

=> Illuminate\Support\Collection {#2189
     all: [
       Spatie\Stats\DataPoint {#2216
         +start: Illuminate\Support\Carbon @1626922800 {#2198
           date: 2021-07-22 00:00:00.0 America/Argentina/Buenos_Aires (-03:00),
         },
         +end: Illuminate\Support\Carbon @1627009200 {#2199
           date: 2021-07-23 00:00:00.0 America/Argentina/Buenos_Aires (-03:00),
         },
         +value: 1,
         +increments: 0,
         +decrements: 0,
         +difference: 0,
       },
       Spatie\Stats\DataPoint {#2226
         +start: Illuminate\Support\Carbon @1627009200 {#2197
           date: 2021-07-23 00:00:00.0 America/Argentina/Buenos_Aires (-03:00),
         },
         +end: Illuminate\Support\Carbon @1627095600 {#2196
           date: 2021-07-24 00:00:00.0 America/Argentina/Buenos_Aires (-03:00),
         },
         +value: 7,
         +increments: 6,
         +decrements: 0,
         +difference: 6,
       },
     ],
   }

I went through your code searching for if you were using cache at any point, but couldn't find it.
Any thoughts on why is this happening?

BTW, executing

Spatie\Stats\StatsQuery::for(App\Stats\PropertyHitsStats::class)
    ->start(now()->subDays(1))
    ->end(now()->subSecond())
    ->groupByDay()
    ->get();

returns exactly the same result

Reading stat issue when using PostgreSQL

My environment

  • PHP 8.1 in Docker
  • PostgreSQL 13.4 in Docker
  • Laravel 9.0.1
  • spatie/laravel-stats 2.0.1

When saving stats al works perfect. I have issue when reading stats in this way:

MyStats::query()
   ->start(Carbon::now())
   ->end(Carbon::now())
   ->groupByDay()
   ->get()

What I get as error:
SQLSTATE[42883]: Undefined function: 7 ERROR: function date_format(timestamp without time zone, unknown) does not exist\nLINE 1: ... 0 end)) as decrements, sum(value) as difference, date_forma...\n ^\nHINT: No function matches the given name and argument types. You might need to add explicit type casts. (SQL: select sum(case when value > 0 then value else 0 end) as increments, abs(sum(case when value < 0 then value else 0 end)) as decrements, sum(value) as difference, date_format(created_at,'%Y-%m-%d') as period from \"stats_events\" where (\"name\" = users) and \"type\" = change and \"created_at\" >= 2022-04-12 09:09:00 and \"created_at\" < 2022-04-12 09:09:00 group by date_format(created_at,'%Y-%m-%d'))

I think your method getPeriodDateFormat only supports mysql and sqlite, could you please add support for PostgreSQL?

Thanks!

Postgres support

I'm not using this package, so I'll refrain from making a PR. But I did use some of the ways the period / formatting worked.

If anyone needs the mysql equivalent, here are the following periods.

public static function getPeriodDateFormat(string $period): string
    {
        return match ($period) {
            'year' => "to_char(created_at::timestamptz, 'YYYY')",
            'month' => "to_char(created_at::timestamptz, 'YYYY-MM')",
            'week' => "to_char(created_at::timestamptz, 'YYYYIW')",
            'day' => "to_char(created_at::timestamptz, 'YYYY-MM-DD')",
            'hour' => "to_char(created_at::timestamptz, 'YYYY-MM-DD HH24')",
            'minute' => "to_char(created_at::timestamptz, 'YYYY-MM-DD HH24:MI')",
        };
    }

Feel free to close this issue! Just posting it here in case someone else searches

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax

The method getLatestSetPerPeriod returns a MySQL error due to incorrect query:

select ROW_NUMBER() OVER (PARTITION BY date_format(created_at,'%Y-%m-%d') ORDER BY `id` DESC) AS rn, ...

What it should be:

select (ROW_NUMBER() OVER (PARTITION BY date_format(created_at,'%Y-%m-%d') ORDER BY `id` DESC)) AS rn, ...

The top version of the query throws errors even in a pure MySQL CLI which precludes that it's any issue in the project or PHP.

MySQL version: 8.0.26
Package version: 1.0.0
PHP version: 8.0.9
Laravel version: 8.60.0

Connection prefix not resolved in StatsQuery getStatsTableName

I needed a simple stats tracking thing for a project and of course Spatie has a package for it. Thank you very much!

Unfortunately I came across an issue when the database connection uses a prefix, for example test_ (config/database.php)

 'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => env('DB_PREFIX', ''),
    'prefix_indexes' => true,
    'strict' => true,
    'engine' => null,
    'options' => array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]),
],

the code below fails

SubscriptionStats::query()->start(Carbon::now()->subMinutes(5))->end(Carbon::now()->addMinutes(30))->get();

with the following message

 Illuminate\Database\QueryException 

  SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'db_name.stats_events' (SQL: select ROW_NUMBER() OVER (PARTITION BY yearweek(created_at, 3) ORDER BY `id` DESC) AS rn, `stats_events`.*, yearweek(created_at, 3) as period from `test_stats_events` where (`name` = test) and `type` = set and `created_at` >= 2022-05-25 15:12:43 and `created_at` < 2022-05-25 15:47:43)

Thats the query being built at #L252

The culprit being the $subject->getTable() which does not add the connection prefix to the table name while using selectRaw.

A fix could be fetching the connection name and prefix like below (#L284)

/** @var Model $subject */
$subject = $this->subject;
$prefix = '';
if (is_string($subject) && class_exists($subject)) {
    $subject = new $subject;
    $connectionName = $subject->getConnectionName() ?: config('database.default');
    $config = Config::get('database.connections.'.$connectionName);
    if( isset( $config['prefix'] ) && !empty( $config['prefix']) ){
        $prefix = $config['prefix'];
    }
}

return $prefix. $subject->getTable();

Most likely this would also need to happen for the Relation at #L280

Although that might warrant some extra thought as we don't want to duplicate the above code at multiple places.

I can probably make a pull request for this if needed. I'm just not really sure what kind of test(s) would be required for this to have "enough" coverage for this specific issue.

test_it_can_resolve_connection_prefix_of_table ?

I haven't checked the other spatie packages if there have been issues similar to this yet. That's probably for the upcoming long weekend.

Alternative

Hi! Is there any alternative laravel package to this package?

SQL Syntax error

<?php
namespace App\Models\Stats;
use Spatie\Stats\BaseStats;
class SearchStartStats extends BaseStats {}

$stats = SearchStartStats::query()->get();

Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(PARTITION BY yearweek(created_at, 3) ORDER BY id DESC) AS rn, stats_events.' at line 1 (SQL: select ROW_NUMBER() OVER (PARTITION BY yearweek(created_at, 3) ORDER BY id DESC) AS rn, stats_events.*, yearweek(created_at, 3) as period from stats_events where (name = SearchStartStats) and type = set and created_at >= 2022-05-23 08:21:26 and created_at < 2022-06-23 08:21:26)",

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.