Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 10 additions & 7 deletions API.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,13 +129,14 @@ public function getAlerts($idSites, $ifSuperUserReturnAllAlerts = false)
* @param bool|string $reportCondition
* @param bool|string $reportValue
* @param array $reportMediums
* @param string $slackChannelID
* @return int ID of new Alert
*/
public function addAlert($name, $idSites, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition = false, $reportValue = false, array $reportMediums = [])
public function addAlert($name, $idSites, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition = false, $reportValue = false, array $reportMediums = [], string $slackChannelID = '')
{
$idSites = Site::getIdSitesFromIdSitesString($idSites);

$this->checkAlert($idSites, $name, $period, $emailMe, $additionalEmails, $phoneNumbers, $metricCondition, $metric, $comparedTo, $reportCondition, $reportUniqueId, $reportMediums);
$this->checkAlert($idSites, $name, $period, $emailMe, $additionalEmails, $phoneNumbers, $slackChannelID, $metricCondition, $metric, $comparedTo, $reportCondition, $reportUniqueId, $reportMediums);

$name = Common::unsanitizeInputValue($name);
$login = Piwik::getCurrentUserLogin();
Expand All @@ -147,7 +148,7 @@ public function addAlert($name, $idSites, $period, $emailMe, $additionalEmails,

$metricValue = Common::forceDotAsSeparatorForDecimalPoint((float)$metricValue);

return $this->getModel()->createAlert($name, $idSites, $login, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition, $reportValue, $reportMediums);
return $this->getModel()->createAlert($name, $idSites, $login, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition, $reportValue, $reportMediums, $slackChannelID);
}

private function filterAdditionalEmails($additionalEmails)
Expand Down Expand Up @@ -181,12 +182,13 @@ private function filterPhoneNumbers($phoneNumbers)
return array_values($phoneNumbers);
}

private function checkAlert($idSites, $name, $period, &$emailMe, &$additionalEmails, &$phoneNumbers, $metricCondition, $metricValue, $comparedTo, $reportCondition, $reportUniqueId, $reportMediums)
private function checkAlert($idSites, $name, $period, &$emailMe, &$additionalEmails, &$phoneNumbers, &$slackChannelID, $metricCondition, $metricValue, $comparedTo, $reportCondition, $reportUniqueId, $reportMediums)
{
Piwik::checkUserHasViewAccess($idSites);
$additionalEmails = in_array('email', $reportMediums) ? $this->filterAdditionalEmails($additionalEmails) : [];
$phoneNumbers = in_array('mobile', $reportMediums) ? $this->filterPhoneNumbers($phoneNumbers) : [];
$emailMe = in_array('email', $reportMediums) && $emailMe;
$slackChannelID = in_array('slack', $reportMediums) ? $slackChannelID : '';

$this->validator->checkName($name);
$this->validator->checkPeriod($period);
Expand Down Expand Up @@ -224,17 +226,18 @@ private function checkAlert($idSites, $name, $period, &$emailMe, &$additionalEma
* @param bool|string $reportCondition
* @param bool|string $reportValue
* @param array $reportMediums
* @param string $slackChannelID
*
* @return boolean
*/
public function editAlert($idAlert, $name, $idSites, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition = false, $reportValue = false, array $reportMediums = [])
public function editAlert($idAlert, $name, $idSites, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition = false, $reportValue = false, array $reportMediums = [], string $slackChannelID = '')
{
// make sure alert exists and user has permission to read
$this->getAlert($idAlert);

$idSites = Site::getIdSitesFromIdSitesString($idSites);

$this->checkAlert($idSites, $name, $period, $emailMe, $additionalEmails, $phoneNumbers, $metricCondition, $metric, $comparedTo, $reportCondition, $reportUniqueId, $reportMediums);
$this->checkAlert($idSites, $name, $period, $emailMe, $additionalEmails, $phoneNumbers, $slackChannelID, $metricCondition, $metric, $comparedTo, $reportCondition, $reportUniqueId, $reportMediums);

$name = Common::unsanitizeInputValue($name);

Expand All @@ -245,7 +248,7 @@ public function editAlert($idAlert, $name, $idSites, $period, $emailMe, $additio

$metricValue = Common::forceDotAsSeparatorForDecimalPoint((float)$metricValue);

return $this->getModel()->updateAlert($idAlert, $name, $idSites, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition, $reportValue, $reportMediums);
return $this->getModel()->updateAlert($idAlert, $name, $idSites, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition, $reportValue, $reportMediums, $slackChannelID);
}

/**
Expand Down
8 changes: 8 additions & 0 deletions Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
namespace Piwik\Plugins\CustomAlerts;

use Piwik\Common;
use Piwik\Container\StaticContainer;
use Piwik\Date;
use Piwik\Period;
use Piwik\Piwik;
Expand Down Expand Up @@ -277,6 +278,13 @@ private function addBasicCreateAndEditVariables($view, $alert)
$view->comparablesDates = $comparablesDates;
$view->reportMetadata = $this->findReportMetadata($alert);
$view->supportsSMS = $this->supportsPlugin('MobileMessaging');
$supportsSlack = $this->supportsPlugin('Slack');
$isSlackOAuthTokenAdded = false;
if ($supportsSlack) {
$slackSettings = StaticContainer::get(\Piwik\Plugins\Slack\SystemSettings::class);
$isSlackOAuthTokenAdded = !empty($slackSettings->slackOauthToken->getValue());
}
$view->isSlackOAuthTokenAdded = $isSlackOAuthTokenAdded;
$view->periodOptions = array(
array('key' => 'day', 'value' => Piwik::translate('Intl_PeriodDay')),
array('key' => 'week', 'value' => Piwik::translate('Intl_PeriodWeek')),
Expand Down
4 changes: 3 additions & 1 deletion CustomAlerts.php
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,8 @@ public function removePhoneNumberFromAllAlerts($phoneNumber)
$alert['report'],
$alert['report_condition'],
$alert['report_matched'],
$alert['report_mediums']
$alert['report_mediums'],
$alert['slack_channel_id']
);
}
}
Expand Down Expand Up @@ -274,6 +275,7 @@ public static function getReportMediumOptions(): array
return [
['key' => 'email', 'value' => Piwik::translate('CustomAlerts_MediumEmail'), 'disabled' => false],
['key' => 'mobile', 'value' => Piwik::translate('CustomAlerts_MediumMobile'), 'disabled' => !PluginManager::getInstance()->isPluginActivated('MobileMessaging')],
['key' => 'slack', 'value' => Piwik::translate('CustomAlerts_MediumSlack'), 'disabled' => !PluginManager::getInstance()->isPluginActivated('Slack')],
];
}

Expand Down
18 changes: 12 additions & 6 deletions Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ public static function install()
`compared_to` SMALLINT (4) UNSIGNED NOT NULL DEFAULT 1 ,
`email_me` BOOLEAN NOT NULL DEFAULT '0',
`additional_emails` TEXT ,
`phone_numbers` TEXT ";
`phone_numbers` TEXT ,
`slack_channel_id` VARCHAR(50) NULL ";

DbHelper::createTable('alert', $tableAlert);

Expand Down Expand Up @@ -67,6 +68,7 @@ public static function install()
`email_me` BOOLEAN NOT NULL DEFAULT '0',
`additional_emails` TEXT ,
`phone_numbers` TEXT ,
`slack_channel_id` VARCHAR(50) NULL ,
PRIMARY KEY (idtriggered)";

DbHelper::createTable('alert_triggered', $tableAlertLog);
Expand Down Expand Up @@ -251,11 +253,12 @@ public function getAllAlertsForPeriod($period)
* @param string $reportCondition
* @param string $reportValue
* @param array $reportMediums
* @param string $slackChannelID
*
* @return int ID of new Alert
* @throws \Exception
*/
public function createAlert($name, $idSites, $login, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition, $reportValue, $reportMediums)
public function createAlert($name, $idSites, $login, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition, $reportValue, $reportMediums, $slackChannelID)
{
$idAlert = $this->getNextAlertId();

Expand All @@ -274,7 +277,8 @@ public function createAlert($name, $idSites, $login, $period, $emailMe, $additio
'compared_to' => $comparedTo,
'report_condition' => $reportCondition,
'report_matched' => $reportValue,
'report_mediums' => json_encode($reportMediums)
'report_mediums' => json_encode($reportMediums),
'slack_channel_id' => $slackChannelID
);

$db = $this->getDb();
Expand Down Expand Up @@ -332,11 +336,12 @@ private function removeAllSites($idAlert)
* @param string $reportCondition
* @param string $reportValue
* @param array $reportMediums
* @param string $slackChannelID
*
* @return int
* @throws \Exception
*/
public function updateAlert($idAlert, $name, $idSites, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition, $reportValue, $reportMediums)
public function updateAlert($idAlert, $name, $idSites, $period, $emailMe, $additionalEmails, $phoneNumbers, $metric, $metricCondition, $metricValue, $comparedTo, $reportUniqueId, $reportCondition, $reportValue, $reportMediums, $slackChannelID)
{
$alert = array(
'name' => $name,
Expand All @@ -352,6 +357,7 @@ public function updateAlert($idAlert, $name, $idSites, $period, $emailMe, $addit
'report_condition' => $reportCondition,
'report_matched' => $reportValue,
'report_mediums' => json_encode($reportMediums),
'slack_channel_id' => $slackChannelID
);

$db = $this->getDb();
Expand Down Expand Up @@ -381,7 +387,7 @@ public function triggerAlert($idAlert, $idSite, $valueNew, $valueOld, $datetime)
{
$alert = $this->getAlert($idAlert);

$keysToKeep = array('idalert', 'name', 'login', 'period', 'metric', 'metric_condition', 'metric_matched', 'report', 'report_condition', 'report_matched', 'report_mediums', 'compared_to', 'email_me', 'additional_emails', 'phone_numbers');
$keysToKeep = array('idalert', 'name', 'login', 'period', 'metric', 'metric_condition', 'metric_matched', 'report', 'report_condition', 'report_matched', 'report_mediums', 'compared_to', 'email_me', 'additional_emails', 'phone_numbers', 'slack_channel_id');

$triggeredAlert = array();
foreach ($keysToKeep as $key) {
Expand All @@ -396,7 +402,7 @@ public function triggerAlert($idAlert, $idSite, $valueNew, $valueOld, $datetime)
$triggeredAlert['idsite'] = $idSite;
$triggeredAlert['additional_emails'] = json_encode($triggeredAlert['additional_emails']);
$triggeredAlert['phone_numbers'] = json_encode($triggeredAlert['phone_numbers']);
$triggeredAlert['report_mediums'] = json_encode($triggeredAlert['report_mediums']);
$triggeredAlert['report_mediums'] = json_encode($triggeredAlert['report_mediums']);

$db = $this->getDb();
$db->insert(
Expand Down
2 changes: 2 additions & 0 deletions Notifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ public function sendNewAlerts($period, $idSite)
$this->sendAlertsPerSmsToRecipient($alerts, new \Piwik\Plugins\MobileMessaging\Model(), $phoneNumber);
}

Piwik::postEvent('CustomAlerts.sendNewAlerts', [$triggeredAlerts]);

foreach ($triggeredAlerts as $triggeredAlert) {
$this->markAlertAsSent($triggeredAlert);
}
Expand Down
2 changes: 2 additions & 0 deletions Updates/5.1.0.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ public function getMigrations(Updater $updater)
return array(
$this->migration->db->addColumn('alert', 'report_mediums', 'TEXT NOT NULL', 'report_matched'),
$this->migration->db->addColumn('alert_triggered', 'report_mediums', 'TEXT NOT NULL', 'report_matched'),
$this->migration->db->addColumn('alert', 'slack_channel_id', 'VARCHAR(50) NULL', 'phone_numbers'),
$this->migration->db->addColumn('alert_triggered', 'slack_channel_id', 'VARCHAR(50) NULL', 'phone_numbers'),
$this->migration->db->sql("UPDATE `$alertTableName` set report_mediums=CASE WHEN (email_me=1 OR additional_emails!='[]') AND phone_numbers!='[]' THEN '$emailPhoneJson' WHEN (email_me=1 OR additional_emails!='[]') AND phone_numbers='[]' THEN '$emailJson' WHEN (email_me!=1 AND additional_emails='[]') AND phone_numbers!='[]' THEN '$phoneJson' ELSE '$emptyJson' END"),
$this->migration->db->sql("UPDATE `$alertTriggeredTableName` set report_mediums=CASE WHEN (email_me=1 OR additional_emails!='[]') AND phone_numbers!='[]' THEN '$emailPhoneJson' WHEN (email_me=1 OR additional_emails!='[]') AND phone_numbers='[]' THEN '$emailJson' WHEN (email_me!=1 AND additional_emails='[]') AND phone_numbers!='[]' THEN '$phoneJson' ELSE '$emptyJson' END"),
);
Expand Down
7 changes: 4 additions & 3 deletions lang/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,12 @@
"FinalTaskRetryWarning": "Final retry of alerts task. Unable to process the following alerts: %1$s",
"MediumEmail": "Email",
"MediumMobile": "Mobile",
"MediumSlack": "Slack",
"MediumTitle": "Send alerts via",
"MediumDescription": "Select the medium to send alerts.",
"EmptyReportMediums": "Report mediums cannot be empty.",
"MediumDescription": "Choose how you want to receive alerts when this custom alert is triggered.",
"EmptyReportMediums": "At least one delivery method must be selected.",
"InvalidReportMediums": "Invalid report mediums value. Allowed values are %1$s.",
"InvalidEmailReportParameter": "Please select \"Send to me\" or specify valid email addresses to email the report.",
"InvalidPhoneNumberReportParameter": "Phone numbers cannot be empty."
"InvalidPhoneNumberReportParameter": "Phone numbers cannot be empty. Please activate at least one phone number by accessing the Mobile Messaging settings page."
}
}
2 changes: 1 addition & 1 deletion phpcs.xml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

<rule ref="Generic.Files.LineLength">
<properties>
<property name="lineLimit" value="260" />
<property name="lineLimit" value="300" />
</properties>
<exclude-pattern>tests/*</exclude-pattern>
</rule>
Expand Down
1 change: 1 addition & 0 deletions templates/form.twig
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
supports-s-m-s="{{ supportsSMS|default(null)|json_encode }}"
mobile-macro="{{ mobileMacro|default(null)|json_encode }}"
phone-numbers="{{ phoneNumbers|default([])|json_encode }}"
is-slack-oauth-token-added="{{ isSlackOAuthTokenAdded|default(null)|json_encode }}"
report-metadata="{{ reportMetadata|default(null)|json_encode }}"
alert-group-conditions="{{ alertGroupConditions|default(null)|json_encode }}"
metric-condition-options="{{ metricConditionOptions|default(null)|json_encode }}"
Expand Down
2 changes: 1 addition & 1 deletion tests/Fixtures/CustomAlerts.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ private function createAlert($name, $period, $idSites, $metric, $report, $login
}

$model = new Model();
$model->createAlert($name, $idSites, $login, $period, 0, $emails, $phoneNumbers, $metric, 'less_than', 5, $comparedTo = 1, $report, 'matches_exactly', $reportMatched, ['email', 'mobile']);
$model->createAlert($name, $idSites, $login, $period, 0, $emails, $phoneNumbers, $metric, 'less_than', 5, $comparedTo = 1, $report, 'matches_exactly', $reportMatched, ['email', 'mobile'], '');
}

private function triggerAlert($idAlert, $valueNew, $valueOld, $datetime)
Expand Down
5 changes: 4 additions & 1 deletion tests/Integration/ApiTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ protected function createAlert(
$report,
$reportCondition,
'Piwik',
['email', 'mobile']
['email', 'mobile'],
''
);
return $id;
}
Expand Down Expand Up @@ -225,6 +226,7 @@ protected function assertIsAlert(
'email_me' => 0,
'additional_emails' => array('test1@example.com', 'test2@example.com'),
'phone_numbers' => array(),
'slack_channel_id' => '',
'compared_to' => 1,
'id_sites' => $idSites,
'report_mediums' => ['email', 'mobile']
Expand Down Expand Up @@ -580,6 +582,7 @@ public function test_triggerAlert_getTriggeredAlertsForPeriod_ShouldMarkAlertAsT
'value_old' => 48,
'additional_emails' => array('test1@example.com', 'test2@example.com'),
'phone_numbers' => array(),
'slack_channel_id' => '',
'email_me' => 0,
'compared_to' => 1,
'id_sites' => array(1, 2),
Expand Down
5 changes: 4 additions & 1 deletion tests/Integration/CustomAlertsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,8 @@ private function createAlert($name, $phoneNumbers, $idSites = array(1), $login =
$report,
'matches_exactly',
'Piwik',
$mediums
$mediums,
''
);

return $this->model->getAlert($id);
Expand Down Expand Up @@ -275,6 +276,7 @@ public function testGetReportMediumOptions()
$this->assertEquals([
['key' => 'email', 'value' => 'CustomAlerts_MediumEmail', 'disabled' => false],
['key' => 'mobile', 'value' => 'CustomAlerts_MediumMobile', 'disabled' => false],
['key' => 'slack', 'value' => 'CustomAlerts_MediumSlack', 'disabled' => true],
], CustomAlerts::getReportMediumOptions());
}

Expand All @@ -284,6 +286,7 @@ public function testGetReportMediumOptionsWhenMobileMessagingPluginDisabled()
$this->assertEquals([
['key' => 'email', 'value' => 'CustomAlerts_MediumEmail', 'disabled' => false],
['key' => 'mobile', 'value' => 'CustomAlerts_MediumMobile', 'disabled' => true],
['key' => 'slack', 'value' => 'CustomAlerts_MediumSlack', 'disabled' => true],
], CustomAlerts::getReportMediumOptions());
}
}
Loading