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/ ...@@ -14,6 +14,7 @@ emT3XDataServer/Source/__history/
emT3XDataServer/Source/__recovery/ emT3XDataServer/Source/__recovery/
emT3XDataServer/Win32/ emT3XDataServer/Win32/
.validation/ .validation/
.claude/
*.exe *.exe
*.local *.local
......
...@@ -172,6 +172,7 @@ procedure TAuthService.Logout; ...@@ -172,6 +172,7 @@ procedure TAuthService.Logout;
begin begin
DeleteToken; DeleteToken;
DMConnection.currentTaskId := ''; DMConnection.currentTaskId := '';
DMConnection.taskItemsTestingMode := False;
DMConnection.timeEntriesWeekOf := ''; DMConnection.timeEntriesWeekOf := '';
DMConnection.timeEntriesStartDate := ''; DMConnection.timeEntriesStartDate := '';
DMConnection.timeEntriesEndDate := ''; DMConnection.timeEntriesEndDate := '';
......
...@@ -21,6 +21,10 @@ type ...@@ -21,6 +21,10 @@ type
public public
currentTaskId: string; 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) // Time Entries range saved when a row opens Task Items, restored by Back ('' = none)
timeEntriesWeekOf: string; timeEntriesWeekOf: string;
timeEntriesStartDate: string; timeEntriesStartDate: string;
......
...@@ -27,6 +27,7 @@ type ...@@ -27,6 +27,7 @@ type
public public
class procedure Display(logoutProc: TLogoutProc); class procedure Display(logoutProc: TLogoutProc);
procedure ShowTaskItems(const ATaskId: string); procedure ShowTaskItems(const ATaskId: string);
procedure SetTaskItemsTitle(const ATestingMode: Boolean);
procedure ShowTimeEntries; procedure ShowTimeEntries;
end; end;
...@@ -62,7 +63,8 @@ begin ...@@ -62,7 +63,8 @@ begin
end end
else else
begin begin
lblAppTitle.Caption := 'Task Items'; // A direct task_id link opens Task Items in Testing mode
SetTaskItemsTitle(True);
ShowForm(TFTaskItems); ShowForm(TFTaskItems);
end; end;
end; end;
...@@ -80,14 +82,24 @@ begin ...@@ -80,14 +82,24 @@ begin
Application.CreateForm(aFormClass, pnlMain.ElementID, FChildForm); Application.CreateForm(aFormClass, pnlMain.ElementID, FChildForm);
end; 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); procedure TFViewMain.ShowTaskItems(const ATaskId: string);
begin begin
DMConnection.currentTaskId := ATaskId; DMConnection.currentTaskId := ATaskId;
lblAppTitle.Caption := 'Task Items'; SetTaskItemsTitle(DMConnection.taskItemsTestingMode);
ShowForm(TFTaskItems); ShowForm(TFTaskItems);
end; 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; procedure TFViewMain.ShowTimeEntries;
begin begin
DMConnection.currentTaskId := ''; DMConnection.currentTaskId := '';
......
...@@ -70,6 +70,42 @@ object FTaskItems: TFTaskItems ...@@ -70,6 +70,42 @@ object FTaskItems: TFTaskItems
WidthPercent = 100.000000000000000000 WidthPercent = 100.000000000000000000
OnClick = btnInsertRowClick OnClick = btnInsertRowClick
end 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 object btnCopyRow: TWebButton
Left = 78 Left = 78
Top = 210 Top = 210
...@@ -168,9 +204,21 @@ object FTaskItems: TFTaskItems ...@@ -168,9 +204,21 @@ object FTaskItems: TFTaskItems
object xdwdsTasksassignedTo: TStringField object xdwdsTasksassignedTo: TStringField
FieldName = 'assignedTo' FieldName = 'assignedTo'
end end
object xdwdsTasksassignedToDesc: TStringField
FieldName = 'assignedToDesc'
end
object xdwdsTasksstatus: TStringField object xdwdsTasksstatus: TStringField
FieldName = 'status' FieldName = 'status'
end end
object xdwdsTasksstatusDesc: TStringField
FieldName = 'statusDesc'
end
object xdwdsTasksitemStatus: TStringField
FieldName = 'itemStatus'
end
object xdwdsTasksitemStatusDesc: TStringField
FieldName = 'itemStatusDesc'
end
object xdwdsTasksstatusDate: TStringField object xdwdsTasksstatusDate: TStringField
FieldName = 'statusDate' FieldName = 'statusDate'
end end
......
...@@ -4,6 +4,18 @@ ...@@ -4,6 +4,18 @@
<h5 class="mb-0" id="lbl_project_name"></h5> <h5 class="mb-0" id="lbl_project_name"></h5>
<div class="d-flex align-items-center gap-2 ms-auto flex-nowrap"> <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 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"> <div class="task-toolbar d-flex align-items-center gap-1 px-2 py-1">
...@@ -59,4 +71,26 @@ ...@@ -59,4 +71,26 @@
</button> </button>
</div> </div>
</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> </div>
...@@ -20,7 +20,11 @@ type ...@@ -20,7 +20,11 @@ type
xdwdsTaskstaskDate: TStringField; xdwdsTaskstaskDate: TStringField;
xdwdsTasksreportedBy: TStringField; xdwdsTasksreportedBy: TStringField;
xdwdsTasksassignedTo: TStringField; xdwdsTasksassignedTo: TStringField;
xdwdsTasksassignedToDesc: TStringField;
xdwdsTasksstatus: TStringField; xdwdsTasksstatus: TStringField;
xdwdsTasksstatusDesc: TStringField;
xdwdsTasksitemStatus: TStringField;
xdwdsTasksitemStatusDesc: TStringField;
xdwdsTasksstatusDate: TStringField; xdwdsTasksstatusDate: TStringField;
xdwdsTasksformSection: TStringField; xdwdsTasksformSection: TStringField;
xdwdsTasksissue: TStringField; xdwdsTasksissue: TStringField;
...@@ -37,6 +41,9 @@ type ...@@ -37,6 +41,9 @@ type
btnFmtItalic: TWebButton; btnFmtItalic: TWebButton;
btnFmtUnderline: TWebButton; btnFmtUnderline: TWebButton;
btnBack: TWebButton; btnBack: TWebButton;
btnMyOpenItems: TWebButton;
btnAllItems: TWebButton;
btnFilters: TWebButton;
[async] procedure btnAddRowClick(Sender: TObject); [async] procedure btnAddRowClick(Sender: TObject);
procedure btnReloadClick(Sender: TObject); procedure btnReloadClick(Sender: TObject);
procedure WebFormCreate(Sender: TObject); procedure WebFormCreate(Sender: TObject);
...@@ -48,12 +55,17 @@ type ...@@ -48,12 +55,17 @@ type
procedure btnFmtItalicClick(Sender: TObject); procedure btnFmtItalicClick(Sender: TObject);
procedure btnFmtUnderlineClick(Sender: TObject); procedure btnFmtUnderlineClick(Sender: TObject);
procedure btnBackClick(Sender: TObject); procedure btnBackClick(Sender: TObject);
procedure btnMyOpenItemsClick(Sender: TObject);
procedure btnAllItemsClick(Sender: TObject);
procedure btnFiltersClick(Sender: TObject);
private private
FTaskId: string; FTaskId: string;
FApplicationOptions: TJSArray; FApplicationOptions: TJSArray;
FVersionOptions: TJSArray;
FReportedByOptions: TJSArray; FReportedByOptions: TJSArray;
FAssignedToOptions: TJSArray; FAssignedToOptions: TJSArray;
FStatusOptions: TJSArray; FStatusOptions: TJSArray;
FItemStatusOptions: TJSArray;
FPendingFocusTaskItemId: integer; FPendingFocusTaskItemId: integer;
FPendingFocusField: string; FPendingFocusField: string;
FSelectedTaskItemId: Integer; FSelectedTaskItemId: Integer;
...@@ -66,7 +78,23 @@ type ...@@ -66,7 +78,23 @@ type
FLastSelectionRange: JSValue; FLastSelectionRange: JSValue;
FNameManager: TNameManager; FNameManager: TNameManager;
FCopyingRow: Boolean; 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; [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); [async] procedure LoadTasks(const ATaskId: string);
procedure RenderTable; procedure RenderTable;
procedure BindTableEditors; procedure BindTableEditors;
...@@ -76,7 +104,7 @@ type ...@@ -76,7 +104,7 @@ type
procedure EnableAutoGrowTextAreas; procedure EnableAutoGrowTextAreas;
procedure GotoRowIndex(AIndex: Integer); procedure GotoRowIndex(AIndex: Integer);
function HtmlEncode(const s: string): string; function HtmlEncode(const s: string): string;
procedure SetTotalRowsLabel(ARowCount: Integer); procedure SetTotalRowsLabel(AShownCount, ATotalCount: Integer);
procedure SetTaskLabel(const ATitle: string); procedure SetTaskLabel(const ATitle: string);
[async] procedure SaveField(AIndex: Integer; const AFieldName: string); [async] procedure SaveField(AIndex: Integer; const AFieldName: string);
procedure EditorBlur(Event: TJSEvent); procedure EditorBlur(Event: TJSEvent);
...@@ -94,15 +122,15 @@ type ...@@ -94,15 +122,15 @@ type
procedure EditorKeyDown(Event: TJSEvent); procedure EditorKeyDown(Event: TJSEvent);
procedure CaptureTableScroll; procedure CaptureTableScroll;
procedure RestoreTableScroll; 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 AddReportedName(const AName: string): TJSArray;
[async] function RenameReportedName(const AOldName, ANewName: string): TJSArray; [async] function RenameReportedName(const AOldName, ANewName: string): TJSArray;
[async] function DeleteReportedName(const AName: string): TJSArray; [async] function DeleteReportedName(const AName: string): TJSArray;
[async] function AddApplicationName(const AName: string): TJSArray; [async] function AddApplicationName(const AName: string): TJSArray;
[async] function RenameApplicationName(const AOldName, ANewName: string): TJSArray; [async] function RenameApplicationName(const AOldName, ANewName: string): TJSArray;
[async] function DeleteApplicationName(const AName: 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 HandleAddManagedName(const AFieldName: string; const ARowIndex: Integer; const ANewName: string);
[async] procedure HandleRenameManagedName(const AFieldName, AOldName, ANewName: string); [async] procedure HandleRenameManagedName(const AFieldName, AOldName, ANewName: string);
[async] procedure HandleDeleteManagedName(const AFieldName, AName: string); [async] procedure HandleDeleteManagedName(const AFieldName, AName: string);
...@@ -123,22 +151,54 @@ implementation ...@@ -123,22 +151,54 @@ implementation
uses uses
ConnectionModule, ConnectionModule,
Auth.Service,
View.Main; View.Main;
{$R *.dfm} {$R *.dfm}
const
// Filter value that matches rows where the column is empty
FILTER_BLANK = '__blank__';
procedure TFTaskItems.WebFormCreate(Sender: TObject); procedure TFTaskItems.WebFormCreate(Sender: TObject);
var
payload: TJSObject;
testingItems: TJSHTMLInputElement;
begin begin
console.log('TFTaskItems.WebFormCreate fired'); 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']; FTaskId := Application.Parameters.Values['task_id'];
if FTaskId = '' then if FTaskId = '' then
FTaskId := DMConnection.currentTaskId; 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; FApplicationOptions := TJSArray.new;
FVersionOptions := TJSArray.new;
FReportedByOptions := TJSArray.new; FReportedByOptions := TJSArray.new;
FAssignedToOptions := TJSArray.new; FAssignedToOptions := TJSArray.new;
FStatusOptions := TJSArray.new; FStatusOptions := TJSArray.new;
FItemStatusOptions := TJSArray.new;
FSelectedTaskItemId := 0; FSelectedTaskItemId := 0;
FSelectedTaskId := 0; FSelectedTaskId := 0;
FCopyingRow := False; FCopyingRow := False;
...@@ -147,7 +207,7 @@ begin ...@@ -147,7 +207,7 @@ begin
FNameManager := TNameManager.Create( FNameManager := TNameManager.Create(
function(const AFieldName: string): TJSArray function(const AFieldName: string): TJSArray
begin begin
Result := uDropdownHelpers.GetOptionsForField(AFieldName, FApplicationOptions, FReportedByOptions, FAssignedToOptions); Result := uDropdownHelpers.GetOptionsForField(AFieldName, FApplicationOptions, FVersionOptions, FReportedByOptions);
end, end,
procedure(const ATriggerId: string) procedure(const ATriggerId: string)
begin begin
...@@ -168,6 +228,7 @@ begin ...@@ -168,6 +228,7 @@ begin
); );
FNameManager.BindControls; FNameManager.BindControls;
BindFilterControls;
// Back only applies when opened from a Time Entries row (no task_id in the URL) // Back only applies when opened from a Time Entries row (no task_id in the URL)
if Application.Parameters.Values['task_id'] = '' then if Application.Parameters.Values['task_id'] = '' then
...@@ -197,6 +258,16 @@ begin ...@@ -197,6 +258,16 @@ begin
end; 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; function TFTaskItems.HtmlEncode(const s: string): string;
begin begin
Result := s; Result := s;
...@@ -398,6 +469,8 @@ begin ...@@ -398,6 +469,8 @@ begin
try try
if await(AddTaskRowAtBottom) then if await(AddTaskRowAtBottom) then
begin begin
// The new row is blank, so it would be hidden by most filters
ClearFilters;
CaptureTableScroll; CaptureTableScroll;
LoadTasks(FTaskId); LoadTasks(FTaskId);
end; end;
...@@ -439,7 +512,7 @@ begin ...@@ -439,7 +512,7 @@ begin
btnDeleteRow.Enabled := False; btnDeleteRow.Enabled := False;
FPendingFocusItemNum := deletedItemNum; FPendingFocusItemNum := deletedItemNum;
FPendingFocusTaskField := 'application'; FPendingFocusTaskField := FirstEditField;
CaptureTableScroll; CaptureTableScroll;
LoadTasks(FTaskId); LoadTasks(FTaskId);
...@@ -470,6 +543,8 @@ begin ...@@ -470,6 +543,8 @@ begin
try try
if await(InsertTaskRowBelowSelection) then if await(InsertTaskRowBelowSelection) then
begin begin
// The new row is blank, so it would be hidden by most filters
ClearFilters;
CaptureTableScroll; CaptureTableScroll;
LoadTasks(FTaskId); LoadTasks(FTaskId);
end; end;
...@@ -489,6 +564,7 @@ begin ...@@ -489,6 +564,7 @@ begin
try try
if await(CopyTaskRow) then if await(CopyTaskRow) then
begin begin
ClearFilters;
CaptureTableScroll; CaptureTableScroll;
await(LoadTasks(FTaskId)); await(LoadTasks(FTaskId));
end; end;
...@@ -514,7 +590,7 @@ begin ...@@ -514,7 +590,7 @@ begin
FSelectedTaskItemId := StrToIntDef(string(TJSObject(response.Result)['value']), 0); FSelectedTaskItemId := StrToIntDef(string(TJSObject(response.Result)['value']), 0);
FPendingFocusTaskItemId := FSelectedTaskItemId; FPendingFocusTaskItemId := FSelectedTaskItemId;
FPendingFocusField := 'application'; FPendingFocusField := FirstEditField;
Result := True; Result := True;
except except
on E: EXDataClientRequestException do on E: EXDataClientRequestException do
...@@ -640,7 +716,7 @@ begin ...@@ -640,7 +716,7 @@ begin
console.log('AddTaskRow response=' + string(TJSJSON.stringify(response.Result))); console.log('AddTaskRow response=' + string(TJSJSON.stringify(response.Result)));
FPendingFocusItemNum := newItemNum; FPendingFocusItemNum := newItemNum;
FPendingFocusTaskField := 'application'; FPendingFocusTaskField := FirstEditField;
Result := True; Result := True;
except except
...@@ -704,13 +780,437 @@ begin ...@@ -704,13 +780,437 @@ begin
end; end;
procedure TFTaskItems.SetTotalRowsLabel(ARowCount: Integer); procedure TFTaskItems.SetTotalRowsLabel(AShownCount, ATotalCount: Integer);
var var
el: TJSHTMLElement; el: TJSHTMLElement;
begin begin
el := TJSHTMLElement(document.getElementById('lbl_total_rows')); 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 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; end;
...@@ -730,7 +1230,6 @@ var ...@@ -730,7 +1230,6 @@ var
resultObj, taskObj: TJSObject; resultObj, taskObj: TJSObject;
itemsArray: TJSArray; itemsArray: TJSArray;
titleText: string; titleText: string;
rowCount: Integer;
begin begin
console.log('ITaskItemService.GetTaskItems called with task_id: ' + ATaskId); console.log('ITaskItemService.GetTaskItems called with task_id: ' + ATaskId);
console.log('Load Tasks Fired'); console.log('Load Tasks Fired');
...@@ -761,13 +1260,13 @@ begin ...@@ -761,13 +1260,13 @@ begin
SetTaskLabel(titleText); SetTaskLabel(titleText);
rowCount := StrToIntDef(string(resultObj['count']), 0);
SetTotalRowsLabel(rowCount);
FApplicationOptions := ExtractOptionNames(TJSArray(resultObj['applicationOptions'])); FApplicationOptions := ExtractOptionNames(TJSArray(resultObj['applicationOptions']));
FVersionOptions := ExtractOptionNames(TJSArray(resultObj['versionOptions']));
FReportedByOptions := ExtractOptionNames(TJSArray(resultObj['reportedByOptions'])); FReportedByOptions := ExtractOptionNames(TJSArray(resultObj['reportedByOptions']));
FAssignedToOptions := ExtractOptionNames(TJSArray(resultObj['assignedToOptions'])); // These lists keep both a value and a display text: the value is saved, the text shown
FStatusOptions := ExtractCodeDescs(TJSArray(resultObj['statusOptions'])); FAssignedToOptions := TJSArray(resultObj['assignedToOptions']);
FStatusOptions := TJSArray(resultObj['statusOptions']);
FItemStatusOptions := TJSArray(resultObj['itemStatusOptions']);
itemsArray := TJSArray(resultObj['items']); itemsArray := TJSArray(resultObj['items']);
if not Assigned(itemsArray) then if not Assigned(itemsArray) then
...@@ -793,6 +1292,9 @@ var ...@@ -793,6 +1292,9 @@ var
host: TJSHTMLElement; host: TJSHTMLElement;
html: string; html: string;
rowIdx: Integer; rowIdx: Integer;
shownCount: Integer;
selectedShown: Boolean;
tableMinWidth: string;
function Th(const s: string): string; function Th(const s: string): string;
begin begin
...@@ -859,11 +1361,7 @@ var ...@@ -859,11 +1361,7 @@ var
begin begin
triggerId := 'task_dd_' + FieldName + '_' + IntToStr(AIdx); 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 '; buttonClass := 'btn btn-sm border w-100 d-flex justify-content-between align-items-center text-start task-dd-toggle btn-light';
if SameText(FieldName, 'status') then
buttonClass := buttonClass + GetTaskStatusClass(Current)
else
buttonClass := buttonClass + 'btn-light';
Result := Result :=
'<div class="dropdown w-100">' + '<div class="dropdown w-100">' +
...@@ -910,6 +1408,62 @@ var ...@@ -910,6 +1408,62 @@ var
'</div>'; '</div>';
end; 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; function RichTextEditor(const FieldName, Value: string; const AIdx: Integer): string;
var var
editorId: string; editorId: string;
...@@ -930,31 +1484,60 @@ begin ...@@ -930,31 +1484,60 @@ begin
if not Assigned(host) then if not Assigned(host) then
Exit; 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 := html :=
'<div class="tasks-vscroll">' + '<div class="tasks-vscroll">' +
'<div class="tasks-hscroll">' + '<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>' + '<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:200px">' + // App
'<col style="width:90px">' + // Version '<col style="width:120px">' + // Version
'<col style="width:140px">' + // Date '<col style="width:140px">'; // Date
html := html +
'<col style="width:120px">' + // Reported '<col style="width:120px">' + // Reported
'<col style="width:120px">' + // Assigned '<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:140px">' + // Status Date
'<col style="width:160px">' + // Form '<col style="width:160px">' + // Form
'<col style="width:520px">' + // Issue '<col style="width:520px">' + // Issue
'<col style="width:520px">' + // Notes '<col style="width:520px">' + // Notes
'</colgroup>' + '</colgroup>' +
'<thead><tr>' + '<thead><tr>' +
ThBlank + ThBlank;
if not FTaskMode then
html := html +
Th('App') + Th('App') +
Th('Version') + Th('Version') +
Th('Date') + Th('Date');
html := html +
Th('Reported') + Th('Reported') +
Th('Assigned') + Th('Assigned') +
Th('Status') + Th('Task Item Status');
if not FTaskMode then
html := html +
Th('Testing Status');
html := html +
Th('Status Date') + Th('Status Date') +
Th('Form') + Th('Form') +
Th('Issue/To-Do') + Th('Issue/To-Do') +
...@@ -962,18 +1545,44 @@ begin ...@@ -962,18 +1545,44 @@ begin
'</tr></thead><tbody>'; '</tr></thead><tbody>';
rowIdx := 0; rowIdx := 0;
shownCount := 0;
selectedShown := False;
xdwdsTasks.First; xdwdsTasks.First;
while not xdwdsTasks.Eof do while not xdwdsTasks.Eof do
begin 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 + 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) + '">' + '<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(SelectList('application', xdwdsTasksapplication.AsString, rowIdx, FApplicationOptions, True)) +
TdNowrap(TextInput('version', xdwdsTasksversion.AsString, rowIdx)) + TdNowrap(SelectList('version', xdwdsTasksversion.AsString, rowIdx, FVersionOptions, True)) +
TdNowrap(DateInput('taskDate', xdwdsTaskstaskDate.AsString, rowIdx)) + TdNowrap(DateInput('taskDate', xdwdsTaskstaskDate.AsString, rowIdx));
html := html +
TdNowrap(SelectList('reportedBy', xdwdsTasksreportedBy.AsString, rowIdx, FReportedByOptions, True)) + TdNowrap(SelectList('reportedBy', xdwdsTasksreportedBy.AsString, rowIdx, FReportedByOptions, True)) +
TdNowrap(SelectList('assignedTo', xdwdsTasksassignedTo.AsString, rowIdx, FAssignedToOptions, True)) + TdNowrap(CodeSelectList('assignedTo', xdwdsTasksassignedTo.AsString, xdwdsTasksassignedToDesc.AsString, rowIdx, FAssignedToOptions, 'userId', 'name')) +
TdNowrap(SelectList('status', xdwdsTasksstatus.AsString, rowIdx, FStatusOptions, False)) + 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(DateInput('statusDate', xdwdsTasksstatusDate.AsString, rowIdx)) +
TdNowrap(TextInput('formSection', xdwdsTasksformSection.AsString, rowIdx)) + TdNowrap(TextInput('formSection', xdwdsTasksformSection.AsString, rowIdx)) +
TdWrap(RichTextEditor('issue', xdwdsTasksissue.AsString, rowIdx)) + TdWrap(RichTextEditor('issue', xdwdsTasksissue.AsString, rowIdx)) +
...@@ -987,6 +1596,22 @@ begin ...@@ -987,6 +1596,22 @@ begin
html := html + '</tbody></table></div></div>'; html := html + '</tbody></table></div></div>';
host.innerHTML := html; 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; BindTableEditors;
EnableAutoGrowTextAreas; EnableAutoGrowTextAreas;
EnableColumnResize; EnableColumnResize;
...@@ -1112,7 +1737,7 @@ begin ...@@ -1112,7 +1737,7 @@ begin
console.log('MoveTaskRow: response=' + string(TJSJSON.stringify(response.Result))); console.log('MoveTaskRow: response=' + string(TJSJSON.stringify(response.Result)));
FPendingFocusTaskItemId := movedTaskItemId; FPendingFocusTaskItemId := movedTaskItemId;
FPendingFocusField := 'application'; FPendingFocusField := FirstEditField;
CaptureTableScroll; CaptureTableScroll;
LoadTasks(FTaskId); LoadTasks(FTaskId);
...@@ -1155,6 +1780,8 @@ begin ...@@ -1155,6 +1780,8 @@ begin
fieldValue := xdwdsTasksassignedTo.AsString fieldValue := xdwdsTasksassignedTo.AsString
else if SameText(AFieldName, 'status') then else if SameText(AFieldName, 'status') then
fieldValue := xdwdsTasksstatus.AsString fieldValue := xdwdsTasksstatus.AsString
else if SameText(AFieldName, 'itemStatus') then
fieldValue := xdwdsTasksitemStatus.AsString
else if SameText(AFieldName, 'statusDate') then else if SameText(AFieldName, 'statusDate') then
fieldValue := xdwdsTasksstatusDate.AsString fieldValue := xdwdsTasksstatusDate.AsString
else if SameText(AFieldName, 'formSection') then else if SameText(AFieldName, 'formSection') then
...@@ -1219,7 +1846,7 @@ procedure TFTaskItems.DropdownItemClick(Event: TJSEvent); ...@@ -1219,7 +1846,7 @@ procedure TFTaskItems.DropdownItemClick(Event: TJSEvent);
var var
el: TJSHTMLElement; el: TJSHTMLElement;
idx: Integer; idx: Integer;
idxStr, fieldName, newVal, triggerId: string; idxStr, fieldName, newVal, newDisplay, triggerId: string;
btn: TJSHTMLElement; btn: TJSHTMLElement;
labelEl: TJSHTMLElement; labelEl: TJSHTMLElement;
begin begin
...@@ -1235,6 +1862,12 @@ begin ...@@ -1235,6 +1862,12 @@ begin
newVal := string(el.getAttribute('data-value')); newVal := string(el.getAttribute('data-value'));
triggerId := string(el.getAttribute('data-trigger-id')); 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); idx := StrToIntDef(idxStr, -1);
if (idx < 0) or (fieldName = '') then if (idx < 0) or (fieldName = '') then
Exit; Exit;
...@@ -1244,7 +1877,23 @@ begin ...@@ -1244,7 +1877,23 @@ begin
Exit; Exit;
xdwdsTasks.Edit; 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; xdwdsTasks.Post;
if triggerId <> '' then if triggerId <> '' then
...@@ -1254,7 +1903,7 @@ begin ...@@ -1254,7 +1903,7 @@ begin
begin begin
labelEl := TJSHTMLElement(btn.querySelector('.task-dd-label')); labelEl := TJSHTMLElement(btn.querySelector('.task-dd-label'));
if Assigned(labelEl) then if Assigned(labelEl) then
labelEl.textContent := newVal; labelEl.textContent := newDisplay;
if SameText(fieldName, 'status') then if SameText(fieldName, 'status') then
ApplyTaskStatusClass(btn, newVal); ApplyTaskStatusClass(btn, newVal);
...@@ -1284,7 +1933,7 @@ begin ...@@ -1284,7 +1933,7 @@ begin
if (idx < 0) or (fieldName = '') then if (idx < 0) or (fieldName = '') then
Exit; 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; Exit;
FNameManager.OpenManager(fieldName, idx, triggerId); FNameManager.OpenManager(fieldName, idx, triggerId);
...@@ -1385,85 +2034,6 @@ begin ...@@ -1385,85 +2034,6 @@ begin
end; 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); [async] procedure TFTaskItems.HandleAddManagedName(const AFieldName: string; const ARowIndex: Integer; const ANewName: string);
var var
newOptions: TJSArray; newOptions: TJSArray;
...@@ -1471,8 +2041,8 @@ var ...@@ -1471,8 +2041,8 @@ var
begin begin
if SameText(AFieldName, 'application') then if SameText(AFieldName, 'application') then
newOptions := await(AddApplicationName(ANewName)) newOptions := await(AddApplicationName(ANewName))
else if SameText(AFieldName, 'assignedTo') then else if SameText(AFieldName, 'version') then
newOptions := await(AddAssignedName(ANewName)) newOptions := AddVersionName(ANewName)
else if SameText(AFieldName, 'reportedBy') then else if SameText(AFieldName, 'reportedBy') then
newOptions := await(AddReportedName(ANewName)) newOptions := await(AddReportedName(ANewName))
else else
...@@ -1483,10 +2053,10 @@ begin ...@@ -1483,10 +2053,10 @@ begin
if SameText(AFieldName, 'application') then if SameText(AFieldName, 'application') then
FApplicationOptions := newOptions FApplicationOptions := newOptions
else if SameText(AFieldName, 'reportedBy') then else if SameText(AFieldName, 'version') then
FReportedByOptions := newOptions FVersionOptions := newOptions
else else
FAssignedToOptions := newOptions; FReportedByOptions := newOptions;
resolvedName := FindOptionIgnoreCase(newOptions, ANewName); resolvedName := FindOptionIgnoreCase(newOptions, ANewName);
if resolvedName = '' then if resolvedName = '' then
...@@ -1514,8 +2084,8 @@ var ...@@ -1514,8 +2084,8 @@ var
begin begin
if SameText(AFieldName, 'application') then if SameText(AFieldName, 'application') then
newOptions := await(RenameApplicationName(AOldName, ANewName)) newOptions := await(RenameApplicationName(AOldName, ANewName))
else if SameText(AFieldName, 'assignedTo') then else if SameText(AFieldName, 'version') then
newOptions := await(RenameAssignedName(AOldName, ANewName)) newOptions := await(RenameVersionName(AOldName, ANewName))
else if SameText(AFieldName, 'reportedBy') then else if SameText(AFieldName, 'reportedBy') then
newOptions := await(RenameReportedName(AOldName, ANewName)) newOptions := await(RenameReportedName(AOldName, ANewName))
else else
...@@ -1526,10 +2096,10 @@ begin ...@@ -1526,10 +2096,10 @@ begin
if SameText(AFieldName, 'application') then if SameText(AFieldName, 'application') then
FApplicationOptions := newOptions FApplicationOptions := newOptions
else if SameText(AFieldName, 'reportedBy') then else if SameText(AFieldName, 'version') then
FReportedByOptions := newOptions FVersionOptions := newOptions
else else
FAssignedToOptions := newOptions; FReportedByOptions := newOptions;
CaptureTableScroll; CaptureTableScroll;
LoadTasks(FTaskId); LoadTasks(FTaskId);
...@@ -1541,8 +2111,8 @@ var ...@@ -1541,8 +2111,8 @@ var
begin begin
if SameText(AFieldName, 'application') then if SameText(AFieldName, 'application') then
newOptions := await(DeleteApplicationName(AName)) newOptions := await(DeleteApplicationName(AName))
else if SameText(AFieldName, 'assignedTo') then else if SameText(AFieldName, 'version') then
newOptions := await(DeleteAssignedName(AName)) newOptions := await(DeleteVersionName(AName))
else if SameText(AFieldName, 'reportedBy') then else if SameText(AFieldName, 'reportedBy') then
newOptions := await(DeleteReportedName(AName)) newOptions := await(DeleteReportedName(AName))
else else
...@@ -1553,10 +2123,10 @@ begin ...@@ -1553,10 +2123,10 @@ begin
if SameText(AFieldName, 'application') then if SameText(AFieldName, 'application') then
FApplicationOptions := newOptions FApplicationOptions := newOptions
else if SameText(AFieldName, 'reportedBy') then else if SameText(AFieldName, 'version') then
FReportedByOptions := newOptions FVersionOptions := newOptions
else else
FAssignedToOptions := newOptions; FReportedByOptions := newOptions;
CaptureTableScroll; CaptureTableScroll;
LoadTasks(FTaskId); LoadTasks(FTaskId);
...@@ -1641,6 +2211,86 @@ begin ...@@ -1641,6 +2211,86 @@ begin
end; 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; [async] function TFTaskItems.AddReportedName(const AName: string): TJSArray;
var var
response: TXDataClientResponse; 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 interface
uses 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 type
TTaskPickedProc = reference to procedure(
ARowIndex: Integer;
const ATaskId, ATaskDisplay, ATaskDate: string
);
TTaskFocusChangedProc = reference to procedure( TTaskFocusChangedProc = reference to procedure(
const ATaskId, ATaskDisplay: string; const ATaskId, ATaskDisplay: string;
AFocused: Boolean 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 private
FClient: TXDataWebClient;
FUserId: string; FUserId: string;
FRowIndex: Integer;
FOnTaskPicked: TTaskPickedProc;
FOnFocusChanged: TTaskFocusChangedProc; FOnFocusChanged: TTaskFocusChangedProc;
FHasChanges: Boolean; // Status, End Date or Focused Task differs from the saved value
FCustomers: TJSArray; FCustomers: TJSArray;
FProjects: 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; FFocusedTasks: TJSArray;
FSavedFocus: Boolean; FSavedFocus: Boolean;
FSavedTaskStatus: string; // selected task's status on the server, '' = no task 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; FSaving: Boolean;
FPrefillToken: Integer; FPrefillToken: Integer;
FScope: string; // MY, ACTIVE or ALL; kept between opens until the page reloads FScope: string; // MY, ACTIVE or ALL
FStatusesLoaded: Boolean; // footer Status dropdown is filled on the first open FTaskFilter: string; // ALL, MY or FOCUSED
FStatusesLoaded: Boolean; // footer Status dropdown is filled
procedure BindEvents; 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 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; function FindProjectCustomer(const AProjectId: string; out ACustomerId: string): Boolean;
procedure ClearSelect(const AElementId: string; ADisabled: Boolean); procedure ClearCombo(ACombo: TWebLookupComboBox; ADisabled: Boolean);
procedure FillSelect(const AElementId: string; AItems: TJSArray); procedure FillCombo(ACombo: TWebLookupComboBox; AItems: TJSArray);
procedure FilterProjects(const ACustomerId: string); procedure FilterProjects(const ACustomerId: string);
function SelectedValue(const AElementId: string): string;
function FindDisplay(AItems: TJSArray; const AValue: string): string; function FindDisplay(AItems: TJSArray; const AValue: string): string;
function FocusCheckbox: TJSHTMLInputElement; procedure ResetChanges;
function TaskStatusSelect: TJSHTMLSelectElement;
function PickerDate: string; function PickerDate: string;
function IsTaskCompleted(const ATaskId: string): Boolean;
function TaskStatus(const ATaskId: string): string; function TaskStatus(const ATaskId: string): string;
function TaskEndDate(const ATaskId: string): string;
function TaskUnavailableReason(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; function IsTaskFocused(const ATaskId: string): Boolean;
procedure SetTaskFocused(const ATaskId, ATaskDisplay: string; AFocused: Boolean); procedure SetTaskFocused(const ATaskId, ATaskDisplay: string; AFocused: Boolean);
procedure SetStatus(const AMessage: string); procedure SetStatus(const AMessage: string);
procedure ClearStatus; procedure ClearStatus;
procedure SetButtonEnabled(const AElementId: string; AEnabled: Boolean);
procedure UpdateButtons; procedure UpdateButtons;
procedure Show;
procedure Hide;
[async] procedure LoadCustomers; [async] procedure LoadCustomers;
[async] procedure LoadStatuses; [async] procedure LoadStatuses;
procedure FillStatuses;
procedure FillCustomers; procedure FillCustomers;
[async] procedure LoadProjects(const ACustomerId: string); [async] procedure LoadProjects(const ACustomerId: string);
[async] procedure LoadTasks(const AProjectId: string); [async] procedure LoadTasks(const AProjectId: string);
[async] procedure PreselectTask(const ATaskId: string; AToken: Integer); [async] procedure PreselectTask(const ATaskId: string; AToken: Integer);
[async] procedure ReloadForDate; [async] procedure ReloadForDate;
procedure SetSelectValue(const AElementId, AValue: string); [async] function ReloadForTaskFilter: Boolean;
procedure HoldTask(const ATaskId, AProjectId: string);
[async] procedure DateChanged(Event: TJSEvent); [async] function RestoreHeldTask(AToken: Integer): Boolean;
[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);
procedure UpdateFocusCheckbox; procedure UpdateFocusCheckbox;
procedure SelectClicked(Event: TJSEvent);
[async] procedure SaveClicked(Event: TJSEvent);
public public
constructor Create(AClient: TXDataWebClient; AOnTaskPicked: TTaskPickedProc; class function CreatePopup(AOwner: TComponent): TFTaskPicker;
AOnFocusChanged: TTaskFocusChangedProc); [async] procedure Start(const AUserId: string; AFocusedTasks: TJSArray;
[async] procedure Open(const AUserId: string; ARowIndex: Integer; AFocusedTasks: TJSArray;
const ATaskId, ATaskDate: string); 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; end;
implementation implementation
constructor TTaskPickerOffCanvas.Create(AClient: TXDataWebClient; AOnTaskPicked: TTaskPickedProc; {$R *.dfm}
AOnFocusChanged: TTaskFocusChangedProc);
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 begin
inherited Create; FHasChanges := False;
FClient := AClient;
FOnTaskPicked := AOnTaskPicked;
FOnFocusChanged := AOnFocusChanged;
FCustomers := TJSArray.new; FCustomers := TJSArray.new;
FProjects := TJSArray.new; FProjects := TJSArray.new;
FTasks := TJSArray.new; FTasks := TJSArray.new;
FTasksProjectId := '';
FVisibleTasks := TJSArray.new;
FHeldTaskId := '';
FHeldProjectId := '';
FLastTaskId := '';
FLastProjectId := '';
FFocusedTasks := TJSArray.new; FFocusedTasks := TJSArray.new;
FRowIndex := -1;
FSavedFocus := False; FSavedFocus := False;
FSavedTaskStatus := ''; FSavedTaskStatus := '';
FSavedEndDate := '';
FSaving := False; FSaving := False;
FPrefillToken := 0; 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; 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; end;
procedure TTaskPickerOffCanvas.BindEvents; // Not while a Save is running (Esc or the X would otherwise close it mid-save)
var procedure TFTaskPicker.WebFormCloseQuery(Sender: TObject; var CanClose: Boolean);
el: TJSHTMLElement;
begin begin
el := TJSHTMLElement(document.getElementById('task_picker_date')); CanClose := not FSaving;
if Assigned(el) then end;
el.addEventListener('change', TJSEventHandler(@DateChanged));
el := TJSHTMLElement(document.getElementById('task_picker_scope')); // TWebLookupComboBox puts each DisplayText into its option as HTML
if Assigned(el) then function TFTaskPicker.HtmlEncode(const s: string): string;
el.addEventListener('change', TJSEventHandler(@ScopeChanged)); 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')); // Sets the scope dropdown. The customer field shows in every scope; projects
if Assigned(el) then // are listed as "SHORT_NAME - project"
el.addEventListener('change', TJSEventHandler(@CustomerChanged)); procedure TFTaskPicker.ApplyScope(const AScope: string);
begin
FScope := AScope;
el := TJSHTMLElement(document.getElementById('task_picker_project')); cboScope.Value := AScope;
if Assigned(el) then end;
el.addEventListener('change', TJSEventHandler(@ProjectChanged));
el := TJSHTMLElement(document.getElementById('task_picker_task')); // Checks the All Tasks / My Tasks / Focused Tasks radio for AFilter
if Assigned(el) then procedure TFTaskPicker.SetTaskFilter(const AFilter: string);
el.addEventListener('change', TJSEventHandler(@TaskChanged)); 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')); // Same rules as emT3's Time Entry screen: My Tasks = assigned to the user,
if Assigned(el) then // Focused = assigned with FOCUSED_TASK = 'T' (flags come with the task list)
el.addEventListener('change', TJSEventHandler(@FocusCheckboxChanged)); 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')); // Fills the Task dropdown from the loaded list through the filter, with no
if Assigned(el) then // server call; keeps the chosen task when it's still listed
el.addEventListener('change', TJSEventHandler(@TaskStatusChanged)); 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')); for i := 0 to FTasks.length - 1 do
if Assigned(el) then begin
el.addEventListener('click', TJSEventHandler(@SaveClicked)); task := TJSObject(FTasks[i]);
if TaskMatchesFilter(task) then
FVisibleTasks.push(task);
end;
el := TJSHTMLElement(document.getElementById('btn_task_picker_select')); FillCombo(cboTask, FVisibleTasks);
if Assigned(el) then
el.addEventListener('click', TJSEventHandler(@SelectClicked));
end;
// Sets the scope dropdown. The customer field shows in every scope; projects if (selectedTask <> '') and (FindDisplay(FVisibleTasks, selectedTask) <> '') then
// are listed as "SHORT_NAME - project" cboTask.Value := selectedTask;
procedure TTaskPickerOffCanvas.ApplyScope(const AScope: string);
begin
FScope := AScope;
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; end;
function TTaskPickerOffCanvas.FindProjectCustomer(const AProjectId: string; out ACustomerId: string): Boolean; function TFTaskPicker.FindProjectCustomer(const AProjectId: string; out ACustomerId: string): Boolean;
var var
project: TJSObject; project: TJSObject;
i: Integer; i: Integer;
...@@ -178,45 +294,40 @@ begin ...@@ -178,45 +294,40 @@ begin
end; end;
end; end;
procedure TTaskPickerOffCanvas.ClearSelect(const AElementId: string; ADisabled: Boolean); // Leaves only the blank option
var procedure TFTaskPicker.ClearCombo(ACombo: TWebLookupComboBox; ADisabled: Boolean);
selectEl: TJSHTMLSelectElement;
begin begin
selectEl := TJSHTMLSelectElement(document.getElementById(AElementId)); FillCombo(ACombo, TJSArray.new);
if not Assigned(selectEl) then ACombo.Enabled := not ADisabled;
Exit;
selectEl.innerHTML := '<option value=""></option>';
selectEl.disabled := ADisabled;
end; 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 var
selectEl: TJSHTMLSelectElement;
optionEl: TJSHTMLOptionElement;
itemObj: TJSObject; itemObj: TJSObject;
i: Integer; i: Integer;
begin begin
selectEl := TJSHTMLSelectElement(document.getElementById(AElementId)); // One list rebuild for the whole fill instead of one per option
if not Assigned(selectEl) then ACombo.LookupValues.BeginUpdate;
Exit; try
ACombo.LookupValues.Clear;
selectEl.innerHTML := '<option value=""></option>'; ACombo.LookupValues.AddPair('', '');
for i := 0 to AItems.length - 1 do for i := 0 to AItems.length - 1 do
begin begin
itemObj := TJSObject(AItems[i]); itemObj := TJSObject(AItems[i]);
optionEl := TJSHTMLOptionElement(document.createElement('option')); ACombo.LookupValues.AddPair(string(itemObj['value']), HtmlEncode(string(itemObj['display'])));
optionEl.value := string(itemObj['value']); end;
optionEl.text := string(itemObj['display']); finally
selectEl.appendChild(optionEl); ACombo.LookupValues.EndUpdate;
end; end;
selectEl.disabled := False; ACombo.ItemIndex := 0;
ACombo.Enabled := True;
end; end;
procedure TTaskPickerOffCanvas.FilterProjects(const ACustomerId: string); procedure TFTaskPicker.FilterProjects(const ACustomerId: string);
var var
filteredProjects: TJSArray; filteredProjects: TJSArray;
project: TJSObject; project: TJSObject;
...@@ -234,21 +345,10 @@ begin ...@@ -234,21 +345,10 @@ begin
filteredProjects.push(project); filteredProjects.push(project);
end; end;
end; end;
FillSelect('task_picker_project', filteredProjects) FillCombo(cboProject, filteredProjects)
end; end;
function TTaskPickerOffCanvas.SelectedValue(const AElementId: string): string; function TFTaskPicker.FindDisplay(AItems: TJSArray; const AValue: 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;
var var
itemObj: TJSObject; itemObj: TJSObject;
i: Integer; i: Integer;
...@@ -263,45 +363,34 @@ begin ...@@ -263,45 +363,34 @@ begin
end; end;
end; end;
function TTaskPickerOffCanvas.FocusCheckbox: TJSHTMLInputElement; function TFTaskPicker.PickerDate: string;
begin begin
Result := TJSHTMLInputElement(document.getElementById('task_picker_add_focus')); Result := edtWorkDate.Text;
end; end;
function TTaskPickerOffCanvas.TaskStatusSelect: TJSHTMLSelectElement; // The task's End Date (COMPLETION_DATE, 'yyyy-mm-dd') as loaded with the task
begin // list; '' = none. A task with one counts as completed.
Result := TJSHTMLSelectElement(document.getElementById('task_picker_task_status')); function TFTaskPicker.TaskEndDate(const ATaskId: string): string;
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;
var var
itemObj: TJSObject; itemObj: TJSObject;
i: Integer; i: Integer;
begin begin
Result := False; Result := '';
for i := 0 to FTasks.length - 1 do for i := 0 to FTasks.length - 1 do
begin begin
itemObj := TJSObject(FTasks[i]); itemObj := TJSObject(FTasks[i]);
if string(itemObj['value']) = ATaskId then 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;
end; end;
// The task's status code as loaded with the task list; '' = unknown // 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 var
itemObj: TJSObject; itemObj: TJSObject;
i: Integer; i: Integer;
...@@ -321,7 +410,7 @@ begin ...@@ -321,7 +410,7 @@ begin
end; end;
// Why hours can't go on the picker date for this task; '' = allowed (or unknown) // 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 var
itemObj: TJSObject; itemObj: TJSObject;
i: Integer; i: Integer;
...@@ -340,18 +429,48 @@ begin ...@@ -340,18 +429,48 @@ begin
end; end;
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 var
reason: string; taskEl: TJSHTMLElement;
begin begin
reason := TaskUnavailableReason(SelectedValue('task_picker_task')); if FClosed then
if reason <> '' then Exit;
SetStatus(reason)
else taskEl := cboTask.ElementHandle;
ClearStatus; 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; 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 var
taskOption: TJSObject; taskOption: TJSObject;
i: Integer; i: Integer;
...@@ -370,11 +489,27 @@ begin ...@@ -370,11 +489,27 @@ begin
end; end;
end; end;
procedure TTaskPickerOffCanvas.SetTaskFocused(const ATaskId, ATaskDisplay: string; AFocused: Boolean); procedure TFTaskPicker.SetTaskFocused(const ATaskId, ATaskDisplay: string; AFocused: Boolean);
var var
taskOption: TJSObject; taskOption: TJSObject;
i: Integer; i: Integer;
begin 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 // Keep the picker's own copy of the focused list in sync with the server
for i := FFocusedTasks.length - 1 downto 0 do for i := FFocusedTasks.length - 1 downto 0 do
begin begin
...@@ -398,192 +533,135 @@ begin ...@@ -398,192 +533,135 @@ begin
end; end;
end; end;
procedure TTaskPickerOffCanvas.SetStatus(const AMessage: string); procedure TFTaskPicker.SetStatus(const AMessage: string);
var
el: TJSHTMLElement;
begin begin
el := TJSHTMLElement(document.getElementById('task_picker_status')); if FClosed then
if not Assigned(el) then
Exit; Exit;
el.innerText := AMessage; lblStatus.Caption := AMessage;
el.classList.remove('d-none'); lblStatus.Visible := True;
end; end;
procedure TTaskPickerOffCanvas.ClearStatus; procedure TFTaskPicker.ClearStatus;
var
el: TJSHTMLElement;
begin begin
el := TJSHTMLElement(document.getElementById('task_picker_status')); if FClosed then
if not Assigned(el) then
Exit; Exit;
el.innerText := ''; lblStatus.Caption := '';
el.classList.add('d-none'); lblStatus.Visible := False;
end; end;
procedure TTaskPickerOffCanvas.SetButtonEnabled(const AElementId: string; AEnabled: Boolean); procedure TFTaskPicker.UpdateButtons;
var
btn: TJSHTMLButtonElement;
begin
btn := TJSHTMLButtonElement(document.getElementById(AElementId));
if Assigned(btn) then
btn.disabled := not AEnabled;
end;
procedure TTaskPickerOffCanvas.UpdateButtons;
var var
hasTask: Boolean; hasTask: Boolean;
focusChanged: Boolean; focusChanged: Boolean;
focusBlocked: Boolean; focusBlocked: Boolean;
statusChanged: Boolean; statusChanged: Boolean;
endDateChanged: Boolean;
pendingStatus: string; pendingStatus: string;
addFocus: TJSHTMLInputElement;
statusSelect: TJSHTMLSelectElement;
begin begin
// Select: any picked task can be sent to the grid. // One button at the right: Save while the Focused Task checkbox, the Status
// Save: only when the Focused Task checkbox or the Status differs from what // or the End Date differs from what is saved on the server; otherwise Select,
// is saved on the server. // which sends the picked task to the grid.
hasTask := SelectedValue('task_picker_task') <> ''; hasTask := cboTask.Value <> '';
statusSelect := TaskStatusSelect; cboTaskStatus.Enabled := hasTask and (not FSaving) and FStatusesLoaded;
pendingStatus := ''; pendingStatus := cboTaskStatus.Value;
statusChanged := False; statusChanged := hasTask and (pendingStatus <> '') and (pendingStatus <> FSavedTaskStatus);
if Assigned(statusSelect) then edtEndDate.Enabled := hasTask and not FSaving;
begin endDateChanged := hasTask and (edtEndDate.Text <> FSavedEndDate);
statusSelect.disabled := (not hasTask) or FSaving or (not FStatusesLoaded);
pendingStatus := statusSelect.value; // A completed task (one with an End Date) can be selected for historical hours
statusChanged := hasTask and (pendingStatus <> '') and (pendingStatus <> FSavedTaskStatus); // but not newly focused (it can still be unfocused if it already is). The End
end; // Date on screen decides, since Save sends it before the focus change.
focusBlocked := hasTask and (edtEndDate.Text <> '') and (not FSavedFocus);
// 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, // Closing the task drops a focus tick that hasn't been saved yet
// the new status decides: Save sends it first, and the server sets the if focusBlocked then
// completion date for CLOSED/COMP and clears it for any other status. chkFocusedTask.Checked := False;
if statusChanged then
focusBlocked := (pendingStatus = 'CLOSED') or (pendingStatus = 'COMP') chkFocusedTask.Enabled := hasTask and (not FSaving) and (not focusBlocked);
else focusChanged := chkFocusedTask.Checked <> FSavedFocus;
focusBlocked := IsTaskCompleted(SelectedValue('task_picker_task'));
FHasChanges := hasTask and (focusChanged or statusChanged or endDateChanged);
focusBlocked := focusBlocked and hasTask and (not FSavedFocus);
btnSave.Visible := FHasChanges;
addFocus := FocusCheckbox; btnSelect.Visible := not FHasChanges;
focusChanged := False; btnSave.Enabled := not FSaving;
btnSelect.Enabled := hasTask and not FSaving;
if Assigned(addFocus) then btnCancel.Enabled := not FSaving;
begin btnClose.Enabled := not FSaving;
// 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;
end; end;
procedure TTaskPickerOffCanvas.Hide; [async] procedure TFTaskPicker.LoadCustomers;
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;
var var
response: TXDataClientResponse; response: TXDataClientResponse;
resultObj: TJSObject; resultObj: TJSObject;
begin begin
response := await(FClient.RawInvokeAsync( response := await(xdwcTaskPicker.RawInvokeAsync(
'ITimeEntryService.GetTaskPickerCustomers', [] 'ITimeEntryService.GetTaskPickerCustomers', []
)); ));
if FClosed then
Exit;
resultObj := TJSObject(response.Result); resultObj := TJSObject(response.Result);
FCustomers := TJSArray(resultObj['options']); FCustomers := TJSArray(resultObj['options']);
FillSelect('task_picker_customer', FCustomers); FillCombo(cboCustomer, FCustomers);
end; end;
// Fills the footer's Status dropdown with the task status codes // The footer's Status options are the task status codes; loaded once and
[async] procedure TTaskPickerOffCanvas.LoadStatuses; // reused by later opens
[async] procedure TFTaskPicker.LoadStatuses;
var var
response: TXDataClientResponse; response: TXDataClientResponse;
resultObj: TJSObject; resultObj: TJSObject;
statuses: TJSArray;
statusObj: TJSObject;
statusSelect: TJSHTMLSelectElement;
optionEl: TJSHTMLOptionElement;
i: Integer;
begin begin
response := await(FClient.RawInvokeAsync( if not Assigned(LoadedStatuses) then
'ITimeEntryService.GetTaskPickerStatuses', [] begin
)); response := await(xdwcTaskPicker.RawInvokeAsync(
'ITimeEntryService.GetTaskPickerStatuses', []
));
resultObj := TJSObject(response.Result); resultObj := TJSObject(response.Result);
statuses := TJSArray(resultObj['options']); LoadedStatuses := TJSArray(resultObj['options']);
end;
statusSelect := TaskStatusSelect; if FClosed then
if not Assigned(statusSelect) then
Exit; Exit;
statusSelect.innerHTML := ''; FillStatuses;
end;
for i := 0 to statuses.length - 1 do // No blank option here: the dropdown shows blank only while no task is picked
begin procedure TFTaskPicker.FillStatuses;
statusObj := TJSObject(statuses[i]); var
statusObj: TJSObject;
i: Integer;
begin
cboTaskStatus.LookupValues.BeginUpdate;
try
cboTaskStatus.LookupValues.Clear;
optionEl := TJSHTMLOptionElement(document.createElement('option')); for i := 0 to LoadedStatuses.length - 1 do
optionEl.value := string(statusObj['value']); begin
optionEl.text := string(statusObj['display']); statusObj := TJSObject(LoadedStatuses[i]);
statusSelect.appendChild(optionEl); cboTaskStatus.LookupValues.AddPair(string(statusObj['value']), HtmlEncode(string(statusObj['display'])));
end;
finally
cboTaskStatus.LookupValues.EndUpdate;
end; end;
// Blank until a task is picked (UpdateFocusCheckbox sets the task's status) // Blank until a task is picked (UpdateFocusCheckbox sets the task's status)
statusSelect.value := FSavedTaskStatus; cboTaskStatus.Value := FSavedTaskStatus;
FStatusesLoaded := True; FStatusesLoaded := True;
end; end;
// Only customers with a listed project (so the scope and Work Date apply to // 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 // them too, like emT3's Time Entry screen); keeps the chosen customer if still listed
procedure TTaskPickerOffCanvas.FillCustomers; procedure TFTaskPicker.FillCustomers;
var var
filteredCustomers: TJSArray; filteredCustomers: TJSArray;
customer: TJSObject; customer: TJSObject;
...@@ -592,7 +670,7 @@ var ...@@ -592,7 +670,7 @@ var
i: Integer; i: Integer;
j: Integer; j: Integer;
begin begin
selectedCustomer := SelectedValue('task_picker_customer'); selectedCustomer := cboCustomer.Value;
filteredCustomers := TJSArray.new; filteredCustomers := TJSArray.new;
for i := 0 to FCustomers.length - 1 do for i := 0 to FCustomers.length - 1 do
...@@ -608,81 +686,77 @@ begin ...@@ -608,81 +686,77 @@ begin
end; end;
end; end;
FillSelect('task_picker_customer', filteredCustomers); FillCombo(cboCustomer, filteredCustomers);
if (selectedCustomer <> '') and (FindDisplay(filteredCustomers, selectedCustomer) <> '') then if (selectedCustomer <> '') and (FindDisplay(filteredCustomers, selectedCustomer) <> '') then
SetSelectValue('task_picker_customer', selectedCustomer); cboCustomer.Value := selectedCustomer;
end; end;
[async] procedure TTaskPickerOffCanvas.LoadProjects(const ACustomerId: string); [async] procedure TFTaskPicker.LoadProjects(const ACustomerId: string);
var var
response: TXDataClientResponse; response: TXDataClientResponse;
resultObj: TJSObject; resultObj: TJSObject;
begin begin
// Projects in the scope that are open on the Work Date (any date when it's // Every project in the scope, whatever its dates (a blank date skips the
// blank); the customer list then follows the projects // server's date filter); the Task list's unavailableReason covers the
response := await(FClient.RawInvokeAsync( // 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', 'ITimeEntryService.GetTaskPickerProjects',
[ACustomerId, FScope, FUserId, PickerDate] [ACustomerId, FScope, FUserId, '', FTaskFilter]
)); ));
if FClosed then
Exit;
resultObj := TJSObject(response.Result); resultObj := TJSObject(response.Result);
FProjects := TJSArray(resultObj['options']); FProjects := TJSArray(resultObj['options']);
FillCustomers; FillCustomers;
end; end;
[async] procedure TTaskPickerOffCanvas.LoadTasks(const AProjectId: string); [async] procedure TFTaskPicker.LoadTasks(const AProjectId: string);
var var
response: TXDataClientResponse; response: TXDataClientResponse;
resultObj: TJSObject; resultObj: TJSObject;
taskDate: string; taskDate: string;
begin begin
// The server returns the project's tasks open on the Work Date (every task // The server returns every task in the project, closed ones included; each
// when it's blank); each one carries unavailableReason for this date and // one carries unavailableReason for the Work Date and this user ('' when
// user ('' when allowed or no date) // allowed or no date), which keeps Select from taking it
taskDate := PickerDate; taskDate := PickerDate;
response := await(FClient.RawInvokeAsync( response := await(xdwcTaskPicker.RawInvokeAsync(
'ITimeEntryService.GetTaskPickerTasks', 'ITimeEntryService.GetTaskPickerTasks',
[AProjectId, FUserId, taskDate] [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); resultObj := TJSObject(response.Result);
FTasks := TJSArray(resultObj['options']); FTasks := TJSArray(resultObj['options']);
FillSelect('task_picker_task', FTasks); FTasksProjectId := AProjectId;
FillTasks;
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;
end; end;
procedure TTaskPickerOffCanvas.SetSelectValue(const AElementId, AValue: string); // Setting a combo's Value in code doesn't fire OnChange, so the cascade
var // handlers don't run
selectEl: TJSHTMLSelectElement; [async] procedure TFTaskPicker.PreselectTask(const ATaskId: string; AToken: Integer);
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);
var var
response: TXDataClientResponse; response: TXDataClientResponse;
context: TJSObject; context: TJSObject;
projectId: string; projectId: string;
customerId: string; customerId: string;
begin begin
response := await(FClient.RawInvokeAsync( response := await(xdwcTaskPicker.RawInvokeAsync(
'ITimeEntryService.GetTaskPickerTaskContext', 'ITimeEntryService.GetTaskPickerTaskContext',
[ATaskId] [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 if AToken <> FPrefillToken then
Exit; Exit;
...@@ -691,89 +765,125 @@ begin ...@@ -691,89 +765,125 @@ begin
if projectId = '' then if projectId = '' then
Exit; Exit;
// Not one of My Projects: switch to Active, which lists every active project // The picker opens on All Projects with no date filter, so every project is listed
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
if not FindProjectCustomer(projectId, customerId) then if not FindProjectCustomer(projectId, customerId) then
begin begin
if PickerDate <> '' then SetStatus('This row''s task couldn''t be found in its project.');
SetStatus('This row''s project isn''t open on this date.')
else
SetStatus('This row''s task couldn''t be found in its project.');
Exit; Exit;
end; end;
SetSelectValue('task_picker_customer', customerId); cboCustomer.Value := customerId;
FilterProjects(customerId); FilterProjects(customerId);
SetSelectValue('task_picker_project', projectId); cboProject.Value := projectId;
await(LoadTasks(projectId)); await(LoadTasks(projectId));
if AToken <> FPrefillToken then if AToken <> FPrefillToken then
Exit; 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 if FindDisplay(FTasks, ATaskId) = '' then
begin begin
if PickerDate <> '' then SetStatus('This row''s task couldn''t be found in its project.');
SetStatus('This row''s task isn''t open on this date.')
else
SetStatus('This row''s task couldn''t be found in its project.');
UpdateFocusCheckbox; UpdateFocusCheckbox;
Exit; Exit;
end; end;
SetSelectValue('task_picker_task', ATaskId); // The picker opens on All Tasks, so the task is listed
cboTask.Value := ATaskId;
HoldTask(ATaskId, projectId);
UpdateFocusCheckbox; UpdateFocusCheckbox;
ShowTaskAvailability;
end; end;
// The Work Date changed: reload the projects (and so the procedure TFTaskPicker.HoldTask(const ATaskId, AProjectId: string);
// customers) and the selected project's tasks for the new date, keeping the begin
// customer, project and task when they're still listed FHeldTaskId := ATaskId;
[async] procedure TTaskPickerOffCanvas.ReloadForDate; 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 var
projectId: string; projectId: string;
taskId: string;
token: Integer; token: Integer;
begin begin
Inc(FPrefillToken); // user took over; abandon any prefill still loading Inc(FPrefillToken); // user took over; abandon any prefill still loading
token := FPrefillToken; token := FPrefillToken;
ClearStatus; ClearStatus;
HideTaskNotice;
projectId := SelectedValue('task_picker_project'); projectId := cboProject.Value;
taskId := SelectedValue('task_picker_task'); if projectId = '' then
begin
ClearSelect('task_picker_project', True); // Loaded tasks kept for restoring the held task were checked against the
ClearSelect('task_picker_task', True); // old date, so RestoreHeldTask has to load them again
UpdateFocusCheckbox; FTasksProjectId := '';
Exit;
end;
try try
await(LoadProjects('')); await(LoadTasks(projectId));
except except
on E: Exception do on E: Exception do
begin begin
SetStatus('Unable to load projects.'); SetStatus('Unable to load tasks.');
Exit; Exit;
end; end;
end; end;
...@@ -781,64 +891,89 @@ begin ...@@ -781,64 +891,89 @@ begin
if token <> FPrefillToken then if token <> FPrefillToken then
Exit; Exit;
// FillCustomers kept the customer if it still has a project on this date UpdateFocusCheckbox;
FilterProjects(SelectedValue('task_picker_customer')); end;
if projectId = '' then [async] procedure TFTaskPicker.edtWorkDateChange(Sender: TObject);
Exit; begin
await(ReloadForDate);
end;
if FindDisplay(FProjects, projectId) = '' then [async] procedure TFTaskPicker.cboScopeChange(Sender: TObject);
begin var
SetStatus('The selected project isn''t open on this date.'); token: Integer;
Exit; begin
end; 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 try
await(LoadTasks(projectId)); await(LoadProjects(''));
except except
on E: Exception do on E: Exception do
begin begin
SetStatus('Unable to load tasks.'); SetStatus('Unable to load projects.');
Exit; Exit;
end; end;
end; end;
// Another scope was picked while this list was loading
if token <> FPrefillToken then if token <> FPrefillToken then
Exit; Exit;
// Keep the chosen task and say whether it can take hours on the new date FilterProjects('');
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;
// Only when a task is selected, so an empty-project status isn't cleared // Back on the held task when this scope lists its project
if SelectedValue('task_picker_task') <> '' then if await(RestoreHeldTask(token)) then
ShowTaskAvailability; UpdateFocusCheckbox;
end; 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 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; 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 var
projectId: string;
token: Integer; token: Integer;
begin begin
Result := False;
Inc(FPrefillToken); // user took over; abandon any prefill still loading Inc(FPrefillToken); // user took over; abandon any prefill still loading
token := FPrefillToken; token := FPrefillToken;
ClearStatus;
ApplyScope(SelectedValue('task_picker_scope')); projectId := cboProject.Value;
SetSelectValue('task_picker_customer', '');
ClearSelect('task_picker_project', True);
ClearSelect('task_picker_task', True);
UpdateFocusCheckbox;
try try
await(LoadProjects('')); await(LoadProjects(''));
...@@ -850,44 +985,70 @@ begin ...@@ -850,44 +985,70 @@ begin
end; end;
end; end;
// Another scope was picked while this list was loading
if token <> FPrefillToken then if token <> FPrefillToken then
Exit; 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; end;
procedure TTaskPickerOffCanvas.CustomerChanged(Event: TJSEvent); procedure TFTaskPicker.cboCustomerChange(Sender: TObject);
var
customerId: string;
begin begin
Inc(FPrefillToken); // user took over; abandon any prefill still loading Inc(FPrefillToken); // user took over; abandon any prefill still loading
HoldTask('', ''); // browsing elsewhere: a filter change no longer brings the task back
ClearStatus; ClearStatus;
ClearSelect('task_picker_project', True); HideTaskNotice;
ClearSelect('task_picker_task', True); ClearCombo(cboProject, True);
ClearCombo(cboTask, True);
UpdateFocusCheckbox; UpdateFocusCheckbox;
customerId := SelectedValue('task_picker_customer'); FilterProjects(cboCustomer.Value);
FilterProjects(customerId);
end; end;
[async] procedure TTaskPickerOffCanvas.ProjectChanged(Event: TJSEvent); [async] procedure TFTaskPicker.cboProjectChange(Sender: TObject);
var var
projectId: string; projectId: string;
customerId: string; customerId: string;
project: TJSObject; project: TJSObject;
i: Integer; i: Integer;
token: Integer;
begin begin
Inc(FPrefillToken); // user took over; abandon any prefill still loading 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; ClearStatus;
ClearSelect('task_picker_task', True); HideTaskNotice;
ClearCombo(cboTask, True);
UpdateFocusCheckbox; UpdateFocusCheckbox;
projectId := SelectedValue('task_picker_project'); projectId := cboProject.Value;
if projectId = '' then if projectId = '' then
Exit; Exit;
customerId := SelectedValue('task_picker_customer'); customerId := cboCustomer.Value;
// No customer chosen: fill it in from the project // No customer chosen: fill it in from the project
if customerId = '' then if customerId = '' then
...@@ -903,141 +1064,226 @@ begin ...@@ -903,141 +1064,226 @@ begin
end; end;
end; end;
TJSHTMLSelectElement(document.getElementById('task_picker_customer')).value := customerId; cboCustomer.Value := customerId;
FilterProjects(customerId); FilterProjects(customerId);
TJSHTMLSelectElement(document.getElementById('task_picker_project')).value := projectId; cboProject.Value := projectId;
end; end;
try try
await(LoadTasks(projectId)); await(LoadTasks(projectId));
except except
on E: Exception do on E: Exception do
begin
SetStatus('Unable to load tasks.'); 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;
end; end;
procedure TTaskPickerOffCanvas.UpdateFocusCheckbox; procedure TFTaskPicker.UpdateFocusCheckbox;
var
addFocus: TJSHTMLInputElement;
statusSelect: TJSHTMLSelectElement;
begin begin
// Reset the checkbox to the task's saved focus state (discards any unsaved toggle) // Reset the checkbox to the task's saved focus state (discards any unsaved toggle)
FSavedFocus := IsTaskFocused(SelectedValue('task_picker_task')); FSavedFocus := IsTaskFocused(cboTask.Value);
chkFocusedTask.Checked := FSavedFocus;
addFocus := FocusCheckbox;
if Assigned(addFocus) then
addFocus.checked := FSavedFocus;
// Same for the Status dropdown: back to the task's saved status (blank with no task) // 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; // And the End Date: the task's COMPLETION_DATE, blank when it has none or no task
if Assigned(statusSelect) then FSavedEndDate := TaskEndDate(cboTask.Value);
statusSelect.value := FSavedTaskStatus; edtEndDate.Text := FSavedEndDate;
UpdateButtons; UpdateButtons;
end; end;
procedure TTaskPickerOffCanvas.TaskChanged(Event: TJSEvent); procedure TFTaskPicker.cboTaskChange(Sender: TObject);
begin begin
Inc(FPrefillToken); // user took over; abandon any prefill still loading 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; ClearStatus;
HideTaskNotice;
UpdateFocusCheckbox; UpdateFocusCheckbox;
ShowTaskAvailability;
end; end;
procedure TTaskPickerOffCanvas.FocusCheckboxChanged(Event: TJSEvent); procedure TFTaskPicker.chkFocusedTaskClick(Sender: TObject);
begin begin
ClearStatus; ClearStatus;
UpdateButtons; UpdateButtons;
end; end;
// Only marks the change; Save sends it, like the Focused Task checkbox // Only marks the change; Save sends it, like the Focused Task checkbox. The End
procedure TTaskPickerOffCanvas.TaskStatusChanged(Event: TJSEvent); // 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 begin
ClearStatus; ClearStatus;
UpdateButtons; UpdateButtons;
end; 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 var
taskId: string; taskId: string;
reason: string; reason: string;
begin begin
Event.preventDefault; taskId := cboTask.Value;
taskId := SelectedValue('task_picker_task');
if taskId = '' then if taskId = '' then
begin begin
SetStatus('Select a task.'); SetStatus('Select a task.');
Exit; Exit;
end; end;
// Listed but can't take hours on this date (completed, not started, or // Every task can be picked in the dropdown, but one that can't take hours on
// outside employment); the picker stays open so the date or task can change // 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); reason := TaskUnavailableReason(taskId);
if reason <> '' then if reason <> '' then
begin begin
SetStatus(reason); ShowTaskNotice(reason);
Exit; Exit;
end; end;
ClearStatus; ClearStatus;
// Sends the task and work date to the grid only; focus and status changes happen through Save // The caller puts the task and work date on the row; focus and status changes happen through Save
if Assigned(FOnTaskPicked) then FSelectedTaskId := taskId;
FOnTaskPicked(FRowIndex, taskId, FindDisplay(FTasks, taskId), PickerDate); FSelectedTaskDisplay := FindDisplay(FTasks, taskId);
FSelectedTaskDate := PickerDate;
Hide; ModalResult := mrOk;
end; end;
[async] procedure TTaskPickerOffCanvas.SaveClicked(Event: TJSEvent); [async] procedure TFTaskPicker.btnSaveClick(Sender: TObject);
var var
taskId: string; taskId: string;
taskDisplay: string; taskDisplay: string;
projectId: string; projectId: string;
methodName: string; methodName: string;
newStatus: string; newStatus: string;
addFocus: TJSHTMLInputElement; endDate: string;
statusSelect: TJSHTMLSelectElement;
focused: Boolean; focused: Boolean;
focusChanged: Boolean; focusChanged: Boolean;
statusChanged: Boolean; statusChanged: Boolean;
endDateChanged: Boolean;
statusSaved: Boolean; statusSaved: Boolean;
focusFailed: Boolean; focusFailed: Boolean;
token: Integer; token: Integer;
begin begin
Event.preventDefault;
if FSaving then if FSaving then
Exit; Exit;
taskId := SelectedValue('task_picker_task'); // Focus, Status and End Date belong to the task, so they need one picked
if taskId = '' then taskId := cboTask.Value;
begin
SetStatus('Select a task.');
Exit;
end;
addFocus := FocusCheckbox; focused := chkFocusedTask.Checked;
statusSelect := TaskStatusSelect; focusChanged := (taskId <> '') and (focused <> FSavedFocus);
if (not Assigned(addFocus)) or (not Assigned(statusSelect)) then
Exit;
focused := addFocus.checked; newStatus := cboTaskStatus.Value;
focusChanged := focused <> FSavedFocus; statusChanged := (taskId <> '') and (newStatus <> '') and (newStatus <> FSavedTaskStatus);
newStatus := statusSelect.value; endDate := edtEndDate.Text;
statusChanged := (newStatus <> '') and (newStatus <> FSavedTaskStatus); endDateChanged := (taskId <> '') and (endDate <> FSavedEndDate);
if (not focusChanged) and (not statusChanged) then if (not focusChanged) and (not statusChanged) and (not endDateChanged) then
begin begin
UpdateButtons; UpdateButtons;
Exit; Exit;
end; 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); taskDisplay := FindDisplay(FTasks, taskId);
projectId := SelectedValue('task_picker_project'); projectId := cboProject.Value;
statusSaved := False; statusSaved := False;
focusFailed := False; focusFailed := False;
...@@ -1045,25 +1291,30 @@ begin ...@@ -1045,25 +1291,30 @@ begin
FSaving := True; FSaving := True;
UpdateButtons; UpdateButtons;
try try
// Status first: closing the task decides whether it can still be focused // Status and End Date first, together: the End Date decides whether the
if statusChanged then // task can still be focused
if statusChanged or endDateChanged then
begin begin
try try
await(FClient.RawInvokeAsync('ITimeEntryService.SetTaskStatus', await(xdwcTaskPicker.RawInvokeAsync('ITimeEntryService.SetTaskStatusAndEndDate',
[taskId, newStatus, PickerDate])); [taskId, newStatus, endDate]));
statusSaved := True; statusSaved := True;
except except
on E: EXDataClientRequestException do on E: EXDataClientRequestException do
SetStatus(E.ErrorResult.ErrorMessage); SetStatus(E.ErrorResult.ErrorMessage);
on E: Exception do on E: Exception do
SetStatus('Unable to save task status.'); SetStatus('Unable to save the task''s status and End Date.');
end; end;
if not statusSaved then if not statusSaved then
Exit; Exit;
if SelectedValue('task_picker_task') = taskId then if cboTask.Value = taskId then
FSavedTaskStatus := newStatus; begin
if newStatus <> '' then
FSavedTaskStatus := newStatus;
FSavedEndDate := endDate;
end;
end; end;
if focusChanged then if focusChanged then
...@@ -1074,7 +1325,7 @@ begin ...@@ -1074,7 +1325,7 @@ begin
methodName := 'ITimeEntryService.RemoveTaskFromFocus'; methodName := 'ITimeEntryService.RemoveTaskFromFocus';
try try
await(FClient.RawInvokeAsync(methodName, [FUserId, taskId])); await(xdwcTaskPicker.RawInvokeAsync(methodName, [FUserId, taskId]));
except except
on E: EXDataClientRequestException do on E: EXDataClientRequestException do
begin begin
...@@ -1093,7 +1344,7 @@ begin ...@@ -1093,7 +1344,7 @@ begin
SetTaskFocused(taskId, taskDisplay, focused); SetTaskFocused(taskId, taskDisplay, focused);
// The user may have picked a different task while the request was running // 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; FSavedFocus := focused;
if Assigned(FOnFocusChanged) then if Assigned(FOnFocusChanged) then
...@@ -1105,12 +1356,11 @@ begin ...@@ -1105,12 +1356,11 @@ begin
UpdateButtons; UpdateButtons;
end; end;
// Reload the task list so its completed flag and availability follow the new // Reload the task list so its End Date and availability follow what was
// status. A task closed here gets the Work Date as its completion date, so it // saved (a task closed on the Work Date can still take hours on it). Skipped
// stays listed for this date. Skipped when the user has moved to another task // when the user has moved to another task or project meanwhile.
// or project meanwhile. if (not statusSaved) or (cboTask.Value <> taskId) or
if (not statusSaved) or (SelectedValue('task_picker_task') <> taskId) or (cboProject.Value <> projectId) then
(SelectedValue('task_picker_project') <> projectId) then
Exit; Exit;
Inc(FPrefillToken); Inc(FPrefillToken);
...@@ -1130,57 +1380,69 @@ begin ...@@ -1130,57 +1380,69 @@ begin
Exit; Exit;
if FindDisplay(FTasks, taskId) <> '' then 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 UpdateFocusCheckbox;
if not focusFailed then
ShowTaskAvailability;
end; 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; const AUserId: string;
ARowIndex: Integer;
AFocusedTasks: TJSArray; AFocusedTasks: TJSArray;
const ATaskId, ATaskDate: string const ATaskId, ATaskDate: string
); );
var var
token: Integer; token: Integer;
dateEl: TJSHTMLInputElement;
begin begin
FUserId := AUserId; FUserId := AUserId;
FRowIndex := ARowIndex;
// Start from the row's (draft) work date; it is only used to validate the chosen task // Start from the row's (draft) work date; it is only used to validate the chosen task
FTasks := TJSArray.new; edtWorkDate.Text := ATaskDate;
dateEl := TJSHTMLInputElement(document.getElementById('task_picker_date'));
if Assigned(dateEl) then
dateEl.value := ATaskDate;
Inc(FPrefillToken); Inc(FPrefillToken);
token := 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 if Assigned(AFocusedTasks) then
FFocusedTasks := AFocusedTasks.slice(0) FFocusedTasks := AFocusedTasks.slice(0)
else else
FFocusedTasks := TJSArray.new; FFocusedTasks := TJSArray.new;
ClearStatus; ClearStatus;
ApplyScope(FScope); // reopen on the last scope picked // Always opens as wide as possible: All Projects and All Tasks. The user can
ClearSelect('task_picker_customer', True); // narrow it from there; nothing is remembered for the next open.
ClearSelect('task_picker_project', True); ApplyScope('ALL');
ClearSelect('task_picker_task', True); SetTaskFilter('ALL');
ClearCombo(cboCustomer, True);
ClearCombo(cboProject, True);
ClearCombo(cboTask, True);
UpdateFocusCheckbox; UpdateFocusCheckbox;
Show;
try try
await(LoadCustomers); await(LoadCustomers);
if not FStatusesLoaded then if FClosed then
await(LoadStatuses); Exit;
await(LoadStatuses);
if FClosed then
Exit;
await(LoadProjects('')); await(LoadProjects(''));
if FClosed then
Exit;
FilterProjects(''); FilterProjects('');
except except
on E: Exception do on E: Exception do
......
...@@ -147,6 +147,9 @@ object FTimeEntries: TFTimeEntries ...@@ -147,6 +147,9 @@ object FTimeEntries: TFTimeEntries
object xdwdsTimeEntriessummary: TStringField object xdwdsTimeEntriessummary: TStringField
FieldName = 'summary' FieldName = 'summary'
end end
object xdwdsTimeEntriesdetails: TStringField
FieldName = 'details'
end
object xdwdsTimeEntriesplace: TStringField object xdwdsTimeEntriesplace: TStringField
FieldName = 'place' FieldName = 'place'
end end
......
...@@ -3,6 +3,13 @@ ...@@ -3,6 +3,13 @@
<h5 class="mb-0 text-nowrap" id="lbl_time_entries_title"></h5> <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"> <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_hours" class="me-2 text-nowrap fw-semibold">Total Hours: 0</div>
<div id="lbl_time_total_rows" class="me-2 text-nowrap"></div> <div id="lbl_time_total_rows" class="me-2 text-nowrap"></div>
...@@ -43,86 +50,21 @@ ...@@ -43,86 +50,21 @@
<div id="time_entries_table_host" class="flex-grow-1 min-h-0 overflow-auto"></div> <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"> <!-- Details (time_items.DETAILS) for one row; OK puts it on the row, the row's Save stores it.
<div class="modal-dialog modal-lg"> Static backdrop so a stray click outside doesn't throw away typed text. -->
<div class="modal-content"> <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasTimeDetails" aria-labelledby="time_details_title"
<div class="modal-header"> data-bs-backdrop="static" style="--bs-offcanvas-width: min(40rem, 100vw);">
<h5 class="modal-title" id="task_picker_title">Find Task</h5> <div class="offcanvas-header">
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> <h5 class="offcanvas-title" id="time_details_title">Details</h5>
</div> <button type="button" class="btn-close" data-bs-dismiss="offcanvas" 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>
<button type="button" class="btn btn-outline-success btn-sm" id="btn_task_picker_save" disabled> <div class="offcanvas-body d-flex flex-column">
Save <textarea id="time_details_text" class="form-control flex-grow-1 mb-3" style="resize: none;" aria-labelledby="time_details_title"></textarea>
</button>
<button type="button" class="btn btn-primary btn-sm" id="btn_task_picker_select" disabled> <div class="d-flex justify-content-end gap-2">
Select <button type="button" class="btn btn-outline-secondary btn-sm" data-bs-dismiss="offcanvas">Cancel</button>
</button> <button type="button" class="btn btn-primary btn-sm" id="btn_time_details_ok">OK</button>
</div>
</div> </div>
</div> </div>
</div> </div>
......
...@@ -5,7 +5,7 @@ interface ...@@ -5,7 +5,7 @@ interface
uses uses
System.SysUtils, System.Classes, System.DateUtils, JS, Web, WEBLib.Graphics, WEBLib.Controls, 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, 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 type
TFTimeEntries = class(TWebForm) TFTimeEntries = class(TWebForm)
...@@ -22,6 +22,7 @@ type ...@@ -22,6 +22,7 @@ type
xdwdsTimeEntriestaskTime: TStringField; xdwdsTimeEntriestaskTime: TStringField;
xdwdsTimeEntriescategory: TStringField; xdwdsTimeEntriescategory: TStringField;
xdwdsTimeEntriessummary: TStringField; xdwdsTimeEntriessummary: TStringField;
xdwdsTimeEntriesdetails: TStringField;
xdwdsTimeEntriescategoryDesc: TStringField; xdwdsTimeEntriescategoryDesc: TStringField;
btnAddEntry: TWebButton; btnAddEntry: TWebButton;
lblValidationMessage: TWebLabel; lblValidationMessage: TWebLabel;
...@@ -52,13 +53,13 @@ type ...@@ -52,13 +53,13 @@ type
FPendingEntryId: string; FPendingEntryId: string;
FLastMouseDownRowIndex: Integer; FLastMouseDownRowIndex: Integer;
FLastMouseDownTime: Double; FLastMouseDownTime: Double;
FTaskPickerOffCanvas: TTaskPickerOffCanvas;
FAddingNewEntry: Boolean; FAddingNewEntry: Boolean;
FNewEntryRowIndex: Integer; FNewEntryRowIndex: Integer;
FEditingEntryId: Integer; FEditingEntryId: Integer;
FEditingRowIndex: Integer; FEditingRowIndex: Integer;
FOriginalTaskDate: string; FOriginalTaskDate: string;
FOriginalHours: Double; FOriginalHours: Double;
FOriginalHoursBlank: Boolean; // Hours was blank (NULL) before the draft
FOriginalTaskId: string; FOriginalTaskId: string;
FOriginalTaskDisplay: string; FOriginalTaskDisplay: string;
FOriginalTaskTime: string; FOriginalTaskTime: string;
...@@ -67,11 +68,15 @@ type ...@@ -67,11 +68,15 @@ type
FOriginalCategory: string; FOriginalCategory: string;
FOriginalCategoryDesc: string; FOriginalCategoryDesc: string;
FOriginalSummary: string; FOriginalSummary: string;
FUserStartDate: string; FOriginalDetails: string;
FUserEndDate: 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 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 LoadTimeEntries;
[async] procedure HideFieldsChanged(Event: TJSEvent);
procedure SetHideFieldsCheckbox(AChecked: Boolean);
procedure KeepEntryIfOutsideRange(const AEntryId, ATaskDate: string); procedure KeepEntryIfOutsideRange(const AEntryId, ATaskDate: string);
function BeginAddEntry: Boolean; function BeginAddEntry: Boolean;
function IsNewEntryRow(AIndex: Integer): Boolean; function IsNewEntryRow(AIndex: Integer): Boolean;
...@@ -81,6 +86,10 @@ type ...@@ -81,6 +86,10 @@ type
procedure NewEntryCancelClick(Event: TJSEvent); procedure NewEntryCancelClick(Event: TJSEvent);
[async] procedure EntryDraftSaveClick(Event: TJSEvent); [async] procedure EntryDraftSaveClick(Event: TJSEvent);
procedure EntryDraftCancelClick(Event: TJSEvent); procedure EntryDraftCancelClick(Event: TJSEvent);
procedure DetailsButtonClick(Event: TJSEvent);
procedure DetailsOkClick(Event: TJSEvent);
procedure ShowDetailsEditor;
procedure HideDetailsEditor;
function BuildTimeEntryPayload(const AEntryId: string): TJSObject; function BuildTimeEntryPayload(const AEntryId: string): TJSObject;
procedure BeginEntryDraft(AIndex: Integer); procedure BeginEntryDraft(AIndex: Integer);
procedure ClearEntryDraft; procedure ClearEntryDraft;
...@@ -89,8 +98,8 @@ type ...@@ -89,8 +98,8 @@ type
function BlockForDraftRow(AIndex: Integer; const AAction: string): Boolean; function BlockForDraftRow(AIndex: Integer; const AAction: string): Boolean;
procedure DocumentFocusIn(Event: TJSEvent); procedure DocumentFocusIn(Event: TJSEvent);
function JsText(const AValue: JSValue): string; function JsText(const AValue: JSValue): string;
function IsTaskOpenOn(const ATaskStart, ATaskEnd, ADate: string): Boolean; [async] function GetTaskDateProblem(AIndex: Integer): string;
procedure RefreshTaskOptionStates(AIndex: Integer; const ADate: string); procedure ShowTaskDateNotice(AIndex: Integer; const AMessage: string);
[async] procedure SaveNewEntry; [async] procedure SaveNewEntry;
procedure CancelNewEntry; procedure CancelNewEntry;
procedure RenderTable; procedure RenderTable;
...@@ -113,6 +122,9 @@ type ...@@ -113,6 +122,9 @@ type
procedure RowFocusOut(Event: TJSEvent); procedure RowFocusOut(Event: TJSEvent);
procedure RowClick(Event: TJSEvent); procedure RowClick(Event: TJSEvent);
function ValidateRow(AIndex: Integer): Boolean; 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 ApplyPendingEntryFocus;
procedure ApplyRowValidation(AIndex: Integer); procedure ApplyRowValidation(AIndex: Integer);
procedure ClearRowValidation(AIndex: Integer); procedure ClearRowValidation(AIndex: Integer);
...@@ -140,14 +152,21 @@ implementation ...@@ -140,14 +152,21 @@ implementation
uses uses
Auth.Service, Auth.Service,
Utils, Utils,
View.Main; View.Main,
View.TaskPicker;
{$R *.dfm} {$R *.dfm}
const
// Web-only limit; time_items.SUMMARY itself is TEXT
SUMMARY_MAX_LENGTH = 500;
procedure TFTimeEntries.WebFormCreate(Sender: TObject); procedure TFTimeEntries.WebFormCreate(Sender: TObject);
var var
payload: TJSObject; payload: TJSObject;
anchorDate: string; anchorDate: string;
detailsOk: TJSHTMLElement;
hideFields: TJSHTMLElement;
begin begin
console.log('TFTimeEntries.WebFormCreate fired'); console.log('TFTimeEntries.WebFormCreate fired');
...@@ -167,8 +186,18 @@ begin ...@@ -167,8 +186,18 @@ begin
FNewEntryRowIndex := -1; FNewEntryRowIndex := -1;
FEditingEntryId := 0; FEditingEntryId := 0;
FEditingRowIndex := -1; 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('mousedown', TJSEventHandler(@DocumentMouseDown));
document.addEventListener('focusin', TJSEventHandler(@DocumentFocusIn)); document.addEventListener('focusin', TJSEventHandler(@DocumentFocusIn));
...@@ -411,8 +440,15 @@ begin ...@@ -411,8 +440,15 @@ begin
else else
SetTimeEntriesLabel(FUserName); SetTimeEntriesLabel(FUserName);
FUserStartDate := JsText(resultObj['userStartDate']); // Saved Compact View setting; after the first load the checkbox is the
FUserEndDate := JsText(resultObj['userEndDate']); // 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); rowCount := StrToIntDef(string(resultObj['count']), 0);
SetTotalRowsLabel(rowCount); SetTotalRowsLabel(rowCount);
...@@ -441,6 +477,47 @@ begin ...@@ -441,6 +477,47 @@ begin
end; 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 // A saved entry dated outside Start-End stays in the grid until the range changes
procedure TFTimeEntries.KeepEntryIfOutsideRange(const AEntryId, ATaskDate: string); procedure TFTimeEntries.KeepEntryIfOutsideRange(const AEntryId, ATaskDate: string);
begin begin
...@@ -465,7 +542,8 @@ var ...@@ -465,7 +542,8 @@ var
html: string; html: string;
rowIdx: Integer; rowIdx: Integer;
hoursText: string; hoursText: string;
rowDate: string; colCount: Integer;
tableMinWidth: Integer;
function Th(const s: string): string; function Th(const s: string): string;
begin begin
...@@ -517,18 +595,16 @@ var ...@@ -517,18 +595,16 @@ var
optionValue: string; optionValue: string;
optionDisplay: string; optionDisplay: string;
triggerId: string; triggerId: string;
taskAttrs: string;
taskStart: string;
taskEnd: string;
openTaskCount: Integer;
begin begin
triggerId := 'time_dd_' + FieldName + '_' + IntToStr(AIdx); triggerId := 'time_dd_' + FieldName + '_' + IntToStr(AIdx);
openTaskCount := 0;
Result := ''; Result := '';
// The task field's wrapper also holds the red popup ShowTaskDateNotice
// shows under it, like the Summary's
if AShowTaskPicker then if AShowTaskPicker then
Result := Result + Result := Result +
'<div class="time-task-wrap">' +
'<div class="input-group input-group-sm flex-nowrap w-100">'; '<div class="input-group input-group-sm flex-nowrap w-100">';
Result := Result + Result := Result +
...@@ -554,44 +630,23 @@ var ...@@ -554,44 +630,23 @@ var
'data-trigger-id="' + triggerId + '">&nbsp;</button>'; 'data-trigger-id="' + triggerId + '">&nbsp;</button>';
end; 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 for i := 0 to Items.length - 1 do
begin begin
optionObj := TJSObject(Items[i]); optionObj := TJSObject(Items[i]);
optionValue := string(optionObj[ValueProp]); optionValue := string(optionObj[ValueProp]);
optionDisplay := string(optionObj[DisplayProp]); 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 + Result := Result +
'<button type="button" class="dropdown-item time-dd-item" ' + '<button type="button" class="dropdown-item time-dd-item" ' +
'data-idx="' + IntToStr(AIdx) + '" ' + 'data-idx="' + IntToStr(AIdx) + '" ' +
'data-field="' + FieldName + '" ' + 'data-field="' + FieldName + '" ' +
'data-value="' + HtmlEncode(optionValue) + '" ' + 'data-value="' + HtmlEncode(optionValue) + '" ' +
'data-display="' + HtmlEncode(optionDisplay) + '" ' + 'data-display="' + HtmlEncode(optionDisplay) + '" ' +
taskAttrs +
'data-trigger-id="' + triggerId + '">' + HtmlEncode(optionDisplay) + '</button>'; 'data-trigger-id="' + triggerId + '">' + HtmlEncode(optionDisplay) + '</button>';
end; 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 + Result := Result +
'</div>' + '</div>' +
'</div>'; '</div>';
...@@ -610,40 +665,71 @@ var ...@@ -610,40 +665,71 @@ var
'<li><button type="button" class="dropdown-item time-task-items-btn" data-idx="' + IntToStr(AIdx) + '"' + '<li><button type="button" class="dropdown-item time-task-items-btn" data-idx="' + IntToStr(AIdx) + '"' +
IfThen(CurrentValue = '', ' disabled', '') + '>Task Items</button></li>' + IfThen(CurrentValue = '', ' disabled', '') + '>Task Items</button></li>' +
'</ul>' + '</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>'; '</div>';
end; end;
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 begin
Result := Result :=
'<textarea rows="1" class="form-control form-control-sm cell-textarea time-textarea time-editor w-100" ' + '<div class="d-flex align-items-start gap-1">' +
'data-idx="' + IntToStr(AIdx) + '" data-field="' + FieldName + '" ' + '<div class="time-summary-wrap flex-grow-1">' +
'style="min-height:31px; height:31px; overflow:hidden; resize:none;">' + HtmlEncode(Value) + '</textarea>'; '<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; end;
begin begin
host := TJSHTMLElement(document.getElementById('time_entries_table_host')); 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 := html :=
'<div class="time-vscroll">' + '<div class="time-vscroll">' +
'<div class="time-hscroll">' + '<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>' + '<colgroup>' +
'<col style="width:140px">' + // Date '<col style="width:125px">' + // Date
'<col style="width:540px">' + // Task '<col style="width:560px">' + // Task
'<col style="width:90px">' + // Hours '<col style="width:90px">' + // Hours
'<col style="width:140px">' + // Time IfThen(not FHideFields,
'<col style="width:160px">' + // Place '<col style="width:140px">' + // Time
'<col style="width:160px">', '') + // Place
'<col style="width:190px">' + // Category '<col style="width:190px">' + // Category
'<col style="width:450px">' + // Summary '<col>' + // Summary + Details button: takes the rest
'</colgroup>' + '</colgroup>' +
'<thead><tr>' + '<thead><tr>' +
Th('Date') + Th('Date') +
Th('Task') + Th('Task') +
Th('Hours') + Th('Hours') +
Th('Time') + IfThen(not FHideFields, Th('Time') + Th('Place'), '') +
Th('Place') +
Th('Category') + Th('Category') +
Th('Summary') + Th('Summary') +
'</tr></thead><tbody>'; '</tr></thead><tbody>';
...@@ -657,28 +743,35 @@ begin ...@@ -657,28 +743,35 @@ begin
else else
hoursText := FormatFloat('0.##', xdwdsTimeEntrieshours.AsFloat); hoursText := FormatFloat('0.##', xdwdsTimeEntrieshours.AsFloat);
rowDate := xdwdsTimeEntriestaskDate.AsString;
html := html + html := html +
'<tr class="time-row-selectable" data-idx="' + IntToStr(rowIdx) + '" data-entry-id="' + IntToStr(xdwdsTimeEntriesentryId.AsInteger) + '" data-task-id="' + xdwdsTimeEntriestaskId.AsString + '">' + '<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(DateInput('taskDate', xdwdsTimeEntriestaskDate.AsString, rowIdx)) +
TdNowrap(SelectList('taskId', xdwdsTimeEntriestaskId.AsString, xdwdsTimeEntriestaskDisplay.AsString, rowIdx, FTaskOptions, 'taskId', 'taskDisplay', False, True)) + 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(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)) + 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>'; '</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 if IsNewEntryRow(rowIdx) then
begin begin
html := html + html := html +
'<tr class="time-new-entry-actions-row">' + '<tr class="time-new-entry-actions-row">' +
'<td colspan="7" class="p-0 border-0">' + '<td colspan="' + IntToStr(colCount) + '" 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="d-flex justify-content-end">' +
'<div class="bg-body border rounded shadow-sm p-2 d-flex gap-2" style="pointer-events:auto;">' + '<div class="position-sticky d-inline-flex py-1 pe-2" style="right:0; z-index:5; pointer-events:none;">' +
'<button type="button" id="btn_time_new_save" class="btn btn-sm btn-success">Save</button>' + '<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_cancel" class="btn btn-sm btn-outline-secondary">Cancel</button>' + '<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>' +
'</div>' + '</div>' +
'</td>' + '</td>' +
...@@ -688,9 +781,13 @@ begin ...@@ -688,9 +781,13 @@ begin
html := html + html := html +
'<tr id="time-edit-actions-' + IntToStr(rowIdx) + '"' + '<tr id="time-edit-actions-' + IntToStr(rowIdx) + '"' +
IfThen(IsDraftEntryRow, '', ' hidden') + '>' + IfThen(IsDraftEntryRow, '', ' hidden') + '>' +
'<td colspan="7">' + '<td colspan="' + IntToStr(colCount) + '">' +
'<button type="button" class="btn btn-sm btn-success time-edit-save" data-idx="' + IntToStr(rowIdx) + '">Save</button> ' + '<div class="d-flex justify-content-end">' +
'<button type="button" class="btn btn-sm btn-outline-secondary time-edit-cancel" data-idx="' + IntToStr(rowIdx) + '">Cancel</button>' + '<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>' + '</td>' +
'</tr>'; '</tr>';
...@@ -762,11 +859,17 @@ begin ...@@ -762,11 +859,17 @@ begin
Result['userId'] := FUserId; Result['userId'] := FUserId;
Result['taskDate'] := xdwdsTimeEntriestaskDate.AsString; Result['taskDate'] := xdwdsTimeEntriestaskDate.AsString;
Result['taskId'] := xdwdsTimeEntriestaskId.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['taskTime'] := xdwdsTimeEntriestaskTime.AsString;
Result['place'] := xdwdsTimeEntriesplace.AsString; Result['place'] := xdwdsTimeEntriesplace.AsString;
Result['category'] := xdwdsTimeEntriescategory.AsString; Result['category'] := xdwdsTimeEntriescategory.AsString;
Result['summary'] := xdwdsTimeEntriessummary.AsString; Result['summary'] := xdwdsTimeEntriessummary.AsString;
Result['details'] := xdwdsTimeEntriesdetails.AsString;
end; end;
...@@ -781,6 +884,7 @@ begin ...@@ -781,6 +884,7 @@ begin
FEditingRowIndex := AIndex; FEditingRowIndex := AIndex;
FOriginalTaskDate := xdwdsTimeEntriestaskDate.AsString; FOriginalTaskDate := xdwdsTimeEntriestaskDate.AsString;
FOriginalHours := xdwdsTimeEntrieshours.AsFloat; FOriginalHours := xdwdsTimeEntrieshours.AsFloat;
FOriginalHoursBlank := xdwdsTimeEntrieshours.IsNull;
FOriginalTaskId := xdwdsTimeEntriestaskId.AsString; FOriginalTaskId := xdwdsTimeEntriestaskId.AsString;
FOriginalTaskDisplay := xdwdsTimeEntriestaskDisplay.AsString; FOriginalTaskDisplay := xdwdsTimeEntriestaskDisplay.AsString;
FOriginalTaskTime := xdwdsTimeEntriestaskTime.AsString; FOriginalTaskTime := xdwdsTimeEntriestaskTime.AsString;
...@@ -789,6 +893,7 @@ begin ...@@ -789,6 +893,7 @@ begin
FOriginalCategory := xdwdsTimeEntriescategory.AsString; FOriginalCategory := xdwdsTimeEntriescategory.AsString;
FOriginalCategoryDesc := xdwdsTimeEntriescategoryDesc.AsString; FOriginalCategoryDesc := xdwdsTimeEntriescategoryDesc.AsString;
FOriginalSummary := xdwdsTimeEntriessummary.AsString; FOriginalSummary := xdwdsTimeEntriessummary.AsString;
FOriginalDetails := xdwdsTimeEntriesdetails.AsString;
end; end;
...@@ -805,6 +910,7 @@ begin ...@@ -805,6 +910,7 @@ begin
FOriginalCategory := ''; FOriginalCategory := '';
FOriginalCategoryDesc := ''; FOriginalCategoryDesc := '';
FOriginalSummary := ''; FOriginalSummary := '';
FOriginalDetails := '';
end; end;
...@@ -881,67 +987,67 @@ begin ...@@ -881,67 +987,67 @@ begin
end; end;
// Same rule the server enforces on Save: ADate must be inside the user's // Save-time check, like CheckSummaryLength: every focused task is listed and can
// employment window and the task's window. Inclusive; '' = open-ended. // be picked, but hours can only go on a date that isn't in the future and is
// All values are 'yyyy-mm-dd', so plain string comparison is date order. // inside the user's employment and the task's and its project's dates. The
function TFTimeEntries.IsTaskOpenOn(const ATaskStart, ATaskEnd, ADate: string): Boolean; // 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 begin
Result := True; Result := '';
if ADate = '' then GotoRowIndex(AIndex);
Exit; // no date yet; required-field validation handles it if xdwdsTimeEntries.Eof then
Exit;
try
response := await(xdwcTimeEntries.RawInvokeAsync(
'ITimeEntryService.GetTimeEntryDateProblem',
[FUserId, xdwdsTimeEntriestaskId.AsString, xdwdsTimeEntriestaskDate.AsString]));
if (FUserStartDate <> '') and (ADate < FUserStartDate) then Result := JsText(TJSObject(response.Result)['value']);
Exit(False); except
if (FUserEndDate <> '') and (ADate > FUserEndDate) then on E: EXDataClientRequestException do
Exit(False); console.log('GetTaskDateProblem ERROR: ' + E.ErrorResult.ErrorMessage);
if (ATaskStart <> '') and (ADate < ATaskStart) then on E: Exception do
Exit(False); console.log('GetTaskDateProblem ERROR: ' + E.Message);
if (ATaskEnd <> '') and (ADate > ATaskEnd) then end;
Exit(False);
end; end;
// Re-check one row's task dropdown items after its date changes, without a re-render: // Shows AMessage like the Summary's "500 characters" error: the Task field
// tasks not open on the new date are hidden, and the empty-menu note shows if none are left // glows red and the red popup under it shows for 6 seconds
procedure TFTimeEntries.RefreshTaskOptionStates(AIndex: Integer; const ADate: string); procedure TFTimeEntries.ShowTaskDateNotice(AIndex: Integer; const AMessage: string);
var var
nodes: TJSNodeList; rowEl: TJSHTMLElement;
item: TJSHTMLElement; toggleEl: TJSHTMLElement;
emptyEl: TJSHTMLElement; noticeEl: TJSHTMLElement;
openTaskCount: Integer;
i: Integer;
begin begin
nodes := document.querySelectorAll( // Required fields passed, so any header message is stale
'.time-dd-item[data-field="taskId"][data-idx="' + IntToStr(AIndex) + '"]'); HideRowValidationMessage;
openTaskCount := 0; rowEl := TJSHTMLElement(document.querySelector('tr[data-idx="' + IntToStr(AIndex) + '"]'));
for i := 0 to nodes.length - 1 do if not Assigned(rowEl) then
begin Exit;
item := TJSHTMLElement(nodes.item(i));
if IsTaskOpenOn(string(item.getAttribute('data-start')), toggleEl := TJSHTMLElement(rowEl.querySelector('.time-dd-toggle[data-field="taskId"]'));
string(item.getAttribute('data-end')), ADate) then noticeEl := TJSHTMLElement(rowEl.querySelector('.time-task-notice'));
begin if (not Assigned(toggleEl)) or (not Assigned(noticeEl)) then
item.removeAttribute('disabled'); Exit;
item.removeAttribute('hidden');
Inc(openTaskCount);
end
else
begin
item.setAttribute('disabled', '');
item.setAttribute('hidden', '');
end;
end;
emptyEl := TJSHTMLElement(document.querySelector( toggleEl.focus;
'.time-dd-empty[data-idx="' + IntToStr(AIndex) + '"]')); asm
if Assigned(emptyEl) then toggleEl.classList.remove('time-field-flash-error');
begin void toggleEl.offsetWidth; // restarts the animation
if openTaskCount > 0 then toggleEl.classList.add('time-field-flash-error');
emptyEl.setAttribute('hidden', '')
else noticeEl.textContent = AMessage;
emptyEl.removeAttribute('hidden'); noticeEl.hidden = false;
clearTimeout(noticeEl.hideTimer);
noticeEl.hideTimer = setTimeout(function() { noticeEl.hidden = true; }, 6000); // 6 seconds
end; end;
end; end;
...@@ -952,6 +1058,7 @@ var ...@@ -952,6 +1058,7 @@ var
resultObj: TJSObject; resultObj: TJSObject;
payload: TJSObject; payload: TJSObject;
newTaskDate: string; newTaskDate: string;
dateProblem: string;
begin begin
if not FAddingNewEntry then if not FAddingNewEntry then
Exit; Exit;
...@@ -970,10 +1077,26 @@ begin ...@@ -970,10 +1077,26 @@ begin
Exit; Exit;
end; end;
if not CheckSummaryLength(FNewEntryRowIndex) then
begin
SetTopControlsEnabled(False);
Exit;
end;
payload := BuildTimeEntryPayload('0'); payload := BuildTimeEntryPayload('0');
Utils.ShowSpinner('spinner'); Utils.ShowSpinner('spinner');
try 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 try
response := await(xdwcTimeEntries.RawInvokeAsync( response := await(xdwcTimeEntries.RawInvokeAsync(
'ITimeEntryService.SaveTimeEntry', 'ITimeEntryService.SaveTimeEntry',
...@@ -1041,6 +1164,7 @@ var ...@@ -1041,6 +1164,7 @@ var
rowSelector: string; rowSelector: string;
saveError: string; saveError: string;
savedTaskDate: string; savedTaskDate: string;
dateProblem: string;
begin begin
saveButton := TJSHTMLButtonElement(Event.target); saveButton := TJSHTMLButtonElement(Event.target);
idx := StrToIntDef(string(saveButton.getAttribute('data-idx')), -1); idx := StrToIntDef(string(saveButton.getAttribute('data-idx')), -1);
...@@ -1063,6 +1187,9 @@ begin ...@@ -1063,6 +1187,9 @@ begin
Exit; Exit;
end; end;
if not CheckSummaryLength(idx) then
Exit;
payload := BuildTimeEntryPayload(IntToStr(savedEntryId)); payload := BuildTimeEntryPayload(IntToStr(savedEntryId));
savedTaskDate := xdwdsTimeEntriestaskDate.AsString; savedTaskDate := xdwdsTimeEntriestaskDate.AsString;
...@@ -1073,10 +1200,16 @@ begin ...@@ -1073,10 +1200,16 @@ begin
'.time-edit-cancel[data-idx="' + IntToStr(idx) + '"]')); '.time-edit-cancel[data-idx="' + IntToStr(idx) + '"]'));
saveError := ''; saveError := '';
dateProblem := '';
saveButton.disabled := True; saveButton.disabled := True;
cancelButton.disabled := True; cancelButton.disabled := True;
rowEl.setAttribute('inert', ''); rowEl.setAttribute('inert', '');
try 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 try
await(xdwcTimeEntries.RawInvokeAsync( await(xdwcTimeEntries.RawInvokeAsync(
'ITimeEntryService.SaveTimeEntry', [payload])); 'ITimeEntryService.SaveTimeEntry', [payload]));
...@@ -1093,7 +1226,13 @@ begin ...@@ -1093,7 +1226,13 @@ begin
rowEl.removeAttribute('inert'); rowEl.removeAttribute('inert');
end; 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 if saveError <> '' then
begin begin
TJSHTMLElement(rowEl.querySelector('[data-field="taskDate"]')).classList.add('is-invalid'); TJSHTMLElement(rowEl.querySelector('[data-field="taskDate"]')).classList.add('is-invalid');
...@@ -1142,7 +1281,10 @@ begin ...@@ -1142,7 +1281,10 @@ begin
xdwdsTimeEntries.Edit; xdwdsTimeEntries.Edit;
xdwdsTimeEntriestaskDate.AsString := FOriginalTaskDate; xdwdsTimeEntriestaskDate.AsString := FOriginalTaskDate;
xdwdsTimeEntrieshours.AsFloat := FOriginalHours; if FOriginalHoursBlank then
xdwdsTimeEntrieshours.Clear
else
xdwdsTimeEntrieshours.AsFloat := FOriginalHours;
xdwdsTimeEntriestaskId.AsString := FOriginalTaskId; xdwdsTimeEntriestaskId.AsString := FOriginalTaskId;
xdwdsTimeEntriestaskDisplay.AsString := FOriginalTaskDisplay; xdwdsTimeEntriestaskDisplay.AsString := FOriginalTaskDisplay;
xdwdsTimeEntriestaskTime.AsString := FOriginalTaskTime; xdwdsTimeEntriestaskTime.AsString := FOriginalTaskTime;
...@@ -1151,6 +1293,7 @@ begin ...@@ -1151,6 +1293,7 @@ begin
xdwdsTimeEntriescategory.AsString := FOriginalCategory; xdwdsTimeEntriescategory.AsString := FOriginalCategory;
xdwdsTimeEntriescategoryDesc.AsString := FOriginalCategoryDesc; xdwdsTimeEntriescategoryDesc.AsString := FOriginalCategoryDesc;
xdwdsTimeEntriessummary.AsString := FOriginalSummary; xdwdsTimeEntriessummary.AsString := FOriginalSummary;
xdwdsTimeEntriesdetails.AsString := FOriginalDetails;
xdwdsTimeEntries.Post; xdwdsTimeEntries.Post;
ClearEntryDraft; ClearEntryDraft;
...@@ -1161,6 +1304,137 @@ begin ...@@ -1161,6 +1304,137 @@ begin
ClearRowValidation(idx); ClearRowValidation(idx);
end; 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; procedure TFTimeEntries.BindTableEditors;
var var
nodes: TJSNodeList; nodes: TJSNodeList;
...@@ -1193,6 +1467,13 @@ begin ...@@ -1193,6 +1467,13 @@ begin
el.addEventListener('click', TJSEventHandler(@EntryDraftSaveClick)); el.addEventListener('click', TJSEventHandler(@EntryDraftSaveClick));
end; 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'); nodes := document.querySelectorAll('.time-dd-item');
console.log('BindTableEditors: time-dd-item count=' + IntToStr(nodes.length)); console.log('BindTableEditors: time-dd-item count=' + IntToStr(nodes.length));
for i := 0 to nodes.length - 1 do for i := 0 to nodes.length - 1 do
...@@ -1280,9 +1561,6 @@ begin ...@@ -1280,9 +1561,6 @@ begin
xdwdsTimeEntries.Post; xdwdsTimeEntries.Post;
if SameText(fieldName, 'taskDate') then
RefreshTaskOptionStates(idx, newVal);
if IsDraftEntryRow then if IsDraftEntryRow then
ShowEntryDraftActions(idx); ShowEntryDraftActions(idx);
...@@ -1565,10 +1843,11 @@ begin ...@@ -1565,10 +1843,11 @@ begin
hasDate := Trim(xdwdsTimeEntriestaskDate.AsString) <> ''; hasDate := Trim(xdwdsTimeEntriestaskDate.AsString) <> '';
hasTask := Trim(xdwdsTimeEntriestaskId.AsString) <> ''; hasTask := Trim(xdwdsTimeEntriestaskId.AsString) <> '';
// Hours is required: zero is allowed; blank or negative is not
if xdwdsTimeEntrieshours.IsNull then if xdwdsTimeEntrieshours.IsNull then
hasHours := False hasHours := False
else else
hasHours := xdwdsTimeEntrieshours.AsFloat > 0; hasHours := xdwdsTimeEntrieshours.AsFloat >= 0;
hasCategory := Trim(xdwdsTimeEntriescategory.AsString) <> ''; hasCategory := Trim(xdwdsTimeEntriescategory.AsString) <> '';
hasSummary := Trim(xdwdsTimeEntriessummary.AsString) <> ''; hasSummary := Trim(xdwdsTimeEntriessummary.AsString) <> '';
...@@ -1576,6 +1855,45 @@ begin ...@@ -1576,6 +1855,45 @@ begin
end; 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; procedure TFTimeEntries.ApplyPendingEntryFocus;
var var
rowEl: TJSHTMLElement; rowEl: TJSHTMLElement;
...@@ -1632,6 +1950,10 @@ var ...@@ -1632,6 +1950,10 @@ var
begin begin
fieldEl := TJSHTMLElement(rowEl.querySelector('[data-field="' + AFieldName + '"]')); 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 if AInvalid then
fieldEl.classList.add('is-invalid') fieldEl.classList.add('is-invalid')
else else
...@@ -1648,10 +1970,11 @@ begin ...@@ -1648,10 +1970,11 @@ begin
rowEl := TJSHTMLElement(document.querySelector('tr[data-idx="' + IntToStr(AIndex) + '"]')); rowEl := TJSHTMLElement(document.querySelector('tr[data-idx="' + IntToStr(AIndex) + '"]'));
// Hours is required: blank or negative is flagged; zero is fine
if xdwdsTimeEntrieshours.IsNull then if xdwdsTimeEntrieshours.IsNull then
hoursInvalid := True hoursInvalid := True
else else
hoursInvalid := xdwdsTimeEntrieshours.AsFloat <= 0; hoursInvalid := xdwdsTimeEntrieshours.AsFloat < 0;
SetInvalid('taskDate', Trim(xdwdsTimeEntriestaskDate.AsString) = ''); SetInvalid('taskDate', Trim(xdwdsTimeEntriestaskDate.AsString) = '');
SetInvalid('taskId', Trim(xdwdsTimeEntriestaskId.AsString) = ''); SetInvalid('taskId', Trim(xdwdsTimeEntriestaskId.AsString) = '');
...@@ -1669,12 +1992,66 @@ begin ...@@ -1669,12 +1992,66 @@ begin
if(!host) return; if(!host) return;
host.querySelectorAll('.time-textarea').forEach(function(editor){ 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() { const fit = function() {
editor.style.height = 'auto'; editor.style.height = 'auto';
editor.style.height = editor.scrollHeight + 'px'; editor.style.height = editor.scrollHeight + 'px';
}; };
fit(); fit();
editor.addEventListener('input', 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; end;
...@@ -1928,6 +2305,7 @@ begin ...@@ -1928,6 +2305,7 @@ begin
xdwdsTimeEntriescategory.AsString := ''; xdwdsTimeEntriescategory.AsString := '';
xdwdsTimeEntriescategoryDesc.AsString := ''; xdwdsTimeEntriescategoryDesc.AsString := '';
xdwdsTimeEntriessummary.AsString := ''; xdwdsTimeEntriessummary.AsString := '';
xdwdsTimeEntriesdetails.AsString := '';
xdwdsTimeEntries.Post; xdwdsTimeEntries.Post;
FAddingNewEntry := True; FAddingNewEntry := True;
...@@ -1956,9 +2334,7 @@ var ...@@ -1956,9 +2334,7 @@ var
taskTime: string; taskTime: string;
place: string; place: string;
placeDesc: string; placeDesc: string;
category: string; details: string;
categoryDesc: string;
summary: string;
begin begin
Result := False; Result := False;
...@@ -2005,9 +2381,7 @@ begin ...@@ -2005,9 +2381,7 @@ begin
taskTime := xdwdsTimeEntriestaskTime.AsString; taskTime := xdwdsTimeEntriestaskTime.AsString;
place := xdwdsTimeEntriesplace.AsString; place := xdwdsTimeEntriesplace.AsString;
placeDesc := xdwdsTimeEntriesplaceDesc.AsString; placeDesc := xdwdsTimeEntriesplaceDesc.AsString;
category := xdwdsTimeEntriescategory.AsString; details := xdwdsTimeEntriesdetails.AsString;
categoryDesc := xdwdsTimeEntriescategoryDesc.AsString;
summary := xdwdsTimeEntriessummary.AsString;
xdwdsTimeEntries.Append; xdwdsTimeEntries.Append;
xdwdsTimeEntriesentryId.AsInteger := 0; xdwdsTimeEntriesentryId.AsInteger := 0;
...@@ -2023,9 +2397,11 @@ begin ...@@ -2023,9 +2397,11 @@ begin
xdwdsTimeEntriestaskTime.AsString := taskTime; xdwdsTimeEntriestaskTime.AsString := taskTime;
xdwdsTimeEntriesplace.AsString := place; xdwdsTimeEntriesplace.AsString := place;
xdwdsTimeEntriesplaceDesc.AsString := placeDesc; xdwdsTimeEntriesplaceDesc.AsString := placeDesc;
xdwdsTimeEntriescategory.AsString := category; // Category and Summary are rarely the same for the copy, so the user fills them in
xdwdsTimeEntriescategoryDesc.AsString := categoryDesc; xdwdsTimeEntriescategory.AsString := '';
xdwdsTimeEntriessummary.AsString := summary; xdwdsTimeEntriescategoryDesc.AsString := '';
xdwdsTimeEntriessummary.AsString := '';
xdwdsTimeEntriesdetails.AsString := details;
xdwdsTimeEntries.Post; xdwdsTimeEntries.Post;
FAddingNewEntry := True; FAddingNewEntry := True;
...@@ -2175,6 +2551,7 @@ var ...@@ -2175,6 +2551,7 @@ var
idx: Integer; idx: Integer;
taskId: string; taskId: string;
taskDate: string; taskDate: string;
picker: TFTaskPicker;
begin begin
Event.preventDefault; Event.preventDefault;
Event.stopPropagation; Event.stopPropagation;
...@@ -2231,9 +2608,6 @@ begin ...@@ -2231,9 +2608,6 @@ begin
btnDeleteEntry.Enabled := not IsNewEntryRow(idx); btnDeleteEntry.Enabled := not IsNewEntryRow(idx);
btnCopyEntry.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 // Pass the row's current task and (draft) date so the picker opens on them
taskId := ''; taskId := '';
taskDate := ''; taskDate := '';
...@@ -2244,7 +2618,18 @@ begin ...@@ -2244,7 +2618,18 @@ begin
taskDate := xdwdsTimeEntriestaskDate.AsString; taskDate := xdwdsTimeEntriestaskDate.AsString;
end; 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; end;
...@@ -2297,6 +2682,8 @@ begin ...@@ -2297,6 +2682,8 @@ begin
Exit; Exit;
end; end;
// The mode isn't tied to the category: Task Items opens in the mode last picked
// with its Testing Mode checkbox
taskId := ''; taskId := '';
GotoRowIndex(idx); GotoRowIndex(idx);
if not xdwdsTimeEntries.Eof then if not xdwdsTimeEntries.Eof then
......
...@@ -42,6 +42,88 @@ ...@@ -42,6 +42,88 @@
min-width: 0; 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 { .time-table .dropdown-menu {
z-index: 1055; z-index: 1055;
} }
......
...@@ -18,7 +18,7 @@ uses ...@@ -18,7 +18,7 @@ uses
View.Login in 'View.Login.pas' {FViewLogin: TWebForm} {*.html}, View.Login in 'View.Login.pas' {FViewLogin: TWebForm} {*.html},
View.ErrorPage in 'View.ErrorPage.pas' {FViewErrorPage: TWebForm} {*.html}, View.ErrorPage in 'View.ErrorPage.pas' {FViewErrorPage: TWebForm} {*.html},
View.TimeEntries in 'View.TimeEntries.pas' {FTimeEntries: 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} {$R *.res}
......
...@@ -156,7 +156,10 @@ ...@@ -156,7 +156,10 @@
<Form>FTimeEntries</Form> <Form>FTimeEntries</Form>
<DesignClass>TWebForm</DesignClass> <DesignClass>TWebForm</DesignClass>
</DCCReference> </DCCReference>
<DCCReference Include="uTaskPickerOffCanvas.pas"/> <DCCReference Include="View.TaskPicker.pas">
<Form>FTaskPicker</Form>
<DesignClass>TWebForm</DesignClass>
</DCCReference>
<None Include="index.html"/> <None Include="index.html"/>
<None Include="css\app.css"/> <None Include="css\app.css"/>
<None Include="config\config.json"/> <None Include="config\config.json"/>
......
...@@ -11,12 +11,11 @@ procedure ClearTaskStatusClasses(const AElement: TJSHTMLElement); ...@@ -11,12 +11,11 @@ procedure ClearTaskStatusClasses(const AElement: TJSHTMLElement);
procedure ApplyTaskStatusClass(const AElement: TJSHTMLElement; const AStatus: string); procedure ApplyTaskStatusClass(const AElement: TJSHTMLElement; const AStatus: string);
function ExtractOptionNames(const SourceArray: TJSArray): TJSArray; 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 ExtractReportedOptionNames(const ResponseResult: TJSObject): TJSArray;
function ExtractApplicationOptionNames(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 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); procedure FocusTrigger(const ATriggerId: string);
...@@ -30,23 +29,24 @@ var ...@@ -30,23 +29,24 @@ var
begin begin
statusText := Trim(AStatus); 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' Result := 'status-cannot-duplicate'
else if SameText(statusText, 'Cannot Test') then else if SameText(statusText, 'CT') then
Result := 'status-cannot-test' Result := 'status-cannot-test'
else if SameText(statusText, 'Future Enhancement') then else if SameText(statusText, 'FE') then
Result := 'status-future-enhancement' Result := 'status-future-enhancement'
else if SameText(statusText, 'Fixed - Verified') then else if SameText(statusText, 'FV') then
Result := 'status-fixed-verified' Result := 'status-fixed-verified'
else if SameText(statusText, 'Fixed') then else if SameText(statusText, 'FX') then
Result := 'status-fixed' Result := 'status-fixed'
else if SameText(statusText, 'Investigating') then else if SameText(statusText, 'IN') then
Result := 'status-investigating' Result := 'status-investigating'
else if SameText(statusText, 'Not Fixed') then else if SameText(statusText, 'NF') then
Result := 'status-not-fixed' Result := 'status-not-fixed'
else if SameText(statusText, 'Non-Issue') then else if SameText(statusText, 'NI') then
Result := 'status-non-issue' Result := 'status-non-issue'
else if SameText(statusText, 'Possibly a Problem') then else if SameText(statusText, 'PP') then
Result := 'status-possibly-a-problem' Result := 'status-possibly-a-problem'
else else
Result := 'status-default'; Result := 'status-default';
...@@ -96,46 +96,28 @@ begin ...@@ -96,46 +96,28 @@ begin
end; end;
end; end;
function ExtractCodeDescs(const SourceArray: TJSArray): TJSArray; function ExtractReportedOptionNames(const ResponseResult: TJSObject): 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;
begin begin
if not Assigned(ResponseResult) then if not Assigned(ResponseResult) then
Exit(TJSArray.new); Exit(TJSArray.new);
Result := ExtractOptionNames(TJSArray(ResponseResult['assignedToOptions'])); Result := ExtractOptionNames(TJSArray(ResponseResult['reportedByOptions']));
end; end;
function ExtractReportedOptionNames(const ResponseResult: TJSObject): TJSArray; function ExtractApplicationOptionNames(const ResponseResult: TJSObject): TJSArray;
begin begin
if not Assigned(ResponseResult) then if not Assigned(ResponseResult) then
Exit(TJSArray.new); Exit(TJSArray.new);
Result := ExtractOptionNames(TJSArray(ResponseResult['reportedByOptions'])); Result := ExtractOptionNames(TJSArray(ResponseResult['applicationOptions']));
end; end;
function ExtractApplicationOptionNames(const ResponseResult: TJSObject): TJSArray; function ExtractVersionOptionNames(const ResponseResult: TJSObject): TJSArray;
begin begin
if not Assigned(ResponseResult) then if not Assigned(ResponseResult) then
Exit(TJSArray.new); Exit(TJSArray.new);
Result := ExtractOptionNames(TJSArray(ResponseResult['applicationOptions'])); Result := ExtractOptionNames(TJSArray(ResponseResult['versionOptions']));
end; end;
function FindOptionIgnoreCase(const AItems: TJSArray; const AName: string): string; function FindOptionIgnoreCase(const AItems: TJSArray; const AName: string): string;
...@@ -156,14 +138,14 @@ begin ...@@ -156,14 +138,14 @@ begin
end; end;
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 begin
if SameText(AFieldName, 'application') then if SameText(AFieldName, 'application') then
Result := AApplicationOptions Result := AApplicationOptions
else if SameText(AFieldName, 'version') then
Result := AVersionOptions
else if SameText(AFieldName, 'reportedBy') then else if SameText(AFieldName, 'reportedBy') then
Result := AReportedByOptions Result := AReportedByOptions
else if SameText(AFieldName, 'assignedTo') then
Result := AAssignedToOptions
else else
Result := nil; Result := nil;
end; end;
......
...@@ -257,7 +257,7 @@ begin ...@@ -257,7 +257,7 @@ begin
Exit; Exit;
end; 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; Exit;
if FCurrentEditName <> '' then if FCurrentEditName <> '' then
...@@ -356,7 +356,7 @@ begin ...@@ -356,7 +356,7 @@ begin
Event.preventDefault; Event.preventDefault;
Event.stopPropagation; 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; Exit;
el := TJSHTMLElement(Event.currentTarget); el := TJSHTMLElement(Event.currentTarget);
...@@ -383,7 +383,7 @@ begin ...@@ -383,7 +383,7 @@ begin
Event.preventDefault; Event.preventDefault;
Event.stopPropagation; 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; Exit;
el := TJSHTMLElement(Event.currentTarget); el := TJSHTMLElement(Event.currentTarget);
...@@ -401,7 +401,7 @@ procedure TNameManager.OpenManager(const AFieldName: string; const ARowIndex: In ...@@ -401,7 +401,7 @@ procedure TNameManager.OpenManager(const AFieldName: string; const ARowIndex: In
var var
titleEl: TJSHTMLElement; titleEl: TJSHTMLElement;
begin 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; Exit;
FCurrentField := AFieldName; FCurrentField := AFieldName;
...@@ -414,10 +414,10 @@ begin ...@@ -414,10 +414,10 @@ begin
begin begin
if SameText(AFieldName, 'application') then if SameText(AFieldName, 'application') then
titleEl.innerHTML := 'Manage Application' titleEl.innerHTML := 'Manage Application'
else if SameText(AFieldName, 'reportedBy') then else if SameText(AFieldName, 'version') then
titleEl.innerHTML := 'Manage Reported By' titleEl.innerHTML := 'Manage Version'
else else
titleEl.innerHTML := 'Manage Assigned To'; titleEl.innerHTML := 'Manage Reported By';
end; end;
ResetInputArea; ResetInputArea;
......
...@@ -127,23 +127,39 @@ object ApiDatabase: TApiDatabase ...@@ -127,23 +127,39 @@ object ApiDatabase: TApiDatabase
Connection = ucETaskApi Connection = ucETaskApi
SQL.Strings = ( SQL.Strings = (
'select' 'select'
' TASK_ITEM_ID,' ' ti.TASK_ITEM_ID,'
' TASK_ID,' ' ti.TASK_ID,'
' ITEM_NUM,' ' ti.ITEM_NUM,'
' APPLICATION,' ' ti.APPLICATION,'
' APP_VERSION,' ' ti.APP_VERSION,'
' TASK_DATE,' ' ti.TASK_DATE,'
' STATUS_DATE,' ' ti.STATUS_DATE,'
' REPORTED_BY,' ' ti.REPORTED_BY,'
' ASSIGNED_TO,' ' ti.ASSIGNED_TO,'
' STATUS,' ' au.USER_ID as ASSIGNED_USER_ID,'
' FIXED_VERSION,' ' au.FIRST_NAME as ASSIGNED_FIRST_NAME,'
' FORM_SECTION,' ' au.LAST_NAME as ASSIGNED_LAST_NAME,'
' ISSUE,' ' ti.STATUS,'
' NOTES' ' ts.CODE_DESC as STATUS_DESC,'
'from task_items' ' ti.ITEM_STATUS,'
'where TASK_ID = :TASK_ID' ' its.CODE_DESC as ITEM_STATUS_DESC,'
'order by ITEM_NUM') ' 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 Left = 58
Top = 26 Top = 26
ParamData = < ParamData = <
...@@ -197,6 +213,35 @@ object ApiDatabase: TApiDatabase ...@@ -197,6 +213,35 @@ object ApiDatabase: TApiDatabase
Required = True Required = True
Size = 100 Size = 100
end 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 object uqTaskItemsFIXED_VERSION: TStringField
FieldName = 'FIXED_VERSION' FieldName = 'FIXED_VERSION'
Required = True Required = True
...@@ -231,6 +276,7 @@ object ApiDatabase: TApiDatabase ...@@ -231,6 +276,7 @@ object ApiDatabase: TApiDatabase
' REPORTED_BY,' ' REPORTED_BY,'
' ASSIGNED_TO,' ' ASSIGNED_TO,'
' STATUS,' ' STATUS,'
' ITEM_STATUS,'
' FIXED_VERSION,' ' FIXED_VERSION,'
' FORM_SECTION,' ' FORM_SECTION,'
' ISSUE,' ' ISSUE,'
...@@ -246,6 +292,7 @@ object ApiDatabase: TApiDatabase ...@@ -246,6 +292,7 @@ object ApiDatabase: TApiDatabase
' null,' ' null,'
' null,' ' null,'
' null,' ' null,'
' '#39'OPEN'#39','
' null,' ' null,'
' null,' ' null,'
' null,' ' null,'
...@@ -278,10 +325,9 @@ object ApiDatabase: TApiDatabase ...@@ -278,10 +325,9 @@ object ApiDatabase: TApiDatabase
' REPORTED_BY,' ' REPORTED_BY,'
' ASSIGNED_TO,' ' ASSIGNED_TO,'
' STATUS,' ' STATUS,'
' ITEM_STATUS,'
' FIXED_VERSION,' ' FIXED_VERSION,'
' FORM_SECTION,' ' FORM_SECTION'
' ISSUE,'
' NOTES'
')' ')'
'select' 'select'
' TASK_ID,' ' TASK_ID,'
...@@ -293,10 +339,9 @@ object ApiDatabase: TApiDatabase ...@@ -293,10 +339,9 @@ object ApiDatabase: TApiDatabase
' REPORTED_BY,' ' REPORTED_BY,'
' ASSIGNED_TO,' ' ASSIGNED_TO,'
' STATUS,' ' STATUS,'
' ITEM_STATUS,'
' FIXED_VERSION,' ' FIXED_VERSION,'
' FORM_SECTION,' ' FORM_SECTION'
' ISSUE,'
' NOTES'
'from task_items' 'from task_items'
'where TASK_ID = :TASK_ID' 'where TASK_ID = :TASK_ID'
' and TASK_ITEM_ID = :TASK_ITEM_ID') ' and TASK_ITEM_ID = :TASK_ITEM_ID')
...@@ -394,23 +439,53 @@ object ApiDatabase: TApiDatabase ...@@ -394,23 +439,53 @@ object ApiDatabase: TApiDatabase
' CODE,' ' CODE,'
' CODE_DESC,' ' CODE_DESC,'
' CODE_TYPE' ' CODE_TYPE'
'FROM etask.task_item_codes' 'FROM codes'
'WHERE CODE_TYPE = '#39'STATUS'#39 'WHERE CATEGORY = '#39'TASK'#39
'ORDER BY CODE') ' AND CODE_TYPE = '#39'STATUS2'#39
'ORDER BY CODE_DESC')
Left = 60 Left = 60
Top = 140 Top = 140
object uqTaskItemCodesCODE: TStringField object uqTaskItemCodesCODE: TStringField
FieldName = 'CODE' FieldName = 'CODE'
Required = True Required = True
Size = 50 Size = 7
end end
object uqTaskItemCodesCODE_DESC: TStringField object uqTaskItemCodesCODE_DESC: TStringField
FieldName = 'CODE_DESC' FieldName = 'CODE_DESC'
Size = 255 Size = 60
end end
object uqTaskItemCodesCODE_TYPE: TStringField object uqTaskItemCodesCODE_TYPE: TStringField
FieldName = 'CODE_TYPE' 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
end end
object uqGetTaskRowPosition: TUniQuery object uqGetTaskRowPosition: TUniQuery
...@@ -672,15 +747,18 @@ object ApiDatabase: TApiDatabase ...@@ -672,15 +747,18 @@ object ApiDatabase: TApiDatabase
object uqTaskAssignedUsers: TUniQuery object uqTaskAssignedUsers: TUniQuery
Connection = ucETaskApi Connection = ucETaskApi
SQL.Strings = ( SQL.Strings = (
'select distinct' 'select'
' TASK_ITEM_USER_ID,' ' u.USER_ID,'
' TASK_ID,' ' u.FIRST_NAME,'
' USER_TYPE,' ' u.LAST_NAME'
' NAME' 'from users u'
'from task_item_user' 'join tasks t'
'where TASK_ID = :TASK_ID' ' on t.TASK_ID = :TASK_ID'
' and USER_TYPE = '#39'Assigned'#39 'where (u.START_DATE is null or t.COMPLETION_DATE is null'
'order by NAME') ' 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 Left = 60
Top = 200 Top = 200
ParamData = < ParamData = <
...@@ -689,119 +767,89 @@ object ApiDatabase: TApiDatabase ...@@ -689,119 +767,89 @@ object ApiDatabase: TApiDatabase
Name = 'TASK_ID' Name = 'TASK_ID'
Value = nil Value = nil
end> end>
object uqTaskAssignedUsersTASK_ITEM_USER_ID: TStringField object uqTaskAssignedUsersUSER_ID: TStringField
FieldName = 'TASK_ITEM_USER_ID' FieldName = 'USER_ID'
Required = True
Size = 50
end
object uqTaskAssignedUsersTASK_ID: TStringField
FieldName = 'TASK_ID'
Required = True Required = True
Size = 7 Size = 7
end end
object uqTaskAssignedUsersUSER_TYPE: TStringField object uqTaskAssignedUsersFIRST_NAME: TStringField
FieldName = 'USER_TYPE' FieldName = 'FIRST_NAME'
Required = True Size = 25
Size = 8
end end
object uqTaskAssignedUsersNAME: TStringField object uqTaskAssignedUsersLAST_NAME: TStringField
FieldName = 'NAME' FieldName = 'LAST_NAME'
Required = True Size = 35
Size = 50
end end
end end
object uqAssignedInsert: TUniQuery object uqCheckAssignedUser: TUniQuery
Connection = ucETaskApi Connection = ucETaskApi
SQL.Strings = ( SQL.Strings = (
'insert into task_item_user (' 'select count(*) as USER_COUNT'
' TASK_ITEM_USER_ID,' 'from task_items ti'
' TASK_ID,' 'join tasks t'
' USER_TYPE,' ' on t.TASK_ID = ti.TASK_ID'
' NAME' 'join users u'
')' ' on u.USER_ID = :USER_ID'
'values (' 'where ti.TASK_ITEM_ID = :TASK_ITEM_ID'
' :TASK_ITEM_USER_ID,' ' and (u.START_DATE is null or t.COMPLETION_DATE is null'
' :TASK_ID,' ' or u.START_DATE <= date(t.COMPLETION_DATE))'
' '#39'Assigned'#39',' ' and (u.END_DATE is null or t.START_DATE is null'
' :NAME' ' or u.END_DATE >= date(t.START_DATE))')
')')
Left = 382 Left = 382
Top = 24 Top = 24
ParamData = < ParamData = <
item item
DataType = ftUnknown DataType = ftUnknown
Name = 'TASK_ITEM_USER_ID' Name = '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'
Value = nil Value = nil
end end
item item
DataType = ftUnknown DataType = ftUnknown
Name = 'TASK_ID' Name = 'TASK_ITEM_ID'
Value = nil Value = nil
end> end>
end end
object uqAssignedDelete: TUniQuery object uqProjectVersions: TUniQuery
Connection = ucETaskApi Connection = ucETaskApi
SQL.Strings = ( SQL.Strings = (
'delete from task_item_user' 'select distinct'
'where TASK_ITEM_USER_ID = :TASK_ITEM_USER_ID' ' trim(ti.APP_VERSION) as NAME'
' and TASK_ID = :TASK_ID' 'from task_items ti'
' and USER_TYPE = '#39'Assigned'#39) 'join tasks t'
Left = 384 ' on t.TASK_ID = ti.TASK_ID'
Top = 140 '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 = < ParamData = <
item item
DataType = ftUnknown DataType = ftUnknown
Name = 'TASK_ITEM_USER_ID'
Value = nil
end
item
DataType = ftUnknown
Name = 'TASK_ID' Name = 'TASK_ID'
Value = nil Value = nil
end> end>
object uqProjectVersionsNAME: TStringField
FieldName = 'NAME'
ReadOnly = True
Size = 50
end
end end
object uqRenameAssignedTo: TUniQuery object uqRenameTaskItemVersion: TUniQuery
Connection = ucETaskApi Connection = ucETaskApi
SQL.Strings = ( SQL.Strings = (
'update task_items' 'update task_items ti'
'set ASSIGNED_TO = :NEW_NAME' 'join tasks t'
'where TASK_ID = :TASK_ID' ' on t.TASK_ID = ti.TASK_ID'
' and lower(ASSIGNED_TO) = lower(:OLD_NAME)') 'join tasks target_task'
Left = 386 ' on target_task.PROJECT_ID = t.PROJECT_ID'
Top = 196 '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 = < ParamData = <
item item
DataType = ftUnknown DataType = ftUnknown
...@@ -819,15 +867,19 @@ object ApiDatabase: TApiDatabase ...@@ -819,15 +867,19 @@ object ApiDatabase: TApiDatabase
Value = nil Value = nil
end> end>
end end
object uqBlankAssignedTo: TUniQuery object uqBlankTaskItemVersion: TUniQuery
Connection = ucETaskApi Connection = ucETaskApi
SQL.Strings = ( SQL.Strings = (
'update task_items' 'update task_items ti'
'set ASSIGNED_TO = null' 'join tasks t'
'where TASK_ID = :TASK_ID' ' on t.TASK_ID = ti.TASK_ID'
' and lower(ASSIGNED_TO) = lower(:NAME)') 'join tasks target_task'
Left = 388 ' on target_task.PROJECT_ID = t.PROJECT_ID'
Top = 254 '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 = < ParamData = <
item item
DataType = ftUnknown DataType = ftUnknown
...@@ -1216,6 +1268,7 @@ object ApiDatabase: TApiDatabase ...@@ -1216,6 +1268,7 @@ object ApiDatabase: TApiDatabase
' PLACE = :PLACE,' ' PLACE = :PLACE,'
' CATEGORY = :CATEGORY,' ' CATEGORY = :CATEGORY,'
' SUMMARY = :SUMMARY,' ' SUMMARY = :SUMMARY,'
' DETAILS = :DETAILS,'
' MODIFY_DATE = now(),' ' MODIFY_DATE = now(),'
' MODIFIED_BY = :MODIFIED_BY' ' MODIFIED_BY = :MODIFIED_BY'
'WHERE ENTRY_ID = :ENTRY_ID' 'WHERE ENTRY_ID = :ENTRY_ID'
...@@ -1260,6 +1313,11 @@ object ApiDatabase: TApiDatabase ...@@ -1260,6 +1313,11 @@ object ApiDatabase: TApiDatabase
end end
item item
DataType = ftUnknown DataType = ftUnknown
Name = 'DETAILS'
Value = nil
end
item
DataType = ftUnknown
Name = 'MODIFIED_BY' Name = 'MODIFIED_BY'
Value = nil Value = nil
end end
...@@ -1312,6 +1370,12 @@ object ApiDatabase: TApiDatabase ...@@ -1312,6 +1370,12 @@ object ApiDatabase: TApiDatabase
'and (:PROJECT_DATE = '#39#39' or (' 'and (:PROJECT_DATE = '#39#39' or ('
' (p.START_DATE is null or date(p.START_DATE) <= :PROJECT_DATE)' ' (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 (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' 'order by'
' c.SHORT_NAME,' ' c.SHORT_NAME,'
' p.NAME' ' p.NAME'
...@@ -1338,6 +1402,11 @@ object ApiDatabase: TApiDatabase ...@@ -1338,6 +1402,11 @@ object ApiDatabase: TApiDatabase
DataType = ftUnknown DataType = ftUnknown
Name = 'PROJECT_DATE' Name = 'PROJECT_DATE'
Value = nil Value = nil
end
item
DataType = ftUnknown
Name = 'TASK_FILTER'
Value = nil
end> end>
object uqTaskPickerProjectsPROJECT_ID: TStringField object uqTaskPickerProjectsPROJECT_ID: TStringField
FieldName = 'PROJECT_ID' FieldName = 'PROJECT_ID'
......
...@@ -28,7 +28,13 @@ type ...@@ -28,7 +28,13 @@ type
uqTaskItemsSTATUS_DATE: TDateField; uqTaskItemsSTATUS_DATE: TDateField;
uqTaskItemsREPORTED_BY: TStringField; uqTaskItemsREPORTED_BY: TStringField;
uqTaskItemsASSIGNED_TO: TStringField; uqTaskItemsASSIGNED_TO: TStringField;
uqTaskItemsASSIGNED_USER_ID: TStringField;
uqTaskItemsASSIGNED_FIRST_NAME: TStringField;
uqTaskItemsASSIGNED_LAST_NAME: TStringField;
uqTaskItemsSTATUS: TStringField; uqTaskItemsSTATUS: TStringField;
uqTaskItemsSTATUS_DESC: TStringField;
uqTaskItemsITEM_STATUS: TStringField;
uqTaskItemsITEM_STATUS_DESC: TStringField;
uqTaskItemsFIXED_VERSION: TStringField; uqTaskItemsFIXED_VERSION: TStringField;
uqTaskItemsFORM_SECTION: TStringField; uqTaskItemsFORM_SECTION: TStringField;
uqTaskItemsISSUE: TStringField; uqTaskItemsISSUE: TStringField;
...@@ -49,6 +55,10 @@ type ...@@ -49,6 +55,10 @@ type
uqTaskItemCodesCODE: TStringField; uqTaskItemCodesCODE: TStringField;
uqTaskItemCodesCODE_DESC: TStringField; uqTaskItemCodesCODE_DESC: TStringField;
uqTaskItemCodesCODE_TYPE: TStringField; uqTaskItemCodesCODE_TYPE: TStringField;
uqTaskStatusCodes: TUniQuery;
uqTaskStatusCodesCODE: TStringField;
uqTaskStatusCodesCODE_DESC: TStringField;
uqTaskStatusCodesCODE_TYPE: TStringField;
uqGetTaskRowPosition: TUniQuery; uqGetTaskRowPosition: TUniQuery;
uqMoveTaskRowTemp: TUniQuery; uqMoveTaskRowTemp: TUniQuery;
uqShiftTaskRowsDown: TUniQuery; uqShiftTaskRowsDown: TUniQuery;
...@@ -64,15 +74,14 @@ type ...@@ -64,15 +74,14 @@ type
uqShiftTaskRowsForInsert: TUniQuery; uqShiftTaskRowsForInsert: TUniQuery;
uqProjectReportedUsers: TUniQuery; uqProjectReportedUsers: TUniQuery;
uqTaskAssignedUsers: TUniQuery; uqTaskAssignedUsers: TUniQuery;
uqAssignedInsert: TUniQuery; uqTaskAssignedUsersUSER_ID: TStringField;
uqAssignedRename: TUniQuery; uqTaskAssignedUsersFIRST_NAME: TStringField;
uqAssignedDelete: TUniQuery; uqTaskAssignedUsersLAST_NAME: TStringField;
uqRenameAssignedTo: TUniQuery; uqCheckAssignedUser: TUniQuery;
uqBlankAssignedTo: TUniQuery; uqProjectVersions: TUniQuery;
uqTaskAssignedUsersTASK_ITEM_USER_ID: TStringField; uqProjectVersionsNAME: TStringField;
uqTaskAssignedUsersTASK_ID: TStringField; uqRenameTaskItemVersion: TUniQuery;
uqTaskAssignedUsersUSER_TYPE: TStringField; uqBlankTaskItemVersion: TUniQuery;
uqTaskAssignedUsersNAME: TStringField;
uqProjectApplications: TUniQuery; uqProjectApplications: TUniQuery;
uqApplicationInsert: TUniQuery; uqApplicationInsert: TUniQuery;
uqApplicationRename: TUniQuery; uqApplicationRename: TUniQuery;
......
...@@ -25,7 +25,11 @@ type ...@@ -25,7 +25,11 @@ type
taskDate: TDateTime; taskDate: TDateTime;
reportedBy: string; reportedBy: string;
assignedTo: string; assignedTo: string;
assignedToDesc: string;
status: string; status: string;
statusDesc: string;
itemStatus: string;
itemStatusDesc: string;
statusDate: TDateTime; statusDate: TDateTime;
fixedVersion: string; fixedVersion: string;
formSection: string; formSection: string;
...@@ -48,11 +52,22 @@ type ...@@ -48,11 +52,22 @@ type
name: string; name: string;
end; end;
TTaskAssignedUserOption = class
public
userId: string;
name: string;
end;
TTaskApplicationOption = class TTaskApplicationOption = class
public public
name: string; name: string;
end; end;
TTaskVersionOption = class
public
name: string;
end;
TTaskItemCode = class TTaskItemCode = class
public public
code: string; code: string;
...@@ -66,16 +81,17 @@ type ...@@ -66,16 +81,17 @@ type
task: TTaskHeader; task: TTaskHeader;
items: TList<TTaskItem>; items: TList<TTaskItem>;
applicationOptions: TList<TTaskApplicationOption>; applicationOptions: TList<TTaskApplicationOption>;
versionOptions: TList<TTaskVersionOption>;
reportedByOptions: TList<TTaskUserOption>; reportedByOptions: TList<TTaskUserOption>;
assignedToOptions: TList<TTaskUserOption>; assignedToOptions: TList<TTaskAssignedUserOption>;
statusOptions: TList<TTaskItemCode>; statusOptions: TList<TTaskItemCode>;
itemStatusOptions: TList<TTaskItemCode>;
constructor Create; constructor Create;
destructor Destroy; override; destructor Destroy; override;
end; end;
TTaskUserOptionsResponse = class TTaskUserOptionsResponse = class
public public
assignedToOptions: TList<TTaskUserOption>;
reportedByOptions: TList<TTaskUserOption>; reportedByOptions: TList<TTaskUserOption>;
constructor Create; constructor Create;
destructor Destroy; override; destructor Destroy; override;
...@@ -88,6 +104,13 @@ type ...@@ -88,6 +104,13 @@ type
destructor Destroy; override; destructor Destroy; override;
end; end;
TTaskVersionOptionsResponse = class
public
versionOptions: TList<TTaskVersionOption>;
constructor Create;
destructor Destroy; override;
end;
TTaskRowSave = class TTaskRowSave = class
public public
taskItemId: integer; taskItemId: integer;
...@@ -122,11 +145,6 @@ type ...@@ -122,11 +145,6 @@ type
[HttpPost] function AddTaskRow(taskId: string; insertAfterItemNum: Integer): Boolean; [HttpPost] function AddTaskRow(taskId: string; insertAfterItemNum: Integer): Boolean;
[HttpPost] function CopyTaskRow(taskId: string; sourceTaskItemId: Integer): Integer; [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 AddReportedName(taskId: string; name: string): TTaskUserOptionsResponse;
[HttpPost]function RenameReportedName(taskId: string; oldName: string; newName: string): TTaskUserOptionsResponse; [HttpPost]function RenameReportedName(taskId: string; oldName: string; newName: string): TTaskUserOptionsResponse;
[HttpPost]function DeleteReportedName(taskId: string; name: string): TTaskUserOptionsResponse; [HttpPost]function DeleteReportedName(taskId: string; name: string): TTaskUserOptionsResponse;
...@@ -135,6 +153,11 @@ type ...@@ -135,6 +153,11 @@ type
[HttpPost] function RenameApplicationName(taskId: string; oldName: string; newName: string): TTaskApplicationOptionsResponse; [HttpPost] function RenameApplicationName(taskId: string; oldName: string; newName: string): TTaskApplicationOptionsResponse;
[HttpPost] function DeleteApplicationName(taskId: string; name: 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] procedure MoveTaskRow(const taskId: Integer; const taskItemId: Integer; const newItemNum: Integer);
[HttpPost] function DeleteTaskRow(const taskId: Integer; const taskItemId: Integer): Boolean; [HttpPost] function DeleteTaskRow(const taskId: Integer; const taskItemId: Integer): Boolean;
[HttpPost] function SaveTaskItemField(const Item: TTaskItemFieldSave): Boolean; [HttpPost] function SaveTaskItemField(const Item: TTaskItemFieldSave): Boolean;
...@@ -148,32 +171,34 @@ begin ...@@ -148,32 +171,34 @@ begin
inherited; inherited;
items := TList<TTaskItem>.Create; items := TList<TTaskItem>.Create;
applicationOptions := TList<TTaskApplicationOption>.Create; applicationOptions := TList<TTaskApplicationOption>.Create;
versionOptions := TList<TTaskVersionOption>.Create;
reportedByOptions := TList<TTaskUserOption>.Create; reportedByOptions := TList<TTaskUserOption>.Create;
assignedToOptions := TList<TTaskUserOption>.Create; assignedToOptions := TList<TTaskAssignedUserOption>.Create;
statusOptions := TList<TTaskItemCode>.Create; statusOptions := TList<TTaskItemCode>.Create;
itemStatusOptions := TList<TTaskItemCode>.Create;
end; end;
destructor TTaskItemsResponse.Destroy; destructor TTaskItemsResponse.Destroy;
begin begin
items.Free; items.Free;
applicationOptions.Free; applicationOptions.Free;
versionOptions.Free;
reportedByOptions.Free; reportedByOptions.Free;
assignedToOptions.Free; assignedToOptions.Free;
statusOptions.Free; statusOptions.Free;
itemStatusOptions.Free;
inherited; inherited;
end; end;
constructor TTaskUserOptionsResponse.Create; constructor TTaskUserOptionsResponse.Create;
begin begin
inherited; inherited;
assignedToOptions := TList<TTaskUserOption>.Create;
reportedByOptions := TList<TTaskUserOption>.Create; reportedByOptions := TList<TTaskUserOption>.Create;
end; end;
destructor TTaskUserOptionsResponse.Destroy; destructor TTaskUserOptionsResponse.Destroy;
begin begin
assignedToOptions := TList<TTaskUserOption>.Create; reportedByOptions.Free;
reportedByOptions := TList<TTaskUserOption>.Create;
inherited; inherited;
end; end;
...@@ -189,6 +214,18 @@ begin ...@@ -189,6 +214,18 @@ begin
inherited; inherited;
end; end;
constructor TTaskVersionOptionsResponse.Create;
begin
inherited;
versionOptions := TList<TTaskVersionOption>.Create;
end;
destructor TTaskVersionOptionsResponse.Destroy;
begin
versionOptions.Free;
inherited;
end;
initialization initialization
RegisterServiceType(TypeInfo(ITaskItemService)); RegisterServiceType(TypeInfo(ITaskItemService));
......
...@@ -16,14 +16,9 @@ type ...@@ -16,14 +16,9 @@ type
private private
function BuildTaskNumber: string; function BuildTaskNumber: string;
function BuildTaskTitle(const taskNumber, projectName, subject: string): string; function BuildTaskTitle(const taskNumber, projectName, subject: string): string;
function FindAssignedOptionId(const taskId, name: string): string; function BuildUserDisplayName(const firstName, lastName: string): string;
function FindAssignedOptionName(const taskId, name: string): string;
function AddTaskRow(taskId: string; insertAfterItemNum: Integer): Boolean; function AddTaskRow(taskId: string; insertAfterItemNum: Integer): Boolean;
function CopyTaskRow(taskId: string; sourceTaskItemId: Integer): Integer; 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); procedure MoveTaskRow(const taskId: Integer; const taskItemId: Integer; const newItemNum: Integer);
function DeleteTaskRow(const taskId, taskItemId: Integer): Boolean; function DeleteTaskRow(const taskId, taskItemId: Integer): Boolean;
function FindProjectId(const taskId: string): string; function FindProjectId(const taskId: string): string;
...@@ -33,6 +28,10 @@ type ...@@ -33,6 +28,10 @@ type
function AddApplicationName(taskId: string; name: string): TTaskApplicationOptionsResponse; function AddApplicationName(taskId: string; name: string): TTaskApplicationOptionsResponse;
function RenameApplicationName(taskId: string; oldName: string; newName: string): TTaskApplicationOptionsResponse; function RenameApplicationName(taskId: string; oldName: string; newName: string): TTaskApplicationOptionsResponse;
function DeleteApplicationName(taskId: string; name: 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 SaveTaskItemField(const Item: TTaskItemFieldSave): Boolean;
function FindReportedOptionId(const taskId, name: string): string; function FindReportedOptionId(const taskId, name: string): string;
function FindReportedOptionName(const taskId, name: string): string; function FindReportedOptionName(const taskId, name: string): string;
...@@ -69,8 +68,10 @@ function TTaskItemService.GetTaskItems(taskId: string): TTaskItemsResponse; ...@@ -69,8 +68,10 @@ function TTaskItemService.GetTaskItems(taskId: string): TTaskItemsResponse;
var var
taskHeader: TTaskHeader; taskHeader: TTaskHeader;
taskUserOption: TTaskUserOption; taskUserOption: TTaskUserOption;
taskAssignedUserOption: TTaskAssignedUserOption;
taskItemCode: TTaskItemCode; taskItemCode: TTaskItemCode;
taskApplicationOption: TTaskApplicationOption; taskApplicationOption: TTaskApplicationOption;
taskVersionOption: TTaskVersionOption;
item: TTaskItem; item: TTaskItem;
begin begin
Logger.Log(4, Format('TaskItemService.GetTaskItems - TASK_ID="%s"', [taskId])); Logger.Log(4, Format('TaskItemService.GetTaskItems - TASK_ID="%s"', [taskId]));
...@@ -121,6 +122,21 @@ begin ...@@ -121,6 +122,21 @@ begin
apiDB.uqProjectApplications.Next; apiDB.uqProjectApplications.Next;
end; 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.Close;
apiDB.uqProjectReportedUsers.ParamByName('TASK_ID').AsString := taskId; apiDB.uqProjectReportedUsers.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqProjectReportedUsers.Open; apiDB.uqProjectReportedUsers.Open;
...@@ -136,17 +152,22 @@ begin ...@@ -136,17 +152,22 @@ begin
apiDB.uqProjectReportedUsers.Next; apiDB.uqProjectReportedUsers.Next;
end; end;
// Users whose employment dates overlap the task's start/end dates
apiDB.uqTaskAssignedUsers.Close; apiDB.uqTaskAssignedUsers.Close;
apiDB.uqTaskAssignedUsers.ParamByName('TASK_ID').AsString := taskId; apiDB.uqTaskAssignedUsers.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqTaskAssignedUsers.Open; apiDB.uqTaskAssignedUsers.Open;
while not apiDB.uqTaskAssignedUsers.Eof do while not apiDB.uqTaskAssignedUsers.Eof do
begin begin
taskUserOption := TTaskUserOption.Create; taskAssignedUserOption := TTaskAssignedUserOption.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(taskUserOption); TXDataOperationContext.Current.Handler.ManagedObjects.Add(taskAssignedUserOption);
taskUserOption.name := apiDB.uqTaskAssignedUsersNAME.AsString; taskAssignedUserOption.userId := apiDB.uqTaskAssignedUsersUSER_ID.AsString;
Result.assignedToOptions.Add(taskUserOption); taskAssignedUserOption.name := BuildUserDisplayName(
apiDB.uqTaskAssignedUsersFIRST_NAME.AsString,
apiDB.uqTaskAssignedUsersLAST_NAME.AsString
);
Result.assignedToOptions.Add(taskAssignedUserOption);
apiDB.uqTaskAssignedUsers.Next; apiDB.uqTaskAssignedUsers.Next;
end; end;
...@@ -168,6 +189,23 @@ begin ...@@ -168,6 +189,23 @@ begin
apiDB.uqTaskItemCodes.Next; apiDB.uqTaskItemCodes.Next;
end; 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.Close;
apiDB.uqTaskItems.ParamByName('TASK_ID').AsString := taskId; apiDB.uqTaskItems.ParamByName('TASK_ID').AsString := taskId;
apiDB.uqTaskItems.Open; apiDB.uqTaskItems.Open;
...@@ -190,7 +228,24 @@ begin ...@@ -190,7 +228,24 @@ begin
item.reportedBy := apiDB.uqTaskItemsREPORTED_BY.AsString; item.reportedBy := apiDB.uqTaskItemsREPORTED_BY.AsString;
item.assignedTo := apiDB.uqTaskItemsASSIGNED_TO.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.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 if apiDB.uqTaskItemsSTATUS_DATE.IsNull then
item.statusDate := 0 item.statusDate := 0
...@@ -449,6 +504,8 @@ var ...@@ -449,6 +504,8 @@ var
Result := 'ASSIGNED_TO' Result := 'ASSIGNED_TO'
else if SameText(AFieldName, 'status') then else if SameText(AFieldName, 'status') then
Result := 'STATUS' Result := 'STATUS'
else if SameText(AFieldName, 'itemStatus') then
Result := 'ITEM_STATUS'
else if SameText(AFieldName, 'statusDate') then else if SameText(AFieldName, 'statusDate') then
Result := 'STATUS_DATE' Result := 'STATUS_DATE'
else if SameText(AFieldName, 'formSection') then else if SameText(AFieldName, 'formSection') then
...@@ -505,6 +562,18 @@ begin ...@@ -505,6 +562,18 @@ begin
if columnName = '' then if columnName = '' then
raise Exception.Create('SaveTaskItemField: Invalid field name: ' + Item.fieldName); 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); uqSaveField := TUniQuery.Create(nil);
try try
uqSaveField.Connection := apiDB.ucETaskApi; uqSaveField.Connection := apiDB.ucETaskApi;
...@@ -588,6 +657,20 @@ begin ...@@ -588,6 +657,20 @@ begin
end; 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; function TTaskItemService.DeleteTaskRow(const taskId: Integer; const taskItemId: Integer): Boolean;
var var
oldItemNum: Integer; oldItemNum: Integer;
...@@ -632,231 +715,6 @@ begin ...@@ -632,231 +715,6 @@ begin
end; 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; function TTaskItemService.FindProjectId(const taskId: string): string;
begin begin
Result := ''; Result := '';
...@@ -1106,6 +964,137 @@ begin ...@@ -1106,6 +964,137 @@ begin
end; 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; function TTaskItemService.FindReportedOptionId(const taskId, name: string): string;
begin begin
Result := ''; Result := '';
......
...@@ -25,6 +25,7 @@ type ...@@ -25,6 +25,7 @@ type
category: string; category: string;
categoryDesc: string; categoryDesc: string;
summary: string; summary: string;
details: string;
end; end;
TTimeEntryTaskOption = class TTimeEntryTaskOption = class
...@@ -46,6 +47,7 @@ type ...@@ -46,6 +47,7 @@ type
userName: string; userName: string;
userStartDate: string; // yyyy-mm-dd employment window, '' = open-ended userStartDate: string; // yyyy-mm-dd employment window, '' = open-ended
userEndDate: string; userEndDate: string;
hideTimeEntriesFields: Boolean; // users.HIDE_TIME_ENTRIES_FIELDS = 'T': Compact View (hide Time and Place)
count: Integer; count: Integer;
items: TList<TTimeEntry>; items: TList<TTimeEntry>;
taskOptions: TList<TTimeEntryTaskOption>; taskOptions: TList<TTimeEntryTaskOption>;
...@@ -61,11 +63,12 @@ type ...@@ -61,11 +63,12 @@ type
userId: string; userId: string;
taskDate: string; taskDate: string;
taskId: string; taskId: string;
hours: Double; hours: Nullable<Double>; // required, 0 allowed; nullable so a missing value is rejected, not saved as 0
taskTime: string; taskTime: string;
place: string; place: string;
category: string; category: string;
summary: string; summary: string;
details: string;
end; end;
TTaskPickerOption = class TTaskPickerOption = class
...@@ -74,8 +77,11 @@ type ...@@ -74,8 +77,11 @@ type
display: string; display: string;
customerId: string; customerId: string;
completed: Boolean; // tasks only: COMPLETION_DATE is set 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 unavailableReason: string; // tasks only: why hours can't go on the picker date, '' = allowed
status: string; // tasks only: task status code 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; end;
TTaskPickerOptionsResponse = class TTaskPickerOptionsResponse = class
...@@ -98,13 +104,17 @@ type ...@@ -98,13 +104,17 @@ type
[HttpGet] function GetTimeEntries(userId, startDate, endDate, keptEntryIds: string): TTimeEntriesResponse; [HttpGet] function GetTimeEntries(userId, startDate, endDate, keptEntryIds: string): TTimeEntriesResponse;
[HttpPost] function AddTimeEntry(userId, taskDate: string): string; [HttpPost] function AddTimeEntry(userId, taskDate: string): string;
[HttpPost] function SaveTimeEntry(Item: TTimeEntrySave): 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 DeleteTimeEntry(userId: string; entryId: Integer): Boolean;
[HttpPost] function AddTaskToFocus(userId, taskId: string): Boolean; [HttpPost] function AddTaskToFocus(userId, taskId: string): Boolean;
[HttpPost] function RemoveTaskFromFocus(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 GetTaskPickerCustomers: TTaskPickerOptionsResponse;
function GetTaskPickerStatuses: 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 GetTaskPickerTasks(projectId, userId, taskDate: string): TTaskPickerOptionsResponse;
function GetTaskPickerTaskContext(taskId: string): TTaskPickerTaskContext; function GetTaskPickerTaskContext(taskId: string): TTaskPickerTaskContext;
end; end;
......
...@@ -21,6 +21,7 @@ type ...@@ -21,6 +21,7 @@ type
function ParseIsoDate(value: string): TDateTime; function ParseIsoDate(value: string): TDateTime;
function FieldText(AQuery: TUniQuery; AFieldName: string): string; function FieldText(AQuery: TUniQuery; AFieldName: string): string;
function DateText(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); procedure CheckTimeEntryDate(userId, taskId: string; taskDate: TDateTime);
function BuildTaskNumber(AQuery: TUniQuery): string; function BuildTaskNumber(AQuery: TUniQuery): string;
function BuildTaskDisplay(AQuery: TUniQuery): string; function BuildTaskDisplay(AQuery: TUniQuery): string;
...@@ -35,15 +36,17 @@ type ...@@ -35,15 +36,17 @@ type
function GetTimeEntries(userId, startDate, endDate, keptEntryIds: string): TTimeEntriesResponse; function GetTimeEntries(userId, startDate, endDate, keptEntryIds: string): TTimeEntriesResponse;
function AddTimeEntry(userId, taskDate: string): string; function AddTimeEntry(userId, taskDate: string): string;
function SaveTimeEntry(Item: TTimeEntrySave): string; function SaveTimeEntry(Item: TTimeEntrySave): string;
function GetTimeEntryDateProblem(userId, taskId, taskDate: string): string;
function GetTaskPickerCustomers: TTaskPickerOptionsResponse; function GetTaskPickerCustomers: TTaskPickerOptionsResponse;
function GetTaskPickerStatuses: 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 GetTaskPickerTasks(projectId, userId, taskDate: string): TTaskPickerOptionsResponse;
function GetTaskPickerTaskContext(taskId: string): TTaskPickerTaskContext; function GetTaskPickerTaskContext(taskId: string): TTaskPickerTaskContext;
function DeleteTimeEntry(userId: string; entryId: Integer): Boolean; function DeleteTimeEntry(userId: string; entryId: Integer): Boolean;
function AddTaskToFocus(userId, taskId: string): Boolean; function AddTaskToFocus(userId, taskId: string): Boolean;
function RemoveTaskFromFocus(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; end;
implementation implementation
...@@ -102,12 +105,14 @@ end; ...@@ -102,12 +105,14 @@ end;
// Hours may only be entered on a date that is not in the future (server's // 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 // today) and is inside the user's employment window, the task's window and the
// window. All values are 'yyyy-mm-dd'; '' is open-ended and all ends are // task's project's window. All values are 'yyyy-mm-dd'; '' is open-ended and
// inclusive. The task's upper bound is its actual COMPLETION_DATE (DUE_DATE is // all ends are inclusive. The task's upper bound is its actual COMPLETION_DATE
// ignored). Returns '' when ADate is '' or allowed, otherwise the message to // (DUE_DATE is ignored). Returns '' when ADate is '' or allowed, otherwise the
// show. Shared by SaveTimeEntry, AddTimeEntry and the task picker. // message to show. Shared by SaveTimeEntry, AddTimeEntry,
function TimeEntryDateProblem(const ADate, AUserStart, AUserEnd, ATaskStart, ATaskEnd: string): string; // GetTimeEntryDateProblem and the task picker.
function TimeEntryDateProblem(const ADate, AUserStart, AUserEnd, ATaskStart, ATaskEnd: string;
const AProjectStart: string = ''; const AProjectEnd: string = ''): string;
begin begin
Result := ''; Result := '';
...@@ -135,16 +140,23 @@ begin ...@@ -135,16 +140,23 @@ begin
Exit(Format( Exit(Format(
'This task was completed on %s, so hours can''t be entered on %s.', 'This task was completed on %s, so hours can''t be entered on %s.',
[ATaskEnd, ADate])); [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; 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 var
q: TUniQuery; q: TUniQuery;
dateValue: string; dateValue: string;
userStart: string; userStart: string;
userEnd: string; userEnd: string;
problem: string;
begin begin
dateValue := FormatDateTime('yyyy-mm-dd', taskDate); dateValue := FormatDateTime('yyyy-mm-dd', taskDate);
...@@ -163,29 +175,45 @@ begin ...@@ -163,29 +175,45 @@ begin
userEnd := DateText(q, 'END_DATE'); userEnd := DateText(q, 'END_DATE');
// Future and employment dates are checked before the task lookup // Future and employment dates are checked before the task lookup
problem := TimeEntryDateProblem(dateValue, userStart, userEnd, '', ''); Result := TimeEntryDateProblem(dateValue, userStart, userEnd, '', '');
if problem <> '' then if Result <> '' then
raise Exception.Create(problem); Exit;
q.Close; 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.ParamByName('TASK_ID').AsString := taskId;
q.Open; q.Open;
if q.IsEmpty then if q.IsEmpty then
raise Exception.Create('Task not found.'); raise Exception.Create('Task not found.');
problem := TimeEntryDateProblem(dateValue, userStart, userEnd, Result := TimeEntryDateProblem(dateValue, userStart, userEnd,
DateText(q, 'START_DATE'), DateText(q, 'COMPLETION_DATE')); DateText(q, 'START_DATE'), DateText(q, 'COMPLETION_DATE'),
DateText(q, 'PROJECT_START_DATE'), DateText(q, 'PROJECT_END_DATE'));
if problem <> '' then
raise Exception.Create(problem);
finally finally
q.Free; q.Free;
end; end;
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; function TTimeEntryService.BuildTaskNumber(AQuery: TUniQuery): string;
procedure AddPart(AValue: string); procedure AddPart(AValue: string);
...@@ -278,7 +306,7 @@ begin ...@@ -278,7 +306,7 @@ begin
try try
userQuery.Connection := apiDB.ucETaskApi; userQuery.Connection := apiDB.ucETaskApi;
userQuery.SQL.Text := 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 ' + 'from users ' +
'where USER_ID = :USER_ID'; 'where USER_ID = :USER_ID';
...@@ -291,6 +319,7 @@ begin ...@@ -291,6 +319,7 @@ begin
AResponse.userStartDate := DateText(userQuery, 'START_DATE'); AResponse.userStartDate := DateText(userQuery, 'START_DATE');
AResponse.userEndDate := DateText(userQuery, 'END_DATE'); AResponse.userEndDate := DateText(userQuery, 'END_DATE');
AResponse.hideTimeEntriesFields := SameText(FieldText(userQuery, 'HIDE_TIME_ENTRIES_FIELDS'), 'T');
finally finally
userQuery.Free; userQuery.Free;
end; end;
...@@ -336,6 +365,7 @@ begin ...@@ -336,6 +365,7 @@ begin
' ti.CATEGORY, ' + ' ti.CATEGORY, ' +
' cat.CODE_DESC as CATEGORY_DESC, ' + ' cat.CODE_DESC as CATEGORY_DESC, ' +
' ti.SUMMARY, ' + ' ti.SUMMARY, ' +
' ti.DETAILS, ' +
' c.SHORT_NAME as CUSTOMER_NAME, ' + ' c.SHORT_NAME as CUSTOMER_NAME, ' +
' p.NAME as PROJECT_NAME, ' + ' p.NAME as PROJECT_NAME, ' +
' t.TASK_NUM_1, ' + ' t.TASK_NUM_1, ' +
...@@ -395,6 +425,7 @@ begin ...@@ -395,6 +425,7 @@ begin
item.categoryDesc := item.category; item.categoryDesc := item.category;
item.summary := FieldText(itemsQuery, 'SUMMARY'); item.summary := FieldText(itemsQuery, 'SUMMARY');
item.details := FieldText(itemsQuery, 'DETAILS');
AResponse.items.Add(item); AResponse.items.Add(item);
itemsQuery.Next; itemsQuery.Next;
...@@ -655,8 +686,12 @@ begin ...@@ -655,8 +686,12 @@ begin
if Trim(Item.taskId) = '' then if Trim(Item.taskId) = '' then
raise Exception.Create('SaveTimeEntry: Task is required.'); raise Exception.Create('SaveTimeEntry: Task is required.');
if Item.hours <= 0 then // Hours is required; zero is allowed, negative is not
raise Exception.Create('SaveTimeEntry: Hours must be greater than zero.'); 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 if Trim(Item.category) = '' then
raise Exception.Create('SaveTimeEntry: Category is required.'); raise Exception.Create('SaveTimeEntry: Category is required.');
...@@ -664,6 +699,10 @@ begin ...@@ -664,6 +699,10 @@ begin
if Trim(Item.summary) = '' then if Trim(Item.summary) = '' then
raise Exception.Create('SaveTimeEntry: Summary is required.'); 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( Logger.Log(4, Format(
'TimeEntryService.SaveTimeEntry - ENTRY_ID="%s" USER_ID="%s"', 'TimeEntryService.SaveTimeEntry - ENTRY_ID="%s" USER_ID="%s"',
[Item.entryId, Item.userId] [Item.entryId, Item.userId]
...@@ -694,6 +733,7 @@ begin ...@@ -694,6 +733,7 @@ begin
' PLACE, ' + ' PLACE, ' +
' CATEGORY, ' + ' CATEGORY, ' +
' SUMMARY, ' + ' SUMMARY, ' +
' DETAILS, ' +
' CREATE_DATE, ' + ' CREATE_DATE, ' +
' CREATED_BY, ' + ' CREATED_BY, ' +
' MODIFY_DATE, ' + ' MODIFY_DATE, ' +
...@@ -709,6 +749,7 @@ begin ...@@ -709,6 +749,7 @@ begin
' :PLACE, ' + ' :PLACE, ' +
' :CATEGORY, ' + ' :CATEGORY, ' +
' :SUMMARY, ' + ' :SUMMARY, ' +
' :DETAILS, ' +
' now(), ' + ' now(), ' +
' :CREATED_BY, ' + ' :CREATED_BY, ' +
' now(), ' + ' now(), ' +
...@@ -719,7 +760,7 @@ begin ...@@ -719,7 +760,7 @@ begin
q.ParamByName('USER_ID').AsString := Item.userId; q.ParamByName('USER_ID').AsString := Item.userId;
q.ParamByName('TASK_DATE').AsDateTime := taskDateValue; q.ParamByName('TASK_DATE').AsDateTime := taskDateValue;
q.ParamByName('TASK_ID').AsString := Item.taskId; 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 if Trim(Item.taskTime) = '' then
q.ParamByName('TASK_TIME').Clear q.ParamByName('TASK_TIME').Clear
...@@ -734,6 +775,11 @@ begin ...@@ -734,6 +775,11 @@ begin
q.ParamByName('CATEGORY').AsString := Item.category; q.ParamByName('CATEGORY').AsString := Item.category;
q.ParamByName('SUMMARY').AsString := Item.summary; 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('CREATED_BY').AsString := Item.userId;
q.ParamByName('MODIFIED_BY').AsString := Item.userId; q.ParamByName('MODIFIED_BY').AsString := Item.userId;
...@@ -751,7 +797,7 @@ begin ...@@ -751,7 +797,7 @@ begin
apiDB.uqSaveTimeEntry.ParamByName('USER_ID').AsString := Item.userId; apiDB.uqSaveTimeEntry.ParamByName('USER_ID').AsString := Item.userId;
apiDB.uqSaveTimeEntry.ParamByName('TASK_DATE').AsDateTime := taskDateValue; apiDB.uqSaveTimeEntry.ParamByName('TASK_DATE').AsDateTime := taskDateValue;
apiDB.uqSaveTimeEntry.ParamByName('TASK_ID').AsString := Item.taskId; 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 if Trim(Item.taskTime) = '' then
apiDB.uqSaveTimeEntry.ParamByName('TASK_TIME').Clear apiDB.uqSaveTimeEntry.ParamByName('TASK_TIME').Clear
...@@ -766,6 +812,11 @@ begin ...@@ -766,6 +812,11 @@ begin
apiDB.uqSaveTimeEntry.ParamByName('CATEGORY').AsString := Item.category; apiDB.uqSaveTimeEntry.ParamByName('CATEGORY').AsString := Item.category;
apiDB.uqSaveTimeEntry.ParamByName('SUMMARY').AsString := Item.summary; 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.ParamByName('MODIFIED_BY').AsString := Item.userId;
apiDB.uqSaveTimeEntry.ExecSQL; apiDB.uqSaveTimeEntry.ExecSQL;
...@@ -789,6 +840,32 @@ begin ...@@ -789,6 +840,32 @@ begin
end; 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; function TTimeEntryService.GetTaskPickerCustomers: TTaskPickerOptionsResponse;
begin begin
Logger.Log(4, 'TimeEntryService.GetTaskPickerCustomers Start'); Logger.Log(4, 'TimeEntryService.GetTaskPickerCustomers Start');
...@@ -874,14 +951,18 @@ end; ...@@ -874,14 +951,18 @@ end;
// status (customer field shown). Every scope lists "SHORT_NAME - project", // status (customer field shown). Every scope lists "SHORT_NAME - project",
// ordered by short name then project, like emT3's Tasks screen. // ordered by short name then project, like emT3's Tasks screen.
// taskDate (yyyy-mm-dd) keeps only projects whose START_DATE-END_DATE includes // taskDate (yyyy-mm-dd) keeps only projects whose START_DATE-END_DATE includes
// it, like emT3's Time Entry screen; '' = any date // it, like emT3's Time Entry screen; '' = any date.
function TTimeEntryService.GetTaskPickerProjects(customerId, scope, userId, taskDate: string): TTaskPickerOptionsResponse; // 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 var
projectDisplay: string; projectDisplay: string;
dateValue: string; dateValue: string;
begin begin
Logger.Log(4, Format('TimeEntryService.GetTaskPickerProjects - CUSTOMER_ID="%s" SCOPE="%s" USER_ID="%s" TASK_DATE="%s"', Logger.Log(4, Format('TimeEntryService.GetTaskPickerProjects - CUSTOMER_ID="%s" SCOPE="%s" USER_ID="%s" TASK_DATE="%s" TASK_FILTER="%s"',
[customerId, scope, userId, taskDate])); [customerId, scope, userId, taskDate, taskFilter]));
Result := TTaskPickerOptionsResponse.Create; Result := TTaskPickerOptionsResponse.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result); TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result);
...@@ -890,6 +971,10 @@ begin ...@@ -890,6 +971,10 @@ begin
if (scope <> 'MY') and (scope <> 'ACTIVE') then if (scope <> 'MY') and (scope <> 'ACTIVE') then
scope := 'ALL'; scope := 'ALL';
taskFilter := UpperCase(Trim(taskFilter));
if (taskFilter <> 'MY') and (taskFilter <> 'FOCUSED') then
taskFilter := 'ALL';
try try
if Trim(taskDate) = '' then if Trim(taskDate) = '' then
dateValue := '' dateValue := ''
...@@ -901,6 +986,7 @@ begin ...@@ -901,6 +986,7 @@ begin
apiDB.uqTaskPickerProjects.ParamByName('SCOPE').AsString := scope; apiDB.uqTaskPickerProjects.ParamByName('SCOPE').AsString := scope;
apiDB.uqTaskPickerProjects.ParamByName('USER_ID').AsString := userId; apiDB.uqTaskPickerProjects.ParamByName('USER_ID').AsString := userId;
apiDB.uqTaskPickerProjects.ParamByName('PROJECT_DATE').AsString := dateValue; apiDB.uqTaskPickerProjects.ParamByName('PROJECT_DATE').AsString := dateValue;
apiDB.uqTaskPickerProjects.ParamByName('TASK_FILTER').AsString := taskFilter;
apiDB.uqTaskPickerProjects.Open; apiDB.uqTaskPickerProjects.Open;
try try
while not apiDB.uqTaskPickerProjects.Eof do while not apiDB.uqTaskPickerProjects.Eof do
...@@ -933,12 +1019,13 @@ begin ...@@ -933,12 +1019,13 @@ begin
end; end;
// The project's tasks, whatever the task's status (the picker's scope decides // Every task in the project, whatever its status or dates (the picker's scope
// which projects are offered). Like emT3's Time Entry screen, only tasks open // decides which projects are offered), so closed tasks and tasks outside the
// on taskDate are listed: START_DATE on or before it and COMPLETION_DATE on or // user's employment are listed too. Each task carries unavailableReason: why
// after it ('' = open-ended); a blank taskDate lists every task. Each task // hours can't go on taskDate for this user, including the project's
// carries unavailableReason: why hours can't go on taskDate for this user (same // START_DATE-END_DATE (same rule as SaveTimeEntry via TimeEntryDateProblem);
// rule as SaveTimeEntry via TimeEntryDateProblem), '' when allowed or taskDate is blank. // '' 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; function TTimeEntryService.GetTaskPickerTasks(projectId, userId, taskDate: string): TTaskPickerOptionsResponse;
var var
q: TUniQuery; q: TUniQuery;
...@@ -946,7 +1033,8 @@ var ...@@ -946,7 +1033,8 @@ var
dateValue: string; dateValue: string;
userStart: string; userStart: string;
userEnd: string; userEnd: string;
dateFilter: string; projectStart: string;
projectEnd: string;
begin begin
Logger.Log(4, Format( Logger.Log(4, Format(
'TimeEntryService.GetTaskPickerTasks - PROJECT_ID="%s" USER_ID="%s" TASK_DATE="%s"', 'TimeEntryService.GetTaskPickerTasks - PROJECT_ID="%s" USER_ID="%s" TASK_DATE="%s"',
...@@ -958,12 +1046,6 @@ begin ...@@ -958,12 +1046,6 @@ begin
else else
dateValue := FormatDateTime('yyyy-mm-dd', ParseIsoDate(Trim(taskDate))); 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; Result := TTaskPickerOptionsResponse.Create;
TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result); TXDataOperationContext.Current.Handler.ManagedObjects.Add(Result);
...@@ -984,6 +1066,19 @@ begin ...@@ -984,6 +1066,19 @@ begin
end; end;
q.Close; 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 := q.SQL.Text :=
'select distinct ' + 'select distinct ' +
' t.TASK_ID, ' + ' t.TASK_ID, ' +
...@@ -998,19 +1093,30 @@ begin ...@@ -998,19 +1093,30 @@ begin
' t.SUBJECT as TASK_SUBJECT, ' + ' t.SUBJECT as TASK_SUBJECT, ' +
' t.START_DATE, ' + ' t.START_DATE, ' +
' t.COMPLETION_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 ' + 'from tasks t ' +
'join project p on p.PROJECT_ID = t.PROJECT_ID ' + 'join project p on p.PROJECT_ID = t.PROJECT_ID ' +
'join customers c on c.CUSTOMER_ID = p.CUSTOMER_ID ' + 'join customers c on c.CUSTOMER_ID = p.CUSTOMER_ID ' +
'where t.PROJECT_ID = :PROJECT_ID ' + 'where t.PROJECT_ID = :PROJECT_ID ' +
dateFilter +
'order by ' + 'order by ' +
' t.TASK_NUM_1, t.TASK_NUM_2, t.TASK_NUM_3, ' + ' 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'; ' t.TASK_NUM_4, t.TASK_NUM_5, t.TASK_NUM_6, t.SUBJECT';
q.ParamByName('PROJECT_ID').AsString := projectId; q.ParamByName('PROJECT_ID').AsString := projectId;
if dateFilter <> '' then q.ParamByName('USER_ID').AsString := userId;
q.ParamByName('TASK_DATE').AsString := dateValue;
q.Open; q.Open;
while not q.Eof do while not q.Eof do
...@@ -1021,9 +1127,13 @@ begin ...@@ -1021,9 +1127,13 @@ begin
option.value := FieldText(q, 'TASK_ID'); option.value := FieldText(q, 'TASK_ID');
option.display := BuildTaskDisplay(q); option.display := BuildTaskDisplay(q);
option.completed := not q.FieldByName('COMPLETION_DATE').IsNull; option.completed := not q.FieldByName('COMPLETION_DATE').IsNull;
option.completionDate := DateText(q, 'COMPLETION_DATE');
option.unavailableReason := TimeEntryDateProblem(dateValue, userStart, userEnd, 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.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); Result.options.Add(option);
q.Next; q.Next;
...@@ -1255,21 +1365,72 @@ begin ...@@ -1255,21 +1365,72 @@ begin
end; end;
end; end;
// Changes a task's status from the task picker, like emT3's New Status on its // Saves the Time Entries page's Compact View checkbox (hides Time and Place)
// Time Entry screen. CLOSED and COMP (the statuses emT3 requires a completion // so it is remembered between sessions
// date for) set COMPLETION_DATE to the picker's work date (today when blank), function TTimeEntryService.SetHideTimeEntriesFields(userId: string; hide: Boolean): Boolean;
// but only when it is empty, as emT3's Task Entry screen does. Any other status var
// reopens the task and clears COMPLETION_DATE (emT3 leaves it, which keeps a q: TUniQuery;
// reopened task counted as completed). An unchanged status writes nothing. begin
function TTimeEntryService.SetTaskStatus(taskId, status, taskDate: string): Boolean; 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 var
q: TUniQuery; q: TUniQuery;
statusCode: string; statusCode: string;
completionDate: TDateTime; endDateValue: TDateTime;
startDate: string;
begin begin
Logger.Log(4, Format( Logger.Log(4, Format(
'TimeEntryService.SetTaskStatus - TASK_ID="%s" STATUS="%s" TASK_DATE="%s"', 'TimeEntryService.SetTaskStatusAndEndDate - TASK_ID="%s" STATUS="%s" END_DATE="%s"',
[taskId, status, taskDate] [taskId, status, endDate]
)); ));
q := TUniQuery.Create(nil); q := TUniQuery.Create(nil);
...@@ -1277,14 +1438,26 @@ begin ...@@ -1277,14 +1438,26 @@ begin
q.Connection := apiDB.ucETaskApi; q.Connection := apiDB.ucETaskApi;
try try
statusCode := Trim(status); statusCode := Trim(status);
endDate := Trim(endDate);
endDateValue := 0;
if Trim(taskId) = '' then if Trim(taskId) = '' then
raise Exception.Create('Select a task.'); raise Exception.Create('Select a task.');
if Trim(taskDate) = '' then if endDate <> '' then
completionDate := Date endDateValue := ParseIsoDate(endDate);
else
completionDate := ParseIsoDate(Trim(taskDate)); 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) // Only codes the picker offers (GetTaskPickerStatuses)
q.SQL.Text := q.SQL.Text :=
...@@ -1299,28 +1472,26 @@ begin ...@@ -1299,28 +1472,26 @@ begin
raise Exception.Create('Unknown task status.'); raise Exception.Create('Unknown task status.');
q.Close; 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 if ((statusCode = 'CLOSED') or (statusCode = 'COMP')) and (endDate = '') then
Exit(True); 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; q.Connection.StartTransaction;
if (statusCode = 'CLOSED') or (statusCode = 'COMP') then if endDate <> '' then
begin begin
q.SQL.Text := q.SQL.Text :=
'update tasks ' + 'update tasks ' +
'set STATUS = :STATUS, ' + 'set STATUS = :STATUS, ' +
' COMPLETION_DATE = coalesce(COMPLETION_DATE, :COMPLETION_DATE) ' + ' COMPLETION_DATE = :COMPLETION_DATE ' +
'where TASK_ID = :TASK_ID'; 'where TASK_ID = :TASK_ID';
q.ParamByName('COMPLETION_DATE').AsDate := completionDate; q.ParamByName('COMPLETION_DATE').AsDate := endDateValue;
end end
else else
q.SQL.Text := q.SQL.Text :=
...@@ -1341,7 +1512,7 @@ begin ...@@ -1341,7 +1512,7 @@ begin
if q.Connection.InTransaction then if q.Connection.InTransaction then
q.Connection.Rollback; q.Connection.Rollback;
Logger.Log(2, 'TimeEntryService.SetTaskStatus - ERROR: ' + E.Message); Logger.Log(2, 'TimeEntryService.SetTaskStatusAndEndDate - ERROR: ' + E.Message);
raise; raise;
end; end;
end; end;
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
MemoLogLevel=5 MemoLogLevel=5
FileLogLevel=5 FileLogLevel=5
webClientVersion=0.9.4.1 webClientVersion=0.9.4.1
LogFileNum=243 LogFileNum=269
[Database] [Database]
--Server=192.168.102.131 --Server=192.168.102.131
......
...@@ -114,11 +114,11 @@ ...@@ -114,11 +114,11 @@
<VerInfo_Locale>1033</VerInfo_Locale> <VerInfo_Locale>1033</VerInfo_Locale>
<DCC_ExeOutput>.\bin</DCC_ExeOutput> <DCC_ExeOutput>.\bin</DCC_ExeOutput>
<DCC_UnitSearchPath>C:\RADTOOLS\FastMM4;$(DCC_UnitSearchPath)</DCC_UnitSearchPath> <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_MajorVer>0</VerInfo_MajorVer>
<VerInfo_MinorVer>9</VerInfo_MinorVer> <VerInfo_MinorVer>9</VerInfo_MinorVer>
<VerInfo_AutoIncVersion>true</VerInfo_AutoIncVersion> <VerInfo_AutoIncVersion>false</VerInfo_AutoIncVersion>
<VerInfo_Build>1</VerInfo_Build> <VerInfo_Build>3</VerInfo_Build>
<VerInfo_Release>4</VerInfo_Release> <VerInfo_Release>4</VerInfo_Release>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition="'$(Cfg_1_Win64)'!=''"> <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