repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Newsletter.php | Beam/extensions/beam-module/src/Model/Newsletter.php | <?php
namespace Remp\BeamModule\Model;
use Remp\BeamModule\Model\BaseModel;
use Recurr\Rule;
class Newsletter extends BaseModel
{
const STATE_STARTED = 'started';
const STATE_PAUSED = 'paused';
const STATE_FINISHED = 'finished';
protected $casts = [
'personalized_content' => 'boolean',
'starts_at' => 'datetime',
'created_at' => 'datetime',
'updated_at' => 'datetime',
'last_sent_at' => 'datetime',
];
protected $attributes = [
'personalized_content' => false,
];
protected $fillable = [
'name',
'mailer_generator_id',
'segment',
'mail_type_code',
'criteria',
'articles_count',
'personalized_content',
'recurrence_rule',
'state',
'timespan',
'email_from',
'email_subject',
'last_sent_at',
'starts_at',
];
/**
* Get the RRule object
* access using $newsletter->rule_object
*
* @return Rule
* @throws \Recurr\Exception\InvalidRRule
*/
public function getRuleObjectAttribute(): ?Rule
{
return $this->recurrence_rule ? new Rule($this->recurrence_rule) : null;
}
public function getSegmentCodeAttribute()
{
return explode('::', $this->segment)[1];
}
public function getSegmentProviderAttribute()
{
return explode('::', $this->segment)[0];
}
public function getRecurrenceRuleInlineAttribute($value)
{
return str_replace("\r\n", " ", $value);
}
public function isFinished()
{
return $this->state === self::STATE_FINISHED;
}
public function isStarted()
{
return $this->state === self::STATE_STARTED;
}
public function isPaused()
{
return $this->state === self::STATE_PAUSED;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ArticleAggregatedView.php | Beam/extensions/beam-module/src/Model/ArticleAggregatedView.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Yadakhov\InsertOnDuplicateKey;
class ArticleAggregatedView extends BaseModel
{
use InsertOnDuplicateKey;
public $timestamps = false;
protected $casts = [
'pageviews' => 'integer',
'timespent' => 'integer',
];
protected $fillable = [
'article_id',
'user_id',
'browser_id',
'date',
'pageviews',
'timespent',
];
public function article(): BelongsTo
{
return $this->belongsTo(Article::class);
}
public function articleAuthors(): HasMany
{
return $this->hasMany(ArticleAuthor::class, 'article_id', 'article_id');
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/EntityParam.php | Beam/extensions/beam-module/src/Model/EntityParam.php | <?php
namespace Remp\BeamModule\Model;
use Remp\BeamModule\Model\BaseModel;
use Illuminate\Database\Eloquent\SoftDeletes;
use Remp\BeamModule\Model\Entity;
class EntityParam extends BaseModel
{
use SoftDeletes;
const TYPE_STRING = "string";
const TYPE_STRING_ARRAY = "string_array";
const TYPE_NUMBER = "number";
const TYPE_NUMBER_ARRAY = "number_array";
const TYPE_BOOLEAN = "boolean";
const TYPE_DATETIME = "datetime";
protected $table = 'entity_params';
protected $fillable = [
'id',
'name',
'type'
];
public function entity()
{
return $this->belongsTo(Entity::class);
}
public static function getAllTypes()
{
return [
self::TYPE_STRING => __("entities.types." . self::TYPE_STRING),
self::TYPE_STRING_ARRAY => __("entities.types." . self::TYPE_STRING_ARRAY),
self::TYPE_NUMBER => __("entities.types." . self::TYPE_NUMBER),
self::TYPE_NUMBER_ARRAY => __("entities.types." . self::TYPE_NUMBER_ARRAY),
self::TYPE_BOOLEAN => __("entities.types." . self::TYPE_BOOLEAN),
self::TYPE_DATETIME => __("entities.types." . self::TYPE_DATETIME),
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Entity.php | Beam/extensions/beam-module/src/Model/Entity.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Entity extends BaseModel
{
protected $table = 'entities';
protected $fillable = [
'name',
'parent_id'
];
public function params(): HasMany
{
return $this->hasMany(EntityParam::class)
->withTrashed()
->orderBy("id");
}
public function isRootEntity()
{
return is_null($this->parent_id) ? true : false;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Tag.php | Beam/extensions/beam-module/src/Model/Tag.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Remp\BeamModule\Database\Factories\TagFactory;
use Remp\Journal\TokenProvider;
class Tag extends BaseModel
{
use HasFactory;
protected $fillable = [
'name',
'external_id',
];
protected $hidden = [
'id',
'pivot',
];
protected static function newFactory(): TagFactory
{
return TagFactory::new();
}
public function articles(): BelongsToMany
{
return $this->belongsToMany(Article::class);
}
public function tagCategories(): BelongsToMany
{
return $this->belongsToMany(TagCategory::class);
}
// Scopes
public function scopeOfSelectedProperty(Builder $query): Builder
{
$tokenProvider = resolve(TokenProvider::class);
$propertyUuid = $tokenProvider->getToken();
if ($propertyUuid) {
$query->whereHas('articles', function (Builder $articlesQuery) {
/** @var Builder|Article $articlesQuery */
$articlesQuery->ofSelectedProperty();
});
}
return $query;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ArticleTitle.php | Beam/extensions/beam-module/src/Model/ArticleTitle.php | <?php
namespace Remp\BeamModule\Model;
class ArticleTitle extends BaseModel
{
protected $fillable = [
'variant',
'title',
'article_id',
];
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Article.php | Beam/extensions/beam-module/src/Model/Article.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Carbon;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Remp\BeamModule\Database\Factories\ArticleFactory;
use Remp\BeamModule\Helpers\Journal\JournalHelpers;
use Remp\BeamModule\Model\Config\ConversionRateConfig;
use Remp\Journal\AggregateRequest;
use Remp\Journal\JournalContract;
use Remp\Journal\TokenProvider;
use Spatie\Searchable\Searchable;
use Spatie\Searchable\SearchResult;
use Yadakhov\InsertOnDuplicateKey;
class Article extends BaseModel implements Searchable
{
use HasFactory;
use InsertOnDuplicateKey;
private const DEFAULT_TITLE_VARIANT = 'default';
private const DEFAULT_IMAGE_VARIANT = 'default';
public const DEFAULT_CONTENT_TYPE = 'article';
private $journal;
private $journalHelpers;
private $cachedAttributes = [];
private $conversionRateConfig;
private int $conversionRateConfigLastLoadTimestamp = 0;
protected $fillable = [
'property_uuid',
'external_id',
'title',
'author',
'url',
'content_type',
'section',
'image_url',
'published_at',
'pageviews_all',
'pageviews_signed_in',
'pageviews_subscribers',
];
protected $casts = [
'published_at' => 'datetime',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
protected static function newFactory(): ArticleFactory
{
return ArticleFactory::new();
}
public function getSearchResult(): SearchResult
{
return new SearchResult($this, $this->title);
}
public function property(): BelongsTo
{
return $this->belongsTo(Property::class, 'property_uuid', 'uuid');
}
public function authors(): BelongsToMany
{
return $this->belongsToMany(Author::class);
}
public function sections(): BelongsToMany
{
return $this->belongsToMany(Section::class);
}
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class);
}
public function conversions(): HasMany
{
return $this->hasMany(Conversion::class);
}
public function conversionSources(): HasManyThrough
{
return $this->hasManyThrough(ConversionSource::class, Conversion::class);
}
public function pageviews(): HasMany
{
return $this->hasMany(ArticlePageviews::class);
}
public function timespent(): HasMany
{
return $this->hasMany(ArticleTimespent::class);
}
public function articleTitles(): HasMany
{
return $this->hasMany(ArticleTitle::class);
}
public function dashboardArticle(): HasOne
{
return $this->hasOne(DashboardArticle::class);
}
// Accessors
/**
* variants_count
* indexed by title variant name first, image variant name second
* @return array
*/
public function getVariantsCountAttribute(): array
{
if (array_key_exists('variants_count', $this->cachedAttributes)) {
return $this->cachedAttributes['variants_count'];
}
$r = (new AggregateRequest('pageviews', 'load'))
->setTime($this->published_at, Carbon::now())
->addGroup('article_id', 'title_variant', 'image_variant')
->addFilter('article_id', $this->external_id);
$results = collect($this->getJournal()->unique($r));
$titleVariants = [];
$imageVariants = [];
foreach ($results as $result) {
if (!$result->count) {
continue;
}
$titleVariant = $result->tags->title_variant ?? self::DEFAULT_TITLE_VARIANT;
if (!isset($titleVariants[$titleVariant])) {
$titleVariants[$titleVariant] = 0;
}
$imageVariant = $result->tags->image_variant ?? self::DEFAULT_IMAGE_VARIANT;
if (!isset($imageVariants[$imageVariant])) {
$imageVariants[$imageVariant] = 0;
}
$titleVariants[$titleVariant] += $result->count;
$imageVariants[$imageVariant] += $result->count;
}
$this->cachedAttributes['variants_count'] = [
'title' => $titleVariants,
'image' => $imageVariants,
];
return $this->cachedAttributes['variants_count'];
}
public function getTitleVariantsCountAttribute(): array
{
return $this->variants_count['title'];
}
public function getImageVariantsCountAttribute(): array
{
return $this->variants_count['image'];
}
/**
* unique_browsers_count
* @return int
*/
public function getUniqueBrowsersCountAttribute(): int
{
if (array_key_exists('unique_browsers_count', $this->cachedAttributes)) {
return $this->cachedAttributes['unique_browsers_count'];
}
$results = $this->getJournalHelpers()->uniqueBrowsersCountForArticles(collect([$this]));
$count = $results[$this->external_id] ?? 0;
$this->cachedAttributes['unique_browsers_count'] = $count;
return $count;
// TODO revert to code below to avoid two Journal API requests after https://gitlab.com/remp/remp/issues/484 is fixed
//$total = 0;
//$variantsCount = $this->variants_count; // Retrieved from accessor
//foreach ($variantsCount as $title => $titleVariants) {
// foreach ($titleVariants as $image => $count) {
// $total += $count;
// }
//}
//return $total;
}
/**
* conversion_rate
*
* Deprecated usage without passing ConversionRateConfig. For now when using without passing $conversionRateConfig,
* it'll fallback to default config until next major release when we'll remove nullable type and
* $conversionRateConfig become mandatory.
*
* @return string
*/
public function getConversionRateAttribute(?ConversionRateConfig $conversionRateConfig = null): string
{
if ($conversionRateConfig === null) {
$conversionRateConfig = $this->getConversionRateConfig();
trigger_error('Usage of this method without $conversionRateConfig argument is deprecated.', E_USER_DEPRECATED);
}
return self::computeConversionRate(
$this->conversions->count(),
$this->unique_browsers_count,
$conversionRateConfig
);
}
/**
* renewed_conversions_count
* @return int
*/
public function getRenewedConversionsCountAttribute(): int
{
$renewSubscriptionsCountSql = <<<SQL
select count(*) as subscriptions_count from (
select c1.user_id from conversions c1
left join conversions c2
on c1.user_id = c2.user_id and c2.paid_at < c1.paid_at and c2.id != c1.id
where c2.id is not Null
and c1.article_id = ?
group by user_id
) t
SQL;
return DB::select($renewSubscriptionsCountSql, [$this->id])[0]->subscriptions_count;
}
/**
* new_conversions_count
* @return int
*/
public function getNewConversionsCountAttribute(): int
{
$newSubscriptionsCountSql = <<<SQL
select count(*) as subscriptions_count from (
select c1.* from conversions c1
left join conversions c2
on c1.user_id = c2.user_id and c2.paid_at < c1.paid_at
where c2.id is Null
and c1.article_id = ?
) t
SQL;
return DB::select($newSubscriptionsCountSql, [$this->id])[0]->subscriptions_count;
}
public function getHasImageVariantsAttribute(): bool
{
return count($this->variants_count['image']) > 1;
}
public function getHasTitleVariantsAttribute(): bool
{
return count($this->variants_count['title']) > 1;
}
/**
* conversion_sources
* @return Collection
*/
public function getConversionSources(): Collection
{
return $this
->conversions()
->with('conversionSources')
->get()
->pluck('conversionSources')
->filter(function ($conversionSource) {
return $conversionSource->isNotEmpty();
})
->flatten();
}
// Mutators
public function setPublishedAtAttribute($value)
{
if (!$value) {
return;
}
$this->attributes['published_at'] = new Carbon($value);
}
// Scopes
public function scopeMostReadByTimespent(Builder $query, Carbon $start, string $getBy, int $limit = null): Builder
{
$innerQuery = ArticleTimespent::where('time_from', '>=', $start)
->groupBy('article_id')
->select(['article_id', DB::raw("sum($getBy) as total_sum")])
->orderByDesc('total_sum');
if ($limit) {
$innerQuery->limit($limit);
}
return $query->joinSub($innerQuery, 't', function ($join) {
$join->on('articles.id', '=', 't.article_id');
})->orderByDesc('t.total_sum');
}
public function scopeMostReadByPageviews(Builder $query, Carbon $start, string $getBy, int $limit = null): Builder
{
$innerQuery = ArticlePageviews::where('time_from', '>=', $start)
->groupBy('article_id')
->select(['article_id', DB::raw("sum($getBy) as total_sum")])
->orderByDesc('total_sum');
$query = $query->joinSub($innerQuery, 't', function ($join) {
$join->on('articles.id', '=', 't.article_id');
})
->orderByDesc('t.total_sum');
if ($limit) {
$query = $query->limit($limit);
}
return $query;
}
public function scopeMostReadByAveragePaymentAmount(Builder $query, Carbon $start, ?int $limit = null): Builder
{
$innerQuery = Conversion::where('paid_at', '>=', $start)
->groupBy('article_id')
->select(['article_id', DB::raw('avg(amount) as average')])
->orderByDesc('average');
$query = $query->joinSub($innerQuery, 'c', function ($join) {
$join->on('articles.id', '=', 'c.article_id');
})->orderByDesc('c.average');
if ($limit) {
$query = $query->limit($limit);
}
return $query;
}
public function scopeMostReadByTotalPaymentAmount(Builder $query, Carbon $start, ?int $limit = null): Builder
{
$innerQuery = Conversion::where('paid_at', '>=', $start)
->groupBy('article_id')
->select(['article_id', DB::raw('sum(amount) as average')])
->orderByDesc('average');
$query = $query->joinSub($innerQuery, 'c', function ($join) {
$join->on('articles.id', '=', 'c.article_id');
})->orderByDesc('c.average');
if ($limit) {
$query = $query->limit($limit);
}
return $query;
}
public function scopeIgnoreAuthorIds(Builder $query, array $authorIds): Builder
{
if ($authorIds) {
$query->join('article_author', 'articles.id', '=', 'article_author.article_id')
->whereNotIn('article_author.author_id', $authorIds);
}
return $query;
}
public function scopeIgnoreContentTypes(Builder $query, array $contentTypes): Builder
{
if ($contentTypes) {
$query->whereNotIn('content_type', $contentTypes);
}
return $query;
}
public function scopePublishedBetween(Builder $query, Carbon $from = null, Carbon $to = null): Builder
{
if ($from) {
$query->where('published_at', '>=', $from);
}
if ($to) {
$query->where('published_at', '<=', $to);
}
return $query;
}
public function scopeOfSelectedProperty(Builder $query): Builder
{
$tokenProvider = resolve(TokenProvider::class);
$propertyUuid = $tokenProvider->getToken();
if ($propertyUuid) {
$query->where('articles.property_uuid', $propertyUuid);
}
return $query;
}
public static function computeConversionRate(
$conversionsCount,
$uniqueBrowsersCount,
ConversionRateConfig $conversionRateConfig
): string {
if ($uniqueBrowsersCount === 0) {
return '0';
}
$multiplier = $conversionRateConfig->getMultiplier();
$conversionRate = (float) ($conversionsCount / $uniqueBrowsersCount) * $multiplier;
$conversionRate = number_format($conversionRate, $conversionRateConfig->getDecimalNumbers());
if ($multiplier == 100) {
return "$conversionRate %";
}
return $conversionRate;
}
// Resolvers
/**
* @deprecated Create your own instance of ConversionRateConfig.
*/
protected function getConversionRateConfig()
{
$cacheDurationInSeconds = 60;
$refreshAfter = $this->conversionRateConfigLastLoadTimestamp + $cacheDurationInSeconds;
$needsRefresh = time() > $refreshAfter;
if (!$this->conversionRateConfig || $needsRefresh) {
$this->conversionRateConfig = ConversionRateConfig::build();
$this->conversionRateConfigLastLoadTimestamp = time();
}
return $this->conversionRateConfig;
}
public function getJournal()
{
if (!$this->journal) {
$this->journal = resolve(JournalContract::class);
}
return $this->journal;
}
public function getJournalHelpers()
{
if (!$this->journalHelpers) {
$this->journalHelpers = new JournalHelpers($this->getJournal());
}
return $this->journalHelpers;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/SegmentRule.php | Beam/extensions/beam-module/src/Model/SegmentRule.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Remp\BeamModule\Database\Factories\SegmentRuleFactory;
class SegmentRule extends BaseModel
{
use HasFactory;
protected $casts = [
'fields' => 'json',
'flags' => 'json',
'timespan' => 'integer',
];
protected $attributes = [
'fields' => '[]',
'flags' => '[]',
];
protected $fillable = [
'id',
'timespan',
'count',
'event_category',
'event_action',
'segment_id',
'operator',
'fields',
'flags',
];
protected static function newFactory(): SegmentRuleFactory
{
return SegmentRuleFactory::new();
}
public function segment(): BelongsTo
{
return $this->belongsTo(Segment::class);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/TagsDataTable.php | Beam/extensions/beam-module/src/Model/TagsDataTable.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Remp\BeamModule\Model\Rules\ValidCarbonDate;
use Yajra\DataTables\DataTables;
use Yajra\DataTables\QueryDataTable;
class TagsDataTable
{
private TagCategory $tagCategory;
public function getDataTable(Request $request, DataTables $datatables)
{
$request->validate([
'published_from' => ['sometimes', new ValidCarbonDate],
'published_to' => ['sometimes', new ValidCarbonDate],
'conversion_from' => ['sometimes', new ValidCarbonDate],
'conversion_to' => ['sometimes', new ValidCarbonDate],
]);
$cols = [
'tags.id',
'tags.name',
'COALESCE(articles_count, 0) AS articles_count',
'COALESCE(conversions_count, 0) AS conversions_count',
'COALESCE(conversions_amount, 0) AS conversions_amount',
'COALESCE(pageviews_all, 0) AS pageviews_all',
'COALESCE(pageviews_not_subscribed, 0) AS pageviews_not_subscribed',
'COALESCE(pageviews_subscribers, 0) AS pageviews_subscribers',
'COALESCE(timespent_all, 0) AS timespent_all',
'COALESCE(timespent_not_subscribed, 0) AS timespent_not_subscribed',
'COALESCE(timespent_subscribers, 0) AS timespent_subscribers',
'COALESCE(timespent_all / pageviews_all, 0) AS avg_timespent_all',
'COALESCE(timespent_not_subscribed / pageviews_not_subscribed, 0) AS avg_timespent_not_subscribed',
'COALESCE(timespent_subscribers / pageviews_subscribers, 0) AS avg_timespent_subscribers',
];
$conversionsQuery = Conversion::selectRaw(implode(',', [
'tag_id',
'count(distinct conversions.id) as conversions_count',
'sum(conversions.amount) as conversions_amount',
]))
->leftJoin('article_tag', 'conversions.article_id', '=', 'article_tag.article_id')
->leftJoin('articles', 'article_tag.article_id', '=', 'articles.id')
->ofSelectedProperty()
->groupBy('tag_id');
$pageviewsQuery = Article::selectRaw(implode(',', [
'tag_id',
'COALESCE(SUM(pageviews_all), 0) AS pageviews_all',
'COALESCE(SUM(pageviews_all) - SUM(pageviews_subscribers), 0) AS pageviews_not_subscribed',
'COALESCE(SUM(pageviews_subscribers), 0) AS pageviews_subscribers',
'COALESCE(SUM(timespent_all), 0) AS timespent_all',
'COALESCE(SUM(timespent_all) - SUM(timespent_subscribers), 0) AS timespent_not_subscribed',
'COALESCE(SUM(timespent_subscribers), 0) AS timespent_subscribers',
'COUNT(*) as articles_count',
]))
->leftJoin('article_tag', 'articles.id', '=', 'article_tag.article_id')
->ofSelectedProperty()
->groupBy('tag_id');
if ($request->input('content_type') && $request->input('content_type') !== 'all') {
$pageviewsQuery->where('content_type', '=', $request->input('content_type'));
$conversionsQuery->where('content_type', '=', $request->input('content_type'));
}
if ($request->input('published_from')) {
$publishedFrom = Carbon::parse($request->input('published_from'), $request->input('tz'));
$conversionsQuery->where('published_at', '>=', $publishedFrom);
$pageviewsQuery->where('published_at', '>=', $publishedFrom);
}
if ($request->input('published_to')) {
$publishedTo = Carbon::parse($request->input('published_to'), $request->input('tz'));
$conversionsQuery->where('published_at', '<=', $publishedTo);
$pageviewsQuery->where('published_at', '<=', $publishedTo);
}
if ($request->input('conversion_from')) {
$conversionFrom = Carbon::parse($request->input('conversion_from'), $request->input('tz'));
$conversionsQuery->where('paid_at', '>=', $conversionFrom);
}
if ($request->input('conversion_to')) {
$conversionTo = Carbon::parse($request->input('conversion_to'), $request->input('tz'));
$conversionsQuery->where('paid_at', '<=', $conversionTo);
}
$tags = Tag::selectRaw(implode(",", $cols))
->leftJoin(DB::raw("({$conversionsQuery->toSql()}) as c"), 'tags.id', '=', 'c.tag_id')->addBinding($conversionsQuery->getBindings())
->leftJoin(DB::raw("({$pageviewsQuery->toSql()}) as pv"), 'tags.id', '=', 'pv.tag_id')->addBinding($pageviewsQuery->getBindings())
->ofSelectedProperty()
->groupBy(['tags.name', 'tags.id', 'articles_count', 'conversions_count', 'conversions_amount', 'pageviews_all',
'pageviews_not_subscribed', 'pageviews_subscribers', 'timespent_all', 'timespent_not_subscribed', 'timespent_subscribers']);
if (isset($this->tagCategory)) {
$tags->whereIn('tags.id', $this->tagCategory->tags()->pluck('tags.id'));
}
$conversionsQuery = Conversion::selectRaw('count(distinct conversions.id) as count, sum(amount) as sum, currency, article_tag.tag_id')
->join('article_tag', 'conversions.article_id', '=', 'article_tag.article_id')
->join('articles', 'article_tag.article_id', '=', 'articles.id')
->ofSelectedProperty()
->groupBy(['article_tag.tag_id', 'conversions.currency']);
if ($request->input('content_type') && $request->input('content_type') !== 'all') {
$conversionsQuery->where('content_type', '=', $request->input('content_type'));
}
if ($request->input('published_from')) {
$conversionsQuery->where('published_at', '>=', Carbon::parse($request->input('published_from'), $request->input('tz')));
}
if ($request->input('published_to')) {
$conversionsQuery->where('published_at', '<=', Carbon::parse($request->input('published_to'), $request->input('tz')));
}
if ($request->input('conversion_from')) {
$conversionFrom = Carbon::parse($request->input('conversion_from'), $request->input('tz'));
$conversionsQuery->where('paid_at', '>=', $conversionFrom);
}
if ($request->input('conversion_to')) {
$conversionTo = Carbon::parse($request->input('conversion_to'), $request->input('tz'));
$conversionsQuery->where('paid_at', '<=', $conversionTo);
}
$conversionAmounts = [];
$conversionCounts = [];
foreach ($conversionsQuery->get() as $record) {
$conversionAmounts[$record['tag_id']][$record->currency] = $record['sum'];
if (!isset($conversionCounts[$record['tag_id']])) {
$conversionCounts[$record['tag_id']] = 0;
}
$conversionCounts[$record['tag_id']] += $record['count'];
}
/** @var QueryDataTable $datatable */
$datatable = $datatables->of($tags);
return $datatable
->addColumn('id', function (Tag $tag) {
return $tag->id;
})
->addColumn('name', function (Tag $tag) {
return [
'url' => route('tags.show', ['tag' => $tag]),
'text' => $tag->name,
];
})
->filterColumn('name', function (Builder $query, $value) use ($request) {
if ($request->input('search')['value'] === $value) {
$query->where(function (Builder $query) use ($value) {
$query->where('tags.name', 'like', '%' . $value . '%');
});
} else {
$tagIds = explode(',', $value);
$query->where(function (Builder $query) use ($tagIds) {
$query->whereIn('tags.id', $tagIds);
});
}
})
->addColumn('conversions_count', function (Tag $tag) use ($conversionCounts) {
return $conversionCounts[$tag->id] ?? 0;
})
->addColumn('conversions_amount', function (Tag $tag) use ($conversionAmounts) {
if (!isset($conversionAmounts[$tag->id])) {
return 0;
}
$amounts = [];
foreach ($conversionAmounts[$tag->id] as $currency => $c) {
$c = round($c, 2);
$amounts[] = "{$c} {$currency}";
}
return $amounts ?: [0];
})
->orderColumn('conversions_count', 'conversions_count $1')
->orderColumn('conversions_amount', 'conversions_amount $1')
->orderColumn('articles_count', 'articles_count $1')
->orderColumn('pageviews_all', 'pageviews_all $1')
->orderColumn('pageviews_not_subscribed', 'pageviews_not_subscribed $1')
->orderColumn('pageviews_subscribers', 'pageviews_subscribers $1')
->orderColumn('avg_timespent_all', 'avg_timespent_all $1')
->orderColumn('avg_timespent_not_subscribed', 'avg_timespent_not_subscribed $1')
->orderColumn('avg_timespent_subscribers', 'avg_timespent_subscribers $1')
->orderColumn('id', 'tags.id $1')
->setTotalRecords(PHP_INT_MAX)
->setFilteredRecords(PHP_INT_MAX)
->make(true);
}
public function setTagCategory(TagCategory $tagCategory): void
{
$this->tagCategory = $tagCategory;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Author.php | Beam/extensions/beam-module/src/Model/Author.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasManyThrough;
use Remp\BeamModule\Database\Factories\AuthorFactory;
use Remp\Journal\TokenProvider;
use Spatie\Searchable\Searchable;
use Spatie\Searchable\SearchResult;
class Author extends BaseModel implements Searchable
{
use HasFactory;
protected $fillable = [
'name',
'external_id',
];
protected $hidden = [
'id',
'pivot',
];
protected static function newFactory(): AuthorFactory
{
return AuthorFactory::new();
}
public function getSearchResult(): SearchResult
{
return new SearchResult($this, $this->name);
}
public function articles(): BelongsToMany
{
return $this->belongsToMany(Article::class);
}
public function latestPublishedArticle()
{
return $this->articles()->orderBy('published_at', 'DESC')->take(1);
}
public function conversions(): HasManyThrough
{
return $this->hasManyThrough(Conversion::class, ArticleAuthor::class, 'article_author.author_id', 'conversions.article_id', 'id', 'article_id');
}
public function scopeOfSelectedProperty(Builder $query): Builder
{
$tokenProvider = resolve(TokenProvider::class);
$propertyUuid = $tokenProvider->getToken();
if ($propertyUuid) {
$query->whereHas('articles', function (Builder $articlesQuery) {
$articlesQuery->ofSelectedProperty();
});
}
return $query;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Property.php | Beam/extensions/beam-module/src/Model/Property.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Remp\BeamModule\Database\Factories\PropertyFactory;
class Property extends BaseModel
{
use HasFactory;
protected $fillable = ['uuid', 'name'];
protected static function newFactory(): PropertyFactory
{
return PropertyFactory::new();
}
public function account(): BelongsTo
{
return $this->belongsTo(Account::class);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Segment.php | Beam/extensions/beam-module/src/Model/Segment.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Remp\BeamModule\Database\Factories\SegmentFactory;
use Spatie\Searchable\Searchable;
use Spatie\Searchable\SearchResult;
class Segment extends BaseModel implements Searchable
{
use HasFactory;
use TableName;
protected $casts = [
'active' => 'boolean',
];
protected $attributes = [
'active' => false,
];
protected $fillable = [
'name',
'code',
'active',
'segment_group_id'
];
protected static function newFactory(): SegmentFactory
{
return SegmentFactory::new();
}
public function getSearchResult(): SearchResult
{
return new SearchResult($this, $this->name);
}
public function rules(): HasMany
{
return $this->hasMany(SegmentRule::class);
}
public function users(): HasMany
{
return $this->hasMany(SegmentUser::class);
}
public function browsers(): HasMany
{
return $this->hasMany(SegmentBrowser::class);
}
public function segmentGroup(): BelongsTo
{
return $this->belongsTo(SegmentGroup::class);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/DashboardArticle.php | Beam/extensions/beam-module/src/Model/DashboardArticle.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class DashboardArticle extends BaseModel
{
protected $fillable = [
'unique_browsers',
'last_dashboard_time',
];
protected $hidden = [
'id',
];
public function article(): BelongsTo
{
return $this->belongsTo(Article::class);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/TagCategory.php | Beam/extensions/beam-module/src/Model/TagCategory.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Remp\BeamModule\Database\Factories\TagCategoryFactory;
use Remp\Journal\TokenProvider;
class TagCategory extends BaseModel
{
use HasFactory;
protected $fillable = [
'name',
'external_id',
];
protected $hidden = [
'id',
'pivot',
'created_at',
'updated_at'
];
protected static function newFactory(): TagCategoryFactory
{
return TagCategoryFactory::new();
}
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class);
}
public function scopeOfSelectedProperty(Builder $query): Builder
{
$tokenProvider = resolve(TokenProvider::class);
$propertyUuid = $tokenProvider->getToken();
if ($propertyUuid) {
$query->whereHas('tags', function (Builder $tagsQuery) {
/** @var Builder|Tag $tagsQuery */
$tagsQuery->ofSelectedProperty();
});
}
return $query;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ArticleViewsSnapshot.php | Beam/extensions/beam-module/src/Model/ArticleViewsSnapshot.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Remp\BeamModule\Database\Factories\ArticleViewsSnapshotFactory;
use Remp\BeamModule\Model\Property\SelectedProperty;
use Remp\BeamModule\Model\Scopes\PropertyTokenScope;
use DB;
class ArticleViewsSnapshot extends BaseModel
{
use HasFactory;
use TableName;
public $timestamps = false;
protected $fillable = [
'time',
'property_token',
'external_article_id',
'referer_medium',
'count'
];
protected $casts = [
'count' => 'integer',
'time' => 'datetime',
];
protected static function newFactory(): ArticleViewsSnapshotFactory
{
return ArticleViewsSnapshotFactory::new();
}
/**
* By default, apply property token filtering when selecting snapshot data
*/
protected static function boot()
{
parent::boot();
$selectedProperty = resolve(SelectedProperty::class);
static::addGlobalScope(new PropertyTokenScope($selectedProperty));
}
public static function deleteForTimes(array $times): int
{
return DB::table(self::getTableName())
->whereIn('time', $times)
->delete();
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Section.php | Beam/extensions/beam-module/src/Model/Section.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Remp\BeamModule\Database\Factories\SectionFactory;
use Remp\Journal\TokenProvider;
class Section extends BaseModel
{
use HasFactory;
protected $fillable = [
'name',
'external_id',
];
protected $hidden = [
'id',
'pivot',
];
protected static function newFactory(): SectionFactory
{
return SectionFactory::new();
}
public function articles(): BelongsToMany
{
return $this->belongsToMany(Article::class);
}
// Scopes
public function scopeOfSelectedProperty(Builder $query): Builder
{
$tokenProvider = resolve(TokenProvider::class);
$propertyUuid = $tokenProvider->getToken();
if ($propertyUuid) {
$query->whereHas('articles', function (Builder $articlesQuery) {
/** @var Builder|Article $articlesQuery */
$articlesQuery->ofSelectedProperty();
});
}
return $query;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/TableName.php | Beam/extensions/beam-module/src/Model/TableName.php | <?php
namespace Remp\BeamModule\Model;
trait TableName
{
/**
* Static function for getting table name.
*
* @return string
*/
public static function getTableName()
{
$class = get_called_class();
return (new $class())->getTable();
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ConversionSource.php | Beam/extensions/beam-module/src/Model/ConversionSource.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ConversionSource extends BaseModel
{
// source determined based on the first pageview of session prior to the payment
public const TYPE_SESSION_FIRST = 'session_first';
// source determined based on the last pageview of session prior to the payment
public const TYPE_SESSION_LAST = 'session_last';
protected $fillable = [
'conversion_id',
'type',
'referer_medium',
'referer_source',
'referer_host_with_path',
'article_id',
];
protected $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
public function conversion(): BelongsTo
{
return $this->belongsTo(Conversion::class);
}
public static function getTypes()
{
return [
self::TYPE_SESSION_LAST,
self::TYPE_SESSION_FIRST
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/BaseModel.php | Beam/extensions/beam-module/src/Model/BaseModel.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Model;
abstract class BaseModel extends Model
{
/**
* asDateTime forces timezone of any date value within the model to be set in the default timezone.
*
* The reason why this method exists is that sometimes PHP ignores the requested timezone in the DateTime object
* and uses the timezone provided in the RFC3339 datetime string. That caused following scenarios:
*
* - Application would try to parse "2021-06-09T20:04:02+02:00".
* - Carbon instance would internally store it in the "+02:00" timezone, not the default timezone.
* - Laravel would format the date to "2021-06-09 20:04:02" and store it to the database.
*
* Database connection is forced to be in +00:00, so the database would accept it as "2021-06-09T20:04:02+00:00".
*
* Because of that, we need to make sure all the dates are in the default timezone before they're written
* to the database.
*/
protected function asDateTime($value)
{
$dateTime = parent::asDateTime($value);
$dateTime->setTimezone(new \DateTimeZone(date_default_timezone_get()));
return $dateTime;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Conversion.php | Beam/extensions/beam-module/src/Model/Conversion.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Carbon;
use Remp\BeamModule\Database\Factories\ConversionFactory;
use Remp\Journal\TokenProvider;
class Conversion extends BaseModel
{
use HasFactory;
protected $fillable = [
'article_external_id',
'transaction_id',
'amount',
'currency',
'paid_at',
'user_id',
'events_aggregated',
];
protected $casts = [
'events_aggregated' => 'boolean',
'source_processed' => 'boolean',
'paid_at' => 'datetime',
];
protected static function newFactory(): ConversionFactory
{
return ConversionFactory::new();
}
public function article(): BelongsTo
{
return $this->belongsTo(Article::class);
}
public function commerceEvents(): HasMany
{
return $this->hasMany(ConversionCommerceEvent::class);
}
public function pageviewEvents(): HasMany
{
return $this->hasMany(ConversionPageviewEvent::class);
}
public function generalEvents(): HasMany
{
return $this->hasMany(ConversionGeneralEvent::class);
}
public function conversionSources(): HasMany
{
return $this->hasMany(ConversionSource::class);
}
// Scopes
public function scopeOfSelectedProperty(Builder $query): Builder
{
$tokenProvider = resolve(TokenProvider::class);
$propertyUuid = $tokenProvider->getToken();
if ($propertyUuid) {
$query->whereHas('article', function (Builder $articleQuery) {
$articleQuery->ofSelectedProperty();
});
}
return $query;
}
public function setArticleExternalIdAttribute($articleExternalId)
{
$article = Article::select()->where([
'external_id' => $articleExternalId
])->first();
if (!$article) {
throw new ModelNotFoundException(sprintf('Unable to link conversion to article %s, no internal record found', $articleExternalId));
}
$this->article_id = $article->id;
}
public function setPaidAtAttribute($value)
{
if (!$value) {
return;
}
$this->attributes['paid_at'] = new Carbon($value);
}
public static function getAggregatedConversionsWithoutSource()
{
return Conversion::select()
->where('events_aggregated', true)
->where('source_processed', false)
->get();
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/SegmentBrowser.php | Beam/extensions/beam-module/src/Model/SegmentBrowser.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Remp\BeamModule\Database\Factories\SegmentBrowserFactory;
class SegmentBrowser extends BaseModel
{
use HasFactory;
use TableName;
protected $fillable = [
'segment_id',
'browser',
];
protected static function newFactory(): SegmentBrowserFactory
{
return SegmentBrowserFactory::new();
}
public function segment(): BelongsTo
{
return $this->belongsTo(Segment::class);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ViewsPerBrowserMv.php | Beam/extensions/beam-module/src/Model/ViewsPerBrowserMv.php | <?php
namespace Remp\BeamModule\Model;
use Remp\BeamModule\Model\BaseModel;
/**
* Class ViewsPerBrowserMv
* Temporary entity working with table representing materialized view
* TODO this will go out after remp#253 issue is closed
* @package App
*/
class ViewsPerBrowserMv extends BaseModel
{
protected $table = 'views_per_browser_mv';
protected $keyType = 'string';
public $timestamps = false;
protected $casts = [
'total_views' => 'integer',
];
protected $fillable = [
'browser_id',
'total_views',
];
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ArticleSection.php | Beam/extensions/beam-module/src/Model/ArticleSection.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Remp\Journal\TokenProvider;
class ArticleSection extends BaseModel
{
protected $table = 'article_section';
public function section(): BelongsTo
{
return $this->belongsTo(Section::class);
}
public function article(): BelongsTo
{
return $this->belongsTo(Article::class);
}
public function scopeOfSelectedProperty(Builder $query): Builder
{
$tokenProvider = resolve(TokenProvider::class);
$propertyUuid = $tokenProvider->getToken();
if ($propertyUuid) {
$query->whereHas('article', function (Builder $articlesQuery) {
$articlesQuery->ofSelectedProperty();
});
}
return $query;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/SegmentGroup.php | Beam/extensions/beam-module/src/Model/SegmentGroup.php | <?php
namespace Remp\BeamModule\Model;
class SegmentGroup extends BaseModel
{
const CODE_AUTHORS_SEGMENTS = 'authors-segments';
const CODE_SECTIONS_SEGMENTS = 'sections-segments';
const CODE_REMP_SEGMENTS = 'remp-segments';
const TYPE_RULE = 'rule';
const TYPE_EXPLICIT = 'explicit';
public static function getByCode($code)
{
return SegmentGroup::where('code', $code)->first();
}
protected $fillable = [
'name',
'code',
'type',
'sorting',
];
protected $casts = [
'sorting' => 'integer',
];
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ArticleTimespent.php | Beam/extensions/beam-module/src/Model/ArticleTimespent.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Remp\BeamModule\Database\Factories\ArticleTimespentFactory;
class ArticleTimespent extends BaseModel implements Aggregable
{
use HasFactory;
public $timestamps = false;
protected $fillable = [
'article_id',
'time_from',
'time_to',
'sum',
'signed_in',
'subscribers',
];
protected static function newFactory(): ArticleTimespentFactory
{
return ArticleTimespentFactory::new();
}
public function aggregatedFields(): array
{
return ['sum', 'signed_in', 'subscribers'];
}
public function groupableFields(): array
{
return ['article_id'];
}
protected $casts = [
'sum' => 'integer',
'signed_in' => 'integer',
'subscribers' => 'integer',
'time_from' => 'datetime',
'time_to' => 'datetime',
];
public function article(): BelongsTo
{
return $this->belongsTo(Article::class);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/NewsletterCriterion.php | Beam/extensions/beam-module/src/Model/NewsletterCriterion.php | <?php
namespace Remp\BeamModule\Model;
use Cache;
use Exception;
use Illuminate\Support\Collection;
use Remp\BeamModule\Helpers\Misc;
use Remp\BeamModule\Model\Newsletter\NewsletterCriterionEnum;
class NewsletterCriterion
{
public function __construct(private NewsletterCriterionEnum $selectedCriterion)
{
}
public static function allCriteriaConcatenated($glue = ',')
{
return implode($glue, array_column(NewsletterCriterionEnum::cases(), 'value'));
}
public function getArticles(
string $timespan,
?int $articlesCount = null,
array $ignoreAuthors = [],
array $ignoreContentTypes = []
): Collection {
$start = Misc::timespanInPast($timespan);
$query = Article::distinct();
switch ($this->selectedCriterion) {
case NewsletterCriterionEnum::TimespentAll:
$query->mostReadByTimespent($start, 'sum', $articlesCount);
break;
case NewsletterCriterionEnum::TimespentSubscribers:
$query->mostReadByTimespent($start, 'subscribers', $articlesCount);
break;
case NewsletterCriterionEnum::TimespentSignedIn:
$query->mostReadByTimespent($start, 'signed_in', $articlesCount);
break;
case NewsletterCriterionEnum::PageViewsAll:
$query->mostReadByPageviews($start, 'sum', $articlesCount);
break;
case NewsletterCriterionEnum::PageViewsSubscribers:
$query->mostReadByPageviews($start, 'subscribers', $articlesCount);
break;
case NewsletterCriterionEnum::PageViewsSignedIn:
$query->mostReadByPageviews($start, 'signed_in', $articlesCount);
break;
case NewsletterCriterionEnum::Conversions:
$query->mostReadByTotalPaymentAmount($start, $articlesCount);
break;
case NewsletterCriterionEnum::AveragePayment:
$query->mostReadByAveragePaymentAmount($start, $articlesCount);
break;
case NewsletterCriterionEnum::Bookmarks:
throw new Exception('not implemented');
default:
throw new Exception('unknown article criterion ' . $this->selectedCriterion->value);
}
// Do not consider older articles
$query->publishedBetween($start);
$ignoreAuthorIds = Author::whereIn('name', $ignoreAuthors)->pluck('id')->toArray();
return $query
->ignoreAuthorIds($ignoreAuthorIds)
->ignoreContentTypes($ignoreContentTypes)
->get();
}
/**
* @param string $timespan
* @param array $ignoreAuthors
*
* @return array of articles (containing only external_id and url attributes)
*/
public function getCachedArticles(string $timespan, array $ignoreAuthors = [], array $ignoreContentTypes = []): array
{
$tag = 'top_articles';
$key = $tag . '|' . $this->selectedCriterion->value . '|' . $timespan;
return Cache::tags($tag)->remember($key, 300, function () use ($timespan, $ignoreAuthors, $ignoreContentTypes) {
return $this->getArticles($timespan, null, $ignoreAuthors, $ignoreContentTypes)->map(function ($article) {
$item = new \stdClass();
$item->external_id = $article->external_id;
$item->url = $article->url;
return $item;
})->toArray();
});
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/SegmentUser.php | Beam/extensions/beam-module/src/Model/SegmentUser.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Remp\BeamModule\Database\Factories\SegmentUserFactory;
class SegmentUser extends BaseModel
{
use HasFactory;
use TableName;
protected $fillable = [
'segment_id',
'user_id',
];
protected static function newFactory(): SegmentUserFactory
{
return SegmentUserFactory::new();
}
public function segment(): BelongsTo
{
return $this->belongsTo(Segment::class);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ConversionGeneralEvent.php | Beam/extensions/beam-module/src/Model/ConversionGeneralEvent.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ConversionGeneralEvent extends BaseModel
{
protected $casts = [
'minutes_to_conversion' => 'integer',
'event_prior_conversion' => 'integer',
'time' => 'datetime',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
protected $fillable = [
'time',
'action',
'category',
'conversion_id',
'rtm_campaign',
'rtm_content',
'rtm_medium',
'rtm_source',
'minutes_to_conversion',
'event_prior_conversion',
];
public function conversion(): BelongsTo
{
return $this->belongsTo(Conversion::class);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/RefererMediumLabel.php | Beam/extensions/beam-module/src/Model/RefererMediumLabel.php | <?php
namespace Remp\BeamModule\Model;
class RefererMediumLabel extends BaseModel
{
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ConversionPageviewEvent.php | Beam/extensions/beam-module/src/Model/ConversionPageviewEvent.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class ConversionPageviewEvent extends BaseModel
{
protected $casts = [
'locked' => 'boolean',
'signed_in' => 'boolean',
'minutes_to_conversion' => 'integer',
'event_prior_conversion' => 'integer',
'time' => 'datetime',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
protected $fillable = [
'time',
'article_id',
'locked',
'signed_in',
'timespent',
'rtm_campaign',
'rtm_content',
'rtm_medium',
'rtm_source',
'conversion_id',
'minutes_to_conversion',
'event_prior_conversion',
];
public function conversion(): BelongsTo
{
return $this->belongsTo(Conversion::class);
}
public function article(): BelongsTo
{
return $this->belongsTo(Article::class);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ArticleTag.php | Beam/extensions/beam-module/src/Model/ArticleTag.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Remp\Journal\TokenProvider;
class ArticleTag extends BaseModel
{
protected $table = 'article_tag';
public function tag(): BelongsTo
{
return $this->belongsTo(Tag::class);
}
public function article(): BelongsTo
{
return $this->belongsTo(Article::class);
}
public function scopeOfSelectedProperty(Builder $query): Builder
{
$tokenProvider = resolve(TokenProvider::class);
$propertyUuid = $tokenProvider->getToken();
if ($propertyUuid) {
$query->whereHas('article', function (Builder $articleQuery) {
$articleQuery->ofSelectedProperty();
});
}
return $query;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ViewsPerUserMv.php | Beam/extensions/beam-module/src/Model/ViewsPerUserMv.php | <?php
namespace Remp\BeamModule\Model;
use Remp\BeamModule\Model\BaseModel;
/*
* Class ViewsPerUserMv
* Temporary entity working with table representing materialized view
* TODO this will go out after remp#253 issue is closed
* @package App
*/
class ViewsPerUserMv extends BaseModel
{
protected $table = 'views_per_user_mv';
protected $keyType = 'string';
public $timestamps = false;
protected $casts = [
'total_views_last_30_days' => 'integer',
'total_views_last_60_days' => 'integer',
'total_views_last_90_days' => 'integer',
];
protected $fillable = [
'user_id',
'total_views_last_30_days',
'total_views_last_60_days',
'total_views_last_90_days',
];
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ConversionCommerceEvent.php | Beam/extensions/beam-module/src/Model/ConversionCommerceEvent.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Remp\BeamModule\Database\Factories\ConversionCommerceEventFactory;
class ConversionCommerceEvent extends BaseModel
{
use HasFactory;
protected $casts = [
'minutes_to_conversion' => 'integer',
'event_prior_conversion' => 'integer',
'time' => 'datetime',
'created_at' => 'datetime',
'updated_at' => 'datetime',
];
protected $fillable = [
'time',
'step',
'funnel_id',
'amount',
'currency',
'rtm_campaign',
'rtm_content',
'rtm_medium',
'rtm_source',
'conversion_id',
'minutes_to_conversion',
'event_prior_conversion',
];
protected static function newFactory(): ConversionCommerceEventFactory
{
return ConversionCommerceEventFactory::new();
}
public function conversion(): BelongsTo
{
return $this->belongsTo(Conversion::class);
}
public function products(): HasMany
{
return $this->hasMany(ConversionCommerceEventProduct::class);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Aggregable.php | Beam/extensions/beam-module/src/Model/Aggregable.php | <?php
namespace Remp\BeamModule\Model;
interface Aggregable
{
/**
* These fields will be aggregated (= summed for that particular day) after 90 days
* to save DB space by CompressAggregations command
* @return array
*/
public function aggregatedFields(): array;
/**
* When doing aggregation, we want put sum of aggregated fields of these columns into different buckets
* e.g. we want to distinguish between referer sources (email, direct)
* and do not aggregate them together for that particular day
* @return array
*/
public function groupableFields(): array;
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/TagTagCategory.php | Beam/extensions/beam-module/src/Model/TagTagCategory.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Remp\Journal\TokenProvider;
class TagTagCategory extends BaseModel
{
protected $table = 'tag_tag_category';
public function tag(): BelongsTo
{
return $this->belongsTo(Tag::class);
}
public function tagCategory(): BelongsTo
{
return $this->belongsTo(TagCategory::class);
}
public function scopeOfSelectedProperty(Builder $query): Builder
{
$tokenProvider = resolve(TokenProvider::class);
$propertyUuid = $tokenProvider->getToken();
if ($propertyUuid) {
$query->whereHas('tag', function (Builder $tagQuery) {
/** @var Builder|Tag $tagQuery */
$tagQuery->ofSelectedProperty();
});
}
return $query;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/TagCategoriesDataTable.php | Beam/extensions/beam-module/src/Model/TagCategoriesDataTable.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Remp\BeamModule\Model\Rules\ValidCarbonDate;
use Yajra\DataTables\DataTables;
use Yajra\DataTables\QueryDataTable;
class TagCategoriesDataTable
{
public function getDataTable(Request $request, DataTables $datatables)
{
$request->validate([
'published_from' => ['sometimes', new ValidCarbonDate],
'published_to' => ['sometimes', new ValidCarbonDate],
'conversion_from' => ['sometimes', new ValidCarbonDate],
'conversion_to' => ['sometimes', new ValidCarbonDate],
]);
$cols = [
'tag_categories.id',
'tag_categories.name',
'COALESCE(tags_count, 0) AS tags_count',
'COALESCE(articles_count, 0) AS articles_count',
'COALESCE(conversions_count, 0) AS conversions_count',
'COALESCE(conversions_amount, 0) AS conversions_amount',
'COALESCE(pageviews_all, 0) AS pageviews_all',
'COALESCE(pageviews_not_subscribed, 0) AS pageviews_not_subscribed',
'COALESCE(pageviews_subscribers, 0) AS pageviews_subscribers',
'COALESCE(timespent_all, 0) AS timespent_all',
'COALESCE(timespent_not_subscribed, 0) AS timespent_not_subscribed',
'COALESCE(timespent_subscribers, 0) AS timespent_subscribers',
'COALESCE(timespent_all / pageviews_all, 0) AS avg_timespent_all',
'COALESCE(timespent_not_subscribed / pageviews_not_subscribed, 0) AS avg_timespent_not_subscribed',
'COALESCE(timespent_subscribers / pageviews_subscribers, 0) AS avg_timespent_subscribers',
];
$tagCategoryTagsQuery = TagTagCategory::selectRaw(implode(',', [
'tag_category_id',
'COUNT(DISTINCT tag_tag_category.tag_id) as tags_count'
]))
->ofSelectedProperty()
->groupBy('tag_category_id');
$tagCategoryArticlesQuery = ArticleTag::selectRaw(implode(',', [
'tag_category_id',
'COUNT(DISTINCT articles.id) as articles_count'
]))
->join('articles', 'article_tag.article_id', '=', 'articles.id')
->join('tag_tag_category', 'article_tag.tag_id', '=', 'tag_tag_category.tag_id')
->ofSelectedProperty()
->groupBy('tag_category_id');
if ($request->input('content_type') && $request->input('content_type') !== 'all') {
$tagCategoryArticlesQuery->where('content_type', '=', $request->input('content_type'));
}
$conversionsQuery = Conversion::selectRaw(implode(',', [
'tag_tag_category.tag_category_id',
'count(distinct conversions.id) as conversions_count',
'sum(conversions.amount) as conversions_amount',
]))
->leftJoin('article_tag', 'conversions.article_id', '=', 'article_tag.article_id')
->join('tag_tag_category', 'tag_tag_category.tag_id', '=', 'article_tag.tag_id')
->leftJoin('articles', 'article_tag.article_id', '=', 'articles.id')
->ofSelectedProperty()
->groupBy('tag_tag_category.tag_category_id');
$pageviewsQuery = Article::selectRaw(implode(',', [
'tag_tag_category.tag_category_id',
'COALESCE(SUM(pageviews_all), 0) AS pageviews_all',
'COALESCE(SUM(pageviews_all) - SUM(pageviews_subscribers), 0) AS pageviews_not_subscribed',
'COALESCE(SUM(pageviews_subscribers), 0) AS pageviews_subscribers',
'COALESCE(SUM(timespent_all), 0) AS timespent_all',
'COALESCE(SUM(timespent_all) - SUM(timespent_subscribers), 0) AS timespent_not_subscribed',
'COALESCE(SUM(timespent_subscribers), 0) AS timespent_subscribers',
]))
->leftJoin('article_tag', 'articles.id', '=', 'article_tag.article_id')
->join('tag_tag_category', 'tag_tag_category.tag_id', '=', 'article_tag.tag_id')
->ofSelectedProperty()
->groupBy('tag_tag_category.tag_category_id');
if ($request->input('content_type') && $request->input('content_type') !== 'all') {
$pageviewsQuery->where('content_type', '=', $request->input('content_type'));
$conversionsQuery->where('content_type', '=', $request->input('content_type'));
}
if ($request->input('published_from')) {
$publishedFrom = Carbon::parse($request->input('published_from'), $request->input('tz'));
$tagCategoryArticlesQuery->where('published_at', '>=', $publishedFrom);
$conversionsQuery->where('published_at', '>=', $publishedFrom);
$pageviewsQuery->where('published_at', '>=', $publishedFrom);
}
if ($request->input('published_to')) {
$publishedTo = Carbon::parse($request->input('published_to'), $request->input('tz'));
$tagCategoryArticlesQuery->where('published_at', '<=', $publishedTo);
$conversionsQuery->where('published_at', '<=', $publishedTo);
$pageviewsQuery->where('published_at', '<=', $publishedTo);
}
if ($request->input('conversion_from')) {
$conversionFrom = Carbon::parse($request->input('conversion_from'), $request->input('tz'));
$conversionsQuery->where('paid_at', '>=', $conversionFrom);
}
if ($request->input('conversion_to')) {
$conversionTo = Carbon::parse($request->input('conversion_to'), $request->input('tz'));
$conversionsQuery->where('paid_at', '<=', $conversionTo);
}
$tagCategories = TagCategory::selectRaw(implode(",", $cols))
->leftJoin(DB::raw("({$tagCategoryArticlesQuery->toSql()}) as aa"), 'tag_categories.id', '=', 'aa.tag_category_id')->addBinding($tagCategoryArticlesQuery->getBindings())
->leftJoin(DB::raw("({$conversionsQuery->toSql()}) as c"), 'tag_categories.id', '=', 'c.tag_category_id')->addBinding($conversionsQuery->getBindings())
->leftJoin(DB::raw("({$pageviewsQuery->toSql()}) as pv"), 'tag_categories.id', '=', 'pv.tag_category_id')->addBinding($pageviewsQuery->getBindings())
->leftJoin(DB::raw("({$tagCategoryTagsQuery->toSql()}) as tct"), 'tag_categories.id', '=', 'tct.tag_category_id')->addBinding($tagCategoryTagsQuery->getBindings())
->ofSelectedProperty()
->groupBy(['tag_categories.name', 'tag_categories.id', 'articles_count', 'conversions_count', 'conversions_amount', 'pageviews_all',
'pageviews_not_subscribed', 'pageviews_subscribers', 'timespent_all', 'timespent_not_subscribed', 'timespent_subscribers']);
$conversionsQuery = Conversion::selectRaw('count(distinct conversions.id) as count, sum(amount) as sum, currency, tag_tag_category.tag_category_id')
->join('article_tag', 'conversions.article_id', '=', 'article_tag.article_id')
->join('tag_tag_category', 'tag_tag_category.tag_id', '=', 'article_tag.tag_id')
->join('articles', 'article_tag.article_id', '=', 'articles.id')
->ofSelectedProperty()
->groupBy(['tag_tag_category.tag_category_id', 'conversions.currency']);
if ($request->input('content_type') && $request->input('content_type') !== 'all') {
$conversionsQuery->where('content_type', '=', $request->input('content_type'));
}
if ($request->input('published_from')) {
$conversionsQuery->where('published_at', '>=', Carbon::parse($request->input('published_from'), $request->input('tz')));
}
if ($request->input('published_to')) {
$conversionsQuery->where('published_at', '<=', Carbon::parse($request->input('published_to'), $request->input('tz')));
}
if ($request->input('conversion_from')) {
$conversionFrom = Carbon::parse($request->input('conversion_from'), $request->input('tz'));
$conversionsQuery->where('paid_at', '>=', $conversionFrom);
}
if ($request->input('conversion_to')) {
$conversionTo = Carbon::parse($request->input('conversion_to'), $request->input('tz'));
$conversionsQuery->where('paid_at', '<=', $conversionTo);
}
$conversionAmounts = [];
$conversionCounts = [];
foreach ($conversionsQuery->get() as $record) {
$conversionAmounts[$record['tag_category_id']][$record->currency] = $record['sum'];
if (!isset($conversionCounts[$record['tag_category_id']])) {
$conversionCounts[$record['tag_category_id']] = 0;
}
$conversionCounts[$record['tag_category_id']] += $record['count'];
}
/** @var QueryDataTable $datatable */
$datatable = $datatables->of($tagCategories);
return $datatable
->addColumn('id', function (TagCategory $tagCategory) {
return $tagCategory->id;
})
->addColumn('name', function (TagCategory $tagCategory) {
return [
'url' => route('tag-categories.show', $tagCategory->id),
'text' => $tagCategory->name,
];
})
->filterColumn('name', function (Builder $query, $value) use ($request) {
if ($request->input('search')['value'] === $value) {
$query->where(function (Builder $query) use ($value) {
$query->where('tag_categories.name', 'like', '%' . $value . '%');
});
} else {
$tagCategoryIds = explode(',', $value);
$query->where(function (Builder $query) use ($tagCategoryIds) {
$query->whereIn('tag_categories.id', $tagCategoryIds);
});
}
})
->addColumn('conversions_count', function (TagCategory $tagCategory) use ($conversionCounts) {
return $conversionCounts[$tagCategory->id] ?? 0;
})
->addColumn('conversions_amount', function (TagCategory $tagCategory) use ($conversionAmounts) {
if (!isset($conversionAmounts[$tagCategory->id])) {
return 0;
}
$amounts = [];
foreach ($conversionAmounts[$tagCategory->id] as $currency => $c) {
$c = round($c, 2);
$amounts[] = "{$c} {$currency}";
}
return $amounts ?: [0];
})
->orderColumn('conversions_count', 'conversions_count $1')
->orderColumn('conversions_amount', 'conversions_amount $1')
->orderColumn('tags_count', 'tags_count $1')
->orderColumn('articles_count', 'articles_count $1')
->orderColumn('pageviews_all', 'pageviews_all $1')
->orderColumn('pageviews_not_subscribed', 'pageviews_not_subscribed $1')
->orderColumn('pageviews_subscribers', 'pageviews_subscribers $1')
->orderColumn('avg_timespent_all', 'avg_timespent_all $1')
->orderColumn('avg_timespent_not_subscribed', 'avg_timespent_not_subscribed $1')
->orderColumn('avg_timespent_subscribers', 'avg_timespent_subscribers $1')
->orderColumn('id', 'tag_categories.id $1')
->make(true);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ArticlesDataTable.php | Beam/extensions/beam-module/src/Model/ArticlesDataTable.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Remp\BeamModule\Model\Rules\ValidCarbonDate;
use Yajra\DataTables\DataTables;
use Yajra\DataTables\QueryDataTable;
class ArticlesDataTable
{
private Author $author;
private Section $section;
private Tag $tag;
private TagCategory $tagCategory;
public function getDataTable(Request $request, DataTables $datatables)
{
$request->validate([
'published_from' => ['sometimes', new ValidCarbonDate],
'published_to' => ['sometimes', new ValidCarbonDate],
'conversion_from' => ['sometimes', new ValidCarbonDate],
'conversion_to' => ['sometimes', new ValidCarbonDate],
]);
// main articles query to fetch list of all articles with related metadata
$articles = Article::selectRaw(implode(',', [
"articles.id",
"articles.title",
"articles.published_at",
"articles.url",
"articles.content_type",
"articles.pageviews_all",
"articles.pageviews_signed_in",
"articles.pageviews_subscribers",
"articles.timespent_all",
"articles.timespent_signed_in",
"articles.timespent_subscribers",
'timespent_all / pageviews_all as avg_timespent_all',
'timespent_signed_in / pageviews_signed_in as avg_timespent_signed_in',
'timespent_subscribers / pageviews_subscribers as avg_timespent_subscribers',
]))
->with(['authors', 'sections', 'tags'])
->ofSelectedProperty()
->groupBy(['articles.id', 'articles.title', 'articles.published_at', 'articles.url', "articles.pageviews_all",
"articles.pageviews_signed_in", "articles.pageviews_subscribers", "articles.timespent_all",
"articles.timespent_signed_in", "articles.timespent_subscribers", 'avg_timespent_all',
'avg_timespent_signed_in', 'avg_timespent_subscribers']);
// filtering query (used as subquery - joins were messing with counts and sums) to fetch matching conversions
$conversionsFilter = Conversion::distinct()
->join('articles', 'articles.id', '=', 'conversions.article_id')
->ofselectedProperty();
if (isset($this->author)) {
$articles->leftJoin('article_author', 'articles.id', '=', 'article_author.article_id')
->where(['article_author.author_id' => $this->author->id]);
$conversionsFilter->leftJoin('article_author', 'articles.id', '=', 'article_author.article_id')
->where(['article_author.author_id' => $this->author->id]);
}
if (isset($this->section)) {
$articles->leftJoin('article_section', 'articles.id', '=', 'article_section.article_id')
->where(['article_section.section_id' => $this->section->id]);
$conversionsFilter->leftJoin('article_section', 'articles.id', '=', 'article_section.article_id')
->where(['article_section.section_id' => $this->section->id]);
}
if (isset($this->tag)) {
$articles->leftJoin('article_tag as at1', 'articles.id', '=', 'at1.article_id')
->where(['at1.tag_id' => $this->tag->id]);
$conversionsFilter->leftJoin('article_tag as at1', 'articles.id', '=', 'at1.article_id')
->where(['at1.tag_id' => $this->tag->id]);
}
if (isset($this->tagCategory)) {
$tags = $this->tagCategory->tags()->pluck('tags.id');
$articles->leftJoin('article_tag as at2', 'articles.id', '=', 'at2.article_id')
->whereIn('at2.tag_id', $tags);
$conversionsFilter->leftJoin('article_tag as at2', 'articles.id', '=', 'at2.article_id')
->whereIn('at2.tag_id', $tags);
}
// adding conditions to queries based on request inputs
if ($request->input('published_from')) {
$publishedFrom = Carbon::parse($request->input('published_from'), $request->input('tz'));
$articles->where('published_at', '>=', $publishedFrom);
$conversionsFilter->where('published_at', '>=', $publishedFrom);
}
if ($request->input('published_to')) {
$publishedTo = Carbon::parse($request->input('published_to'), $request->input('tz'));
$articles->where('published_at', '<=', $publishedTo);
$conversionsFilter->where('published_at', '<=', $publishedTo);
}
if ($request->input('conversion_from')) {
$conversionFrom = Carbon::parse($request->input('conversion_from'), $request->input('tz'));
$articles->where('paid_at', '>=', $conversionFrom);
$conversionsFilter->where('paid_at', '>=', $conversionFrom);
}
if ($request->input('conversion_to')) {
$conversionTo = Carbon::parse($request->input('conversion_to'), $request->input('tz'));
$articles->where('paid_at', '<=', $conversionTo);
$conversionsFilter->where('paid_at', '<=', $conversionTo);
}
// fetch conversions that match the filter
$matchedConversions = $conversionsFilter->pluck('conversions.id')->toArray();
// conversion aggregations that are joined to main query (this is required for orderColumn() to work)
$conversionsJoin = Conversion::selectRaw(implode(',', [
'count(*) as conversions_count',
'sum(amount) as conversions_sum',
'avg(amount) as conversions_avg',
'article_id'
]))
->ofSelectedProperty()
->groupBy(['article_id']);
if ($matchedConversions) {
// intentional sprintf, eloquent was using bindings in wrong order in final query
$conversionsJoin->whereRaw(sprintf('id IN (%s)', implode(',', $matchedConversions)));
} else {
// no conversions matched, don't join anything
$conversionsJoin->whereRaw('1 = 0');
}
$articles->leftJoinSub($conversionsJoin, 'conversions', function ($join) {
$join->on('articles.id', '=', 'conversions.article_id');
});
// conversion aggregations for displaying (these are grouped also by the currency)
$conversionsQuery = Conversion::selectRaw(implode(',', [
'count(*) as count',
'sum(amount) as sum',
'avg(amount) as avg',
'currency',
'article_id'
]))
->whereIn('id', $matchedConversions)
->ofSelectedProperty()
->groupBy(['article_id', 'currency']);
$conversionCount = [];
$conversionSum = [];
$conversionAvg = [];
foreach ($conversionsQuery->get() as $record) {
if (!isset($conversionCount[$record->article_id])) {
$conversionCount[$record->article_id] = 0;
}
$conversionCount[$record->article_id] += $record['count'];
$conversionSum[$record->article_id][$record->currency] = $record['sum'];
$conversionAvg[$record->article_id][$record->currency] = $record['avg'];
}
/** @var QueryDataTable $datatable */
$datatable = $datatables->of($articles);
return $datatable
->addColumn('id', function (Article $article) {
return $article->id;
})
->addColumn('title', function (Article $article) {
return [
'url' => route('articles.show', ['article' => $article->id]),
'text' => $article->title,
];
})
->addColumn('conversions_count', function (Article $article) use ($conversionCount) {
return $conversionCount[$article->id] ?? 0;
})
->addColumn('conversions_sum', function (Article $article) use ($conversionSum) {
if (!isset($conversionSum[$article->id])) {
return [0];
}
$amounts = null;
foreach ($conversionSum[$article->id] as $currency => $c) {
$c = round($c, 2);
$amounts[] = "{$c} {$currency}";
}
return $amounts ?: [0];
})
->addColumn('conversions_avg', function (Article $article) use ($conversionAvg) {
if (!isset($conversionAvg[$article->id])) {
return [0];
}
$amounts = null;
foreach ($conversionAvg[$article->id] as $currency => $c) {
$c = round($c, 2);
$amounts[] = "{$c} {$currency}";
}
return $amounts ?: [0];
})
->filterColumn('title', function (Builder $query, $value) {
$query->where('articles.title', 'like', "%{$value}%");
})
->filterColumn('content_type', function (Builder $query, $value) {
$values = explode(',', $value);
$query->whereIn('articles.content_type', $values);
})
->filterColumn('sections[, ].name', function (Builder $query, $value) {
$values = explode(',', $value);
$filterQuery = \DB::table('article_section')
->select(['article_section.article_id'])
->whereIn('article_section.section_id', $values);
$query->whereIn('articles.id', $filterQuery);
})
->filterColumn('authors[, ].name', function (Builder $query, $value) {
$values = explode(',', $value);
$filterQuery = \DB::table('article_author')
->select(['article_author.article_id'])
->whereIn('article_author.author_id', $values);
$query->whereIn('articles.id', $filterQuery);
})
->filterColumn('tags[, ].name', function (Builder $query, $value) {
$values = explode(',', $value);
$filterQuery = \DB::table('article_tag')
->select(['article_tag.article_id'])
->whereIn('article_tag.tag_id', $values);
$query->whereIn('articles.id', $filterQuery);
})
->orderColumn('avg_sum', 'timespent_sum / pageviews_all $1')
->orderColumn('avg_timespent_signed_in', 'avg_timespent_signed_in $1')
->orderColumn('avg_timespent_all', 'avg_timespent_all $1')
->orderColumn('pageviews_all', 'pageviews_all $1')
->orderColumn('timespent_sum', 'timespent_sum $1')
->orderColumn('conversions_count', 'conversions_count $1')
->orderColumn('conversions_sum', 'conversions_sum $1')
->orderColumn('conversions_avg', 'conversions_avg $1')
->orderColumn('id', 'articles.id $1')
->make(true);
}
public function setAuthor(Author $author): void
{
$this->author = $author;
}
public function setSection(Section $section): void
{
$this->section = $section;
}
public function setTag(Tag $tag): void
{
$this->tag = $tag;
}
public function setTagCategory(TagCategory $tagCategory): void
{
$this->tagCategory = $tagCategory;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ArticleAuthor.php | Beam/extensions/beam-module/src/Model/ArticleAuthor.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Remp\Journal\TokenProvider;
class ArticleAuthor extends BaseModel
{
protected $table = 'article_author';
public function author(): BelongsTo
{
return $this->belongsTo(Author::class);
}
public function article(): BelongsTo
{
return $this->belongsTo(Article::class);
}
public function scopeOfSelectedProperty(Builder $query): Builder
{
$tokenProvider = resolve(TokenProvider::class);
$propertyUuid = $tokenProvider->getToken();
if ($propertyUuid) {
$query->whereHas('article', function (Builder $articleQuery) {
$articleQuery->ofSelectedProperty();
});
}
return $query;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/ArticlePageviews.php | Beam/extensions/beam-module/src/Model/ArticlePageviews.php | <?php
namespace Remp\BeamModule\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Remp\BeamModule\Database\Factories\ArticlePageviewsFactory;
class ArticlePageviews extends BaseModel implements Aggregable
{
use HasFactory;
public $timestamps = false;
protected $fillable = [
'article_id',
'time_from',
'time_to',
'sum',
'signed_in',
'subscribers',
];
protected static function newFactory(): ArticlePageviewsFactory
{
return ArticlePageviewsFactory::new();
}
public function aggregatedFields(): array
{
return ['sum', 'signed_in', 'subscribers'];
}
public function groupableFields(): array
{
return ['article_id'];
}
protected $casts = [
'sum' => 'integer',
'signed_in' => 'integer',
'subscribers' => 'integer',
'time_from' => 'datetime',
'time_to' => 'datetime',
];
public function article(): BelongsTo
{
return $this->belongsTo(Article::class);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Scopes/PropertyTokenScope.php | Beam/extensions/beam-module/src/Model/Scopes/PropertyTokenScope.php | <?php
namespace Remp\BeamModule\Model\Scopes;
use Remp\BeamModule\Model\Property\SelectedProperty;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
class PropertyTokenScope implements Scope
{
private $selectedProperty;
public function __construct(SelectedProperty $selectedProperty)
{
$this->selectedProperty = $selectedProperty;
}
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
*
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$token = $this->selectedProperty->getToken();
if ($token) {
$builder->where('property_token', $token);
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/SearchAspects/ArticleSearchAspect.php | Beam/extensions/beam-module/src/Model/SearchAspects/ArticleSearchAspect.php | <?php
namespace Remp\BeamModule\Model\SearchAspects;
use Remp\BeamModule\Model\Article;
use Illuminate\Support\Collection;
use Spatie\Searchable\SearchAspect;
class ArticleSearchAspect extends SearchAspect
{
public function getResults(string $term): Collection
{
return Article::query()
->where('title', 'LIKE', "%{$term}%")
->orWhere('external_id', '=', $term)
->orWhereHas('tags', function ($query) use ($term) {
$query->where('name', 'LIKE', "{$term}%");
})
->orWhereHas('sections', function ($query) use ($term) {
$query->where('name', 'LIKE', "{$term}%");
})
->orderBy('published_at', 'DESC')
->take(config('search.maxResultCount'))
->with(['tags', 'sections'])
->get();
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/SearchAspects/AuthorSearchAspect.php | Beam/extensions/beam-module/src/Model/SearchAspects/AuthorSearchAspect.php | <?php
namespace Remp\BeamModule\Model\SearchAspects;
use Remp\BeamModule\Model\Author;
use Illuminate\Support\Collection;
use Spatie\Searchable\SearchAspect;
class AuthorSearchAspect extends SearchAspect
{
public function getResults(string $term): Collection
{
return Author::query()
->where('name', 'LIKE', "%{$term}%")
->with('latestPublishedArticle')
->get();
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/SearchAspects/SegmentSearchAspect.php | Beam/extensions/beam-module/src/Model/SearchAspects/SegmentSearchAspect.php | <?php
namespace Remp\BeamModule\Model\SearchAspects;
use Remp\BeamModule\Model\Segment;
use Illuminate\Support\Collection;
use Spatie\Searchable\SearchAspect;
class SegmentSearchAspect extends SearchAspect
{
public function getResults(string $term): Collection
{
return Segment::query()
->where('name', 'LIKE', "{$term}%")
->orWhere('code', 'LIKE', "{$term}%")
->orderBy('updated_at', 'DESC')
->take(config('search.maxResultCount'))
->get();
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Rules/ValidCarbonDate.php | Beam/extensions/beam-module/src/Model/Rules/ValidCarbonDate.php | <?php
namespace Remp\BeamModule\Model\Rules;
use Carbon\Carbon;
use Exception;
use Illuminate\Contracts\Validation\Rule;
class ValidCarbonDate implements Rule
{
/**
* @inheritDoc
*/
public function passes($attribute, $value)
{
try {
Carbon::parse($value);
return true;
} catch (Exception $e) {
return false;
}
}
/**
* @inheritDoc
*/
public function message()
{
return 'The :attribute is not a valid date.';
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Charts/ConversionsSankeyDiagram.php | Beam/extensions/beam-module/src/Model/Charts/ConversionsSankeyDiagram.php | <?php
namespace Remp\BeamModule\Model\Charts;
use Remp\BeamModule\Helpers\Colors;
use Remp\BeamModule\Helpers\Journal\JournalHelpers;
use Illuminate\Support\Collection;
use Remp\Journal\JournalContract;
class ConversionsSankeyDiagram
{
const NODE_ARTICLES = 'articles';
const NODE_TITLE = 'homepage + other';
const NODE_PURCHASE = 'purchase';
private $conversionSources;
private $conversionSourceType;
private $journalHelper;
public $nodes = [];
public $links = [];
public $nodeColors = [];
public function __construct(JournalContract $journal, Collection $conversionSources, string $conversionSourceType)
{
$this->conversionSources = $conversionSources;
$this->conversionSourceType = $conversionSourceType;
$this->journalHelper = new JournalHelpers($journal);
$this->retrieveNodesAndLinks();
if (!empty($this->nodes)) {
$nodeNames = array_column($this->nodes, 'name');
$this->nodeColors = Colors::assignColorsToMediumRefers($nodeNames, true);
$this->nodeColors[self::NODE_TITLE] = '#e05767';
$this->nodeColors[self::NODE_ARTICLES] = '#e05767';
$this->nodeColors[self::NODE_PURCHASE] = '#b71e2d';
}
}
private function retrieveNodesAndLinks()
{
$conversionSourcesByType = $this->conversionSources->where('type', $this->conversionSourceType);
$conversionSourcesByMedium = $conversionSourcesByType->groupBy('referer_medium');
$conversionsCount = $conversionSourcesByType->count();
$totalArticlesCount = $totalTitlesCount = 0;
foreach ($conversionSourcesByMedium as $medium => $conversionSources) {
$medium = $this->journalHelper->refererMediumLabel($medium);
$articlesCount = $conversionSources->filter(function ($conversionSource) {
return $conversionSource->article_id !== null;
})->count();
$titlesCount = $conversionSources->count() - $articlesCount;
$this->addNodesAndLinks($medium, self::NODE_ARTICLES, $articlesCount / $conversionsCount * 100);
$this->addNodesAndLinks($medium, self::NODE_TITLE, $titlesCount / $conversionsCount * 100);
$totalArticlesCount += $articlesCount;
$totalTitlesCount += $titlesCount;
}
if ($conversionsCount > 0) {
if ($totalArticlesCount > 0) {
$this->addNodesAndLinks(self::NODE_ARTICLES, self::NODE_PURCHASE, $totalArticlesCount / $conversionsCount * 100);
}
if ($totalTitlesCount > 0) {
$this->addNodesAndLinks(self::NODE_TITLE, self::NODE_PURCHASE, $totalTitlesCount / $conversionsCount * 100);
}
}
}
private function addNodesAndLinks(string $source, string $target, float $connectionValue)
{
if (!$connectionValue) {
return;
}
$this->addNode($source);
$this->addNode($target);
$this->links[] = [
'source' => $source,
'target' => $target,
'value' => $connectionValue
];
}
private function addNode(string $nodeName)
{
if (!in_array($nodeName, array_column($this->nodes, 'name'))) {
$this->nodes[] = ['name' => $nodeName];
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Snapshots/SnapshotTimePoints.php | Beam/extensions/beam-module/src/Model/Snapshots/SnapshotTimePoints.php | <?php
namespace Remp\BeamModule\Model\Snapshots;
class SnapshotTimePoints
{
private $includedPoints;
private $excludedPoints;
private $includedPointsMapping;
/**
* Helper structure to store which time points in article_views_snapshots table we use when displaying points in Dashboard
* or compressing the table.
*
* @param array $includedPoints string array of datetimes
* @param array $excludedPoints string array of datetimes
* @param array $includedPointsMapping included time points mapped to time points we want them to show at
*/
public function __construct(array $includedPoints, array $excludedPoints, array $includedPointsMapping = [])
{
$this->includedPoints = $includedPoints;
$this->excludedPoints = $excludedPoints;
$this->includedPointsMapping = $includedPointsMapping;
}
public function getIncludedPoints(): array
{
return $this->includedPoints;
}
public function getExcludedPoints(): array
{
return $this->excludedPoints;
}
public function getIncludedPointsMapping(): array
{
return $this->includedPointsMapping;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Snapshots/SnapshotHelpers.php | Beam/extensions/beam-module/src/Model/Snapshots/SnapshotHelpers.php | <?php
namespace Remp\BeamModule\Model\Snapshots;
use Remp\BeamModule\Helpers\Journal\JournalInterval;
use Remp\BeamModule\Model\ArticleViewsSnapshot;
use Cache;
use Carbon\Carbon;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
class SnapshotHelpers
{
/**
* Load concurrents histogram for given interval
* Concurrents counts are grouped by time and referer_medium
*
* @param JournalInterval $interval
* @param null $externalArticleId if specified, show histogram only for this article
* @param bool $addLastMinute include last minute (for incomplete interval)
*
* @return Collection collection of concurrent time objects (properties: time, count, referer_medium)
*/
public function concurrentsHistogram(
JournalInterval $interval,
$externalArticleId = null,
bool $addLastMinute = false
) {
/** @var Carbon $from */
$from = $interval->timeAfter;
/** @var Carbon $to */
$to = $interval->timeBefore;
$timePoints = $this->timePoints($from, $to, $interval->intervalMinutes, $addLastMinute, function (Builder $query) use ($externalArticleId) {
if ($externalArticleId) {
$query->where('external_article_id', $externalArticleId);
}
});
$q = ArticleViewsSnapshot::select('time', 'referer_medium', DB::raw('sum(count) as count'))
->whereIn('time', $timePoints->getIncludedPoints())
->groupBy(['time', 'referer_medium']);
if ($externalArticleId) {
$q->where('external_article_id', $externalArticleId);
}
$timePointsMapping = $timePoints->getIncludedPointsMapping();
// get cache key from binded parameters - parameters from scope may occur (e.g. `property_token`)
$bindings = implode('', $q->getBindings());
$cacheKey = "concurrentHistogram.". hash('md5', $bindings);
$concurrents = Cache::get($cacheKey);
if (!$concurrents) {
$concurrents = collect();
foreach ($q->get() as $item) {
$concurrents->push((object) [
// concurrent snapshots may not be stored in DB precisely for each time interval start (e.g. snapshotting took too long).
// therefore we use provided mapping to display them nicely in graph
'time' => $timePointsMapping[$item->time->toIso8601ZuluString()],
'real_time' => $item->time->toIso8601ZuluString(),
'count' => $item->count,
'referer_medium' => $item->referer_medium,
]);
}
if ($interval->cacheTTL > 0) {
Cache::put($cacheKey, $concurrents, $interval->cacheTTL);
}
}
return $concurrents;
}
/**
* Load concurrents histogram for given interval
* Concurrents counts are grouped by time, referer_medium
*
* @param JournalInterval $interval
* @param array $externalArticleIds
*
* @return ArticleViewsSnapshot[]
*/
public function concurrentArticlesHistograms(
JournalInterval $interval,
array $externalArticleIds
) {
sort($externalArticleIds);
$cacheKey = "concurrentArticlesHistograms." . hash('md5', implode('.', $externalArticleIds));
$result = Cache::get($cacheKey);
if (!$result) {
/** @var Carbon $from */
$from = $interval->timeAfter;
/** @var Carbon $to */
$to = $interval->timeBefore;
$q = DB::table(ArticleViewsSnapshot::getTableName())
->select('time', 'external_article_id', DB::raw('sum(count) as count'), DB::raw('UNIX_TIMESTAMP(time) as timestamp'))
->where('time', '>=', $from)
->where('time', '<=', $to)
->whereIn('external_article_id', $externalArticleIds)
->groupBy(['time', 'external_article_id'])
->orderBy('external_article_id')
->orderBy('time');
$result = $q->get();
// Set 10 minute cache
Cache::put($cacheKey, $result, 600);
}
return $result;
}
/**
* Computes lowest time point (present in DB) per each $intervalMinutes window, in [$from, $to] interval
*
* @param Carbon $from (including)
* @param Carbon $to (excluding)
* @param int $intervalMinutes
* @param bool $addLastMinute
* @param callable|null $conditions
*
* @return SnapshotTimePoints containing array for included/excluded time points (and mapping to lowest time point)
*/
public function timePoints(
Carbon $from,
Carbon $to,
int $intervalMinutes,
bool $addLastMinute = false,
callable $conditions = null
): SnapshotTimePoints {
$q = DB::table(ArticleViewsSnapshot::getTableName())
->select('time')
->where('time', '>=', $from)
->where('time', '<=', $to)
->groupBy('time')
->orderBy('time');
if ($conditions) {
$conditions($q);
}
$timeRecords = $q->get()
->map(function ($item) {
return Carbon::parse($item->time);
})->toArray();
$timePoints = [];
foreach ($timeRecords as $timeRecord) {
$timePoints[$timeRecord->toIso8601ZuluString()] = false;
}
$includedPointsMapping = [];
$timeIterator = clone $from;
while ($timeIterator->lte($to)) {
$upperLimit = (clone $timeIterator)->addMinutes($intervalMinutes);
$i = 0;
while ($i < count($timeRecords)) {
if ($timeRecords[$i]->gte($timeIterator) && $timeRecords[$i]->lt($upperLimit)) {
$timePoints[$timeRecords[$i]->toIso8601ZuluString()] = true;
$includedPointsMapping[$timeRecords[$i]->toIso8601ZuluString()] = $timeIterator->toIso8601ZuluString();
break;
}
$i++;
}
$timeIterator->addMinutes($intervalMinutes);
}
// Add last minute
if ($addLastMinute && count($timeRecords) > 0) {
// moves the internal pointer to the end of the array
end($timePoints);
$timePoints[key($timePoints)] = true;
if (!isset($includedPointsMapping[key($timePoints)])) {
$includedPointsMapping[key($timePoints)] = key($timePoints);
}
}
// Filter results
$includedPoints = [];
$excludedPoints = [];
foreach ($timePoints as $timeValue => $isIncluded) {
if ($isIncluded) {
$includedPoints[] = $timeValue;
} else {
$excludedPoints[] = $timeValue;
}
}
return new SnapshotTimePoints($includedPoints, $excludedPoints, $includedPointsMapping);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Config/ConfigNames.php | Beam/extensions/beam-module/src/Model/Config/ConfigNames.php | <?php
namespace Remp\BeamModule\Model\Config;
class ConfigNames
{
const AUTHOR_SEGMENTS_MIN_RATIO = 'author_segments_min_ratio';
const AUTHOR_SEGMENTS_MIN_VIEWS = 'author_segments_min_views';
const AUTHOR_SEGMENTS_MIN_AVERAGE_TIMESPENT = 'author_segments_min_average_timespent';
const AUTHOR_SEGMENTS_DAYS_IN_PAST = 'author_segments_days_in_past';
const SECTION_SEGMENTS_MIN_RATIO = 'section_segments_min_ratio';
const SECTION_SEGMENTS_MIN_VIEWS = 'section_segments_min_views';
const SECTION_SEGMENTS_MIN_AVERAGE_TIMESPENT = 'section_segments_min_average_timespent';
const SECTION_SEGMENTS_DAYS_IN_PAST = 'section_segments_days_in_past';
const CONVERSION_RATE_MULTIPLIER = 'conversion_rate_multiplier';
const CONVERSION_RATE_DECIMAL_NUMBERS = 'conversion_rate_multiplier_decimals';
const CONVERSIONS_COUNT_THRESHOLD_LOW = 'conversions_count_threshold_low';
const CONVERSIONS_COUNT_THRESHOLD_MEDIUM = 'conversions_count_threshold_medium';
const CONVERSIONS_COUNT_THRESHOLD_HIGH = 'conversions_count_threshold_high';
const CONVERSION_RATE_THRESHOLD_LOW = 'conversion_rate_threshold_low';
const CONVERSION_RATE_THRESHOLD_MEDIUM = 'conversion_rate_threshold_medium';
const CONVERSION_RATE_THRESHOLD_HIGH = 'conversion_rate_threshold_high';
const DASHBOARD_FRONTPAGE_REFERER = 'dashboard_frontpage_referer';
/**
* Lists config options that can specified for token properties
* @return array
*/
public static function propertyConfigs(): array
{
return [
self::CONVERSION_RATE_MULTIPLIER,
self::CONVERSION_RATE_DECIMAL_NUMBERS,
self::CONVERSIONS_COUNT_THRESHOLD_LOW,
self::CONVERSIONS_COUNT_THRESHOLD_MEDIUM,
self::CONVERSIONS_COUNT_THRESHOLD_HIGH,
self::CONVERSION_RATE_THRESHOLD_LOW,
self::CONVERSION_RATE_THRESHOLD_MEDIUM,
self::CONVERSION_RATE_THRESHOLD_HIGH,
self::DASHBOARD_FRONTPAGE_REFERER
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Config/ConversionRateConfig.php | Beam/extensions/beam-module/src/Model/Config/ConversionRateConfig.php | <?php
namespace Remp\BeamModule\Model\Config;
class ConversionRateConfig
{
private int $multiplier;
private int $decimalNumbers;
/**
* @deprecated Use static method build() instead. This constructor will be marked as private in the next major release.
*/
public function __construct()
{
}
public static function build(): self
{
$config = new self();
$config->multiplier = Config::loadByName(ConfigNames::CONVERSION_RATE_MULTIPLIER);
$config->decimalNumbers = Config::loadByName(ConfigNames::CONVERSION_RATE_DECIMAL_NUMBERS);
return $config;
}
/**
* @deprecated Use static method build() instead. This method will be removed in the next major release.
*/
public function load()
{
$loadedConfig = self::build();
$this->multiplier = $loadedConfig->multiplier;
$this->decimalNumbers = $loadedConfig->decimalNumbers;
}
public function getMultiplier(): int
{
if (!$this->multiplier) {
$this->load();
}
return $this->multiplier;
}
public function getDecimalNumbers(): int
{
if (!$this->decimalNumbers) {
$this->load();
}
return $this->decimalNumbers;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Config/Config.php | Beam/extensions/beam-module/src/Model/Config/Config.php | <?php
namespace Remp\BeamModule\Model\Config;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Remp\BeamModule\Model\BaseModel;
use Remp\BeamModule\Model\Property;
use Remp\BeamModule\Model\Property\SelectedProperty;
class Config extends BaseModel
{
protected $fillable = [
'name',
'display_name',
'value',
'description',
'type',
'sorting',
'config_category_id'
];
protected $casts = [
'sorting' => 'integer',
'locked' => 'boolean',
];
private $selectedProperty;
public function __construct(array $attributes = [])
{
parent::__construct($attributes);
$this->selectedProperty = resolve(SelectedProperty::class);
}
public function configCategory(): BelongsTo
{
return $this->belongsTo(ConfigCategory::class);
}
public function property(): BelongsTo
{
return $this->belongsTo(Property::class);
}
public function scopeGlobal(Builder $query)
{
return $query->whereNull('property_id');
}
public function scopeOfSelectedToken(Builder $query)
{
$tokenUuid = $this->selectedProperty->getToken();
if ($tokenUuid) {
return $query->whereHas('property', function (Builder $query) use ($tokenUuid) {
$query->where('uuid', $tokenUuid);
});
}
return $query;
}
public function scopeOfCategory(Builder $query, $categoryCode)
{
return $query->whereHas('configCategory', function (Builder $query) use ($categoryCode) {
$query->where('code', $categoryCode);
});
}
public function getValue()
{
switch (mb_strtolower($this->type)) {
case 'double':
return (double) $this->value;
case 'float':
return (float) $this->value;
case 'int':
case 'integer':
return (int) $this->value;
case 'bool':
case 'boolean':
return (bool) $this->value;
default:
return $this->value;
}
}
public static function loadAllPropertyConfigs(string $name): array
{
$configs = Config::with('property')
->where('name', $name)
->whereNotNull('property_id')
->get();
$results = [];
foreach ($configs as $config) {
$results[$config->property->id] = $config->getValue();
}
return $results;
}
public static function loadByName(string $name, $globalOnly = false)
{
$q = Config::where('name', $name);
$fallback = false;
// Try to load property config if present
if (!$globalOnly && in_array($name, ConfigNames::propertyConfigs(), true)) {
$fallback = true;
$q = $q->ofSelectedToken();
}
$config = $q->first();
// If not, fallback to global config
if (!$config && $fallback) {
$config = Config::where('name', $name)->first();
}
if (!$config) {
throw new \Exception("missing configuration for '$name'");
}
return $config->getValue();
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Config/ConfigCategory.php | Beam/extensions/beam-module/src/Model/Config/ConfigCategory.php | <?php
namespace Remp\BeamModule\Model\Config;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Http\Request;
use Remp\BeamModule\Http\Requests\AuthorSegmentsConfigurationRequest;
use Remp\BeamModule\Model\BaseModel;
class ConfigCategory extends BaseModel
{
const CODE_DASHBOARD = 'dashboard';
const CODE_AUTHOR_SEGMENTS = 'author-segments';
const CODE_SECTION_SEGMENTS = 'section-segments';
protected $fillable = [
'code',
'display_name',
];
public function configs(): HasMany
{
return $this->hasMany(Config::class);
}
public function getPairedRequestType(Request $request)
{
if ($this->code === self::CODE_AUTHOR_SEGMENTS) {
return new AuthorSegmentsConfigurationRequest($request->all());
}
return $request;
}
public static function getSettingsTabUrl(string $configCategoryCode)
{
return route('settings.index') . '#' . $configCategoryCode;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Pageviews/PageviewsHelper.php | Beam/extensions/beam-module/src/Model/Pageviews/PageviewsHelper.php | <?php
namespace Remp\BeamModule\Model\Pageviews;
use Remp\BeamModule\Model\ArticlePageviews;
use Remp\BeamModule\Helpers\Journal\JournalInterval;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
class PageviewsHelper
{
/**
* Load concurrents histogram for given interval
* Concurrents counts are grouped by time and referer_medium
*
* @param JournalInterval $interval
* @param ?int $articleId if specified, show histogram only for this article
*
* @return Collection collection of concurrent time objects (properties: time, sum)
*/
public function pageviewsHistogram(JournalInterval $interval, ?int $articleId = null)
{
$from = $interval->timeAfter;
$to = $interval->timeBefore;
$interval->setIntervalMinutes($this->getInterval($articleId, $from, $to, $interval->intervalMinutes));
$data = $this->loadIntervalData($articleId, $from, $to, $interval->intervalMinutes);
$concurrents = collect();
foreach ($data as $pageviewRecord) {
$concurrents->push((object) [
'time' => $pageviewRecord->interval_from,
'count' => $pageviewRecord->sum,
]);
}
return $concurrents;
}
private function loadIntervalData($articleId, Carbon $from, Carbon $to, int $interval)
{
$articleId = $articleId ?? true;
[$fromIsoString, $toIsoString] = $this->getRoundIsoDates($from, $to, $interval);
$sql = <<<SQL
WITH RECURSIVE seq AS (SELECT ? AS interval_from, TIMESTAMPADD(MINUTE , ?, ?) AS interval_to
UNION ALL
SELECT TIMESTAMPADD(MINUTE , ?, interval_from), TIMESTAMPADD(MINUTE , ?, interval_to)
FROM seq
WHERE interval_to <= ?)
SELECT /*+ SET_VAR(cte_max_recursion_depth = 1M) */
seq.interval_from,
seq.interval_to,
COALESCE(SUM(article_pageviews.sum), 0) as sum
FROM seq
LEFT JOIN article_pageviews ON (
article_pageviews.article_id = ? AND article_pageviews.time_from >= seq.interval_from AND article_pageviews.time_to <= seq.interval_to
)
GROUP BY seq.interval_from, seq.interval_to
SQL;
return DB::select($sql, [
$fromIsoString,
$interval,
$fromIsoString,
$interval,
$interval,
$toIsoString,
$articleId,
]);
}
private function getInterval($articleId, $from, $to, $intervalMinutes)
{
$maxInterval = $this->getMaxIntervalAvailable($articleId, $from, $to);
$interval = $maxInterval ?? $intervalMinutes;
return min($interval, 1440);
}
private function getMaxIntervalAvailable($articleId, Carbon $from, Carbon $to)
{
return ArticlePageviews::where('article_id', $articleId)
->where('time_from', '>=', $from)
->where('time_to', '<=', $to)
->max(DB::raw('TIMESTAMPDIFF(MINUTE, time_from, time_to)'));
}
private function getRoundIsoDates($from, $to, $interval)
{
switch ($interval) {
case 1440:
return [
$from->floorDay()->toIso8601String(),
$to->ceilDay()->toIso8601String(),
];
case 60:
return [
$from->floorHour()->toIso8601String(),
$to->ceilHour()->toIso8601String(),
];
case 20:
return [
$from->floorMinutes(20)->toIso8601String(),
$to->ceilMinutes(20)->toIso8601String(),
];
default:
return [
$from->floorDay()->toIso8601String(),
$to->ceilDay()->toIso8601String(),
];
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Pageviews/Api/v1/TimeHistogram.php | Beam/extensions/beam-module/src/Model/Pageviews/Api/v1/TimeHistogram.php | <?php
namespace Remp\BeamModule\Model\Pageviews\Api\v1;
use Remp\BeamModule\Http\Requests\Api\v1\PageviewsTimeHistogramRequest;
use DateInterval;
use DatePeriod;
use DB;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Carbon;
class TimeHistogram
{
public function getTimeHistogram(PageviewsTimeHistogramRequest $request)
{
$timeFrom = Carbon::parse($request->json('from'));
$timeTo = Carbon::parse($request->json('to'));
$pageviewsQuery = DB::table('article_pageviews')
->select(
DB::raw('DATE(article_pageviews.time_from) as date'),
DB::raw('CAST(SUM(article_pageviews.sum) AS UNSIGNED) as pageviews')
)
->where('article_pageviews.time_from', '>=', $timeFrom)
->where('article_pageviews.time_from', '<', $timeTo)
->groupBy('date');
$sectionFilters = $this->getFilters($request, 'sections');
$this->addSectionsCondition($pageviewsQuery, $sectionFilters);
$authorFilters = $this->getFilters($request, 'authors');
$this->addAuthorsCondition($pageviewsQuery, $authorFilters);
$tagFilters = $this->getFilters($request, 'tags');
$this->addTagsCondition($pageviewsQuery, $tagFilters);
$tagCategoryFilters = $this->getFilters($request, 'tag_categories');
$this->addTagCategoriesCondition($pageviewsQuery, $tagCategoryFilters);
$contentType = $request->json('content_type');
if ($contentType) {
$this->addContentTypeCondition($pageviewsQuery, $contentType);
}
$data = $pageviewsQuery->pluck('pageviews', 'date');
return $this->fillMissingDates($timeFrom, $timeTo, $data);
}
private function fillMissingDates($from, $to, $data)
{
$result = [];
$period = new DatePeriod($from, new DateInterval('P1D'), $to);
foreach ($period as $date) {
$date = $date->format('Y-m-d');
$result[] = ['date' => $date, 'pageviews' => $data[$date] ?? 0];
}
return $result;
}
private function getFilters($request, $filterName): array
{
$result = [];
$filters = $request->json($filterName) ?? [];
foreach ($filters as $filter) {
$filterValueType = null;
$filterValues = null;
if (isset($filter['external_ids'])) {
$filterValueType = 'external_id';
$filterValues = $filter['external_ids'];
} elseif (isset($filter['names'])) {
$filterValueType = 'name';
$filterValues = $filter['names'];
}
$result[] = [$filterValueType, $filterValues];
}
return $result;
}
private function checkQueryType($type): void
{
if (!in_array($type, ['external_id', 'name'], true)) {
throw new \Exception("type '$type' is not one of 'external_id' or 'name' values");
}
}
private function addSectionsCondition(Builder $articlePageviewsQuery, array $sectionFilters): void
{
foreach ($sectionFilters as [$type, $values]) {
$this->checkQueryType($type);
$articlePageviewsQuery->whereIn('article_pageviews.article_id', function ($query) use ($type, $values) {
$query->select('article_id')
->from('article_section')
->join('sections', 'article_section.section_id', '=', 'sections.id')
->whereIn('sections.' . $type, $values);
});
}
}
private function addAuthorsCondition(Builder $articlePageviewsQuery, array $authorsFilter): void
{
foreach ($authorsFilter as [$type, $values]) {
$this->checkQueryType($type);
$articlePageviewsQuery->whereIn('article_pageviews.article_id', function ($query) use ($type, $values) {
$query->select('article_id')
->from('article_author')
->join('authors', 'article_author.author_id', '=', 'authors.id')
->whereIn('authors.' . $type, $values);
});
}
}
private function addContentTypeCondition(Builder $articlePageviewsQuery, string $contentType): void
{
$articlePageviewsQuery->join('articles', 'article_pageviews.article_id', '=', 'articles.id')
->where('articles.content_type', '=', $contentType);
}
private function addTagsCondition(Builder $articlePageviewsQuery, array $tagFilters): void
{
foreach ($tagFilters as [$type, $values]) {
$this->checkQueryType($type);
$articlePageviewsQuery->whereIn('article_pageviews.article_id', function ($query) use ($type, $values) {
$query->select('article_id')
->from('article_tag')
->join('tags', 'article_tag.tag_id', '=', 'tags.id')
->whereIn('tags.' . $type, $values);
});
}
}
private function addTagCategoriesCondition(Builder $articlePageviewsQuery, array $tagCategoryFilters): void
{
foreach ($tagCategoryFilters as [$type, $values]) {
$this->checkQueryType($type);
$articlePageviewsQuery->whereIn('article_pageviews.article_id', function ($query) use ($type, $values) {
$query->select('article_id')
->from('article_tag as at')
->join('tag_tag_category', 'tag_tag_category.tag_id', '=', 'at.tag_id')
->join('tag_categories', 'tag_categories.id', '=', 'tag_tag_category.tag_category_id')
->whereIn('tag_categories.' . $type, $values);
});
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Pageviews/Api/v1/TopSearch.php | Beam/extensions/beam-module/src/Model/Pageviews/Api/v1/TopSearch.php | <?php
namespace Remp\BeamModule\Model\Pageviews\Api\v1;
use Remp\BeamModule\Http\Requests\Api\v1\TopArticlesSearchRequest;
use Remp\BeamModule\Http\Requests\Api\v1\TopAuthorsSearchRequest;
use Remp\BeamModule\Http\Requests\Api\v1\TopTagsSearchRequest;
use DB;
use Illuminate\Database\Query\Builder;
use Illuminate\Support\Carbon;
class TopSearch
{
public function topArticles(TopArticlesSearchRequest $request)
{
$limit = $request->json('limit');
$timeFrom = Carbon::parse($request->json('from'));
$pageviewsQuery = DB::table('article_pageviews')
->where('article_pageviews.time_from', '>=', $timeFrom)
->groupBy('article_pageviews.article_id')
->select(
'article_pageviews.article_id',
DB::raw('CAST(SUM(article_pageviews.sum) AS UNSIGNED) as pageviews')
)
->orderBy('pageviews', 'DESC')
->limit($limit);
[$sectionValueType, $sectionValues] = $this->getFilter($request, 'sections');
if ($sectionValueType && $sectionValues) {
$this->addSectionsCondition($pageviewsQuery, $sectionValueType, $sectionValues);
}
[$authorValueType, $authorValues] = $this->getFilter($request, 'authors');
if ($authorValueType && $authorValues) {
$this->addAuthorsCondition($pageviewsQuery, $authorValueType, $authorValues);
}
[$tagValueType, $tagValues] = $this->getFilter($request, 'tags');
if ($tagValueType && $tagValues) {
$this->addTagsCondition($pageviewsQuery, $tagValueType, $tagValues);
}
[$tagCategoryValueType, $tagCategoryValues] = $this->getFilter($request, 'tag_categories');
if ($tagCategoryValueType && $tagCategoryValues) {
$this->addTagCategoriesCondition($pageviewsQuery, $tagCategoryValueType, $tagCategoryValues);
}
$contentType = $request->json('content_type');
if ($contentType) {
$this->addContentTypeCondition($pageviewsQuery, $contentType);
}
$data = DB::table('articles')
->joinSub($pageviewsQuery, 'top_articles_by_pageviews', function ($join) {
$join->on('articles.id', '=', 'top_articles_by_pageviews.article_id');
})
->select('articles.id', 'articles.external_id', 'top_articles_by_pageviews.pageviews');
return $data->get();
}
public function topAuthors(TopAuthorsSearchRequest $request)
{
$limit = $request->json('limit');
$timeFrom = Carbon::parse($request->json('from'));
$topAuthorsQuery = DB::table('article_pageviews')
->where('article_pageviews.time_from', '>=', $timeFrom)
->join('article_author', 'article_pageviews.article_id', '=', 'article_author.article_id')
->groupBy(['article_author.author_id'])
->select('article_author.author_id', DB::raw('CAST(SUM(article_pageviews.sum) AS UNSIGNED) as pageviews'))
->orderBy('pageviews', 'DESC')
->limit($limit);
[$sectionValueType, $sectionValues] = $this->getFilter($request, 'sections');
if ($sectionValueType && $sectionValues) {
$this->addSectionsCondition($topAuthorsQuery, $sectionValueType, $sectionValues);
}
[$tagValueType, $tagValues] = $this->getFilter($request, 'tags');
if ($tagValueType && $tagValues) {
$this->addTagsCondition($topAuthorsQuery, $tagValueType, $tagValues);
}
[$tagCategoryValueType, $tagCategoryValues] = $this->getFilter($request, 'tag_categories');
if ($tagCategoryValueType && $tagCategoryValues) {
$this->addTagCategoriesCondition($topAuthorsQuery, $tagCategoryValueType, $tagCategoryValues);
}
$contentType = $request->json('content_type');
if ($contentType) {
$this->addContentTypeCondition($topAuthorsQuery, $contentType);
}
$data = DB::table('authors')
->joinSub($topAuthorsQuery, 'top_authors', function ($join) {
$join->on('authors.id', '=', 'top_authors.author_id');
})
->select('authors.external_id', 'authors.name', 'top_authors.pageviews');
return $data->get();
}
public function topPostTags(TopTagsSearchRequest $request)
{
$limit = $request->json('limit');
$timeFrom = Carbon::parse($request->json('from'));
$topTagsQuery = DB::table('article_pageviews')
->where('article_pageviews.time_from', '>=', $timeFrom)
->join('article_tag', 'article_pageviews.article_id', '=', 'article_tag.article_id')
->groupBy(['article_tag.tag_id'])
->select('article_tag.tag_id', DB::raw('CAST(SUM(article_pageviews.sum) AS UNSIGNED) as pageviews'))
->orderBy('pageviews', 'DESC')
->limit($limit);
[$sectionValueType, $sectionValues] = $this->getFilter($request, 'sections');
if ($sectionValueType && $sectionValues) {
$this->addSectionsCondition($topTagsQuery, $sectionValueType, $sectionValues);
}
[$authorValueType, $authorValues] = $this->getFilter($request, 'authors');
if ($authorValueType && $authorValues) {
$this->addAuthorsCondition($topTagsQuery, $authorValueType, $authorValues);
}
[$tagCategoryValueType, $tagCategoryValues] = $this->getFilter($request, 'tag_categories');
if ($tagCategoryValueType && $tagCategoryValues) {
$this->addTagCategoriesCondition($topTagsQuery, $tagCategoryValueType, $tagCategoryValues);
}
$contentType = $request->json('content_type');
if ($contentType) {
$this->addContentTypeCondition($topTagsQuery, $contentType);
}
$data = DB::table('tags')
->joinSub($topTagsQuery, 'top_tags', function ($join) {
$join->on('tags.id', '=', 'top_tags.tag_id');
})
->select('tags.id', 'tags.name', 'tags.external_id', 'top_tags.pageviews');
return $data->get();
}
private function getFilter($request, $filterName): array
{
$filter = $request->json($filterName);
$filterValueType = null;
$filterValues = null;
if (isset($filter['external_id'])) {
$filterValueType = 'external_id';
$filterValues = $filter['external_id'];
} elseif (isset($filter['name'])) {
$filterValueType = 'name';
$filterValues = $filter['name'];
}
return [$filterValueType, $filterValues];
}
private function checkQueryType($type)
{
if (!in_array($type, ['external_id', 'name'], true)) {
throw new \Exception("type '$type' is not one of 'external_id' or 'name' values");
}
}
private function addSectionsCondition(Builder $articlePageviewsQuery, string $type, array $values): void
{
$this->checkQueryType($type);
$articlePageviewsQuery->whereIn('article_pageviews.article_id', function ($query) use ($type, $values) {
$query->select('article_id')
->from('article_section')
->join('sections', 'article_section.section_id', '=', 'sections.id')
->whereIn('sections.' . $type, $values);
});
}
private function addAuthorsCondition(Builder $articlePageviewsQuery, string $type, array $values): void
{
$this->checkQueryType($type);
$articlePageviewsQuery->whereIn('article_pageviews.article_id', function ($query) use ($type, $values) {
$query->select('article_id')
->from('article_author')
->join('authors', 'article_author.author_id', '=', 'authors.id')
->whereIn('authors.' . $type, $values);
});
}
private function addContentTypeCondition(Builder $articlePageviewsQuery, string $contentType): void
{
$articlePageviewsQuery->join('articles', 'article_pageviews.article_id', '=', 'articles.id')
->where('articles.content_type', '=', $contentType);
}
private function addTagsCondition(Builder $articlePageviewsQuery, string $type, array $values): void
{
$this->checkQueryType($type);
$articlePageviewsQuery->whereIn('article_pageviews.article_id', function ($query) use ($type, $values) {
$query->select('article_id')
->from('article_tag')
->join('tags', 'article_tag.tag_id', '=', 'tags.id')
->whereIn('tags.' . $type, $values);
});
}
private function addTagCategoriesCondition(Builder $articlePageviewsQuery, string $type, array $values): void
{
$this->checkQueryType($type);
$articlePageviewsQuery->whereIn('article_pageviews.article_id', function ($query) use ($type, $values) {
$query->select('article_id')
->from('article_tag as at')
->join('tag_tag_category', 'tag_tag_category.tag_id', '=', 'at.tag_id')
->join('tag_categories', 'tag_categories.id', '=', 'tag_tag_category.tag_category_id')
->whereIn('tag_categories.' . $type, $values);
});
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Pageviews/Api/v2/TopSearch.php | Beam/extensions/beam-module/src/Model/Pageviews/Api/v2/TopSearch.php | <?php
namespace Remp\BeamModule\Model\Pageviews\Api\v2;
use Cache;
use DB;
use Illuminate\Database\Query\Builder;
use Illuminate\Database\Query\JoinClause;
use Illuminate\Support\Carbon;
use Remp\BeamModule\Http\Requests\Api\v2\TopArticlesSearchRequest;
use Remp\BeamModule\Http\Requests\Api\v2\TopAuthorsSearchRequest;
use Remp\BeamModule\Http\Requests\Api\v2\TopTagsSearchRequest;
class TopSearch
{
private const THRESHOLD_DIFF_DAYS = 7;
public function topArticles(TopArticlesSearchRequest $request)
{
$limit = $request->json('limit');
$timeFrom = Carbon::parse($request->json('from'));
$timeTo = $request->json('to') ? Carbon::parse($request->json('to')) : null;
$publishedFrom = $request->json('published_from') ? Carbon::parse($request->json('published_from')) : null;
$publishedTo = $request->json('published_to') ? Carbon::parse($request->json('published_to')) : null;
$useArticlesTableAsDataSource = $this->shouldUseArticlesTableAsDataSource($timeFrom, $publishedFrom, $timeTo);
if ($useArticlesTableAsDataSource) {
$baseQuery = DB::table('articles')
->orderBy('pageviews_all', 'DESC')
->limit($limit);
} else {
$baseQuery = DB::table('article_pageviews')
->groupBy('article_pageviews.article_id')
->select(
'article_pageviews.article_id',
DB::raw('CAST(SUM(article_pageviews.sum) AS UNSIGNED) as pageviews')
)
->orderBy('pageviews', 'DESC')
->limit($limit);
}
$sectionFilters = $this->getFilters($request, 'sections');
$this->addSectionsCondition($baseQuery, $sectionFilters, $useArticlesTableAsDataSource);
$authorFilters = $this->getFilters($request, 'authors');
$this->addAuthorsCondition($baseQuery, $authorFilters, $useArticlesTableAsDataSource);
$tagFilters = $this->getFilters($request, 'tags');
$this->addTagsCondition($baseQuery, $tagFilters, $useArticlesTableAsDataSource);
$tagCategoryFilters = $this->getFilters($request, 'tag_categories');
$this->addTagCategoriesCondition($baseQuery, $tagCategoryFilters, $useArticlesTableAsDataSource);
$contentType = $request->json('content_type');
if ($contentType) {
$this->addContentTypeCondition($baseQuery, $contentType, $useArticlesTableAsDataSource);
}
if ($publishedFrom) {
$this->addPublishedFromCondition($baseQuery, $publishedFrom, $useArticlesTableAsDataSource);
}
if ($publishedTo) {
$this->addPublishedToCondition($baseQuery, $publishedTo, $useArticlesTableAsDataSource);
}
if (!$useArticlesTableAsDataSource) {
if ($timeTo === null) {
$timeTo = Carbon::now();
}
$diffInDays = $timeFrom->diffInDays($timeTo);
// for longer time periods irrelevant low pageviews data will be cut off
if ($diffInDays > self::THRESHOLD_DIFF_DAYS) {
$thresholdPageviews = $this->getPageviewsThreshold(clone $baseQuery, $timeTo, $limit);
if (!$this->hasAlreadyJoinedArticlesTable($baseQuery)) {
$baseQuery->join('articles', 'article_pageviews.article_id', '=', 'articles.id');
}
$baseQuery->where('articles.pageviews_all', '>=', $thresholdPageviews);
}
$baseQuery->where('article_pageviews.time_from', '>=', $timeFrom);
if ($timeTo !== null) {
$baseQuery->where('article_pageviews.time_to', '<', $timeTo);
}
$data = DB::table('articles')
->joinSub($baseQuery, 'top_articles_by_pageviews', function ($join) {
$join->on('articles.id', '=', 'top_articles_by_pageviews.article_id');
})
->select('articles.id', 'articles.external_id', 'top_articles_by_pageviews.pageviews');
} else {
$data = $baseQuery->select('articles.id', 'articles.external_id', 'articles.pageviews_all as pageviews');
}
return $data->get();
}
public function topAuthors(TopAuthorsSearchRequest $request)
{
$limit = $request->json('limit');
$timeFrom = Carbon::parse($request->json('from'));
$topAuthorsQuery = DB::table('article_pageviews')
->where('article_pageviews.time_from', '>=', $timeFrom)
->join('article_author', 'article_pageviews.article_id', '=', 'article_author.article_id')
->groupBy(['article_author.author_id'])
->select('article_author.author_id', DB::raw('CAST(SUM(article_pageviews.sum) AS UNSIGNED) as pageviews'))
->orderBy('pageviews', 'DESC')
->limit($limit);
$sectionFilters = $this->getFilters($request, 'sections');
$this->addSectionsCondition($topAuthorsQuery, $sectionFilters);
$tagFilters = $this->getFilters($request, 'tags');
$this->addTagsCondition($topAuthorsQuery, $tagFilters);
$tagCategoryFilters = $this->getFilters($request, 'tag_categories');
$this->addTagCategoriesCondition($topAuthorsQuery, $tagCategoryFilters);
$contentType = $request->json('content_type');
if ($contentType) {
$this->addContentTypeCondition($topAuthorsQuery, $contentType);
}
$data = DB::table('authors')
->joinSub($topAuthorsQuery, 'top_authors', function ($join) {
$join->on('authors.id', '=', 'top_authors.author_id');
})
->select('authors.external_id', 'authors.name', 'top_authors.pageviews');
return $data->get();
}
public function topPostTags(TopTagsSearchRequest $request)
{
$limit = $request->json('limit');
$timeFrom = Carbon::parse($request->json('from'));
$topTagsQuery = DB::table('article_pageviews')
->where('article_pageviews.time_from', '>=', $timeFrom)
->join('article_tag', 'article_pageviews.article_id', '=', 'article_tag.article_id')
->groupBy(['article_tag.tag_id'])
->select('article_tag.tag_id', DB::raw('CAST(SUM(article_pageviews.sum) AS UNSIGNED) as pageviews'))
->orderBy('pageviews', 'DESC')
->limit($limit);
$sectionFilters = $this->getFilters($request, 'sections');
$this->addSectionsCondition($topTagsQuery, $sectionFilters);
$authorFilters = $this->getFilters($request, 'authors');
$this->addAuthorsCondition($topTagsQuery, $authorFilters);
$tagCategoryFilters = $this->getFilters($request, 'tag_categories');
$this->addTagCategoriesCondition($topTagsQuery, $tagCategoryFilters);
$contentType = $request->json('content_type');
if ($contentType) {
$this->addContentTypeCondition($topTagsQuery, $contentType);
}
$data = DB::table('tags')
->joinSub($topTagsQuery, 'top_tags', function ($join) {
$join->on('tags.id', '=', 'top_tags.tag_id');
})
->select('tags.id', 'tags.name', 'tags.external_id', 'top_tags.pageviews');
return $data->get();
}
private function getFilters($request, $filterName): array
{
$result = [];
$filters = $request->json($filterName) ?? [];
foreach ($filters as $filter) {
$filterValueType = null;
$filterValues = null;
if (isset($filter['external_ids'])) {
$filterValueType = 'external_id';
$filterValues = $filter['external_ids'];
} elseif (isset($filter['names'])) {
$filterValueType = 'name';
$filterValues = $filter['names'];
}
$result[] = [$filterValueType, $filterValues];
}
return $result;
}
private function checkQueryType($type): void
{
if (!in_array($type, ['external_id', 'name'], true)) {
throw new \Exception("type '$type' is not one of 'external_id' or 'name' values");
}
}
private function addSectionsCondition(Builder $baseQuery, array $sectionFilters, bool $isArticlesTable = false): void
{
$column = $isArticlesTable ? 'articles.id' : 'article_pageviews.article_id';
foreach ($sectionFilters as [$type, $values]) {
$this->checkQueryType($type);
$baseQuery->whereIn($column, function ($query) use ($type, $values) {
$query->select('article_id')
->from('article_section')
->join('sections', 'article_section.section_id', '=', 'sections.id')
->whereIn('sections.' . $type, $values);
});
}
}
private function addAuthorsCondition(Builder $articlePageviewsQuery, array $authorsFilter, bool $isArticlesTable = false): void
{
$column = $isArticlesTable ? 'articles.id' : 'article_pageviews.article_id';
foreach ($authorsFilter as [$type, $values]) {
$this->checkQueryType($type);
$articlePageviewsQuery->whereIn($column, function ($query) use ($type, $values) {
$query->select('article_id')
->from('article_author')
->join('authors', 'article_author.author_id', '=', 'authors.id')
->whereIn('authors.' . $type, $values);
});
}
}
private function addContentTypeCondition(Builder $baseQuery, string $contentType, bool $isArticlesTable = false): void
{
if (!$isArticlesTable && !$this->hasAlreadyJoinedArticlesTable($baseQuery)) {
$baseQuery->join('articles', 'article_pageviews.article_id', '=', 'articles.id');
}
$baseQuery->where('articles.content_type', '=', $contentType);
}
private function addTagsCondition(Builder $articlePageviewsQuery, array $tagFilters, bool $isArticlesTable = false): void
{
$column = $isArticlesTable ? 'articles.id' : 'article_pageviews.article_id';
foreach ($tagFilters as [$type, $values]) {
$this->checkQueryType($type);
$articlePageviewsQuery->whereIn($column, function ($query) use ($type, $values) {
$query->select('article_id')
->from('article_tag')
->join('tags', 'article_tag.tag_id', '=', 'tags.id')
->whereIn('tags.' . $type, $values);
});
}
}
private function addTagCategoriesCondition(Builder $articlePageviewsQuery, array $tagCategoryFilters, bool $isArticlesTable = false): void
{
$column = $isArticlesTable ? 'articles.id' : 'article_pageviews.article_id';
foreach ($tagCategoryFilters as [$type, $values]) {
$this->checkQueryType($type);
$articlePageviewsQuery->whereIn($column, function ($query) use ($type, $values) {
$query->select('article_id')
->from('article_tag as at')
->join('tag_tag_category', 'tag_tag_category.tag_id', '=', 'at.tag_id')
->join('tag_categories', 'tag_categories.id', '=', 'tag_tag_category.tag_category_id')
->whereIn('tag_categories.' . $type, $values);
});
}
}
private function addPublishedFromCondition(Builder $articlePageviewsQuery, Carbon $publishedFrom, bool $isArticlesTable): void
{
if (!$isArticlesTable && !$this->hasAlreadyJoinedArticlesTable($articlePageviewsQuery)) {
$articlePageviewsQuery->join('articles', 'article_pageviews.article_id', '=', 'articles.id');
}
$articlePageviewsQuery->where('articles.published_at', '>=', $publishedFrom);
}
private function addPublishedToCondition(Builder $articlePageviewsQuery, Carbon $publishedTo, bool $isArticlesTable): void
{
if (!$isArticlesTable && !$this->hasAlreadyJoinedArticlesTable($articlePageviewsQuery)) {
$articlePageviewsQuery->join('articles', 'article_pageviews.article_id', '=', 'articles.id');
}
$articlePageviewsQuery->where('articles.published_at', '<', $publishedTo);
}
private function shouldUseArticlesTableAsDataSource(Carbon $timeFrom, ?Carbon $publishedFrom = null, ?Carbon $timeTo = null): bool
{
if ($timeTo && $timeTo < Carbon::now()) {
return false;
}
if ($publishedFrom) {
$publishedFrom = Carbon::parse($publishedFrom);
if ($publishedFrom >= $timeFrom) {
return true;
}
}
$cacheKey = "articlePageviewsFirstItemTime";
$result = Cache::get($cacheKey);
if (!$result) {
$data = DB::table('article_pageviews')
->orderBy('time_from')
->limit(1)
->first();
if (!$data) {
return true;
}
$result = $data->time_from;
// Cache data for one day
Cache::put($cacheKey, $result, 86400);
}
$timeFromThresholdObject = Carbon::parse($result);
return $timeFromThresholdObject > $timeFrom;
}
private function hasAlreadyJoinedArticlesTable(Builder $builder): bool
{
if (!is_array($builder->joins)) {
return false;
}
return in_array('articles', array_map(function ($item) {
/** @var JoinClause $item */
return $item->table;
}, $builder->joins), true);
}
private function getPageviewsThreshold(Builder $query, Carbon $timeTo, int $limit): int
{
$timeFrom = (clone $timeTo)->subDays(3);
$data = $query->where('article_pageviews.time_from', '>=', $timeFrom)
->limit(1)
->offset($limit - 1)
->first();
return $data ? $data->pageviews : 0;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Newsletter/NewsletterCriterionEnum.php | Beam/extensions/beam-module/src/Model/Newsletter/NewsletterCriterionEnum.php | <?php
namespace Remp\BeamModule\Model\Newsletter;
enum NewsletterCriterionEnum: string
{
case AveragePayment = 'average_payment';
case TimespentAll = 'timespent_all';
case PageViewsSignedIn = 'pageviews_signed_in';
case PageViewsSubscribers = 'pageviews_subscribers';
case TimespentSubscribers = 'timespent_subscribers';
case Conversions = 'conversions';
case TimespentSignedIn = 'timespent_signed_in';
case PageViewsAll = 'pageviews_all';
case Bookmarks = 'bookmarks';
public static function getFriendlyList(): array
{
return [
self::Bookmarks->value => 'Bookmarks',
self::PageViewsAll->value => 'Pageviews all',
self::PageViewsSignedIn->value => 'Pageviews signed in',
self::PageViewsSubscribers->value => 'Pageviews subscribers',
self::TimespentAll->value => 'Time spent all',
self::TimespentSignedIn->value => 'Time spent signed in',
self::TimespentSubscribers->value => 'Time spent subscribers',
self::Conversions->value => 'Conversions',
self::AveragePayment->value => 'Average payment'
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Model/Property/SelectedProperty.php | Beam/extensions/beam-module/src/Model/Property/SelectedProperty.php | <?php
namespace Remp\BeamModule\Model\Property;
use Remp\BeamModule\Model\Account;
use Remp\BeamModule\Model\Property;
use InvalidArgumentException;
use Remp\Journal\TokenProvider;
class SelectedProperty implements TokenProvider
{
const SELECTED_PROPERTY_TOKEN_UUID = 'selected_property_token_uuid';
private $cachedSelectInputData;
public function getToken(): ?string
{
return \Session::get(self::SELECTED_PROPERTY_TOKEN_UUID);
}
/**
* @param string|null $propertyToken
* @throws InvalidArgumentException when assigned token is not in DB
*/
public function setToken(?string $propertyToken)
{
if (!$propertyToken) {
\Session::remove(self::SELECTED_PROPERTY_TOKEN_UUID);
} else {
$property = Property::where('uuid', $propertyToken)->first();
if (!$property) {
throw new InvalidArgumentException("No such token");
}
\Session::put(self::SELECTED_PROPERTY_TOKEN_UUID, $property->uuid);
}
}
public function selectInputData()
{
if ($this->cachedSelectInputData) {
return $this->cachedSelectInputData;
}
$selectedPropertyTokenUuid = $this->getToken();
$accountPropertyTokens = [
[
'name' => null,
'tokens' => [
[
'uuid' => null,
'name' => 'All properties',
'selected' => true,
]
]
]
];
foreach (Account::with('properties')->get() as $account) {
$tokens = [];
foreach ($account->properties as $property) {
$selected = $property->uuid === $selectedPropertyTokenUuid;
if ($selected) {
$accountPropertyTokens[0]['tokens'][0]['selected'] = false;
}
$tokens[] = [
'uuid' => $property->uuid,
'name' => $property->name,
'selected' => $selected
];
}
if (count($tokens) > 0) {
$accountPropertyTokens[] = [
'name' => $account->name,
'tokens' => $tokens
];
}
}
// Convert to object recursively
$this->cachedSelectInputData = json_decode(json_encode($accountPropertyTokens));
return $this->cachedSelectInputData;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Helpers/DebugProxy.php | Beam/extensions/beam-module/src/Helpers/DebugProxy.php | <?php
namespace Remp\BeamModule\Helpers;
class DebugProxy
{
private $obj;
private $isDebug;
/**
* DebugProxy wraps an object and performs any function call on underlying object in case $isDebug === true
* In case of false, no function call is made
* This can be useful for example for output tools you do not want in production, such as ProgressBar
*/
public function __construct($obj, bool $isDebug)
{
$this->obj = $obj;
$this->isDebug = $isDebug;
}
public function __call($name, $arguments)
{
if ($this->isDebug) {
call_user_func_array([$this->obj, $name], $arguments);
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Helpers/Misc.php | Beam/extensions/beam-module/src/Helpers/Misc.php | <?php
namespace Remp\BeamModule\Helpers;
use Carbon\CarbonInterval;
use Illuminate\Support\Carbon;
class Misc
{
// e.g. 3d 4h 2m
const TIMESPAN_VALIDATION_REGEX = '/^(\d+d)?\s*(\d+h)?\s*(\d+m)?$/i';
/**
* Converts timespan string to Carbon object in past
* @param string $timespan format specifying number of days, hours and minutes, e.g. 3d 4h 5m
* @param Carbon|null $from
*
* @return Carbon
*/
public static function timespanInPast(string $timespan, Carbon $from = null): Carbon
{
$c = $from ?? Carbon::now();
$matches = [];
preg_match("/^(?:(\d+)d)?\s*(?:(\d+)h)?\s*(?:(\d+)m)?$/i", $timespan, $matches);
if ($matches[1] ?? false) {
$c->subDays($matches[1]);
}
if ($matches[2] ?? false) {
$c->subHours($matches[2]);
}
if ($matches[3] ?? false) {
$c->subMinutes($matches[3]);
}
return $c;
}
/**
* Convert any Carbon parseable date to format that can be safely used in SQL (with correct time zone)
* TODO: this can be removed after update to Laravel 8 and getting rid of upsert, see Article#upsert method
* @param $date
*
* @return string
*/
public static function dateToSql($date): string
{
return Carbon::parse($date)
->tz(date_default_timezone_get())
->toDateTimeString();
}
public static function secondsIntoReadableTime(int $seconds): string
{
if ($seconds === 0) {
return "0s";
}
$output = '';
$interval = CarbonInterval::seconds($seconds)->cascade();
if ($interval->hours > 0) {
$output .= "{$interval->hours}h ";
}
if ($interval->minutes > 0) {
$output .= "{$interval->minutes}m ";
}
if ($interval->seconds > 0) {
$output .= "{$interval->seconds}s";
}
return trim($output);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Helpers/Colors.php | Beam/extensions/beam-module/src/Helpers/Colors.php | <?php
namespace Remp\BeamModule\Helpers;
use Illuminate\Support\Facades\Cache;
class Colors
{
private const PREDEFINED_ORDER = ['internal', 'direct/IM', 'search', 'social', 'external', 'email'];
private const CACHE_KEY_REFERER_MEDIUM_TAGS_ORDERING = 'referer_medium_tags_ordering';
/**
* Order referer medium tags by given rules
* Rules applied in order:
* 1. caching order (if enabled), all tags has to be present in the cached field otherwise not applied
* 2. predefined order
* 3. tag count order (descending)
*
* @param array $refererMediumTagCounts
*
* @return array list of ordered tags
*/
public static function orderRefererMediumTags(array $refererMediumTagCounts): array
{
if (Cache::has(self::CACHE_KEY_REFERER_MEDIUM_TAGS_ORDERING)) {
$cachedOrderedTags = Cache::get(self::CACHE_KEY_REFERER_MEDIUM_TAGS_ORDERING);
// check if all tags are in the cached results
$allTagsPresent = empty(array_diff(
array_keys($refererMediumTagCounts),
$cachedOrderedTags
));
if ($allTagsPresent) {
return array_values(array_intersect($cachedOrderedTags, array_keys($refererMediumTagCounts)));
}
}
// First, take predefined order (flipped - keep tags as keys)
$predefinedOrder = array_flip(array_intersect(self::PREDEFINED_ORDER, array_keys($refererMediumTagCounts)));
// Second, take rest of the tags and sort them according to counts, descending
$unorderedTags = array_diff_key($refererMediumTagCounts, $predefinedOrder);
arsort($unorderedTags);
$toReturn = array_merge(array_keys($predefinedOrder), array_keys($unorderedTags));
Cache::forever(self::CACHE_KEY_REFERER_MEDIUM_TAGS_ORDERING, $toReturn);
return $toReturn;
}
public static function assignColorsToGeneralTags(iterable $tags, $caching = true): array
{
$i = 0;
$colors = [];
foreach ($tags as $tag) {
$colors[$tag] = self::generateColor('general_tag', $tag, $i++, true);
}
return $colors;
}
public static function assignColorsToVariantTags(iterable $tags, $caching = true): array
{
$predefined = [
'A' => '#E63952',
'B' => '#00C7DF',
'C' => '#FFC34A',
'D' => '#DEDEDE',
'E' => '#CDE092',
'F' => '#3B40b6',
];
$i = 0;
$colors = [];
foreach ($tags as $tag) {
$colors[$tag] = $predefined[$tag] ?? self::generateColor('ab_test_variants', $tag, $i++, $caching);
}
return $colors;
}
public static function assignColorsToMediumRefers(iterable $mediumReferers, $caching = true): array
{
$predefined = [
'internal' => '#E63952',
'direct/IM' => '#00C7DF',
'social' => '#FFC34A',
'search' => '#DEDEDE',
'external' => '#CDE092',
'email' => '#3B40b6',
];
$i = 0;
$colors = [];
foreach ($mediumReferers as $mediumReferer) {
$colors[$mediumReferer] = $predefined[$mediumReferer] ?? self::generateColor('medium_referer', $mediumReferer, $i++, $caching);
}
return $colors;
}
private static function generateColor(string $colorType, string $tag, int $index, bool $caching): string
{
$cacheKey = "COLOR::{$colorType}::$tag";
if ($caching && Cache::has($cacheKey)) {
return Cache::get($cacheKey);
}
// predefined colors
$colors = [
'#3366cc',
'#dc3912',
'#ff9900',
'#109618',
'#990099',
'#0099c6',
'#dd4477',
'#66aa00',
'#b82e2e',
'#316395',
'#994499',
'#22aa99',
'#aaaa11',
'#6633cc',
'#e67300',
'#8b0707',
'#651067',
'#329262',
'#5574a6',
'#3b3eac'
];
if ($index < count($colors)) {
$color = $colors[$index];
} else {
// random color
$color = '#' . str_pad(dechex(random_int(0, 0xFFFFFF)), 6, '0', STR_PAD_LEFT);
}
if ($caching) {
Cache::forever($cacheKey, $color);
}
return $color;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Helpers/Journal/JournalHelpers.php | Beam/extensions/beam-module/src/Helpers/Journal/JournalHelpers.php | <?php
namespace Remp\BeamModule\Helpers\Journal;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\RefererMediumLabel;
use Cache;
use Carbon\Carbon;
use Illuminate\Support\Collection;
use Remp\Journal\AggregateRequest;
use Remp\Journal\ConcurrentsRequest;
use Remp\Journal\JournalContract;
use Remp\Journal\ListRequest;
class JournalHelpers
{
const CATEGORY_ACTION_SEPARATOR = '::';
private $journal;
private $cachedRefererMediumLabels;
public function __construct(JournalContract $journal)
{
$this->journal = $journal;
}
public function currentConcurrentsCount(callable $conditions = null, Carbon $now = null): Collection
{
$timeBefore = $now;
if ($timeBefore === null) {
$timeBefore = Carbon::now()->microsecond(0);
}
$timeAfter = (clone $timeBefore)->subSeconds(600); // Last 10 minutes
$req = new ConcurrentsRequest();
$req->setTimeAfter($timeAfter);
$req->setTimeBefore($timeBefore);
if ($conditions) {
$conditions($req);
}
return collect($this->journal->concurrents($req));
}
/**
* Get available referer mediums in pageviews segments storage per last $hoursAgo
* Useful for filtering in data tables
* @param int $hoursAgo
*
* @return Collection
*/
public function derivedRefererMediumGroups(int $hoursAgo = 12): Collection
{
$ar = (new AggregateRequest('pageviews', 'load'))
->setTime(Carbon::now()->subHours($hoursAgo), Carbon::now())
->addGroup('derived_referer_medium');
$results = collect($this->journal->count($ar));
return $results->pluck('tags.derived_referer_medium');
}
/**
* Load unique users count per each article
*
* @param Collection $articles
*
* @return Collection containing mapping of articles' external_ids to unique users count
*/
public function uniqueBrowsersCountForArticles(Collection $articles): Collection
{
$minimalPublishedTime = Carbon::now();
foreach ($articles as $article) {
if ($minimalPublishedTime->gt($article->published_at)) {
$minimalPublishedTime = $article->published_at;
}
}
// sort article IDs to help journal caching mechanism cache this payload
$externalArticleIds = $articles->pluck('external_id')->sortDesc(SORT_NUMERIC)->toArray();
$r = (new AggregateRequest('pageviews', 'load'))
->setTime($minimalPublishedTime, Carbon::now())
->addGroup('article_id')
->addFilter('article_id', ...$externalArticleIds);
$result = collect($this->journal->unique($r));
return $result
->filter(function ($item) {
return $item->tags !== null;
})
->mapWithKeys(function ($item) {
return [$item->tags->article_id => $item->count];
});
}
/**
* Load timespent count per each article
*
* @param Collection $articles
* @param Carbon $since
*
* @return Collection containing mapping of articles' external_ids to timespent in seconds
*/
public function timespentForArticles(Collection $articles, Carbon $since): Collection
{
$externalArticleIds = $articles->pluck('external_id')->toArray();
$request = new AggregateRequest('pageviews', 'timespent');
$request->setTimeAfter($since);
$request->setTimeBefore(Carbon::now());
$request->addGroup('article_id');
$request->addFilter('article_id', ...$externalArticleIds);
$result = collect($this->journal->avg($request));
return $result
->filter(function ($item) {
return $item->tags !== null;
})
->mapWithKeys(function ($item) {
return [$item->tags->article_id => $item->avg];
});
}
/**
* Load a/b test flags for articles
*
* @param Collection $articles
* @param Carbon $since
*
* @return Collection containing mapping of articles' external_ids to a/b test flags
*/
public function abTestFlagsForArticles(Collection $articles, Carbon $since): Collection
{
$externalArticleIds = $articles->pluck('external_id')->sortDesc(SORT_NUMERIC)->toArray();
$cacheKey = "abTestFlagsForArticles." . hash('md5', implode('', $externalArticleIds));
$result = Cache::get($cacheKey);
if (!$result) {
$request = new AggregateRequest('pageviews', 'load');
$request->setTimeAfter($since);
$request->setTimeBefore(Carbon::now());
$request->addGroup('article_id', 'title_variant', 'image_variant');
$request->addFilter('article_id', ...$externalArticleIds);
$result = collect($this->journal->count($request));
// Set 10 minutes cache
Cache::put($cacheKey, $result, 600);
}
$articles = collect();
foreach ($result as $item) {
$key = $item->tags->article_id;
if (!$articles->has($key)) {
$articles->put($key, (object) [
'title_variants' => collect(),
'image_variants' => collect()
]);
}
$articles[$key]->title_variants->push($item->tags->title_variant);
$articles[$key]->image_variants->push($item->tags->image_variant);
}
return $articles->map(function ($item) {
$hasTitleTest = $item->title_variants->filter(function ($variant) {
return $variant !== '';
})->unique()->count() > 1;
$hasImageTest = $item->image_variants->filter(function ($variant) {
return $variant !== '';
})->unique()->count() > 1;
return (object) [
'has_title_test' => $hasTitleTest,
'has_image_test' => $hasImageTest
];
});
}
/**
* Get time iterator, which is the earliest point of time (Carbon instance) that when
* interval of length $intervalMinutes is added,
* the resulting Carbon instance is greater or equal to $timeAfter
*
* This is useful for preparing data for histogram graphs
*
* @param Carbon $timeAfter
* @param int $intervalMinutes
* @param \DateTimeZone|string $tz Default value is `UTC`.
*
* @return Carbon
*/
public static function getTimeIterator(Carbon $timeAfter, int $intervalMinutes, $tz = 'UTC'): Carbon
{
$timeIterator = (clone $timeAfter)->tz($tz)->startOfDay();
while ($timeIterator->lessThanOrEqualTo($timeAfter)) {
$timeIterator->addMinutes($intervalMinutes);
}
return $timeIterator->subMinutes($intervalMinutes);
}
public function refererMediumLabel(string $medium, bool $cached = true): string
{
if (!$cached || !$this->cachedRefererMediumLabels) {
$this->cachedRefererMediumLabels = RefererMediumLabel::all();
}
foreach ($this->cachedRefererMediumLabels as $row) {
if ($medium === $row->referer_medium) {
return $row->label;
}
}
// TODO: extract to seeders
// Built-in labels
switch ($medium) {
case 'direct':
return 'direct/IM';
default:
return $medium;
}
}
/**
* Returns list of all categories and actions for stored events
* @param \Remp\BeamModule\Model\Article|null $article if provided, load events data only for particular article
*
* @return array array of objects having category and action parameters
*/
public function eventsCategoriesActions(?Article $article = null): array
{
$r = AggregateRequest::from('events')->addGroup('category', 'action');
if ($article !== null) {
$r->addFilter('article_id', $article->external_id);
}
$results = [];
foreach ($this->journal->count($r) as $item) {
if (!empty($item->tags->action) && !empty($item->tags->category)) {
$results[] = (object) $item->tags;
}
}
return $results;
}
/**
* @param JournalInterval $journalInterval load events only for particular interval
* @param string[] $requestedCategoryActionEvents array of strings having format 'category::action'
* @param \Remp\BeamModule\Model\Article|null $article if provided, load only events linked to particular article
*
* @return array List of events as provided by Journal API
*/
public function loadEvents(JournalInterval $journalInterval, array $requestedCategoryActionEvents, ?Article $article = null): array
{
if (!$requestedCategoryActionEvents) {
return [];
}
$categories = [];
$categoryActions = [];
foreach ($requestedCategoryActionEvents as $item) {
[$category, $action] = explode(self::CATEGORY_ACTION_SEPARATOR, $item);
$categories[] = $category;
if (! array_key_exists($category, $categoryActions)) {
$categoryActions[$category] = [];
}
$categoryActions[$category][] = $action;
}
$r = ListRequest::from('events')
->setTime($journalInterval->timeAfter, $journalInterval->timeBefore)
->addFilter('category', ...$categories);
if ($article) {
$r->addFilter('article_id', $article->external_id);
}
$response = $this->journal->list($r);
$events = [];
foreach ($response[0]->events ?? [] as $event) {
if (! in_array($event->action, $categoryActions[$event->category], true)) {
// ATM Journal API doesn't provide way to simultaneously check for category and action on the same record,
// therefore check first category in the request and check action here
continue;
}
$events[] = $event;
}
return $events;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Helpers/Journal/JournalInterval.php | Beam/extensions/beam-module/src/Helpers/Journal/JournalInterval.php | <?php
namespace Remp\BeamModule\Helpers\Journal;
use Remp\BeamModule\Model\Article;
use Carbon\Carbon;
use InvalidArgumentException;
class JournalInterval
{
/**
* Retention rules of article snapshots
* Rules are used during compression of traffic data and also for rendering articles' traffic histogram
* Rules define maximal detail of traffic for given window we can display
* Array item describes [INTERVAL_START, INTERVAL_END, WINDOW_SIZE, WINDOW_SIZE_STRING], all in minutes
*/
const RETENTION_RULES = [
[0, 10, 1, '1m'], // in interval [0, 10) minutes, keep snapshot of article traffic every minute
[10, 60, 5, '5m'], // in interval [10, 60) minutes, keep snapshot of article traffic max every 5 minutes
[60, 60*24, 20, '20m'], // [60m, 1d)
[60*24 , 60*24*8, 60, '1h'], // [1d, 8d)
[60*24*7 , 60*24*30, 120, '2h'], // [7d, 30d)
[60*24*30 , 60*24*90, 180, '3h'], // [30d, 90d)
[60*24*90 , 60*24*180, 360, '6h'], // [90d, 180d)
[60*24*180 , 60*24*365, 720, '12h'], // [180d, 1y)
[60*24*365 , null, 1440, '24h'], // [1y, unlimited)
];
public $timeAfter;
public $timeBefore;
public $intervalText;
public $intervalMinutes;
public $tz;
public $cacheTTL;
public function __construct(
\DateTimeZone $tz,
string $interval,
Article $article = null,
array $allowedIntervals = null,
int $cacheTTL = null
) {
if ($allowedIntervals && !in_array($interval, $allowedIntervals)) {
throw new InvalidArgumentException("Parameter 'interval' must be one of the [" . implode(',', $allowedIntervals) . "] values, instead '$interval' provided");
}
$this->tz = $tz;
switch ($interval) {
case 'today':
$this->timeAfter = Carbon::today($tz);
$this->timeBefore = Carbon::now($tz);
$this->intervalText = '20m';
$this->intervalMinutes = 20;
break;
case '1day':
$this->timeBefore = Carbon::now($tz);
$this->timeAfter = $this->timeBefore->copy()->subDay();
$this->intervalText = '20m';
$this->intervalMinutes = 20;
break;
case '7days':
$this->timeAfter = Carbon::today($tz)->subDays(6);
$this->timeBefore = Carbon::now($tz);
$this->intervalText = '1h';
$this->intervalMinutes = 60;
break;
case '30days':
$this->timeAfter = Carbon::today($tz)->subDays(29);
$this->timeBefore = Carbon::now($tz);
$this->intervalText = '2h';
$this->intervalMinutes = 120;
break;
case 'all':
if (!$article) {
throw new InvalidArgumentException("Missing article for 'all' option");
}
[$intervalText, $intervalMinutes] = self::getIntervalDependingOnArticlePublishedDate($article);
$this->timeAfter = (clone $article->published_at)->tz($tz);
$this->timeBefore = Carbon::now($tz);
$this->intervalText = $intervalText;
$this->intervalMinutes = $intervalMinutes;
break;
case 'first1day':
if (!$article) {
throw new InvalidArgumentException("Missing article for 'first1day' option");
}
$this->timeAfter = (clone $article->published_at)->tz($tz);
$this->timeBefore = $this->timeAfter->copy()->addDay();
$this->intervalText = '20m';
$this->intervalMinutes = 20;
break;
case 'first7days':
if (!$article) {
throw new InvalidArgumentException("Missing article for 'first7days' option");
}
$this->timeAfter = (clone $article->published_at)->tz($tz);
$this->timeBefore = $this->timeAfter->copy()->addDays(7);
$this->intervalText = '1h';
$this->intervalMinutes = 60;
break;
case 'first14days':
if (!$article) {
throw new InvalidArgumentException("Missing article for 'first14days' option");
}
$this->timeAfter = (clone $article->published_at)->tz($tz);
$this->timeBefore = $this->timeAfter->copy()->addDays(14);
$this->intervalText = '1h';
$this->intervalMinutes = 60;
break;
default:
throw new InvalidArgumentException("Parameter 'interval' must be one of the [today,1day,7days,30days,all] values, instead '$interval' provided");
}
if (!$cacheTTL) {
$this->cacheTTL = $this->intervalMinutes * 60;
}
}
/**
* @param \Remp\BeamModule\Model\Article $article
*
* @return array
* @throws \Exception
*/
private static function getIntervalDependingOnArticlePublishedDate(Article $article): array
{
$articleAgeInMins = $article->published_at->diffInMinutes(Carbon::now());
foreach (self::RETENTION_RULES as $rule) {
$startMinute = $rule[0];
$endMinute = $rule[1];
$windowSizeInMinutes = $rule[2];
$windowSizeText = $rule[3];
if ($endMinute === null || $articleAgeInMins < $endMinute) {
return [$windowSizeText, $windowSizeInMinutes];
}
}
throw new \Exception("No fitting rule for article {$article->id}");
}
public function setIntervalMinutes($minutes): void
{
$this->intervalMinutes = $minutes;
$this->intervalText = $minutes . 'm';
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Request.php | Beam/extensions/beam-module/src/Http/Request.php | <?php
namespace Remp\BeamModule\Http;
class Request extends \Illuminate\Http\Request
{
public function isSecure(): bool
{
$isSecure = parent::isSecure();
if ($isSecure) {
return true;
}
if ($this->server->get('HTTPS') == 'on') {
return true;
}
if ($this->server->get('HTTP_X_FORWARDED_PROTO') == 'https') {
return true;
}
if ($this->server->get('HTTP_X_FORWARDED_SSL') == 'on') {
return true;
}
return false;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/ConversionsSankeyRequest.php | Beam/extensions/beam-module/src/Http/Requests/ConversionsSankeyRequest.php | <?php
namespace Remp\BeamModule\Http\Requests;
use Remp\BeamModule\Model\ConversionSource;
use Illuminate\Foundation\Http\FormRequest;
class ConversionsSankeyRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'tz' => 'timezone|required',
'interval' => 'required|in:7,30',
'conversionSourceType' => 'required|in:'.implode(',', ConversionSource::getTypes())
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/EntityRequest.php | Beam/extensions/beam-module/src/Http/Requests/EntityRequest.php | <?php
namespace Remp\BeamModule\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class EntityRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$id = $this->entity->id ?? '';
return [
'name' => "required|string|unique:entities,name,{$id}|max:255",
'parent_id' => 'required|integer',
'params' => 'required|array',
'params.*.name' => 'required|string',
'params.*.type' => 'required|string',
'params_to_delete' => 'array',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/ArticlesListRequest.php | Beam/extensions/beam-module/src/Http/Requests/ArticlesListRequest.php | <?php
namespace Remp\BeamModule\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ArticlesListRequest extends FormRequest
{
public function authorize()
{
return true;
}
protected function prepareForValidation()
{
$this->merge([
'external_ids' => array_filter(explode(',', $this->get('external_ids'))),
'ids' => array_filter(explode(',', $this->get('ids'))),
]);
}
public function rules()
{
// TODO: add prohibited_if rule for each field after update to Laravel 8
return [
'external_ids' => 'array',
'external_ids.*' => 'string',
'ids' => 'array',
'ids.*' => 'integer',
'published_from' => 'date',
'published_to' => 'date',
'per_page' => 'integer'
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/ConversionUpsertRequest.php | Beam/extensions/beam-module/src/Http/Requests/ConversionUpsertRequest.php | <?php
namespace Remp\BeamModule\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ConversionUpsertRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'conversions.*.article_external_id' => "required|string|exists:articles,external_id",
'conversions.*.transaction_id' => "required|string",
'conversions.*.amount' => "required|numeric",
'conversions.*.currency' => "required|string",
'conversions.*.paid_at' => "required|date",
'conversions.*.user_id' => "required|string",
];
}
public function messages()
{
return [
'conversions.*.article_external_id.exists' => "Article with provided external ID doesn't exist",
'conversions.*.transaction_id.unique' => 'Conversion with given transaction ID has already been recorded',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/AuthorSegmentsConfigurationRequest.php | Beam/extensions/beam-module/src/Http/Requests/AuthorSegmentsConfigurationRequest.php | <?php
namespace Remp\BeamModule\Http\Requests;
use Remp\BeamModule\Model\Config\ConfigNames;
use Illuminate\Foundation\Http\FormRequest;
class AuthorSegmentsConfigurationRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
ConfigNames::AUTHOR_SEGMENTS_MIN_VIEWS => 'required|numeric|min:0',
ConfigNames::AUTHOR_SEGMENTS_MIN_AVERAGE_TIMESPENT => 'required|numeric|min:0',
ConfigNames::AUTHOR_SEGMENTS_MIN_RATIO => 'required|numeric|between:0,1',
ConfigNames::AUTHOR_SEGMENTS_DAYS_IN_PAST => 'required|numeric|between:1,90',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/SectionSegmentsTestRequest.php | Beam/extensions/beam-module/src/Http/Requests/SectionSegmentsTestRequest.php | <?php
namespace Remp\BeamModule\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SectionSegmentsTestRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'min_views' => 'required|numeric',
'min_average_timespent' => 'required|numeric',
'min_ratio' => 'required|numeric',
'email' => 'required|email',
'history' => 'required|in:30,60,90',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/ConversionRequest.php | Beam/extensions/beam-module/src/Http/Requests/ConversionRequest.php | <?php
namespace Remp\BeamModule\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ConversionRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
$transactionId = $this->conversion->transaction_id ?? '';
return [
'article_external_id' => "required|string|exists:articles,external_id",
'transaction_id' => "required|string|unique:conversions,transaction_id,{$transactionId},transaction_id",
'amount' => "required|numeric",
'currency' => "required|string",
'paid_at' => "required|date",
'user_id' => 'required|numeric',
];
}
public function messages()
{
return [
'article_external_id.exists' => "Article with provided external ID doesn't exist",
'transaction_id.unique' => 'Conversion with given transaction ID has already been recorded',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/SegmentRequest.php | Beam/extensions/beam-module/src/Http/Requests/SegmentRequest.php | <?php
namespace Remp\BeamModule\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SegmentRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
$id = $this->segment->id ?? '';
return [
'name' => "required|string|unique:segments,name,{$id}|max:255",
'code' => "required|string|unique:segments,code,{$id}",
'active' => 'required|boolean',
'rules' => 'required|array',
'rules.*.timespan' => 'required|integer',
'rules.*.count' => 'required|integer',
'rules.*.event_category' => 'required|string',
'rules.*.event_action' => 'required|string',
'rules.*.operator' => 'required|string',
'rules.*.fields' => 'array',
'rules.*.flags' => 'array',
'rules.*.flags.*.key' => 'string',
'rules.*.flags.*.value' => 'string|nullable|in:"0","1"',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/SearchRequest.php | Beam/extensions/beam-module/src/Http/Requests/SearchRequest.php | <?php
namespace Remp\BeamModule\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SearchRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'term' => 'required|string'
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/NewsletterRequest.php | Beam/extensions/beam-module/src/Http/Requests/NewsletterRequest.php | <?php
namespace Remp\BeamModule\Http\Requests;
use Remp\BeamModule\Helpers\Misc;
use Remp\BeamModule\Model\NewsletterCriterion;
use Illuminate\Foundation\Http\FormRequest;
class NewsletterRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|string',
'segment' => 'required|string',
'mail_type_code' => 'required|string',
'mailer_generator_id' => 'required|integer',
'criteria' => 'required|string|in:' . NewsletterCriterion::allCriteriaConcatenated(),
'articles_count' => 'required|integer|min:1|max:100',
'personalized_content' => 'boolean',
'starts_at' => 'required|date',
'timespan' => [
'required',
'regex:' . Misc::TIMESPAN_VALIDATION_REGEX
],
'email_subject' => 'required|string',
'email_from' => 'required|string',
'recurrence_rule' => 'nullable|string',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/DataTable.php | Beam/extensions/beam-module/src/Http/Requests/DataTable.php | <?php
namespace Remp\BeamModule\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class DataTable extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'order.0.column',
'order.0.dir',
'start',
'length',
'search.value',
'start',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/AuthorSegmentsTestRequest.php | Beam/extensions/beam-module/src/Http/Requests/AuthorSegmentsTestRequest.php | <?php
namespace Remp\BeamModule\Http\Requests;
use Remp\BeamModule\Model\NewsletterCriterion;
use Illuminate\Foundation\Http\FormRequest;
class AuthorSegmentsTestRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'min_views' => 'required|numeric',
'min_average_timespent' => 'required|numeric',
'min_ratio' => 'required|numeric',
'email' => 'required|email',
'history' => 'required|in:30,60,90',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/ArticleRequest.php | Beam/extensions/beam-module/src/Http/Requests/ArticleRequest.php | <?php
namespace Remp\BeamModule\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class ArticleRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'external_id' => "required|string",
'property_uuid' => "required|string|exists:properties,uuid",
'title' => "required|string",
'url' => "required|url",
'authors' => 'array',
'sections' => 'array',
'tags' => 'array',
'image_url' => 'nullable|url',
'published_at' => 'date',
'authors.*' => 'string',
'sections.*' => 'string',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/Api/v1/ReadArticlesRequest.php | Beam/extensions/beam-module/src/Http/Requests/Api/v1/ReadArticlesRequest.php | <?php
namespace Remp\BeamModule\Http\Requests\Api\v1;
use Illuminate\Foundation\Http\FormRequest;
class ReadArticlesRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'from' => 'date',
'to' => 'date',
'user_id' => 'string|required_without:browser_id',
'browser_id' => 'string|required_without:user_id',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/Api/v1/PageviewsTimeHistogramRequest.php | Beam/extensions/beam-module/src/Http/Requests/Api/v1/PageviewsTimeHistogramRequest.php | <?php
namespace Remp\BeamModule\Http\Requests\Api\v1;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Arr;
class PageviewsTimeHistogramRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'from' => 'required|date',
'to' => 'required|date',
'content_type' => 'string',
'sections.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in sections filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in sections filter");
}
}],
'sections.*.external_ids' => 'array',
'sections.*.external_ids.*' => 'string',
'sections.*.names' => 'array',
'sections.*.names.*' => 'string',
'authors.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in authors filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in authors filter");
}
}],
'authors.*.external_ids' => 'array',
'authors.*.external_ids.*' => 'string',
'authors.*.names' => 'array',
'authors.*.names.*' => 'string',
'tags.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in tags filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in tags filter");
}
}],
'tags.*.external_ids' => 'array',
'tags.*.external_ids.*' => 'string',
'tags.*.names' => 'array',
'tags.*.names.*' => 'string',
'tag_categories.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in tag categories filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in tag categories filter");
}
}],
'tag_categories.*.external_ids' => 'array',
'tag_categories.*.external_ids.*' => 'string',
'tag_categories.*.names' => 'array',
'tag_categories.*.names.*' => 'string',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/Api/v1/UnreadArticlesRequest.php | Beam/extensions/beam-module/src/Http/Requests/Api/v1/UnreadArticlesRequest.php | <?php
namespace Remp\BeamModule\Http\Requests\Api\v1;
use Remp\BeamModule\Helpers\Misc;
use Remp\BeamModule\Model\NewsletterCriterion;
use Illuminate\Foundation\Http\FormRequest;
class UnreadArticlesRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'timespan' => [
'required',
'regex:' . Misc::TIMESPAN_VALIDATION_REGEX
],
'articles_count' => 'required|integer',
'criteria.*' => 'required|string|in:' . NewsletterCriterion::allCriteriaConcatenated(),
'user_ids.*' => 'required|integer',
'read_articles_timespan' => [
'regex:' . Misc::TIMESPAN_VALIDATION_REGEX
],
'ignore_authors.*' => 'string',
'ignore_content_types.*' => 'string',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/Api/v1/TopTagsSearchRequest.php | Beam/extensions/beam-module/src/Http/Requests/Api/v1/TopTagsSearchRequest.php | <?php
namespace Remp\BeamModule\Http\Requests\Api\v1;
use Illuminate\Support\Arr;
use Illuminate\Foundation\Http\FormRequest;
class TopTagsSearchRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'from' => 'required|date',
'limit' => 'required|integer',
'sections' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_id', 'name'])) {
$fail("You can not have both 'external_id' and 'name' arrays specified in sections filter");
}
if (!array_key_exists('external_id', $value) && !array_key_exists('name', $value)) {
$fail("You have to specify either 'external_id' or 'name' array in sections filter");
}
}],
'sections.external_id' => 'array',
'sections.external_id.*' => 'string',
'sections.name' => 'array',
'sections.name.*' => 'string',
'authors' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_id', 'name'])) {
$fail("You can not have both 'external_id' and 'name' arrays specified in authors filter");
}
if (!array_key_exists('external_id', $value) && !array_key_exists('name', $value)) {
$fail("You have to specify either 'external_id' or 'name' array in authors filter");
}
}],
'authors.external_id' => 'array',
'authors.external_id.*' => 'string',
'authors.name' => 'array',
'authors.name.*' => 'string',
'content_type' => 'string',
'tag_categories' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_id', 'name'])) {
$fail("You can not have both 'external_id' and 'name' arrays specified in tag categories filter");
}
if (!array_key_exists('external_id', $value) && !array_key_exists('name', $value)) {
$fail("You have to specify either 'external_id' or 'name' array in tag categories filter");
}
}],
'tag_categories.external_id' => 'array',
'tag_categories.external_id.*' => 'string',
'tag_categories.name' => 'array',
'tag_categories.name.*' => 'string',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/Api/v1/ArticleUpsertRequest.php | Beam/extensions/beam-module/src/Http/Requests/Api/v1/ArticleUpsertRequest.php | <?php
namespace Remp\BeamModule\Http\Requests\Api\v1;
use Illuminate\Foundation\Http\FormRequest;
class ArticleUpsertRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'articles.*.external_id' => "required|string",
'articles.*.property_uuid' => "required|string|exists:properties,uuid",
'articles.*.title' => "required|string",
'articles.*.url' => "required|url",
'articles.*.authors' => 'array',
'articles.*.sections' => 'array',
'articles.*.tags' => 'array',
'articles.*.image_url' => 'nullable|url',
'articles.*.published_at' => 'date',
'articles.*.content_type' => 'string',
'articles.*.authors.*' => 'string',
'articles.*.sections.*' => 'string',
'articles.*.titles.*' => 'nullable|string',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/Api/v1/TopArticlesSearchRequest.php | Beam/extensions/beam-module/src/Http/Requests/Api/v1/TopArticlesSearchRequest.php | <?php
namespace Remp\BeamModule\Http\Requests\Api\v1;
use Illuminate\Support\Arr;
use Illuminate\Foundation\Http\FormRequest;
class TopArticlesSearchRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'from' => 'required|date',
'limit' => 'required|integer',
'sections' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_id', 'name'])) {
$fail("You can not have both 'external_id' and 'name' arrays specified in sections filter");
}
if (!array_key_exists('external_id', $value) && !array_key_exists('name', $value)) {
$fail("You have to specify either 'external_id' or 'name' array in sections filter");
}
}],
'sections.external_id' => 'array',
'sections.external_id.*' => 'string',
'sections.name' => 'array',
'sections.name.*' => 'string',
'authors' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_id', 'name'])) {
$fail("You can not have both 'external_id' and 'name' arrays specified in authors filter");
}
if (!array_key_exists('external_id', $value) && !array_key_exists('name', $value)) {
$fail("You have to specify either 'external_id' or 'name' array in authors filter");
}
}],
'authors.external_id' => 'array',
'authors.external_id.*' => 'string',
'authors.name' => 'array',
'authors.name.*' => 'string',
'content_type' => 'string',
'tags' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_id', 'name'])) {
$fail("You can not have both 'external_id' and 'name' arrays specified in tags filter");
}
if (!array_key_exists('external_id', $value) && !array_key_exists('name', $value)) {
$fail("You have to specify either 'external_id' or 'name' array in tags filter");
}
}],
'tags.external_id' => 'array',
'tags.external_id.*' => 'string',
'tags.name' => 'array',
'tags.name.*' => 'string',
'tag_categories' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_id', 'name'])) {
$fail("You can not have both 'external_id' and 'name' arrays specified in tag categories filter");
}
if (!array_key_exists('external_id', $value) && !array_key_exists('name', $value)) {
$fail("You have to specify either 'external_id' or 'name' array in tag categories filter");
}
}],
'tag_categories.external_id' => 'array',
'tag_categories.external_id.*' => 'string',
'tag_categories.name' => 'array',
'tag_categories.name.*' => 'string',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/Api/v1/TopAuthorsSearchRequest.php | Beam/extensions/beam-module/src/Http/Requests/Api/v1/TopAuthorsSearchRequest.php | <?php
namespace Remp\BeamModule\Http\Requests\Api\v1;
use Illuminate\Support\Arr;
use Illuminate\Foundation\Http\FormRequest;
class TopAuthorsSearchRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'from' => 'required|date',
'limit' => 'required|integer',
'sections' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_id', 'name'])) {
$fail("You can not have both 'external_id' and 'name' arrays specified in sections filter");
}
if (!array_key_exists('external_id', $value) && !array_key_exists('name', $value)) {
$fail("You have to specify either 'external_id' or 'name' array in sections filter");
}
}],
'sections.external_id' => 'array',
'sections.external_id.*' => 'string',
'sections.name' => 'array',
'sections.name.*' => 'string',
'content_type' => 'string',
'tags' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_id', 'name'])) {
$fail("You can not have both 'external_id' and 'name' arrays specified in tags filter");
}
if (!array_key_exists('external_id', $value) && !array_key_exists('name', $value)) {
$fail("You have to specify either 'external_id' or 'name' array in tags filter");
}
}],
'tags.external_id' => 'array',
'tags.external_id.*' => 'string',
'tags.name' => 'array',
'tags.name.*' => 'string',
'tag_categories' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_id', 'name'])) {
$fail("You can not have both 'external_id' and 'name' arrays specified in tag categories filter");
}
if (!array_key_exists('external_id', $value) && !array_key_exists('name', $value)) {
$fail("You have to specify either 'external_id' or 'name' array in tag categories filter");
}
}],
'tag_categories.external_id' => 'array',
'tag_categories.external_id.*' => 'string',
'tag_categories.name' => 'array',
'tag_categories.name.*' => 'string',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/Api/v2/TopTagsSearchRequest.php | Beam/extensions/beam-module/src/Http/Requests/Api/v2/TopTagsSearchRequest.php | <?php
namespace Remp\BeamModule\Http\Requests\Api\v2;
use Illuminate\Support\Arr;
use Illuminate\Foundation\Http\FormRequest;
class TopTagsSearchRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'from' => 'required|date',
'limit' => 'required|integer',
'sections.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in sections filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in sections filter");
}
}],
'sections.*.external_ids' => 'array',
'sections.*.external_ids.*' => 'string',
'sections.*.names' => 'array',
'sections.*.names.*' => 'string',
'authors.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in authors filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in authors filter");
}
}],
'authors.*.external_ids' => 'array',
'authors.*.external_ids.*' => 'string',
'authors.*.names' => 'array',
'authors.*.names.*' => 'string',
'content_type' => 'string',
'tag_categories.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in tag categories filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in tag categories filter");
}
}],
'tag_categories.*.external_ids' => 'array',
'tag_categories.*.external_ids.*' => 'string',
'tag_categories.*.names' => 'array',
'tag_categories.*.names.*' => 'string',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/Api/v2/ArticleUpsertRequest.php | Beam/extensions/beam-module/src/Http/Requests/Api/v2/ArticleUpsertRequest.php | <?php
namespace Remp\BeamModule\Http\Requests\Api\v2;
use Illuminate\Foundation\Http\FormRequest;
class ArticleUpsertRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'articles.*.external_id' => "required|string",
'articles.*.property_uuid' => "required|string|exists:properties,uuid",
'articles.*.title' => "required|string",
'articles.*.url' => "required|url",
'articles.*.image_url' => 'nullable|url',
'articles.*.published_at' => 'required|date',
'articles.*.titles.*' => 'nullable|string',
'articles.*.content_type' => 'string',
// authors
'articles.*.authors' => 'array',
'articles.*.authors.*' => 'array',
'articles.*.authors.*.external_id' => 'required|string',
'articles.*.authors.*.name' => 'required|string',
// sections
'articles.*.sections' => 'array',
'articles.*.sections.*' => 'array',
'articles.*.sections.*.external_id' => 'required|string',
'articles.*.sections.*.name' => 'required|string',
// tags
'articles.*.tags' => 'array',
'articles.*.tags.*' => 'array',
'articles.*.tags.*.external_id' => 'required|string',
'articles.*.tags.*.name' => 'required|string',
'articles.*.tags.*.categories' => 'array',
'articles.*.tags.*.categories.*' => 'array',
'articles.*.tags.*.categories.*.external_id' => 'required|string',
'articles.*.tags.*.categories.*.name' => 'required|string',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/Api/v2/TopArticlesSearchRequest.php | Beam/extensions/beam-module/src/Http/Requests/Api/v2/TopArticlesSearchRequest.php | <?php
namespace Remp\BeamModule\Http\Requests\Api\v2;
use Illuminate\Support\Arr;
use Illuminate\Foundation\Http\FormRequest;
class TopArticlesSearchRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'from' => 'required|date',
'limit' => 'required|integer',
'sections.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in sections filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in sections filter");
}
}],
'sections.*.external_ids' => 'array',
'sections.*.external_ids.*' => 'string',
'sections.*.names' => 'array',
'sections.*.names.*' => 'string',
'authors.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in authors filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in authors filter");
}
}],
'authors.*.external_ids' => 'array',
'authors.*.external_ids.*' => 'string',
'authors.*.names' => 'array',
'authors.*.names.*' => 'string',
'content_type' => 'string',
'tags.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in tags filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in tags filter");
}
}],
'tags.*.external_ids' => 'array',
'tags.*.external_ids.*' => 'string',
'tags.*.names' => 'array',
'tags.*.names.*' => 'string',
'tag_categories.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in tag categories filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in tag categories filter");
}
}],
'tag_categories.*.external_ids' => 'array',
'tag_categories.*.external_ids.*' => 'string',
'tag_categories.*.names' => 'array',
'tag_categories.*.names.*' => 'string',
'published_from' => 'date',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Requests/Api/v2/TopAuthorsSearchRequest.php | Beam/extensions/beam-module/src/Http/Requests/Api/v2/TopAuthorsSearchRequest.php | <?php
namespace Remp\BeamModule\Http\Requests\Api\v2;
use Illuminate\Support\Arr;
use Illuminate\Foundation\Http\FormRequest;
class TopAuthorsSearchRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'from' => 'required|date',
'limit' => 'required|integer',
'sections.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in sections filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in sections filter");
}
}],
'sections.*.external_ids' => 'array',
'sections.*.external_ids.*' => 'string',
'sections.*.names' => 'array',
'sections.*.names.*' => 'string',
'content_type' => 'string',
'tags.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in tags filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in tags filter");
}
}],
'tags.*.external_ids' => 'array',
'tags.*.external_ids.*' => 'string',
'tags.*.names' => 'array',
'tags.*.names.*' => 'string',
'tag_categories.*' => ['array', function ($attr, $value, $fail) {
if (Arr::has($value, ['external_ids', 'names'])) {
$fail("You can not have both 'external_ids' and 'names' arrays specified in tag categories filter");
}
if (!array_key_exists('external_ids', $value) && !array_key_exists('names', $value)) {
$fail("You have to specify either 'external_ids' or 'names' array in tag categories filter");
}
}],
'tag_categories.*.external_ids' => 'array',
'tag_categories.*.external_ids.*' => 'string',
'tag_categories.*.names' => 'array',
'tag_categories.*.names.*' => 'string',
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/AuthorSegmentsController.php | Beam/extensions/beam-module/src/Http/Controllers/AuthorSegmentsController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Remp\BeamModule\Console\Commands\ComputeAuthorsSegments;
use Remp\BeamModule\Http\Requests\AuthorSegmentsTestRequest;
use Remp\BeamModule\Model\Config\ConfigCategory;
use Remp\BeamModule\Model\Segment;
use Remp\BeamModule\Model\SegmentGroup;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\DataTables;
class AuthorSegmentsController extends Controller
{
public function index()
{
return view('beam::authors.segments.index', [
'authorSegmentsSettingsUrl' => ConfigCategory::getSettingsTabUrl(ConfigCategory::CODE_AUTHOR_SEGMENTS)
]);
}
public function json(Request $request, Datatables $datatables)
{
$columns = ['id', 'name', 'code', 'created_at',
DB::raw('(SELECT COUNT(*) FROM segment_users WHERE segment_users.segment_id=segments.id) as users_count'),
DB::raw('(SELECT COUNT(*) FROM segment_browsers WHERE segment_browsers.segment_id=segments.id) as browsers_count'),
];
$segments = Segment::select($columns)
->where('segment_group_id', SegmentGroup::getByCode(SegmentGroup::CODE_AUTHORS_SEGMENTS)->id);
return $datatables->of($segments)
->make(true);
}
public function testingConfiguration()
{
return view('beam::authors.segments.configuration');
}
public function validateTest(AuthorSegmentsTestRequest $request)
{
return response()->json();
}
public function compute(AuthorSegmentsTestRequest $request)
{
$email = $request->get('email');
Artisan::queue(ComputeAuthorsSegments::COMMAND, [
'--email' => $email,
'--history' => (int) $request->get('history'),
'--min_views' => $request->get('min_views'),
'--min_average_timespent' => $request->get('min_average_timespent'),
'--min_ratio' => $request->get('min_ratio'),
]);
return view('beam::authors.segments.compute', compact('email'));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/AuthorController.php | Beam/extensions/beam-module/src/Http/Controllers/AuthorController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\ArticleAuthor;
use Remp\BeamModule\Model\ArticlesDataTable;
use Remp\BeamModule\Model\Author;
use Remp\BeamModule\Model\Conversion;
use Remp\BeamModule\Http\Resources\AuthorResource;
use Remp\BeamModule\Model\Rules\ValidCarbonDate;
use Remp\BeamModule\Model\Tag;
use Remp\BeamModule\Model\Section;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\DataTables;
use Html;
use Yajra\DataTables\QueryDataTable;
class AuthorController extends Controller
{
public function index(Request $request)
{
return response()->format([
'html' => view('beam::authors.index', [
'authors' => Author::query()->pluck('name', 'id'),
'publishedFrom' => $request->input('published_from', 'today - 30 days'),
'publishedTo' => $request->input('published_to', 'now'),
'conversionFrom' => $request->input('conversion_from', 'today - 30 days'),
'conversionTo' => $request->input('conversion_to', 'now'),
'contentTypes' => array_merge(
['all'],
Article::groupBy('content_type')->pluck('content_type')->toArray()
),
'contentType' => $request->input('content_type', 'all'),
]),
'json' => AuthorResource::collection(Author::paginate($request->get('per_page', 15)))->preserveQuery(),
]);
}
public function show(Author $author, Request $request)
{
return response()->format([
'html' => view('beam::authors.show', [
'author' => $author,
'contentTypes' => Article::groupBy('content_type')->pluck('content_type', 'content_type'),
'sections' => Section::query()->pluck('name', 'id'),
'tags' => Tag::query()->pluck('name', 'id'),
'authors' => Author::query()->pluck('name', 'id'),
'publishedFrom' => $request->input('published_from', 'today - 30 days'),
'publishedTo' => $request->input('published_to', 'now'),
'conversionFrom' => $request->input('conversion_from', 'today - 30 days'),
'conversionTo' => $request->input('conversion_to', 'now'),
]),
'json' => new AuthorResource($author),
]);
}
public function dtAuthors(Request $request, Datatables $datatables)
{
$request->validate([
'published_from' => ['sometimes', new ValidCarbonDate],
'published_to' => ['sometimes', new ValidCarbonDate],
'conversion_from' => ['sometimes', new ValidCarbonDate],
'conversion_to' => ['sometimes', new ValidCarbonDate],
]);
$cols = [
'authors.id',
'authors.name',
'COALESCE(articles_count, 0) AS articles_count',
'COALESCE(conversions_count, 0) AS conversions_count',
'COALESCE(conversions_amount, 0) AS conversions_amount',
'COALESCE(pageviews_all, 0) AS pageviews_all',
'COALESCE(pageviews_signed_in, 0) AS pageviews_signed_in',
'COALESCE(pageviews_subscribers, 0) AS pageviews_subscribers',
'COALESCE(timespent_all, 0) AS timespent_all',
'COALESCE(timespent_signed_in, 0) AS timespent_signed_in',
'COALESCE(timespent_subscribers, 0) AS timespent_subscribers',
'COALESCE(timespent_all / pageviews_all, 0) AS avg_timespent_all',
'COALESCE(timespent_signed_in / pageviews_signed_in, 0) AS avg_timespent_signed_in',
'COALESCE(timespent_subscribers / pageviews_subscribers, 0) AS avg_timespent_subscribers',
];
$conversionsQuery = Conversion::selectRaw(implode(',', [
'author_id',
'count(distinct conversions.id) as conversions_count',
'sum(conversions.amount) as conversions_amount',
]))
->leftJoin('article_author', 'conversions.article_id', '=', 'article_author.article_id')
->leftJoin('articles', 'article_author.article_id', '=', 'articles.id')
->ofSelectedProperty()
->groupBy('author_id');
$pageviewsQuery = Article::selectRaw(implode(',', [
'author_id',
'COALESCE(SUM(pageviews_all), 0) AS pageviews_all',
'COALESCE(SUM(pageviews_signed_in), 0) AS pageviews_signed_in',
'COALESCE(SUM(pageviews_subscribers), 0) AS pageviews_subscribers',
'COALESCE(SUM(timespent_all), 0) AS timespent_all',
'COALESCE(SUM(timespent_signed_in), 0) AS timespent_signed_in',
'COALESCE(SUM(timespent_subscribers), 0) AS timespent_subscribers',
'COUNT(*) as articles_count'
]))
->leftJoin('article_author', 'articles.id', '=', 'article_author.article_id')
->ofSelectedProperty()
->groupBy('author_id');
if ($request->input('published_from')) {
$publishedFrom = Carbon::parse($request->input('published_from'), $request->input('tz'));
$conversionsQuery->where('published_at', '>=', $publishedFrom);
$pageviewsQuery->where('published_at', '>=', $publishedFrom);
}
if ($request->input('published_to')) {
$publishedTo = Carbon::parse($request->input('published_to'), $request->input('tz'));
$conversionsQuery->where('published_at', '<=', $publishedTo);
$pageviewsQuery->where('published_at', '<=', $publishedTo);
}
if ($request->input('conversion_from')) {
$conversionFrom = Carbon::parse($request->input('conversion_from'), $request->input('tz'));
$conversionsQuery->where('paid_at', '>=', $conversionFrom);
}
if ($request->input('conversion_to')) {
$conversionTo = Carbon::parse($request->input('conversion_to'), $request->input('tz'));
$conversionsQuery->where('paid_at', '<=', $conversionTo);
}
if ($request->input('content_type') && $request->input('content_type') !== 'all') {
$conversionsQuery->where('content_type', '=', $request->input('content_type'));
$pageviewsQuery->where('content_type', '=', $request->input('content_type'));
}
$authors = Author::selectRaw(implode(",", $cols))
->leftJoin(DB::raw("({$conversionsQuery->toSql()}) as c"), 'authors.id', '=', 'c.author_id')->addBinding($conversionsQuery->getBindings())
->leftJoin(DB::raw("({$pageviewsQuery->toSql()}) as pv"), 'authors.id', '=', 'pv.author_id')->addBinding($pageviewsQuery->getBindings())
// has to be below manually added bindings
->ofSelectedProperty()
->groupBy(['authors.name', 'authors.id', 'articles_count', 'conversions_count', 'conversions_amount', 'pageviews_all',
'pageviews_signed_in', 'pageviews_subscribers', 'timespent_all', 'timespent_signed_in', 'timespent_subscribers']);
$conversionsQuery = Conversion::selectRaw('count(distinct conversions.id) as count, sum(amount) as sum, currency, article_author.author_id')
->join('article_author', 'conversions.article_id', '=', 'article_author.article_id')
->join('articles', 'article_author.article_id', '=', 'articles.id')
->ofSelectedProperty()
->groupBy(['article_author.author_id', 'conversions.currency']);
if ($request->input('published_from')) {
$conversionsQuery->where('published_at', '>=', Carbon::parse($request->input('published_from'), $request->input('tz')));
}
if ($request->input('published_to')) {
$conversionsQuery->where('published_at', '<=', Carbon::parse($request->input('published_to'), $request->input('tz')));
}
if ($request->input('conversion_from')) {
$conversionFrom = Carbon::parse($request->input('conversion_from'), $request->input('tz'));
$conversionsQuery->where('paid_at', '>=', $conversionFrom);
}
if ($request->input('conversion_to')) {
$conversionTo = Carbon::parse($request->input('conversion_to'), $request->input('tz'));
$conversionsQuery->where('paid_at', '<=', $conversionTo);
}
if ($request->input('content_type') && $request->input('content_type') !== 'all') {
$conversionsQuery->where('content_type', '=', $request->input('content_type'));
}
$conversionAmounts = [];
$conversionCounts = [];
foreach ($conversionsQuery->get() as $record) {
$conversionAmounts[$record['author_id']][$record->currency] = $record['sum'];
if (!isset($conversionCounts[$record['author_id']])) {
$conversionCounts[$record['author_id']] = 0;
}
$conversionCounts[$record['author_id']] += $record['count'];
}
/** @var QueryDataTable $datatable */
$datatable = $datatables->of($authors);
return $datatable
->addColumn('id', function (Author $author) {
return $author->id;
})
->addColumn('name', function (Author $author) {
return [
'url' => route('authors.show', ['author' => $author]),
'text' => $author->name,
];
})
->filterColumn('name', function (Builder $query, $value) use ($request) {
if ($request->input('search')['value'] === $value) {
$query->where(function (Builder $query) use ($value) {
$query->where('authors.name', 'like', '%' . $value . '%');
});
} else {
$authorIds = explode(',', $value);
$query->where(function (Builder $query) use ($authorIds) {
$query->whereIn('authors.id', $authorIds);
});
}
})
->addColumn('conversions_count', function (Author $author) use ($conversionCounts) {
return $conversionCounts[$author->id] ?? 0;
})
->addColumn('conversions_amount', function (Author $author) use ($conversionAmounts) {
if (!isset($conversionAmounts[$author->id])) {
return 0;
}
$amounts = [];
foreach ($conversionAmounts[$author->id] as $currency => $c) {
$c = round($c, 2);
$amounts[] = "{$c} {$currency}";
}
return $amounts ?: [0];
})
->orderColumn('articles_count', 'articles_count $1')
->orderColumn('conversions_count', 'conversions_count $1')
->orderColumn('conversions_amount', 'conversions_amount $1')
->orderColumn('pageviews_all', 'pageviews_all $1')
->orderColumn('pageviews_signed_in', 'pageviews_signed_in $1')
->orderColumn('pageviews_subscribers', 'pageviews_subscribers $1')
->orderColumn('avg_timespent_all', 'avg_timespent_all $1')
->orderColumn('avg_timespent_signed_in', 'avg_timespent_signed_in $1')
->orderColumn('avg_timespent_subscribers', 'avg_timespent_subscribers $1')
->orderColumn('id', 'authors.id $1')
->setTotalRecords(PHP_INT_MAX)
->setFilteredRecords(PHP_INT_MAX)
->make(true);
}
public function dtArticles(Author $author, Request $request, DataTables $datatables, ArticlesDataTable $articlesDataTable)
{
$articlesDataTable->setAuthor($author);
return $articlesDataTable->getDataTable($request, $datatables);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/JournalProxyController.php | Beam/extensions/beam-module/src/Http/Controllers/JournalProxyController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use Illuminate\Http\Request;
use Remp\Journal\JournalException;
class JournalProxyController extends Controller
{
private $journalClient;
public function __construct(Client $journalClient)
{
$this->journalClient = $journalClient;
}
public function pageviewsProgressCount(Request $request)
{
return $this->proxyCall($request, '/journal/pageviews/actions/progress/count');
}
public function pageviewsUniqueBrowsersCount(Request $request)
{
return $this->proxyCall($request, '/journal/pageviews/actions/load/unique/browsers');
}
public function commercePurchaseCount(Request $request)
{
return $this->proxyCall($request, '/journal/commerce/steps/purchase/count');
}
private function proxyCall(Request $request, string $journalUri)
{
$requestJson = $request->json()->all();
try {
$segmentsResponse = $this->journalClient->post($journalUri, [
'json' => $requestJson
]);
} catch (ConnectException $e) {
throw new JournalException("Could not connect to Journal $journalUri endpoint: {$e->getMessage()}");
}
return response()->json(json_decode($segmentsResponse->getBody()));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/ConversionController.php | Beam/extensions/beam-module/src/Http/Controllers/ConversionController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Remp\BeamModule\Http\Requests\ConversionRequest;
use Remp\BeamModule\Http\Requests\ConversionUpsertRequest;
use Remp\BeamModule\Http\Resources\ConversionResource;
use Remp\BeamModule\Jobs\ProcessConversionJob;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Author;
use Remp\BeamModule\Model\Conversion;
use Remp\BeamModule\Model\ConversionCommerceEvent;
use Remp\BeamModule\Model\ConversionGeneralEvent;
use Remp\BeamModule\Model\ConversionPageviewEvent;
use Remp\BeamModule\Model\Rules\ValidCarbonDate;
use Remp\BeamModule\Model\Section;
use Remp\BeamModule\Model\Tag;
use Yajra\DataTables\DataTables;
use Yajra\DataTables\QueryDataTable;
class ConversionController extends Controller
{
public function index(Request $request)
{
$conversions = Conversion::select('conversions.*')
->join('articles', 'articles.id', '=', 'conversions.article_id');
$conversionFrom = $request->get('conversion_from');
if ($conversionFrom) {
$conversions = $conversions->where('paid_at', '>=', Carbon::parse($conversionFrom));
}
$conversionTo = $request->get('conversion_to');
if ($conversionTo) {
$conversions = $conversions->where('paid_at', '<=', Carbon::parse($conversionTo));
}
$articlePublishedFrom = $request->get('article_published_from');
if ($articlePublishedFrom) {
$conversions = $conversions->where('articles.published_at', '>=', Carbon::parse($articlePublishedFrom));
}
$articlePublishedTo = $request->get('article_published_to');
if ($articlePublishedTo) {
$conversions = $conversions->where('articles.published_at', '<=', Carbon::parse($articlePublishedTo));
}
$articleContentType = $request->get('article_content_type');
if ($articleContentType) {
$conversions = $conversions->where('articles.content_type', '=', $articleContentType);
}
return response()->format([
'html' => view('beam::conversions.index', [
'contentTypes' => Article::groupBy('content_type')->pluck('content_type', 'content_type'),
'authors' => Author::query()->pluck('name', 'id'),
'sections' => Section::query()->pluck('name', 'id'),
'tags' => Tag::query()->pluck('name', 'id'),
'conversionFrom' => $request->get('conversion_from', 'today - 30 days'),
'conversionTo' => $request->get('conversion_to', 'now'),
]),
'json' => ConversionResource::collection($conversions->paginate($request->get('per_page', 15)))->preserveQuery(),
]);
}
public function json(Request $request, Datatables $datatables)
{
$request->validate([
'conversion_from' => ['sometimes', new ValidCarbonDate],
'conversion_to' => ['sometimes', new ValidCarbonDate],
'article_published_from' => ['sometimes', new ValidCarbonDate],
'article_published_to' => ['sometimes', new ValidCarbonDate],
]);
$conversions = Conversion::select('conversions.*', 'articles.content_type')
->with(['article', 'article.authors', 'article.sections', 'article.tags'])
->ofSelectedProperty()
->join('articles', 'articles.id', '=', 'conversions.article_id');
if ($request->input('conversion_from')) {
$conversions->where('paid_at', '>=', Carbon::parse($request->input('conversion_from'), $request->input('tz')));
}
if ($request->input('conversion_to')) {
$conversions->where('paid_at', '<=', Carbon::parse($request->input('conversion_to'), $request->input('tz')));
}
if ($request->input('article_published_from')) {
$conversions->where('articles.published_at', '>=', Carbon::parse($request->input('article_published_from'), $request->input('tz')));
}
if ($request->input('article_published_to')) {
$conversions->where('articles.published_at', '<=', Carbon::parse($request->input('article_published_to'), $request->input('tz')));
}
/** @var QueryDataTable $datatable */
$datatable = $datatables->of($conversions);
return $datatable
->addColumn('id', function (Conversion $conversion) {
return $conversion->id;
})
->addColumn('actions', function (Conversion $conversion) {
return [
'show' => route('conversions.show', $conversion),
];
})
->addColumn('article.title', function (Conversion $conversion) {
return [
'url' => route('articles.show', $conversion->article->id),
'text' => $conversion->article->title,
];
})
->filterColumn('article.title', function (Builder $query, $value) {
$query->where('articles.title', 'like', '%' . $value . '%');
})
->filterColumn('content_type', function (Builder $query, $value) {
$values = explode(',', $value);
$query->whereIn('articles.content_type', $values);
})
->filterColumn('article.authors[, ].name', function (Builder $query, $value) {
$values = explode(",", $value);
$filterQuery = \DB::table('articles')
->select(['articles.id'])
->join('article_author', 'articles.id', '=', 'article_author.article_id', 'left')
->whereIn('article_author.author_id', $values);
$query->whereIn('articles.id', $filterQuery);
})
->filterColumn('article.sections[, ].name', function (Builder $query, $value) {
$values = explode(",", $value);
$filterQuery = \DB::table('articles')
->select(['articles.id'])
->join('article_section', 'articles.id', '=', 'article_section.article_id', 'left')
->whereIn('article_section.section_id', $values);
$query->whereIn('articles.id', $filterQuery);
})
->filterColumn('article.tags[, ].name', function (Builder $query, $value) {
$values = explode(",", $value);
$filterQuery = \DB::table('articles')
->select(['articles.id'])
->join('article_tag', 'articles.id', '=', 'article_tag.article_id', 'left')
->whereIn('article_tag.tag_id', $values);
$query->whereIn('articles.id', $filterQuery);
})
->orderColumn('id', 'conversions.id $1')
->rawColumns(['actions'])
->make(true);
}
public function store(ConversionRequest $request)
{
$conversion = new Conversion();
$conversion->fill($request->all());
$conversion->save();
return response()->format([
'html' => redirect(route('conversions.index'))->with('success', 'Conversion created'),
'json' => new ConversionResource($conversion),
]);
}
private function eventsPriorConversion(Conversion $conversion, $daysInPast): array
{
$from = (clone $conversion->paid_at)->subDays($daysInPast);
$events = [];
/** @var ConversionPageviewEvent $event */
foreach ($conversion->pageviewEvents()->where('time', '>=', $from)->get() as $event) {
$obj = new \stdClass();
$obj->name = 'pageview';
$obj->time = $event->time;
$obj->tags = [];
if ($event->article) {
$obj->tags[] = (object) [
'title' => $event->article->title,
'href' => route('articles.show', ['article' => $event->article->id]),
];
$obj->tags[] = (object) [
'title' => $event->locked ? 'Locked' : 'Unlocked',
];
if ($event->timespent) {
$obj->tags[] = (object) [
'title' => "Timespent: {$event->timespent} s",
];
}
}
$obj->tags[] = (object) [
'title' => $event->signed_in ? 'Signed in' : 'Anonymous',
];
$events[$event->time->toDateTimeString()] = $obj;
}
/** @var ConversionCommerceEvent $event */
foreach ($conversion->commerceEvents()->where('time', '>=', $from)->get() as $event) {
$obj = new \stdClass();
$obj->name = "commerce:$event->step";
$obj->time = $event->time;
$obj->tags[] = (object) [
'title' => "Funnel: {$event->funnel_id}",
];
if ($event->amount) {
$obj->tags[] = (object) [
'title' => "Amount: {$event->amount} {$event->currency}",
];
}
$events[$event->time->toDateTimeString()] = $obj;
}
/** @var ConversionGeneralEvent $event */
foreach ($conversion->generalEvents()->where('time', '>=', $from)->get() as $event) {
$obj = new \stdClass();
$obj->name = "{$event->action}:{$event->category}";
$obj->time = $event->time;
$obj->tags = [];
$events[$event->time->toDateTimeString()] = $obj;
}
krsort($events);
return $events;
}
public function show(Conversion $conversion)
{
$events = $this->eventsPriorConversion($conversion, 10);
return response()->format([
'html' => view('beam::conversions.show', [
'conversion' => $conversion,
'events' => $events
]),
'json' => new ConversionResource($conversion),
]);
}
public function upsert(ConversionUpsertRequest $request)
{
Log::info('Upserting conversions', ['params' => $request->json()->all()]);
$conversions = [];
foreach ($request->get('conversions', []) as $c) {
// When saving to DB, Eloquent strips timezone information,
// therefore convert to UTC
$c['paid_at'] = Carbon::parse($c['paid_at']);
$conversion = Conversion::firstOrNew([
'transaction_id' => $c['transaction_id'],
]);
$conversion->fill($c);
$conversion->save();
$conversions[] = $conversion;
if (!$conversion->events_aggregated) {
ProcessConversionJob::dispatch($conversion);
}
}
return response()->format([
'html' => redirect(route('conversions.index'))->with('success', 'Conversions created'),
'json' => ConversionResource::collection(collect($conversions)),
]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/AccountController.php | Beam/extensions/beam-module/src/Http/Controllers/AccountController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Illuminate\Http\Request;
use Ramsey\Uuid\Uuid;
use Remp\BeamModule\Model\Account;
use Yajra\DataTables\DataTables;
class AccountController extends Controller
{
public function index()
{
return view('beam::accounts.index');
}
public function json(Request $request, Datatables $datatables)
{
$columns = ['id', 'name', 'created_at'];
$accounts = Account::select($columns);
return $datatables->of($accounts)
->addColumn('actions', function (Account $account) {
return [
'edit' => route('accounts.edit', $account),
];
})
->addColumn('name', function (Account $account) {
return [
'url' => route('accounts.edit', ['account' => $account]),
'text' => $account->name,
];
})
->rawColumns(['actions'])
->make(true);
}
public function create()
{
return view('beam::accounts.create', [
'account' => new Account,
]);
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$this->validate($request, [
'name' => 'bail|required|unique:accounts|max:255',
]);
$account = new Account();
$account->fill($request->all());
$account->uuid = Uuid::uuid4();
$account->save();
return response()->format([
'html' => $this->getRouteBasedOnAction(
$request->get('action'),
[
self::FORM_ACTION_SAVE_CLOSE => 'accounts.index',
self::FORM_ACTION_SAVE => 'accounts.edit',
],
$account
)->with('success', sprintf('Account [%s] was created', $account->name)),
]);
}
public function show(Account $account)
{
//
}
public function edit(Account $account)
{
return view('beam::accounts.edit', [
'account' => $account,
]);
}
public function update(Request $request, Account $account)
{
$this->validate($request, [
'name' => 'bail|required|unique:accounts|max:255',
]);
$account->fill($request->all());
$account->save();
return response()->format([
'html' => $this->getRouteBasedOnAction(
$request->get('action'),
[
self::FORM_ACTION_SAVE_CLOSE => 'accounts.index',
self::FORM_ACTION_SAVE => 'accounts.edit',
],
$account
)->with('success', sprintf('Account [%s] was updated', $account->name)),
]);
}
public function destroy(Account $account)
{
$account->delete();
return redirect(route('accounts.properties.index', $account))->with('success', 'Account removed');
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/Controller.php | Beam/extensions/beam-module/src/Http/Controllers/Controller.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
const FORM_ACTION_SAVE_CLOSE = 'save_close';
const FORM_ACTION_SAVE = 'save';
/**
* Decide where to redirect based on form action.
*
* Array $formActionRoutes should contain at least route for FORM_ACTION_SAVE action. Format:
*
* [
* self::FORM_ACTION_SAVE_CLOSE => 'resource.index',
* self::FORM_ACTION_SAVE => 'resource.edit',
* ]
*
* @param string $action
* @param array $formActionRoutes
* @return \Illuminate\Routing\Redirector|\Illuminate\Http\RedirectResponse
*/
protected function getRouteBasedOnAction(string $action, array $formActionRoutes, $resource)
{
// FORM_ACTION_SAVE must be set, it's default action
// if it's not, redirect back to previous view
if (!isset($formActionRoutes[self::FORM_ACTION_SAVE])) {
return redirect()->back();
}
// if action wasn't provided with actions routes, use default action (FORM_ACTION_SAVE)
if (!isset($formActionRoutes[$action])) {
$action = self::FORM_ACTION_SAVE;
}
return redirect()->route($formActionRoutes[$action], $resource);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/SectionSegmentsController.php | Beam/extensions/beam-module/src/Http/Controllers/SectionSegmentsController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Remp\BeamModule\Console\Commands\ComputeSectionSegments;
use Remp\BeamModule\Http\Requests\SectionSegmentsTestRequest;
use Remp\BeamModule\Model\Config\ConfigCategory;
use Remp\BeamModule\Model\Segment;
use Remp\BeamModule\Model\SegmentGroup;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\DataTables;
class SectionSegmentsController extends Controller
{
public function index()
{
return view('beam::sections.segments.index', [
'sectionSegmentsSettingsUrl' => ConfigCategory::getSettingsTabUrl(ConfigCategory::CODE_SECTION_SEGMENTS)
]);
}
public function json(Request $request, Datatables $datatables)
{
$columns = ['id', 'name', 'code', 'created_at',
DB::raw('(SELECT COUNT(*) FROM segment_users WHERE segment_users.segment_id=segments.id) as users_count'),
DB::raw('(SELECT COUNT(*) FROM segment_browsers WHERE segment_browsers.segment_id=segments.id) as browsers_count'),
];
$segments = Segment::select($columns)
->where('segment_group_id', SegmentGroup::getByCode(SegmentGroup::CODE_SECTIONS_SEGMENTS)->id);
return $datatables->of($segments)
->make(true);
}
public function testingConfiguration()
{
return view('beam::sections.segments.configuration');
}
public function validateTest(SectionSegmentsTestRequest $request)
{
return response()->json();
}
public function compute(SectionSegmentsTestRequest $request)
{
$email = $request->get('email');
Artisan::queue(ComputeSectionSegments::COMMAND, [
'--email' => $email,
'--history' => (int) $request->get('history'),
'--min_views' => $request->get('min_views'),
'--min_average_timespent' => $request->get('min_average_timespent'),
'--min_ratio' => $request->get('min_ratio'),
]);
return view('beam::sections.segments.compute', compact('email'));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/NewsletterController.php | Beam/extensions/beam-module/src/Http/Controllers/NewsletterController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Remp\BeamModule\Contracts\Mailer\MailerContract;
use Remp\BeamModule\Http\Requests\NewsletterRequest;
use Remp\BeamModule\Http\Resources\NewsletterResource;
use Remp\BeamModule\Model\Newsletter;
use Remp\LaravelHelpers\Resources\JsonResource;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Yajra\DataTables\DataTables;
class NewsletterController extends Controller
{
private $mailer;
public function __construct(MailerContract $mailer)
{
$this->mailer = $mailer;
}
public function json(Request $request, Datatables $datatables)
{
$columns = ['id', 'name', 'segment', 'state', 'mailer_generator_id', 'created_at', 'updated_at', 'starts_at'];
$newsletters = Newsletter::select($columns);
return $datatables->of($newsletters)
->addColumn('newsletter', function (Newsletter $newsletter) {
return [
'url' => route('newsletters.edit', ['newsletter' => $newsletter]),
'text' => $newsletter->name,
];
})
->addColumn('action_methods', function (Newsletter $newsletter) {
return [
'start' => 'POST',
'pause' => 'POST',
'destroy' => 'DELETE',
];
})
->addColumn('actions', function (Newsletter $n) {
return [
'edit' => route('newsletters.edit', $n),
'start' => $n->isPaused() ? route('newsletters.start', $n) : null,
'pause' => $n->isStarted() ? route('newsletters.pause', $n) : null,
'destroy' => route('newsletters.destroy', $n),
];
})
->rawColumns(['actions', 'action_methods', 'newsletter'])
->make(true);
}
public function validateForm(NewsletterRequest $request)
{
return response()->json(false);
}
public function index()
{
return response()->format([
'html' => view('beam::newsletters.index'),
'json' => NewsletterResource::collection(Newsletter::paginate()),
]);
}
public function create()
{
$segments = $this->loadSegments();
$generators = $this->loadGenerators();
$criteria = $this->loadCriteria();
$mailTypes = $this->loadMailTypes();
$newsletter = new Newsletter();
$newsletter->starts_at = Carbon::now()->addHour();
$newsletter->articles_count = 1;
$newsletter->personalized_content = false;
if ($generators->isEmpty()) {
flash('No source templates using best_performing_articles generator were configured on Mailer', 'danger');
}
if ($mailTypes->isEmpty()) {
flash('No mail types are available on Mailer, please configure them first', 'danger');
}
if (empty($segments)) {
flash('No segments are available on Mailer, please configure them first', 'danger');
}
return response()->format([
'html' => view(
'beam::newsletters.create',
compact(['newsletter', 'segments', 'generators', 'criteria', 'mailTypes'])
),
'json' => [],
]);
}
public function edit($id)
{
$newsletter = Newsletter::find($id);
$segments = $this->loadSegments();
$generators = $this->loadGenerators();
$criteria = $this->loadCriteria();
$mailTypes = $this->loadMailTypes();
return response()->format([
'html' => view(
'beam::newsletters.edit',
compact(['newsletter', 'segments', 'generators', 'criteria', 'mailTypes'])
),
'json' => [],
]);
}
public function destroy(Newsletter $newsletter)
{
$newsletter->delete();
return response()->format([
'html' => redirect(route('newsletters.index'))->with('success', sprintf(
"Newsletter [%s] was removed",
$newsletter->name
)),
'json' => new NewsletterResource([]),
]);
}
private function loadCriteria()
{
return Newsletter\NewsletterCriterionEnum::getFriendlyList();
}
private function loadGenerators()
{
return $this->mailer->generatorTemplates('best_performing_articles')
->mapWithKeys(function ($item) {
return [$item->id => $item->title];
});
}
private function loadSegments()
{
return $this->mailer->segments()->mapToGroups(function ($item) {
return [$item->provider => [$item->provider . '::' . $item->code => $item->name]];
})->mapWithKeys(function ($item, $key) {
return [$key => $item->collapse()];
})->toArray();
}
private function loadMailTypes()
{
return $this->mailer->mailTypes()
->mapWithKeys(function ($item) {
return [$item->code => $item->title];
});
}
public function store(NewsletterRequest $request)
{
$newsletter = new Newsletter();
$newsletter->fill($request->all());
$newsletter->state = Newsletter::STATE_PAUSED;
$newsletter->save();
return response()->format([
'html' => $this->getRouteBasedOnAction(
$request->get('action'),
[
self::FORM_ACTION_SAVE_CLOSE => 'newsletters.index',
self::FORM_ACTION_SAVE => 'newsletters.edit',
],
$newsletter
)->with('success', sprintf('Newsletter [%s] was created', $newsletter->name)),
'json' => new NewsletterResource($newsletter)
]);
}
public function update(NewsletterRequest $request, Newsletter $newsletter)
{
$newsletter->fill($request->all());
$newsletter->personalized_content = $request->input('personalized_content', false);
$newsletter->save();
return response()->format([
'html' => $this->getRouteBasedOnAction(
$request->get('action'),
[
self::FORM_ACTION_SAVE_CLOSE => 'newsletters.index',
self::FORM_ACTION_SAVE => 'newsletters.edit',
],
$newsletter
)->with('success', sprintf('Newsletter [%s] was updated', $newsletter->name)),
'json' => new NewsletterResource($newsletter)
]);
}
public function start(Newsletter $newsletter)
{
if ($newsletter->isFinished()) {
return response()->format([
'html' => redirect(route('newsletters.index'))->with('success', sprintf(
'Newsletter [%s] was already finished, cannot start it again.',
$newsletter->name
)),
'json' => new JsonResource(new BadRequestHttpException('cannot start already finished newsletter')),
]);
}
$newsletter->state = Newsletter::STATE_STARTED;
$newsletter->save();
return response()->format([
'html' => redirect(route('newsletters.index'))->with('success', sprintf(
'Newsletter [%s] was started manually',
$newsletter->name
)),
'json' => new NewsletterResource([]),
]);
}
public function pause(Newsletter $newsletter)
{
if ($newsletter->isFinished()) {
return response()->format([
'html' => redirect(route('newsletters.index'))->with('success', sprintf(
'Newsletter [%s] was already finished, cannot be paused.',
$newsletter->name
)),
'json' => new JsonResource(new BadRequestHttpException('cannot pause already finished newsletter')),
]);
}
$newsletter->state = Newsletter::STATE_PAUSED;
$newsletter->save();
return response()->format([
'html' => redirect(route('newsletters.index'))->with('success', sprintf(
'Newsletter [%s] was paused manually',
$newsletter->name
)),
'json' => new NewsletterResource([]),
]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/UserPathController.php | Beam/extensions/beam-module/src/Http/Controllers/UserPathController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Remp\BeamModule\Http\Requests\ConversionsSankeyRequest;
use Remp\BeamModule\Http\Resources\ConversionsSankeyResource;
use Remp\BeamModule\Model\Author;
use Remp\BeamModule\Model\Charts\ConversionsSankeyDiagram;
use Remp\BeamModule\Model\Conversion;
use Remp\BeamModule\Model\ConversionCommerceEvent;
use Remp\BeamModule\Model\ConversionGeneralEvent;
use Remp\BeamModule\Model\ConversionPageviewEvent;
use Remp\BeamModule\Model\ConversionSource;
use Remp\BeamModule\Model\Section;
use Remp\Journal\JournalContract;
class UserPathController extends Controller
{
private $journal;
public function __construct(JournalContract $journal)
{
$this->journal = $journal;
}
public function index()
{
$authors = Author::all();
$sections = Section::all();
$sumCategories = Conversion::select('amount', 'currency')->groupBy('amount', 'currency')->get();
return view('beam::userpath.index', [
'authors' => $authors,
'sections' => $sections,
'days' => range(1, 14),
'sumCategories' => $sumCategories,
'conversionSourceTypes' => ConversionSource::getTypes()
]);
}
public function stats(Request $request)
{
$days = (int) $request->get('days');
$minutes = $days * 24 * 60;
$authors = $request->get('authors', []);
$sections = $request->get('sections', []);
$sums = $request->get('sums', []);
$conversionsQuery = Conversion::select('conversions.*')
->join('articles', 'articles.id', '=', 'conversions.article_id')
->join('article_author', 'articles.id', '=', 'article_author.article_id')
->join('article_section', 'articles.id', '=', 'article_section.article_id');
if ($authors) {
$conversionsQuery->whereIn('article_author.author_id', $authors);
}
if ($sections) {
$conversionsQuery->whereIn('article_section.section_id', $sections);
}
if ($sums) {
$conversionsQuery->where(function ($query) use ($sums) {
foreach ($sums as $sum) {
$query->orWhere(function ($query) use ($sum) {
[$amount, $currency] = explode('|', $sum, 2);
$query->where('conversions.amount', $amount);
$query->where('conversions.currency', $currency);
});
}
});
}
$lastActionsLimit = 5;
// commerce events
$commerceEventsQuery = ConversionCommerceEvent::where('minutes_to_conversion', '<=', $minutes)
->select('step', 'funnel_id', DB::raw('count(*) as group_count'))
->groupBy('step', 'funnel_id')
->orderByDesc('group_count');
$commerceLastEventsQuery = ConversionCommerceEvent::where('minutes_to_conversion', '<=', $minutes)
->select('step', DB::raw('count(*) as group_count'))
->groupBy('step')
->where('event_prior_conversion', '<=', $lastActionsLimit);
// pageview events
$pageviewEventsQuery = ConversionPageviewEvent::select(
'locked',
'signed_in',
DB::raw('count(*) as group_count'),
DB::raw('coalesce(avg(timespent), 0) as timespent_avg')
)
->where('minutes_to_conversion', '<=', $minutes)
->groupBy('locked', 'signed_in')
->orderByDesc('group_count');
$pageviewLastEventsQuery = ConversionPageviewEvent::where('minutes_to_conversion', '<=', $minutes)
->where('event_prior_conversion', '<=', $lastActionsLimit);
// general events
$generalEventsQuery = ConversionGeneralEvent::select('action', 'category', DB::raw('count(*) as group_count'))
->where('minutes_to_conversion', '<=', $minutes)
->groupBy('action', 'category')
->orderByDesc('group_count');
$generalLastEventsQuery = ConversionGeneralEvent::select('action', 'category', DB::raw('count(*) as group_count'))
->where('event_prior_conversion', '<=', $lastActionsLimit)
->where('minutes_to_conversion', '<=', $minutes)
->groupBy('action', 'category');
if ($authors || $sections || $sums) {
$commerceJoin = function ($join) {
$join->on('conversion_commerce_events.conversion_id', '=', 'c.id');
};
$pageviewJoin = function ($join) {
$join->on('conversion_pageview_events.conversion_id', '=', 'c.id');
};
$generalJoin = function ($join) {
$join->on('conversion_general_events.conversion_id', '=', 'c.id');
};
$commerceEventsQuery->joinSub($conversionsQuery, 'c', $commerceJoin);
$pageviewEventsQuery->joinSub($conversionsQuery, 'c', $pageviewJoin);
$generalEventsQuery->joinSub($conversionsQuery, 'c', $generalJoin);
$commerceLastEventsQuery->joinSub($conversionsQuery, 'c', $commerceJoin);
$pageviewLastEventsQuery->joinSub($conversionsQuery, 'c', $pageviewJoin);
$generalLastEventsQuery->joinSub($conversionsQuery, 'c', $generalJoin);
}
$total = $pageviewCount = $pageviewLastEventsQuery->count();
$absoluteCounts = [
['name' => 'pageview', 'count'=>$pageviewCount]
];
foreach ($generalLastEventsQuery->get() as $event) {
$absoluteCounts[] = [
'name' => $event->action . ':' . $event->category,
'count' => $event['group_count']
];
$total += $event['group_count'];
}
foreach ($commerceLastEventsQuery->get() as $event) {
$absoluteCounts[] = [
'name' => $event->step,
'count' => $event['group_count']
];
$total += $event['group_count'];
}
return response()->json([
'commerceEvents' => $commerceEventsQuery->get(),
'pageviewEvents' => $pageviewEventsQuery->get(),
'generalEvents' => $generalEventsQuery->get(),
'lastEvents' => [
'limit' => $lastActionsLimit,
'absoluteCounts' => $absoluteCounts,
'total' => $total
]
]);
}
public function diagramData(ConversionsSankeyRequest $request)
{
$from = Carbon::now($request->get('tz'))->subDays($request->get('interval'));
$to = Carbon::now($request->get('tz'));
$conversionSources = Conversion::whereBetween('paid_at', [$from, $to])
->with('conversionSources')
->has('conversionSources')
->get()
->pluck('conversionSources')
->flatten();
$conversionsSankeyDiagram = new ConversionsSankeyDiagram($this->journal, $conversionSources, $request->get('conversionSourceType'));
return new ConversionsSankeyResource($conversionsSankeyDiagram);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/SearchController.php | Beam/extensions/beam-module/src/Http/Controllers/SearchController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Remp\BeamModule\Http\Requests\SearchRequest;
use Remp\BeamModule\Http\Resources\SearchResource;
use Remp\BeamModule\Model\SearchAspects\ArticleSearchAspect;
use Remp\BeamModule\Model\SearchAspects\AuthorSearchAspect;
use Remp\BeamModule\Model\SearchAspects\SegmentSearchAspect;
use Spatie\Searchable\Search;
class SearchController extends Controller
{
public function search(SearchRequest $request)
{
$searchTerm = $request->query('term');
$searchResults['articles'] = (new Search())->registerAspect(ArticleSearchAspect::class)->search($searchTerm)->pluck('searchable');
$searchResults['authors'] = (new Search())->registerAspect(AuthorSearchAspect::class)->search($searchTerm)->pluck('searchable');
$searchResults['authors'] = $searchResults['authors']->sortByDesc('latestPublishedArticle.0.published_at')->take(config('search.maxResultCount'));
$searchResults['segments'] = (new Search())->registerAspect(SegmentSearchAspect::class)->search($searchTerm)->pluck('searchable');
$searchCollection = collect($searchResults);
return new SearchResource($searchCollection);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/ArticleController.php | Beam/extensions/beam-module/src/Http/Controllers/ArticleController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Remp\BeamModule\Http\Requests\ArticleRequest;
use Remp\BeamModule\Http\Requests\ArticlesListRequest;
use Remp\BeamModule\Http\Resources\ArticleResource;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Author;
use Remp\BeamModule\Model\Config\ConversionRateConfig;
use Remp\BeamModule\Model\Rules\ValidCarbonDate;
use Remp\BeamModule\Model\Section;
use Remp\BeamModule\Model\Tag;
use Yajra\DataTables\DataTables;
use Yajra\DataTables\EloquentDataTable;
use Yajra\DataTables\QueryDataTable;
class ArticleController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(ArticlesListRequest $request)
{
$articles = null;
$articlesBuilder = Article::with(['authors:id,external_id', 'sections:id,external_id', 'tags:id,external_id']);
$externalIds = $request->input('external_ids', []);
if (count($externalIds)) {
$articles = $articlesBuilder->whereIn('external_id', array_map('strval', $externalIds))->get();
}
if (!$articles) {
$ids = $request->input('ids', []);
if (count($request->ids)) {
$articles = $articlesBuilder->whereIntegerInRaw('id', $ids)->get();
}
}
$publishedFrom = $request->input('published_from');
$publishedTo = $request->input('published_to');
if (!$articles && ($publishedFrom || $publishedTo)) {
if ($publishedFrom) {
$articlesBuilder = $articlesBuilder->whereDate('published_at', '>=', $publishedFrom);
}
if ($publishedTo) {
$articlesBuilder = $articlesBuilder->whereDate('published_at', '<', $publishedTo);
}
$articles = $articlesBuilder->get();
}
$contentType = $request->input('content_type');
if ($contentType) {
$articles = $articlesBuilder->where('content_type', '=', $contentType)->get();
}
if (!$articles) {
$articles = $articlesBuilder->paginate($request->get('per_page', 15));
}
return response()->format([
'html' => redirect()->route('articles.pageviews'),
'json' => ArticleResource::collection($articles)->preserveQuery(),
]);
}
public function conversions(Request $request)
{
return response()->format([
'html' => view('beam::articles.conversions', [
'authors' => Author::all(['name', 'id'])->pluck('name', 'id'),
'contentTypes' => Article::groupBy('content_type')->pluck('content_type', 'content_type'),
'sections' => Section::all(['name', 'id'])->pluck('name', 'id'),
'tags' => Tag::all(['name', 'id'])->pluck('name', 'id'),
'publishedFrom' => $request->input('published_from', 'today - 30 days'),
'publishedTo' => $request->input('published_to', 'now'),
'conversionFrom' => $request->input('conversion_from', 'today - 30 days'),
'conversionTo' => $request->input('conversion_to', 'now'),
]),
'json' => ArticleResource::collection(Article::paginate()),
]);
}
public function dtConversions(Request $request, Datatables $datatables)
{
$request->validate([
'published_from' => ['sometimes', new ValidCarbonDate],
'published_to' => ['sometimes', new ValidCarbonDate],
'conversion_from' => ['sometimes', new ValidCarbonDate],
'conversion_to' => ['sometimes', new ValidCarbonDate],
]);
$articlesQuery = Article::query()->selectRaw(implode(',', [
"articles.id",
"articles.external_id",
"articles.title",
"articles.content_type",
"articles.url",
"articles.published_at",
"articles.pageviews_all",
"count(conversions.id) as conversions_count",
"coalesce(sum(conversions.amount), 0) as conversions_sum",
"avg(conversions.amount) as conversions_avg",
"coalesce(cast(count(conversions.id) AS DECIMAL(15, 10)) / articles.pageviews_all, 0) as conversions_rate",
]))
->with(['authors', 'sections', 'tags'])
->leftJoin('conversions', 'articles.id', '=', 'conversions.article_id')
->groupBy(['articles.id', 'articles.title', 'articles.url', 'articles.published_at'])
->ofSelectedProperty();
$conversionsQuery = \DB::table('conversions')
->select([
DB::raw('count(*) as count'),
DB::raw('sum(amount) as sum'),
DB::raw('avg(amount) as avg'),
'currency',
'article_id',
'articles.external_id',
])
->join('articles', 'articles.id', '=', 'conversions.article_id')
->groupBy(['conversions.article_id', 'articles.external_id', 'conversions.currency']);
if ($request->input('published_from')) {
$publishedFrom = Carbon::parse($request->input('published_from'), $request->input('tz'));
$articlesQuery->where('published_at', '>=', $publishedFrom);
}
if ($request->input('published_to')) {
$publishedTo = Carbon::parse($request->input('published_to'), $request->input('tz'));
$articlesQuery->where('published_at', '<=', $publishedTo);
}
if ($request->input('conversion_from')) {
$conversionFrom = Carbon::parse($request->input('conversion_from'), $request->input('tz'));
$articlesQuery->where('paid_at', '>=', $conversionFrom);
$conversionsQuery->where('paid_at', '>=', $conversionFrom);
}
if ($request->input('conversion_to')) {
$conversionTo = Carbon::parse($request->input('conversion_to'), $request->input('tz'));
$articlesQuery->where('paid_at', '<=', $conversionTo);
$conversionsQuery->where('paid_at', '<=', $conversionTo);
}
$columns = $request->input('columns');
$authorsIndex = array_search('authors', array_column($columns, 'name'), true);
if (isset($columns[$authorsIndex]['search']['value'])) {
$values = explode(',', $columns[$authorsIndex]['search']['value']);
$articlesQuery->join('article_author', 'articles.id', '=', 'article_author.article_id')
->whereIn('article_author.author_id', $values);
}
$sectionsIndex = array_search('sections[, ].name', array_column($columns, 'name'), true);
if (isset($columns[$sectionsIndex]['search']['value'])) {
$values = explode(',', $columns[$sectionsIndex]['search']['value']);
$articlesQuery->join('article_section', 'articles.id', '=', 'article_section.article_id')
->whereIn('article_section.section_id', $values);
}
$tagsIndex = array_search('tags[, ].name', array_column($columns, 'name'), true);
if (isset($columns[$tagsIndex]['search']['value'])) {
$values = explode(',', $columns[$tagsIndex]['search']['value']);
$articlesQuery->join('article_tag', 'articles.id', '=', 'article_tag.article_id')
->whereIn('article_tag.tag_id', $values);
}
$conversionsQuery->whereIntegerInRaw('article_id', $articlesQuery->pluck('id'));
$conversionSums = [];
$conversionAverages = [];
foreach ($conversionsQuery->get() as $record) {
$conversionSums[$record->article_id][$record->currency] = $record->sum;
$conversionAverages[$record->article_id][$record->currency] = $record->avg;
}
$conversionRateConfig = ConversionRateConfig::build();
/** @var EloquentDataTable $dt */
$dt = $datatables->of($articlesQuery);
return $dt
->addColumn('id', function (Article $article) {
return $article->id;
})
->addColumn('title', function (Article $article) {
return [
'url' => route('articles.show', ['article' => $article->id]),
'text' => $article->title,
];
})
->addColumn('conversions_rate', function (Article $article) use ($conversionRateConfig) {
return Article::computeConversionRate($article->conversions_count, $article->pageviews_all, $conversionRateConfig);
})
->addColumn('amount', function (Article $article) use ($conversionSums) {
if (!isset($conversionSums[$article->id])) {
return [0];
}
$amounts = [];
foreach ($conversionSums[$article->id] as $currency => $c) {
$c = round($c, 2);
$amounts[] = "{$c} {$currency}";
}
return $amounts ?: [0];
})
->addColumn('average', function (Article $article) use ($conversionAverages) {
if (!isset($conversionAverages[$article->id])) {
return [0];
}
$average = [];
foreach ($conversionAverages[$article->id] as $currency => $c) {
$c = round($c, 2);
$average[] = "{$c} {$currency}";
}
return $average ?: [0];
})
->addColumn('authors', function (Article $article) {
$authors = $article->authors->map(function (Author $author) {
return ['link' => html()->a(route('authors.show', $author), $author->name)];
});
return $authors->implode('link', '<br/>');
})
->orderColumn('amount', 'conversions_sum $1')
->orderColumn('average', 'conversions_avg $1')
->orderColumn('conversions_count', 'conversions_count $1')
->orderColumn('conversions_rate', 'conversions_rate $1')
->orderColumn('id', 'articles.id $1')
->filterColumn('title', function (Builder $query, $value) {
$query->where('articles.title', 'like', '%' . $value . '%');
})
->filterColumn('content_type', function (Builder $query, $value) {
$values = explode(',', $value);
$query->whereIn('articles.content_type', $values);
})
->filterColumn('authors', function (Builder $query, $value) {
$values = explode(",", $value);
$filterQuery = \DB::table('articles')
->select(['articles.id'])
->join('article_author', 'articles.id', '=', 'article_author.article_id', 'left')
->whereIn('article_author.author_id', $values);
$query->whereIn('articles.id', $filterQuery);
})
->filterColumn('sections[, ].name', function (Builder $query, $value) {
$values = explode(",", $value);
$filterQuery = \DB::table('articles')
->select(['articles.id'])
->join('article_section', 'articles.id', '=', 'article_section.article_id', 'left')
->whereIn('article_section.section_id', $values);
$query->whereIn('articles.id', $filterQuery);
})
->filterColumn('tags[, ].name', function (Builder $query, $value) {
$values = explode(",", $value);
$filterQuery = \DB::table('articles')
->select(['articles.id'])
->join('article_tag', 'articles.id', '=', 'article_tag.article_id', 'left')
->whereIn('article_tag.tag_id', $values);
$query->whereIn('articles.id', $filterQuery);
})
->rawColumns(['authors'])
->make();
}
public function pageviews(Request $request)
{
return response()->format([
'html' => view('beam::articles.pageviews', [
'authors' => Author::query()->pluck('name', 'id'),
'contentTypes' => Article::groupBy('content_type')->pluck('content_type', 'content_type'),
'sections' => Section::query()->pluck('name', 'id'),
'tags' => Tag::query()->pluck('name', 'id'),
'publishedFrom' => $request->input('published_from', 'today - 30 days'),
'publishedTo' => $request->input('published_to', 'now'),
]),
'json' => ArticleResource::collection(Article::paginate()),
]);
}
public function dtPageviews(Request $request, Datatables $datatables)
{
$request->validate([
'published_from' => ['sometimes', new ValidCarbonDate],
'published_to' => ['sometimes', new ValidCarbonDate],
]);
$articles = Article::selectRaw('articles.*,' .
'CASE pageviews_all WHEN 0 THEN 0 ELSE (pageviews_subscribers/pageviews_all)*100 END AS pageviews_subscribers_ratio')
->with(['authors', 'sections', 'tags'])
->ofSelectedProperty();
if ($request->input('published_from')) {
$articles->where('published_at', '>=', Carbon::parse($request->input('published_from'), $request->input('tz')));
}
if ($request->input('published_to')) {
$articles->where('published_at', '<=', Carbon::parse($request->input('published_to'), $request->input('tz')));
}
/** @var QueryDataTable $datatable */
$datatable = $datatables->of($articles);
return $datatable
->addColumn('id', function (Article $article) {
return $article->id;
})
->addColumn('title', function (Article $article) {
return [
'url' => route('articles.show', ['article' => $article->id]),
'text' => $article->title,
];
})
->addColumn('avg_sum_all', function (Article $article) {
if (!$article->timespent_all || !$article->pageviews_all) {
return 0;
}
return round($article->timespent_all / $article->pageviews_all);
})
->addColumn('avg_sum_signed_in', function (Article $article) {
if (!$article->timespent_signed_in || !$article->pageviews_signed_in) {
return 0;
}
return round($article->timespent_signed_in / $article->pageviews_signed_in);
})
->addColumn('avg_sum_subscribers', function (Article $article) {
if (!$article->timespent_subscribers || !$article->pageviews_subscribers) {
return 0;
}
return round($article->timespent_subscribers / $article->pageviews_subscribers);
})
->addColumn('authors', function (Article $article) {
$authors = $article->authors->map(function (Author $author) {
return ['link' => html()->a(route('authors.show', $author), $author->name)];
});
return $authors->implode('link', '<br/>');
})
->filterColumn('title', function (Builder $query, $value) {
$query->where('articles.title', 'like', '%' . $value . '%');
})
->filterColumn('content_type', function (Builder $query, $value) {
$values = explode(',', $value);
$query->whereIn('articles.content_type', $values);
})
->filterColumn('authors', function (Builder $query, $value) {
$values = explode(',', $value);
$filterQuery = \DB::table('articles')
->select(['articles.id'])
->join('article_author', 'articles.id', '=', 'article_author.article_id', 'left')
->whereIn('article_author.author_id', $values);
$query->whereIn('articles.id', $filterQuery);
})
->filterColumn('sections[, ].name', function (Builder $query, $value) {
$values = explode(',', $value);
$filterQuery = \DB::table('articles')
->select(['articles.id'])
->join('article_section', 'articles.id', '=', 'article_section.article_id', 'left')
->whereIn('article_section.section_id', $values);
$query->whereIn('articles.id', $filterQuery);
})
->filterColumn('tags[, ].name', function (Builder $query, $value) {
$values = explode(',', $value);
$filterQuery = \DB::table('articles')
->select(['articles.id'])
->join('article_tag', 'articles.id', '=', 'article_tag.article_id', 'left')
->whereIn('article_tag.tag_id', $values);
$query->whereIn('articles.id', $filterQuery);
})
->orderColumn('avg_sum_all', 'timespent_all / pageviews_all $1')
->orderColumn('avg_sum_signed_in', 'timespent_signed_in / pageviews_signed_in $1')
->orderColumn('avg_sum_subscribers', 'timespent_subscribers / pageviews_subscribers $1')
->orderColumn('pageviews_subscribers_ratio', 'pageviews_subscribers_ratio $1')
->orderColumn('id', 'articles.id $1')
->rawColumns(['authors'])
->make(true);
}
public function store(ArticleRequest $request)
{
/** @var Article $article */
$article = Article::firstOrNew([
'external_id' => $request->get('external_id'),
]);
$article->fill($request->all());
$article->save();
$article->sections()->detach();
foreach ($request->get('sections', []) as $sectionName) {
$section = Section::firstOrCreate([
'name' => $sectionName,
]);
$article->sections()->attach($section);
}
$article->tags()->detach();
foreach ($request->get('tags', []) as $tagName) {
$tag = Tag::firstOrCreate([
'name' => $tagName,
]);
$article->tags()->attach($tag);
}
$article->authors()->detach();
foreach ($request->get('authors', []) as $authorName) {
$section = Author::firstOrCreate([
'name' => $authorName,
]);
$article->authors()->attach($section);
}
$article->load(['authors', 'sections', 'tags']);
return response()->format([
'html' => redirect(route('articles.pageviews'))->with('success', 'Article created'),
'json' => new ArticleResource($article),
]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/SettingsController.php | Beam/extensions/beam-module/src/Http/Controllers/SettingsController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Illuminate\Http\Request;
use Remp\BeamModule\Http\Resources\ConfigResource;
use Remp\BeamModule\Model\Config\Config;
use Remp\BeamModule\Model\Config\ConfigCategory;
use Illuminate\Support\Facades\Validator;
class SettingsController extends Controller
{
public function index()
{
return response()->format([
'html' => view('beam::settings.index', [
'configsByCategories' => Config::global()->with('configCategory')->get()->groupBy('configCategory.display_name'),
]),
'json' => ConfigResource::collection(Config::get()),
]);
}
public function update(ConfigCategory $configCategory, Request $request)
{
$settings = $request->get('settings');
$pairedRequest = $configCategory->getPairedRequestType($request);
if ($pairedRequest !== $request) {
$validator = Validator::make($settings, $pairedRequest->rules(), $pairedRequest->messages() ?? []);
if ($validator->fails()) {
return redirect($request->get('redirect_url') ?? route('settings.index'))
->withErrors($validator)
->withInput();
}
}
foreach ($settings as $name => $value) {
Config::global()
->where('name', $name)
->update(['value' => $value]);
}
return response()->format([
'html' => redirect($request->get('redirect_url') ?? route('settings.index'))->with('success', 'Settings updated'),
'json' => ConfigResource::collection(Config::global()->get()),
]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/AuthController.php | Beam/extensions/beam-module/src/Http/Controllers/AuthController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function logout()
{
Auth::logout();
return redirect()->back();
}
public function error(Request $request)
{
$message = $request->get('error');
return response()->format([
'html' => view('beam::auth.error', [
'message' => $message,
]),
'json' => [
'message' => $message,
],
]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.