refactor(edge/jobs): migrate view to react [EE-2236] (#10661)

pull/10663/head
Chaim Lev-Ari 8 months ago committed by GitHub
parent 86c4b3059e
commit 66770bebd4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -1,108 +0,0 @@
<div class="datatable">
<rd-widget>
<rd-widget-body classes="no-padding">
<div class="toolBar">
<div class="toolBarTitle vertical-center">
<div class="widget-icon space-right">
<pr-icon icon="$ctrl.titleIcon"></pr-icon>
</div>
{{ $ctrl.titleText }}
</div>
<div class="searchBar vertical-center">
<pr-icon icon="'search'" class-name="'icon'"></pr-icon>
<input type="text" class="searchInput" ng-model="$ctrl.state.textFilter" placeholder="Search..." auto-focus ng-model-options="{ debounce: 300 }" />
</div>
<div class="actionBar">
<button type="button" class="btn btn-sm btn-danger" ng-disabled="$ctrl.state.selectedItemCount === 0" ng-click="$ctrl.removeAction($ctrl.state.selectedItems)">
<pr-icon icon="'trash-2'"></pr-icon>Remove
</button>
<button type="button" class="btn btn-sm btn-primary" ui-sref="edge.jobs.new"> <pr-icon icon="'plus'"></pr-icon>Add Edge job </button>
</div>
</div>
<div class="table-responsive">
<table class="table-hover nowrap-cells table">
<thead>
<tr>
<th>
<div class="vertical-center">
<span class="md-checkbox">
<input id="select_all" type="checkbox" ng-model="$ctrl.state.selectAll" ng-change="$ctrl.selectAll()" />
<label for="select_all"></label>
</span>
<table-column-header
col-title="'Name'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'Name'"
is-sorted-desc="$ctrl.state.orderBy === 'Name' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('Name')"
></table-column-header>
</div>
</th>
<th>
<table-column-header
col-title="'CronExpression'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'CronExpression'"
is-sorted-desc="$ctrl.state.orderBy === 'CronExpression' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('CronExpression')"
></table-column-header>
</th>
<th>
<table-column-header
col-title="'Created'"
can-sort="true"
is-sorted="$ctrl.state.orderBy === 'Created'"
is-sorted-desc="$ctrl.state.orderBy === 'Created' && $ctrl.state.reverseOrder"
ng-click="$ctrl.changeOrderBy('Created')"
></table-column-header>
</th>
</tr>
</thead>
<tbody>
<tr
dir-paginate="item in ($ctrl.state.filteredDataSet = ($ctrl.dataset | filter:$ctrl.state.textFilter | orderBy:$ctrl.state.orderBy:$ctrl.state.reverseOrder | itemsPerPage: $ctrl.state.paginatedItemLimit))"
ng-class="{ active: item.Checked }"
>
<td>
<span class="md-checkbox">
<input id="select_{{ $index }}" type="checkbox" ng-model="item.Checked" ng-click="$ctrl.selectItem(item, $event)" />
<label for="select_{{ $index }}"></label>
</span>
<a ui-sref="edge.jobs.job({id: item.Id})">{{ item.Name }}</a>
</td>
<td>
{{ item.CronExpression }}
</td>
<td>{{ item.Created | getisodatefromtimestamp }}</td>
</tr>
<tr ng-if="!$ctrl.dataset">
<td colspan="3" class="text-muted text-center">Loading...</td>
</tr>
<tr ng-if="$ctrl.state.filteredDataSet.length === 0">
<td colspan="3" class="text-muted text-center">No Edge job available.</td>
</tr>
</tbody>
</table>
</div>
<div class="footer" ng-if="$ctrl.dataset">
<div class="infoBar" ng-if="$ctrl.state.selectedItemCount !== 0"> {{ $ctrl.state.selectedItemCount }} item(s) selected </div>
<div class="paginationControls">
<form class="form-inline">
<span class="limitSelector">
<span class="mr-1"> Items per page </span>
<select class="form-control" ng-model="$ctrl.state.paginatedItemLimit" ng-change="$ctrl.changePaginationLimit()" data-cy="component-paginationSelect">
<option value="0">All</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</span>
<dir-pagination-controls max-size="5"></dir-pagination-controls>
</form>
</div>
</div>
</rd-widget-body>
</rd-widget>
</div>

@ -1,15 +0,0 @@
import angular from 'angular';
angular.module('portainer.edge').component('edgeJobsDatatable', {
templateUrl: './edgeJobsDatatable.html',
controller: 'GenericDatatableController',
bindings: {
titleText: '@',
titleIcon: '@',
dataset: '<',
tableKey: '@',
orderBy: '@',
reverseOrder: '<',
removeAction: '<',
},
});

@ -9,9 +9,10 @@ import { ListView as EdgeStacksListView } from '@/react/edge/edge-stacks/ListVie
import { ListView as EdgeGroupsListView } from '@/react/edge/edge-groups/ListView';
import { templatesModule } from './templates';
import { jobsModule } from './jobs';
export const viewsModule = angular
.module('portainer.edge.react.views', [templatesModule])
.module('portainer.edge.react.views', [templatesModule, jobsModule])
.component(
'waitingRoomView',
r2a(withUIRouter(withReactQuery(withCurrentUser(WaitingRoomView))), [])

@ -0,0 +1,13 @@
import angular from 'angular';
import { r2a } from '@/react-tools/react2angular';
import { withCurrentUser } from '@/react-tools/withCurrentUser';
import { withUIRouter } from '@/react-tools/withUIRouter';
import { ListView } from '@/react/edge/edge-jobs/ListView';
export const jobsModule = angular
.module('portainer.edge.react.views.jobs', [])
.component(
'edgeJobsView',
r2a(withUIRouter(withCurrentUser(ListView)), [])
).name;

@ -1,20 +0,0 @@
<page-header title="'Edge Jobs'" breadcrumbs="['Edge Jobs']" reload="true"> </page-header>
<information-panel title-text="Information">
<span class="small">
<p class="text-muted">Edge Jobs requires Docker Standalone and a cron implementation that reads jobs from <code>/etc/cron.d</code></p>
</span>
</information-panel>
<div class="row">
<div class="col-sm-12">
<edge-jobs-datatable
title-text="Edge jobs"
title-icon="clock"
dataset="$ctrl.edgeJobs"
table-key="edgeJobs"
order-by="Name"
remove-action="$ctrl.removeAction"
></edge-jobs-datatable>
</div>
</div>

@ -1,53 +0,0 @@
import _ from 'lodash-es';
import { confirmDelete } from '@@/modals/confirm';
export class EdgeJobsViewController {
/* @ngInject */
constructor($async, $state, EdgeJobService, Notifications) {
this.$async = $async;
this.$state = $state;
this.EdgeJobService = EdgeJobService;
this.Notifications = Notifications;
this.removeAction = this.removeAction.bind(this);
this.deleteJobsAsync = this.deleteJobsAsync.bind(this);
this.deleteJobs = this.deleteJobs.bind(this);
}
removeAction(selectedItems) {
confirmDelete('Do you want to remove the selected Edge job(s)?').then((confirmed) => {
if (!confirmed) {
return;
}
this.deleteJobs(selectedItems);
});
}
deleteJobs(edgeJobs) {
return this.$async(this.deleteJobsAsync, edgeJobs);
}
async deleteJobsAsync(edgeJobs) {
for (let edgeJob of edgeJobs) {
try {
await this.EdgeJobService.remove(edgeJob.Id);
this.Notifications.success('Edge job successfully removed', edgeJob.Name);
_.remove(this.edgeJobs, edgeJob);
} catch (err) {
this.Notifications.error('Failure', err, 'Unable to remove Edge job ' + edgeJob.Name);
}
}
this.$state.reload();
}
async $onInit() {
try {
const edgeJobs = await this.EdgeJobService.edgeJobs();
this.edgeJobs = edgeJobs;
} catch (err) {
this.Notifications.error('Failure', err, 'Unable to retrieve Edge jobs');
this.edgeJobs = [];
}
}
}

@ -1,7 +0,0 @@
import angular from 'angular';
import { EdgeJobsViewController } from './edgeJobsViewController';
angular.module('portainer.edge').component('edgeJobsView', {
templateUrl: './edgeJobsView.html',
controller: EdgeJobsViewController,
});

@ -0,0 +1,34 @@
import { Clock } from 'lucide-react';
import { Datatable } from '@@/datatables';
import { createPersistedStore } from '@@/datatables/types';
import { useTableState } from '@@/datatables/useTableState';
import { useEdgeJobs } from '../queries/useEdgeJobs';
import { TableActions } from './TableActions';
import { columns } from './columns';
const tableKey = 'edge-jobs';
const settingsStore = createPersistedStore(tableKey);
export function EdgeJobsDatatable() {
const jobsQuery = useEdgeJobs();
const tableState = useTableState(settingsStore, tableKey);
return (
<Datatable
columns={columns}
isLoading={jobsQuery.isLoading}
dataset={jobsQuery.data || []}
settingsManager={tableState}
emptyContentLabel="No Edge jobs available."
title="Edge Jobs"
titleIcon={Clock}
renderTableActions={(selectedItems) => (
<TableActions selectedItems={selectedItems} />
)}
/>
);
}

@ -0,0 +1,21 @@
import { InformationPanel } from '@@/InformationPanel';
import { PageHeader } from '@@/PageHeader';
import { EdgeJobsDatatable } from './EdgeJobsDatatable';
export function ListView() {
return (
<>
<PageHeader title="Edge Jobs" breadcrumbs="Edge Jobs" reload />
<InformationPanel title="Information">
<p className="small text-muted">
Edge Jobs requires Docker Standalone and a cron implementation that
reads jobs from <code>/etc/cron.d</code>
</p>
</InformationPanel>
<EdgeJobsDatatable />
</>
);
}

@ -0,0 +1,37 @@
import { notifySuccess } from '@/portainer/services/notifications';
import { AddButton } from '@@/buttons';
import { DeleteButton } from '@@/buttons/DeleteButton';
import { EdgeJob } from '../types';
import { useDeleteEdgeJobsMutation } from './useDeleteEdgeJobsMutation';
export function TableActions({
selectedItems,
}: {
selectedItems: Array<EdgeJob>;
}) {
const removeMutation = useDeleteEdgeJobsMutation();
return (
<div className="flex items-center gap-2">
<DeleteButton
confirmMessage="Do you want to remove the selected Edge Job(s)?"
disabled={selectedItems.length === 0}
onConfirmed={() => handleRemove(selectedItems)}
/>
<AddButton>Add Edge job</AddButton>
</div>
);
async function handleRemove(selectedItems: Array<EdgeJob>) {
const ids = selectedItems.map((item) => item.Id);
removeMutation.mutate(ids, {
onSuccess: () => {
notifySuccess('Success', 'Edge Job(s) removed');
},
});
}
}

@ -0,0 +1,20 @@
import { createColumnHelper } from '@tanstack/react-table';
import { isoDateFromTimestamp } from '@/portainer/filters/filters';
import { buildNameColumn } from '@@/datatables/buildNameColumn';
import { EdgeJob } from '../types';
const columnHelper = createColumnHelper<EdgeJob>();
export const columns = [
buildNameColumn<EdgeJob>('Name', '.job'),
columnHelper.accessor('CronExpression', {
header: 'Cron Expression',
}),
columnHelper.accessor('Created', {
header: 'Created',
cell: ({ getValue }) => isoDateFromTimestamp(getValue()),
}),
];

@ -0,0 +1 @@
export { ListView } from './ListView';

@ -0,0 +1,35 @@
import { useMutation, useQueryClient } from 'react-query';
import { promiseSequence } from '@/portainer/helpers/promise-utils';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import {
mutationOptions,
withError,
withInvalidate,
} from '@/react-tools/react-query';
import { EdgeJob } from '../types';
import { buildUrl } from '../queries/build-url';
import { queryKeys } from '../queries/query-keys';
export function useDeleteEdgeJobsMutation() {
const queryClient = useQueryClient();
return useMutation(
(edgeJobIds: Array<EdgeJob['Id']>) =>
promiseSequence(
edgeJobIds.map((edgeJobId) => () => deleteEdgeJob(edgeJobId))
),
mutationOptions(
withError('Unable to delete Edge job(s)'),
withInvalidate(queryClient, [queryKeys.base()])
)
);
}
async function deleteEdgeJob(id: EdgeJob['Id']) {
try {
await axios.delete(buildUrl({ id }));
} catch (e) {
throw parseAxiosError(e, 'Unable to delete edge job');
}
}

@ -0,0 +1,10 @@
import { EdgeJob } from '../types';
export function buildUrl({
action,
id,
}: { id?: EdgeJob['Id']; action?: string } = {}) {
const baseUrl = '/edge_jobs';
const url = id ? `${baseUrl}/${id}` : baseUrl;
return action ? `${url}/${action}` : url;
}

@ -0,0 +1,3 @@
export const queryKeys = {
base: () => ['edge', 'jobs'] as const,
};

@ -0,0 +1,25 @@
import { useQuery } from 'react-query';
import axios, { parseAxiosError } from '@/portainer/services/axios';
import { EdgeJob } from '../types';
import { buildUrl } from './build-url';
import { queryKeys } from './query-keys';
async function getEdgeJobs() {
try {
const { data } = await axios.get<EdgeJob[]>(buildUrl());
return data;
} catch (err) {
throw parseAxiosError(err as Error, 'Failed fetching edge jobs');
}
}
export function useEdgeJobs<T = EdgeJob[]>({
select,
}: {
select?: (jobs: EdgeJob[]) => T;
} = {}) {
return useQuery(queryKeys.base(), getEdgeJobs, { select });
}

@ -0,0 +1,26 @@
import { EnvironmentId } from '@/react/portainer/environments/types';
export interface EdgeJob {
Id: number;
Created: number;
CronExpression: string;
Endpoints: Record<EnvironmentId, EndpointMeta>;
EdgeGroups: number[];
Name: string;
ScriptPath: string;
Recurring: boolean;
Version: number;
/** Field used for log collection of Endpoints belonging to EdgeGroups */
GroupLogsCollection: Record<EnvironmentId, EndpointMeta>;
}
enum LogsStatus {
Idle = 1,
Pending = 2,
Collected = 3,
}
interface EndpointMeta {
LogsStatus: LogsStatus;
CollectLogs: boolean;
}
Loading…
Cancel
Save