Visualizza deal definitivi

Per visualizzare i dati finali, puoi utilizzare i seguenti metodi offerte per il tuo account e uno qualsiasi dei tuoi clienti.

Visualizza un singolo deal

Puoi utilizzare lo buyers.finalizedDeals.get per recuperare uno specifico FinalizedDeal associati al tuo account o a uno dei tuoi clienti.

L'esempio seguente mostra come recuperare un singolo FinalizedDeal con il metodo get.

REST

Richiesta

GET https://authorizedbuyersmarketplace.googleapis.com/v1/buyers/12345678/finalizedDeals/1840860?alt=json
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

Risposta

{
 "name": "buyers/12345678/finalizedDeals/1840860",
 "deal": {
   "name": "buyers/12345678/proposals/MP8642048/deals/1840860",
   "createTime": "2031-03-26T05:53:33.053Z",
   "updateTime": "2031-03-26T05:54:33.442Z",
   "displayName": "test-pg-deal-4",
   "buyer": "buyers/12345678",
   "publisherProfile": "buyers/12345678/publisherProfiles/PP12345",
   "flightStartTime": "2032-03-31T16:00:00Z",
   "flightEndTime": "2032-03-31T18:59:00Z",
   "targeting": {
     "inventorySizeTargeting": {
       "targetedInventorySizes": [
         {
           "width": "200",
           "height": "200",
           "type": "PIXEL"
         },
         {
           "width": "234",
           "height": "60",
           "type": "PIXEL"
         },
         {
           "width": "240",
           "height": "400",
           "type": "PIXEL"
         },
         {
           "width": "300",
           "height": "250",
           "type": "PIXEL"
         },
         {
           "width": "300",
           "height": "600",
           "type": "PIXEL"
         },
         {
           "width": "300",
           "height": "1050",
           "type": "PIXEL"
         }
       ]
     }
   },
   "creativeRequirements": {
     "creativePreApprovalPolicy": "SELLER_PRE_APPROVAL_NOT_REQUIRED",
     "creativeSafeFrameCompatibility": "COMPATIBLE",
     "programmaticCreativeSource": "ADVERTISER",
     "creativeFormat": "DISPLAY"
   },
   "deliveryControl": {
     "deliveryRateType": "EVENLY"
   },
   "billedBuyer": "buyers/12345678",
   "dealType": "PROGRAMMATIC_GUARANTEED",
   "programmaticGuaranteedTerms": {
     "guaranteedLooks": "1",
     "fixedPrice": {
       "type": "CPM",
       "amount": {
         "currencyCode": "USD",
         "nanos": 10000000
       }
     },
     "reservationType": "STANDARD"
   },
   "sellerTimeZone": {
     "id": "Asia/Shanghai"
   }
 },
 "dealServingStatus": "ENDED",
 "dealPausingInfo": {
   "pausingConsented": true
  },
 "rtbMetrics": {},
 "readyToServe": false
}

C#

/* Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using Google.Apis.AuthorizedBuyersMarketplace.v1;
using Google.Apis.AuthorizedBuyersMarketplace.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.AuthorizedBuyersMarketplace.Examples.v1.Buyers.FinalizedDeals
{
    /// <summary>
    /// Gets a single finalized deal for the given buyer and deal IDs.
    ///
    /// Note that deal IDs for finalized deals are identical to those of
    /// non-finalized deals–when a deal becomes finalized, its deal ID will not
    /// change.
    /// </summary>
    public class GetFinalizedDeals : ExampleBase
    {
        private AuthorizedBuyersMarketplaceService mkService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public GetFinalizedDeals()
        {
            mkService = Utilities.GetAuthorizedBuyersMarketplaceService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example gets a finalized deal for given buyer and deal IDs.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id", "deal_id"};
            bool showHelp = false;

            string accountId = null;
            string dealId = null;

            OptionSet options = new OptionSet {
                "Get a finalized deal for the given buyer and deal IDs.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource under which the auction " +
                     "package is being retrieved. This will be used to construct the name used " +
                     "as a path parameter for the auctionPackages.get request."),
                    a => accountId = a
                },
                {
                    "d|deal_id=",
                    ("[Required] The resource ID of the buyers.finalizedDeals resource that " +
                     "is being retrieved. This will be used to construct the name used as a " +
                     "path parameter for the finalizedDeals.get request."),
                    d => dealId = d
                },
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if (showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set optional arguments.
            parsedArgs["account_id"] = accountId;
            parsedArgs["deal_id"] = dealId;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["account_id"];
            string dealId = (string) parsedArgs["deal_id"];
            string name = $"buyers/{accountId}/finalizedDeals/{dealId}";

            BuyersResource.FinalizedDealsResource.GetRequest request =
                mkService.Buyers.FinalizedDeals.Get(name);
            FinalizedDeal response = null;

            Console.WriteLine("Getting finalized deal with name: {0}", name);

            try
            {
                response = request.Execute();
            }
            catch (Exception exception)
            {
                throw new ApplicationException(
                    $"Marketplace API returned error response:\n{exception.Message}");
            }

            Utilities.PrintFinalizedDeal(response);
        }
    }
}

Java

/*
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.api.services.samples.authorizedbuyers.marketplace.v1.buyers.finalizedDeals;

import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.FinalizedDeal;
import com.google.api.services.samples.authorizedbuyers.marketplace.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * This sample illustrates how to get a finalized deal for the given buyer and deal IDs.
 *
 * <p>Note that deal IDs for finalized deals are identical to those of non-finalized deals–when a
 * deal becomes finalized, its deal ID will not change.
 */
public class GetFinalizedDeals {

  public static void execute(AuthorizedBuyersMarketplace marketplaceClient, Namespace parsedArgs) {
    Long accountId = parsedArgs.getLong("account_id");
    Long dealId = parsedArgs.getLong("deal_id");
    String name = String.format("buyers/%d/finalizedDeals/%d", accountId, dealId);

    FinalizedDeal finalizedDeal = null;

    try {
      finalizedDeal = marketplaceClient.buyers().finalizedDeals().get(name).execute();
    } catch (IOException ex) {
      System.out.printf("Marketplace API returned error response:%n%s", ex);
      System.exit(1);
    }

    System.out.printf(
        "Found finalized deal with ID \"%d\" for buyer account ID \"%d\":%n", dealId, accountId);
    Utils.printFinalizedDeal(finalizedDeal);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("GetFinalizedDeals")
            .build()
            .defaultHelp(true)
            .description(("Get a finalized deal for the given buyer account ID and deal ID."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the buyers resource under which the finalized deal exists. "
                + "This will be used to construct the parent used as a path parameter for the "
                + "finalizedDeals.get request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-d", "--deal_id")
        .help(
            "The resource ID of the buyers.finalizedDeals resource that is being retrieved. "
                + "This will be used to construct the name used as a path parameter for the "
                + "finalizedDeals.get request.")
        .required(true)
        .type(Long.class);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    AuthorizedBuyersMarketplace client = null;
    try {
      client = Utils.getMarketplaceClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create Marketplace API service:%n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:%n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}


Python

#!/usr/bin/python
#
# Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Gets a single finalized deal for the given account and deal IDs."""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_FINALIZED_DEALS_NAME_TEMPLATE = 'buyers/%s/finalizedDeals/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'
DEFAULT_FINALIZED_DEAL_RESOURCE_ID = 'ENTER_DEAL_RESOURCE_ID_HERE'


def main(marketplace, args):
    finalized_deal_name = _FINALIZED_DEALS_NAME_TEMPLATE % (
        args.account_id, args.deal_id)

    print(f'Get finalized deal with name "{finalized_deal_name}":')
    try:
        # Construct and execute the request.
        response = marketplace.buyers().finalizedDeals().get(
            name=finalized_deal_name).execute()
    except HttpError as e:
        print(e)
        sys.exit(1)

    pprint.pprint(response)


if __name__ == '__main__':
    try:
        service = util.get_service(version='v1')
    except IOError as ex:
        print(f'Unable to create marketplace service - {ex}')
        print('Did you specify the key file in util.py?')
        sys.exit(1)

    parser = argparse.ArgumentParser(
        description=('Get a finalized deal for the given buyer account ID and '
                     'deal ID.'))
    # Required fields.
    parser.add_argument(
        '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
        help=('The resource ID of the buyers resource for which the finalized '
              'deal is being accessed. This will be used to construct the '
              'name used as a path parameter for the finalizedDeals.get '
              'request.'))
    parser.add_argument(
        '-d', '--deal_id', default=DEFAULT_FINALIZED_DEAL_RESOURCE_ID,
        help=('The resource ID of the buyers.finalizedDeals resource that is '
              'being accessed. Note that this will be identical to the '
              'resource ID of the corresponding buyers.proposals.deals '
              'resource. This will be used to construct the name used as a '
              'path parameter for the finalizedDeals.get request.'))

    main(service, parser.parse_args())

Elenca deal come offerente

Puoi utilizzare lo bidders.finalizedDeals.list per sfogliare tutti i deal definitivi negoziati da un acquirente associato al tuo account offerente.

Puoi utilizzare questo metodo per eseguire ricerche ampie in più account.

L'esempio seguente mostra come elencare i deal definitivi con il list.

REST

Richiesta

GET https://authorizedbuyersmarketplace.googleapis.com/v1/bidders/12345678/finalizedDeals?filter=deal.dealType+%3D+PROGRAMMATIC_GUARANTEED&orderBy=deal.flightStartTime+desc&pageSize=3&alt=json
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

Risposta

{
 "finalizedDeals": [
   {
     "name": "buyers/12345678/finalizedDeals/2809704",
     "deal": {
       "name": "buyers/12345678/proposals/MP24462282/deals/2809704",
       "createTime": "2031-05-10T21:12:10.586Z",
       "updateTime": "2031-08-18T16:23:35.087Z",
       "displayName": "test-pg-deal-1",
       "buyer": "buyers/12345678",
       "publisherProfile": "buyers/12345678/publisherProfiles/PP62461",
       "flightStartTime": "2031-12-14T16:00:00Z",
       "flightEndTime": "2031-03-07T15:59:00Z",
       "targeting": {
         "inventorySizeTargeting": {
           "targetedInventorySizes": [
             {
               "width": "1",
               "height": "1",
               "type": "NATIVE"
             }
           ]
         }
       },
       "creativeRequirements": {
         "creativePreApprovalPolicy": "SELLER_PRE_APPROVAL_NOT_REQUIRED",
         "creativeSafeFrameCompatibility": "COMPATIBLE",
         "programmaticCreativeSource": "ADVERTISER",
         "creativeFormat": "DISPLAY"
       },
       "deliveryControl": {
         "deliveryRateType": "FRONT_LOADED"
       },
       "billedBuyer": "buyers/12345678",
       "dealType": "PROGRAMMATIC_GUARANTEED",
       "programmaticGuaranteedTerms": {
         "guaranteedLooks": "1000",
         "fixedPrice": {
           "type": "CPM",
           "amount": {
             "currencyCode": "CNY",
             "units": "20"
           }
         },
         "reservationType": "STANDARD"
       },
       "sellerTimeZone": {
         "id": "Asia/Shanghai"
       }
     },
     "dealServingStatus": "PAUSED_BY_SELLER",
     "dealPausingInfo": {
        "pausingConsented": true,
       "pauseRole": "SELLER"
     },
     "rtbMetrics": {}
   },
   {
     "name": "buyers/12345678/finalizedDeals/1537354",
     "deal": {
       "name": "buyers/39382167/proposals/MP14640061/deals/1537354",
       "createTime": "2031-06-11T15:03:25.412Z",
       "updateTime": "2031-06-11T15:18:34.209Z",
       "displayName": "test-pg-deal-2",
       "buyer": "buyers/39382167",
       "publisherProfile": "buyers/39382167/publisherProfiles/PP382992",
       "flightStartTime": "2032-12-13T16:00:00Z",
       "flightEndTime": "2034-03-06T15:59:00Z",
       "targeting": {
         "inventorySizeTargeting": {
           "targetedInventorySizes": [
             {
               "width": "1",
               "height": "1",
               "type": "NATIVE"
             }
           ]
         }
       },
       "creativeRequirements": {
         "creativePreApprovalPolicy": "SELLER_PRE_APPROVAL_NOT_REQUIRED",
         "creativeSafeFrameCompatibility": "COMPATIBLE",
         "programmaticCreativeSource": "ADVERTISER",
         "creativeFormat": "DISPLAY"
       },
       "deliveryControl": {
         "deliveryRateType": "FRONT_LOADED"
       },
       "billedBuyer": "buyers/39382167",
       "dealType": "PROGRAMMATIC_GUARANTEED",
       "programmaticGuaranteedTerms": {
          "guaranteedLooks": "1000",
          "fixedPrice": {
           "type": "CPM",
           "amount": {
             "currencyCode": "CNY",
             "units": "20"
           }
         },
         "reservationType": "STANDARD"
       },
       "sellerTimeZone": {
         "id": "Asia/Shanghai"
       }
     },
     "dealServingStatus": "ACTIVE",
     "dealPausingInfo": {
       "pausingConsented": true
     },
     "rtbMetrics": {},
     "readyToServe": true
   },
   {
     "name": "buyers/6524914/finalizedDeals/3126325",
     "deal": {
       "name": "buyers/6524914/proposals/MP17820211/deals/1518325",
       "createTime": "2031-05-11T15:16:49.903Z",
       "updateTime": "2031-05-11T15:21:34.162Z",
       "displayName": "test-pg-deal-3",
       "client": "buyers/6524914/clients/19823764",
       "publisherProfile": "buyers/6524914/publisherProfiles/2109413",
       "flightStartTime": "2032-04-11T16:00:00Z",
       "flightEndTime": "2032-10-13T15:59:00Z",
       "targeting": {
         "inventorySizeTargeting": {
           "targetedInventorySizes": [
             {
               "width": "1",
               "height": "1",
               "type": "NATIVE"
             }
           ]
         }
       },
       "creativeRequirements": {
         "creativePreApprovalPolicy": "SELLER_PRE_APPROVAL_NOT_REQUIRED",
         "creativeSafeFrameCompatibility": "COMPATIBLE",
         "programmaticCreativeSource": "ADVERTISER",
         "creativeFormat": "DISPLAY"
       },
       "deliveryControl": {
         "deliveryRateType": "FRONT_LOADED"
       },
       "billedBuyer": "buyers/6524914",
       "dealType": "PROGRAMMATIC_GUARANTEED",
       "programmaticGuaranteedTerms": {
         "guaranteedLooks": "1000",
         "fixedPrice": {
           "type": "CPM",
           "amount": {
             "currencyCode": "CNY",
             "units": "18"
           }
         },
         "reservationType": "STANDARD"
       },
       "sellerTimeZone": {
         "id": "Asia/Shanghai"
       }
     },
     "dealServingStatus": "ACTIVE",
     "dealPausingInfo": {},
     "rtbMetrics": {},
     "readyToServe": true
   }
 ],
 "nextPageToken": "CAMQy_DV1qLx9gIYy_DV1qLx9gI="
}

C#

/* Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using Google.Apis.AuthorizedBuyersMarketplace.v1;
using Google.Apis.AuthorizedBuyersMarketplace.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.AuthorizedBuyersMarketplace.Examples.v1.Bidders.FinalizedDeals
{
    /// <summary>
    /// Lists finalized deals for the given bidder, their buyers, and clients.
    /// </summary>
    public class ListFinalizedDeals : ExampleBase
    {
        private AuthorizedBuyersMarketplaceService mkService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public ListFinalizedDeals()
        {
            mkService = Utilities.GetAuthorizedBuyersMarketplaceService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example lists finalized deals for a given bidder, their buyers, " +
                "and clients.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id"};
            bool showHelp = false;

            string accountId = null;
            string filter = null;
            string orderBy = null;
            int? pageSize = null;

            string defaultFilter = "deal.dealType = PROGRAMMATIC_GUARANTEED";
            string defaultOrderBy = "deal.flightStartTime desc";

            OptionSet options = new OptionSet {
                "List finalized deals for the given bidder, their buyers, and clients.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the bidders resource under which the " +
                     "finalized deals are being retrieved. This will be used to construct the " +
                     "parent used as a path parameter for the finalizedDeals.list request."),
                    a => accountId = a
                },
                {
                    "f|filter=",
                    ("Query string to filter finalized deals. By default, this example will " +
                     "fitler by deal type to retrieve programmatic guaranteed deals to " +
                     "demonstrate usage."),
                    f => filter =  f
                },
                {
                    "o|order_by=",
                    ("Query string used to sort the response of the list method. By default, " +
                     "this example will return deals in descending order of their flight start " +
                     "time to demonstrate usage. To learn more about the syntax for this " +
                     "parameter, see: " +
                     "https://cloud.google.com/apis/design/design_patterns#sorting_order"),
                    o => orderBy =  o
                },
                {
                    "p|page_size=",
                    ("The number of rows to return per page. The server may return fewer rows " +
                     "than specified."),
                    (int p) => pageSize =  p
                },
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if (showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs["account_id"] = accountId;
            parsedArgs["filter"] = filter ?? defaultFilter;
            parsedArgs["order_by"] = orderBy ?? defaultOrderBy;
            parsedArgs["pageSize"] = pageSize ?? Utilities.MAX_PAGE_SIZE;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["account_id"];
            string parent = $"bidders/{accountId}";
            string pageToken = null;

            Console.WriteLine(@"Listing finalized deals for bidder account ""{0}""", parent);
            do
            {
                BiddersResource.FinalizedDealsResource.ListRequest request =
                    mkService.Bidders.FinalizedDeals.List(parent);
                request.Filter = (string) parsedArgs["filter"];
                request.OrderBy = (string) parsedArgs["order_by"];
                request.PageSize = (int) parsedArgs["pageSize"];
                request.PageToken = pageToken;

                ListFinalizedDealsResponse page = null;

                try
                {
                    page = request.Execute();
                }
                catch (Exception exception)
                {
                    throw new ApplicationException(
                        $"Marketplace API returned error response:\n{exception.Message}");
                }

                var finalizedDeals = page.FinalizedDeals;
                pageToken = page.NextPageToken;

                if (finalizedDeals == null)
                {
                    Console.WriteLine("No finalized deals found for bidder account.");
                }
                else
                {
                    foreach (FinalizedDeal finalizedDeal in finalizedDeals)
                    {
                        Utilities.PrintFinalizedDeal(finalizedDeal);
                    }
                }
            }
            while(pageToken != null);
        }
    }
}

Java

/*
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.api.services.samples.authorizedbuyers.marketplace.v1.bidders.finalizedDeals;

import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.FinalizedDeal;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.ListFinalizedDealsResponse;
import com.google.api.services.samples.authorizedbuyers.marketplace.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/**
 * This sample illustrates how to list finalized deals for a given bidder, their buyers, and
 * clients.
 */
public class ListFinalizedDeals {

  public static void execute(AuthorizedBuyersMarketplace marketplaceClient, Namespace parsedArgs) {
    Long accountId = parsedArgs.getLong("account_id");
    Integer pageSize = parsedArgs.getInt("page_size");
    String parentBidderName = String.format("bidders/%d", accountId);
    String pageToken = null;

    System.out.printf("Found finalized deals for bidder account ID '%d':%n", accountId);

    do {
      List<FinalizedDeal> finalizedDeals = null;

      try {
        ListFinalizedDealsResponse response =
            marketplaceClient
                .bidders()
                .finalizedDeals()
                .list(parentBidderName)
                .setFilter(parsedArgs.getString("filter"))
                .setOrderBy(parsedArgs.getString("order_by"))
                .setPageSize(pageSize)
                .setPageToken(pageToken)
                .execute();

        finalizedDeals = response.getFinalizedDeals();
        pageToken = response.getNextPageToken();
      } catch (IOException ex) {
        System.out.printf("Marketplace API returned error response:%n%s", ex);
        System.exit(1);
      }
      if (finalizedDeals == null) {
        System.out.println("No finalized deals found.");
      } else {
        for (FinalizedDeal finalizedDeal : finalizedDeals) {
          Utils.printFinalizedDeal(finalizedDeal);
        }
      }
    } while (pageToken != null);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("ListFinalizedDeals")
            .build()
            .defaultHelp(true)
            .description(("Lists finalized deals associated with the given bidder account."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the bidders resource under which the finalized deals are being"
                + " retrieved. This will be used to construct the parent used as a path parameter"
                + " for the finalizedDeals.list request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-f", "--filter")
        .help(
            "Query string to filter finalized deals. By default, this example will filter by "
                + "deal type to retrieve programmatic guaranteed deals to demonstrate usage.")
        .setDefault("deal.dealType = PROGRAMMATIC_GUARANTEED");
    parser
        .addArgument("-o", "--order_by")
        .help(
            "Query string used to sort the response of the list method. By default, this "
                + "example will return deals in descending order of their flight start time to "
                + "demonstrate usage. To learn more about the syntax for this parameter, see: "
                + "https://cloud.google.com/apis/design/design_patterns#sorting_order")
        .setDefault("deal.flightStartTime desc");
    parser
        .addArgument("-p", "--page_size")
        .help(
            "The number of rows to return per page. The server may return fewer rows than "
                + "specified.")
        .setDefault(Utils.getMaximumPageSize())
        .type(Integer.class);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    AuthorizedBuyersMarketplace client = null;
    try {
      client = Utils.getMarketplaceClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create Marketplace API service:%n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:%n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}

Python

#!/usr/bin/python
#
# Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Lists finalized deals for the given bidder, their buyers, and clients."""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_BIDDER_NAME_TEMPLATE = 'bidders/%s'

DEFAULT_BIDDER_RESOURCE_ID = 'ENTER_BIDDER_RESOURCE_ID_HERE'


def main(marketplace, args):
    account_id = args.account_id
    list_filter = args.filter
    order_by = args.order_by
    page_size = args.page_size

    page_token = None
    more_pages = True

    print(f'Listing finalized deals for bidder account: "{account_id}".')
    while more_pages:
        try:
            # Construct and execute the request.
            response = marketplace.bidders().finalizedDeals().list(
                parent=_BIDDER_NAME_TEMPLATE % account_id, pageToken=page_token,
                filter=list_filter, orderBy=order_by,
                pageSize=page_size).execute()
        except HttpError as e:
            print(e)
            sys.exit(1)

        pprint.pprint(response)

        page_token = response.get('nextPageToken')
        more_pages = bool(page_token)


if __name__ == '__main__':
    try:
        service = util.get_service(version='v1')
    except IOError as ex:
        print(f'Unable to create marketplace service - {ex}')
        print('Did you specify the key file in util.py?')
        sys.exit(1)

    parser = argparse.ArgumentParser(
        description=('Lists finalized deals for the given bidder account, its '
                     'buyers, and clients.'))
    # Required fields.
    parser.add_argument(
        '-a', '--account_id', default=DEFAULT_BIDDER_RESOURCE_ID,
        help=('The resource ID of the bidders resource for which the finalized '
              'deals are being retrieved. This will be used to construct the '
              'parent used as a path parameter for the finalizedDeals.list '
              'request.'))
    # Optional fields.
    parser.add_argument(
        '-f', '--filter', default='deal.dealType = PROGRAMMATIC_GUARANTEED',
        help=('Query string to filter clients. By default, this example will '
              'filter by deal type to retrieve programmatic guaranteed deals '
              'to demonstrate usage.'))
    parser.add_argument(
        '-o', '--order_by', default='deal.flightStartTime desc',
        help=('Query string used to sort the response of the list method. By '
              'default, this will return deals in descending order of their '
              'flight start time to demonstrate usage. To learn more about '
              'the syntax for this parameter, see: '
              'https://cloud.google.com/apis/design/design_patterns'
              '#sorting_order'))
    parser.add_argument(
        '-p', '--page_size', default=util.MAX_PAGE_SIZE,
        help=('The number of rows to return per page. The server may return '
              'fewer rows than specified.'))

    main(service, parser.parse_args())

Mostra deal come acquirente

Puoi utilizzare lo buyers.finalizedDeals.list per sfogliare tutti i deal definitivi associati al tuo account o a qualsiasi dei suoi clienti.

L'esempio seguente mostra come elencare i deal definitivi con il list.

REST

Richiesta

GET https://authorizedbuyersmarketplace.googleapis.com/v1/buyers/12345678/finalizedDeals?filter=deal.dealType+%3D+PROGRAMMATIC_GUARANTEED&orderBy=deal.flightStartTime+desc&pageSize=3&alt=json
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

Risposta

{
 "finalizedDeals": [
   {
     "name": "buyers/12345678/finalizedDeals/2809704",
     "deal": {
       "name": "buyers/12345678/proposals/MP24462282/deals/2809704",
       "createTime": "2032-05-10T21:12:10.586Z",
       "updateTime": "2032-08-18T16:23:35.087Z",
       "displayName": "test-pg-deal-1",
       "buyer": "buyers/12345678",
       "publisherProfile": "buyers/12345678/publisherProfiles/PP62461",
       "flightStartTime": "2032-12-14T16:00:00Z",
       "flightEndTime": "2032-03-07T15:59:00Z",
       "targeting": {
         "inventorySizeTargeting": {
           "targetedInventorySizes": [
             {
               "width": "1",
               "height": "1",
               "type": "NATIVE"
             }
           ]
         }
       },
       "creativeRequirements": {
         "creativePreApprovalPolicy": "SELLER_PRE_APPROVAL_NOT_REQUIRED",
         "creativeSafeFrameCompatibility": "COMPATIBLE",
         "programmaticCreativeSource": "ADVERTISER",
         "creativeFormat": "DISPLAY"
       },
       "deliveryControl": {
         "deliveryRateType": "FRONT_LOADED"
       },
       "billedBuyer": "buyers/12345678",
       "dealType": "PROGRAMMATIC_GUARANTEED",
       "programmaticGuaranteedTerms": {
         "guaranteedLooks": "1000",
         "fixedPrice": {
           "type": "CPM",
           "amount": {
             "currencyCode": "CNY",
             "units": "20"
           }
         },
         "reservationType": "STANDARD"
       },
       "sellerTimeZone": {
         "id": "Asia/Shanghai"
       }
     },
     "dealServingStatus": "PAUSED_BY_SELLER",
     "dealPausingInfo": {
       "pausingConsented": true,
       "pauseRole": "SELLER"
     },
     "rtbMetrics": {}
   },
   {
     "name": "buyers/12345678/finalizedDeals/3853354",
     "deal": {
       "name": "buyers/12345678/proposals/MP75020085/deals/3853354",
       "createTime": "2031-05-08T15:03:25.212Z",
       "updateTime": "2031-05-08T15:18:34.329Z",
       "displayName": "test-pg-deal-5",
       "buyer": "buyers/12345678",
       "publisherProfile": "buyers/12345678/publisherProfiles/PP54321",
       "flightStartTime": "2032-12-13T16:00:00Z",
       "flightEndTime": "2033-03-06T15:59:00Z",
       "targeting": {
         "inventorySizeTargeting": {
           "targetedInventorySizes": [
             {
               "width": "1",
               "height": "1",
               "type": "NATIVE"
             }
           ]
         }
       },
       "creativeRequirements": {
         "creativePreApprovalPolicy": "SELLER_PRE_APPROVAL_NOT_REQUIRED",
         "creativeSafeFrameCompatibility": "COMPATIBLE",
         "programmaticCreativeSource": "ADVERTISER",
         "creativeFormat": "DISPLAY"
       },
       "deliveryControl": {
         "deliveryRateType": "FRONT_LOADED"
       },
       "billedBuyer": "buyers/12345678",
       "dealType": "PROGRAMMATIC_GUARANTEED",
       "programmaticGuaranteedTerms": {
         "guaranteedLooks": "1000",
         "fixedPrice": {
           "type": "CPM",
           "amount": {
             "currencyCode": "CNY",
             "units": "20"
           }
         },
         "reservationType": "STANDARD"
       },
       "sellerTimeZone": {
         "id": "Asia/Shanghai"
       }
     },
     "dealServingStatus": "ACTIVE",
     "dealPausingInfo": {
       "pausingConsented": true
     },
     "rtbMetrics": {},
     "readyToServe": true
   },
   {
     "name": "buyers/12345678/finalizedDeals/1840860",
     "deal": {
       "name": "buyers/12345678/proposals/MP8642048/deals/1840860",
       "createTime": "2031-03-26T05:53:33.053Z",
       "updateTime": "2031-03-26T05:54:33.442Z",
       "displayName": "test-pg-deal-4",
       "buyer": "buyers/12345678",
       "publisherProfile": "buyers/12345678/publisherProfiles/PP12345",
       "flightStartTime": "2032-03-31T16:00:00Z",
       "flightEndTime": "2032-03-31T18:59:00Z",
       "targeting": {
         "inventorySizeTargeting": {
           "targetedInventorySizes": [
             {
               "width": "200",
               "height": "200",
               "type": "PIXEL"
             },
             {
               "width": "234",
               "height": "60",
               "type": "PIXEL"
             },
             {
               "width": "240",
               "height": "400",
               "type": "PIXEL"
             },
             {
               "width": "300",
               "height": "250",
               "type": "PIXEL"
             },
             {
               "width": "300",
               "height": "600",
               "type": "PIXEL"
             },
             {
               "width": "300",
               "height": "1050",
               "type": "PIXEL"
             }
           ]
         }
       },
       "creativeRequirements": {
         "creativePreApprovalPolicy": "SELLER_PRE_APPROVAL_NOT_REQUIRED",
         "creativeSafeFrameCompatibility": "COMPATIBLE",
         "programmaticCreativeSource": "ADVERTISER",
         "creativeFormat": "DISPLAY"
       },
       "deliveryControl": {
         "deliveryRateType": "EVENLY"
       },
       "billedBuyer": "buyers/12345678",
       "dealType": "PROGRAMMATIC_GUARANTEED",
       "programmaticGuaranteedTerms": {
         "guaranteedLooks": "1",
         "fixedPrice": {
           "type": "CPM",
           "amount": {
             "currencyCode": "USD",
             "nanos": 10000000
           }
         },
         "reservationType": "STANDARD"
       },
       "sellerTimeZone": {
         "id": "Asia/Shanghai"
       }
     },
     "dealServingStatus": "ENDED",
     "dealPausingInfo": {
       "pausingConsented": true
     },
     "rtbMetrics": {},
     "readyToServe": false
   }
 ],
 "nextPageToken": "CAMQqbLfqKHx9gIYqbLfqKHx9gI="
}

C#

/* Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using Google.Apis.AuthorizedBuyersMarketplace.v1;
using Google.Apis.AuthorizedBuyersMarketplace.v1.Data;
using Mono.Options;

using System;
using System.Collections.Generic;

namespace Google.Apis.AuthorizedBuyersMarketplace.Examples.v1.Buyers.FinalizedDeals
{
    /// <summary>
    /// Lists finalized deals for a given buyer and their clients.
    /// </summary>
    public class ListFinalizedDeals : ExampleBase
    {
        private AuthorizedBuyersMarketplaceService mkService;

        /// <summary>
        /// Constructor.
        /// </summary>
        public ListFinalizedDeals()
        {
            mkService = Utilities.GetAuthorizedBuyersMarketplaceService();
        }

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example lists finalized deals for a given buyer and their clients.";
        }

        /// <summary>
        /// Parse specified arguments.
        /// </summary>
        protected override Dictionary<string, object> ParseArguments(List<string> exampleArgs) {
            string[] requiredOptions = new string[] {"account_id"};
            bool showHelp = false;

            string accountId = null;
            string filter = null;
            string orderBy = null;
            int? pageSize = null;

            string defaultFilter = "deal.dealType = PROGRAMMATIC_GUARANTEED";
            string defaultOrderBy = "deal.flightStartTime desc";

            OptionSet options = new OptionSet {
                "List finalized deals for the given buyer account and their clients.",
                {
                    "h|help",
                    "Show help message and exit.",
                    h => showHelp = h != null
                },
                {
                    "a|account_id=",
                    ("[Required] The resource ID of the buyers resource under which the " +
                     "finalized deals are being retrieved. This will be used to construct the " +
                     "parent used as a path parameter for the finalizedDeals.list request."),
                    a => accountId = a
                },
                {
                    "f|filter=",
                    ("Query string to filter finalized deals. By default, this example will " +
                     "fitler by deal type to retrieve programmatic guaranteed deals to " +
                     "demonstrate usage."),
                    f => filter =  f
                },
                {
                    "o|order_by=",
                    ("Query string used to sort the response of the list method. By default, " +
                     "this example will return deals in descending order of their flight start " +
                     "time to demonstrate usage. To learn more about the syntax for this " +
                     "parameter, see: " +
                     "https://cloud.google.com/apis/design/design_patterns#sorting_order"),
                    o => orderBy =  o
                },
                {
                    "p|page_size=",
                    ("The number of rows to return per page. The server may return fewer rows " +
                     "than specified."),
                    (int p) => pageSize =  p
                },
            };

            List<string> extras = options.Parse(exampleArgs);
            var parsedArgs = new Dictionary<string, object>();

            // Show help message.
            if (showHelp == true)
            {
                options.WriteOptionDescriptions(Console.Out);
                Environment.Exit(0);
            }
            // Set arguments.
            parsedArgs["account_id"] = accountId;
            parsedArgs["filter"] = filter ?? defaultFilter;
            parsedArgs["order_by"] = orderBy ?? defaultOrderBy;
            parsedArgs["pageSize"] = pageSize ?? Utilities.MAX_PAGE_SIZE;
            // Validate that options were set correctly.
            Utilities.ValidateOptions(options, parsedArgs, requiredOptions, extras);

            return parsedArgs;
        }

        /// <summary>
        /// Run the example.
        /// </summary>
        /// <param name="parsedArgs">Parsed arguments for the example.</param>
        protected override void Run(Dictionary<string, object> parsedArgs)
        {
            string accountId = (string) parsedArgs["account_id"];
            string parent = $"buyers/{accountId}";
            string pageToken = null;

            Console.WriteLine(@"Listing finalized deals for buyer account ""{0}""", parent);
            do
            {
                BuyersResource.FinalizedDealsResource.ListRequest request =
                    mkService.Buyers.FinalizedDeals.List(parent);
                request.Filter = (string) parsedArgs["filter"];
                request.OrderBy = (string) parsedArgs["order_by"];
                request.PageSize = (int) parsedArgs["pageSize"];
                request.PageToken = pageToken;

                ListFinalizedDealsResponse page = null;

                try
                {
                    page = request.Execute();
                }
                catch (Exception exception)
                {
                    throw new ApplicationException(
                        $"Marketplace API returned error response:\n{exception.Message}");
                }

                var finalizedDeals = page.FinalizedDeals;
                pageToken = page.NextPageToken;

                if (finalizedDeals == null)
                {
                    Console.WriteLine("No finalized deals found for buyer account.");
                }
                else
                {
                    foreach (FinalizedDeal finalizedDeal in finalizedDeals)
                    {
                        Utilities.PrintFinalizedDeal(finalizedDeal);
                    }
                }
            }
            while(pageToken != null);
        }
    }
}

Java

/*
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.api.services.samples.authorizedbuyers.marketplace.v1.buyers.finalizedDeals;

import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.FinalizedDeal;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.ListFinalizedDealsResponse;
import com.google.api.services.samples.authorizedbuyers.marketplace.Utils;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.List;
import net.sourceforge.argparse4j.ArgumentParsers;
import net.sourceforge.argparse4j.inf.ArgumentParser;
import net.sourceforge.argparse4j.inf.ArgumentParserException;
import net.sourceforge.argparse4j.inf.Namespace;

/** This sample illustrates how to list finalized deals for a given buyer and their clients. */
public class ListFinalizedDeals {

  public static void execute(AuthorizedBuyersMarketplace marketplaceClient, Namespace parsedArgs) {
    Long accountId = parsedArgs.getLong("account_id");
    Integer pageSize = parsedArgs.getInt("page_size");
    String parentBuyerName = String.format("buyers/%d", accountId);
    String pageToken = null;

    System.out.printf("Found finalized deals for buyer account ID '%d':%n", accountId);

    do {
      List<FinalizedDeal> finalizedDeals = null;

      try {
        ListFinalizedDealsResponse response =
            marketplaceClient
                .buyers()
                .finalizedDeals()
                .list(parentBuyerName)
                .setFilter(parsedArgs.getString("filter"))
                .setOrderBy(parsedArgs.getString("order_by"))
                .setPageSize(pageSize)
                .setPageToken(pageToken)
                .execute();

        finalizedDeals = response.getFinalizedDeals();
        pageToken = response.getNextPageToken();
      } catch (IOException ex) {
        System.out.printf("Marketplace API returned error response:%n%s", ex);
        System.exit(1);
      }
      if (finalizedDeals == null) {
        System.out.println("No finalized deals found.");
      } else {
        for (FinalizedDeal finalizedDeal : finalizedDeals) {
          Utils.printFinalizedDeal(finalizedDeal);
        }
      }
    } while (pageToken != null);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("ListFinalizedDeals")
            .build()
            .defaultHelp(true)
            .description(("Lists finalized deals associated with the given buyer account."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the buyers resource under which the finalized deals are being"
                + " retrieved. This will be used to construct the parent used as a path parameter"
                + " for the finalizedDeals.list request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-f", "--filter")
        .help(
            "Query string to filter finalized deals. By default, this example will filter by "
                + "deal type to retrieve programmatic guaranteed deals to demonstrate usage.")
        .setDefault("deal.dealType = PROGRAMMATIC_GUARANTEED");
    parser
        .addArgument("-o", "--order_by")
        .help(
            "Query string used to sort the response of the list method. By default, this "
                + "example will return deals in descending order of their flight start time to "
                + "demonstrate usage. To learn more about the syntax for this parameter, see: "
                + "https://cloud.google.com/apis/design/design_patterns#sorting_order")
        .setDefault("deal.flightStartTime desc");
    parser
        .addArgument("-p", "--page_size")
        .help(
            "The number of rows to return per page. The server may return fewer rows than "
                + "specified.")
        .setDefault(Utils.getMaximumPageSize())
        .type(Integer.class);

    Namespace parsedArgs = null;
    try {
      parsedArgs = parser.parseArgs(args);
    } catch (ArgumentParserException ex) {
      parser.handleError(ex);
      System.exit(1);
    }

    AuthorizedBuyersMarketplace client = null;
    try {
      client = Utils.getMarketplaceClient();
    } catch (IOException ex) {
      System.out.printf("Unable to create Marketplace API service:%n%s", ex);
      System.out.println("Did you specify a valid path to a service account key file?");
      System.exit(1);
    } catch (GeneralSecurityException ex) {
      System.out.printf("Unable to establish secure HttpTransport:%n%s", ex);
      System.exit(1);
    }

    execute(client, parsedArgs);
  }
}


Python

#!/usr/bin/python
#
# Copyright 2021 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Lists finalized deals for the given buyers and their clients."""


import argparse
import os
import pprint
import sys

sys.path.insert(0, os.path.abspath('../../..'))

from googleapiclient.errors import HttpError

import util


_BUYER_NAME_TEMPLATE = 'buyers/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'


def main(marketplace, args):
    account_id = args.account_id
    list_filter = args.filter
    order_by = args.order_by
    page_size = args.page_size

    page_token = None
    more_pages = True

    print(f'Listing finalized deals for buyer account: "{account_id}".')
    while more_pages:
        try:
            # Construct and execute the request.
            response = marketplace.buyers().finalizedDeals().list(
                parent=_BUYER_NAME_TEMPLATE % account_id, pageToken=page_token,
                filter=list_filter, orderBy=order_by,
                pageSize=page_size).execute()
        except HttpError as e:
            print(e)
            sys.exit(1)

        pprint.pprint(response)

        page_token = response.get('nextPageToken')
        more_pages = bool(page_token)


if __name__ == '__main__':
    try:
        service = util.get_service(version='v1')
    except IOError as ex:
        print(f'Unable to create marketplace service - {ex}')
        print('Did you specify the key file in util.py?')
        sys.exit(1)

    parser = argparse.ArgumentParser(
        description=('Lists finalized deals for the given buyer account and '
                     'its clients.'))
    # Required fields.
    parser.add_argument(
        '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
        help=('The resource ID of the buyers resource for which the finalized '
              'deals are being retrieved. This will be used to construct the '
              'parent used as a path parameter for the finalizedDeals.list '
              'request.'))
    # Optional fields.
    parser.add_argument(
        '-f', '--filter', default='deal.dealType = PROGRAMMATIC_GUARANTEED',
        help=('Query string to filter clients. By default, this example will '
              'filter by deal type to retrieve programmatic guaranteed deals '
              'to demonstrate usage.'))
    parser.add_argument(
        '-o', '--order_by', default='deal.flightStartTime desc',
        help=('Query string used to sort the response of the list method. By '
              'default, this will return deals in descending order of their '
              'flight start time to demonstrate usage. To learn more about '
              'the syntax for this parameter, see: '
              'https://cloud.google.com/apis/design/design_patterns'
              '#sorting_order'))
    parser.add_argument(
        '-p', '--page_size', default=util.MAX_PAGE_SIZE,
        help=('The number of rows to return per page. The server may return '
              'fewer rows than specified.'))

    main(service, parser.parse_args())