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/Campaign/extensions/campaign-module/src/Contracts/SegmentCacheException.php
Campaign/extensions/campaign-module/src/Contracts/SegmentCacheException.php
<?php namespace Remp\CampaignModule\Contracts; class SegmentCacheException extends \Exception { }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Contracts/SegmentException.php
Campaign/extensions/campaign-module/src/Contracts/SegmentException.php
<?php namespace Remp\CampaignModule\Contracts; class SegmentException extends \Exception { }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Contracts/SegmentContract.php
Campaign/extensions/campaign-module/src/Contracts/SegmentContract.php
<?php namespace Remp\CampaignModule\Contracts; use Remp\CampaignModule\CampaignSegment; use Illuminate\Support\Collection; interface SegmentContract { const CACHE_TAG = 'segment'; public function list(): Collection; public function checkUser(CampaignSegment $campaignSegment, string $userId): bool; public function checkBrowser(CampaignSegment $campaignSegment, string $browserId): bool; public function users(CampaignSegment $campaignSegment): Collection; public function provider(): string; public function cacheEnabled(CampaignSegment $campaignSegment): bool; public function addUserToCache(CampaignSegment $campaignSegment, string $userId): bool; public function removeUserFromCache(CampaignSegment $campaignSegment, string $userId): bool; /** * setCache stores and provides cache object for campaign segment providers. * * @param $cache \stdClass Array of objects keyed by name of the segment provider. Internals * of the stored object is defined by contract of provider itself * and not subject of validation here. */ public function setProviderData($cache): void; /** * getProviderData returns internal per-provider data objects to be stored * by third party and possibly provided later via *setCache()* call. * * @return \stdClass */ public function getProviderData(); }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Contracts/StatsHelper.php
Campaign/extensions/campaign-module/src/Contracts/StatsHelper.php
<?php namespace Remp\CampaignModule\Contracts; use Remp\CampaignModule\Campaign; use Remp\CampaignModule\CampaignBanner; use Remp\CampaignModule\CampaignBannerPurchaseStats; use Remp\CampaignModule\CampaignBannerStats; use Remp\CampaignModule\Models\Interval\Interval; use Remp\CampaignModule\Models\Interval\IntervalModeEnum; use Illuminate\Support\Carbon; use Illuminate\Support\Collection; use Illuminate\Support\Facades\DB; class StatsHelper { private $stats; public function __construct(StatsContract $statsContract) { $this->stats = $statsContract; } /** * * @param Campaign $campaign * @param Carbon|null $from Expected time in UTC * @param Carbon|null $to Expected time in UTC * * @return array [$campaignStats, $variantsStats] */ public function cachedCampaignAndVariantsStats(Campaign $campaign, Carbon $from = null, Carbon $to = null): array { /** @var Collection $campaignBanners */ $campaignBanners = $campaign->campaignBanners()->withTrashed()->get(); $campaignData = [ 'click_count' => 0, 'show_count' => 0, 'payment_count' => 0, 'purchase_count' => 0, 'purchase_sums' => [], 'ctr' => 0, 'conversions' => 0, ]; $variantsData = []; foreach ($campaignBanners as $campaignBanner) { $variantsData[$campaignBanner->uuid] = $campaignData; } $statsQuerySelect = 'campaign_banner_id, '. 'SUM(click_count) AS click_count, '. 'SUM(show_count) as show_count, '. 'SUM(payment_count) as payment_count, '. 'SUM(purchase_count) as purchase_count'; $statsQuery = CampaignBannerStats::select(DB::raw($statsQuerySelect)) ->whereIn('campaign_banner_id', $campaignBanners->pluck('id')) ->groupBy('campaign_banner_id'); $purchaseStatsQuerySelect = 'campaign_banner_id, '. 'SUM(`sum`) AS purchase_sum, '. 'currency'; $purchaseStatsQuery = CampaignBannerPurchaseStats::select(DB::raw($purchaseStatsQuerySelect)) ->whereIn('campaign_banner_id', $campaignBanners->pluck('id')) ->groupBy(['campaign_banner_id', 'currency']); if ($from) { $statsQuery->where('time_from', '>=', $from); $purchaseStatsQuery->where('time_from', '>=', $from); } if ($to) { $statsQuery->where('time_to', '<=', $to); $purchaseStatsQuery->where('time_to', '<=', $to); } /** @var CampaignBannerStats $stat */ foreach ($statsQuery->get() as $stat) { // Campaign banner may already be soft-deleted $statCampaignBanner = $stat->campaignBanner()->withTrashed()->first(); $variantData = $variantsData[$statCampaignBanner->uuid]; $variantData['click_count'] = (int) $stat->click_count; $variantData['show_count'] = (int) $stat->show_count; $variantData['payment_count'] = (int) $stat->payment_count; $variantData['purchase_count'] = (int) $stat->purchase_count; $variantsData[$statCampaignBanner->uuid] = StatsHelper::addCalculatedValues($variantData); $campaignData['click_count'] += $variantData['click_count']; $campaignData['show_count'] += $variantData['show_count']; $campaignData['payment_count'] += $variantData['payment_count']; $campaignData['purchase_count'] += $variantData['purchase_count']; } $campaignData = StatsHelper::addCalculatedValues($campaignData); foreach ($purchaseStatsQuery->get() as $stat) { // Campaign banner may already be soft-deleted $statCampaignBanner = $stat->campaignBanner()->withTrashed()->first(); if (!array_key_exists($statCampaignBanner->uuid, $variantsData)) { throw new \LogicException("Campaign banner {$statCampaignBanner->uuid} has aggregated purchases without other aggregated attributes."); } if (!array_key_exists($stat->currency, $variantsData[$statCampaignBanner->uuid]['purchase_sums'])) { $variantsData[$statCampaignBanner->uuid]['purchase_sums'][$stat->currency] = 0.0; } $variantsData[$statCampaignBanner->uuid]['purchase_sums'][$stat->currency] += (double) $stat['purchase_sum']; if (!array_key_exists($stat->currency, $campaignData['purchase_sums'])) { $campaignData['purchase_sums'][$stat->currency] = 0.0; } $campaignData['purchase_sums'][$stat->currency] += (double) $stat['purchase_sum']; } return [$campaignData, $variantsData]; } /** * @param Campaign $campaign * @param Carbon|null $from Expected time in UTC * @param Carbon|null $to Expected time in UTC * * @return array */ public function campaignStats(Campaign $campaign, Carbon $from = null, Carbon $to = null) { return $this->variantsStats($campaign->variants_uuids, $from, $to); } /** * @param CampaignBanner $variant * @param Carbon|null $from Expected time in UTC * @param Carbon|null $to Expected time in UTC * * @return array */ public function variantStats(CampaignBanner $variant, Carbon $from = null, Carbon $to = null) { return $this->variantsStats([$variant->uuid], $from, $to); } public function addCalculatedValues($data) { // calculate ctr & conversions if (isset($data['show_count']) && $data['show_count'] > 0) { if ($data['click_count']) { $data['ctr'] = ($data['click_count'] / $data['show_count']) * 100; } if ($data['purchase_count']) { $data['conversions'] = ($data['purchase_count'] / $data['show_count']) * 100; } } return $data; } private function variantsStats($variantUuids, Carbon $from = null, Carbon $to = null) { $data = [ 'click_count' => $this->campaignStatsCount($variantUuids, 'click', $from, $to), 'show_count' => $this->campaignStatsCount($variantUuids, 'show', $from, $to), 'payment_count' => $this->campaignPaymentStatsCount($variantUuids, 'payment', $from, $to), 'purchase_count' => $this->campaignPaymentStatsCount($variantUuids, 'purchase', $from, $to), 'purchase_sum' => $this->campaignPaymentStatsSum($variantUuids, 'purchase', $from, $to), ]; return $data; } private function campaignStatsCount($variantUuids, $type, Carbon $from = null, Carbon $to = null) { $r = $this->stats->count() ->events('banner', $type) ->forVariants($variantUuids); if ($from) { $r->from($from); } if ($to) { $r->to($to); } return $r->get()[0]; } private function campaignPaymentStatsCount($variantUuids, $step, Carbon $from = null, Carbon $to = null) { $r = $this->stats->count() ->commerce($step) ->forVariants($variantUuids); if ($from) { $r->from($from); } if ($to) { $r->to($to); } return $r->get()[0]; } private function campaignPaymentStatsSum($variantUuids, $step, Carbon $from = null, Carbon $to = null) { $r = $this->stats->sum() ->commerce($step) ->forVariants($variantUuids) ->groupBy('currency'); if ($from) { $r->from($from); } if ($to) { $r->to($to); } return $r->get(); } /** * Calculate Elasticsearch interval based on date range */ public function calcInterval(Carbon $from, Carbon $to, IntervalModeEnum $intervalMode = IntervalModeEnum::Auto): Interval { if ($intervalMode !== IntervalModeEnum::Auto) { return $intervalMode->toInterval(); } // Automatic interval selection based on time range $diff = $from->diffInSeconds($to); return match (true) { $diff > IntervalModeEnum::Year->minRangeSeconds() => IntervalModeEnum::Year->toInterval(), $diff > IntervalModeEnum::Month->minRangeSeconds() => IntervalModeEnum::Month->toInterval(), $diff > IntervalModeEnum::Week->minRangeSeconds() => IntervalModeEnum::Week->toInterval(), $diff > IntervalModeEnum::Day->minRangeSeconds() => IntervalModeEnum::Day->toInterval(), $diff > IntervalModeEnum::Hour->minRangeSeconds() => IntervalModeEnum::Hour->toInterval(), $diff >= IntervalModeEnum::Min15->minRangeSeconds() => IntervalModeEnum::Min15->toInterval(), default => IntervalModeEnum::Min5->toInterval(), }; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Contracts/StatsContract.php
Campaign/extensions/campaign-module/src/Contracts/StatsContract.php
<?php namespace Remp\CampaignModule\Contracts; use Carbon\Carbon; use Remp\CampaignModule\Contracts\Remp\StatsRequest; /** * Beam segments API fluent interface * for accessing campaigns statistics */ interface StatsContract { /** * filter results by variant id * * @param int $variantId * @return StatsRequest */ public function forVariant($variantId) : StatsRequest; /** * filter results by variant ids * * @param array $variantIds * @return StatsRequest */ public function forVariants(array $variantIds) : StatsRequest; /** * get results from events table * * @param string $categoryArg * @param string $actionArg * @return StatsRequest */ public function events(string $categoryArg, string $actionArg): StatsRequest; /** * get results from pageviews table * * @return StatsRequest */ public function pageviews(): StatsRequest; /** * get results from pageviews timespent table * * @return StatsRequest */ public function timespent(): StatsRequest; /** * filter results by start date * * @param Carbon $from * @return StatsRequest */ public function from(Carbon $from): StatsRequest; /** * filter results by end date * * @param Carbon $to * @return StatsRequest */ public function to(Carbon $to): StatsRequest; /** * get results from commerce table * * @param string $step * @return StatsRequest */ public function commerce(string $step): StatsRequest; /** * return time histogram buckets instead of normal results * * @param string $interval * @return StatsRequest */ public function timeHistogram(string $interval): StatsRequest; /** * use count action on results * * @return StatsRequest */ public function count(): StatsRequest; /** * use sum action on results * * @return StatsRequest */ public function sum(): StatsRequest; /** * filter by any field * * @param string $field name of field * @param array $values array of values * @return StatsRequest */ public function filterBy(string $field, ...$values): StatsRequest; /** * group results by one or more fields * * @param array $fields * @return StatsRequest */ public function groupBy(...$fields): StatsRequest; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Contracts/RedisAwareInterface.php
Campaign/extensions/campaign-module/src/Contracts/RedisAwareInterface.php
<?php namespace Remp\CampaignModule\Contracts; interface RedisAwareInterface { public function setRedisClient(\Predis\Client $redis): self; }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Contracts/SegmentAggregator.php
Campaign/extensions/campaign-module/src/Contracts/SegmentAggregator.php
<?php namespace Remp\CampaignModule\Contracts; use Remp\CampaignModule\CampaignSegment; use Illuminate\Support\Collection; use Laravel\SerializableClosure\SerializableClosure; use Predis\Client; use Illuminate\Support\Facades\Redis; class SegmentAggregator implements SegmentContract { const TAG = 'segments'; private const SEGMENT_AGGREGATOR_REDIS_KEY = 'segment_aggregator'; /** @var SegmentContract[] */ private $contracts = []; private $errors = []; public function __construct($segmentContracts) { /** @var SegmentContract $contract */ foreach ($segmentContracts as $contract) { $this->contracts[$contract->provider()] = $contract; } } public function provider(): string { throw new SegmentException("Aggregator cannot return provider value"); } public function list(): Collection { $collection = collect([]); foreach ($this->contracts as $contract) { try { $list = $contract->list(); $collection = $collection->merge($list); } catch (\Exception $e) { $this->errors[] = sprintf("%s: %s", $contract->provider(), $e->getMessage()); } } return $collection; } public function checkUser(CampaignSegment $campaignSegment, string $userId): bool { if (!isset($this->contracts[$campaignSegment->provider])) { return false; } return $this->contracts[$campaignSegment->provider] ->checkUser($campaignSegment, $userId); } public function checkBrowser(CampaignSegment $campaignSegment, string $browserId): bool { if (!isset($this->contracts[$campaignSegment->provider])) { return false; } return $this->contracts[$campaignSegment->provider] ->checkBrowser($campaignSegment, $browserId); } public function users(CampaignSegment $campaignSegment): Collection { return $this->contracts[$campaignSegment->provider] ->users($campaignSegment); } public function cacheEnabled(CampaignSegment $campaignSegment): bool { if (!isset($this->contracts[$campaignSegment->provider])) { return false; } return $this->contracts[$campaignSegment->provider] ->cacheEnabled($campaignSegment); } /** * @throws SegmentCacheException Exception is thrown if cache is disabled for segment's provider. */ public function addUserToCache(CampaignSegment $campaignSegment, string $userId): bool { if (!$this->cacheEnabled($campaignSegment)) { throw new SegmentCacheException("Unable to add user to segment's cache. Cache is disabled for this segment provider."); } return $this->contracts[$campaignSegment->provider] ->addUserToCache($campaignSegment, $userId); } /** * @throws SegmentCacheException Exception is thrown if cache is disabled for segment's provider. */ public function removeUserFromCache(CampaignSegment $campaignSegment, string $userId): bool { if (!$this->cacheEnabled($campaignSegment)) { throw new SegmentCacheException("Unable to remove user from segment's cache. Cache is disabled for this segment provider."); } return $this->contracts[$campaignSegment->provider] ->removeUserFromCache($campaignSegment, $userId); } /** * Key returns unique key under which the data for given campaignSegment are cached. * * @return string */ public static function cacheKey(CampaignSegment $campaignSegment): string { return "{$campaignSegment->provider}|{$campaignSegment->code}"; } public function setProviderData($cache): void { foreach ($this->contracts as $provider => $contract) { if ($cache && isset($cache->$provider)) { $contract->setProviderData($cache->$provider); } } } public function getProviderData() { $cache = new \stdClass; foreach ($this->contracts as $provider => $contract) { if ($cc = $contract->getProviderData()) { $cache->$provider = $cc; } } return $cache; } public function hasErrors() { return count($this->errors) > 0; } public function getErrors() { return $this->errors; } public function refreshRedisClient(Client|\Redis $redisClient): void { foreach ($this->contracts as $contract) { if ($contract instanceof RedisAwareInterface) { $contract->setRedisClient($redisClient); } } } /** * SegmentAggregator contains Guzzle clients which have properties defined as closures. * It's not possible to serialize closures in plain PHP, but Laravel provides a workaround. * This will store a function returning segmentAggregator into the redis which can be later * used in plain PHP to bypass Laravel initialization just to get the aggregator. */ public function serializeToRedis() { $serializableClosure = new SerializableClosure(function () { return $this; }); Redis::set(self::SEGMENT_AGGREGATOR_REDIS_KEY, serialize($serializableClosure)); $dimensionMap = app(\Remp\CampaignModule\Models\Dimension\Map::class); $positionsMap = app(\Remp\CampaignModule\Models\Position\Map::class); $alignmentsMap = app(\Remp\CampaignModule\Models\Alignment\Map::class); $colorSchemesMap = app(\Remp\CampaignModule\Models\ColorScheme\Map::class); Redis::set(\Remp\CampaignModule\Models\Dimension\Map::DIMENSIONS_MAP_REDIS_KEY, $dimensionMap->dimensions()->toJson()); Redis::set(\Remp\CampaignModule\Models\Position\Map::POSITIONS_MAP_REDIS_KEY, $positionsMap->positions()->toJson()); Redis::set(\Remp\CampaignModule\Models\Alignment\Map::ALIGNMENTS_MAP_REDIS_KEY, $alignmentsMap->alignments()->toJson()); Redis::set(\Remp\CampaignModule\Models\ColorScheme\Map::COLOR_SCHEMES_MAP_REDIS_KEY, $colorSchemesMap->colorSchemes()->toJson()); } public static function unserializeFromRedis(Client|\Redis $redisClient): ?SegmentAggregator { $serializedClosure = $redisClient->get(self::SEGMENT_AGGREGATOR_REDIS_KEY); /* @var ?SegmentAggregator $segmentAggregator */ $segmentAggregator = $serializedClosure ? unserialize($serializedClosure)() : null; // set the redis to avoid duplicated connection $segmentAggregator?->refreshRedisClient($redisClient); return $segmentAggregator; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Contracts/StatsException.php
Campaign/extensions/campaign-module/src/Contracts/StatsException.php
<?php namespace Remp\CampaignModule\Contracts; class StatsException extends \Exception { }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Contracts/Remp/Segment.php
Campaign/extensions/campaign-module/src/Contracts/Remp/Segment.php
<?php namespace Remp\CampaignModule\Contracts\Remp; use Remp\CampaignModule\CampaignSegment; use Remp\CampaignModule\Contracts\SegmentContract; use Remp\CampaignModule\Contracts\SegmentException; use GuzzleHttp\Client; use GuzzleHttp\Exception\ConnectException; use Illuminate\Support\Collection; class Segment implements SegmentContract { const PROVIDER_ALIAS = 'remp_segment'; const ENDPOINT_LIST = 'segments'; const ENDPOINT_USERS_CHECK = 'segments/%s/users/check/%s'; const ENDPOINT_BROWSERS_CHECK = 'segments/%s/browsers/check/%s'; const ENDPOINT_USERS = 'segments/%s/users'; private $client; private $cache; private $eventRules; private $overridableFields; private $flags; public function __construct(Client $client) { $this->client = $client; $this->cache = new \stdClass; $this->eventRules = new \stdClass; } public function provider(): string { return static::PROVIDER_ALIAS; } /** * @return Collection * @throws SegmentException */ public function list(): Collection { try { $response = $this->client->get(self::ENDPOINT_LIST); } catch (ConnectException $e) { throw new SegmentException("Could not connect to Segment:List endpoint: {$e->getMessage()}"); } $list = json_decode($response->getBody()); $campaignSegments = []; foreach ($list as $item) { $cs = new CampaignSegment(); $cs->name = $item->name; $cs->provider = self::PROVIDER_ALIAS; $cs->code = $item->code; $cs->group = $item->group; $campaignSegments[] = $cs; } $collection = collect($campaignSegments); return $collection; } /** * @param CampaignSegment $campaignSegment * @param $userId * @return bool * @throws SegmentException */ public function checkUser(CampaignSegment $campaignSegment, string $userId): bool { return $this->check($campaignSegment, self::ENDPOINT_USERS_CHECK, $userId); } /** * @param CampaignSegment $campaignSegment * @param string $browserId * @return bool * @throws SegmentException */ public function checkBrowser(CampaignSegment $campaignSegment, string $browserId): bool { return $this->check($campaignSegment, self::ENDPOINT_BROWSERS_CHECK, $browserId); } /** * @param CampaignSegment $campaignSegment * @param string $endpoint * @param string $checkedId * * @return mixed * @throws SegmentException */ private function check(CampaignSegment $campaignSegment, $endpoint, $checkedId) { try { $params = []; $cso = $campaignSegment->getOverrides(); if ($cso) { $params['fields'] = json_encode($cso); } if ($this->cache) { $params['cache'] = json_encode($this->cache); } $response = $this->client->get(sprintf($endpoint, $campaignSegment->code, $checkedId), [ 'query' => $params, ]); } catch (ConnectException $e) { // Log::warning("Could not connect to Segment:Check endpoint: {$e->getMessage()}"); return false; } $result = json_decode($response->getBody()); if ($result->cache) { foreach (get_object_vars($result->cache) as $ruleId => $ruleCache) { $this->cache->$ruleId = $ruleCache; } } if (isset($result->event_rules)) { $this->eventRules = $result->event_rules; } if (isset($result->overridable_fields)) { $this->overridableFields = $result->overridable_fields; } if (isset($result->flags)) { $this->flags = $result->flags; } return $result->check; } /** * @param CampaignSegment $campaignSegment * @return Collection * @throws SegmentException */ public function users(CampaignSegment $campaignSegment): Collection { try { $response = $this->client->get(sprintf(self::ENDPOINT_USERS, $campaignSegment->code), [ 'query' => [ 'fields' => json_encode($campaignSegment->getOverrides()) ], ]); } catch (ConnectException $e) { throw new SegmentException("Could not connect to Segment:Users endpoint: {$e->getMessage()}"); } $list = json_decode($response->getBody()); $collection = collect($list); return $collection; } public function cacheEnabled(CampaignSegment $campaignSegment): bool { return false; } public function addUserToCache(CampaignSegment $campaignSegment, string $userId): bool { return false; } public function removeUserFromCache(CampaignSegment $campaignSegment, string $userId): bool { return false; } public function setProviderData($cache): void { $this->cache = $cache; } public function getProviderData() { $pd = new \stdClass(); if ($this->cache) { $pd->cache = $this->cache; } if ($this->eventRules) { $pd->event_rules = $this->eventRules; } if ($this->overridableFields) { $pd->overridable_fields = $this->overridableFields; } if ($this->flags) { $pd->flags = $this->flags; } return $pd; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Contracts/Remp/Stats.php
Campaign/extensions/campaign-module/src/Contracts/Remp/Stats.php
<?php namespace Remp\CampaignModule\Contracts\Remp; use GuzzleHttp\Client; use Remp\CampaignModule\Contracts\StatsContract; use Carbon\Carbon; class Stats implements StatsContract { private $client; private $timeOffset; public function __construct(Client $client, $timeOffset = null) { $this->client = $client; $this->timeOffset = $timeOffset; } public function forVariant($variantId) : StatsRequest { return (new StatsRequest($this->client, $this->timeOffset))->forVariant($variantId); } public function forVariants(array $variantIds) : StatsRequest { return (new StatsRequest($this->client, $this->timeOffset))->forVariants($variantIds); } public function events(string $categoryArg, string $actionArg): StatsRequest { return (new StatsRequest($this->client, $this->timeOffset))->events($categoryArg, $actionArg); } public function pageviews(): StatsRequest { return (new StatsRequest($this->client, $this->timeOffset))->pageviews(); } public function timespent(): StatsRequest { return (new StatsRequest($this->client, $this->timeOffset))->timespent(); } public function from(Carbon $from): StatsRequest { return (new StatsRequest($this->client, $this->timeOffset))->from($from); } public function to(Carbon $to): StatsRequest { return (new StatsRequest($this->client, $this->timeOffset))->to($to); } public function commerce(string $step): StatsRequest { return (new StatsRequest($this->client, $this->timeOffset))->commerce($step); } public function timeHistogram(string $interval): StatsRequest { return (new StatsRequest($this->client, $this->timeOffset))->timeHistogram($interval); } public function count(): StatsRequest { return (new StatsRequest($this->client, $this->timeOffset))->count(); } public function sum(): StatsRequest { return (new StatsRequest($this->client, $this->timeOffset))->sum(); } public function filterBy(string $field, ...$values): StatsRequest { return (new StatsRequest($this->client, $this->timeOffset))->filterBy($field, $values); } public function groupBy(...$fields): StatsRequest { return (new StatsRequest($this->client, $this->timeOffset))->groupBy($fields); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Contracts/Remp/StatsRequest.php
Campaign/extensions/campaign-module/src/Contracts/Remp/StatsRequest.php
<?php namespace Remp\CampaignModule\Contracts\Remp; use Carbon\Carbon; use GuzzleHttp\Client; use GuzzleHttp\RequestOptions; use Remp\CampaignModule\Contracts\StatsContract; use Remp\CampaignModule\Contracts\StatsException; use GuzzleHttp\Exception\ClientException; class StatsRequest implements StatsContract { /** @var Client guzzle http client */ private $client; /** @var string timezone offset */ private $timeOffset; /** @var string action */ private $action; /** @var string table */ private $table; /** @var array url arguments */ private $args = []; /** @var string from date object */ private $from; /** @var string to date object */ private $to; /** @var array group by fields */ private $groupBy = []; /** @var array filter by fields */ private $filterBy = []; /** @var array time histogram options */ private $timeHistogram = []; public function __construct(Client $client, $timeOffset = null) { $this->timeOffset = is_null($timeOffset) ? "0h" : $timeOffset; $this->client = $client; } public function forVariant($variantId) : StatsRequest { $this->filterBy("rtm_variant", $variantId); return $this; } public function forVariants(array $variantIds): StatsRequest { foreach ($variantIds as $variantId) { $this->forVariant($variantId); } return $this; } public function events(string $categoryArg, string $actionArg) : StatsRequest { $this->args['categories'] = $categoryArg; $this->args['actions'] = $actionArg; $this->table = "events"; return $this; } public function pageviews() : StatsRequest { $this->table = "pageviews"; return $this; } public function timespent() : StatsRequest { $this->table = "pageviews"; $this->action = "sum"; return $this; } public function from(Carbon $from): StatsRequest { $this->from = $from->setTimezone('UTC')->toRfc3339String(); return $this; } public function to(Carbon $to): StatsRequest { $this->to = $to->setTimezone('UTC')->toRfc3339String(); return $this; } public function commerce(string $step) : StatsRequest { $this->args['steps'] = $step; $this->table = "commerce"; return $this; } public function timeHistogram(string $interval, ?string $timeZone = null) : StatsRequest { $this->timeHistogram = [ 'interval' => $interval, 'offset' => $this->timeOffset ]; if ($timeZone) { $this->timeHistogram['time_zone'] = $timeZone; } return $this; } public function count() : StatsRequest { $this->action = 'count'; return $this; } public function sum() : StatsRequest { $this->action = 'sum'; return $this; } public function filterBy(string $field, ...$values) : StatsRequest { if (isset($this->filterBy[$field])) { $this->filterBy[$field]['values'] = array_merge( $this->filterBy[$field]['values'], $values ); return $this; } $this->filterBy[$field] = [ 'tag' => $field, 'values' => $values, ]; return $this; } public function groupBy(...$fields) : StatsRequest { $this->groupBy = array_merge($this->groupBy, $fields); return $this; } private function url() : string { $url = 'journal/' . $this->table; foreach ($this->args as $arg => $val) { $url .= '/' . $arg . '/' . $val; } if ($this->action) { $url .= '/' . $this->action; } return $url; } public function get() { $payload = [ 'filter_by' => array_values($this->filterBy), 'group_by' => $this->groupBy, ]; if ($this->from) { $payload['time_after'] = $this->from; } if ($this->to) { $payload['time_before'] = $this->to; } if ($this->timeHistogram) { $payload['time_histogram'] = $this->timeHistogram; } try { $result = $this->client->post($this->url(), [ RequestOptions::JSON => $payload, RequestOptions::HEADERS => [ 'Accept' => 'application/vnd.goa.error, application/vnd.count+json; type=collection', 'Content-Type' => 'application/json' ] ]); } catch (ClientException $e) { throw new StatsException('bad request', 400, $e); } $stream = $result->getBody(); try { $data = \GuzzleHttp\Utils::jsonDecode($stream->getContents()); } catch (\Exception $e) { throw new StatsException('cannot decode json response', 400, $e); } return $data; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Contracts/Crm/Segment.php
Campaign/extensions/campaign-module/src/Contracts/Crm/Segment.php
<?php namespace Remp\CampaignModule\Contracts\Crm; use Remp\CampaignModule\CampaignSegment; use Remp\CampaignModule\Contracts\RedisAwareInterface; use Remp\CampaignModule\Contracts\SegmentAggregator; use Remp\CampaignModule\Contracts\SegmentContract; use Remp\CampaignModule\Contracts\SegmentException; use GuzzleHttp\Client; use GuzzleHttp\Exception\ConnectException; use Illuminate\Support\Collection; class Segment implements SegmentContract, RedisAwareInterface { const PROVIDER_ALIAS = 'crm_segment'; const ENDPOINT_LIST = 'user-segments/list'; const ENDPOINT_CHECK = 'user-segments/check'; const ENDPOINT_USERS = 'user-segments/users'; private $client; private $providerData; private $redis; public function __construct(Client $client, \Predis\Client|\Redis $redis) { $this->client = $client; $this->providerData = new \stdClass; $this->redis = $redis; } public function setRedisClient(\Predis\Client|\Redis $redis): self { $this->redis = $redis; return $this; } public function provider(): string { return static::PROVIDER_ALIAS; } /** * @return Collection * @throws SegmentException */ public function list(): Collection { try { $response = $this->client->get(self::ENDPOINT_LIST); } catch (ConnectException $e) { throw new SegmentException("Could not connect to Segment:List endpoint: {$e->getMessage()}"); } $list = json_decode($response->getBody()); $campaignSegments = []; foreach ($list->segments as $item) { $cs = new CampaignSegment(); $cs->name = $item->name; $cs->provider = self::PROVIDER_ALIAS; $cs->code = $item->code; $cs->group = $item->group; $campaignSegments[] = $cs; } $collection = collect($campaignSegments); return $collection; } /** * @param CampaignSegment $campaignSegment * @param string $userId * @return bool */ public function checkUser(CampaignSegment $campaignSegment, string $userId): bool { return $this->redis->sismember(SegmentAggregator::cacheKey($campaignSegment), $userId); } /** * @param CampaignSegment $campaignSegment * @param string $browserId * @return bool */ public function checkBrowser(CampaignSegment $campaignSegment, string $browserId): bool { // CRM segments don't support browser tracking return false; } /** * @param CampaignSegment $campaignSegment * @return Collection * @throws SegmentException */ public function users(CampaignSegment $campaignSegment): Collection { try { $response = $this->client->get(self::ENDPOINT_USERS, [ 'query' => [ 'code' => $campaignSegment->code, ], ]); } catch (ConnectException $e) { throw new SegmentException("Could not connect to Segment:Check endpoint: {$e->getMessage()}"); } $list = json_decode($response->getBody()); $userIds = array_map(function ($item) { return $item->id; }, $list->users); return collect($userIds); } public function cacheEnabled(CampaignSegment $campaignSegment): bool { return true; } public function setProviderData($providerData): void { $this->providerData = $providerData; } public function getProviderData() { return $this->providerData; } public function addUserToCache(CampaignSegment $campaignSegment, string $userId): bool { return $this->redis->sadd( SegmentAggregator::cacheKey($campaignSegment), $this->redis instanceof \Redis ? $userId : [$userId] ) ?: false; } public function removeUserFromCache(CampaignSegment $campaignSegment, string $userId): bool { return $this->redis->srem(SegmentAggregator::cacheKey($campaignSegment), $userId) ?: false; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Console/Command.php
Campaign/extensions/campaign-module/src/Console/Command.php
<?php namespace Remp\CampaignModule\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/Campaign/extensions/campaign-module/src/Console/Commands/PostInstallCommand.php
Campaign/extensions/campaign-module/src/Console/Commands/PostInstallCommand.php
<?php namespace Remp\CampaignModule\Console\Commands; use Remp\CampaignModule\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() { return self::SUCCESS; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Console/Commands/CampaignEventsPopulatorCommand.php
Campaign/extensions/campaign-module/src/Console/Commands/CampaignEventsPopulatorCommand.php
<?php namespace Remp\CampaignModule\Console\Commands; use Exception; use GuzzleHttp\Client; use GuzzleHttp\Exception\GuzzleException; use Illuminate\Console\Command; use Illuminate\Support\Carbon; use Illuminate\Support\Facades\DB; use Illuminate\Support\Str; use Remp\CampaignModule\Campaign; class CampaignEventsPopulatorCommand extends Command { protected $signature = 'campaign:populate-events {--campaign-id= : Specific campaign ID to generate events for} {--from= : Start date (YYYY-MM-DD)} {--to= : End date (YYYY-MM-DD)} {--events-per-day=1000 : Average number of show events per day} {--dry-run : Show what would be generated without writing}'; protected $description = 'Generates realistic banner tracking events for testing campaign statistics'; private const CLICK_RATE_MIN = 2; private const CLICK_RATE_MAX = 5; private const PURCHASE_RATE_MIN = 5; private const PURCHASE_RATE_MAX = 20; private const BUSINESS_HOURS_WEIGHT = 70; private ?Client $trackerClient = null; private ?string $propertyToken = null; public function handle(): int { $campaignId = $this->option('campaign-id'); $from = $this->option('from') ? Carbon::parse($this->option('from'), 'UTC') : now('UTC')->subDays(365); $to = $this->option('to') ? Carbon::parse($this->option('to'), 'UTC') : now('UTC'); $eventsPerDay = (int)$this->option('events-per-day'); $isDryRun = $this->option('dry-run'); $this->line('Campaign Events Generator'); $this->line("Date range: <info>{$from->toDateString()}</info> to <info>{$to->toDateString()}</info>"); $this->line("Events per day: <info>~{$eventsPerDay}</info>"); if ($isDryRun) { $this->warn('DRY RUN MODE - No data will be written'); } $this->line(''); $campaigns = $campaignId ? Campaign::where('id', $campaignId)->get() : Campaign::all(); if ($campaigns->isEmpty()) { $this->error('No campaigns found!'); return 1; } $variantUuids = $campaigns->flatMap(fn($campaign) => $campaign->campaignBanners->pluck('uuid'))->toArray(); if (empty($variantUuids)) { $this->error('No campaign banner variants found!'); return 1; } $this->line('Found <info>' . count($variantUuids) . '</info> campaign banner variants'); collect($variantUuids)->each(fn($uuid) => $this->line(" - {$uuid}")); $this->line(''); if ($isDryRun) { return $this->handleDryRun($from, $to, $eventsPerDay); } if (!$this->connectToTracker()) { return 1; } [$totalShows, $totalClicks, $totalPurchases] = $this->generateEvents($variantUuids, $from, $to, $eventsPerDay); $this->line('Generation complete'); $this->line('Total shows: <info>' . number_format($totalShows) . '</info>'); $clickPercentage = $totalShows > 0 ? ' (' . round($totalClicks / $totalShows * 100, 2) . '%)' : ''; $this->line('Total clicks: <info>' . number_format($totalClicks) . '</info>' . $clickPercentage); $purchasePercentage = $totalClicks > 0 ? ' (' . round($totalPurchases / $totalClicks * 100, 2) . '% of clicks)' : ''; $this->line('Total purchases: <info>' . number_format($totalPurchases) . '</info>' . $purchasePercentage); $this->line(''); $this->refreshCaches(); $this->aggregateStats($from, $to); $this->line('Done! Visit <info>' . route('campaigns.stats', $campaignId ?: $campaigns->first()->id) . '</info> to see the results.'); return 0; } private function handleDryRun(Carbon $from, Carbon $to, int $eventsPerDay): int { $daysDiff = $from->diffInDays($to); $estimatedShows = $daysDiff * $eventsPerDay; $estimatedClicks = (int)($estimatedShows * 0.035); $estimatedPurchases = (int)($estimatedClicks * 0.015); $this->line('Estimated generation:'); $this->line(" Days: <info>{$daysDiff}</info>"); $this->line(" Shows: <info>~" . number_format($estimatedShows) . "</info>"); $this->line(" Clicks: <info>~" . number_format($estimatedClicks) . "</info>"); $this->line(" Purchases: <info>~" . number_format($estimatedPurchases) . "</info>"); return 0; } private function connectToTracker(): bool { $trackerUrl = config('services.remp.beam.tracker_addr'); if (!$trackerUrl) { $this->error('REMP_TRACKER_ADDR is not configured. Please set it in your .env file.'); return false; } $this->propertyToken = $this->getPropertyToken(); if (!$this->propertyToken) { $this->error('No property token found. Please seed Beam database first (php artisan db:seed).'); return false; } $this->trackerClient = new Client([ 'base_uri' => rtrim($trackerUrl, '/'), 'timeout' => 30, 'connect_timeout' => 5, ]); $this->line("Connected to Tracker at <info>{$trackerUrl}</info>"); $this->line("Using property token: <info>{$this->propertyToken}</info>"); return true; } private function getPropertyToken(): ?string { try { return DB::table('beam.properties') ->orderBy('id') ->value('uuid'); } catch (Exception $e) { $this->warn('Could not retrieve property token from Beam database: ' . $e->getMessage()); return null; } } private function generateEvents(array $variantUuids, Carbon $from, Carbon $to, int $eventsPerDay): array { $this->line(''); $this->line('Generating events...'); $totalShows = 0; $totalClicks = 0; $totalPurchases = 0; $currentDate = $from->copy(); $progressBar = $this->output->createProgressBar($from->diffInDays($to) + 1); while ($currentDate->lte($to)) { if ($currentDate->isWeekend()) { $baseShowsPerDay = rand((int)($eventsPerDay * 0.3), (int)($eventsPerDay * 0.8)); } else { $baseShowsPerDay = rand((int)($eventsPerDay * 0.8), (int)($eventsPerDay * 1.2)); } for ($i = 0; $i < $baseShowsPerDay; $i++) { $eventTime = $this->generateRandomTimeForDate($currentDate); $variantUuid = $variantUuids[array_rand($variantUuids)]; $userId = 'user_' . rand(1, 10000); $browserId = 'browser_' . rand(1, 5000); $this->sendShowEvent($eventTime, $variantUuid, $userId, $browserId); $totalShows++; if (rand(1, 100) > rand(self::CLICK_RATE_MIN, self::CLICK_RATE_MAX)) { continue; } $clickTime = $eventTime->copy()->addSeconds(rand(1, 30)); $this->sendClickEvent($clickTime, $variantUuid, $userId, $browserId); $totalClicks++; if (rand(1, 1000) > rand(self::PURCHASE_RATE_MIN, self::PURCHASE_RATE_MAX)) { continue; } $purchaseTime = $clickTime->copy()->addMinutes(rand(1, 60)); $this->sendPurchaseEvent($purchaseTime, $variantUuid, $userId, $browserId); $totalPurchases++; } $progressBar->advance(); $currentDate->addDay(); } $progressBar->finish(); $this->line(''); $this->line(''); return [$totalShows, $totalClicks, $totalPurchases]; } private function sendShowEvent(Carbon $time, string $variantUuid, string $userId, string $browserId): void { $this->sendTrackerEvent('/track/event', [ 'system' => [ 'property_token' => $this->propertyToken, 'time' => $time->toIso8601String(), ], 'user' => [ 'id' => $userId, 'browser_id' => $browserId, 'source' => [ 'rtm_variant' => $variantUuid, ], ], 'category' => 'banner', 'action' => 'show', 'remp_event_id' => Str::uuid()->toString(), ]); } private function sendClickEvent(Carbon $time, string $variantUuid, string $userId, string $browserId): void { $this->sendTrackerEvent('/track/event', [ 'system' => [ 'property_token' => $this->propertyToken, 'time' => $time->toIso8601String(), ], 'user' => [ 'id' => $userId, 'browser_id' => $browserId, 'source' => [ 'rtm_variant' => $variantUuid, ], ], 'category' => 'banner', 'action' => 'click', 'remp_event_id' => Str::uuid()->toString(), ]); } private function sendPurchaseEvent(Carbon $time, string $variantUuid, string $userId, string $browserId): void { $amount = (float)rand(500, 20000) / 100; $transactionId = Str::uuid()->toString(); $this->sendTrackerEvent('/track/commerce', [ 'system' => [ 'property_token' => $this->propertyToken, 'time' => $time->toIso8601String(), ], 'user' => [ 'id' => $userId, 'browser_id' => $browserId, 'source' => [ 'rtm_variant' => $variantUuid, ], ], 'step' => 'purchase', 'purchase' => [ 'transaction_id' => $transactionId, 'revenue' => [ 'amount' => $amount, 'currency' => 'EUR', ], 'product_ids' => [], ], 'remp_commerce_id' => $transactionId, ]); } private function sendTrackerEvent(string $endpoint, array $payload): void { try { $this->trackerClient->post($endpoint, [ 'json' => $payload, 'headers' => [ 'Content-Type' => 'application/json', ], ]); } catch (GuzzleException) { // Silently ignore tracking errors to avoid stopping batch generation // Most likely cause: tracker is processing events too slowly } } private function refreshCaches(): void { $this->newLine(); $this->line('Waiting for Elasticsearch to index events...'); sleep(10); $this->newLine(); $this->line('Open a new terminal on your <info>host machine</info> and run:'); $this->line(' <comment>docker compose restart beam_segments</comment>'); $this->newLine(); $this->line('Press <info>Enter</info> when done...'); fgets(STDIN); $this->line('Refreshing campaign cache...'); $this->call('campaigns:refresh-cache'); } private function aggregateStats(Carbon $from, Carbon $to): void { $this->line(''); $this->line('Aggregating stats from Elasticsearch to MySQL...'); $this->warn('This may take a few minutes for large date ranges'); $hourCurrent = $from->copy()->setTime(0, 0); $hourEnd = $to->copy()->setTime(0, 0); $aggregateBar = $this->output->createProgressBar($hourCurrent->diffInHours($hourEnd)); while ($hourCurrent->lte($hourEnd)) { $this->callSilently('campaigns:aggregate-stats', [ '--now' => $hourCurrent->toDateTimeString(), '--include-inactive' => true ]); $hourCurrent->addHour(); $aggregateBar->advance(); } $aggregateBar->finish(); $this->line(''); $this->line(''); } private function generateRandomTimeForDate(Carbon $date): Carbon { $hour = rand(0, 100) < self::BUSINESS_HOURS_WEIGHT ? rand(9, 18) : rand(0, 23); $minute = rand(0, 59); $second = rand(0, 59); return $date->copy()->setTime($hour, $minute, $second); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Console/Commands/AggregateCampaignStats.php
Campaign/extensions/campaign-module/src/Console/Commands/AggregateCampaignStats.php
<?php namespace Remp\CampaignModule\Console\Commands; use Remp\CampaignModule\Campaign; use Remp\CampaignModule\CampaignBannerPurchaseStats; use Remp\CampaignModule\CampaignBannerStats; use Remp\CampaignModule\Contracts\StatsHelper; use Illuminate\Console\Command; use Illuminate\Support\Carbon; class AggregateCampaignStats extends Command { const COMMAND = 'campaigns:aggregate-stats'; protected $signature = self::COMMAND . ' {--now=} {--include-inactive}'; protected $description = 'Reads campaign stats from journal and stores aggregated data'; private $statsHelper; public function __construct(StatsHelper $statsHelper) { parent::__construct(); $this->statsHelper = $statsHelper; } public function handle() { $now = $this->option('now') ? Carbon::parse($this->option('now')) : Carbon::now(); $timeFrom = $now->minute(0)->second(0); $timeTo = (clone $timeFrom)->addHour(); $this->line(sprintf("Fetching stats data for campaigns between <info>%s</info> to <info>%s</info>.", $timeFrom, $timeTo)); $campaigns = Campaign::all(); if (!$this->option('include-inactive')) { $campaigns = $campaigns->filter(function ($item) { return $item->active; }); } foreach ($campaigns as $campaign) { foreach ($campaign->campaignBanners as $campaignBanner) { $stats = $this->statsHelper->variantStats($campaignBanner, $timeFrom, $timeTo); /** @var CampaignBannerStats $cbs */ $cbs = CampaignBannerStats::firstOrNew([ 'campaign_banner_id' => $campaignBanner->id, 'time_from' => $timeFrom, 'time_to' => $timeTo, ]); $cbs->click_count = $stats['click_count']->count ?? 0; $cbs->show_count = $stats['show_count']->count ?? 0; $cbs->payment_count = $stats['payment_count']->count ?? 0; $cbs->purchase_count = $stats['purchase_count']->count ?? 0; $cbs->save(); $sums = []; foreach ($stats['purchase_sum'] as $sumItem) { $currency = $sumItem->tags->currency ?? null; if ($currency) { if (!array_key_exists($currency, $sums)) { $sums[$currency] = 0.0; } $sums[$currency] += (double) $sumItem->sum; } } foreach ($sums as $currency => $sum) { $purchaseStat = CampaignBannerPurchaseStats::firstOrNew([ 'campaign_banner_id' => $campaignBanner->id, 'time_from' => $timeFrom, 'time_to' => $timeTo, 'currency' => $currency ]); /** @var CampaignBannerPurchaseStats $purchaseStat */ $purchaseStat->sum = $sum; $purchaseStat->save(); } } } $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/Campaign/extensions/campaign-module/src/Console/Commands/CampaignsRefreshCache.php
Campaign/extensions/campaign-module/src/Console/Commands/CampaignsRefreshCache.php
<?php namespace Remp\CampaignModule\Console\Commands; use Remp\CampaignModule\Banner; use Remp\CampaignModule\Contracts\SegmentAggregator; use Remp\CampaignModule\Snippet; use Illuminate\Console\Command; use Remp\CampaignModule\Campaign; class CampaignsRefreshCache extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'campaigns:refresh-cache'; /** * The console command description. * * @var string */ protected $description = 'Removes cached campaigns and banners and cache the latest version immediately.'; /** * @var SegmentAggregator */ private $segmentAggregator; /** * Create a new command instance. * * @return void */ public function __construct(SegmentAggregator $segmentAggregator) { parent::__construct(); $this->segmentAggregator = $segmentAggregator; } /** * Execute the console command. * * @return mixed */ public function handle() { // serialize segment aggregator (for showtime.php) $this->segmentAggregator->serializeToRedis(); $activeCampaignIds = Campaign::refreshActiveCampaignsCache(); foreach (Campaign::whereIn('id', $activeCampaignIds)->get() as $campaign) { $this->line(sprintf('Refreshing campaign: <info>%s</info>', $campaign->name)); $campaign->cache(); }; foreach (Banner::all() as $banner) { $this->line(sprintf('Refreshing banner: <info>%s</info>', $banner->name)); $banner->cache(); } Snippet::refreshSnippetsCache(); $this->line('Campaigns cache refreshed.'); return 0; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Concerns/HasCacheableRelation.php
Campaign/extensions/campaign-module/src/Concerns/HasCacheableRelation.php
<?php namespace Remp\CampaignModule\Concerns; use Illuminate\Support\Collection; use Illuminate\Support\Str; /** * @property array $cacheableRelations */ trait HasCacheableRelation { public function hydrateFromCache(array $cachedData): void { $this->setRawAttributes($cachedData); $this->exists = true; $this->wasRecentlyCreated = false; foreach ($this->cacheableRelations as $relationName => $relatedModelClass) { $key = Str::snake($relationName); if (!isset($cachedData[$key])) { continue; } $cachedRecord = $cachedData[$key]; if (is_array($cachedRecord) && !isset($cachedRecord['id'])) { $relationRecords = new Collection(); foreach ($cachedRecord as $relationRecord) { $relatedModel = new $relatedModelClass(); if (method_exists($relatedModel, 'hydrateFromCache')) { $relatedModel->hydrateFromCache($relationRecord); } else { $relatedModel->setRawAttributes($relationRecord); $relatedModel->exists = true; $relatedModel->wasRecentlyCreated = false; } $relationRecords->push($relatedModel); } unset($this->$relationName); $this->setRelation($relationName, $relationRecords); } else { $relatedModel = new $relatedModelClass(); if (method_exists($relatedModel, 'hydrateFromCache')) { $relatedModel->hydrateFromCache($cachedRecord); } else { $relatedModel->setRawAttributes($cachedRecord); $relatedModel->exists = true; $relatedModel->wasRecentlyCreated = false; } unset($this->$relationName); $this->setRelation($relationName, $relatedModel); } } // Arrays and json are already casted in the cached data, we want to avoid double casting. It would cause // issues and throw errors. $this->casts = array_filter($this->casts, fn ($value) => $value !== 'json' && $value !== 'array'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Models/Alignment/Map.php
Campaign/extensions/campaign-module/src/Models/Alignment/Map.php
<?php namespace Remp\CampaignModule\Models\Alignment; use Illuminate\Support\Collection; class Map { const ALIGNMENTS_MAP_REDIS_KEY = 'alignments_map'; /** @var Alignment[] */ protected array $alignments = []; public function __construct(array $alignmentsConfig) { foreach ($alignmentsConfig as $key => $dc) { $this->alignments[$key] = new Alignment( $key, $dc['name'], $dc['style'] ); } } public function alignments(): Collection { return collect($this->alignments); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Models/Alignment/Alignment.php
Campaign/extensions/campaign-module/src/Models/Alignment/Alignment.php
<?php namespace Remp\CampaignModule\Models\Alignment; class Alignment { public function __construct( public string $key, public string $name, public array $style ) { } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Models/Dimension/Dimensions.php
Campaign/extensions/campaign-module/src/Models/Dimension/Dimensions.php
<?php namespace Remp\CampaignModule\Models\Dimension; class Dimensions { public function __construct( public string $key, public string $name, public $width, public $height ) { } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Models/Dimension/Map.php
Campaign/extensions/campaign-module/src/Models/Dimension/Map.php
<?php namespace Remp\CampaignModule\Models\Dimension; use Illuminate\Support\Collection; class Map { const DIMENSIONS_MAP_REDIS_KEY = 'dimensions_map'; /** @var Dimensions[] */ protected array $dimensions = []; public function __construct(array $dimensionsConfig) { foreach ($dimensionsConfig as $key => $dc) { $this->dimensions[$key] = new Dimensions( $key, $dc['name'], $dc['width'], $dc['height'] ); } } public function dimensions(): Collection { return collect($this->dimensions); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Models/SearchAspects/SnippetSearchAspect.php
Campaign/extensions/campaign-module/src/Models/SearchAspects/SnippetSearchAspect.php
<?php namespace Remp\CampaignModule\Models\SearchAspects; use Remp\CampaignModule\Snippet; use Illuminate\Support\Collection; use Spatie\Searchable\SearchAspect; class SnippetSearchAspect extends SearchAspect { public function getResults(string $term): Collection { return Snippet::query() ->where('name', 'LIKE', "%{$term}%") ->orderBy('name') ->take(config('search.maxResultCount')) ->get(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Models/SearchAspects/CampaignSearchAspect.php
Campaign/extensions/campaign-module/src/Models/SearchAspects/CampaignSearchAspect.php
<?php namespace Remp\CampaignModule\Models\SearchAspects; use Remp\CampaignModule\Campaign; use Illuminate\Support\Collection; use Spatie\Searchable\SearchAspect; class CampaignSearchAspect extends SearchAspect { public function getResults(string $term): Collection { return Campaign::query() ->where('name', 'LIKE', "%{$term}%") ->orWhere('uuid', $term) ->orWhere('public_id', $term) ->orWhereHas('banners', function ($query) use ($term) { $query->where('name', 'LIKE', "%{$term}%"); }) ->orderBy('updated_at', 'DESC') ->take(config('search.maxResultCount')) ->with('banners') ->get(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Models/SearchAspects/BannerSearchAspect.php
Campaign/extensions/campaign-module/src/Models/SearchAspects/BannerSearchAspect.php
<?php namespace Remp\CampaignModule\Models\SearchAspects; use Remp\CampaignModule\Banner; use Illuminate\Support\Collection; use Spatie\Searchable\SearchAspect; class BannerSearchAspect extends SearchAspect { public function getResults(string $term): Collection { return Banner::query() ->where('name', 'LIKE', "%{$term}%") ->orWhere('uuid', $term) ->orWhere('public_id', $term) ->orderBy('updated_at', 'DESC') ->take(config('search.maxResultCount')) ->get(); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Models/Position/Position.php
Campaign/extensions/campaign-module/src/Models/Position/Position.php
<?php namespace Remp\CampaignModule\Models\Position; class Position { public function __construct( public string $key, public string $name, public array $style ) { foreach ($this->style as $pos => $val) { $this->style[$pos] = intval($val); } } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Models/Position/Map.php
Campaign/extensions/campaign-module/src/Models/Position/Map.php
<?php namespace Remp\CampaignModule\Models\Position; use Illuminate\Support\Collection; class Map { const POSITIONS_MAP_REDIS_KEY = 'positions_map'; /** @var Position[] */ protected array $positions = []; public function __construct(array $positionsConfig) { foreach ($positionsConfig as $key => $dc) { $this->positions[$key] = new Position( $key, $dc['name'], $dc['style'] ); } } public function positions(): Collection { return collect($this->positions); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Models/ColorScheme/ColorScheme.php
Campaign/extensions/campaign-module/src/Models/ColorScheme/ColorScheme.php
<?php namespace Remp\CampaignModule\Models\ColorScheme; class ColorScheme { public function __construct( public string $key, public string $label, public string $textColor, public string $backgroundColor, public string $buttonTextColor, public string $buttonBackgroundColor, public string $closeTextColor ) { } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Models/ColorScheme/Map.php
Campaign/extensions/campaign-module/src/Models/ColorScheme/Map.php
<?php namespace Remp\CampaignModule\Models\ColorScheme; use Illuminate\Support\Collection; class Map { const COLOR_SCHEMES_MAP_REDIS_KEY = 'color_schemes_map'; /** @var ColorScheme[] */ protected array $colorSchemes = []; public function __construct(array $colorSchemesConfig) { foreach ($colorSchemesConfig as $key => $dc) { $this->colorSchemes[$key] = new ColorScheme( $key, $dc['label'], $dc['textColor'], $dc['backgroundColor'], $dc['buttonTextColor'], $dc['buttonBackgroundColor'], $dc['closeTextColor'], ); } } public function colorSchemes(): Collection { return collect($this->colorSchemes); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Models/Interval/IntervalModeEnum.php
Campaign/extensions/campaign-module/src/Models/Interval/IntervalModeEnum.php
<?php namespace Remp\CampaignModule\Models\Interval; use LogicException; enum IntervalModeEnum: string { case Auto = 'auto'; case Year = 'year'; case Month = 'month'; case Week = 'week'; case Day = 'day'; case Hour = 'hour'; case Min15 = '15min'; case Min5 = '5min'; public function toInterval(): Interval { return match ($this) { self::Year => new Interval('8760h', 'month', 12), // 365 days * 24 hours self::Month => new Interval('720h', 'day', 30), // 30 days * 24 hours self::Week => new Interval('168h', 'week', 1), // 7 days * 24 hours self::Day => new Interval('24h', 'day', 1), self::Hour => new Interval('3600s', 'hour', 1), // 60 minutes * 60 seconds self::Min15 => new Interval('900s', 'minute', 15), // 15 minutes * 60 seconds self::Min5 => new Interval('300s', 'minute', 5), // 5 minutes * 60 seconds self::Auto => throw new LogicException('Auto interval mode should be handled by calcInterval logic'), }; } public function minRangeSeconds(): int { return match ($this) { self::Year => 5 * 365 * 24 * 3600, // > 5 years self::Month => 2 * 365 * 24 * 3600, // > 2 years self::Week => 90 * 24 * 3600, // > 90 days self::Day => 3 * 24 * 3600, // > 3 days self::Hour => 8 * 3600, // > 8 hours self::Min15 => 2 * 3600, // >= 2 hours self::Min5 => 0, // No minimum (fallback) self::Auto => throw new LogicException('Auto mode has no range threshold'), }; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Models/Interval/Interval.php
Campaign/extensions/campaign-module/src/Models/Interval/Interval.php
<?php namespace Remp\CampaignModule\Models\Interval; readonly class Interval { /** * @param string $interval Elasticsearch interval format (e.g., '24h', '3600s', '900s') * @param string $timeUnit Chart.js time unit for display (e.g., 'month', 'day', 'hour', 'minute') * @param int $stepSize Chart.js step size for axis labels (e.g., 1, 12, 15) * * @see IntervalModeEnum::toInterval() For usage examples */ public function __construct( public string $interval, public string $timeUnit, public int $stepSize, ) { } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Providers/ShowtimeServiceProvider.php
Campaign/extensions/campaign-module/src/Providers/ShowtimeServiceProvider.php
<?php namespace Remp\CampaignModule\Providers; use Remp\CampaignModule\Contracts\SegmentAggregator; use Remp\CampaignModule\Http\Showtime\DeviceRulesEvaluator; use Remp\CampaignModule\Http\Showtime\LazyDeviceDetector; use Remp\CampaignModule\Http\Showtime\LazyGeoReader; use Remp\CampaignModule\Http\Showtime\Showtime; use Remp\CampaignModule\Http\Showtime\ShowtimeConfig; use Illuminate\Contracts\Support\DeferrableProvider; use Illuminate\Support\Facades\Redis; use Illuminate\Support\ServiceProvider; use Psr\Log\LoggerInterface; class ShowtimeServiceProvider extends ServiceProvider implements DeferrableProvider { /** * Register services. * * @return void */ public function register() { $this->app->bind(Showtime::class, function ($app) { return new Showtime( Redis::connection()->client(), $this->app->get(SegmentAggregator::class), $this->app->get(LazyGeoReader::class), $this->app->get(ShowtimeConfig::class), $this->app->get(DeviceRulesEvaluator::class), $this->app->get(LoggerInterface::class), ); }); $this->app->bind(DeviceRulesEvaluator::class, function ($app) { return new DeviceRulesEvaluator( Redis::connection()->client(), $this->app->get(LazyDeviceDetector::class), ); }); } public function provides() { return [Showtime::class]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Providers/BeamSegmentsServiceProvider.php
Campaign/extensions/campaign-module/src/Providers/BeamSegmentsServiceProvider.php
<?php namespace Remp\CampaignModule\Providers; use Remp\CampaignModule\Contracts\Remp\Segment; use Remp\CampaignModule\Contracts\SegmentAggregator; use Remp\CampaignModule\Contracts\SegmentContract; use GuzzleHttp\Client; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; class BeamSegmentsServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->bind(Segment::class, function (Application $app) { $client = new Client([ 'base_uri' => config('services.remp.beam.segments_addr'), 'timeout' => config('services.remp.beam.segments_timeout'), 'connect_timeout' => 1, ]); return new Segment($client); }); if (config('services.remp.beam.segments_addr')) { $this->app->tag(Segment::class, [SegmentAggregator::TAG]); } } public function provides() { return [SegmentContract::class]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Providers/StatsServiceProvider.php
Campaign/extensions/campaign-module/src/Providers/StatsServiceProvider.php
<?php namespace Remp\CampaignModule\Providers; use Remp\CampaignModule\Contracts\StatsContract; use GuzzleHttp\Client; use Remp\CampaignModule\Contracts\Remp\Stats; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; class StatsServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->bind(StatsContract::class, function (Application $app) { $client = new Client([ 'base_uri' => config('services.remp.beam.segments_addr'), 'timeout' => config('services.remp.beam.segments_timeout'), 'connect_timeout' => 1, ]); return new Stats($client); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/src/Providers/CrmSegmentServiceProvider.php
Campaign/extensions/campaign-module/src/Providers/CrmSegmentServiceProvider.php
<?php namespace Remp\CampaignModule\Providers; use Remp\CampaignModule\Contracts\Crm\Segment; use Remp\CampaignModule\Contracts\SegmentAggregator; use Remp\CampaignModule\Contracts\SegmentContract; use GuzzleHttp\Client; use Illuminate\Foundation\Application; use Illuminate\Support\ServiceProvider; class CrmSegmentServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { $this->app->bind(Segment::class, function (Application $app) { $client = new Client([ 'base_uri' => config('services.remp.crm_segment.base_url'), 'headers' => [ 'Authorization' => 'Bearer ' . $app['config']->get('services.remp.crm_segment.token'), ], ]); /** @var \Predis\Client|\Redis $redis */ $redis = $app->make('redis')->connection()->client(); return new Segment($client, $redis); }); if (config('services.remp.crm_segment.base_url')) { $this->app->tag(Segment::class, [SegmentAggregator::TAG]); } } public function provides() { return [SegmentContract::class]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/tests/TestCase.php
Campaign/extensions/campaign-module/tests/TestCase.php
<?php namespace Remp\CampaignModule\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/Campaign/extensions/campaign-module/tests/CreatesApplication.php
Campaign/extensions/campaign-module/tests/CreatesApplication.php
<?php namespace Remp\CampaignModule\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/Campaign/extensions/campaign-module/tests/Feature/ShowtimeTest.php
Campaign/extensions/campaign-module/tests/Feature/ShowtimeTest.php
<?php namespace Remp\CampaignModule\Tests\Feature; use PHPUnit\Framework\Attributes\DataProvider; use Remp\CampaignModule\Database\Seeders\CountrySeeder; use Remp\CampaignModule\Http\Showtime\DeviceRulesEvaluator; use Remp\CampaignModule\Http\Showtime\LazyDeviceDetector; use Remp\CampaignModule\Http\Showtime\ShowtimeConfig; use Remp\CampaignModule\Http\Showtime\ShowtimeTestable; use Remp\CampaignModule\Banner; use Remp\CampaignModule\Campaign; use Remp\CampaignModule\CampaignBanner; use Remp\CampaignModule\CampaignSegment; use Remp\CampaignModule\Contracts\SegmentAggregator; use Remp\CampaignModule\Http\Showtime\LazyGeoReader; use Remp\CampaignModule\Schedule; use Remp\CampaignModule\ShortMessageTemplate; use Faker\Provider\Base; use Faker\Provider\Uuid; use Illuminate\Http\Request; use Illuminate\Support\Carbon; use Mockery; use Monolog\Logger; use Predis\ClientInterface; use Remp\CampaignModule\Tests\TestCase; use Illuminate\Foundation\Testing\RefreshDatabase; class ShowtimeTest extends TestCase { use RefreshDatabase; protected ShowtimeTestable $showtime; protected $segmentAggregator; protected Campaign $campaign; protected CampaignBanner $campaignBanner; protected function setUp(): void { parent::setUp(); // Prepare showtime $redis = resolve(ClientInterface::class); $this->segmentAggregator = Mockery::mock(SegmentAggregator::class); $geoReader = Mockery::mock(LazyGeoReader::class); $geoReader->shouldReceive('countryCode')->andReturn('SK'); $logger = Mockery::mock(Logger::class); $showtimeConfig = new ShowtimeConfig(); $deviceDetectionRules = new DeviceRulesEvaluator($redis, resolve(LazyDeviceDetector::class)); $showtime = new ShowtimeTestable($redis, $this->segmentAggregator, $geoReader, $showtimeConfig, $deviceDetectionRules, $logger); $showtime->setDimensionMap(resolve(\Remp\CampaignModule\Models\Dimension\Map::class)); $showtime->setAlignmentsMap(resolve(\Remp\CampaignModule\Models\Alignment\Map::class)); $showtime->setPositionMap(resolve(\Remp\CampaignModule\Models\Position\Map::class)); $showtime->setColorSchemesMap(resolve(\Remp\CampaignModule\Models\ColorScheme\Map::class)); $this->showtime = $showtime; // Prepare banner and campaign $banner = $this->prepareBanner(); $campaign = $this->prepareCampaign(); $this->campaignBanner = $this->prepareCampaignBanners($campaign,$banner); CampaignBanner::factory()->create([ 'campaign_id' => $campaign->id, 'control_group' => 1, 'proportion' => 0, 'weight' => 2 ]); $this->campaign = $campaign; } private function scheduleCampaign() { Schedule::create([ 'start_time' => Carbon::now(), 'status' => Schedule::STATUS_EXECUTED, 'campaign_id' => $this->campaign->id, ]); } // data being sent by user's remplib private function getUserData( $url = null, $userId = null, $browserId = null, $isDesktop = true, $campaigns = null, $language = null, $campaignsSession = null ) { if (!$url) { $url = 'test.example'; } if (!$userId) { $userId = Base::randomNumber(5); } if (!$browserId) { $browserId = Uuid::uuid(); } $desktopUa = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246'; $mobileUa = 'Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36'; $d = [ 'url' => $url, 'userId' => $userId, 'browserId' => $browserId, 'campaigns' => $campaigns, 'language' => $language, 'campaignsSession' => $campaignsSession, 'userAgent' => $isDesktop ? $desktopUa : $mobileUa ]; return json_decode(json_encode($d)); } public function testPageviewAttributesFilter() { $this->scheduleCampaign(); $userData = $this->getUserData(); $activeCampaignUuids = []; $userData->pageviewAttributes = []; $bannerVariant = $this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids); $this->assertNotNull($bannerVariant); $this->campaign->update([ 'pageview_attributes' => [ [ 'name' => 'author', 'operator' => '=', 'value' => 'author_value_1' ], [ 'name' => 'category', 'operator' => '=', 'value' => 'category_value_1', ], ] ]); $activeCampaignUuids = []; $bannerVariant = $this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids); $this->assertNull($bannerVariant); $userData->pageviewAttributes = json_decode(json_encode([ 'author' => 'author_value_1', 'category' => [ 'category_value_1', 'category_value_2', ], ]), false); $activeCampaignUuids = []; $bannerVariant = $this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids); $this->assertNotNull($bannerVariant); $this->assertNotEmpty($activeCampaignUuids); $this->campaign->update([ 'pageview_attributes' => [ [ 'name' => 'author', 'operator' => '!=', 'value' => 'author_value_1' ], [ 'name' => 'category', 'operator' => '!=', 'value' => 'category_value_1', ], ] ]); $userData->pageviewAttributes = json_decode(json_encode([ 'author' => 'author_value_2', 'category' => [ 'category_value_2', 'category_value_3', ], ]), false); $activeCampaignUuids = []; $bannerVariant = $this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids); $this->assertNotNull($bannerVariant); $this->assertNotEmpty($activeCampaignUuids); $userData->pageviewAttributes = json_decode(json_encode([ 'author' => 'author_value_1', 'category' => [ 'category_value_2', 'category_value_3', ], ]), false); $activeCampaignUuids = []; $bannerVariant = $this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids); $this->assertNull($bannerVariant); $userData->pageviewAttributes = json_decode(json_encode([ 'author' => 'author_value_2', 'category' => [ 'category_value_1', 'category_value_3', ], ]), false); $activeCampaignUuids = []; $bannerVariant = $this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids); $this->assertNull($bannerVariant); } public function testStoppedCampaign() { $activeCampaignUuids = []; $data = $this->getUserData(); $this->assertNull($this->showtime->shouldDisplay($this->campaign, $data, $activeCampaignUuids)); $this->assertEmpty($activeCampaignUuids); } public function testCampaignWithoutBanners() { $data = $this->getUserData(); $activeCampaignUuids = []; $campaign = Campaign::factory()->create(); $this->assertNull($this->showtime->shouldDisplay($campaign, $data, $activeCampaignUuids)); $this->assertEmpty($activeCampaignUuids); } public function testCampaignOncePerSession() { $this->campaign->update([ 'once_per_session' => 1 ]); $this->scheduleCampaign(); $activeCampaignUuids = []; $userData = $this->getUserData(); $bannerVariant = $this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids); $this->assertNotNull($bannerVariant); $this->assertEquals($this->campaignBanner->id, $bannerVariant->id); $this->assertCount(1, $activeCampaignUuids); $this->assertEquals($this->campaign->uuid, $activeCampaignUuids[0]['uuid']); $activeCampaignUuids = []; $campaignsSession = [$this->campaign->uuid => ['seen' => 1]]; $userData = $this->getUserData(null, null, null, true, null, null, $campaignsSession); $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->assertEmpty($activeCampaignUuids); } public function testCampaignSignedInUser() { $this->campaign->update([ 'signed_in' => 1 ]); $this->scheduleCampaign(); $activeCampaignUuids = []; $userData = $this->getUserData(); $userData->userId = null; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->assertCount(0, $activeCampaignUuids); $userData->userId = 1; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); } public function testAdBlock() { $this->scheduleCampaign(); $activeCampaignUuids = []; $userData = $this->getUserData(); $this->campaign->update([ 'using_adblock' => 1 ]); $userData->usingAdblock = false; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->assertCount(0, $activeCampaignUuids); $userData->usingAdblock = true; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); $this->campaign->update([ 'using_adblock' => 0 ]); $userData->usingAdblock = true; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $userData->usingAdblock = false; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); } public function testUrlFilters() { $this->scheduleCampaign(); $activeCampaignUuids = []; $this->campaign->update([ 'url_filter' => Campaign::URL_FILTER_ONLY_AT, 'url_patterns' => ['dennikn.sk/1315683', 'minuta'] ]); $userData = $this->getUserData('dennikn.sk/1315683'); $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $userData = $this->getUserData('dennikn.sk/99999'); $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $userData = $this->getUserData('dennikn.sk/minuta/1'); $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->campaign->update([ 'url_filter' => Campaign::URL_FILTER_EXCEPT_AT, 'url_patterns' => ['minuta'] ]); $userData = $this->getUserData('dennikn.sk/99999'); $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $userData = $this->getUserData('dennikn.sk/minuta/1'); $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); } public function testTraficSourceFilters() { $this->scheduleCampaign(); $activeCampaignUuids = []; // test referer source $this->campaign->update([ 'source_filter' => Campaign::SOURCE_FILTER_REFERER_ONLY_AT, 'source_patterns' => ['facebook.com'], ]); $userData = $this->getUserData(); $userData->referer = 'http://facebook.com/abcd'; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $userData->referer = 'twitter.com/realDonaldTrump'; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->campaign->update([ 'source_filter' => Campaign::SOURCE_FILTER_REFERER_EXCEPT_AT, 'source_patterns' => ['facebook.com'] ]); $userData->referer = 'http://facebook.com/abcd'; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $userData->referer = 'twitter.com/realDonaldTrump'; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); // test session source $this->campaign->update([ 'source_filter' => Campaign::SOURCE_FILTER_SESSION_ONLY_AT, 'source_patterns' => ['facebook.com'], ]); $userData = $this->getUserData(); $userData->sessionReferer = 'http://facebook.com/abcd'; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $userData->sessionReferer = 'twitter.com/realDonaldTrump'; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->campaign->update([ 'source_filter' => Campaign::SOURCE_FILTER_SESSION_EXCEPT_AT, 'source_patterns' => ['facebook.com'] ]); $userData->sessionReferer = 'http://facebook.com/abcd'; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $userData->sessionReferer = 'twitter.com/realDonaldTrump'; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); } public function testDeviceRules() { $this->scheduleCampaign(); $activeCampaignUuids = []; $this->campaign->update([ 'devices' => [Campaign::DEVICE_MOBILE], ]); $userData = $this->getUserData(null, null, null, true); $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $userData = $this->getUserData(null, null, null, false); $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); } public static function operatingSystemsDataProvider() { return [ [ [Campaign::OPERATING_SYSTEM_ANDROID], [ // Samsung Galaxy S22 5G 'Mozilla/5.0 (Linux; Android 13; SM-S901B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Mobile Safari/537.36' => true, // iPhone 12 'Mozilla/5.0 (iPhone13,2; U; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/15E148 Safari/602.1' => false, // Edge on Win 10 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246' => false, ], ], [ [Campaign::OPERATING_SYSTEM_IOS, Campaign::OPERATING_SYSTEM_WINDOWS], [ // iPhone 12 'Mozilla/5.0 (iPhone13,2; U; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/15E148 Safari/602.1' => true, // Edge on Win 10 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246' => true, // Samsung Galaxy S22 5G 'Mozilla/5.0 (Linux; Android 13; SM-S901B) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Mobile Safari/537.36' => false, ], ], [ [Campaign::OPERATING_SYSTEM_MAC], [ // Safari on Mac OSX 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9' => true, // Edge on Win 10 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246' => false, // iPhone 12 'Mozilla/5.0 (iPhone13,2; U; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/15E148 Safari/602.1' => false, ], ], [ [], [ // Safari on Mac OSX 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9' => true, // Edge on Win 10 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246' => true, // iPhone 12 'Mozilla/5.0 (iPhone13,2; U; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) Version/10.0 Mobile/15E148 Safari/602.1' => true, ], ], [ [], [ null => true, ], ], [ [Campaign::OPERATING_SYSTEM_MAC], [ null => false, ], ], ]; } #[DataProvider('operatingSystemsDataProvider')] public function testOperatingSystemRules(array $operatingSystems, array $userAgents) { $this->scheduleCampaign(); $activeCampaignUuids = []; $this->campaign->update([ 'operating_systems' => empty($operatingSystems) ? null : $operatingSystems, ]); $userData = $this->getUserData(null, null, null, true); foreach ($userAgents as $userAgent => $shouldMatch) { if ($userAgent === null) { unset($userData->userAgent); } else { $userData->userAgent = $userAgent; } if ($shouldMatch) { $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); } else { $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); } } } public function testCountryRules() { $this->seed(CountrySeeder::class); $this->scheduleCampaign(); $activeCampaignUuids = []; // Mocked geo reader returns SK country code by default for all IPs $request = Mockery::mock(Request::class); $request->shouldReceive('ip')->andReturn('1.1.1.1'); $this->showtime->setRequest($request); $this->campaign->countries()->sync([ 'SK' => ['blacklisted' => 0] ]); $userData = $this->getUserData(); $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->campaign->countries()->sync([ 'SK' => ['blacklisted' => 1] ]); $this->campaign->load(['countries', 'countriesBlacklist', 'countriesWhitelist']); $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); } public function testLanguageRules() { $this->scheduleCampaign(); $activeCampaignUuids = []; $this->campaign->update(['languages' => ["cs", "sk"]]); $userData = $this->getUserData(language: 'sk-SK'); $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $userData = $this->getUserData(language: 'en-US'); $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); } public function testSegmentRules() { $this->scheduleCampaign(); $activeCampaignUuids = []; $campaignSegment = CampaignSegment::create([ 'campaign_id' => $this->campaign->id, 'code' => 'test_segment', 'provider' => 'remp_segment', 'inclusive' => 1 ]); $userData = $this->getUserData(); $this->segmentAggregator->shouldReceive('cacheEnabled')->andReturn(false, false); $this->segmentAggregator->shouldReceive('checkUser')->andReturn(false, true); $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->assertCount(0, $activeCampaignUuids); $this->showtime->flushLocalCache(); $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); $campaignSegment->update(['inclusive' => 0]); $this->campaign->load('segments'); $userData->userId = null; $this->segmentAggregator->shouldReceive('checkBrowser')->andReturn(false, true); $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->showtime->flushLocalCache(); $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); } public function testPageviewRules() { $this->scheduleCampaign(); // Always rule $this->campaign->update([ 'pageview_rules' => [ 'display_banner' => 'always' ] ]); $campaignsData = [$this->campaign->uuid => ['count' => 1, 'seen' => 0]]; $userData = $this->getUserData(null, null, null, true, $campaignsData); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); // Every rule $this->campaign->update([ 'pageview_rules' => [ 'display_banner' => 'every', 'display_banner_every' => 3 ] ]); $campaignsData = [$this->campaign->uuid => ['count' => 1, 'seen' => 0]]; $userData = $this->getUserData(null, null, null, true, $campaignsData); $activeCampaignUuids = []; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); // campaign should still be counted as active $campaignsData = [$this->campaign->uuid => ['count' => 3, 'seen' => 0]]; $userData = $this->getUserData(null, null, null, true, $campaignsData); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); // campaign should still be counted as active } public function testPageviewRulesAfterClickRule() { $this->scheduleCampaign(); $campaignsDataClicked = [ $this->campaign->uuid => [ 'count' => 1, 'seen' => 0, 'clickedAt' => Carbon::now()->subHours(2)->getTimestamp(), ], ]; $campaignsSessionDataClicked = [ $this->campaign->uuid => [ 'clickedAt' => Carbon::now()->subHours(2)->getTimestamp(), ], ]; $userDataClicked = $this->getUserData(campaigns: $campaignsDataClicked, campaignsSession: $campaignsSessionDataClicked); $campaignsDataNoClick = [$this->campaign->uuid => ['count' => 1, 'seen' => 0]]; $userDataNoClick = $this->getUserData(campaigns: $campaignsDataNoClick); // ALWAYS rule $this->campaign->update([ 'pageview_rules' => [ 'after_banner_clicked_display' => 'always', ] ]); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userDataClicked, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userDataNoClick, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); // NEVER rule $this->campaign->update([ 'pageview_rules' => [ 'after_banner_clicked_display' => 'never', ] ]); $activeCampaignUuids = []; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userDataClicked, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userDataNoClick, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); // NOT IN SESSION rule $this->campaign->update([ 'pageview_rules' => [ 'after_banner_clicked_display' => 'never_in_session', ] ]); $activeCampaignUuids = []; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userDataClicked, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userDataNoClick, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); // CLOSE FOR HOURS rule - should display $this->campaign->update([ 'pageview_rules' => [ 'after_banner_clicked_display' => 'close_for_hours', 'after_clicked_hours' => 1 ] ]); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userDataClicked, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userDataNoClick, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); // CLOSE FOR HOURS rule - should not display $this->campaign->update([ 'pageview_rules' => [ 'after_banner_clicked_display' => 'close_for_hours', 'after_clicked_hours' => 3 ] ]); $activeCampaignUuids = []; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userDataClicked, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); } public function testPageviewRulesAfterCloseRule() { $this->scheduleCampaign(); $campaignsDataClosed = [ $this->campaign->uuid => [ 'count' => 1, 'seen' => 0, 'closedAt' => Carbon::now()->subHours(2)->getTimestamp(), ], ]; $campaignsSessionDataClosed = [ $this->campaign->uuid => [ 'closedAt' => Carbon::now()->subHours(2)->getTimestamp(), ], ]; $userDataClosed = $this->getUserData(campaigns: $campaignsDataClosed, campaignsSession: $campaignsSessionDataClosed); $campaignsDataNoClose = [$this->campaign->uuid => ['count' => 1, 'seen' => 0]]; $userDataNoClose = $this->getUserData(campaigns: $campaignsDataNoClose); // ALWAYS rule $this->campaign->update([ 'pageview_rules' => [ 'after_banner_closed_display' => 'always', ] ]); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userDataClosed, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userDataNoClose, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); // NEVER rule $this->campaign->update([ 'pageview_rules' => [ 'after_banner_closed_display' => 'never', ] ]); $activeCampaignUuids = []; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userDataClosed, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userDataNoClose, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); // NOT IN SESSION rule $this->campaign->update([ 'pageview_rules' => [ 'after_banner_closed_display' => 'never_in_session', ] ]); $activeCampaignUuids = []; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userDataClosed, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userDataNoClose, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); // CLOSE FOR HOURS rule - should display $this->campaign->update([ 'pageview_rules' => [ 'after_banner_closed_display' => 'close_for_hours', 'after_closed_hours' => 1 ] ]); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userDataClosed, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userDataNoClose, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); // CLOSE FOR HOURS rule - should not display $this->campaign->update([ 'pageview_rules' => [ 'after_banner_closed_display' => 'close_for_hours', 'after_closed_hours' => 3 ] ]); $activeCampaignUuids = []; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userDataClosed, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); } public function testSeenCountRules() { $this->scheduleCampaign(); $this->campaign->update([ 'pageview_rules' => [ 'display_times' => 1, 'display_n_times' => 2 ] ]); $campaignsData = [$this->campaign->uuid => ['seen' => 1, 'count' => 0]]; $userData = $this->getUserData(null, null, null, true, $campaignsData); $activeCampaignUuids = []; $this->assertNotNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); $campaignsData = [$this->campaign->uuid => ['seen' => 2, 'count' => 0]]; $userData = $this->getUserData(null, null, null, true, $campaignsData); $activeCampaignUuids = []; $this->assertNull($this->showtime->shouldDisplay($this->campaign, $userData, $activeCampaignUuids)); $this->assertCount(1, $activeCampaignUuids); } public function testPrioritizeCampaignBannerOnDifferentPosition(): void { $campaign1 = $this->prepareCampaign(); $campaign2 = $this->prepareCampaign(); $campaigns = [$campaign1->id => $campaign1, $campaign2->id => $campaign2]; $campaignBanner1 = $this->prepareCampaignBanners($campaign1, $this->prepareBanner(Banner::POSITION_TOP_LEFT, Banner::DISPLAY_TYPE_INLINE, '#test-id')); $campaignBanner2 = $this->prepareCampaignBanners($campaign2, $this->prepareBanner(Banner::POSITION_BOTTOM_LEFT, Banner::DISPLAY_TYPE_OVERLAY)); $campaignBanners = [$campaignBanner1, $campaignBanner2];
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
true
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/tests/Unit/ScheduleTest.php
Campaign/extensions/campaign-module/tests/Unit/ScheduleTest.php
<?php namespace Remp\CampaignModule\Tests\Unit; use Remp\CampaignModule\Schedule; use Carbon\Carbon; use Remp\CampaignModule\Tests\TestCase; class ScheduleTest extends TestCase { public function testWaitingSchedule() { $schedule = new Schedule([ 'start_time' => new Carbon('2017-11-01 01:23:45'), 'end_time' => new Carbon('2017-11-02 01:23:45'), ]); Carbon::setTestNow(new Carbon('2017-11-01 00:00:00')); $this->assertFalse($schedule->isRunning()); $this->assertTrue($schedule->isRunnable()); $this->assertTrue($schedule->isEditable()); } public function testForcedRunnningBeforeScheduledStarted() { $schedule = new Schedule([ 'start_time' => new Carbon('2017-11-01 01:23:45'), 'end_time' => new Carbon('2017-11-02 01:23:45'), ]); $schedule->status = Schedule::STATUS_EXECUTED; Carbon::setTestNow(new Carbon('2017-11-01 00:00:00')); $this->assertTrue($schedule->isRunning()); $this->assertFalse($schedule->isRunnable()); $this->assertFalse($schedule->isEditable()); } public function testForcedRunnningAfterScheduledEnd() { $schedule = new Schedule([ 'start_time' => new Carbon('2017-11-01 01:23:45'), 'end_time' => new Carbon('2017-11-02 01:23:45'), ]); $schedule->status = Schedule::STATUS_EXECUTED; Carbon::setTestNow(new Carbon('2017-11-03 00:00:00')); $this->assertFalse($schedule->isRunning()); $this->assertFalse($schedule->isRunnable()); $this->assertFalse($schedule->isEditable()); } public function testForcedStoppedBeforeScheduledStarted() { $schedule = new Schedule([ 'start_time' => new Carbon('2017-11-01 01:23:45'), 'end_time' => new Carbon('2017-11-02 01:23:45'), ]); $schedule->status = Schedule::STATUS_STOPPED; Carbon::setTestNow(new Carbon('2017-11-01 00:00:00')); $this->assertFalse($schedule->isRunning()); $this->assertFalse($schedule->isRunnable()); $this->assertFalse($schedule->isEditable()); } public function testNativeRunning() { $schedule = new Schedule([ 'start_time' => new Carbon('2017-11-01 01:23:45'), 'end_time' => new Carbon('2017-11-02 01:23:45'), ]); Carbon::setTestNow(new Carbon('2017-11-02 00:00:00')); $this->assertTrue($schedule->isRunning()); $this->assertFalse($schedule->isRunnable()); $this->assertFalse($schedule->isEditable()); } public function testNativeFinished() { $schedule = new Schedule([ 'start_time' => new Carbon('2017-11-01 01:23:45'), 'end_time' => new Carbon('2017-11-02 01:23:45'), ]); Carbon::setTestNow(new Carbon('2017-11-03 00:00:00')); $this->assertFalse($schedule->isRunning()); $this->assertFalse($schedule->isRunnable()); $this->assertFalse($schedule->isEditable()); } public function testPausedRunnable() { $schedule = new Schedule([ 'start_time' => new Carbon('2017-11-01 01:23:45'), 'end_time' => new Carbon('2017-11-02 01:23:45'), ]); $schedule->status = Schedule::STATUS_PAUSED; Carbon::setTestNow(new Carbon('2017-11-02 00:00:00')); $this->assertFalse($schedule->isRunning()); $this->assertTrue($schedule->isRunnable()); $this->assertFalse($schedule->isEditable()); } public function testPausedNotRunnable() { $schedule = new Schedule([ 'start_time' => new Carbon('2017-11-01 01:23:45'), 'end_time' => new Carbon('2017-11-02 01:23:45'), ]); $schedule->status = Schedule::STATUS_PAUSED; Carbon::setTestNow(new Carbon('2017-11-03 00:00:00')); $this->assertFalse($schedule->isRunning()); $this->assertFalse($schedule->isRunnable()); $this->assertFalse($schedule->isEditable()); } public function testNoEndTime() { $schedule = new Schedule([ 'start_time' => new Carbon('2017-11-01 01:23:45'), ]); Carbon::setTestNow(new Carbon('2017-11-01 00:00:00')); $this->assertFalse($schedule->isRunning()); $this->assertTrue($schedule->isRunnable()); $this->assertTrue($schedule->isEditable()); Carbon::setTestNow(new Carbon('2017-11-03 00:00:00')); $this->assertTrue($schedule->isRunning()); $this->assertFalse($schedule->isRunnable()); $this->assertFalse($schedule->isEditable()); $schedule->status = Schedule::STATUS_STOPPED; $this->assertFalse($schedule->isRunning()); $this->assertFalse($schedule->isRunnable()); $this->assertFalse($schedule->isEditable()); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/tests/Unit/BannerTest.php
Campaign/extensions/campaign-module/tests/Unit/BannerTest.php
<?php namespace Remp\CampaignModule\Tests\Unit; use Illuminate\Foundation\Testing\RefreshDatabase; use PHPUnit\Framework\Attributes\DataProvider; use Remp\CampaignModule\Banner; use Remp\CampaignModule\HtmlTemplate; use Remp\CampaignModule\BarTemplate; use Remp\CampaignModule\Snippet; use Remp\CampaignModule\Tests\TestCase; class BannerTest extends TestCase { use RefreshDatabase; public static function snippetExtractionProvider(): array { return [ 'noSnippets' => [ 'bannerJs' => 'console.log("Hello World");', 'snippetsData' => [], 'expectedSnippets' => [], ], 'singleSnippet' => [ 'bannerJs' => 'var foo = "{{ foobar }}";', 'snippetsData' => [ ['name' => 'foobar', 'value' => 'test value'], ], 'expectedSnippets' => ['foobar'], ], 'multipleSnippets' => [ 'bannerJs' => 'var foo = "{{ foobar }}"; var baz = "{{ bazBar }}";', 'snippetsData' => [ ['name' => 'foobar', 'value' => 'test value'], ['name' => 'bazBar', 'value' => 'another value'], ], 'expectedSnippets' => ['foobar', 'bazBar'], ], 'nestedSnippets' => [ 'bannerJs' => 'var foo = "{{ foobar }}";', 'snippetsData' => [ ['name' => 'foobar', 'value' => 'test value with {{ bazBar }}'], ['name' => 'bazBar', 'value' => 'nested value'], ], 'expectedSnippets' => ['foobar', 'bazBar'], ], 'deeplyNestedSnippets' => [ 'bannerJs' => 'var foo = "{{ level1 }}";', 'snippetsData' => [ ['name' => 'level1', 'value' => 'Level 1 with {{ level2 }}'], ['name' => 'level2', 'value' => 'Level 2 with {{ level3 }}'], ['name' => 'level3', 'value' => 'Level 3 final value'], ], 'expectedSnippets' => ['level1', 'level2', 'level3'], ], 'circularReference' => [ 'bannerJs' => 'var foo = "{{ snippet1 }}";', 'snippetsData' => [ ['name' => 'snippet1', 'value' => 'Value with {{ snippet2 }}'], ['name' => 'snippet2', 'value' => 'Value with {{ snippet1 }}'], ], 'expectedSnippets' => ['snippet1', 'snippet2'], ], 'duplicateReferences' => [ 'bannerJs' => 'var foo = "{{ foobar }}"; var bar = "{{ bazBar }}";', 'snippetsData' => [ ['name' => 'foobar', 'value' => 'Value with {{ shared }}'], ['name' => 'bazBar', 'value' => 'Another value with {{ shared }}'], ['name' => 'shared', 'value' => 'Shared value'], ], 'expectedSnippets' => ['foobar', 'bazBar', 'shared'], ], 'nonExistentSnippet' => [ 'bannerJs' => 'var foo = "{{ existingSnippet }}"; var bar = "{{ nonExistent }}";', 'snippetsData' => [ ['name' => 'existingSnippet', 'value' => 'test value'], ], 'expectedSnippets' => ['existingSnippet', 'nonExistent'], ], 'variousWhitespace' => [ 'bannerJs' => 'var foo = "{{foobar}}"; var bar = "{{ bazBar }}"; var baz = "{{ qux}}";', 'snippetsData' => [ ['name' => 'foobar', 'value' => 'test value'], ['name' => 'bazBar', 'value' => 'another value'], ['name' => 'qux', 'value' => 'third value'], ], 'expectedSnippets' => ['foobar', 'bazBar', 'qux'], ], ]; } #[DataProvider('snippetExtractionProvider')] public function testGetUsedSnippetCodes(string $bannerJs, array $snippetsData, array $expectedSnippets) { $banner = Banner::factory()->create(['js' => $bannerJs]); foreach ($snippetsData as $snippetData) { Snippet::create($snippetData); } $snippets = $banner->getUsedSnippetCodes(); $this->assertCount(count($expectedSnippets), $snippets); foreach ($expectedSnippets as $expectedSnippet) { $this->assertContains($expectedSnippet, $snippets); } } public function testGetUsedSnippetCodesFromHtmlTemplateText() { $banner = Banner::factory()->create([ 'template' => Banner::TEMPLATE_HTML, 'js' => null, ]); // Delete factory's default template HtmlTemplate::where('banner_id', $banner->id)->delete(); $template = new HtmlTemplate([ 'text' => '<p>Hello {{ userName }}, welcome to {{ siteName }}!</p>', 'css' => '.banner { color: red; }', 'dimensions' => 'medium', 'text_align' => 'left', 'text_color' => '#000', 'font_size' => '14', 'background_color' => '#fff', ]); $template->banner_id = $banner->id; $template->save(); Snippet::create(['name' => 'userName', 'value' => 'John']); Snippet::create(['name' => 'siteName', 'value' => 'Example.com']); $snippets = $banner->fresh()->getUsedSnippetCodes(); $this->assertCount(2, $snippets); $this->assertContains('userName', $snippets); $this->assertContains('siteName', $snippets); } public function testGetUsedSnippetCodesFromHtmlTemplateCss() { $banner = Banner::factory()->create([ 'template' => Banner::TEMPLATE_HTML, 'js' => null, ]); // Delete factory's default template HtmlTemplate::where('banner_id', $banner->id)->delete(); $template = new HtmlTemplate([ 'text' => '<p>Simple text</p>', 'css' => '.banner { background-image: url("{{ backgroundUrl }}"); color: {{ textColor }}; }', 'dimensions' => 'medium', 'text_align' => 'left', 'text_color' => '#000', 'font_size' => '14', 'background_color' => '#fff', ]); $template->banner_id = $banner->id; $template->save(); Snippet::create(['name' => 'backgroundUrl', 'value' => 'https://example.com/bg.jpg']); Snippet::create(['name' => 'textColor', 'value' => '#333']); $snippets = $banner->fresh()->getUsedSnippetCodes(); $this->assertCount(2, $snippets); $this->assertContains('backgroundUrl', $snippets); $this->assertContains('textColor', $snippets); } public function testGetUsedSnippetCodesFromBarTemplate() { $banner = Banner::factory()->create([ 'template' => Banner::TEMPLATE_BAR, 'js' => null, ]); $template = new BarTemplate([ 'main_text' => 'Check out {{ offerName }}!', 'button_text' => '{{ ctaText }}', ]); $template->banner_id = $banner->id; $template->save(); Snippet::create(['name' => 'offerName', 'value' => 'Special Offer']); Snippet::create(['name' => 'ctaText', 'value' => 'Click Here']); $snippets = $banner->fresh()->getUsedSnippetCodes(); $this->assertCount(2, $snippets); $this->assertContains('offerName', $snippets); $this->assertContains('ctaText', $snippets); } public function testGetUsedSnippetCodesFromTemplateWithNestedSnippets() { $banner = Banner::factory()->create([ 'template' => Banner::TEMPLATE_HTML, 'js' => null, ]); // Delete factory's default template HtmlTemplate::where('banner_id', $banner->id)->delete(); $template = new HtmlTemplate([ 'text' => '<p>{{ greeting }}</p>', 'css' => '.banner { color: {{ primaryColor }}; }', 'dimensions' => 'medium', 'text_align' => 'left', 'text_color' => '#000', 'font_size' => '14', 'background_color' => '#fff', ]); $template->banner_id = $banner->id; $template->save(); Snippet::create(['name' => 'greeting', 'value' => 'Hello {{ userName }}']); Snippet::create(['name' => 'userName', 'value' => 'John']); Snippet::create(['name' => 'primaryColor', 'value' => '{{ brandColor }}']); Snippet::create(['name' => 'brandColor', 'value' => '#ff0000']); $snippets = $banner->fresh()->getUsedSnippetCodes(); $this->assertCount(4, $snippets); $this->assertContains('greeting', $snippets); $this->assertContains('userName', $snippets); $this->assertContains('primaryColor', $snippets); $this->assertContains('brandColor', $snippets); } public function testGetUsedSnippetCodesFromBothJsAndTemplate() { $banner = Banner::factory()->create([ 'template' => Banner::TEMPLATE_HTML, 'js' => 'console.log("{{ jsSnippet }}");', ]); // Delete factory's default template HtmlTemplate::where('banner_id', $banner->id)->delete(); $template = new HtmlTemplate([ 'text' => '<p>{{ textSnippet }}</p>', 'css' => '.banner { color: {{ cssSnippet }}; }', 'dimensions' => 'medium', 'text_align' => 'left', 'text_color' => '#000', 'font_size' => '14', 'background_color' => '#fff', ]); $template->banner_id = $banner->id; $template->save(); Snippet::create(['name' => 'jsSnippet', 'value' => 'JS Value']); Snippet::create(['name' => 'textSnippet', 'value' => 'Text Value']); Snippet::create(['name' => 'cssSnippet', 'value' => 'red']); $snippets = $banner->fresh()->getUsedSnippetCodes(); $this->assertCount(3, $snippets); $this->assertContains('jsSnippet', $snippets); $this->assertContains('textSnippet', $snippets); $this->assertContains('cssSnippet', $snippets); } public function testGetUsedSnippetCodesFromJsIncludes() { $banner = Banner::factory()->create([ 'template' => Banner::TEMPLATE_HTML, 'js_includes' => ['{{ cdn_domain }}/main.js', '{{ cdn_domain }}{{ theme }}.js'], ]); Snippet::create(['name' => 'cdn_domain', 'value' => '{{ protocol}}://remp.press']); Snippet::create(['name' => 'theme', 'value' => 'dark']); Snippet::create(['name' => 'protocol', 'value' => 'https']); $snippets = $banner->fresh()->getUsedSnippetCodes(); $this->assertCount(3, $snippets); $this->assertContains('cdn_domain', $snippets); $this->assertContains('theme', $snippets); $this->assertContains('protocol', $snippets); } public function testGetUsedSnippetCodesFromCssIncludes() { $banner = Banner::factory()->create([ 'template' => Banner::TEMPLATE_HTML, 'css_includes' => ['{{ cdn_domain }}/main.css', '{{ cdn_domain }}{{ theme }}.css'], ]); Snippet::create(['name' => 'cdn_domain', 'value' => '{{ protocol}}://remp.press']); Snippet::create(['name' => 'theme', 'value' => 'dark']); Snippet::create(['name' => 'protocol', 'value' => 'https']); $snippets = $banner->fresh()->getUsedSnippetCodes(); $this->assertCount(3, $snippets); $this->assertContains('cdn_domain', $snippets); $this->assertContains('theme', $snippets); $this->assertContains('protocol', $snippets); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/tests/Unit/Rules/ContainsHtmlLinkTest.php
Campaign/extensions/campaign-module/tests/Unit/Rules/ContainsHtmlLinkTest.php
<?php namespace Remp\CampaignModule\Tests\Unit\Rules; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Remp\CampaignModule\Rules\ContainsHtmlLink; class ContainsHtmlLinkTest extends TestCase { private ContainsHtmlLink $rule; protected function setUp(): void { parent::setUp(); $this->rule = new ContainsHtmlLink(); } private function validate(mixed $value): ?string { $errorMessage = null; $fail = function (string $message) use (&$errorMessage) { $errorMessage = $message; }; $this->rule->validate('terms', $value, $fail); return $errorMessage; } #[DataProvider('validHtmlLinkProvider')] public function testPassesWithValidHtmlLinks(string $value): void { $this->assertNull($this->validate($value)); } public static function validHtmlLinkProvider(): array { return [ 'simpleLink' => ['<a href="#">Link</a>'], 'linkWithUrl' => ['<a href="https://example.com">Terms</a>'], 'linkWithTextAround' => ['By clicking Subscribe, you agree with <a href="#">Terms</a>'], 'linkWithAttributes' => ['<a href="#" target="_blank" class="link">Terms</a>'], 'multipleLinks' => ['<a href="#">One</a> and <a href="#">Two</a>'], 'linkWithWhitespace' => ['< a href="#">Link</ a>'], ]; } #[DataProvider('invalidHtmlLinkProvider')] public function testFailsWithInvalidHtmlLinks(mixed $value): void { $error = $this->validate($value); $this->assertNotNull($error); $this->assertStringContainsString('HTML link', $error); } public static function invalidHtmlLinkProvider(): array { return [ 'emptyString' => [''], 'nullValue' => [null], 'textWithoutLink' => ['By clicking Subscribe, you agree with Terms'], 'htmlWithoutLink' => ['<em>Subscribe</em> to agree with <strong>Terms</strong>'], 'incompleteAnchorTag' => ['<a href="#">Terms'], 'justOpeningTag' => ['<a>'], ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/routes/web.php
Campaign/extensions/campaign-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\CampaignModule\Http\Controllers\AuthController; use Remp\CampaignModule\Http\Controllers\CampaignController; use Remp\CampaignModule\Http\Controllers\CollectionController; use Remp\CampaignModule\Http\Controllers\DashboardController; use Remp\CampaignModule\Http\Controllers\BannerController; use Remp\CampaignModule\Http\Controllers\ScheduleController; use Remp\CampaignModule\Http\Controllers\SnippetController; use Remp\CampaignModule\Http\Controllers\CampaignsComparisonController; use Remp\CampaignModule\Http\Controllers\StatsController; use Remp\CampaignModule\Http\Controllers\SearchController; use Remp\CampaignModule\Http\Middleware\CollectionQueryString; use Remp\LaravelSso\Http\Middleware\VerifyJwtToken; Route::get('/error', [AuthController::class, 'error'])->name('sso.error'); Route::get('campaigns/showtime', [CampaignController::class, 'showtime'])->name('campaigns.showtime'); Route::middleware([VerifyJwtToken::class, CollectionQueryString::class])->group(function () { Route::get('/', [DashboardController::class, 'index']); Route::get('dashboard', [DashboardController::class, 'index'])->name('dashboard'); Route::get('banners/json', [BannerController::class, 'json'])->name('banners.json'); Route::get('snippets/json', [SnippetController::class, 'json'])->name('snippets.json'); Route::get('banners/{sourceBanner}/copy', [BannerController::class, 'copy'])->name('banners.copy'); Route::get('campaigns/json', [CampaignController::class, 'json'])->name('campaigns.json'); Route::get('campaigns/{sourceCampaign}/copy', [CampaignController::class, 'copy'])->name('campaigns.copy'); Route::get('campaigns/{campaign}/schedule/json', [ScheduleController::class, 'json'])->name('campaign.schedule.json'); Route::get('schedule/json', [ScheduleController::class, 'json'])->name('schedule.json'); Route::post('schedule/{schedule}/start', [ScheduleController::class, 'start'])->name('schedule.start'); Route::post('schedule/{schedule}/pause', [ScheduleController::class, 'pause'])->name('schedule.pause'); Route::post('schedule/{schedule}/stop', [ScheduleController::class, 'stop'])->name('schedule.stop'); Route::get('comparison', [CampaignsComparisonController::class, 'index'])->name('comparison.index'); Route::get('comparison/json', [CampaignsComparisonController::class, 'json'])->name('comparison.json'); Route::put('comparison/{campaign}', [CampaignsComparisonController::class, 'add'])->name('comparison.add'); Route::post('comparison/addAll', [CampaignsComparisonController::class, 'addAll'])->name('comparison.addAll'); Route::post('comparison/removeAll', [CampaignsComparisonController::class, 'removeAll'])->name('comparison.removeAll'); Route::delete('comparison/{campaign}/', [CampaignsComparisonController::class, 'remove'])->name('comparison.remove'); Route::post('campaigns/validate', [CampaignController::class, 'validateForm'])->name('campaigns.validateForm'); Route::post('banners/validate', [BannerController::class, 'validateForm'])->name('banners.validateForm'); Route::post('snippets/validate/{snippet?}', [SnippetController::class, 'validateForm'])->name('snippets.validateForm'); Route::get('campaigns/{campaign}/stats', [CampaignController::class, 'stats'])->name('campaigns.stats'); Route::post('campaigns/{campaign}/stats/data', [StatsController::class, 'getStats'])->name('campaigns.stats.data'); Route::get('auth/logout', [AuthController::class, 'logout'])->name('auth.logout'); Route::resource('banners', BannerController::class); Route::resource('campaigns', CampaignController::class); Route::resource('collections', CollectionController::class)->only(['index', 'create', 'edit', 'update', 'store']); Route::resource('snippets', SnippetController::class); Route::resource('schedule', ScheduleController::class)->only(['index', 'create', 'edit', 'update', 'destroy']); Route::resource('campaigns.schedule', ScheduleController::class); Route::get('collections/json', [CollectionController::class, 'json'])->name('collections.json'); Route::get('collections/{collection}/destroy', [CollectionController::class, 'destroy'])->name('collections.destroy'); 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/Campaign/extensions/campaign-module/routes/channels.php
Campaign/extensions/campaign-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/Campaign/extensions/campaign-module/routes/api.php
Campaign/extensions/campaign-module/routes/api.php
<?php use Remp\CampaignModule\Http\Controllers\SegmentCacheController; use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | 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! | */ use Remp\CampaignModule\Http\Controllers\CampaignController; use Remp\CampaignModule\Http\Controllers\BannerController; use Remp\CampaignModule\Http\Controllers\ScheduleController; Route::middleware('auth:api')->group(function() { Route::prefix('schedule')->group(function() { Route::post('{schedule}/start', [ScheduleController::class, 'start'])->name('schedule.start'); Route::post('{schedule}/pause', [ScheduleController::class, 'pause'])->name('schedule.pause'); Route::post('{schedule}/stop', [ScheduleController::class, 'stop'])->name('schedule.stop'); }); Route::post('banners/{banner}/one-time-display', [BannerController::class, 'oneTimeDisplay'])->name('banners.one_time_display'); Route::apiResource('campaigns', CampaignController::class)->names('campaigns'); Route::apiResource('banners', BannerController::class)->names('banners'); Route::apiResource('schedule', ScheduleController::class)->names('schedule'); Route::post('campaigns/toggle-active/{campaign}', [CampaignController::class, 'toggleActive'])->name('campaigns.toggle_active'); Route::post( 'segment-cache/provider/{segment_provider}/code/{segment_code}/add-user', [SegmentCacheController::class, 'addUserToCache'] ); Route::post( 'segment-cache/provider/{segment_provider}/code/{segment_code}/remove-user', [SegmentCacheController::class, 'removeUserFromCache'] ); });
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/routes/console.php
Campaign/extensions/campaign-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/Campaign/extensions/campaign-module/public/showtime.php
Campaign/extensions/campaign-module/public/showtime.php
<?php use Monolog\Formatter\NormalizerFormatter; use Remp\CampaignModule\Banner; use Remp\CampaignModule\Campaign; use Remp\CampaignModule\CampaignBanner; use Remp\CampaignModule\Contracts\SegmentAggregator; use Remp\CampaignModule\Http\Showtime\DeviceRulesEvaluator; use Remp\CampaignModule\Http\Showtime\LazyDeviceDetector; use Remp\CampaignModule\Http\Showtime\LazyGeoReader; use Remp\CampaignModule\Http\Showtime\Showtime; use Remp\CampaignModule\Http\Showtime\ShowtimeResponse; use Remp\CampaignModule\Http\Showtime\ShowtimeConfig; use Illuminate\Support\HtmlString; use Illuminate\Support\Str; use Monolog\Logger; require_once __DIR__ . '/../../../vendor/autoload.php'; /** * asset overrides Laravel's helper function to prevent usage of Laravel's app() * * @param $path * @param null $secure * @return string */ function asset($path, $secure = null) { return ((isSecure() ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/' . trim($path, '/')); } function isSecure(): bool { if ((isset($_SERVER['HTTPS']) && (($_SERVER['HTTPS'] === 'on') || ($_SERVER['HTTPS'] === '1'))) || (isset($_SERVER['HTTPS']) && $_SERVER['SERVER_PORT'] === 443)) { return true; } if ((!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') || (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] === 'on')) { return true; } return false; } /** * public_path overrides Laravel's helper function to prevent usage of Laravel's app() * * @param string $path * @return string */ function public_path($path = '') { return __DIR__ .'/../../'.($path ? DIRECTORY_SEPARATOR.ltrim($path, DIRECTORY_SEPARATOR) : $path); } /** * Note: mix overrides Laravel's helper function to prevent usage of Laravel's app() * Get the path to a versioned Mix file. * * @param string $path * @param string $manifestDirectory * @return HtmlString|string * * @throws \Exception */ function mix($path, $manifestDirectory = '') { static $manifests = []; if (! Str::startsWith($path, '/')) { $path = "/{$path}"; } if ($manifestDirectory && ! Str::startsWith($manifestDirectory, '/')) { $manifestDirectory = "/{$manifestDirectory}"; } if (file_exists(public_path($manifestDirectory.'/hot'))) { $url = rtrim(file_get_contents(public_path($manifestDirectory.'/hot'))); if (Str::startsWith($url, ['http://', 'https://'])) { return new HtmlString(Str::after($url, ':').$path); } return new HtmlString("//localhost:8080{$path}"); } $manifestPath = public_path($manifestDirectory.'/mix-manifest.json'); if (! isset($manifests[$manifestPath])) { if (! file_exists($manifestPath)) { throw new Exception('The Mix manifest does not exist.'); } $manifests[$manifestPath] = json_decode(file_get_contents($manifestPath), true); } $manifest = $manifests[$manifestPath]; if (! isset($manifest[$path])) { $exception = new Exception("Unable to locate Mix file: {$path}."); if (! app('config')->get('app.debug')) { report($exception); return $path; } else { throw $exception; } } return new HtmlString($manifestDirectory.$manifest[$path]); } class PlainPhpShowtimeResponse implements ShowtimeResponse { public function jsonResponse($response, $statusCode = 400) { header('Content-Type: application/json'); http_response_code($statusCode); echo json_encode($response); exit; } /** * @param string $callback jsonp callback name * @param array $response response to be json-encoded and returned * @param int $statusCode http status code to be returned */ private function jsonpResponse($callback, $response, $statusCode = 200) { http_response_code($statusCode); $params = json_encode($response); echo "{$callback}({$params})"; exit; } public function error($callback, int $statusCode, array $errors) { $this->jsonpResponse($callback, [ 'success' => false, 'errors' => $errors, ], $statusCode); } public function success(string $callback, $data, $activeCampaigns, $providerData, $suppressedBanners, array $evaluationMessages = []) { $responseData = [ 'success' => true, 'errors' => [], 'data' => empty($data) ? [] : $data, 'activeCampaignIds' => array_column($activeCampaigns, 'uuid'), 'activeCampaigns' => $activeCampaigns, 'providerData' => $providerData, 'suppressedBanners' => $suppressedBanners, ]; if ($evaluationMessages) { $responseData['evaluationMessages'] = $evaluationMessages; } $this->jsonpResponse($callback, $responseData); } public function renderCampaign(CampaignBanner $variant, Campaign $campaign, array $alignments, array $dimensions, array $positions, array $colorSchemes, array $snippets, mixed $userData): string { return $this->renderInternal( banner: $variant->banner, alignments: $alignments, dimensions: $dimensions, positions: $positions, colorSchemes: $colorSchemes, snippets: $snippets, variantUuid: $variant->uuid, campaignUuid: $campaign->uuid, isControlGroup: (int) $variant->control_group, variantPublicId: $variant->public_id, campaignPublicId: $campaign->public_id, userData: $userData ); } public function renderBanner(Banner $banner, array $alignments, array $dimensions, array $positions, array $colorSchemes, array $snippets): string { return $this->renderInternal( banner: $banner, alignments: $alignments, dimensions: $dimensions, positions: $positions, colorSchemes: $colorSchemes, snippets: $snippets, ); } private function renderInternal( ?Banner $banner, $alignments, $dimensions, $positions, $colorSchemes, $snippets, $variantUuid = null, $campaignUuid = null, $isControlGroup = 0, $variantPublicId = null, $campaignPublicId = null, $userData = null ) { $alignmentsJson = json_encode($alignments); $dimensionsJson = json_encode($dimensions); $positionsJson = json_encode($positions); $colorSchemesJson = json_encode($colorSchemes); $snippetsJson = json_encode($snippets); $userDataJson = json_encode($userData); $bannerJs = asset(mix('/js/banner.js', '/assets/lib')); if (!$banner ){ $js = 'var bannerUuid = null;'; } else { $js = " var bannerUuid = '{$banner->uuid}'; var bannerPublicId = '{$banner->public_id}'; var bannerId = 'b-' + bannerUuid; var bannerJsonData = {$banner->toJson()}; "; } if ($variantUuid) { $js .= "var variantUuid = '{$variantUuid}';\n"; $js .= "var variantPublicId = '{$variantPublicId}';\n"; } else { $js .= "var variantUuid = null;\n"; $js .= "var variantPublicId = null;\n"; } if ($campaignUuid) { $js .= "var campaignUuid = '{$campaignUuid}';\n"; $js .= "var campaignPublicId = '{$campaignPublicId}';\n"; } else { $js .= "var campaignUuid = null;\n"; $js .= "var campaignPublicId = null;\n"; } $js .= <<<JS var isControlGroup = {$isControlGroup} var scripts = []; if (typeof window.remplib.banner === 'undefined') { scripts.push("{$bannerJs}"); } var styles = []; var waiting = scripts.length + styles.length; var run = function() { if (waiting) { return; } var banner = {}; var alignments = JSON.parse('{$alignmentsJson}'); var dimensions = JSON.parse('{$dimensionsJson}'); var positions = JSON.parse('{$positionsJson}'); var colorSchemes = JSON.parse('{$colorSchemesJson}'); var snippets = {$snippetsJson}; var userData = JSON.parse('{$userDataJson}'); if (!isControlGroup) { var campaignUserData = null; if (userData && userData.campaigns && userData.campaigns[campaignPublicId]) { campaignUserData = userData.campaigns[campaignPublicId]; } banner = remplib.banner.parseUserData(remplib.banner.fromModel(bannerJsonData), campaignUserData); } banner.show = false; banner.alignmentOptions = alignments; banner.dimensionOptions = dimensions; banner.positionOptions = positions; banner.colorSchemes = colorSchemes; banner.snippets = snippets; banner.campaignUuid = campaignUuid; banner.campaignPublicId = campaignPublicId; banner.variantUuid = variantUuid; banner.variantPublicId = variantPublicId; if (bannerUuid) { banner.uuid = bannerUuid; banner.publicId = bannerPublicId; } if (typeof remplib.campaign.bannerUrlParams !== "undefined") { banner.urlParams = remplib.campaign.bannerUrlParams; } if (isControlGroup) { banner.displayDelay = 0; banner.displayType = 'none'; } else { var d = document.createElement('div'); d.id = bannerId; var bp = document.createElement('banner-preview'); d.appendChild(bp); var target = null; if (banner.displayType === 'inline') { target = document.querySelector(banner.targetSelector); if (target === null) { console.warn("REMP: unable to display banner, selector not matched: " + banner.targetSelector); return; } } else { target = document.getElementsByTagName('body')[0]; } target.appendChild(d); remplib.banner.bindPreview('#' + bannerId, banner); } setTimeout(function() { var event = { rtm_source: "remp_campaign", rtm_medium: banner.displayType, rtm_content: banner.uuid }; if (banner.campaignUuid) { event.rtm_campaign = banner.campaignUuid; } if (banner.variantUuid) { event.rtm_variant = banner.variantUuid; } if (!banner.manualEventsTracking) { remplib.tracker.trackEvent("banner", "show", null, null, event); } banner.show = true; if (banner.closeTimeout) { setTimeout(function() { banner.show = false; }, banner.closeTimeout); } if (banner.campaignUuid && banner.variantUuid) { remplib.campaign.handleBannerDisplayed(banner.campaignUuid, banner.uuid, banner.variantUuid, banner.campaignPublicId, banner.publicId, banner.variantPublicId); } if (typeof resolve !== "undefined") { resolve(true); } }, banner.displayDelay); } run(); for (var i=0; i<scripts.length; i++) { remplib.loadScript(scripts[i], function() { waiting -= 1; run(); }); } for (i=0; i<styles.length; i++) { remplib.loadStyle(styles[i], function() { waiting -= 1; run(); }); } JS; return $js; } } $dotenv = \Dotenv\Dotenv::createImmutable(__DIR__ . '/../../../'); $dotenv->load(); $logger = new Logger('showtime'); $streamHandler = new \Monolog\Handler\StreamHandler(__DIR__ . '/../../../storage/logs/laravel.log'); $formatter = $streamHandler->getFormatter(); if ($formatter instanceof NormalizerFormatter) { $formatter->setDateFormat('Y-m-d H:i:s'); $streamHandler->setFormatter($formatter); } $logger->pushHandler($streamHandler); try { $sentryDSN = env('SENTRY_DSN'); if (!empty($sentryDSN)) { $sentryClientOptions = [ 'dsn' => $sentryDSN, 'environment' => env('APP_ENV', 'production'), 'send_default_pii' => true, // enabled to see same details as with laravel sentry ]; $sampleRate = env('SENTRY_SHOWTIME_SAMPLERATE', 1); if (is_numeric($sampleRate)) { $sentryClientOptions['sample_rate'] = (float) $sampleRate; } else { $logger->warning("invalid SENTRY_SHOWTIME_SAMPLERATE='{$sampleRate}' configured, defaulting to '1'."); } $client = \Sentry\ClientBuilder::create($sentryClientOptions)->getClient(); $handler = new \Sentry\Monolog\Handler(new \Sentry\State\Hub($client)); $logger->pushHandler($handler); } } catch (\Exception $e) { $logger->warning('unable to register sentry notifier: ' . $e->getMessage()); } $showtimeResponse = new PlainPhpShowtimeResponse(); $data = filter_input(INPUT_GET, 'data'); $callback = filter_input(INPUT_GET, 'callback'); $showtimeConfig = new ShowtimeConfig(); if (!empty($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { $showtimeConfig->setAcceptLanguage($_SERVER['HTTP_ACCEPT_LANGUAGE']); } $showtimeConfig->setDebugKey(env('CAMPAIGN_DEBUG_KEY')); if ($data === null || $callback === null) { $showtimeResponse->jsonResponse(['errors' => ['invalid request, data or callback params missing']]); return; } header('Content-Type: application/javascript'); try { // dependencies initialization if (env('REDIS_CLIENT', 'predis') === 'phpredis') { $redis = new \Redis(); if (env('REDIS_PERSISTENT', false)) { $redis->pconnect(env('REDIS_HOST'), (int) env('REDIS_PORT', 6379), 5, 'showtime-'.env('REDIS_DEFAULT_DATABASE')); } else { $redis->connect(env('REDIS_HOST'), (int) env('REDIS_PORT', 6379), 5); } if ($pwd = env('REDIS_PASSWORD')) { $redis->auth($pwd); } $redis->setOption(\Redis::OPT_PREFIX, env('REDIS_PREFIX', '')); $redis->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_NONE); $redis->select((int) env('REDIS_DEFAULT_DATABASE', 0)); } else { $redis = new \Predis\Client([ 'scheme' => 'tcp', 'host' => env('REDIS_HOST'), 'port' => env('REDIS_PORT') ?: 6379, 'password' => env('REDIS_PASSWORD') ?: null, 'database' => env('REDIS_DEFAULT_DATABASE') ?: 0, 'persistent' => env('REDIS_PERSISTENT', false), ], [ 'prefix' => env('REDIS_PREFIX') ?: '', ]); } $segmentAggregator = SegmentAggregator::unserializeFromRedis($redis); if (!$segmentAggregator) { $logger->error("unable to get cached segment aggregator, have you run 'campaigns:refresh-cache' command?"); $showtimeResponse->error($callback, 500, ['Internal error, application might not have been correctly initialized.']); } if (extension_loaded('apcu')) { $cache = new \MatthiasMullie\Scrapbook\Psr16\SimpleCache( new \MatthiasMullie\Scrapbook\Adapters\Apc(), ); } elseif (env('REDIS_CLIENT', 'predis') === 'phpredis') { $cache = new \MatthiasMullie\Scrapbook\Psr16\SimpleCache( new \MatthiasMullie\Scrapbook\Adapters\Redis($redis), ); } else { $cache = new \Kodus\PredisSimpleCache\PredisSimpleCache($redis, 60*60*24); } $deviceDetector = new LazyDeviceDetector($cache); $deviceRulesEvaluator = new DeviceRulesEvaluator($redis, $deviceDetector); if (file_exists(env('MAXMIND_DATABASE'))) { $maxmindDbPath = env('MAXMIND_DATABASE'); } else { $maxmindDbPath = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . env('MAXMIND_DATABASE'); } $geoReader = new LazyGeoReader($maxmindDbPath); $prioritizeBannerOnSamePosition = filter_var( env('PRIORITIZE_BANNERS_ON_SAME_POSITION', false), FILTER_VALIDATE_BOOLEAN, ['options' => ['default' => false]] ); $showtimeConfig->setPrioritizeBannerOnSamePosition($prioritizeBannerOnSamePosition); $showtimeConfig->setOneTimeBannerEnabled(env('ONE_TIME_BANNER_ENABLED', true)); $showtime = new Showtime($redis, $segmentAggregator, $geoReader, $showtimeConfig, $deviceRulesEvaluator, $logger); $showtime->showtime($data, $callback, $showtimeResponse); } catch (\Exception $exception) { $logger->error($exception); $showtimeResponse->error($callback, 500, ['Internal error, unable to display campaigns.']); }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/config/search.php
Campaign/extensions/campaign-module/config/search.php
<?php return [ /* |-------------------------------------------------------------------------- | Maximum number of returned search results |-------------------------------------------------------------------------- | | This value represents limit for number of returned search results. | IMPORTANT: this number affects each searchable entity separately | e.g.: when maxResultCount is being set to 5 and you search | model_1 and model_2 you can get max 10 results */ 'maxResultCount' => env('SEARCH_MAX_RESULT_COUNT', 5), ];
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/config/services.php
Campaign/extensions/campaign-module/config/services.php
<?php return [ /* |-------------------------------------------------------------------------- | Third Party Services |-------------------------------------------------------------------------- | | This file is for storing the credentials for third party services such | as Mailgun, Postmark, AWS and more. This file provides the de facto | location for this type of information, allowing packages to have | a conventional file to locate the various service credentials. | */ 'maxmind' => [ 'database' => base_path(env('MAXMIND_DATABASE')), ], 'crm_segment' => [ 'base_url' => env('CRM_SEGMENT_API_ADDR'), 'token' => env('CRM_SEGMENT_API_TOKEN'), ], 'beam' => [ 'web_addr' => env('REMP_BEAM_ADDR'), 'segments_addr' => env('REMP_SEGMENTS_ADDR'), 'segments_timeout' => (int) env('REMP_SEGMENTS_TIMEOUT') ?: 5, ], 'mailer' => [ 'web_addr' => env('REMP_MAILER_ADDR'), ], 'sso' => [ 'web_addr' => env('REMP_SSO_ADDR'), 'api_token' => env('REMP_SSO_API_TOKEN'), ], 'linked' => [ 'beam' => [ 'url' => env('REMP_BEAM_ADDR'), 'icon' => 'album', ], 'campaign' => [ 'url' => '/', '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/Campaign/extensions/campaign-module/config/newsletter_banners.php
Campaign/extensions/campaign-module/config/newsletter_banners.php
<?php return [ /* |-------------------------------------------------------------------------- | API ENDPOINT |-------------------------------------------------------------------------- | | Endpoint for newsletter subscriptions */ 'endpoint' => env('NEWSLETTER_BANNER_API_ENDPOINT', ''), /* |-------------------------------------------------------------------------- | USE XHR |-------------------------------------------------------------------------- | | API ENDPOINT can be requested by XHR (1) or regular form submission (2) */ 'use_xhr' => !!env('NEWSLETTER_BANNER_USE_XHR', true), /* |-------------------------------------------------------------------------- | REQUEST BODY |-------------------------------------------------------------------------- | | Available options: x-www-form-urlencoded (default), form-data, json */ 'request_body' => env('NEWSLETTER_BANNER_REQUEST_BODY', 'json'), /* |-------------------------------------------------------------------------- | REQUEST HEADERS |-------------------------------------------------------------------------- | | Add any HTTP header you need (JSON) | Not applicable if used with form-data `request_body`, use `params_extra` instead. */ 'request_headers' => json_decode(env('NEWSLETTER_BANNER_REQUEST_HEADERS', /** @lang JSON */ ' { } '), null, 512, JSON_THROW_ON_ERROR), /* |-------------------------------------------------------------------------- | PARAMS TRANSPOSITION |-------------------------------------------------------------------------- | | Specify params transposition according to your endpoint implementation */ 'params_transposition' => json_decode(env('NEWSLETTER_BANNER_PARAMS_TRANSPOSITION', /** @lang JSON */ ' { "email": "email", "newsletter_id": "newsletter_id", "source": "source" } '), null, 512, JSON_THROW_ON_ERROR), /* |-------------------------------------------------------------------------- | EXTRA PARAMS |-------------------------------------------------------------------------- | | These params will be added to every request. | Do not use any names from NEWSLETTER_BANNER_PARAMS_TRANSPOSITION to avoid conflicts | */ 'params_extra' => env('NEWSLETTER_BANNER_PARAMS_EXTRA') ? explode(",", env('NEWSLETTER_BANNER_PARAMS_EXTRA')) : [], ];
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/config/banners.php
Campaign/extensions/campaign-module/config/banners.php
<?php $config = [ 'dimensions' => [ 'landscape' => [ 'name' => 'Landscape (728x90)', 'width' => '728px', 'height' => '90px', ], 'medium_rectangle' => [ 'name' => 'Medium rectangle (300x250)', 'width' => '300px', 'height' => '250px', ], 'bar' => [ 'name' => 'Bar (728x50)', 'width' => '728px', 'height' => '50px', ], 'notification' => [ 'name' => 'Notification (300x50)', 'width' => '300px', 'height' => '50px', ], 'square' => [ 'name' => 'Square (300x300)', 'width' => '300px', 'height' => '300px', ], 'full_width' => [ 'name' => 'Full width', 'width' => '100%', 'height' => 'auto', ], 'hidden' => [ 'name' => 'Hidden (tracking) / JS-based', 'width' => '0px', 'height' => '0px', ] ], 'positions' => [ 'top_left' => [ 'name' => 'Top-Left', 'style' => [ 'top' => '0px', 'left' => '0px', ], ], 'top_right' => [ 'name' => 'Top-Right', 'style' => [ 'top' => '0px', 'right' => '0px', ], ], 'bottom_left' => [ 'name' => 'Bottom-Left', 'style' => [ 'bottom' => '0px', 'left' => '0px', ], ], 'bottom_right' => [ 'name' => 'Bottom-Right', 'style' => [ 'bottom' => '0px', 'right' => '0px', ], ], ], 'alignments' => [ 'left' => [ 'name' => 'Left', 'style' => [ 'text-align' => 'left', 'justify-content' => 'flex-start', ], ], 'center' => [ 'name' => 'Center', 'style' => [ 'text-align' => 'center', 'justify-content' => 'center', ], ], 'right' => [ 'name' => 'Right', 'style' => [ 'text-align' => 'right', 'justify-content' => 'flex-end', ], ], ], 'color_schemes' => [ 'grey' => [ 'label' => 'Grey', 'textColor' => '#000000', 'backgroundColor' => '#ededed', 'buttonTextColor' => '#ffffff', 'buttonBackgroundColor' => '#000000', 'closeTextColor' => '#000000' ], 'yellow' => [ 'label' => 'Yellow', 'textColor' => '#000000', 'backgroundColor' => '#f7bc1e', 'buttonTextColor' => '#ffffff', 'buttonBackgroundColor' => '#000000', 'closeTextColor' => '#000000' ], 'blue' => [ 'label' => 'Blue', 'textColor' => '#ffffff', 'backgroundColor' => '#008099', 'buttonTextColor' => '#ffffff', 'buttonBackgroundColor' => '#000000', 'closeTextColor' => '#000000' ], 'dark_blue' => [ 'label' => 'Dark Blue', 'textColor' => '#ffffff', 'backgroundColor' => '#1f3f82', 'buttonTextColor' => '#000000', 'buttonBackgroundColor' => '#ffffff', 'closeTextColor' => '#000000' ], 'green' => [ 'label' => 'Green', 'textColor' => '#ffffff', 'backgroundColor' => '#008577', 'buttonTextColor' => '#ffffff', 'buttonBackgroundColor' => '#000000', 'closeTextColor' => '#000000' ], 'violet' => [ 'label' => 'Violet', 'textColor' => '#ffffff', 'backgroundColor' => '#9c27b0', 'buttonTextColor' => '#ffffff', 'buttonBackgroundColor' => '#000000', 'closeTextColor' => '#000000' ], 'red' => [ 'label' => 'Red', 'textColor' => '#ffffff', 'backgroundColor' => '#E3165B', 'buttonTextColor' => '#ffffff', 'buttonBackgroundColor' => '#000000', 'closeTextColor' => '#000000' ], 'dark_red' => [ 'label' => 'Dark red', 'textColor' => '#ffffff', 'backgroundColor' => '#b00c28', 'buttonTextColor' => '#ffffff', 'buttonBackgroundColor' => '#000000', 'closeTextColor' => '#000000' ], 'black' => [ 'label' => 'Black', 'textColor' => '#ffffff', 'backgroundColor' => '#262325', 'buttonTextColor' => '#000000', 'buttonBackgroundColor' => '#ffffff', 'closeTextColor' => '#000000' ], ], 'prioritize_banners_on_same_position' => env('PRIORITIZE_BANNERS_ON_SAME_POSITION', false), 'one_time_banner_enabled' => env('ONE_TIME_BANNER_ENABLED', true), 'campaign_debug_key' => env('CAMPAIGN_DEBUG_KEY'), ]; if (file_exists(__DIR__ . '/banners.local.php')) { $config = array_replace_recursive($config, require __DIR__ . '/banners.local.php'); } return $config;
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/config/system.php
Campaign/extensions/campaign-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), ];
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/factories/CampaignBannerFactory.php
Campaign/extensions/campaign-module/database/factories/CampaignBannerFactory.php
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Remp\CampaignModule\CampaignBanner; /** @extends Factory<CampaignBanner> */ class CampaignBannerFactory extends Factory { protected $model = CampaignBanner::class; public function definition() { return [ 'control_group' => 0, 'proportion' => 100, 'weight' => 1, 'uuid' => $this->faker->uuid, ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/factories/CampaignFactory.php
Campaign/extensions/campaign-module/database/factories/CampaignFactory.php
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Remp\CampaignModule\Campaign; /** @extends Factory<Campaign> */ class CampaignFactory extends Factory { protected $model = Campaign::class; public function definition() { return [ 'name' => $this->faker->words(2, true), 'uuid' => $this->faker->uuid, 'pageview_rules' => [], 'devices' => [], 'signed_in' => $this->faker->boolean(), 'once_per_session' => $this->faker->boolean(), 'url_filter' => 'everywhere', 'source_filter' => 'everywhere', ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/factories/MediumRectangleTemplateFactory.php
Campaign/extensions/campaign-module/database/factories/MediumRectangleTemplateFactory.php
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Remp\CampaignModule\MediumRectangleTemplate; /** @extends Factory<MediumRectangleTemplate> */ class MediumRectangleTemplateFactory extends Factory { protected $model = MediumRectangleTemplate::class; public function definition() { return [ 'header_text' => $this->faker->words(1, true), 'main_text' => $this->faker->words(3, true), 'button_text' => $this->faker->words(1, true), 'color_scheme' => 'grey', ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/factories/BannerFactory.php
Campaign/extensions/campaign-module/database/factories/BannerFactory.php
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Remp\CampaignModule\Banner; use Remp\CampaignModule\HtmlTemplate; /** @extends Factory<Banner> */ class BannerFactory extends Factory { protected $model = Banner::class; public function definition() { return [ 'uuid' => $this->faker->uuid, 'name' => $this->faker->word, 'transition' => $this->faker->randomElement(['fade', 'bounce', 'shake', 'none']), 'target_url' => $this->faker->url, 'position' => $this->faker->randomElement(['top_left', 'top_right', 'bottom_left', 'bottom_right']), 'display_delay' => $this->faker->numberBetween(1000, 5000), 'display_type' => 'overlay', 'offset_horizontal' => 0, 'offset_vertical' => 0, 'closeable' => $this->faker->boolean, 'target_selector' => '#test', 'manual_events_tracking' => 0, 'template' => Banner::TEMPLATE_HTML, ]; } public function configure() { return $this->afterCreating(function (Banner $banner) { // Every banner must have a template - create default if none exists if ($banner->template === Banner::TEMPLATE_HTML) { $existingTemplate = HtmlTemplate::where('banner_id', $banner->id)->first(); if (!$existingTemplate) { $template = new HtmlTemplate([ 'text' => 'Default text', 'css' => '', 'dimensions' => 'medium', 'text_align' => 'left', 'text_color' => '#000000', 'font_size' => '14', 'background_color' => '#ffffff', ]); $template->banner_id = $banner->id; $template->save(); // Clear relationship cache so fresh() will load the new template $banner->unsetRelation('htmlTemplate'); } } }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/factories/BarTemplateFactory.php
Campaign/extensions/campaign-module/database/factories/BarTemplateFactory.php
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Remp\CampaignModule\BarTemplate; /** @extends Factory<BarTemplate> */ class BarTemplateFactory extends Factory { protected $model = BarTemplate::class; public function definition() { return [ 'main_text' => $this->faker->words(3, true), 'button_text' => $this->faker->words(1, true), 'color_scheme' => 'grey', ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/factories/CampaignSegmentFactory.php
Campaign/extensions/campaign-module/database/factories/CampaignSegmentFactory.php
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Remp\CampaignModule\CampaignSegment; /** @extends Factory<CampaignSegment> */ class CampaignSegmentFactory extends Factory { protected $model = CampaignSegment::class; public function definition() { return [ 'campaign_id' => 1, 'code' => 'demo_segment', 'provider' => 'remp_segment', ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/factories/ShortMessageTemplateFactory.php
Campaign/extensions/campaign-module/database/factories/ShortMessageTemplateFactory.php
<?php namespace Database\Factories; use Illuminate\Database\Eloquent\Factories\Factory; use Remp\CampaignModule\ShortMessageTemplate; /** @extends Factory<ShortMessageTemplate> */ class ShortMessageTemplateFactory extends Factory { protected $model = ShortMessageTemplate::class; public function definition() { return [ 'text' => $this->faker->words(3, true), 'color_scheme' => 'grey', ]; } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2024_12_03_095025_banner_use_color_scheme_and_drop_color_columns.php
Campaign/extensions/campaign-module/database/migrations/2024_12_03_095025_banner_use_color_scheme_and_drop_color_columns.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class BannerUseColorSchemeAndDropColorColumns extends Migration { public function up() { // add color scheme column to all banner templates which support it Schema::table('bar_templates', function (Blueprint $table) { $table->string('color_scheme')->nullable()->after('button_text'); }); Schema::table('collapsible_bar_templates', function (Blueprint $table) { $table->string('color_scheme')->nullable()->after('initial_state'); }); Schema::table('medium_rectangle_templates', function (Blueprint $table) { $table->string('color_scheme')->nullable()->after('button_text'); }); Schema::table('newsletter_rectangle_templates', function (Blueprint $table) { $table->string('color_scheme')->nullable()->after('height'); }); Schema::table('overlay_rectangle_templates', function (Blueprint $table) { $table->string('color_scheme')->nullable()->after('image_link'); }); Schema::table('short_message_templates', function (Blueprint $table) { $table->string('color_scheme')->nullable()->after('text'); }); // set color schemes based on background color // (we used to derive the banner's color scheme by referencing the background color) $colorSchemes = config('banners.color_schemes'); // added old background colors from before change (fix banner color contrasts: remp/remp#1379) $colorSchemes['blue']['oldBackgroundColor'] = '#00b7db'; $colorSchemes['green']['oldBackgroundColor'] = '#009688'; $colorSchemes['red']['oldBackgroundColor'] = '#e91e63'; foreach ($colorSchemes as $code => $colorScheme) { $backgroundColors = array_filter([ $colorScheme['backgroundColor'], $colorScheme['oldBackgroundColor'] ?? null, ]); DB::table('bar_templates') ->whereIn('background_color', $backgroundColors) ->update([ 'color_scheme' => $code ]); DB::table('collapsible_bar_templates') ->whereIn('background_color', $backgroundColors) ->update([ 'color_scheme' => $code ]); DB::table('medium_rectangle_templates') ->whereIn('background_color', $backgroundColors) ->update([ 'color_scheme' => $code ]); DB::table('newsletter_rectangle_templates') ->whereIn('background_color', $backgroundColors) ->update([ 'color_scheme' => $code ]); DB::table('overlay_rectangle_templates') ->whereIn('background_color', $backgroundColors) ->update([ 'color_scheme' => $code ]); DB::table('short_message_templates') ->whereIn('background_color', $backgroundColors) ->update([ 'color_scheme' => $code ]); } // drop old color columns and set `color_scheme` column to not nullable Schema::table('bar_templates', function (Blueprint $table) { $table->dropColumn('background_color'); $table->dropColumn('text_color'); $table->dropColumn('button_background_color'); $table->dropColumn('button_text_color'); $table->string('color_scheme')->nullable(false)->change(); }); Schema::table('collapsible_bar_templates', function (Blueprint $table) { $table->dropColumn('background_color'); $table->dropColumn('text_color'); $table->dropColumn('button_background_color'); $table->dropColumn('button_text_color'); $table->string('color_scheme')->nullable(false)->change(); }); Schema::table('medium_rectangle_templates', function (Blueprint $table) { $table->dropColumn('background_color'); $table->dropColumn('text_color'); $table->dropColumn('button_background_color'); $table->dropColumn('button_text_color'); $table->string('color_scheme')->nullable(false)->change(); }); Schema::table('newsletter_rectangle_templates', function (Blueprint $table) { $table->dropColumn('background_color'); $table->dropColumn('text_color'); $table->dropColumn('button_background_color'); $table->dropColumn('button_text_color'); $table->string('color_scheme')->nullable(false)->change(); }); Schema::table('overlay_rectangle_templates', function (Blueprint $table) { $table->dropColumn('background_color'); $table->dropColumn('text_color'); $table->dropColumn('button_background_color'); $table->dropColumn('button_text_color'); $table->string('color_scheme')->nullable(false)->change(); }); Schema::table('short_message_templates', function (Blueprint $table) { $table->dropColumn('background_color'); $table->dropColumn('text_color'); $table->string('color_scheme')->nullable(false)->change(); }); } public function down() { // create old color columns Schema::table('bar_templates', function (Blueprint $table) { $table->string('background_color')->nullable(); $table->string('text_color')->nullable(); $table->string('button_background_color')->nullable(); $table->string('button_text_color')->nullable(); }); Schema::table('collapsible_bar_templates', function (Blueprint $table) { $table->string('background_color')->nullable(); $table->string('text_color')->nullable(); $table->string('button_background_color')->nullable(); $table->string('button_text_color')->nullable(); }); Schema::table('medium_rectangle_templates', function (Blueprint $table) { $table->string('background_color')->nullable(); $table->string('text_color')->nullable(); $table->string('button_background_color')->nullable(); $table->string('button_text_color')->nullable(); }); Schema::table('newsletter_rectangle_templates', function (Blueprint $table) { $table->string('background_color')->nullable(); $table->string('text_color')->nullable(); $table->string('button_background_color')->nullable(); $table->string('button_text_color')->nullable(); }); Schema::table('overlay_rectangle_templates', function (Blueprint $table) { $table->string('background_color')->nullable(); $table->string('text_color')->nullable(); $table->string('button_background_color')->nullable(); $table->string('button_text_color')->nullable(); }); Schema::table('short_message_templates', function (Blueprint $table) { $table->string('background_color')->nullable(); $table->string('text_color')->nullable(); }); $colorSchemes = config('banners.color_schemes'); foreach ($colorSchemes as $code => $colorScheme) { DB::table('bar_templates') ->where('color_scheme', $code) ->update([ 'background_color' => $colorScheme['backgroundColor'], 'text_color' => $colorScheme['textColor'], 'button_background_color' => $colorScheme['buttonBackgroundColor'], 'button_text_color' => $colorScheme['buttonTextColor'], ]); DB::table('collapsible_bar_templates') ->where('color_scheme', $code) ->update([ 'background_color' => $colorScheme['backgroundColor'], 'text_color' => $colorScheme['textColor'], 'button_background_color' => $colorScheme['buttonBackgroundColor'], 'button_text_color' => $colorScheme['buttonTextColor'], ]); DB::table('medium_rectangle_templates') ->where('color_scheme', $code) ->update([ 'background_color' => $colorScheme['backgroundColor'], 'text_color' => $colorScheme['textColor'], 'button_background_color' => $colorScheme['buttonBackgroundColor'], 'button_text_color' => $colorScheme['buttonTextColor'], ]); DB::table('newsletter_rectangle_templates') ->where('color_scheme', $code) ->update([ 'background_color' => $colorScheme['backgroundColor'], 'text_color' => $colorScheme['textColor'], 'button_background_color' => $colorScheme['buttonBackgroundColor'], 'button_text_color' => $colorScheme['buttonTextColor'], ]); DB::table('overlay_rectangle_templates') ->where('color_scheme', $code) ->update([ 'background_color' => $colorScheme['backgroundColor'], 'text_color' => $colorScheme['textColor'], 'button_background_color' => $colorScheme['buttonBackgroundColor'], 'button_text_color' => $colorScheme['buttonTextColor'], ]); DB::table('short_message_templates') ->where('color_scheme', $code) ->update([ 'background_color' => $colorScheme['backgroundColor'], 'text_color' => $colorScheme['textColor'], ]); } // drop `color_scheme` column Schema::table('bar_templates', function (Blueprint $table) { $table->dropColumn('color_scheme'); $table->string('background_color')->nullable(false)->change(); $table->string('text_color')->nullable(false)->change(); $table->string('button_background_color')->nullable(false)->change(); $table->string('button_text_color')->nullable(false)->change(); }); Schema::table('collapsible_bar_templates', function (Blueprint $table) { $table->dropColumn('color_scheme'); $table->string('background_color')->nullable(false)->change(); $table->string('text_color')->nullable(false)->change(); $table->string('button_background_color')->nullable(false)->change(); $table->string('button_text_color')->nullable(false)->change(); }); Schema::table('medium_rectangle_templates', function (Blueprint $table) { $table->dropColumn('color_scheme'); $table->string('background_color')->nullable(false)->change(); $table->string('text_color')->nullable(false)->change(); $table->string('button_background_color')->nullable(false)->change(); $table->string('button_text_color')->nullable(false)->change(); }); Schema::table('newsletter_rectangle_templates', function (Blueprint $table) { $table->dropColumn('color_scheme'); $table->string('background_color')->nullable(false)->change(); $table->string('text_color')->nullable(false)->change(); $table->string('button_background_color')->nullable(false)->change(); $table->string('button_text_color')->nullable(false)->change(); }); Schema::table('overlay_rectangle_templates', function (Blueprint $table) { $table->dropColumn('color_scheme'); $table->string('background_color')->nullable(false)->change(); $table->string('text_color')->nullable(false)->change(); $table->string('button_background_color')->nullable(false)->change(); $table->string('button_text_color')->nullable(false)->change(); }); Schema::table('short_message_templates', function (Blueprint $table) { $table->dropColumn('color_scheme'); $table->string('background_color')->nullable(false)->change(); $table->string('text_color')->nullable(false)->change(); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2019_06_04_081518_rename_collapsible_bar_template_collapse_text_column.php
Campaign/extensions/campaign-module/database/migrations/2019_06_04_081518_rename_collapsible_bar_template_collapse_text_column.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class RenameCollapsibleBarTemplateCollapseTextColumn extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('collapsible_bar_templates', function (Blueprint $table) { $table->renameColumn('collapse_text', 'header_text'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('collapsible_bar_templates', function (Blueprint $table) { $table->renameColumn('header_text', 'collapse_text'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2020_08_17_073631_migrate_old_campaign_pageview_rules_format_to_new.php
Campaign/extensions/campaign-module/database/migrations/2020_08_17_073631_migrate_old_campaign_pageview_rules_format_to_new.php
<?php use Illuminate\Database\Migrations\Migration; class MigrateOldCampaignPageviewRulesFormatToNew extends Migration { /** * Run the migrations. * * @return void */ public function up() { $output = new \Symfony\Component\Console\Output\ConsoleOutput(); $campaigns = \DB::table('campaigns')->select(['id', 'pageview_rules'])->get(); foreach ($campaigns as $campaign) { if ($campaign->pageview_rules === null) { continue; } $stopCampaign = false; $newPageviewRules = [ 'display_banner' => 'always', 'display_banner_every' => 2, 'display_times' => false, 'display_n_times' => 2, ]; $pageviewRules = json_decode($campaign->pageview_rules, true); foreach ($pageviewRules as $pageviewRule) { if (in_array($pageviewRule['rule'], ['since', 'before'])) { $stopCampaign = true; continue; } if ($pageviewRule['rule'] === 'every' && $pageviewRule['num'] !== null && $pageviewRule['num'] != 1) { $newPageviewRules['display_banner'] = 'every'; $newPageviewRules['display_banner_every'] = $pageviewRule['num']; } } $campaignObj = \Remp\CampaignModule\Campaign::find($campaign->id); $campaignObj->pageview_rules = $newPageviewRules; $campaignObj->save(); if ($stopCampaign) { $stopped = false; /** @var \Remp\CampaignModule\Schedule $schedule */ foreach ($campaignObj->schedules()->runningOrPlanned()->get() as $schedule) { $schedule->status = \Remp\CampaignModule\Schedule::STATUS_STOPPED; $schedule->end_time = \Carbon\Carbon::now(); $schedule->save(); $stopped = true; } if ($stopped) { $output->writeln('Campaign with ID: ' . $campaignObj->id . ' was stopped because we cant translate its pageview rules to new format. Old pageview rules were: ' . $campaign->pageview_rules); } } } } /** * Reverse the migrations. * * @return void */ public function down() { } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2017_12_07_133131_short_message_templates.php
Campaign/extensions/campaign-module/database/migrations/2017_12_07_133131_short_message_templates.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class ShortMessageTemplates extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('short_message_templates', function (Blueprint $table) { $table->increments('id'); $table->integer('banner_id')->unsigned(); $table->string('text'); $table->string('background_color'); $table->string('text_color'); $table->foreign('banner_id')->references('id')->on('banners'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('short_message_templates'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2023_09_12_121415_create_campaign_collections_table.php
Campaign/extensions/campaign-module/database/migrations/2023_09_12_121415_create_campaign_collections_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCampaignCollectionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('campaign_collections', function (Blueprint $table) { $table->id(); $table->bigInteger('collection_id')->unsigned(); $table->foreign('collection_id')->references('id')->on('collections'); $table->integer('campaign_id')->unsigned(); $table->foreign('campaign_id')->references('id')->on('campaigns'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('campaign_collections'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2017_11_20_084233_alternative_banner.php
Campaign/extensions/campaign-module/database/migrations/2017_11_20_084233_alternative_banner.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AlternativeBanner extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('campaigns', function (Blueprint $table) { $table->integer('alt_banner_id')->unsigned()->nullable(true)->after('banner_id'); $table->foreign('alt_banner_id')->references('id')->on('banners'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaigns', function (Blueprint $table) { $table->dropForeign(['alt_banner_id']); $table->dropColumn("alt_banner_id"); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2017_08_28_062959_banner_display_type.php
Campaign/extensions/campaign-module/database/migrations/2017_08_28_062959_banner_display_type.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class BannerDisplayType extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('banners', function (Blueprint $table) { $table->string('display_type'); $table->string('position')->nullable()->change(); $table->integer('display_delay')->nullable()->change(); $table->boolean('closeable')->nullable()->change(); $table->string('target_selector')->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('banners', function (Blueprint $table) { $table->removeColumn('display_type'); $table->string('position')->change(); $table->integer('display_delay')->change(); $table->boolean('closeable')->change(); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2017_11_02_120230_campaing_once_per_session.php
Campaign/extensions/campaign-module/database/migrations/2017_11_02_120230_campaing_once_per_session.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CampaingOncePerSession extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('campaigns', function (Blueprint $table) { $table->boolean("once_per_session")->nullable(false); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaigns', function (Blueprint $table) { $table->dropColumn("once_per_session"); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2017_06_28_132802_campaign_segments.php
Campaign/extensions/campaign-module/database/migrations/2017_06_28_132802_campaign_segments.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CampaignSegments extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('campaign_segments', function (Blueprint $table) { $table->increments('id'); $table->integer("campaign_id")->unsigned(); $table->string("code"); $table->string("provider"); $table->timestamps(); $table->foreign('campaign_id')->references('id')->on('campaigns'); }); Schema::table('campaigns', function (Blueprint $table) { $table->dropColumn('segment_id'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaigns', function (Blueprint $table) { $table->string('segment_id'); }); Schema::drop('campaign_segments'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_03_26_143751_change_pageview_rules_column_type.php
Campaign/extensions/campaign-module/database/migrations/2018_03_26_143751_change_pageview_rules_column_type.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; use Illuminate\Support\Facades\DB; class ChangePageviewRulesColumnType extends Migration { /** * Run the migrations. * * @return void */ public function up() { // DISABLING TRANSACTION in old migration // since it is already applied in production and it breaks php test // reason: https://github.com/laravel/framework/issues/35380 //DB::transaction(function () { $pageviewRulesData = DB::table('campaigns')->select('id', 'pageview_rules')->get(); Schema::table('campaigns', function (Blueprint $table) { $table->dropColumn("pageview_rules"); }); Schema::table('campaigns', function (Blueprint $table) { $table->json("pageview_rules")->nullable(true); }); foreach($pageviewRulesData as $row) { DB::table('campaigns')->where('id', $row->id)->update([ 'pageview_rules' => $row->pageview_rules ]); } //}); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaigns', function (Blueprint $table) { $table->string("pageview_rules")->change(); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2017_05_26_090050_banner_campaigns.php
Campaign/extensions/campaign-module/database/migrations/2017_05_26_090050_banner_campaigns.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class BannerCampaigns extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('campaigns', function (Blueprint $table) { $table->increments('id'); $table->uuid('uuid'); $table->string('name'); $table->boolean('active'); $table->integer('banner_id')->unsigned(); $table->string('segment_id'); $table->timestamps(); $table->foreign('banner_id')->references('id')->on('banners'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('campaigns'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_12_12_140812_overlay_rectangle_templates.php
Campaign/extensions/campaign-module/database/migrations/2018_12_12_140812_overlay_rectangle_templates.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class OverlayRectangleTemplates extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('overlay_rectangle_templates', function (Blueprint $table) { $table->increments('id'); $table->integer('banner_id')->unsigned(); $table->string('header_text')->nullable(true); $table->string('main_text')->nullable(true); $table->string('button_text')->nullable(true); $table->string('background_color')->nullable(true); $table->string('text_color')->nullable(true); $table->string('button_background_color'); $table->string('button_text_color'); $table->string('width')->nullable(true); $table->string('height')->nullable(true); $table->string('image_link')->nullable(true); $table->foreign('banner_id')->references('id')->on('banners'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('overlay_rectangle_templates'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2020_06_08_115935_add_manual_events_tracking_to_banners.php
Campaign/extensions/campaign-module/database/migrations/2020_06_08_115935_add_manual_events_tracking_to_banners.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddManualEventsTrackingToBanners extends Migration { public function up() { Schema::table('banners', function (Blueprint $table) { $table->boolean('manual_events_tracking')->nullable()->default(false); }); DB::statement('UPDATE banners SET manual_events_tracking = :value', [ 'value' => 0 ]); Schema::table('banners', function (Blueprint $table) { $table->boolean('manual_events_tracking')->nullable(false)->default(false)->change(); }); } public function down() { Schema::table('banners', function (Blueprint $table) { $table->dropColumn('manual_events_tracking'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_04_25_115245_variant_control_group.php
Campaign/extensions/campaign-module/database/migrations/2018_04_25_115245_variant_control_group.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class VariantControlGroup extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('campaign_banners', function (Blueprint $table) { $table->dropForeign(['banner_id']); }); // DISABLING TRANSACTION in old migration // since it is already applied in production and it breaks php test // reason: https://github.com/laravel/framework/issues/35380 //DB::transaction(function () { Schema::table('campaign_banners', function (Blueprint $table) { $table->integer('control_group')->nullable()->default(0); $table->integer('banner_id')->unsigned()->nullable()->change(); }); $campaigns = DB::select("SELECT campaign_id FROM campaign_banners GROUP BY campaign_id"); foreach ($campaigns as $campaign) { $id = $campaign->campaign_id; DB::statement("INSERT INTO campaign_banners (`campaign_id`, `banner_id`, `variant`, `control_group`) VALUES({$id}, null, 'Control Group', 1)"); } //}); Schema::table('campaign_banners', function (Blueprint $table) { $table->foreign('banner_id')->references('id')->on('banners'); }); } /** * Reverse the migrations. * * @return void */ public function down() { //DB::transaction(function () { DB::statement("DELETE FROM campaign_banners WHERE control_group = 1"); Schema::table('campaign_banners', function (Blueprint $table) { $table->dropColumn('control_group'); $table->integer('banner_id')->nullable(true); }); //}); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2025_11_13_132323_increase_target_url_length_in_banners_table.php
Campaign/extensions/campaign-module/database/migrations/2025_11_13_132323_increase_target_url_length_in_banners_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class IncreaseTargetUrlLengthInBannersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('banners', function (Blueprint $table) { $table->string('target_url', 768) ->nullable() ->change(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('banners', function (Blueprint $table) { }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_04_04_135617_precise_banner_position.php
Campaign/extensions/campaign-module/database/migrations/2018_04_04_135617_precise_banner_position.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class PreciseBannerPosition extends Migration { private $positionMap; public function __construct() { $this->positionMap = app(\Remp\CampaignModule\Models\Position\Map::class); } /** * Run the migrations. * * @return void */ public function up() { Schema::table('banners', function (Blueprint $table) { $table->integer('offset_vertical')->nullable()->after('position'); $table->integer('offset_horizontal')->nullable()->after('position'); }); foreach (DB::query()->from('banners')->get() as $banner) { $pos = $this->positionMap->positions()->first()->style; $query = DB::table('banners')->where([ 'id' => $banner->id ]); $query->update([ 'offset_vertical' => intval(isset($pos['top']) ? $pos['top'] : $pos['bottom']), 'offset_horizontal' => intval(isset($pos['left']) ? $pos['left'] : $pos['right']), ]); } Schema::table('banners', function (Blueprint $table) { $table->integer('offset_vertical')->nullable(false)->change(); $table->integer('offset_horizontal')->nullable(false)->change(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('banners', function (Blueprint $table) { $table->dropColumn('offset_horizontal'); $table->dropColumn('offset_vertical'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2017_09_22_073840_bar_banner_template.php
Campaign/extensions/campaign-module/database/migrations/2017_09_22_073840_bar_banner_template.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class BarBannerTemplate extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('bar_templates', function (Blueprint $table) { $table->increments('id'); $table->integer('banner_id')->unsigned(); $table->string('main_text'); $table->string('button_text'); $table->string('background_color'); $table->string('text_color'); $table->string('button_background_color'); $table->string('button_text_color'); $table->foreign('banner_id')->references('id')->on('banners'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('bar_templates'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2020_06_24_123600_overlay_two_buttons_signature.php
Campaign/extensions/campaign-module/database/migrations/2020_06_24_123600_overlay_two_buttons_signature.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class OverlayTwoButtonsSignature extends Migration { public function up() { Schema::create('overlay_two_buttons_signature_templates', function (Blueprint $table) { $table->increments('id'); $table->integer('banner_id')->unsigned(); $table->text('text_before')->nullable(true); $table->string('text_after')->nullable(true); $table->string('text_btn_primary'); $table->string('text_btn_primary_minor')->nullable(true); $table->string('text_btn_secondary')->nullable(true); $table->string('text_btn_secondary_minor')->nullable(true); $table->string('target_url_secondary')->nullable(true); $table->string('signature_image_url')->nullable(true); $table->string('text_signature')->nullable(true); $table->foreign('banner_id')->references('id')->on('banners'); $table->timestamps(); }); } public function down() { Schema::dropIfExists('overlay_two_buttons_signature_templates'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2023_09_12_121136_create_collections_table.php
Campaign/extensions/campaign-module/database/migrations/2023_09_12_121136_create_collections_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCollectionsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('collections', function (Blueprint $table) { $table->id()->unsigned(); $table->string('name'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('collections'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_11_15_140341_rename_campaign_usingadblock_column.php
Campaign/extensions/campaign-module/database/migrations/2018_11_15_140341_rename_campaign_usingadblock_column.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class RenameCampaignUsingadblockColumn extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('campaigns', function (Blueprint $table) { $table->renameColumn('usingAdblock', 'using_adblock'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaigns', function (Blueprint $table) { $table->renameColumn('using_adblock', 'usingAdblock'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_07_06_141409_drop_variant_name.php
Campaign/extensions/campaign-module/database/migrations/2018_07_06_141409_drop_variant_name.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class DropVariantName extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table("campaign_banners", function (Blueprint $table) { $table->dropColumn("variant"); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table("campaign_banners", function (Blueprint $table) { $table->string("variant"); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_04_25_115736_variant_proportion.php
Campaign/extensions/campaign-module/database/migrations/2018_04_25_115736_variant_proportion.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class VariantProportion extends Migration { /** * Run the migrations. * * @return void */ public function up() { // DISABLING TRANSACTION in old migration // since it is already applied in production and it breaks php test // reason: https://github.com/laravel/framework/issues/35380 //DB::transaction(function () { Schema::table('campaign_banners', function (Blueprint $table) { $table->integer('proportion')->nullable(); }); $rows = DB::select("SELECT * FROM campaign_banners WHERE control_group != 1"); $counts = []; foreach ($rows as $row) { if (array_key_exists($row->campaign_id, $counts)) { $counts[$row->campaign_id]++; } else { $counts[$row->campaign_id] = 1; } } foreach ($counts as $campaignId => $count) { $proportion = intval(100 / $count); DB::statement("UPDATE campaign_banners SET proportion = {$proportion} WHERE campaign_id = {$campaignId} AND control_group != 1"); DB::statement("UPDATE campaign_banners SET proportion = 0 WHERE campaign_id = {$campaignId} AND control_group = 1"); } Schema::table('campaign_banners', function (Blueprint $table) { $table->integer('proportion')->nullable(false)->change(); }); //}); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaign_banners', function (Blueprint $table) { $table->dropColumn('proportion'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2017_04_19_084922_transforming_banner_to_text.php
Campaign/extensions/campaign-module/database/migrations/2017_04_19_084922_transforming_banner_to_text.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class TransformingBannerToText extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('banners', function (Blueprint $table) { $table->string('target_url'); $table->dropColumn('storage_uri'); $table->dropColumn('width'); $table->dropColumn('height'); $table->string('text'); $table->string('dimensions'); $table->string('text_align'); $table->string('text_color'); $table->string('font_size'); $table->string('background_color'); $table->string('position'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('banners', function (Blueprint $table) { $table->dropColumn(['target_url', 'text_color', 'background_color', 'position', 'text', 'dimensions', 'text_align', 'font_size']); $table->string('storage_uri'); $table->integer('width'); $table->integer('height'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2021_05_21_072312_add_public_id.php
Campaign/extensions/campaign-module/database/migrations/2021_05_21_072312_add_public_id.php
<?php use Remp\CampaignModule\IdentificationTrait; use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddPublicId extends Migration { use IdentificationTrait; public function up(): void { Schema::table('campaigns', function (Blueprint $table) { $table->char('public_id', 6)->after('uuid'); }); foreach (DB::query()->from('campaigns')->get() as $item) { DB::table('campaigns') ->where(['id' => $item->id]) ->update(['public_id' => self::generatePublicId()]); } Schema::table('banners', function (Blueprint $table) { $table->char('public_id', 6)->after('uuid'); }); foreach (DB::query()->from('banners')->get() as $item) { DB::table('banners') ->where(['id' => $item->id]) ->update(['public_id' => self::generatePublicId()]); } Schema::table('campaign_banners', function (Blueprint $table) { $table->char('public_id', 6)->after('uuid'); }); foreach (DB::query()->from('campaign_banners')->get() as $item) { DB::table('campaign_banners') ->where(['id' => $item->id]) ->update(['public_id' => self::generatePublicId()]); } } public function down(): void { Schema::table('campaigns', function (Blueprint $table) { $table->dropColumn('public_id'); }); Schema::table('banners', function (Blueprint $table) { $table->dropColumn('public_id'); }); Schema::table('campaign_banners', function (Blueprint $table) { $table->dropColumn('public_id'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2023_03_20_121715_rename_variables_to_snippets.php
Campaign/extensions/campaign-module/database/migrations/2023_03_20_121715_rename_variables_to_snippets.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class RenameVariablesToSnippets extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::rename('variables', 'snippets'); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::rename('snippets', 'variables'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2019_03_26_092200_create_campaign_banner_purchase_stats_table.php
Campaign/extensions/campaign-module/database/migrations/2019_03_26_092200_create_campaign_banner_purchase_stats_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateCampaignBannerPurchaseStatsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('campaign_banner_purchase_stats', function (Blueprint $table) { $table->increments('id'); $table->integer('campaign_banner_id')->unsigned(); $table->timestamp('time_from')->nullable(); $table->timestamp('time_to')->nullable(); $table->decimal('sum',10,2); $table->string('currency'); $table->foreign('campaign_banner_id')->references('id')->on('campaign_banners'); $table->index('time_from'); $table->index('time_to'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('campaign_banner_purchase_stats'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2017_10_12_084905_create_failed_jobs_table.php
Campaign/extensions/campaign-module/database/migrations/2017_10_12_084905_create_failed_jobs_table.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateFailedJobsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('failed_jobs', function (Blueprint $table) { $table->bigIncrements('id'); $table->text('connection'); $table->text('queue'); $table->longText('payload'); $table->longText('exception'); $table->timestamp('failed_at')->useCurrent(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('failed_jobs'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2017_10_11_092115_campaign_user_state.php
Campaign/extensions/campaign-module/database/migrations/2017_10_11_092115_campaign_user_state.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CampaignUserState extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('campaigns', function (Blueprint $table) { $table->boolean("signed_in")->nullable(true); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaigns', function (Blueprint $table) { $table->dropColumn("signed_in"); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_04_25_134100_variants_weight.php
Campaign/extensions/campaign-module/database/migrations/2018_04_25_134100_variants_weight.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class VariantsWeight extends Migration { /** * Run the migrations. * * @return void */ public function up() { // DISABLING TRANSACTION in old migration // since it is already applied in production and it breaks php test // reason: https://github.com/laravel/framework/issues/35380 //DB::transaction(function () { Schema::table('campaign_banners', function (Blueprint $table) { $table->integer('weight')->nullable(); }); $variants = DB::select("SELECT * FROM campaign_banners WHERE control_group = 0 ORDER BY variant"); $weight = 1; foreach($variants as $variant) { $campaignId = $variant->campaign_id; $bannerId = $variant->banner_id; DB::statement("UPDATE campaign_banners SET `weight` = {$weight} WHERE campaign_id = {$campaignId} AND banner_id = {$bannerId}"); $weight++; } DB::statement("UPDATE campaign_banners SET `weight` = {$weight} WHERE control_group = 1"); Schema::table('campaign_banners', function (Blueprint $table) { $table->integer('weight')->nullable(false)->change(); }); //}); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaign_banners', function (Blueprint $table) { $table->dropColumn('weight'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_04_26_104002_variant_soft_delete.php
Campaign/extensions/campaign-module/database/migrations/2018_04_26_104002_variant_soft_delete.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class VariantSoftDelete extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('campaign_banners', function (Blueprint $table) { $table->softDeletes(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaign_banners', function (Blueprint $table) { $table->dropSoftDeletes(); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2019_07_11_085137_campaign_country_primary_key.php
Campaign/extensions/campaign-module/database/migrations/2019_07_11_085137_campaign_country_primary_key.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CampaignCountryPrimaryKey extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (!Schema::hasColumn('campaign_country', 'id')) { Schema::table('campaign_country', function (Blueprint $table) { $table->increments('id')->first(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaign_country', function (Blueprint $table) { $table->dropColumn('id'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2017_09_27_075942_medium_rectangle_dimensions.php
Campaign/extensions/campaign-module/database/migrations/2017_09_27_075942_medium_rectangle_dimensions.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class MediumRectangleDimensions extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('medium_rectangle_templates', function (Blueprint $table) { $table->string("width")->nullable(); $table->string("height")->nullable(); $table->string("header_text")->nullable()->change(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('medium_rectangle_templates', function (Blueprint $table) { $table->dropColumn(["width", "height"]); $table->string("header_text")->nullable(false)->change(); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_03_02_132258_campaigns_pageview_rules.php
Campaign/extensions/campaign-module/database/migrations/2018_03_02_132258_campaigns_pageview_rules.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CampaignsPageviewRules extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('campaigns', function (Blueprint $table) { $table->string("pageview_rules")->nullable(true); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaigns', function (Blueprint $table) { $table->dropColumn("pageview_rules"); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2023_09_05_145623_add_languages_column_to_campaigns.php
Campaign/extensions/campaign-module/database/migrations/2023_09_05_145623_add_languages_column_to_campaigns.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddLanguagesColumnToCampaigns extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('campaigns', function (Blueprint $table) { $table->json('languages')->nullable(true)->default(null)->after('devices'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaigns', function (Blueprint $table) { $table->dropColumn('languages'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_12_31_093613_collapsible_bar_template.php
Campaign/extensions/campaign-module/database/migrations/2018_12_31_093613_collapsible_bar_template.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CollapsibleBarTemplate extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('collapsible_bar_templates', function (Blueprint $table) { $table->increments('id'); $table->integer('banner_id')->unsigned(); $table->string('collapse_text'); $table->string('main_text'); $table->string('button_text'); $table->string('background_color'); $table->string('text_color'); $table->string('button_background_color'); $table->string('button_text_color'); $table->string('initial_state'); $table->foreign('banner_id')->references('id')->on('banners'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('collapsible_bar_templates'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2023_02_15_131950_add_force_initial_to_collapsible_bar.php
Campaign/extensions/campaign-module/database/migrations/2023_02_15_131950_add_force_initial_to_collapsible_bar.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddForceInitialToCollapsibleBar extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('collapsible_bar_templates', function (Blueprint $table) { $table->boolean('force_initial_state')->default(false); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('collapsible_bar_templates', function (Blueprint $table) { $table->dropColumn('force_initial_state'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_03_22_162154_campaign_drop_active_flag.php
Campaign/extensions/campaign-module/database/migrations/2018_03_22_162154_campaign_drop_active_flag.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CampaignDropActiveFlag extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('campaigns', function (Blueprint $table) { $table->dropColumn("active"); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaigns', function (Blueprint $table) { $table->boolean('active')->after('name'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_02_22_101337_campaign_geotargeting.php
Campaign/extensions/campaign-module/database/migrations/2018_02_22_101337_campaign_geotargeting.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; use Remp\CampaignModule\Database\Seeders\CountrySeeder; class CampaignGeotargeting extends Migration { /** * Run the migrations. * * @return void */ public function up() { // create countries table Schema::create('countries', function (Blueprint $table) { $table->string('iso_code', 5)->primary(); $table->string('name'); }); // pivot table to connect countries to campaigns Schema::create('campaign_country', function (Blueprint $table) { $table->increments('id'); $table->integer('campaign_id')->unsigned(); $table->string('country_iso_code', 5); $table->boolean('blacklisted')->default(false); $table->unique(['campaign_id', 'country_iso_code'], 'campaign_country_unique'); $table->foreign('campaign_id')->references('id')->on('campaigns'); $table->foreign('country_iso_code')->references('iso_code')->on('countries'); }); Artisan::call('db:seed', ['--class' => CountrySeeder::class]); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('campaign_country'); Schema::drop('countries'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_10_22_091546_add_campaign_addblock_column.php
Campaign/extensions/campaign-module/database/migrations/2018_10_22_091546_add_campaign_addblock_column.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddCampaignAddblockColumn extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table("campaigns", function (Blueprint $table) { $table->boolean("usingAdblock")->nullable()->default(null); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table("campaigns", function (Blueprint $table) { $table->dropColumn("usingAdblock"); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2017_10_30_115547_campaign_scheduler.php
Campaign/extensions/campaign-module/database/migrations/2017_10_30_115547_campaign_scheduler.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CampaignScheduler extends Migration { public function up() { Schema::create('schedules', function (Blueprint $table) { $table->increments('id'); $table->integer('campaign_id')->unsigned(); $table->dateTime('start_time'); $table->dateTime('end_time')->nullable(); $table->enum('status', ['ready', 'executed', 'paused', 'stopped'])->default('ready'); $table->foreign('campaign_id')->references('id')->on('campaigns'); $table->timestamps(); }); } public function down() { Schema::drop('schedules'); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_04_26_102135_variants_primary_key.php
Campaign/extensions/campaign-module/database/migrations/2018_04_26_102135_variants_primary_key.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class VariantsPrimaryKey extends Migration { /** * Run the migrations. * * @return void */ public function up() { if (!Schema::hasColumn('campaign_banners', 'id')) { Schema::table('campaign_banners', function (Blueprint $table) { $table->increments('id')->first(); }); } } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('campaign_banners', function (Blueprint $table) { $table->dropColumn('id'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false
remp2020/remp
https://github.com/remp2020/remp/blob/c616d27734c65eb87b470751928ff1119c535549/Campaign/extensions/campaign-module/database/migrations/2018_04_04_214416_banner_close_text.php
Campaign/extensions/campaign-module/database/migrations/2018_04_04_214416_banner_close_text.php
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class BannerCloseText extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('banners', function (Blueprint $table) { $table->string('close_text', 191)->nullable(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('banners', function (Blueprint $table) { $table->dropColumn('close_text'); }); } }
php
MIT
c616d27734c65eb87b470751928ff1119c535549
2026-01-05T05:12:01.604239Z
false