Skip to content
This repository has been archived by the owner on Jul 21, 2022. It is now read-only.

Commit

Permalink
Merge 18e3b68 into b82d5e1
Browse files Browse the repository at this point in the history
  • Loading branch information
RasmusGodske authored May 11, 2022
2 parents b82d5e1 + 18e3b68 commit 828a7af
Show file tree
Hide file tree
Showing 20 changed files with 1,396 additions and 306 deletions.
17 changes: 17 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: Debug Tests",
"type": "python",
"request": "launch",
"program": "${file}",
"purpose": ["debug-test"],
"console": "integratedTerminal",
"justMyCode": false
}
]
}
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"editor.quickSuggestions": {
"comments": true
}
}
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ pytest-cov = "*"
pytest-order = "*"
pytest-depends = "*"
testcontainers = "*"
requests-mock = "*"

[packages]
origin-platform-utils = "0.6.5"
Expand Down
442 changes: 230 additions & 212 deletions Pipfile.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion chart/Chart.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ name: eo-meteringpoints
description: A Helm chart for Kubernetes

type: application
version: 0.1.6
version: 0.1.7

dependencies:
- name: eo-base-helm-chart
Expand Down
2 changes: 1 addition & 1 deletion chart/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ eo-base-helm-chart:
SQL_POOL_SIZE: 1
image:
repository: ghcr.io/energinet-datahub/eo-meteringpoints-api
tag: 0.1.6
tag: 0.1.7
pullPolicy: Always

envSecrets:
Expand Down
Empty file modified scripts/lint.sh
100644 → 100755
Empty file.
25 changes: 21 additions & 4 deletions src/meteringpoints_api/app.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
# First party
from meteringpoints_api.endpoints.create_meteringpoint_relations import (
CreateMeteringPointRelations,
)
from meteringpoints_api.endpoints.get_meteringpoint_details import (
GetMeteringPointDetails,
)
from meteringpoints_api.endpoints.get_meteringpoint_list import (
GetMeteringPointList,
)
from meteringpoints_shared.config import (
INTERNAL_TOKEN_SECRET,
)
from origin.api import Application, ScopedGuard

from meteringpoints_shared.config import INTERNAL_TOKEN_SECRET

from .endpoints import GetMeteringPointDetails, GetMeteringPointList


def create_app() -> Application:
"""Create a new instance of the application."""
Expand All @@ -28,4 +37,12 @@ def create_app() -> Application:
guards=[ScopedGuard('meteringpoints.read')],
)

app.add_endpoint(
method='POST',
path='/createrelations',
endpoint=CreateMeteringPointRelations(),
# Should require write too in the future
guards=[ScopedGuard('meteringpoints.read')],
)

return app
80 changes: 0 additions & 80 deletions src/meteringpoints_api/endpoints.py

This file was deleted.

148 changes: 148 additions & 0 deletions src/meteringpoints_api/endpoints/create_meteringpoint_relations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
from typing import List, Optional
from dataclasses import dataclass

from origin.api import Endpoint, Context
from origin.models.meteringpoints import MeteringPoint
from meteringpoints_shared.config import DATASYNC_BASE_URL
from meteringpoints_shared.datasync_httpclient import DataSyncHttpClient


class CreateMeteringPointRelations(Endpoint):
"""Returns details about a single MeteringPoint."""

@dataclass
class Request:
"""TODO."""

tin: Optional[str]
ssn: Optional[str] = None

@dataclass
class Response:
"""TODO."""

success: bool

def handle_request(
self,
request: Request,
context: Context,
) -> Response:
"""Handle HTTP request."""

http_client = DataSyncHttpClient(
base_url=DATASYNC_BASE_URL,
internal_token=context.internal_token_encoded,
)

try:
meteringpoint_ids = get_meteringpoint_ids(
datasync_http_client=http_client,
request=request,
)

create_meteringpoint_relationships(
datasync_http_client=http_client,
request=request,
meteringpoint_ids=meteringpoint_ids,
)

except Exception as error:
print(f'failed to create relationship: {error}')
return self.Response(
success=False,
)

return self.Response(
success=True,
)

# --- Helper functions -------------------------------------


def get_meteringpoint_ids(
datasync_http_client: DataSyncHttpClient,
request: CreateMeteringPointRelations.Request
) -> List[str]:
"""
Return list of meteringpoint ids, belonging to user.
:param datasync_http_client: Datasync http client
:type datasync_http_client: DataSyncHttpClient
:param request: Request object
:type request: CreateMeteringPointRelations.Request
:raises Exception: Raises exception on any kind of error
:return: List of meteringpoint ids
:rtype: List[str]
"""
meteringpoints: List[str] = []

if request.tin:
meteringpoints = datasync_http_client.get_meteringpoints_by_tin(
request.tin
)
elif request.ssn:
# IMPLEMENT THIS
print("httpClient.get_meteringpoints_by_ssn() not implemented")
pass
else:
raise Exception(
"Either request.tin or request.ssn needs to be defined"
)

meteringpoint_ids = [MeteringPoint(gsrn=mp) for mp in meteringpoints]

if not meteringpoint_ids:
raise Exception("No meteringpoints found for user")

return meteringpoint_ids


def create_meteringpoint_relationships(
datasync_http_client: DataSyncHttpClient,
request: CreateMeteringPointRelations.Request,
meteringpoint_ids: List[str]
) -> bool:
"""
Create relationships between user and provided meteringpoint.
Calls datasync service to create relationships between meterinpoints
and user.
:param datasync_http_client: DataSync http client
:type datasync_http_client: DataSyncHttpClient
:param request: Request object
:type request: CreateMeteringPointRelations.Request
:param meteringpoint_ids: Meteringpoint ids(gsrn)
:type meteringpoint_ids: List[str]
:raises Exception: Raised on any error
:return: True if successful False on error
:rtype: bool
"""
if request.tin:
name_id = request.tin
elif request.ssn:
name_id = request.ssn
else:
raise Exception(
"Either request.tin or request.ssn needs to be defined"
)

meteringpoint_relationship_results = datasync_http_client.\
create_meteringpoint_relationships(
name_id=name_id,
meteringpoint_ids=meteringpoint_ids,
)

if len(meteringpoint_relationship_results.failed_relationships) != 0:
fail_count = len(
meteringpoint_relationship_results.failed_relationships
)
mp_count = len(meteringpoint_ids)

raise Exception(
f'Failed to create {fail_count}/{mp_count} relationships'
)

return True
49 changes: 49 additions & 0 deletions src/meteringpoints_api/endpoints/get_meteringpoint_details.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
# Standard Library
from dataclasses import dataclass
from typing import Optional

# First party
from meteringpoints_shared.db import db
from meteringpoints_shared.queries import (
MeteringPointQuery,
)
from origin.api import Context, Endpoint
from origin.models.meteringpoints import (
MeteringPoint,
)


class GetMeteringPointDetails(Endpoint):
"""Returns details about a single MeteringPoint."""

@dataclass
class Request:
"""TODO."""

gsrn: str

@dataclass
class Response:
"""TODO."""

success: bool
meteringpoint: Optional[MeteringPoint]

@db.session()
def handle_request(
self,
request: Request,
context: Context,
session: db.Session,
) -> Response:
"""Handle HTTP request."""

meteringpoint = MeteringPointQuery(session) \
.is_accessible_by(context.token.subject) \
.has_gsrn(request.gsrn) \
.one_or_none()

return self.Response(
success=meteringpoint is not None,
meteringpoint=meteringpoint,
)
Loading

0 comments on commit 828a7af

Please sign in to comment.