Portal/rsconcept/backend/apps/oss/models/api_OSS.py

59 lines
2.0 KiB
Python

''' Models: OSS API. '''
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import QuerySet
from apps.rsform.models import LibraryItem, LibraryItemType
from shared import messages as msg
from .Argument import Argument
from .Operation import Operation, OperationType
from .SynthesisSubstitution import SynthesisSubstitution
class OperationSchema:
''' Operations schema API. '''
def __init__(self, item: LibraryItem):
if item.item_type != LibraryItemType.OPERATION_SCHEMA:
raise ValueError(msg.libraryTypeUnexpected())
self.item = item
@staticmethod
def create(**kwargs) -> 'OperationSchema':
item = LibraryItem.objects.create(item_type=LibraryItemType.OPERATION_SCHEMA, **kwargs)
return OperationSchema(item=item)
def operations(self) -> QuerySet[Operation]:
''' Get QuerySet containing all operations of current OSS. '''
return Operation.objects.filter(oss=self.item)
def arguments(self) -> QuerySet[Argument]:
''' Operation arguments. '''
return Argument.objects.filter(operation__oss=self.item)
def substitutions(self) -> QuerySet[SynthesisSubstitution]:
''' Operation arguments. '''
return SynthesisSubstitution.objects.filter(operation__oss=self.item)
@transaction.atomic
def create_operation(self, operation_type: OperationType, alias: str, **kwargs) -> Operation:
''' Insert new operation. '''
if self.operations().filter(alias=alias).exists():
raise ValidationError(msg.aliasTaken(alias))
result = Operation.objects.create(
oss=self.item,
alias=alias,
operation_type=operation_type,
**kwargs
)
self.item.save()
result.refresh_from_db()
return result
@transaction.atomic
def delete_operation(self, operation: Operation):
''' Delete operation. '''
operation.delete()
self.item.save()