diff --git a/sdk/dotnet/Timr.Api/Endpoints/TaskApi.cs b/sdk/dotnet/Timr.Api/Endpoints/TaskApi.cs index b75dfa3..9f78881 100644 --- a/sdk/dotnet/Timr.Api/Endpoints/TaskApi.cs +++ b/sdk/dotnet/Timr.Api/Endpoints/TaskApi.cs @@ -61,6 +61,29 @@ public interface ITaskApi : IApi /// <?> Task CreateTaskOrDefaultAsync(TaskCreate taskCreate, System.Threading.CancellationToken cancellationToken = default); + /// + /// Delete a Task + /// + /// + /// Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// Cancellation Token to cancel the request. + /// <> + Task DeleteTaskAsync(string id, System.Threading.CancellationToken cancellationToken = default); + + /// + /// Delete a Task + /// + /// + /// Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + /// + /// ID of the Task. + /// Cancellation Token to cancel the request. + /// <?> + Task DeleteTaskOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default); + /// /// List Tasks /// @@ -224,6 +247,36 @@ public interface ICreateTaskApiResponse : Timr.Api.Client.IApiResponse, ICreated bool IsUnprocessableContent { get; } } + /// + /// The + /// + public interface IDeleteTaskApiResponse : Timr.Api.Client.IApiResponse, IForbidden, INotFound, IConflict + { + /// + /// Returns true if the response is 204 NoContent + /// + /// + bool IsNoContent { get; } + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + bool IsForbidden { get; } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + bool IsNotFound { get; } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + bool IsConflict { get; } + } + /// /// The /// @@ -351,6 +404,26 @@ internal void ExecuteOnErrorCreateTask(Exception exception) OnErrorCreateTask?.Invoke(this, new ExceptionEventArgs(exception)); } + /// + /// The event raised after the server response + /// + public event EventHandler? OnDeleteTask; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorDeleteTask; + + internal void ExecuteOnDeleteTask(TaskApi.DeleteTaskApiResponse apiResponse) + { + OnDeleteTask?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorDeleteTask(Exception exception) + { + OnErrorDeleteTask?.Invoke(this, new ExceptionEventArgs(exception)); + } + /// /// The event raised after the server response /// @@ -906,6 +979,382 @@ private void OnDeserializationErrorDefaultImplementation(Exception exception, Ht partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); } + partial void FormatDeleteTask(ref string id); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateDeleteTask(string id) + { + if (id == null) + throw new ArgumentNullException(nameof(id)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterDeleteTaskDefaultImplementation(IDeleteTaskApiResponse apiResponseLocalVar, string id) + { + bool suppressDefaultLog = false; + AfterDeleteTask(ref suppressDefaultLog, apiResponseLocalVar, id); + if (!suppressDefaultLog) + Logger.LogInformation(RestLogEvents.ApiRequestCompleted, "{0,-9} | {1} | {2}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterDeleteTask(ref bool suppressDefaultLog, IDeleteTaskApiResponse apiResponseLocalVar, string id); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorDeleteTaskDefaultImplementation(Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id) + { + bool suppressDefaultLogLocalVar = false; + OnErrorDeleteTask(ref suppressDefaultLogLocalVar, exceptionLocalVar, pathFormatLocalVar, pathLocalVar, id); + if (!suppressDefaultLogLocalVar) + Logger.LogError(RestLogEvents.ApiRequestFailed, exceptionLocalVar, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorDeleteTask(ref bool suppressDefaultLogLocalVar, Exception exceptionLocalVar, string pathFormatLocalVar, string pathLocalVar, string id); + + /// + /// Delete a Task Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + /// + /// ID of the Task. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteTaskOrDefaultAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await DeleteTaskAsync(id, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// Delete a Task Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + /// + /// Thrown when fails to make API call + /// ID of the Task. + /// Cancellation Token to cancel the request. + /// <> + public async Task DeleteTaskAsync(string id, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateDeleteTask(id); + + FormatDeleteTask(ref id); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = HttpClient.BaseAddress.AbsolutePath == "/" + ? "/tasks/{id}" + : string.Concat(HttpClient.BaseAddress.AbsolutePath.TrimEnd('/'), "/tasks/{id}"); + uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7Bid%7D", Uri.EscapeDataString(id.ToString())); + + List tokenBaseLocalVars = new List(); + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar1); + + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); + + OAuthToken oauthTokenLocalVar2 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); + + tokenBaseLocalVars.Add(oauthTokenLocalVar2); + + oauthTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, ""); + + string[] acceptLocalVars = new string[] { + "application/problem+json" + }; + + IEnumerable acceptHeaderValuesLocalVar = ClientUtils.SelectHeaderAcceptArray(acceptLocalVars); + + foreach (var acceptLocalVar in acceptHeaderValuesLocalVar) + httpRequestMessageLocalVar.Headers.Accept.Add(acceptLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Delete; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + DeleteTaskApiResponse apiResponseLocalVar; + + switch ((int)httpResponseMessageLocalVar.StatusCode) { + default: { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + apiResponseLocalVar = new(Logger, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/tasks/{id}", requestedAtLocalVar, _jsonSerializerOptions); + + break; + } + } + + AfterDeleteTaskDefaultImplementation(apiResponseLocalVar, id); + + Events.ExecuteOnDeleteTask(apiResponseLocalVar); + + if (apiResponseLocalVar.StatusCode == (HttpStatusCode) 429) + foreach(TokenBase tokenBaseLocalVar in tokenBaseLocalVars) + tokenBaseLocalVar.BeginRateLimit(); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorDeleteTaskDefaultImplementation(e, "/tasks/{id}", uriBuilderLocalVar.Path, id); + Events.ExecuteOnErrorDeleteTask(e); + throw; + } + } + + /// + /// The + /// + public partial class DeleteTaskApiResponse : Timr.Api.Client.ApiResponse, IDeleteTaskApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteTaskApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public DeleteTaskApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, System.IO.Stream contentStream, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, contentStream, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(global::System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 204 NoContent + /// + /// + public bool IsNoContent => 204 == (int)StatusCode; + + /// + /// Returns true if the response is 403 Forbidden + /// + /// + public bool IsForbidden => 403 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 403 Forbidden + /// + /// + public Timr.Api.Model.Error? Forbidden() + { + bool suppressDefault = false; + Timr.Api.Model.Error? result = null; + OnForbidden(ref suppressDefault, ref result); + if (!suppressDefault) + result = DefaultForbidden(); + return result; + } + + private Timr.Api.Model.Error? DefaultForbidden() + { + // NOTICE: Consider this AsModel template deprecated. Implement the appropriate partial method instead + return IsForbidden + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + partial void OnForbidden(ref bool suppressDefault, ref Timr.Api.Model.Error? result); + + /// + /// Returns true if the response is 403 Forbidden and the deserialized response is not null + /// + /// + /// + public bool TryForbidden([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Forbidden(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)403); + } + + return result != null; + } + + /// + /// Returns true if the response is 404 NotFound + /// + /// + public bool IsNotFound => 404 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 404 NotFound + /// + /// + public Timr.Api.Model.Error? NotFound() + { + bool suppressDefault = false; + Timr.Api.Model.Error? result = null; + OnNotFound(ref suppressDefault, ref result); + if (!suppressDefault) + result = DefaultNotFound(); + return result; + } + + private Timr.Api.Model.Error? DefaultNotFound() + { + // NOTICE: Consider this AsModel template deprecated. Implement the appropriate partial method instead + return IsNotFound + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + partial void OnNotFound(ref bool suppressDefault, ref Timr.Api.Model.Error? result); + + /// + /// Returns true if the response is 404 NotFound and the deserialized response is not null + /// + /// + /// + public bool TryNotFound([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = NotFound(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)404); + } + + return result != null; + } + + /// + /// Returns true if the response is 409 Conflict + /// + /// + public bool IsConflict => 409 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 409 Conflict + /// + /// + public Timr.Api.Model.Error? Conflict() + { + bool suppressDefault = false; + Timr.Api.Model.Error? result = null; + OnConflict(ref suppressDefault, ref result); + if (!suppressDefault) + result = DefaultConflict(); + return result; + } + + private Timr.Api.Model.Error? DefaultConflict() + { + // NOTICE: Consider this AsModel template deprecated. Implement the appropriate partial method instead + return IsConflict + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + partial void OnConflict(ref bool suppressDefault, ref Timr.Api.Model.Error? result); + + /// + /// Returns true if the response is 409 Conflict and the deserialized response is not null + /// + /// + /// + public bool TryConflict([NotNullWhen(true)]out Timr.Api.Model.Error? result) + { + result = null; + + try + { + result = Conflict(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)409); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(RestLogEvents.ApiDeserializationFailed, exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + partial void FormatFetchTasks(ref Option parentTaskId, ref Option traverseTaskTree, ref Option name, ref Option bookable, ref Option billable, Option activeAt, ref Option pageToken, ref Option limit, ref Option sortDirection, ref Option sortBy); /// diff --git a/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskApi.java b/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskApi.java index de0812a..94216c3 100644 --- a/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskApi.java +++ b/sdk/java-restclient/src/main/java/com/timr/api/apis/TaskApi.java @@ -141,6 +141,90 @@ public ResponseSpec createTaskWithResponseSpec(TaskCreate taskCreate) throws Res return createTaskRequestCreation(taskCreate); } + /** + * Delete a Task + * Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Task. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec deleteTaskRequestCreation(String id) throws RestClientResponseException { + Object postBody = null; + // verify the required parameter 'id' is set + if (id == null) { + throw new RestClientResponseException("Missing the required parameter 'id' when calling deleteTask", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap<>(); + + pathParams.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap<>(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap<>(); + final MultiValueMap formParams = new LinkedMultiValueMap<>(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return apiClient.invokeAPI("/tasks/{id}", HttpMethod.DELETE, pathParams, localVarQueryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * Delete a Task + * Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Task. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public void deleteTask(String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + deleteTaskRequestCreation(id).body(localVarReturnType); + } + + /** + * Delete a Task + * Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Task. + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteTaskWithHttpInfo(String id) throws RestClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference<>() {}; + return deleteTaskRequestCreation(id).toEntity(localVarReturnType); + } + + /** + * Delete a Task + * Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Task. + * @return ResponseSpec + * @throws RestClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec deleteTaskWithResponseSpec(String id) throws RestClientResponseException { + return deleteTaskRequestCreation(id); + } + /** * List Tasks * Lists the Tasks the authenticated user or API token can access. diff --git a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskApi.java b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskApi.java index 665a6ed..081d15f 100644 --- a/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskApi.java +++ b/sdk/java-resttemplate/src/main/java/com/timr/api/apis/TaskApi.java @@ -102,6 +102,60 @@ public ResponseEntity createTaskWithHttpInfo(@jakarta.annotation.Nonnull T ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/tasks", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); } + /** + * Delete a Task + * Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Task. (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void deleteTask(@jakarta.annotation.Nonnull String id) throws RestClientException { + deleteTaskWithHttpInfo(id); + } + + /** + * Delete a Task + * Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + *

204 - Deleted. No content is returned. + *

403 - Forbidden + *

404 - Not Found + *

409 - Conflict + * @param id ID of the Task. (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity deleteTaskWithHttpInfo(@jakarta.annotation.Nonnull String id) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'id' is set + if (id == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'id' when calling deleteTask"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("id", id); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/problem+json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "OAuth2", "OAuth2" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/tasks/{id}", HttpMethod.DELETE, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } /** * List Tasks * Lists the Tasks the authenticated user or API token can access. diff --git a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskApi.kt b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskApi.kt index 1e7b73e..b8fea2c 100644 --- a/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskApi.kt +++ b/sdk/kotlin-okhttp/src/main/kotlin/com/timr/api/apis/TaskApi.kt @@ -136,6 +136,77 @@ open class TaskApi(basePath: kotlin.String = defaultBasePath, client: Call.Facto ) } + /** + * DELETE /tasks/{id} + * Delete a Task + * Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + * @param id ID of the Task. + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + suspend fun deleteTask(id: kotlin.String) : Unit = withContext(Dispatchers.IO) { + val localVarResponse = deleteTaskWithHttpInfo(id = id) + + return@withContext when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * DELETE /tasks/{id} + * Delete a Task + * Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + * @param id ID of the Task. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + suspend fun deleteTaskWithHttpInfo(id: kotlin.String) : ApiResponse = withContext(Dispatchers.IO) { + val localVariableConfig = deleteTaskRequestConfig(id = id) + + return@withContext request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteTask + * + * @param id ID of the Task. + * @return RequestConfig + */ + fun deleteTaskRequestConfig(id: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/problem+json" + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/tasks/{id}".replace("{"+"id"+"}", encodeURIComponent(id.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + /** * GET /tasks * List Tasks diff --git a/sdk/python/timr_api/api/task_api.py b/sdk/python/timr_api/api/task_api.py index 691f8c9..708aa51 100644 --- a/sdk/python/timr_api/api/task_api.py +++ b/sdk/python/timr_api/api/task_api.py @@ -327,6 +327,277 @@ def _create_task_serialize( + @validate_call + def delete_task( + self, + id: Annotated[StrictStr, Field(description="ID of the Task.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete a Task + + Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + + :param id: ID of the Task. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_task_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def delete_task_with_http_info( + self, + id: Annotated[StrictStr, Field(description="ID of the Task.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete a Task + + Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + + :param id: ID of the Task. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_task_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def delete_task_without_preload_content( + self, + id: Annotated[StrictStr, Field(description="ID of the Task.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete a Task + + Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + + :param id: ID of the Task. (required) + :type id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_task_serialize( + id=id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '403': "Error", + '404': "Error", + '409': "Error", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _delete_task_serialize( + self, + id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[ + str, Union[str, bytes, List[str], List[bytes], List[Tuple[str, bytes]]] + ] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if id is not None: + _path_params['id'] = id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + if 'Accept' not in _header_params: + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/problem+json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'OAuth2', + 'OAuth2' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/tasks/{id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + @validate_call def fetch_tasks( self, diff --git a/sdk/python/timr_api/configuration.py b/sdk/python/timr_api/configuration.py index d48217f..b46a8be 100644 --- a/sdk/python/timr_api/configuration.py +++ b/sdk/python/timr_api/configuration.py @@ -569,7 +569,7 @@ def to_debug_report(self) -> str: return "Python SDK Debug Report:\n"\ "OS: {env}\n"\ "Python Version: {pyversion}\n"\ - "Version of the API: 1.0.1\n"\ + "Version of the API: 1.1.0\n"\ "SDK Package Version: 2.0.0".\ format(env=sys.platform, pyversion=sys.version) diff --git a/sdk/swift/TimrApi/APIs/TaskAPI.swift b/sdk/swift/TimrApi/APIs/TaskAPI.swift index 8983b18..a75d91b 100644 --- a/sdk/swift/TimrApi/APIs/TaskAPI.swift +++ b/sdk/swift/TimrApi/APIs/TaskAPI.swift @@ -54,6 +54,51 @@ open class TaskAPI { return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) } + /** + Delete a Task + + - parameter id: (path) ID of the Task. + - returns: Void + */ + @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) + open class func deleteTask(id: String) async throws { + return try await deleteTaskWithRequestBuilder(id: id).execute().body + } + + /** + Delete a Task + - DELETE /tasks/{id} + - Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + - OAuth: + - type: oauth2 + - name: OAuth2 + - OAuth: + - type: oauth2 + - name: OAuth2 + - parameter id: (path) ID of the Task. + - returns: RequestBuilder + */ + open class func deleteTaskWithRequestBuilder(id: String) -> RequestBuilder { + var localVariablePath = "/tasks/{id}" + let idPreEscape = "\(APIHelper.mapValueToPathItem(id))" + let idPostEscape = idPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{id}", with: idPostEscape, options: .literal, range: nil) + let localVariableURLString = TimrAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = TimrAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters, requiresAuthentication: true) + } + /** List Tasks diff --git a/sdk/typescript-fetch/src/apis/TaskApi.ts b/sdk/typescript-fetch/src/apis/TaskApi.ts index 14698c6..cc26397 100644 --- a/sdk/typescript-fetch/src/apis/TaskApi.ts +++ b/sdk/typescript-fetch/src/apis/TaskApi.ts @@ -59,6 +59,13 @@ export interface CreateTaskRequest { taskCreate: TaskCreate; } +export interface DeleteTaskRequest { + /** + * ID of the Task. + */ + id: string; +} + export interface FetchTasksRequest { /** * Only return Tasks whose parent is the Task with this ID. @@ -241,6 +248,62 @@ export class TaskApi extends runtime.BaseAPI { return await response.value(); } + /** + * Creates request options for deleteTask without sending the request + */ + async deleteTaskRequestOpts(requestParameters: DeleteTaskRequest): Promise { + if (requestParameters['id'] == null) { + throw new runtime.RequiredError( + 'id', + 'Required parameter "id" was null or undefined when calling deleteTask().' + ); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + if (this.configuration && this.configuration.accessToken) { + // oauth required + headerParameters["Authorization"] = await this.configuration.accessToken("OAuth2", []); + } + + + let urlPath = `/tasks/{id}`; + urlPath = urlPath.replace('{id}', encodeURIComponent(String(requestParameters['id']))); + + return { + path: urlPath, + method: 'DELETE', + headers: headerParameters, + query: queryParameters, + }; + } + + /** + * Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can\'t be deleted; the request is answered with 409 and nothing is deleted. + * Delete a Task + */ + async deleteTaskRaw(requestParameters: DeleteTaskRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + const requestOptions = await this.deleteTaskRequestOpts(requestParameters); + const response = await this.request(requestOptions, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can\'t be deleted; the request is answered with 409 and nothing is deleted. + * Delete a Task + */ + async deleteTask(id: string, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.deleteTaskRaw({ id: id, }, initOverrides); + } + /** * Creates request options for fetchTasks without sending the request */ diff --git a/spec/openapi.yaml b/spec/openapi.yaml index 39d9259..0a4658d 100644 --- a/spec/openapi.yaml +++ b/spec/openapi.yaml @@ -10,7 +10,7 @@ info: license: name: Apache 2.0 url: https://www.apache.org/licenses/LICENSE-2.0.html - version: 1.0.1 + version: 1.1.0 servers: - url: https://api.timr.com/v1/ @@ -2088,6 +2088,30 @@ paths: "422": $ref: '#/components/responses/UnprocessableContent' + delete: + operationId: deleteTask + tags: + - Task + summary: Delete a Task + description: Deletes the Task together with all its subtasks. A Task that has recorded or running Project Times on itself or any of its subtasks can't be deleted; the request is answered with 409 and nothing is deleted. + parameters: + - name: id + in: path + description: ID of the Task. + required: true + example: 074e7048-9097-11eb-a8b3-0242ac130003 + schema: + type: string + responses: + "204": + description: Deleted. No content is returned. + "403": + $ref: '#/components/responses/Forbidden' + "404": + $ref: '#/components/responses/NotFound' + "409": + $ref: '#/components/responses/Conflict' + /tasks/{task_id}/users: get: operationId: fetchTaskToUserAssignments