Skip to content

Commit

Permalink
Add function to reset database readings
Browse files Browse the repository at this point in the history
  • Loading branch information
K-Ko committed Aug 6, 2016
1 parent 04fc8b7 commit bdee90b
Show file tree
Hide file tree
Showing 7 changed files with 189 additions and 18 deletions.
88 changes: 71 additions & 17 deletions api/r6/routes/data.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,12 @@
/**
*
*/
$api->put('/data/:guid', $APIkeyRequired, function($guid) use ($api) {

$request = json_decode($api->request->getBody(), TRUE);
$api->put(
'/data/:guid',
$APIkeyRequired,
function($guid) use ($api)
{
$request = json_decode($api->request->getBody(), true);

// Check request for 'timestamp' attribute, take as is if numeric,
// otherwise convert datetime to timestamp
Expand All @@ -31,11 +34,10 @@
}

if ($cnt) $api->stopAPI($cnt.' reading(s) added', 201);

})->name('PUT /data/:guid')->help = array(
'since' => 'r2',
'description' => 'Save a reading value',
'apikey' => TRUE,
'apikey' => true,
'payload' => array(
'{"data":"<value>"}' => 'JSON encoded value, use server time',
'{"data":"<value>","timestamp":"<timestamp>"}' => 'JSON encoded value, use provided timestamp',
Expand All @@ -46,8 +48,12 @@
/**
*
*/
$api->post('/data/:guid', $APIkeyRequired, function($guid) use ($api) {
$request = json_decode($api->request->getBody(), TRUE);
$api->post(
'/data/:guid',
$APIkeyRequired,
function($guid) use ($api)
{
$request = json_decode($api->request->getBody(), true);
// Check request for 'value' attribute
if (!isset($request['data'])) $api->stopAPI('Data required for data update', 400);
// Check request for 'timestamp' attribute, take as is if numeric,
Expand All @@ -57,36 +63,43 @@
? $request['timestamp']
: strtotime($request['timestamp'])
)
: FALSE;
: false;
if (!$timestamp) $api->stopAPI('Timestamp required for data update', 400);
if (!Channel::byGUID($guid)->update($request, $timestamp)) {
$api->stopAPI('Invalid data', 405);
}
})->name('POST /data/:guid')->help = array(
'since' => 'r4',
'description' => 'Update a reading value, timestamp is required here',
'apikey' => TRUE,
'apikey' => true,
'payload' => array('{"data":"<value>","timestamp":"<timestamp>"}' => 'JSON encoded value'),
);

/**
*
*/
$api->put('/data/raw/:guid', $APIkeyRequired, function($guid) use ($api) {
$api->put(
'/data/raw/:guid',
$APIkeyRequired,
function($guid) use ($api)
{
// Channel handles raw data
$cnt = Channel::byGUID($guid)->write($api->request->getBody());
if ($cnt) $api->stopAPI($cnt.' reading(s) added', 201);
})->name('PUT /data/raw/:guid')->help = array(
'since' => 'r4',
'description' => 'Save raw data, channel decide what to do with them',
'apikey' => TRUE,
'apikey' => true,
'payload' => array('raw data in any format' => 'Channel have to handle it'),
);

/**
*
*/
$api->get('/data/:period/:guid', $accessibleChannel, function($period, $guid) use ($api)
$api->get(
'/data/:period/:guid',
$accessibleChannel,
function($period, $guid) use ($api)
{
$request = $api->request->get();
$request['period'] = $period;
Expand Down Expand Up @@ -117,7 +130,10 @@
/**
*
*/
$api->get('/data/:guid(/:p1(/:p2))', $accessibleChannel, function($guid, $p1='', $p2='') use ($api)
$api->get(
'/data/:guid(/:p1(/:p2))',
$accessibleChannel,
function($guid, $p1='', $p2='') use ($api)
{
$request = $api->request->get();
$request['p1'] = $p1;
Expand Down Expand Up @@ -182,7 +198,9 @@
/**
*
*/
$api->get('/data/actual/:guid+', function($guid) use ($api)
$api->get(
'/data/actual/:guid+',
function($guid) use ($api)
{
$guids = $guid;
$request = $api->request->get();
Expand Down Expand Up @@ -230,7 +248,10 @@
/**
*
*/
$api->get('/data/stats', function() use ($api) {
$api->get(
'/data/stats',
function() use ($api)
{
$api->render($api->db->queryRowsArray(
'SELECT c.`guid`, c.`name`, c.`description`, c.`numeric`, c.`decimals`,
t.*, IFNULL(n.`data`, s.`data`) AS `data`
Expand All @@ -248,7 +269,11 @@
/**
*
*/
$api->delete('/data/:guid/:timestamp', $APIkeyRequired, function($guid, $timestamp) use ($api) {
$api->delete(
'/data/:guid/:timestamp',
$APIkeyRequired,
function($guid, $timestamp) use ($api)
{
$channel = Channel::byGUID($guid);
$tbl = $channel->numeric ? new \ORM\ReadingNum : new \ORM\ReadingStr;
if ($tbl->filterByIdTimestamp($channel->entity, $timestamp)->findOne()->getId()) {
Expand All @@ -260,5 +285,34 @@
})->name('DELETE /data/:guid/:timestamp')->help = array(
'since' => 'r2',
'description' => 'Delete a reading value',
'apikey' => TRUE,
'apikey' => true,
);

/**
* Undocumented
*/
$api->delete(
'/data',
$APIkeyRequired,
function() use ($api)
{
if (!\ORM\Settings::getCoreValue(null, 'EmptyDatabaseAllowed')) {
$api->stopAPI('Delete all data is not allowed, '
.'change the "Empty database allowed" flag first!');
}

$tables = array(
'pvlng_reading_last',
'pvlng_reading_num', 'pvlng_reading_str',
'pvlng_reading_num_tmp', 'pvlng_reading_str_tmp',
'pvlng_reading_num_calc', 'pvlng_reading_tmp'
);

foreach ($tables as $table) {
$api->db->truncate($table);
}

\ORM\Settings::setCoreValue(null, 'EmptyDatabaseAllowed', 0);

$api->stopAPI('All data deleted', 200);
});
20 changes: 20 additions & 0 deletions core/ORM/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,14 @@ public static function getCoreValue($name, $key, $default=null)
return self::getScopeValue('core', $name, $key, $default);
}

/**
*
*/
public static function setCoreValue($name, $key, $value)
{
return self::setScopeValue('core', $name, $key, $value);
}

/**
*
*/
Expand Down Expand Up @@ -104,4 +112,16 @@ protected static function getScopeValue($scope, $name, $key, $default=null)
return $self->getKey() ? $self->getValue() : $default;
}

/**
*
*/
protected static function setScopeValue($scope, $name, $key, $value)
{
$self = new self;
$self->filterByScopeNameKey($scope, $name, $key)->findOne();
if ($self->getKey()) {
return $self->setValue($value)->update();
}
}

}
6 changes: 5 additions & 1 deletion frontend/View/Settings/content.scope.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
<div class="grid_5 omega">
<!-- IF {VAR} == "core--Password" -->
<input id="p1" type="password" name="d[p1]">
<small style="margin-left:1em">Fill only to change it!</small>
&nbsp; &nbsp; Fill only to change it!
<br />
<input id="p2" type="password" name="d[p2]" style="margin-top:.5em">
<!-- ELSEIF {TYPE} == "num" -->
Expand All @@ -43,6 +43,10 @@
<!-- ELSE -->
<input id="{VAR}" type="text" name="d[{VAR}]" value="{VALUE}" style="width:100%">
<!-- ENDIF -->

<!-- IF {VAR} == "core--EmptyDatabaseAllowed" && {VALUE} -->
&nbsp; &nbsp; <button id="empty-database">Delete all data</button>
<!-- ENDIF -->
</div>

<div class="clear"></div>
Expand Down
66 changes: 66 additions & 0 deletions frontend/View/Settings/script.js.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<script>
/**
*
*
* @author Knut Kohl <[email protected]>
* @copyright 2012-2016 Knut Kohl
* @license MIT License (MIT) http://opensource.org/licenses/MIT
* @version 1.0.0
*/

var resetTimer;

/**
*
*/
function resetDeleteButton() {
var b = $('#empty-database'), s = $('span', b);
b.removeClass('confirm');
s.text(s.data('text'));
$.wait(false);
}

/**
*
*/
$(function() {

$('#empty-database').on('click', function(event) {

var b = $(this), s = $('span', b);

if (!b.hasClass('confirm')) {

s.data('text', s.text()).text('Click again if you are ABSOLUTELY sure ...');
b.addClass('confirm');
resetTimer = setTimeout(resetDeleteButton, 8000);

} else {

clearTimeout(resetTimer);

$.wait();

$.ajax({
type: 'DELETE',
url: PVLngAPI + 'data',
dataType: 'json',
}).done(function(data, textStatus, jqXHR) {
$('[name="d[core--EmptyDatabaseAllowed]"]').val(0).change();
b.replaceWith('<strong>'+data.message+'</strong>');
}).fail(function(jqXHR, textStatus, errorThrown) {
$.pnotify({
type: textStatus, hide: false, text: jqXHR.responseJSON.message
});
}).always(function() {
resetDeleteButton();
});

}

event.preventDefault();
});

});

</script>
5 changes: 5 additions & 0 deletions frontend/View/Settings/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,8 @@
margin-left: 1em;
display: block;
}

#empty-database.confirm .ui-button-text {
color: red;
font-weight: bold;
}
11 changes: 11 additions & 0 deletions lib/slimMVC/MySQLi.php
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,17 @@ public function queryCol( $query ) {
return $rows;
}

/**
*
*/
public function truncate( $table, $optimize=true ) {
$rc = $this->query('TRUNCATE `{1}`', $table);
if ($optimize) {
$rc += $this->query('OPTIMIZE `{1}`', $table);
}
return $rc;
}

/**
*
*/
Expand Down
11 changes: 11 additions & 0 deletions sql/patches/004.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
INSERT INTO `pvlng_settings`
(`scope`, `name`, `key`, `value`, `order`, `description`, `type`, `data`)
VALUES
('core', '', 'EmptyDatabaseAllowed', '0', 100, 'Enable function for deletion of all measuring data from database.<br>Channels and channel hierarchy will <strong>not</strong> be deleted!<br><strong style=\"color:red\">Only if this is allowed, the deletion is possible!</strong>', 'bool', '');

UPDATE `pvlng_type` SET `unit` = '', `icon` = '/images/ico/calculator_scientific.png' WHERE `id` = 15;

INSERT INTO `pvlng_type`
(`id`, `name`, `description`, `model`, `unit`, `type`, `childs`, `read`, `write`, `graph`, `icon`)
VALUES
(33, 'Percentage calculator', 'model::Ratio', 'Ratio', '%', 'sensor', 2, 1, 0, 1, '/images/ico/edit_percent.png');

0 comments on commit bdee90b

Please sign in to comment.