Skip to content

Commit

Permalink
Support setting billing account on Collection
Browse files Browse the repository at this point in the history
  • Loading branch information
JureZmrzlikar committed Jun 13, 2022
1 parent 2fb653a commit a2b0ad8
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
9 changes: 9 additions & 0 deletions docs/CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ Change Log
All notable changes to this project are documented in this file.


==========
Unreleased
==========

Added
-----
- Support setting billing account on ``Collection`` resource


===================
15.0.0 - 2022-06-06
===================
Expand Down
16 changes: 16 additions & 0 deletions src/resdk/resources/collection.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
"""Collection resources."""
import logging
from urllib.parse import urljoin

from resdk.shortcuts.collection import CollectionRelationsMixin

from ..utils.decorators import assert_object_exists
from .base import BaseResolweResource
from .descriptor import DescriptorSchema
from .utils import _get_billing_account_id


class BaseCollection(BaseResolweResource):
Expand Down Expand Up @@ -203,3 +205,17 @@ def duplicate(self):
"""
duplicated = self.api().duplicate.post({"ids": [self.id]})
return self.__class__(resolwe=self.resolwe, **duplicated[0])

@assert_object_exists
def assign_to_billing_account(self, billing_account_name):
"""Assign given collection to a billing account."""
billing_account_id = _get_billing_account_id(self.resolwe, billing_account_name)

# Assign collection to a billing account
response = self.resolwe.session.post(
urljoin(
self.resolwe.url, f"api/billingaccount/{billing_account_id}/collection"
),
data={"collection_id": self.id},
)
response.raise_for_status()
15 changes: 15 additions & 0 deletions src/resdk/resources/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
"""Resource utility functions."""
import functools
from datetime import datetime
from urllib.parse import urljoin

import pytz
import tzlocal
Expand Down Expand Up @@ -204,3 +206,16 @@ def parse_resolwe_datetime(dtime):
local_time = utc_aware.astimezone(local_tz)

return local_time


@functools.lru_cache(128)
def _get_billing_account_id(res, name):
"""Get billing account ID based on it's name."""
response = res.session.get(urljoin(res.url, f"api/billingaccount"))
if not response.json():
raise ValueError(f"You do not have sufficient permissions for assigning billing accounts.")
for item in response.json():
if item["name"] == name:
return item["id"]
else:
raise ValueError(f'Could not find a billing account with name "{name}"')

0 comments on commit a2b0ad8

Please sign in to comment.