ดูดีลที่กําลังดําเนินการ

คุณใช้วิธีการต่อไปนี้เพื่อดูไฟล์ที่กำลังดำเนินการอยู่ได้ ดีลสำหรับบัญชีผู้ซื้อ และลูกค้าของคุณ

ดูดีลแต่ละรายการ

คุณสามารถใช้ buyers.proposals.deals.get วิธีดึงข้อมูล Deal เฉพาะที่เชื่อมโยงกับข้อเสนอสำหรับผู้ซื้อ หรือลูกค้าของคุณ

ตัวอย่างต่อไปนี้แสดงวิธีดึงข้อมูล Deal แต่ละรายการที่มี เมธอด get

REST

ส่งคำขอ

GET https://authorizedbuyersmarketplace.googleapis.com/v1/buyers/12345678/proposals/MP21673270/deals/52404?alt=json
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

คำตอบ

{
 "name": "buyers/12345678/proposals/MP21673270/deals/52404",
 "createTime": "2036-12-27T04:02:39.731Z",
 "updateTime": "2036-12-27T04:03:51.097Z",
 "proposalRevision": "4",
 "displayName": "test_deal_7435251",
 "buyer": "buyers/12345678",
 "publisherProfile": "buyers/12345678/publisherProfiles/PP54321",
 "flightStartTime": "2036-12-28T00:00:00Z",
 "flightEndTime": "2036-12-30T23:59:00Z",
 "targeting": {
   "inventorySizeTargeting": {
     "targetedInventorySizes": [
       {
         "width": "1024",
         "height": "768",
         "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": "100",
   "fixedPrice": {
     "type": "CPM",
     "amount": {
       "currencyCode": "CNY",
       "units": "10"
     }
   },
   "reservationType": "STANDARD"
 },
 "sellerTimeZone": {
   "id": "Asia/Shanghai"
 }
}

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.Clients.Users
{
    /// <summary>
    /// Deletes client user for the given buyer, client, and user IDs.
    /// </summary>
    public class DeleteClientUsers : ExampleBase
    {
        private AuthorizedBuyersMarketplaceService mkService;

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

        /// <summary>
        /// Returns a description about the code example.
        /// </summary>
        public override string Description
        {
            get => "This code example deletes a specific client user for a given client.";
        }

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

            string accountId = null;
            string clientId = null;
            string userId = null;


            OptionSet options = new OptionSet {
                "Delete a client user with the given buyer, client, and user 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 parent " +
                     "client was created. This will be used to construct the name used as a path " +
                     "parameter for the users.delete request."),
                    a => accountId = a
                },
                {
                    "c|client_id=",
                    ("[Required] The resource ID of the buyers.clients resource for which the " +
                     "client user was created. This will be used to construct the name used as " +
                     "a path parameter for the users.delete request."),
                    c => clientId = c
                },
                {
                    "u|user_id=",
                    ("[Required] The resource ID of the buyers.clients.users resource for which " +
                     "the client user was created. This will be used to construct the name used " +
                     "as a path parameter for the users.delete request."),
                    u => userId = u
                },
            };

            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["client_id"] = clientId;
            parsedArgs["user_id"] = userId;
            // 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 clientId = (string) parsedArgs["client_id"];
            string userId = (string) parsedArgs["user_id"];
            string name = $"buyers/{accountId}/clients/{clientId}/users/{userId}";

            BuyersResource.ClientsResource.UsersResource.DeleteRequest request =
                mkService.Buyers.Clients.Users.Delete(name);

            Console.WriteLine("Deleting client user with name: {0}", name);

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

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.clients.users;

import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace;
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 delete a client user for the given buyer, client, and user IDs.
 */
public class DeleteClientUsers {

  public static void execute(AuthorizedBuyersMarketplace marketplaceClient, Namespace parsedArgs) {
    Long accountId = parsedArgs.getLong("account_id");
    Long clientId = parsedArgs.getLong("client_id");
    Long clientUserId = parsedArgs.getLong("client_user_id");
    String name = String.format("buyers/%d/clients/%d/users/%d", accountId, clientId, clientUserId);

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

    System.out.printf("Deleted client user with name \"%s\":%n", name);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("DeactivateClientUsers")
            .build()
            .defaultHelp(true)
            .description(("Delete a client user with the given buyer, client, and user ID."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the buyers resource under which the parent client was created. "
                + "This will be used to construct the name used as a path parameter for the "
                + "users.delete request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-c", "--client_id")
        .help(
            "The resource ID of the buyers.clients resource under which the client user was"
                + " created. This will be used to construct the name used as a path parameter for"
                + " the users.delete request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("-u", "--client_user_id")
        .help(
            "The resource ID of the buyers.clients.users resource that is being deleted. "
                + "This will be used to construct the name used as a path parameter for the "
                + "users.delete 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.

"""Deletes a user with the given account, client, and user ID.

Note that this is intended to completely disassociate a given client user from a
client. As a result, the email associated with the client user will lose access
to the Authorized Buyers UI once it is deleted. To restore access, create and
activate a new client user using the same email address.
"""


import argparse
import os
import pprint
import sys

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

from googleapiclient.errors import HttpError

import util


_CLIENT_USERS_NAME_TEMPLATE = 'buyers/%s/clients/%s/users/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'
DEFAULT_CLIENT_RESOURCE_ID = 'ENTER_CLIENT_RESOURCE_ID_HERE'
DEFAULT_CLIENT_USER_RESOURCE_ID = 'ENTER_CLIENT_USER_RESOURCE_ID_HERE'


def main(marketplace, args):
  client_user_name = _CLIENT_USERS_NAME_TEMPLATE % (
      args.account_id, args.client_id, args.client_user_id)

  print(f'Deleting client user with name "{client_user_name}".')
  try:
    # Construct and execute the request.
    response = marketplace.buyers().clients().users().delete(
        name=client_user_name).execute()
  except HttpError as e:
    print(e)
    sys.exit(1)


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=('Delete a client user for the given buyer account, client, '
                   'and client user ID.'))
  # Required fields.
  parser.add_argument(
      '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
      help=('The resource ID of the buyers resource under which the client '
            'user was created. This will be used to construct the name used as '
            'a path parameter for the users.delete request.'))
  parser.add_argument(
      '-c', '--client_id', default=DEFAULT_CLIENT_RESOURCE_ID,
      help=('The resource ID of the buyers.clients resource under which the '
            'client user was created. This will be used to construct the name '
            'used as a path parameter for the users.delete request.'))
  parser.add_argument(
      '-u', '--client_user_id', default=DEFAULT_CLIENT_USER_RESOURCE_ID,
      help=('The resource ID of the buyers.clients.users resource for which '
            'the client user was created. This will be used to construct the '
            'name used as a path parameter for the users.delete request.'))

  main(service, parser.parse_args())

แสดงดีลหลายรายการ

คุณสามารถใช้ buyers.proposals.deals.list เพื่อเลื่อนดูดีลทั้งหมดที่เชื่อมโยงกับข้อเสนอสำหรับบัญชีของคุณ หรือ ลูกค้าของคุณ

ตัวอย่างต่อไปนี้แสดงวิธีแสดงดีลด้วยเมธอด list

REST

ส่งคำขอ

GET https://authorizedbuyersmarketplace.googleapis.com/v1/buyers/12345678/proposals/MP21673270/deals?pageSize=50&alt=json
Authorization: Bearer ACCESS_TOKEN
Content-Type: application/json

คำตอบ

{
 "deals": [
   {
     "name": "buyers/12345678/proposals/MP21673270/deals/52404",
     "createTime": "2036-12-27T04:02:39.731Z",
     "updateTime": "2036-12-27T04:03:51.097Z",
     "proposalRevision": "4",
     "displayName": "test_deal_7435251",
     "buyer": "buyers/12345678",
     "publisherProfile": "buyers/12345678/publisherProfiles/PP54321",
     "flightStartTime": "2036-12-28T00:00:00Z",
     "flightEndTime": "2036-12-30T23:59:00Z",
     "targeting": {
       "inventorySizeTargeting": {
         "targetedInventorySizes": [
           {
             "width": "1024",
             "height": "768",
             "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": "100",
       "fixedPrice": {
         "type": "CPM",
         "amount": {
           "currencyCode": "CNY",
           "units": "10"
         }
       },
       "reservationType": "STANDARD"
     },
     "sellerTimeZone": {
       "id": "Asia/Shanghai"
     }
   }
 ]
}

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.Proposals.Deals
{
    /// <summary>
    /// Lists deals for the given buyer's proposal.
    /// </summary>
    public class ListDeals : ExampleBase
    {
        private AuthorizedBuyersMarketplaceService mkService;

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

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

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

            string accountId = null;
            string proposalId = null;
            int? pageSize = null;

            OptionSet options = new OptionSet {
                "List deals for a given buyer's proposal.",
                {
                    "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 " +
                     "deals are being retrieved. This will be used to construct the parent used " +
                     "as a path parameter for the deals.list request."),
                    a => accountId = a
                },
                {
                    "proposal_id=",
                    ("[Required] The resource ID of the buyers.proposals resource under which " +
                     "the deals are being retrieved. This will be used to construct the parent " +
                     "used as a path parameter for the deals.list request."),
                    p => proposalId = p
                },
                {
                    "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["proposal_id"] = proposalId;
            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 proposalId = (string) parsedArgs["proposal_id"];
            string parent = $"buyers/{accountId}/proposals/{proposalId}";
            string pageToken = null;

            Console.WriteLine(@"Listing deals for proposal with name ""{0}""", parent);
            do
            {
                BuyersResource.ProposalsResource.DealsResource.ListRequest request =
                    mkService.Buyers.Proposals.Deals.List(parent);
                request.PageSize = (int) parsedArgs["pageSize"];
                request.PageToken = pageToken;

                ListDealsResponse page = null;

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

                var deals = page.Deals;
                pageToken = page.NextPageToken;

                if (deals == null)
                {
                    Console.WriteLine("No deals found for specified proposal.");
                }
                else
                {
                    foreach (Deal deal in deals)
                    {
                        Utilities.PrintDeal(deal);
                    }
                }
            }
            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.proposals.deals;

import com.google.api.services.authorizedbuyersmarketplace.v1.AuthorizedBuyersMarketplace;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.Deal;
import com.google.api.services.authorizedbuyersmarketplace.v1.model.ListDealsResponse;
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 deals for the given buyer's proposal. */
public class ListDeals {

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

    System.out.printf("Found deals for proposal with name \"%s\":%n", parent);

    do {
      List<Deal> deals = null;

      try {
        ListDealsResponse response =
            marketplaceClient
                .buyers()
                .proposals()
                .deals()
                .list(parent)
                .setPageSize(pageSize)
                .setPageToken(pageToken)
                .execute();

        deals = response.getDeals();
        pageToken = response.getNextPageToken();
      } catch (IOException ex) {
        System.out.printf("Marketplace API returned error response:%n%s", ex);
        System.exit(1);
      }
      if (deals == null) {
        System.out.println("No proposals found.");
      } else {
        for (Deal deal : deals) {
          Utils.printDeal(deal);
        }
      }
    } while (pageToken != null);
  }

  public static void main(String[] args) {
    ArgumentParser parser =
        ArgumentParsers.newFor("ListDeals")
            .build()
            .defaultHelp(true)
            .description(("Lists deals for the given buyer's proposal."));
    parser
        .addArgument("-a", "--account_id")
        .help(
            "The resource ID of the buyers resource under which the deals are being retrieved. This"
                + " will be used to construct the parent used as a path parameter for the"
                + " deals.list request.")
        .required(true)
        .type(Long.class);
    parser
        .addArgument("--proposal_id")
        .help(
            "The resource ID of the buyers.proposals resource under which the deals are being"
                + " retrieved. This will be used to construct the parent used as a path parameter"
                + " for the deals.list request.")
        .required(true);
    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.

"""This example lists deals for the specified buyer's proposal."""


import argparse
import os
import pprint
import sys

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

from googleapiclient.errors import HttpError

import util


_PROPOSAL_NAME_TEMPLATE = 'buyers/%s/proposals/%s'

DEFAULT_BUYER_RESOURCE_ID = 'ENTER_BUYER_RESOURCE_ID_HERE'
DEFAULT_PROPOSAL_RESOURCE_ID = 'ENTER_PROPOSAL_RESOURCE_ID_HERE'


def main(marketplace, args):
    proposal_name = _PROPOSAL_NAME_TEMPLATE % (
        args.account_id, args.proposal_id)
    page_size = args.page_size

    page_token = None
    more_pages = True

    print(f'Listing deals for proposal "{proposal_name}":')
    while more_pages:
        try:
            # Construct and execute the request.
            response = marketplace.buyers().proposals().deals().list(
                parent=proposal_name, pageToken=page_token,
                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 deals for the given buyer\'s proposal.')
    # Required fields.
    parser.add_argument(
        '-a', '--account_id', default=DEFAULT_BUYER_RESOURCE_ID,
        help=('The resource ID of the buyers resource under which the deals '
              'were created. This will be used to construct the parent used as '
              'a path parameter for the deals.list request.'))
    parser.add_argument(
        '-p', '--proposal_id', default=DEFAULT_PROPOSAL_RESOURCE_ID,
        help=('The resource ID of the buyers.proposals resource under which '
              'the deals were created. This will be used to construct the name '
              'used as a path parameter for the deals.list request.'))
    # Optional fields.
    parser.add_argument(
        '--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())