Commit abc2ddb4 by Daniel Barker

Task Items testing mode/filters, TMS Find Task form, Time Entry details

Task Items
- Testing Mode checkbox: Testing Items shows every column, Task Items hides App, Version, Date and Testing Status. Kept until logout. Task Items button from emT3 opens list in Testing Mode
- Added filtering functionality. My Open Items / All Items / Filters. Filters button opens offcanvas with additional filtering options.
- New Task Item Status column (ITEM_STATUS, codes STATUS); Testing Status now saves STATUS2 codes and displays descriptions. New rows default to OPEN.
- Assigned saves a USER_ID chosen from users employed during the task's dates ("First L."); validated on save.
- Version is now a managed list from the project's existing versions (RenameVersionName / DeleteVersionName).

Time Entries
- Compact View checkbox hides Time and Place; saved per user (users.HIDE_TIME_ENTRIES_FIELDS via SetHideTimeEntriesFields).
- Details button per row edits time_items.DETAILS in an offcanvas.
- Summary limited to 500 characters with inline notices.
- Hours required, zero allowed, negative rejected.
- All focused tasks listed; date problems checked before save via GetTimeEntryDateProblem and shown under the Task field. Date rule now includes the project's start/end dates.

Find Task
- Replace uTaskPickerOffCanvas with the View.TaskPicker TMS popup form.
- All / My / Focused task filter (GetTaskPickerProjects taskFilter).
- Lists every task in the project; unavailable ones show why and can't be selected.
- Footer End Date; SetTaskStatus -> SetTaskStatusAndEndDate (Closed/Complete require an End Date, not before the task's start date).
parent dd94c9fb
......@@ -14,6 +14,7 @@ emT3XDataServer/Source/__history/
emT3XDataServer/Source/__recovery/
emT3XDataServer/Win32/
.validation/
.claude/
*.exe
*.local
......
......@@ -172,6 +172,7 @@ procedure TAuthService.Logout;
begin
DeleteToken;
DMConnection.currentTaskId := '';
DMConnection.taskItemsTestingMode := False;
DMConnection.timeEntriesWeekOf := '';
DMConnection.timeEntriesStartDate := '';
DMConnection.timeEntriesEndDate := '';
......
......@@ -21,6 +21,10 @@ type
public
currentTaskId: string;
// Task Items view: True = Testing Items mode (every column), False = Task Items mode
// (App, Version, Date and Testing Status hidden). Set by the screen's Testing Mode
// checkbox and kept until logout or refresh; a direct task_id link always opens in Testing mode.
taskItemsTestingMode: Boolean;
// Time Entries range saved when a row opens Task Items, restored by Back ('' = none)
timeEntriesWeekOf: string;
timeEntriesStartDate: string;
......
......@@ -27,6 +27,7 @@ type
public
class procedure Display(logoutProc: TLogoutProc);
procedure ShowTaskItems(const ATaskId: string);
procedure SetTaskItemsTitle(const ATestingMode: Boolean);
procedure ShowTimeEntries;
end;
......@@ -62,7 +63,8 @@ begin
end
else
begin
lblAppTitle.Caption := 'Task Items';
// A direct task_id link opens Task Items in Testing mode
SetTaskItemsTitle(True);
ShowForm(TFTaskItems);
end;
end;
......@@ -80,14 +82,24 @@ begin
Application.CreateForm(aFormClass, pnlMain.ElementID, FChildForm);
end;
// Opened from a Time Entries row; the URL is left as-is, so a refresh lands back on Time Entries
// Opened from a Time Entries row; the URL is left as-is, so a refresh lands back on Time Entries.
// Opens in the mode last picked with the screen's Testing Mode checkbox (Task Items at first).
procedure TFViewMain.ShowTaskItems(const ATaskId: string);
begin
DMConnection.currentTaskId := ATaskId;
lblAppTitle.Caption := 'Task Items';
SetTaskItemsTitle(DMConnection.taskItemsTestingMode);
ShowForm(TFTaskItems);
end;
// Page title for the Task Items screen's mode; also called when its Testing Mode checkbox changes
procedure TFViewMain.SetTaskItemsTitle(const ATestingMode: Boolean);
begin
if ATestingMode then
lblAppTitle.Caption := 'Testing Items'
else
lblAppTitle.Caption := 'Task Items';
end;
procedure TFViewMain.ShowTimeEntries;
begin
DMConnection.currentTaskId := '';
......
......@@ -70,6 +70,42 @@ object FTaskItems: TFTaskItems
WidthPercent = 100.000000000000000000
OnClick = btnInsertRowClick
end
object btnMyOpenItems: TWebButton
Left = 438
Top = 88
Width = 96
Height = 25
Caption = 'My Open Items'
ElementID = 'btn_my_open_items'
ElementFont = efCSS
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnClick = btnMyOpenItemsClick
end
object btnAllItems: TWebButton
Left = 438
Top = 119
Width = 96
Height = 25
Caption = 'All Items'
ElementID = 'btn_all_items'
ElementFont = efCSS
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnClick = btnAllItemsClick
end
object btnFilters: TWebButton
Left = 438
Top = 150
Width = 96
Height = 25
Caption = 'Filters'
ElementID = 'btn_filters'
ElementFont = efCSS
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnClick = btnFiltersClick
end
object btnCopyRow: TWebButton
Left = 78
Top = 210
......@@ -168,9 +204,21 @@ object FTaskItems: TFTaskItems
object xdwdsTasksassignedTo: TStringField
FieldName = 'assignedTo'
end
object xdwdsTasksassignedToDesc: TStringField
FieldName = 'assignedToDesc'
end
object xdwdsTasksstatus: TStringField
FieldName = 'status'
end
object xdwdsTasksstatusDesc: TStringField
FieldName = 'statusDesc'
end
object xdwdsTasksitemStatus: TStringField
FieldName = 'itemStatus'
end
object xdwdsTasksitemStatusDesc: TStringField
FieldName = 'itemStatusDesc'
end
object xdwdsTasksstatusDate: TStringField
FieldName = 'statusDate'
end
......
......@@ -4,6 +4,18 @@
<h5 class="mb-0" id="lbl_project_name"></h5>
<div class="d-flex align-items-center gap-2 ms-auto flex-nowrap">
<!-- Checked = Testing Items mode (every column); unchecked = Task Items mode
(App, Version, Date and Testing Status hidden) -->
<div class="form-check mb-0 me-2 text-nowrap">
<input class="form-check-input" type="checkbox" id="chk_testing_items" />
<label class="form-check-label small" for="chk_testing_items"
title="Show the App, Version, Date and Testing Status columns">Testing Mode</label>
</div>
<button id="btn_my_open_items" type="button" class="btn btn-sm btn-outline-secondary text-nowrap">My Open Items</button>
<button id="btn_all_items" type="button" class="btn btn-sm btn-outline-secondary text-nowrap">All Items</button>
<button id="btn_filters" type="button" class="btn btn-sm btn-outline-secondary text-nowrap">Filters</button>
<div id="lbl_total_rows" class="me-2 text-nowrap"></div>
<div class="task-toolbar d-flex align-items-center gap-1 px-2 py-1">
......@@ -59,4 +71,26 @@
</button>
</div>
</div>
<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasFilters" aria-labelledby="flt_title">
<div class="offcanvas-header">
<h5 class="offcanvas-title" id="flt_title">Filters</h5>
<button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
</div>
<div class="offcanvas-body">
<h6>Assigned</h6>
<div id="flt_assigned_list" class="mb-3"></div>
<h6>Task Item Status</h6>
<div id="flt_item_status_list" class="mb-3"></div>
<div id="flt_status_wrap">
<h6>Testing Status</h6>
<div id="flt_status_list" class="mb-3"></div>
</div>
<button id="btn_flt_clear" type="button" class="btn btn-secondary">Clear Filters</button>
</div>
</div>
</div>
......@@ -20,7 +20,11 @@ type
xdwdsTaskstaskDate: TStringField;
xdwdsTasksreportedBy: TStringField;
xdwdsTasksassignedTo: TStringField;
xdwdsTasksassignedToDesc: TStringField;
xdwdsTasksstatus: TStringField;
xdwdsTasksstatusDesc: TStringField;
xdwdsTasksitemStatus: TStringField;
xdwdsTasksitemStatusDesc: TStringField;
xdwdsTasksstatusDate: TStringField;
xdwdsTasksformSection: TStringField;
xdwdsTasksissue: TStringField;
......@@ -37,6 +41,9 @@ type
btnFmtItalic: TWebButton;
btnFmtUnderline: TWebButton;
btnBack: TWebButton;
btnMyOpenItems: TWebButton;
btnAllItems: TWebButton;
btnFilters: TWebButton;
[async] procedure btnAddRowClick(Sender: TObject);
procedure btnReloadClick(Sender: TObject);
procedure WebFormCreate(Sender: TObject);
......@@ -48,12 +55,17 @@ type
procedure btnFmtItalicClick(Sender: TObject);
procedure btnFmtUnderlineClick(Sender: TObject);
procedure btnBackClick(Sender: TObject);
procedure btnMyOpenItemsClick(Sender: TObject);
procedure btnAllItemsClick(Sender: TObject);
procedure btnFiltersClick(Sender: TObject);
private
FTaskId: string;
FApplicationOptions: TJSArray;
FVersionOptions: TJSArray;
FReportedByOptions: TJSArray;
FAssignedToOptions: TJSArray;
FStatusOptions: TJSArray;
FItemStatusOptions: TJSArray;
FPendingFocusTaskItemId: integer;
FPendingFocusField: string;
FSelectedTaskItemId: Integer;
......@@ -66,7 +78,23 @@ type
FLastSelectionRange: JSValue;
FNameManager: TNameManager;
FCopyingRow: Boolean;
FTaskMode: Boolean;
FUserId: string;
// Selected filter values per column ('' list = no filter); FILTER_BLANK matches an empty value
FAssignedFilter: TJSArray;
FItemStatusFilter: TJSArray;
FStatusFilter: TJSArray;
[async] function CopyTaskRow: Boolean;
function FirstEditField: string;
procedure BindFilterControls;
procedure TestingItemsChanged(Event: TJSEvent);
procedure FillFilterLists;
procedure FilterCheckChange(Event: TJSEvent);
procedure FilterClearClick(Event: TJSEvent);
procedure ClearFilters;
procedure UpdateFilterSummary(const AGroup: string);
function RowMatchesFilters: Boolean;
function ActiveFilterCount: Integer;
[async] procedure LoadTasks(const ATaskId: string);
procedure RenderTable;
procedure BindTableEditors;
......@@ -76,7 +104,7 @@ type
procedure EnableAutoGrowTextAreas;
procedure GotoRowIndex(AIndex: Integer);
function HtmlEncode(const s: string): string;
procedure SetTotalRowsLabel(ARowCount: Integer);
procedure SetTotalRowsLabel(AShownCount, ATotalCount: Integer);
procedure SetTaskLabel(const ATitle: string);
[async] procedure SaveField(AIndex: Integer; const AFieldName: string);
procedure EditorBlur(Event: TJSEvent);
......@@ -94,15 +122,15 @@ type
procedure EditorKeyDown(Event: TJSEvent);
procedure CaptureTableScroll;
procedure RestoreTableScroll;
[async] function AddAssignedName(const AName: string): TJSArray;
[async] function RenameAssignedName(const AOldName, ANewName: string): TJSArray;
[async] function DeleteAssignedName(const AName: string): TJSArray;
[async] function AddReportedName(const AName: string): TJSArray;
[async] function RenameReportedName(const AOldName, ANewName: string): TJSArray;
[async] function DeleteReportedName(const AName: string): TJSArray;
[async] function AddApplicationName(const AName: string): TJSArray;
[async] function RenameApplicationName(const AOldName, ANewName: string): TJSArray;
[async] function DeleteApplicationName(const AName: string): TJSArray;
function AddVersionName(const AName: string): TJSArray;
[async] function RenameVersionName(const AOldName, ANewName: string): TJSArray;
[async] function DeleteVersionName(const AName: string): TJSArray;
[async] procedure HandleAddManagedName(const AFieldName: string; const ARowIndex: Integer; const ANewName: string);
[async] procedure HandleRenameManagedName(const AFieldName, AOldName, ANewName: string);
[async] procedure HandleDeleteManagedName(const AFieldName, AName: string);
......@@ -123,22 +151,54 @@ implementation
uses
ConnectionModule,
Auth.Service,
View.Main;
{$R *.dfm}
const
// Filter value that matches rows where the column is empty
FILTER_BLANK = '__blank__';
procedure TFTaskItems.WebFormCreate(Sender: TObject);
var
payload: TJSObject;
testingItems: TJSHTMLInputElement;
begin
console.log('TFTaskItems.WebFormCreate fired');
// Filters always start at All Items when the screen opens
FAssignedFilter := TJSArray.new;
FItemStatusFilter := TJSArray.new;
FStatusFilter := TJSArray.new;
FUserId := '';
payload := AuthService.TokenPayload;
if Assigned(payload) then
FUserId := JS.toString(payload.Properties['user_id']);
FTaskId := Application.Parameters.Values['task_id'];
if FTaskId = '' then
FTaskId := DMConnection.currentTaskId;
// From a Time Entries row: the mode last picked with the Testing Mode checkbox
// (Task Items at first). A direct task_id link (emT3 desktop) opens in Testing mode.
FTaskMode := (Application.Parameters.Values['task_id'] = '') and
(not DMConnection.taskItemsTestingMode);
testingItems := TJSHTMLInputElement(document.getElementById('chk_testing_items'));
if Assigned(testingItems) then
begin
testingItems.checked := not FTaskMode;
testingItems.addEventListener('change', TJSEventHandler(@TestingItemsChanged));
end;
FApplicationOptions := TJSArray.new;
FVersionOptions := TJSArray.new;
FReportedByOptions := TJSArray.new;
FAssignedToOptions := TJSArray.new;
FStatusOptions := TJSArray.new;
FItemStatusOptions := TJSArray.new;
FSelectedTaskItemId := 0;
FSelectedTaskId := 0;
FCopyingRow := False;
......@@ -147,7 +207,7 @@ begin
FNameManager := TNameManager.Create(
function(const AFieldName: string): TJSArray
begin
Result := uDropdownHelpers.GetOptionsForField(AFieldName, FApplicationOptions, FReportedByOptions, FAssignedToOptions);
Result := uDropdownHelpers.GetOptionsForField(AFieldName, FApplicationOptions, FVersionOptions, FReportedByOptions);
end,
procedure(const ATriggerId: string)
begin
......@@ -168,6 +228,7 @@ begin
);
FNameManager.BindControls;
BindFilterControls;
// Back only applies when opened from a Time Entries row (no task_id in the URL)
if Application.Parameters.Values['task_id'] = '' then
......@@ -197,6 +258,16 @@ begin
end;
// First editable column after the item number, used to place focus after add/move/delete
function TFTaskItems.FirstEditField: string;
begin
if FTaskMode then
Result := 'reportedBy'
else
Result := 'application';
end;
function TFTaskItems.HtmlEncode(const s: string): string;
begin
Result := s;
......@@ -398,6 +469,8 @@ begin
try
if await(AddTaskRowAtBottom) then
begin
// The new row is blank, so it would be hidden by most filters
ClearFilters;
CaptureTableScroll;
LoadTasks(FTaskId);
end;
......@@ -439,7 +512,7 @@ begin
btnDeleteRow.Enabled := False;
FPendingFocusItemNum := deletedItemNum;
FPendingFocusTaskField := 'application';
FPendingFocusTaskField := FirstEditField;
CaptureTableScroll;
LoadTasks(FTaskId);
......@@ -470,6 +543,8 @@ begin
try
if await(InsertTaskRowBelowSelection) then
begin
// The new row is blank, so it would be hidden by most filters
ClearFilters;
CaptureTableScroll;
LoadTasks(FTaskId);
end;
......@@ -489,6 +564,7 @@ begin
try
if await(CopyTaskRow) then
begin
ClearFilters;
CaptureTableScroll;
await(LoadTasks(FTaskId));
end;
......@@ -514,7 +590,7 @@ begin
FSelectedTaskItemId := StrToIntDef(string(TJSObject(response.Result)['value']), 0);
FPendingFocusTaskItemId := FSelectedTaskItemId;
FPendingFocusField := 'application';
FPendingFocusField := FirstEditField;
Result := True;
except
on E: EXDataClientRequestException do
......@@ -640,7 +716,7 @@ begin
console.log('AddTaskRow response=' + string(TJSJSON.stringify(response.Result)));
FPendingFocusItemNum := newItemNum;
FPendingFocusTaskField := 'application';
FPendingFocusTaskField := FirstEditField;
Result := True;
except
......@@ -704,13 +780,437 @@ begin
end;
procedure TFTaskItems.SetTotalRowsLabel(ARowCount: Integer);
procedure TFTaskItems.SetTotalRowsLabel(AShownCount, ATotalCount: Integer);
var
el: TJSHTMLElement;
begin
el := TJSHTMLElement(document.getElementById('lbl_total_rows'));
if not Assigned(el) then
Exit;
if ActiveFilterCount = 0 then
el.innerText := 'Total Rows: ' + IntToStr(ATotalCount)
else
el.innerText := 'Showing ' + IntToStr(AShownCount) + ' of ' + IntToStr(ATotalCount);
end;
procedure TFTaskItems.BindFilterControls;
var
el: TJSHTMLElement;
begin
// One listener for every checkbox, since the lists are rebuilt each time the panel opens
el := TJSHTMLElement(document.getElementById('offcanvasFilters'));
if Assigned(el) then
el.innerText := 'Total Rows: ' + IntToStr(ARowCount);
el.addEventListener('change', TJSEventHandler(@FilterCheckChange));
el := TJSHTMLElement(document.getElementById('btn_flt_clear'));
if Assigned(el) then
el.addEventListener('click', TJSEventHandler(@FilterClearClick));
end;
// Testing Mode checkbox: switches between Testing Items mode (every column) and
// Task Items mode (App, Version, Date and Testing Status hidden). The rows are the
// same in both, so this only re-renders; the choice is kept for the next time
// Task Items opens this session.
procedure TFTaskItems.TestingItemsChanged(Event: TJSEvent);
var
testingMode: Boolean;
begin
testingMode := TJSHTMLInputElement(Event.target).checked;
FTaskMode := not testingMode;
DMConnection.taskItemsTestingMode := testingMode;
if Assigned(FViewMain) then
FViewMain.SetTaskItemsTitle(testingMode);
// Shows or hides the Testing Status filter; Task mode ignores any it has
FillFilterLists;
if xdwdsTasks.Active then
begin
CaptureTableScroll;
RenderTable;
end;
end;
// Builds the checkbox lists from the current options and filter selections
procedure TFTaskItems.FillFilterLists;
var
assignedItems: TJSArray;
itemObj: TJSObject;
optionObj: TJSObject;
html: string;
value: string;
display: string;
i: Integer;
j: Integer;
found: Boolean;
el: TJSHTMLElement;
function CheckboxHtml(const AGroup, AValue, AText: string; const AFilter: TJSArray; const AIdx: Integer): string;
var
checkId: string;
checkedAttr: string;
begin
checkId := 'flt_' + AGroup + '_' + IntToStr(AIdx);
checkedAttr := '';
if AFilter.indexOf(AValue) >= 0 then
checkedAttr := ' checked';
Result :=
'<div class="form-check">' +
'<input class="form-check-input task-filter-check" type="checkbox" id="' + checkId + '" ' +
'data-filter="' + AGroup + '" value="' + HtmlEncode(AValue) + '"' + checkedAttr + '>' +
'<label class="form-check-label" for="' + checkId + '">' + HtmlEncode(AText) + '</label>' +
'</div>';
end;
function CodeListHtml(const AGroup: string; const AOptions, AFilter: TJSArray): string;
var
k: Integer;
optionCount: Integer;
codeObj: TJSObject;
begin
Result := '';
optionCount := 0;
if Assigned(AOptions) then
optionCount := AOptions.length;
for k := 0 to optionCount - 1 do
begin
codeObj := TJSObject(AOptions[k]);
Result := Result + CheckboxHtml(AGroup, string(codeObj['code']), string(codeObj['codeDesc']), AFilter, k);
end;
Result := Result + CheckboxHtml(AGroup, FILTER_BLANK, '(Blank)', AFilter, optionCount);
end;
// Multi-select dropdown: the checkboxes sit in the menu, which stays open while ticking;
// the button shows what's selected (see UpdateFilterSummary)
function DropdownHtml(const AGroup, AItemsHtml: string): string;
begin
Result :=
'<div class="dropdown w-100">' +
'<button type="button" class="btn btn-sm border w-100 d-flex justify-content-between align-items-center text-start btn-light" ' +
'data-bs-toggle="dropdown" data-bs-auto-close="outside" data-bs-display="static" aria-expanded="false">' +
'<span class="text-truncate task-filter-summary" data-filter="' + AGroup + '">All</span>' +
'<span class="dropdown-toggle dropdown-toggle-split border-0 ms-2"></span>' +
'</button>' +
'<div class="dropdown-menu w-100 px-3 py-2" style="max-height: 300px; overflow-y: auto;">' +
AItemsHtml +
'</div>' +
'</div>';
end;
begin
// Assigned: the people actually on these items (including older typed-in names)
assignedItems := TJSArray.new;
if xdwdsTasks.Active then
begin
xdwdsTasks.First;
while not xdwdsTasks.Eof do
begin
value := Trim(xdwdsTasksassignedTo.AsString);
if value <> '' then
begin
found := False;
for i := 0 to assignedItems.length - 1 do
if string(TJSObject(assignedItems[i])['value']) = value then
begin
found := True;
Break;
end;
if not found then
begin
itemObj := TJSObject.new;
itemObj['value'] := value;
itemObj['display'] := xdwdsTasksassignedToDesc.AsString;
assignedItems.push(itemObj);
end;
end;
xdwdsTasks.Next;
end;
end;
// Keep anyone already selected (e.g. you, from My Open Items) even with no items
for i := 0 to FAssignedFilter.length - 1 do
begin
value := string(FAssignedFilter[i]);
if value = FILTER_BLANK then
Continue;
found := False;
for j := 0 to assignedItems.length - 1 do
if string(TJSObject(assignedItems[j])['value']) = value then
begin
found := True;
Break;
end;
if not found then
begin
display := value;
if Assigned(FAssignedToOptions) then
for j := 0 to FAssignedToOptions.length - 1 do
begin
optionObj := TJSObject(FAssignedToOptions[j]);
if string(optionObj['userId']) = value then
begin
display := string(optionObj['name']);
Break;
end;
end;
itemObj := TJSObject.new;
itemObj['value'] := value;
itemObj['display'] := display;
assignedItems.push(itemObj);
end;
end;
asm
assignedItems.sort(function(a, b) { return String(a.display).localeCompare(String(b.display)); });
end;
html := '';
for i := 0 to assignedItems.length - 1 do
begin
itemObj := TJSObject(assignedItems[i]);
html := html + CheckboxHtml('assigned', string(itemObj['value']), string(itemObj['display']), FAssignedFilter, i);
end;
html := html + CheckboxHtml('assigned', FILTER_BLANK, '(Unassigned)', FAssignedFilter, assignedItems.length);
el := TJSHTMLElement(document.getElementById('flt_assigned_list'));
if Assigned(el) then
el.innerHTML := DropdownHtml('assigned', html);
el := TJSHTMLElement(document.getElementById('flt_item_status_list'));
if Assigned(el) then
el.innerHTML := DropdownHtml('itemStatus', CodeListHtml('itemStatus', FItemStatusOptions, FItemStatusFilter));
el := TJSHTMLElement(document.getElementById('flt_status_list'));
if Assigned(el) then
el.innerHTML := DropdownHtml('status', CodeListHtml('status', FStatusOptions, FStatusFilter));
UpdateFilterSummary('assigned');
UpdateFilterSummary('itemStatus');
UpdateFilterSummary('status');
// Testing Status is hidden in Task mode, so it can't be filtered there either
el := TJSHTMLElement(document.getElementById('flt_status_wrap'));
if Assigned(el) then
begin
if FTaskMode then
el.classList.add('d-none')
else
el.classList.remove('d-none');
end;
end;
procedure TFTaskItems.FilterCheckChange(Event: TJSEvent);
var
el: TJSHTMLElement;
group: string;
value: string;
isChecked: Boolean;
filterList: TJSArray;
idx: Integer;
begin
el := TJSHTMLElement(Event.target);
if not Assigned(el) or not el.classList.contains('task-filter-check') then
Exit;
group := string(el.getAttribute('data-filter'));
value := string(TJSObject(el)['value']);
isChecked := Boolean(TJSObject(el)['checked']);
if group = 'assigned' then
filterList := FAssignedFilter
else if group = 'itemStatus' then
filterList := FItemStatusFilter
else if group = 'status' then
filterList := FStatusFilter
else
Exit;
idx := filterList.indexOf(value);
if isChecked and (idx < 0) then
filterList.push(value)
else if (not isChecked) and (idx >= 0) then
filterList.splice(idx, 1);
UpdateFilterSummary(group);
CaptureTableScroll;
RenderTable;
end;
procedure TFTaskItems.FilterClearClick(Event: TJSEvent);
begin
ClearFilters;
CaptureTableScroll;
RenderTable;
end;
procedure TFTaskItems.ClearFilters;
var
nodes: TJSNodeList;
i: Integer;
begin
FAssignedFilter := TJSArray.new;
FItemStatusFilter := TJSArray.new;
FStatusFilter := TJSArray.new;
nodes := document.querySelectorAll('.task-filter-check');
for i := 0 to nodes.length - 1 do
TJSObject(nodes.item(i))['checked'] := False;
UpdateFilterSummary('assigned');
UpdateFilterSummary('itemStatus');
UpdateFilterSummary('status');
end;
// Button text for one filter dropdown: "All", up to two names, or "3 selected"
procedure TFTaskItems.UpdateFilterSummary(const AGroup: string);
var
summaryEl: TJSHTMLElement;
labelEl: TJSHTMLElement;
nodes: TJSNodeList;
names: string;
i: Integer;
begin
summaryEl := TJSHTMLElement(document.querySelector('.task-filter-summary[data-filter="' + AGroup + '"]'));
if not Assigned(summaryEl) then
Exit;
nodes := document.querySelectorAll('.task-filter-check[data-filter="' + AGroup + '"]:checked');
if nodes.length = 0 then
summaryEl.textContent := 'All'
else if nodes.length <= 2 then
begin
names := '';
for i := 0 to nodes.length - 1 do
begin
labelEl := TJSHTMLElement(document.querySelector('label[for="' + TJSHTMLElement(nodes.item(i)).id + '"]'));
if not Assigned(labelEl) then
Continue;
if names <> '' then
names := names + ', ';
names := names + string(labelEl.textContent);
end;
summaryEl.textContent := names;
end
else
summaryEl.textContent := IntToStr(nodes.length) + ' selected';
end;
// Checks the current dataset row: any selected value in a column matches (OR),
// and every column with a selection must match (AND)
function TFTaskItems.RowMatchesFilters: Boolean;
function Matches(const AFilter: TJSArray; const AValue: string): Boolean;
var
i: Integer;
rowValue: string;
filterValue: string;
begin
if AFilter.length = 0 then
Exit(True);
rowValue := Trim(AValue);
for i := 0 to AFilter.length - 1 do
begin
filterValue := string(AFilter[i]);
if filterValue = FILTER_BLANK then
begin
if rowValue = '' then
Exit(True);
end
else if SameText(rowValue, Trim(filterValue)) then
Exit(True);
end;
Result := False;
end;
begin
Result :=
Matches(FAssignedFilter, xdwdsTasksassignedTo.AsString) and
Matches(FItemStatusFilter, xdwdsTasksitemStatus.AsString);
if not FTaskMode then
Result := Result and Matches(FStatusFilter, xdwdsTasksstatus.AsString);
end;
// Number of columns with a filter selected
function TFTaskItems.ActiveFilterCount: Integer;
begin
Result := 0;
if FAssignedFilter.length > 0 then
Inc(Result);
if FItemStatusFilter.length > 0 then
Inc(Result);
if (not FTaskMode) and (FStatusFilter.length > 0) then
Inc(Result);
end;
// Assigned = me, and Task Item Status is one of the open statuses (blank counts as open)
procedure TFTaskItems.btnMyOpenItemsClick(Sender: TObject);
begin
FAssignedFilter := TJSArray.new;
if FUserId <> '' then
FAssignedFilter.push(FUserId);
FItemStatusFilter := TJSArray.new;
FItemStatusFilter.push('OPEN');
FItemStatusFilter.push('REPORT');
FItemStatusFilter.push('EVAL');
FItemStatusFilter.push('INTERM');
FItemStatusFilter.push('WAITING');
FItemStatusFilter.push(FILTER_BLANK);
FStatusFilter := TJSArray.new;
FillFilterLists;
CaptureTableScroll;
RenderTable;
end;
procedure TFTaskItems.btnAllItemsClick(Sender: TObject);
begin
ClearFilters;
CaptureTableScroll;
RenderTable;
end;
procedure TFTaskItems.btnFiltersClick(Sender: TObject);
begin
FillFilterLists;
asm
var el = document.getElementById('offcanvasFilters');
if (el) {
var oc = bootstrap.Offcanvas.getOrCreateInstance(el);
oc.show();
}
end;
end;
......@@ -730,7 +1230,6 @@ var
resultObj, taskObj: TJSObject;
itemsArray: TJSArray;
titleText: string;
rowCount: Integer;
begin
console.log('ITaskItemService.GetTaskItems called with task_id: ' + ATaskId);
console.log('Load Tasks Fired');
......@@ -761,13 +1260,13 @@ begin
SetTaskLabel(titleText);
rowCount := StrToIntDef(string(resultObj['count']), 0);
SetTotalRowsLabel(rowCount);
FApplicationOptions := ExtractOptionNames(TJSArray(resultObj['applicationOptions']));
FVersionOptions := ExtractOptionNames(TJSArray(resultObj['versionOptions']));
FReportedByOptions := ExtractOptionNames(TJSArray(resultObj['reportedByOptions']));
FAssignedToOptions := ExtractOptionNames(TJSArray(resultObj['assignedToOptions']));
FStatusOptions := ExtractCodeDescs(TJSArray(resultObj['statusOptions']));
// These lists keep both a value and a display text: the value is saved, the text shown
FAssignedToOptions := TJSArray(resultObj['assignedToOptions']);
FStatusOptions := TJSArray(resultObj['statusOptions']);
FItemStatusOptions := TJSArray(resultObj['itemStatusOptions']);
itemsArray := TJSArray(resultObj['items']);
if not Assigned(itemsArray) then
......@@ -793,6 +1292,9 @@ var
host: TJSHTMLElement;
html: string;
rowIdx: Integer;
shownCount: Integer;
selectedShown: Boolean;
tableMinWidth: string;
function Th(const s: string): string;
begin
......@@ -859,11 +1361,7 @@ var
begin
triggerId := 'task_dd_' + FieldName + '_' + IntToStr(AIdx);
buttonClass := 'btn btn-sm border w-100 d-flex justify-content-between align-items-center text-start task-dd-toggle ';
if SameText(FieldName, 'status') then
buttonClass := buttonClass + GetTaskStatusClass(Current)
else
buttonClass := buttonClass + 'btn-light';
buttonClass := 'btn btn-sm border w-100 d-flex justify-content-between align-items-center text-start task-dd-toggle btn-light';
Result :=
'<div class="dropdown w-100">' +
......@@ -910,6 +1408,62 @@ var
'</div>';
end;
// Dropdown that saves one property of each option (e.g. a code or USER_ID) and shows another
function CodeSelectList(const FieldName, CurrentValue, CurrentDisplay: string; const AIdx: Integer; const Items: TJSArray; const ValueProp, DisplayProp: string): string;
var
i: Integer;
optionObj: TJSObject;
optionValue: string;
optionDisplay: string;
triggerId: string;
buttonClass: string;
begin
triggerId := 'task_dd_' + FieldName + '_' + IntToStr(AIdx);
buttonClass := 'btn btn-sm border w-100 d-flex justify-content-between align-items-center text-start task-dd-toggle ';
if SameText(FieldName, 'status') then
buttonClass := buttonClass + GetTaskStatusClass(CurrentValue)
else
buttonClass := buttonClass + 'btn-light';
Result :=
'<div class="dropdown w-100">' +
'<button id="' + triggerId + '" class="' + buttonClass + '" ' +
'type="button" data-bs-toggle="dropdown" aria-expanded="false" ' +
'data-idx="' + IntToStr(AIdx) + '" data-field="' + FieldName + '">' +
'<span class="task-dd-label text-truncate">' + HtmlEncode(CurrentDisplay) + '</span>' +
'<span class="dropdown-toggle dropdown-toggle-split border-0 ms-2"></span>' +
'</button>' +
'<div class="dropdown-menu w-100 p-0 overflow-hidden">';
Result := Result +
'<button type="button" class="dropdown-item task-dd-item" ' +
'data-idx="' + IntToStr(AIdx) + '" ' +
'data-field="' + FieldName + '" ' +
'data-value="" ' +
'data-display="" ' +
'data-trigger-id="' + triggerId + '"></button>';
if Assigned(Items) then
for i := 0 to Items.length - 1 do
begin
optionObj := TJSObject(Items[i]);
optionValue := string(optionObj[ValueProp]);
optionDisplay := string(optionObj[DisplayProp]);
Result := Result +
'<button type="button" class="dropdown-item task-dd-item" ' +
'data-idx="' + IntToStr(AIdx) + '" ' +
'data-field="' + FieldName + '" ' +
'data-value="' + HtmlEncode(optionValue) + '" ' +
'data-display="' + HtmlEncode(optionDisplay) + '" ' +
'data-trigger-id="' + triggerId + '">' + HtmlEncode(optionDisplay) + '</button>';
end;
Result := Result +
'</div>' +
'</div>';
end;
function RichTextEditor(const FieldName, Value: string; const AIdx: Integer): string;
var
editorId: string;
......@@ -930,31 +1484,60 @@ begin
if not Assigned(host) then
Exit;
// Task mode hides App, Version, Date and Testing Status; Testing mode shows every column.
// The <col>, <th> and <td> lists must hide the same columns so column resizing stays aligned.
if FTaskMode then
tableMinWidth := '1225px'
else
tableMinWidth := '1880px';
html :=
'<div class="tasks-vscroll">' +
'<div class="tasks-hscroll">' +
'<table class="table table-sm table-bordered align-middle mb-0 tasks-table" style="min-width: 1700px; table-layout: fixed;">' +
'<table class="table table-sm table-bordered align-middle mb-0 tasks-table" style="min-width: ' + tableMinWidth + '; table-layout: fixed;">' +
'<colgroup>' +
'<col style="width:40px">' + // Item Num
'<col style="width:40px">'; // Item Num
if not FTaskMode then
html := html +
'<col style="width:200px">' + // App
'<col style="width:90px">' + // Version
'<col style="width:140px">' + // Date
'<col style="width:120px">' + // Version
'<col style="width:140px">'; // Date
html := html +
'<col style="width:120px">' + // Reported
'<col style="width:120px">' + // Assigned
'<col style="width:195px">' + // Status
'<col style="width:150px">'; // Task Item Status
if not FTaskMode then
html := html +
'<col style="width:195px">'; // Testing Status
html := html +
'<col style="width:140px">' + // Status Date
'<col style="width:160px">' + // Form
'<col style="width:520px">' + // Issue
'<col style="width:520px">' + // Notes
'</colgroup>' +
'<thead><tr>' +
ThBlank +
ThBlank;
if not FTaskMode then
html := html +
Th('App') +
Th('Version') +
Th('Date') +
Th('Date');
html := html +
Th('Reported') +
Th('Assigned') +
Th('Status') +
Th('Task Item Status');
if not FTaskMode then
html := html +
Th('Testing Status');
html := html +
Th('Status Date') +
Th('Form') +
Th('Issue/To-Do') +
......@@ -962,18 +1545,44 @@ begin
'</tr></thead><tbody>';
rowIdx := 0;
shownCount := 0;
selectedShown := False;
xdwdsTasks.First;
while not xdwdsTasks.Eof do
begin
// rowIdx must count every row, shown or not: data-idx is resolved by GotoRowIndex,
// which walks the full dataset
if not RowMatchesFilters then
begin
xdwdsTasks.Next;
Inc(rowIdx);
Continue;
end;
Inc(shownCount);
if xdwdsTaskstaskItemId.AsInteger = FSelectedTaskItemId then
selectedShown := True;
html := html +
'<tr class="task-row-selectable" data-task-item-id="' + IntToStr(xdwdsTaskstaskItemId.AsInteger) + '" data-task-id="' + xdwdsTaskstaskId.AsString + '" data-item-num="' + IntToStr(xdwdsTasksitemNum.AsInteger) + '">' +
TdNowrap(ItemNumInput(xdwdsTasksitemNum.AsInteger, rowIdx)) +
TdNowrap(ItemNumInput(xdwdsTasksitemNum.AsInteger, rowIdx));
if not FTaskMode then
html := html +
TdNowrap(SelectList('application', xdwdsTasksapplication.AsString, rowIdx, FApplicationOptions, True)) +
TdNowrap(TextInput('version', xdwdsTasksversion.AsString, rowIdx)) +
TdNowrap(DateInput('taskDate', xdwdsTaskstaskDate.AsString, rowIdx)) +
TdNowrap(SelectList('version', xdwdsTasksversion.AsString, rowIdx, FVersionOptions, True)) +
TdNowrap(DateInput('taskDate', xdwdsTaskstaskDate.AsString, rowIdx));
html := html +
TdNowrap(SelectList('reportedBy', xdwdsTasksreportedBy.AsString, rowIdx, FReportedByOptions, True)) +
TdNowrap(SelectList('assignedTo', xdwdsTasksassignedTo.AsString, rowIdx, FAssignedToOptions, True)) +
TdNowrap(SelectList('status', xdwdsTasksstatus.AsString, rowIdx, FStatusOptions, False)) +
TdNowrap(CodeSelectList('assignedTo', xdwdsTasksassignedTo.AsString, xdwdsTasksassignedToDesc.AsString, rowIdx, FAssignedToOptions, 'userId', 'name')) +
TdNowrap(CodeSelectList('itemStatus', xdwdsTasksitemStatus.AsString, xdwdsTasksitemStatusDesc.AsString, rowIdx, FItemStatusOptions, 'code', 'codeDesc'));
if not FTaskMode then
html := html +
TdNowrap(CodeSelectList('status', xdwdsTasksstatus.AsString, xdwdsTasksstatusDesc.AsString, rowIdx, FStatusOptions, 'code', 'codeDesc'));
html := html +
TdNowrap(DateInput('statusDate', xdwdsTasksstatusDate.AsString, rowIdx)) +
TdNowrap(TextInput('formSection', xdwdsTasksformSection.AsString, rowIdx)) +
TdWrap(RichTextEditor('issue', xdwdsTasksissue.AsString, rowIdx)) +
......@@ -987,6 +1596,22 @@ begin
html := html + '</tbody></table></div></div>';
host.innerHTML := html;
SetTotalRowsLabel(shownCount, rowIdx);
if ActiveFilterCount = 0 then
btnFilters.Caption := 'Filters'
else
btnFilters.Caption := 'Filters (' + IntToStr(ActiveFilterCount) + ')';
// Don't let Insert/Copy/Delete act on a row the filters are hiding
if (FSelectedTaskItemId > 0) and not selectedShown then
begin
FSelectedTaskItemId := 0;
FSelectedTaskId := 0;
btnInsertRow.Enabled := False;
btnDeleteRow.Enabled := False;
end;
BindTableEditors;
EnableAutoGrowTextAreas;
EnableColumnResize;
......@@ -1112,7 +1737,7 @@ begin
console.log('MoveTaskRow: response=' + string(TJSJSON.stringify(response.Result)));
FPendingFocusTaskItemId := movedTaskItemId;
FPendingFocusField := 'application';
FPendingFocusField := FirstEditField;
CaptureTableScroll;
LoadTasks(FTaskId);
......@@ -1155,6 +1780,8 @@ begin
fieldValue := xdwdsTasksassignedTo.AsString
else if SameText(AFieldName, 'status') then
fieldValue := xdwdsTasksstatus.AsString
else if SameText(AFieldName, 'itemStatus') then
fieldValue := xdwdsTasksitemStatus.AsString
else if SameText(AFieldName, 'statusDate') then
fieldValue := xdwdsTasksstatusDate.AsString
else if SameText(AFieldName, 'formSection') then
......@@ -1219,7 +1846,7 @@ procedure TFTaskItems.DropdownItemClick(Event: TJSEvent);
var
el: TJSHTMLElement;
idx: Integer;
idxStr, fieldName, newVal, triggerId: string;
idxStr, fieldName, newVal, newDisplay, triggerId: string;
btn: TJSHTMLElement;
labelEl: TJSHTMLElement;
begin
......@@ -1235,6 +1862,12 @@ begin
newVal := string(el.getAttribute('data-value'));
triggerId := string(el.getAttribute('data-trigger-id'));
// Code lists carry the description separately; name lists show the value itself
if el.hasAttribute('data-display') then
newDisplay := string(el.getAttribute('data-display'))
else
newDisplay := newVal;
idx := StrToIntDef(idxStr, -1);
if (idx < 0) or (fieldName = '') then
Exit;
......@@ -1244,7 +1877,23 @@ begin
Exit;
xdwdsTasks.Edit;
xdwdsTasks.FieldByName(fieldName).AsString := newVal;
if SameText(fieldName, 'assignedTo') then
begin
xdwdsTasksassignedTo.AsString := newVal;
xdwdsTasksassignedToDesc.AsString := newDisplay;
end
else if SameText(fieldName, 'status') then
begin
xdwdsTasksstatus.AsString := newVal;
xdwdsTasksstatusDesc.AsString := newDisplay;
end
else if SameText(fieldName, 'itemStatus') then
begin
xdwdsTasksitemStatus.AsString := newVal;
xdwdsTasksitemStatusDesc.AsString := newDisplay;
end
else
xdwdsTasks.FieldByName(fieldName).AsString := newVal;
xdwdsTasks.Post;
if triggerId <> '' then
......@@ -1254,7 +1903,7 @@ begin
begin
labelEl := TJSHTMLElement(btn.querySelector('.task-dd-label'));
if Assigned(labelEl) then
labelEl.textContent := newVal;
labelEl.textContent := newDisplay;
if SameText(fieldName, 'status') then
ApplyTaskStatusClass(btn, newVal);
......@@ -1284,7 +1933,7 @@ begin
if (idx < 0) or (fieldName = '') then
Exit;
if not (SameText(fieldName, 'assignedTo') or SameText(fieldName, 'application') or SameText(fieldName, 'reportedBy')) then
if not (SameText(fieldName, 'application') or SameText(fieldName, 'version') or SameText(fieldName, 'reportedBy')) then
Exit;
FNameManager.OpenManager(fieldName, idx, triggerId);
......@@ -1385,85 +2034,6 @@ begin
end;
[async] function TFTaskItems.AddAssignedName(const AName: string): TJSArray;
var
response: TXDataClientResponse;
resultObj: TJSObject;
begin
Result := nil;
try
response := await(xdwcTasks.RawInvokeAsync(
'ITaskItemService.AddAssignedName',
[FTaskId, Trim(AName)]
));
resultObj := TJSObject(response.Result);
Result := ExtractAssignedOptionNames(resultObj);
FAssignedToOptions := Result;
except
on E: EXDataClientRequestException do
begin
console.log('AddAssignedName ERROR: ' + E.ErrorResult.ErrorMessage);
Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
Exit;
end;
end;
end;
[async] function TFTaskItems.RenameAssignedName(const AOldName, ANewName: string): TJSArray;
var
response: TXDataClientResponse;
resultObj: TJSObject;
begin
Result := nil;
try
response := await(xdwcTasks.RawInvokeAsync(
'ITaskItemService.RenameAssignedName',
[FTaskId, Trim(AOldName), Trim(ANewName)]
));
resultObj := TJSObject(response.Result);
Result := ExtractAssignedOptionNames(resultObj);
FAssignedToOptions := Result;
except
on E: EXDataClientRequestException do
begin
console.log('RenameAssignedName ERROR: ' + E.ErrorResult.ErrorMessage);
Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
Exit;
end;
end;
end;
[async] function TFTaskItems.DeleteAssignedName(const AName: string): TJSArray;
var
response: TXDataClientResponse;
resultObj: TJSObject;
begin
Result := nil;
try
response := await(xdwcTasks.RawInvokeAsync(
'ITaskItemService.DeleteAssignedName',
[FTaskId, Trim(AName)]
));
resultObj := TJSObject(response.Result);
Result := ExtractAssignedOptionNames(resultObj);
FAssignedToOptions := Result;
except
on E: EXDataClientRequestException do
begin
console.log('DeleteAssignedName ERROR: ' + E.ErrorResult.ErrorMessage);
Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
Exit;
end;
end;
end;
[async] procedure TFTaskItems.HandleAddManagedName(const AFieldName: string; const ARowIndex: Integer; const ANewName: string);
var
newOptions: TJSArray;
......@@ -1471,8 +2041,8 @@ var
begin
if SameText(AFieldName, 'application') then
newOptions := await(AddApplicationName(ANewName))
else if SameText(AFieldName, 'assignedTo') then
newOptions := await(AddAssignedName(ANewName))
else if SameText(AFieldName, 'version') then
newOptions := AddVersionName(ANewName)
else if SameText(AFieldName, 'reportedBy') then
newOptions := await(AddReportedName(ANewName))
else
......@@ -1483,10 +2053,10 @@ begin
if SameText(AFieldName, 'application') then
FApplicationOptions := newOptions
else if SameText(AFieldName, 'reportedBy') then
FReportedByOptions := newOptions
else if SameText(AFieldName, 'version') then
FVersionOptions := newOptions
else
FAssignedToOptions := newOptions;
FReportedByOptions := newOptions;
resolvedName := FindOptionIgnoreCase(newOptions, ANewName);
if resolvedName = '' then
......@@ -1514,8 +2084,8 @@ var
begin
if SameText(AFieldName, 'application') then
newOptions := await(RenameApplicationName(AOldName, ANewName))
else if SameText(AFieldName, 'assignedTo') then
newOptions := await(RenameAssignedName(AOldName, ANewName))
else if SameText(AFieldName, 'version') then
newOptions := await(RenameVersionName(AOldName, ANewName))
else if SameText(AFieldName, 'reportedBy') then
newOptions := await(RenameReportedName(AOldName, ANewName))
else
......@@ -1526,10 +2096,10 @@ begin
if SameText(AFieldName, 'application') then
FApplicationOptions := newOptions
else if SameText(AFieldName, 'reportedBy') then
FReportedByOptions := newOptions
else if SameText(AFieldName, 'version') then
FVersionOptions := newOptions
else
FAssignedToOptions := newOptions;
FReportedByOptions := newOptions;
CaptureTableScroll;
LoadTasks(FTaskId);
......@@ -1541,8 +2111,8 @@ var
begin
if SameText(AFieldName, 'application') then
newOptions := await(DeleteApplicationName(AName))
else if SameText(AFieldName, 'assignedTo') then
newOptions := await(DeleteAssignedName(AName))
else if SameText(AFieldName, 'version') then
newOptions := await(DeleteVersionName(AName))
else if SameText(AFieldName, 'reportedBy') then
newOptions := await(DeleteReportedName(AName))
else
......@@ -1553,10 +2123,10 @@ begin
if SameText(AFieldName, 'application') then
FApplicationOptions := newOptions
else if SameText(AFieldName, 'reportedBy') then
FReportedByOptions := newOptions
else if SameText(AFieldName, 'version') then
FVersionOptions := newOptions
else
FAssignedToOptions := newOptions;
FReportedByOptions := newOptions;
CaptureTableScroll;
LoadTasks(FTaskId);
......@@ -1641,6 +2211,86 @@ begin
end;
// Versions are only stored on the rows, so a new one just joins the list here;
// it's kept once the row it's picked for is saved
function TFTaskItems.AddVersionName(const AName: string): TJSArray;
var
i: Integer;
newName: string;
begin
Result := nil;
newName := Trim(AName);
if newName = '' then
Exit;
Result := TJSArray.new;
if Assigned(FVersionOptions) then
for i := 0 to FVersionOptions.length - 1 do
Result.push(FVersionOptions[i]);
if FindOptionIgnoreCase(Result, newName) = '' then
begin
Result.push(newName);
Result.sort;
end;
FVersionOptions := Result;
end;
[async] function TFTaskItems.RenameVersionName(const AOldName, ANewName: string): TJSArray;
var
response: TXDataClientResponse;
resultObj: TJSObject;
begin
Result := nil;
try
response := await(xdwcTasks.RawInvokeAsync(
'ITaskItemService.RenameVersionName',
[FTaskId, Trim(AOldName), Trim(ANewName)]
));
resultObj := TJSObject(response.Result);
Result := ExtractVersionOptionNames(resultObj);
FVersionOptions := Result;
except
on E: EXDataClientRequestException do
begin
console.log('RenameVersionName ERROR: ' + E.ErrorResult.ErrorMessage);
Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
Exit;
end;
end;
end;
[async] function TFTaskItems.DeleteVersionName(const AName: string): TJSArray;
var
response: TXDataClientResponse;
resultObj: TJSObject;
begin
Result := nil;
try
response := await(xdwcTasks.RawInvokeAsync(
'ITaskItemService.DeleteVersionName',
[FTaskId, Trim(AName)]
));
resultObj := TJSObject(response.Result);
Result := ExtractVersionOptionNames(resultObj);
FVersionOptions := Result;
except
on E: EXDataClientRequestException do
begin
console.log('DeleteVersionName ERROR: ' + E.ErrorResult.ErrorMessage);
Utils.ShowErrorModal(E.ErrorResult.ErrorMessage);
Exit;
end;
end;
end;
[async] function TFTaskItems.AddReportedName(const AName: string): TJSArray;
var
response: TXDataClientResponse;
......
object FTaskPicker: TFTaskPicker
Width = 840
Height = 470
CSSLibrary = cssBootstrap
ElementFont = efCSS
OnClose = WebFormClose
OnCloseQuery = WebFormCloseQuery
OnCreate = WebFormCreate
object lblStatus: TWebLabel
Left = 24
Top = 256
Width = 3
Height = 15
ElementID = 'task_picker_status'
ElementFont = efCSS
HeightPercent = 100.000000000000000000
ShowAccelChar = False
Visible = False
WidthPercent = 100.000000000000000000
end
object lblTaskNotice: TWebLabel
Left = 24
Top = 232
Width = 3
Height = 15
ElementID = 'task_picker_task_notice'
ElementFont = efCSS
HeightPercent = 100.000000000000000000
ShowAccelChar = False
Visible = False
WidthPercent = 100.000000000000000000
end
object edtWorkDate: TWebEdit
Left = 24
Top = 64
Width = 121
Height = 22
ElementID = 'task_picker_date'
ElementFont = efCSS
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnChange = edtWorkDateChange
end
object rbAllTasks: TWebRadioButton
Left = 296
Top = 64
Width = 113
Height = 22
Caption = 'All Tasks'
Checked = True
ChildOrder = 1
Color = clNone
ElementID = 'task_picker_task_filter_all'
ElementFont = efCSS
GroupName = 'task_picker_task_filter'
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnClick = rbTaskFilterClick
end
object rbMyTasks: TWebRadioButton
Left = 424
Top = 64
Width = 113
Height = 22
Caption = 'My Tasks'
Checked = False
ChildOrder = 2
Color = clNone
ElementID = 'task_picker_task_filter_my'
ElementFont = efCSS
GroupName = 'task_picker_task_filter'
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnClick = rbTaskFilterClick
end
object rbFocusedTasks: TWebRadioButton
Left = 552
Top = 64
Width = 113
Height = 22
Caption = 'Focused Tasks'
Checked = False
ChildOrder = 3
Color = clNone
ElementID = 'task_picker_task_filter_focused'
ElementFont = efCSS
GroupName = 'task_picker_task_filter'
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnClick = rbTaskFilterClick
end
object cboScope: TWebLookupComboBox
Left = 24
Top = 136
Width = 233
Height = 22
ChildOrder = 4
ElementID = 'task_picker_scope'
ElementFont = efCSS
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnChange = cboScopeChange
ItemIndex = -1
LookupValues = <
item
Value = 'MY'
DisplayText = 'My Projects'
end
item
Value = 'ACTIVE'
DisplayText = 'Active Projects'
end
item
Value = 'ALL'
DisplayText = 'All Projects'
end>
end
object cboCustomer: TWebLookupComboBox
Left = 280
Top = 136
Width = 233
Height = 22
ChildOrder = 5
ElementID = 'task_picker_customer'
ElementFont = efCSS
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnChange = cboCustomerChange
ItemIndex = -1
LookupValues = <>
end
object cboProject: TWebLookupComboBox
Left = 536
Top = 136
Width = 233
Height = 22
ChildOrder = 6
ElementID = 'task_picker_project'
ElementFont = efCSS
Enabled = False
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnChange = cboProjectChange
ItemIndex = -1
LookupValues = <>
end
object cboTask: TWebLookupComboBox
Left = 24
Top = 208
Width = 745
Height = 22
ChildOrder = 7
ElementID = 'task_picker_task'
ElementFont = efCSS
Enabled = False
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnChange = cboTaskChange
ItemIndex = -1
LookupValues = <>
end
object chkFocusedTask: TWebCheckBox
Left = 24
Top = 424
Width = 113
Height = 22
Caption = 'Focused Task'
ChildOrder = 8
ElementID = 'task_picker_add_focus'
ElementFont = efCSS
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnClick = chkFocusedTaskClick
end
object cboTaskStatus: TWebLookupComboBox
Left = 200
Top = 424
Width = 145
Height = 22
ChildOrder = 9
ElementID = 'task_picker_task_status'
ElementFont = efCSS
Enabled = False
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnChange = cboTaskStatusChange
ItemIndex = -1
LookupValues = <>
end
object edtEndDate: TWebEdit
Left = 360
Top = 424
Width = 145
Height = 22
ChildOrder = 14
ElementID = 'task_picker_end_date'
ElementFont = efCSS
Enabled = False
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnChange = edtEndDateChange
end
object btnClose: TWebButton
Left = 752
Top = 16
Width = 25
Height = 25
ChildOrder = 10
ElementID = 'btn_task_picker_close'
ElementFont = efCSS
HeightStyle = ssAuto
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnClick = btnCloseClick
end
object btnCancel: TWebButton
Left = 520
Top = 424
Width = 80
Height = 25
Caption = 'Cancel'
ChildOrder = 11
ElementID = 'btn_task_picker_cancel'
ElementFont = efCSS
HeightStyle = ssAuto
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnClick = btnCancelClick
end
object btnSave: TWebButton
Left = 608
Top = 424
Width = 80
Height = 25
Caption = 'Save'
ChildOrder = 12
ElementID = 'btn_task_picker_save'
ElementFont = efCSS
HeightStyle = ssAuto
HeightPercent = 100.000000000000000000
Visible = False
WidthPercent = 100.000000000000000000
OnClick = btnSaveClick
end
object btnSelect: TWebButton
Left = 696
Top = 424
Width = 80
Height = 25
Caption = 'Select'
ChildOrder = 13
ElementID = 'btn_task_picker_select'
ElementFont = efCSS
Enabled = False
HeightStyle = ssAuto
HeightPercent = 100.000000000000000000
WidthPercent = 100.000000000000000000
OnClick = btnSelectClick
end
object tmrTaskNotice: TWebTimer
Enabled = False
Interval = 6000
OnTimer = tmrTaskNoticeTimer
Left = 120
Top = 344
end
object xdwcTaskPicker: TXDataWebClient
Connection = DMConnection.ApiConnection
Left = 40
Top = 344
end
end
<!-- Find Task: a TMS popup form (TFTaskPicker), opened from a Time Entries row's task menu.
The popup itself gets its border, rounding and shadow from ElementPopupClassName.
Every input, select and button here is bound to a component in View.TaskPicker.dfm
by its id; the selects' options come from each TWebLookupComboBox's LookupValues. -->
<div class="d-flex flex-column h-100 bg-body">
<div class="d-flex align-items-center justify-content-between px-3 py-2 border-bottom flex-shrink-0">
<h5 class="mb-0" id="task_picker_title">Find Task</h5>
<button type="button" class="btn-close" id="btn_task_picker_close" aria-label="Close"></button>
</div>
<div class="p-3 flex-grow-1 overflow-auto">
<div class="row g-2 align-items-end mb-3">
<div class="col-md-4">
<label for="task_picker_date" class="form-label">Work Date</label>
<input type="date" id="task_picker_date" class="form-control form-control-sm"
title="Select also sets the row's date. Every task is listed, but only one that can take hours on this date can be selected." />
</div>
<!-- Filters the loaded project's task list in the browser, like emT3's
All / My Tasks / Focused on the Time Entry screen -->
<div class="col-md d-flex align-items-center flex-wrap gap-3 pb-1" id="task_picker_task_filter_group">
<div class="form-check form-check-inline m-0">
<input class="form-check-input" type="radio" name="task_picker_task_filter"
id="task_picker_task_filter_all" value="ALL" checked />
<label class="form-check-label" for="task_picker_task_filter_all">All Tasks</label>
</div>
<div class="form-check form-check-inline m-0">
<input class="form-check-input" type="radio" name="task_picker_task_filter"
id="task_picker_task_filter_my" value="MY" />
<label class="form-check-label" for="task_picker_task_filter_my">My Tasks</label>
</div>
<div class="form-check form-check-inline m-0">
<input class="form-check-input" type="radio" name="task_picker_task_filter"
id="task_picker_task_filter_focused" value="FOCUSED" />
<label class="form-check-label" for="task_picker_task_filter_focused">Focused Tasks</label>
</div>
</div>
</div>
<div class="row g-2 align-items-end mb-3">
<div class="col-md">
<label for="task_picker_scope" class="form-label">Show</label>
<select id="task_picker_scope" class="form-select form-select-sm">
<option value="MY" selected>My Projects</option>
<option value="ACTIVE">Active Projects</option>
<option value="ALL">All Projects</option>
</select>
</div>
<div class="col-md" id="task_picker_customer_group">
<label for="task_picker_customer" class="form-label">Customer</label>
<select id="task_picker_customer" class="form-select form-select-sm">
<option value=""></option>
</select>
</div>
<div class="col-md">
<label for="task_picker_project" class="form-label">Project</label>
<select id="task_picker_project" class="form-select form-select-sm" disabled>
<option value=""></option>
</select>
</div>
</div>
<div class="row g-2 align-items-end mb-3">
<div class="col-md">
<label for="task_picker_task" class="form-label">Task</label>
<!-- lblTaskNotice: the red popup Select shows under the Task dropdown for a
task that can't take hours on the Work Date, styled like the Time
Entries Summary's limit popup (css/time-entries.css); starts hidden
through its Visible in the .dfm -->
<div class="time-task-wrap">
<select id="task_picker_task" class="form-select form-select-sm" disabled>
<option value=""></option>
</select>
<div id="task_picker_task_notice" class="time-summary-notice time-summary-notice-error"
role="status" aria-live="polite"></div>
</div>
</div>
</div>
<!-- lblStatus; starts hidden through its Visible in the .dfm -->
<div id="task_picker_status" class="alert alert-danger py-1 px-2 mb-0 small"></div>
</div>
<div class="d-flex align-items-center gap-2 px-3 py-2 border-top flex-shrink-0">
<div class="d-flex align-items-center gap-2">
<input class="form-check-input m-0" type="checkbox" id="task_picker_add_focus" />
<label class="form-check-label mb-0" for="task_picker_add_focus">
Focused Task
</label>
</div>
<!-- The selected task's own status; Save applies it with Focused Task -->
<div class="d-flex align-items-center gap-2 ms-3">
<label for="task_picker_task_status" class="form-label mb-0">Status</label>
<select id="task_picker_task_status" class="form-select form-select-sm" style="width: 9rem;" disabled></select>
</div>
<!-- The selected task's End Date (tasks.COMPLETION_DATE); optional, except
that Closed and Complete need one. Picking a status fills it; Save
stores it with the Status. -->
<div class="d-flex align-items-center gap-2 ms-3 me-auto">
<label for="task_picker_end_date" class="form-label mb-0 text-nowrap">End Date</label>
<input type="date" id="task_picker_end_date" class="form-control form-control-sm" style="width: 9.5rem;" disabled
title="When the task was completed. Hours can't be entered after it." />
</div>
<!-- With unsaved Status, End Date or Focused Task changes, Save shows in place of
Select and Cancel undoes the changes; otherwise Cancel closes.
Save starts hidden through btnSave.Visible in the .dfm. -->
<button type="button" class="btn btn-outline-secondary btn-sm" id="btn_task_picker_cancel">Cancel</button>
<button type="button" class="btn btn-success btn-sm" id="btn_task_picker_save">Save</button>
<button type="button" class="btn btn-primary btn-sm" id="btn_task_picker_select" disabled>Select</button>
</div>
</div>
unit uTaskPickerOffCanvas;
unit View.TaskPicker;
// Find Task: a TMS popup form opened from a Time Entries row. The caller creates
// it with CreatePopup, awaits Load, starts it with Start (which loads the lists
// while the form is showing), awaits Execute and frees it. mrOk means Select
// was clicked and SelectedTaskId / SelectedTaskDisplay / SelectedTaskDate hold
// the pick. Focused Task changes are saved while the form stays open, so they
// reach the caller right away through OnFocusChanged.
interface
uses
System.SysUtils, JS, Web, XData.Web.Client;
System.SysUtils, System.Classes, JS, Web, WEBLib.Graphics, WEBLib.Controls,
WEBLib.Forms, WEBLib.Dialogs, Vcl.Controls, Vcl.StdCtrls, WEBLib.StdCtrls,
WEBLib.ExtCtrls, XData.Web.Client, ConnectionModule, WEBLib.DBCtrls;
type
TTaskPickedProc = reference to procedure(
ARowIndex: Integer;
const ATaskId, ATaskDisplay, ATaskDate: string
);
TTaskFocusChangedProc = reference to procedure(
const ATaskId, ATaskDisplay: string;
AFocused: Boolean
);
TTaskPickerOffCanvas = class
TFTaskPicker = class(TWebForm)
edtWorkDate: TWebEdit;
rbAllTasks: TWebRadioButton;
rbMyTasks: TWebRadioButton;
rbFocusedTasks: TWebRadioButton;
cboScope: TWebLookupComboBox;
cboCustomer: TWebLookupComboBox;
cboProject: TWebLookupComboBox;
cboTask: TWebLookupComboBox;
lblTaskNotice: TWebLabel;
tmrTaskNotice: TWebTimer;
lblStatus: TWebLabel;
chkFocusedTask: TWebCheckBox;
cboTaskStatus: TWebLookupComboBox;
edtEndDate: TWebEdit;
btnClose: TWebButton;
btnCancel: TWebButton;
btnSave: TWebButton;
btnSelect: TWebButton;
xdwcTaskPicker: TXDataWebClient;
procedure WebFormCreate(Sender: TObject);
procedure WebFormClose(Sender: TObject; var Action: TCloseAction);
procedure WebFormCloseQuery(Sender: TObject; var CanClose: Boolean);
[async] procedure edtWorkDateChange(Sender: TObject);
[async] procedure rbTaskFilterClick(Sender: TObject);
[async] procedure cboScopeChange(Sender: TObject);
procedure cboCustomerChange(Sender: TObject);
[async] procedure cboProjectChange(Sender: TObject);
procedure cboTaskChange(Sender: TObject);
procedure chkFocusedTaskClick(Sender: TObject);
procedure cboTaskStatusChange(Sender: TObject);
procedure edtEndDateChange(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
[async] procedure btnSaveClick(Sender: TObject);
procedure btnSelectClick(Sender: TObject);
procedure tmrTaskNoticeTimer(Sender: TObject);
private
FClient: TXDataWebClient;
FUserId: string;
FRowIndex: Integer;
FOnTaskPicked: TTaskPickedProc;
FOnFocusChanged: TTaskFocusChangedProc;
FHasChanges: Boolean; // Status, End Date or Focused Task differs from the saved value
FCustomers: TJSArray;
FProjects: TJSArray;
FTasks: TJSArray;
FTasks: TJSArray; // every task loaded for the project
FTasksProjectId: string; // the project FTasks was loaded for, '' = none
FVisibleTasks: TJSArray; // FTasks after the All / My / Focused filter (what the Task dropdown lists)
// The held task: the row's task, or the last one the user picked. A scope or
// task filter change can drop it from the lists; when they list it again it
// comes back. Picking another customer, project or task replaces it.
FHeldTaskId: string;
FHeldProjectId: string;
// The last task held (row's task or user's pick) and its project. Unlike the
// held task, browsing to another customer or project keeps it, so picking
// its project again selects it again. Picking the blank task clears it.
FLastTaskId: string;
FLastProjectId: string;
FFocusedTasks: TJSArray;
FSavedFocus: Boolean;
FSavedTaskStatus: string; // selected task's status on the server, '' = no task
FSavedEndDate: string; // selected task's End Date (COMPLETION_DATE) on the server, 'yyyy-mm-dd', '' = none
FSaving: Boolean;
FPrefillToken: Integer;
FScope: string; // MY, ACTIVE or ALL; kept between opens until the page reloads
FStatusesLoaded: Boolean; // footer Status dropdown is filled on the first open
procedure BindEvents;
FScope: string; // MY, ACTIVE or ALL
FTaskFilter: string; // ALL, MY or FOCUSED
FStatusesLoaded: Boolean; // footer Status dropdown is filled
FClosed: Boolean; // the caller frees the form on close, so late server replies must not touch its controls
FSelectedTaskId: string;
FSelectedTaskDisplay: string;
FSelectedTaskDate: string;
function HtmlEncode(const s: string): string;
procedure ApplyScope(const AScope: string);
procedure SetTaskFilter(const AFilter: string);
function TaskMatchesFilter(ATask: TJSObject): Boolean;
procedure FillTasks;
function FindProjectCustomer(const AProjectId: string; out ACustomerId: string): Boolean;
procedure ClearSelect(const AElementId: string; ADisabled: Boolean);
procedure FillSelect(const AElementId: string; AItems: TJSArray);
procedure ClearCombo(ACombo: TWebLookupComboBox; ADisabled: Boolean);
procedure FillCombo(ACombo: TWebLookupComboBox; AItems: TJSArray);
procedure FilterProjects(const ACustomerId: string);
function SelectedValue(const AElementId: string): string;
function FindDisplay(AItems: TJSArray; const AValue: string): string;
function FocusCheckbox: TJSHTMLInputElement;
function TaskStatusSelect: TJSHTMLSelectElement;
procedure ResetChanges;
function PickerDate: string;
function IsTaskCompleted(const ATaskId: string): Boolean;
function TaskStatus(const ATaskId: string): string;
function TaskEndDate(const ATaskId: string): string;
function TaskUnavailableReason(const ATaskId: string): string;
procedure ShowTaskAvailability;
procedure ShowTaskNotice(const AMessage: string);
procedure HideTaskNotice;
function IsTaskFocused(const ATaskId: string): Boolean;
procedure SetTaskFocused(const ATaskId, ATaskDisplay: string; AFocused: Boolean);
procedure SetStatus(const AMessage: string);
procedure ClearStatus;
procedure SetButtonEnabled(const AElementId: string; AEnabled: Boolean);
procedure UpdateButtons;
procedure Show;
procedure Hide;
[async] procedure LoadCustomers;
[async] procedure LoadStatuses;
procedure FillStatuses;
procedure FillCustomers;
[async] procedure LoadProjects(const ACustomerId: string);
[async] procedure LoadTasks(const AProjectId: string);
[async] procedure PreselectTask(const ATaskId: string; AToken: Integer);
[async] procedure ReloadForDate;
procedure SetSelectValue(const AElementId, AValue: string);
[async] procedure DateChanged(Event: TJSEvent);
[async] procedure ScopeChanged(Event: TJSEvent);
procedure CustomerChanged(Event: TJSEvent);
[async] procedure ProjectChanged(Event: TJSEvent);
procedure TaskChanged(Event: TJSEvent);
procedure FocusCheckboxChanged(Event: TJSEvent);
procedure TaskStatusChanged(Event: TJSEvent);
[async] function ReloadForTaskFilter: Boolean;
procedure HoldTask(const ATaskId, AProjectId: string);
[async] function RestoreHeldTask(AToken: Integer): Boolean;
procedure UpdateFocusCheckbox;
procedure SelectClicked(Event: TJSEvent);
[async] procedure SaveClicked(Event: TJSEvent);
public
constructor Create(AClient: TXDataWebClient; AOnTaskPicked: TTaskPickedProc;
AOnFocusChanged: TTaskFocusChangedProc);
[async] procedure Open(const AUserId: string; ARowIndex: Integer; AFocusedTasks: TJSArray;
class function CreatePopup(AOwner: TComponent): TFTaskPicker;
[async] procedure Start(const AUserId: string; AFocusedTasks: TJSArray;
const ATaskId, ATaskDate: string);
property OnFocusChanged: TTaskFocusChangedProc read FOnFocusChanged write FOnFocusChanged;
property SelectedTaskId: string read FSelectedTaskId;
property SelectedTaskDisplay: string read FSelectedTaskDisplay;
property SelectedTaskDate: string read FSelectedTaskDate;
end;
implementation
constructor TTaskPickerOffCanvas.Create(AClient: TXDataWebClient; AOnTaskPicked: TTaskPickedProc;
AOnFocusChanged: TTaskFocusChangedProc);
{$R *.dfm}
var
// Each open is a new form, so this is kept here until the page reloads
LoadedStatuses: TJSArray = nil; // footer Status options, loaded on the first open
// A centered popup with a dimmed backdrop, styled with Bootstrap classes instead
// of the TMS caption bar. Only Cancel, the X and Esc close it, not a click outside,
// so a stray click doesn't lose the picked task.
class function TFTaskPicker.CreatePopup(AOwner: TComponent): TFTaskPicker;
begin
Result := TFTaskPicker.Create(AOwner);
Result.Popup := True;
Result.PopupClose := pcNever;
Result.PopupOpacity := 0.5;
Result.Border := fbNone;
Result.Shadow := False;
Result.ElementPopupClassName := 'border rounded-3 shadow overflow-hidden bg-body';
end;
procedure TFTaskPicker.WebFormCreate(Sender: TObject);
begin
inherited Create;
FClient := AClient;
FOnTaskPicked := AOnTaskPicked;
FOnFocusChanged := AOnFocusChanged;
FHasChanges := False;
FCustomers := TJSArray.new;
FProjects := TJSArray.new;
FTasks := TJSArray.new;
FTasksProjectId := '';
FVisibleTasks := TJSArray.new;
FHeldTaskId := '';
FHeldProjectId := '';
FLastTaskId := '';
FLastProjectId := '';
FFocusedTasks := TJSArray.new;
FRowIndex := -1;
FSavedFocus := False;
FSavedTaskStatus := '';
FSavedEndDate := '';
FSaving := False;
FPrefillToken := 0;
FScope := 'MY';
// Every open starts as wide as possible; Start sets the dropdown and radio to match
FScope := 'ALL';
FTaskFilter := 'ALL';
FStatusesLoaded := False;
FClosed := False;
end;
BindEvents;
// The caller frees the form right after, so any load still running stops when
// its reply arrives (FClosed, and the token for the prefill)
procedure TFTaskPicker.WebFormClose(Sender: TObject; var Action: TCloseAction);
begin
FClosed := True;
Inc(FPrefillToken);
end;
procedure TTaskPickerOffCanvas.BindEvents;
var
el: TJSHTMLElement;
// Not while a Save is running (Esc or the X would otherwise close it mid-save)
procedure TFTaskPicker.WebFormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
el := TJSHTMLElement(document.getElementById('task_picker_date'));
if Assigned(el) then
el.addEventListener('change', TJSEventHandler(@DateChanged));
CanClose := not FSaving;
end;
el := TJSHTMLElement(document.getElementById('task_picker_scope'));
if Assigned(el) then
el.addEventListener('change', TJSEventHandler(@ScopeChanged));
// TWebLookupComboBox puts each DisplayText into its option as HTML
function TFTaskPicker.HtmlEncode(const s: string): string;
begin
Result := s;
Result := StringReplace(Result, '&', '&amp;', [rfReplaceAll]);
Result := StringReplace(Result, '<', '&lt;', [rfReplaceAll]);
Result := StringReplace(Result, '>', '&gt;', [rfReplaceAll]);
Result := StringReplace(Result, '"', '&quot;', [rfReplaceAll]);
Result := StringReplace(Result, '''', '&#39;', [rfReplaceAll]);
end;
el := TJSHTMLElement(document.getElementById('task_picker_customer'));
if Assigned(el) then
el.addEventListener('change', TJSEventHandler(@CustomerChanged));
// Sets the scope dropdown. The customer field shows in every scope; projects
// are listed as "SHORT_NAME - project"
procedure TFTaskPicker.ApplyScope(const AScope: string);
begin
FScope := AScope;
el := TJSHTMLElement(document.getElementById('task_picker_project'));
if Assigned(el) then
el.addEventListener('change', TJSEventHandler(@ProjectChanged));
cboScope.Value := AScope;
end;
el := TJSHTMLElement(document.getElementById('task_picker_task'));
if Assigned(el) then
el.addEventListener('change', TJSEventHandler(@TaskChanged));
// Checks the All Tasks / My Tasks / Focused Tasks radio for AFilter
procedure TFTaskPicker.SetTaskFilter(const AFilter: string);
begin
FTaskFilter := AFilter;
if AFilter = 'MY' then
rbMyTasks.Checked := True
else if AFilter = 'FOCUSED' then
rbFocusedTasks.Checked := True
else
rbAllTasks.Checked := True;
end;
el := TJSHTMLElement(document.getElementById('task_picker_add_focus'));
if Assigned(el) then
el.addEventListener('change', TJSEventHandler(@FocusCheckboxChanged));
// Same rules as emT3's Time Entry screen: My Tasks = assigned to the user,
// Focused = assigned with FOCUSED_TASK = 'T' (flags come with the task list)
function TFTaskPicker.TaskMatchesFilter(ATask: TJSObject): Boolean;
begin
if FTaskFilter = 'MY' then
Result := JS.isBoolean(ATask['assigned']) and Boolean(ATask['assigned'])
else if FTaskFilter = 'FOCUSED' then
Result := JS.isBoolean(ATask['focused']) and Boolean(ATask['focused'])
else
Result := True;
end;
el := TJSHTMLElement(document.getElementById('task_picker_task_status'));
if Assigned(el) then
el.addEventListener('change', TJSEventHandler(@TaskStatusChanged));
// Fills the Task dropdown from the loaded list through the filter, with no
// server call; keeps the chosen task when it's still listed
procedure TFTaskPicker.FillTasks;
var
task: TJSObject;
selectedTask: string;
i: Integer;
begin
selectedTask := cboTask.Value;
FVisibleTasks := TJSArray.new;
el := TJSHTMLElement(document.getElementById('btn_task_picker_save'));
if Assigned(el) then
el.addEventListener('click', TJSEventHandler(@SaveClicked));
for i := 0 to FTasks.length - 1 do
begin
task := TJSObject(FTasks[i]);
if TaskMatchesFilter(task) then
FVisibleTasks.push(task);
end;
el := TJSHTMLElement(document.getElementById('btn_task_picker_select'));
if Assigned(el) then
el.addEventListener('click', TJSEventHandler(@SelectClicked));
end;
FillCombo(cboTask, FVisibleTasks);
// Sets the scope dropdown. The customer field shows in every scope; projects
// are listed as "SHORT_NAME - project"
procedure TTaskPickerOffCanvas.ApplyScope(const AScope: string);
begin
FScope := AScope;
if (selectedTask <> '') and (FindDisplay(FVisibleTasks, selectedTask) <> '') then
cboTask.Value := selectedTask;
SetSelectValue('task_picker_scope', AScope);
if FTasks.length = 0 then
SetStatus('No tasks in this project.')
else if FVisibleTasks.length = 0 then
begin
if FTaskFilter = 'FOCUSED' then
SetStatus('None of this project''s tasks are in your Focused Tasks.')
else
SetStatus('None of this project''s tasks are assigned to you.');
end;
end;
function TTaskPickerOffCanvas.FindProjectCustomer(const AProjectId: string; out ACustomerId: string): Boolean;
function TFTaskPicker.FindProjectCustomer(const AProjectId: string; out ACustomerId: string): Boolean;
var
project: TJSObject;
i: Integer;
......@@ -178,45 +294,40 @@ begin
end;
end;
procedure TTaskPickerOffCanvas.ClearSelect(const AElementId: string; ADisabled: Boolean);
var
selectEl: TJSHTMLSelectElement;
// Leaves only the blank option
procedure TFTaskPicker.ClearCombo(ACombo: TWebLookupComboBox; ADisabled: Boolean);
begin
selectEl := TJSHTMLSelectElement(document.getElementById(AElementId));
if not Assigned(selectEl) then
Exit;
selectEl.innerHTML := '<option value=""></option>';
selectEl.disabled := ADisabled;
FillCombo(ACombo, TJSArray.new);
ACombo.Enabled := not ADisabled;
end;
procedure TTaskPickerOffCanvas.FillSelect(const AElementId: string; AItems: TJSArray);
// A blank option, then AItems ({value, display}); the blank one is selected
procedure TFTaskPicker.FillCombo(ACombo: TWebLookupComboBox; AItems: TJSArray);
var
selectEl: TJSHTMLSelectElement;
optionEl: TJSHTMLOptionElement;
itemObj: TJSObject;
i: Integer;
begin
selectEl := TJSHTMLSelectElement(document.getElementById(AElementId));
if not Assigned(selectEl) then
Exit;
selectEl.innerHTML := '<option value=""></option>';
// One list rebuild for the whole fill instead of one per option
ACombo.LookupValues.BeginUpdate;
try
ACombo.LookupValues.Clear;
ACombo.LookupValues.AddPair('', '');
for i := 0 to AItems.length - 1 do
begin
itemObj := TJSObject(AItems[i]);
optionEl := TJSHTMLOptionElement(document.createElement('option'));
optionEl.value := string(itemObj['value']);
optionEl.text := string(itemObj['display']);
selectEl.appendChild(optionEl);
for i := 0 to AItems.length - 1 do
begin
itemObj := TJSObject(AItems[i]);
ACombo.LookupValues.AddPair(string(itemObj['value']), HtmlEncode(string(itemObj['display'])));
end;
finally
ACombo.LookupValues.EndUpdate;
end;
selectEl.disabled := False;
ACombo.ItemIndex := 0;
ACombo.Enabled := True;
end;
procedure TTaskPickerOffCanvas.FilterProjects(const ACustomerId: string);
procedure TFTaskPicker.FilterProjects(const ACustomerId: string);
var
filteredProjects: TJSArray;
project: TJSObject;
......@@ -234,21 +345,10 @@ begin
filteredProjects.push(project);
end;
end;
FillSelect('task_picker_project', filteredProjects)
FillCombo(cboProject, filteredProjects)
end;
function TTaskPickerOffCanvas.SelectedValue(const AElementId: string): string;
var
selectEl: TJSHTMLSelectElement;
begin
Result := '';
selectEl := TJSHTMLSelectElement(document.getElementById(AElementId));
if Assigned(selectEl) then
Result := string(selectEl.value);
end;
function TTaskPickerOffCanvas.FindDisplay(AItems: TJSArray; const AValue: string): string;
function TFTaskPicker.FindDisplay(AItems: TJSArray; const AValue: string): string;
var
itemObj: TJSObject;
i: Integer;
......@@ -263,45 +363,34 @@ begin
end;
end;
function TTaskPickerOffCanvas.FocusCheckbox: TJSHTMLInputElement;
function TFTaskPicker.PickerDate: string;
begin
Result := TJSHTMLInputElement(document.getElementById('task_picker_add_focus'));
Result := edtWorkDate.Text;
end;
function TTaskPickerOffCanvas.TaskStatusSelect: TJSHTMLSelectElement;
begin
Result := TJSHTMLSelectElement(document.getElementById('task_picker_task_status'));
end;
function TTaskPickerOffCanvas.PickerDate: string;
var
dateEl: TJSHTMLInputElement;
begin
Result := '';
dateEl := TJSHTMLInputElement(document.getElementById('task_picker_date'));
if Assigned(dateEl) then
Result := dateEl.value;
end;
// The server marks a task completed when its COMPLETION_DATE is set
function TTaskPickerOffCanvas.IsTaskCompleted(const ATaskId: string): Boolean;
// The task's End Date (COMPLETION_DATE, 'yyyy-mm-dd') as loaded with the task
// list; '' = none. A task with one counts as completed.
function TFTaskPicker.TaskEndDate(const ATaskId: string): string;
var
itemObj: TJSObject;
i: Integer;
begin
Result := False;
Result := '';
for i := 0 to FTasks.length - 1 do
begin
itemObj := TJSObject(FTasks[i]);
if string(itemObj['value']) = ATaskId then
Exit(JS.isBoolean(itemObj['completed']) and Boolean(itemObj['completed']));
begin
if JS.isString(itemObj['completionDate']) then
Exit(string(itemObj['completionDate']));
Exit;
end;
end;
end;
// The task's status code as loaded with the task list; '' = unknown
function TTaskPickerOffCanvas.TaskStatus(const ATaskId: string): string;
function TFTaskPicker.TaskStatus(const ATaskId: string): string;
var
itemObj: TJSObject;
i: Integer;
......@@ -321,7 +410,7 @@ begin
end;
// Why hours can't go on the picker date for this task; '' = allowed (or unknown)
function TTaskPickerOffCanvas.TaskUnavailableReason(const ATaskId: string): string;
function TFTaskPicker.TaskUnavailableReason(const ATaskId: string): string;
var
itemObj: TJSObject;
i: Integer;
......@@ -340,18 +429,48 @@ begin
end;
end;
procedure TTaskPickerOffCanvas.ShowTaskAvailability;
// Like the Time Entries Summary's "500 characters" error: the Task dropdown
// glows red and the red popup under it shows for 6 seconds
procedure TFTaskPicker.ShowTaskNotice(const AMessage: string);
var
reason: string;
taskEl: TJSHTMLElement;
begin
reason := TaskUnavailableReason(SelectedValue('task_picker_task'));
if reason <> '' then
SetStatus(reason)
else
ClearStatus;
if FClosed then
Exit;
taskEl := cboTask.ElementHandle;
asm
taskEl.classList.remove('time-field-flash-error');
void taskEl.offsetWidth; // restarts the animation
taskEl.classList.add('time-field-flash-error');
end;
cboTask.SetFocus;
lblTaskNotice.Caption := AMessage;
lblTaskNotice.Visible := True;
// Restart the 6 seconds if it was already showing
tmrTaskNotice.Enabled := False;
tmrTaskNotice.Enabled := True;
end;
function TTaskPickerOffCanvas.IsTaskFocused(const ATaskId: string): Boolean;
// The notice is about the task picked when Select was clicked, so it goes
// when the task or Work Date changes
procedure TFTaskPicker.HideTaskNotice;
begin
if FClosed then
Exit;
tmrTaskNotice.Enabled := False;
lblTaskNotice.Visible := False;
end;
procedure TFTaskPicker.tmrTaskNoticeTimer(Sender: TObject);
begin
HideTaskNotice;
end;
function TFTaskPicker.IsTaskFocused(const ATaskId: string): Boolean;
var
taskOption: TJSObject;
i: Integer;
......@@ -370,11 +489,27 @@ begin
end;
end;
procedure TTaskPickerOffCanvas.SetTaskFocused(const ATaskId, ATaskDisplay: string; AFocused: Boolean);
procedure TFTaskPicker.SetTaskFocused(const ATaskId, ATaskDisplay: string; AFocused: Boolean);
var
taskOption: TJSObject;
i: Integer;
begin
// The loaded task list's My Tasks / Focused flags (AddTaskToFocus assigns the
// task to the user if needed; removing focus keeps the assignment). The
// dropdown isn't refiltered, so the task stays listed until the filter changes.
for i := 0 to FTasks.length - 1 do
begin
taskOption := TJSObject(FTasks[i]);
if string(taskOption['value']) = ATaskId then
begin
taskOption['focused'] := AFocused;
if AFocused then
taskOption['assigned'] := True;
Break;
end;
end;
// Keep the picker's own copy of the focused list in sync with the server
for i := FFocusedTasks.length - 1 downto 0 do
begin
......@@ -398,192 +533,135 @@ begin
end;
end;
procedure TTaskPickerOffCanvas.SetStatus(const AMessage: string);
var
el: TJSHTMLElement;
procedure TFTaskPicker.SetStatus(const AMessage: string);
begin
el := TJSHTMLElement(document.getElementById('task_picker_status'));
if not Assigned(el) then
if FClosed then
Exit;
el.innerText := AMessage;
el.classList.remove('d-none');
lblStatus.Caption := AMessage;
lblStatus.Visible := True;
end;
procedure TTaskPickerOffCanvas.ClearStatus;
var
el: TJSHTMLElement;
procedure TFTaskPicker.ClearStatus;
begin
el := TJSHTMLElement(document.getElementById('task_picker_status'));
if not Assigned(el) then
if FClosed then
Exit;
el.innerText := '';
el.classList.add('d-none');
lblStatus.Caption := '';
lblStatus.Visible := False;
end;
procedure TTaskPickerOffCanvas.SetButtonEnabled(const AElementId: string; AEnabled: Boolean);
var
btn: TJSHTMLButtonElement;
begin
btn := TJSHTMLButtonElement(document.getElementById(AElementId));
if Assigned(btn) then
btn.disabled := not AEnabled;
end;
procedure TTaskPickerOffCanvas.UpdateButtons;
procedure TFTaskPicker.UpdateButtons;
var
hasTask: Boolean;
focusChanged: Boolean;
focusBlocked: Boolean;
statusChanged: Boolean;
endDateChanged: Boolean;
pendingStatus: string;
addFocus: TJSHTMLInputElement;
statusSelect: TJSHTMLSelectElement;
begin
// Select: any picked task can be sent to the grid.
// Save: only when the Focused Task checkbox or the Status differs from what
// is saved on the server.
hasTask := SelectedValue('task_picker_task') <> '';
statusSelect := TaskStatusSelect;
pendingStatus := '';
statusChanged := False;
if Assigned(statusSelect) then
begin
statusSelect.disabled := (not hasTask) or FSaving or (not FStatusesLoaded);
pendingStatus := statusSelect.value;
statusChanged := hasTask and (pendingStatus <> '') and (pendingStatus <> FSavedTaskStatus);
end;
// A completed task can be selected for historical hours but not newly focused
// (it can still be unfocused if it already is). With a status change pending,
// the new status decides: Save sends it first, and the server sets the
// completion date for CLOSED/COMP and clears it for any other status.
if statusChanged then
focusBlocked := (pendingStatus = 'CLOSED') or (pendingStatus = 'COMP')
else
focusBlocked := IsTaskCompleted(SelectedValue('task_picker_task'));
focusBlocked := focusBlocked and hasTask and (not FSavedFocus);
addFocus := FocusCheckbox;
focusChanged := False;
if Assigned(addFocus) then
begin
// Closing the task drops a focus tick that hasn't been saved yet
if focusBlocked then
addFocus.checked := False;
addFocus.disabled := (not hasTask) or FSaving or focusBlocked;
focusChanged := addFocus.checked <> FSavedFocus;
end;
SetButtonEnabled('btn_task_picker_select', hasTask and not FSaving);
SetButtonEnabled('btn_task_picker_save', hasTask and (focusChanged or statusChanged) and not FSaving);
end;
procedure TTaskPickerOffCanvas.Show;
begin
asm
const el = document.getElementById('task_picker_modal');
if (!el || !window.bootstrap) return;
// The modal's backdrop is added to <body>; left inside the form's TMS
// containers (which carry their own z-index) the modal sits under it.
// So it moves to <body> while open and goes back into the form when hidden,
// so the form still frees it and no second copy of its IDs is left behind.
if (el.parentNode !== document.body) {
const home = el.parentNode;
const homeNext = el.nextSibling;
el.addEventListener('hidden.bs.modal', function () {
if (home.isConnected)
home.insertBefore(el, (homeNext && homeNext.parentNode === home) ? homeNext : null);
else {
bootstrap.Modal.getOrCreateInstance(el).dispose();
el.remove();
}
}, { once: true });
document.body.appendChild(el);
}
const modal = bootstrap.Modal.getOrCreateInstance(el);
modal.show();
end;
// One button at the right: Save while the Focused Task checkbox, the Status
// or the End Date differs from what is saved on the server; otherwise Select,
// which sends the picked task to the grid.
hasTask := cboTask.Value <> '';
cboTaskStatus.Enabled := hasTask and (not FSaving) and FStatusesLoaded;
pendingStatus := cboTaskStatus.Value;
statusChanged := hasTask and (pendingStatus <> '') and (pendingStatus <> FSavedTaskStatus);
edtEndDate.Enabled := hasTask and not FSaving;
endDateChanged := hasTask and (edtEndDate.Text <> FSavedEndDate);
// A completed task (one with an End Date) can be selected for historical hours
// but not newly focused (it can still be unfocused if it already is). The End
// Date on screen decides, since Save sends it before the focus change.
focusBlocked := hasTask and (edtEndDate.Text <> '') and (not FSavedFocus);
// Closing the task drops a focus tick that hasn't been saved yet
if focusBlocked then
chkFocusedTask.Checked := False;
chkFocusedTask.Enabled := hasTask and (not FSaving) and (not focusBlocked);
focusChanged := chkFocusedTask.Checked <> FSavedFocus;
FHasChanges := hasTask and (focusChanged or statusChanged or endDateChanged);
btnSave.Visible := FHasChanges;
btnSelect.Visible := not FHasChanges;
btnSave.Enabled := not FSaving;
btnSelect.Enabled := hasTask and not FSaving;
btnCancel.Enabled := not FSaving;
btnClose.Enabled := not FSaving;
end;
procedure TTaskPickerOffCanvas.Hide;
begin
asm
const el = document.getElementById('task_picker_modal');
if (!el || !window.bootstrap) return;
const modal = bootstrap.Modal.getOrCreateInstance(el);
modal.hide();
end;
end;
[async] procedure TTaskPickerOffCanvas.LoadCustomers;
[async] procedure TFTaskPicker.LoadCustomers;
var
response: TXDataClientResponse;
resultObj: TJSObject;
begin
response := await(FClient.RawInvokeAsync(
response := await(xdwcTaskPicker.RawInvokeAsync(
'ITimeEntryService.GetTaskPickerCustomers', []
));
if FClosed then
Exit;
resultObj := TJSObject(response.Result);
FCustomers := TJSArray(resultObj['options']);
FillSelect('task_picker_customer', FCustomers);
FillCombo(cboCustomer, FCustomers);
end;
// Fills the footer's Status dropdown with the task status codes
[async] procedure TTaskPickerOffCanvas.LoadStatuses;
// The footer's Status options are the task status codes; loaded once and
// reused by later opens
[async] procedure TFTaskPicker.LoadStatuses;
var
response: TXDataClientResponse;
resultObj: TJSObject;
statuses: TJSArray;
statusObj: TJSObject;
statusSelect: TJSHTMLSelectElement;
optionEl: TJSHTMLOptionElement;
i: Integer;
begin
response := await(FClient.RawInvokeAsync(
'ITimeEntryService.GetTaskPickerStatuses', []
));
if not Assigned(LoadedStatuses) then
begin
response := await(xdwcTaskPicker.RawInvokeAsync(
'ITimeEntryService.GetTaskPickerStatuses', []
));
resultObj := TJSObject(response.Result);
statuses := TJSArray(resultObj['options']);
resultObj := TJSObject(response.Result);
LoadedStatuses := TJSArray(resultObj['options']);
end;
statusSelect := TaskStatusSelect;
if not Assigned(statusSelect) then
if FClosed then
Exit;
statusSelect.innerHTML := '';
FillStatuses;
end;
for i := 0 to statuses.length - 1 do
begin
statusObj := TJSObject(statuses[i]);
// No blank option here: the dropdown shows blank only while no task is picked
procedure TFTaskPicker.FillStatuses;
var
statusObj: TJSObject;
i: Integer;
begin
cboTaskStatus.LookupValues.BeginUpdate;
try
cboTaskStatus.LookupValues.Clear;
optionEl := TJSHTMLOptionElement(document.createElement('option'));
optionEl.value := string(statusObj['value']);
optionEl.text := string(statusObj['display']);
statusSelect.appendChild(optionEl);
for i := 0 to LoadedStatuses.length - 1 do
begin
statusObj := TJSObject(LoadedStatuses[i]);
cboTaskStatus.LookupValues.AddPair(string(statusObj['value']), HtmlEncode(string(statusObj['display'])));
end;
finally
cboTaskStatus.LookupValues.EndUpdate;
end;
// Blank until a task is picked (UpdateFocusCheckbox sets the task's status)
statusSelect.value := FSavedTaskStatus;
cboTaskStatus.Value := FSavedTaskStatus;
FStatusesLoaded := True;
end;
// Only customers with a listed project (so the scope and Work Date apply to
// them too, like emT3's Time Entry screen); keeps the chosen customer if still listed
procedure TTaskPickerOffCanvas.FillCustomers;
procedure TFTaskPicker.FillCustomers;
var
filteredCustomers: TJSArray;
customer: TJSObject;
......@@ -592,7 +670,7 @@ var
i: Integer;
j: Integer;
begin
selectedCustomer := SelectedValue('task_picker_customer');
selectedCustomer := cboCustomer.Value;
filteredCustomers := TJSArray.new;
for i := 0 to FCustomers.length - 1 do
......@@ -608,81 +686,77 @@ begin
end;
end;
FillSelect('task_picker_customer', filteredCustomers);
FillCombo(cboCustomer, filteredCustomers);
if (selectedCustomer <> '') and (FindDisplay(filteredCustomers, selectedCustomer) <> '') then
SetSelectValue('task_picker_customer', selectedCustomer);
cboCustomer.Value := selectedCustomer;
end;
[async] procedure TTaskPickerOffCanvas.LoadProjects(const ACustomerId: string);
[async] procedure TFTaskPicker.LoadProjects(const ACustomerId: string);
var
response: TXDataClientResponse;
resultObj: TJSObject;
begin
// Projects in the scope that are open on the Work Date (any date when it's
// blank); the customer list then follows the projects
response := await(FClient.RawInvokeAsync(
// Every project in the scope, whatever its dates (a blank date skips the
// server's date filter); the Task list's unavailableReason covers the
// project's dates instead. My Tasks / Focused Tasks keep only projects with
// a task assigned to / focused by the user. The customer list then follows
// the projects.
response := await(xdwcTaskPicker.RawInvokeAsync(
'ITimeEntryService.GetTaskPickerProjects',
[ACustomerId, FScope, FUserId, PickerDate]
[ACustomerId, FScope, FUserId, '', FTaskFilter]
));
if FClosed then
Exit;
resultObj := TJSObject(response.Result);
FProjects := TJSArray(resultObj['options']);
FillCustomers;
end;
[async] procedure TTaskPickerOffCanvas.LoadTasks(const AProjectId: string);
[async] procedure TFTaskPicker.LoadTasks(const AProjectId: string);
var
response: TXDataClientResponse;
resultObj: TJSObject;
taskDate: string;
begin
// The server returns the project's tasks open on the Work Date (every task
// when it's blank); each one carries unavailableReason for this date and
// user ('' when allowed or no date)
// The server returns every task in the project, closed ones included; each
// one carries unavailableReason for the Work Date and this user ('' when
// allowed or no date), which keeps Select from taking it
taskDate := PickerDate;
response := await(FClient.RawInvokeAsync(
response := await(xdwcTaskPicker.RawInvokeAsync(
'ITimeEntryService.GetTaskPickerTasks',
[AProjectId, FUserId, taskDate]
));
if FClosed then
Exit;
// Every task comes back, with its My Tasks / Focused flags; the radios then
// filter this list until the project changes (or the Work Date reloads it)
resultObj := TJSObject(response.Result);
FTasks := TJSArray(resultObj['options']);
FillSelect('task_picker_task', FTasks);
if FTasks.length = 0 then
begin
if taskDate <> '' then
SetStatus('No tasks in this project are open on this date.')
else
SetStatus('No tasks in this project.');
end;
FTasksProjectId := AProjectId;
FillTasks;
end;
procedure TTaskPickerOffCanvas.SetSelectValue(const AElementId, AValue: string);
var
selectEl: TJSHTMLSelectElement;
begin
// Setting .value in code does not fire 'change', so the cascade handlers do not run
selectEl := TJSHTMLSelectElement(document.getElementById(AElementId));
if Assigned(selectEl) then
selectEl.value := AValue;
end;
[async] procedure TTaskPickerOffCanvas.PreselectTask(const ATaskId: string; AToken: Integer);
// Setting a combo's Value in code doesn't fire OnChange, so the cascade
// handlers don't run
[async] procedure TFTaskPicker.PreselectTask(const ATaskId: string; AToken: Integer);
var
response: TXDataClientResponse;
context: TJSObject;
projectId: string;
customerId: string;
begin
response := await(FClient.RawInvokeAsync(
response := await(xdwcTaskPicker.RawInvokeAsync(
'ITimeEntryService.GetTaskPickerTaskContext',
[ATaskId]
));
// Picker was reopened or the user changed a dropdown while this was loading
// Picker was closed or the user changed a dropdown while this was loading
if AToken <> FPrefillToken then
Exit;
......@@ -691,89 +765,125 @@ begin
if projectId = '' then
Exit;
// Not one of My Projects: switch to Active, which lists every active project
if (not FindProjectCustomer(projectId, customerId)) and (FScope = 'MY') then
begin
ApplyScope('ACTIVE');
await(LoadProjects(''));
FilterProjects('');
if AToken <> FPrefillToken then
Exit;
end;
// Not active (closed, complete or pending): switch to All, which lists every project
if (not FindProjectCustomer(projectId, customerId)) and (FScope = 'ACTIVE') then
begin
ApplyScope('ALL');
await(LoadProjects(''));
FilterProjects('');
if AToken <> FPrefillToken then
Exit;
end;
// Still not listed under All: its project isn't open on the Work Date
// The picker opens on All Projects with no date filter, so every project is listed
if not FindProjectCustomer(projectId, customerId) then
begin
if PickerDate <> '' then
SetStatus('This row''s project isn''t open on this date.')
else
SetStatus('This row''s task couldn''t be found in its project.');
SetStatus('This row''s task couldn''t be found in its project.');
Exit;
end;
SetSelectValue('task_picker_customer', customerId);
cboCustomer.Value := customerId;
FilterProjects(customerId);
SetSelectValue('task_picker_project', projectId);
cboProject.Value := projectId;
await(LoadTasks(projectId));
if AToken <> FPrefillToken then
Exit;
// Not open on the Work Date (e.g. the row's date was just changed), or moved
// Every task in the project is listed, so it's missing only if it moved
if FindDisplay(FTasks, ATaskId) = '' then
begin
if PickerDate <> '' then
SetStatus('This row''s task isn''t open on this date.')
else
SetStatus('This row''s task couldn''t be found in its project.');
SetStatus('This row''s task couldn''t be found in its project.');
UpdateFocusCheckbox;
Exit;
end;
SetSelectValue('task_picker_task', ATaskId);
// The picker opens on All Tasks, so the task is listed
cboTask.Value := ATaskId;
HoldTask(ATaskId, projectId);
UpdateFocusCheckbox;
ShowTaskAvailability;
end;
// The Work Date changed: reload the projects (and so the
// customers) and the selected project's tasks for the new date, keeping the
// customer, project and task when they're still listed
[async] procedure TTaskPickerOffCanvas.ReloadForDate;
procedure TFTaskPicker.HoldTask(const ATaskId, AProjectId: string);
begin
FHeldTaskId := ATaskId;
if ATaskId = '' then
FHeldProjectId := ''
else
begin
FHeldProjectId := AProjectId;
FLastTaskId := ATaskId;
FLastProjectId := AProjectId;
end;
end;
// After a scope or task filter change has reloaded the projects: when the held
// task's project is listed again, chooses its customer and project, and the
// task too when the task filter lists it. False when its project isn't listed,
// the task load failed or the user changed something meanwhile.
[async] function TFTaskPicker.RestoreHeldTask(AToken: Integer): Boolean;
var
customerId: string;
begin
Result := False;
if FHeldTaskId = '' then
Exit;
if not FindProjectCustomer(FHeldProjectId, customerId) then
Exit;
cboCustomer.Value := customerId;
FilterProjects(customerId);
cboProject.Value := FHeldProjectId;
// The project's tasks may still be loaded from before the change (their
// focus flags are kept current); otherwise load them
if FTasksProjectId = FHeldProjectId then
FillTasks
else
begin
ClearCombo(cboTask, True);
try
await(LoadTasks(FHeldProjectId));
except
on E: Exception do
begin
SetStatus('Unable to load tasks.');
Exit;
end;
end;
if AToken <> FPrefillToken then
Exit;
end;
if FindDisplay(FVisibleTasks, FHeldTaskId) <> '' then
cboTask.Value := FHeldTaskId;
Result := True;
end;
// The Work Date changed. The lists don't depend on it, but each task's
// unavailableReason does, so the selected project's tasks are reloaded;
// FillTasks keeps the chosen task.
[async] procedure TFTaskPicker.ReloadForDate;
var
projectId: string;
taskId: string;
token: Integer;
begin
Inc(FPrefillToken); // user took over; abandon any prefill still loading
token := FPrefillToken;
ClearStatus;
HideTaskNotice;
projectId := SelectedValue('task_picker_project');
taskId := SelectedValue('task_picker_task');
ClearSelect('task_picker_project', True);
ClearSelect('task_picker_task', True);
UpdateFocusCheckbox;
projectId := cboProject.Value;
if projectId = '' then
begin
// Loaded tasks kept for restoring the held task were checked against the
// old date, so RestoreHeldTask has to load them again
FTasksProjectId := '';
Exit;
end;
try
await(LoadProjects(''));
await(LoadTasks(projectId));
except
on E: Exception do
begin
SetStatus('Unable to load projects.');
SetStatus('Unable to load tasks.');
Exit;
end;
end;
......@@ -781,64 +891,89 @@ begin
if token <> FPrefillToken then
Exit;
// FillCustomers kept the customer if it still has a project on this date
FilterProjects(SelectedValue('task_picker_customer'));
UpdateFocusCheckbox;
end;
if projectId = '' then
Exit;
[async] procedure TFTaskPicker.edtWorkDateChange(Sender: TObject);
begin
await(ReloadForDate);
end;
if FindDisplay(FProjects, projectId) = '' then
begin
SetStatus('The selected project isn''t open on this date.');
Exit;
end;
[async] procedure TFTaskPicker.cboScopeChange(Sender: TObject);
var
token: Integer;
begin
Inc(FPrefillToken); // user took over; abandon any prefill still loading
token := FPrefillToken;
ClearStatus;
SetSelectValue('task_picker_project', projectId);
ApplyScope(cboScope.Value);
cboCustomer.Value := '';
ClearCombo(cboProject, True);
ClearCombo(cboTask, True);
UpdateFocusCheckbox;
try
await(LoadTasks(projectId));
await(LoadProjects(''));
except
on E: Exception do
begin
SetStatus('Unable to load tasks.');
SetStatus('Unable to load projects.');
Exit;
end;
end;
// Another scope was picked while this list was loading
if token <> FPrefillToken then
Exit;
// Keep the chosen task and say whether it can take hours on the new date
if (taskId <> '') and (FindDisplay(FTasks, taskId) <> '') then
SetSelectValue('task_picker_task', taskId)
else if (taskId <> '') and (FTasks.length > 0) then
SetStatus('The selected task isn''t open on this date.');
UpdateFocusCheckbox;
FilterProjects('');
// Only when a task is selected, so an empty-project status isn't cleared
if SelectedValue('task_picker_task') <> '' then
ShowTaskAvailability;
// Back on the held task when this scope lists its project
if await(RestoreHeldTask(token)) then
UpdateFocusCheckbox;
end;
[async] procedure TTaskPickerOffCanvas.DateChanged(Event: TJSEvent);
// All Tasks / My Tasks / Focused Tasks filter the Customer and Project lists
// as well as the Task list
[async] procedure TFTaskPicker.rbTaskFilterClick(Sender: TObject);
var
newFilter: string;
begin
await(ReloadForDate);
if Sender = rbMyTasks then
newFilter := 'MY'
else if Sender = rbFocusedTasks then
newFilter := 'FOCUSED'
else
newFilter := 'ALL';
// A click on the radio that's already checked changes nothing
if newFilter = FTaskFilter then
Exit;
FTaskFilter := newFilter;
ClearStatus;
HideTaskNotice;
await(ReloadForTaskFilter);
end;
[async] procedure TTaskPickerOffCanvas.ScopeChanged(Event: TJSEvent);
// Reloads the projects (and so the customers) for the task filter: My Tasks
// and Focused Tasks list only customers and projects with a task assigned to /
// focused by the user. The customer, project and task stay chosen while they're
// still listed; the project's loaded tasks are just refiltered. Returns False
// when the load failed or the user changed something meanwhile.
[async] function TFTaskPicker.ReloadForTaskFilter: Boolean;
var
projectId: string;
token: Integer;
begin
Result := False;
Inc(FPrefillToken); // user took over; abandon any prefill still loading
token := FPrefillToken;
ClearStatus;
ApplyScope(SelectedValue('task_picker_scope'));
SetSelectValue('task_picker_customer', '');
ClearSelect('task_picker_project', True);
ClearSelect('task_picker_task', True);
UpdateFocusCheckbox;
projectId := cboProject.Value;
try
await(LoadProjects(''));
......@@ -850,44 +985,70 @@ begin
end;
end;
// Another scope was picked while this list was loading
if token <> FPrefillToken then
Exit;
FilterProjects('');
// FillCustomers kept the customer if it still has a listed project, and a
// listed project's customer is always listed
FilterProjects(cboCustomer.Value);
if (FHeldTaskId <> '') and (FindDisplay(FProjects, FHeldProjectId) <> '') then
begin
if not await(RestoreHeldTask(token)) then
Exit;
end
else if (projectId <> '') and (FindDisplay(FProjects, projectId) <> '') then
begin
cboProject.Value := projectId;
FillTasks; // keeps the chosen task when the filter still lists it
end
else
begin
// The chosen project (if any) has no task for this filter
FTasks := TJSArray.new;
FTasksProjectId := '';
FVisibleTasks := TJSArray.new;
ClearCombo(cboTask, True);
end;
UpdateFocusCheckbox;
Result := True;
end;
procedure TTaskPickerOffCanvas.CustomerChanged(Event: TJSEvent);
var
customerId: string;
procedure TFTaskPicker.cboCustomerChange(Sender: TObject);
begin
Inc(FPrefillToken); // user took over; abandon any prefill still loading
HoldTask('', ''); // browsing elsewhere: a filter change no longer brings the task back
ClearStatus;
ClearSelect('task_picker_project', True);
ClearSelect('task_picker_task', True);
HideTaskNotice;
ClearCombo(cboProject, True);
ClearCombo(cboTask, True);
UpdateFocusCheckbox;
customerId := SelectedValue('task_picker_customer');
FilterProjects(customerId);
FilterProjects(cboCustomer.Value);
end;
[async] procedure TTaskPickerOffCanvas.ProjectChanged(Event: TJSEvent);
[async] procedure TFTaskPicker.cboProjectChange(Sender: TObject);
var
projectId: string;
customerId: string;
project: TJSObject;
i: Integer;
token: Integer;
begin
Inc(FPrefillToken); // user took over; abandon any prefill still loading
token := FPrefillToken;
HoldTask('', ''); // browsing elsewhere: a filter change no longer brings the task back
ClearStatus;
ClearSelect('task_picker_task', True);
HideTaskNotice;
ClearCombo(cboTask, True);
UpdateFocusCheckbox;
projectId := SelectedValue('task_picker_project');
projectId := cboProject.Value;
if projectId = '' then
Exit;
customerId := SelectedValue('task_picker_customer');
customerId := cboCustomer.Value;
// No customer chosen: fill it in from the project
if customerId = '' then
......@@ -903,141 +1064,226 @@ begin
end;
end;
TJSHTMLSelectElement(document.getElementById('task_picker_customer')).value := customerId;
cboCustomer.Value := customerId;
FilterProjects(customerId);
TJSHTMLSelectElement(document.getElementById('task_picker_project')).value := projectId;
cboProject.Value := projectId;
end;
try
await(LoadTasks(projectId));
except
on E: Exception do
begin
SetStatus('Unable to load tasks.');
Exit;
end;
end;
// The user changed something else while the tasks were loading
if token <> FPrefillToken then
Exit;
// Back on this project's last task when the task filter lists it
if (projectId = FLastProjectId) and (FindDisplay(FVisibleTasks, FLastTaskId) <> '') then
begin
cboTask.Value := FLastTaskId;
HoldTask(FLastTaskId, projectId);
UpdateFocusCheckbox;
end;
end;
procedure TTaskPickerOffCanvas.UpdateFocusCheckbox;
var
addFocus: TJSHTMLInputElement;
statusSelect: TJSHTMLSelectElement;
procedure TFTaskPicker.UpdateFocusCheckbox;
begin
// Reset the checkbox to the task's saved focus state (discards any unsaved toggle)
FSavedFocus := IsTaskFocused(SelectedValue('task_picker_task'));
addFocus := FocusCheckbox;
if Assigned(addFocus) then
addFocus.checked := FSavedFocus;
FSavedFocus := IsTaskFocused(cboTask.Value);
chkFocusedTask.Checked := FSavedFocus;
// Same for the Status dropdown: back to the task's saved status (blank with no task)
FSavedTaskStatus := TaskStatus(SelectedValue('task_picker_task'));
FSavedTaskStatus := TaskStatus(cboTask.Value);
cboTaskStatus.Value := FSavedTaskStatus;
statusSelect := TaskStatusSelect;
if Assigned(statusSelect) then
statusSelect.value := FSavedTaskStatus;
// And the End Date: the task's COMPLETION_DATE, blank when it has none or no task
FSavedEndDate := TaskEndDate(cboTask.Value);
edtEndDate.Text := FSavedEndDate;
UpdateButtons;
end;
procedure TTaskPickerOffCanvas.TaskChanged(Event: TJSEvent);
procedure TFTaskPicker.cboTaskChange(Sender: TObject);
begin
Inc(FPrefillToken); // user took over; abandon any prefill still loading
// The picked task is the one held through filter changes (none for the blank option)
HoldTask(cboTask.Value, cboProject.Value);
if cboTask.Value = '' then
begin
// Cleared on purpose: re-picking the project shouldn't bring it back
FLastTaskId := '';
FLastProjectId := '';
end;
ClearStatus;
HideTaskNotice;
UpdateFocusCheckbox;
ShowTaskAvailability;
end;
procedure TTaskPickerOffCanvas.FocusCheckboxChanged(Event: TJSEvent);
procedure TFTaskPicker.chkFocusedTaskClick(Sender: TObject);
begin
ClearStatus;
UpdateButtons;
end;
// Only marks the change; Save sends it, like the Focused Task checkbox
procedure TTaskPickerOffCanvas.TaskStatusChanged(Event: TJSEvent);
// Only marks the change; Save sends it, like the Focused Task checkbox. The End
// Date follows the status so the user sees what Save will store and can adjust
// it: back to the saved one for the saved status, the Work Date (today when
// blank) for a blank End Date on Closed or Complete, blank for any other status.
procedure TFTaskPicker.cboTaskStatusChange(Sender: TObject);
var
newStatus: string;
begin
ClearStatus;
newStatus := cboTaskStatus.Value;
if newStatus = FSavedTaskStatus then
edtEndDate.Text := FSavedEndDate
else if (newStatus = 'CLOSED') or (newStatus = 'COMP') then
begin
if edtEndDate.Text = '' then
begin
if PickerDate <> '' then
edtEndDate.Text := PickerDate
else
edtEndDate.Text := FormatDateTime('yyyy-mm-dd', Date);
end;
end
else
edtEndDate.Text := '';
UpdateButtons;
end;
// Only marks the change; Save sends it with the Status
procedure TFTaskPicker.edtEndDateChange(Sender: TObject);
begin
ClearStatus;
UpdateButtons;
end;
procedure TTaskPickerOffCanvas.SelectClicked(Event: TJSEvent);
// Puts Focused Task, Status and End Date back to their saved values
procedure TFTaskPicker.ResetChanges;
begin
chkFocusedTask.Checked := FSavedFocus;
cboTaskStatus.Value := FSavedTaskStatus;
edtEndDate.Text := FSavedEndDate;
UpdateButtons;
end;
// The X closes without picking a task, like Esc
procedure TFTaskPicker.btnCloseClick(Sender: TObject);
begin
if FSaving then
Exit;
ModalResult := mrCancel;
end;
// With unsaved changes, Cancel undoes them and the picker stays open;
// with none, it closes the picker
procedure TFTaskPicker.btnCancelClick(Sender: TObject);
begin
if FSaving then
Exit;
if not FHasChanges then
begin
ModalResult := mrCancel;
Exit;
end;
ResetChanges;
ClearStatus;
end;
procedure TFTaskPicker.btnSelectClick(Sender: TObject);
var
taskId: string;
reason: string;
begin
Event.preventDefault;
taskId := SelectedValue('task_picker_task');
taskId := cboTask.Value;
if taskId = '' then
begin
SetStatus('Select a task.');
Exit;
end;
// Listed but can't take hours on this date (completed, not started, or
// outside employment); the picker stays open so the date or task can change
// Every task can be picked in the dropdown, but one that can't take hours on
// the Work Date (future date, outside employment, or outside the task's or
// project's dates) isn't sent to the grid: the reason shows under the Task
// dropdown and the picker stays open so the date or task can change
reason := TaskUnavailableReason(taskId);
if reason <> '' then
begin
SetStatus(reason);
ShowTaskNotice(reason);
Exit;
end;
ClearStatus;
// Sends the task and work date to the grid only; focus and status changes happen through Save
if Assigned(FOnTaskPicked) then
FOnTaskPicked(FRowIndex, taskId, FindDisplay(FTasks, taskId), PickerDate);
// The caller puts the task and work date on the row; focus and status changes happen through Save
FSelectedTaskId := taskId;
FSelectedTaskDisplay := FindDisplay(FTasks, taskId);
FSelectedTaskDate := PickerDate;
Hide;
ModalResult := mrOk;
end;
[async] procedure TTaskPickerOffCanvas.SaveClicked(Event: TJSEvent);
[async] procedure TFTaskPicker.btnSaveClick(Sender: TObject);
var
taskId: string;
taskDisplay: string;
projectId: string;
methodName: string;
newStatus: string;
addFocus: TJSHTMLInputElement;
statusSelect: TJSHTMLSelectElement;
endDate: string;
focused: Boolean;
focusChanged: Boolean;
statusChanged: Boolean;
endDateChanged: Boolean;
statusSaved: Boolean;
focusFailed: Boolean;
token: Integer;
begin
Event.preventDefault;
if FSaving then
Exit;
taskId := SelectedValue('task_picker_task');
if taskId = '' then
begin
SetStatus('Select a task.');
Exit;
end;
// Focus, Status and End Date belong to the task, so they need one picked
taskId := cboTask.Value;
addFocus := FocusCheckbox;
statusSelect := TaskStatusSelect;
if (not Assigned(addFocus)) or (not Assigned(statusSelect)) then
Exit;
focused := chkFocusedTask.Checked;
focusChanged := (taskId <> '') and (focused <> FSavedFocus);
focused := addFocus.checked;
focusChanged := focused <> FSavedFocus;
newStatus := cboTaskStatus.Value;
statusChanged := (taskId <> '') and (newStatus <> '') and (newStatus <> FSavedTaskStatus);
newStatus := statusSelect.value;
statusChanged := (newStatus <> '') and (newStatus <> FSavedTaskStatus);
endDate := edtEndDate.Text;
endDateChanged := (taskId <> '') and (endDate <> FSavedEndDate);
if (not focusChanged) and (not statusChanged) then
if (not focusChanged) and (not statusChanged) and (not endDateChanged) then
begin
UpdateButtons;
Exit;
end;
// End Date isn't required, except that emT3 needs one for a Closed or
// Complete task (the server checks this too)
if (statusChanged or endDateChanged) and (endDate = '') and
((newStatus = 'CLOSED') or (newStatus = 'COMP')) then
begin
SetStatus('A Closed or Complete task needs an End Date.');
Exit;
end;
taskDisplay := FindDisplay(FTasks, taskId);
projectId := SelectedValue('task_picker_project');
projectId := cboProject.Value;
statusSaved := False;
focusFailed := False;
......@@ -1045,25 +1291,30 @@ begin
FSaving := True;
UpdateButtons;
try
// Status first: closing the task decides whether it can still be focused
if statusChanged then
// Status and End Date first, together: the End Date decides whether the
// task can still be focused
if statusChanged or endDateChanged then
begin
try
await(FClient.RawInvokeAsync('ITimeEntryService.SetTaskStatus',
[taskId, newStatus, PickerDate]));
await(xdwcTaskPicker.RawInvokeAsync('ITimeEntryService.SetTaskStatusAndEndDate',
[taskId, newStatus, endDate]));
statusSaved := True;
except
on E: EXDataClientRequestException do
SetStatus(E.ErrorResult.ErrorMessage);
on E: Exception do
SetStatus('Unable to save task status.');
SetStatus('Unable to save the task''s status and End Date.');
end;
if not statusSaved then
Exit;
if SelectedValue('task_picker_task') = taskId then
FSavedTaskStatus := newStatus;
if cboTask.Value = taskId then
begin
if newStatus <> '' then
FSavedTaskStatus := newStatus;
FSavedEndDate := endDate;
end;
end;
if focusChanged then
......@@ -1074,7 +1325,7 @@ begin
methodName := 'ITimeEntryService.RemoveTaskFromFocus';
try
await(FClient.RawInvokeAsync(methodName, [FUserId, taskId]));
await(xdwcTaskPicker.RawInvokeAsync(methodName, [FUserId, taskId]));
except
on E: EXDataClientRequestException do
begin
......@@ -1093,7 +1344,7 @@ begin
SetTaskFocused(taskId, taskDisplay, focused);
// The user may have picked a different task while the request was running
if SelectedValue('task_picker_task') = taskId then
if cboTask.Value = taskId then
FSavedFocus := focused;
if Assigned(FOnFocusChanged) then
......@@ -1105,12 +1356,11 @@ begin
UpdateButtons;
end;
// Reload the task list so its completed flag and availability follow the new
// status. A task closed here gets the Work Date as its completion date, so it
// stays listed for this date. Skipped when the user has moved to another task
// or project meanwhile.
if (not statusSaved) or (SelectedValue('task_picker_task') <> taskId) or
(SelectedValue('task_picker_project') <> projectId) then
// Reload the task list so its End Date and availability follow what was
// saved (a task closed on the Work Date can still take hours on it). Skipped
// when the user has moved to another task or project meanwhile.
if (not statusSaved) or (cboTask.Value <> taskId) or
(cboProject.Value <> projectId) then
Exit;
Inc(FPrefillToken);
......@@ -1130,57 +1380,69 @@ begin
Exit;
if FindDisplay(FTasks, taskId) <> '' then
SetSelectValue('task_picker_task', taskId);
begin
// The saved change can drop it from My Tasks / Focused: keep it selected
// under All Tasks, which lists its customer and project too
if FindDisplay(FVisibleTasks, taskId) = '' then
begin
SetTaskFilter('ALL');
if not await(ReloadForTaskFilter) then
Exit;
end;
UpdateFocusCheckbox;
cboTask.Value := taskId;
end;
// Keep a focus error on screen rather than replacing it
if not focusFailed then
ShowTaskAvailability;
UpdateFocusCheckbox;
end;
[async] procedure TTaskPickerOffCanvas.Open(
// Called after Load, before Execute: fills the form for the row and loads the
// lists while it shows
[async] procedure TFTaskPicker.Start(
const AUserId: string;
ARowIndex: Integer;
AFocusedTasks: TJSArray;
const ATaskId, ATaskDate: string
);
var
token: Integer;
dateEl: TJSHTMLInputElement;
begin
FUserId := AUserId;
FRowIndex := ARowIndex;
// Start from the row's (draft) work date; it is only used to validate the chosen task
FTasks := TJSArray.new;
dateEl := TJSHTMLInputElement(document.getElementById('task_picker_date'));
if Assigned(dateEl) then
dateEl.value := ATaskDate;
edtWorkDate.Text := ATaskDate;
Inc(FPrefillToken);
token := FPrefillToken;
// Work on a copy so the grid's task options are only changed through FOnFocusChanged
// Work on a copy so the grid's task options are only changed through OnFocusChanged
if Assigned(AFocusedTasks) then
FFocusedTasks := AFocusedTasks.slice(0)
else
FFocusedTasks := TJSArray.new;
ClearStatus;
ApplyScope(FScope); // reopen on the last scope picked
ClearSelect('task_picker_customer', True);
ClearSelect('task_picker_project', True);
ClearSelect('task_picker_task', True);
// Always opens as wide as possible: All Projects and All Tasks. The user can
// narrow it from there; nothing is remembered for the next open.
ApplyScope('ALL');
SetTaskFilter('ALL');
ClearCombo(cboCustomer, True);
ClearCombo(cboProject, True);
ClearCombo(cboTask, True);
UpdateFocusCheckbox;
Show;
try
await(LoadCustomers);
if not FStatusesLoaded then
await(LoadStatuses);
if FClosed then
Exit;
await(LoadStatuses);
if FClosed then
Exit;
await(LoadProjects(''));
if FClosed then
Exit;
FilterProjects('');
except
on E: Exception do
......
......@@ -147,6 +147,9 @@ object FTimeEntries: TFTimeEntries
object xdwdsTimeEntriessummary: TStringField
FieldName = 'summary'
end
object xdwdsTimeEntriesdetails: TStringField
FieldName = 'details'
end
object xdwdsTimeEntriesplace: TStringField
FieldName = 'place'
end
......
......@@ -3,6 +3,13 @@
<h5 class="mb-0 text-nowrap" id="lbl_time_entries_title"></h5>
<div class="d-flex align-items-center gap-2 ms-auto flex-nowrap">
<!-- Compact View hides the Time and Place columns (Hours always shows); saved per user (users.HIDE_TIME_ENTRIES_FIELDS) -->
<div class="form-check mb-0 me-2 text-nowrap">
<input class="form-check-input" type="checkbox" id="chk_hide_time_fields" />
<label class="form-check-label small" for="chk_hide_time_fields"
title="Hide the Time and Place columns">Compact View</label>
</div>
<div id="lbl_time_total_hours" class="me-2 text-nowrap fw-semibold">Total Hours: 0</div>
<div id="lbl_time_total_rows" class="me-2 text-nowrap"></div>
......@@ -43,86 +50,21 @@
<div id="time_entries_table_host" class="flex-grow-1 min-h-0 overflow-auto"></div>
<div class="modal fade" tabindex="-1" id="task_picker_modal" aria-labelledby="task_picker_title" aria-hidden="true" data-bs-backdrop="static">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="task_picker_title">Find Task</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="row g-2 mb-3">
<div class="col-md-4">
<label for="task_picker_date" class="form-label">Work Date</label>
<input type="date" id="task_picker_date" class="form-control form-control-sm"
title="Select also sets the row's date. Only projects and tasks open on this date are listed." />
</div>
</div>
<div class="row g-2 align-items-end mb-3">
<div class="col-md">
<label for="task_picker_scope" class="form-label">Show</label>
<select id="task_picker_scope" class="form-select form-select-sm">
<option value="MY" selected>My Projects</option>
<option value="ACTIVE">Active Projects</option>
<option value="ALL">All Projects</option>
</select>
</div>
<div class="col-md" id="task_picker_customer_group">
<label for="task_picker_customer" class="form-label">Customer</label>
<select id="task_picker_customer" class="form-select form-select-sm">
<option value=""></option>
</select>
</div>
<div class="col-md">
<label for="task_picker_project" class="form-label">Project</label>
<select id="task_picker_project" class="form-select form-select-sm" disabled>
<option value=""></option>
</select>
</div>
</div>
<div class="row g-2 align-items-end mb-3">
<div class="col-md">
<label for="task_picker_task" class="form-label">Task</label>
<select id="task_picker_task" class="form-select form-select-sm" disabled>
<option value=""></option>
</select>
</div>
</div>
<div id="task_picker_status" class="alert alert-danger py-1 px-2 mb-0 d-none small"></div>
</div>
<div class="modal-footer">
<div class="d-flex align-items-center gap-2">
<input class="form-check-input m-0" type="checkbox" id="task_picker_add_focus" />
<label class="form-check-label mb-0" for="task_picker_add_focus">
Focused Task
</label>
</div>
<!-- The selected task's own status; Save applies it with Focused Task -->
<div class="d-flex align-items-center gap-2 ms-3 me-auto">
<label for="task_picker_task_status" class="form-label mb-0">Status</label>
<select id="task_picker_task_status" class="form-select form-select-sm" style="width: 9rem;" disabled></select>
</div>
<button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="modal">
Cancel
</button>
<!-- Details (time_items.DETAILS) for one row; OK puts it on the row, the row's Save stores it.
Static backdrop so a stray click outside doesn't throw away typed text. -->
<div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasTimeDetails" aria-labelledby="time_details_title"
data-bs-backdrop="static" style="--bs-offcanvas-width: min(40rem, 100vw);">
<div class="offcanvas-header">
<h5 class="offcanvas-title" id="time_details_title">Details</h5>
<button type="button" class="btn-close" data-bs-dismiss="offcanvas" aria-label="Close"></button>
</div>
<button type="button" class="btn btn-outline-success btn-sm" id="btn_task_picker_save" disabled>
Save
</button>
<div class="offcanvas-body d-flex flex-column">
<textarea id="time_details_text" class="form-control flex-grow-1 mb-3" style="resize: none;" aria-labelledby="time_details_title"></textarea>
<button type="button" class="btn btn-primary btn-sm" id="btn_task_picker_select" disabled>
Select
</button>
</div>
<div class="d-flex justify-content-end gap-2">
<button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="offcanvas">Cancel</button>
<button type="button" class="btn btn-primary btn-sm" id="btn_time_details_ok">OK</button>
</div>
</div>
</div>
......
......@@ -5,7 +5,7 @@ interface
uses
System.SysUtils, System.Classes, System.DateUtils, JS, Web, WEBLib.Graphics, WEBLib.Controls,
WEBLib.Forms, WEBLib.Dialogs, Vcl.Controls, Vcl.StdCtrls, WEBLib.StdCtrls, WEBLib.ExtCtrls, System.StrUtils,
XData.Web.Client, ConnectionModule, XData.Web.JsonDataset, Data.DB, XData.Web.Dataset, uTaskPickerOffCanvas;
XData.Web.Client, ConnectionModule, XData.Web.JsonDataset, Data.DB, XData.Web.Dataset;
type
TFTimeEntries = class(TWebForm)
......@@ -22,6 +22,7 @@ type
xdwdsTimeEntriestaskTime: TStringField;
xdwdsTimeEntriescategory: TStringField;
xdwdsTimeEntriessummary: TStringField;
xdwdsTimeEntriesdetails: TStringField;
xdwdsTimeEntriescategoryDesc: TStringField;
btnAddEntry: TWebButton;
lblValidationMessage: TWebLabel;
......@@ -52,13 +53,13 @@ type
FPendingEntryId: string;
FLastMouseDownRowIndex: Integer;
FLastMouseDownTime: Double;
FTaskPickerOffCanvas: TTaskPickerOffCanvas;
FAddingNewEntry: Boolean;
FNewEntryRowIndex: Integer;
FEditingEntryId: Integer;
FEditingRowIndex: Integer;
FOriginalTaskDate: string;
FOriginalHours: Double;
FOriginalHoursBlank: Boolean; // Hours was blank (NULL) before the draft
FOriginalTaskId: string;
FOriginalTaskDisplay: string;
FOriginalTaskTime: string;
......@@ -67,11 +68,15 @@ type
FOriginalCategory: string;
FOriginalCategoryDesc: string;
FOriginalSummary: string;
FUserStartDate: string;
FUserEndDate: string;
FOriginalDetails: string;
FDetailsRowIndex: Integer; // row whose Details the offcanvas is editing
FKeptEntryIds: string; // comma list of entries saved outside the range, shown until the range changes
FHideFields: Boolean; // Compact View: Time and Place aren't rendered (Hours always is)
FHideFieldsLoaded: Boolean; // the saved setting is applied from the first load only
[async] procedure LoadTimeEntries;
[async] procedure HideFieldsChanged(Event: TJSEvent);
procedure SetHideFieldsCheckbox(AChecked: Boolean);
procedure KeepEntryIfOutsideRange(const AEntryId, ATaskDate: string);
function BeginAddEntry: Boolean;
function IsNewEntryRow(AIndex: Integer): Boolean;
......@@ -81,6 +86,10 @@ type
procedure NewEntryCancelClick(Event: TJSEvent);
[async] procedure EntryDraftSaveClick(Event: TJSEvent);
procedure EntryDraftCancelClick(Event: TJSEvent);
procedure DetailsButtonClick(Event: TJSEvent);
procedure DetailsOkClick(Event: TJSEvent);
procedure ShowDetailsEditor;
procedure HideDetailsEditor;
function BuildTimeEntryPayload(const AEntryId: string): TJSObject;
procedure BeginEntryDraft(AIndex: Integer);
procedure ClearEntryDraft;
......@@ -89,8 +98,8 @@ type
function BlockForDraftRow(AIndex: Integer; const AAction: string): Boolean;
procedure DocumentFocusIn(Event: TJSEvent);
function JsText(const AValue: JSValue): string;
function IsTaskOpenOn(const ATaskStart, ATaskEnd, ADate: string): Boolean;
procedure RefreshTaskOptionStates(AIndex: Integer; const ADate: string);
[async] function GetTaskDateProblem(AIndex: Integer): string;
procedure ShowTaskDateNotice(AIndex: Integer; const AMessage: string);
[async] procedure SaveNewEntry;
procedure CancelNewEntry;
procedure RenderTable;
......@@ -113,6 +122,9 @@ type
procedure RowFocusOut(Event: TJSEvent);
procedure RowClick(Event: TJSEvent);
function ValidateRow(AIndex: Integer): Boolean;
function CheckSummaryLength(AIndex: Integer): Boolean;
function DetailsButtonClass(const ADetails: string): string;
function DetailsButtonTitle(const ADetails: string): string;
procedure ApplyPendingEntryFocus;
procedure ApplyRowValidation(AIndex: Integer);
procedure ClearRowValidation(AIndex: Integer);
......@@ -140,14 +152,21 @@ implementation
uses
Auth.Service,
Utils,
View.Main;
View.Main,
View.TaskPicker;
{$R *.dfm}
const
// Web-only limit; time_items.SUMMARY itself is TEXT
SUMMARY_MAX_LENGTH = 500;
procedure TFTimeEntries.WebFormCreate(Sender: TObject);
var
payload: TJSObject;
anchorDate: string;
detailsOk: TJSHTMLElement;
hideFields: TJSHTMLElement;
begin
console.log('TFTimeEntries.WebFormCreate fired');
......@@ -167,8 +186,18 @@ begin
FNewEntryRowIndex := -1;
FEditingEntryId := 0;
FEditingRowIndex := -1;
FDetailsRowIndex := -1;
FHideFields := False;
FHideFieldsLoaded := False;
// The Details offcanvas is part of the form's html, so its OK button is wired once here
detailsOk := TJSHTMLElement(document.getElementById('btn_time_details_ok'));
if Assigned(detailsOk) then
detailsOk.addEventListener('click', TJSEventHandler(@DetailsOkClick));
FTaskPickerOffCanvas :=TTaskPickerOffCanvas.Create(xdwcTimeEntries, @TaskPickerTaskSelected, @TaskPickerFocusChanged);
hideFields := TJSHTMLElement(document.getElementById('chk_hide_time_fields'));
if Assigned(hideFields) then
hideFields.addEventListener('change', TJSEventHandler(@HideFieldsChanged));
document.addEventListener('mousedown', TJSEventHandler(@DocumentMouseDown));
document.addEventListener('focusin', TJSEventHandler(@DocumentFocusIn));
......@@ -411,8 +440,15 @@ begin
else
SetTimeEntriesLabel(FUserName);
FUserStartDate := JsText(resultObj['userStartDate']);
FUserEndDate := JsText(resultObj['userEndDate']);
// Saved Compact View setting; after the first load the checkbox is the
// source, so a reload can't undo a change that is still being saved
if not FHideFieldsLoaded then
begin
FHideFields := JS.isBoolean(resultObj['hideTimeEntriesFields']) and
Boolean(resultObj['hideTimeEntriesFields']);
FHideFieldsLoaded := True;
SetHideFieldsCheckbox(FHideFields);
end;
rowCount := StrToIntDef(string(resultObj['count']), 0);
SetTotalRowsLabel(rowCount);
......@@ -441,6 +477,47 @@ begin
end;
procedure TFTimeEntries.SetHideFieldsCheckbox(AChecked: Boolean);
var
chk: TJSHTMLInputElement;
begin
chk := TJSHTMLInputElement(document.getElementById('chk_hide_time_fields'));
if Assigned(chk) then
chk.checked := AChecked;
end;
// Compact View: re-renders the grid without (or with) Time and Place,
// then saves the choice to users.HIDE_TIME_ENTRIES_FIELDS for the next session.
// Row values aren't touched, so drafts and unsaved edits carry over.
[async] procedure TFTimeEntries.HideFieldsChanged(Event: TJSEvent);
var
hide: Boolean;
begin
hide := TJSHTMLInputElement(Event.target).checked;
FHideFields := hide;
FHideFieldsLoaded := True;
if xdwdsTimeEntries.Active then
begin
CaptureTableScroll;
RenderTable;
end;
if FUserId = '' then
Exit;
try
await(xdwcTimeEntries.RawInvokeAsync(
'ITimeEntryService.SetHideTimeEntriesFields', [FUserId, hide]
));
except
on E: EXDataClientRequestException do
Utils.ShowErrorModal('Unable to save the Compact View setting: ' + E.ErrorResult.ErrorMessage);
end;
end;
// A saved entry dated outside Start-End stays in the grid until the range changes
procedure TFTimeEntries.KeepEntryIfOutsideRange(const AEntryId, ATaskDate: string);
begin
......@@ -465,7 +542,8 @@ var
html: string;
rowIdx: Integer;
hoursText: string;
rowDate: string;
colCount: Integer;
tableMinWidth: Integer;
function Th(const s: string): string;
begin
......@@ -517,18 +595,16 @@ var
optionValue: string;
optionDisplay: string;
triggerId: string;
taskAttrs: string;
taskStart: string;
taskEnd: string;
openTaskCount: Integer;
begin
triggerId := 'time_dd_' + FieldName + '_' + IntToStr(AIdx);
openTaskCount := 0;
Result := '';
// The task field's wrapper also holds the red popup ShowTaskDateNotice
// shows under it, like the Summary's
if AShowTaskPicker then
Result := Result +
'<div class="time-task-wrap">' +
'<div class="input-group input-group-sm flex-nowrap w-100">';
Result := Result +
......@@ -554,44 +630,23 @@ var
'data-trigger-id="' + triggerId + '">&nbsp;</button>';
end;
// Every focused task is listed whatever the row's date; whether it can take
// hours on that date is checked when the row is saved (GetTaskDateProblem)
for i := 0 to Items.length - 1 do
begin
optionObj := TJSObject(Items[i]);
optionValue := string(optionObj[ValueProp]);
optionDisplay := string(optionObj[DisplayProp]);
// Tasks carry their date window; ones not open on the row's date are
// hidden (and disabled), like emT3's Time Entry screen
taskAttrs := '';
if FieldName = 'taskId' then
begin
taskStart := JsText(optionObj['startDate']);
taskEnd := JsText(optionObj['completionDate']);
taskAttrs := 'data-start="' + taskStart + '" data-end="' + taskEnd + '" ';
if IsTaskOpenOn(taskStart, taskEnd, rowDate) then
Inc(openTaskCount)
else
taskAttrs := taskAttrs + 'disabled hidden ';
end;
Result := Result +
'<button type="button" class="dropdown-item time-dd-item" ' +
'data-idx="' + IntToStr(AIdx) + '" ' +
'data-field="' + FieldName + '" ' +
'data-value="' + HtmlEncode(optionValue) + '" ' +
'data-display="' + HtmlEncode(optionDisplay) + '" ' +
taskAttrs +
'data-trigger-id="' + triggerId + '">' + HtmlEncode(optionDisplay) + '</button>';
end;
// Shown instead of an empty menu when no focused task is open on the row's date
if FieldName = 'taskId' then
Result := Result +
'<span class="dropdown-item-text small text-body-secondary time-dd-empty" ' +
'data-idx="' + IntToStr(AIdx) + '"' +
IfThen(openTaskCount > 0, ' hidden', '') + '>' +
'No focused tasks are open on this date.</span>';
Result := Result +
'</div>' +
'</div>';
......@@ -610,40 +665,71 @@ var
'<li><button type="button" class="dropdown-item time-task-items-btn" data-idx="' + IntToStr(AIdx) + '"' +
IfThen(CurrentValue = '', ' disabled', '') + '>Task Items</button></li>' +
'</ul>' +
'</div>' +
'<div class="time-summary-notice time-summary-notice-error time-task-notice" ' +
'data-idx="' + IntToStr(AIdx) + '" role="status" aria-live="polite" hidden></div>' +
'</div>';
end;
end;
function SummaryTextArea(const FieldName, Value: string; const AIdx: Integer): string;
// maxlength stops typing/pasting past the limit. Typing into the limit glows red
// with "Maximum length is 500 characters"; a cut-off paste glows amber with its
// own notice. Both use the popup under the field (EnableAutoGrowTextAreas)
// The Details button sits to the right of the summary on every row,
// filled in when the row has details
function SummaryTextArea(const FieldName, Value, ADetails: string; const AIdx: Integer): string;
begin
Result :=
'<textarea rows="1" class="form-control form-control-sm cell-textarea time-textarea time-editor w-100" ' +
'data-idx="' + IntToStr(AIdx) + '" data-field="' + FieldName + '" ' +
'style="min-height:31px; height:31px; overflow:hidden; resize:none;">' + HtmlEncode(Value) + '</textarea>';
'<div class="d-flex align-items-start gap-1">' +
'<div class="time-summary-wrap flex-grow-1">' +
'<textarea rows="1" class="form-control form-control-sm cell-textarea time-textarea time-editor w-100" ' +
'data-idx="' + IntToStr(AIdx) + '" data-field="' + FieldName + '" ' +
'maxlength="' + IntToStr(SUMMARY_MAX_LENGTH) + '" ' +
'style="min-height:31px; height:31px; overflow:hidden; resize:none;">' + HtmlEncode(Value) + '</textarea>' +
'<div class="time-summary-notice" role="status" aria-live="polite" hidden></div>' +
'</div>' +
'<button type="button" class="' + DetailsButtonClass(ADetails) + '" ' +
'title="' + DetailsButtonTitle(ADetails) + '" ' +
'data-idx="' + IntToStr(AIdx) + '">Details</button>' +
'</div>';
end;
begin
host := TJSHTMLElement(document.getElementById('time_entries_table_host'));
// Compact View leaves Time (140) and Place (160) out entirely;
// Every column but Summary has a fixed width; Summary's <col> has none, so it
// takes whatever width the table has past the min-width (never less than 525)
if FHideFields then
begin
colCount := 5;
tableMinWidth := 1770 - 140 - 160;
end
else
begin
colCount := 7;
tableMinWidth := 1770;
end;
html :=
'<div class="time-vscroll">' +
'<div class="time-hscroll">' +
'<table class="table table-sm table-bordered align-middle mb-0 time-table" style="min-width: 1710px; table-layout: fixed;">' +
'<table class="table table-sm table-bordered align-middle mb-0 time-table" style="min-width: ' + IntToStr(tableMinWidth) + 'px; table-layout: fixed;">' +
'<colgroup>' +
'<col style="width:140px">' + // Date
'<col style="width:540px">' + // Task
'<col style="width:125px">' + // Date
'<col style="width:560px">' + // Task
'<col style="width:90px">' + // Hours
'<col style="width:140px">' + // Time
'<col style="width:160px">' + // Place
IfThen(not FHideFields,
'<col style="width:140px">' + // Time
'<col style="width:160px">', '') + // Place
'<col style="width:190px">' + // Category
'<col style="width:450px">' + // Summary
'<col>' + // Summary + Details button: takes the rest
'</colgroup>' +
'<thead><tr>' +
Th('Date') +
Th('Task') +
Th('Hours') +
Th('Time') +
Th('Place') +
IfThen(not FHideFields, Th('Time') + Th('Place'), '') +
Th('Category') +
Th('Summary') +
'</tr></thead><tbody>';
......@@ -657,28 +743,35 @@ begin
else
hoursText := FormatFloat('0.##', xdwdsTimeEntrieshours.AsFloat);
rowDate := xdwdsTimeEntriestaskDate.AsString;
html := html +
'<tr class="time-row-selectable" data-idx="' + IntToStr(rowIdx) + '" data-entry-id="' + IntToStr(xdwdsTimeEntriesentryId.AsInteger) + '" data-task-id="' + xdwdsTimeEntriestaskId.AsString + '">' +
TdNowrap(DateInput('taskDate', xdwdsTimeEntriestaskDate.AsString, rowIdx)) +
TdNowrap(SelectList('taskId', xdwdsTimeEntriestaskId.AsString, xdwdsTimeEntriestaskDisplay.AsString, rowIdx, FTaskOptions, 'taskId', 'taskDisplay', False, True)) +
TdNowrap(HoursInput('hours', hoursText, rowIdx)) +
TdNowrap(HoursInput('hours', hoursText, rowIdx));
if not FHideFields then
html := html +
TdNowrap(TextInput('taskTime', xdwdsTimeEntriestaskTime.AsString, rowIdx)) +
TdNowrap(SelectList('place', xdwdsTimeEntriesplace.AsString, xdwdsTimeEntriesplaceDesc.AsString, rowIdx, FPlaceOptions, 'code', 'codeDesc', True, False)) +
TdNowrap(SelectList('place', xdwdsTimeEntriesplace.AsString, xdwdsTimeEntriesplaceDesc.AsString, rowIdx, FPlaceOptions, 'code', 'codeDesc', True, False));
html := html +
TdNowrap(SelectList('category', xdwdsTimeEntriescategory.AsString, xdwdsTimeEntriescategoryDesc.AsString, rowIdx, FCategoryOptions, 'code', 'codeDesc', False, False)) +
TdWrap(SummaryTextArea('summary', xdwdsTimeEntriessummary.AsString, rowIdx)) +
TdWrap(SummaryTextArea('summary', xdwdsTimeEntriessummary.AsString, xdwdsTimeEntriesdetails.AsString, rowIdx)) +
'</tr>';
// Row action buttons sit at the right; sticky right:0 keeps them in view
// when the table is scrolled sideways
if IsNewEntryRow(rowIdx) then
begin
html := html +
'<tr class="time-new-entry-actions-row">' +
'<td colspan="7" class="p-0 border-0">' +
'<div class="position-sticky d-inline-flex py-1 ps-2" style="left:0; z-index:5; pointer-events:none;">' +
'<div class="bg-body border rounded shadow-sm p-2 d-flex gap-2" style="pointer-events:auto;">' +
'<button type="button" id="btn_time_new_save" class="btn btn-sm btn-success">Save</button>' +
'<button type="button" id="btn_time_new_cancel" class="btn btn-sm btn-outline-secondary">Cancel</button>' +
'<td colspan="' + IntToStr(colCount) + '" class="p-0 border-0">' +
'<div class="d-flex justify-content-end">' +
'<div class="position-sticky d-inline-flex py-1 pe-2" style="right:0; z-index:5; pointer-events:none;">' +
'<div class="bg-body border rounded shadow-sm p-2 d-flex gap-2" style="pointer-events:auto;">' +
'<button type="button" id="btn_time_new_save" class="btn btn-sm btn-success">Save</button>' +
'<button type="button" id="btn_time_new_cancel" class="btn btn-sm btn-outline-secondary">Cancel</button>' +
'</div>' +
'</div>' +
'</div>' +
'</td>' +
......@@ -688,9 +781,13 @@ begin
html := html +
'<tr id="time-edit-actions-' + IntToStr(rowIdx) + '"' +
IfThen(IsDraftEntryRow, '', ' hidden') + '>' +
'<td colspan="7">' +
'<button type="button" class="btn btn-sm btn-success time-edit-save" data-idx="' + IntToStr(rowIdx) + '">Save</button> ' +
'<button type="button" class="btn btn-sm btn-outline-secondary time-edit-cancel" data-idx="' + IntToStr(rowIdx) + '">Cancel</button>' +
'<td colspan="' + IntToStr(colCount) + '">' +
'<div class="d-flex justify-content-end">' +
'<div class="position-sticky d-flex gap-2" style="right:0;">' +
'<button type="button" class="btn btn-sm btn-success time-edit-save" data-idx="' + IntToStr(rowIdx) + '">Save</button>' +
'<button type="button" class="btn btn-sm btn-outline-secondary time-edit-cancel" data-idx="' + IntToStr(rowIdx) + '">Cancel</button>' +
'</div>' +
'</div>' +
'</td>' +
'</tr>';
......@@ -762,11 +859,17 @@ begin
Result['userId'] := FUserId;
Result['taskDate'] := xdwdsTimeEntriestaskDate.AsString;
Result['taskId'] := xdwdsTimeEntriestaskId.AsString;
Result['hours'] := xdwdsTimeEntrieshours.AsFloat;
// Hours is required (ValidateRow blocks a blank); if one gets through it goes as
// null and the server rejects it rather than saving 0
if xdwdsTimeEntrieshours.IsNull then
Result['hours'] := nil
else
Result['hours'] := xdwdsTimeEntrieshours.AsFloat;
Result['taskTime'] := xdwdsTimeEntriestaskTime.AsString;
Result['place'] := xdwdsTimeEntriesplace.AsString;
Result['category'] := xdwdsTimeEntriescategory.AsString;
Result['summary'] := xdwdsTimeEntriessummary.AsString;
Result['details'] := xdwdsTimeEntriesdetails.AsString;
end;
......@@ -781,6 +884,7 @@ begin
FEditingRowIndex := AIndex;
FOriginalTaskDate := xdwdsTimeEntriestaskDate.AsString;
FOriginalHours := xdwdsTimeEntrieshours.AsFloat;
FOriginalHoursBlank := xdwdsTimeEntrieshours.IsNull;
FOriginalTaskId := xdwdsTimeEntriestaskId.AsString;
FOriginalTaskDisplay := xdwdsTimeEntriestaskDisplay.AsString;
FOriginalTaskTime := xdwdsTimeEntriestaskTime.AsString;
......@@ -789,6 +893,7 @@ begin
FOriginalCategory := xdwdsTimeEntriescategory.AsString;
FOriginalCategoryDesc := xdwdsTimeEntriescategoryDesc.AsString;
FOriginalSummary := xdwdsTimeEntriessummary.AsString;
FOriginalDetails := xdwdsTimeEntriesdetails.AsString;
end;
......@@ -805,6 +910,7 @@ begin
FOriginalCategory := '';
FOriginalCategoryDesc := '';
FOriginalSummary := '';
FOriginalDetails := '';
end;
......@@ -881,67 +987,67 @@ begin
end;
// Same rule the server enforces on Save: ADate must be inside the user's
// employment window and the task's window. Inclusive; '' = open-ended.
// All values are 'yyyy-mm-dd', so plain string comparison is date order.
function TFTimeEntries.IsTaskOpenOn(const ATaskStart, ATaskEnd, ADate: string): Boolean;
// Save-time check, like CheckSummaryLength: every focused task is listed and can
// be picked, but hours can only go on a date that isn't in the future and is
// inside the user's employment and the task's and its project's dates. The
// server answers with the same rule SaveTimeEntry enforces. Returns the reason
// ('' = allowed); if the check itself fails it returns '' and SaveTimeEntry
// reports any problem.
[async] function TFTimeEntries.GetTaskDateProblem(AIndex: Integer): string;
var
response: TXDataClientResponse;
begin
Result := True;
Result := '';
if ADate = '' then
Exit; // no date yet; required-field validation handles it
GotoRowIndex(AIndex);
if xdwdsTimeEntries.Eof then
Exit;
try
response := await(xdwcTimeEntries.RawInvokeAsync(
'ITimeEntryService.GetTimeEntryDateProblem',
[FUserId, xdwdsTimeEntriestaskId.AsString, xdwdsTimeEntriestaskDate.AsString]));
if (FUserStartDate <> '') and (ADate < FUserStartDate) then
Exit(False);
if (FUserEndDate <> '') and (ADate > FUserEndDate) then
Exit(False);
if (ATaskStart <> '') and (ADate < ATaskStart) then
Exit(False);
if (ATaskEnd <> '') and (ADate > ATaskEnd) then
Exit(False);
Result := JsText(TJSObject(response.Result)['value']);
except
on E: EXDataClientRequestException do
console.log('GetTaskDateProblem ERROR: ' + E.ErrorResult.ErrorMessage);
on E: Exception do
console.log('GetTaskDateProblem ERROR: ' + E.Message);
end;
end;
// Re-check one row's task dropdown items after its date changes, without a re-render:
// tasks not open on the new date are hidden, and the empty-menu note shows if none are left
procedure TFTimeEntries.RefreshTaskOptionStates(AIndex: Integer; const ADate: string);
// Shows AMessage like the Summary's "500 characters" error: the Task field
// glows red and the red popup under it shows for 6 seconds
procedure TFTimeEntries.ShowTaskDateNotice(AIndex: Integer; const AMessage: string);
var
nodes: TJSNodeList;
item: TJSHTMLElement;
emptyEl: TJSHTMLElement;
openTaskCount: Integer;
i: Integer;
rowEl: TJSHTMLElement;
toggleEl: TJSHTMLElement;
noticeEl: TJSHTMLElement;
begin
nodes := document.querySelectorAll(
'.time-dd-item[data-field="taskId"][data-idx="' + IntToStr(AIndex) + '"]');
// Required fields passed, so any header message is stale
HideRowValidationMessage;
openTaskCount := 0;
for i := 0 to nodes.length - 1 do
begin
item := TJSHTMLElement(nodes.item(i));
rowEl := TJSHTMLElement(document.querySelector('tr[data-idx="' + IntToStr(AIndex) + '"]'));
if not Assigned(rowEl) then
Exit;
if IsTaskOpenOn(string(item.getAttribute('data-start')),
string(item.getAttribute('data-end')), ADate) then
begin
item.removeAttribute('disabled');
item.removeAttribute('hidden');
Inc(openTaskCount);
end
else
begin
item.setAttribute('disabled', '');
item.setAttribute('hidden', '');
end;
end;
toggleEl := TJSHTMLElement(rowEl.querySelector('.time-dd-toggle[data-field="taskId"]'));
noticeEl := TJSHTMLElement(rowEl.querySelector('.time-task-notice'));
if (not Assigned(toggleEl)) or (not Assigned(noticeEl)) then
Exit;
emptyEl := TJSHTMLElement(document.querySelector(
'.time-dd-empty[data-idx="' + IntToStr(AIndex) + '"]'));
if Assigned(emptyEl) then
begin
if openTaskCount > 0 then
emptyEl.setAttribute('hidden', '')
else
emptyEl.removeAttribute('hidden');
toggleEl.focus;
asm
toggleEl.classList.remove('time-field-flash-error');
void toggleEl.offsetWidth; // restarts the animation
toggleEl.classList.add('time-field-flash-error');
noticeEl.textContent = AMessage;
noticeEl.hidden = false;
clearTimeout(noticeEl.hideTimer);
noticeEl.hideTimer = setTimeout(function() { noticeEl.hidden = true; }, 6000); // 6 seconds
end;
end;
......@@ -952,6 +1058,7 @@ var
resultObj: TJSObject;
payload: TJSObject;
newTaskDate: string;
dateProblem: string;
begin
if not FAddingNewEntry then
Exit;
......@@ -970,10 +1077,26 @@ begin
Exit;
end;
if not CheckSummaryLength(FNewEntryRowIndex) then
begin
SetTopControlsEnabled(False);
Exit;
end;
payload := BuildTimeEntryPayload('0');
Utils.ShowSpinner('spinner');
try
// The task can be picked for any date; whether it can take hours on this
// one is checked here and shown under the Task field
dateProblem := await(GetTaskDateProblem(FNewEntryRowIndex));
if dateProblem <> '' then
begin
ShowTaskDateNotice(FNewEntryRowIndex, dateProblem);
SetTopControlsEnabled(False);
Exit;
end;
try
response := await(xdwcTimeEntries.RawInvokeAsync(
'ITimeEntryService.SaveTimeEntry',
......@@ -1041,6 +1164,7 @@ var
rowSelector: string;
saveError: string;
savedTaskDate: string;
dateProblem: string;
begin
saveButton := TJSHTMLButtonElement(Event.target);
idx := StrToIntDef(string(saveButton.getAttribute('data-idx')), -1);
......@@ -1063,6 +1187,9 @@ begin
Exit;
end;
if not CheckSummaryLength(idx) then
Exit;
payload := BuildTimeEntryPayload(IntToStr(savedEntryId));
savedTaskDate := xdwdsTimeEntriestaskDate.AsString;
......@@ -1073,10 +1200,16 @@ begin
'.time-edit-cancel[data-idx="' + IntToStr(idx) + '"]'));
saveError := '';
dateProblem := '';
saveButton.disabled := True;
cancelButton.disabled := True;
rowEl.setAttribute('inert', '');
try
// The task can be picked for any date; whether it can take hours on this
// one is checked first and shown under the Task field
dateProblem := await(GetTaskDateProblem(idx));
if dateProblem = '' then
try
await(xdwcTimeEntries.RawInvokeAsync(
'ITimeEntryService.SaveTimeEntry', [payload]));
......@@ -1093,7 +1226,13 @@ begin
rowEl.removeAttribute('inert');
end;
// Shown after the row is no longer inert so the date field can take focus
// Both shown after the row is no longer inert so the field can take focus
if dateProblem <> '' then
begin
ShowTaskDateNotice(idx, dateProblem);
Exit;
end;
if saveError <> '' then
begin
TJSHTMLElement(rowEl.querySelector('[data-field="taskDate"]')).classList.add('is-invalid');
......@@ -1142,7 +1281,10 @@ begin
xdwdsTimeEntries.Edit;
xdwdsTimeEntriestaskDate.AsString := FOriginalTaskDate;
xdwdsTimeEntrieshours.AsFloat := FOriginalHours;
if FOriginalHoursBlank then
xdwdsTimeEntrieshours.Clear
else
xdwdsTimeEntrieshours.AsFloat := FOriginalHours;
xdwdsTimeEntriestaskId.AsString := FOriginalTaskId;
xdwdsTimeEntriestaskDisplay.AsString := FOriginalTaskDisplay;
xdwdsTimeEntriestaskTime.AsString := FOriginalTaskTime;
......@@ -1151,6 +1293,7 @@ begin
xdwdsTimeEntriescategory.AsString := FOriginalCategory;
xdwdsTimeEntriescategoryDesc.AsString := FOriginalCategoryDesc;
xdwdsTimeEntriessummary.AsString := FOriginalSummary;
xdwdsTimeEntriesdetails.AsString := FOriginalDetails;
xdwdsTimeEntries.Post;
ClearEntryDraft;
......@@ -1161,6 +1304,137 @@ begin
ClearRowValidation(idx);
end;
// Details (time_items.DETAILS) has no grid column; the row's Details button
// edits it in an offcanvas. OK puts the text on the row, and the row's Save stores it.
// The button is on every row, so the click is left to bubble to RowClick,
// which refuses to switch rows while a new entry, a draft or an incomplete
// row is open. The editor opens only if RowClick made this row active.
procedure TFTimeEntries.DetailsButtonClick(Event: TJSEvent);
var
el: TJSHTMLElement;
idx: Integer;
detailsText: TJSHTMLElement;
begin
Event.preventDefault;
el := TJSHTMLElement(Event.currentTarget);
idx := StrToIntDef(string(el.getAttribute('data-idx')), -1);
if (idx < 0) or (not xdwdsTimeEntries.Active) then
Exit;
window.setTimeout(
procedure
begin
if FActiveRowIndex <> idx then
Exit;
GotoRowIndex(idx);
if xdwdsTimeEntries.Eof then
Exit;
FDetailsRowIndex := idx;
detailsText := TJSHTMLElement(document.getElementById('time_details_text'));
TJSObject(detailsText)['value'] := xdwdsTimeEntriesdetails.AsString;
ShowDetailsEditor;
end,
0);
end;
// Filled (primary) when the row has details, outline when it has none
function TFTimeEntries.DetailsButtonClass(const ADetails: string): string;
begin
Result := 'btn btn-sm text-nowrap flex-shrink-0 time-edit-details ' +
IfThen(Trim(ADetails) <> '', 'btn-primary', 'btn-outline-secondary');
end;
function TFTimeEntries.DetailsButtonTitle(const ADetails: string): string;
begin
Result := IfThen(Trim(ADetails) <> '', 'View or edit details', 'Add details');
end;
procedure TFTimeEntries.DetailsOkClick(Event: TJSEvent);
var
idx: Integer;
newVal: string;
detailsBtn: TJSHTMLElement;
begin
Event.preventDefault;
idx := FDetailsRowIndex;
FDetailsRowIndex := -1;
HideDetailsEditor;
if (idx < 0) or (not xdwdsTimeEntries.Active) then
Exit;
newVal := string(TJSObject(document.getElementById('time_details_text'))['value']);
GotoRowIndex(idx);
if xdwdsTimeEntries.Eof then
Exit;
if newVal = xdwdsTimeEntriesdetails.AsString then
Exit;
// Same as any other edit: a saved row joins its draft (Save/Cancel)
BeginEntryDraft(idx);
xdwdsTimeEntries.Edit;
xdwdsTimeEntriesdetails.AsString := newVal;
xdwdsTimeEntries.Post;
// The table isn't redrawn here, so restyle this row's button
detailsBtn := TJSHTMLElement(document.querySelector(
'.time-edit-details[data-idx="' + IntToStr(idx) + '"]'));
if Assigned(detailsBtn) then
begin
detailsBtn.className := DetailsButtonClass(newVal);
detailsBtn.title := DetailsButtonTitle(newVal);
end;
if IsDraftEntryRow then
begin
ShowEntryDraftActions(idx);
SetTopControlsEnabled(False);
end;
end;
procedure TFTimeEntries.ShowDetailsEditor;
begin
asm
var el = document.getElementById('offcanvasTimeDetails');
if (el) {
el.addEventListener('shown.bs.offcanvas', function () {
var text = document.getElementById('time_details_text');
if (text) text.focus();
}, { once: true });
var oc = bootstrap.Offcanvas.getOrCreateInstance(el);
oc.show();
}
end;
end;
procedure TFTimeEntries.HideDetailsEditor;
begin
asm
var el = document.getElementById('offcanvasTimeDetails');
if (el) {
var oc = bootstrap.Offcanvas.getOrCreateInstance(el);
oc.hide();
}
end;
end;
procedure TFTimeEntries.BindTableEditors;
var
nodes: TJSNodeList;
......@@ -1193,6 +1467,13 @@ begin
el.addEventListener('click', TJSEventHandler(@EntryDraftSaveClick));
end;
nodes := document.querySelectorAll('.time-edit-details');
for i := 0 to nodes.length - 1 do
begin
el := TJSHTMLElement(nodes.item(i));
el.addEventListener('click', TJSEventHandler(@DetailsButtonClick));
end;
nodes := document.querySelectorAll('.time-dd-item');
console.log('BindTableEditors: time-dd-item count=' + IntToStr(nodes.length));
for i := 0 to nodes.length - 1 do
......@@ -1280,9 +1561,6 @@ begin
xdwdsTimeEntries.Post;
if SameText(fieldName, 'taskDate') then
RefreshTaskOptionStates(idx, newVal);
if IsDraftEntryRow then
ShowEntryDraftActions(idx);
......@@ -1565,10 +1843,11 @@ begin
hasDate := Trim(xdwdsTimeEntriestaskDate.AsString) <> '';
hasTask := Trim(xdwdsTimeEntriestaskId.AsString) <> '';
// Hours is required: zero is allowed; blank or negative is not
if xdwdsTimeEntrieshours.IsNull then
hasHours := False
else
hasHours := xdwdsTimeEntrieshours.AsFloat > 0;
hasHours := xdwdsTimeEntrieshours.AsFloat >= 0;
hasCategory := Trim(xdwdsTimeEntriescategory.AsString) <> '';
hasSummary := Trim(xdwdsTimeEntriessummary.AsString) <> '';
......@@ -1576,6 +1855,45 @@ begin
end;
// Save-time only, so older entries over the limit can still be selected,
// but must be trimmed before they are saved; maxlength keeps new typing
// within the limit
function TFTimeEntries.CheckSummaryLength(AIndex: Integer): Boolean;
var
rowEl: TJSHTMLElement;
summaryEl: TJSHTMLElement;
begin
Result := True;
GotoRowIndex(AIndex);
if xdwdsTimeEntries.Eof then
Exit;
if Length(xdwdsTimeEntriessummary.AsString) <= SUMMARY_MAX_LENGTH then
Exit;
Result := False;
// Required fields passed, so any header message is stale; the length message
// shows in the red popup under the summary instead (EnableAutoGrowTextAreas
// handles 'time-summary-limit': red glow + popup, like typing past the limit)
HideRowValidationMessage;
rowEl := TJSHTMLElement(document.querySelector('tr[data-idx="' + IntToStr(AIndex) + '"]'));
if not Assigned(rowEl) then
Exit;
summaryEl := TJSHTMLElement(rowEl.querySelector('[data-field="summary"]'));
if not Assigned(summaryEl) then
Exit;
summaryEl.focus;
asm
summaryEl.dispatchEvent(new CustomEvent('time-summary-limit'));
end;
end;
procedure TFTimeEntries.ApplyPendingEntryFocus;
var
rowEl: TJSHTMLElement;
......@@ -1632,6 +1950,10 @@ var
begin
fieldEl := TJSHTMLElement(rowEl.querySelector('[data-field="' + AFieldName + '"]'));
// Time and Place aren't rendered while Compact View is checked
if not Assigned(fieldEl) then
Exit;
if AInvalid then
fieldEl.classList.add('is-invalid')
else
......@@ -1648,10 +1970,11 @@ begin
rowEl := TJSHTMLElement(document.querySelector('tr[data-idx="' + IntToStr(AIndex) + '"]'));
// Hours is required: blank or negative is flagged; zero is fine
if xdwdsTimeEntrieshours.IsNull then
hoursInvalid := True
else
hoursInvalid := xdwdsTimeEntrieshours.AsFloat <= 0;
hoursInvalid := xdwdsTimeEntrieshours.AsFloat < 0;
SetInvalid('taskDate', Trim(xdwdsTimeEntriestaskDate.AsString) = '');
SetInvalid('taskId', Trim(xdwdsTimeEntriestaskId.AsString) = '');
......@@ -1669,12 +1992,66 @@ begin
if(!host) return;
host.querySelectorAll('.time-textarea').forEach(function(editor){
const notice = editor.parentElement.querySelector('.time-summary-notice');
const max = editor.maxLength;
let noticeTimer = 0;
const fit = function() {
editor.style.height = 'auto';
editor.style.height = editor.scrollHeight + 'px';
};
fit();
editor.addEventListener('input', fit);
if (max <= 0) return;
// Nothing marks the field while it sits at the limit; it only glows
// briefly when a keystroke or paste runs into it. AError = red (typing
// blocked), otherwise amber (paste cut short).
const flash = function(AError) {
editor.classList.remove('time-summary-flash', 'time-summary-flash-error');
void editor.offsetWidth; // restarts the animation
editor.classList.add(AError ? 'time-summary-flash-error' : 'time-summary-flash');
};
const showNotice = function(text, AError) {
if (!notice) return;
notice.textContent = text;
notice.classList.toggle('time-summary-notice-error', !!AError);
notice.hidden = false;
clearTimeout(noticeTimer);
noticeTimer = setTimeout(function() { notice.hidden = true; }, 6000); // 6 seconds
};
// Characters left after replacing the current selection
const room = function() {
return max - (editor.value.length - (editor.selectionEnd - editor.selectionStart));
};
// Typing at the limit does nothing, so glow and say why
editor.addEventListener('beforeinput', function(e) {
if ((e.inputType === 'insertText' || e.inputType === 'insertLineBreak') && room() <= 0) {
flash(true);
showNotice('Maximum length is ' + max + ' characters', true);
}
});
// Save blocked because an older summary is over the limit (CheckSummaryLength)
editor.addEventListener('time-summary-limit', function() {
flash(true);
showNotice('Summary must be ' + max + ' characters or fewer before saving this entry.', true);
});
// maxlength cuts a long paste without saying so
editor.addEventListener('paste', function(e) {
const data = e.clipboardData || window.clipboardData;
if (!data) return;
const text = (data.getData('text') || '').replace(/\r\n?/g, '\n');
if (text.length > room()) {
flash(false);
showNotice('Pasted text was cut to fit the ' + max + ' character limit.', false);
}
});
});
})();
end;
......@@ -1928,6 +2305,7 @@ begin
xdwdsTimeEntriescategory.AsString := '';
xdwdsTimeEntriescategoryDesc.AsString := '';
xdwdsTimeEntriessummary.AsString := '';
xdwdsTimeEntriesdetails.AsString := '';
xdwdsTimeEntries.Post;
FAddingNewEntry := True;
......@@ -1956,9 +2334,7 @@ var
taskTime: string;
place: string;
placeDesc: string;
category: string;
categoryDesc: string;
summary: string;
details: string;
begin
Result := False;
......@@ -2005,9 +2381,7 @@ begin
taskTime := xdwdsTimeEntriestaskTime.AsString;
place := xdwdsTimeEntriesplace.AsString;
placeDesc := xdwdsTimeEntriesplaceDesc.AsString;
category := xdwdsTimeEntriescategory.AsString;
categoryDesc := xdwdsTimeEntriescategoryDesc.AsString;
summary := xdwdsTimeEntriessummary.AsString;
details := xdwdsTimeEntriesdetails.AsString;
xdwdsTimeEntries.Append;
xdwdsTimeEntriesentryId.AsInteger := 0;
......@@ -2023,9 +2397,11 @@ begin
xdwdsTimeEntriestaskTime.AsString := taskTime;
xdwdsTimeEntriesplace.AsString := place;
xdwdsTimeEntriesplaceDesc.AsString := placeDesc;
xdwdsTimeEntriescategory.AsString := category;
xdwdsTimeEntriescategoryDesc.AsString := categoryDesc;
xdwdsTimeEntriessummary.AsString := summary;
// Category and Summary are rarely the same for the copy, so the user fills them in
xdwdsTimeEntriescategory.AsString := '';
xdwdsTimeEntriescategoryDesc.AsString := '';
xdwdsTimeEntriessummary.AsString := '';
xdwdsTimeEntriesdetails.AsString := details;
xdwdsTimeEntries.Post;
FAddingNewEntry := True;
......@@ -2175,6 +2551,7 @@ var
idx: Integer;
taskId: string;
taskDate: string;
picker: TFTaskPicker;
begin
Event.preventDefault;
Event.stopPropagation;
......@@ -2231,9 +2608,6 @@ begin
btnDeleteEntry.Enabled := not IsNewEntryRow(idx);
btnCopyEntry.Enabled := not IsNewEntryRow(idx);
if not Assigned(FTaskPickerOffCanvas) then
FTaskPickerOffCanvas := TTaskPickerOffCanvas.Create(xdwcTimeEntries, @TaskPickerTaskSelected, @TaskPickerFocusChanged);
// Pass the row's current task and (draft) date so the picker opens on them
taskId := '';
taskDate := '';
......@@ -2244,7 +2618,18 @@ begin
taskDate := xdwdsTimeEntriestaskDate.AsString;
end;
await(FTaskPickerOffCanvas.Open(FUserId, idx, FTaskOptions, taskId, taskDate));
// Find Task is its own popup form, created for each open and freed on close
picker := TFTaskPicker.CreatePopup(Self);
try
await(TFTaskPicker, picker.Load());
picker.OnFocusChanged := @TaskPickerFocusChanged;
picker.Start(FUserId, FTaskOptions, taskId, taskDate); // loads the lists while the form shows
if await(TModalResult, picker.Execute) = mrOk then
TaskPickerTaskSelected(idx, picker.SelectedTaskId, picker.SelectedTaskDisplay, picker.SelectedTaskDate);
finally
picker.Free;
end;
end;
......@@ -2297,6 +2682,8 @@ begin
Exit;
end;
// The mode isn't tied to the category: Task Items opens in the mode last picked
// with its Testing Mode checkbox
taskId := '';
GotoRowIndex(idx);
if not xdwdsTimeEntries.Eof then
......
......@@ -42,6 +42,88 @@
min-width: 0;
}
/* Summary's 500-character limit: nothing shows while the field sits at the
limit; it only glows briefly when a keystroke or paste runs into it */
.time-summary-wrap {
position: relative;
min-width: 0; /* lets the summary shrink beside the Details button */
}
/* A paste cut short (amber) */
.time-summary-wrap textarea.time-summary-flash {
animation: time-summary-flash 600ms ease-out;
}
@keyframes time-summary-flash {
from {
border-color: var(--bs-warning);
box-shadow: 0 0 0 .3rem rgba(var(--bs-warning-rgb), .6);
}
to {
box-shadow: 0 0 0 .25rem rgba(var(--bs-warning-rgb), 0);
}
}
/* Typing blocked at the limit (red) */
.time-summary-wrap textarea.time-summary-flash-error {
animation: time-summary-flash-error 600ms ease-out;
}
@keyframes time-summary-flash-error {
from {
border-color: var(--bs-danger);
box-shadow: 0 0 0 .3rem rgba(var(--bs-danger-rgb), .6);
}
to {
box-shadow: 0 0 0 .25rem rgba(var(--bs-danger-rgb), 0);
}
}
/* Shown for 6 seconds under the Summary: a paste cut off (amber), or typing
or saving past the 500-character limit (red, below) */
.time-summary-notice {
position: absolute;
top: calc(100% + 2px);
right: 0;
z-index: 6;
padding: .125rem .5rem;
font-size: .75rem;
white-space: nowrap;
color: var(--bs-warning-text-emphasis);
background: var(--bs-warning-bg-subtle);
border: 1px solid var(--bs-warning-border-subtle);
border-radius: var(--bs-border-radius-sm);
box-shadow: var(--bs-box-shadow-sm);
pointer-events: none;
}
/* Same popup in red, for "Maximum length is 500 characters" */
.time-summary-notice.time-summary-notice-error {
color: var(--bs-danger-text-emphasis);
background: var(--bs-danger-bg-subtle);
border-color: var(--bs-danger-border-subtle);
}
/* The same red glow and popup for a task that can't take hours on the date:
under a grid row's Task field when it's saved, and under the Find Task
picker's Task dropdown when Select is clicked */
.time-field-flash-error {
animation: time-summary-flash-error 600ms ease-out;
}
.time-task-wrap {
position: relative;
min-width: 0;
}
/* Left-aligned under the Task field (the Summary's sits at the right) */
.time-task-wrap > .time-summary-notice {
left: 0;
right: auto;
}
.time-table .dropdown-menu {
z-index: 1055;
}
......
......@@ -18,7 +18,7 @@ uses
View.Login in 'View.Login.pas' {FViewLogin: TWebForm} {*.html},
View.ErrorPage in 'View.ErrorPage.pas' {FViewErrorPage: TWebForm} {*.html},
View.TimeEntries in 'View.TimeEntries.pas' {FTimeEntries: TWebForm} {*.html},
uTaskPickerOffCanvas in 'uTaskPickerOffCanvas.pas';
View.TaskPicker in 'View.TaskPicker.pas' {FTaskPicker: TWebForm} {*.html};
{$R *.res}
......
......@@ -156,7 +156,10 @@
<Form>FTimeEntries</Form>
<DesignClass>TWebForm</DesignClass>
</DCCReference>
<DCCReference Include="uTaskPickerOffCanvas.pas"/>
<DCCReference Include="View.TaskPicker.pas">
<Form>FTaskPicker</Form>
<DesignClass>TWebForm</DesignClass>
</DCCReference>
<None Include="index.html"/>
<None Include="css\app.css"/>
<None Include="config\config.json"/>
......
......@@ -11,12 +11,11 @@ procedure ClearTaskStatusClasses(const AElement: TJSHTMLElement);
procedure ApplyTaskStatusClass(const AElement: TJSHTMLElement; const AStatus: string);
function ExtractOptionNames(const SourceArray: TJSArray): TJSArray;
function ExtractCodeDescs(const SourceArray: TJSArray): TJSArray;
function ExtractAssignedOptionNames(const ResponseResult: TJSObject): TJSArray;
function ExtractReportedOptionNames(const ResponseResult: TJSObject): TJSArray;
function ExtractApplicationOptionNames(const ResponseResult: TJSObject): TJSArray;
function ExtractVersionOptionNames(const ResponseResult: TJSObject): TJSArray;
function FindOptionIgnoreCase(const AItems: TJSArray; const AName: string): string;
function GetOptionsForField(const AFieldName: string; const AApplicationOptions, AReportedByOptions, AAssignedToOptions: TJSArray): TJSArray;
function GetOptionsForField(const AFieldName: string; const AApplicationOptions, AVersionOptions, AReportedByOptions: TJSArray): TJSArray;
procedure FocusTrigger(const ATriggerId: string);
......@@ -30,23 +29,24 @@ var
begin
statusText := Trim(AStatus);
if SameText(statusText, 'Cannot Duplicate') then
// Testing Status codes (codes table, CATEGORY = 'TASK', CODE_TYPE = 'STATUS2')
if SameText(statusText, 'CD') then
Result := 'status-cannot-duplicate'
else if SameText(statusText, 'Cannot Test') then
else if SameText(statusText, 'CT') then
Result := 'status-cannot-test'
else if SameText(statusText, 'Future Enhancement') then
else if SameText(statusText, 'FE') then
Result := 'status-future-enhancement'
else if SameText(statusText, 'Fixed - Verified') then
else if SameText(statusText, 'FV') then
Result := 'status-fixed-verified'
else if SameText(statusText, 'Fixed') then
else if SameText(statusText, 'FX') then
Result := 'status-fixed'
else if SameText(statusText, 'Investigating') then
else if SameText(statusText, 'IN') then
Result := 'status-investigating'
else if SameText(statusText, 'Not Fixed') then
else if SameText(statusText, 'NF') then
Result := 'status-not-fixed'
else if SameText(statusText, 'Non-Issue') then
else if SameText(statusText, 'NI') then
Result := 'status-non-issue'
else if SameText(statusText, 'Possibly a Problem') then
else if SameText(statusText, 'PP') then
Result := 'status-possibly-a-problem'
else
Result := 'status-default';
......@@ -96,46 +96,28 @@ begin
end;
end;
function ExtractCodeDescs(const SourceArray: TJSArray): TJSArray;
var
i: Integer;
optionObj: TJSObject;
begin
Result := TJSArray.new;
if not Assigned(SourceArray) then
Exit;
for i := 0 to SourceArray.length - 1 do
begin
optionObj := TJSObject(SourceArray[i]);
if Assigned(optionObj) then
Result.push(string(optionObj['codeDesc']));
end;
end;
function ExtractAssignedOptionNames(const ResponseResult: TJSObject): TJSArray;
function ExtractReportedOptionNames(const ResponseResult: TJSObject): TJSArray;
begin
if not Assigned(ResponseResult) then
Exit(TJSArray.new);
Result := ExtractOptionNames(TJSArray(ResponseResult['assignedToOptions']));
Result := ExtractOptionNames(TJSArray(ResponseResult['reportedByOptions']));
end;
function ExtractReportedOptionNames(const ResponseResult: TJSObject): TJSArray;
function ExtractApplicationOptionNames(const ResponseResult: TJSObject): TJSArray;
begin
if not Assigned(ResponseResult) then
Exit(TJSArray.new);
Result := ExtractOptionNames(TJSArray(ResponseResult['reportedByOptions']));
Result := ExtractOptionNames(TJSArray(ResponseResult['applicationOptions']));
end;
function ExtractApplicationOptionNames(const ResponseResult: TJSObject): TJSArray;
function ExtractVersionOptionNames(const ResponseResult: TJSObject): TJSArray;
begin
if not Assigned(ResponseResult) then
Exit(TJSArray.new);
Result := ExtractOptionNames(TJSArray(ResponseResult['applicationOptions']));
Result := ExtractOptionNames(TJSArray(ResponseResult['versionOptions']));
end;
function FindOptionIgnoreCase(const AItems: TJSArray; const AName: string): string;
......@@ -156,14 +138,14 @@ begin
end;
end;
function GetOptionsForField(const AFieldName: string; const AApplicationOptions, AReportedByOptions, AAssignedToOptions: TJSArray): TJSArray;
function GetOptionsForField(const AFieldName: string; const AApplicationOptions, AVersionOptions, AReportedByOptions: TJSArray): TJSArray;
begin
if SameText(AFieldName, 'application') then
Result := AApplicationOptions
else if SameText(AFieldName, 'version') then
Result := AVersionOptions
else if SameText(AFieldName, 'reportedBy') then
Result := AReportedByOptions
else if SameText(AFieldName, 'assignedTo') then
Result := AAssignedToOptions
else
Result := nil;
end;
......
......@@ -257,7 +257,7 @@ begin
Exit;
end;
if not (SameText(FCurrentField, 'assignedTo') or SameText(FCurrentField, 'application') or SameText(FCurrentField, 'reportedBy')) then
if not (SameText(FCurrentField, 'application') or SameText(FCurrentField, 'version') or SameText(FCurrentField, 'reportedBy')) then
Exit;
if FCurrentEditName <> '' then
......@@ -356,7 +356,7 @@ begin
Event.preventDefault;
Event.stopPropagation;
if not (SameText(FCurrentField, 'assignedTo') or SameText(FCurrentField, 'application') or SameText(FCurrentField, 'reportedBy')) then
if not (SameText(FCurrentField, 'application') or SameText(FCurrentField, 'version') or SameText(FCurrentField, 'reportedBy')) then
Exit;
el := TJSHTMLElement(Event.currentTarget);
......@@ -383,7 +383,7 @@ begin
Event.preventDefault;
Event.stopPropagation;
if not (SameText(FCurrentField, 'assignedTo') or SameText(FCurrentField, 'application') or SameText(FCurrentField, 'reportedBy')) then
if not (SameText(FCurrentField, 'application') or SameText(FCurrentField, 'version') or SameText(FCurrentField, 'reportedBy')) then
Exit;
el := TJSHTMLElement(Event.currentTarget);
......@@ -401,7 +401,7 @@ procedure TNameManager.OpenManager(const AFieldName: string; const ARowIndex: In
var
titleEl: TJSHTMLElement;
begin
if not (SameText(AFieldName, 'assignedTo') or SameText(AFieldName, 'application') or SameText(AFieldName, 'reportedBy')) then
if not (SameText(AFieldName, 'application') or SameText(AFieldName, 'version') or SameText(AFieldName, 'reportedBy')) then
Exit;
FCurrentField := AFieldName;
......@@ -414,10 +414,10 @@ begin
begin
if SameText(AFieldName, 'application') then
titleEl.innerHTML := 'Manage Application'
else if SameText(AFieldName, 'reportedBy') then
titleEl.innerHTML := 'Manage Reported By'
else if SameText(AFieldName, 'version') then
titleEl.innerHTML := 'Manage Version'
else
titleEl.innerHTML := 'Manage Assigned To';
titleEl.innerHTML := 'Manage Reported By';
end;
ResetInputArea;
......
......@@ -127,23 +127,39 @@ object ApiDatabase: TApiDatabase
Connection = ucETaskApi
SQL.Strings = (
'select'
' TASK_ITEM_ID,'
' TASK_ID,'
' ITEM_NUM,'
' APPLICATION,'
' APP_VERSION,'
' TASK_DATE,'
' STATUS_DATE,'
' REPORTED_BY,'
' ASSIGNED_TO,'
' STATUS,'
' FIXED_VERSION,'
' FORM_SECTION,'
' ISSUE,'
' NOTES'
'from task_items'
'where TASK_ID = :TASK_ID'
'order by ITEM_NUM')
' ti.TASK_ITEM_ID,'
' ti.TASK_ID,'
' ti.ITEM_NUM,'
' ti.APPLICATION,'
' ti.APP_VERSION,'
' ti.TASK_DATE,'
' ti.STATUS_DATE,'
' ti.REPORTED_BY,'
' ti.ASSIGNED_TO,'
' au.USER_ID as ASSIGNED_USER_ID,'
' au.FIRST_NAME as ASSIGNED_FIRST_NAME,'
' au.LAST_NAME as ASSIGNED_LAST_NAME,'
' ti.STATUS,'
' ts.CODE_DESC as STATUS_DESC,'
' ti.ITEM_STATUS,'
' its.CODE_DESC as ITEM_STATUS_DESC,'
' ti.FIXED_VERSION,'
' ti.FORM_SECTION,'
' ti.ISSUE,'
' ti.NOTES'
'from task_items ti'
'left join users au'
' on au.USER_ID = ti.ASSIGNED_TO'
'left join codes ts'
' on ts.CATEGORY = '#39'TASK'#39
' and ts.CODE_TYPE = '#39'STATUS2'#39
' and ts.CODE = ti.STATUS'
'left join codes its'
' on its.CATEGORY = '#39'TASK'#39
' and its.CODE_TYPE = '#39'STATUS'#39
' and its.CODE = ti.ITEM_STATUS'
'where ti.TASK_ID = :TASK_ID'
'order by ti.ITEM_NUM')
Left = 58
Top = 26
ParamData = <
......@@ -197,6 +213,35 @@ object ApiDatabase: TApiDatabase
Required = True
Size = 100
end
object uqTaskItemsASSIGNED_USER_ID: TStringField
FieldName = 'ASSIGNED_USER_ID'
ReadOnly = True
Size = 7
end
object uqTaskItemsASSIGNED_FIRST_NAME: TStringField
FieldName = 'ASSIGNED_FIRST_NAME'
ReadOnly = True
Size = 25
end
object uqTaskItemsASSIGNED_LAST_NAME: TStringField
FieldName = 'ASSIGNED_LAST_NAME'
ReadOnly = True
Size = 35
end
object uqTaskItemsSTATUS_DESC: TStringField
FieldName = 'STATUS_DESC'
ReadOnly = True
Size = 60
end
object uqTaskItemsITEM_STATUS: TStringField
FieldName = 'ITEM_STATUS'
Size = 7
end
object uqTaskItemsITEM_STATUS_DESC: TStringField
FieldName = 'ITEM_STATUS_DESC'
ReadOnly = True
Size = 60
end
object uqTaskItemsFIXED_VERSION: TStringField
FieldName = 'FIXED_VERSION'
Required = True
......@@ -231,6 +276,7 @@ object ApiDatabase: TApiDatabase
' REPORTED_BY,'
' ASSIGNED_TO,'
' STATUS,'
' ITEM_STATUS,'
' FIXED_VERSION,'
' FORM_SECTION,'
' ISSUE,'
......@@ -246,6 +292,7 @@ object ApiDatabase: TApiDatabase
' null,'
' null,'
' null,'
' '#39'OPEN'#39','
' null,'
' null,'
' null,'
......@@ -278,10 +325,9 @@ object ApiDatabase: TApiDatabase
' REPORTED_BY,'
' ASSIGNED_TO,'
' STATUS,'
' ITEM_STATUS,'
' FIXED_VERSION,'
' FORM_SECTION,'
' ISSUE,'
' NOTES'
' FORM_SECTION'
')'
'select'
' TASK_ID,'
......@@ -293,10 +339,9 @@ object ApiDatabase: TApiDatabase
' REPORTED_BY,'
' ASSIGNED_TO,'
' STATUS,'
' ITEM_STATUS,'
' FIXED_VERSION,'
' FORM_SECTION,'
' ISSUE,'
' NOTES'
' FORM_SECTION'
'from task_items'
'where TASK_ID = :TASK_ID'
' and TASK_ITEM_ID = :TASK_ITEM_ID')
......@@ -394,23 +439,53 @@ object ApiDatabase: TApiDatabase
' CODE,'
' CODE_DESC,'
' CODE_TYPE'
'FROM etask.task_item_codes'
'WHERE CODE_TYPE = '#39'STATUS'#39
'ORDER BY CODE')
'FROM codes'
'WHERE CATEGORY = '#39'TASK'#39
' AND CODE_TYPE = '#39'STATUS2'#39
'ORDER BY CODE_DESC')
Left = 60
Top = 140
object uqTaskItemCodesCODE: TStringField
FieldName = 'CODE'
Required = True
Size = 50
Size = 7
end
object uqTaskItemCodesCODE_DESC: TStringField
FieldName = 'CODE_DESC'
Size = 255
Size = 60
end
object uqTaskItemCodesCODE_TYPE: TStringField
FieldName = 'CODE_TYPE'
Size = 50
Required = True
Size = 7
end
end
object uqTaskStatusCodes: TUniQuery
Connection = ucETaskApi
SQL.Strings = (
'SELECT'
' CODE,'
' CODE_DESC,'
' CODE_TYPE'
'FROM codes'
'WHERE CATEGORY = '#39'TASK'#39
' AND CODE_TYPE = '#39'STATUS'#39
'ORDER BY CODE_DESC')
Left = 58
Top = 376
object uqTaskStatusCodesCODE: TStringField
FieldName = 'CODE'
Required = True
Size = 7
end
object uqTaskStatusCodesCODE_DESC: TStringField
FieldName = 'CODE_DESC'
Size = 60
end
object uqTaskStatusCodesCODE_TYPE: TStringField
FieldName = 'CODE_TYPE'
Required = True
Size = 7
end
end
object uqGetTaskRowPosition: TUniQuery
......@@ -672,15 +747,18 @@ object ApiDatabase: TApiDatabase
object uqTaskAssignedUsers: TUniQuery
Connection = ucETaskApi
SQL.Strings = (
'select distinct'
' TASK_ITEM_USER_ID,'
' TASK_ID,'
' USER_TYPE,'
' NAME'
'from task_item_user'
'where TASK_ID = :TASK_ID'
' and USER_TYPE = '#39'Assigned'#39
'order by NAME')
'select'
' u.USER_ID,'
' u.FIRST_NAME,'
' u.LAST_NAME'
'from users u'
'join tasks t'
' on t.TASK_ID = :TASK_ID'
'where (u.START_DATE is null or t.COMPLETION_DATE is null'
' or u.START_DATE <= date(t.COMPLETION_DATE))'
' and (u.END_DATE is null or t.START_DATE is null'
' or u.END_DATE >= date(t.START_DATE))'
'order by u.FIRST_NAME, u.LAST_NAME')
Left = 60
Top = 200
ParamData = <
......@@ -689,119 +767,89 @@ object ApiDatabase: TApiDatabase
Name = 'TASK_ID'
Value = nil
end>
object uqTaskAssignedUsersTASK_ITEM_USER_ID: TStringField
FieldName = 'TASK_ITEM_USER_ID'
Required = True
Size = 50
end
object uqTaskAssignedUsersTASK_ID: TStringField
FieldName = 'TASK_ID'
object uqTaskAssignedUsersUSER_ID: TStringField
FieldName = 'USER_ID'
Required = True
Size = 7
end
object uqTaskAssignedUsersUSER_TYPE: TStringField
FieldName = 'USER_TYPE'
Required = True
Size = 8
object uqTaskAssignedUsersFIRST_NAME: TStringField
FieldName = 'FIRST_NAME'
Size = 25
end
object uqTaskAssignedUsersNAME: TStringField
FieldName = 'NAME'
Required = True
Size = 50
object uqTaskAssignedUsersLAST_NAME: TStringField
FieldName = 'LAST_NAME'
Size = 35
end
end
object uqAssignedInsert: TUniQuery
object uqCheckAssignedUser: TUniQuery
Connection = ucETaskApi
SQL.Strings = (
'insert into task_item_user ('
' TASK_ITEM_USER_ID,'
' TASK_ID,'
' USER_TYPE,'
' NAME'
')'
'values ('
' :TASK_ITEM_USER_ID,'
' :TASK_ID,'
' '#39'Assigned'#39','
' :NAME'
')')
'select count(*) as USER_COUNT'
'from task_items ti'
'join tasks t'
' on t.TASK_ID = ti.TASK_ID'
'join users u'
' on u.USER_ID = :USER_ID'
'where ti.TASK_ITEM_ID = :TASK_ITEM_ID'
' and (u.START_DATE is null or t.COMPLETION_DATE is null'
' or u.START_DATE <= date(t.COMPLETION_DATE))'
' and (u.END_DATE is null or t.START_DATE is null'
' or u.END_DATE >= date(t.START_DATE))')
Left = 382
Top = 24
ParamData = <
item
DataType = ftUnknown
Name = 'TASK_ITEM_USER_ID'
Value = nil
end
item
DataType = ftUnknown
Name = 'TASK_ID'
Value = nil
end
item
DataType = ftUnknown
Name = 'NAME'
Value = nil
end>
end
object uqAssignedRename: TUniQuery
LocalUpdate = True
Connection = ucETaskApi
SQL.Strings = (
'update task_item_user'
'set NAME = :NEW_NAME'
'where TASK_ITEM_USER_ID = :TASK_ITEM_USER_ID'
' and TASK_ID = :TASK_ID'
' and USER_TYPE = '#39'Assigned'#39)
Left = 382
Top = 84
ParamData = <
item
DataType = ftUnknown
Name = 'NEW_NAME'
Value = nil
end
item
DataType = ftUnknown
Name = 'TASK_ITEM_USER_ID'
Name = 'USER_ID'
Value = nil
end
item
DataType = ftUnknown
Name = 'TASK_ID'
Name = 'TASK_ITEM_ID'
Value = nil
end>
end
object uqAssignedDelete: TUniQuery
object uqProjectVersions: TUniQuery
Connection = ucETaskApi
SQL.Strings = (
'delete from task_item_user'
'where TASK_ITEM_USER_ID = :TASK_ITEM_USER_ID'
' and TASK_ID = :TASK_ID'
' and USER_TYPE = '#39'Assigned'#39)
Left = 384
Top = 140
'select distinct'
' trim(ti.APP_VERSION) as NAME'
'from task_items ti'
'join tasks t'
' on t.TASK_ID = ti.TASK_ID'
'join tasks target_task'
' on target_task.PROJECT_ID = t.PROJECT_ID'
'where target_task.TASK_ID = :TASK_ID'
' and ti.APP_VERSION is not null'
' and trim(ti.APP_VERSION) <> '#39#39
'order by NAME')
Left = 236
Top = 376
ParamData = <
item
DataType = ftUnknown
Name = 'TASK_ITEM_USER_ID'
Value = nil
end
item
DataType = ftUnknown
Name = 'TASK_ID'
Value = nil
end>
object uqProjectVersionsNAME: TStringField
FieldName = 'NAME'
ReadOnly = True
Size = 50
end
end
object uqRenameAssignedTo: TUniQuery
object uqRenameTaskItemVersion: TUniQuery
Connection = ucETaskApi
SQL.Strings = (
'update task_items'
'set ASSIGNED_TO = :NEW_NAME'
'where TASK_ID = :TASK_ID'
' and lower(ASSIGNED_TO) = lower(:OLD_NAME)')
Left = 386
Top = 196
'update task_items ti'
'join tasks t'
' on t.TASK_ID = ti.TASK_ID'
'join tasks target_task'
' on target_task.PROJECT_ID = t.PROJECT_ID'
'set ti.APP_VERSION = :NEW_NAME'
'where target_task.TASK_ID = :TASK_ID'
' and lower(trim(ti.APP_VERSION)) = lower(:OLD_NAME)')
Left = 236
Top = 430
ParamData = <
item
DataType = ftUnknown
......@@ -819,15 +867,19 @@ object ApiDatabase: TApiDatabase
Value = nil
end>
end
object uqBlankAssignedTo: TUniQuery
object uqBlankTaskItemVersion: TUniQuery
Connection = ucETaskApi
SQL.Strings = (
'update task_items'
'set ASSIGNED_TO = null'
'where TASK_ID = :TASK_ID'
' and lower(ASSIGNED_TO) = lower(:NAME)')
Left = 388
Top = 254
'update task_items ti'
'join tasks t'
' on t.TASK_ID = ti.TASK_ID'
'join tasks target_task'
' on target_task.PROJECT_ID = t.PROJECT_ID'
'set ti.APP_VERSION = null'
'where target_task.TASK_ID = :TASK_ID'
' and lower(trim(ti.APP_VERSION)) = lower(:NAME)')
Left = 236
Top = 484
ParamData = <
item
DataType = ftUnknown
......@@ -1216,6 +1268,7 @@ object ApiDatabase: TApiDatabase
' PLACE = :PLACE,'
' CATEGORY = :CATEGORY,'
' SUMMARY = :SUMMARY,'
' DETAILS = :DETAILS,'
' MODIFY_DATE = now(),'
' MODIFIED_BY = :MODIFIED_BY'
'WHERE ENTRY_ID = :ENTRY_ID'
......@@ -1260,6 +1313,11 @@ object ApiDatabase: TApiDatabase
end
item
DataType = ftUnknown
Name = 'DETAILS'
Value = nil
end
item
DataType = ftUnknown
Name = 'MODIFIED_BY'
Value = nil
end
......@@ -1312,6 +1370,12 @@ object ApiDatabase: TApiDatabase
'and (:PROJECT_DATE = '#39#39' or ('
' (p.START_DATE is null or date(p.START_DATE) <= :PROJECT_DATE)'
' and (p.END_DATE is null or date(p.END_DATE) >= :PROJECT_DATE)))'
'and (:TASK_FILTER = '#39'ALL'#39' or exists ('
' select 1 from tasks t'
' join task_assigned_user tau on tau.TASK_ID = t.TASK_ID'
' where t.PROJECT_ID = p.PROJECT_ID'
' and tau.USER_ID = :USER_ID'
' and (:TASK_FILTER <> '#39'FOCUSED'#39' or tau.FOCUSED_TASK = '#39'T'#39')))'
'order by'
' c.SHORT_NAME,'
' p.NAME'
......@@ -1338,6 +1402,11 @@ object ApiDatabase: TApiDatabase
DataType = ftUnknown
Name = 'PROJECT_DATE'
Value = nil
end
item
DataType = ftUnknown
Name = 'TASK_FILTER'
Value = nil
end>
object uqTaskPickerProjectsPROJECT_ID: TStringField
FieldName = 'PROJECT_ID'
......
......@@ -28,7 +28,13 @@ type
uqTaskItemsSTATUS_DATE: TDateField;
uqTaskItemsREPORTED_BY: TStringField;
uqTaskItemsASSIGNED_TO: TStringField;
uqTaskItemsASSIGNED_USER_ID: TStringField;
uqTaskItemsASSIGNED_FIRST_NAME: TStringField;
uqTaskItemsASSIGNED_LAST_NAME: TStringField;
uqTaskItemsSTATUS: TStringField;
uqTaskItemsSTATUS_DESC: TStringField;
uqTaskItemsITEM_STATUS: TStringField;
uqTaskItemsITEM_STATUS_DESC: TStringField;
uqTaskItemsFIXED_VERSION: TStringField;
uqTaskItemsFORM_SECTION: TStringField;
uqTaskItemsISSUE: TStringField;
......@@ -49,6 +55,10 @@ type
uqTaskItemCodesCODE: TStringField;
uqTaskItemCodesCODE_DESC: TStringField;
uqTaskItemCodesCODE_TYPE: TStringField;
uqTaskStatusCodes: TUniQuery;
uqTaskStatusCodesCODE: TStringField;
uqTaskStatusCodesCODE_DESC: TStringField;
uqTaskStatusCodesCODE_TYPE: TStringField;
uqGetTaskRowPosition: TUniQuery;
uqMoveTaskRowTemp: TUniQuery;
uqShiftTaskRowsDown: TUniQuery;
......@@ -64,15 +74,14 @@ type
uqShiftTaskRowsForInsert: TUniQuery;
uqProjectReportedUsers: TUniQuery;
uqTaskAssignedUsers: TUniQuery;
uqAssignedInsert: TUniQuery;
uqAssignedRename: TUniQuery;
uqAssignedDelete: TUniQuery;
uqRenameAssignedTo: TUniQuery;
uqBlankAssignedTo: TUniQuery;
uqTaskAssignedUsersTASK_ITEM_USER_ID: TStringField;
uqTaskAssignedUsersTASK_ID: TStringField;
uqTaskAssignedUsersUSER_TYPE: TStringField;
uqTaskAssignedUsersNAME: TStringField;
uqTaskAssignedUsersUSER_ID: TStringField;
uqTaskAssignedUsersFIRST_NAME: TStringField;
uqTaskAssignedUsersLAST_NAME: TStringField;
uqCheckAssignedUser: TUniQuery;
uqProjectVersions: TUniQuery;
uqProjectVersionsNAME: TStringField;
uqRenameTaskItemVersion: TUniQuery;
uqBlankTaskItemVersion: TUniQuery;
uqProjectApplications: TUniQuery;
uqApplicationInsert: TUniQuery;
uqApplicationRename: TUniQuery;
......
......@@ -25,7 +25,11 @@ type
taskDate: TDateTime;
reportedBy: string;
assignedTo: string;
assignedToDesc: string;
status: string;
statusDesc: string;
itemStatus: string;
itemStatusDesc: string;
statusDate: TDateTime;
fixedVersion: string;
formSection: string;
......@@ -48,11 +52,22 @@ type
name: string;
end;
TTaskAssignedUserOption = class
public
userId: string;
name: string;
end;
TTaskApplicationOption = class
public
name: string;
end;
TTaskVersionOption = class
public
name: string;
end;
TTaskItemCode = class
public
code: string;
......@@ -66,16 +81,17 @@ type
task: TTaskHeader;
items: TList<TTaskItem>;
applicationOptions: TList<TTaskApplicationOption>;
versionOptions: TList<TTaskVersionOption>;
reportedByOptions: TList<TTaskUserOption>;
assignedToOptions: TList<TTaskUserOption>;
assignedToOptions: TList<TTaskAssignedUserOption>;
statusOptions: TList<TTaskItemCode>;
itemStatusOptions: TList<TTaskItemCode>;
constructor Create;
destructor Destroy; override;
end;
TTaskUserOptionsResponse = class
public
assignedToOptions: TList<TTaskUserOption>;
reportedByOptions: TList<TTaskUserOption>;
constructor Create;
destructor Destroy; override;
......@@ -88,6 +104,13 @@ type
destructor Destroy; override;
end;
TTaskVersionOptionsResponse = class
public
versionOptions: TList<TTaskVersionOption>;
constructor Create;
destructor Destroy; override;
end;
TTaskRowSave = class
public
taskItemId: integer;
......@@ -122,11 +145,6 @@ type
[HttpPost] function AddTaskRow(taskId: string; insertAfterItemNum: Integer): Boolean;
[HttpPost] function CopyTaskRow(taskId: string; sourceTaskItemId: Integer): Integer;
[HttpPost] function AddAssignedName(taskId: string; name: string): TTaskUserOptionsResponse;
[HttpPost] function RenameAssignedName(taskId: string; oldName: string; newName: string): TTaskUserOptionsResponse;
[HttpPost] function DeleteAssignedName(taskId: string; name: string): TTaskUserOptionsResponse;
[HttpPost] function AddReportedName(taskId: string; name: string): TTaskUserOptionsResponse;
[HttpPost]function RenameReportedName(taskId: string; oldName: string; newName: string): TTaskUserOptionsResponse;
[HttpPost]function DeleteReportedName(taskId: string; name: string): TTaskUserOptionsResponse;
......@@ -135,6 +153,11 @@ type
[HttpPost] function RenameApplicationName(taskId: string; oldName: string; newName: string): TTaskApplicationOptionsResponse;
[HttpPost] function DeleteApplicationName(taskId: string; name: string): TTaskApplicationOptionsResponse;
// Versions have no table of their own: the list is the versions already used in the project,
// so adding one is just saving it on a row
[HttpPost] function RenameVersionName(taskId: string; oldName: string; newName: string): TTaskVersionOptionsResponse;
[HttpPost] function DeleteVersionName(taskId: string; name: string): TTaskVersionOptionsResponse;
[HttpPost] procedure MoveTaskRow(const taskId: Integer; const taskItemId: Integer; const newItemNum: Integer);
[HttpPost] function DeleteTaskRow(const taskId: Integer; const taskItemId: Integer): Boolean;
[HttpPost] function SaveTaskItemField(const Item: TTaskItemFieldSave): Boolean;
......@@ -148,32 +171,34 @@ begin
inherited;
items := TList<TTaskItem>.Create;
applicationOptions := TList<TTaskApplicationOption>.Create;
versionOptions := TList<TTaskVersionOption>.Create;
reportedByOptions := TList<TTaskUserOption>.Create;
assignedToOptions := TList<TTaskUserOption>.Create;
assignedToOptions := TList<TTaskAssignedUserOption>.Create;
statusOptions := TList<TTaskItemCode>.Create;
itemStatusOptions := TList<TTaskItemCode>.Create;
end;
destructor TTaskItemsResponse.Destroy;
begin
items.Free;
applicationOptions.Free;
versionOptions.Free;
reportedByOptions.Free;
assignedToOptions.Free;
statusOptions.Free;
itemStatusOptions.Free;
inherited;
end;
constructor TTaskUserOptionsResponse.Create;
begin
inherited;
assignedToOptions := TList<TTaskUserOption>.Create;
reportedByOptions := TList<TTaskUserOption>.Create;
end;
destructor TTaskUserOptionsResponse.Destroy;
begin
assignedToOptions := TList<TTaskUserOption>.Create;
reportedByOptions := TList<TTaskUserOption>.Create;
reportedByOptions.Free;
inherited;
end;
......@@ -189,6 +214,18 @@ begin
inherited;
end;
constructor TTaskVersionOptionsResponse.Create;
begin
inherited;
versionOptions := TList<TTaskVersionOption>.Create;
end;
destructor TTaskVersionOptionsResponse.Destroy;
begin
versionOptions.Free;
inherited;
end;
initialization
RegisterServiceType(TypeInfo(ITaskItemService));
......
......@@ -16,14 +16,9 @@ type
private
function BuildTaskNumber: string;
function BuildTaskTitle(const taskNumber, projectName, subject: string): string;
function FindAssignedOptionId(const taskId, name: string): string;
function FindAssignedOptionName(const taskId, name: string): string;
function BuildUserDisplayName(const firstName, lastName: string): string;
function AddTaskRow(taskId: string; insertAfterItemNum: Integer): Boolean;
function CopyTaskRow(taskId: string; sourceTaskItemId: Integer): Integer;
function BuildAssignedOptionsResponse(const taskId: string): TTaskUserOptionsResponse;
function AddAssignedName(taskId: string; name: string): TTaskUserOptionsResponse;
function RenameAssignedName(taskId: string; oldName: string; newName: string): TTaskUserOptionsResponse;
function DeleteAssignedName(taskId: string; name: string): TTaskUserOptionsResponse;
procedure MoveTaskRow(const taskId: Integer; const taskItemId: Integer; const newItemNum: Integer);
function DeleteTaskRow(const taskId, taskItemId: Integer): Boolean;
function FindProjectId(const taskId: string): string;
......@@ -33,6 +28,10 @@ type
function AddApplicationName(taskId: string; name: string): TTaskApplicationOptionsResponse;
function RenameApplicationName(taskId: string; oldName: string; newName: string): TTaskApplicationOptionsResponse;
function DeleteApplicationName(taskId: string; name: string): TTaskApplicationOptionsResponse;
function FindVersionName(const taskId, name: string): string;
function BuildVersionOptionsResponse(const taskId: string): TTaskVersionOptionsResponse;
function RenameVersionName(taskId: string; oldName: string; newName: string): TTaskVersionOptionsResponse;
function DeleteVersionName(taskId: string; name: string): TTaskVersionOptionsResponse;
function SaveTaskItemField(const Item: TTaskItemFieldSave): Boolean;
function FindReportedOptionId(const taskId, name: string): string;
function FindReportedOptionName(const taskId, name: string): string;
......@@ -69,8 +68,10 @@ function TTaskItemService.GetTaskItems(taskId: string): TTaskItemsResponse;
var
taskHeader: TTaskHeader;
taskUserOption: TTaskUserOption;
taskAssignedUserOption: TTaskAssignedUserOption;
taskItemCode: TTaskItemCode;
taskApplicationOption: TTaskApplicationOption;
taskVersionOption: TTaskVersionOption;
item: TTaskItem;
begin
Logger.Log(4, Format('TaskItemService.GetTaskItems - TASK_ID="%s"', [taskId]));
......@@ -121,6 +122,21 @@ begin
apiDB.uqProjectApplications.Next;
end;
apiDB.uqProjectVersions.Close;
apiDB.uqProjectVersions.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqProjectVersions.Open;
while not apiDB.uqProjectVersions.Eof do
begin
taskVersionOption := TTaskVersionOption.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(taskVersionOption);
taskVersionOption.name := apiDB.uqProjectVersionsNAME.AsString;
Result.versionOptions.Add(taskVersionOption);
apiDB.uqProjectVersions.Next;
end;
apiDB.uqProjectReportedUsers.Close;
apiDB.uqProjectReportedUsers.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqProjectReportedUsers.Open;
......@@ -136,17 +152,22 @@ begin
apiDB.uqProjectReportedUsers.Next;
end;
// Users whose employment dates overlap the task's start/end dates
apiDB.uqTaskAssignedUsers.Close;
apiDB.uqTaskAssignedUsers.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqTaskAssignedUsers.Open;
while not apiDB.uqTaskAssignedUsers.Eof do
begin
taskUserOption := TTaskUserOption.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(taskUserOption);
taskAssignedUserOption := TTaskAssignedUserOption.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(taskAssignedUserOption);
taskUserOption.name := apiDB.uqTaskAssignedUsersNAME.AsString;
Result.assignedToOptions.Add(taskUserOption);
taskAssignedUserOption.userId := apiDB.uqTaskAssignedUsersUSER_ID.AsString;
taskAssignedUserOption.name := BuildUserDisplayName(
apiDB.uqTaskAssignedUsersFIRST_NAME.AsString,
apiDB.uqTaskAssignedUsersLAST_NAME.AsString
);
Result.assignedToOptions.Add(taskAssignedUserOption);
apiDB.uqTaskAssignedUsers.Next;
end;
......@@ -168,6 +189,23 @@ begin
apiDB.uqTaskItemCodes.Next;
end;
apiDB.uqTaskStatusCodes.Close;
apiDB.uqTaskStatusCodes.Open;
while not apiDB.uqTaskStatusCodes.Eof do
begin
taskItemCode := TTaskItemCode.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(taskItemCode);
taskItemCode.code := apiDB.uqTaskStatusCodesCODE.AsString;
taskItemCode.codeDesc := apiDB.uqTaskStatusCodesCODE_DESC.AsString;
taskItemCode.codeType := apiDB.uqTaskStatusCodesCODE_TYPE.AsString;
Result.itemStatusOptions.Add(taskItemCode);
apiDB.uqTaskStatusCodes.Next;
end;
apiDB.uqTaskItems.Close;
apiDB.uqTaskItems.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqTaskItems.Open;
......@@ -190,7 +228,24 @@ begin
item.reportedBy := apiDB.uqTaskItemsREPORTED_BY.AsString;
item.assignedTo := apiDB.uqTaskItemsASSIGNED_TO.AsString;
// ASSIGNED_TO holds a USER_ID; older rows hold a typed-in name, shown as-is
if apiDB.uqTaskItemsASSIGNED_USER_ID.IsNull then
item.assignedToDesc := item.assignedTo
else
item.assignedToDesc := BuildUserDisplayName(
apiDB.uqTaskItemsASSIGNED_FIRST_NAME.AsString,
apiDB.uqTaskItemsASSIGNED_LAST_NAME.AsString
);
item.status := apiDB.uqTaskItemsSTATUS.AsString;
item.statusDesc := apiDB.uqTaskItemsSTATUS_DESC.AsString;
// A value with no matching code (e.g. not yet converted) shows as-is
if item.statusDesc = '' then
item.statusDesc := item.status;
item.itemStatus := apiDB.uqTaskItemsITEM_STATUS.AsString;
item.itemStatusDesc := apiDB.uqTaskItemsITEM_STATUS_DESC.AsString;
if item.itemStatusDesc = '' then
item.itemStatusDesc := item.itemStatus;
if apiDB.uqTaskItemsSTATUS_DATE.IsNull then
item.statusDate := 0
......@@ -449,6 +504,8 @@ var
Result := 'ASSIGNED_TO'
else if SameText(AFieldName, 'status') then
Result := 'STATUS'
else if SameText(AFieldName, 'itemStatus') then
Result := 'ITEM_STATUS'
else if SameText(AFieldName, 'statusDate') then
Result := 'STATUS_DATE'
else if SameText(AFieldName, 'formSection') then
......@@ -505,6 +562,18 @@ begin
if columnName = '' then
raise Exception.Create('SaveTaskItemField: Invalid field name: ' + Item.fieldName);
// Assigned must be a user employed at some point during the task's dates
if SameText(Item.fieldName, 'assignedTo') and (Trim(Item.value) <> '') then
begin
apiDB.uqCheckAssignedUser.Close;
apiDB.uqCheckAssignedUser.ParamByName('USER_ID').AsString := Trim(Item.value);
apiDB.uqCheckAssignedUser.ParamByName('TASK_ITEM_ID').AsInteger := Item.taskItemId;
apiDB.uqCheckAssignedUser.Open;
if apiDB.uqCheckAssignedUser.FieldByName('USER_COUNT').AsInteger = 0 then
raise Exception.Create('That user was not employed during this task''s dates.');
end;
uqSaveField := TUniQuery.Create(nil);
try
uqSaveField.Connection := apiDB.ucETaskApi;
......@@ -588,6 +657,20 @@ begin
end;
// "First L." - first name and last initial
function TTaskItemService.BuildUserDisplayName(const firstName, lastName: string): string;
begin
Result := Trim(firstName);
if Trim(lastName) <> '' then
begin
if Result <> '' then
Result := Result + ' ';
Result := Result + UpperCase(Copy(Trim(lastName), 1, 1)) + '.';
end;
end;
function TTaskItemService.DeleteTaskRow(const taskId: Integer; const taskItemId: Integer): Boolean;
var
oldItemNum: Integer;
......@@ -632,231 +715,6 @@ begin
end;
function TTaskItemService.FindAssignedOptionId(const taskId, name: string): string;
begin
Result := '';
apiDB.uqTaskAssignedUsers.Close;
apiDB.uqTaskAssignedUsers.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqTaskAssignedUsers.Open;
while not apiDB.uqTaskAssignedUsers.Eof do
begin
if SameText(Trim(apiDB.uqTaskAssignedUsersNAME.AsString), Trim(name)) then
begin
Result := apiDB.uqTaskAssignedUsersTASK_ITEM_USER_ID.AsString;
Exit;
end;
apiDB.uqTaskAssignedUsers.Next;
end;
end;
function TTaskItemService.FindAssignedOptionName(const taskId, name: string): string;
begin
Result := '';
apiDB.uqTaskAssignedUsers.Close;
apiDB.uqTaskAssignedUsers.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqTaskAssignedUsers.Open;
while not apiDB.uqTaskAssignedUsers.Eof do
begin
if SameText(Trim(apiDB.uqTaskAssignedUsersNAME.AsString), Trim(name)) then
begin
Result := apiDB.uqTaskAssignedUsersNAME.AsString;
Exit;
end;
apiDB.uqTaskAssignedUsers.Next;
end;
end;
function TTaskItemService.AddAssignedName(taskId: string; name: string): TTaskUserOptionsResponse;
var
newName: string;
existingName: string;
newGuid: TGuid;
begin
try
newName := Trim(name);
if newName = '' then
raise Exception.Create('Assigned name cannot be blank.');
existingName := FindAssignedOptionName(taskId, newName);
if existingName = '' then
begin
CreateGUID(newGuid);
apiDB.uqAssignedInsert.Connection.StartTransaction;
try
apiDB.uqAssignedInsert.Close;
apiDB.uqAssignedInsert.ParamByName('TASK_ITEM_USER_ID').AsString := GuidToString(newGuid);
apiDB.uqAssignedInsert.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqAssignedInsert.ParamByName('NAME').AsString := newName;
apiDB.uqAssignedInsert.ExecSQL;
apiDB.uqAssignedInsert.Connection.Commit;
except
on E: Exception do
begin
if apiDB.uqAssignedInsert.Connection.InTransaction then
apiDB.uqAssignedInsert.Connection.Rollback;
raise;
end;
end;
end;
Result := BuildAssignedOptionsResponse(taskId);
except
on E: Exception do
begin
Logger.Log(2, 'TaskItemService.AddAssignedName - ERROR: ' + E.Message);
raise;
end;
end;
end;
function TTaskItemService.RenameAssignedName(taskId: string; oldName: string; newName: string): TTaskUserOptionsResponse;
var
oldAssignedId: string;
existingAssignedId: string;
trimmedOldName: string;
trimmedNewName: string;
begin
try
trimmedOldName := Trim(oldName);
trimmedNewName := Trim(newName);
if trimmedOldName = '' then
raise Exception.Create('Old assigned name cannot be blank.');
if trimmedNewName = '' then
raise Exception.Create('New assigned name cannot be blank.');
oldAssignedId := FindAssignedOptionId(taskId, trimmedOldName);
if oldAssignedId = '' then
raise Exception.Create('Assigned name not found.');
existingAssignedId := FindAssignedOptionId(taskId, trimmedNewName);
apiDB.uqAssignedRename.Connection.StartTransaction;
try
apiDB.uqRenameAssignedTo.Close;
apiDB.uqRenameAssignedTo.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqRenameAssignedTo.ParamByName('OLD_NAME').AsString := trimmedOldName;
apiDB.uqRenameAssignedTo.ParamByName('NEW_NAME').AsString := trimmedNewName;
apiDB.uqRenameAssignedTo.ExecSQL;
if (existingAssignedId <> '') and (not SameText(existingAssignedId, oldAssignedId)) then
begin
apiDB.uqAssignedDelete.Close;
apiDB.uqAssignedDelete.ParamByName('TASK_ITEM_USER_ID').AsString := oldAssignedId;
apiDB.uqAssignedDelete.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqAssignedDelete.ExecSQL;
end
else
begin
apiDB.uqAssignedRename.Close;
apiDB.uqAssignedRename.ParamByName('TASK_ITEM_USER_ID').AsString := oldAssignedId;
apiDB.uqAssignedRename.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqAssignedRename.ParamByName('NEW_NAME').AsString := trimmedNewName;
apiDB.uqAssignedRename.ExecSQL;
end;
apiDB.uqAssignedRename.Connection.Commit;
except
on E: Exception do
begin
if apiDB.uqAssignedRename.Connection.InTransaction then
apiDB.uqAssignedRename.Connection.Rollback;
raise;
end;
end;
Result := BuildAssignedOptionsResponse(taskId);
except
on E: Exception do
begin
Logger.Log(2, 'TaskItemService.RenameAssignedName - ERROR: ' + E.Message);
raise;
end;
end;
end;
function TTaskItemService.DeleteAssignedName(taskId: string; name: string): TTaskUserOptionsResponse;
var
assignedId: string;
assignedName: string;
begin
try
assignedId := FindAssignedOptionId(taskId, name);
assignedName := FindAssignedOptionName(taskId, name);
if assignedId = '' then
raise Exception.Create('Assigned name not found.');
apiDB.uqAssignedDelete.Connection.StartTransaction;
try
apiDB.uqBlankAssignedTo.Close;
apiDB.uqBlankAssignedTo.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqBlankAssignedTo.ParamByName('NAME').AsString := assignedName;
apiDB.uqBlankAssignedTo.ExecSQL;
apiDB.uqAssignedDelete.Close;
apiDB.uqAssignedDelete.ParamByName('TASK_ITEM_USER_ID').AsString := assignedId;
apiDB.uqAssignedDelete.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqAssignedDelete.ExecSQL;
apiDB.uqAssignedDelete.Connection.Commit;
except
on E: Exception do
begin
if apiDB.uqAssignedDelete.Connection.InTransaction then
apiDB.uqAssignedDelete.Connection.Rollback;
raise;
end;
end;
Result := BuildAssignedOptionsResponse(taskId);
except
on E: Exception do
begin
Logger.Log(2, 'TaskItemService.DeleteAssignedName - ERROR: ' + E.Message);
raise;
end;
end;
end;
function TTaskItemService.BuildAssignedOptionsResponse(const taskId: string): TTaskUserOptionsResponse;
var
taskUserOption: TTaskUserOption;
begin
Result := TTaskUserOptionsResponse.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result);
apiDB.uqTaskAssignedUsers.Close;
apiDB.uqTaskAssignedUsers.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqTaskAssignedUsers.Open;
while not apiDB.uqTaskAssignedUsers.Eof do
begin
taskUserOption := TTaskUserOption.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(taskUserOption);
taskUserOption.name := apiDB.uqTaskAssignedUsersNAME.AsString;
Result.assignedToOptions.Add(taskUserOption);
apiDB.uqTaskAssignedUsers.Next;
end;
end;
function TTaskItemService.FindProjectId(const taskId: string): string;
begin
Result := '';
......@@ -1106,6 +964,137 @@ begin
end;
function TTaskItemService.FindVersionName(const taskId, name: string): string;
begin
Result := '';
apiDB.uqProjectVersions.Close;
apiDB.uqProjectVersions.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqProjectVersions.Open;
while not apiDB.uqProjectVersions.Eof do
begin
if SameText(Trim(apiDB.uqProjectVersionsNAME.AsString), Trim(name)) then
begin
Result := apiDB.uqProjectVersionsNAME.AsString;
Exit;
end;
apiDB.uqProjectVersions.Next;
end;
end;
function TTaskItemService.BuildVersionOptionsResponse(const taskId: string): TTaskVersionOptionsResponse;
var
taskVersionOption: TTaskVersionOption;
begin
Result := TTaskVersionOptionsResponse.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result);
apiDB.uqProjectVersions.Close;
apiDB.uqProjectVersions.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqProjectVersions.Open;
while not apiDB.uqProjectVersions.Eof do
begin
taskVersionOption := TTaskVersionOption.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(taskVersionOption);
taskVersionOption.name := apiDB.uqProjectVersionsNAME.AsString;
Result.versionOptions.Add(taskVersionOption);
apiDB.uqProjectVersions.Next;
end;
end;
// Renames the version on every item in the task's project
function TTaskItemService.RenameVersionName(taskId: string; oldName: string; newName: string): TTaskVersionOptionsResponse;
var
trimmedOldName: string;
trimmedNewName: string;
begin
try
trimmedOldName := Trim(oldName);
trimmedNewName := Trim(newName);
if trimmedOldName = '' then
raise Exception.Create('Old version cannot be blank.');
if trimmedNewName = '' then
raise Exception.Create('New version cannot be blank.');
if FindVersionName(taskId, trimmedOldName) = '' then
raise Exception.Create('Version not found.');
apiDB.uqRenameTaskItemVersion.Connection.StartTransaction;
try
apiDB.uqRenameTaskItemVersion.Close;
apiDB.uqRenameTaskItemVersion.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqRenameTaskItemVersion.ParamByName('OLD_NAME').AsString := trimmedOldName;
apiDB.uqRenameTaskItemVersion.ParamByName('NEW_NAME').AsString := trimmedNewName;
apiDB.uqRenameTaskItemVersion.ExecSQL;
apiDB.uqRenameTaskItemVersion.Connection.Commit;
except
on E: Exception do
begin
if apiDB.uqRenameTaskItemVersion.Connection.InTransaction then
apiDB.uqRenameTaskItemVersion.Connection.Rollback;
raise;
end;
end;
Result := BuildVersionOptionsResponse(taskId);
except
on E: Exception do
begin
Logger.Log(2, 'TaskItemService.RenameVersionName - ERROR: ' + E.Message);
raise;
end;
end;
end;
// Clears the version from every item in the task's project
function TTaskItemService.DeleteVersionName(taskId: string; name: string): TTaskVersionOptionsResponse;
var
versionName: string;
begin
try
versionName := FindVersionName(taskId, name);
if versionName = '' then
raise Exception.Create('Version not found.');
apiDB.uqBlankTaskItemVersion.Connection.StartTransaction;
try
apiDB.uqBlankTaskItemVersion.Close;
apiDB.uqBlankTaskItemVersion.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqBlankTaskItemVersion.ParamByName('NAME').AsString := versionName;
apiDB.uqBlankTaskItemVersion.ExecSQL;
apiDB.uqBlankTaskItemVersion.Connection.Commit;
except
on E: Exception do
begin
if apiDB.uqBlankTaskItemVersion.Connection.InTransaction then
apiDB.uqBlankTaskItemVersion.Connection.Rollback;
raise;
end;
end;
Result := BuildVersionOptionsResponse(taskId);
except
on E: Exception do
begin
Logger.Log(2, 'TaskItemService.DeleteVersionName - ERROR: ' + E.Message);
raise;
end;
end;
end;
function TTaskItemService.FindReportedOptionId(const taskId, name: string): string;
begin
Result := '';
......
......@@ -25,6 +25,7 @@ type
category: string;
categoryDesc: string;
summary: string;
details: string;
end;
TTimeEntryTaskOption = class
......@@ -46,6 +47,7 @@ type
userName: string;
userStartDate: string; // yyyy-mm-dd employment window, '' = open-ended
userEndDate: string;
hideTimeEntriesFields: Boolean; // users.HIDE_TIME_ENTRIES_FIELDS = 'T': Compact View (hide Time and Place)
count: Integer;
items: TList<TTimeEntry>;
taskOptions: TList<TTimeEntryTaskOption>;
......@@ -61,11 +63,12 @@ type
userId: string;
taskDate: string;
taskId: string;
hours: Double;
hours: Nullable<Double>; // required, 0 allowed; nullable so a missing value is rejected, not saved as 0
taskTime: string;
place: string;
category: string;
summary: string;
details: string;
end;
TTaskPickerOption = class
......@@ -74,8 +77,11 @@ type
display: string;
customerId: string;
completed: Boolean; // tasks only: COMPLETION_DATE is set
completionDate: string; // tasks only: COMPLETION_DATE as 'yyyy-mm-dd' (the picker's End Date), '' = none
unavailableReason: string; // tasks only: why hours can't go on the picker date, '' = allowed
status: string; // tasks only: task status code
assigned: Boolean; // tasks only: the user has a task_assigned_user row (My Tasks)
focused: Boolean; // tasks only: that row has FOCUSED_TASK = 'T' (Focused Tasks)
end;
TTaskPickerOptionsResponse = class
......@@ -98,13 +104,17 @@ type
[HttpGet] function GetTimeEntries(userId, startDate, endDate, keptEntryIds: string): TTimeEntriesResponse;
[HttpPost] function AddTimeEntry(userId, taskDate: string): string;
[HttpPost] function SaveTimeEntry(Item: TTimeEntrySave): string;
// Why hours can't go on taskDate for this user and task ('' = allowed); the
// grid asks before SaveTimeEntry, which still enforces the same rule
function GetTimeEntryDateProblem(userId, taskId, taskDate: string): string;
[HttpPost] function DeleteTimeEntry(userId: string; entryId: Integer): Boolean;
[HttpPost] function AddTaskToFocus(userId, taskId: string): Boolean;
[HttpPost] function RemoveTaskFromFocus(userId, taskId: string): Boolean;
[HttpPost] function SetTaskStatus(taskId, status, taskDate: string): Boolean;
[HttpPost] function SetTaskStatusAndEndDate(taskId, status, endDate: string): Boolean;
[HttpPost] function SetHideTimeEntriesFields(userId: string; hide: Boolean): Boolean;
function GetTaskPickerCustomers: TTaskPickerOptionsResponse;
function GetTaskPickerStatuses: TTaskPickerOptionsResponse;
function GetTaskPickerProjects(customerId, scope, userId, taskDate: string): TTaskPickerOptionsResponse;
function GetTaskPickerProjects(customerId, scope, userId, taskDate, taskFilter: string): TTaskPickerOptionsResponse;
function GetTaskPickerTasks(projectId, userId, taskDate: string): TTaskPickerOptionsResponse;
function GetTaskPickerTaskContext(taskId: string): TTaskPickerTaskContext;
end;
......
......@@ -21,6 +21,7 @@ type
function ParseIsoDate(value: string): TDateTime;
function FieldText(AQuery: TUniQuery; AFieldName: string): string;
function DateText(AQuery: TUniQuery; AFieldName: string): string;
function TimeEntryTaskDateProblem(userId, taskId: string; taskDate: TDateTime): string;
procedure CheckTimeEntryDate(userId, taskId: string; taskDate: TDateTime);
function BuildTaskNumber(AQuery: TUniQuery): string;
function BuildTaskDisplay(AQuery: TUniQuery): string;
......@@ -35,15 +36,17 @@ type
function GetTimeEntries(userId, startDate, endDate, keptEntryIds: string): TTimeEntriesResponse;
function AddTimeEntry(userId, taskDate: string): string;
function SaveTimeEntry(Item: TTimeEntrySave): string;
function GetTimeEntryDateProblem(userId, taskId, taskDate: string): string;
function GetTaskPickerCustomers: TTaskPickerOptionsResponse;
function GetTaskPickerStatuses: TTaskPickerOptionsResponse;
function GetTaskPickerProjects(customerId, scope, userId, taskDate: string): TTaskPickerOptionsResponse;
function GetTaskPickerProjects(customerId, scope, userId, taskDate, taskFilter: string): TTaskPickerOptionsResponse;
function GetTaskPickerTasks(projectId, userId, taskDate: string): TTaskPickerOptionsResponse;
function GetTaskPickerTaskContext(taskId: string): TTaskPickerTaskContext;
function DeleteTimeEntry(userId: string; entryId: Integer): Boolean;
function AddTaskToFocus(userId, taskId: string): Boolean;
function RemoveTaskFromFocus(userId, taskId: string): Boolean;
function SetTaskStatus(taskId, status, taskDate: string): Boolean;
function SetTaskStatusAndEndDate(taskId, status, endDate: string): Boolean;
function SetHideTimeEntriesFields(userId: string; hide: Boolean): Boolean;
end;
implementation
......@@ -102,12 +105,14 @@ end;
// Hours may only be entered on a date that is not in the future (server's
// today) and is inside both the user's employment window and the task's
// window. All values are 'yyyy-mm-dd'; '' is open-ended and all ends are
// inclusive. The task's upper bound is its actual COMPLETION_DATE (DUE_DATE is
// ignored). Returns '' when ADate is '' or allowed, otherwise the message to
// show. Shared by SaveTimeEntry, AddTimeEntry and the task picker.
function TimeEntryDateProblem(const ADate, AUserStart, AUserEnd, ATaskStart, ATaskEnd: string): string;
// today) and is inside the user's employment window, the task's window and the
// task's project's window. All values are 'yyyy-mm-dd'; '' is open-ended and
// all ends are inclusive. The task's upper bound is its actual COMPLETION_DATE
// (DUE_DATE is ignored). Returns '' when ADate is '' or allowed, otherwise the
// message to show. Shared by SaveTimeEntry, AddTimeEntry,
// GetTimeEntryDateProblem and the task picker.
function TimeEntryDateProblem(const ADate, AUserStart, AUserEnd, ATaskStart, ATaskEnd: string;
const AProjectStart: string = ''; const AProjectEnd: string = ''): string;
begin
Result := '';
......@@ -135,16 +140,23 @@ begin
Exit(Format(
'This task was completed on %s, so hours can''t be entered on %s.',
[ATaskEnd, ADate]));
if ((AProjectStart <> '') and (ADate < AProjectStart)) or
((AProjectEnd <> '') and (ADate > AProjectEnd)) then
Exit(Format(
'This task''s project isn''t open on %s, so hours can''t be entered on it.',
[ADate]));
end;
procedure TTimeEntryService.CheckTimeEntryDate(userId, taskId: string; taskDate: TDateTime);
// Why userId can't enter hours on taskId for taskDate ('' = allowed). Raises
// only when the user or task doesn't exist.
function TTimeEntryService.TimeEntryTaskDateProblem(userId, taskId: string; taskDate: TDateTime): string;
var
q: TUniQuery;
dateValue: string;
userStart: string;
userEnd: string;
problem: string;
begin
dateValue := FormatDateTime('yyyy-mm-dd', taskDate);
......@@ -163,29 +175,45 @@ begin
userEnd := DateText(q, 'END_DATE');
// Future and employment dates are checked before the task lookup
problem := TimeEntryDateProblem(dateValue, userStart, userEnd, '', '');
if problem <> '' then
raise Exception.Create(problem);
Result := TimeEntryDateProblem(dateValue, userStart, userEnd, '', '');
if Result <> '' then
Exit;
q.Close;
q.SQL.Text := 'select START_DATE, COMPLETION_DATE from tasks where TASK_ID = :TASK_ID';
q.SQL.Text :=
'select ' +
' t.START_DATE, ' +
' t.COMPLETION_DATE, ' +
' p.START_DATE as PROJECT_START_DATE, ' +
' p.END_DATE as PROJECT_END_DATE ' +
'from tasks t ' +
'left join project p on p.PROJECT_ID = t.PROJECT_ID ' +
'where t.TASK_ID = :TASK_ID';
q.ParamByName('TASK_ID').AsString := taskId;
q.Open;
if q.IsEmpty then
raise Exception.Create('Task not found.');
problem := TimeEntryDateProblem(dateValue, userStart, userEnd,
DateText(q, 'START_DATE'), DateText(q, 'COMPLETION_DATE'));
if problem <> '' then
raise Exception.Create(problem);
Result := TimeEntryDateProblem(dateValue, userStart, userEnd,
DateText(q, 'START_DATE'), DateText(q, 'COMPLETION_DATE'),
DateText(q, 'PROJECT_START_DATE'), DateText(q, 'PROJECT_END_DATE'));
finally
q.Free;
end;
end;
procedure TTimeEntryService.CheckTimeEntryDate(userId, taskId: string; taskDate: TDateTime);
var
problem: string;
begin
problem := TimeEntryTaskDateProblem(userId, taskId, taskDate);
if problem <> '' then
raise Exception.Create(problem);
end;
function TTimeEntryService.BuildTaskNumber(AQuery: TUniQuery): string;
procedure AddPart(AValue: string);
......@@ -278,7 +306,7 @@ begin
try
userQuery.Connection := apiDB.ucETaskApi;
userQuery.SQL.Text :=
'select USER_ID, NAME, USER_NAME, START_DATE, END_DATE ' +
'select USER_ID, NAME, USER_NAME, START_DATE, END_DATE, HIDE_TIME_ENTRIES_FIELDS ' +
'from users ' +
'where USER_ID = :USER_ID';
......@@ -291,6 +319,7 @@ begin
AResponse.userStartDate := DateText(userQuery, 'START_DATE');
AResponse.userEndDate := DateText(userQuery, 'END_DATE');
AResponse.hideTimeEntriesFields := SameText(FieldText(userQuery, 'HIDE_TIME_ENTRIES_FIELDS'), 'T');
finally
userQuery.Free;
end;
......@@ -336,6 +365,7 @@ begin
' ti.CATEGORY, ' +
' cat.CODE_DESC as CATEGORY_DESC, ' +
' ti.SUMMARY, ' +
' ti.DETAILS, ' +
' c.SHORT_NAME as CUSTOMER_NAME, ' +
' p.NAME as PROJECT_NAME, ' +
' t.TASK_NUM_1, ' +
......@@ -395,6 +425,7 @@ begin
item.categoryDesc := item.category;
item.summary := FieldText(itemsQuery, 'SUMMARY');
item.details := FieldText(itemsQuery, 'DETAILS');
AResponse.items.Add(item);
itemsQuery.Next;
......@@ -655,8 +686,12 @@ begin
if Trim(Item.taskId) = '' then
raise Exception.Create('SaveTimeEntry: Task is required.');
if Item.hours <= 0 then
raise Exception.Create('SaveTimeEntry: Hours must be greater than zero.');
// Hours is required; zero is allowed, negative is not
if not Item.hours.HasValue then
raise Exception.Create('SaveTimeEntry: Hours is required.');
if Item.hours.Value < 0 then
raise Exception.Create('SaveTimeEntry: Hours cannot be negative.');
if Trim(Item.category) = '' then
raise Exception.Create('SaveTimeEntry: Category is required.');
......@@ -664,6 +699,10 @@ begin
if Trim(Item.summary) = '' then
raise Exception.Create('SaveTimeEntry: Summary is required.');
// Web limit only; time_items.SUMMARY itself is TEXT
if Length(Item.summary) > 500 then
raise Exception.Create('SaveTimeEntry: Summary must be 500 characters or fewer.');
Logger.Log(4, Format(
'TimeEntryService.SaveTimeEntry - ENTRY_ID="%s" USER_ID="%s"',
[Item.entryId, Item.userId]
......@@ -694,6 +733,7 @@ begin
' PLACE, ' +
' CATEGORY, ' +
' SUMMARY, ' +
' DETAILS, ' +
' CREATE_DATE, ' +
' CREATED_BY, ' +
' MODIFY_DATE, ' +
......@@ -709,6 +749,7 @@ begin
' :PLACE, ' +
' :CATEGORY, ' +
' :SUMMARY, ' +
' :DETAILS, ' +
' now(), ' +
' :CREATED_BY, ' +
' now(), ' +
......@@ -719,7 +760,7 @@ begin
q.ParamByName('USER_ID').AsString := Item.userId;
q.ParamByName('TASK_DATE').AsDateTime := taskDateValue;
q.ParamByName('TASK_ID').AsString := Item.taskId;
q.ParamByName('HOURS').AsFloat := Item.hours;
q.ParamByName('HOURS').AsFloat := Item.hours.Value;
if Trim(Item.taskTime) = '' then
q.ParamByName('TASK_TIME').Clear
......@@ -734,6 +775,11 @@ begin
q.ParamByName('CATEGORY').AsString := Item.category;
q.ParamByName('SUMMARY').AsString := Item.summary;
if Trim(Item.details) = '' then
q.ParamByName('DETAILS').Clear
else
q.ParamByName('DETAILS').AsString := Item.details;
q.ParamByName('CREATED_BY').AsString := Item.userId;
q.ParamByName('MODIFIED_BY').AsString := Item.userId;
......@@ -751,7 +797,7 @@ begin
apiDB.uqSaveTimeEntry.ParamByName('USER_ID').AsString := Item.userId;
apiDB.uqSaveTimeEntry.ParamByName('TASK_DATE').AsDateTime := taskDateValue;
apiDB.uqSaveTimeEntry.ParamByName('TASK_ID').AsString := Item.taskId;
apiDB.uqSaveTimeEntry.ParamByName('HOURS').AsFloat := Item.hours;
apiDB.uqSaveTimeEntry.ParamByName('HOURS').AsFloat := Item.hours.Value;
if Trim(Item.taskTime) = '' then
apiDB.uqSaveTimeEntry.ParamByName('TASK_TIME').Clear
......@@ -766,6 +812,11 @@ begin
apiDB.uqSaveTimeEntry.ParamByName('CATEGORY').AsString := Item.category;
apiDB.uqSaveTimeEntry.ParamByName('SUMMARY').AsString := Item.summary;
if Trim(Item.details) = '' then
apiDB.uqSaveTimeEntry.ParamByName('DETAILS').Clear
else
apiDB.uqSaveTimeEntry.ParamByName('DETAILS').AsString := Item.details;
apiDB.uqSaveTimeEntry.ParamByName('MODIFIED_BY').AsString := Item.userId;
apiDB.uqSaveTimeEntry.ExecSQL;
......@@ -789,6 +840,32 @@ begin
end;
// Read-only: the grid calls this before SaveTimeEntry so a task that can't take
// hours on the row's date is reported under the Task field, not as a save error
function TTimeEntryService.GetTimeEntryDateProblem(userId, taskId, taskDate: string): string;
begin
Logger.Log(4, Format(
'TimeEntryService.GetTimeEntryDateProblem - USER_ID="%s" TASK_ID="%s" TASK_DATE="%s"',
[userId, taskId, taskDate]));
try
Result := '';
// Blank date or task: the grid's required-field check reports those
if (Trim(taskDate) = '') or (Trim(taskId) = '') then
Exit;
Result := TimeEntryTaskDateProblem(userId, taskId, ParseIsoDate(Trim(taskDate)));
except
on E: Exception do
begin
Logger.Log(2, 'TimeEntryService.GetTimeEntryDateProblem - ERROR: ' + E.Message);
raise;
end;
end;
end;
function TTimeEntryService.GetTaskPickerCustomers: TTaskPickerOptionsResponse;
begin
Logger.Log(4, 'TimeEntryService.GetTaskPickerCustomers Start');
......@@ -874,14 +951,18 @@ end;
// status (customer field shown). Every scope lists "SHORT_NAME - project",
// ordered by short name then project, like emT3's Tasks screen.
// taskDate (yyyy-mm-dd) keeps only projects whose START_DATE-END_DATE includes
// it, like emT3's Time Entry screen; '' = any date
function TTimeEntryService.GetTaskPickerProjects(customerId, scope, userId, taskDate: string): TTaskPickerOptionsResponse;
// it, like emT3's Time Entry screen; '' = any date.
// taskFilter matches the picker's task radios: MY = only projects with a task
// assigned to the user (task_assigned_user), FOCUSED = only projects with a
// task the user has focused (FOCUSED_TASK = 'T'), ALL = no task filter. The
// picker's customer list follows these projects.
function TTimeEntryService.GetTaskPickerProjects(customerId, scope, userId, taskDate, taskFilter: string): TTaskPickerOptionsResponse;
var
projectDisplay: string;
dateValue: string;
begin
Logger.Log(4, Format('TimeEntryService.GetTaskPickerProjects - CUSTOMER_ID="%s" SCOPE="%s" USER_ID="%s" TASK_DATE="%s"',
[customerId, scope, userId, taskDate]));
Logger.Log(4, Format('TimeEntryService.GetTaskPickerProjects - CUSTOMER_ID="%s" SCOPE="%s" USER_ID="%s" TASK_DATE="%s" TASK_FILTER="%s"',
[customerId, scope, userId, taskDate, taskFilter]));
Result := TTaskPickerOptionsResponse.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result);
......@@ -890,6 +971,10 @@ begin
if (scope <> 'MY') and (scope <> 'ACTIVE') then
scope := 'ALL';
taskFilter := UpperCase(Trim(taskFilter));
if (taskFilter <> 'MY') and (taskFilter <> 'FOCUSED') then
taskFilter := 'ALL';
try
if Trim(taskDate) = '' then
dateValue := ''
......@@ -901,6 +986,7 @@ begin
apiDB.uqTaskPickerProjects.ParamByName('SCOPE').AsString := scope;
apiDB.uqTaskPickerProjects.ParamByName('USER_ID').AsString := userId;
apiDB.uqTaskPickerProjects.ParamByName('PROJECT_DATE').AsString := dateValue;
apiDB.uqTaskPickerProjects.ParamByName('TASK_FILTER').AsString := taskFilter;
apiDB.uqTaskPickerProjects.Open;
try
while not apiDB.uqTaskPickerProjects.Eof do
......@@ -933,12 +1019,13 @@ begin
end;
// The project's tasks, whatever the task's status (the picker's scope decides
// which projects are offered). Like emT3's Time Entry screen, only tasks open
// on taskDate are listed: START_DATE on or before it and COMPLETION_DATE on or
// after it ('' = open-ended); a blank taskDate lists every task. Each task
// carries unavailableReason: why hours can't go on taskDate for this user (same
// rule as SaveTimeEntry via TimeEntryDateProblem), '' when allowed or taskDate is blank.
// Every task in the project, whatever its status or dates (the picker's scope
// decides which projects are offered), so closed tasks and tasks outside the
// user's employment are listed too. Each task carries unavailableReason: why
// hours can't go on taskDate for this user, including the project's
// START_DATE-END_DATE (same rule as SaveTimeEntry via TimeEntryDateProblem);
// '' when allowed or taskDate is blank. The picker lists every task but shows
// the reason and refuses Select for one that has one.
function TTimeEntryService.GetTaskPickerTasks(projectId, userId, taskDate: string): TTaskPickerOptionsResponse;
var
q: TUniQuery;
......@@ -946,7 +1033,8 @@ var
dateValue: string;
userStart: string;
userEnd: string;
dateFilter: string;
projectStart: string;
projectEnd: string;
begin
Logger.Log(4, Format(
'TimeEntryService.GetTaskPickerTasks - PROJECT_ID="%s" USER_ID="%s" TASK_DATE="%s"',
......@@ -958,12 +1046,6 @@ begin
else
dateValue := FormatDateTime('yyyy-mm-dd', ParseIsoDate(Trim(taskDate)));
dateFilter := '';
if dateValue <> '' then
dateFilter :=
' and (t.START_DATE is null or date(t.START_DATE) <= :TASK_DATE) ' +
' and (t.COMPLETION_DATE is null or date(t.COMPLETION_DATE) >= :TASK_DATE) ';
Result := TTaskPickerOptionsResponse.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result);
......@@ -984,6 +1066,19 @@ begin
end;
q.Close;
// No project row: treat the project as open-ended
projectStart := '';
projectEnd := '';
q.SQL.Text := 'select START_DATE, END_DATE from project where PROJECT_ID = :PROJECT_ID';
q.ParamByName('PROJECT_ID').AsString := projectId;
q.Open;
if not q.IsEmpty then
begin
projectStart := DateText(q, 'START_DATE');
projectEnd := DateText(q, 'END_DATE');
end;
q.Close;
q.SQL.Text :=
'select distinct ' +
' t.TASK_ID, ' +
......@@ -998,19 +1093,30 @@ begin
' t.SUBJECT as TASK_SUBJECT, ' +
' t.START_DATE, ' +
' t.COMPLETION_DATE, ' +
' t.STATUS ' +
' t.STATUS, ' +
// Same checks as emT3's Time Entry screen (uqProjectTasks) behind its
// My Tasks and Focused filters; the picker filters on them client-side
' case when exists ( ' +
' select 1 from task_assigned_user tau ' +
' where tau.TASK_ID = t.TASK_ID ' +
' and tau.USER_ID = :USER_ID ' +
' ) then ''T'' else ''F'' end as USER_HAS_TASK, ' +
' case when exists ( ' +
' select 1 from task_assigned_user tau ' +
' where tau.TASK_ID = t.TASK_ID ' +
' and tau.USER_ID = :USER_ID ' +
' and tau.FOCUSED_TASK = ''T'' ' +
' ) then ''T'' else ''F'' end as USER_HAS_FOCUSED_TASK ' +
'from tasks t ' +
'join project p on p.PROJECT_ID = t.PROJECT_ID ' +
'join customers c on c.CUSTOMER_ID = p.CUSTOMER_ID ' +
'where t.PROJECT_ID = :PROJECT_ID ' +
dateFilter +
'order by ' +
' t.TASK_NUM_1, t.TASK_NUM_2, t.TASK_NUM_3, ' +
' t.TASK_NUM_4, t.TASK_NUM_5, t.TASK_NUM_6, t.SUBJECT';
q.ParamByName('PROJECT_ID').AsString := projectId;
if dateFilter <> '' then
q.ParamByName('TASK_DATE').AsString := dateValue;
q.ParamByName('USER_ID').AsString := userId;
q.Open;
while not q.Eof do
......@@ -1021,9 +1127,13 @@ begin
option.value := FieldText(q, 'TASK_ID');
option.display := BuildTaskDisplay(q);
option.completed := not q.FieldByName('COMPLETION_DATE').IsNull;
option.completionDate := DateText(q, 'COMPLETION_DATE');
option.unavailableReason := TimeEntryDateProblem(dateValue, userStart, userEnd,
DateText(q, 'START_DATE'), DateText(q, 'COMPLETION_DATE'));
DateText(q, 'START_DATE'), DateText(q, 'COMPLETION_DATE'),
projectStart, projectEnd);
option.status := FieldText(q, 'STATUS');
option.assigned := FieldText(q, 'USER_HAS_TASK') = 'T';
option.focused := FieldText(q, 'USER_HAS_FOCUSED_TASK') = 'T';
Result.options.Add(option);
q.Next;
......@@ -1255,21 +1365,72 @@ begin
end;
end;
// Changes a task's status from the task picker, like emT3's New Status on its
// Time Entry screen. CLOSED and COMP (the statuses emT3 requires a completion
// date for) set COMPLETION_DATE to the picker's work date (today when blank),
// but only when it is empty, as emT3's Task Entry screen does. Any other status
// reopens the task and clears COMPLETION_DATE (emT3 leaves it, which keeps a
// reopened task counted as completed). An unchanged status writes nothing.
function TTimeEntryService.SetTaskStatus(taskId, status, taskDate: string): Boolean;
// Saves the Time Entries page's Compact View checkbox (hides Time and Place)
// so it is remembered between sessions
function TTimeEntryService.SetHideTimeEntriesFields(userId: string; hide: Boolean): Boolean;
var
q: TUniQuery;
begin
Logger.Log(4, Format(
'TimeEntryService.SetHideTimeEntriesFields - USER_ID="%s" HIDE="%s"',
[userId, BoolToStr(hide, True)]
));
q := TUniQuery.Create(nil);
try
q.Connection := apiDB.ucETaskApi;
try
if Trim(userId) = '' then
raise Exception.Create('SetHideTimeEntriesFields: Invalid userId.');
q.Connection.StartTransaction;
q.SQL.Text :=
'update users ' +
'set HIDE_TIME_ENTRIES_FIELDS = :HIDE ' +
'where USER_ID = :USER_ID';
if hide then
q.ParamByName('HIDE').AsString := 'T'
else
q.ParamByName('HIDE').AsString := 'F';
q.ParamByName('USER_ID').AsString := userId;
q.ExecSQL;
q.Connection.Commit;
Result := True;
except
on E: Exception do
begin
if q.Connection.InTransaction then
q.Connection.Rollback;
Logger.Log(2, 'TimeEntryService.SetHideTimeEntriesFields - ERROR: ' + E.Message);
raise;
end;
end;
finally
q.Free;
end;
end;
// Saves a task's status and End Date (COMPLETION_DATE) from the task picker's
// footer, like emT3's New Status on its Time Entry screen. The picker fills
// End Date as the status changes (the Work Date for a blank End Date on CLOSED
// or COMP, blank for any other status) and the user can adjust it, so both
// are stored as sent. endDate '' clears COMPLETION_DATE; status '' keeps the
// current status. CLOSED and COMP (the statuses emT3 requires a completion date
// for) need an End Date, and an End Date can't be before the task's START_DATE.
function TTimeEntryService.SetTaskStatusAndEndDate(taskId, status, endDate: string): Boolean;
var
q: TUniQuery;
statusCode: string;
completionDate: TDateTime;
endDateValue: TDateTime;
startDate: string;
begin
Logger.Log(4, Format(
'TimeEntryService.SetTaskStatus - TASK_ID="%s" STATUS="%s" TASK_DATE="%s"',
[taskId, status, taskDate]
'TimeEntryService.SetTaskStatusAndEndDate - TASK_ID="%s" STATUS="%s" END_DATE="%s"',
[taskId, status, endDate]
));
q := TUniQuery.Create(nil);
......@@ -1277,14 +1438,26 @@ begin
q.Connection := apiDB.ucETaskApi;
try
statusCode := Trim(status);
endDate := Trim(endDate);
endDateValue := 0;
if Trim(taskId) = '' then
raise Exception.Create('Select a task.');
if Trim(taskDate) = '' then
completionDate := Date
else
completionDate := ParseIsoDate(Trim(taskDate));
if endDate <> '' then
endDateValue := ParseIsoDate(endDate);
q.SQL.Text := 'select STATUS, START_DATE from tasks where TASK_ID = :TASK_ID';
q.ParamByName('TASK_ID').AsString := taskId;
q.Open;
if q.IsEmpty then
raise Exception.Create('Task not found.');
if statusCode = '' then
statusCode := FieldText(q, 'STATUS');
startDate := DateText(q, 'START_DATE');
q.Close;
// Only codes the picker offers (GetTaskPickerStatuses)
q.SQL.Text :=
......@@ -1299,28 +1472,26 @@ begin
raise Exception.Create('Unknown task status.');
q.Close;
q.SQL.Text := 'select STATUS from tasks where TASK_ID = :TASK_ID';
q.ParamByName('TASK_ID').AsString := taskId;
q.Open;
if q.IsEmpty then
raise Exception.Create('Task not found.');
if FieldText(q, 'STATUS') = statusCode then
Exit(True);
if ((statusCode = 'CLOSED') or (statusCode = 'COMP')) and (endDate = '') then
raise Exception.Create('A Closed or Complete task needs an End Date.');
q.Close;
// ISO date strings compare in date order
if (endDate <> '') and (startDate <> '') and
(FormatDateTime('yyyy-mm-dd', endDateValue) < startDate) then
raise Exception.Create(Format(
'End Date can''t be before the task''s start date (%s).', [startDate]));
q.Connection.StartTransaction;
if (statusCode = 'CLOSED') or (statusCode = 'COMP') then
if endDate <> '' then
begin
q.SQL.Text :=
'update tasks ' +
'set STATUS = :STATUS, ' +
' COMPLETION_DATE = coalesce(COMPLETION_DATE, :COMPLETION_DATE) ' +
' COMPLETION_DATE = :COMPLETION_DATE ' +
'where TASK_ID = :TASK_ID';
q.ParamByName('COMPLETION_DATE').AsDate := completionDate;
q.ParamByName('COMPLETION_DATE').AsDate := endDateValue;
end
else
q.SQL.Text :=
......@@ -1341,7 +1512,7 @@ begin
if q.Connection.InTransaction then
q.Connection.Rollback;
Logger.Log(2, 'TimeEntryService.SetTaskStatus - ERROR: ' + E.Message);
Logger.Log(2, 'TimeEntryService.SetTaskStatusAndEndDate - ERROR: ' + E.Message);
raise;
end;
end;
......
......@@ -2,7 +2,7 @@
MemoLogLevel=5
FileLogLevel=5
webClientVersion=0.9.4.1
LogFileNum=243
LogFileNum=269
[Database]
--Server=192.168.102.131
......
......@@ -114,11 +114,11 @@
<VerInfo_Locale>1033</VerInfo_Locale>
<DCC_ExeOutput>.\bin</DCC_ExeOutput>
<DCC_UnitSearchPath>C:\RADTOOLS\FastMM4;$(DCC_UnitSearchPath)</DCC_UnitSearchPath>
<VerInfo_Keys>CompanyName=EM Systems;FileDescription=$(MSBuildProjectName);FileVersion=0.9.4.1;InternalName=;LegalCopyright=;LegalTrademarks=;OriginalFilename=;ProgramID=com.embarcadero.$(MSBuildProjectName);ProductName=$(MSBuildProjectName);ProductVersion=0.9.11;Comments=</VerInfo_Keys>
<VerInfo_Keys>CompanyName=EM Systems;FileDescription=$(MSBuildProjectName);FileVersion=0.9.4.3;InternalName=;LegalCopyright=;LegalTrademarks=;OriginalFilename=;ProgramID=com.embarcadero.$(MSBuildProjectName);ProductName=$(MSBuildProjectName);ProductVersion=0.9.11;Comments=</VerInfo_Keys>
<VerInfo_MajorVer>0</VerInfo_MajorVer>
<VerInfo_MinorVer>9</VerInfo_MinorVer>
<VerInfo_AutoIncVersion>true</VerInfo_AutoIncVersion>
<VerInfo_Build>1</VerInfo_Build>
<VerInfo_AutoIncVersion>false</VerInfo_AutoIncVersion>
<VerInfo_Build>3</VerInfo_Build>
<VerInfo_Release>4</VerInfo_Release>
</PropertyGroup>
<PropertyGroup Condition="'$(Cfg_1_Win64)'!=''">
......
-- emT3 web: database update for Task Items testing mode, Compact View and Time Entry details
-- MariaDB. Safe to re-run. Note: ALTER TABLE auto-commits, so this can't run as one transaction.
--
-- Before running: make sure the STATUS2 descriptions in step 3 match the ones used on dev,
-- since step 4 converts existing task_items.STATUS values by matching on CODE_DESC.
-- To undo the status conversion, restore task_items from task_items_bak_20261126.
-- 1. Back up task_items before converting Testing Status values
CREATE TABLE IF NOT EXISTS task_items_bak_20261126 AS
SELECT * FROM task_items;
-- 2. New columns
-- Task Item Status (codes TASK / STATUS); existing rows stay blank, new rows default to OPEN
ALTER TABLE task_items
ADD COLUMN IF NOT EXISTS ITEM_STATUS varchar(7) DEFAULT NULL AFTER NOTES;
-- Time Entries Compact View (hides Time and Place), saved per user
ALTER TABLE users
ADD COLUMN IF NOT EXISTS HIDE_TIME_ENTRIES_FIELDS varchar(1) DEFAULT 'F' AFTER AUTO_LAUNCH_TASK_TRACKER;
-- Time Entry Details offcanvas
ALTER TABLE time_items
ADD COLUMN IF NOT EXISTS DETAILS text DEFAULT NULL AFTER SUMMARY;
-- 3. Testing Status codes (codes TASK / STATUS2)
INSERT IGNORE INTO codes (CATEGORY, CODE_TYPE, CODE, CODE_DESC, CREATE_DATE) VALUES
('TASK', 'STATUS2', 'CD', 'Cannot Duplicate', NOW()),
('TASK', 'STATUS2', 'CT', 'Cannot Test', NOW()),
('TASK', 'STATUS2', 'FE', 'Future Enhancement', NOW()),
('TASK', 'STATUS2', 'FV', 'Fixed - Verified', NOW()),
('TASK', 'STATUS2', 'FX', 'Fixed', NOW()),
('TASK', 'STATUS2', 'IN', 'Investigating', NOW()),
('TASK', 'STATUS2', 'NF', 'Not Fixed', NOW()),
('TASK', 'STATUS2', 'NI', 'Non-Issue', NOW()),
('TASK', 'STATUS2', 'PP', 'Possibly a Problem', NOW());
-- 4. Convert existing Testing Status descriptions to their codes
UPDATE task_items ti
JOIN codes c
ON c.CATEGORY = 'TASK'
AND c.CODE_TYPE = 'STATUS2'
AND c.CODE_DESC = TRIM(ti.STATUS)
SET ti.STATUS = c.CODE;
-- 5. Checks
-- a) Testing Status values that still aren't a code (should return no rows)
SELECT ti.STATUS, COUNT(*) AS ROW_COUNT
FROM task_items ti
WHERE TRIM(IFNULL(ti.STATUS, '')) <> ''
AND ti.STATUS NOT IN (SELECT CODE FROM codes WHERE CATEGORY = 'TASK' AND CODE_TYPE = 'STATUS2')
GROUP BY ti.STATUS;
-- b) Task Item Status list (must include OPEN, which new rows default to)
SELECT CODE, CODE_DESC FROM codes WHERE CATEGORY = 'TASK' AND CODE_TYPE = 'STATUS' ORDER BY CODE_DESC;
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment