Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.06 KB | None | 0 0
  1. <?php
  2.  
  3. require_once '../init.php';
  4.  
  5. /**
  6. * This scripts updates companies from which we have not received any traffic in
  7. * the past 40 days as paused, along with tracking the status of the active ones
  8. * on a day by day basis
  9. */
  10. class MediaCompaniesWithTraffic {
  11. use \Crones\Cron;
  12.  
  13. /**
  14. * Mode for initializing companies and checking the past 40 days of clicks
  15. */
  16. CONST MODE_INIT = 'init';
  17. /**
  18. * The mode that should be run daily to keep track of the active companies that
  19. * don't receive traffic and set the ones that have not received traffic in 40
  20. * days as inactive
  21. */
  22. CONST MODE_DAILY = 'daily';
  23.  
  24. /**
  25. * 0 For a paused company
  26. */
  27. CONST STATUS_PAUSE = 0;
  28. /**
  29. * 1 For an active company
  30. */
  31. CONST STATUS_ACTIVE = 1;
  32. /**
  33. * -1 For a banned company
  34. */
  35. CONST STATUS_BANNED = -1;
  36. /**
  37. * Maximum ammount of days a company can be inactive before the robot pauses it
  38. */
  39. CONST MAX_INACTIVE_DAYS = 40;
  40.  
  41. /**
  42. * @var DB\PGConnection Postgres database connection
  43. */
  44. protected $db_pg;
  45. /**
  46. * @var \DB\Empresa Company database connection
  47. */
  48. protected $db_company;
  49.  
  50. /**
  51. * The mode in which this script is meant to be run
  52. * Defaults to MODE_DAILY
  53. * @var one of the MODE_ constant values from this class
  54. */
  55. protected $run_mode = self::MODE_DAILY;
  56. /**
  57. * The date from which the robot shold be looking
  58. * @var string A DateTime formatted string. Defaults to -1 days
  59. */
  60. protected $date_from = '-1 days';
  61. /**
  62. * @var int|boolean The target company to check only said company
  63. */
  64. protected $target_company = false;
  65.  
  66. /**
  67. * @var array The companies that are to be processed by the script
  68. */
  69. protected $valid_comapnies = [];
  70. /**
  71. * @var array The companies that have not received traffic since $date_from
  72. */
  73. protected $companies_with_traffic = [];
  74. /**
  75. * @var array An array with the company ids that have to be saved (have changes)
  76. */
  77. protected $companies_to_save = [];
  78. /**
  79. * Array storing each company original status to avoid saving too much logs
  80. * @var array
  81. */
  82. protected $original_status = [];
  83.  
  84.  
  85. /**
  86. * @var string The name of the robot (for saving and emails)
  87. */
  88. private $robot_name = 'INACTIVE_COMPANY_ROBOT';
  89. /**
  90. * @var array The temaplate for the filtros->status field in case it's not set
  91. */
  92. private $status_template;
  93. /**
  94. * The minimum creation date to check for traffic activity for the companies
  95. * @var string|int The date in Ymd format
  96. */
  97. private $min_date_creation;
  98.  
  99. /**
  100. * Handles logging
  101. * @var CLogger
  102. */
  103. private $logger;
  104. /**
  105. * If we want the status changes logged
  106. * @var boolean
  107. */
  108. private $log_status_changes = true;
  109.  
  110.  
  111. /**
  112. * Creates an instance of the robot and sets variables with the ones given as
  113. * commandline parameters
  114. * @param array $params The commandline parameters parsed as a key => value list
  115. */
  116. public function __construct($params) {
  117. $this->min_date_creation = (new DateTime('-' . self::MAX_INACTIVE_DAYS . ' days'))->format('Ymd');
  118. $this->init_params($params);
  119.  
  120. $this->date_from = new DateTime($this->date_from);
  121.  
  122. $this->status_template = [
  123. 'status' => self::STATUS_ACTIVE,
  124. 'fecha_mod' => (new DateTime())->format('Ymd'),
  125. 'fecha_inactividad' => 0,
  126. 'dias_inactividad' => 0,
  127. ];
  128.  
  129. $this->db_pg = new DB\PGConnection();
  130. $this->db_company = new DB\Empresa('media2_new', true);
  131.  
  132. $this->logger = new CLogger(__CLASS__);
  133. CLogger::$console = true;
  134. }
  135.  
  136. /**
  137. * Executes the main cron
  138. * @see \Crones\Cron::run()
  139. */
  140. public function run() {
  141. $this->logger->log('Starting company inactivity robot in mode: ' . $this->run_mode, CLogger::LEVEL_INFO);
  142.  
  143. $this->logger->log('Loading companies...', CLogger::LEVEL_INFO);
  144. $time = microtime(true);
  145. $this->valid_comapnies = $this->db_company->getEmpresas(null, 'id_empresa, filtros, fecha');
  146. $this->logger->log('Company load took ' . (number_format(microtime(true) - $time, 4)) . 's', CLOG_INFO);
  147.  
  148. foreach ( $this->valid_comapnies as $k => $v ) {
  149. $this->valid_comapnies[$k]['filtros'] = json_decode( $v['filtros'], true );
  150. if (isset($this->valid_comapnies[$k]['filtros']['status']['status']))
  151. $this->original_status[$k] = $this->valid_comapnies[$k]['filtros']['status']['status'];
  152. }
  153.  
  154. if ($this->run_mode === self::MODE_INIT) {
  155. $this->logger->log('Forcing date to ' . self::MAX_INACTIVE_DAYS . ' days ago', CLogger::LEVEL_INFO);
  156. $this->date_from = new DateTime('-' . self::MAX_INACTIVE_DAYS . ' days');
  157.  
  158. $this->getClickData();
  159. $this->initCompanies();
  160. }
  161. elseif($this->run_mode == self::MODE_DAILY) {
  162. $this->getClickData();
  163. }
  164.  
  165.  
  166. $this->markTraffic();
  167. $this->updateCompanies();
  168. }
  169.  
  170. /**
  171. * Load company ids that have received any traffic since $this->date_from->format('Ymd')
  172. */
  173. protected function getClickData() {
  174. $this->logger->log('Loading click details...', CLogger::LEVEL_INFO);
  175. $time = microtime(true);
  176. $q = 'SELECT id_empresa FROM adt_mkt_imp WHERE fecha >= ' . $this->date_from->format('Ymd') . ' GROUP BY id_empresa';
  177. $res = $this->db_pg->query($q);
  178.  
  179. $this->companies_with_traffic = [];
  180. while ($row = $this->db_pg->fetchAssoc($res)) {
  181. $this->companies_with_traffic[] = $row['id_empresa'];
  182. }
  183.  
  184. $this->db_pg->freeResult($res);
  185. $this->logger->log('Load took ' . (number_format(microtime(true) - $time, 4)) . 's', CLOG_INFO);
  186. }
  187.  
  188. /**
  189. * Called while MODE_INIT is set and all companies must be updated
  190. */
  191. protected function initCompanies() {
  192. $this->logger->log('Overwriting all company status data', CLogger::LEVEL_INFO);
  193.  
  194. $this->original_status = [];
  195. foreach ($this->valid_comapnies as $company => $company_details) {
  196. $this->valid_comapnies[$company]['filtros']['status'] = $this->status_template;
  197. $this->companies_to_save[] = $company;
  198. }
  199. }
  200.  
  201. /**
  202. * Marks the companies without traffic and sets them to be updated
  203. */
  204. protected function markTraffic() {
  205. $add = ($this->run_mode === self::MODE_INIT) ? self::MAX_INACTIVE_DAYS : 1;
  206.  
  207. $this->logger->log('Marking companies without traffic', CLogger::LEVEL_INFO);
  208. // Mark companies without traffic
  209. foreach ($this->valid_comapnies as $company => $company_details) {
  210. // If it has traffic, nothing to do or was created outside of the check range
  211. if ($this->target_company && $this->target_company != $company) continue;
  212. if (in_array($company, $this->companies_with_traffic)) continue;
  213. if ($this->min_date_creation < $this->valid_comapnies[$company]['fecha']) continue;
  214.  
  215. if (!isset($this->valid_comapnies[$company]['filtros']['status'])) {
  216. $this->valid_comapnies[$company]['filtros']['status'] = $this->status_template;
  217. }
  218.  
  219. if ($this->valid_comapnies[$company]['filtros']['status']['dias_inactividad'] == 0) {
  220. $this->valid_comapnies[$company]['filtros']['status']['fecha_inactividad'] = (new DateTime('-' . $add . ' days'))->format('Ymd');
  221. }
  222.  
  223. $this->valid_comapnies[$company]['filtros']['status']['dias_inactividad'] += $add;
  224.  
  225. // If inactive days exceed the max inactive days limit pause it
  226. if ($this->valid_comapnies[$company]['filtros']['status']['dias_inactividad'] >= self::MAX_INACTIVE_DAYS) {
  227. $this->valid_comapnies[$company]['filtros']['status']['status'] = self::STATUS_PAUSE;
  228. 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);
  229. }
  230.  
  231. // var_dump($this->valid_comapnies[$company]['filtros']['status']);
  232.  
  233. // Don't update companies with over MAX_INACTIVE_DAYS (40) days of inactivity
  234. if ($this->valid_comapnies[$company]['filtros']['status']['dias_inactividad'] > self::MAX_INACTIVE_DAYS) continue;
  235.  
  236. $this->companies_to_save[] = $company;
  237. }
  238.  
  239. $this->logger->log('Marking companies WITH traffic', CLogger::LEVEL_INFO);
  240. // Mark companies with traffic
  241. foreach ($this->companies_with_traffic as $company) {
  242. if ($this->target_company && $this->target_company != $company) continue;
  243.  
  244. if ($this->valid_comapnies[$company]['filtros']['status']['dias_inactividad'] > 0 && $this->valid_comapnies[$company]['filtros']['status']['status'] != self::STATUS_BANNED) {
  245. $this->valid_comapnies[$company]['filtros']['status']['dias_inactividad'] = $this->valid_comapnies[$company]['filtros']['status']['fecha_inactividad'] = 0;
  246. $this->valid_comapnies[$company]['filtros']['status']['status'] = self::STATUS_ACTIVE;
  247. $this->companies_to_save[] = $company;
  248. if ($this->log_status_changes) $this->logger->log('Company ' . $company . ' marked as active and count reset', CLOG_INFO);
  249. }
  250. }
  251.  
  252. }
  253.  
  254. /**
  255. * Saves changes to the companies
  256. */
  257. protected function updateCompanies() {
  258. $this->logger->log('Begin save process', CLogger::LEVEL_INFO);
  259. $this->companies_to_save = array_unique($this->companies_to_save);
  260. $under = $over = 0;
  261.  
  262. // TODO: Remove if everything works as expected as this check should not be needed after a week
  263. $is_safe_log_date = (new DateTime())->format('Ymd') > 20180315;
  264. foreach ($this->companies_to_save as $company) {
  265. $data = $this->valid_comapnies[$company];
  266.  
  267. $data['filtros']['status']['status'] = (string)$data['filtros']['status']['status'];
  268. $data['filtros']['status']['fecha_mod'] = (string)$data['filtros']['status']['fecha_mod'];
  269. $data['filtros']['status']['fecha_inactividad'] = (string)$data['filtros']['status']['fecha_inactividad'];
  270. $data['filtros']['status']['dias_inactividad'] = (string)$data['filtros']['status']['dias_inactividad'];
  271.  
  272. if ($data['filtros']['status']['dias_inactividad'] < self::MAX_INACTIVE_DAYS) {
  273. // if ($under == 0 ) var_dump ($data['filtros']['status']);
  274. $under++;
  275. }
  276. else {
  277. // if ($over == 0 ) var_dump ($data['filtros']['status']);
  278. $over++;
  279. }
  280.  
  281. //'fecha_mod' => (new DateTime())->format('Ymd'),
  282. // 'fecha_inactividad' => 0,
  283. // 'dias_inactividad' => 0,
  284.  
  285.  
  286. // Save log only if the robot has been active over a week and we have changed the company status
  287. $save_log = true;
  288. if (isset($this->original_status[$company]) && $this->original_status[$company] == $data['filtros']['status']['status'] && $is_safe_log_date) $save_log = false;
  289.  
  290. if ($this->live) {
  291. $this->db_company->saveEmpresa(
  292. $company,
  293. [
  294. 'filtros' => json_encode($data['filtros'])
  295. ],
  296. $this->robot_name,
  297. $save_log
  298. );
  299. }
  300. }
  301. $this->logger->log('End save process', CLogger::LEVEL_INFO);
  302. // $over_chunk = array_chunk($over, 10)[0];
  303. // $under_chunk = array_chunk($under, 10)[0];
  304.  
  305. // var_dump(['over' => $over_chunk, 'under' => $under_chunk]);
  306. $this->logger->log("Over max inactive days: $over", CLOG_INFO);
  307. $this->logger->log("Under max inactive days: $under", CLOG_INFO);
  308. }
  309. }
  310.  
  311. /**
  312. * Executes MediaCompaniesWithTraffic initializing it with the given parameters and calling run()
  313. * @param array $params The parameters
  314. */
  315. function media_companies_with_traffic ($params) {
  316. (new MediaCompaniesWithTraffic($params))->run();
  317. }
  318.  
  319. if (IS_DEV) call_user_func_array(preg_replace('!.php$!','',basename(__FILE__)), [CRobots::convertParams($argv)]);
  320.  
  321. \AFF
  322. \Crones
  323. \DB
  324. \MB
  325.  
  326. Class Hierarchy Diagram
  327.  
  328. Errors
  329. Markers
  330.  
  331. Documentation is powered by phpDocumentor and authored on April 23rd, 2018 at 03:20.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement