Start working on tasks feature

This commit is contained in:
Bernd Bestel 2018-09-22 22:01:32 +02:00
parent bcb359e317
commit 6fe0100927
No known key found for this signature in database
GPG Key ID: 71BD34C0D4891300
13 changed files with 477 additions and 2 deletions

View File

@ -0,0 +1,21 @@
<?php
namespace Grocy\Controllers;
use \Grocy\Services\TasksService;
class TasksApiController extends BaseApiController
{
public function __construct(\Slim\Container $container)
{
parent::__construct($container);
$this->TasksService = new TasksService();
}
protected $TasksService;
public function Current(\Slim\Http\Request $request, \Slim\Http\Response $response, array $args)
{
return $this->ApiResponse($this->TasksService->GetCurrent());
}
}

View File

@ -0,0 +1,43 @@
<?php
namespace Grocy\Controllers;
use \Grocy\Services\TasksService;
class TasksController extends BaseController
{
public function __construct(\Slim\Container $container)
{
parent::__construct($container);
$this->TasksService = new TasksService();
}
protected $TasksService;
public function Overview(\Slim\Http\Request $request, \Slim\Http\Response $response, array $args)
{
return $this->AppContainer->view->render($response, 'tasks', [
'tasks' => $this->Database->tasks()->orderBy('name'),
'nextXDays' => 5
]);
}
public function TaskEditForm(\Slim\Http\Request $request, \Slim\Http\Response $response, array $args)
{
if ($args['taskdId'] == 'new')
{
return $this->AppContainer->view->render($response, 'taskform', [
'mode' => 'create',
'taskCategories' => $this->Database->task_categories()->orderBy('name')
]);
}
else
{
return $this->AppContainer->view->render($response, 'taskform', [
'task' => $this->Database->tasks($args['taskId']),
'mode' => 'edit',
'taskCategories' => $this->Database->task_categories()->orderBy('name')
]);
}
}
}

View File

@ -1278,6 +1278,29 @@
}
}
}
},
"/tasks/get-current": {
"get": {
"description": "Returns all tasks which are not done yet",
"tags": [
"Tasks"
],
"responses": {
"200": {
"description": "An array of Task objects",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Task"
}
}
}
}
}
}
}
}
},
"components": {
@ -1292,7 +1315,8 @@
"quantity_units",
"shopping_list",
"recipes",
"recipes_pos"
"recipes_pos",
"tasks"
]
},
"StockTransactionType": {
@ -1898,6 +1922,25 @@
}
}
}
},
"Task": {
"type": "object",
"properties": {
"id": {
"type": "integer"
},
"name": {
"type": "string"
},
"due": {
"type": "string",
"format": "date-time"
},
"row_created_timestamp": {
"type": "string",
"format": "date-time"
}
}
}
},
"examples": {

24
migrations/0036.sql Normal file
View File

@ -0,0 +1,24 @@
CREATE TABLE tasks (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT NOT NULL UNIQUE,
description TEXT,
due DATETIME,
started TINYINT NOT NULL DEFAULT 0 CHECK(started IN (0, 1)),
done TINYINT NOT NULL DEFAULT 0 CHECK(done IN (0, 1)),
category_id INTEGER,
row_created_timestamp DATETIME DEFAULT (datetime('now', 'localtime'))
);
CREATE TABLE task_categories (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
name TEXT NOT NULL UNIQUE,
description TEXT,
row_created_timestamp DATETIME DEFAULT (datetime('now', 'localtime'))
);
CREATE VIEW tasks_current
AS
SELECT *
FROM tasks
WHERE due IS NULL
OR (due IS NOT NULL AND due > datetime('now', 'localtime'));

55
public/viewjs/taskform.js Normal file
View File

@ -0,0 +1,55 @@
$('#save-task-button').on('click', function(e)
{
e.preventDefault();
if (Grocy.EditMode === 'create')
{
Grocy.Api.Post('add-object/tasks', $('#task-form').serializeJSON(),
function(result)
{
window.location.href = U('/tasks');
},
function(xhr)
{
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
else
{
Grocy.Api.Post('edit-object/tasks/' + Grocy.EditObjectId, $('#task-form').serializeJSON(),
function(result)
{
window.location.href = U('/tasks');
},
function(xhr)
{
Grocy.FrontendHelpers.ShowGenericError('Error while saving, probably this item already exists', xhr.response)
}
);
}
});
$('#task-form input').keyup(function (event)
{
Grocy.FrontendHelpers.ValidateForm('task-form');
});
$('#task-form input').keydown(function (event)
{
if (event.keyCode === 13) //Enter
{
if (document.getElementById('task-form').checkValidity() === false) //There is at least one validation error
{
event.preventDefault();
return false;
}
else
{
$('#save-task-button').click();
}
}
});
$('#name').focus();
Grocy.FrontendHelpers.ValidateForm('task-form');

121
public/viewjs/tasks.js Normal file
View File

@ -0,0 +1,121 @@
var tasksTable = $('#tasks-table').DataTable({
'paginate': false,
'order': [[2, 'desc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 }
],
'language': JSON.parse(L('datatables_localization')),
'scrollY': false,
'colReorder': true,
'stateSave': true,
'stateSaveParams': function(settings, data)
{
data.search.search = "";
}
});
$("#search").on("keyup", function()
{
var value = $(this).val();
if (value === "all")
{
value = "";
}
tasksTable.search(value).draw();
});
$(document).on('click', '.do-task-button', function(e)
{
var taskId = $(e.currentTarget).attr('data-task-id');
var doneTime = moment().format('YYYY-MM-DD HH:mm:ss');
Grocy.Api.Get('tasks/track-task-execution/' + taskId + '?tracked_time=' + trackedTime,
function()
{
Grocy.Api.Get('tasks/get-task-details/' + taskId,
function(result)
{
var taskRow = $('#task-' + taskId + '-row');
var nextXDaysThreshold = moment().add($("#info-due-tasks").data("next-x-days"), "days");
var now = moment();
var nextExecutionTime = moment(result.next_estimated_execution_time);
taskRow.removeClass("table-warning");
taskRow.removeClass("table-danger");
if (nextExecutionTime.isBefore(now))
{
taskRow.addClass("table-danger");
}
else if (nextExecutionTime.isBefore(nextXDaysThreshold))
{
taskRow.addClass("table-warning");
}
$('#task-' + taskId + '-last-tracked-time').parent().effect('highlight', { }, 500);
$('#task-' + taskId + '-last-tracked-time').fadeOut(500, function()
{
$(this).text(trackedTime).fadeIn(500);
});
$('#task-' + taskId + '-last-tracked-time-timeago').attr('datetime', trackedTime);
if (result.task.period_type == "dynamic-regular")
{
$('#task-' + taskId + '-next-execution-time').parent().effect('highlight', { }, 500);
$('#task-' + taskId + '-next-execution-time').fadeOut(500, function()
{
$(this).text(result.next_estimated_execution_time).fadeIn(500);
});
$('#task-' + taskId + '-next-execution-time-timeago').attr('datetime', result.next_estimated_execution_time);
}
toastr.success(L('Tracked execution of task #1 on #2', taskName, trackedTime));
RefreshContextualTimeago();
RefreshStatistics();
},
function(xhr)
{
console.error(xhr);
}
);
},
function(xhr)
{
console.error(xhr);
}
);
});
function RefreshStatistics()
{
var nextXDays = $("#info-due-tasks").data("next-x-days");
Grocy.Api.Get('tasks/get-current',
function(result)
{
var dueCount = 0;
var overdueCount = 0;
var now = moment();
var nextXDaysThreshold = moment().add(nextXDays, "days");
result.forEach(element => {
var date = moment(element.due);
if (date.isBefore(now))
{
overdueCount++;
}
else if (date.isBefore(nextXDaysThreshold))
{
dueCount++;
}
});
$("#info-due-tasks").text(Pluralize(dueCount, L('#1 task is due to be done within the next #2 days', dueCount, nextXDays), L('#1 tasks are due to be done within the next #2 days', dueCount, nextXDays)));
$("#info-overdue-tasks").text(Pluralize(overdueCount, L('#1 task is overdue to be done', overdueCount), L('#1 tasks are overdue to be done', overdueCount)));
},
function(xhr)
{
console.error(xhr);
}
);
}
RefreshStatistics();

View File

@ -53,6 +53,10 @@ $app->group('', function()
$this->get('/batteries', '\Grocy\Controllers\BatteriesController:BatteriesList');
$this->get('/battery/{batteryId}', '\Grocy\Controllers\BatteriesController:BatteryEditForm');
// Task routes
$this->get('/tasks', '\Grocy\Controllers\TasksController:Overview');
$this->get('/task/{taskId}', '\Grocy\Controllers\TasksController:TaskEditForm');
// OpenAPI routes
$this->get('/api', '\Grocy\Controllers\OpenApiController:DocumentationUi');
$this->get('/manageapikeys', '\Grocy\Controllers\OpenApiController:ApiKeysList');
@ -102,6 +106,9 @@ $app->group('/api', function()
$this->get('/batteries/track-charge-cycle/{batteryId}', '\Grocy\Controllers\BatteriesApiController:TrackChargeCycle');
$this->get('/batteries/get-battery-details/{batteryId}', '\Grocy\Controllers\BatteriesApiController:BatteryDetails');
$this->get('/batteries/get-current', '\Grocy\Controllers\BatteriesApiController:Current');
// Tasks
$this->get('/tasks/get-current', '\Grocy\Controllers\TasksApiController:Current');
})->add(new ApiKeyAuthMiddleware($appContainer, $appContainer->LoginControllerInstance->GetSessionCookieName(), $appContainer->ApiKeyHeaderName))
->add(JsonMiddleware::class)
->add(new CorsMiddleware([

View File

@ -87,6 +87,12 @@ class DemoDataGeneratorService extends BaseService
INSERT INTO batteries (name, description, used_in, charge_interval_days) VALUES ('{$localizationService->Localize('Battery')}3', '{$localizationService->Localize('Warranty ends')} 2022', '{$localizationService->Localize('Heat remote control')}', 60); --3
INSERT INTO batteries (name, description, used_in, charge_interval_days) VALUES ('{$localizationService->Localize('Battery')}4', '{$localizationService->Localize('Warranty ends')} 2028', '{$localizationService->Localize('Heat remote control')}', 60); --4
INSERT INTO task_categories (name) VALUES ('{$localizationService->Localize('Home')}'); --1
INSERT INTO task_categories (name) VALUES ('{$localizationService->Localize('Life')}'); --2
INSERT INTO task_categories (name) VALUES ('{$localizationService->Localize('Projects')}'); --3
INSERT INTO tasks (name, category_id, due) VALUES ('{$localizationService->Localize('Repair the garage door')}', 1, date(datetime('now', 'localtime'), '+14 day'));
INSERT INTO migrations (migration) VALUES (-1);
";

18
services/TasksService.php Normal file
View File

@ -0,0 +1,18 @@
<?php
namespace Grocy\Services;
class TasksService extends BaseService
{
public function GetCurrent()
{
$sql = 'SELECT * from tasks_current';
return $this->DatabaseService->ExecuteDbQuery($sql)->fetchAll(\PDO::FETCH_OBJ);
}
private function TaskExists($taskId)
{
$taskRow = $this->Database->tasks()->where('id = :1', $taskId)->fetch();
return $taskRow !== null;
}
}

View File

@ -2,11 +2,13 @@
<script src="{{ $U('/viewjs/components/datetimepicker.js', true) }}?v={{ $version }}"></script>
@endpush
@php if(!isset($isRequired)) { $isRequired = true; } @endphp
<div class="form-group">
<label for="{{ $id }}">{{ $L($label) }} <span class="small text-muted"><time id="datetimepicker-timeago" class="timeago timeago-contextual"></time>@if(!empty($hint))<br>{{ $L($hint) }}@endif</span></label>
<div class="input-group">
<div class="input-group date datetimepicker @if(!empty($additionalCssClasses)){{ $additionalCssClasses }}@endif" id="{{ $id }}" data-target-input="nearest">
<input type="text" required class="form-control datetimepicker-input"
<input type="text" @if($isRequired) required @endif class="form-control datetimepicker-input"
data-target="#{{ $id }}" data-format="{{ $format }}"
data-init-with-now="{{ BoolToString($initWithNow) }}"
data-limit-end-to-now="{{ BoolToString($limitEndToNow) }}"

View File

@ -84,6 +84,12 @@
<span class="nav-link-text">{{ $L('Recipes') }}</span>
</a>
</li>
<li class="nav-item" data-toggle="tooltip" data-placement="right" title="{{ $L('Tasks') }}" data-nav-for-page="tasks">
<a class="nav-link discrete-link" href="{{ $U('/tasks') }}">
<i class="fas fa-tasks"></i>
<span class="nav-link-text">{{ $L('Tasks') }}</span>
</a>
</li>
<li class="nav-item mt-4" data-toggle="tooltip" data-placement="right" title="{{ $L('Purchase') }}" data-nav-for-page="purchase">
<a class="nav-link discrete-link" href="{{ $U('/purchase') }}">

63
views/taskform.blade.php Normal file
View File

@ -0,0 +1,63 @@
@extends('layout.default')
@if($mode == 'edit')
@section('title', $L('Edit task'))
@else
@section('title', $L('Create task'))
@endif
@section('viewJsName', 'taskform')
@section('content')
<div class="row">
<div class="col-lg-6 col-xs-12">
<h1>@yield('title')</h1>
<script>Grocy.EditMode = '{{ $mode }}';</script>
@if($mode == 'edit')
<script>Grocy.EditObjectId = {{ $task->id }};</script>
@endif
<form id="task-form" novalidate>
<div class="form-group">
<label for="name">{{ $L('Name') }}</label>
<input type="text" class="form-control" required id="name" name="name" value="@if($mode == 'edit'){{ $task->name }}@endif">
<div class="invalid-feedback">{{ $L('A name is required') }}</div>
</div>
<div class="form-group">
<label for="description">{{ $L('Description') }}</label>
<textarea class="form-control" rows="2" id="description" name="description">@if($mode == 'edit'){{ $task->description }}@endif</textarea>
</div>
@include('components.datetimepicker', array(
'id' => 'due',
'label' => 'Due',
'format' => 'YYYY-MM-DD',
'initWithNow' => false,
'limitEndToNow' => false,
'limitStartToNow' => false,
'invalidFeedback' => $L('A due dat is required'),
'nextInputSelector' => '',
'additionalCssClasses' => 'date-only-datetimepicker',
'isRequired' => false
))
<div class="form-group">
<label for="category_id">{{ $L('Category') }}</label>
<select class="form-control" id="category_id" name="category_id">
<option></option>
@foreach($taskCategories as $taskCategory)
<option @if($mode == 'edit' && $taskCategory->id == $task->category_id) selected="selected" @endif value="{{ $taskCategory->id }}">{{ $taskCategory->name }}</option>
@endforeach
</select>
</div>
<button id="save-task-button" type="submit" class="btn btn-success">{{ $L('Save') }}</button>
</form>
</div>
</div>
@stop

66
views/tasks.blade.php Normal file
View File

@ -0,0 +1,66 @@
@extends('layout.default')
@section('title', $L('Tasks'))
@section('activeNav', 'tasks')
@section('viewJsName', 'tasks')
@push('pageScripts')
<script src="{{ $U('/node_modules/jquery-ui-dist/jquery-ui.min.js?v=', true) }}{{ $version }}"></script>
@endpush
@section('content')
<div class="row">
<div class="col">
<h1>@yield('title')</h1>
<p id="info-due-tasks" data-next-x-days="{{ $nextXDays }}" class="btn btn-lg btn-warning no-real-button responsive-button mr-2"></p>
<p id="info-overdue-tasks" class="btn btn-lg btn-danger no-real-button responsive-button"></p>
</div>
</div>
<div class="row mt-3">
<div class="col-xs-12 col-md-6 col-xl-3">
<label for="search">{{ $L('Search') }}</label> <i class="fas fa-search"></i>
<input type="text" class="form-control" id="search">
</div>
</div>
<div class="row">
<div class="col">
<table id="tasks-table" class="table table-sm table-striped dt-responsive">
<thead>
<tr>
<th>#</th>
<th>{{ $L('Aufgabe') }}</th>
<th>{{ $L('Due') }}</th>
</tr>
</thead>
<tbody>
@foreach($tasks as $task)
<tr id="task-{{ $task->id }}-row" class="@if($task->due < date('Y-m-d H:i:s')) table-danger @elseif($task->due < date('Y-m-d H:i:s', strtotime("+$nextXDays days"))) table-warning @endif">
<td class="fit-content">
<a class="btn btn-success btn-sm do-task-button" href="#" data-toggle="tooltip" title="{{ $L('Mark task "#1" as completed', $task->name) }}"
data-task-id="{{ $task->id }}">
<i class="fas fa-check"></i>
</a>
<a class="btn btn-success btn-sm start-task-button" href="#" data-toggle="tooltip" title="{{ $L('Start task "#1"', $task->name) }}"
data-task-id="{{ $task->id }}">
<i class="fas fa-play"></i>
</a>
<a class="btn btn-info btn-sm" href="{{ $U('/task/') }}{{ $task->id }}">
<i class="fas fa-edit"></i>
</a>
</td>
<td>
{{ $task->name }}
</td>
<td>
<span>{{ $task->due }}</span>
<time class="timeago timeago-contextual" datetime="{{ $task->due }}"></time>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
@stop