Skip to content

Commit

Permalink
Merge pull request #749 from open-rmf/port/hammer
Browse files Browse the repository at this point in the history
Port/hammer
  • Loading branch information
aaronchongth authored Aug 25, 2023
2 parents f903af6 + de3a5ad commit 1fb4560
Show file tree
Hide file tree
Showing 14 changed files with 445 additions and 193 deletions.
117 changes: 117 additions & 0 deletions packages/api-client/lib/openapi/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,6 +321,12 @@ export interface ApiServerModelsTortoiseModelsScheduledTaskScheduledTask {
* @memberof ApiServerModelsTortoiseModelsScheduledTaskScheduledTask
*/
last_ran?: string | null;
/**
*
* @type {any}
* @memberof ApiServerModelsTortoiseModelsScheduledTaskScheduledTask
*/
except_dates?: any;
/**
*
* @type {Array<ApiServerModelsTortoiseModelsScheduledTaskScheduledTaskScheduleLeaf>}
Expand Down Expand Up @@ -7340,6 +7346,60 @@ export class LiftsApi extends BaseAPI {
*/
export const TasksApiAxiosParamCreator = function (configuration?: Configuration) {
return {
/**
*
* @summary Del Scheduled Tasks Event
* @param {number} taskId
* @param {string} eventDate
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
delScheduledTasksEventScheduledTasksTaskIdClearPut: async (
taskId: number,
eventDate: string,
options: AxiosRequestConfig = {},
): Promise<RequestArgs> => {
// verify required parameter 'taskId' is not null or undefined
assertParamExists('delScheduledTasksEventScheduledTasksTaskIdClearPut', 'taskId', taskId);
// verify required parameter 'eventDate' is not null or undefined
assertParamExists(
'delScheduledTasksEventScheduledTasksTaskIdClearPut',
'eventDate',
eventDate,
);
const localVarPath = `/scheduled_tasks/{task_id}/clear`.replace(
`{${'task_id'}}`,
encodeURIComponent(String(taskId)),
);
// use dummy base URL string because the URL constructor only accepts absolute URLs.
const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL);
let baseOptions;
if (configuration) {
baseOptions = configuration.baseOptions;
}

const localVarRequestOptions = { method: 'PUT', ...baseOptions, ...options };
const localVarHeaderParameter = {} as any;
const localVarQueryParameter = {} as any;

if (eventDate !== undefined) {
localVarQueryParameter['event_date'] =
(eventDate as any) instanceof Date ? (eventDate as any).toISOString() : eventDate;
}

setSearchParams(localVarUrlObj, localVarQueryParameter);
let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {};
localVarRequestOptions.headers = {
...localVarHeaderParameter,
...headersFromBaseOptions,
...options.headers,
};

return {
url: toPathString(localVarUrlObj),
options: localVarRequestOptions,
};
},
/**
*
* @summary Del Scheduled Tasks
Expand Down Expand Up @@ -8386,6 +8446,27 @@ export const TasksApiAxiosParamCreator = function (configuration?: Configuration
export const TasksApiFp = function (configuration?: Configuration) {
const localVarAxiosParamCreator = TasksApiAxiosParamCreator(configuration);
return {
/**
*
* @summary Del Scheduled Tasks Event
* @param {number} taskId
* @param {string} eventDate
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
async delScheduledTasksEventScheduledTasksTaskIdClearPut(
taskId: number,
eventDate: string,
options?: AxiosRequestConfig,
): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<any>> {
const localVarAxiosArgs =
await localVarAxiosParamCreator.delScheduledTasksEventScheduledTasksTaskIdClearPut(
taskId,
eventDate,
options,
);
return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration);
},
/**
*
* @summary Del Scheduled Tasks
Expand Down Expand Up @@ -8824,6 +8905,23 @@ export const TasksApiFactory = function (
) {
const localVarFp = TasksApiFp(configuration);
return {
/**
*
* @summary Del Scheduled Tasks Event
* @param {number} taskId
* @param {string} eventDate
* @param {*} [options] Override http request option.
* @throws {RequiredError}
*/
delScheduledTasksEventScheduledTasksTaskIdClearPut(
taskId: number,
eventDate: string,
options?: any,
): AxiosPromise<any> {
return localVarFp
.delScheduledTasksEventScheduledTasksTaskIdClearPut(taskId, eventDate, options)
.then((request) => request(axios, basePath));
},
/**
*
* @summary Del Scheduled Tasks
Expand Down Expand Up @@ -9183,6 +9281,25 @@ export const TasksApiFactory = function (
* @extends {BaseAPI}
*/
export class TasksApi extends BaseAPI {
/**
*
* @summary Del Scheduled Tasks Event
* @param {number} taskId
* @param {string} eventDate
* @param {*} [options] Override http request option.
* @throws {RequiredError}
* @memberof TasksApi
*/
public delScheduledTasksEventScheduledTasksTaskIdClearPut(
taskId: number,
eventDate: string,
options?: AxiosRequestConfig,
) {
return TasksApiFp(this.configuration)
.delScheduledTasksEventScheduledTasksTaskIdClearPut(taskId, eventDate, options)
.then((request) => request(this.axios, this.basePath));
}

/**
*
* @summary Del Scheduled Tasks
Expand Down
2 changes: 1 addition & 1 deletion packages/api-client/lib/version.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@ import { version as rmfModelVer } from 'rmf-models';

export const version = {
rmfModels: rmfModelVer,
rmfServer: '0aa093dff56cb468ad8d8e51f28b930fe88492d9',
rmfServer: 'c8c43e395caae7ccc858008b7663d30914b2cc62',
openapiGenerator: '6.2.1',
};
34 changes: 34 additions & 0 deletions packages/api-client/schema/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1250,6 +1250,39 @@ export default {
},
},
},
'/scheduled_tasks/{task_id}/clear': {
put: {
tags: ['Tasks'],
summary: 'Del Scheduled Tasks Event',
operationId: 'del_scheduled_tasks_event_scheduled_tasks__task_id__clear_put',
parameters: [
{
required: true,
schema: { title: 'Task Id', type: 'integer' },
name: 'task_id',
in: 'path',
},
{
required: true,
schema: { title: 'Event Date', type: 'string', format: 'date-time' },
name: 'event_date',
in: 'query',
},
],
responses: {
'200': {
description: 'Successful Response',
content: { 'application/json': { schema: {} } },
},
'422': {
description: 'Validation Error',
content: {
'application/json': { schema: { $ref: '#/components/schemas/HTTPValidationError' } },
},
},
},
},
},
'/favorite_tasks': {
get: {
tags: ['Tasks'],
Expand Down Expand Up @@ -3669,6 +3702,7 @@ export default {
task_request: { title: 'Task Request' },
created_by: { title: 'Created By', maxLength: 255, type: 'string' },
last_ran: { title: 'Last Ran', type: 'string', format: 'date-time', nullable: true },
except_dates: { title: 'Except Dates' },
schedules: {
title: 'Schedules',
type: 'array',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class ScheduledTask(Model):
created_by = CharField(255)
schedules: ReverseRelation["ScheduledTaskSchedule"]
last_ran: Optional[datetime] = DatetimeField(null=True)
except_dates = JSONField(null=True, default=list)


class ScheduledTaskSchedule(Model):
Expand Down
25 changes: 25 additions & 0 deletions packages/api-server/api_server/routes/tasks/scheduled_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ class PostScheduledTaskRequest(BaseModel):
schedules: list[ttm.ScheduledTaskSchedulePydantic]


def datetime_to_date_format(date: datetime) -> str:
return date.date().strftime("%m/%d/%Y").lstrip("0")


async def schedule_task(task: ttm.ScheduledTask, task_repo: TaskRepository):
await task.fetch_related("schedules")
jobs: list[tuple[ttm.ScheduledTaskSchedule, schedule.Job]] = []
Expand All @@ -49,6 +53,8 @@ async def run():

def do():
logger.info(f"starting task {task.pk}")
if datetime_to_date_format(datetime.now()) in task.except_dates:
return
asyncio.get_event_loop().create_task(run())

for _, j in jobs:
Expand Down Expand Up @@ -129,6 +135,25 @@ async def get_scheduled_task(task_id: int) -> ttm.ScheduledTask:
return task


@router.put("/{task_id}/clear")
async def del_scheduled_tasks_event(
task_id: int,
event_date: datetime,
task_repo: TaskRepository = Depends(task_repo_dep),
):
task = await get_scheduled_task(task_id)
if task is None:
raise HTTPException(404)

task.except_dates.append(datetime_to_date_format(event_date))
await task.save()

for sche in task.schedules:
schedule.clear(sche.get_id())

await schedule_task(task, task_repo)


@router.delete("/{task_id}")
async def del_scheduled_tasks(task_id: int):
async with tortoise.transactions.in_transaction():
Expand Down
12 changes: 6 additions & 6 deletions packages/dashboard-e2e/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,13 @@ browser.overwriteCommand(
```

```ts
// this will fail depending on the context on which `getLoopOption` is called.
const getLoopOption = async () => {
return $$('[role=option]').find(async (elem) => await elem.getText() === 'Loop');
// this will fail depending on the context on which `getPatrolOption` is called.
const getPatrolOption = async () => {
return $$('[role=option]').find(async (elem) => await elem.getText() === 'Patrol');
};

await browser.waitUntil(async () => !!(await getLoopOption)); // ok
await console.log(await getLoopOption()); // error
await browser.waitUntil(async () => !!(await getPatrolOption)); // ok
await console.log(await getPatrolOption()); // error
```

Possible reason is because async selectors chaining relies on a "finalizer" or some kind of context to resolve the promises. As a result, when running `getLoopOption` without a wdio await, the chaining does not work. But this is all speculation, the inner workings of async selector chainings are very complex.
Possible reason is because async selectors chaining relies on a "finalizer" or some kind of context to resolve the promises. As a result, when running `getPatrolOption` without a wdio await, the chaining does not work. But this is all speculation, the inner workings of async selector chainings are very complex.
12 changes: 6 additions & 6 deletions packages/dashboard-e2e/tests/ui-interactions/submit-task.test.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import { getAppBar } from '../utils';

describe('submit task', () => {
it('can submit loop task', async () => {
it('can submit patrol task', async () => {
const appBar = await getAppBar();
await (await appBar.$('button[aria-label="Tasks"]')).click();
await (await appBar.$('button[aria-label="new task"]')).click();
await (await $('#task-type')).click();
const getLoopOption = async () => {
const getPatrolOption = async () => {
const options = await $$('[role=option]');
for (const opt of options) {
const text = await opt.getText();
if (text === 'Loop') {
if (text === 'Patrol') {
return opt;
}
}
return null;
};
await browser.waitUntil(async () => !!(await getLoopOption()));
const loopOption = (await getLoopOption())!;
await loopOption.click();
await browser.waitUntil(async () => !!(await getPatrolOption()));
const patrolOption = (await getPatrolOption())!;
await patrolOption.click();

await (await $('#place-input')).setValue('coe');

Expand Down
2 changes: 1 addition & 1 deletion packages/dashboard/src/components/app-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,6 @@ export const AppEvents = {
refreshAlertCount: new Subject<number>(),
alertListOpenedAlert: new Subject<Alert | null>(),
disabledLayers: new ReplaySubject<Record<string, boolean>>(),
zoom: new BehaviorSubject<number>(0.5),
zoom: new BehaviorSubject<number | null>(null),
mapCenter: new BehaviorSubject<[number, number]>([0, 0]),
};
49 changes: 32 additions & 17 deletions packages/dashboard/src/components/appbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,10 @@ export const AppBar = React.memo(({ extraToolbarItems }: AppBarProps): React.Rea
const [brandingIconPath, setBrandingIconPath] = React.useState<string>('');
const [settingsAnchor, setSettingsAnchor] = React.useState<HTMLElement | null>(null);
const [openCreateTaskForm, setOpenCreateTaskForm] = React.useState(false);
const [placeNames, setPlaceNames] = React.useState<string[]>([]);
const [workcells, setWorkcells] = React.useState<string[]>();
const [waypointNames, setWaypointNames] = React.useState<string[]>([]);
const [cleaningZoneNames, setCleaningZoneNames] = React.useState<string[]>([]);
const [pickupPoints, setPickupPoints] = React.useState<Record<string, string>>({});
const [dropoffPoints, setDropoffPoints] = React.useState<Record<string, string>>({});
const [favoritesTasks, setFavoritesTasks] = React.useState<TaskFavorite[]>([]);
const [refreshTaskAppCount, setRefreshTaskAppCount] = React.useState(0);
const [username, setUsername] = React.useState<string | null>(null);
Expand Down Expand Up @@ -204,23 +206,37 @@ export const AppBar = React.memo(({ extraToolbarItems }: AppBarProps): React.Rea
})();
}, [logoResourcesContext, safeAsync, curTheme]);

React.useEffect(() => {
if (!resourceManager?.dispensers) {
return;
}
setWorkcells(Object.keys(resourceManager.dispensers.dispensers));
}, [resourceManager]);

React.useEffect(() => {
if (!rmf) {
return;
}

const subs: Subscription[] = [];
subs.push(
rmf.buildingMapObs.subscribe((map) =>
setPlaceNames(getPlaces(map).map((p) => p.vertex.name)),
),
rmf.buildingMapObs.subscribe((map) => {
const places = getPlaces(map);
const waypointNames: string[] = [];
const pickupPoints: Record<string, string> = {};
const dropoffPoints: Record<string, string> = {};
const cleaningZoneNames: string[] = [];
for (const p of places) {
if (p.pickupHandler !== undefined && p.pickupHandler.length !== 0) {
pickupPoints[p.vertex.name] = p.pickupHandler;
}
if (p.dropoffHandler !== undefined && p.dropoffHandler.length !== 0) {
dropoffPoints[p.vertex.name] = p.dropoffHandler;
}
if (p.cleaningZone !== undefined && p.cleaningZone === true) {
cleaningZoneNames.push(p.vertex.name);
}
waypointNames.push(p.vertex.name);
}

setPickupPoints(pickupPoints);
setDropoffPoints(dropoffPoints);
setCleaningZoneNames(cleaningZoneNames);
setWaypointNames(waypointNames);
}),
);
subs.push(
AppEvents.refreshAlertCount.subscribe((_) => {
Expand Down Expand Up @@ -548,11 +564,10 @@ export const AppBar = React.memo(({ extraToolbarItems }: AppBarProps): React.Rea
{openCreateTaskForm && (
<CreateTaskForm
user={username ? username : 'unknown user'}
cleaningZones={placeNames}
loopWaypoints={placeNames}
deliveryWaypoints={placeNames}
dispensers={workcells}
ingestors={workcells}
patrolWaypoints={waypointNames}
cleaningZones={cleaningZoneNames}
pickupPoints={pickupPoints}
dropoffPoints={dropoffPoints}
favoritesTasks={favoritesTasks}
open={openCreateTaskForm}
onClose={() => setOpenCreateTaskForm(false)}
Expand Down
Loading

0 comments on commit 1fb4560

Please sign in to comment.