Skip to main content

google_billingbudgets1_beta1/
api.rs

1#![allow(clippy::ptr_arg)]
2
3use std::collections::{BTreeSet, HashMap};
4
5use tokio::time::sleep;
6
7// ##############
8// UTILITIES ###
9// ############
10
11/// Identifies the an OAuth2 authorization scope.
12/// A scope is needed when requesting an
13/// [authorization token](https://developers.google.com/youtube/v3/guides/authentication).
14#[derive(PartialEq, Eq, Ord, PartialOrd, Hash, Debug, Clone, Copy)]
15pub enum Scope {
16    /// View and manage your Google Cloud Platform billing accounts
17    CloudBilling,
18
19    /// See, edit, configure, and delete your Google Cloud data and see the email address for your Google Account.
20    CloudPlatform,
21}
22
23impl AsRef<str> for Scope {
24    fn as_ref(&self) -> &str {
25        match *self {
26            Scope::CloudBilling => "https://www.googleapis.com/auth/cloud-billing",
27            Scope::CloudPlatform => "https://www.googleapis.com/auth/cloud-platform",
28        }
29    }
30}
31
32#[allow(clippy::derivable_impls)]
33impl Default for Scope {
34    fn default() -> Scope {
35        Scope::CloudBilling
36    }
37}
38
39// ########
40// HUB ###
41// ######
42
43/// Central instance to access all CloudBillingBudget related resource activities
44///
45/// # Examples
46///
47/// Instantiate a new hub
48///
49/// ```test_harness,no_run
50/// extern crate hyper;
51/// extern crate hyper_rustls;
52/// extern crate google_billingbudgets1_beta1 as billingbudgets1_beta1;
53/// use billingbudgets1_beta1::api::GoogleCloudBillingBudgetsV1beta1CreateBudgetRequest;
54/// use billingbudgets1_beta1::{Result, Error};
55/// # async fn dox() {
56/// use billingbudgets1_beta1::{CloudBillingBudget, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
57///
58/// // Get an ApplicationSecret instance by some means. It contains the `client_id` and
59/// // `client_secret`, among other things.
60/// let secret: yup_oauth2::ApplicationSecret = Default::default();
61/// // Instantiate the authenticator. It will choose a suitable authentication flow for you,
62/// // unless you replace  `None` with the desired Flow.
63/// // Provide your own `AuthenticatorDelegate` to adjust the way it operates and get feedback about
64/// // what's going on. You probably want to bring in your own `TokenStorage` to persist tokens and
65/// // retrieve them from storage.
66/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
67///     .with_native_roots()
68///     .unwrap()
69///     .https_only()
70///     .enable_http2()
71///     .build();
72///
73/// let executor = hyper_util::rt::TokioExecutor::new();
74/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
75///     secret,
76///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
77///     yup_oauth2::client::CustomHyperClientBuilder::from(
78///         hyper_util::client::legacy::Client::builder(executor).build(connector),
79///     ),
80/// ).build().await.unwrap();
81///
82/// let client = hyper_util::client::legacy::Client::builder(
83///     hyper_util::rt::TokioExecutor::new()
84/// )
85/// .build(
86///     hyper_rustls::HttpsConnectorBuilder::new()
87///         .with_native_roots()
88///         .unwrap()
89///         .https_or_http()
90///         .enable_http2()
91///         .build()
92/// );
93/// let mut hub = CloudBillingBudget::new(client, auth);
94/// // As the method needs a request, you would usually fill it with the desired information
95/// // into the respective structure. Some of the parts shown here might not be applicable !
96/// // Values shown here are possibly random and not representative !
97/// let mut req = GoogleCloudBillingBudgetsV1beta1CreateBudgetRequest::default();
98///
99/// // You can configure optional parameters by calling the respective setters at will, and
100/// // execute the final call using `doit()`.
101/// // Values shown here are possibly random and not representative !
102/// let result = hub.billing_accounts().budgets_create(req, "parent")
103///              .doit().await;
104///
105/// match result {
106///     Err(e) => match e {
107///         // The Error enum provides details about what exactly happened.
108///         // You can also just use its `Debug`, `Display` or `Error` traits
109///          Error::HttpError(_)
110///         |Error::Io(_)
111///         |Error::MissingAPIKey
112///         |Error::MissingToken(_)
113///         |Error::Cancelled
114///         |Error::UploadSizeLimitExceeded(_, _)
115///         |Error::Failure(_)
116///         |Error::BadRequest(_)
117///         |Error::FieldClash(_)
118///         |Error::JsonDecodeError(_, _) => println!("{}", e),
119///     },
120///     Ok(res) => println!("Success: {:?}", res),
121/// }
122/// # }
123/// ```
124#[derive(Clone)]
125pub struct CloudBillingBudget<C> {
126    pub client: common::Client<C>,
127    pub auth: Box<dyn common::GetToken>,
128    _user_agent: String,
129    _base_url: String,
130    _root_url: String,
131}
132
133impl<C> common::Hub for CloudBillingBudget<C> {}
134
135impl<'a, C> CloudBillingBudget<C> {
136    pub fn new<A: 'static + common::GetToken>(
137        client: common::Client<C>,
138        auth: A,
139    ) -> CloudBillingBudget<C> {
140        CloudBillingBudget {
141            client,
142            auth: Box::new(auth),
143            _user_agent: "google-api-rust-client/7.0.0".to_string(),
144            _base_url: "https://billingbudgets.googleapis.com/".to_string(),
145            _root_url: "https://billingbudgets.googleapis.com/".to_string(),
146        }
147    }
148
149    pub fn billing_accounts(&'a self) -> BillingAccountMethods<'a, C> {
150        BillingAccountMethods { hub: self }
151    }
152
153    /// Set the user-agent header field to use in all requests to the server.
154    /// It defaults to `google-api-rust-client/7.0.0`.
155    ///
156    /// Returns the previously set user-agent.
157    pub fn user_agent(&mut self, agent_name: String) -> String {
158        std::mem::replace(&mut self._user_agent, agent_name)
159    }
160
161    /// Set the base url to use in all requests to the server.
162    /// It defaults to `https://billingbudgets.googleapis.com/`.
163    ///
164    /// Returns the previously set base url.
165    pub fn base_url(&mut self, new_base_url: String) -> String {
166        std::mem::replace(&mut self._base_url, new_base_url)
167    }
168
169    /// Set the root url to use in all requests to the server.
170    /// It defaults to `https://billingbudgets.googleapis.com/`.
171    ///
172    /// Returns the previously set root url.
173    pub fn root_url(&mut self, new_root_url: String) -> String {
174        std::mem::replace(&mut self._root_url, new_root_url)
175    }
176}
177
178// ############
179// SCHEMAS ###
180// ##########
181/// AllUpdatesRule defines notifications that are sent based on budget spend and thresholds.
182///
183/// This type is not used in any activity, and only used as *part* of another schema.
184///
185#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
186#[serde_with::serde_as]
187#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
188pub struct GoogleCloudBillingBudgetsV1beta1AllUpdatesRule {
189    /// Optional. When set to true, disables default notifications sent when a threshold is exceeded. Default notifications are sent to those with Billing Account Administrator and Billing Account User IAM roles for the target account.
190    #[serde(rename = "disableDefaultIamRecipients")]
191    pub disable_default_iam_recipients: Option<bool>,
192    /// Optional. When set to true, and when the budget has a single project configured, notifications will be sent to project level recipients of that project. This field will be ignored if the budget has multiple or no project configured. Currently, project level recipients are the users with `Owner` role on a cloud project.
193    #[serde(rename = "enableProjectLevelRecipients")]
194    pub enable_project_level_recipients: Option<bool>,
195    /// Optional. Targets to send notifications to when a threshold is exceeded. This is in addition to default recipients who have billing account IAM roles. The value is the full REST resource name of a monitoring notification channel with the form `projects/{project_id}/notificationChannels/{channel_id}`. A maximum of 5 channels are allowed. See https://cloud.google.com/billing/docs/how-to/budgets-notification-recipients for more details.
196    #[serde(rename = "monitoringNotificationChannels")]
197    pub monitoring_notification_channels: Option<Vec<String>>,
198    /// Optional. The name of the Pub/Sub topic where budget related messages will be published, in the form `projects/{project_id}/topics/{topic_id}`. Updates are sent at regular intervals to the topic. The topic needs to be created before the budget is created; see https://cloud.google.com/billing/docs/how-to/budgets-programmatic-notifications for more details. Caller is expected to have `pubsub.topics.setIamPolicy` permission on the topic when it's set for a budget, otherwise, the API call will fail with PERMISSION_DENIED. See https://cloud.google.com/billing/docs/how-to/budgets-programmatic-notifications#permissions_required_for_this_task for more details on Pub/Sub roles and permissions.
199    #[serde(rename = "pubsubTopic")]
200    pub pubsub_topic: Option<String>,
201    /// Optional. Required when AllUpdatesRule.pubsub_topic is set. The schema version of the notification sent to AllUpdatesRule.pubsub_topic. Only "1.0" is accepted. It represents the JSON schema as defined in https://cloud.google.com/billing/docs/how-to/budgets-programmatic-notifications#notification_format.
202    #[serde(rename = "schemaVersion")]
203    pub schema_version: Option<String>,
204}
205
206impl common::Part for GoogleCloudBillingBudgetsV1beta1AllUpdatesRule {}
207
208/// A budget is a plan that describes what you expect to spend on Cloud projects, plus the rules to execute as spend is tracked against that plan, (for example, send an alert when 90% of the target spend is met). The budget time period is configurable, with options such as month (default), quarter, year, or custom time period.
209///
210/// # Activities
211///
212/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
213/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
214///
215/// * [budgets create billing accounts](BillingAccountBudgetCreateCall) (response)
216/// * [budgets get billing accounts](BillingAccountBudgetGetCall) (response)
217/// * [budgets patch billing accounts](BillingAccountBudgetPatchCall) (response)
218#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
219#[serde_with::serde_as]
220#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
221pub struct GoogleCloudBillingBudgetsV1beta1Budget {
222    /// Optional. Rules to apply to notifications sent based on budget spend and thresholds.
223    #[serde(rename = "allUpdatesRule")]
224    pub all_updates_rule: Option<GoogleCloudBillingBudgetsV1beta1AllUpdatesRule>,
225    /// Required. Budgeted amount.
226    pub amount: Option<GoogleCloudBillingBudgetsV1beta1BudgetAmount>,
227    /// Optional. Filters that define which resources are used to compute the actual spend against the budget amount, such as projects, services, and the budget's time period, as well as other filters.
228    #[serde(rename = "budgetFilter")]
229    pub budget_filter: Option<GoogleCloudBillingBudgetsV1beta1Filter>,
230    /// User data for display name in UI. Validation: <= 60 chars.
231    #[serde(rename = "displayName")]
232    pub display_name: Option<String>,
233    /// Optional. Etag to validate that the object is unchanged for a read-modify-write operation. An empty etag will cause an update to overwrite other changes.
234    pub etag: Option<String>,
235    /// Output only. Resource name of the budget. The resource name implies the scope of a budget. Values are of the form `billingAccounts/{billingAccountId}/budgets/{budgetId}`.
236    pub name: Option<String>,
237    /// no description provided
238    #[serde(rename = "ownershipScope")]
239    pub ownership_scope: Option<String>,
240    /// Optional. Rules that trigger alerts (notifications of thresholds being crossed) when spend exceeds the specified percentages of the budget. Optional for `pubsubTopic` notifications. Required if using email notifications.
241    #[serde(rename = "thresholdRules")]
242    pub threshold_rules: Option<Vec<GoogleCloudBillingBudgetsV1beta1ThresholdRule>>,
243}
244
245impl common::ResponseResult for GoogleCloudBillingBudgetsV1beta1Budget {}
246
247/// The budgeted amount for each usage period.
248///
249/// This type is not used in any activity, and only used as *part* of another schema.
250///
251#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
252#[serde_with::serde_as]
253#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
254pub struct GoogleCloudBillingBudgetsV1beta1BudgetAmount {
255    /// Use the last period's actual spend as the budget for the present period. LastPeriodAmount can only be set when the budget's time period is a Filter.calendar_period. It cannot be set in combination with Filter.custom_period.
256    #[serde(rename = "lastPeriodAmount")]
257    pub last_period_amount: Option<GoogleCloudBillingBudgetsV1beta1LastPeriodAmount>,
258    /// A specified amount to use as the budget. `currency_code` is optional. If specified when creating a budget, it must match the currency of the billing account. If specified when updating a budget, it must match the currency_code of the existing budget. The `currency_code` is provided on output.
259    #[serde(rename = "specifiedAmount")]
260    pub specified_amount: Option<GoogleTypeMoney>,
261}
262
263impl common::Part for GoogleCloudBillingBudgetsV1beta1BudgetAmount {}
264
265/// Request for CreateBudget
266///
267/// # Activities
268///
269/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
270/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
271///
272/// * [budgets create billing accounts](BillingAccountBudgetCreateCall) (request)
273#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
274#[serde_with::serde_as]
275#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
276pub struct GoogleCloudBillingBudgetsV1beta1CreateBudgetRequest {
277    /// Required. Budget to create.
278    pub budget: Option<GoogleCloudBillingBudgetsV1beta1Budget>,
279}
280
281impl common::RequestValue for GoogleCloudBillingBudgetsV1beta1CreateBudgetRequest {}
282
283/// All date times begin at 12 AM US and Canadian Pacific Time (UTC-8).
284///
285/// This type is not used in any activity, and only used as *part* of another schema.
286///
287#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
288#[serde_with::serde_as]
289#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
290pub struct GoogleCloudBillingBudgetsV1beta1CustomPeriod {
291    /// Optional. The end date of the time period. Budgets with elapsed end date won't be processed. If unset, specifies to track all usage incurred since the start_date.
292    #[serde(rename = "endDate")]
293    pub end_date: Option<GoogleTypeDate>,
294    /// Required. The start date must be after January 1, 2017.
295    #[serde(rename = "startDate")]
296    pub start_date: Option<GoogleTypeDate>,
297}
298
299impl common::Part for GoogleCloudBillingBudgetsV1beta1CustomPeriod {}
300
301/// A filter for a budget, limiting the scope of the cost to calculate.
302///
303/// This type is not used in any activity, and only used as *part* of another schema.
304///
305#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
306#[serde_with::serde_as]
307#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
308pub struct GoogleCloudBillingBudgetsV1beta1Filter {
309    /// Optional. Specifies to track usage for recurring calendar period. For example, assume that CalendarPeriod.QUARTER is set. The budget will track usage from April 1 to June 30, when the current calendar month is April, May, June. After that, it will track usage from July 1 to September 30 when the current calendar month is July, August, September, so on.
310    #[serde(rename = "calendarPeriod")]
311    pub calendar_period: Option<String>,
312    /// Optional. If Filter.credit_types_treatment is INCLUDE_SPECIFIED_CREDITS, this is a list of credit types to be subtracted from gross cost to determine the spend for threshold calculations. See [a list of acceptable credit type values](https://cloud.google.com/billing/docs/how-to/export-data-bigquery-tables#credits-type). If Filter.credit_types_treatment is **not** INCLUDE_SPECIFIED_CREDITS, this field must be empty.
313    #[serde(rename = "creditTypes")]
314    pub credit_types: Option<Vec<String>>,
315    /// Optional. If not set, default behavior is `INCLUDE_ALL_CREDITS`.
316    #[serde(rename = "creditTypesTreatment")]
317    pub credit_types_treatment: Option<String>,
318    /// Optional. Specifies to track usage from any start date (required) to any end date (optional). This time period is static, it does not recur.
319    #[serde(rename = "customPeriod")]
320    pub custom_period: Option<GoogleCloudBillingBudgetsV1beta1CustomPeriod>,
321    /// Optional. A single label and value pair specifying that usage from only this set of labeled resources should be included in the budget. If omitted, the report will include all labeled and unlabeled usage. An object containing a single `"key": value` pair. Example: `{ "name": "wrench" }`. _Currently, multiple entries or multiple values per entry are not allowed._
322    pub labels: Option<HashMap<String, Vec<serde_json::Value>>>,
323    /// Optional. A set of projects of the form `projects/{project}`, specifying that usage from only this set of projects should be included in the budget. If omitted, the report will include all usage for the billing account, regardless of which project the usage occurred on.
324    pub projects: Option<Vec<String>>,
325    /// Optional. A set of folder and organization names of the form `folders/{folderId}` or `organizations/{organizationId}`, specifying that usage from only this set of folders and organizations should be included in the budget. If omitted, the budget includes all usage that the billing account pays for. If the folder or organization contains projects that are paid for by a different Cloud Billing account, the budget *doesn't* apply to those projects.
326    #[serde(rename = "resourceAncestors")]
327    pub resource_ancestors: Option<Vec<String>>,
328    /// Optional. A set of services of the form `services/{service_id}`, specifying that usage from only this set of services should be included in the budget. If omitted, the report will include usage for all the services. The service names are available through the Catalog API: https://cloud.google.com/billing/v1/how-tos/catalog-api.
329    pub services: Option<Vec<String>>,
330    /// Optional. A set of subaccounts of the form `billingAccounts/{account_id}`, specifying that usage from only this set of subaccounts should be included in the budget. If a subaccount is set to the name of the parent account, usage from the parent account will be included. If omitted, the report will include usage from the parent account and all subaccounts, if they exist.
331    pub subaccounts: Option<Vec<String>>,
332}
333
334impl common::Part for GoogleCloudBillingBudgetsV1beta1Filter {}
335
336/// Describes a budget amount targeted to the last Filter.calendar_period spend. At this time, the amount is automatically 100% of the last calendar period's spend; that is, there are no other options yet. Future configuration options will be described here (for example, configuring a percentage of last period's spend). LastPeriodAmount cannot be set for a budget configured with a Filter.custom_period.
337///
338/// This type is not used in any activity, and only used as *part* of another schema.
339///
340#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
341#[serde_with::serde_as]
342#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
343pub struct GoogleCloudBillingBudgetsV1beta1LastPeriodAmount {
344    _never_set: Option<bool>,
345}
346
347impl common::Part for GoogleCloudBillingBudgetsV1beta1LastPeriodAmount {}
348
349/// Response for ListBudgets
350///
351/// # Activities
352///
353/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
354/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
355///
356/// * [budgets list billing accounts](BillingAccountBudgetListCall) (response)
357#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
358#[serde_with::serde_as]
359#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
360pub struct GoogleCloudBillingBudgetsV1beta1ListBudgetsResponse {
361    /// List of the budgets owned by the requested billing account.
362    pub budgets: Option<Vec<GoogleCloudBillingBudgetsV1beta1Budget>>,
363    /// If not empty, indicates that there may be more budgets that match the request; this value should be passed in a new `ListBudgetsRequest`.
364    #[serde(rename = "nextPageToken")]
365    pub next_page_token: Option<String>,
366}
367
368impl common::ResponseResult for GoogleCloudBillingBudgetsV1beta1ListBudgetsResponse {}
369
370/// ThresholdRule contains the definition of a threshold. Threshold rules define the triggering events used to generate a budget notification email. When a threshold is crossed (spend exceeds the specified percentages of the budget), budget alert emails are sent to the email recipients you specify in the [NotificationsRule](#notificationsrule). Threshold rules also affect the fields included in the [JSON data object](https://cloud.google.com/billing/docs/how-to/budgets-programmatic-notifications#notification_format) sent to a Pub/Sub topic. Threshold rules are *required* if using email notifications. Threshold rules are *optional* if only setting a [`pubsubTopic` NotificationsRule](#NotificationsRule), unless you want your JSON data object to include data about the thresholds you set. For more information, see [set budget threshold rules and actions](https://cloud.google.com/billing/docs/how-to/budgets#budget-actions).
371///
372/// This type is not used in any activity, and only used as *part* of another schema.
373#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
374#[serde_with::serde_as]
375#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
376pub struct GoogleCloudBillingBudgetsV1beta1ThresholdRule {
377    /// Optional. The type of basis used to determine if spend has passed the threshold. Behavior defaults to CURRENT_SPEND if not set.
378    #[serde(rename = "spendBasis")]
379    pub spend_basis: Option<String>,
380    /// Required. Send an alert when this threshold is exceeded. This is a 1.0-based percentage, so 0.5 = 50%. Validation: non-negative number.
381    #[serde(rename = "thresholdPercent")]
382    pub threshold_percent: Option<f64>,
383}
384
385impl common::Part for GoogleCloudBillingBudgetsV1beta1ThresholdRule {}
386
387/// Request for UpdateBudget
388///
389/// # Activities
390///
391/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
392/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
393///
394/// * [budgets patch billing accounts](BillingAccountBudgetPatchCall) (request)
395#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
396#[serde_with::serde_as]
397#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
398pub struct GoogleCloudBillingBudgetsV1beta1UpdateBudgetRequest {
399    /// Required. The updated budget object. The budget to update is specified by the budget name in the budget.
400    pub budget: Option<GoogleCloudBillingBudgetsV1beta1Budget>,
401    /// Optional. Indicates which fields in the provided budget to update. Read-only fields (such as `name`) cannot be changed. If this is not provided, then only fields with non-default values from the request are updated. See https://developers.google.com/protocol-buffers/docs/proto3#default for more details about default values.
402    #[serde(rename = "updateMask")]
403    pub update_mask: Option<common::FieldMask>,
404}
405
406impl common::RequestValue for GoogleCloudBillingBudgetsV1beta1UpdateBudgetRequest {}
407
408/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); }
409///
410/// # Activities
411///
412/// This type is used in activities, which are methods you may call on this type or where this type is involved in.
413/// The list links the activity name, along with information about where it is used (one of *request* and *response*).
414///
415/// * [budgets delete billing accounts](BillingAccountBudgetDeleteCall) (response)
416#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
417#[serde_with::serde_as]
418#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
419pub struct GoogleProtobufEmpty {
420    _never_set: Option<bool>,
421}
422
423impl common::ResponseResult for GoogleProtobufEmpty {}
424
425/// Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp
426///
427/// This type is not used in any activity, and only used as *part* of another schema.
428///
429#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
430#[serde_with::serde_as]
431#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
432pub struct GoogleTypeDate {
433    /// Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant.
434    pub day: Option<i32>,
435    /// Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day.
436    pub month: Option<i32>,
437    /// Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year.
438    pub year: Option<i32>,
439}
440
441impl common::Part for GoogleTypeDate {}
442
443/// Represents an amount of money with its currency type.
444///
445/// This type is not used in any activity, and only used as *part* of another schema.
446///
447#[cfg_attr(feature = "utoipa", derive(utoipa::ToSchema))]
448#[serde_with::serde_as]
449#[derive(Default, Clone, Debug, serde::Serialize, serde::Deserialize)]
450pub struct GoogleTypeMoney {
451    /// The three-letter currency code defined in ISO 4217.
452    #[serde(rename = "currencyCode")]
453    pub currency_code: Option<String>,
454    /// Number of nano (10^-9) units of the amount. The value must be between -999,999,999 and +999,999,999 inclusive. If `units` is positive, `nanos` must be positive or zero. If `units` is zero, `nanos` can be positive, zero, or negative. If `units` is negative, `nanos` must be negative or zero. For example $-1.75 is represented as `units`=-1 and `nanos`=-750,000,000.
455    pub nanos: Option<i32>,
456    /// The whole units of the amount. For example if `currencyCode` is `"USD"`, then 1 unit is one US dollar.
457    #[serde_as(as = "Option<serde_with::DisplayFromStr>")]
458    pub units: Option<i64>,
459}
460
461impl common::Part for GoogleTypeMoney {}
462
463// ###################
464// MethodBuilders ###
465// #################
466
467/// A builder providing access to all methods supported on *billingAccount* resources.
468/// It is not used directly, but through the [`CloudBillingBudget`] hub.
469///
470/// # Example
471///
472/// Instantiate a resource builder
473///
474/// ```test_harness,no_run
475/// extern crate hyper;
476/// extern crate hyper_rustls;
477/// extern crate google_billingbudgets1_beta1 as billingbudgets1_beta1;
478///
479/// # async fn dox() {
480/// use billingbudgets1_beta1::{CloudBillingBudget, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
481///
482/// let secret: yup_oauth2::ApplicationSecret = Default::default();
483/// let connector = hyper_rustls::HttpsConnectorBuilder::new()
484///     .with_native_roots()
485///     .unwrap()
486///     .https_only()
487///     .enable_http2()
488///     .build();
489///
490/// let executor = hyper_util::rt::TokioExecutor::new();
491/// let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
492///     secret,
493///     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
494///     yup_oauth2::client::CustomHyperClientBuilder::from(
495///         hyper_util::client::legacy::Client::builder(executor).build(connector),
496///     ),
497/// ).build().await.unwrap();
498///
499/// let client = hyper_util::client::legacy::Client::builder(
500///     hyper_util::rt::TokioExecutor::new()
501/// )
502/// .build(
503///     hyper_rustls::HttpsConnectorBuilder::new()
504///         .with_native_roots()
505///         .unwrap()
506///         .https_or_http()
507///         .enable_http2()
508///         .build()
509/// );
510/// let mut hub = CloudBillingBudget::new(client, auth);
511/// // Usually you wouldn't bind this to a variable, but keep calling *CallBuilders*
512/// // like `budgets_create(...)`, `budgets_delete(...)`, `budgets_get(...)`, `budgets_list(...)` and `budgets_patch(...)`
513/// // to build up your call.
514/// let rb = hub.billing_accounts();
515/// # }
516/// ```
517pub struct BillingAccountMethods<'a, C>
518where
519    C: 'a,
520{
521    hub: &'a CloudBillingBudget<C>,
522}
523
524impl<'a, C> common::MethodsBuilder for BillingAccountMethods<'a, C> {}
525
526impl<'a, C> BillingAccountMethods<'a, C> {
527    /// Create a builder to help you perform the following task:
528    ///
529    /// Creates a new budget. See [Quotas and limits](https://cloud.google.com/billing/quotas) for more information on the limits of the number of budgets you can create.
530    ///
531    /// # Arguments
532    ///
533    /// * `request` - No description provided.
534    /// * `parent` - Required. The name of the billing account to create the budget in. Values are of the form `billingAccounts/{billingAccountId}`.
535    pub fn budgets_create(
536        &self,
537        request: GoogleCloudBillingBudgetsV1beta1CreateBudgetRequest,
538        parent: &str,
539    ) -> BillingAccountBudgetCreateCall<'a, C> {
540        BillingAccountBudgetCreateCall {
541            hub: self.hub,
542            _request: request,
543            _parent: parent.to_string(),
544            _delegate: Default::default(),
545            _additional_params: Default::default(),
546            _scopes: Default::default(),
547        }
548    }
549
550    /// Create a builder to help you perform the following task:
551    ///
552    /// Deletes a budget. Returns successfully if already deleted.
553    ///
554    /// # Arguments
555    ///
556    /// * `name` - Required. Name of the budget to delete. Values are of the form `billingAccounts/{billingAccountId}/budgets/{budgetId}`.
557    pub fn budgets_delete(&self, name: &str) -> BillingAccountBudgetDeleteCall<'a, C> {
558        BillingAccountBudgetDeleteCall {
559            hub: self.hub,
560            _name: name.to_string(),
561            _delegate: Default::default(),
562            _additional_params: Default::default(),
563            _scopes: Default::default(),
564        }
565    }
566
567    /// Create a builder to help you perform the following task:
568    ///
569    /// Returns a budget. WARNING: There are some fields exposed on the Google Cloud Console that aren't available on this API. When reading from the API, you will not see these fields in the return value, though they may have been set in the Cloud Console.
570    ///
571    /// # Arguments
572    ///
573    /// * `name` - Required. Name of budget to get. Values are of the form `billingAccounts/{billingAccountId}/budgets/{budgetId}`.
574    pub fn budgets_get(&self, name: &str) -> BillingAccountBudgetGetCall<'a, C> {
575        BillingAccountBudgetGetCall {
576            hub: self.hub,
577            _name: name.to_string(),
578            _delegate: Default::default(),
579            _additional_params: Default::default(),
580            _scopes: Default::default(),
581        }
582    }
583
584    /// Create a builder to help you perform the following task:
585    ///
586    /// Returns a list of budgets for a billing account. WARNING: There are some fields exposed on the Google Cloud Console that aren't available on this API. When reading from the API, you will not see these fields in the return value, though they may have been set in the Cloud Console.
587    ///
588    /// # Arguments
589    ///
590    /// * `parent` - Required. Name of billing account to list budgets under. Values are of the form `billingAccounts/{billingAccountId}`.
591    pub fn budgets_list(&self, parent: &str) -> BillingAccountBudgetListCall<'a, C> {
592        BillingAccountBudgetListCall {
593            hub: self.hub,
594            _parent: parent.to_string(),
595            _scope: Default::default(),
596            _page_token: Default::default(),
597            _page_size: Default::default(),
598            _delegate: Default::default(),
599            _additional_params: Default::default(),
600            _scopes: Default::default(),
601        }
602    }
603
604    /// Create a builder to help you perform the following task:
605    ///
606    /// Updates a budget and returns the updated budget. WARNING: There are some fields exposed on the Google Cloud Console that aren't available on this API. Budget fields that are not exposed in this API will not be changed by this method.
607    ///
608    /// # Arguments
609    ///
610    /// * `request` - No description provided.
611    /// * `name` - Output only. Resource name of the budget. The resource name implies the scope of a budget. Values are of the form `billingAccounts/{billingAccountId}/budgets/{budgetId}`.
612    pub fn budgets_patch(
613        &self,
614        request: GoogleCloudBillingBudgetsV1beta1UpdateBudgetRequest,
615        name: &str,
616    ) -> BillingAccountBudgetPatchCall<'a, C> {
617        BillingAccountBudgetPatchCall {
618            hub: self.hub,
619            _request: request,
620            _name: name.to_string(),
621            _delegate: Default::default(),
622            _additional_params: Default::default(),
623            _scopes: Default::default(),
624        }
625    }
626}
627
628// ###################
629// CallBuilders   ###
630// #################
631
632/// Creates a new budget. See [Quotas and limits](https://cloud.google.com/billing/quotas) for more information on the limits of the number of budgets you can create.
633///
634/// A builder for the *budgets.create* method supported by a *billingAccount* resource.
635/// It is not used directly, but through a [`BillingAccountMethods`] instance.
636///
637/// # Example
638///
639/// Instantiate a resource method builder
640///
641/// ```test_harness,no_run
642/// # extern crate hyper;
643/// # extern crate hyper_rustls;
644/// # extern crate google_billingbudgets1_beta1 as billingbudgets1_beta1;
645/// use billingbudgets1_beta1::api::GoogleCloudBillingBudgetsV1beta1CreateBudgetRequest;
646/// # async fn dox() {
647/// # use billingbudgets1_beta1::{CloudBillingBudget, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
648///
649/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
650/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
651/// #     .with_native_roots()
652/// #     .unwrap()
653/// #     .https_only()
654/// #     .enable_http2()
655/// #     .build();
656///
657/// # let executor = hyper_util::rt::TokioExecutor::new();
658/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
659/// #     secret,
660/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
661/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
662/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
663/// #     ),
664/// # ).build().await.unwrap();
665///
666/// # let client = hyper_util::client::legacy::Client::builder(
667/// #     hyper_util::rt::TokioExecutor::new()
668/// # )
669/// # .build(
670/// #     hyper_rustls::HttpsConnectorBuilder::new()
671/// #         .with_native_roots()
672/// #         .unwrap()
673/// #         .https_or_http()
674/// #         .enable_http2()
675/// #         .build()
676/// # );
677/// # let mut hub = CloudBillingBudget::new(client, auth);
678/// // As the method needs a request, you would usually fill it with the desired information
679/// // into the respective structure. Some of the parts shown here might not be applicable !
680/// // Values shown here are possibly random and not representative !
681/// let mut req = GoogleCloudBillingBudgetsV1beta1CreateBudgetRequest::default();
682///
683/// // You can configure optional parameters by calling the respective setters at will, and
684/// // execute the final call using `doit()`.
685/// // Values shown here are possibly random and not representative !
686/// let result = hub.billing_accounts().budgets_create(req, "parent")
687///              .doit().await;
688/// # }
689/// ```
690pub struct BillingAccountBudgetCreateCall<'a, C>
691where
692    C: 'a,
693{
694    hub: &'a CloudBillingBudget<C>,
695    _request: GoogleCloudBillingBudgetsV1beta1CreateBudgetRequest,
696    _parent: String,
697    _delegate: Option<&'a mut dyn common::Delegate>,
698    _additional_params: HashMap<String, String>,
699    _scopes: BTreeSet<String>,
700}
701
702impl<'a, C> common::CallBuilder for BillingAccountBudgetCreateCall<'a, C> {}
703
704impl<'a, C> BillingAccountBudgetCreateCall<'a, C>
705where
706    C: common::Connector,
707{
708    /// Perform the operation you have build so far.
709    pub async fn doit(
710        mut self,
711    ) -> common::Result<(common::Response, GoogleCloudBillingBudgetsV1beta1Budget)> {
712        use std::borrow::Cow;
713        use std::io::{Read, Seek};
714
715        use common::{url::Params, ToParts};
716        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
717
718        let mut dd = common::DefaultDelegate;
719        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
720        dlg.begin(common::MethodInfo {
721            id: "billingbudgets.billingAccounts.budgets.create",
722            http_method: hyper::Method::POST,
723        });
724
725        for &field in ["alt", "parent"].iter() {
726            if self._additional_params.contains_key(field) {
727                dlg.finished(false);
728                return Err(common::Error::FieldClash(field));
729            }
730        }
731
732        let mut params = Params::with_capacity(4 + self._additional_params.len());
733        params.push("parent", self._parent);
734
735        params.extend(self._additional_params.iter());
736
737        params.push("alt", "json");
738        let mut url = self.hub._base_url.clone() + "v1beta1/{+parent}/budgets";
739        if self._scopes.is_empty() {
740            self._scopes
741                .insert(Scope::CloudPlatform.as_ref().to_string());
742        }
743
744        #[allow(clippy::single_element_loop)]
745        for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
746            url = params.uri_replacement(url, param_name, find_this, true);
747        }
748        {
749            let to_remove = ["parent"];
750            params.remove_params(&to_remove);
751        }
752
753        let url = params.parse_with_url(&url);
754
755        let mut json_mime_type = mime::APPLICATION_JSON;
756        let mut request_value_reader = {
757            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
758            common::remove_json_null_values(&mut value);
759            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
760            serde_json::to_writer(&mut dst, &value).unwrap();
761            dst
762        };
763        let request_size = request_value_reader
764            .seek(std::io::SeekFrom::End(0))
765            .unwrap();
766        request_value_reader
767            .seek(std::io::SeekFrom::Start(0))
768            .unwrap();
769
770        loop {
771            let token = match self
772                .hub
773                .auth
774                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
775                .await
776            {
777                Ok(token) => token,
778                Err(e) => match dlg.token(e) {
779                    Ok(token) => token,
780                    Err(e) => {
781                        dlg.finished(false);
782                        return Err(common::Error::MissingToken(e));
783                    }
784                },
785            };
786            request_value_reader
787                .seek(std::io::SeekFrom::Start(0))
788                .unwrap();
789            let mut req_result = {
790                let client = &self.hub.client;
791                dlg.pre_request();
792                let mut req_builder = hyper::Request::builder()
793                    .method(hyper::Method::POST)
794                    .uri(url.as_str())
795                    .header(USER_AGENT, self.hub._user_agent.clone());
796
797                if let Some(token) = token.as_ref() {
798                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
799                }
800
801                let request = req_builder
802                    .header(CONTENT_TYPE, json_mime_type.to_string())
803                    .header(CONTENT_LENGTH, request_size as u64)
804                    .body(common::to_body(
805                        request_value_reader.get_ref().clone().into(),
806                    ));
807
808                client.request(request.unwrap()).await
809            };
810
811            match req_result {
812                Err(err) => {
813                    if let common::Retry::After(d) = dlg.http_error(&err) {
814                        sleep(d).await;
815                        continue;
816                    }
817                    dlg.finished(false);
818                    return Err(common::Error::HttpError(err));
819                }
820                Ok(res) => {
821                    let (mut parts, body) = res.into_parts();
822                    let mut body = common::Body::new(body);
823                    if !parts.status.is_success() {
824                        let bytes = common::to_bytes(body).await.unwrap_or_default();
825                        let error = serde_json::from_str(&common::to_string(&bytes));
826                        let response = common::to_response(parts, bytes.into());
827
828                        if let common::Retry::After(d) =
829                            dlg.http_failure(&response, error.as_ref().ok())
830                        {
831                            sleep(d).await;
832                            continue;
833                        }
834
835                        dlg.finished(false);
836
837                        return Err(match error {
838                            Ok(value) => common::Error::BadRequest(value),
839                            _ => common::Error::Failure(response),
840                        });
841                    }
842                    let response = {
843                        let bytes = common::to_bytes(body).await.unwrap_or_default();
844                        let encoded = common::to_string(&bytes);
845                        match serde_json::from_str(&encoded) {
846                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
847                            Err(error) => {
848                                dlg.response_json_decode_error(&encoded, &error);
849                                return Err(common::Error::JsonDecodeError(
850                                    encoded.to_string(),
851                                    error,
852                                ));
853                            }
854                        }
855                    };
856
857                    dlg.finished(true);
858                    return Ok(response);
859                }
860            }
861        }
862    }
863
864    ///
865    /// Sets the *request* property to the given value.
866    ///
867    /// Even though the property as already been set when instantiating this call,
868    /// we provide this method for API completeness.
869    pub fn request(
870        mut self,
871        new_value: GoogleCloudBillingBudgetsV1beta1CreateBudgetRequest,
872    ) -> BillingAccountBudgetCreateCall<'a, C> {
873        self._request = new_value;
874        self
875    }
876    /// Required. The name of the billing account to create the budget in. Values are of the form `billingAccounts/{billingAccountId}`.
877    ///
878    /// Sets the *parent* path property to the given value.
879    ///
880    /// Even though the property as already been set when instantiating this call,
881    /// we provide this method for API completeness.
882    pub fn parent(mut self, new_value: &str) -> BillingAccountBudgetCreateCall<'a, C> {
883        self._parent = new_value.to_string();
884        self
885    }
886    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
887    /// while executing the actual API request.
888    ///
889    /// ````text
890    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
891    /// ````
892    ///
893    /// Sets the *delegate* property to the given value.
894    pub fn delegate(
895        mut self,
896        new_value: &'a mut dyn common::Delegate,
897    ) -> BillingAccountBudgetCreateCall<'a, C> {
898        self._delegate = Some(new_value);
899        self
900    }
901
902    /// Set any additional parameter of the query string used in the request.
903    /// It should be used to set parameters which are not yet available through their own
904    /// setters.
905    ///
906    /// Please note that this method must not be used to set any of the known parameters
907    /// which have their own setter method. If done anyway, the request will fail.
908    ///
909    /// # Additional Parameters
910    ///
911    /// * *$.xgafv* (query-string) - V1 error format.
912    /// * *access_token* (query-string) - OAuth access token.
913    /// * *alt* (query-string) - Data format for response.
914    /// * *callback* (query-string) - JSONP
915    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
916    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
917    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
918    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
919    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
920    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
921    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
922    pub fn param<T>(mut self, name: T, value: T) -> BillingAccountBudgetCreateCall<'a, C>
923    where
924        T: AsRef<str>,
925    {
926        self._additional_params
927            .insert(name.as_ref().to_string(), value.as_ref().to_string());
928        self
929    }
930
931    /// Identifies the authorization scope for the method you are building.
932    ///
933    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
934    /// [`Scope::CloudPlatform`].
935    ///
936    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
937    /// tokens for more than one scope.
938    ///
939    /// Usually there is more than one suitable scope to authorize an operation, some of which may
940    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
941    /// sufficient, a read-write scope will do as well.
942    pub fn add_scope<St>(mut self, scope: St) -> BillingAccountBudgetCreateCall<'a, C>
943    where
944        St: AsRef<str>,
945    {
946        self._scopes.insert(String::from(scope.as_ref()));
947        self
948    }
949    /// Identifies the authorization scope(s) for the method you are building.
950    ///
951    /// See [`Self::add_scope()`] for details.
952    pub fn add_scopes<I, St>(mut self, scopes: I) -> BillingAccountBudgetCreateCall<'a, C>
953    where
954        I: IntoIterator<Item = St>,
955        St: AsRef<str>,
956    {
957        self._scopes
958            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
959        self
960    }
961
962    /// Removes all scopes, and no default scope will be used either.
963    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
964    /// for details).
965    pub fn clear_scopes(mut self) -> BillingAccountBudgetCreateCall<'a, C> {
966        self._scopes.clear();
967        self
968    }
969}
970
971/// Deletes a budget. Returns successfully if already deleted.
972///
973/// A builder for the *budgets.delete* method supported by a *billingAccount* resource.
974/// It is not used directly, but through a [`BillingAccountMethods`] instance.
975///
976/// # Example
977///
978/// Instantiate a resource method builder
979///
980/// ```test_harness,no_run
981/// # extern crate hyper;
982/// # extern crate hyper_rustls;
983/// # extern crate google_billingbudgets1_beta1 as billingbudgets1_beta1;
984/// # async fn dox() {
985/// # use billingbudgets1_beta1::{CloudBillingBudget, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
986///
987/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
988/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
989/// #     .with_native_roots()
990/// #     .unwrap()
991/// #     .https_only()
992/// #     .enable_http2()
993/// #     .build();
994///
995/// # let executor = hyper_util::rt::TokioExecutor::new();
996/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
997/// #     secret,
998/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
999/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
1000/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
1001/// #     ),
1002/// # ).build().await.unwrap();
1003///
1004/// # let client = hyper_util::client::legacy::Client::builder(
1005/// #     hyper_util::rt::TokioExecutor::new()
1006/// # )
1007/// # .build(
1008/// #     hyper_rustls::HttpsConnectorBuilder::new()
1009/// #         .with_native_roots()
1010/// #         .unwrap()
1011/// #         .https_or_http()
1012/// #         .enable_http2()
1013/// #         .build()
1014/// # );
1015/// # let mut hub = CloudBillingBudget::new(client, auth);
1016/// // You can configure optional parameters by calling the respective setters at will, and
1017/// // execute the final call using `doit()`.
1018/// // Values shown here are possibly random and not representative !
1019/// let result = hub.billing_accounts().budgets_delete("name")
1020///              .doit().await;
1021/// # }
1022/// ```
1023pub struct BillingAccountBudgetDeleteCall<'a, C>
1024where
1025    C: 'a,
1026{
1027    hub: &'a CloudBillingBudget<C>,
1028    _name: String,
1029    _delegate: Option<&'a mut dyn common::Delegate>,
1030    _additional_params: HashMap<String, String>,
1031    _scopes: BTreeSet<String>,
1032}
1033
1034impl<'a, C> common::CallBuilder for BillingAccountBudgetDeleteCall<'a, C> {}
1035
1036impl<'a, C> BillingAccountBudgetDeleteCall<'a, C>
1037where
1038    C: common::Connector,
1039{
1040    /// Perform the operation you have build so far.
1041    pub async fn doit(mut self) -> common::Result<(common::Response, GoogleProtobufEmpty)> {
1042        use std::borrow::Cow;
1043        use std::io::{Read, Seek};
1044
1045        use common::{url::Params, ToParts};
1046        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1047
1048        let mut dd = common::DefaultDelegate;
1049        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1050        dlg.begin(common::MethodInfo {
1051            id: "billingbudgets.billingAccounts.budgets.delete",
1052            http_method: hyper::Method::DELETE,
1053        });
1054
1055        for &field in ["alt", "name"].iter() {
1056            if self._additional_params.contains_key(field) {
1057                dlg.finished(false);
1058                return Err(common::Error::FieldClash(field));
1059            }
1060        }
1061
1062        let mut params = Params::with_capacity(3 + self._additional_params.len());
1063        params.push("name", self._name);
1064
1065        params.extend(self._additional_params.iter());
1066
1067        params.push("alt", "json");
1068        let mut url = self.hub._base_url.clone() + "v1beta1/{+name}";
1069        if self._scopes.is_empty() {
1070            self._scopes
1071                .insert(Scope::CloudPlatform.as_ref().to_string());
1072        }
1073
1074        #[allow(clippy::single_element_loop)]
1075        for &(find_this, param_name) in [("{+name}", "name")].iter() {
1076            url = params.uri_replacement(url, param_name, find_this, true);
1077        }
1078        {
1079            let to_remove = ["name"];
1080            params.remove_params(&to_remove);
1081        }
1082
1083        let url = params.parse_with_url(&url);
1084
1085        loop {
1086            let token = match self
1087                .hub
1088                .auth
1089                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1090                .await
1091            {
1092                Ok(token) => token,
1093                Err(e) => match dlg.token(e) {
1094                    Ok(token) => token,
1095                    Err(e) => {
1096                        dlg.finished(false);
1097                        return Err(common::Error::MissingToken(e));
1098                    }
1099                },
1100            };
1101            let mut req_result = {
1102                let client = &self.hub.client;
1103                dlg.pre_request();
1104                let mut req_builder = hyper::Request::builder()
1105                    .method(hyper::Method::DELETE)
1106                    .uri(url.as_str())
1107                    .header(USER_AGENT, self.hub._user_agent.clone());
1108
1109                if let Some(token) = token.as_ref() {
1110                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1111                }
1112
1113                let request = req_builder
1114                    .header(CONTENT_LENGTH, 0_u64)
1115                    .body(common::to_body::<String>(None));
1116
1117                client.request(request.unwrap()).await
1118            };
1119
1120            match req_result {
1121                Err(err) => {
1122                    if let common::Retry::After(d) = dlg.http_error(&err) {
1123                        sleep(d).await;
1124                        continue;
1125                    }
1126                    dlg.finished(false);
1127                    return Err(common::Error::HttpError(err));
1128                }
1129                Ok(res) => {
1130                    let (mut parts, body) = res.into_parts();
1131                    let mut body = common::Body::new(body);
1132                    if !parts.status.is_success() {
1133                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1134                        let error = serde_json::from_str(&common::to_string(&bytes));
1135                        let response = common::to_response(parts, bytes.into());
1136
1137                        if let common::Retry::After(d) =
1138                            dlg.http_failure(&response, error.as_ref().ok())
1139                        {
1140                            sleep(d).await;
1141                            continue;
1142                        }
1143
1144                        dlg.finished(false);
1145
1146                        return Err(match error {
1147                            Ok(value) => common::Error::BadRequest(value),
1148                            _ => common::Error::Failure(response),
1149                        });
1150                    }
1151                    let response = {
1152                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1153                        let encoded = common::to_string(&bytes);
1154                        match serde_json::from_str(&encoded) {
1155                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1156                            Err(error) => {
1157                                dlg.response_json_decode_error(&encoded, &error);
1158                                return Err(common::Error::JsonDecodeError(
1159                                    encoded.to_string(),
1160                                    error,
1161                                ));
1162                            }
1163                        }
1164                    };
1165
1166                    dlg.finished(true);
1167                    return Ok(response);
1168                }
1169            }
1170        }
1171    }
1172
1173    /// Required. Name of the budget to delete. Values are of the form `billingAccounts/{billingAccountId}/budgets/{budgetId}`.
1174    ///
1175    /// Sets the *name* path property to the given value.
1176    ///
1177    /// Even though the property as already been set when instantiating this call,
1178    /// we provide this method for API completeness.
1179    pub fn name(mut self, new_value: &str) -> BillingAccountBudgetDeleteCall<'a, C> {
1180        self._name = new_value.to_string();
1181        self
1182    }
1183    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1184    /// while executing the actual API request.
1185    ///
1186    /// ````text
1187    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1188    /// ````
1189    ///
1190    /// Sets the *delegate* property to the given value.
1191    pub fn delegate(
1192        mut self,
1193        new_value: &'a mut dyn common::Delegate,
1194    ) -> BillingAccountBudgetDeleteCall<'a, C> {
1195        self._delegate = Some(new_value);
1196        self
1197    }
1198
1199    /// Set any additional parameter of the query string used in the request.
1200    /// It should be used to set parameters which are not yet available through their own
1201    /// setters.
1202    ///
1203    /// Please note that this method must not be used to set any of the known parameters
1204    /// which have their own setter method. If done anyway, the request will fail.
1205    ///
1206    /// # Additional Parameters
1207    ///
1208    /// * *$.xgafv* (query-string) - V1 error format.
1209    /// * *access_token* (query-string) - OAuth access token.
1210    /// * *alt* (query-string) - Data format for response.
1211    /// * *callback* (query-string) - JSONP
1212    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1213    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
1214    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1215    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1216    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1217    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1218    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1219    pub fn param<T>(mut self, name: T, value: T) -> BillingAccountBudgetDeleteCall<'a, C>
1220    where
1221        T: AsRef<str>,
1222    {
1223        self._additional_params
1224            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1225        self
1226    }
1227
1228    /// Identifies the authorization scope for the method you are building.
1229    ///
1230    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1231    /// [`Scope::CloudPlatform`].
1232    ///
1233    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1234    /// tokens for more than one scope.
1235    ///
1236    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1237    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1238    /// sufficient, a read-write scope will do as well.
1239    pub fn add_scope<St>(mut self, scope: St) -> BillingAccountBudgetDeleteCall<'a, C>
1240    where
1241        St: AsRef<str>,
1242    {
1243        self._scopes.insert(String::from(scope.as_ref()));
1244        self
1245    }
1246    /// Identifies the authorization scope(s) for the method you are building.
1247    ///
1248    /// See [`Self::add_scope()`] for details.
1249    pub fn add_scopes<I, St>(mut self, scopes: I) -> BillingAccountBudgetDeleteCall<'a, C>
1250    where
1251        I: IntoIterator<Item = St>,
1252        St: AsRef<str>,
1253    {
1254        self._scopes
1255            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1256        self
1257    }
1258
1259    /// Removes all scopes, and no default scope will be used either.
1260    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1261    /// for details).
1262    pub fn clear_scopes(mut self) -> BillingAccountBudgetDeleteCall<'a, C> {
1263        self._scopes.clear();
1264        self
1265    }
1266}
1267
1268/// Returns a budget. WARNING: There are some fields exposed on the Google Cloud Console that aren't available on this API. When reading from the API, you will not see these fields in the return value, though they may have been set in the Cloud Console.
1269///
1270/// A builder for the *budgets.get* method supported by a *billingAccount* resource.
1271/// It is not used directly, but through a [`BillingAccountMethods`] instance.
1272///
1273/// # Example
1274///
1275/// Instantiate a resource method builder
1276///
1277/// ```test_harness,no_run
1278/// # extern crate hyper;
1279/// # extern crate hyper_rustls;
1280/// # extern crate google_billingbudgets1_beta1 as billingbudgets1_beta1;
1281/// # async fn dox() {
1282/// # use billingbudgets1_beta1::{CloudBillingBudget, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1283///
1284/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1285/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1286/// #     .with_native_roots()
1287/// #     .unwrap()
1288/// #     .https_only()
1289/// #     .enable_http2()
1290/// #     .build();
1291///
1292/// # let executor = hyper_util::rt::TokioExecutor::new();
1293/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1294/// #     secret,
1295/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1296/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
1297/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
1298/// #     ),
1299/// # ).build().await.unwrap();
1300///
1301/// # let client = hyper_util::client::legacy::Client::builder(
1302/// #     hyper_util::rt::TokioExecutor::new()
1303/// # )
1304/// # .build(
1305/// #     hyper_rustls::HttpsConnectorBuilder::new()
1306/// #         .with_native_roots()
1307/// #         .unwrap()
1308/// #         .https_or_http()
1309/// #         .enable_http2()
1310/// #         .build()
1311/// # );
1312/// # let mut hub = CloudBillingBudget::new(client, auth);
1313/// // You can configure optional parameters by calling the respective setters at will, and
1314/// // execute the final call using `doit()`.
1315/// // Values shown here are possibly random and not representative !
1316/// let result = hub.billing_accounts().budgets_get("name")
1317///              .doit().await;
1318/// # }
1319/// ```
1320pub struct BillingAccountBudgetGetCall<'a, C>
1321where
1322    C: 'a,
1323{
1324    hub: &'a CloudBillingBudget<C>,
1325    _name: String,
1326    _delegate: Option<&'a mut dyn common::Delegate>,
1327    _additional_params: HashMap<String, String>,
1328    _scopes: BTreeSet<String>,
1329}
1330
1331impl<'a, C> common::CallBuilder for BillingAccountBudgetGetCall<'a, C> {}
1332
1333impl<'a, C> BillingAccountBudgetGetCall<'a, C>
1334where
1335    C: common::Connector,
1336{
1337    /// Perform the operation you have build so far.
1338    pub async fn doit(
1339        mut self,
1340    ) -> common::Result<(common::Response, GoogleCloudBillingBudgetsV1beta1Budget)> {
1341        use std::borrow::Cow;
1342        use std::io::{Read, Seek};
1343
1344        use common::{url::Params, ToParts};
1345        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1346
1347        let mut dd = common::DefaultDelegate;
1348        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1349        dlg.begin(common::MethodInfo {
1350            id: "billingbudgets.billingAccounts.budgets.get",
1351            http_method: hyper::Method::GET,
1352        });
1353
1354        for &field in ["alt", "name"].iter() {
1355            if self._additional_params.contains_key(field) {
1356                dlg.finished(false);
1357                return Err(common::Error::FieldClash(field));
1358            }
1359        }
1360
1361        let mut params = Params::with_capacity(3 + self._additional_params.len());
1362        params.push("name", self._name);
1363
1364        params.extend(self._additional_params.iter());
1365
1366        params.push("alt", "json");
1367        let mut url = self.hub._base_url.clone() + "v1beta1/{+name}";
1368        if self._scopes.is_empty() {
1369            self._scopes
1370                .insert(Scope::CloudPlatform.as_ref().to_string());
1371        }
1372
1373        #[allow(clippy::single_element_loop)]
1374        for &(find_this, param_name) in [("{+name}", "name")].iter() {
1375            url = params.uri_replacement(url, param_name, find_this, true);
1376        }
1377        {
1378            let to_remove = ["name"];
1379            params.remove_params(&to_remove);
1380        }
1381
1382        let url = params.parse_with_url(&url);
1383
1384        loop {
1385            let token = match self
1386                .hub
1387                .auth
1388                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1389                .await
1390            {
1391                Ok(token) => token,
1392                Err(e) => match dlg.token(e) {
1393                    Ok(token) => token,
1394                    Err(e) => {
1395                        dlg.finished(false);
1396                        return Err(common::Error::MissingToken(e));
1397                    }
1398                },
1399            };
1400            let mut req_result = {
1401                let client = &self.hub.client;
1402                dlg.pre_request();
1403                let mut req_builder = hyper::Request::builder()
1404                    .method(hyper::Method::GET)
1405                    .uri(url.as_str())
1406                    .header(USER_AGENT, self.hub._user_agent.clone());
1407
1408                if let Some(token) = token.as_ref() {
1409                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1410                }
1411
1412                let request = req_builder
1413                    .header(CONTENT_LENGTH, 0_u64)
1414                    .body(common::to_body::<String>(None));
1415
1416                client.request(request.unwrap()).await
1417            };
1418
1419            match req_result {
1420                Err(err) => {
1421                    if let common::Retry::After(d) = dlg.http_error(&err) {
1422                        sleep(d).await;
1423                        continue;
1424                    }
1425                    dlg.finished(false);
1426                    return Err(common::Error::HttpError(err));
1427                }
1428                Ok(res) => {
1429                    let (mut parts, body) = res.into_parts();
1430                    let mut body = common::Body::new(body);
1431                    if !parts.status.is_success() {
1432                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1433                        let error = serde_json::from_str(&common::to_string(&bytes));
1434                        let response = common::to_response(parts, bytes.into());
1435
1436                        if let common::Retry::After(d) =
1437                            dlg.http_failure(&response, error.as_ref().ok())
1438                        {
1439                            sleep(d).await;
1440                            continue;
1441                        }
1442
1443                        dlg.finished(false);
1444
1445                        return Err(match error {
1446                            Ok(value) => common::Error::BadRequest(value),
1447                            _ => common::Error::Failure(response),
1448                        });
1449                    }
1450                    let response = {
1451                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1452                        let encoded = common::to_string(&bytes);
1453                        match serde_json::from_str(&encoded) {
1454                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1455                            Err(error) => {
1456                                dlg.response_json_decode_error(&encoded, &error);
1457                                return Err(common::Error::JsonDecodeError(
1458                                    encoded.to_string(),
1459                                    error,
1460                                ));
1461                            }
1462                        }
1463                    };
1464
1465                    dlg.finished(true);
1466                    return Ok(response);
1467                }
1468            }
1469        }
1470    }
1471
1472    /// Required. Name of budget to get. Values are of the form `billingAccounts/{billingAccountId}/budgets/{budgetId}`.
1473    ///
1474    /// Sets the *name* path property to the given value.
1475    ///
1476    /// Even though the property as already been set when instantiating this call,
1477    /// we provide this method for API completeness.
1478    pub fn name(mut self, new_value: &str) -> BillingAccountBudgetGetCall<'a, C> {
1479        self._name = new_value.to_string();
1480        self
1481    }
1482    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1483    /// while executing the actual API request.
1484    ///
1485    /// ````text
1486    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1487    /// ````
1488    ///
1489    /// Sets the *delegate* property to the given value.
1490    pub fn delegate(
1491        mut self,
1492        new_value: &'a mut dyn common::Delegate,
1493    ) -> BillingAccountBudgetGetCall<'a, C> {
1494        self._delegate = Some(new_value);
1495        self
1496    }
1497
1498    /// Set any additional parameter of the query string used in the request.
1499    /// It should be used to set parameters which are not yet available through their own
1500    /// setters.
1501    ///
1502    /// Please note that this method must not be used to set any of the known parameters
1503    /// which have their own setter method. If done anyway, the request will fail.
1504    ///
1505    /// # Additional Parameters
1506    ///
1507    /// * *$.xgafv* (query-string) - V1 error format.
1508    /// * *access_token* (query-string) - OAuth access token.
1509    /// * *alt* (query-string) - Data format for response.
1510    /// * *callback* (query-string) - JSONP
1511    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1512    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
1513    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1514    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1515    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1516    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1517    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1518    pub fn param<T>(mut self, name: T, value: T) -> BillingAccountBudgetGetCall<'a, C>
1519    where
1520        T: AsRef<str>,
1521    {
1522        self._additional_params
1523            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1524        self
1525    }
1526
1527    /// Identifies the authorization scope for the method you are building.
1528    ///
1529    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1530    /// [`Scope::CloudPlatform`].
1531    ///
1532    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1533    /// tokens for more than one scope.
1534    ///
1535    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1536    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1537    /// sufficient, a read-write scope will do as well.
1538    pub fn add_scope<St>(mut self, scope: St) -> BillingAccountBudgetGetCall<'a, C>
1539    where
1540        St: AsRef<str>,
1541    {
1542        self._scopes.insert(String::from(scope.as_ref()));
1543        self
1544    }
1545    /// Identifies the authorization scope(s) for the method you are building.
1546    ///
1547    /// See [`Self::add_scope()`] for details.
1548    pub fn add_scopes<I, St>(mut self, scopes: I) -> BillingAccountBudgetGetCall<'a, C>
1549    where
1550        I: IntoIterator<Item = St>,
1551        St: AsRef<str>,
1552    {
1553        self._scopes
1554            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1555        self
1556    }
1557
1558    /// Removes all scopes, and no default scope will be used either.
1559    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1560    /// for details).
1561    pub fn clear_scopes(mut self) -> BillingAccountBudgetGetCall<'a, C> {
1562        self._scopes.clear();
1563        self
1564    }
1565}
1566
1567/// Returns a list of budgets for a billing account. WARNING: There are some fields exposed on the Google Cloud Console that aren't available on this API. When reading from the API, you will not see these fields in the return value, though they may have been set in the Cloud Console.
1568///
1569/// A builder for the *budgets.list* method supported by a *billingAccount* resource.
1570/// It is not used directly, but through a [`BillingAccountMethods`] instance.
1571///
1572/// # Example
1573///
1574/// Instantiate a resource method builder
1575///
1576/// ```test_harness,no_run
1577/// # extern crate hyper;
1578/// # extern crate hyper_rustls;
1579/// # extern crate google_billingbudgets1_beta1 as billingbudgets1_beta1;
1580/// # async fn dox() {
1581/// # use billingbudgets1_beta1::{CloudBillingBudget, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1582///
1583/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1584/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1585/// #     .with_native_roots()
1586/// #     .unwrap()
1587/// #     .https_only()
1588/// #     .enable_http2()
1589/// #     .build();
1590///
1591/// # let executor = hyper_util::rt::TokioExecutor::new();
1592/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1593/// #     secret,
1594/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1595/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
1596/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
1597/// #     ),
1598/// # ).build().await.unwrap();
1599///
1600/// # let client = hyper_util::client::legacy::Client::builder(
1601/// #     hyper_util::rt::TokioExecutor::new()
1602/// # )
1603/// # .build(
1604/// #     hyper_rustls::HttpsConnectorBuilder::new()
1605/// #         .with_native_roots()
1606/// #         .unwrap()
1607/// #         .https_or_http()
1608/// #         .enable_http2()
1609/// #         .build()
1610/// # );
1611/// # let mut hub = CloudBillingBudget::new(client, auth);
1612/// // You can configure optional parameters by calling the respective setters at will, and
1613/// // execute the final call using `doit()`.
1614/// // Values shown here are possibly random and not representative !
1615/// let result = hub.billing_accounts().budgets_list("parent")
1616///              .scope("sed")
1617///              .page_token("amet.")
1618///              .page_size(-59)
1619///              .doit().await;
1620/// # }
1621/// ```
1622pub struct BillingAccountBudgetListCall<'a, C>
1623where
1624    C: 'a,
1625{
1626    hub: &'a CloudBillingBudget<C>,
1627    _parent: String,
1628    _scope: Option<String>,
1629    _page_token: Option<String>,
1630    _page_size: Option<i32>,
1631    _delegate: Option<&'a mut dyn common::Delegate>,
1632    _additional_params: HashMap<String, String>,
1633    _scopes: BTreeSet<String>,
1634}
1635
1636impl<'a, C> common::CallBuilder for BillingAccountBudgetListCall<'a, C> {}
1637
1638impl<'a, C> BillingAccountBudgetListCall<'a, C>
1639where
1640    C: common::Connector,
1641{
1642    /// Perform the operation you have build so far.
1643    pub async fn doit(
1644        mut self,
1645    ) -> common::Result<(
1646        common::Response,
1647        GoogleCloudBillingBudgetsV1beta1ListBudgetsResponse,
1648    )> {
1649        use std::borrow::Cow;
1650        use std::io::{Read, Seek};
1651
1652        use common::{url::Params, ToParts};
1653        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1654
1655        let mut dd = common::DefaultDelegate;
1656        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1657        dlg.begin(common::MethodInfo {
1658            id: "billingbudgets.billingAccounts.budgets.list",
1659            http_method: hyper::Method::GET,
1660        });
1661
1662        for &field in ["alt", "parent", "scope", "pageToken", "pageSize"].iter() {
1663            if self._additional_params.contains_key(field) {
1664                dlg.finished(false);
1665                return Err(common::Error::FieldClash(field));
1666            }
1667        }
1668
1669        let mut params = Params::with_capacity(6 + self._additional_params.len());
1670        params.push("parent", self._parent);
1671        if let Some(value) = self._scope.as_ref() {
1672            params.push("scope", value);
1673        }
1674        if let Some(value) = self._page_token.as_ref() {
1675            params.push("pageToken", value);
1676        }
1677        if let Some(value) = self._page_size.as_ref() {
1678            params.push("pageSize", value.to_string());
1679        }
1680
1681        params.extend(self._additional_params.iter());
1682
1683        params.push("alt", "json");
1684        let mut url = self.hub._base_url.clone() + "v1beta1/{+parent}/budgets";
1685        if self._scopes.is_empty() {
1686            self._scopes
1687                .insert(Scope::CloudPlatform.as_ref().to_string());
1688        }
1689
1690        #[allow(clippy::single_element_loop)]
1691        for &(find_this, param_name) in [("{+parent}", "parent")].iter() {
1692            url = params.uri_replacement(url, param_name, find_this, true);
1693        }
1694        {
1695            let to_remove = ["parent"];
1696            params.remove_params(&to_remove);
1697        }
1698
1699        let url = params.parse_with_url(&url);
1700
1701        loop {
1702            let token = match self
1703                .hub
1704                .auth
1705                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
1706                .await
1707            {
1708                Ok(token) => token,
1709                Err(e) => match dlg.token(e) {
1710                    Ok(token) => token,
1711                    Err(e) => {
1712                        dlg.finished(false);
1713                        return Err(common::Error::MissingToken(e));
1714                    }
1715                },
1716            };
1717            let mut req_result = {
1718                let client = &self.hub.client;
1719                dlg.pre_request();
1720                let mut req_builder = hyper::Request::builder()
1721                    .method(hyper::Method::GET)
1722                    .uri(url.as_str())
1723                    .header(USER_AGENT, self.hub._user_agent.clone());
1724
1725                if let Some(token) = token.as_ref() {
1726                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
1727                }
1728
1729                let request = req_builder
1730                    .header(CONTENT_LENGTH, 0_u64)
1731                    .body(common::to_body::<String>(None));
1732
1733                client.request(request.unwrap()).await
1734            };
1735
1736            match req_result {
1737                Err(err) => {
1738                    if let common::Retry::After(d) = dlg.http_error(&err) {
1739                        sleep(d).await;
1740                        continue;
1741                    }
1742                    dlg.finished(false);
1743                    return Err(common::Error::HttpError(err));
1744                }
1745                Ok(res) => {
1746                    let (mut parts, body) = res.into_parts();
1747                    let mut body = common::Body::new(body);
1748                    if !parts.status.is_success() {
1749                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1750                        let error = serde_json::from_str(&common::to_string(&bytes));
1751                        let response = common::to_response(parts, bytes.into());
1752
1753                        if let common::Retry::After(d) =
1754                            dlg.http_failure(&response, error.as_ref().ok())
1755                        {
1756                            sleep(d).await;
1757                            continue;
1758                        }
1759
1760                        dlg.finished(false);
1761
1762                        return Err(match error {
1763                            Ok(value) => common::Error::BadRequest(value),
1764                            _ => common::Error::Failure(response),
1765                        });
1766                    }
1767                    let response = {
1768                        let bytes = common::to_bytes(body).await.unwrap_or_default();
1769                        let encoded = common::to_string(&bytes);
1770                        match serde_json::from_str(&encoded) {
1771                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
1772                            Err(error) => {
1773                                dlg.response_json_decode_error(&encoded, &error);
1774                                return Err(common::Error::JsonDecodeError(
1775                                    encoded.to_string(),
1776                                    error,
1777                                ));
1778                            }
1779                        }
1780                    };
1781
1782                    dlg.finished(true);
1783                    return Ok(response);
1784                }
1785            }
1786        }
1787    }
1788
1789    /// Required. Name of billing account to list budgets under. Values are of the form `billingAccounts/{billingAccountId}`.
1790    ///
1791    /// Sets the *parent* path property to the given value.
1792    ///
1793    /// Even though the property as already been set when instantiating this call,
1794    /// we provide this method for API completeness.
1795    pub fn parent(mut self, new_value: &str) -> BillingAccountBudgetListCall<'a, C> {
1796        self._parent = new_value.to_string();
1797        self
1798    }
1799    /// Optional. Set the scope of the budgets to be returned, in the format of the resource name. The scope of a budget is the cost that it tracks, such as costs for a single project, or the costs for all projects in a folder. Only project scope (in the format of "projects/project-id" or "projects/123") is supported in this field. When this field is set to a project's resource name, the budgets returned are tracking the costs for that project.
1800    ///
1801    /// Sets the *scope* query property to the given value.
1802    pub fn scope(mut self, new_value: &str) -> BillingAccountBudgetListCall<'a, C> {
1803        self._scope = Some(new_value.to_string());
1804        self
1805    }
1806    /// Optional. The value returned by the last `ListBudgetsResponse` which indicates that this is a continuation of a prior `ListBudgets` call, and that the system should return the next page of data.
1807    ///
1808    /// Sets the *page token* query property to the given value.
1809    pub fn page_token(mut self, new_value: &str) -> BillingAccountBudgetListCall<'a, C> {
1810        self._page_token = Some(new_value.to_string());
1811        self
1812    }
1813    /// Optional. The maximum number of budgets to return per page. The default and maximum value are 100.
1814    ///
1815    /// Sets the *page size* query property to the given value.
1816    pub fn page_size(mut self, new_value: i32) -> BillingAccountBudgetListCall<'a, C> {
1817        self._page_size = Some(new_value);
1818        self
1819    }
1820    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
1821    /// while executing the actual API request.
1822    ///
1823    /// ````text
1824    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
1825    /// ````
1826    ///
1827    /// Sets the *delegate* property to the given value.
1828    pub fn delegate(
1829        mut self,
1830        new_value: &'a mut dyn common::Delegate,
1831    ) -> BillingAccountBudgetListCall<'a, C> {
1832        self._delegate = Some(new_value);
1833        self
1834    }
1835
1836    /// Set any additional parameter of the query string used in the request.
1837    /// It should be used to set parameters which are not yet available through their own
1838    /// setters.
1839    ///
1840    /// Please note that this method must not be used to set any of the known parameters
1841    /// which have their own setter method. If done anyway, the request will fail.
1842    ///
1843    /// # Additional Parameters
1844    ///
1845    /// * *$.xgafv* (query-string) - V1 error format.
1846    /// * *access_token* (query-string) - OAuth access token.
1847    /// * *alt* (query-string) - Data format for response.
1848    /// * *callback* (query-string) - JSONP
1849    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
1850    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
1851    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
1852    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
1853    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
1854    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
1855    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
1856    pub fn param<T>(mut self, name: T, value: T) -> BillingAccountBudgetListCall<'a, C>
1857    where
1858        T: AsRef<str>,
1859    {
1860        self._additional_params
1861            .insert(name.as_ref().to_string(), value.as_ref().to_string());
1862        self
1863    }
1864
1865    /// Identifies the authorization scope for the method you are building.
1866    ///
1867    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
1868    /// [`Scope::CloudPlatform`].
1869    ///
1870    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
1871    /// tokens for more than one scope.
1872    ///
1873    /// Usually there is more than one suitable scope to authorize an operation, some of which may
1874    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
1875    /// sufficient, a read-write scope will do as well.
1876    pub fn add_scope<St>(mut self, scope: St) -> BillingAccountBudgetListCall<'a, C>
1877    where
1878        St: AsRef<str>,
1879    {
1880        self._scopes.insert(String::from(scope.as_ref()));
1881        self
1882    }
1883    /// Identifies the authorization scope(s) for the method you are building.
1884    ///
1885    /// See [`Self::add_scope()`] for details.
1886    pub fn add_scopes<I, St>(mut self, scopes: I) -> BillingAccountBudgetListCall<'a, C>
1887    where
1888        I: IntoIterator<Item = St>,
1889        St: AsRef<str>,
1890    {
1891        self._scopes
1892            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
1893        self
1894    }
1895
1896    /// Removes all scopes, and no default scope will be used either.
1897    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
1898    /// for details).
1899    pub fn clear_scopes(mut self) -> BillingAccountBudgetListCall<'a, C> {
1900        self._scopes.clear();
1901        self
1902    }
1903}
1904
1905/// Updates a budget and returns the updated budget. WARNING: There are some fields exposed on the Google Cloud Console that aren't available on this API. Budget fields that are not exposed in this API will not be changed by this method.
1906///
1907/// A builder for the *budgets.patch* method supported by a *billingAccount* resource.
1908/// It is not used directly, but through a [`BillingAccountMethods`] instance.
1909///
1910/// # Example
1911///
1912/// Instantiate a resource method builder
1913///
1914/// ```test_harness,no_run
1915/// # extern crate hyper;
1916/// # extern crate hyper_rustls;
1917/// # extern crate google_billingbudgets1_beta1 as billingbudgets1_beta1;
1918/// use billingbudgets1_beta1::api::GoogleCloudBillingBudgetsV1beta1UpdateBudgetRequest;
1919/// # async fn dox() {
1920/// # use billingbudgets1_beta1::{CloudBillingBudget, FieldMask, hyper_rustls, hyper_util, yup_oauth2};
1921///
1922/// # let secret: yup_oauth2::ApplicationSecret = Default::default();
1923/// # let connector = hyper_rustls::HttpsConnectorBuilder::new()
1924/// #     .with_native_roots()
1925/// #     .unwrap()
1926/// #     .https_only()
1927/// #     .enable_http2()
1928/// #     .build();
1929///
1930/// # let executor = hyper_util::rt::TokioExecutor::new();
1931/// # let auth = yup_oauth2::InstalledFlowAuthenticator::with_client(
1932/// #     secret,
1933/// #     yup_oauth2::InstalledFlowReturnMethod::HTTPRedirect,
1934/// #     yup_oauth2::client::CustomHyperClientBuilder::from(
1935/// #         hyper_util::client::legacy::Client::builder(executor).build(connector),
1936/// #     ),
1937/// # ).build().await.unwrap();
1938///
1939/// # let client = hyper_util::client::legacy::Client::builder(
1940/// #     hyper_util::rt::TokioExecutor::new()
1941/// # )
1942/// # .build(
1943/// #     hyper_rustls::HttpsConnectorBuilder::new()
1944/// #         .with_native_roots()
1945/// #         .unwrap()
1946/// #         .https_or_http()
1947/// #         .enable_http2()
1948/// #         .build()
1949/// # );
1950/// # let mut hub = CloudBillingBudget::new(client, auth);
1951/// // As the method needs a request, you would usually fill it with the desired information
1952/// // into the respective structure. Some of the parts shown here might not be applicable !
1953/// // Values shown here are possibly random and not representative !
1954/// let mut req = GoogleCloudBillingBudgetsV1beta1UpdateBudgetRequest::default();
1955///
1956/// // You can configure optional parameters by calling the respective setters at will, and
1957/// // execute the final call using `doit()`.
1958/// // Values shown here are possibly random and not representative !
1959/// let result = hub.billing_accounts().budgets_patch(req, "name")
1960///              .doit().await;
1961/// # }
1962/// ```
1963pub struct BillingAccountBudgetPatchCall<'a, C>
1964where
1965    C: 'a,
1966{
1967    hub: &'a CloudBillingBudget<C>,
1968    _request: GoogleCloudBillingBudgetsV1beta1UpdateBudgetRequest,
1969    _name: String,
1970    _delegate: Option<&'a mut dyn common::Delegate>,
1971    _additional_params: HashMap<String, String>,
1972    _scopes: BTreeSet<String>,
1973}
1974
1975impl<'a, C> common::CallBuilder for BillingAccountBudgetPatchCall<'a, C> {}
1976
1977impl<'a, C> BillingAccountBudgetPatchCall<'a, C>
1978where
1979    C: common::Connector,
1980{
1981    /// Perform the operation you have build so far.
1982    pub async fn doit(
1983        mut self,
1984    ) -> common::Result<(common::Response, GoogleCloudBillingBudgetsV1beta1Budget)> {
1985        use std::borrow::Cow;
1986        use std::io::{Read, Seek};
1987
1988        use common::{url::Params, ToParts};
1989        use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, LOCATION, USER_AGENT};
1990
1991        let mut dd = common::DefaultDelegate;
1992        let mut dlg: &mut dyn common::Delegate = self._delegate.unwrap_or(&mut dd);
1993        dlg.begin(common::MethodInfo {
1994            id: "billingbudgets.billingAccounts.budgets.patch",
1995            http_method: hyper::Method::PATCH,
1996        });
1997
1998        for &field in ["alt", "name"].iter() {
1999            if self._additional_params.contains_key(field) {
2000                dlg.finished(false);
2001                return Err(common::Error::FieldClash(field));
2002            }
2003        }
2004
2005        let mut params = Params::with_capacity(4 + self._additional_params.len());
2006        params.push("name", self._name);
2007
2008        params.extend(self._additional_params.iter());
2009
2010        params.push("alt", "json");
2011        let mut url = self.hub._base_url.clone() + "v1beta1/{+name}";
2012        if self._scopes.is_empty() {
2013            self._scopes
2014                .insert(Scope::CloudPlatform.as_ref().to_string());
2015        }
2016
2017        #[allow(clippy::single_element_loop)]
2018        for &(find_this, param_name) in [("{+name}", "name")].iter() {
2019            url = params.uri_replacement(url, param_name, find_this, true);
2020        }
2021        {
2022            let to_remove = ["name"];
2023            params.remove_params(&to_remove);
2024        }
2025
2026        let url = params.parse_with_url(&url);
2027
2028        let mut json_mime_type = mime::APPLICATION_JSON;
2029        let mut request_value_reader = {
2030            let mut value = serde_json::value::to_value(&self._request).expect("serde to work");
2031            common::remove_json_null_values(&mut value);
2032            let mut dst = std::io::Cursor::new(Vec::with_capacity(128));
2033            serde_json::to_writer(&mut dst, &value).unwrap();
2034            dst
2035        };
2036        let request_size = request_value_reader
2037            .seek(std::io::SeekFrom::End(0))
2038            .unwrap();
2039        request_value_reader
2040            .seek(std::io::SeekFrom::Start(0))
2041            .unwrap();
2042
2043        loop {
2044            let token = match self
2045                .hub
2046                .auth
2047                .get_token(&self._scopes.iter().map(String::as_str).collect::<Vec<_>>()[..])
2048                .await
2049            {
2050                Ok(token) => token,
2051                Err(e) => match dlg.token(e) {
2052                    Ok(token) => token,
2053                    Err(e) => {
2054                        dlg.finished(false);
2055                        return Err(common::Error::MissingToken(e));
2056                    }
2057                },
2058            };
2059            request_value_reader
2060                .seek(std::io::SeekFrom::Start(0))
2061                .unwrap();
2062            let mut req_result = {
2063                let client = &self.hub.client;
2064                dlg.pre_request();
2065                let mut req_builder = hyper::Request::builder()
2066                    .method(hyper::Method::PATCH)
2067                    .uri(url.as_str())
2068                    .header(USER_AGENT, self.hub._user_agent.clone());
2069
2070                if let Some(token) = token.as_ref() {
2071                    req_builder = req_builder.header(AUTHORIZATION, format!("Bearer {}", token));
2072                }
2073
2074                let request = req_builder
2075                    .header(CONTENT_TYPE, json_mime_type.to_string())
2076                    .header(CONTENT_LENGTH, request_size as u64)
2077                    .body(common::to_body(
2078                        request_value_reader.get_ref().clone().into(),
2079                    ));
2080
2081                client.request(request.unwrap()).await
2082            };
2083
2084            match req_result {
2085                Err(err) => {
2086                    if let common::Retry::After(d) = dlg.http_error(&err) {
2087                        sleep(d).await;
2088                        continue;
2089                    }
2090                    dlg.finished(false);
2091                    return Err(common::Error::HttpError(err));
2092                }
2093                Ok(res) => {
2094                    let (mut parts, body) = res.into_parts();
2095                    let mut body = common::Body::new(body);
2096                    if !parts.status.is_success() {
2097                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2098                        let error = serde_json::from_str(&common::to_string(&bytes));
2099                        let response = common::to_response(parts, bytes.into());
2100
2101                        if let common::Retry::After(d) =
2102                            dlg.http_failure(&response, error.as_ref().ok())
2103                        {
2104                            sleep(d).await;
2105                            continue;
2106                        }
2107
2108                        dlg.finished(false);
2109
2110                        return Err(match error {
2111                            Ok(value) => common::Error::BadRequest(value),
2112                            _ => common::Error::Failure(response),
2113                        });
2114                    }
2115                    let response = {
2116                        let bytes = common::to_bytes(body).await.unwrap_or_default();
2117                        let encoded = common::to_string(&bytes);
2118                        match serde_json::from_str(&encoded) {
2119                            Ok(decoded) => (common::to_response(parts, bytes.into()), decoded),
2120                            Err(error) => {
2121                                dlg.response_json_decode_error(&encoded, &error);
2122                                return Err(common::Error::JsonDecodeError(
2123                                    encoded.to_string(),
2124                                    error,
2125                                ));
2126                            }
2127                        }
2128                    };
2129
2130                    dlg.finished(true);
2131                    return Ok(response);
2132                }
2133            }
2134        }
2135    }
2136
2137    ///
2138    /// Sets the *request* property to the given value.
2139    ///
2140    /// Even though the property as already been set when instantiating this call,
2141    /// we provide this method for API completeness.
2142    pub fn request(
2143        mut self,
2144        new_value: GoogleCloudBillingBudgetsV1beta1UpdateBudgetRequest,
2145    ) -> BillingAccountBudgetPatchCall<'a, C> {
2146        self._request = new_value;
2147        self
2148    }
2149    /// Output only. Resource name of the budget. The resource name implies the scope of a budget. Values are of the form `billingAccounts/{billingAccountId}/budgets/{budgetId}`.
2150    ///
2151    /// Sets the *name* path property to the given value.
2152    ///
2153    /// Even though the property as already been set when instantiating this call,
2154    /// we provide this method for API completeness.
2155    pub fn name(mut self, new_value: &str) -> BillingAccountBudgetPatchCall<'a, C> {
2156        self._name = new_value.to_string();
2157        self
2158    }
2159    /// The delegate implementation is consulted whenever there is an intermediate result, or if something goes wrong
2160    /// while executing the actual API request.
2161    ///
2162    /// ````text
2163    ///                   It should be used to handle progress information, and to implement a certain level of resilience.
2164    /// ````
2165    ///
2166    /// Sets the *delegate* property to the given value.
2167    pub fn delegate(
2168        mut self,
2169        new_value: &'a mut dyn common::Delegate,
2170    ) -> BillingAccountBudgetPatchCall<'a, C> {
2171        self._delegate = Some(new_value);
2172        self
2173    }
2174
2175    /// Set any additional parameter of the query string used in the request.
2176    /// It should be used to set parameters which are not yet available through their own
2177    /// setters.
2178    ///
2179    /// Please note that this method must not be used to set any of the known parameters
2180    /// which have their own setter method. If done anyway, the request will fail.
2181    ///
2182    /// # Additional Parameters
2183    ///
2184    /// * *$.xgafv* (query-string) - V1 error format.
2185    /// * *access_token* (query-string) - OAuth access token.
2186    /// * *alt* (query-string) - Data format for response.
2187    /// * *callback* (query-string) - JSONP
2188    /// * *fields* (query-string) - Selector specifying which fields to include in a partial response.
2189    /// * *key* (query-string) - API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token.
2190    /// * *oauth_token* (query-string) - OAuth 2.0 token for the current user.
2191    /// * *prettyPrint* (query-boolean) - Returns response with indentations and line breaks.
2192    /// * *quotaUser* (query-string) - Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters.
2193    /// * *uploadType* (query-string) - Legacy upload protocol for media (e.g. "media", "multipart").
2194    /// * *upload_protocol* (query-string) - Upload protocol for media (e.g. "raw", "multipart").
2195    pub fn param<T>(mut self, name: T, value: T) -> BillingAccountBudgetPatchCall<'a, C>
2196    where
2197        T: AsRef<str>,
2198    {
2199        self._additional_params
2200            .insert(name.as_ref().to_string(), value.as_ref().to_string());
2201        self
2202    }
2203
2204    /// Identifies the authorization scope for the method you are building.
2205    ///
2206    /// Use this method to actively specify which scope should be used, instead of the default [`Scope`] variant
2207    /// [`Scope::CloudPlatform`].
2208    ///
2209    /// The `scope` will be added to a set of scopes. This is important as one can maintain access
2210    /// tokens for more than one scope.
2211    ///
2212    /// Usually there is more than one suitable scope to authorize an operation, some of which may
2213    /// encompass more rights than others. For example, for listing resources, a *read-only* scope will be
2214    /// sufficient, a read-write scope will do as well.
2215    pub fn add_scope<St>(mut self, scope: St) -> BillingAccountBudgetPatchCall<'a, C>
2216    where
2217        St: AsRef<str>,
2218    {
2219        self._scopes.insert(String::from(scope.as_ref()));
2220        self
2221    }
2222    /// Identifies the authorization scope(s) for the method you are building.
2223    ///
2224    /// See [`Self::add_scope()`] for details.
2225    pub fn add_scopes<I, St>(mut self, scopes: I) -> BillingAccountBudgetPatchCall<'a, C>
2226    where
2227        I: IntoIterator<Item = St>,
2228        St: AsRef<str>,
2229    {
2230        self._scopes
2231            .extend(scopes.into_iter().map(|s| String::from(s.as_ref())));
2232        self
2233    }
2234
2235    /// Removes all scopes, and no default scope will be used either.
2236    /// In this case, you have to specify your API-key using the `key` parameter (see [`Self::param()`]
2237    /// for details).
2238    pub fn clear_scopes(mut self) -> BillingAccountBudgetPatchCall<'a, C> {
2239        self._scopes.clear();
2240        self
2241    }
2242}