Esempio n. 1
0
class IncrementEvent(Model.REA.Entity):
    """
    Economic Event represents either an increment or a decrement in the
    value of economic resources that are under the control of the enterprise.
    Some economic events occur instantaneously, such as sales of goods; some
    occur over time, such as rentals, labor acquisition, and provision and use
    of services.

    # Model-Driven Design Using Business Patterns
    # Authors: Hruby, Pavel
    # ISBN-10 3-540-30154-2 Springer Berlin Heidelberg New York
    # ISBN-13 978-3-540-30154-7 Springer Berlin Heidelberg New York
    """
    id = Integer(primary_key=True, foreign_key=Model.REA.Entity.use('id'))

    provider = Many2One(label="Agent provider",
                        model=Model.REA.Agent,
                        nullable=False)

    resource = Many2One(label='Resource Inflow',
                        model=Model.REA.Resource,
                        nullable=False)

    value = Decimal(label="increment value", default=decimalType(0))

    date = DateTime(label="Event Date",
                    default=lambda **kwargs: datetime.now())
Esempio n. 2
0
class HistoryInput:
    """Internal Model linking Operations with their inputs and together.

    The main purpose of this model is to represent the Direct Acyclic Graph
    (DAG) of Operations history, and its "weighing": the links to Operation
    inputs.

    Additionally, some things to keep track of for :ref:`cancel and oblivion
    <op_cancel_revert_obliviate>` are also stored there.
    """
    operation = Many2One(model='Model.Wms.Operation',
                         index=True,
                         primary_key=True,
                         foreign_key_options={'ondelete': 'cascade'})
    """The Operation we are interested in."""

    avatar = Many2One(model='Model.Wms.Goods.Avatar',
                      primary_key=True,
                      foreign_key_options={'ondelete': 'cascade'})
    """One of the inputs of the :attr:`operation`."""

    latest_previous_op = Many2One(model='Model.Wms.Operation', index=True)
    """The latest operation that affected :attr:`avatars` before :attr:`operation`.

    This is both the fundamental data structure suporting history (DAG)
    aspects of Operations, as is exposed in the :attr:`Operation.follows`
    and :attr:`Operation.followers` attributes and, on the other hand, the
    preservation of :attr:`reason
    <anyblok_wms_base.bloks.wms_core.goods.Avatar.reason>` for restore if
    needed, even after the :attr:`current operation <operation>` is done.
    """

    orig_dt_until = DateTime(label="Original dt_until of avatars")
    """Saving the original ``dt_until`` value of the :attr:`Avatar <avatar>`
Esempio n. 3
0
class DecrementCommitment(Model.REA.Entity):
    """
    Commitment is a promise or obligation of economic agents to perform
    an economic event in the future. For example, line items on a sales order
    represent commitments to sell goods.

    # Model-Driven Design Using Business Patterns
    # Authors: Hruby, Pavel
    # ISBN-10 3-540-30154-2 Springer Berlin Heidelberg New York
    # ISBN-13 978-3-540-30154-7 Springer Berlin Heidelberg New York
    """
    id = Integer(primary_key=True, foreign_key=Model.REA.Entity.use('id'))

    recipient = Many2One(label="Agent recipient",
                         model=Model.REA.Agent,
                         nullable=False)

    resource = Many2One(label="Reservation Resource",
                        model=Model.REA.Resource,
                        nullable=False)

    value = Decimal(label="Value decrement", default=decimalType(0))

    fulfilled = Boolean(label="Is Fulfilled", default=False)

    def fulfill(self):
        """
        :return: True if commitment is fulfilled
        """
        if not self.fulfilled:
            self.registry.REA.DecrementEvent.create_event_from_commitment(self)
            self.fulfilled = True
            return True
        return False
Esempio n. 4
0
class Root(Declarations.Model.FuretUI.Menu,
           Declarations.Mixin.FuretUIMenuChildren):
    id = Integer(primary_key=True,
                 foreign_key=Declarations.Model.FuretUI.Menu.use('id'))
    label = String()
    type = Selection(selections={
        'space': 'Space',
        'resource': 'Resource'
    },
                     default='space',
                     nullable=False)
    resource = Many2One(model=Declarations.Model.FuretUI.Resource)
    space = Many2One(model=Declarations.Model.FuretUI.Space)

    # TODO check resource space requirement

    def get_i18n_to_export(self, external_id):
        if not self.label:
            return []

        return [(f'menu:{external_id}', self.label)]

    def delete(self, *a, **kw):
        print('titi 1')
        query = f"delete from {self.__tablename__} where id={self.id};"
        print(query)
        self.execute_sql_statement(text(query))
        print('titi 2')
        query = f"delete from furetui_menu where id={self.id};"
        print(query)
        self.execute_sql_statement(text(query))
        print('titi 3')
Esempio n. 5
0
 class Address:
     id = Integer(primary_key=True)
     street = String(nullable=False)
     city = Many2One(model=Declarations.Model.City, nullable=False)
     customer = Many2One(model=Declarations.Model.Customer,
                         nullable=False,
                         one2many="addresses")
Esempio n. 6
0
class Reservation:

    physobj = Many2One(model=Wms.PhysObj, primary_key=True, index=True)
    quantity = Integer()
    """The quantity that this Reservation provides.

    If the PhysObj in the application have ``quantity`` field
    (see :ref:`improvement_no_quantities`), this is not necessarily its value
    within :attr:`goods`. Instead, it is the quantity within the
    :attr:`request_item` that the current Reservation provides.

    Use-case some PhysObj being sold either as packs of 10 or by
    the unit. If one wants to reserve 13 of them,
    it should be expressable as one pack of 10 and 3 units.
    Then maybe (depending on the needs), would it be actually
    smarter of the application to not issue an Unpack.
    """
    request_item = Many2One(model=Wms.Reservation.RequestItem, index=True)

    goods = Function(fget='_goods_get', fset='_goods_set', fexpr='_goods_expr')
    """Compatibility wrapper.

    Before the merge of Goods and Locations as PhysObj, :attr:`physobj` was
    ``goods``.

    This does not extend to compatibility of the former low level ``goods_id``
    column.
    """
    def _goods_get(self):
        deprecation_warn_goods()
        return self.physobj

    def _goods_set(self, value):
        deprecation_warn_goods()
        self.physobj = value

    @classmethod
    def _goods_expr(cls):
        deprecation_warn_goods()
        return cls.physobj

    @classmethod
    def define_table_args(cls):
        return super(Reservation, cls).define_table_args() + (CheckConstraint(
            'quantity > 0', name='positive_qty'), )

    def is_transaction_owner(self):
        """Check that the current transaction is the owner of the reservation.
        """
        return self.request_item.request.is_txn_reservations_owner()

    def is_transaction_allowed(self,
                               opcls,
                               state,
                               dt_execution,
                               inputs=None,
                               **kwargs):
        """TODO add allowances, like a Move not far."""
        return self.is_transaction_owner()
Esempio n. 7
0
class Menu:

    id = Integer(primary_key=True)
    label = String(nullable=False)
    space = Many2One(model=Web.Space,
                     one2many='menus',
                     foreign_key_options={'ondelete': 'cascade'})
    parent = Many2One(model='Model.Web.Menu',
                      one2many='children',
                      foreign_key_options={'ondelete': 'cascade'})
    order = Integer(nullable=False, default=100)
    icon = String()
    position = Selection(selections=[('left',
                                      'On the left'), ('right',
                                                       'On the right')])
    type = Selection(selections=[('client', 'Client'), ('action', 'Action')],
                     default='action',
                     nullable=False)
    action = Many2One(model=Web.Action, one2many="menus")
    client = String()

    @classmethod
    def recMenu(cls, menus):
        res = []
        for menu in menus:
            actionId = ''
            if menu.type == 'client':
                actionId = menu.client
            elif menu.type == 'action':
                actionId = menu.action and menu.action.id or ''

            m = {
                'id': str(menu.id),
                'label': menu.label,
                'image': {
                    'type': 'font-icon',
                    'value': menu.icon
                },
                'actionId': actionId,
                'submenus': [],
            }
            if menu.children:
                query = cls.query().filter(cls.parent == menu)
                query = query.order_by(cls.order)
                m['submenus'] = cls.recMenu(query.all())

            res.append(m)

        return res

    @classmethod
    def getMenusForSpace(cls, space, position):
        query = cls.query().filter(
            cls.space == space,
            cls.parent == None,  # noqa
            cls.position == position)
        query = query.order_by(cls.order)
        return cls.recMenu(query.all())
Esempio n. 8
0
    class Person:

        id = Integer(primary_key=True)
        address_1_id = Integer(foreign_key=Model.Address.use('id'))
        address_2_id = Integer(foreign_key=Model.Address.use('id'))
        address_1 = Many2One(model=Model.Address,
                             column_names=['address_1_id'])
        address_2 = Many2One(model=Model.Address,
                             column_names=['address_2_id'])
Esempio n. 9
0
class Address:

    id = Integer(primary_key=True)
    street = String(nullable=False)
    city = Many2One(model=Declarations.Model.City, nullable=False)
    customer = Many2One(model=Declarations.Model.Customer,
                        nullable=False,
                        foreign_key_options={'ondelete': 'cascade'},
                        one2many="addresses")
Esempio n. 10
0
 class PersonAddress:
     id = Integer(primary_key=True)
     person = Many2One(
         model='Model.Person', nullable=False,
         foreign_key_options={'ondelete': 'cascade'})
     address = Many2One(
         model=Model.Address, nullable=False,
         foreign_key_options={'ondelete': 'cascade'})
     create_at = DateTime(default=datetime.now)
     foo = String(default='bar')
Esempio n. 11
0
 class TestLink:
     id = Integer(primary_key=True)
     left = Many2One(
         model='Model.Test', nullable=False,
         foreign_key_options={'ondelete': 'cascade'})
     right = Many2One(
         model='Model.Test', nullable=False,
         foreign_key_options={'ondelete': 'cascade'})
     create_at = DateTime(default=datetime.now)
     foo = String(default='bar')
class EventGuest:
    guest = Many2One(
        model=Declarations.Model.Guest,
        primary_key=True,
        column_names="guest_id",
    )
    event = Many2One(
        model="Model.Event",
        primary_key=True,
        column_names="event_id",
    )
    position = Integer(label="Position of guest at an event")
Esempio n. 13
0
class Button:

    id = Integer(primary_key=True)
    action = Many2One(model=Model.Web.Action,
                      one2many='buttons',
                      foreign_key_options={'ondelete': 'cascade'})
    view = Many2One(model=Model.Web.View,
                    one2many='buttons',
                    foreign_key_options={'ondelete': 'cascade'})
    method = String(nullable=False)
    label = String(nullable=False)
    mode = Selection(selections=[('action', 'Action'), ('more', 'More')],
                     default='action',
                     nullable=False)
Esempio n. 14
0
class Search:

    id = Integer(primary_key=True)
    action = Many2One(model=Model.Web.Action, one2many='searchs',
                      foreign_key_options={'ondelete': 'cascade'})
    view = Many2One(model=Model.Web.View, one2many='searchs',
                    foreign_key_options={'ondelete': 'cascade'})
    fieldname = String(nullable=False)
    path = String()
    label = String()
    type = Selection(
        selections=[('search', 'Search on specific key'),
                    ('filter', 'Defined search')],
        default='search', nullable=False
    )

    def format_for_furetui(self, model):
        if self.path:
            key = self.path + '.' + self.fieldname
        else:
            key = self.fieldname

        Model = self.registry.get(model)
        for k in key.split('.')[:-1]:
            Model = Model.getRemoteModelFor(k)

        label = Model.fields_description(
            self.fieldname)[self.fieldname]['label']

        return {
            'fieldname': self.fieldname,
            'key': key,
            'model': Model.__registry_name__,
            'label': label,
            'type': self.type,
        }

    @classmethod
    def get_from_action(cls, action):
        res = []
        for search in action.searchs:
            res.append(search.format_for_furetui(action.model))
        return res

    @classmethod
    def get_from_view(cls, view):
        res = cls.get_from_action(view.action)
        for search in view.searchs:
            res.append(search.format_for_furetui(view.action.model))
        return res
Esempio n. 15
0
class Service(Mixin.UuidColumn, Mixin.TrackModel):
    """ Carrier service
    Model.Delivery.Carrier.Service
    """
    CARRIER_CODE = None

    name = String(label="Name", nullable=False, size=128)
    product_code = String(label="Product code", unique=True, nullable=False)
    carrier = Many2One(label="Name",
                       model=Declarations.Model.Delivery.Carrier,
                       one2many='services',
                       nullable=False)
    credential = Many2One(label="Credential",
                          model=Declarations.Model.Delivery.Carrier.Credential,
                          one2many='services',
                          nullable=False)
    properties = Jsonb(label="Properties")
    carrier_code = Selection(selections='get_carriers')

    @classmethod
    def define_mapper_args(cls):
        mapper_args = super(Service, cls).define_mapper_args()
        if cls.__registry_name__ == 'Model.Delivery.Carrier.Service':
            mapper_args.update({'polymorphic_on': cls.carrier_code})

        mapper_args.update({'polymorphic_identity': cls.CARRIER_CODE})
        return mapper_args

    @classmethod
    def query(cls, *args, **kwargs):
        query = super(Service, cls).query(*args, **kwargs)
        if cls.__registry_name__.startswith('Model.Delivery.Carrier.Service.'):
            query = query.filter(cls.carrier_code == cls.CARRIER_CODE)

        return query

    @classmethod
    def get_carriers(cls):
        return dict()

    def create_label(self, *args, **kwargs):
        raise Exception("Creating a label directly from Carrier.Service class "
                        "is Forbidden. Please use a specialized one like "
                        "Colissimo, Dhl, etc...")

    def get_label_status(self, *args, **kwargs):
        raise Exception("Update the status of the label directly from "
                        "Carrier.Service class is Forbidden. Please use "
                        "a specialized one like Colissimo, Dhl, etc...")
Esempio n. 16
0
class Room(Mixin.IdColumn, Mixin.TrackModel):

    name = String(label="Room name", nullable=False, index=True)
    capacity = Integer(label="Capacity", nullable=False)
    address = Many2One(
        label="Address", model=Model.Address, nullable=False, one2many="rooms"
    )
Esempio n. 17
0
    class Person:
        __db_schema__ = 'test_db_other_m2o_schema'

        name = String(primary_key=True)
        address = Many2One(model=Model.Address,
                           remote_columns="id", column_names="id_of_address",
                           one2many="persons", nullable=False)
Esempio n. 18
0
class Template:
    """Add family relationship to template
    """
    family = Many2One(label="Family",
                      model=Declarations.Model.Product.Family,
                      one2many='templates',
                      nullable=False)

    @classmethod
    def create(cls, family, **kwargs):
        data = kwargs.copy()
        if family.template_schema:
            sch = family.template_schema(registry=cls.registry)
            data = sch.load(kwargs, instances=dict(default=family))
        return cls.insert(family=family, **data)

    def amend(self, family, **kwargs):
        data = kwargs.copy()
        properties = data.pop('properties', dict())
        if properties:
            for k, v in properties.items():
                self.properties[k] = v
        if family.template_schema:
            sch = family.template_schema(registry=self.registry, partial=True)
            data.update(dict(properties=self.properties))
            data = sch.load(data, instances=dict(default=family))
        self.update(family=family, **data)
        return self
Esempio n. 19
0
class FuretUIMenuParent:
    parent = Many2One(
        model='Model.FuretUI.Menu',
        primaryjoin=("ModelFuretUIMenu.id == ModelFuretUIMenu.parent_id"
                     " and ModelFuretUIMenu.menu_type.in_(["
                     "'Model.FuretUI.Menu.Root', 'Model.FuretUI.Menu.Node'"
                     "])"))
class TodoItem:
    id = Integer(primary_key=True)
    name = String(label="Name", nullable=False)
    position = Integer(label="Position")
    todo_list = Many2One(
        label="Todo list",
        model=Model.TodoList,
        nullable=False,
        foreign_key_options={"ondelete": "cascade"},
        one2many=(
            "todo_items",
            dict(
                order_by="ModelTodoItem.position",
                collection_class=ordering_list("position"),
            ),
        ),
    )

    def __str__(self):
        return ("{self.position} {self.name}").format(self=self)

    def __repr__(self):
        msg = ("<TodoItem: position={self.position}, name={self.name}, "
               "id={self.id}>")
        return msg.format(self=self)
Esempio n. 21
0
    class TestView:
        code = String(primary_key=True)
        val1 = Integer(primary_key=True)
        val2 = Integer()
        parent = Many2One(model='Model.TestView')

        @classmethod
        def sqlalchemy_view_declaration(cls):
            T1 = cls.registry.T1
            TP = cls.registry.T1.aliased()
            T2 = cls.registry.T2
            subquery = union(
                select([
                    T1.code.label('code'),
                    TP.id.label('parent_val1'),
                    TP.code.label('parent_code')
                ]).where(T1.parent_id == TP.id),
                select([
                    T1.code.label('code'),
                    expression.literal_column("null as parent_val1"),
                    expression.literal_column("null as parent_code")
                ]).where(T1.parent_id.is_(None))
            ).alias()
            query = select([T1.code.label('code'),
                            T1.val.label('val1'),
                            T2.val.label('val2'),
                            subquery.c.parent_val1.label('parent_val1'),
                            subquery.c.parent_code.label('parent_code')])
            query = query.where(subquery.c.code == T1.code)
            query = query.where(subquery.c.code == T2.code)
            return query
Esempio n. 22
0
class State(Mixin.UuidColumn, Mixin.TrackModel):

    STATE_TYPE = None

    device = Many2One(
        label="Devie",
        model=Declarations.Model.Iot.Device,
        one2many="states",
        nullable=False,
    )
    state_type = Selection(selections="get_device_types", nullable=False)

    @classmethod
    def define_mapper_args(cls):
        mapper_args = super().define_mapper_args()
        if cls.__registry_name__ == "Model.Iot.State":
            mapper_args.update({"polymorphic_on": cls.state_type})

        mapper_args.update({"polymorphic_identity": cls.STATE_TYPE})
        return mapper_args

    @classmethod
    def get_device_types(cls):
        return dict(
            DESIRED_RELAY="RelayDesired",
            RELAY="Relay",
            TEMPERATURE="Thermometer",
            FUEL_GAUGE="fuelgauge",
            WEATHER_STATION="WeatherStation",
        )

    @classmethod
    def query(cls, *args, **kwargs):
        query = super().query(*args, **kwargs)
        if cls.__registry_name__.startswith("Model.Iot.State."):
            query = query.filter(cls.state_type == cls.STATE_TYPE)

        return query

    @classmethod
    def get_device_state(
        cls,
        code: str,
    ) -> Union["registry.Model.Iot.State.Relay",
               "registry.Model.Iot.State.DesiredRelay",
               "registry.Model.Iot.State.Thermometer",
               "registry.Model.Iot.State.FuelGauge",
               "registry.Model.Iot.State.WeatherStation", ]:
        """Cast states.State -> DeviceState is done throught fastAPI"""
        Device = cls.registry.Iot.Device
        state = (cls.query().join(Device).filter(Device.code == code).order_by(
            cls.registry.Iot.State.create_date.desc()).first())
        if not state:
            device = Device.query().filter_by(code=code).one()
            # We don't want to instert a new state here, just creating
            # a default instance
            state = cls(device=device)
            cls.registry.flush()
        return state
Esempio n. 23
0
        class TeamOwner:
            team = Many2One(model=Model.Team)

            @restrict_query_by_user()
            def restric_by_user_team(cls, query, user):
                User = cls.anyblok.Pyramid.User
                return (query.join(
                    cls.team).join(User).filter(User.login == user.login))
class Address:

    university = Many2One(
        label="University",
        model=Model.University,
        nullable=True,
        one2many="addresses",
    )
Esempio n. 25
0
class Color:

    id = Integer(primary_key=True)
    list_view = Many2One(model=Model.Web.View.List,
                         nullable=False, one2many="colors",
                         foreign_key_options={'ondelete': 'cascade'})
    name = String(nullable=False)
    condition = String(nullable=False)
Esempio n. 26
0
    class Person:

        name = String(primary_key=True)
        address = Many2One(model=Model.Address,
                           remote_columns="id",
                           column_names="id_of_address",
                           one2many="persons",
                           nullable=False)
Esempio n. 27
0
            class Test2:

                id = Integer(primary_key=True)
                other_test_id = Integer(
                    foreign_key=Model.Test.use('id'), nullable=False)
                other_test_id2 = String(
                    foreign_key=Model.Test.use('id2'), nullable=False)
                test = Many2One(model=Model.Test)
Esempio n. 28
0
class Item(Mixin.UuidColumn, Mixin.TrackModel):
    SCHEMA = PriceListItemSchema

    @classmethod
    def get_schema_definition(cls, **kwargs):
        return cls.SCHEMA(**kwargs)

    price_list = Many2One(label="Pricelist",
                          model=Declarations.Model.Sale.PriceList,
                          nullable=False,
                          one2many="price_list_items")
    item = Many2One(label="Product Item",
                    model=Declarations.Model.Product.Item,
                    nullable=False,
                    unique=True,
                    one2many="prices")
    unit_price_untaxed = Decimal(label="Price untaxed", default=D(0))
    unit_price = Decimal(label="Price", default=D(0))
    unit_tax = Decimal(label="Tax", default=D(0))

    def __str__(self):
        return "{self.item.code} {self.unit_price_untaxed}".format(self=self)

    def __repr__(self):
        return ("<PriceListItem(uuid={self.uuid}, item.code={self.item.code}, "
                "unit_price_untaxed={self.unit_price_untaxed}>").format(
                    self=self)

    @classmethod
    def create(cls, keep_gross=True, **kwargs):
        data = kwargs.copy()
        if cls.get_schema_definition:
            sch = cls.get_schema_definition(registry=cls.registry)
            data = sch.load(kwargs)
        net = data.get('unit_price_untaxed') or D(0)
        gross = data.get('unit_price') or D(0)
        tax = data.get('unit_tax') or D(0)
        price = compute_price(net=net,
                              gross=gross,
                              tax=tax,
                              keep_gross=keep_gross)
        data['unit_price_untaxed'] = price.net.amount
        data['unit_price'] = price.gross.amount
        data['unit_tax'] = compute_tax(tax)
        return cls.insert(**data)
Esempio n. 29
0
class History(Declarations.Mixin.DramatiqMessageStatus):
    """History of the state change for the message"""

    id = Integer(primary_key=True)
    message = Many2One(model=Declarations.Model.Dramatiq.Message,
                       one2many="histories",
                       nullable=False,
                       foreign_key_options={'ondelete': 'cascade'})
    error = Text()
Esempio n. 30
0
            class Test2:

                id = Integer(primary_key=True)
                test_id = Integer(
                    foreign_key=Model.Test.use('id'), nullable=False)
                test_id2 = String(
                    foreign_key=Model.Test.use('id2'), nullable=False)
                test = Many2One(model=Model.Test,
                                remote_columns=('id', 'id2'),
                                column_names=('test_id', 'test_id2'))