2018-08-08 19:25:53 +00:00
|
|
|
import uuid
|
|
|
|
from datetime import datetime
|
2018-11-11 20:52:55 +00:00
|
|
|
from typing import Union
|
2018-08-08 19:25:53 +00:00
|
|
|
|
2018-10-05 15:13:23 +00:00
|
|
|
from boltons import urlutils
|
2018-09-30 10:29:33 +00:00
|
|
|
from citext import CIText
|
2018-08-08 19:25:53 +00:00
|
|
|
from flask import g
|
2021-12-30 18:46:34 +00:00
|
|
|
from flask_login import current_user
|
2020-08-17 14:45:18 +00:00
|
|
|
from sqlalchemy import TEXT
|
2018-08-08 19:25:53 +00:00
|
|
|
from sqlalchemy.dialects.postgresql import UUID
|
|
|
|
from sqlalchemy_utils import LtreeType
|
|
|
|
from sqlalchemy_utils.types.ltree import LQUERY
|
2019-12-12 00:25:11 +00:00
|
|
|
from teal.db import CASCADE_OWN, UUIDLtree, check_range, IntEnum
|
2018-10-05 15:13:23 +00:00
|
|
|
from teal.resource import url_for_resource
|
2018-08-08 19:25:53 +00:00
|
|
|
|
2018-11-13 14:52:27 +00:00
|
|
|
from ereuse_devicehub.db import create_view, db, exp, f
|
2018-11-12 17:15:24 +00:00
|
|
|
from ereuse_devicehub.resources.device.models import Component, Device
|
2020-08-17 14:45:18 +00:00
|
|
|
from ereuse_devicehub.resources.enums import TransferState
|
2018-09-30 10:29:33 +00:00
|
|
|
from ereuse_devicehub.resources.models import Thing
|
2018-08-08 19:25:53 +00:00
|
|
|
from ereuse_devicehub.resources.user.models import User
|
|
|
|
|
|
|
|
|
|
|
|
class Lot(Thing):
|
2018-08-09 19:46:54 +00:00
|
|
|
id = db.Column(UUID(as_uuid=True), primary_key=True) # uuid is generated on init by default
|
2018-09-30 10:29:33 +00:00
|
|
|
name = db.Column(CIText(), nullable=False)
|
2018-11-06 17:08:57 +00:00
|
|
|
description = db.Column(CIText())
|
|
|
|
description.comment = """A comment about the lot."""
|
2018-08-08 19:25:53 +00:00
|
|
|
closed = db.Column(db.Boolean, default=False, nullable=False)
|
2019-06-19 11:35:26 +00:00
|
|
|
closed.comment = """A closed lot cannot be modified anymore."""
|
2019-12-09 16:24:24 +00:00
|
|
|
|
2018-08-08 19:25:53 +00:00
|
|
|
devices = db.relationship(Device,
|
2018-09-20 16:25:47 +00:00
|
|
|
backref=db.backref('lots', lazy=True, collection_class=set),
|
2018-08-08 19:25:53 +00:00
|
|
|
secondary=lambda: LotDevice.__table__,
|
2018-11-13 14:52:27 +00:00
|
|
|
lazy=True,
|
2018-08-08 19:25:53 +00:00
|
|
|
collection_class=set)
|
2019-06-19 11:35:26 +00:00
|
|
|
"""The **children** devices that the lot has.
|
2020-04-01 17:11:14 +00:00
|
|
|
|
|
|
|
Note that the lot can have more devices, if they are inside
|
2018-09-11 19:50:40 +00:00
|
|
|
descendant lots.
|
|
|
|
"""
|
2018-11-13 14:52:27 +00:00
|
|
|
parents = db.relationship(lambda: Lot,
|
|
|
|
viewonly=True,
|
|
|
|
lazy=True,
|
|
|
|
collection_class=set,
|
|
|
|
secondary=lambda: LotParent.__table__,
|
|
|
|
primaryjoin=lambda: Lot.id == LotParent.child_id,
|
|
|
|
secondaryjoin=lambda: LotParent.parent_id == Lot.id,
|
|
|
|
cascade='refresh-expire', # propagate changes outside ORM
|
|
|
|
backref=db.backref('children',
|
|
|
|
viewonly=True,
|
|
|
|
lazy=True,
|
|
|
|
cascade='refresh-expire',
|
|
|
|
collection_class=set)
|
|
|
|
)
|
|
|
|
"""The parent lots."""
|
|
|
|
|
|
|
|
all_devices = db.relationship(Device,
|
|
|
|
viewonly=True,
|
|
|
|
lazy=True,
|
|
|
|
collection_class=set,
|
|
|
|
secondary=lambda: LotDeviceDescendants.__table__,
|
|
|
|
primaryjoin=lambda: Lot.id == LotDeviceDescendants.ancestor_lot_id,
|
|
|
|
secondaryjoin=lambda: LotDeviceDescendants.device_id == Device.id)
|
|
|
|
"""All devices, including components, inside this lot and its
|
|
|
|
descendants.
|
|
|
|
"""
|
2021-02-05 12:21:20 +00:00
|
|
|
amount = db.Column(db.Integer, check_range('amount', min=0, max=100), default=0)
|
2020-04-01 17:11:14 +00:00
|
|
|
owner_id = db.Column(UUID(as_uuid=True),
|
2020-08-17 14:45:18 +00:00
|
|
|
db.ForeignKey(User.id),
|
|
|
|
nullable=False,
|
|
|
|
default=lambda: g.user.id)
|
2020-04-01 17:11:14 +00:00
|
|
|
owner = db.relationship(User, primaryjoin=owner_id == User.id)
|
2019-12-12 00:25:11 +00:00
|
|
|
transfer_state = db.Column(IntEnum(TransferState), default=TransferState.Initial, nullable=False)
|
|
|
|
transfer_state.comment = TransferState.__doc__
|
2019-12-19 00:38:03 +00:00
|
|
|
receiver_address = db.Column(CIText(),
|
2021-02-10 12:05:43 +00:00
|
|
|
db.ForeignKey(User.email),
|
|
|
|
nullable=False,
|
|
|
|
default=lambda: g.user.email)
|
|
|
|
receiver = db.relationship(User, primaryjoin=receiver_address == User.email)
|
2018-08-08 19:25:53 +00:00
|
|
|
|
2018-11-06 17:08:57 +00:00
|
|
|
def __init__(self, name: str, closed: bool = closed.default.arg,
|
|
|
|
description: str = None) -> None:
|
2019-06-19 11:35:26 +00:00
|
|
|
"""Initializes a lot
|
2018-08-09 19:46:54 +00:00
|
|
|
:param name:
|
|
|
|
:param closed:
|
|
|
|
"""
|
2018-11-06 17:08:57 +00:00
|
|
|
super().__init__(id=uuid.uuid4(), name=name, closed=closed, description=description)
|
2018-08-27 14:32:45 +00:00
|
|
|
Path(self) # Lots have always one edge per default.
|
2018-08-08 19:25:53 +00:00
|
|
|
|
2018-12-30 11:43:29 +00:00
|
|
|
@property
|
|
|
|
def type(self) -> str:
|
|
|
|
return self.__class__.__name__
|
|
|
|
|
2018-10-05 15:13:23 +00:00
|
|
|
@property
|
|
|
|
def url(self) -> urlutils.URL:
|
2019-05-11 14:27:22 +00:00
|
|
|
"""The URL where to GET this action."""
|
2018-10-05 15:13:23 +00:00
|
|
|
return urlutils.URL(url_for_resource(Lot, item_id=self.id))
|
|
|
|
|
2018-10-06 10:45:56 +00:00
|
|
|
@property
|
|
|
|
def descendants(self):
|
|
|
|
return self.descendantsq(self.id)
|
|
|
|
|
2021-05-31 09:34:46 +00:00
|
|
|
@property
|
|
|
|
def is_temporary(self):
|
2022-01-26 10:34:35 +00:00
|
|
|
return not bool(self.trade)
|
2021-05-31 09:34:46 +00:00
|
|
|
|
2021-12-30 18:46:34 +00:00
|
|
|
@property
|
2022-01-26 10:31:00 +00:00
|
|
|
def is_incoming(self):
|
|
|
|
return bool(self.trade and self.trade.user_to == current_user)
|
2021-12-30 18:46:34 +00:00
|
|
|
|
|
|
|
@property
|
|
|
|
def is_outgoing(self):
|
2022-01-26 10:34:35 +00:00
|
|
|
return bool(self.trade and self.trade.user_from == current_user)
|
2021-12-30 18:46:34 +00:00
|
|
|
|
2018-10-06 10:45:56 +00:00
|
|
|
@classmethod
|
|
|
|
def descendantsq(cls, id):
|
|
|
|
_id = UUIDLtree.convert(id)
|
|
|
|
return (cls.id == Path.lot_id) & Path.path.lquery(exp.cast('*.{}.*'.format(_id), LQUERY))
|
|
|
|
|
2018-08-09 22:52:01 +00:00
|
|
|
@classmethod
|
|
|
|
def roots(cls):
|
|
|
|
"""Gets the lots that are not under any other lot."""
|
2018-09-11 20:51:13 +00:00
|
|
|
return cls.query.join(cls.paths).filter(db.func.nlevel(Path.path) == 1)
|
2018-08-09 22:52:01 +00:00
|
|
|
|
2018-11-13 14:52:27 +00:00
|
|
|
def add_children(self, *children):
|
|
|
|
"""Add children lots to this lot.
|
|
|
|
|
|
|
|
This operation is highly costly as it forces refreshing
|
|
|
|
many models in session.
|
|
|
|
"""
|
|
|
|
for child in children:
|
|
|
|
if isinstance(child, Lot):
|
|
|
|
Path.add(self.id, child.id)
|
|
|
|
db.session.refresh(child)
|
|
|
|
else:
|
|
|
|
assert isinstance(child, uuid.UUID)
|
|
|
|
Path.add(self.id, child)
|
|
|
|
# We need to refresh the models involved in this operation
|
|
|
|
# outside the session / ORM control so the models
|
|
|
|
# that have relationships to this model
|
|
|
|
# with the cascade 'refresh-expire' can welcome the changes
|
|
|
|
db.session.refresh(self)
|
|
|
|
|
|
|
|
def remove_children(self, *children):
|
|
|
|
"""Remove children lots from this lot.
|
|
|
|
|
|
|
|
This operation is highly costly as it forces refreshing
|
|
|
|
many models in session.
|
|
|
|
"""
|
|
|
|
for child in children:
|
|
|
|
if isinstance(child, Lot):
|
|
|
|
Path.delete(self.id, child.id)
|
|
|
|
db.session.refresh(child)
|
|
|
|
else:
|
|
|
|
assert isinstance(child, uuid.UUID)
|
|
|
|
Path.delete(self.id, child)
|
|
|
|
db.session.refresh(self)
|
|
|
|
|
2018-11-11 20:52:55 +00:00
|
|
|
def delete(self):
|
|
|
|
"""Deletes the lot.
|
|
|
|
|
|
|
|
This method removes the children lots and children
|
|
|
|
devices orphan from this lot and then marks this lot
|
|
|
|
for deletion.
|
|
|
|
"""
|
2018-11-13 14:52:27 +00:00
|
|
|
self.remove_children(*self.children)
|
2018-11-11 20:52:55 +00:00
|
|
|
db.session.delete(self)
|
|
|
|
|
2018-11-13 14:52:27 +00:00
|
|
|
def _refresh_models_with_relationships_to_lots(self):
|
|
|
|
session = db.Session.object_session(self)
|
|
|
|
for model in session:
|
|
|
|
if isinstance(model, (Device, Lot, Path)):
|
|
|
|
session.expire(model)
|
|
|
|
|
2018-11-11 20:52:55 +00:00
|
|
|
def __contains__(self, child: Union['Lot', Device]):
|
|
|
|
if isinstance(child, Lot):
|
|
|
|
return Path.has_lot(self.id, child.id)
|
|
|
|
elif isinstance(child, Device):
|
|
|
|
device = db.session.query(LotDeviceDescendants) \
|
|
|
|
.filter(LotDeviceDescendants.device_id == child.id) \
|
|
|
|
.filter(LotDeviceDescendants.ancestor_lot_id == self.id) \
|
|
|
|
.one_or_none()
|
|
|
|
return device
|
|
|
|
else:
|
|
|
|
raise TypeError('Lot only contains devices and lots, not {}'.format(child.__class__))
|
2018-11-04 21:40:14 +00:00
|
|
|
|
2018-08-09 19:46:54 +00:00
|
|
|
def __repr__(self) -> str:
|
|
|
|
return '<Lot {0.name} devices={0.devices!r}>'.format(self)
|
|
|
|
|
2018-08-08 19:25:53 +00:00
|
|
|
|
|
|
|
class LotDevice(db.Model):
|
|
|
|
device_id = db.Column(db.BigInteger, db.ForeignKey(Device.id), primary_key=True)
|
|
|
|
lot_id = db.Column(UUID(as_uuid=True), db.ForeignKey(Lot.id), primary_key=True)
|
|
|
|
created = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
|
|
|
|
author_id = db.Column(UUID(as_uuid=True),
|
|
|
|
db.ForeignKey(User.id),
|
|
|
|
nullable=False,
|
|
|
|
default=lambda: g.user.id)
|
|
|
|
author = db.relationship(User, primaryjoin=author_id == User.id)
|
2019-06-19 11:35:26 +00:00
|
|
|
author_id.comment = """The user that put the device in the lot."""
|
2018-08-08 19:25:53 +00:00
|
|
|
|
|
|
|
|
2018-08-27 14:32:45 +00:00
|
|
|
class Path(db.Model):
|
2018-08-08 19:25:53 +00:00
|
|
|
id = db.Column(db.UUID(as_uuid=True),
|
|
|
|
primary_key=True,
|
|
|
|
server_default=db.text('gen_random_uuid()'))
|
2019-02-07 12:47:42 +00:00
|
|
|
lot_id = db.Column(db.UUID(as_uuid=True), db.ForeignKey(Lot.id), nullable=False)
|
2018-08-08 19:25:53 +00:00
|
|
|
lot = db.relationship(Lot,
|
2018-11-11 20:52:55 +00:00
|
|
|
backref=db.backref('paths',
|
|
|
|
lazy=True,
|
|
|
|
collection_class=set,
|
|
|
|
cascade=CASCADE_OWN),
|
2018-08-08 19:25:53 +00:00
|
|
|
primaryjoin=Lot.id == lot_id)
|
2018-08-09 19:46:54 +00:00
|
|
|
path = db.Column(LtreeType, nullable=False)
|
|
|
|
created = db.Column(db.TIMESTAMP(timezone=True), server_default=db.text('CURRENT_TIMESTAMP'))
|
2019-06-19 11:35:26 +00:00
|
|
|
created.comment = """When Devicehub created this."""
|
2018-08-08 19:25:53 +00:00
|
|
|
|
|
|
|
__table_args__ = (
|
2018-08-27 14:32:45 +00:00
|
|
|
# dag.delete_edge needs to disable internally/temporarily the unique constraint
|
|
|
|
db.UniqueConstraint(path, name='path_unique', deferrable=True, initially='immediate'),
|
2018-08-08 19:25:53 +00:00
|
|
|
db.Index('path_gist', path, postgresql_using='gist'),
|
2019-02-07 12:47:42 +00:00
|
|
|
db.Index('path_btree', path, postgresql_using='btree'),
|
|
|
|
db.Index('lot_id_index', lot_id, postgresql_using='hash')
|
2018-08-08 19:25:53 +00:00
|
|
|
)
|
|
|
|
|
2018-08-09 19:46:54 +00:00
|
|
|
def __init__(self, lot: Lot) -> None:
|
|
|
|
super().__init__(lot=lot)
|
|
|
|
self.path = UUIDLtree(lot.id)
|
|
|
|
|
2018-08-08 19:25:53 +00:00
|
|
|
@classmethod
|
|
|
|
def add(cls, parent_id: uuid.UUID, child_id: uuid.UUID):
|
|
|
|
"""Creates an edge between parent and child."""
|
|
|
|
db.session.execute(db.func.add_edge(str(parent_id), str(child_id)))
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def delete(cls, parent_id: uuid.UUID, child_id: uuid.UUID):
|
|
|
|
"""Deletes the edge between parent and child."""
|
|
|
|
db.session.execute(db.func.delete_edge(str(parent_id), str(child_id)))
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def has_lot(cls, parent_id: uuid.UUID, child_id: uuid.UUID) -> bool:
|
2018-09-11 19:50:40 +00:00
|
|
|
parent_id = UUIDLtree.convert(parent_id)
|
|
|
|
child_id = UUIDLtree.convert(child_id)
|
|
|
|
return bool(
|
|
|
|
db.session.execute(
|
|
|
|
"SELECT 1 from path where path ~ '*.{}.*.{}.*'".format(parent_id, child_id)
|
|
|
|
).first()
|
|
|
|
)
|
2018-11-11 20:52:55 +00:00
|
|
|
|
|
|
|
|
|
|
|
class LotDeviceDescendants(db.Model):
|
|
|
|
"""A view facilitating querying inclusion between devices and lots,
|
|
|
|
including components.
|
|
|
|
|
|
|
|
The view has 4 columns:
|
|
|
|
1. The ID of the device.
|
|
|
|
2. The ID of a lot containing the device.
|
|
|
|
3. The ID of the lot that directly contains the device.
|
|
|
|
4. If 1. is a component, the ID of the device that is inside the lot.
|
|
|
|
"""
|
|
|
|
|
|
|
|
_ancestor = Lot.__table__.alias(name='ancestor')
|
|
|
|
"""Ancestor lot table."""
|
|
|
|
_desc = Lot.__table__.alias()
|
|
|
|
"""Descendant lot table."""
|
|
|
|
lot_device = _desc \
|
|
|
|
.join(LotDevice, _desc.c.id == LotDevice.lot_id) \
|
|
|
|
.join(Path, _desc.c.id == Path.lot_id)
|
|
|
|
"""Join: Path -- Lot -- LotDevice"""
|
|
|
|
|
|
|
|
descendants = "path.path ~ (CAST('*.'|| replace(CAST({}.id as text), '-', '_') " \
|
|
|
|
"|| '.*' AS LQUERY))".format(_ancestor.name)
|
|
|
|
"""Query that gets the descendants of the ancestor lot."""
|
|
|
|
devices = db.select([
|
|
|
|
LotDevice.device_id,
|
|
|
|
_desc.c.id.label('parent_lot_id'),
|
2018-11-13 14:52:27 +00:00
|
|
|
_ancestor.c.id.label('ancestor_lot_id'),
|
2022-04-06 11:05:31 +00:00
|
|
|
db.column('padding') # foo column to have same nunber of columns on joined selects (union)
|
2019-01-23 16:59:29 +00:00
|
|
|
]).select_from(_ancestor).select_from(lot_device).where(db.text(descendants))
|
2018-11-11 20:52:55 +00:00
|
|
|
|
|
|
|
# Components
|
|
|
|
_parent_device = Device.__table__.alias(name='parent_device')
|
|
|
|
"""The device that has the access to the lot."""
|
|
|
|
lot_device_component = lot_device \
|
|
|
|
.join(_parent_device, _parent_device.c.id == LotDevice.device_id) \
|
|
|
|
.join(Component, _parent_device.c.id == Component.parent_id)
|
|
|
|
"""Join: Path -- Lot -- LotDevice -- ParentDevice (Device) -- Component"""
|
|
|
|
|
|
|
|
components = db.select([
|
|
|
|
Component.id.label('device_id'),
|
|
|
|
_desc.c.id.label('parent_lot_id'),
|
2018-11-13 14:52:27 +00:00
|
|
|
_ancestor.c.id.label('ancestor_lot_id'),
|
2018-11-11 20:52:55 +00:00
|
|
|
LotDevice.device_id.label('device_parent_id'),
|
2019-01-23 16:59:29 +00:00
|
|
|
]).select_from(_ancestor).select_from(lot_device_component).where(db.text(descendants))
|
2018-11-11 20:52:55 +00:00
|
|
|
|
2018-11-13 14:52:27 +00:00
|
|
|
__table__ = create_view('lot_device_descendants', devices.union(components))
|
|
|
|
|
|
|
|
|
|
|
|
class LotParent(db.Model):
|
|
|
|
i = f.index(Path.path, db.func.text2ltree(f.replace(exp.cast(Path.lot_id, TEXT), '-', '_')))
|
|
|
|
|
2018-11-11 20:52:55 +00:00
|
|
|
__table__ = create_view(
|
2018-11-13 14:52:27 +00:00
|
|
|
'lot_parent',
|
|
|
|
db.select([
|
|
|
|
Path.lot_id.label('child_id'),
|
|
|
|
exp.cast(f.replace(exp.cast(f.subltree(Path.path, i - 1, i), TEXT), '_', '-'),
|
|
|
|
UUID).label('parent_id')
|
|
|
|
]).select_from(Path).where(i > 0),
|
2018-11-11 20:52:55 +00:00
|
|
|
)
|