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/Http/Controllers/SegmentController.php | Beam/extensions/beam-module/src/Http/Controllers/SegmentController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Illuminate\Http\Request;
use Remp\BeamModule\Http\Requests\SegmentRequest;
use Remp\BeamModule\Model\Segment;
use Remp\BeamModule\Model\SegmentGroup;
use Remp\BeamModule\Model\SegmentRule;
use Remp\Journal\JournalContract;
use Yajra\DataTables\DataTables;
class SegmentController extends Controller
{
private $journalContract;
public function __construct(JournalContract $journalContract)
{
$this->journalContract = $journalContract;
}
public function index()
{
return view('beam::segments.index');
}
public function json(Request $request, Datatables $datatables)
{
$columns = ['id', 'name', 'active', 'code', 'created_at', 'updated_at'];
$segments = Segment::select($columns)
->where('segment_group_id', SegmentGroup::getByCode(SegmentGroup::CODE_REMP_SEGMENTS)->id);
return $datatables->of($segments)
->addColumn('actions', function (Segment $segment) {
return [
'edit' => route('segments.edit', $segment),
'copy' => route('segments.copy', $segment),
];
})
->addColumn('name', function (Segment $segment) {
return [
'url' => route('segments.edit', ['segment' => $segment]),
'text' => $segment->name,
];
})
->rawColumns(['name.text', 'code', 'active', 'actions'])
->make(true);
}
public function create()
{
$segment = new Segment();
list($segment, $categories) = $this->processOldSegment($segment, old(), $segment->rules->toArray());
return view('beam::segments.create', [
'segment' => $segment,
'categories' => $categories,
]);
}
public function betaCreate()
{
$segment = new Segment();
list($segment, $categories) = $this->processOldSegment($segment, old(), $segment->rules->toArray());
return view('beam::segments.beta.create', [
'segment' => $segment,
'categories' => $categories,
]);
}
public function copy(Segment $sourceSegment)
{
$segment = new Segment();
$segment->fill($sourceSegment->toArray());
list($segment, $categories) = $this->processOldSegment($segment, old(), $sourceSegment->rules->toArray());
flash(sprintf('Form has been pre-filled with data from segment "%s"', $sourceSegment->name))->info();
return view('beam::segments.create', [
'segment' => $segment,
'categories' => $categories,
]);
}
public function store(SegmentRequest $request)
{
$segment = new Segment();
$segment = $this->saveSegment($segment, $request->all(), $request->get('rules'));
return response()->format([
'html' => $this->getRouteBasedOnAction(
$request->get('action'),
[
self::FORM_ACTION_SAVE_CLOSE => 'segments.index',
self::FORM_ACTION_SAVE => 'segments.edit',
],
$segment
)->with('success', sprintf('Segment [%s] was created', $segment->name)),
]);
}
public function show(Segment $segment)
{
//
}
public function edit(Segment $segment)
{
list($segment, $categories) = $this->processOldSegment($segment, old(), $segment->rules->toArray());
return view('beam::segments.edit', [
'segment' => $segment,
'categories' => $categories,
]);
}
public function betaEdit(Segment $segment)
{
list($segment, $categories) = $this->processOldSegment($segment, old(), $segment->rules->toArray());
return view('beam::segments.beta.edit', [
'segment' => $segment,
'categories' => $categories,
]);
}
public function update(SegmentRequest $request, Segment $segment)
{
$segment = $this->saveSegment($segment, $request->all(), $request->get('rules'));
return response()->format([
'html' => $this->getRouteBasedOnAction(
$request->get('action'),
[
self::FORM_ACTION_SAVE_CLOSE => 'segments.index',
self::FORM_ACTION_SAVE => 'segments.edit',
],
$segment
)->with('success', sprintf('Segment [%s] was updated', $segment->name)),
]);
}
public function destroy(Segment $segment)
{
$segment->delete();
return redirect(route('segments.index', $segment))->with('success', 'Segment removed');
}
/**
* process data from old not valid form
*
* @param Segment $segment
* @param array $old
* @param array $segmentRules
* @return array
*/
public function processOldSegment(Segment $segment, array $old, array $segmentRules)
{
$segment->fill($old);
$rulesData = $old['rules'] ?? $segmentRules;
$segment['removedRules'] = $old['removedRules'] ?? [];
if ($rulesData) {
$rules = [];
foreach ($rulesData as $rule) {
$rules[] = $segment->rules()->make($rule);
}
$segment->setRelation('rules', collect($rules));
}
$categories = collect($this->journalContract->categories());
return [
$segment,
$categories
];
}
/**
* save segment and relations
*
* @param \Remp\BeamModule\Model\Segment $segment
* @param array $data
* @param array $rules
* @return Segment
*/
public function saveSegment(Segment $segment, array $data, array $rules)
{
if (!array_key_exists('segment_group_id', $data)) {
$data['segment_group_id'] = SegmentGroup::getByCode(SegmentGroup::CODE_REMP_SEGMENTS)->id;
}
$segment->fill($data);
$segment->save();
foreach ($rules as $rule) {
$loadedRule = SegmentRule::findOrNew($rule['id']);
$loadedRule->segment_id = $segment->id;
$loadedRule->fill($rule);
$loadedRule->fields = array_filter($loadedRule->fields, function ($item) {
return !empty($item["key"]);
});
$loadedRule->save();
}
if (isset($data['removedRules'])) {
SegmentRule::destroy($data['removedRules']);
}
return $segment;
}
public function embed(Request $request)
{
$segment = null;
if ($segmentId = $request->get('segmentId')) {
$segment = Segment::find($segmentId);
}
return view('beam::segments.beta.embed', [
'segment' => $segment,
]);
}
}
| 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/PropertyController.php | Beam/extensions/beam-module/src/Http/Controllers/PropertyController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Illuminate\Http\Request;
use Ramsey\Uuid\Uuid;
use Remp\BeamModule\Model\Account;
use Remp\BeamModule\Model\Property;
use Remp\BeamModule\Model\Property\SelectedProperty;
use Yajra\DataTables\DataTables;
class PropertyController extends Controller
{
private $selectedProperty;
public function __construct(SelectedProperty $selectedProperty)
{
$this->selectedProperty = $selectedProperty;
}
public function index(Account $account)
{
return view('beam::properties.index', [
'account' => $account,
]);
}
public function json(Account $account, Request $request, Datatables $datatables)
{
$properties = $account->properties()->getQuery();
return $datatables->of($properties)
->addColumn('actions', function (Property $property) use ($account) {
return [
'edit' => route('accounts.properties.edit', [$account, $property]),
];
})
->addColumn('name', function (Property $property) use ($account) {
return [
'url' => route('accounts.properties.edit', ['account' => $account, 'property' => $property]),
'text' => $property->name,
];
})
->rawColumns(['actions'])
->setRowId('id')
->make(true);
}
public function create(Account $account)
{
return view('beam::properties.create', [
'account' => $account,
'property' => new Property(),
]);
}
/**
* Store a newly created resource in storage.
*
* @param Account $account
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
* @internal param $accountId
*/
public function store(Account $account, Request $request)
{
$this->validate($request, [
'name' => 'bail|required|unique:properties|max:255',
]);
$property = new Property();
$property->fill($request->all());
$property->uuid = Uuid::uuid4();
$property->account()->associate($account);
$property->save();
return response()->format([
'html' => $this->getRouteBasedOnAction(
$request->get('action'),
[
self::FORM_ACTION_SAVE_CLOSE => 'accounts.properties.index',
self::FORM_ACTION_SAVE => 'accounts.properties.edit',
],
[$account, $property]
)->with('success', sprintf('Property [%s] was created', $property->name)),
]);
}
public function edit(Account $account, Property $property)
{
return view('beam::properties.edit', [
'account' => $account,
'property' => $property,
]);
}
public function update(Account $account, Property $property, Request $request)
{
$this->validate($request, [
'name' => 'bail|required|unique:properties|max:255',
]);
$property->fill($request->all());
$property->save();
return response()->format([
'html' => $this->getRouteBasedOnAction(
$request->get('action'),
[
self::FORM_ACTION_SAVE_CLOSE => 'accounts.properties.index',
self::FORM_ACTION_SAVE => 'accounts.properties.edit',
],
[$account, $property]
)->with('success', sprintf('Property [%s] was updated', $property->name)),
]);
}
public function destroy(Property $property, Account $account)
{
$property->delete();
return redirect(route('accounts.properties.index', $account))->with('success', 'Property removed');
}
/**
* Method for switching selected property token
* Careful, it's not protected by user authentication, since it should be also available from public dashboard
* @param Request $request
*
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function switch(Request $request)
{
$propertyToken = $request->input('token');
try {
$this->selectedProperty->setToken($propertyToken);
} catch (\InvalidArgumentException $exception) {
abort('400', 'No such token');
}
return back();
}
}
| 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/EntitiesController.php | Beam/extensions/beam-module/src/Http/Controllers/EntitiesController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Illuminate\Http\Request;
use Remp\BeamModule\Http\Requests\EntityRequest;
use Remp\BeamModule\Http\Resources\EntityResource;
use Remp\BeamModule\Model\Entity;
use Remp\BeamModule\Model\EntityParam;
use Yajra\DataTables\DataTables;
class EntitiesController extends Controller
{
public function index()
{
return view('beam::entities.index');
}
public function json(Request $request, DataTables $datatables)
{
$columns = ['id', 'name'];
$entities = Entity::select($columns)->with("params")->whereNotNull('parent_id');
return $datatables->of($entities)
->addColumn('name', function (Entity $entity) {
return [
'url' => route('entities.edit', ['entity' => $entity]),
'text' => $entity->name,
];
})
->addColumn('params', function (Entity $entity) {
$params = [];
foreach ($entity->params as $param) {
$type = __("entities.types." . $param->type);
$params[] = "<strong>{$type}</strong> {$param->name}";
}
return $params;
})
->addColumn('actions', function (Entity $entity) {
return [
'edit' => route('entities.edit', $entity)
];
})
->rawColumns(['actions'])
->make(true);
}
public function create()
{
$entity = new Entity();
return response()->format([
'html' => view('beam::entities.create', [
'entity' => $entity,
'rootEntities' => Entity::where('parent_id', null)->get()
]),
'json' => new EntityResource($entity)
]);
}
public function store(EntityRequest $request)
{
$entity = new Entity();
$entity = $this->saveEntity($entity, $request);
return response()->format([
'html' => $this->getRouteBasedOnAction(
$request->get('action'),
[
self::FORM_ACTION_SAVE_CLOSE => 'entities.index',
self::FORM_ACTION_SAVE => 'entities.edit',
],
$entity
)->with('success', sprintf('Entity [%s] was created', $entity->name)),
]);
}
public function edit(Entity $entity)
{
if ($entity->isRootEntity()) {
return response('Forbidden', 403);
}
return view('beam::entities.edit', [
'entity' => $entity,
'rootEntities' => Entity::where('parent_id', null)->get()
]);
}
public function update(Entity $entity, EntityRequest $request)
{
$entity = $this->saveEntity($entity, $request);
return response()->format([
'html' => $this->getRouteBasedOnAction(
$request->get('action'),
[
self::FORM_ACTION_SAVE_CLOSE => 'entities.index',
self::FORM_ACTION_SAVE => 'entities.edit',
],
$entity
)->with('success', sprintf('Entity [%s] was updated', $entity->name)),
]);
}
public function destroy(Entity $entity)
{
$entity->delete();
return response()->format([
'html' => redirect(route('entities.index'))->with('success', 'Entity removed'),
'json' => new EntityResource([]),
]);
}
public function validateForm(EntityRequest $request, Entity $entity = null)
{
return response()->json(false);
}
public function saveEntity(Entity $entity, EntityRequest $request)
{
$entity->fill($request->all());
$entity->save();
$paramsToDelete = $request->get("params_to_delete") ?? [];
EntityParam::whereIn("id", $paramsToDelete)->delete();
$paramsData = $request->get("params") ?? [];
foreach ($paramsData as $paramData) {
$param = EntityParam::findOrNew($paramData["id"]);
$param->fill($paramData);
$param->entity()->associate($entity);
$param->save();
}
return $entity;
}
}
| 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/ArticleDetailsController.php | Beam/extensions/beam-module/src/Http/Controllers/ArticleDetailsController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Remp\BeamModule\Helpers\Colors;
use Remp\BeamModule\Helpers\Journal\JournalHelpers;
use Remp\BeamModule\Helpers\Journal\JournalInterval;
use Remp\BeamModule\Helpers\Misc;
use Remp\BeamModule\Http\Requests\ArticlesListRequest;
use Remp\BeamModule\Http\Resources\ArticleResource;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\ArticleTitle;
use Remp\BeamModule\Model\ConversionSource;
use Remp\BeamModule\Model\Pageviews\PageviewsHelper;
use Remp\BeamModule\Model\Rules\ValidCarbonDate;
use Remp\BeamModule\Model\Snapshots\SnapshotHelpers;
use Remp\Journal\AggregateRequest;
use Remp\Journal\JournalContract;
class ArticleDetailsController extends Controller
{
private const ALLOWED_INTERVALS = 'today,1day,7days,30days,all,first1day,first7days,first14days';
private JournalContract $journal;
private JournalHelpers $journalHelper;
private SnapshotHelpers $snapshotHelpers;
private PageviewsHelper $pageviewsHelper;
public function __construct(JournalContract $journal, SnapshotHelpers $snapshotHelpers, PageviewsHelper $pageviewsHelper)
{
$this->journal = $journal;
$this->journalHelper = new JournalHelpers($journal);
$this->snapshotHelpers = $snapshotHelpers;
$this->pageviewsHelper = $pageviewsHelper;
}
public function variantsHistogram(Article $article, Request $request)
{
$request->validate([
'tz' => 'timezone',
'interval' => 'required|in:' . self::ALLOWED_INTERVALS,
'type' => 'required|in:title,image',
]);
$type = $request->get('type');
$groupBy = $type === 'title' ? 'title_variant' : 'image_variant';
$tz = new \DateTimeZone($request->get('tz', 'UTC'));
$journalInterval = new JournalInterval($tz, $request->get('interval'), $article);
$data = $this->histogram($article, $journalInterval, $groupBy, function (AggregateRequest $request) {
$request->addFilter('derived_referer_medium', 'internal');
});
$data['colors'] = array_values(Colors::assignColorsToVariantTags($data['tags']));
$tagToColor = [];
for ($i = 0, $iMax = count($data['tags']); $i < $iMax; $i++) {
$tagToColor[$data['tags'][$i]] = $data['colors'][$i];
}
$data['tagLabels'] = [];
$articleTitles = $article
->articleTitles()
->whereIn('variant', $data['tags'])
->get()
->groupBy('variant');
$data['events'] = [];
$pageviewSums = [];
foreach ($articleTitles as $variant => $variantTitles) {
$variantTitle = $variantTitles[0];
$data['events'][] = (object) [
'color' => $tagToColor[$variant],
'date' => $variantTitle->created_at->toIso8601ZuluString(),
'title' => "<b>{$variant} Title Variant Added</b><br />{$variantTitle->title}",
];
for ($i = 1; $i < $variantTitles->count(); $i++) {
$oldTitle = $variantTitles[$i-1];
$newTitle = $variantTitles[$i];
$text = null;
if ($newTitle->title === null) {
$text = "<b>{$variant} Title Variant Deleted</b><br /><strike>{$oldTitle->title}</strike>";
} elseif ($oldTitle->title === null) {
$text = "<b>{$variant} Title Variant Added</b><br />{$newTitle->title}";
} else {
$text = "<b>{$variant} Title Variant Changed</b><br />" .
"<b>From:</b> {$oldTitle->title}<br />" .
"<b>To:</b> {$newTitle->title}";
}
$data['events'][] = (object) [
'color' => $tagToColor[$variant],
'date' => $newTitle->created_at->toIso8601ZuluString(),
'title' => $text
];
}
$pageviewSums[$variant] = 0;
foreach ($data['results'] as $resultRow) {
if (isset($resultRow[$variant])) {
$pageviewSums[$variant] += $resultRow[$variant];
}
}
$data['tagLabels'][$variant] = (object) [
'color' => $tagToColor[$variant],
'labels' => $variantTitles->map(function ($variantTitle) {
return html_entity_decode($variantTitle->title, ENT_QUOTES);
}),
'pageloads_count' => ($type === 'title' ? ' <span style="color: black;">(' . $pageviewSums[$variantTitle->variant] . ' internal pageviews)</span> ' : '')
];
}
return response()->json($data);
}
private function itemTag($item): string
{
return $this->journalHelper->refererMediumLabel($item->referer_medium);
}
private function histogramFromPageviews(Article $article, JournalInterval $journalInterval)
{
$tag = 'pageviews';
$records = $this->pageviewsHelper->pageviewsHistogram($journalInterval, $article->id);
$results = [];
foreach ($records as $item) {
$zuluTime = Carbon::parse($item->time)->toIso8601ZuluString();
$results[$zuluTime]= [$tag => $item->count, 'Date' => $zuluTime];
}
return [
'publishedAt' => $article->published_at->toIso8601ZuluString(),
'intervalMinutes' => $journalInterval->intervalMinutes,
'results' => array_values($results),
'minDate' => $journalInterval->timeAfter->toIso8601ZuluString(),
'maxDate' => $journalInterval->timeBefore->toIso8601ZuluString(),
'tags' => [$tag]
];
}
private function histogramFromSnapshots(Article $article, JournalInterval $journalInterval)
{
$records = $this->snapshotHelpers->concurrentsHistogram($journalInterval, $article->external_id, true);
$tags = [];
foreach ($records as $item) {
$tags[$this->itemTag($item)] = true;
}
$tags = array_keys($tags);
$emptyValues = [];
foreach ($tags as $tag) {
$emptyValues[$tag] = 0;
}
$results = [];
foreach ($records as $item) {
$zuluTime = Carbon::parse($item->time)->toIso8601ZuluString();
if (!array_key_exists($zuluTime, $results)) {
$results[$zuluTime] = array_merge($emptyValues, ['Date' => $zuluTime]);
}
$results[$zuluTime][$this->itemTag($item)] += $item->count;
}
return [
'publishedAt' => $article->published_at->toIso8601ZuluString(),
'intervalMinutes' => $journalInterval->intervalMinutes,
'results' => array_values($results),
'minDate' => $journalInterval->timeAfter->toIso8601ZuluString(),
'maxDate' => $journalInterval->timeBefore->toIso8601ZuluString(),
'tags' => $tags
];
}
public function timeHistogram(Article $article, Request $request)
{
$request->validate([
'tz' => 'timezone',
'interval' => 'required|in:' . self::ALLOWED_INTERVALS,
'events.*' => 'in:conversions,title_changes'
]);
$tz = new \DateTimeZone($request->get('tz', 'UTC'));
$journalInterval = new JournalInterval($tz, $request->get('interval'), $article);
$dataSource = $request->get('dataSource');
switch ($dataSource) {
case 'snapshots':
$data = $this->histogramFromSnapshots($article, $journalInterval);
break;
case 'journal':
$data = $this->histogram($article, $journalInterval, 'derived_referer_medium');
break;
case 'pageviews':
$data = $this->histogramFromPageviews($article, $journalInterval);
break;
default:
throw new \Exception("unknown pageviews data source {$dataSource}");
}
$data['colors'] = array_values(Colors::assignColorsToMediumRefers($data['tags']));
$data['events'] = [];
$eventOptions = $request->get('events', []);
if (in_array('conversions', $eventOptions, false)) {
$conversions = $article->conversions()
->whereBetween('paid_at', [$journalInterval->timeAfter, $journalInterval->timeBefore])
->get();
foreach ($conversions as $conversion) {
$data['events'][] = (object) [
'color' => '#651067',
'date' => $conversion->paid_at->toIso8601ZuluString(),
'title' => "{$conversion->amount} {$conversion->currency}"
];
}
}
if (in_array('title_changes', $eventOptions, false)) {
$articleTitles = $article->articleTitles()
->orderBy('updated_at')
->get()
->groupBy('variant');
$hasSingleVariant = $articleTitles->count() === 1;
foreach ($articleTitles as $variant => $variantTitles) {
$variantText = $hasSingleVariant ? 'Title' : $variant . ' Title Variant';
$variantTitle = $variantTitles[0];
$data['events'][] = (object) [
'color' => '#28F16F',
'date' => $variantTitle->created_at->toIso8601ZuluString(),
'title' => "<b>{$variantText} Added</b><br />{$variantTitle->title}",
];
// If more titles
for ($i = 1; $i < $variantTitles->count(); $i++) {
$oldTitle = $variantTitles[$i-1];
$newTitle = $variantTitles[$i];
$text = null;
if ($newTitle->title === null) {
$text = "<b>{$variantText} Deleted</b><br /><strike>{$oldTitle->title}</strike>";
} elseif ($oldTitle->title === null) {
$text = "<b>{$variantText} Added</b><br />{$newTitle->title}";
} else {
$text = "<b>{$variantText} Changed</b><br />" .
"<b>From:</b> {$oldTitle->title}<br />" .
"<b>To:</b> {$newTitle->title}";
}
$data['events'][] = (object) [
'color' => '#28F16F',
'date' => $newTitle->created_at->toIso8601ZuluString(),
'title' => $text,
];
}
}
}
$requestedExternalEvents = $request->get('externalEvents', []);
$externalEvents = $this->loadExternalEvents($article, $journalInterval, $requestedExternalEvents);
$data['events'] += $externalEvents;
return response()->json($data);
}
private function loadExternalEvents(Article $article, JournalInterval $journalInterval, $requestedExternalEvents): array
{
$eventData = $this->journalHelper->loadEvents($journalInterval, $requestedExternalEvents, $article);
$tags = [];
$events = [];
foreach ($eventData as $eventItem) {
$title = $eventItem->category . ':' . $eventItem->action;
$tags[$title] = true;
$events[] = (object) [
'date' => Carbon::parse($eventItem->system->time)->toIso8601ZuluString(),
'title' => $title,
];
}
$colors = Colors::assignColorsToGeneralTags(array_keys($tags));
foreach ($events as $event) {
$event->color = $colors[$event->title];
}
return $events;
}
private function histogram(Article $article, JournalInterval $journalInterval, string $groupBy, callable $addConditions = null)
{
$getTag = function ($record) use ($groupBy) {
if ($groupBy === 'derived_referer_medium') {
return $this->journalHelper->refererMediumLabel($record->tags->$groupBy);
}
return $record->tags->$groupBy;
};
$journalRequest = (new AggregateRequest('pageviews', 'load'))
->addFilter('article_id', $article->external_id)
->setTime($journalInterval->timeAfter, $journalInterval->timeBefore)
->setTimeHistogram($journalInterval->intervalText)
->addGroup($groupBy);
if ($addConditions) {
$addConditions($journalRequest);
}
$currentRecords = collect($this->journal->count($journalRequest));
$tags = [];
foreach ($currentRecords as $records) {
$tags[] = $getTag($records);
}
// Values might be missing in time histogram, therefore fill all tags with 0s by default
$results = [];
$timeIterator = JournalHelpers::getTimeIterator($journalInterval->timeAfter, $journalInterval->intervalMinutes);
while ($timeIterator->lessThan($journalInterval->timeBefore)) {
$zuluDate = $timeIterator->toIso8601ZuluString();
$results[$zuluDate] = collect($tags)->mapWithKeys(function ($item) {
return [$item => 0];
});
$results[$zuluDate]['Date'] = $zuluDate;
$timeIterator->addMinutes($journalInterval->intervalMinutes);
}
// Save results
foreach ($currentRecords as $records) {
if (!isset($records->time_histogram)) {
continue;
}
$currentTag = $getTag($records);
foreach ($records->time_histogram as $timeValue) {
$results[$timeValue->time][$currentTag] = $timeValue->value;
}
}
$results = array_values($results);
return [
'publishedAt' => $article->published_at->toIso8601ZuluString(),
'intervalMinutes' => $journalInterval->intervalMinutes,
'results' => $results,
'tags' => $tags
];
}
public function showByParameter(Request $request, Article $article = null)
{
if (!$article) {
$externalId = $request->input('external_id');
$url = $request->input('url');
if ($externalId) {
$article = Article::where('external_id', $externalId)->first();
if (!$article) {
abort(404, 'No article found for given external_id parameter');
}
} elseif ($url) {
$article = Article::where('url', $url)->first();
if (!$article) {
abort(404, 'No article found for given URL parameter');
}
} else {
abort(404, 'Please specify either article ID, external_id or URL');
}
}
return redirect()->route('articles.show', ['article' => $article->id]);
}
public function list(ArticlesListRequest $request)
{
$externalIds = $request->external_ids;
if (!empty($externalIds)) {
$articles = Article::whereIn('external_id', $externalIds)->get();
}
$ids = $request->ids;
if (!empty($ids)) {
$articles = Article::whereIn('id', $ids)->get();
}
return response()->json(['articles' => $articles ?? collect([])]);
}
public function show(Request $request, Article $article = null)
{
if (!$article) {
$externalId = $request->input('external_id');
$url = $request->input('url');
if ($externalId) {
$article = Article::where('external_id', $externalId)->first();
if (!$article) {
abort(404, 'No article found for given external_id parameter');
}
} elseif ($url) {
$article = Article::where('url', $url)->first();
if (!$article) {
abort(404, 'No article found for given URL parameter');
}
} else {
abort(404, 'Please specify either article ID, external_id or URL');
}
}
$conversionsSums = collect();
foreach ($article->conversions as $conversions) {
if (!$conversionsSums->has($conversions->currency)) {
$conversionsSums[$conversions->currency] = 0;
}
$conversionsSums[$conversions->currency] += $conversions->amount;
}
$conversionsSums = $conversionsSums->map(function ($sum, $currency) {
return number_format($sum, 2) . ' ' . $currency;
})->values()->implode(', ');
$pageviewsSubscribersToAllRatio =
$article->pageviews_all == 0 ? 0 : ($article->pageviews_subscribers / $article->pageviews_all) * 100;
$mediums = $this->journalHelper->derivedRefererMediumGroups()->mapWithKeys(function ($item) {
return [$item => $this->journalHelper->refererMediumLabel($item)];
});
$externalEvents = [];
foreach ($this->journalHelper->eventsCategoriesActions($article) as $item) {
$externalEvents[] = (object) [
'text' => $item->category . ':' . $item->action,
'value' => $item->category . JournalHelpers::CATEGORY_ACTION_SEPARATOR . $item->action,
];
}
return response()->format([
'html' => view('beam::articles.show', [
'article' => $article,
'pageviewsSubscribersToAllRatio' => $pageviewsSubscribersToAllRatio,
'conversionsSums' => $conversionsSums,
'dataFrom' => $request->input('data_from', 'today - 30 days'),
'dataTo' => $request->input('data_to', 'now'),
'mediums' => $mediums,
'mediumColors' => Colors::assignColorsToMediumRefers($mediums),
'visitedFrom' => $request->input('visited_from', 'today - 30 days'),
'visitedTo' => $request->input('visited_to', 'now'),
'externalEvents' => $externalEvents,
'averageTimeSpentSubscribers' => Misc::secondsIntoReadableTime($article->pageviews_subscribers ? round($article->timespent_subscribers / $article->pageviews_subscribers) : 0),
'averageTimeSpentSignedId' => Misc::secondsIntoReadableTime($article->pageviews_signed_in ? round($article->timespent_signed_in / $article->pageviews_signed_in) : 0),
'averageTimeSpentAll' => Misc::secondsIntoReadableTime($article->pageviews_all ? round($article->timespent_all / $article->pageviews_all) : 0)
]),
'json' => new ArticleResource($article),
]);
}
public function dtReferers(Article $article, Request $request)
{
$request->validate([
'visited_to' => ['sometimes', new ValidCarbonDate],
'visited_from' => ['sometimes', new ValidCarbonDate],
]);
$length = $request->input('length');
$start = $request->input('start');
$orderOptions = $request->input('order');
$draw = $request->input('draw');
$visitedTo = Carbon::parse($request->input('visited_to'), $request->input('tz'));
$visitedFrom = Carbon::parse($request->input('visited_from'), $request->input('tz'));
$ar = (new AggregateRequest('pageviews', 'load'))
->setTime($visitedFrom, $visitedTo)
->addGroup('derived_referer_host_with_path', 'derived_referer_medium', 'derived_referer_source')
->addFilter('article_id', $article->external_id);
$columns = $request->input('columns');
foreach ($columns as $index => $column) {
if (isset($column['search']['value'])) {
$ar->addFilter($column['name'], ...explode(',', $column['search']['value']));
}
}
$data = collect();
$records = $this->journal->count($ar);
// 'derived_referer_source' has priority over 'derived_referer_host_with_path'
// since we do not want to distinguish between e.g. m.facebook.com and facebook.com, all should be categorized as one
$aggregated = [];
foreach ($records as $record) {
$derivedMedium = $this->journalHelper->refererMediumLabel($record->tags->derived_referer_medium);
$derivedSource = $record->tags->derived_referer_source;
$source = $record->tags->derived_referer_host_with_path;
$count = $record->count;
if (!array_key_exists($derivedMedium, $aggregated)) {
$aggregated[$derivedMedium] = [];
}
$key = $source;
if ($derivedSource) {
$key = $derivedSource;
}
if (!array_key_exists($key, $aggregated[$derivedMedium])) {
$aggregated[$derivedMedium][$key] = 0;
}
$aggregated[$derivedMedium][$key] += $count;
}
// retrieve conversion sources and group their counts by type(first/last), url and medium as well (same url cases)
$conversionSourcesCounts = [];
$conversionSources = $article->conversionSources()
->where('conversions.paid_at', '>=', $visitedFrom)
->where('conversions.paid_at', '<', $visitedTo)
->get();
foreach ($conversionSources as $conversionSource) {
$medium = $this->journalHelper->refererMediumLabel($conversionSource->referer_medium);
$source = empty($conversionSource->referer_source) ? $conversionSource->referer_host_with_path : $conversionSource->referer_source;
$type = $conversionSource->type;
if (!isset($conversionSourcesCounts[$medium][$source][$type])) {
$conversionSourcesCounts[$medium][$source][$type] = 0;
}
$conversionSourcesCounts[$medium][$source][$type]++;
}
foreach ($aggregated as $medium => $mediumSources) {
foreach ($mediumSources as $source => $count) {
$data->push([
'derived_referer_medium' => $medium,
'source' => $source,
'first_conversion_source_count' => $conversionSourcesCounts[$medium][$source][ConversionSource::TYPE_SESSION_FIRST] ?? 0,
'last_conversion_source_count' => $conversionSourcesCounts[$medium][$source][ConversionSource::TYPE_SESSION_LAST] ?? 0,
'visits_count' => $count,
]);
if (isset($conversionSourcesCounts[$medium][$source][ConversionSource::TYPE_SESSION_FIRST])) {
unset($conversionSourcesCounts[$medium][$source][ConversionSource::TYPE_SESSION_FIRST]);
}
if (isset($conversionSourcesCounts[$medium][$source][ConversionSource::TYPE_SESSION_LAST])) {
unset($conversionSourcesCounts[$medium][$source][ConversionSource::TYPE_SESSION_LAST]);
}
}
}
// add also conversion sources that do not match witch article source
foreach ($conversionSourcesCounts as $medium => $mediumSources) {
foreach ($mediumSources as $source => $commerceCountByType) {
if (!isset($commerceCountByType[ConversionSource::TYPE_SESSION_FIRST]) && !isset($commerceCountByType[ConversionSource::TYPE_SESSION_LAST])) {
continue;
}
$data->push([
'derived_referer_medium' => $medium,
'source' => $source,
'first_conversion_source_count' => $commerceCountByType[ConversionSource::TYPE_SESSION_FIRST] ?? 0,
'last_conversion_source_count' => $commerceCountByType[ConversionSource::TYPE_SESSION_LAST] ?? 0,
'visits_count' => 0,
]);
}
}
if (count($orderOptions) > 0) {
$option = $orderOptions[0];
$orderColumn = $columns[$option['column']]['name'];
$orderDirectionDesc = $option['dir'] === 'desc';
$data = $data->sortBy($orderColumn, SORT_REGULAR, $orderDirectionDesc)->values();
}
$recordsTotal = $data->count();
$data = $data->slice($start, $length)->values();
return response()->json([
'draw' => $draw,
'recordsTotal' => $recordsTotal,
'recordsFiltered' => $recordsTotal,
'data' => $data
]);
}
}
| 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/SectionController.php | Beam/extensions/beam-module/src/Http/Controllers/SectionController.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\Resources\SectionResource;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\ArticlesDataTable;
use Remp\BeamModule\Model\Author;
use Remp\BeamModule\Model\Conversion;
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 SectionController extends Controller
{
public function index(Request $request)
{
return response()->format([
'html' => view('beam::sections.index', [
'sections' => Section::query()->pluck('name', 'id'),
'contentTypes' => array_merge(
['all'],
Article::groupBy('content_type')->pluck('content_type')->toArray()
),
'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'),
'contentType' => $request->input('content_type', 'all'),
]),
'json' => SectionResource::collection(Section::paginate($request->get('per_page', 15)))->preserveQuery(),
]);
}
public function show(Section $section, Request $request)
{
return response()->format([
'html' => view('beam::sections.show', [
'section' => $section,
'contentTypes' => Article::groupBy('content_type')->pluck('content_type', 'content_type'),
'authors' => Author::all(['name', 'id'])->pluck('name', 'id'),
'tags' => Tag::all(['name', 'id'])->pluck('name', 'id'),
'sections' => Section::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' => new SectionResource($section),
]);
}
public function dtSections(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 = [
'sections.id',
'sections.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(',', [
'section_id',
'count(distinct conversions.id) as conversions_count',
'sum(conversions.amount) as conversions_amount',
]))
->ofSelectedProperty()
->leftJoin('article_section', 'conversions.article_id', '=', 'article_section.article_id')
->leftJoin('articles', 'article_section.article_id', '=', 'articles.id')
->groupBy('section_id');
$pageviewsQuery = Article::selectRaw(implode(',', [
'section_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'
]))
->ofSelectedProperty()
->leftJoin('article_section', 'articles.id', '=', 'article_section.article_id')
->groupBy('section_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);
}
$sections = Section::selectRaw(implode(",", $cols))
->leftJoin(DB::raw("({$conversionsQuery->toSql()}) as c"), 'sections.id', '=', 'c.section_id')->addBinding($conversionsQuery->getBindings())
->leftJoin(DB::raw("({$pageviewsQuery->toSql()}) as pv"), 'sections.id', '=', 'pv.section_id')->addBinding($pageviewsQuery->getBindings())
->ofSelectedProperty()
->groupBy(['sections.name', 'sections.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, article_section.section_id')
->join('article_section', 'conversions.article_id', '=', 'article_section.article_id')
->join('articles', 'article_section.article_id', '=', 'articles.id')
->ofSelectedProperty()
->groupBy(['article_section.section_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['section_id']][$record->currency] = $record['sum'];
if (!isset($conversionCounts[$record['section_id']])) {
$conversionCounts[$record['section_id']] = 0;
}
$conversionCounts[$record['section_id']] += $record['count'];
}
/** @var QueryDataTable $datatable */
$datatable = $datatables->of($sections);
return $datatable
->addColumn('id', function (Section $section) {
return $section->id;
})
->addColumn('name', function (Section $section) {
return [
'url' => route('sections.show', ['section' => $section]),
'text' => $section->name,
];
})
->filterColumn('name', function (Builder $query, $value) use ($request) {
if ($request->input('search')['value'] === $value) {
$query->where(function (Builder $query) use ($value) {
$query->where('sections.name', 'like', '%' . $value . '%');
});
} else {
$sectionIds = explode(',', $value);
$query->where(function (Builder $query) use ($sectionIds) {
$query->whereIn('sections.id', $sectionIds);
});
}
})
->addColumn('conversions_count', function (Section $section) use ($conversionCounts) {
return $conversionCounts[$section->id] ?? 0;
})
->addColumn('conversions_amount', function (Section $section) use ($conversionAmounts) {
if (!isset($conversionAmounts[$section->id])) {
return 0;
}
$amounts = [];
foreach ($conversionAmounts[$section->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', 'sections.id $1')
->setTotalRecords(PHP_INT_MAX)
->setFilteredRecords(PHP_INT_MAX)
->make(true);
}
public function dtArticles(Section $section, Request $request, Datatables $datatables, ArticlesDataTable $articlesDataTable)
{
ini_set('memory_limit', '512M');
$articlesDataTable->setSection($section);
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/TagController.php | Beam/extensions/beam-module/src/Http/Controllers/TagController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\ArticlesDataTable;
use Remp\BeamModule\Model\Author;
use Illuminate\Http\Request;
use Remp\BeamModule\Http\Resources\TagResource;
use Remp\BeamModule\Model\Tag;
use Remp\BeamModule\Model\Section;
use Remp\BeamModule\Model\TagsDataTable;
use Yajra\DataTables\DataTables;
use Html;
class TagController extends Controller
{
public function index(Request $request)
{
return response()->format([
'html' => view('beam::tags.index', [
'tags' => Tag::query()->pluck('name', 'id'),
'contentTypes' => array_merge(
['all'],
Article::groupBy('content_type')->pluck('content_type')->toArray()
),
'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'),
'contentType' => $request->input('content_type', 'all'),
]),
'json' => TagResource::collection(Tag::paginate($request->get('per_page', 15)))->preserveQuery(),
]);
}
public function show(Tag $tag, Request $request)
{
return response()->format([
'html' => view('beam::tags.show', [
'tag' => $tag,
'tags' => Tag::all(['name', 'id'])->pluck('name', 'id'),
'contentTypes' => Article::groupBy('content_type')->pluck('content_type', 'content_type'),
'sections' => Section::all(['name', 'id'])->pluck('name', 'id'),
'authors' => Author::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' => new TagResource($tag),
]);
}
public function dtTags(Request $request, DataTables $datatables, TagsDataTable $tagsDataTable)
{
return $tagsDataTable->getDataTable($request, $datatables);
}
public function dtArticles(Tag $tag, Request $request, Datatables $datatables, ArticlesDataTable $articlesDataTable)
{
$articlesDataTable->setTag($tag);
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/TagCategoryController.php | Beam/extensions/beam-module/src/Http/Controllers/TagCategoryController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\ArticlesDataTable;
use Remp\BeamModule\Model\Author;
use Remp\BeamModule\Model\Tag;
use Remp\BeamModule\Model\Section;
use Remp\BeamModule\Http\Resources\TagCategoryResource;
use Remp\BeamModule\Model\TagCategoriesDataTable;
use Remp\BeamModule\Model\TagCategory;
use Yajra\DataTables\DataTables;
use Illuminate\Http\Request;
use Html;
use Remp\BeamModule\Model\TagsDataTable;
class TagCategoryController extends Controller
{
public function index(Request $request)
{
return response()->format([
'html' => view('beam::tagcategories.index', [
'tagCategories' => TagCategory::query()->pluck('name', 'id'),
'contentTypes' => array_merge(
['all'],
Article::groupBy('content_type')->pluck('content_type')->toArray()
),
'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'),
'contentType' => $request->input('content_type', 'all'),
]),
'json' => TagCategoryResource::collection(TagCategory::paginate()),
]);
}
public function show(TagCategory $tagCategory, Request $request)
{
return response()->format([
'html' => view('beam::tagcategories.show', [
'tagCategory' => $tagCategory,
'tags' => Tag::query()->pluck('name', 'id'),
'contentTypes' => Article::groupBy('content_type')->pluck('content_type', 'content_type'),
'sections' => Section::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 TagCategoryResource($tagCategory),
]);
}
public function dtTagCategories(Request $request, DataTables $datatables, TagCategoriesDataTable $tagCategoriesDataTable)
{
return $tagCategoriesDataTable->getDataTable($request, $datatables);
}
public function dtTags(TagCategory $tagCategory, Request $request, DataTables $datatables, TagsDataTable $tagsDataTable)
{
$tagsDataTable->setTagCategory($tagCategory);
return $tagsDataTable->getDataTable($request, $datatables);
}
public function dtArticles(TagCategory $tagCategory, Request $request, DataTables $datatables, ArticlesDataTable $articlesDataTable)
{
$articlesDataTable->setTagCategory($tagCategory);
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/DashboardController.php | Beam/extensions/beam-module/src/Http/Controllers/DashboardController.php | <?php
namespace Remp\BeamModule\Http\Controllers;
use Remp\BeamModule\Model\DashboardArticle;
use Illuminate\Support\Arr;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Helpers\Journal\JournalHelpers;
use Remp\BeamModule\Helpers\Colors;
use Remp\BeamModule\Helpers\Journal\JournalInterval;
use Remp\BeamModule\Model\Config\Config;
use Remp\BeamModule\Model\Config\ConfigCategory;
use Remp\BeamModule\Model\Config\ConfigNames;
use Remp\BeamModule\Model\Property\SelectedProperty;
use Remp\BeamModule\Model\Config\ConversionRateConfig;
use Remp\BeamModule\Model\Snapshots\SnapshotHelpers;
use Carbon\Carbon;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use InvalidArgumentException;
use Log;
use Remp\Journal\AggregateRequest;
use Remp\Journal\ConcurrentsRequest;
use Remp\Journal\JournalContract;
use Remp\Journal\JournalException;
class DashboardController extends Controller
{
private const NUMBER_OF_ARTICLES = 30;
private $journal;
private $journalHelper;
private $snapshotHelpers;
private $selectedProperty;
public function __construct(
JournalContract $journal,
SnapshotHelpers $snapshotHelpers,
SelectedProperty $selectedProperty,
) {
$this->journal = $journal;
$this->journalHelper = new JournalHelpers($journal);
$this->snapshotHelpers = $snapshotHelpers;
$this->selectedProperty = $selectedProperty;
}
public function index()
{
return $this->dashboardView('beam::dashboard.index');
}
public function public()
{
return $this->dashboardView('beam::dashboard.public');
}
private function dashboardView($template)
{
$conversionRateConfig = ConversionRateConfig::build();
$data = [
'options' => $this->options(),
'conversionRateMultiplier' => $conversionRateConfig->getMultiplier(),
];
if (!config('beam.disable_token_filtering')) {
$data['accountPropertyTokens'] = $this->selectedProperty->selectInputData();
}
$externalEvents = [];
try {
foreach ($this->journalHelper->eventsCategoriesActions() as $item) {
$externalEvents[] = (object) [
'text' => $item->category . ':' . $item->action,
'value' => $item->category . JournalHelpers::CATEGORY_ACTION_SEPARATOR . $item->action,
];
}
} catch (JournalException | ClientException | RequestException $exception) {
// if Journal is down, do not crash, but allowed page to be rendered (so user can switch to other page)
Log::error($exception->getMessage());
}
$data['externalEvents'] = $externalEvents;
return view($template, $data);
}
public function options(): array
{
$options = [];
foreach (Config::ofCategory(ConfigCategory::CODE_DASHBOARD)->get() as $config) {
$options[$config->name] = Config::loadByName($config->name);
}
// Additional options
$options['dashboard_frontpage_referer_of_properties'] = array_values(Config::loadAllPropertyConfigs(ConfigNames::DASHBOARD_FRONTPAGE_REFERER));
$options['article_traffic_graph_show_interval_7d'] = config('beam.article_traffic_graph_show_interval_7d');
$options['article_traffic_graph_show_interval_30d'] = config('beam.article_traffic_graph_show_interval_30d');
return $options;
}
private function getJournalParameters($interval, $tz)
{
switch ($interval) {
case 'today':
return [Carbon::tomorrow($tz), Carbon::today($tz), '20m', 20];
case '7days':
return [Carbon::tomorrow($tz), Carbon::today($tz)->subDays(6), '1h', 60];
case '30days':
return [Carbon::tomorrow($tz), Carbon::today($tz)->subDays(29), '2h', 120];
default:
throw new InvalidArgumentException("Parameter 'interval' must be one of the [today,7days,30days] values, instead '$interval' provided");
}
}
/**
* Return the time histogram for articles.
*
* Note: This action is cached. To improve response time especially for
* longer time intervals and first request, consider to preheat cache
* by calling this action from CLI command.
*
* @param Request $request
*
* @return \Illuminate\Http\JsonResponse
*/
public function timeHistogramNew(Request $request)
{
$request->validate([
'tz' => 'timezone',
'interval' => 'required|in:today,7days,30days',
'settings.compareWith' => 'required|in:last_week,average'
]);
$settings = $request->get('settings');
$tz = new \DateTimeZone($request->get('tz', 'UTC'));
$interval = $request->get('interval');
$journalInterval = new JournalInterval($tz, $interval, null, ['today', '7days', '30days']);
$from = $journalInterval->timeAfter;
$to = $journalInterval->timeBefore;
// for today histogram we need data not older than 1 minute
if ($interval === 'today') {
$journalInterval->cacheTTL = 60;
}
$toNextDayStart = (clone $to)->tz($tz)->addDay()->startOfDay();
$intervalMinutes = $journalInterval->intervalMinutes;
$currentData = $this->snapshotHelpers->concurrentsHistogram($journalInterval, null, true);
$tags = [];
foreach ($currentData as $item) {
$tags[$this->itemTag($item)] = true;
}
// Compute shadow values for today and 7-days intervals
$shadowRecords = [];
if ($interval !== '30days') {
$numberOfAveragedWeeks = $settings['compareWith'] === 'average' ? 4 : 1;
for ($i = 1; $i <= $numberOfAveragedWeeks; $i++) {
$shadowFrom = (clone $from)->subWeeks($i);
$shadowTo = $toNextDayStart->copy()->subWeeks($i);
// If there was a time shift, remember time needs to be adjusted by the timezone difference
$diff = $shadowFrom->diff($from);
$hourDifference = $diff->invert === 0 ? $diff->h : - $diff->h;
$shadowInterval = clone $journalInterval;
$shadowInterval->timeAfter = $shadowFrom;
$shadowInterval->timeBefore = $shadowTo;
// shadow values could be cached for 24 hours
$shadowInterval->cacheTTL = 86400;
foreach ($this->snapshotHelpers->concurrentsHistogram($shadowInterval) as $item) {
// we want to plot previous results on same points as current ones,
// therefore add week which was subtracted when data was queried
$correctedDate = Carbon::parse($item->time)
->addWeeks($i)
->addHours($hourDifference);
if ($correctedDate->lt($from) || $correctedDate->gt($toNextDayStart)) {
// some days might be longer (e.g. time-shift)
// therefore we do want to map all values to current week
// and avoid those which aren't
continue;
}
$correctedDate = $correctedDate->toIso8601ZuluString();
$currentTag = $this->itemTag($item);
$tags[$currentTag] = true;
if (!array_key_exists($correctedDate, $shadowRecords)) {
$shadowRecords[$correctedDate] = [];
}
if (!array_key_exists($currentTag, $shadowRecords[$correctedDate])) {
$shadowRecords[$correctedDate][$currentTag] = collect();
}
$shadowRecords[$correctedDate][$currentTag]->push($item->count);
}
}
// Shadow records might not be in the correct order (if some key is missing from particular week, it's added at the end)
// therefore reorder
ksort($shadowRecords);
}
// Get tags
$tags = array_keys($tags);
$emptyValues = [];
$totalTagCounts = [];
foreach ($tags as $tag) {
$emptyValues[$tag] = 0;
$totalTagCounts[$tag] = 0;
}
$results = [];
$shadowResults = [];
$shadowResultsSummed = [];
// Save current results
foreach ($currentData as $item) {
$zuluTime = Carbon::parse($item->time)->toIso8601ZuluString();
if (!array_key_exists($zuluTime, $results)) {
$results[$zuluTime] = array_merge($emptyValues, ['Date' => $zuluTime]);
}
$tag = $this->itemTag($item);
$results[$zuluTime][$tag] += $item->count;
$totalTagCounts[$tag] += $item->count;
}
// Save shadow results
foreach ($shadowRecords as $date => $tagsAndValues) {
foreach ($tagsAndValues as $tag => $values) {
if (!array_key_exists($date, $shadowResults)) {
$shadowResults[$date] = $emptyValues;
$shadowResults[$date]['Date'] = $date;
}
if (!array_key_exists($date, $shadowResultsSummed)) {
$shadowResultsSummed[$date]['Date'] = $date;
$shadowResultsSummed[$date]['value'] = 0;
}
$avg = (int) round($values->avg());
$shadowResults[$date][$tag] = $avg;
$shadowResultsSummed[$date]['value'] += $avg;
}
}
$orderedTags = Colors::orderRefererMediumTags($totalTagCounts);
$jsonResponse = [
'results' => array_values($results),
'previousResults' => array_values($shadowResults),
'previousResultsSummed' => array_values($shadowResultsSummed),
'intervalMinutes' => $intervalMinutes,
'tags' => $orderedTags,
'colors' => array_values(Colors::assignColorsToMediumRefers($orderedTags)),
'events' => $this->loadExternalEvents($journalInterval, $request->get('externalEvents', []))
];
if ($interval === 'today') {
$jsonResponse['maxDate'] = $toNextDayStart->toIso8601ZuluString();
}
return response()->json($jsonResponse);
}
private function itemTag($item): string
{
return $this->journalHelper->refererMediumLabel($item->referer_medium);
}
private function getRefererMediumFromJournalRecord($record)
{
return $this->journalHelper->refererMediumLabel($record->tags->derived_referer_medium);
}
public function timeHistogram(Request $request)
{
$request->validate([
'tz' => 'timezone',
'interval' => 'required|in:today,7days,30days',
'settings.compareWith' => 'required|in:last_week,average'
]);
$settings = $request->get('settings');
$tz = new \DateTimeZone($request->get('tz', 'UTC'));
$interval = $request->get('interval');
[$timeBefore, $timeAfter, $intervalText, $intervalMinutes] = $this->getJournalParameters($interval, $tz);
$endOfDay = (clone $timeAfter)->tz($tz)->endOfDay();
$journalRequest = new AggregateRequest('pageviews', 'load');
$journalRequest->setTimeAfter($timeAfter);
$journalRequest->setTimeBefore($timeBefore);
$journalRequest->setTimeHistogram($intervalText);
$journalRequest->addGroup('derived_referer_medium');
$currentRecords = collect($this->journal->count($journalRequest));
// Get all tags
$tags = [];
$totalCounts = [];
foreach ($currentRecords as $record) {
$tag = $this->getRefererMediumFromJournalRecord($record);
$totalCounts[$tag] = 0;
$tags[$tag] = true;
}
// Compute shadow values for today and 7-days intervals
$shadowRecords = [];
if ($interval !== '30days') {
$numberOfAveragedWeeks = $settings['compareWith'] === 'average' ? 4 : 1;
for ($i = 1; $i <= $numberOfAveragedWeeks; $i++) {
$from = (clone $timeAfter)->subWeeks($i);
$to = (clone $timeBefore)->subWeeks($i);
// If there was a time shift, remember time needs to be adjusted by the timezone difference
$diff = $from->diff($timeAfter);
$hourDifference = $diff->invert === 0 ? $diff->h : - $diff->h;
foreach ($this->pageviewRecordsBasedOnRefererMedium($from, $to, $intervalText) as $record) {
$currentTag = $this->getRefererMediumFromJournalRecord($record);
// update tags
$tags[$currentTag] = true;
if (!isset($record->time_histogram)) {
continue;
}
foreach ($record->time_histogram as $timeValue) {
// we want to plot previous results on same points as current ones,
// therefore add week which was subtracted when data was queried
$correctedDate = Carbon::parse($timeValue->time)
->addWeeks($i)
->addHours($hourDifference)
->toIso8601ZuluString();
if (!array_key_exists($correctedDate, $shadowRecords)) {
$shadowRecords[$correctedDate] = [];
}
if (!array_key_exists($currentTag, $shadowRecords[$correctedDate])) {
$shadowRecords[$correctedDate][$currentTag] = collect();
}
$shadowRecords[$correctedDate][$currentTag]->push($timeValue->value);
}
}
}
}
$tags = array_keys($tags);
// Values might be missing in time histogram, therefore fill all tags with 0s by default
$results = [];
$shadowResults = [];
$shadowResultsSummed = [];
$timeIterator = JournalHelpers::getTimeIterator($timeAfter, $intervalMinutes);
$emptyValues = collect($tags)->mapWithKeys(function ($item) {
return [$item => 0];
})->toArray();
while ($timeIterator->lessThan($timeBefore)) {
$zuluDate = $timeIterator->toIso8601ZuluString();
$results[$zuluDate] = $emptyValues;
$results[$zuluDate]['Date'] = $zuluDate;
if (count($shadowRecords) > 0) {
$shadowResults[$zuluDate] = $emptyValues;
$shadowResults[$zuluDate]['Date'] = $shadowResultsSummed[$zuluDate]['Date'] = $zuluDate;
$shadowResultsSummed[$zuluDate]['value'] = 0;
}
$timeIterator->addMinutes($intervalMinutes);
}
// Save current results
foreach ($currentRecords as $record) {
if (!isset($record->time_histogram)) {
continue;
}
$currentTag = $this->getRefererMediumFromJournalRecord($record);
foreach ($record->time_histogram as $timeValue) {
$results[$timeValue->time][$currentTag] = $timeValue->value;
}
$totalCounts[$currentTag] += $record->count;
}
// Save shadow results
foreach ($shadowRecords as $date => $tagsAndValues) {
// check if all keys exists - e.g. some days might be longer (time-shift)
// therefore we do want to map all values to current week
if (!array_key_exists($date, $shadowResults)) {
continue;
}
foreach ($tagsAndValues as $tag => $values) {
$avg = (int) round($values->avg());
$shadowResults[$date][$tag] = $avg;
$shadowResultsSummed[$date]['value'] += $avg;
}
}
// What part of current results we should draw (omit future 0 values)
$numberOfCurrentValues = (int) floor((Carbon::now($tz)->getTimestamp() - $timeAfter->getTimestamp()) / ($intervalMinutes * 60));
if ($interval === 'today') {
// recompute last interval - it's not fully loaded, yet we want at least partial results
// to see the current traffic
$results = collect(array_values($results))->take($numberOfCurrentValues + 1);
$unfinished = $results->pop();
$unfinishedDate = Carbon::parse($unfinished['Date']);
$current = Carbon::now();
// if recent interval is bigger than 120 seconds, recompute its values and add it back to results
// smaller intervals do not make good approximations
if ((clone $current)->subSeconds(120)->gt($unfinishedDate)) {
$increaseRate = ($intervalMinutes * 60) / ($current->getTimestamp() - $unfinishedDate->getTimestamp());
foreach ($tags as $tag) {
$unfinished[$tag] = (int)($unfinished[$tag] * $increaseRate);
}
$unfinished['Date'] = $current->subMinutes($intervalMinutes)->toIso8601ZuluString();
$unfinished['_unfinished'] = true;
$results->push($unfinished);
}
} else {
$results = collect(array_values($results))->take($numberOfCurrentValues);
}
$events = $this->loadExternalEvents(new JournalInterval($tz, $interval, null, ['today', '7days', '30days']), $request->get('externalEvents', []));
$orderedTags = Colors::orderRefererMediumTags($totalCounts);
$jsonResponse = [
'intervalMinutes' => $intervalMinutes,
'results' => $results,
'previousResults' => array_values($shadowResults),
'previousResultsSummed' => array_values($shadowResultsSummed),
'tags' => $orderedTags,
'colors' => array_values(Colors::assignColorsToMediumRefers($orderedTags)),
'events' => $events,
];
if ($interval === 'today') {
$jsonResponse['maxDate'] = $endOfDay->subMinutes($intervalMinutes)->toIso8601ZuluString();
}
return response()->json($jsonResponse);
}
private function pageviewRecordsBasedOnRefererMedium(
Carbon $timeAfter,
Carbon $timeBefore,
string $interval
) {
$journalRequest = new AggregateRequest('pageviews', 'load');
$journalRequest->setTimeAfter($timeAfter);
$journalRequest->setTimeBefore($timeBefore);
$journalRequest->setTimeHistogram($interval);
$journalRequest->addGroup('derived_referer_medium');
return collect($this->journal->count($journalRequest));
}
private function loadExternalEvents(JournalInterval $journalInterval, $requestedExternalEvents): array
{
$eventData = $this->journalHelper->loadEvents($journalInterval, $requestedExternalEvents);
$tags = [];
$articles = [];
$events = [];
foreach ($eventData as $eventItem) {
$title = $eventItem->category . ':' . $eventItem->action;
$tags[$title] = true;
$date = Carbon::parse($eventItem->system->time);
$text = "<b>$title</b><br />" .
'At: ' . $date->copy()->tz($journalInterval->tz)->format('Y-m-d H:i');
if (isset($eventItem->article_id)) {
$article = $articles[$eventItem->article_id] ?? null;
if (!$article) {
$article = Article::where('external_id', $eventItem->article_id)->first();
}
if ($article) {
$articles[$eventItem->article_id] = $article;
$url = route('articles.show', $article->id);
$articleTitle = Str::limit($article->title, 50);
$text .= '<br />Article: <a style="text-decoration: underline; color: #fff" href="'. $url .'">' . $articleTitle . '</b>';
}
}
$events[] = (object) [
'date' => $date->toIso8601ZuluString(),
'id' => $title,
'title' => $text,
];
}
$colors = Colors::assignColorsToGeneralTags(array_keys($tags));
foreach ($events as $event) {
$event->color = $colors[$event->id];
}
return $events;
}
public function mostReadArticles(Request $request)
{
$request->validate([
'settings.onlyTrafficFromFrontPage' => 'required|boolean'
]);
$settings = $request->get('settings');
$timeBefore = Carbon::now();
$frontpageReferers = (array) Config::loadByName(ConfigNames::DASHBOARD_FRONTPAGE_REFERER);
if (!$frontpageReferers) {
$frontpageReferers = array_values(Config::loadAllPropertyConfigs(ConfigNames::DASHBOARD_FRONTPAGE_REFERER));
}
$filterFrontPage = $frontpageReferers && $settings['onlyTrafficFromFrontPage'];
// records are already sorted
$records = $this->journalHelper->currentConcurrentsCount(function (ConcurrentsRequest $req) use ($filterFrontPage, $frontpageReferers) {
$req->addGroup('article_id', 'canonical_url');
if ($filterFrontPage) {
$req->addFilter('derived_referer_host_with_path', ...$frontpageReferers);
}
}, $timeBefore);
$computerConcurrents = $this->journalHelper->currentConcurrentsCount(function (ConcurrentsRequest $req) use ($filterFrontPage, $frontpageReferers) {
$req->addFilter('derived_ua_device', 'Computer');
if ($filterFrontPage) {
$req->addFilter('derived_referer_host_with_path', ...$frontpageReferers);
}
}, $timeBefore);
$computerConcurrentsCount = $computerConcurrents->first()->count;
$articlesIds = array_filter($records->pluck('tags.article_id')->toArray());
$articleQuery = Article::with(['dashboardArticle', 'conversions'])
->whereIn(
'external_id',
array_map('strval', $articlesIds)
);
$articles = [];
foreach ($articleQuery->get() as $article) {
$articles[$article->external_id] = $article;
}
$topPages = [];
$articleCounter = 0;
$totalConcurrents = 0;
foreach ($records as $record) {
$totalConcurrents += $record->count;
if ($articleCounter >= self::NUMBER_OF_ARTICLES) {
continue;
}
$article = null;
if ($record->tags->article_id) {
// check if the article is recognized
$article = $articles[$record->tags->article_id] ?? null;
if (!$article) {
continue;
}
$key = $record->tags->article_id;
} else {
$key = $record->tags->canonical_url ?? '';
}
// Some articles might have multiple canonical URLs. Merge them.
if (isset($topPages[$key])) {
$obj = $topPages[$key];
$obj->count += $record->count;
} else {
$obj = new \stdClass();
$obj->count = $record->count;
$obj->external_article_id = $record->tags->article_id;
if ($record->tags->article_id) {
$articleCounter++;
}
}
if ($article) {
$obj->landing_page = false;
$obj->title = $article->title;
$obj->published_at = $article->published_at->toAtomString();
$obj->conversions_count = (clone $article)->conversions->count();
$obj->article = $article;
} else {
$obj->title = $record->tags->canonical_url ?: 'Landing page / Other pages';
$obj->landing_page = true;
}
$topPages[$key] = $obj;
}
$mobileConcurrentsPercentage = 0;
if ($totalConcurrents > 0 && $computerConcurrentsCount > 0) {
$mobileConcurrentsPercentage = (($totalConcurrents - $computerConcurrentsCount) / $totalConcurrents) * 100;
} elseif ($totalConcurrents > 0 && $computerConcurrentsCount === 0) {
$mobileConcurrentsPercentage = null;
}
usort($topPages, function ($a, $b) {
return -($a->count <=> $b->count);
});
$topPages = array_slice($topPages, 0, 30);
// Add chart data into top articles
$tz = new \DateTimeZone('UTC');
$journalInterval = new JournalInterval($tz, '1day');
$topPages = $this->addOverviewChartData($topPages, $journalInterval);
$topArticles = collect($topPages)->filter(function ($item) {
return !empty($item->external_article_id);
})->pluck('article');
$this->updateDasboardArticle($topArticles);
$externalIdsToUniqueUsersCount = $this->getUniqueBrowserCountData($topArticles);
// Timespent is computed as average of timespent values 2 hours in the past
$externalIdsToTimespent = $this->journalHelper->timespentForArticles(
$topArticles,
(clone $timeBefore)->subHours(2)
);
// Check for A/B titles/images for last 5 minutes
$externalIdsToAbTestFlags = $this->journalHelper->abTestFlagsForArticles($topArticles, Carbon::now()->subMinutes(5));
$conversionRateConfig = ConversionRateConfig::build();
$threeMonthsAgo = Carbon::now()->subMonths(3);
foreach ($topPages as $item) {
if ($item->external_article_id) {
$secondsTimespent = $externalIdsToTimespent->get($item->external_article_id, 0);
$item->avg_timespent_string = $secondsTimespent >= 3600 ?
gmdate('H:i:s', $secondsTimespent) :
gmdate('i:s', $secondsTimespent);
$item->unique_browsers_count = $externalIdsToUniqueUsersCount[$item->external_article_id];
// Show conversion rate only for articles published in last 3 months
if ($item->conversions_count !== 0 && $item->article->published_at->gte($threeMonthsAgo)) {
$item->conversion_rate = Article::computeConversionRate($item->conversions_count, $item->unique_browsers_count, $conversionRateConfig);
}
$item->has_title_test = $externalIdsToAbTestFlags[$item->external_article_id]->has_title_test ?? false;
$item->has_image_test = $externalIdsToAbTestFlags[$item->external_article_id]->has_image_test ?? false;
$item->url = route('articles.show', ['article' => $item->article->id]);
}
}
return response()->json([
'articles' => $topPages,
'mobileConcurrentsPercentage' => $mobileConcurrentsPercentage,
'totalConcurrents' => $totalConcurrents,
]);
}
private function updateDasboardArticle(Collection $articles)
{
$articleIds = $articles->pluck('id')->toArray();
$dashboardArticles = DashboardArticle::whereIn('article_id', $articleIds)->get();
$storedDashboardArticles = array_intersect($articleIds, $dashboardArticles->pluck('article_id')->toArray());
if ($storedDashboardArticles) {
DashboardArticle::whereIn('article_id', $storedDashboardArticles)
->update(['last_dashboard_time' => Carbon::now()]);
}
$unstoredDashboardArticles = array_diff($articleIds, $storedDashboardArticles);
if ($unstoredDashboardArticles) {
$data = [];
$now = Carbon::now();
foreach ($unstoredDashboardArticles as $articleId) {
$data[] = [
'article_id' => $articleId,
'last_dashboard_time' => $now,
'created_at' => $now,
];
}
DashboardArticle::insert($data);
}
}
/**
* @param \stdClass[] $topPages
* @param JournalInterval $journalInterval
* @return \stdClass[]
* @throws \Exception
*/
private function addOverviewChartData(array $topPages, JournalInterval $journalInterval)
{
$articleIds = array_filter(Arr::pluck($topPages, 'article.external_id'));
//no articles present in the topPages
if (empty($articleIds)) {
return $topPages;
}
$currentDataSource = config('beam.pageview_graph_data_source');
switch ($currentDataSource) {
case 'snapshots':
$articlesChartData = $this->getOverviewChartDataFromSnapshots($articleIds, $journalInterval);
break;
case 'journal':
$articlesChartData = $this->getOverviewChartDataFromJournal($articleIds, $journalInterval);
break;
default:
throw new \Exception("unknown pageviews data source {$currentDataSource}");
}
//add chart data into topPages object
$topPages = array_map(function ($topPage) use ($articlesChartData) {
if (!isset($topPage->article) || !isset($articlesChartData[$topPage->article->external_id])) {
return $topPage;
}
$topPage->chartData = $articlesChartData[$topPage->article->external_id];
return $topPage;
}, $topPages);
return $topPages;
}
private function getOverviewChartDataFromSnapshots(array $articleIds, JournalInterval $journalInterval)
{
$records = $this->snapshotHelpers->concurrentArticlesHistograms($journalInterval, $articleIds);
$recordsByArticleId = $records->groupBy('external_article_id');
$resultsSkeleton = $this->prefillOverviewResults($journalInterval);
$articlesChartData = [];
// use zero-value timePoints as a base so we don't need to worry about missing snapshot values later
$articleSkeleton = $this->createArticleSkeleton($resultsSkeleton);
foreach ($recordsByArticleId as $articleId => $items) {
$timePointToMatch = reset($resultsSkeleton)['Date'];
$results = $articleSkeleton;
foreach ($items as $item) {
if ($item->timestamp < $resultsSkeleton[$timePointToMatch]['Timestamp']) {
// skip all the data items earlier that the current $timePoint
continue;
}
// move $timePoint iterator forward until it matches item's timestamp
do {
$timePointToSet = $timePointToMatch;
$timePointToMatch = next($resultsSkeleton)['Date'] ?? null;
} while ($timePointToMatch && $item->timestamp >= $resultsSkeleton[$timePointToMatch]['Timestamp']);
// found the $timePoint, set the snapshot value
$results[$timePointToSet] = [
't' => $resultsSkeleton[$timePointToSet]['Timestamp'],
'c' => (int) $item->count,
];
if (!$timePointToMatch) {
break;
}
}
$articlesChartData[$articleId] = array_values($results);
}
return $articlesChartData;
}
private function getUniqueBrowserCountData(Collection $articles): array
{
$articles = (clone $articles)->keyBy('external_id');
$result = [];
/** @var Article $article */
foreach ($articles as $article) {
if ($article->dashboardArticle && $article->dashboardArticle->unique_browsers) {
$result[$article->external_id] = $article->dashboardArticle->unique_browsers;
$articles->forget($article->external_id);
}
}
// Check if we have stats for all articles. If we do, return immediately.
if (!$articles->count()) {
return $result;
}
// If some articles are missing the stats, make the realtime call.
$realtimeResults = $this->journalHelper->uniqueBrowsersCountForArticles($articles);
foreach ($realtimeResults as $externalArticleId => $count) {
/** @var Article $article */
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | true |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Http/Controllers/Api/v1/AuthorController.php | Beam/extensions/beam-module/src/Http/Controllers/Api/v1/AuthorController.php | <?php
namespace Remp\BeamModule\Http\Controllers\Api\v1;
use Remp\BeamModule\Http\Requests\Api\v1\TopAuthorsSearchRequest;
use Remp\BeamModule\Model\Pageviews\Api\v1\TopSearch;
class AuthorController
{
public function topAuthors(TopAuthorsSearchRequest $request, TopSearch $topSearch)
{
return response()->json($topSearch->topAuthors($request));
}
}
| 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/Api/v1/JournalController.php | Beam/extensions/beam-module/src/Http/Controllers/Api/v1/JournalController.php | <?php
namespace Remp\BeamModule\Http\Controllers\Api\v1;
use Remp\BeamModule\Helpers\Journal\JournalHelpers;
use Remp\BeamModule\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Remp\Journal\ConcurrentsRequest;
use Remp\Journal\JournalContract;
class JournalController extends Controller
{
private $journal;
private $journalHelpers;
public function __construct(JournalContract $journalContract)
{
$this->journal = $journalContract;
$this->journalHelpers = new JournalHelpers($journalContract);
}
public function flags()
{
return $this->journal->flags();
}
public function actions($group, $category)
{
return collect($this->journal->actions($group, $category));
}
public function articlesConcurrentsCount(Request $request)
{
$externalIds = (array) $request->input('external_id', []);
$urls = (array) $request->input('url', []);
if (!$externalIds && !$urls) {
abort(400, 'Please specify either external_id(s) or url(s) parameters');
}
$records = $this->journalHelpers->currentConcurrentsCount(function (ConcurrentsRequest $r) use ($externalIds, $urls) {
if (count($externalIds) > 0) {
$r->addFilter('article_id', ...$externalIds);
$r->addGroup('article_id');
}
if (count($urls) > 0) {
$r->addFilter('url', ...$urls);
$r->addGroup('url');
}
});
$articles = [];
foreach ($records as $record) {
$obj = [
'count' => $record->count,
];
if (isset($record->tags->article_id)) {
$obj['external_id'] = $record->tags->article_id;
}
if (isset($record->tags->url)) {
$obj['url'] = $record->tags->url;
}
$articles[] = $obj;
}
return response()->json([
'articles' => $articles,
]);
}
public function concurrentsCount()
{
$records = $this->journalHelpers->currentConcurrentsCount();
return response()->json([
'total' => $records->sum('count'),
]);
}
}
| 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/Api/v1/ArticleController.php | Beam/extensions/beam-module/src/Http/Controllers/Api/v1/ArticleController.php | <?php
namespace Remp\BeamModule\Http\Controllers\Api\v1;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Log;
use Remp\BeamModule\Helpers\Misc;
use Remp\BeamModule\Http\Requests\Api\v1\ArticleUpsertRequest;
use Remp\BeamModule\Http\Requests\Api\v1\ReadArticlesRequest;
use Remp\BeamModule\Http\Requests\Api\v1\TopArticlesSearchRequest;
use Remp\BeamModule\Http\Requests\Api\v1\UnreadArticlesRequest;
use Remp\BeamModule\Http\Resources\ArticleResource;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Author;
use Remp\BeamModule\Model\Newsletter\NewsletterCriterionEnum;
use Remp\BeamModule\Model\NewsletterCriterion;
use Remp\BeamModule\Model\Pageviews\Api\v1\TopSearch;
use Remp\BeamModule\Model\Section;
use Remp\BeamModule\Model\Tag;
use Remp\Journal\AggregateRequest;
use Remp\Journal\JournalContract;
use Remp\Journal\ListRequest;
class ArticleController
{
public function topArticles(TopArticlesSearchRequest $request, TopSearch $topSearch)
{
return response()->json($topSearch->topArticles($request));
}
public function upsert(ArticleUpsertRequest $request)
{
Log::info('Upserting articles', ['params' => $request->json()->all()]);
$articles = [];
foreach ($request->get('articles', []) as $a) {
// When saving to DB, Eloquent strips timezone information,
// therefore convert to UTC
$a['published_at'] = Carbon::parse($a['published_at']);
$a['content_type'] = $a['content_type'] ?? Article::DEFAULT_CONTENT_TYPE;
$article = Article::updateOrCreate(
['external_id' => $a['external_id']],
$a
);
$article->sections()->detach();
foreach ($a['sections'] ?? [] as $sectionName) {
$section = Section::firstOrCreate([
'name' => $sectionName,
]);
$article->sections()->attach($section);
}
$article->tags()->detach();
foreach ($a['tags'] ?? [] as $tagName) {
$tag = Tag::firstOrCreate([
'name' => $tagName,
]);
$article->tags()->attach($tag);
}
$article->authors()->detach();
foreach ($a['authors'] as $authorName) {
$section = Author::firstOrCreate([
'name' => $authorName,
]);
$article->authors()->attach($section);
}
// Load existing titles
$existingArticleTitles = $article->articleTitles()
->orderBy('updated_at')
->get()
->groupBy('variant');
$lastTitles = [];
foreach ($existingArticleTitles as $variant => $variantTitles) {
$lastTitles[$variant] = $variantTitles->last()->title;
}
// Saving titles
$newTitles = $a['titles'] ?? [];
$newTitleVariants = array_keys($newTitles);
$lastTitleVariants = array_keys($lastTitles);
// Titles that were not present in new titles, but were previously recorded
foreach (array_diff($lastTitleVariants, $newTitleVariants) as $variant) {
$lastTitle = $lastTitles[$variant];
if ($lastTitle !== null) {
// title was deleted and it was not recorded yet
$article->articleTitles()->create([
'variant' => $variant,
'title' => null // deleted flag
]);
}
}
// New titles, not previously recorded
foreach (array_diff($newTitleVariants, $lastTitleVariants) as $variant) {
$newTitle = html_entity_decode($newTitles[$variant], ENT_QUOTES);
$article->articleTitles()->create([
'variant' => $variant,
'title' => $newTitle
]);
}
// Changed titles
foreach (array_intersect($newTitleVariants, $lastTitleVariants) as $variant) {
$lastTitle = $lastTitles[$variant];
$newTitle = html_entity_decode($newTitles[$variant], ENT_QUOTES);
if ($lastTitle !== $newTitle) {
$article->articleTitles()->create([
'variant' => $variant,
'title' => $newTitle
]);
}
}
$article->load(['authors', 'sections', 'tags']);
$articles[] = $article;
}
return response()->format([
'html' => redirect(route('articles.pageviews'))->with('success', 'Article created'),
'json' => ArticleResource::collection(collect($articles)),
]);
}
public function unreadArticlesForUsers(UnreadArticlesRequest $request, JournalContract $journal)
{
// Request with timespan 30 days typically takes about 50 seconds,
// therefore add some safe margin to request execution time
set_time_limit(120);
$articlesCount = $request->input('articles_count');
$timespan = $request->input('timespan');
$readArticlesTimespan = $request->input('read_articles_timespan');
$ignoreAuthors = $request->input('ignore_authors', []);
$ignoreContentTypes = $request->input('ignore_content_types', []);
$topArticlesPerCriterion = [];
/** @var NewsletterCriterion[] $criteria */
$criteria = [];
foreach ($request->input('criteria') as $criteriaString) {
$criteria[] = new NewsletterCriterion(NewsletterCriterionEnum::from($criteriaString));
$topArticlesPerCriterion[] = null;
}
$topArticlesPerUser = [];
$timeAfter = Misc::timespanInPast($timespan);
// If no read_articles_timespan is specified, check for week old read articles (past given timespan)
$readArticlesAfter = $readArticlesTimespan ? Misc::timespanInPast($readArticlesTimespan) : (clone $timeAfter)->subWeek();
$timeBefore = Carbon::now();
foreach (array_chunk($request->user_ids, 100) as $userIdsChunk) {
$usersReadArticles = $this->readArticlesForUsers($journal, $readArticlesAfter, $timeBefore, $userIdsChunk);
// Save top articles per user
foreach ($userIdsChunk as $userId) {
$topArticlesUrls = [];
$topArticlesUrlsOrdered = [];
$i = 0;
$criterionIndex = 0;
while (count($topArticlesUrls) < $articlesCount) {
if (!$topArticlesPerCriterion[$criterionIndex]) {
$criterion = $criteria[$criterionIndex];
$topArticlesPerCriterion[$criterionIndex] = $criterion->getCachedArticles($timespan, $ignoreAuthors, $ignoreContentTypes);
}
if ($i >= count($topArticlesPerCriterion[$criterionIndex])) {
if ($criterionIndex === count($criteria) - 1) {
break;
}
$criterionIndex++;
$i = 0;
continue;
}
$topArticle = $topArticlesPerCriterion[$criterionIndex][$i];
if ((!array_key_exists($userId, $usersReadArticles) || !array_key_exists($topArticle->external_id, $usersReadArticles[$userId]))
&& !array_key_exists($topArticle->url, $topArticlesUrls)) {
$topArticlesUrls[$topArticle->url] = true;
$topArticlesUrlsOrdered[] = $topArticle->url;
}
$i++;
}
$topArticlesPerUser[$userId] = $topArticlesUrlsOrdered;
}
}
return response()->json([
'status' => 'ok',
'data' => $topArticlesPerUser
]);
}
private function readArticlesForUsers(JournalContract $journal, Carbon $timeAfter, Carbon $timeBefore, array $userIds): array
{
$usersReadArticles = [];
$r = new AggregateRequest('pageviews', 'load');
$r->setTimeAfter($timeAfter);
$r->setTimeBefore($timeBefore);
$r->addGroup('user_id', 'article_id');
$r->addFilter('user_id', ...$userIds);
$result = collect($journal->count($r));
foreach ($result as $item) {
if ($item->tags->article_id !== '') {
$userId = $item->tags->user_id;
if (!array_key_exists($userId, $usersReadArticles)) {
$usersReadArticles[$userId] = [];
}
$usersReadArticles[$userId][$item->tags->article_id] = true;
}
}
return $usersReadArticles;
}
public function readArticles(ReadArticlesRequest $request, JournalContract $journal)
{
$from = $request->input('from');
$to = $request->input('to');
$userId = $request->input('user_id');
$browserId = $request->input('browser_id');
$r = new ListRequest('pageviews');
$r->addFilter('action', 'load');
$r->addGroup('user_id', 'browser_id', 'article_id', 'time');
if ($from) {
$r->setTimeAfter(Carbon::parse($from));
}
if ($to) {
$r->setTimeBefore(Carbon::parse($to));
}
if ($userId) {
$r->addFilter('user_id', $userId);
}
if ($browserId) {
$r->addFilter('browser_id', $browserId);
}
$articles = [];
$result = $journal->list($r);
foreach ($result as $item) {
if ($item->tags->article_id !== '') {
$articleId = $item->tags->article_id;
if (!array_key_exists($articleId, $articles)) {
$articles[$articleId] = $item->tags;
} else if (strtotime($articles[$articleId]->time) < strtotime($item->tags->time)) {
$articles[$articleId] = $item->tags;
}
}
}
// sort by time
uasort($articles, fn($a, $b) => strtotime($b->time) <=> strtotime($a->time));
return response()->json(array_values($articles));
}
}
| 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/Api/v1/TagController.php | Beam/extensions/beam-module/src/Http/Controllers/Api/v1/TagController.php | <?php
namespace Remp\BeamModule\Http\Controllers\Api\v1;
use Remp\BeamModule\Http\Requests\Api\v1\TopTagsSearchRequest;
use Remp\BeamModule\Model\Pageviews\Api\v1\TopSearch;
class TagController
{
public function topTags(TopTagsSearchRequest $request, TopSearch $topSearch)
{
return response()->json($topSearch->topPostTags($request));
}
}
| 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/Api/v1/PageviewController.php | Beam/extensions/beam-module/src/Http/Controllers/Api/v1/PageviewController.php | <?php
namespace Remp\BeamModule\Http\Controllers\Api\v1;
use Remp\BeamModule\Http\Requests\Api\v1\PageviewsTimeHistogramRequest;
use Remp\BeamModule\Model\Pageviews\Api\v1\TimeHistogram;
class PageviewController
{
public function timeHistogram(PageviewsTimeHistogramRequest $request, TimeHistogram $timeHistogram)
{
return response()->json($timeHistogram->getTimeHistogram($request));
}
}
| 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/Api/v2/AuthorController.php | Beam/extensions/beam-module/src/Http/Controllers/Api/v2/AuthorController.php | <?php
namespace Remp\BeamModule\Http\Controllers\Api\v2;
use Remp\BeamModule\Http\Requests\Api\v2\TopAuthorsSearchRequest;
use Remp\BeamModule\Model\Pageviews\Api\v2\TopSearch;
class AuthorController
{
public function topAuthors(TopAuthorsSearchRequest $request, TopSearch $topSearch)
{
return response()->json($topSearch->topAuthors($request));
}
}
| 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/Api/v2/ArticleController.php | Beam/extensions/beam-module/src/Http/Controllers/Api/v2/ArticleController.php | <?php
namespace Remp\BeamModule\Http\Controllers\Api\v2;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Author;
use Remp\BeamModule\Http\Requests\Api\v2\ArticleUpsertRequest;
use Remp\BeamModule\Http\Requests\Api\v2\TopArticlesSearchRequest;
use Remp\BeamModule\Http\Resources\ArticleResource;
use Remp\BeamModule\Model\Pageviews\Api\v2\TopSearch;
use Remp\BeamModule\Model\Tag;
use Remp\BeamModule\Model\Section;
use Remp\BeamModule\Model\TagCategory;
use Illuminate\Support\Carbon;
class ArticleController
{
public function topArticles(TopArticlesSearchRequest $request, TopSearch $topSearch)
{
return response()->json($topSearch->topArticles($request));
}
public function upsert(ArticleUpsertRequest $request)
{
$articles = [];
foreach ($request->get('articles', []) as $a) {
// When saving to DB, Eloquent strips timezone information,
// therefore convert to UTC
$a['published_at'] = Carbon::parse($a['published_at']);
$a['content_type'] = $a['content_type'] ?? Article::DEFAULT_CONTENT_TYPE;
$article = Article::updateOrCreate(
['external_id' => $a['external_id']],
$a
);
$article->sections()->detach();
foreach ($a['sections'] ?? [] as $section) {
$sectionObj = $this->upsertSection($section);
$article->sections()->attach($sectionObj);
}
$article->tags()->detach();
foreach ($a['tags'] ?? [] as $tag) {
$tagObj = $this->upsertTag($tag);
$article->tags()->attach($tagObj);
$tagObj->tagCategories()->detach();
foreach ($tag['categories'] ?? [] as $tagCategory) {
$tagCategoryObj = $this->upsertTagCategory($tagCategory);
$tagObj->tagCategories()->attach($tagCategoryObj);
}
}
$article->authors()->detach();
foreach ($a['authors'] ?? [] as $author) {
$authorObj = $this->upsertAuthor($author);
$article->authors()->attach($authorObj);
}
if (isset($a['titles']) && is_array($a['titles'])) {
// Load existing titles
$existingArticleTitles = $article->articleTitles()
->orderBy('updated_at')
->get()
->groupBy('variant');
$lastTitles = [];
foreach ($existingArticleTitles as $variant => $variantTitles) {
$lastTitles[$variant] = $variantTitles->last()->title;
}
// Saving titles
$newTitles = $a['titles'];
$newTitleVariants = array_keys($newTitles);
$lastTitleVariants = array_keys($lastTitles);
// Titles that were not present in new titles, but were previously recorded
foreach (array_diff($lastTitleVariants, $newTitleVariants) as $variant) {
$lastTitle = $lastTitles[$variant];
if ($lastTitle !== null) {
// title was deleted and it was not recorded yet
$article->articleTitles()->create([
'variant' => $variant,
'title' => null // deleted flag
]);
}
}
// New titles, not previously recorded
foreach (array_diff($newTitleVariants, $lastTitleVariants) as $variant) {
$newTitle = html_entity_decode($newTitles[$variant], ENT_QUOTES);
$article->articleTitles()->create([
'variant' => $variant,
'title' => $newTitle
]);
}
// Changed titles
foreach (array_intersect($newTitleVariants, $lastTitleVariants) as $variant) {
$lastTitle = $lastTitles[$variant];
$newTitle = html_entity_decode($newTitles[$variant], ENT_QUOTES);
if ($lastTitle !== $newTitle) {
$article->articleTitles()->create([
'variant' => $variant,
'title' => $newTitle
]);
}
}
}
$article->load(['authors', 'sections', 'tags', 'tags.tagCategories']);
$articles[] = $article;
}
return response()->format([
'html' => redirect(route('articles.pageviews'))->with('success', 'Article created'),
'json' => ArticleResource::collection(collect($articles)),
]);
}
private function upsertSection($section): Section
{
$sectionObj = Section::where('external_id', $section['external_id'])->first();
if ($sectionObj) {
$sectionObj->update($section);
return $sectionObj;
}
$sectionObj = Section::where('name', $section['name'])->first();
if ($sectionObj && $sectionObj->external_id === null) {
$sectionObj->update($section);
return $sectionObj;
}
return Section::firstOrCreate($section);
}
private function upsertTag($tag): Tag
{
$tagObj = Tag::where('external_id', $tag['external_id'])->first();
if ($tagObj) {
$tagObj->name = $tag['name'];
$tagObj->save();
return $tagObj;
}
$tagObj = Tag::where('name', $tag['name'])->first();
if ($tagObj && $tagObj->external_id === null) {
$tagObj->external_id = $tag['external_id'];
$tagObj->save();
return $tagObj;
}
return Tag::firstOrCreate([
'name' => $tag['name'],
'external_id' => $tag['external_id'],
]);
}
private function upsertTagCategory($tagCategory): TagCategory
{
$tagCategoryObj = TagCategory::where('external_id', $tagCategory['external_id'])->first();
if ($tagCategoryObj) {
$tagCategoryObj->update($tagCategory);
return $tagCategoryObj;
}
$tagCategoryObj = TagCategory::where('name', $tagCategory['name'])->first();
if ($tagCategoryObj && $tagCategoryObj->external_id === null) {
$tagCategoryObj->update($tagCategory);
return $tagCategoryObj;
}
return TagCategory::firstOrCreate($tagCategory);
}
private function upsertAuthor($author): Author
{
$authorObj = Author::where('external_id', $author['external_id'])->first();
if ($authorObj) {
$authorObj->update($author);
return $authorObj;
}
$authorObj = Author::where('name', $author['name'])->first();
if ($authorObj && $authorObj->external_id === null) {
$authorObj->update($author);
return $authorObj;
}
return Author::firstOrCreate($author);
}
}
| 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/Api/v2/TagController.php | Beam/extensions/beam-module/src/Http/Controllers/Api/v2/TagController.php | <?php
namespace Remp\BeamModule\Http\Controllers\Api\v2;
use Remp\BeamModule\Http\Requests\Api\v2\TopTagsSearchRequest;
use Remp\BeamModule\Model\Pageviews\Api\v2\TopSearch;
class TagController
{
public function topTags(TopTagsSearchRequest $request, TopSearch $topSearch)
{
return response()->json($topSearch->topPostTags($request));
}
}
| 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/Middleware/DashboardBasicAuth.php | Beam/extensions/beam-module/src/Http/Middleware/DashboardBasicAuth.php | <?php
namespace Remp\BeamModule\Http\Middleware;
use Closure;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
class DashboardBasicAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
*
* @return mixed
* @throws \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException
*/
public function handle($request, Closure $next)
{
// temporarily support 2 passwords
$credentials = [
config('dashboard.username') => config('dashboard.password'),
config('dashboard.username2') => config('dashboard.password2'),
];
unset($credentials[null]);
unset($credentials['']);
if (array_key_exists($request->getUser(), $credentials)
&& $credentials[$request->getUser()] === $request->getPassword()) {
return $next($request);
}
throw new UnauthorizedHttpException('Basic', 'Invalid credentials.');
}
}
| 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/Resources/EntityResource.php | Beam/extensions/beam-module/src/Http/Resources/EntityResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Remp\LaravelHelpers\Resources\JsonResource;
class EntityResource extends JsonResource
{
}
| 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/Resources/ConfigResource.php | Beam/extensions/beam-module/src/Http/Resources/ConfigResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Remp\LaravelHelpers\Resources\JsonResource;
class ConfigResource extends JsonResource
{
}
| 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/Resources/TagCategoryResource.php | Beam/extensions/beam-module/src/Http/Resources/TagCategoryResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Remp\LaravelHelpers\Resources\JsonResource;
class TagCategoryResource extends JsonResource
{
}
| 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/Resources/AuthorResource.php | Beam/extensions/beam-module/src/Http/Resources/AuthorResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Remp\LaravelHelpers\Resources\JsonResource;
class AuthorResource extends JsonResource
{
}
| 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/Resources/ConversionResource.php | Beam/extensions/beam-module/src/Http/Resources/ConversionResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Remp\LaravelHelpers\Resources\JsonResource;
class ConversionResource extends JsonResource
{
public function toArray($request)
{
$values = parent::toArray($request);
$values['article_external_id'] = $this->article->external_id;
return $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/Http/Resources/TagResource.php | Beam/extensions/beam-module/src/Http/Resources/TagResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Remp\LaravelHelpers\Resources\JsonResource;
class TagResource extends JsonResource
{
}
| 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/Resources/SectionResource.php | Beam/extensions/beam-module/src/Http/Resources/SectionResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Remp\LaravelHelpers\Resources\JsonResource;
class SectionResource extends JsonResource
{
}
| 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/Resources/ArticleSearchResource.php | Beam/extensions/beam-module/src/Http/Resources/ArticleSearchResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Remp\BeamModule\Model\Article;
use Remp\LaravelHelpers\Resources\JsonResource;
//use Illuminate\Http\Resources\Json\JsonResource;
/**
* Class ArticleSearchResource
*
* @mixin Article
* @package App\Http\Resources
*/
class ArticleSearchResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'type' => 'article',
'title' => $this->title,
'tags' => $this->tags->pluck('name'),
'sections' => $this->sections->pluck('name'),
'search_result_url' => route('articles.show', $this)
];
}
}
| 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/Resources/NewsletterResource.php | Beam/extensions/beam-module/src/Http/Resources/NewsletterResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Remp\LaravelHelpers\Resources\JsonResource;
class NewsletterResource extends JsonResource
{
}
| 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/Resources/AuthorSearchResource.php | Beam/extensions/beam-module/src/Http/Resources/AuthorSearchResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Remp\BeamModule\Model\Author;
use Remp\LaravelHelpers\Resources\JsonResource;
/**
* Class AuthorSearchResource
*
* @mixin Author
* @package App\Http\Resources
*/
class AuthorSearchResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'type' => 'author',
'name' => $this->name,
'search_result_url' => route('authors.show', $this)
];
}
}
| 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/Resources/ArticleResource.php | Beam/extensions/beam-module/src/Http/Resources/ArticleResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Remp\BeamModule\Model\Article;
use Remp\LaravelHelpers\Resources\JsonResource;
/**
* Class ArticleResource
*
* @mixin Article
* @package App\Http\Resources
*/
class ArticleResource extends JsonResource
{
/**
* Checks for 'extended' value in request. If true, additional parameters from Article accessors are provided.
* @param \Illuminate\Http\Request $request
*
* @return array
*/
public function toArray($request)
{
$values = parent::toArray($request);
foreach ($this->authors as $author) {
$values['authors'][] = [
'id' => $author->id,
'external_id' => $author->external_id,
];
}
foreach ($this->tags as $tag) {
$values['tags'][] = [
'id' => $tag->id,
'external_id' => $tag->external_id,
];
}
foreach ($this->sections as $section) {
$values['sections'][] = [
'id' => $section->id,
'external_id' => $section->external_id,
];
}
$extended = (bool) $request->input('extended', false);
if ($extended) {
$values['unique_browsers_count'] = $this->unique_browsers_count;
$values['conversion_rate'] = $this->conversion_rate;
$values['renewed_conversions_count'] = $this->renewed_conversions_count;
$values['new_conversions_count'] = $this->new_conversions_count;
$values['has_image_variants'] = $this->has_image_variants;
$values['has_title_variants'] = $this->has_title_variants;
}
return $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/Http/Resources/ConversionsSankeyResource.php | Beam/extensions/beam-module/src/Http/Resources/ConversionsSankeyResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Remp\BeamModule\Model\Charts\ConversionsSankeyDiagram;
use Remp\LaravelHelpers\Resources\JsonResource;
/**
* Class SankeyDiagramResource
*
* @mixin ConversionsSankeyDiagram
* @package App\Http\Resources
*/
class ConversionsSankeyResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'nodes' => $this->nodes,
'links' => $this->links,
'nodeColors' => $this->nodeColors
];
}
}
| 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/Resources/SearchResource.php | Beam/extensions/beam-module/src/Http/Resources/SearchResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Illuminate\Support\Arr;
use Remp\LaravelHelpers\Resources\JsonResource;
class SearchResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
$authors = $this->get('authors');
$articles = $this->get('articles');
$segments = $this->get('segments');
return Arr::collapse([
$this->when($authors->isNotEmpty(), AuthorSearchResource::collection($authors)->toArray(app('request'))),
$this->when($articles->isNotEmpty(), ArticleSearchResource::collection($articles)->toArray(app('request'))),
$this->when($segments->isNotEmpty(), SegmentSearchResource::collection($segments)->toArray(app('request')))
]);
}
}
| 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/Resources/SegmentSearchResource.php | Beam/extensions/beam-module/src/Http/Resources/SegmentSearchResource.php | <?php
namespace Remp\BeamModule\Http\Resources;
use Remp\BeamModule\Model\Segment;
use Remp\LaravelHelpers\Resources\JsonResource;
/**
* Class SegmentSearchResource
*
* @mixin Segment
* @package App\Http\Resources
*/
class SegmentSearchResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'type' => 'segment',
'name' => $this->name,
'code' => $this->code,
'search_result_url' => route('segments.edit', $this)
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Mail/SectionSegmentsResult.php | Beam/extensions/beam-module/src/Mail/SectionSegmentsResult.php | <?php
namespace Remp\BeamModule\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class SectionSegmentsResult extends Mailable
{
use Queueable, SerializesModels;
private $results;
private $minimalViews;
private $minimalAverageTimespent;
private $minimalRatio;
private $historyDays;
public function __construct($results, $minimalViews, $minimalAverageTimespent, $minimalRatio, $historyDays)
{
$this->results = $results;
$this->minimalViews = $minimalViews;
$this->minimalAverageTimespent = $minimalAverageTimespent;
$this->minimalRatio = $minimalRatio;
$this->historyDays = $historyDays;
}
public function build()
{
return $this->view('sections.segments.results_email')
->with([
'results' => $this->results,
'minimal_views' => $this->minimalViews,
'minimal_average_timespent' => $this->minimalAverageTimespent,
'minimal_ratio' => $this->minimalRatio,
'history_days' => $this->historyDays
]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Mail/AuthorSegmentsResult.php | Beam/extensions/beam-module/src/Mail/AuthorSegmentsResult.php | <?php
namespace Remp\BeamModule\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class AuthorSegmentsResult extends Mailable
{
use Queueable, SerializesModels;
private $results;
private $minimalViews;
private $minimalAverageTimespent;
private $minimalRatio;
private $historyDays;
public function __construct($results, $minimalViews, $minimalAverageTimespent, $minimalRatio, $historyDays)
{
$this->results = $results;
$this->minimalViews = $minimalViews;
$this->minimalAverageTimespent = $minimalAverageTimespent;
$this->minimalRatio = $minimalRatio;
$this->historyDays = $historyDays;
}
public function build()
{
return $this->view('authors.segments.results_email')
->with([
'results' => $this->results,
'minimal_views' => $this->minimalViews,
'minimal_average_timespent' => $this->minimalAverageTimespent,
'minimal_ratio' => $this->minimalRatio,
'history_days' => $this->historyDays
]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Contracts/Mailer/MailerException.php | Beam/extensions/beam-module/src/Contracts/Mailer/MailerException.php | <?php
namespace Remp\BeamModule\Contracts\Mailer;
class MailerException extends \Exception
{
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Contracts/Mailer/Mailer.php | Beam/extensions/beam-module/src/Contracts/Mailer/Mailer.php | <?php
namespace Remp\BeamModule\Contracts\Mailer;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ConnectException;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
class Mailer implements MailerContract
{
const ENDPOINT_GENERATOR_TEMPLATES = 'api/v1/mailers/generator-templates';
const ENDPOINT_SEGMENTS = 'api/v1/segments/list';
const ENDPOINT_MAIL_TYPES = 'api/v1/mailers/mail-types';
const ENDPOINT_GENERATE_EMAIL = 'api/v1/mailers/generate-mail';
const ENDPOINT_CREATE_TEMPLATE = 'api/v1/mailers/templates';
const ENDPOINT_CREATE_JOB = 'api/v1/mailers/jobs';
private $client;
public function __construct(Client $client)
{
$this->client = $client;
}
public function segments(): Collection
{
try {
$response = $this->client->get(self::ENDPOINT_SEGMENTS);
} catch (ConnectException $e) {
throw new MailerException("Could not connect to Mailer endpoint: {$e->getMessage()}");
}
return collect(json_decode($response->getBody())->data);
}
public function generatorTemplates($generator = null): Collection
{
$params = [];
if ($generator) {
$params['query'] = ['generator' => $generator];
}
try {
$response = $this->client->get(self::ENDPOINT_GENERATOR_TEMPLATES, $params);
} catch (ConnectException $e) {
throw new MailerException("Could not connect to Mailer endpoint: {$e->getMessage()}");
}
return collect(json_decode($response->getBody())->data);
}
public function generateEmail($sourceTemplateId, array $generatorParameters): Collection
{
$postParams = [
'source_template_id' => $sourceTemplateId
];
$postParams = array_merge($postParams, $generatorParameters);
try {
$response = $this->client->post(self::ENDPOINT_GENERATE_EMAIL, [
'form_params' => $postParams
]);
} catch (ConnectException $e) {
throw new MailerException("Could not connect to Mailer endpoint: {$e->getMessage()}");
}
return collect(json_decode($response->getBody())->data);
}
public function mailTypes(): Collection
{
try {
$response = $this->client->get(self::ENDPOINT_MAIL_TYPES);
} catch (ConnectException $e) {
throw new MailerException("Could not connect to Mailer endpoint: {$e->getMessage()}");
}
return collect(json_decode($response->getBody())->data);
}
public function createTemplate(
$name,
$code,
$description,
$from,
$subject,
$templateText,
$templateHtml,
$mailTypeCode,
$extras = null
): int {
$multipart = [
[
'name' => 'name',
'contents' => $name
],
[
'name' => 'code',
'contents' => $code
],
[
'name' => 'description',
'contents' => $description
],
[
'name' => 'from',
'contents' => $from
],
[
'name' => 'subject',
'contents' => $subject
],
[
'name' => 'template_text',
'contents' => $templateText
],
[
'name' => 'template_html',
'contents' => $templateHtml
],
[
'name' => 'mail_type_code',
'contents' => $mailTypeCode
]
];
if ($extras) {
$multipart[] = [
'name' => 'extras',
'contents' => $extras
];
}
try {
$response = $this->client->post(self::ENDPOINT_CREATE_TEMPLATE, [
'multipart' => $multipart
]);
} catch (ConnectException $e) {
throw new MailerException("Could not connect to Mailer endpoint: {$e->getMessage()}");
} catch (ClientException $e) {
Log::error('Unable to create Mailer template: ' . self::ENDPOINT_CREATE_TEMPLATE . ': ' . json_encode($multipart));
throw $e;
}
$output = json_decode($response->getBody());
if ($output->status === 'error') {
throw new MailerException("Error while creating template: {$output->message}");
}
return $output->id;
}
public function createJob($segmentCode, $segmentProvider, $templateId): int
{
$postParams = [
'segment_code' => $segmentCode,
'segment_provider' => $segmentProvider,
'template_id' => $templateId
];
try {
$response = $this->client->post(self::ENDPOINT_CREATE_JOB, [
'form_params' => $postParams
]);
} catch (ConnectException $e) {
throw new MailerException("Could not connect to Mailer endpoint: {$e->getMessage()}");
}
return json_decode($response->getBody())->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/Contracts/Mailer/MailerContract.php | Beam/extensions/beam-module/src/Contracts/Mailer/MailerContract.php | <?php
namespace Remp\BeamModule\Contracts\Mailer;
use Illuminate\Support\Collection;
interface MailerContract
{
public function segments(): Collection;
public function generatorTemplates($generator = null): Collection;
public function mailTypes(): Collection;
public function generateEmail($sourceTemplateId, array $generatorParameters): Collection;
public function createTemplate(
$name,
$code,
$description,
$from,
$subject,
$templateText,
$templateHtml,
$mailTypeCode,
$extras = null
): int;
public function createJob($segmentCode, $segmentProvider, $templateId): int;
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Console/Command.php | Beam/extensions/beam-module/src/Console/Command.php | <?php
namespace Remp\BeamModule\Console;
use Illuminate\Console\Command as ConsoleCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class Command extends ConsoleCommand
{
public function initialize(InputInterface $input, OutputInterface $output)
{
parent::initialize($input, $output);
$memoryLimits = config('system.commands_memory_limits');
if (isset($memoryLimits[$this->getName()])) {
ini_set('memory_limit', $memoryLimits[$this->getName()]);
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Console/Commands/DeleteDuplicatePageviews.php | Beam/extensions/beam-module/src/Console/Commands/DeleteDuplicatePageviews.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Model\ArticlePageviews;
use Remp\BeamModule\Console\Command;
use Illuminate\Support\Carbon;
class DeleteDuplicatePageviews extends Command
{
const COMMAND = 'data:delete-duplicate-pageviews';
protected $signature = self::COMMAND . ' {--date=}';
protected $description = 'Delete duplicate pageviews and keeps the shortest available interval.';
public function handle()
{
$dateFrom = $this->option('date') ? Carbon::parse($this->option('date')) : Carbon::now()->startOfDay();
$dateTo = (clone $dateFrom)->endOfDay();
$this->line('');
$this->line(sprintf("***** Deleting duplicate pageviews starting between <info>%s</info> - <info>%s</info> *****", $dateFrom, $dateTo));
$this->line('');
$removeIds = \DB::select("
SELECT DISTINCT ap_old.id
FROM article_pageviews ap_new
JOIN article_pageviews ap_old ON
ap_new.article_id = ap_old.article_id
AND ap_old.time_from <= ap_new.time_from
AND ap_old.time_to >= ap_new.time_to
AND ap_old.id != ap_new.id
WHERE ap_new.time_from >= ? AND ap_new.time_from <= ?", [$dateFrom, $dateTo]);
$removeIds = array_map(static function ($value) {
return $value->id;
}, $removeIds);
$deletedCount = 0;
while ($ids = array_splice($removeIds, 0, 1000)) {
$deletedCount += ArticlePageviews::whereIn('id', $ids)->delete();
}
$this->line(sprintf("Removed <info>%s</info> rows.", $deletedCount));
$this->line(' <info>OK!</info>');
return self::SUCCESS;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Console/Commands/CompressSnapshots.php | Beam/extensions/beam-module/src/Console/Commands/CompressSnapshots.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Helpers\Journal\JournalInterval;
use Remp\BeamModule\Model\ArticleViewsSnapshot;
use Remp\BeamModule\Model\Snapshots\SnapshotHelpers;
use Carbon\Carbon;
use Remp\BeamModule\Console\Command;
class CompressSnapshots extends Command
{
const COMMAND = 'pageviews:compress-snapshots';
protected $signature = self::COMMAND . ' {--now=}';
protected $description = 'Compress snapshots according to the retention rules';
private $snapshotHelpers;
public function __construct()
{
parent::__construct();
$this->snapshotHelpers = new SnapshotHelpers();
}
public function handle()
{
$this->line('');
$this->line('<info>***** Compressing snapshots *****</info>');
$this->line('');
// Start compression from last hour (to avoid complicated rounding of retention intervals, to get "nice" datetimes in dashboard)
$now = Carbon::now();
$now->setTime($now->hour, 0);
// $now can be optionally rewritten (useful in tests)
$now = $this->option('now') ? Carbon::parse($this->option('now')) : $now;
$this->compress($now);
$this->line(' <info>OK!</info>');
return 0;
}
private function compress(Carbon $now)
{
foreach (JournalInterval::RETENTION_RULES as $rule) {
$startMinute = $rule[0];
$endMinute = $rule[1];
$windowSizeInMinutes = $rule[2];
$this->line("Applying retention rule [{$startMinute}m, " . ($endMinute ?? 'unlimited ') . "m), window size $windowSizeInMinutes minutes");
$periods = $this->computeDayPeriods($now, $startMinute, $endMinute);
foreach ($periods as $period) {
$from = $period[0];
$to = $period[1];
$this->line("Compressing snapshots between {$from} and {$to}");
$timePoints = $this->snapshotHelpers->timePoints($from, $to, $windowSizeInMinutes);
$excludedTimePoints = array_map(function (string $zuluTimeString) {
return Carbon::parse($zuluTimeString);
}, $timePoints->getExcludedPoints());
foreach (array_chunk($excludedTimePoints, 200) as $excludedTimePointsChunk) {
$deletedCount = ArticleViewsSnapshot::deleteForTimes($excludedTimePointsChunk);
if ($deletedCount > 0) {
$this->line("$deletedCount records deleted");
}
}
}
}
}
/**
* Function that computes interval [$now-$endMinute, $now-$startMinute] and splits it to days
* @param Carbon $now
* @param int $startMinute
* @param int|null $endMinute
*
* @return array
*/
public function computeDayPeriods(Carbon $now, int $startMinute, ?int $endMinute): array
{
$periods = [];
$to = (clone $now)->subMinutes($startMinute);
if ($endMinute !== null) {
$from = (clone $now)->subMinutes($endMinute);
} else {
// If $endMinute is null, do not construct unlimited interval,
// go back only few days since the previous values have already been compressed
$from = (clone $to)->subDays(2);
}
$timeIterator = clone $from;
// Split by days
while ($timeIterator->lt($to)) {
$end = (clone $timeIterator)->addDay();
$periods[] = [clone $timeIterator, $to->lt($end) ? $to : $end];
$timeIterator->addDay();
}
return $periods;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Console/Commands/PostInstallCommand.php | Beam/extensions/beam-module/src/Console/Commands/PostInstallCommand.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Illuminate\Support\Facades\Artisan;
use Remp\BeamModule\Console\Command;
class PostInstallCommand extends Command
{
protected $signature = 'service:post-install';
protected $description = 'Executes services needed to be run after the Beam installation/update';
public function handle()
{
try {
Artisan::call('db:seed', [
'--class' => \Remp\BeamModule\Database\Seeders\ConfigSeeder::class,
'--force' => true,
]);
Artisan::call('db:seed', [
'--class' => \Remp\BeamModule\Database\Seeders\SegmentGroupSeeder::class,
'--force' => true,
]);
} catch (\Exception $e) {
// Do nothing. DB might not be initialized yet, or we're in the CI where there's just no DB.
}
return self::SUCCESS;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Console/Commands/SendNewslettersCommand.php | Beam/extensions/beam-module/src/Console/Commands/SendNewslettersCommand.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Carbon\Carbon;
use Recurr\Transformer\ArrayTransformer;
use Recurr\Transformer\ArrayTransformerConfig;
use Recurr\Transformer\Constraint\AfterConstraint;
use Remp\BeamModule\Console\Command;
use Remp\BeamModule\Contracts\Mailer\MailerContract;
use Remp\BeamModule\Model\Newsletter;
use Remp\BeamModule\Model\Newsletter\NewsletterCriterionEnum;
use Remp\BeamModule\Model\NewsletterCriterion;
class SendNewslettersCommand extends Command
{
const COMMAND = 'newsletters:send';
protected $signature = self::COMMAND . '
{--ignore-content-type=* : Content type to be excluded }
{--ignore-author=* : Author ID to be excluded }
';
protected $description = 'Process newsletters data and generate Mailer jobs.';
private $transformer;
private $mailer;
public function __construct(MailerContract $mailer)
{
parent::__construct();
$config = new ArrayTransformerConfig();
$this->transformer = new ArrayTransformer($config);
$this->mailer = $mailer;
}
public function handle()
{
$ignoreAuthors = $this->input->getOption('ignore-author') ?: config('beam.newsletter_ignored_authors');
$ignoreContentTypes = $this->input->getOption('ignore-content-type') ?: config('beam.newsletter_ignored_content_types');
$this->line(Carbon::now() . ': Processing newsletters');
$newsletters = Newsletter::where('state', Newsletter::STATE_STARTED)
->where('starts_at', '<=', Carbon::now())
->get();
if ($newsletters->count() === 0) {
$this->info("No newsletters to process");
return 0;
}
foreach ($newsletters as $newsletter) {
$this->line(Carbon::now() . ": * {$newsletter->name}");
$nextSending = $newsletter->starts_at;
$hasMore = false;
if ($newsletter->rule_object) {
[$nextSending, $hasMore] = $this->retrieveNextSending($newsletter);
}
if ($nextSending) {
$this->line(Carbon::now() . ": Sending...");
$this->sendNewsletter(
newsletter: $newsletter,
ignoreAuthors: $ignoreAuthors,
ignoreContentTypes: $ignoreContentTypes,
);
$this->line(Carbon::now() . ": Sent.");
$newsletter->last_sent_at = Carbon::now();
if (!$hasMore) {
$newsletter->state = Newsletter::STATE_FINISHED;
}
} elseif (!$hasMore) {
$this->line(Carbon::now() . ": Marking as finished.");
$newsletter->state = Newsletter::STATE_FINISHED;
}
$newsletter->save();
}
$this->line(Carbon::now() . ': Done!');
return 0;
}
private function retrieveNextSending($newsletter)
{
// newsletter hasn't been sent yet, include all dates after starts_at (incl.)
// if has been sent yet, count all dates after last_sent_at (excl.)
$afterConstraint = $newsletter->last_sent_at ?
new AfterConstraint($newsletter->last_sent_at, false) :
new AfterConstraint($newsletter->starts_at, true);
$recurrenceCollection = $this->transformer->transform($newsletter->rule_object, $afterConstraint);
$nextSending = null;
$now = Carbon::now();
foreach ($recurrenceCollection as $recurrence) {
if ($recurrence->getStart() >= $now) {
break;
}
$nextSending = Carbon::instance($recurrence->getStart());
}
$hasMore = $recurrenceCollection->count() > 1;
return [$nextSending, $hasMore];
}
private function sendNewsletter(Newsletter $newsletter, array $ignoreAuthors, array $ignoreContentTypes)
{
$criterion = new NewsletterCriterion(NewsletterCriterionEnum::from($newsletter->criteria));
$articles = $newsletter->personalized_content ? [] :
$criterion->getArticles(
timespan: $newsletter->timespan,
articlesCount: $newsletter->articles_count,
ignoreAuthors: $ignoreAuthors,
ignoreContentTypes: $ignoreContentTypes,
);
if ($articles->count() === 0) {
$this->line(Carbon::now() . ': <comment>WARNING:</comment> No articles found for selected timespan, nothing is sent');
return;
}
[$htmlContent, $textContent] = $this->generateEmail($newsletter, $articles);
$templateId = $this->createTemplate($newsletter, $htmlContent, $textContent);
$this->createJob($newsletter, $templateId);
}
private function createJob($newsletter, $templateId)
{
$jobId = $this->mailer->createJob($newsletter->segment_code, $newsletter->segment_provider, $templateId);
$this->line(sprintf(Carbon::now() . ': Mailer job successfully created (id: %s)', $jobId));
}
private function createTemplate($newsletter, $htmlContent, $textContent): int
{
$extras = null;
if ($newsletter->personalized_content) {
$extras = json_encode([
'generator' => 'beam-unread-articles',
'parameters' => [
'criteria' => [
$newsletter->criteria
],
'timespan' => $newsletter->timespan,
'articles_count' => $newsletter->articles_count
]
]);
}
return $this->mailer->createTemplate(
$newsletter->name,
'beam_newsletter',
'Newsletter generated by Beam',
$newsletter->email_from,
$newsletter->email_subject,
$textContent,
$htmlContent,
$newsletter->mail_type_code,
$extras
);
}
private function generateEmail($newsletter, $articles)
{
$params = [];
if ($newsletter->personalized_content) {
$params['dynamic'] = true;
$params['articles_count'] = $newsletter->articles_count;
} else {
$articles = $articles->pluck('url')->toArray();
$params['articles']= implode("\n", $articles);
foreach ($articles as $article) {
$this->line(sprintf(Carbon::now() . ': ' . $article));
}
}
$output = $this->mailer->generateEmail($newsletter->mailer_generator_id, $params);
return [$output['htmlContent'], $output['textContent']];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Console/Commands/AggregateArticlesViews.php | Beam/extensions/beam-module/src/Console/Commands/AggregateArticlesViews.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Remp\BeamModule\Console\Command;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\ArticleAggregatedView;
use Remp\BeamModule\Model\ViewsPerBrowserMv;
use Remp\BeamModule\Model\ViewsPerUserMv;
use Remp\Journal\AggregateRequest;
use Remp\Journal\JournalContract;
class AggregateArticlesViews extends Command
{
const KEY_SEPARATOR = '||||';
const COMMAND = 'pageviews:aggregate-articles-views';
const TIMESPENT_IGNORE_THRESHOLD_SECS = 3600;
// TODO remove skip-temp-aggregation after temp aggregation tables are no longer used
protected $signature = self::COMMAND . '
{--date= : Date you want to aggregate.}
{--date-from= : Start of a date range you want to aggregate. Needs to be combined with --date-to.}
{--date-to= : End of a date range you want to aggregate. Needs to be combined with --date-from.}
{--step=40 : Time frame (in minutes) which aggregation should use to request the date. Bigger the traffic, smaller the window. If the time-frame is too broad, it might cause Segments API to return an error due to the amount of buckets necessary to generate in Elasticsearch.}
{--skip-temp-aggregation}';
protected $description = 'Aggregate pageviews and time spent data for each user and article for yesterday';
private $journalContract;
public function __construct(JournalContract $journalContract)
{
parent::__construct();
// Client in Journal uses exponential back-off retry strategy, see service provider for details
$this->journalContract = $journalContract;
}
public function handle()
{
$this->line('');
$this->line('<info>***** Aggregatting article views *****</info>');
$this->line('');
$step = filter_var($this->option('step'), FILTER_VALIDATE_INT);
if (!$step) {
$this->error('Invalid --step option (expecting integer): ' . $this->option('step'));
return self::FAILURE;
}
// TODO set this up depending finalized conditions
// First delete data older than 30 days
$dateThreshold = Carbon::today()->subDays(30)->toDateString();
ArticleAggregatedView::where('date', '<=', $dateThreshold)->delete();
$dateFrom = $this->option('date-from');
$dateTo = $this->option('date-to');
if ($dateFrom || $dateTo) {
if (!$dateFrom) {
$this->error('Missing --date-from option');
return self::FAILURE;
}
if (!$dateTo) {
$this->error('Missing --date-to option');
return self::FAILURE;
}
$from = Carbon::parse($dateFrom)->startOfDay();
$to = Carbon::parse($dateTo)->startOfDay();
while ($from->lte($to)) {
$this->aggregateDay($from, $step);
$from->addDay();
}
} else {
$date = $this->option('date') ? Carbon::parse($this->option('date')) : Carbon::yesterday();
$this->aggregateDay($date, $step);
}
// Update 'materialized view' to test author segments conditions
// TODO only temporary, remove this after conditions are finalized
if (!$this->option('skip-temp-aggregation')) {
$this->createTemporaryAggregations();
}
$this->line(' <info>OK!</info>');
return self::SUCCESS;
}
private function aggregateDay(Carbon $startDate, int $step)
{
ArticleAggregatedView::where('date', $startDate)->delete();
// Aggregate pageviews and timespent data in time windows
$timeWindowMinutes = $step; // in minutes
$timeWindowsCount = 1440 / $timeWindowMinutes; // 1440 - number of minutes in day
$timeAfter = $startDate;
$timeBefore = (clone $timeAfter)->addMinutes($timeWindowMinutes);
$date = $timeAfter->toDateString();
for ($i = 0; $i < $timeWindowsCount; $i++) {
[$data, $articleIds] = $this->aggregatePageviews([], [], $timeAfter, $timeBefore);
[$data, $articleIds] = $this->aggregateTimespent($data, $articleIds, $timeAfter, $timeBefore);
$this->storeData($data, $articleIds, $date);
$timeAfter = $timeAfter->addMinutes($timeWindowMinutes);
$timeBefore = $timeBefore->addMinutes($timeWindowMinutes);
}
}
private function createTemporaryAggregations()
{
$days30ago = Carbon::today()->subDays(30);
$days60ago = Carbon::today()->subDays(60);
$days90ago = Carbon::today()->subDays(90);
ViewsPerBrowserMv::query()->delete();
$this->aggregateViewsPer('browser', 'total_views_last_30_days', $days30ago);
$this->aggregateViewsPer('browser', 'total_views_last_60_days', $days60ago);
$this->aggregateViewsPer('browser', 'total_views_last_90_days', $days90ago);
ViewsPerUserMv::query()->delete();
$this->aggregateViewsPer('user', 'total_views_last_30_days', $days30ago);
$this->aggregateViewsPer('user', 'total_views_last_60_days', $days60ago);
$this->aggregateViewsPer('user', 'total_views_last_90_days', $days90ago);
}
private function aggregateViewsPer($groupBy, $daysColumn, Carbon $daysAgo)
{
if ($groupBy === 'browser') {
$tableToUpdate = 'views_per_browser_mv';
$groupParameter = 'browser_id';
} else {
$tableToUpdate = 'views_per_user_mv';
$groupParameter = 'user_id';
}
$today = Carbon::today();
// aggregate values in 14-days windows to avoid filling all the RAM while querying DB
$daysWindow = 14;
$startDate = clone $daysAgo;
while ($startDate->lessThan($today)) {
$end = (clone $startDate)->addDays($daysWindow - 1)->toDateString();
$start = $startDate->toDateString();
$sql = <<<SQL
INSERT INTO $tableToUpdate ($groupParameter, $daysColumn)
SELECT $groupParameter, sum(pageviews)
FROM article_aggregated_views
JOIN article_author ON article_author.article_id = article_aggregated_views.article_id
WHERE timespent <= 3600 AND date >= ? and date <= ?
SQL;
DB::insert($sql . ($groupBy === 'user' ? "and user_id <> ''" : '') . " group by $groupParameter
ON DUPLICATE KEY UPDATE $daysColumn = $daysColumn + VALUES(`$daysColumn`)", [$start, $end]);
$startDate->addDays($daysWindow);
}
}
/**
* @param array $data
* @param array $articleIds
* @param $timeAfter
* @param $timeBefore
* @return array {
* @type array $data parsed data appended to provided $data param
* @type array $articleIds list of touched articleIds appended to provided $articleIds param
* }
*
*/
private function aggregateTimespent(array $data, array $articleIds, $timeAfter, $timeBefore): array
{
$this->line(sprintf("Fetching aggregated <info>timespent</info> data from <info>%s</info> to <info>%s</info>.", $timeAfter, $timeBefore));
$request = new AggregateRequest('pageviews', 'timespent');
$request->setTimeAfter($timeAfter);
$request->setTimeBefore($timeBefore);
$request->addGroup('article_id', 'user_id', 'browser_id');
$records = collect($this->journalContract->sum($request));
if (count($records) === 0 || (count($records) === 1 && !isset($records[0]->tags->article_id))) {
$this->line(sprintf("No articles to process."));
return [$data, $articleIds];
}
$bar = $this->output->createProgressBar(count($records));
$bar->setFormat('%message%: %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
$bar->setMessage('Processing timespent');
foreach ($records as $record) {
$articleId = $record->tags->article_id;
$userId = $record->tags->user_id ?? '';
$browserId = $record->tags->browser_id ?? '';
if (empty($articleId) || (empty($userId) && empty($browserId))) {
$bar->advance();
continue;
}
$sum = (int) $record->sum;
if ($sum >= self::TIMESPENT_IGNORE_THRESHOLD_SECS) {
continue;
}
$key = $browserId . self::KEY_SEPARATOR . $userId;
if (!array_key_exists($key, $data)) {
$data[$key] = [];
}
if (!array_key_exists($articleId, $data[$key])) {
$data[$key][$articleId] = [
'pageviews' => 0,
'timespent' => 0
];
}
$data[$key][$articleId]['timespent'] += $sum;
$articleIds[$articleId] = true;
$bar->advance();
}
$bar->finish();
$this->line(' <info>OK!</info>');
return [$data, $articleIds];
}
/**
* @param array $data
* @param array $articleIds
* @param $timeAfter
* @param $timeBefore
* @return array {
* @type array $data parsed data appended to provided $data param
* @type array $articleIds list of touched articleIds appended to provided $articleIds param
* }
*
*/
private function aggregatePageviews(array $data, array $articleIds, $timeAfter, $timeBefore): array
{
$this->line(sprintf("Fetching aggregated <info>pageviews</info> data from <info>%s</info> to <info>%s</info>.", $timeAfter, $timeBefore));
$request = new AggregateRequest('pageviews', 'load');
$request->setTimeAfter($timeAfter);
$request->setTimeBefore($timeBefore);
$request->addGroup('article_id', 'user_id', 'browser_id');
$records = collect($this->journalContract->count($request));
if (count($records) === 0 || (count($records) === 1 && !isset($records[0]->tags->article_id))) {
$this->line(sprintf("No articles to process."));
return [$data, $articleIds];
}
$bar = $this->output->createProgressBar(count($records));
$bar->setFormat('%message%: %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
$bar->setMessage('Processing pageviews');
foreach ($records as $record) {
$articleId = $record->tags->article_id;
$userId = $record->tags->user_id ?? '';
$browserId = $record->tags->browser_id ?? '';
if (empty($articleId) || (empty($userId) && empty($browserId))) {
$bar->advance();
continue;
}
$key = $browserId . self::KEY_SEPARATOR . $userId;
$count = $record->count;
if (!array_key_exists($key, $data)) {
$data[$key] = [];
}
if (!array_key_exists($articleId, $data[$key])) {
$data[$key][$articleId] = [
'pageviews' => 0,
'timespent' => 0
];
}
$data[$key][$articleId]['pageviews'] += $count;
$articleIds[$articleId] = true;
$bar->advance();
}
$bar->finish();
$this->line(' <info>OK!</info>');
return [$data, $articleIds];
}
private function storeData(array $data, array $articleIds, string $date)
{
if (empty($data)) {
return;
}
$bar = $this->output->createProgressBar(count($data));
$bar->setFormat('%message%: %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
$bar->setMessage('Storing aggregated data');
$articleIdMap = Article::whereIn(
'external_id',
array_map('strval', array_keys($articleIds))
)->pluck('id', 'external_id');
$items = [];
foreach ($data as $key => $articlesData) {
[$browserId, $userId] = explode(self::KEY_SEPARATOR, $key, 2);
foreach ($articlesData as $externalArticleId => $record) {
if (!isset($articleIdMap[$externalArticleId])) {
continue;
}
$items[] = [
'article_id' => $articleIdMap[$externalArticleId],
'browser_id' => $browserId === '' ? null : $browserId,
'user_id' => $userId === '' ? null : $userId,
'date' => $date,
'pageviews' => $record['pageviews'],
'timespent' => $record['timespent']
];
}
$bar->advance();
}
foreach (array_chunk($items, 500) as $itemsChunk) {
ArticleAggregatedView::insertOnDuplicateKey($itemsChunk, [
'pageviews' => DB::raw('pageviews + VALUES(pageviews)')->getValue(DB::connection()->getQueryGrammar()),
'timespent' => DB::raw('timespent + VALUES(timespent)')->getValue(DB::connection()->getQueryGrammar()),
]);
}
$bar->finish();
$this->line(' <info>OK!</info>');
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Console/Commands/ElasticWriteAliasRollover.php | Beam/extensions/beam-module/src/Console/Commands/ElasticWriteAliasRollover.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Carbon\Carbon;
use Illuminate\Support\Str;
use GuzzleHttp\Client;
use Remp\BeamModule\Console\Command;
class ElasticWriteAliasRollover extends Command
{
const COMMAND = 'service:elastic-write-alias-rollover';
protected $signature = self::COMMAND . ' {--host=} {--write-alias=} {--read-alias=} {--auth=} {--max-age=} {--max-size=} {--max-primary-shard-size=}';
protected $description = 'Rollover write index and assign newly created index to read index';
public function handle()
{
if (!$this->input->getOption('host')) {
$this->line('<error>ERROR</error> You need to provide <info>--host</info> option with address to your Elastic instance (e.g. <info>--host=http://localhost:9200</info>)');
return 1;
}
if (!$this->input->getOption('write-alias')) {
$this->line('<error>ERROR</error> You need to provide <info>--write-alias</info> option with name of the write alias you use (e.g. <info>--write-alias=pageviews_write</info>)');
return 1;
}
if (!$this->input->getOption('read-alias')) {
$this->line('<error>ERROR</error> You need to provide <info>--read-alias</info> option with name of the read alias you use (e.g. <info>--read-alias=pageviews</info>)');
return 1;
}
$client = new Client([
'base_uri' => $this->input->getOption('host'),
]);
$this->line('');
$this->info('**** ' . self::COMMAND . ' (date: ' . (new Carbon())->format(DATE_RFC3339) . ') ****');
$this->line(sprintf(
"Executing rollover, host: <info>%s</info>, write-alias: <info>%s</info>, read-alias: <info>%s</info>",
$this->input->getOption('host'),
$this->input->getOption('write-alias'),
$this->input->getOption('read-alias')
));
$options = [];
if ($this->input->getOption('auth')) {
$auth = $this->input->getOption('auth');
if (!Str::contains($auth, ':')) {
$this->line("<error>ERROR</error> You need to provide <info>--auth</info> option with a name and a password (to Elastic instance) separated by ':', e.g. admin:password");
return 1;
}
[$user, $pass] = explode(':', $auth, 2);
$options = [
'auth' => [$user, $pass]
];
}
$conditions = [
'max_age' => $this->input->getOption('max-age') ?? '31d',
'max_size' => $this->input->getOption('max-size') ?? '4gb',
//'max_docs' => 1, // condition for testing
];
if ($this->input->getOption('max-primary-shard-size')) {
$conditions['max_primary_shard_size'] = $this->input->getOption('max-primary-shard-size');
}
// execute rollover; https://www.elastic.co/guide/en/elasticsearch/reference/7.17/indices-rollover-index.html
$response = $client->post(sprintf("/%s/_rollover", $this->input->getOption('write-alias')), array_merge([
'json' => [
'conditions' => $conditions,
],
], $options));
$body = json_decode($response->getBody(), true);
if (!$body['rolled_over']) {
$this->line(' * Rollover condition not matched, done.');
return 3;
}
$this->line(sprintf(
' * Rolled over, adding newly created <info>%s</info> to alias <info>%s</info>.',
$body['new_index'],
$this->input->getOption('read-alias')
));
// if rollover happened, add newly created index to the read alias (so it contains all the indices)
$client->post("/_aliases", array_merge([
'json' => [
'actions' => [
'add' => [
'index' => $body['new_index'],
'alias' => $this->input->getOption('read-alias')
],
],
],
], $options));
$this->line(' * Alias created, done.');
return 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/Console/Commands/DashboardRefresh.php | Beam/extensions/beam-module/src/Console/Commands/DashboardRefresh.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Helpers\Journal\JournalHelpers;
use Carbon\Carbon;
use Remp\BeamModule\Console\Command;
use Illuminate\Database\Eloquent\Builder;
class DashboardRefresh extends Command
{
const COMMAND = 'dashboard:refresh';
protected $signature = self::COMMAND;
protected $description = 'Refresh cached dashboard stats';
private JournalHelpers $journalHelpers;
public function __construct(JournalHelpers $journalHelpers)
{
parent::__construct();
$this->journalHelpers = $journalHelpers;
}
public function handle()
{
$this->line('<info>***** Dashboard refresh (' . Carbon::now()->format(DATE_RFC3339) . ') *****</info>');
$articlesToRefresh = Article::whereHas('dashboardArticle', function (Builder $query) {
$query->where('last_dashboard_time', '>=', Carbon::now()->subHour());
})->get()->keyBy('external_id');
$this->getOutput()->write("Refreshing <comment>{$articlesToRefresh->count()}</comment> articles: ");
$uniqueBrowserCounts = $this->journalHelpers->uniqueBrowsersCountForArticles($articlesToRefresh);
$this->line('OK');
$this->getOutput()->write('Updating database: ');
$articlesToUpdate = Article::with('dashboardArticle')
->whereIn('external_id', $uniqueBrowserCounts->keys()->filter())
->get();
/** @var Article $article */
foreach ($articlesToUpdate as $article) {
$article->dashboardArticle()->updateOrCreate([], [
'unique_browsers' => (int) $uniqueBrowserCounts[$article->external_id],
]);
}
$this->line('OK');
return self::SUCCESS;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Console/Commands/AggregatePageviewTimespentJob.php | Beam/extensions/beam-module/src/Console/Commands/AggregatePageviewTimespentJob.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\ArticleTimespent;
use Remp\BeamModule\Helpers\DebugProxy;
use Remp\BeamModule\Console\Command;
use Illuminate\Support\Carbon;
use Remp\Journal\AggregateRequest;
use Remp\Journal\JournalContract;
use Symfony\Component\Console\Helper\ProgressBar;
class AggregatePageviewTimespentJob extends Command
{
const COMMAND = 'pageviews:aggregate-timespent';
protected $signature = self::COMMAND . ' {--now=} {--debug} {--article_id=}';
protected $description = 'Reads pageview/timespent data from journal and stores aggregated data';
public function handle(JournalContract $journalContract)
{
$debug = $this->option('debug') ?? false;
$articleId = $this->option('article_id') ?? null;
$now = $this->option('now') ? Carbon::parse($this->option('now')) : Carbon::now();
$timeBefore = $now->floorMinutes(20);
$timeAfter = (clone $timeBefore)->subMinutes(20);
$this->line(sprintf("Fetching aggregated timespent data from <info>%s</info> to <info>%s</info>.", $timeAfter, $timeBefore));
$request = new AggregateRequest('pageviews', 'timespent');
$request->setTimeAfter($timeAfter);
$request->setTimeBefore($timeBefore);
if ($articleId) {
$request->addFilter('article_id', $articleId);
}
$request->addGroup('article_id', 'signed_in', 'subscriber');
$records = collect($journalContract->sum($request));
if (count($records) === 1 && !isset($records[0]->tags->article_id)) {
$this->line("No articles to process, exiting.");
return 0;
}
/** @var ProgressBar $bar */
$bar = new DebugProxy($this->output->createProgressBar(count($records)), $debug);
$bar->setFormat('%message%: %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
$bar->setMessage('Processing pageviews');
$all = [];
$signedIn = [];
$subscribers = [];
foreach ($records as $record) {
if (empty($record->tags->article_id)) {
$bar->advance();
continue;
}
$bar->setMessage(sprintf("Processing pageviews for article ID: <info>%s</info>", $record->tags->article_id));
$articleId = $record->tags->article_id;
$all[$articleId] = $all[$articleId] ?? 0;
$signedIn[$articleId] = $signedIn[$articleId] ?? 0;
$subscribers[$articleId] = $subscribers[$articleId] ?? 0;
$all[$articleId] += $record->sum;
if (filter_var($record->tags->signed_in, FILTER_VALIDATE_BOOLEAN) === true) {
$signedIn[$articleId] += $record->sum;
}
if (filter_var($record->tags->subscriber, FILTER_VALIDATE_BOOLEAN) === true) {
$subscribers[$articleId] += $record->sum;
}
$bar->advance();
}
$bar->finish();
$this->line("\n<info>Pageviews loaded from Journal API</info>");
if (count($all) === 0) {
$this->line("No data to store for articles, exiting.");
return 0;
}
$externalIdsChunks = array_chunk(array_keys($all), 200);
/** @var ProgressBar $bar */
$bar = new DebugProxy($this->output->createProgressBar(count($externalIdsChunks)), $debug);
$bar->setFormat('%message%: [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
$bar->setMessage('Storing aggregated data');
$processedArticles = 0;
foreach ($externalIdsChunks as $externalIdsChunk) {
$articles = Article::whereIn(
'external_id',
array_map('strval', $externalIdsChunk)
)->get();
foreach ($articles as $article) {
$at = ArticleTimespent::firstOrNew([
'article_id' => $article->id,
'time_from' => $timeAfter,
'time_to' => $timeBefore,
]);
$at->sum = $all[$article->external_id];
$at->signed_in = $signedIn[$article->external_id];
$at->subscribers = $subscribers[$article->external_id];
$at->save();
$article->timespent_all = $article->timespent()->sum('sum');
$article->timespent_subscribers = $article->timespent()->sum('subscribers');
$article->timespent_signed_in = $article->timespent()->sum('signed_in');
$article->save();
}
$processedArticles += count($externalIdsChunk);
$bar->setMessage(sprintf('Storing aggregated data (<info>%s/%s</info> articles)', $processedArticles, count($all)));
$bar->advance();
}
$bar->finish();
$this->line(' <info>OK!</info>');
return 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/Console/Commands/DeleteOldAggregations.php | Beam/extensions/beam-module/src/Console/Commands/DeleteOldAggregations.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Model\ConversionCommerceEvent;
use Remp\BeamModule\Model\ConversionGeneralEvent;
use Remp\BeamModule\Model\ConversionPageviewEvent;
use Carbon\Carbon;
use Remp\BeamModule\Console\Command;
class DeleteOldAggregations extends Command
{
const COMMAND = 'data:delete-old-aggregations';
protected $signature = self::COMMAND . ' {--days=}';
protected $description = 'Delete old aggregated data.';
public function handle()
{
$sub = (int)($this->option('days') ?? config('beam.aggregated_data_retention_period'));
if ($sub < 0) {
$this->info("Negative number of days ($sub), not deleting data.");
return 0;
}
$this->line('');
$this->line('<info>***** Deleting old aggregations *****</info>');
$this->line('');
$this->line('Deleting aggregated data older than <info>' . $sub . ' days</info>.');
$threshold = Carbon::today()->subDays($sub);
$this->deleteConversionEventsData($threshold);
$this->line(' <info>OK!</info>');
return 0;
}
private function deleteConversionEventsData($threshold)
{
$this->line('Deleting <info>Conversions events</info> data');
ConversionCommerceEvent::where('time', '<', $threshold)->delete();
ConversionGeneralEvent::where('time', '<', $threshold)->delete();
ConversionPageviewEvent::where('time', '<', $threshold)->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/Console/Commands/AggregatePageviews.php | Beam/extensions/beam-module/src/Console/Commands/AggregatePageviews.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Console\Command;
class AggregatePageviews extends Command
{
const COMMAND = 'pageviews:aggregate';
protected $signature = self::COMMAND . ' {--now=} {--debug} {--article_id=}';
protected $description = 'Runs aggregate pageview timespent/load jobs.';
public function handle()
{
$arguments = [];
if ($this->option('now')) {
$arguments['--now'] = $this->option('now');
}
if ($this->option('debug')) {
$arguments['--debug'] = true;
}
if ($this->option('article_id')) {
$arguments['--article_id'] = $this->option('article_id');
}
$this->call('pageviews:aggregate-load', $arguments);
$this->call('pageviews:aggregate-timespent', $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/Console/Commands/ProcessConversionSources.php | Beam/extensions/beam-module/src/Console/Commands/ProcessConversionSources.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Conversion;
use Remp\BeamModule\Model\ConversionCommerceEvent;
use Remp\BeamModule\Model\ConversionSource;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Log;
use Remp\Journal\JournalContract;
use Remp\Journal\JournalException;
use Remp\Journal\ListRequest;
class ProcessConversionSources extends Command
{
const COMMAND = 'conversions:process-sources';
private $journal;
protected $signature = self::COMMAND . ' {--conversion_id=}';
protected $description = 'Retrieve visit sources that lead to conversion';
public function __construct(JournalContract $journal)
{
parent::__construct();
$this->journal = $journal;
}
public function handle()
{
$this->line('Started processing of conversion sources');
$conversionId = $this->option('conversion_id') ?? null;
try {
if ($conversionId) {
$conversion = Conversion::find($conversionId);
if (!$conversion) {
$this->error("Conversion with ID $conversionId not found.");
return 1;
}
if (!$conversion->events_aggregated) {
$this->warn("Conversion with ID $conversionId needs to be aggregated prior to running of this command.");
return 1;
}
if ($conversion->source_processed) {
$this->info("Sources for conversion with ID $conversionId has already been processed.");
return 1;
}
$this->processConversionSources($conversion);
$conversion->source_processed = true;
$conversion->save();
} else {
$conversionsToProcess = Conversion::select()
->where('events_aggregated', true)
->where('source_processed', false)
->orderBy('paid_at', 'DESC')
->get();
foreach ($conversionsToProcess as $conversion) {
$this->processConversionSources($conversion);
$conversion->source_processed = true;
$conversion->save();
}
}
} catch (JournalException $exception) {
$this->error($exception->getMessage());
}
$this->line(' <info>Done!</info>');
return 0;
}
private function processConversionSources(Conversion $conversion)
{
$this->line("Processing sources for conversion <info>#{$conversion->id}</info>");
/** @var ConversionCommerceEvent $paymentEvent */
$paymentEvent = $conversion->commerceEvents()
->where('step', 'payment')
->latest('time')
->first();
if (!$paymentEvent) {
Log::warning("No payment event found in DB for conversion: {$conversion->id}");
$this->warn("No payment event found in DB for conversion with ID $conversion->id, skipping...");
return;
}
if (!$browserId = $this->getConversionBrowserId($conversion)) {
return;
}
// with payment event and browser ID we can determine session and find first/last pageview of session
$from = (clone $paymentEvent->time)->subDay();
$to = (clone $paymentEvent->time);
$pageviewsListRequest = ListRequest::from('pageviews')
->setTime($from, $to)
->addFilter('browser_id', $browserId);
$pageviewJournalEvents = $this->journal->list($pageviewsListRequest);
if (empty($pageviewJournalEvents)) {
$this->warn("No pageview found in journal for conversion with ID $paymentEvent->conversion_id, skipping...");
return;
}
$pageviews = collect($pageviewJournalEvents[0]->pageviews);
$pageviews = $pageviews->sortByDesc(function ($item) {
return new Carbon($item->system->time);
});
$lastSessionPageview = $pageviews->first();
$firstSessionPageview = null;
foreach ($pageviews as $pageview) {
if ($pageview->user->remp_session_id === $lastSessionPageview->user->remp_session_id) {
$firstSessionPageview = $pageview;
}
}
$this->createConversionSourceModel($firstSessionPageview, $conversion, ConversionSource::TYPE_SESSION_FIRST);
$this->createConversionSourceModel($lastSessionPageview, $conversion, ConversionSource::TYPE_SESSION_LAST);
}
private function getConversionBrowserId(Conversion $conversion)
{
$paymentListRequest = ListRequest::from('commerce')
->addFilter('transaction_id', $conversion->transaction_id)
->addFilter('step', 'payment')
->addGroup('browser_id');
$paymentJournalEvent = $this->journal->list($paymentListRequest);
if (empty($paymentJournalEvent)) {
$this->warn("No payment event found in journal for conversion with ID $conversion->id, skipping...");
return false;
}
if (empty($paymentJournalEvent[0]->tags->browser_id)) {
Log::warning("No browser_id available in commerce event for transaction_id: {$conversion->transaction_id}");
$this->warn("No identifiable browser found in journal for conversion with ID $conversion->id, skipping...");
return false;
}
return $paymentJournalEvent[0]->tags->browser_id;
}
private function createConversionSourceModel($pageview, Conversion $conversion, string $type)
{
$conversionSource = new ConversionSource();
$conversionSource->type = $type;
$conversionSource->referer_medium = $pageview->user->derived_referer_medium;
if (!empty($pageview->user->derived_referer_source)) {
$conversionSource->referer_source = $pageview->user->derived_referer_source;
}
if (!empty($pageview->user->derived_referer_host_with_path)) {
$conversionSource->referer_host_with_path = $pageview->user->derived_referer_host_with_path;
}
if (isset($pageview->article->id)) {
$article = Article::where('external_id', $pageview->article->id)->first();
if ($article) {
$conversionSource->article_id = $article->id;
}
}
$conversionSource->conversion()->associate($conversion);
$conversionSource->save();
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Console/Commands/ElasticDataRetention.php | Beam/extensions/beam-module/src/Console/Commands/ElasticDataRetention.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Illuminate\Support\Str;
use Carbon\Carbon;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use Remp\BeamModule\Console\Command;
class ElasticDataRetention extends Command
{
const COMMAND = 'service:elastic-data-retention';
protected $signature = self::COMMAND . ' {--host=} {--match-index=} {--date=} {--auth=}';
protected $description = 'Data retention tries to find index based on match-index and date options and removes it';
public function handle()
{
if (!$this->input->getOption('host')) {
$this->line('<error>ERROR</error> You need to provide <info>--host</info> option with address to your Elastic instance (e.g. <info>--host=http://localhost:9200</info>)');
return 1;
}
if (!$this->input->getOption('match-index')) {
$this->line('<error>ERROR</error> You need to provide <info>--match-index</info> option with name of the index you want to cleanup (e.g. <info>--write-alias=pageviews_write</info>)');
return 1;
}
if (!$this->input->getOption('date')) {
$this->line('<error>ERROR</error> You need to provide <info>--date</info> option with date that will be searched within index name (e.g. <info>--date="90 days ago"</info>)');
return 1;
}
$date = new Carbon($this->input->getOption('date'));
$client = new Client([
'base_uri' => $this->input->getOption('host'),
]);
$this->line('');
$this->info('**** ' . self::COMMAND . ' (date: ' . (new Carbon())->format(DATE_RFC3339) . ') ****');
$targetIndices = sprintf(
"/%s*%s*",
$this->input->getOption('match-index'),
$date->format('Y.m.d')
);
$this->line(sprintf(
"Executing data retention for <info>%s%s</info> (date: %s)",
$this->input->getOption('host'),
$targetIndices,
$this->input->getOption('date')
));
// Return status 404 in case wildcard match doesn't find an index to delete
$targetIndices .= '?allow_no_indices=false';
$options = [];
if ($this->input->getOption('auth')) {
$auth = $this->input->getOption('auth');
if (!Str::contains($auth, ':')) {
$this->line("<error>ERROR</error> You need to provide <info>--auth</info> option with a name and a password (to Elastic instance) separated by ':', e.g. admin:password");
return 1;
}
[$user, $pass] = explode(':', $auth, 2);
$options = [
'auth' => [$user, $pass]
];
}
// execute index delete; https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-delete-index.html
try {
$client->delete($targetIndices, $options);
} catch (ClientException $e) {
$body = json_decode($e->getResponse()->getBody());
if ($e->getCode() === 404 && $body->error->type ?? '' === 'index_not_found_exception') {
$this->line(' * No index to delete.');
return 0;
}
$this->line("<error>ERROR</error> Client exception: " . $e->getMessage());
return 2;
}
$this->line(' * Done, index deleted.');
return 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/Console/Commands/SnapshotArticlesViews.php | Beam/extensions/beam-module/src/Console/Commands/SnapshotArticlesViews.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Helpers\Journal\JournalHelpers;
use Remp\BeamModule\Model\ArticleViewsSnapshot;
use Carbon\Carbon;
use Remp\BeamModule\Console\Command;
use Remp\Journal\ConcurrentsRequest;
use Remp\Journal\JournalContract;
class SnapshotArticlesViews extends Command
{
const COMMAND = 'pageviews:snapshot';
protected $signature = self::COMMAND . ' {--time=}';
protected $description = 'Snapshot current traffic data (rounded to minutes) from concurrents segment index';
private $journal;
private $journalHelper;
public function __construct(JournalContract $journal)
{
parent::__construct();
$this->journal = $journal;
$this->journalHelper = new JournalHelpers($journal);
}
public function handle()
{
$thisMinute = Carbon::now();
if ($this->hasOption('time')) {
$thisMinute = Carbon::parse($this->option('time'));
}
$this->line('');
$this->line("<info>***** Snapshotting traffic data for $thisMinute *****</info>");
$this->line('');
$this->snapshot($thisMinute);
$this->line(' <info>OK!</info>');
return 0;
}
private function snapshot(Carbon $now)
{
$to = $now;
$records = $this->journalHelper->currentConcurrentsCount(function (ConcurrentsRequest $req) {
$req->addGroup('article_id', 'derived_referer_medium', 'token');
}, $to);
$items = [];
$dbTime = $to->second(0)->microsecond(0);
foreach ($records as $record) {
$token = $record->tags->token;
$articleId = $record->tags->article_id;
$refererMedium = $record->tags->derived_referer_medium;
$items[] = [
'time' => $dbTime,
'property_token' => $token,
'external_article_id' => $articleId,
'referer_medium' => $refererMedium,
'count' => $record->count
];
}
// Save
ArticleViewsSnapshot::where('time', $dbTime)->delete();
foreach (array_chunk($items, 100) as $itemsChunk) {
ArticleViewsSnapshot::insert($itemsChunk);
$count = count($itemsChunk);
$this->line("$count records inserted");
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Console/Commands/CompressAggregations.php | Beam/extensions/beam-module/src/Console/Commands/CompressAggregations.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Model\ArticlePageviews;
use Remp\BeamModule\Model\ArticleTimespent;
use Remp\BeamModule\Model\Aggregable;
use Carbon\Carbon;
use Remp\BeamModule\Console\Command;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class CompressAggregations extends Command
{
const COMMAND = 'pageviews:compress-aggregations';
protected $signature = self::COMMAND . ' {--threshold=} {--debug}';
protected $description = 'Compress aggregations older than 90 days to daily aggregates.';
public function handle()
{
$debug = $this->option('debug') ?? false;
$sub = (int)($this->option('threshold') ?? config('beam.aggregated_data_retention_period'));
if ($sub < 0) {
$this->info("Negative threshold given ($sub), not compressing data.");
return 0;
}
$this->line('');
$this->line('<info>***** Compressing aggregations *****</info>');
$this->line('');
$this->line('Compressing data older than <info>' . $sub . ' days</info>.');
$threshold = Carbon::today()->subDays($sub);
$this->line('Processing <info>ArticlePageviews</info> table');
$this->aggregate(ArticlePageviews::class, $threshold, $debug);
$this->line('Processing <info>ArticleTimespents</info> table');
$this->aggregate(ArticleTimespent::class, $threshold, $debug);
$this->line(' <info>OK!</info>');
return 0;
}
public function aggregate($modelClass, Carbon $threshold, bool $debug)
{
if (!in_array(Aggregable::class, class_implements($modelClass), true)) {
throw new \InvalidArgumentException("'$modelClass' doesn't implement '" . Aggregable::class . "' interface");
}
/** @var Model|Aggregable $model */
$model = new $modelClass();
$this->getOutput()->write('Determining earliest date to compress: ');
$dateFromRaw = $modelClass::whereRaw('TIMESTAMPDIFF(HOUR, time_from, time_to) < 24')->min('time_from');
if (!$dateFromRaw) {
$this->line('nothing to compress!');
return;
}
$dateFrom = (new Carbon($dateFromRaw))->setTime(0, 0, 0);
$this->line($dateFrom->format('Y-m-d'));
while ($dateFrom <= $threshold) {
$this->getOutput()->write(" * Processing {$dateFrom->format('Y-m-d')}: ");
$dateTo = (clone $dateFrom)->addDay();
$ids = DB::table($model->getTable())
->select('id')
->whereRaw('TIMESTAMPDIFF(HOUR, time_from, time_to) < 24')
->where('time_from', '>=', $dateFrom)
->where('time_from', '<', $dateTo);
$rows = $model::select(
array_merge(
[
DB::raw("GROUP_CONCAT(DISTINCT id ORDER BY id SEPARATOR',') as ids_to_delete"),
],
$model->groupableFields(),
$this->getSumAgregablesSelection($model)
)
)
->whereIn('id', $ids)
->groupBy(...$model->groupableFields())
->cursor();
$limit = 256;
$i = 0;
$compressedRecords = [];
$idsToDelete = [];
foreach ($rows as $row) {
$data = $row->toArray();
$data['time_from'] = $dateFrom;
$data['time_to'] = $dateTo;
foreach (explode(',', $data['ids_to_delete']) as $id) {
$idsToDelete[] = (int) $id;
}
unset($data['ids_to_delete']);
$compressedRecords[] = $data;
if ($i >= $limit) {
if ($debug) {
$this->getOutput()->write('.');
}
DB::transaction(function () use ($modelClass, $compressedRecords, $idsToDelete) {
$modelClass::insert($compressedRecords);
$modelClass::whereIn('id', $idsToDelete)->delete();
});
$i = 0;
$compressedRecords = [];
$idsToDelete = [];
}
$i += 1;
}
if (count($compressedRecords)) {
DB::transaction(function () use ($modelClass, $compressedRecords, $idsToDelete) {
$modelClass::insert($compressedRecords);
$modelClass::whereIn('id', $idsToDelete)->delete();
});
}
$this->line('OK!');
$dateFrom = $dateFrom->addDay();
}
}
private function getSumAgregablesSelection(Aggregable $model): array
{
$items = [];
foreach ($model->aggregatedFields() as $field) {
$items[] = DB::raw("sum($field) as $field");
}
return $items;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Console/Commands/ComputeAuthorsSegments.php | Beam/extensions/beam-module/src/Console/Commands/ComputeAuthorsSegments.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Model\ArticleAggregatedView;
use Remp\BeamModule\Model\Author;
use Remp\BeamModule\Mail\AuthorSegmentsResult;
use Remp\BeamModule\Model\Config\Config;
use Remp\BeamModule\Model\Config\ConfigNames;
use Remp\BeamModule\Model\Segment;
use Remp\BeamModule\Model\SegmentBrowser;
use Remp\BeamModule\Model\SegmentGroup;
use Remp\BeamModule\Model\SegmentUser;
use Carbon\Carbon;
use Remp\BeamModule\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use PDO;
class ComputeAuthorsSegments extends Command
{
const COMMAND = 'segments:compute-author-segments';
const ALL_CONFIGS = [
ConfigNames::AUTHOR_SEGMENTS_MIN_RATIO,
ConfigNames::AUTHOR_SEGMENTS_MIN_AVERAGE_TIMESPENT,
ConfigNames::AUTHOR_SEGMENTS_MIN_VIEWS,
ConfigNames::AUTHOR_SEGMENTS_DAYS_IN_PAST
];
private $minViews;
private $minAverageTimespent;
private $minRatio;
private $historyDays;
private $dateThreshold;
protected $signature = self::COMMAND . '
{--email=}
{--history=}
{--min_views=}
{--min_average_timespent=}
{--min_ratio=}';
protected $description = "Generate authors' segments from aggregated pageviews and timespent data.";
public function handle()
{
ini_set('memory_limit', -1);
// Using Cursor on large number of results causing memory issues
// https://github.com/laravel/framework/issues/14919
DB::connection()->getPdo()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$this->line('');
$this->line('<info>***** Computing author segments *****</info>');
$this->line('');
$email = $this->option('email');
$historyDays = $this->option('history');
if ($historyDays === null) {
$historyDays = Config::loadByName(ConfigNames::SECTION_SEGMENTS_DAYS_IN_PAST);
}
if (!in_array($historyDays, [30,60,90])) {
$this->output->writeln('<error>ERROR</error> Invalid --history value provided (allowed values are 30, 60, 90): ' . $historyDays);
return 1;
}
$this->minViews = Config::loadByName(ConfigNames::AUTHOR_SEGMENTS_MIN_VIEWS);
$this->minAverageTimespent = Config::loadByName(ConfigNames::AUTHOR_SEGMENTS_MIN_AVERAGE_TIMESPENT);
$this->minRatio = Config::loadByName(ConfigNames::AUTHOR_SEGMENTS_MIN_RATIO);
$this->historyDays = $historyDays;
$this->dateThreshold = Carbon::today()->subDays($historyDays);
if ($email) {
// Only compute segment statistics
$this->line('Generating authors segments statistics');
$this->computeAuthorSegments($email);
} else {
// Generate real segments
$this->line('Generating authors segments');
$this->recomputeBrowsersForAuthorSegments();
$this->recomputeUsersForAuthorSegments();
$deletedSegments = self::deleteEmptySegments();
$this->line('Deleting empty author segments');
if ($deletedSegments > 0) {
$this->line("Deleted $deletedSegments segments");
}
}
$this->line(' <info>OK!</info>');
return 0;
}
/**
* @param $email
*/
private function computeAuthorSegments($email)
{
$minimalViews = $this->option('min_views') ?? $this->minViews;
$minimalAverageTimespent = $this->option('min_average_timespent') ?? $this->minAverageTimespent;
$minimalRatio = $this->option('min_ratio') ?? $this->minRatio;
$results = [];
$fromDay = $this->dateThreshold->toDateString();
// only 30, 60 and 90 are allowed values
$columnDays = 'total_views_last_' . $this->historyDays .'_days';
$this->line("running browsers query");
$browsersSql = <<<SQL
SELECT T.author_id, authors.name, count(*) AS browser_count
FROM
(SELECT browser_id, author_id, sum(pageviews) AS author_browser_views, avg(timespent) AS average_timespent
FROM article_aggregated_views C JOIN article_author A ON A.article_id = C.article_id
WHERE timespent <= 3600
AND date >= ?
GROUP BY browser_id, author_id
HAVING
author_browser_views >= ? AND
average_timespent >= ? AND
author_browser_views/(SELECT $columnDays FROM views_per_browser_mv WHERE browser_id = C.browser_id) >= ?
) T
JOIN authors ON authors.id = T.author_id
GROUP BY author_id
ORDER BY browser_count DESC
SQL;
$resultsBrowsers = DB::select($browsersSql, [$fromDay, $minimalViews, $minimalAverageTimespent, $minimalRatio]);
foreach ($resultsBrowsers as $item) {
$obj = new \stdClass();
$obj->name = $item->name;
$obj->browser_count = $item->browser_count;
$obj->user_count = 0;
$results[$item->author_id] = $obj;
}
$this->line("running users query");
$usersSql = <<<SQL
SELECT T.author_id, authors.name, count(*) AS user_count
FROM
(SELECT user_id, author_id, sum(pageviews) AS author_user_views, avg(timespent) AS average_timespent
FROM article_aggregated_views C JOIN article_author A ON A.article_id = C.article_id
WHERE timespent <= 3600
AND user_id <> ''
AND date >= ?
GROUP BY user_id, author_id
HAVING
author_user_views >= ? AND
average_timespent >= ? AND
author_user_views/(SELECT $columnDays FROM views_per_user_mv WHERE user_id = C.user_id) >= ?
) T JOIN authors ON authors.id = T.author_id
GROUP BY author_id ORDER BY user_count DESC
SQL;
$resultsUsers = DB::select($usersSql, [$fromDay, $minimalViews, $minimalAverageTimespent, $minimalRatio]);
foreach ($resultsUsers as $item) {
if (!array_key_exists($item->author_id, $results)) {
$obj = new \stdClass();
$obj->name = $item->name;
$obj->browser_count = 0;
$obj->user_count = 0;
$results[$item->author_id] = $obj;
}
$results[$item->author_id]->user_count = $item->user_count;
}
Mail::to($email)->send(
new AuthorSegmentsResult($results, $minimalViews, $minimalAverageTimespent, $minimalRatio, $this->historyDays)
);
}
private function recomputeUsersForAuthorSegments()
{
SegmentUser::whereHas('segment.segmentGroup', function ($q) {
$q->where('code', '=', SegmentGroup::CODE_AUTHORS_SEGMENTS);
})->delete();
$authorUsers = $this->groupDataFor('user_id');
$this->line("Updating segments users");
foreach ($authorUsers as $authorId => $users) {
if (count($users) === 0) {
continue;
}
$segment = $this->getOrCreateAuthorSegment($authorId);
foreach (array_chunk($users, 100) as $usersChunk) {
$toInsert = collect($usersChunk)->map(function ($userId) use ($segment) {
return [
'segment_id' => $segment->id,
'user_id' => $userId,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
];
});
SegmentUser::insert($toInsert->toArray());
}
}
}
private function recomputeBrowsersForAuthorSegments()
{
SegmentBrowser::whereHas('segment.segmentGroup', function ($q) {
$q->where('code', '=', SegmentGroup::CODE_AUTHORS_SEGMENTS);
})->delete();
$authorBrowsers = $this->groupDataFor('browser_id');
$this->line("Updating segments browsers");
foreach ($authorBrowsers as $authorId => $browsers) {
if (count($browsers) === 0) {
continue;
}
$segment = $this->getOrCreateAuthorSegment($authorId);
foreach (array_chunk($browsers, 100) as $browsersChunk) {
$toInsert = collect($browsersChunk)->map(function ($browserId) use ($segment) {
return [
'segment_id' => $segment->id,
'browser_id' => $browserId,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
];
});
SegmentBrowser::insert($toInsert->toArray());
}
}
}
private function aggregatedPageviewsFor($groupParameter)
{
$results = [];
// Not using model to save memory
$queryItems = DB::table(ArticleAggregatedView::getTableName())
->select($groupParameter, DB::raw('sum(pageviews) as total_pageviews'))
->whereNotNull($groupParameter)
->where('date', '>=', $this->dateThreshold)
->groupBy($groupParameter)
->cursor();
foreach ($queryItems as $item) {
$results[$item->$groupParameter] = (int) $item->total_pageviews;
}
return $results;
}
private function groupDataFor($groupParameter)
{
$this->getOutput()->write("Computing total pageviews for parameter '$groupParameter': ");
$totalPageviews = $this->aggregatedPageviewsFor($groupParameter);
$this->line(count($totalPageviews));
$segments = [];
$processed = 0;
$step = 500;
$bar = $this->output->createProgressBar(count($totalPageviews));
$bar->setFormat('%message%: %current%/%max% [%bar%] %percent:1s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
$bar->setMessage("Computing segment items for parameter '$groupParameter'");
foreach (array_chunk($totalPageviews, $step, true) as $totalPageviewsChunk) {
$forItems = array_map('strval', array_keys($totalPageviewsChunk));
$queryItems = DB::table(ArticleAggregatedView::getTableName())->select(
$groupParameter,
'author_id',
DB::raw('sum(pageviews) as total_pageviews'),
DB::raw('avg(timespent) as average_timespent')
)
->join('article_author', 'article_author.article_id', '=', 'article_aggregated_views.article_id')
->whereNotNull($groupParameter)
->where('date', '>=', $this->dateThreshold)
->whereIn($groupParameter, $forItems)
->groupBy([$groupParameter, 'author_id'])
->havingRaw('avg(timespent) >= ?', [$this->minAverageTimespent])
->cursor();
foreach ($queryItems as $item) {
if ($totalPageviews[$item->$groupParameter] === 0) {
continue;
}
$ratio = (int) $item->total_pageviews / $totalPageviews[$item->$groupParameter];
if ($ratio >= $this->minRatio && $item->total_pageviews >= $this->minViews) {
if (!array_key_exists($item->author_id, $segments)) {
$segments[$item->author_id] = [];
}
$segments[$item->author_id][] = $item->$groupParameter;
}
}
$processed += $step;
$bar->setProgress($processed);
}
$bar->finish();
$this->line('');
return $segments;
}
private function getOrCreateAuthorSegment($authorId)
{
$segmentGroup = SegmentGroup::where(['code' => SegmentGroup::CODE_AUTHORS_SEGMENTS])->first();
$author = Author::find($authorId);
return Segment::updateOrCreate([
'code' => 'author-' . $author->id
], [
'name' => 'Author ' . $author->name,
'active' => true,
'segment_group_id' => $segmentGroup->id,
]);
}
public static function deleteEmptySegments(): int
{
$first = DB::table(SegmentUser::getTableName())
->select('segment_id')
->groupBy('segment_id');
$unionQuery = DB::table(SegmentBrowser::getTableName())
->select('segment_id')
->groupBy('segment_id')
->union($first);
return Segment::leftJoinSub($unionQuery, 't', function ($join) {
$join->on('segments.id', '=', 't.segment_id');
})->whereNull('t.segment_id')
->where('segment_group_id', SegmentGroup::getByCode(SegmentGroup::CODE_AUTHORS_SEGMENTS)->id)
->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/Console/Commands/ComputeSectionSegments.php | Beam/extensions/beam-module/src/Console/Commands/ComputeSectionSegments.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Model\ArticleAggregatedView;
use Remp\BeamModule\Mail\SectionSegmentsResult;
use Remp\BeamModule\Model\Config\Config;
use Remp\BeamModule\Model\Config\ConfigNames;
use Remp\BeamModule\Model\Section;
use Remp\BeamModule\Model\Segment;
use Remp\BeamModule\Model\SegmentBrowser;
use Remp\BeamModule\Model\SegmentGroup;
use Remp\BeamModule\Model\SegmentUser;
use Carbon\Carbon;
use Remp\BeamModule\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use PDO;
class ComputeSectionSegments extends Command
{
const COMMAND = 'segments:compute-section-segments';
const ALL_CONFIGS = [
ConfigNames::SECTION_SEGMENTS_MIN_RATIO,
ConfigNames::SECTION_SEGMENTS_MIN_AVERAGE_TIMESPENT,
ConfigNames::SECTION_SEGMENTS_MIN_VIEWS,
ConfigNames::SECTION_SEGMENTS_DAYS_IN_PAST
];
private $minViews;
private $minAverageTimespent;
private $minRatio;
private $historyDays;
private $dateThreshold;
protected $signature = self::COMMAND . '
{--email=}
{--history=}
{--min_views=}
{--min_average_timespent=}
{--min_ratio=}';
protected $description = "Generate sections' segments from aggregated pageviews and timespent data.";
public function handle()
{
// Using Cursor on large number of results causing memory issues
// https://github.com/laravel/framework/issues/14919
DB::connection()->getPdo()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
$this->line('');
$this->line('<info>***** Computing section segments *****</info>');
$this->line('');
$email = $this->option('email');
$historyDays = $this->option('history');
if ($historyDays === null) {
$historyDays = Config::loadByName(ConfigNames::SECTION_SEGMENTS_DAYS_IN_PAST);
}
if (!in_array($historyDays, [30,60,90])) {
$this->output->writeln('<error>ERROR</error> Invalid --history value provided (allowed values are 30, 60, 90): ' . $historyDays);
return 1;
}
$this->minViews = Config::loadByName(ConfigNames::SECTION_SEGMENTS_MIN_VIEWS);
$this->minAverageTimespent = Config::loadByName(ConfigNames::SECTION_SEGMENTS_MIN_AVERAGE_TIMESPENT);
$this->minRatio = Config::loadByName(ConfigNames::SECTION_SEGMENTS_MIN_RATIO);
$this->historyDays = $historyDays;
$this->dateThreshold = Carbon::today()->subDays($historyDays);
if ($email) {
// Only compute segment statistics
$this->line('Generating sections segments statistics');
$this->computeSectionSegments($email);
} else {
// Generate real segments
$this->line('Generating sections segments');
$this->recomputeBrowsersForSectionSegments();
$this->recomputeUsersForSectionSegments();
$deletedSegments = self::deleteEmptySegments();
$this->line('Deleting empty section segments');
if ($deletedSegments > 0) {
$this->line("Deleted $deletedSegments segments");
}
}
$this->line(' <info>OK!</info>');
return 0;
}
/**
* @param $email
*/
private function computeSectionSegments($email)
{
$minimalViews = $this->option('min_views') ?? $this->minViews;
$minimalAverageTimespent = $this->option('min_average_timespent') ?? $this->minAverageTimespent;
$minimalRatio = $this->option('min_ratio') ?? $this->minRatio;
$results = [];
$fromDay = $this->dateThreshold->toDateString();
// only 30, 60 and 90 are allowed values
$columnDays = 'total_views_last_' . $this->historyDays .'_days';
$this->line("running browsers query");
$browsersSql = <<<SQL
SELECT T.section_id, sections.name, count(*) AS browser_count
FROM
(SELECT browser_id, section_id, sum(pageviews) AS section_browser_views, avg(timespent) AS average_timespent
FROM article_aggregated_views C JOIN article_section A ON A.article_id = C.article_id
WHERE timespent <= 3600
AND date >= ?
GROUP BY browser_id, section_id
HAVING
section_browser_views >= ? AND
average_timespent >= ? AND
section_browser_views/(SELECT $columnDays FROM views_per_browser_mv WHERE browser_id = C.browser_id) >= ?
) T
JOIN sections ON sections.id = T.section_id
GROUP BY section_id
ORDER BY browser_count DESC
SQL;
$resultsBrowsers = DB::select($browsersSql, [$fromDay, $minimalViews, $minimalAverageTimespent, $minimalRatio]);
foreach ($resultsBrowsers as $item) {
$obj = new \stdClass();
$obj->name = $item->name;
$obj->browser_count = $item->browser_count;
$obj->user_count = 0;
$results[$item->section_id] = $obj;
}
$this->line("running users query");
$usersSql = <<<SQL
SELECT T.section_id, sections.name, count(*) AS user_count
FROM
(SELECT user_id, section_id, sum(pageviews) AS section_user_views, avg(timespent) AS average_timespent
FROM article_aggregated_views C JOIN article_section A ON A.article_id = C.article_id
WHERE timespent <= 3600
AND user_id <> ''
AND date >= ?
GROUP BY user_id, section_id
HAVING
section_user_views >= ? AND
average_timespent >= ? AND
section_user_views/(SELECT $columnDays FROM views_per_user_mv WHERE user_id = C.user_id) >= ?
) T JOIN sections ON sections.id = T.section_id
GROUP BY section_id ORDER BY user_count DESC
SQL;
$resultsUsers = DB::select($usersSql, [$fromDay, $minimalViews, $minimalAverageTimespent, $minimalRatio]);
foreach ($resultsUsers as $item) {
if (!array_key_exists($item->section_id, $results)) {
$obj = new \stdClass();
$obj->name = $item->name;
$obj->browser_count = 0;
$obj->user_count = 0;
$results[$item->section_id] = $obj;
}
$results[$item->section_id]->user_count = $item->user_count;
}
Mail::to($email)->send(
new SectionSegmentsResult($results, $minimalViews, $minimalAverageTimespent, $minimalRatio, $this->historyDays)
);
}
private function recomputeUsersForSectionSegments()
{
SegmentUser::whereHas('segment.segmentGroup', function ($q) {
$q->where('code', '=', SegmentGroup::CODE_SECTIONS_SEGMENTS);
})->delete();
$sectionUsers = $this->groupDataFor('user_id');
$this->line("Updating segments users");
foreach ($sectionUsers as $sectionId => $users) {
if (count($users) === 0) {
continue;
}
$segment = $this->getOrCreateSectionSegment($sectionId);
foreach (array_chunk($users, 100) as $usersChunk) {
$toInsert = collect($usersChunk)->map(function ($userId) use ($segment) {
return [
'segment_id' => $segment->id,
'user_id' => $userId,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
];
});
SegmentUser::insert($toInsert->toArray());
}
}
}
private function recomputeBrowsersForSectionSegments()
{
SegmentBrowser::whereHas('segment.segmentGroup', function ($q) {
$q->where('code', '=', SegmentGroup::CODE_SECTIONS_SEGMENTS);
})->delete();
$sectionBrowsers = $this->groupDataFor('browser_id');
$this->line("Updating segments browsers");
foreach ($sectionBrowsers as $sectionId => $browsers) {
if (count($browsers) === 0) {
continue;
}
$segment = $this->getOrCreateSectionSegment($sectionId);
foreach (array_chunk($browsers, 100) as $browsersChunk) {
$toInsert = collect($browsersChunk)->map(function ($browserId) use ($segment) {
return [
'segment_id' => $segment->id,
'browser_id' => $browserId,
'created_at' => Carbon::now(),
'updated_at' => Carbon::now(),
];
});
SegmentBrowser::insert($toInsert->toArray());
}
}
}
private function aggregatedPageviewsFor($groupParameter)
{
$results = [];
// Not using model to save memory
$queryItems = DB::table(ArticleAggregatedView::getTableName())
->select($groupParameter, DB::raw('sum(pageviews) as total_pageviews'))
->whereNotNull($groupParameter)
->where('date', '>=', $this->dateThreshold)
->groupBy($groupParameter)
->cursor();
foreach ($queryItems as $item) {
$results[$item->$groupParameter] = (int) $item->total_pageviews;
}
return $results;
}
private function groupDataFor($groupParameter)
{
$this->getOutput()->write("Computing total pageviews for parameter '$groupParameter': ");
$totalPageviews = $this->aggregatedPageviewsFor($groupParameter);
$this->line(count($totalPageviews));
$segments = [];
$processed = 0;
$step = 500;
$bar = $this->output->createProgressBar(count($totalPageviews));
$bar->setFormat('%message%: %current%/%max% [%bar%] %percent:1s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
$bar->setMessage("Computing segment items for parameter '$groupParameter'");
foreach (array_chunk($totalPageviews, 500, true) as $totalPageviewsChunk) {
$forItems = array_map('strval', array_keys($totalPageviewsChunk));
$queryItems = DB::table(ArticleAggregatedView::getTableName())->select(
$groupParameter,
'section_id',
DB::raw('sum(pageviews) as total_pageviews'),
DB::raw('avg(timespent) as average_timespent')
)
->join('article_section', 'article_section.article_id', '=', 'article_aggregated_views.article_id')
->whereNotNull($groupParameter)
->where('date', '>=', $this->dateThreshold)
->whereIn($groupParameter, $forItems)
->groupBy([$groupParameter, 'section_id'])
->havingRaw('avg(timespent) >= ?', [$this->minAverageTimespent])
->cursor();
foreach ($queryItems as $item) {
if ($totalPageviews[$item->$groupParameter] === 0) {
continue;
}
$ratio = (int) $item->total_pageviews / $totalPageviews[$item->$groupParameter];
if ($ratio >= $this->minRatio && $item->total_pageviews >= $this->minViews) {
if (!array_key_exists($item->section_id, $segments)) {
$segments[$item->section_id] = [];
}
$segments[$item->section_id][] = $item->$groupParameter;
}
}
$processed += $step;
$bar->setProgress($processed);
}
$bar->finish();
$this->line('');
return $segments;
}
private function getOrCreateSectionSegment($sectionId)
{
$segmentGroup = SegmentGroup::where(['code' => SegmentGroup::CODE_SECTIONS_SEGMENTS])->first();
$section = Section::find($sectionId);
return Segment::updateOrCreate([
'code' => 'section-' . ($section ? $section->id : $sectionId)
], [
'name' => 'Section ' . ($section ? $section->name : $sectionId),
'active' => true,
'segment_group_id' => $segmentGroup->id,
]);
}
public static function deleteEmptySegments(): int
{
$first = DB::table(SegmentUser::getTableName())
->select('segment_id')
->groupBy('segment_id');
$unionQuery = DB::table(SegmentBrowser::getTableName())
->select('segment_id')
->groupBy('segment_id')
->union($first);
return Segment::leftJoinSub($unionQuery, 't', function ($join) {
$join->on('segments.id', '=', 't.segment_id');
})->whereNull('t.segment_id')
->where('segment_group_id', SegmentGroup::getByCode(SegmentGroup::CODE_SECTIONS_SEGMENTS)->id)
->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/Console/Commands/AggregatePageviewLoadJob.php | Beam/extensions/beam-module/src/Console/Commands/AggregatePageviewLoadJob.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\ArticlePageviews;
use Remp\BeamModule\Helpers\DebugProxy;
use Remp\BeamModule\Console\Command;
use Illuminate\Support\Carbon;
use Remp\Journal\AggregateRequest;
use Remp\Journal\JournalContract;
use Symfony\Component\Console\Helper\ProgressBar;
class AggregatePageviewLoadJob extends Command
{
const COMMAND = 'pageviews:aggregate-load';
protected $signature = self::COMMAND . ' {--now=} {--debug} {--article_id=}';
protected $description = 'Reads pageview/load data from journal and stores aggregated data';
public function handle(JournalContract $journalContract)
{
$debug = $this->option('debug') ?? false;
$articleId = $this->option('article_id') ?? null;
$now = $this->option('now') ? Carbon::parse($this->option('now')) : Carbon::now();
$timeBefore = $now->floorMinutes(20);
$timeAfter = (clone $timeBefore)->subMinutes(20);
$this->line(sprintf("Fetching aggregated pageviews data from <info>%s</info> to <info>%s</info>.", $timeAfter, $timeBefore));
$request = new AggregateRequest('pageviews', 'load');
$request->setTimeAfter($timeAfter);
$request->setTimeBefore($timeBefore);
if ($articleId) {
$request->addFilter('article_id', $articleId);
}
$request->addGroup('article_id', 'signed_in', 'subscriber');
$records = collect($journalContract->count($request));
if (count($records) === 0 || (count($records) === 1 && !isset($records[0]->tags->article_id))) {
$this->line(sprintf("No articles to process, exiting."));
return 0;
}
/** @var ProgressBar $bar */
$bar = new DebugProxy($this->output->createProgressBar(count($records)), $debug);
$bar->setFormat('%message%: %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
$bar->setMessage('Processing pageviews');
$all = [];
$signedIn = [];
$subscribers = [];
foreach ($records as $record) {
if (empty($record->tags->article_id)) {
$bar->advance();
continue;
}
$bar->setMessage(sprintf("Processing pageviews for article ID: <info>%s</info>", $record->tags->article_id));
$articleId = $record->tags->article_id;
$all[$articleId] = $all[$articleId] ?? 0;
$signedIn[$articleId] = $signedIn[$articleId] ?? 0;
$subscribers[$articleId] = $subscribers[$articleId] ?? 0;
$all[$articleId] += $record->count;
if (filter_var($record->tags->signed_in, FILTER_VALIDATE_BOOLEAN) === true) {
$signedIn[$articleId] += $record->count;
}
if (filter_var($record->tags->subscriber, FILTER_VALIDATE_BOOLEAN) === true) {
$subscribers[$articleId] += $record->count;
}
$bar->advance();
}
$bar->finish();
$this->line("\n<info>Pageviews loaded from Journal API</info>");
if (count($all) === 0) {
$this->line(sprintf('No data to store for articles, exiting.'));
return 0;
}
$externalIdsChunks = array_chunk(array_keys($all), 200);
/** @var ProgressBar $bar */
$bar = new DebugProxy($this->output->createProgressBar(count($externalIdsChunks)), $debug);
$bar->setFormat('%message%: [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
$bar->setMessage('Storing aggregated data');
$processedArticles = 0;
foreach ($externalIdsChunks as $externalIdsChunk) {
$articles = Article::whereIn(
'external_id',
array_map('strval', $externalIdsChunk)
)->get();
foreach ($articles as $article) {
$ap = ArticlePageviews::firstOrNew([
'article_id' => $article->id,
'time_from' => $timeAfter,
'time_to' => $timeBefore,
]);
$ap->sum = $all[$article->external_id];
$ap->signed_in = $signedIn[$article->external_id];
$ap->subscribers = $subscribers[$article->external_id];
$ap->save();
$article->pageviews_all = $article->pageviews()->sum('sum');
$article->pageviews_subscribers = $article->pageviews()->sum('subscribers');
$article->pageviews_signed_in = $article->pageviews()->sum('signed_in');
$article->save();
}
$processedArticles += count($externalIdsChunk);
$bar->setMessage(sprintf('Storing aggregated data (<info>%s/%s</info> articles)', $processedArticles, count($all)));
$bar->advance();
}
$bar->finish();
$this->line(" <info>OK!</info> (number of processed articles: $processedArticles)");
return 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/Console/Commands/AggregateConversionEvents.php | Beam/extensions/beam-module/src/Console/Commands/AggregateConversionEvents.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Helpers\Journal\JournalHelpers;
use Remp\BeamModule\Model\Conversion;
use Remp\BeamModule\Model\ConversionCommerceEvent;
use Remp\BeamModule\Model\ConversionCommerceEventProduct;
use Remp\BeamModule\Model\ConversionGeneralEvent;
use Remp\BeamModule\Model\ConversionPageviewEvent;
use Carbon\Carbon;
use Remp\BeamModule\Console\Command;
use Illuminate\Support\Collection;
use Remp\Journal\AggregateRequest;
use Remp\Journal\JournalContract;
use Remp\Journal\JournalException;
use Remp\Journal\ListRequest;
class AggregateConversionEvents extends Command
{
const COMMAND = 'conversions:aggregate-events';
const DAYS_IN_PAST = 14;
private const TEMP_PRODUCT_IDS_LABEL = 'TEMP_product_ids';
protected $signature = self::COMMAND . ' {--conversion_id=} {--days=' . self::DAYS_IN_PAST . '}';
protected $description = 'Aggregate events prior given conversion';
private $journal;
private $journalHelper;
public function __construct(JournalContract $journal)
{
parent::__construct();
$this->journal = $journal;
$this->journalHelper = new JournalHelpers($journal);
}
public function handle()
{
$this->line('Aggregation of conversion events started');
$conversionId = $this->option('conversion_id') ?? null;
$days = (int) $this->option('days');
if ($conversionId) {
$conversion = Conversion::find($conversionId);
if (!$conversion) {
$this->error("Conversion with ID $conversionId not found.");
return 1;
}
if ($conversion->events_aggregated) {
$this->info("Conversion with ID $conversionId already aggregated.");
return 2;
}
$this->aggregateConversion($conversion, $days);
} else {
foreach ($this->getUnaggregatedConversions() as $conversion) {
$this->aggregateConversion($conversion, $days);
}
}
$this->line(' <info>Done!</info>');
return 0;
}
protected function getBrowsersForUser(Conversion $conversion, $days, $category, $action = null)
{
$before = $conversion->paid_at;
// take maximum one year old browser IDs
$after = (clone $before)->subDays($days);
$browserIds = [];
$records = $this->journal->count(AggregateRequest::from($category, $action)
->addGroup('browser_id')
->addFilter('user_id', $conversion->user_id)
->setTime($after, $before));
foreach ($records as $record) {
if (!$record->count) {
continue;
}
if ($record->tags->browser_id && $record->tags->browser_id !== '') {
$browserIds[] = $record->tags->browser_id;
}
}
return $browserIds;
}
private function getUnaggregatedConversions(): Collection
{
return Conversion::where('events_aggregated', 0)
->orderBy('paid_at', 'DESC')
->get();
}
protected function aggregateConversion(Conversion $conversion, int $days)
{
if (!$conversion->user_id) {
$this->line("Conversion #{$conversion->id} has no assigned user.");
return;
}
$this->line("Aggregating conversion <info>#{$conversion->id}</info>");
$userBrowserIds = array_unique(
array_merge(
$this->getBrowsersForUser($conversion, $days, 'pageviews', 'load'),
$this->getBrowsersForUser($conversion, $days, 'commerce'),
$this->getBrowsersForUser($conversion, $days, 'events'),
)
);
try {
$pageviewEvents = $this->loadPageviewEvents(
$conversion,
$userBrowserIds,
$days
);
$commerceEvents = $this->loadCommerceEvents(
$conversion,
$userBrowserIds,
$days
);
$generalEvents = $this->loadGeneralEvents(
$conversion,
$userBrowserIds,
$days
);
// Compute event numbers prior conversion (across all event types)
$times = [];
foreach ($pageviewEvents as $event) {
$times[] = $event['time']->timestamp;
}
foreach ($commerceEvents as $event) {
$times[] = $event['time']->timestamp;
}
foreach ($generalEvents as $event) {
$times[] = $event['time']->timestamp;
}
rsort($times);
$timesIndex = [];
foreach ($times as $i => $timestamp) {
$timesIndex[(string)$timestamp] = $i + 1;
}
// Save events
$this->savePageviewEvents($pageviewEvents, $timesIndex);
$this->saveCommerceEvents($commerceEvents, $timesIndex);
$this->saveGeneralEvents($generalEvents, $timesIndex);
$conversion->events_aggregated = true;
$conversion->save();
} catch (JournalException $exception) {
$this->error($exception->getMessage());
}
}
protected function savePageviewEvents(array &$events, &$timesIndex)
{
foreach ($events as $data) {
$data['event_prior_conversion'] = $timesIndex[(string)$data['time']->timestamp];
ConversionPageviewEvent::create($data);
}
}
protected function saveCommerceEvents(array &$events, &$timesIndex)
{
foreach ($events as $data) {
$data['event_prior_conversion'] = $timesIndex[(string)$data['time']->timestamp];
$productIds = $data[self::TEMP_PRODUCT_IDS_LABEL];
unset($data[self::TEMP_PRODUCT_IDS_LABEL]);
$commerceEvent = ConversionCommerceEvent::create($data);
foreach ($productIds as $productId) {
$product = new ConversionCommerceEventProduct(['product_id' => $productId]);
$commerceEvent->products()->save($product);
}
}
}
protected function saveGeneralEvents(array &$events, &$timesIndex)
{
foreach ($events as $data) {
$data['event_prior_conversion'] = $timesIndex[(string)$data['time']->timestamp];
ConversionGeneralEvent::create($data);
}
}
protected function loadPageviewEvents(Conversion $conversion, array $browserIds, $days): array
{
if (!$browserIds) {
return [];
}
$from = (clone $conversion->paid_at)->subDays($days);
$to = $conversion->paid_at;
$r = ListRequest::from('pageviews')
->setTime($from, $to)
->addFilter('browser_id', ...$browserIds)
->setLoadTimespent();
$events = collect($this->journal->list($r));
$toSave = [];
if ($events->isNotEmpty()) {
foreach ($events[0]->pageviews as $item) {
if (!isset($item->article->id)) {
continue;
}
$article = Article::where('external_id', $item->article->id)->first();
if ($article) {
$time = Carbon::parse($item->system->time);
$timeToConversion = $time->diffInMinutes($conversion->paid_at);
$toSave[] = [
'conversion_id' => $conversion->id,
'time' => $time,
'minutes_to_conversion' => $timeToConversion,
'article_id' => $article->id,
'locked' => isset($item->article->locked) ? filter_var($item->article->locked, FILTER_VALIDATE_BOOLEAN) : null,
'signed_in' => isset($item->user->id),
'timespent' => $item->user->timespent ?? null,
// Background compatibility with utm_ -- will be removed
'rtm_campaign' => $item->user->source->rtm_campaign ?? $item->user->source->utm_campaign ?? null,
'rtm_content' => $item->user->source->rtm_content ?? $item->user->source->utm_content ?? null,
'rtm_medium' => $item->user->source->rtm_medium ?? $item->user->source->utm_medium ?? null,
'rtm_source' => $item->user->source->rtm_source ?? $item->user->source->utm_source ?? null,
];
}
}
}
return $toSave;
}
protected function loadCommerceEvents(Conversion $conversion, array $browserIds, $days): array
{
$from = (clone $conversion->paid_at)->subDays($days);
$to = $conversion->paid_at;
$processedIds = [];
$toSave = [];
$process = function ($request) use ($conversion, &$processedIds, &$toSave) {
$events = collect($this->journal->list($request));
if ($events->isNotEmpty()) {
foreach ($events[0]->commerces as $item) {
if (array_key_exists($item->id, $processedIds)) {
continue;
}
$processedIds[$item->id] = true;
$time = Carbon::parse($item->system->time);
$timeToConversion = $time->diffInMinutes($conversion->paid_at);
$step = $item->step;
$toSave[] = [
'time' => $time,
'minutes_to_conversion' => $timeToConversion,
'step' => $step,
'funnel_id' => $item->$step->funnel_id ?? null,
'amount' => $item->$step->revenue->amount ?? null,
'currency' => $item->$step->revenue->currency ?? null,
// background compatibility with utm -- will be removed
'rtm_campaign' => $item->source->rtm_campaign ?? $item->source->utm_campaign ?? null,
'rtm_content' => $item->source->rtm_content ?? $item->source->utm_content ?? null,
'rtm_medium' => $item->source->rtm_medium ?? $item->source->utm_medium ?? null,
'rtm_source' => $item->source->rtm_source ?? $item->source->utm_source ?? null,
'conversion_id' => $conversion->id,
self::TEMP_PRODUCT_IDS_LABEL => $item->$step->product_ids ?? [] // this will be removed later
];
}
}
};
if ($browserIds) {
$process(ListRequest::from("commerce")
->setTime($from, $to)
->addFilter('browser_id', ...$browserIds));
}
$process(ListRequest::from("commerce")
->setTime($from, $to)
->addFilter('user_id', $conversion->user_id));
return $toSave;
}
protected function loadGeneralEvents(Conversion $conversion, array $browserIds, $days): array
{
$from = (clone $conversion->paid_at)->subDays($days);
$to = $conversion->paid_at;
$processedIds = [];
$toSave = [];
$process = function ($request) use ($conversion, &$processedIds, &$toSave) {
$events = collect($this->journal->list($request));
if ($events->isNotEmpty()) {
foreach ($events[0]->events as $item) {
if (array_key_exists($item->id, $processedIds)) {
continue;
}
$processedIds[$item->id] = true;
$time = Carbon::parse($item->system->time);
$timeToConversion = $time->diffInMinutes($conversion->paid_at);
$toSave[] = [
'time' => $time,
'minutes_to_conversion' => $timeToConversion,
'action' => $item->action ?? null,
'category' => $item->category ?? null,
'conversion_id' => $conversion->id,
// Background compatibility with utm_ -- will be removed
'rtm_campaign' => $item->rtm_campaign ?? $item->utm_campaign ?? null,
'rtm_content' => $item->rtm_content ?? $item->utm_content ?? null,
'rtm_medium' => $item->rtm_medium ?? $item->utm_medium ?? null,
'rtm_source' => $item->rtm_source ?? $item->utm_source ?? null,
];
}
}
};
if ($browserIds) {
$process(ListRequest::from('events')
->setTime($from, $to)
->addFilter('browser_id', ...$browserIds));
}
$process(ListRequest::from('events')
->setTime($from, $to)
->addFilter('user_id', $conversion->user_id));
return $toSave;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/src/Console/Commands/ProcessPageviewLoyalVisitors.php | Beam/extensions/beam-module/src/Console/Commands/ProcessPageviewLoyalVisitors.php | <?php
namespace Remp\BeamModule\Console\Commands;
use Remp\BeamModule\Model\Segment;
use Remp\BeamModule\Model\SegmentGroup;
use Remp\BeamModule\Console\Command;
use Illuminate\Support\Carbon;
use Remp\Journal\AggregateRequest;
use Remp\Journal\JournalContract;
class ProcessPageviewLoyalVisitors extends Command
{
protected $signature = 'pageviews:loyal-visitors {--days=}';
protected $description = 'Determines number of articles read by top 10% of readers and creates segment based on it';
public function handle(JournalContract $journalContract)
{
$days = $this->option('days') ?? 30;
if (!$days) {
$this->line("No days to process, exiting.");
return 0;
}
$bar = $this->output->createProgressBar($days);
$bar->setFormat('%message%: %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%');
$bar->setMessage('Extracting aggregated pageview data (days)');
$browsersToUsers = [];
$readers = [];
foreach (range(1, $days) as $dayOffset) {
$now = Carbon::now();
$timeBefore = $now->copy()->setTime(0, 0)->subDays($dayOffset);
$timeAfter = $now->copy()->setTime(0, 0)->subDays($dayOffset+1);
$request = new AggregateRequest('pageviews', 'load');
$request->setTimeAfter($timeAfter);
$request->setTimeBefore($timeBefore);
$request->addFilter('_article', 'true');
$request->addGroup("user_id", "browser_id");
$pageviews = collect($journalContract->count($request));
foreach ($pageviews as $record) {
if ($record->count === 0) {
continue;
}
if (!empty($record->tags->user_id)) {
if (!isset($readers[$record->tags->user_id])) {
$readers[$record->tags->user_id] = 0;
}
if (isset($record->tags->browser_id) && !isset($browsersToUsers[$record->tags->browser_id])) {
$browsersToUsers[$record->tags->browser_id] = $record->tags->user_id;
}
$readers[$record->tags->user_id] += $record->count;
}
if (!empty($record->tags->browser_id)) {
if (!isset($readers[$record->tags->browser_id])) {
$readers[$record->tags->browser_id] = 0;
}
if (isset($browsersToUsers[$record->tags->browser_id])) {
$userId = $browsersToUsers[$record->tags->browser_id];
$readers[$userId] += $record->count;
} else {
$readers[$record->tags->browser_id] += $record->count;
}
}
}
$bar->advance();
break;
}
$bar->finish();
$this->line(' <info>OK!</info>');
rsort($readers, SORT_NUMERIC);
$topReaders = array_slice($readers, 0, ceil(count($readers) * 0.1));
$treshold = array_pop($topReaders);
$this->line("Top 10% of your readers read at least <info>{$treshold} articles within {$days} days range</info>");
if ($treshold <= 1) {
$this->line("No segment will be created, treshold would be too low");
return 1;
}
$segmentCode = "{$treshold}-plus-article-views-in-{$days}-days";
if (Segment::where(['code' => $segmentCode])->exists()) {
$this->line("Segment <info>{$segmentCode}</info> already exists, no new segment was created");
return 2;
}
$segment = Segment::create([
'name' => "{$treshold}+ article views in {$days} days",
'code' => $segmentCode,
'active' => true,
'segment_group_id' => SegmentGroup::getByCode(SegmentGroup::CODE_REMP_SEGMENTS)->id,
]);
$segment->rules()->create([
'timespan' => $days*24*60,
'count' => $treshold,
'event_category' => 'pageview',
'event_action' => 'load',
'operator' => '>=',
'fields' => [],
'flags' => ['is_article' => '1'],
]);
$this->line("Segment <info>{$segmentCode}</info> was created, you can use it to target your loyal audience");
return 0;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/TestCase.php | Beam/extensions/beam-module/tests/TestCase.php | <?php
namespace Remp\BeamModule\Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/CreatesApplication.php | Beam/extensions/beam-module/tests/CreatesApplication.php | <?php
namespace Remp\BeamModule\Tests;
use Illuminate\Contracts\Console\Kernel;
trait CreatesApplication
{
/**
* Creates the application.
*
* @return \Illuminate\Foundation\Application
*/
public function createApplication()
{
$app = require __DIR__ . '/../../../bootstrap/app.php';
if ($path = realpath(__DIR__ . '/../../../bootstrap/app.php')) {
$app = require $path;
}
// from vendor
if ($path = realpath(__DIR__ . '/../../../../bootstrap/app.php')) {
$app = require $path;
}
$app->make(Kernel::class)->bootstrap();
return $app;
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/CompressAggregationsTest.php | Beam/extensions/beam-module/tests/Feature/CompressAggregationsTest.php | <?php
namespace Remp\BeamModule\Tests\Feature;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\ArticlePageviews;
use Remp\BeamModule\Model\ArticleTimespent;
use Remp\BeamModule\Console\Commands\CompressAggregations;
use Remp\BeamModule\Model\Property;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Remp\BeamModule\Tests\TestCase;
class CompressAggregationsTest extends TestCase
{
use RefreshDatabase;
private $thresholdPeriod;
protected function setUp(): void
{
parent::setUp();
$this->thresholdPeriod = config('beam.aggregated_data_retention_period');
Article::unsetEventDispatcher();
}
public function testPageviewsAggregations()
{
$this->runAndTestArticleAggregations(ArticlePageviews::class);
}
public function testTimespentAggregations()
{
$this->runAndTestArticleAggregations(ArticleTimespent::class);
}
public function runAndTestArticleAggregations($className)
{
$property = Property::factory()->create();
$article1 = Article::factory()->create(['property_uuid' => $property->uuid]);
$article2 = Article::factory()->create(['property_uuid' => $property->uuid]);
// Prepare data to be aggregated
$ag1 = $className::factory()->create([
'article_id' => $article1->id,
'time_from' => Carbon::today()->hour(9)->subDays(91),
'time_to' => Carbon::today()->hour(10)->subDays(91),
]);
$ag2 = $className::factory()->create([
'article_id' => $article1->id,
'time_from' => Carbon::today()->hour(10)->subDays(91),
'time_to' => Carbon::today()->hour(11)->subDays(91),
]);
$className::factory()->create([
'article_id' => $article2->id,
'time_from' => Carbon::today()->hour(10)->subDays(91),
'time_to' => Carbon::today()->hour(11)->subDays(91),
]);
$className::factory()->create([
'article_id' => $article1->id,
'time_from' => Carbon::today()->hour(10)->subDays(90),
'time_to' => Carbon::today()->hour(11)->subDays(90),
]);
// These won't be aggregated
$className::factory()->create([
'article_id' => $article1->id,
'time_from' => Carbon::today()->hour(10)->subDays(89),
'time_to' => Carbon::today()->hour(11)->subDays(89),
]);
// Prepare asserts
$runAsserts = function () use ($ag1, $ag2, $article1, $article2, $className) {
$ag = $className::where('article_id', $article1->id)
->where('time_to', '<=', Carbon::today()->subDays(90))->first();
$this->assertEquals($ag1->sum + $ag2->sum, $ag->sum);
$this->assertEquals($ag1->signed_in + $ag2->signed_in, $ag->signed_in);
$this->assertEquals($ag1->subscribers + $ag2->subscribers, $ag->subscribers);
$this->assertEquals(3, $className::where('article_id', $article1->id)->count());
$this->assertEquals(1, $className::where('article_id', $article2->id)->count());
};
// Run test
$this->artisan(CompressAggregations::COMMAND);
$runAsserts();
// Make sure when command is run twice, results are the same
$this->artisan(CompressAggregations::COMMAND);
$runAsserts();
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/ComputeAuthorsSegmentsTest.php | Beam/extensions/beam-module/tests/Feature/ComputeAuthorsSegmentsTest.php | <?php
namespace Remp\BeamModule\Tests\Feature;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Remp\BeamModule\Console\Commands\ComputeAuthorsSegments;
use Remp\BeamModule\Database\Seeders\ConfigSeeder;
use Remp\BeamModule\Database\Seeders\SegmentGroupSeeder;
use Remp\BeamModule\Model\Account;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\ArticleAggregatedView;
use Remp\BeamModule\Model\Author;
use Remp\BeamModule\Model\Property;
use Remp\BeamModule\Model\Segment;
use Remp\BeamModule\Model\SegmentBrowser;
use Remp\BeamModule\Model\SegmentUser;
use Remp\BeamModule\Tests\TestCase;
class ComputeAuthorsSegmentsTest extends TestCase
{
use RefreshDatabase;
public function setUp(): void
{
parent::setUp();
$this->seed(ConfigSeeder::class);
$this->seed(SegmentGroupSeeder::class);
}
public function testJob()
{
Article::unsetEventDispatcher();
$account = Account::factory()->create();
$property = Property::factory()->create(['account_id' => $account->id]);
$article = Article::factory()->create([
'external_id' => 1,
'property_uuid' => $property->uuid,
]);
$author = Author::factory()->create();
$article->authors()->save($author);
$date = Carbon::today()->toDateString();
// First we need aggregated data
// These pageviews/timespent data are above defined author segments critera,
// see job implementation for details
$items = [
[
'article_id' => $article->id,
'user_id' => null,
'browser_id' => 'XYZ',
'date' => $date,
'pageviews' => 10,
'timespent' => 1800 // 30 min
],
[
'article_id' => $article->id,
'user_id' => '9',
'browser_id' => 'ABC',
'date' => $date,
'pageviews' => 10,
'timespent' => 1800 // 30 min
]
];
ArticleAggregatedView::insert($items);
$this->artisan(ComputeAuthorsSegments::COMMAND);
$segment = Segment::where('code', 'author-' . $author->id)->first();
$segmentBrowserIds = $segment->browsers->pluck('browser_id');
$segmentUserIds = $segment->users->pluck('user_id');
$this->assertContains('ABC', $segmentBrowserIds);
$this->assertContains('XYZ', $segmentBrowserIds);
$this->assertContains('9', $segmentUserIds);
}
public function testDeletingEmptySegments()
{
SegmentBrowser::query()->delete();
SegmentUser::query()->delete();
Segment::query()->delete();
$s1 = Segment::factory()->author()->create();
$s1->users()->save(SegmentUser::factory()->make());
$s1->browsers()->save(SegmentBrowser::factory()->make());
$s2 = Segment::factory()->author()->create();
$s2->users()->save(SegmentUser::factory()->make());
$s3 = Segment::factory()->author()->create();
$s3->browsers()->save(SegmentBrowser::factory()->make());
Segment::factory()->author()->create();
$this->assertEquals(4, Segment::all()->count());
ComputeAuthorsSegments::deleteEmptySegments();
// Check that only segments without browsers and users were deleted
$this->assertEquals(3, Segment::all()->count());
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/ProcessConversionSourcesTest.php | Beam/extensions/beam-module/tests/Feature/ProcessConversionSourcesTest.php | <?php
namespace Remp\BeamModule\Tests\Feature;
use Remp\BeamModule\Model\Account;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Console\Commands\ProcessConversionSources;
use Remp\BeamModule\Model\Conversion;
use Remp\BeamModule\Model\ConversionCommerceEvent;
use Remp\BeamModule\Model\ConversionSource;
use Remp\BeamModule\Model\Property;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;
use Remp\Journal\Journal;
use Remp\Journal\JournalContract;
use Remp\BeamModule\Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery;
class ProcessConversionSourcesTest extends TestCase
{
use RefreshDatabase;
/** @var Property */
private $property;
/** @var JournalContract */
private $journal;
protected function setUp(): void
{
parent::setUp();
Article::unsetEventDispatcher();
$account = Account::factory()->create();
$this->property = Property::factory()->create(['account_id' => $account->id]);
// Mock Journal data
$this->journal = Mockery::mock(Journal::class);
// Bypass RempJournalServiceProvider binding
$this->app->instance('mockJournal', $this->journal);
$this->app->when(ProcessConversionSources::class)
->needs(JournalContract::class)
->give('mockJournal');
}
public function testSuccessMultiplePageviews()
{
$referalArticle = Article::factory()->create([
'external_id' => 9,
'property_uuid' => $this->property->uuid,
]);
$conversionArticle = Article::factory()->create([
'external_id' => 'article1',
'property_uuid' => $this->property->uuid,
]);
$conversion = Conversion::factory()->create([
'user_id' => 26,
'transaction_id' => '1234567890',
'article_id' => $conversionArticle->id,
'events_aggregated' => true,
]);
ConversionCommerceEvent::factory()->create([
'conversion_id' => $conversion,
'step' => 'payment',
'time' => Carbon::createFromTimeString('2020-08-06T14:36:47Z'),
]);
$this->journal->shouldReceive('addFilter')
->withArgs([$conversion->transaction_id]);
$this->journal->shouldReceive('list')
->andReturn(
$this->loadJson('step_payment_1234567890.json'), // to get browser ID
$this->loadJson('testSuccessMultiplePageviews_pageviews.json'), // to get pageviews
);
$this->artisan(ProcessConversionSources::COMMAND, ['--conversion_id' => $conversion->id]);
//retrieve processed conversion sources
$conversionSources = ConversionSource::where(['conversion_id' => $conversion->id])->get();
$firstConversionSource = $conversionSources->where('type', ConversionSource::TYPE_SESSION_FIRST)->first();
$lastConversionSource = $conversionSources->where('type', ConversionSource::TYPE_SESSION_LAST)->first();
$this->assertEquals(2, $conversionSources->count());
$this->assertEquals('search', $firstConversionSource->referer_medium);
$this->assertEquals('internal', $lastConversionSource->referer_medium);
$this->assertNull($firstConversionSource->referer_host_with_path);
$this->assertEquals('http://localhost:63342/remp-sample-blog/index.html', $lastConversionSource->referer_host_with_path);
$this->assertEquals($referalArticle->id, $lastConversionSource->article_id);
$conversion->refresh();
$this->assertTrue($conversion->source_processed);
}
public function testSuccessfulSinglePageview()
{
$conversionArticle = Article::factory()->create([
'external_id' => 'article1',
'property_uuid' => $this->property->uuid,
]);
$conversion = Conversion::factory()->create([
'user_id' => 26,
'article_id' => $conversionArticle->id,
'transaction_id' => '1234567890',
'events_aggregated' => true,
]);
ConversionCommerceEvent::factory()->create([
'conversion_id' => $conversion,
'step' => 'payment',
'time' => Carbon::createFromTimeString('2020-08-06T14:36:47Z'),
]);
$this->journal->shouldReceive('addFilter')
->withArgs([$conversion->transaction_id]);
$this->journal->shouldReceive('list')
->andReturn(
$this->loadJson('step_payment_1234567890.json'), // to get browser ID
$this->loadJson('testSuccessSinglePageview_pageviews.json'), // to get pageviews
);
$this->artisan(ProcessConversionSources::COMMAND, ['--conversion_id' => $conversion->id]);
//retrieve processed conversion sources
$conversionSources = ConversionSource::where(['conversion_id' => $conversion->id])->get();
$firstConversionSource = $conversionSources->where('type', ConversionSource::TYPE_SESSION_FIRST)->first();
$lastConversionSource = $conversionSources->where('type', ConversionSource::TYPE_SESSION_LAST)->first();
$this->assertEquals(2, $conversionSources->count());
$this->assertEquals('social', $firstConversionSource->referer_medium);
$this->assertEquals('social', $lastConversionSource->referer_medium);
$conversion->refresh();
$this->assertTrue($conversion->source_processed);
}
public function testNoPageview()
{
$conversionArticle = Article::factory()->create([
'external_id' => 'article1',
'property_uuid' => $this->property->uuid,
]);
$conversion = Conversion::factory()->create([
'user_id' => 26,
'article_id' => $conversionArticle->id,
'transaction_id' => '1234567890',
'events_aggregated' => true,
]);
ConversionCommerceEvent::factory()->create([
'conversion_id' => $conversion,
'step' => 'payment',
'time' => Carbon::createFromTimeString('2020-08-06T14:36:47Z'),
]);
$this->journal->shouldReceive('addFilter')
->withArgs([$conversion->transaction_id]);
$this->journal->shouldReceive('list')
->andReturn(
$this->loadJson('step_payment_1234567890.json'), // to get browser ID
$this->loadJson('testNoPageview_pageviews.json'), // to get pageviews
);
$this->artisan(ProcessConversionSources::COMMAND, ['--conversion_id' => $conversion->id]);
//retrieve processed conversion sources
$conversionSources = ConversionSource::where(['conversion_id' => $conversion->id])->get();
$this->assertEquals(0, $conversionSources->count());
$conversion->refresh();
$this->assertTrue($conversion->source_processed);
}
public function testEventsNotAggregatedYet()
{
$conversionArticle = Article::factory()->create([
'external_id' => 'article1',
'property_uuid' => $this->property->uuid,
]);
$conversion = Conversion::factory()->create([
'user_id' => 26,
'article_id' => $conversionArticle->id,
'transaction_id' => '1234567890',
'events_aggregated' => false,
]);
$this->journal->shouldNotReceive('list');
$this->artisan(ProcessConversionSources::COMMAND, ['--conversion_id' => $conversion->id]);
$conversion->refresh();
$this->assertFalse($conversion->source_processed);
}
public function testMissingCommercePaymentEvent()
{
$conversionArticle = Article::factory()->create([
'external_id' => 'article1',
'property_uuid' => $this->property->uuid,
]);
$conversion = Conversion::factory()->create([
'user_id' => 26,
'article_id' => $conversionArticle->id,
'transaction_id' => '1234567890',
'events_aggregated' => true,
]);
ConversionCommerceEvent::factory()->create([
'conversion_id' => $conversion,
'step' => 'payment',
'time' => Carbon::createFromTimeString('2020-08-06T14:36:47Z'),
]);
// return empty commerce events list
$this->journal->shouldReceive('list')->andReturn([]);
Log::shouldReceive('warning');
$this->artisan(ProcessConversionSources::COMMAND, ['--conversion_id' => $conversion->id]);
$conversion->refresh();
$this->assertTrue($conversion->source_processed);
}
public function testMissingBrowserId()
{
$conversionArticle = Article::factory()->create([
'external_id' => 'article1',
'property_uuid' => $this->property->uuid,
]);
$conversion = Conversion::factory()->create([
'user_id' => 26,
'article_id' => $conversionArticle->id,
'transaction_id' => '1234567890',
'events_aggregated' => true,
]);
ConversionCommerceEvent::factory()->create([
'conversion_id' => $conversion,
'step' => 'payment',
'time' => Carbon::createFromTimeString('2020-08-06T14:36:47Z'),
]);
// return empty commerce events list
$this->journal->shouldReceive('list')
->andReturn($this->loadJson('step_payment_1234567890_missing_browser_id.json'));
Log::shouldReceive('warning');
$this->artisan(ProcessConversionSources::COMMAND, ['--conversion_id' => $conversion->id]);
$conversion->refresh();
$this->assertTrue($conversion->source_processed);
}
private function loadJson($file)
{
return json_decode(
file_get_contents(__DIR__ . '/ProcessConversionSourcesTest/' . $file),
false,
512,
JSON_THROW_ON_ERROR
);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/AggregateArticlesViewsTest.php | Beam/extensions/beam-module/tests/Feature/AggregateArticlesViewsTest.php | <?php
namespace Remp\BeamModule\Tests\Feature;
use Remp\BeamModule\Model\Account;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\ArticleAggregatedView;
use Remp\BeamModule\Console\Commands\AggregateArticlesViews;
use Remp\BeamModule\Model\Property;
use Mockery;
use Remp\Journal\Journal;
use Remp\Journal\JournalContract;
use Remp\BeamModule\Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class AggregateArticlesViewsTest extends TestCase
{
use RefreshDatabase;
public function testJob()
{
Article::unsetEventDispatcher();
$pageviews1 = <<<JSON
[
{
"count": 8,
"tags": {
"article_id": "2148518",
"user_id": "1234",
"browser_id": "abcd"
}
},
{
"count": 3,
"tags": {
"article_id": "1148518",
"user_id": "1234",
"browser_id": "abcd"
}
}
]
JSON;
$pageviews2 = <<<JSON
[
{
"count": 3,
"tags": {
"article_id": "1148518",
"user_id": "1234",
"browser_id": "abcd"
}
}
]
JSON;
$pageviews3 = '[]';
$timespent1 = <<<JSON
[
{
"sum": 10,
"tags": {
"article_id": "2148518",
"user_id": "1234",
"browser_id": "abcd"
}
}
]
JSON;
$timespent2 = <<<JSON
[
{
"sum": 25,
"tags": {
"article_id": "2148518",
"user_id": "1234",
"browser_id": "abcd"
}
}
]
JSON;
$timespent3 = '[]';
$account = Account::factory()->create();
$property = Property::factory()->create(['account_id' => $account->id]);
$article1148518 = Article::factory()->create([
'external_id' => 1148518,
'property_uuid' => $property->uuid,
]);
$article2148518 = Article::factory()->create([
'external_id' => 2148518,
'property_uuid' => $property->uuid,
]);
// Mock Journal data
// job aggregates pageviews day data in time windows
$journalMock = Mockery::mock(Journal::class);
$journalMock->shouldReceive('count')->andReturn(
json_decode($pageviews1),
json_decode($pageviews2),
json_decode($pageviews3)
);
// job aggregates timespent day data in time windows
$journalMock->shouldReceive('sum')->andReturn(
json_decode($timespent1),
json_decode($timespent2),
json_decode($timespent3)
);
// Bypass RempJournalServiceProvider binding
$this->app->instance('mockJournal', $journalMock);
$this->app->when(AggregateArticlesViews::class)
->needs(JournalContract::class)
->give('mockJournal');
$this->artisan(AggregateArticlesViews::COMMAND);
$articleView2148518 = ArticleAggregatedView::where([
'article_id' => $article2148518->id,
'user_id' => '1234'
])->first();
$this->assertEquals(8, $articleView2148518->pageviews);
$this->assertEquals(35, $articleView2148518->timespent);
$articleView1148518 = ArticleAggregatedView::where([
'article_id' => $article1148518->id,
'user_id' => '1234'
])->first();
$this->assertEquals(6, $articleView1148518->pageviews);
$this->assertEquals(0, $articleView1148518->timespent);
// Test when aggregation is run twice (and no aggregated data is returned), former data is deleted
$this->artisan(AggregateArticlesViews::COMMAND);
$this->assertEquals(0, ArticleAggregatedView::all()->count());
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/CompressSnapshotsTest.php | Beam/extensions/beam-module/tests/Feature/CompressSnapshotsTest.php | <?php
namespace Remp\BeamModule\Tests\Feature;
use Remp\BeamModule\Console\Commands\CompressSnapshots;
use Remp\BeamModule\Model\ArticleViewsSnapshot;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Remp\BeamModule\Tests\TestCase;
class CompressSnapshotsTest extends TestCase
{
use RefreshDatabase;
public function testComputePeriods()
{
$command = new CompressSnapshots();
$periods = $command->computeDayPeriods(Carbon::now(), 0, 60);
$this->assertCount(1, $periods);
$periods = $command->computeDayPeriods(Carbon::now(), 0, 60 * 24);
$this->assertCount(1, $periods);
$periods = $command->computeDayPeriods(Carbon::now(), 0, 60 * 25);
$this->assertCount(2, $periods);
$periods = $command->computeDayPeriods(Carbon::now(), 0, 60 * 60);
$this->assertCount(3, $periods);
}
public function testCompression()
{
$start = Carbon::now();
$start->setTime($start->hour, $start->minute, 0, 0);
//Last 10 minutes should be kept
for ($i = 0; $i < 10; $i++) {
ArticleViewsSnapshot::factory()->create(['time' => (clone $start)->subMinutes($i)]);
}
$this->artisan(CompressSnapshots::COMMAND, ['--now' => $start]);
$this->assertEquals(10, ArticleViewsSnapshot::all()->count());
// Between
for ($i = 10; $i < 30; $i++) {
ArticleViewsSnapshot::factory()->create(['time' => (clone $start)->subMinutes($i)]);
}
$this->artisan(CompressSnapshots::COMMAND, ['--now' => $start]);
$this->assertEquals(10 + 5, ArticleViewsSnapshot::all()->count());
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/DataTables/AuthorsDataTableTest.php | Beam/extensions/beam-module/tests/Feature/DataTables/AuthorsDataTableTest.php | <?php
namespace Remp\BeamModule\Tests\Feature\DataTables;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Author;
use Remp\BeamModule\Model\Conversion;
use Remp\BeamModule\Model\Property\SelectedProperty;
use Remp\BeamModule\Model\Property;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Remp\LaravelSso\Http\Middleware\VerifyJwtToken;
use Remp\BeamModule\Tests\TestCase;
class AuthorsDataTableTest extends TestCase
{
use RefreshDatabase;
protected $authors;
public function setUp(): void
{
parent::setUp();
Article::unsetEventDispatcher();
$this->withoutMiddleware([
VerifyJwtToken::class,
]);
Property::factory()->create(['uuid' => 'prop_1']);
Property::factory()->create(['uuid' => 'prop_2']);
/** @var Article $prop1SharedArticle */
$prop1SharedArticle = Article::factory()->create(['property_uuid' => 'prop_1', 'content_type' => 'article']);
/** @var Article $prop2Article */
$prop2Article = Article::factory()->create(['property_uuid' => 'prop_2', 'content_type' => 'article']);
/** @var Article $prop2SharedArticle */
$prop2SharedArticle = Article::factory()->create(['property_uuid' => 'prop_2', 'content_type' => 'blog']);
$this->authors = [
1 => Author::factory()->create(),
2 => Author::factory()->create(),
];
// assign authors
$prop1SharedArticle->authors()->attach($this->authors[1]);
$prop1SharedArticle->authors()->attach($this->authors[2]);
$prop2Article->authors()->attach($this->authors[2]);
$prop2SharedArticle->authors()->attach($this->authors[1]);
$prop2SharedArticle->authors()->attach($this->authors[2]);
// assign conversions
$prop1SharedArticle->conversions()->saveMany(
Conversion::factory()->count(2)->make(['article_id' => $prop1SharedArticle])
);
$prop2Article->conversions()->saveMany(
Conversion::factory()->count(3)->make(['article_id' => $prop2Article])
);
$prop2SharedArticle->conversions()->saveMany(
Conversion::factory()->count(4)->make(['article_id' => $prop2SharedArticle])
);
}
public function testAllAuthors()
{
$json = $this->request();
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->authors[2]->id);
$json->assertJsonPath('data.0.articles_count', 3);
$json->assertJsonPath('data.0.conversions_count', 9);
$json->assertJsonPath('data.1.id', $this->authors[1]->id);
$json->assertJsonPath('data.1.articles_count', 2);
$json->assertJsonPath('data.1.conversions_count', 6);
}
public function testPropertyAuthors()
{
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_1');
$json = $this->request();
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->authors[1]->id);
$json->assertJsonPath('data.0.articles_count', 1);
$json->assertJsonPath('data.0.conversions_count', 2);
$json->assertJsonPath('data.1.id', $this->authors[2]->id);
$json->assertJsonPath('data.1.articles_count', 1);
$json->assertJsonPath('data.1.conversions_count', 2);
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_2');
$json = $this->request();
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->authors[2]->id);
$json->assertJsonPath('data.0.articles_count', 2);
$json->assertJsonPath('data.0.conversions_count', 7);
$json->assertJsonPath('data.1.id', $this->authors[1]->id);
$json->assertJsonPath('data.1.articles_count', 1);
$json->assertJsonPath('data.1.conversions_count', 4);
}
public function testAuthorsContentType()
{
$json = $this->request('article');
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->authors[2]->id);
$json->assertJsonPath('data.0.articles_count', 2);
$json->assertJsonPath('data.0.conversions_count', 5);
$json->assertJsonPath('data.1.id', $this->authors[1]->id);
$json->assertJsonPath('data.1.articles_count', 1);
$json->assertJsonPath('data.1.conversions_count', 2);
$json = $this->request('blog');
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->authors[1]->id);
$json->assertJsonPath('data.0.articles_count', 1);
$json->assertJsonPath('data.0.conversions_count', 4);
$json->assertJsonPath('data.1.id', $this->authors[2]->id);
$json->assertJsonPath('data.1.articles_count', 1);
$json->assertJsonPath('data.1.conversions_count', 4);
}
private function request(string $contentType = null)
{
return $this->getJson(route('authors.dtAuthors', [
'content_type' => $contentType,
'columns[0][data]' => 'articles_count',
'columns[1][data]' => 'id',
'order[0][column]' => 0,
'order[0][dir]' => 'desc',
'order[1][column]' => 1,
'order[1][dir]' => 'asc',
]));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/DataTables/ArticleConversionsDataTableTest.php | Beam/extensions/beam-module/tests/Feature/DataTables/ArticleConversionsDataTableTest.php | <?php
namespace Remp\BeamModule\Tests\Feature\DataTables;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Remp\BeamModule\Database\Seeders\ConfigSeeder;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Conversion;
use Remp\BeamModule\Model\Property;
use Remp\BeamModule\Model\Property\SelectedProperty;
use Remp\BeamModule\Tests\TestCase;
use Remp\Journal\JournalContract;
use Remp\LaravelSso\Http\Middleware\VerifyJwtToken;
class ArticleConversionsDataTableTest extends TestCase
{
use RefreshDatabase;
/** @var Article[] */
protected $articles;
public function setUp(): void
{
parent::setUp();
$this->seed(ConfigSeeder::class);
Article::unsetEventDispatcher();
$this->withoutMiddleware([
VerifyJwtToken::class,
]);
Property::factory()->create(['uuid' => 'prop_1']);
Property::factory()->create(['uuid' => 'prop_2']);
$this->articles = [
'prop1' => Article::factory()->create(['property_uuid' => 'prop_1']),
'prop2' => Article::factory()->create(['property_uuid' => 'prop_2']),
];
// assign conversions
$this->articles['prop1']->conversions()->saveMany(
Conversion::factory()->count(2)->make(['article_id' => $this->articles['prop1']])
);
$this->articles['prop2']->conversions()->saveMany(
Conversion::factory()->count(3)->make(['article_id' => $this->articles['prop2']])
);
$journalMock = \Mockery::mock(JournalContract::class);
// mock unavailable unique browser counts so the conversion_rate calculation can proceed
$journalMock->shouldReceive('unique')->andReturn([]);
$this->app->instance(JournalContract::class, $journalMock);
}
public function testAllArticles()
{
$json = $this->request();
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 2);
$json->assertJsonPath('data.0.id', $this->articles['prop2']->id);
$json->assertJsonPath('data.0.conversions_count', 3);
$json->assertJsonPath('data.1.id', $this->articles['prop1']->id);
$json->assertJsonPath('data.1.conversions_count', 2);
}
public function testPropertyArticles()
{
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_1');
$json = $this->request();
$json->assertSuccessful();
$json->assertJson(['recordsTotal' => 1]);
$json->assertJsonPath('data.0.id', $this->articles['prop1']->id);
$json->assertJsonPath('data.0.conversions_count', 2);
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_2');
$json = $this->request();
$json->assertSuccessful();
$json->assertJson(['recordsTotal' => 1]);
$json->assertJsonPath('data.0.id', $this->articles['prop2']->id);
$json->assertJsonPath('data.0.conversions_count', 3);
}
private function request()
{
return $this->getJson(route('articles.dtConversions', [
'columns[0][data]' => 'conversions_count',
'order[0][column]' => 0,
'order[0][dir]' => 'desc',
]));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/DataTables/SectionsDataTableTest.php | Beam/extensions/beam-module/tests/Feature/DataTables/SectionsDataTableTest.php | <?php
namespace Remp\BeamModule\Tests\Feature\DataTables;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Conversion;
use Remp\BeamModule\Model\Property\SelectedProperty;
use Remp\BeamModule\Model\Property;
use Remp\BeamModule\Model\Section;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Remp\LaravelSso\Http\Middleware\VerifyJwtToken;
use Remp\BeamModule\Tests\TestCase;
class SectionsDataTableTest extends TestCase
{
use RefreshDatabase;
/** @var Article[] */
protected $articles;
/** @var Section[] */
protected $sections;
public function setUp(): void
{
parent::setUp();
Article::unsetEventDispatcher();
$this->withoutMiddleware([
VerifyJwtToken::class,
]);
Property::factory()->create(['uuid' => 'prop_1']);
Property::factory()->create(['uuid' => 'prop_2']);
$this->articles = [
'prop1_shared' => Article::factory()->create(['property_uuid' => 'prop_1']),
'prop2' => Article::factory()->create(['property_uuid' => 'prop_2']),
'prop2_shared' => Article::factory()->create(['property_uuid' => 'prop_2']),
];
$this->sections = [
1 => Section::factory()->create(),
2 => Section::factory()->create(),
];
// assign sections
$this->articles['prop1_shared']->sections()->attach($this->sections[1]);
$this->articles['prop1_shared']->sections()->attach($this->sections[2]);
$this->articles['prop2']->sections()->attach($this->sections[2]);
$this->articles['prop2_shared']->sections()->attach($this->sections[1]);
$this->articles['prop2_shared']->sections()->attach($this->sections[2]);
// assign conversions
$this->articles['prop1_shared']->conversions()->saveMany(
Conversion::factory()->count(2)->make(['article_id' => $this->articles['prop1_shared']])
);
$this->articles['prop2']->conversions()->saveMany(
Conversion::factory()->count(3)->make(['article_id' => $this->articles['prop2']])
);
$this->articles['prop2_shared']->conversions()->saveMany(
Conversion::factory()->count(4)->make(['article_id' => $this->articles['prop2_shared']])
);
}
public function testAllSections()
{
$json = $this->requestSections();
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->sections[2]->id);
$json->assertJsonPath('data.0.articles_count', 3);
$json->assertJsonPath('data.0.conversions_count', 9);
$json->assertJsonPath('data.1.id', $this->sections[1]->id);
$json->assertJsonPath('data.1.articles_count', 2);
$json->assertJsonPath('data.1.conversions_count', 6);
}
public function testPropertySections()
{
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_1');
$json = $this->requestSections();
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->sections[1]->id);
$json->assertJsonPath('data.0.articles_count', 1);
$json->assertJsonPath('data.0.conversions_count', 2);
$json->assertJsonPath('data.1.id', $this->sections[2]->id);
$json->assertJsonPath('data.1.articles_count', 1);
$json->assertJsonPath('data.1.conversions_count', 2);
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_2');
$json = $this->requestSections();
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->sections[2]->id);
$json->assertJsonPath('data.0.articles_count', 2);
$json->assertJsonPath('data.0.conversions_count', 7);
$json->assertJsonPath('data.1.id', $this->sections[1]->id);
$json->assertJsonPath('data.1.articles_count', 1);
$json->assertJsonPath('data.1.conversions_count', 4);
}
public function testAllSectionArticles()
{
$json = $this->requestSectionArticles($this->sections[1]);
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->articles['prop2_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 4);
$json->assertJsonPath('data.1.id', $this->articles['prop1_shared']->id);
$json->assertJsonPath('data.1.conversions_count', 2);
$json = $this->requestSectionArticles($this->sections[2]);
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->articles['prop2_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 4);
$json->assertJsonPath('data.1.id', $this->articles['prop2']->id);
$json->assertJsonPath('data.1.conversions_count', 3);
$json->assertJsonPath('data.2.id', $this->articles['prop1_shared']->id);
$json->assertJsonPath('data.2.conversions_count', 2);
}
public function testPropertySectionArticles()
{
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_1');
$json = $this->requestSectionArticles($this->sections[1]);
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->articles['prop1_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 2);
$json = $this->requestSectionArticles($this->sections[2]);
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->articles['prop1_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 2);
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_2');
$json = $this->requestSectionArticles($this->sections[1]);
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->articles['prop2_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 4);
$json = $this->requestSectionArticles($this->sections[2]);
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->articles['prop2_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 4);
$json->assertJsonPath('data.1.id', $this->articles['prop2']->id);
$json->assertJsonPath('data.1.conversions_count', 3);
}
private function requestSections()
{
return $this->getJson(route('sections.dtSections', [
'columns[0][data]' => 'conversions_count',
'columns[1][data]' => 'id',
'order[0][column]' => 0,
'order[0][dir]' => 'desc',
'order[1][column]' => 1,
'order[1][dir]' => 'asc',
]));
}
private function requestSectionArticles(Section $section)
{
return $this->getJson(route('sections.dtArticles', [
'section' => $section->id,
'columns[0][data]' => 'conversions_count',
'columns[1][data]' => 'id',
'order[0][column]' => 0,
'order[0][dir]' => 'desc',
'order[1][column]' => 1,
'order[1][dir]' => 'asc',
]));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/DataTables/TagCategoriesDataTableTest.php | Beam/extensions/beam-module/tests/Feature/DataTables/TagCategoriesDataTableTest.php | <?php
namespace Remp\BeamModule\Tests\Feature\DataTables;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Conversion;
use Remp\BeamModule\Model\Property\SelectedProperty;
use Remp\BeamModule\Model\Tag;
use Remp\BeamModule\Model\Property;
use Remp\BeamModule\Model\TagCategory;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Remp\LaravelSso\Http\Middleware\VerifyJwtToken;
use Remp\BeamModule\Tests\TestCase;
class TagCategoriesDataTableTest extends TestCase
{
use RefreshDatabase;
/** @var Article[] */
protected $articles;
/** @var Tag[] */
protected $tags;
/** @var TagCategory[] */
protected $tagCategories;
public function setUp(): void
{
parent::setUp();
Article::unsetEventDispatcher();
$this->withoutMiddleware([
VerifyJwtToken::class,
]);
Property::factory()->create(['uuid' => 'prop_1']);
Property::factory()->create(['uuid' => 'prop_2']);
Property::factory()->create(['uuid' => 'prop_3']);
Property::factory()->create(['uuid' => 'prop_4']);
$this->articles = [
'prop1' => Article::factory()->create(['property_uuid' => 'prop_1']),
'prop1_shared' => Article::factory()->create(['property_uuid' => 'prop_1']),
'prop2' => Article::factory()->create(['property_uuid' => 'prop_2']),
'prop2_shared' => Article::factory()->create(['property_uuid' => 'prop_2']),
'prop3' => Article::factory()->create(['property_uuid' => 'prop_3']),
'prop4' => Article::factory()->create(['property_uuid' => 'prop_4']),
];
$this->tags = [
1 => Tag::factory()->create(),
2 => Tag::factory()->create(),
3 => Tag::factory()->create(),
4 => Tag::factory()->create(),
];
$this->tagCategories = [
1 => TagCategory::factory()->create(),
2 => TagCategory::factory()->create(),
3 => TagCategory::factory()->create(), // has prop_3 only tag
];
// assign tag categories
$this->tags[1]->tagCategories()->attach($this->tagCategories[1]);
$this->tags[1]->tagCategories()->attach($this->tagCategories[2]);
$this->tags[2]->tagCategories()->attach($this->tagCategories[2]);
$this->tags[3]->tagCategories()->attach($this->tagCategories[3]);
$this->tags[4]->tagCategories()->attach($this->tagCategories[3]);
// assign tags
$this->articles['prop1']->tags()->attach($this->tags[1]);
$this->articles['prop1_shared']->tags()->attach($this->tags[1]);
$this->articles['prop1_shared']->tags()->attach($this->tags[2]);
$this->articles['prop2']->tags()->attach($this->tags[2]);
$this->articles['prop2_shared']->tags()->attach($this->tags[1]);
$this->articles['prop2_shared']->tags()->attach($this->tags[2]);
$this->articles['prop3']->tags()->attach($this->tags[3]);
$this->articles['prop4']->tags()->attach($this->tags[4]);
// assign conversions
$this->articles['prop1']->conversions()->saveMany(
Conversion::factory()->count(1)->make(['article_id' => $this->articles['prop1']])
);
$this->articles['prop1_shared']->conversions()->saveMany(
Conversion::factory()->count(2)->make(['article_id' => $this->articles['prop1_shared']])
);
$this->articles['prop2']->conversions()->saveMany(
Conversion::factory()->count(3)->make(['article_id' => $this->articles['prop2']])
);
$this->articles['prop2_shared']->conversions()->saveMany(
Conversion::factory()->count(4)->make(['article_id' => $this->articles['prop2_shared']])
);
}
public function testAllTagCategories()
{
$json = $this->requestTagCategories();
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 3);
$json->assertJsonPath('data.0.id', $this->tagCategories[2]->id);
$json->assertJsonPath('data.0.tags_count', 2);
$json->assertJsonPath('data.0.articles_count', 4);
$json->assertJsonPath('data.0.conversions_count', 10);
$json->assertJsonPath('data.1.id', $this->tagCategories[1]->id);
$json->assertJsonPath('data.1.tags_count', 1);
$json->assertJsonPath('data.1.articles_count', 3);
$json->assertJsonPath('data.1.conversions_count', 7);
$json->assertJsonPath('data.2.id', $this->tagCategories[3]->id);
$json->assertJsonPath('data.2.tags_count', 2);
$json->assertJsonPath('data.2.articles_count', 2);
$json->assertJsonPath('data.2.conversions_count', 0);
}
public function testPropertyTagCategories()
{
$this->setProperty('prop_1');
$json = $this->requestTagCategories();
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 2);
$json->assertJsonPath('data.0.id', $this->tagCategories[1]->id);
$json->assertJsonPath('data.0.tags_count', 1);
$json->assertJsonPath('data.0.articles_count', 2);
$json->assertJsonPath('data.0.conversions_count', 3);
$json->assertJsonPath('data.1.id', $this->tagCategories[2]->id);
$json->assertJsonPath('data.1.tags_count', 2);
$json->assertJsonPath('data.1.articles_count', 2);
$json->assertJsonPath('data.1.conversions_count', 3);
$this->setProperty('prop_2');
$json = $this->requestTagCategories();
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 2);
$json->assertJsonPath('data.0.id', $this->tagCategories[2]->id);
$json->assertJsonPath('data.0.tags_count', 2);
$json->assertJsonPath('data.0.articles_count', 2);
$json->assertJsonPath('data.0.conversions_count', 7);
$json->assertJsonPath('data.1.id', $this->tagCategories[1]->id);
$json->assertJsonPath('data.1.tags_count', 1);
$json->assertJsonPath('data.1.articles_count', 1);
$json->assertJsonPath('data.1.conversions_count', 4);
$this->setProperty('prop_3');
$json = $this->requestTagCategories();
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 1);
$json->assertJsonPath('data.0.id', $this->tagCategories[3]->id);
$json->assertJsonPath('data.0.tags_count', 1);
$json->assertJsonPath('data.0.articles_count', 1);
$json->assertJsonPath('data.0.conversions_count', 0);
}
public function testAllTagCategoryArticles()
{
$json = $this->requestTagCategoryArticles($this->tagCategories[1]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 3);
$json->assertJsonPath('data.0.id', $this->articles['prop2_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 4);
$json->assertJsonPath('data.1.id', $this->articles['prop1_shared']->id);
$json->assertJsonPath('data.1.conversions_count', 2);
$json->assertJsonPath('data.2.id', $this->articles['prop1']->id);
$json->assertJsonPath('data.2.conversions_count', 1);
$json = $this->requestTagCategoryArticles($this->tagCategories[2]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 4);
$json->assertJsonPath('data.0.id', $this->articles['prop2_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 4);
$json->assertJsonPath('data.1.id', $this->articles['prop2']->id);
$json->assertJsonPath('data.1.conversions_count', 3);
$json->assertJsonPath('data.2.id', $this->articles['prop1_shared']->id);
$json->assertJsonPath('data.2.conversions_count', 2);
$json->assertJsonPath('data.3.id', $this->articles['prop1']->id);
$json->assertJsonPath('data.3.conversions_count', 1);
}
public function testPropertyTagCategoryArticles()
{
$this->setProperty('prop_1');
$json = $this->requestTagCategoryArticles($this->tagCategories[1]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 2);
$json->assertJsonPath('data.0.id', $this->articles['prop1_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 2);
$json->assertJsonPath('data.1.id', $this->articles['prop1']->id);
$json->assertJsonPath('data.1.conversions_count', 1);
$this->setProperty('prop_2');
$json = $this->requestTagCategoryArticles($this->tagCategories[1]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 1);
$json->assertJsonPath('data.0.id', $this->articles['prop2_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 4);
$this->setProperty('prop_1');
$json = $this->requestTagCategoryArticles($this->tagCategories[2]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 2);
$json->assertJsonPath('data.0.id', $this->articles['prop1_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 2);
$json->assertJsonPath('data.1.id', $this->articles['prop1']->id);
$json->assertJsonPath('data.1.conversions_count', 1);
$this->setProperty('prop_2');
$json = $this->requestTagCategoryArticles($this->tagCategories[2]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 2);
$json->assertJsonPath('data.0.id', $this->articles['prop2_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 4);
$json->assertJsonPath('data.1.id', $this->articles['prop2']->id);
$json->assertJsonPath('data.1.conversions_count', 3);
}
public function testAllTagCategoryTags()
{
$json = $this->requestTagCategoryTags($this->tagCategories[1]);
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->tags[1]->id);
$json->assertJsonPath('data.0.articles_count', 3);
$json->assertJsonPath('data.0.conversions_count', 7);
$json = $this->requestTagCategoryTags($this->tagCategories[2]);
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->tags[2]->id);
$json->assertJsonPath('data.0.articles_count', 3);
$json->assertJsonPath('data.0.conversions_count', 9);
$json->assertJsonPath('data.1.id', $this->tags[1]->id);
$json->assertJsonPath('data.1.articles_count', 3);
$json->assertJsonPath('data.1.conversions_count', 7);
}
public function testPropertyTagCategoryTags()
{
$this->setProperty('prop_1');
$json = $this->requestTagCategoryTags($this->tagCategories[1]);
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->tags[1]->id);
$json->assertJsonPath('data.0.articles_count', 2);
$json->assertJsonPath('data.0.conversions_count', 3);
$this->setProperty('prop_2');
$json = $this->requestTagCategoryTags($this->tagCategories[1]);
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->tags[1]->id);
$json->assertJsonPath('data.0.articles_count', 1);
$json->assertJsonPath('data.0.conversions_count', 4);
$this->setProperty('prop_1');
$json = $this->requestTagCategoryTags($this->tagCategories[2]);
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->tags[1]->id);
$json->assertJsonPath('data.0.articles_count', 2);
$json->assertJsonPath('data.0.conversions_count', 3);
$json->assertJsonPath('data.1.id', $this->tags[2]->id);
$json->assertJsonPath('data.1.articles_count', 1);
$json->assertJsonPath('data.1.conversions_count', 2);
$this->setProperty('prop_2');
$json = $this->requestTagCategoryTags($this->tagCategories[2]);
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->tags[2]->id);
$json->assertJsonPath('data.0.articles_count', 2);
$json->assertJsonPath('data.0.conversions_count', 7);
$json->assertJsonPath('data.1.id', $this->tags[1]->id);
$json->assertJsonPath('data.1.articles_count', 1);
$json->assertJsonPath('data.1.conversions_count', 4);
}
private function setProperty(string $property)
{
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken($property);
}
private function requestTagCategories()
{
return $this->getJson(route('tagCategories.dtTagCategories', [
'columns[0][data]' => 'conversions_count',
'columns[1][data]' => 'id',
'order[0][column]' => 0,
'order[0][dir]' => 'desc',
'order[1][column]' => 1,
'order[1][dir]' => 'asc',
]));
}
private function requestTagCategoryArticles(TagCategory $tagCategory)
{
return $this->getJson(route('tagCategories.dtArticles', [
'tagCategory' => $tagCategory->id,
'columns[0][data]' => 'conversions_count',
'columns[1][data]' => 'id',
'order[0][column]' => 0,
'order[0][dir]' => 'desc',
'order[1][column]' => 1,
'order[1][dir]' => 'asc',
]));
}
private function requestTagCategoryTags(TagCategory $tagCategory)
{
return $this->getJson(route('tagCategories.dtTags', [
'tagCategory' => $tagCategory->id,
'columns[0][data]' => 'conversions_count',
'columns[1][data]' => 'id',
'order[0][column]' => 0,
'order[0][dir]' => 'desc',
'order[1][column]' => 1,
'order[1][dir]' => 'asc',
]));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/DataTables/ConversionsDataTableTest.php | Beam/extensions/beam-module/tests/Feature/DataTables/ConversionsDataTableTest.php | <?php
namespace Remp\BeamModule\Tests\Feature\DataTables;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Conversion;
use Remp\BeamModule\Model\Property\SelectedProperty;
use Remp\BeamModule\Model\Property;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Remp\LaravelSso\Http\Middleware\VerifyJwtToken;
use Remp\BeamModule\Tests\TestCase;
class ConversionsDataTableTest extends TestCase
{
use RefreshDatabase;
/** @var Article[] */
protected $articles;
public function setUp(): void
{
parent::setUp();
Article::unsetEventDispatcher();
$this->withoutMiddleware([
VerifyJwtToken::class,
]);
Property::factory()->create(['uuid' => 'prop_1']);
Property::factory()->create(['uuid' => 'prop_2']);
$this->articles = [
'prop1' => Article::factory()->create(['property_uuid' => 'prop_1']),
'prop2' => Article::factory()->create(['property_uuid' => 'prop_2']),
];
// assign conversions
$this->articles['prop1']->conversions()->saveMany(
Conversion::factory()->count(2)->make(['article_id' => $this->articles['prop1']])
);
$this->articles['prop2']->conversions()->saveMany(
Conversion::factory()->count(3)->make(['article_id' => $this->articles['prop2']])
);
}
public function testAllConversions()
{
$json = $this->request();
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 5);
}
public function testPropertyConversions()
{
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_1');
$json = $this->request();
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 2);
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_2');
$json = $this->request();
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 3);
}
private function request()
{
return $this->getJson(route('conversions.json'));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/DataTables/TagsDataTableTest.php | Beam/extensions/beam-module/tests/Feature/DataTables/TagsDataTableTest.php | <?php
namespace Remp\BeamModule\Tests\Feature\DataTables;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Conversion;
use Remp\BeamModule\Model\Property\SelectedProperty;
use Remp\BeamModule\Model\Tag;
use Remp\BeamModule\Model\Property;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Remp\LaravelSso\Http\Middleware\VerifyJwtToken;
use Remp\BeamModule\Tests\TestCase;
class TagsDataTableTest extends TestCase
{
use RefreshDatabase;
/** @var Article[] */
protected $articles;
/** @var Tag[] */
protected $tags;
public function setUp(): void
{
parent::setUp();
Article::unsetEventDispatcher();
$this->withoutMiddleware([
VerifyJwtToken::class,
]);
Property::factory()->create(['uuid' => 'prop_1']);
Property::factory()->create(['uuid' => 'prop_2']);
$this->articles = [
'prop1_shared' => Article::factory()->create(['property_uuid' => 'prop_1']),
'prop2' => Article::factory()->create(['property_uuid' => 'prop_2']),
'prop2_shared' => Article::factory()->create(['property_uuid' => 'prop_2']),
];
$this->tags = [
1 => Tag::factory()->create(),
2 => Tag::factory()->create(),
];
// assign tags
$this->articles['prop1_shared']->tags()->attach($this->tags[1]);
$this->articles['prop1_shared']->tags()->attach($this->tags[2]);
$this->articles['prop2']->tags()->attach($this->tags[2]);
$this->articles['prop2_shared']->tags()->attach($this->tags[1]);
$this->articles['prop2_shared']->tags()->attach($this->tags[2]);
// assign conversions
$this->articles['prop1_shared']->conversions()->saveMany(
Conversion::factory()->count(2)->make(['article_id' => $this->articles['prop1_shared']])
);
$this->articles['prop2']->conversions()->saveMany(
Conversion::factory()->count(3)->make(['article_id' => $this->articles['prop2']])
);
$this->articles['prop2_shared']->conversions()->saveMany(
Conversion::factory()->count(4)->make(['article_id' => $this->articles['prop2_shared']])
);
}
public function testAllTags()
{
$json = $this->requestTags();
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->tags[2]->id);
$json->assertJsonPath('data.0.articles_count', 3);
$json->assertJsonPath('data.0.conversions_count', 9);
$json->assertJsonPath('data.1.id', $this->tags[1]->id);
$json->assertJsonPath('data.1.articles_count', 2);
$json->assertJsonPath('data.1.conversions_count', 6);
}
public function testPropertyTags()
{
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_1');
$json = $this->requestTags();
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->tags[1]->id);
$json->assertJsonPath('data.0.articles_count', 1);
$json->assertJsonPath('data.0.conversions_count', 2);
$json->assertJsonPath('data.1.id', $this->tags[2]->id);
$json->assertJsonPath('data.1.articles_count', 1);
$json->assertJsonPath('data.1.conversions_count', 2);
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_2');
$json = $this->requestTags();
$json->assertSuccessful();
$json->assertJsonPath('data.0.id', $this->tags[2]->id);
$json->assertJsonPath('data.0.articles_count', 2);
$json->assertJsonPath('data.0.conversions_count', 7);
$json->assertJsonPath('data.1.id', $this->tags[1]->id);
$json->assertJsonPath('data.1.articles_count', 1);
$json->assertJsonPath('data.1.conversions_count', 4);
}
public function testAllTagArticles()
{
$json = $this->requestSectionTags($this->tags[1]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 2);
$json->assertJsonPath('data.0.id', $this->articles['prop2_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 4);
$json->assertJsonPath('data.1.id', $this->articles['prop1_shared']->id);
$json->assertJsonPath('data.1.conversions_count', 2);
$json = $this->requestSectionTags($this->tags[2]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 3);
$json->assertJsonPath('data.0.id', $this->articles['prop2_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 4);
$json->assertJsonPath('data.1.id', $this->articles['prop2']->id);
$json->assertJsonPath('data.1.conversions_count', 3);
$json->assertJsonPath('data.2.id', $this->articles['prop1_shared']->id);
$json->assertJsonPath('data.2.conversions_count', 2);
}
public function testPropertyTagArticles()
{
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_1');
$json = $this->requestSectionTags($this->tags[1]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 1);
$json->assertJsonPath('data.0.id', $this->articles['prop1_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 2);
$json = $this->requestSectionTags($this->tags[2]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 1);
$json->assertJsonPath('data.0.id', $this->articles['prop1_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 2);
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_2');
$json = $this->requestSectionTags($this->tags[1]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 1);
$json->assertJsonPath('data.0.id', $this->articles['prop2_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 4);
$json = $this->requestSectionTags($this->tags[2]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 2);
$json->assertJsonPath('data.0.id', $this->articles['prop2_shared']->id);
$json->assertJsonPath('data.0.conversions_count', 4);
$json->assertJsonPath('data.1.id', $this->articles['prop2']->id);
$json->assertJsonPath('data.1.conversions_count', 3);
}
private function requestTags()
{
return $this->getJson(route('tags.dtTags', [
'columns[0][data]' => 'conversions_count',
'columns[1][data]' => 'id',
'order[0][column]' => 0,
'order[0][dir]' => 'desc',
'order[1][column]' => 1,
'order[1][dir]' => 'asc',
]));
}
private function requestSectionTags(Tag $tag)
{
return $this->getJson(route('tags.dtArticles', [
'tag' => $tag->id,
'columns[0][data]' => 'conversions_count',
'columns[1][data]' => 'id',
'order[0][column]' => 0,
'order[0][dir]' => 'desc',
'order[1][column]' => 1,
'order[1][dir]' => 'asc',
]));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/DataTables/ArticlePageviewsDataTableTest.php | Beam/extensions/beam-module/tests/Feature/DataTables/ArticlePageviewsDataTableTest.php | <?php
namespace Remp\BeamModule\Tests\Feature\DataTables;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Property\SelectedProperty;
use Remp\BeamModule\Model\Property;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Remp\LaravelSso\Http\Middleware\VerifyJwtToken;
use Remp\BeamModule\Tests\TestCase;
class ArticlePageviewsDataTableTest extends TestCase
{
use RefreshDatabase;
/** @var Article[] */
protected $articles;
public function setUp(): void
{
parent::setUp();
Article::unsetEventDispatcher();
$this->withoutMiddleware([
VerifyJwtToken::class,
]);
Property::factory()->create(['uuid' => 'prop_1']);
Property::factory()->create(['uuid' => 'prop_2']);
$this->articles = [
'prop1' => Article::factory()->create(['property_uuid' => 'prop_1']),
'prop2' => Article::factory()->create(['property_uuid' => 'prop_2']),
];
}
public function testAllArticles()
{
$json = $this->request();
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 2);
$json->assertJsonPath('data.0.id', $this->articles['prop1']->id);
$json->assertJsonPath('data.1.id', $this->articles['prop2']->id);
}
public function testPropertyArticles()
{
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_1');
$json = $this->request();
$json->assertSuccessful();
$json->assertJson(['recordsTotal' => 1]);
$json->assertJsonPath('data.0.id', $this->articles['prop1']->id);
/** @var SelectedProperty $selectedProperty */
$selectedProperty = resolve(SelectedProperty::class);
$selectedProperty->setToken('prop_2');
$json = $this->request();
$json->assertSuccessful();
$json->assertJson(['recordsTotal' => 1]);
$json->assertJsonPath('data.0.id', $this->articles['prop2']->id);
}
private function request()
{
return $this->getJson(route('articles.dtPageviews', [
'columns[0][data]' => 'id',
'order[0][column]' => 0,
'order[0][dir]' => 'asc',
]));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/API/ConversionsApiTest.php | Beam/extensions/beam-module/tests/Feature/API/ConversionsApiTest.php | <?php
namespace Remp\BeamModule\Tests\Feature\API;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Conversion;
use Remp\BeamModule\Model\Property;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Remp\LaravelSso\Http\Middleware\VerifyJwtToken;
use Remp\BeamModule\Tests\TestCase;
class ConversionsApiTest extends TestCase
{
use RefreshDatabase;
public function setUp(): void
{
parent::setUp();
Article::unsetEventDispatcher();
$this->withoutMiddleware([
VerifyJwtToken::class,
]);
Property::factory()->create(['uuid' => 'prop_1']);
Property::factory()->create(['uuid' => 'prop_2']);
$articles = [
'prop1' => Article::factory()->create(['property_uuid' => 'prop_1']),
'prop2' => Article::factory()->create(['property_uuid' => 'prop_2']),
];
// assign conversions
$articles['prop1']->conversions()->save(
Conversion::factory()->create(['article_id' => $articles['prop1'], 'paid_at' => new Carbon("2021-11-08T10:00:00")])
);
$articles['prop1']->conversions()->save(
Conversion::factory()->create(['article_id' => $articles['prop1'], 'paid_at' => new Carbon("2021-11-07T10:00:00")])
);
$articles['prop2']->conversions()->save(
Conversion::factory()->create(['article_id' => $articles['prop2'], 'paid_at' => new Carbon("2021-11-06T10:00:00")])
);
$articles['prop2']->conversions()->save(
Conversion::factory()->create(['article_id' => $articles['prop2'], 'paid_at' => new Carbon("2021-11-05T10:00:00")])
);
$articles['prop2']->conversions()->save(
Conversion::factory()->create(['article_id' => $articles['prop2'], 'paid_at' => new Carbon("2021-11-04T10:00:00")])
);
}
public function testConversionFilteredByConversionTime()
{
$json = $this->request(['conversion_from' => "2021-11-05T00:00:00"]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 4);
$json = $this->request([
'conversion_from' => "2021-11-05T00:00:00",
'conversion_to' => "2021-11-07T23:59:59"
]);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 3);
$json = $this->request(['conversion_to' => '2021-11-06T00:00:00']);
$json->assertSuccessful();
$json->assertJsonPath('recordsTotal', 2);
}
private function request(array $parameters = [])
{
return $this->getJson(route('conversions.json', $parameters));
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Feature/API/TopSearchTest.php | Beam/extensions/beam-module/tests/Feature/API/TopSearchTest.php | <?php
namespace Remp\BeamModule\Tests\Feature\API;
use Carbon\Carbon;
use Illuminate\Auth\Middleware\Authenticate;
use Illuminate\Foundation\Testing\RefreshDatabase;
use PHPUnit\Framework\Attributes\DataProvider;
use Remp\BeamModule\Model\Article;
use Remp\BeamModule\Model\Property;
use Remp\BeamModule\Tests\TestCase;
class TopSearchTest extends TestCase
{
use RefreshDatabase;
private array $articles = [];
public function setUp(): void
{
parent::setUp();
Article::unsetEventDispatcher();
$this->withoutMiddleware([
Authenticate::class,
]);
Property::factory()->create(['uuid' => 'test_property_uuid']);
$this->articles = [
'ar1' => Article::factory()->create([
'property_uuid' => 'test_property_uuid',
'external_id' => 'ar1',
'published_at' => new Carbon("2021-11-01T10:00:00"),
'pageviews_all' => 1000
]),
'ar2' => Article::factory()->create([
'property_uuid' => 'test_property_uuid',
'external_id' => 'ar2',
'published_at' => new Carbon("2021-11-10T10:00:00"),
'pageviews_all' => 2000
]),
'ar3' => Article::factory()->create([
'property_uuid' => 'test_property_uuid',
'external_id' => 'ar3',
'published_at' => new Carbon("2021-11-02T10:00:00"),
'pageviews_all' => 1500
]),
'ar4' => Article::factory()->create([
'property_uuid' => 'test_property_uuid',
'external_id' => 'ar4',
'published_at' => new Carbon("2021-11-12T10:00:00"),
'pageviews_all' => 3000
]),
];
}
public static function byPublishedAtDataProvider(): array
{
return [
'ByPublishFrom' => [
'requestParams' => [
'from' => "2021-11-01T00:00:00",
'limit' => 10,
'published_from' => "2021-11-05T00:00:00"
],
'expectedArticleKeys' => ['ar4', 'ar2'],
'expectedCount' => 2
],
'ByPublishedTo' => [
'requestParams' => [
'from' => "2021-11-01T00:00:00",
'limit' => 10,
'published_to' => "2021-11-05T00:00:00"
],
'expectedArticleKeys' => ['ar3', 'ar1'],
'expectedCount' => 2
],
'ByPublishedFromAndTo' => [
'requestParams' => [
'from' => "2021-11-01T00:00:00",
'limit' => 10,
'published_from' => "2021-11-02T00:00:00",
'published_to' => "2021-11-11T00:00:00"
],
'expectedArticleKeys' => ['ar2', 'ar3'],
'expectedCount' => 2
],
'WithoutPublishedFilters' => [
'requestParams' => [
'from' => "2021-11-01T00:00:00",
'limit' => 10
],
'expectedArticleKeys' => ['ar4', 'ar2', 'ar3', 'ar1'],
'expectedCount' => 4
],
];
}
#[DataProvider('byPublishedAtDataProvider')]
public function testTopSearchApi(array $requestParams, array $expectedArticleKeys, int $expectedCount)
{
$response = $this->request($requestParams);
$response->assertSuccessful();
$data = $response->json();
$this->assertCount($expectedCount, $data);
foreach ($expectedArticleKeys as $i => $expectedKey) {
$this->assertEquals($expectedKey, $data[$i]['external_id']);
}
}
private function request(array $parameters = [])
{
return $this->postJson(route('api.articles.top.v2'), $parameters);
}
} | php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Unit/SnapshotHelperTest.php | Beam/extensions/beam-module/tests/Unit/SnapshotHelperTest.php | <?php
namespace Remp\BeamModule\Tests\Unit;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Carbon;
use Remp\BeamModule\Model\ArticleViewsSnapshot;
use Remp\BeamModule\Model\Snapshots\SnapshotHelpers;
use Remp\BeamModule\Tests\TestCase;
class SnapshotHelperTest extends TestCase
{
use RefreshDatabase;
/** @var SnapshotHelpers */
private $snapshotHelpers;
protected function setUp(): void
{
parent::setUp();
$this->snapshotHelpers = new SnapshotHelpers();
}
public function testExcludedTimePoints()
{
$start = Carbon::today();
$shouldBeExcluded = [];
$shouldBeKept = [];
// Window 0-4 min
$shouldBeKept[] = ArticleViewsSnapshot::factory()->create(['time' => $start]);
$shouldBeExcluded[] = ArticleViewsSnapshot::factory()->create(['time' => (clone $start)->addMinutes(1)]);
$shouldBeExcluded[] = ArticleViewsSnapshot::factory()->create(['time' => (clone $start)->addMinutes(2)]);
$shouldBeExcluded[] = ArticleViewsSnapshot::factory()->create(['time' => (clone $start)->addMinutes(3)]);
$shouldBeExcluded[] = ArticleViewsSnapshot::factory()->create(['time' => (clone $start)->addMinutes(4)]);
// Window 5-9 min
$shouldBeKept[] = ArticleViewsSnapshot::factory()->create(['time' => (clone $start)->addMinutes(6)]);
$shouldBeExcluded[] = ArticleViewsSnapshot::factory()->create(['time' => (clone $start)->addMinutes(7)]);
$shouldBeExcluded[] = ArticleViewsSnapshot::factory()->create(['time' => (clone $start)->addMinutes(8)]);
// Window 10-14 min
$shouldBeKept[] = ArticleViewsSnapshot::factory()->create(['time' => (clone $start)->addMinutes(10)]);
// Window 15-19 min
$shouldBeKept[] = ArticleViewsSnapshot::factory()->create(['time' => (clone $start)->addMinutes(16)]);
$timePoints = $this->snapshotHelpers->timePoints($start, (clone $start)->addMinutes(20), 5);
foreach ($shouldBeExcluded as $item) {
$this->assertTrue(in_array($item->time->toIso8601ZuluString(), $timePoints->getExcludedPoints()));
}
foreach ($shouldBeKept as $item) {
$this->assertFalse(in_array($item->time->toIso8601ZuluString(), $timePoints->getExcludedPoints()));
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Unit/ColorsTest.php | Beam/extensions/beam-module/tests/Unit/ColorsTest.php | <?php
namespace Remp\BeamModule\Tests\Unit;
use Remp\BeamModule\Helpers\Colors;
use Remp\BeamModule\Tests\TestCase;
class ColorsTest extends TestCase
{
public function testOrdering()
{
$tags = [
'internal' => 1200,
'email' => 10,
'unknown_3' => 10000,
'direct/IM' => 1500,
'unknown_1' => 4000,
'unknown_2' => 8000,
];
$orderedTags = Colors::orderRefererMediumTags($tags, true);
$this->assertEquals(['internal', 'direct/IM', 'email', 'unknown_3', 'unknown_2', 'unknown_1'], $orderedTags);
$tagWithDifferentCounts = [
'unknown_1' => 10,
'internal' => 1,
'unknown_3' => 2,
];
$orderedTags = Colors::orderRefererMediumTags($tagWithDifferentCounts, true);
// order will be influenced by previously cached results
$this->assertEquals(['internal', 'unknown_3', 'unknown_1'], $orderedTags);
$tagWithDifferentCounts2 = [
'unknown_1' => 10,
'internal' => 1,
'unknown_3' => 2,
'previously_unknown' => 5,
];
$orderedTags = Colors::orderRefererMediumTags($tagWithDifferentCounts2, true);
// order will not be influenced by previously cached results (because 'previously_unknown' tag was introduced)
$this->assertEquals(['internal', 'unknown_1', 'previously_unknown', 'unknown_3'], $orderedTags);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/tests/Unit/HelpersTest.php | Beam/extensions/beam-module/tests/Unit/HelpersTest.php | <?php
namespace Remp\BeamModule\Tests\Unit;
use Remp\BeamModule\Helpers\Misc;
use Illuminate\Support\Carbon;
use Remp\BeamModule\Tests\TestCase;
class HelpersTest extends TestCase
{
public function testTimespanInPast()
{
$now = Carbon::now();
$tests = [
['4d', (clone $now)->subDays(4)],
['1d 2h', (clone $now)->subDays(1)->subHours(2)],
['11d 5h 5m', (clone $now)->subDays(11)->subHours(5)->subMinutes(5)],
['2d 7m', (clone $now)->subDays(2)->subMinutes(7)],
['1m', (clone $now)->subMinutes(1)],
];
foreach ($tests as $test) {
$past = Misc::timespanInPast($test[0], clone $now);
$this->assertTrue($past->eq($test[1]), "Dates not equal for timespan $test[0]");
}
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/routes/web.php | Beam/extensions/beam-module/routes/web.php | <?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
use Remp\BeamModule\Http\Controllers\DashboardController;
use Remp\BeamModule\Http\Controllers\AccountController;
use Remp\BeamModule\Http\Controllers\SegmentController;
use Remp\BeamModule\Http\Controllers\PropertyController;
use Remp\BeamModule\Http\Controllers\ArticleController;
use Remp\BeamModule\Http\Controllers\AuthController;
use Remp\BeamModule\Http\Controllers\ArticleDetailsController;
use Remp\BeamModule\Http\Controllers\AuthorController;
use Remp\BeamModule\Http\Controllers\AuthorSegmentsController;
use Remp\BeamModule\Http\Controllers\ConversionController;
use Remp\BeamModule\Http\Controllers\SearchController;
use Remp\BeamModule\Http\Controllers\UserPathController;
use Remp\BeamModule\Http\Controllers\NewsletterController;
use Remp\BeamModule\Http\Controllers\SectionController;
use Remp\BeamModule\Http\Controllers\SectionSegmentsController;
use Remp\BeamModule\Http\Controllers\TagCategoryController;
use Remp\BeamModule\Http\Controllers\TagController;
use Remp\BeamModule\Http\Controllers\EntitiesController;
use Remp\BeamModule\Http\Controllers\SettingsController;
use Remp\BeamModule\Http\Middleware\DashboardBasicAuth;
use Remp\LaravelSso\Http\Middleware\VerifyJwtToken;
Route::get('/error', [AuthController::class, 'error'])->name('sso.error');
// Temporarily use basic auth for public dashboard
// TODO: remove once authentication layer is done
Route::middleware(DashboardBasicAuth::class)->group(function () {
Route::get('public', [DashboardController::class, 'public'])->name('dashboard.public');
Route::post('public/articlesJson', [DashboardController::class, 'mostReadArticles'])->name('public.articles.json');
Route::post('public/timeHistogramJson', [DashboardController::class, 'timeHistogram'])->name('public.timeHistogram.json');
Route::post('public/timeHistogramNewJson', [DashboardController::class, 'timeHistogramNew'])->name('public.timeHistogramNew.json');
});
// Public route for switching token, available from both public dashboard and authenticated section
Route::post('/properties/switch', [PropertyController::class, 'switch'])->name('properties.switch');
Route::middleware(VerifyJwtToken::class)->group(function () {
Route::get('/', [DashboardController::class, 'index'])->name('dashboard.index');
Route::get('dashboard', [DashboardController::class, 'index'])->name('dashboard.index');
Route::post('dashboard/articlesJson', [DashboardController::class, 'mostReadArticles'])->name('dashboard.articles.json');
Route::post('dashboard/timeHistogramJson', [DashboardController::class, 'timeHistogram'])->name('dashboard.timeHistogram.json');
Route::post('dashboard/timeHistogramNewJson', [DashboardController::class, 'timeHistogramNew'])->name('dashboard.timeHistogramNew.json');
Route::get('accounts/json', [AccountController::class, 'json'])->name('accounts.json');
Route::get('accounts/{account}/properties/json', [PropertyController::class, 'json'])->name('accounts.properties.json');
Route::get('segments/json', [SegmentController::class, 'json'])->name('segments.json');
Route::get('segments/{sourceSegment}/copy', [SegmentController::class, 'copy'])->name('segments.copy');
Route::get('segments/beta/embed', [SegmentController::class, 'embed'])->name('segments.beta.embed');
Route::get('segments/beta/create', [SegmentController::class, 'betaCreate'])->name('segments.beta.create');
Route::get('segments/beta/{segment}/edit', [SegmentController::class, 'betaEdit'])->name('segments.beta.edit');
Route::get('articles/conversions', [ArticleController::class, 'conversions'])->name('articles.conversions');
Route::get('articles/dtConversions', [ArticleController::class, 'dtConversions'])->name('articles.dtConversions');
Route::get('articles/pageviews', [ArticleController::class, 'pageviews'])->name('articles.pageviews');
Route::get('articles/dtPageviews', [ArticleController::class, 'dtPageviews'])->name('articles.dtPageviews');
Route::post('articles/upsert', [ArticleController::class, 'upsert'])->name('articles.upsert');
Route::get('conversions/json', [ConversionController::class, 'json'])->name('conversions.json');
Route::post('conversions/upsert', [ConversionController::class, 'upsert'])->name('conversions.upsert');
Route::get('author-segments', [AuthorSegmentsController::class, 'index'])->name('authorSegments.index');
Route::get('author-segments/json', [AuthorSegmentsController::class, 'json'])->name('authorSegments.json');
Route::get('author-segments/test-parameters', [AuthorSegmentsController::class, 'testingConfiguration'])->name('authorSegments.testingConfiguration');
Route::post('author-segments/compute', [AuthorSegmentsController::class, 'compute'])->name('authorSegments.compute');
Route::post('author-segments/validate-test', [AuthorSegmentsController::class, 'validateTest'])->name('authorSegments.validateTest');
Route::get('section-segments', [SectionSegmentsController::class, 'index'])->name('sectionSegments.index');
Route::get('section-segments/json', [SectionSegmentsController::class, 'json'])->name('sectionSegments.json');
Route::get('section-segments/test-parameters', [SectionSegmentsController::class, 'testingConfiguration'])->name('sectionSegments.testingConfiguration');
Route::post('section-segments/compute', [SectionSegmentsController::class, 'compute'])->name('sectionSegments.compute');
Route::post('section-segments/validate-test', [SectionSegmentsController::class, 'validateTest'])->name('sectionSegments.validateTest');
Route::get('authors/dtAuthors', [AuthorController::class, 'dtAuthors'])->name('authors.dtAuthors');
Route::get('authors/{author}/dtArticles', [AuthorController::class, 'dtArticles'])->name('authors.dtArticles');
Route::get('auth/logout', [AuthController::class, 'logout'])->name('auth.logout');
Route::resource('accounts', AccountController::class);
Route::resource('accounts.properties', PropertyController::class);
Route::resource('segments', SegmentController::class);
Route::get('articles/{article}/histogramJson', [ArticleDetailsController::class, 'timeHistogram'])->name('articles.timeHistogram.json');
Route::get('articles/{article}/variantsHistogramJson', [ArticleDetailsController::class, 'variantsHistogram'])->name('articles.variantsHistogram.json');
Route::get('articles/{article}/dtReferers', [ArticleDetailsController::class, 'dtReferers'])->name('articles.dtReferers');
Route::resource('articles', ArticleController::class, [
'only' => ['index', 'store'],
]);
Route::resource('articles', ArticleDetailsController::class, [
'only' => ['show'],
]);
Route::get('article/{article?}', [ArticleDetailsController::class, 'showByParameter']);
Route::get('newsletters/json', [NewsletterController::class, 'json'])->name('newsletters.json');
Route::post('newsletters/validate', [NewsletterController::class, 'validateForm'])->name('newsletters.validateForm');
Route::post('newsletters/{newsletter}/start', [NewsletterController::class, 'start'])->name('newsletters.start');
Route::post('newsletters/{newsletter}/pause', [NewsletterController::class, 'pause'])->name('newsletters.pause');
Route::resource('newsletters', NewsletterController::class, ['except' => ['show']]);
Route::get('userpath', [UserPathController::class, 'index'])->name('userpath.index');
Route::post('userpath/statsJson', [UserPathController::class, 'stats'])->name('userpath.stats');
Route::post('userpath/diagram', [UserPathController::class, 'diagramData'])->name('userpath.diagramData');
Route::resource('conversions', ConversionController::class, [
'only' => ['index', 'store', 'show']
]);
Route::resource('authors', AuthorController::class, [
'only' => ['index', 'show']
]);
Route::get('sections/dtSections', [SectionController::class, 'dtSections'])->name('sections.dtSections');
Route::get('sections/{section}/dtArticles', [SectionController::class, 'dtArticles'])->name('sections.dtArticles');
Route::resource('sections', SectionController::class, [
'only' => ['index', 'show']
]);
Route::get('tags/dtTags', [TagController::class, 'dtTags'])->name('tags.dtTags');
Route::get('tags/{tag}/dtArticles', [TagController::class, 'dtArticles'])->name('tags.dtArticles');
Route::resource('tags', TagController::class, [
'only' => ['index', 'show']
]);
Route::get('tag-categories/dtTagCategories', [TagCategoryController::class, 'dtTagCategories'])->name('tagCategories.dtTagCategories');
Route::get('tag-categories/{tagCategory}/dtTags', [TagCategoryController::class, 'dtTags'])->name('tagCategories.dtTags');
Route::get('tag-categories/{tagCategory}/dtArticles', [TagCategoryController::class, 'dtArticles'])->name('tagCategories.dtArticles');
Route::resource('tag-categories', TagCategoryController::class, [
'only' => ['index', 'show']
]);
Route::get('settings', [SettingsController::class, 'index'])->name('settings.index');
Route::post('settings/{configCategory}', [SettingsController::class, 'update'])->name('settings.update');
Route::post('entities/validate/{entity?}', [EntitiesController::class, 'validateForm'])->name('entities.validateForm');
Route::get('entities/json', [EntitiesController::class, 'json'])->name('entities.json');
Route::resource('entities', EntitiesController::class);
Route::get('search', [SearchController::class, 'search'])->name('search');
});
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/routes/channels.php | Beam/extensions/beam-module/routes/channels.php | <?php
/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/
Broadcast::channel('App.User.{id}', function ($user, $id) {
return (int) $user->id === (int) $id;
});
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/routes/api.php | Beam/extensions/beam-module/routes/api.php | <?php
use Illuminate\Http\Middleware\HandleCors;
use Remp\BeamModule\Http\Controllers\Api\v1\ArticleController as ArticleControllerApiV1;
use Remp\BeamModule\Http\Controllers\Api\v1\AuthorController as AuthorControllerApiV1;
use Remp\BeamModule\Http\Controllers\Api\v1\JournalController;
use Remp\BeamModule\Http\Controllers\Api\v1\PageviewController;
use Remp\BeamModule\Http\Controllers\Api\v1\TagController as TagControllerApiV1;
use Remp\BeamModule\Http\Controllers\Api\v2\ArticleController as ArticleControllerApiV2;
use Remp\BeamModule\Http\Controllers\Api\v2\AuthorController as AuthorControllerApiV2;
use Remp\BeamModule\Http\Controllers\Api\v2\TagController as TagControllerApiV2;
use Remp\BeamModule\Http\Controllers\ArticleController;
use Remp\BeamModule\Http\Controllers\ArticleDetailsController;
use Remp\BeamModule\Http\Controllers\ConversionController;
use Remp\BeamModule\Http\Controllers\DashboardController;
use Remp\BeamModule\Http\Controllers\JournalProxyController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::middleware('auth:api')->group(function () {
Route::apiResource('articles', ArticleController::class, [
'only' => ['index', 'store'],
]);
Route::apiResource('conversions', ConversionController::class, [
'only' => ['index', 'store']
]);
Route::post('articles/unread', [ArticleControllerApiV1::class, 'unreadArticlesForUsers'])->name('articles.unreadArticlesForUsers');
Route::post('articles/read', [ArticleControllerApiV1::class, 'readArticles'])->name('articles.readArticles');
Route::post('articles/upsert', [ArticleControllerApiV1::class, 'upsert'])->name('articles.upsert');
Route::post('conversions/upsert', [ConversionController::class, 'upsert'])->name('conversions.upsert');
Route::get('article/{article?}', [ArticleDetailsController::class, 'show']);
Route::get('article/{article}/histogram', [ArticleDetailsController::class, 'timeHistogram']);
Route::get('article/{article}/variants-histogram', [ArticleDetailsController::class, 'variantsHistogram']);
Route::get('/journal/concurrents/count/', [JournalController::class, 'concurrentsCount']);
Route::match(['GET', 'POST'], '/journal/concurrents/count/articles', [JournalController::class, 'articlesConcurrentsCount']);
Route::post('/journal/concurrents/count/', [JournalController::class, 'concurrentsCount']);
// Pure proxy calls to Journal API (TODO: rework to more user-friendly API)
Route::post('/journal/pageviews/actions/progress/count', [JournalProxyController::class, 'pageviewsProgressCount']);
Route::post('/journal/pageviews/actions/load/unique/browsers', [JournalProxyController::class, 'pageviewsUniqueBrowsersCount']);
Route::post('/journal/commerce/steps/purchase/count', [JournalProxyController::class, 'commercePurchaseCount']);
Route::post('articles/top', [ArticleControllerApiV1::class, 'topArticles'])->name('articles.top');
Route::post('authors/top', [AuthorControllerApiV1::class, 'topAuthors'])->name('authors.top');
Route::post('tags/top', [TagControllerApiV1::class, 'topTags'])->name('tags.top');
Route::post('pageviews/histogram', [PageviewController::class, 'timeHistogram']);
Route::group(['prefix' => 'v2'], function () {
Route::post('articles/top', [ArticleControllerApiV2::class, 'topArticles'])->name('articles.top.v2');
Route::post('authors/top', [AuthorControllerApiV2::class, 'topAuthors'])->name('authors.top.v2');
Route::post('tags/top', [TagControllerApiV2::class, 'topTags'])->name('tags.top.v2');
Route::post('articles/upsert', [ArticleControllerApiV2::class, 'upsert'])->name('articles.upsert.v2');
});
Route::get('authors', [\Remp\BeamModule\Http\Controllers\AuthorController::class, 'index'])->name('authors.index');
Route::get('sections', [\Remp\BeamModule\Http\Controllers\SectionController::class, 'index'])->name('sections.index');
Route::get('tags', [\Remp\BeamModule\Http\Controllers\TagController::class, 'index'])->name('tags.index');
});
Route::get('/journal/{group}/categories/{category}/actions', [JournalController::class, 'actions']);
Route::get('/journal/flags', [JournalController::class, 'flags']);
Route::middleware(HandleCors::class)->group(function () {
Route::get('/dashboard/options', [DashboardController::class, 'options'])->name('dashboard.options');
});
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/routes/console.php | Beam/extensions/beam-module/routes/console.php | <?php
use Illuminate\Foundation\Inspiring;
use Illuminate\Support\Facades\Artisan;
/*
|--------------------------------------------------------------------------
| Console Routes
|--------------------------------------------------------------------------
|
| This file is where you may define all of your Closure based console
| commands. Each Closure is bound to a command instance allowing a
| simple approach to interacting with each command's IO methods.
|
*/
Artisan::command('inspire', function () {
$this->comment(Inspiring::quote());
})->purpose('Display an inspiring quote');
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/config/services.php | Beam/extensions/beam-module/config/services.php | <?php
return [
'beam' => [
'web_addr' => env('REMP_BEAM_ADDR'),
'tracker_addr' => env('REMP_TRACKER_ADDR'),
'tracker_property_token' => env('REMP_TRACKER_ADDR'),
'segments_addr' => env('REMP_SEGMENTS_ADDR'),
'segments_auth_token' => env('REMP_SEGMENTS_AUTH_TOKEN'),
],
'campaign' => [
'web_addr' => env('REMP_CAMPAIGN_ADDR'),
],
'mailer' => [
'web_addr' => env('REMP_MAILER_ADDR'),
'api_token' => env('REMP_MAILER_API_TOKEN')
],
'sso' => [
'web_addr' => env('REMP_SSO_ADDR'),
'api_token' => env('REMP_SSO_API_TOKEN'),
],
'linked' => [
'beam' => [
'url' => '/',
'icon' => 'album',
],
'campaign' => [
'url' => env('REMP_CAMPAIGN_ADDR'),
'icon' => 'trending-up',
],
'mailer' => [
'url' => env('REMP_MAILER_ADDR'),
'icon' => 'email',
],
],
];
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/config/beam.php | Beam/extensions/beam-module/config/beam.php | <?php
// Basic Beam settings
return [
/*
|--------------------------------------------------------------------------
| Data retention/compression period
|--------------------------------------------------------------------------
|
| Beam aggregates data from Segments API, here we set up how long these data are kept for.
| Negative value means data are kept indefinitely.
|
*/
'aggregated_data_retention_period' => env('AGGREGATED_DATA_RETENTION_PERIOD', 90),
/*
|--------------------------------------------------------------------------
| Pageview graph data source
|--------------------------------------------------------------------------
|
| Valid values:
| snapshots - load data stored in DB snapshots of Journal API (data represents recorded concurrents for points in time)
| journal - (default for now) load data directly from Journal API (data represents total number of pageviews for specific intervals).
|
*/
'pageview_graph_data_source' => env('PAGEVIEW_GRAPH_DATA_SOURCE', 'journal'),
/*
|--------------------------------------------------------------------------
| Article traffic graph data source
|--------------------------------------------------------------------------
|
| Valid values:
| snapshots - load data stored in DB snapshots of Journal API (data represents recorded concurrents for points in time)
| journal - load data directly from Journal API (data represents total number of pageviews for specific intervals).
| pageviews - (default for now) load data from article_pageviews DB table.
|
*/
'article_traffic_graph_data_source' => env('ARTICLE_TRAFFIC_GRAPH_DATA_SOURCE', 'pageviews'),
// Temporarily disable property token filtering for debugging
'disable_token_filtering' => env('DISABLE_TOKEN_FILTERING', false),
/*
|--------------------------------------------------------------------------
| Article traffic graph additional intervals
|--------------------------------------------------------------------------
*/
'article_traffic_graph_show_interval_7d' => env('ARTICLE_TRAFFIC_GRAPH_SHOW_INTERVAL_7D', true),
'article_traffic_graph_show_interval_30d' => env('ARTICLE_TRAFFIC_GRAPH_SHOW_INTERVAL_30D', true),
/*
|--------------------------------------------------------------------------
| Newsletter sending configuration
|--------------------------------------------------------------------------
*/
'newsletter_ignored_content_types' => env('NEWSLETTER_IGNORED_CONTENT_TYPES')
? explode(",", env('NEWSLETTER_IGNORED_CONTENT_TYPES'))
: [],
'newsletter_ignored_authors' => env('NEWSLETTER_IGNORED_AUTHORS')
? explode(",", env('NEWSLETTER_IGNORED_AUTHORS'))
: [],
];
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/config/system.php | Beam/extensions/beam-module/config/system.php | <?php
$definition = env('COMMANDS_MEMORY_LIMITS');
$limits = [];
if (!empty($definition)) {
foreach (explode(',', $definition) as $commandLimit) {
$config = explode('::', $commandLimit);
if (count($config) !== 2 || empty($config[0]) || empty($config[1])) {
throw new \Exception('invalid format of COMMANDS_MEMORY_LIMITS entry; expected "command::limit", got "' . $commandLimit . '"');
}
$limits[$config[0]] = $config[1];
}
}
return [
'commands_memory_limits' => $limits,
'commands_overlapping_expires_at' => env('COMMANDS_OVERLAPPING_EXPIRES_AT', 15),
'commands' => [
'aggregate_article_views' => [
'default_step' => env('AGGREGATE_ARTICLE_VIEWS_DEFAULT_STEP'),
],
],
];
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/ArticleViewsSnapshotFactory.php | Beam/extensions/beam-module/database/factories/ArticleViewsSnapshotFactory.php | <?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
namespace Remp\BeamModule\Database\Factories;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\ArticleViewsSnapshot;
class ArticleViewsSnapshotFactory extends Factory
{
protected $model = ArticleViewsSnapshot::class;
public function definition()
{
$refererMediums = ['external', 'internal', 'direct', 'email', 'social'];
return [
'time' => Carbon::now(),
'property_token' => $this->faker->uuid,
'external_article_id' => $this->faker->numberBetween(9999, 10000000),
'referer_medium' => $refererMediums[array_rand($refererMediums)],
'count' => $this->faker->numberBetween(1, 1000)
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/SegmentUserFactory.php | Beam/extensions/beam-module/database/factories/SegmentUserFactory.php | <?php
namespace Remp\BeamModule\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\SegmentUser;
class SegmentUserFactory extends Factory
{
protected $model = SegmentUser::class;
public function definition()
{
return [
'user_id' => $this->faker->numberBetween(1, 1000000),
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/SegmentFactory.php | Beam/extensions/beam-module/database/factories/SegmentFactory.php | <?php
namespace Remp\BeamModule\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\Segment;
use Remp\BeamModule\Model\SegmentGroup;
class SegmentFactory extends Factory
{
protected $model = Segment::class;
public function definition()
{
$segmentName = $this->faker->domainWord;
return [
'name' => $segmentName,
'code' => "$segmentName-segment",
'active' => true,
];
}
public function author()
{
return $this->state(['segment_group_id' => SegmentGroup::getByCode(SegmentGroup::CODE_AUTHORS_SEGMENTS)->id]);
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/SegmentRuleFactory.php | Beam/extensions/beam-module/database/factories/SegmentRuleFactory.php | <?php
namespace Remp\BeamModule\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\SegmentRule;
class SegmentRuleFactory extends Factory
{
protected $model = SegmentRule::class;
public function definition()
{
return [
'event_category' => 'banner',
'event_action' => 'show',
'operator' => '<',
'count' => $this->faker->numberBetween(1, 5),
'timespan' => 1440 * $this->faker->numberBetween(1, 7),
'fields' => [
[
'key' => 'rtm_campaign',
'value' => null,
]
],
'flags' => [],
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/SegmentBrowserFactory.php | Beam/extensions/beam-module/database/factories/SegmentBrowserFactory.php | <?php
namespace Remp\BeamModule\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\SegmentBrowser;
class SegmentBrowserFactory extends Factory
{
protected $model = SegmentBrowser::class;
public function definition()
{
return [
'browser_id' => $this->faker->uuid,
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/ArticleTimespentFactory.php | Beam/extensions/beam-module/database/factories/ArticleTimespentFactory.php | <?php
namespace Remp\BeamModule\Database\Factories;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\ArticleTimespent;
class ArticleTimespentFactory extends Factory
{
protected $model = ArticleTimespent::class;
public function definition()
{
$sum = $this->faker->numberBetween(100, 400);
$signedIn = $this->faker->numberBetween(1, 50);
$subscribers = $sum - $signedIn;
$timeTo = Carbon::instance($this->faker->dateTimeBetween('-30 days', 'now'));
$timeFrom = (clone $timeTo)->subHour();
return [
'article_id' => function () {
return \Remp\BeamModule\Model\Article::factory()->create()->id;
},
'time_from' => $timeFrom,
'time_to' => $timeTo,
'sum' => $sum,
'signed_in' => $signedIn,
'subscribers' => $subscribers
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/ArticleFactory.php | Beam/extensions/beam-module/database/factories/ArticleFactory.php | <?php
namespace Remp\BeamModule\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\Article;
class ArticleFactory extends Factory
{
protected $model = Article::class;
public function definition()
{
return [
'external_id' => $this->faker->uuid,
'title' => $this->faker->words(5, true),
'url' => $this->faker->url,
'content_type' => 'article',
'image_url' => $this->faker->imageUrl(),
'published_at' => $this->faker->dateTimeBetween('-30 days', 'now')->format(DATE_RFC3339),
'pageviews_all' => $this->faker->numberBetween(0, 20000),
'pageviews_signed_in' => $this->faker->numberBetween(0, 20000),
'pageviews_subscribers' => $this->faker->numberBetween(0, 20000),
'timespent_all' => $this->faker->numberBetween(0, 600000),
'timespent_signed_in' => $this->faker->numberBetween(0, 600000),
'timespent_subscribers' => $this->faker->numberBetween(0, 600000),
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/ConversionCommerceEventFactory.php | Beam/extensions/beam-module/database/factories/ConversionCommerceEventFactory.php | <?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
namespace Remp\BeamModule\Database\Factories;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\ConversionCommerceEvent;
class ConversionCommerceEventFactory extends Factory
{
protected $model = ConversionCommerceEvent::class;
public function definition()
{
$steps = ['checkout', 'payment', 'purchase', 'refund'];
return [
'time' => Carbon::now(),
'step' => $steps[array_rand($steps)],
'minutes_to_conversion' => $this->faker->numberBetween(1, 1000),
'event_prior_conversion' => $this->faker->numberBetween(1, 10),
'funnel_id' => $this->faker->numberBetween(1, 10),
'amount' => $this->faker->numberBetween(5, 20),
'currency' => $this->faker->randomElement(['EUR','USD']),
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/ConversionFactory.php | Beam/extensions/beam-module/database/factories/ConversionFactory.php | <?php
namespace Remp\BeamModule\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\Conversion;
class ConversionFactory extends Factory
{
protected $model = Conversion::class;
public function definition()
{
return [
'amount' => $this->faker->numberBetween(5, 50),
'currency' => $this->faker->randomElement(['EUR','USD']),
'paid_at' => $this->faker->dateTimeBetween('-30 days', 'now')->format(DATE_RFC3339),
'transaction_id' => $this->faker->uuid,
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/TagFactory.php | Beam/extensions/beam-module/database/factories/TagFactory.php | <?php
/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/
namespace Remp\BeamModule\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\Tag;
class TagFactory extends Factory
{
protected $model = Tag::class;
public function definition()
{
return [
'name' => $this->faker->domainWord,
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/ArticlePageviewsFactory.php | Beam/extensions/beam-module/database/factories/ArticlePageviewsFactory.php | <?php
namespace Remp\BeamModule\Database\Factories;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\ArticlePageviews;
class ArticlePageviewsFactory extends Factory
{
protected $model = ArticlePageviews::class;
public function definition()
{
$sum = $this->faker->numberBetween(5, 10);
$signedIn = $this->faker->numberBetween(1, 5);
$subscribers = $sum - $signedIn;
$timeTo = Carbon::instance($this->faker->dateTimeBetween('-30 days', 'now'));
$timeFrom = (clone $timeTo)->subHour();
return [
'article_id' => function () {
return \Remp\BeamModule\Model\Article::factory()->create()->id;
},
'time_from' => $timeFrom,
'time_to' => $timeTo,
'sum' => $sum,
'signed_in' => $signedIn,
'subscribers' => $subscribers
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/PropertyFactory.php | Beam/extensions/beam-module/database/factories/PropertyFactory.php | <?php
namespace Remp\BeamModule\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\Account;
use Remp\BeamModule\Model\Property;
class PropertyFactory extends Factory
{
protected $model = Property::class;
public function definition()
{
return [
'name' => 'DEMO property',
'uuid' => $this->faker->uuid,
'account_id' => function () {
return Account::factory()->create()->id;
},
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/AuthorFactory.php | Beam/extensions/beam-module/database/factories/AuthorFactory.php | <?php
namespace Remp\BeamModule\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\Author;
class AuthorFactory extends Factory
{
protected $model = Author::class;
public function definition()
{
return [
'name' => $this->faker->name(),
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/TagCategoryFactory.php | Beam/extensions/beam-module/database/factories/TagCategoryFactory.php | <?php
namespace Remp\BeamModule\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\TagCategory;
class TagCategoryFactory extends Factory
{
protected $model = TagCategory::class;
public function definition()
{
return [
'name' => $this->faker->domainWord,
'external_id' => $this->faker->uuid,
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/SectionFactory.php | Beam/extensions/beam-module/database/factories/SectionFactory.php | <?php
namespace Remp\BeamModule\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\Section;
class SectionFactory extends Factory
{
protected $model = Section::class;
public function definition()
{
return [
'name' => $this->faker->domainWord,
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/factories/AccountFactory.php | Beam/extensions/beam-module/database/factories/AccountFactory.php | <?php
namespace Remp\BeamModule\Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Remp\BeamModule\Model\Account;
class AccountFactory extends Factory
{
protected $model = Account::class;
public function definition()
{
return [
'name' => 'DEMO account',
'uuid' => $this->faker->uuid,
];
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/migrations/2021_05_31_000000_add_uuid_to_failed_jobs_table.php | Beam/extensions/beam-module/database/migrations/2021_05_31_000000_add_uuid_to_failed_jobs_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
class AddUuidToFailedJobsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('failed_jobs', function (Blueprint $table) {
$table->string('uuid')->after('id')->nullable()->unique();
});
DB::table('failed_jobs')->whereNull('uuid')->cursor()->each(function ($job) {
DB::table('failed_jobs')
->where('id', $job->id)
->update(['uuid' => (string)Str::uuid()]);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('failed_jobs', function (Blueprint $table) {
$table->dropColumn('uuid');
});
}
}
| php | MIT | c616d27734c65eb87b470751928ff1119c535549 | 2026-01-05T05:12:01.604239Z | false |
remp2020/remp | https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Beam/extensions/beam-module/database/migrations/2019_09_05_093404_create_config_categories_table.php | Beam/extensions/beam-module/database/migrations/2019_09_05_093404_create_config_categories_table.php | <?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateConfigCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('config_categories', function (Blueprint $table) {
$table->increments('id');
$table->string('code');
$table->string('display_name');
$table->timestamps();
$table->unique('code');
});
Schema::table('configs', function (Blueprint $table) {
$table->integer('config_category_id')
->unsigned()
->nullable()
->after('id');
$table->foreign('config_category_id')->references('id')->on('config_categories');
});
Artisan::call('db:seed', [
'--class' => \Remp\BeamModule\Database\Seeders\ConfigSeeder::class,
'--force' => true,
]);
}
}
| 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.