Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- require_once '../init.php';
- /**
- * This scripts updates companies from which we have not received any traffic in
- * the past 40 days as paused, along with tracking the status of the active ones
- * on a day by day basis
- */
- class MediaCompaniesWithTraffic {
- use \Crones\Cron;
- /**
- * Mode for initializing companies and checking the past 40 days of clicks
- */
- CONST MODE_INIT = 'init';
- /**
- * The mode that should be run daily to keep track of the active companies that
- * don't receive traffic and set the ones that have not received traffic in 40
- * days as inactive
- */
- CONST MODE_DAILY = 'daily';
- /**
- * 0 For a paused company
- */
- CONST STATUS_PAUSE = 0;
- /**
- * 1 For an active company
- */
- CONST STATUS_ACTIVE = 1;
- /**
- * -1 For a banned company
- */
- CONST STATUS_BANNED = -1;
- /**
- * Maximum ammount of days a company can be inactive before the robot pauses it
- */
- CONST MAX_INACTIVE_DAYS = 40;
- /**
- * @var DB\PGConnection Postgres database connection
- */
- protected $db_pg;
- /**
- * @var \DB\Empresa Company database connection
- */
- protected $db_company;
- /**
- * The mode in which this script is meant to be run
- * Defaults to MODE_DAILY
- * @var one of the MODE_ constant values from this class
- */
- protected $run_mode = self::MODE_DAILY;
- /**
- * The date from which the robot shold be looking
- * @var string A DateTime formatted string. Defaults to -1 days
- */
- protected $date_from = '-1 days';
- /**
- * @var int|boolean The target company to check only said company
- */
- protected $target_company = false;
- /**
- * @var array The companies that are to be processed by the script
- */
- protected $valid_comapnies = [];
- /**
- * @var array The companies that have not received traffic since $date_from
- */
- protected $companies_with_traffic = [];
- /**
- * @var array An array with the company ids that have to be saved (have changes)
- */
- protected $companies_to_save = [];
- /**
- * Array storing each company original status to avoid saving too much logs
- * @var array
- */
- protected $original_status = [];
- /**
- * @var string The name of the robot (for saving and emails)
- */
- private $robot_name = 'INACTIVE_COMPANY_ROBOT';
- /**
- * @var array The temaplate for the filtros->status field in case it's not set
- */
- private $status_template;
- /**
- * The minimum creation date to check for traffic activity for the companies
- * @var string|int The date in Ymd format
- */
- private $min_date_creation;
- /**
- * Handles logging
- * @var CLogger
- */
- private $logger;
- /**
- * If we want the status changes logged
- * @var boolean
- */
- private $log_status_changes = true;
- /**
- * Creates an instance of the robot and sets variables with the ones given as
- * commandline parameters
- * @param array $params The commandline parameters parsed as a key => value list
- */
- public function __construct($params) {
- $this->min_date_creation = (new DateTime('-' . self::MAX_INACTIVE_DAYS . ' days'))->format('Ymd');
- $this->init_params($params);
- $this->date_from = new DateTime($this->date_from);
- $this->status_template = [
- 'status' => self::STATUS_ACTIVE,
- 'fecha_mod' => (new DateTime())->format('Ymd'),
- 'fecha_inactividad' => 0,
- 'dias_inactividad' => 0,
- ];
- $this->db_pg = new DB\PGConnection();
- $this->db_company = new DB\Empresa('media2_new', true);
- $this->logger = new CLogger(__CLASS__);
- CLogger::$console = true;
- }
- /**
- * Executes the main cron
- * @see \Crones\Cron::run()
- */
- public function run() {
- $this->logger->log('Starting company inactivity robot in mode: ' . $this->run_mode, CLogger::LEVEL_INFO);
- $this->logger->log('Loading companies...', CLogger::LEVEL_INFO);
- $time = microtime(true);
- $this->valid_comapnies = $this->db_company->getEmpresas(null, 'id_empresa, filtros, fecha');
- $this->logger->log('Company load took ' . (number_format(microtime(true) - $time, 4)) . 's', CLOG_INFO);
- foreach ( $this->valid_comapnies as $k => $v ) {
- $this->valid_comapnies[$k]['filtros'] = json_decode( $v['filtros'], true );
- if (isset($this->valid_comapnies[$k]['filtros']['status']['status']))
- $this->original_status[$k] = $this->valid_comapnies[$k]['filtros']['status']['status'];
- }
- if ($this->run_mode === self::MODE_INIT) {
- $this->logger->log('Forcing date to ' . self::MAX_INACTIVE_DAYS . ' days ago', CLogger::LEVEL_INFO);
- $this->date_from = new DateTime('-' . self::MAX_INACTIVE_DAYS . ' days');
- $this->getClickData();
- $this->initCompanies();
- }
- elseif($this->run_mode == self::MODE_DAILY) {
- $this->getClickData();
- }
- $this->markTraffic();
- $this->updateCompanies();
- }
- /**
- * Load company ids that have received any traffic since $this->date_from->format('Ymd')
- */
- protected function getClickData() {
- $this->logger->log('Loading click details...', CLogger::LEVEL_INFO);
- $time = microtime(true);
- $q = 'SELECT id_empresa FROM adt_mkt_imp WHERE fecha >= ' . $this->date_from->format('Ymd') . ' GROUP BY id_empresa';
- $res = $this->db_pg->query($q);
- $this->companies_with_traffic = [];
- while ($row = $this->db_pg->fetchAssoc($res)) {
- $this->companies_with_traffic[] = $row['id_empresa'];
- }
- $this->db_pg->freeResult($res);
- $this->logger->log('Load took ' . (number_format(microtime(true) - $time, 4)) . 's', CLOG_INFO);
- }
- /**
- * Called while MODE_INIT is set and all companies must be updated
- */
- protected function initCompanies() {
- $this->logger->log('Overwriting all company status data', CLogger::LEVEL_INFO);
- $this->original_status = [];
- foreach ($this->valid_comapnies as $company => $company_details) {
- $this->valid_comapnies[$company]['filtros']['status'] = $this->status_template;
- $this->companies_to_save[] = $company;
- }
- }
- /**
- * Marks the companies without traffic and sets them to be updated
- */
- protected function markTraffic() {
- $add = ($this->run_mode === self::MODE_INIT) ? self::MAX_INACTIVE_DAYS : 1;
- $this->logger->log('Marking companies without traffic', CLogger::LEVEL_INFO);
- // Mark companies without traffic
- foreach ($this->valid_comapnies as $company => $company_details) {
- // If it has traffic, nothing to do or was created outside of the check range
- if ($this->target_company && $this->target_company != $company) continue;
- if (in_array($company, $this->companies_with_traffic)) continue;
- if ($this->min_date_creation < $this->valid_comapnies[$company]['fecha']) continue;
- if (!isset($this->valid_comapnies[$company]['filtros']['status'])) {
- $this->valid_comapnies[$company]['filtros']['status'] = $this->status_template;
- }
- if ($this->valid_comapnies[$company]['filtros']['status']['dias_inactividad'] == 0) {
- $this->valid_comapnies[$company]['filtros']['status']['fecha_inactividad'] = (new DateTime('-' . $add . ' days'))->format('Ymd');
- }
- $this->valid_comapnies[$company]['filtros']['status']['dias_inactividad'] += $add;
- // If inactive days exceed the max inactive days limit pause it
- if ($this->valid_comapnies[$company]['filtros']['status']['dias_inactividad'] >= self::MAX_INACTIVE_DAYS) {
- $this->valid_comapnies[$company]['filtros']['status']['status'] = self::STATUS_PAUSE;
- if ($this->log_status_changes) $this->logger->log('Company ' . $company . ' marked as paused (' . $this->valid_comapnies[$company]['filtros']['status']['dias_inactividad'] . ') inactive days', CLOG_INFO);
- }
- // var_dump($this->valid_comapnies[$company]['filtros']['status']);
- // Don't update companies with over MAX_INACTIVE_DAYS (40) days of inactivity
- if ($this->valid_comapnies[$company]['filtros']['status']['dias_inactividad'] > self::MAX_INACTIVE_DAYS) continue;
- $this->companies_to_save[] = $company;
- }
- $this->logger->log('Marking companies WITH traffic', CLogger::LEVEL_INFO);
- // Mark companies with traffic
- foreach ($this->companies_with_traffic as $company) {
- if ($this->target_company && $this->target_company != $company) continue;
- if ($this->valid_comapnies[$company]['filtros']['status']['dias_inactividad'] > 0 && $this->valid_comapnies[$company]['filtros']['status']['status'] != self::STATUS_BANNED) {
- $this->valid_comapnies[$company]['filtros']['status']['dias_inactividad'] = $this->valid_comapnies[$company]['filtros']['status']['fecha_inactividad'] = 0;
- $this->valid_comapnies[$company]['filtros']['status']['status'] = self::STATUS_ACTIVE;
- $this->companies_to_save[] = $company;
- if ($this->log_status_changes) $this->logger->log('Company ' . $company . ' marked as active and count reset', CLOG_INFO);
- }
- }
- }
- /**
- * Saves changes to the companies
- */
- protected function updateCompanies() {
- $this->logger->log('Begin save process', CLogger::LEVEL_INFO);
- $this->companies_to_save = array_unique($this->companies_to_save);
- $under = $over = 0;
- // TODO: Remove if everything works as expected as this check should not be needed after a week
- $is_safe_log_date = (new DateTime())->format('Ymd') > 20180315;
- foreach ($this->companies_to_save as $company) {
- $data = $this->valid_comapnies[$company];
- $data['filtros']['status']['status'] = (string)$data['filtros']['status']['status'];
- $data['filtros']['status']['fecha_mod'] = (string)$data['filtros']['status']['fecha_mod'];
- $data['filtros']['status']['fecha_inactividad'] = (string)$data['filtros']['status']['fecha_inactividad'];
- $data['filtros']['status']['dias_inactividad'] = (string)$data['filtros']['status']['dias_inactividad'];
- if ($data['filtros']['status']['dias_inactividad'] < self::MAX_INACTIVE_DAYS) {
- // if ($under == 0 ) var_dump ($data['filtros']['status']);
- $under++;
- }
- else {
- // if ($over == 0 ) var_dump ($data['filtros']['status']);
- $over++;
- }
- //'fecha_mod' => (new DateTime())->format('Ymd'),
- // 'fecha_inactividad' => 0,
- // 'dias_inactividad' => 0,
- // Save log only if the robot has been active over a week and we have changed the company status
- $save_log = true;
- if (isset($this->original_status[$company]) && $this->original_status[$company] == $data['filtros']['status']['status'] && $is_safe_log_date) $save_log = false;
- if ($this->live) {
- $this->db_company->saveEmpresa(
- $company,
- [
- 'filtros' => json_encode($data['filtros'])
- ],
- $this->robot_name,
- $save_log
- );
- }
- }
- $this->logger->log('End save process', CLogger::LEVEL_INFO);
- // $over_chunk = array_chunk($over, 10)[0];
- // $under_chunk = array_chunk($under, 10)[0];
- // var_dump(['over' => $over_chunk, 'under' => $under_chunk]);
- $this->logger->log("Over max inactive days: $over", CLOG_INFO);
- $this->logger->log("Under max inactive days: $under", CLOG_INFO);
- }
- }
- /**
- * Executes MediaCompaniesWithTraffic initializing it with the given parameters and calling run()
- * @param array $params The parameters
- */
- function media_companies_with_traffic ($params) {
- (new MediaCompaniesWithTraffic($params))->run();
- }
- if (IS_DEV) call_user_func_array(preg_replace('!.php$!','',basename(__FILE__)), [CRobots::convertParams($argv)]);
- \AFF
- \Crones
- \DB
- \MB
- Class Hierarchy Diagram
- Errors
- Markers
- Documentation is powered by phpDocumentor and authored on April 23rd, 2018 at 03:20.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement