class RepresentedRepresentor(Entity): """Relation from a representing party to the person representing the party""" using_options(tablename='party_representor') from_date = Field(Date(), default=datetime.date.today, required=True, index=True) thru_date = Field(Date(), default=end_of_times, required=True, index=True) comment = Field(camelot.types.RichText()) established_from = ManyToOne(Person, required=True, ondelete='cascade', onupdate='cascade') established_to = ManyToOne(DirectedDirector, required=True, ondelete='cascade', onupdate='cascade') class Admin(EntityAdmin): verbose_name = _('Represented by') list_display = ['established_from', 'from_date', 'thru_date'] form_display = [ 'established_from', 'from_date', 'thru_date', 'comment' ] field_attributes = {'established_from': {'name': _('Name')}}
class PartyCategory(Entity): using_options(tablename='party_category') name = Field(Unicode(40), index=True, required=True) color = Field(camelot.types.Color()) # end category definition parties = ManyToMany('Party', lazy=True, tablename='party_category_party', remote_colname='party_id', local_colname='party_category_id') def get_contact_mechanisms(self, virtual_address_type): """Function to be used to do messaging :param virtual_address_type: a virtual address type, such as 'phone' or 'email' :return: a generator that yields strings of contact mechanisms, egg '*****@*****.**' """ for party in self.parties: for party_contact_mechanism in party.contact_mechanisms: contact_mechanism = party_contact_mechanism.contact_mechanism if contact_mechanism: virtual_address = contact_mechanism.mechanism if virtual_address and virtual_address[ 0] == virtual_address_type: yield virtual_address[1] def __unicode__(self): return self.name or '' class Admin(EntityAdmin): verbose_name = _('Category') verbose_name_plural = _('Categories') list_display = ['name', 'color']
class Tag(self.Entity): score1 = Field(Float) score2 = Field(Float) user = ManyToOne('User') score = ColumnProperty(lambda c: c.score1 * c.score2)
class A(self.Entity): using_options(shortnames=True) key1 = Field(Integer, primary_key=True, autoincrement=False) key2 = Field(String(40), primary_key=True) bs_ = ManyToMany('B', local_colname=['foo', 'bar'], remote_colname="baz")
class Organization(Party): """An organization represents any internal or external organization. Organizations can include businesses and groups of individuals""" using_options(tablename='organization') party_id = Field(Integer, ForeignKey('party.id'), primary_key=True) __mapper_args__ = {'polymorphic_identity': u'organization'} name = Field(Unicode(50), required=True, index=True) logo = Field(camelot.types.Image(upload_to='organization-logo'), deferred=True) tax_id = Field(Unicode(20)) directors = OneToMany('DirectedDirector', inverse='established_from', cascade='all, delete, delete-orphan') employees = OneToMany('EmployerEmployee', inverse='established_from', cascade='all, delete, delete-orphan') suppliers = OneToMany('SupplierCustomer', inverse='established_to', cascade='all, delete, delete-orphan') customers = OneToMany('SupplierCustomer', inverse='established_from', cascade='all, delete, delete-orphan') shareholders = OneToMany('SharedShareholder', inverse='established_from', cascade='all, delete, delete-orphan') def __unicode__(self): return self.name or '' @property def number_of_shares_issued(self): return sum((shareholder.shares for shareholder in self.shareholders), 0)
class PartyAddressRoleType(Entity): using_options(tablename='party_address_role_type') code = Field(Unicode(10)) description = Field(Unicode(40)) class Admin(EntityAdmin): verbose_name = _('Address role type') list_display = ['code', 'description']
class A(self.Entity): using_options(shortnames=True) key1 = Field(Integer, primary_key=True, autoincrement=False) key2 = Field(String(40), primary_key=True) bs_ = ManyToMany('B', table=a_b, primaryjoin=lambda: and_(A.key1 == a_b.c.a_key1, A.key2 == a_b.c.a_key2), secondaryjoin=lambda: B.id == a_b.c.b_id, foreign_keys=[a_b.c.a_key1, a_b.c.a_key2, a_b.c.b_id])
class DirectedDirector(PartyRelationship): """Relation from a directed organization to a director""" using_options(tablename='party_relationship_dir') established_from = ManyToOne(Organization, required=True, ondelete='cascade', onupdate='cascade') established_to = ManyToOne(Party, required=True, ondelete='cascade', onupdate='cascade') title = Field(Unicode(256)) represented_by = OneToMany('RepresentedRepresentor', inverse='established_to') partyrelationship_id = Field(Integer, ForeignKey('party_relationship.id'), primary_key=True) __mapper_args__ = {'polymorphic_identity': 'directeddirector'} class Admin(PartyRelationship.Admin): verbose_name = _('Direction structure') verbose_name_plural = _('Direction structures') list_display = [ 'established_from', 'established_to', 'title', 'represented_by' ] list_search = [ 'established_from.full_name', 'established_to.full_name' ] field_attributes = { 'established_from': { 'name': _('Organization') }, 'established_to': { 'name': _('Director') } } class DirectorAdmin(Admin): verbose_name = _('Director') list_display = ['established_to', 'title', 'from_date', 'thru_date'] form_display = [ 'established_to', 'title', 'from_date', 'thru_date', 'represented_by', 'comment' ] class DirectedAdmin(Admin): verbose_name = _('Directed organization') list_display = ['established_from', 'title', 'from_date', 'thru_date'] form_display = [ 'established_from', 'title', 'from_date', 'thru_date', 'represented_by', 'comment' ]
class SharedShareholder(PartyRelationship): """Relation from a shared organization to a shareholder""" using_options(tablename='party_relationship_shares') established_from = ManyToOne(Organization, required=True, ondelete='cascade', onupdate='cascade') established_to = ManyToOne(Party, required=True, ondelete='cascade', onupdate='cascade') shares = Field(Integer()) partyrelationship_id = Field(Integer, ForeignKey('party_relationship.id'), primary_key=True) __mapper_args__ = {'polymorphic_identity': 'sharedshareholder'} class Admin(PartyRelationship.Admin): verbose_name = _('Shareholder structure') verbose_name_plural = _('Shareholder structures') list_display = [ 'established_from', 'established_to', 'shares', ] list_search = [ 'established_from.full_name', 'established_to.full_name' ] field_attributes = { 'established_from': { 'name': _('Organization') }, 'established_to': { 'name': _('Shareholder') } } class ShareholderAdmin(Admin): verbose_name = _('Shareholder') list_display = ['established_to', 'shares', 'from_date', 'thru_date'] form_display = [ 'established_to', 'shares', 'from_date', 'thru_date', 'comment' ] form_size = (500, 300) class SharedAdmin(Admin): verbose_name = _('Shares') verbose_name_plural = _('Shares') list_display = ['established_from', 'shares', 'from_date', 'thru_date'] form_display = [ 'established_from', 'shares', 'from_date', 'thru_date', 'comment' ] form_size = (500, 300)
class Record(self.Entity): title = Field(String(100)) year = Field(Integer) artist = ManyToOne('Artist') genres = ManyToMany('Genre') # order titles descending by year, then by title using_options(order_by=['-year', 'title']) def __str__(self): return "%s - %s (%d)" % (self.artist.name, self.title, self.year)
class GeographicBoundary(Entity): """The base class for Country and City""" using_options(tablename='geographic_boundary') code = Field(Unicode(10)) name = Field(Unicode(40), required=True) row_type = schema.Column(Unicode(40), nullable=False) __mapper_args__ = {'polymorphic_on': row_type} @ColumnProperty def full_name(self): return self.code + ' ' + self.name def __unicode__(self): return u'%s %s' % (self.code, self.name)
class TreeNode( self.Entity ): using_options(order_by='name') name = Field(String(50), required=True) parent = ManyToOne('TreeNode') children = OneToMany('TreeNode', inverse='parent') root = ManyToOne('TreeNode')
class PartyRelationship(Entity): using_options(tablename='party_relationship') from_date = Field(Date(), default=datetime.date.today, required=True, index=True) thru_date = Field(Date(), default=end_of_times, required=True, index=True) comment = Field(camelot.types.RichText()) row_type = schema.Column(Unicode(40), nullable=False) __mapper_args__ = {'polymorphic_on': row_type} class Admin(EntityAdmin): verbose_name = _('Relationship') verbose_name_plural = _('Relationships') list_display = ['from_date', 'thru_date']
class User( self.Entity ): name = Field(String(50)) boston_addresses = OneToMany('Address', primaryjoin=lambda: and_(Address.user_id == User.id, Address.city == u'Boston'), viewonly=True ) addresses = OneToMany('Address')
class ContactMechanism(Entity): using_options(tablename='contact_mechanism') mechanism = Field(camelot.types.VirtualAddress(256), required=True) party_address = ManyToOne(PartyAddress, ondelete='set null', onupdate='cascade') party_contact_mechanisms = OneToMany('PartyContactMechanism') def __unicode__(self): if self.mechanism: return u'%s : %s' % (self.mechanism[0], self.mechanism[1]) class Admin(EntityAdmin): form_size = (700, 150) verbose_name = _('Contact mechanism') list_display = ['mechanism'] form_display = Form(['mechanism', 'party_address']) field_attributes = {'mechanism': {'minimal_column_width': 25}} def get_depending_objects(self, contact_mechanism): for party_contact_mechanism in contact_mechanism.party_contact_mechanisms: yield party_contact_mechanism party = party_contact_mechanism.party if party: yield party
class City(GeographicBoundary): """A subclass of GeographicBoundary used to store the name, the postal code and the Country of a city""" using_options(tablename='geographic_boundary_city') country = ManyToOne(Country, required=True, ondelete='cascade', onupdate='cascade') geographicboundary_id = Field(camelot.types.PrimaryKey(), ForeignKey('geographic_boundary.id'), primary_key=True) __mapper_args__ = {'polymorphic_identity': 'city'} def __unicode__(self): if None not in (self.code, self.name, self.country): return u'{0.code} {0.name} [{1.code}]'.format(self, self.country) return u'' @classmethod def get_or_create(cls, country, code, name): city = City.query.filter_by(code=code, country=country).first() if not city: city = City(code=code, name=name, country=country) orm.object_session(city).flush() return city class Admin(EntityAdmin): verbose_name = _('City') verbose_name_plural = _('Cities') form_size = (700, 150) list_display = ['code', 'name', 'country']
class PartyContactMechanism(Entity): using_options(tablename='party_contact_mechanism') party = ManyToOne(Party, required=True, ondelete='cascade', onupdate='cascade') contact_mechanism = ManyToOne(ContactMechanism, lazy='joined', required=True, ondelete='cascade', onupdate='cascade') from_date = Field(Date(), default=datetime.date.today, required=True, index=True) thru_date = Field(Date(), default=end_of_times, index=True) comment = Field(Unicode(256)) @hybrid.hybrid_property def mechanism(self): if self.contact_mechanism != None: return self.contact_mechanism.mechanism @mechanism.setter def mechanism_setter(self, value): if value != None: if self.contact_mechanism: self.contact_mechanism.mechanism = value else: self.contact_mechanism = ContactMechanism(mechanism=value) @mechanism.expression def mechanism_expression(self): return ContactMechanism.mechanism def party_name(self): return sql.select([Party.full_name], whereclause=(Party.id == self.party_id)) party_name = ColumnProperty(party_name, deferred=True) def __unicode__(self): return unicode(self.contact_mechanism) Admin = PartyContactMechanismAdmin
class EmployerEmployee(PartyRelationship): """Relation from employer to employee""" using_options(tablename='party_relationship_empl') established_from = ManyToOne(Organization, required=True, ondelete='cascade', onupdate='cascade') # the employer established_to = ManyToOne(Person, required=True, ondelete='cascade', onupdate='cascade') # the employee partyrelationship_id = Field(Integer, ForeignKey('party_relationship.id'), primary_key=True) __mapper_args__ = {'polymorphic_identity': 'employeremployee'} @ColumnProperty def first_name(self): return sql.select([Person.first_name], Person.party_id == self.established_to_party_id) @ColumnProperty def last_name(self): return sql.select([Person.last_name], Person.party_id == self.established_to_party_id) @ColumnProperty def social_security_number(self): return sql.select([Person.social_security_number], Person.party_id == self.established_to_party_id) def __unicode__(self): return u'%s %s %s' % (unicode(self.established_to), _('Employed by'), unicode(self.established_from)) class Admin(PartyRelationship.Admin): verbose_name = _('Employment relation') verbose_name_plural = _('Employment relations') list_filter = ['established_from.name'] list_search = [ 'established_from.name', 'established_to.first_name', 'established_to.last_name' ] class EmployeeAdmin(EntityAdmin): verbose_name = _('Employee') list_display = ['established_to', 'from_date', 'thru_date'] form_display = ['established_to', 'comment', 'from_date', 'thru_date'] field_attributes = {'established_to': {'name': _('Name')}} class EmployerAdmin(EntityAdmin): verbose_name = _('Employer') list_display = ['established_from', 'from_date', 'thru_date'] form_display = [ 'established_from', 'comment', 'from_date', 'thru_date' ] field_attributes = {'established_from': {'name': _('Name')}}
class Address(Entity): """The Address to be given to a Party (a Person or an Organization)""" using_options(tablename='address') street1 = Field(Unicode(128), required=True) street2 = Field(Unicode(128)) city = ManyToOne(City, required=True, ondelete='cascade', onupdate='cascade', lazy='subquery') party_addresses = OneToMany('PartyAddress') def name(self): return sql.select( [self.street1 + ', ' + GeographicBoundary.full_name], whereclause=( GeographicBoundary.id == self.city_geographicboundary_id)) name = ColumnProperty(name, deferred=True) @classmethod def get_or_create(cls, street1, street2, city): address = cls.query.filter_by(street1=street1, street2=street2, city=city).first() if not address: address = cls(street1=street1, street2=street2, city=city) orm.object_session(address).flush() return address def __unicode__(self): return u'%s, %s' % (self.street1 or '', self.city or '') class Admin(EntityAdmin): verbose_name = _('Address') verbose_name_plural = _('Addresses') list_display = ['street1', 'street2', 'city'] form_size = (700, 150) field_attributes = {'street1': {'minimal_column_width': 30}} def get_depending_objects(self, address): for party_address in address.party_addresses: yield party_address if party_address.party != None: yield party_address.party
class Activitate(Entity): __tablename__ = 'activitati' tip = Column(String(30)) __mapper_args__ = {'polymorphic_on': tip} nume = Field(Unicode(50), required=True, index=True) coordonator = ManyToOne('ResurseUmane', inverse='activitati_coordonate') membrii = ManyToMany('ResurseUmane') aprobata = Column(Boolean) res_fin = OneToMany('ResurseFinanciare', inverse="activitate") res_logistice = ManyToMany('ResursaLogistica') #todo adaugat faze activitate faze = OneToMany("FazeActivitate") def __unicode__(self): return self.nume or '' class Admin(EntityAdmin): verbose_name = 'Activitate' verbose_name_plural = 'Activitati' list_display = ['nume', 'aprobata'] form_display = TabForm([('Importante', Form(['nume', 'coordonator'])), ('Participanti', Form(['membrii'])), ('Resurse', Form(['res_fin', 'res_logistice'])), ('Faze', Form(['faze']))]) field_attributes = dict(ResurseUmane.Admin.field_attributes) form_actions = [RapoarteActivitati()] class Admin2(EntityAdmin): verbose_name = 'Calendar activitati' list_display = ['nume', 'coordonator', 'aprobata'] def get_query(self): session = Session return session.query(Activitate).join(ResurseUmane).filter( ResurseUmane.id == 1) # todo schimbat cu userul # curent class Admin3(EntityAdmin): verbose_name = 'Proiect Departament' verbose_name_plural = 'Proiecte Departament' list_display = ['nume', 'coordonator', 'aprobata', 'tip'] Admin3 = not_editable_admin(Admin3)
class BatchJobType(Entity): """The type of batch job, the user will be able to filter his jobs based on their type. A type might be 'Create management reports' """ using_options(tablename='batch_job_type') name = Field(sqlalchemy.types.Unicode(256), required=True) parent = ManyToOne('BatchJobType') def __unicode__(self): return self.name @classmethod def get_or_create(cls, name): batch_job_type = cls.query.filter_by(name=name).first() if not batch_job_type: batch_job_type = cls(name=name) batch_job_type.flush() return batch_job_type class Admin(EntityAdmin): verbose_name = _('Batch job type') list_display = ['name', 'parent']
class SupplierCustomer(PartyRelationship): """Relation from supplier to customer""" using_options(tablename='party_relationship_suppl') established_from = ManyToOne(Party, required=True, ondelete='cascade', onupdate='cascade') established_to = ManyToOne(Party, required=True, ondelete='cascade', onupdate='cascade') partyrelationship_id = Field(Integer, ForeignKey('party_relationship.id'), primary_key=True) __mapper_args__ = {'polymorphic_identity': 'suppliercustomer'} class Admin(PartyRelationship.Admin): verbose_name = _('Supplier - Customer') list_display = [ 'established_from', 'established_to', 'from_date', 'thru_date' ] class CustomerAdmin(EntityAdmin): verbose_name = _('Customer') list_display = [ 'established_to', ] form_display = ['established_to', 'comment', 'from_date', 'thru_date'] field_attributes = {'established_to': {'name': _('Name')}} class SupplierAdmin(EntityAdmin): verbose_name = _('Supplier') list_display = [ 'established_from', ] form_display = [ 'established_from', 'comment', 'from_date', 'thru_date' ] field_attributes = {'established_from': {'name': _('Name')}}
class Person(Party): """Person represents natural persons """ using_options(tablename='person') party_id = Field(camelot.types.PrimaryKey(), ForeignKey('party.id'), primary_key=True) __mapper_args__ = {'polymorphic_identity': u'person'} first_name = schema.Column(Unicode(40), nullable=False) last_name = schema.Column(Unicode(40), nullable=False) # end short person definition middle_name = schema.Column(Unicode(40)) personal_title = schema.Column(Unicode(10)) suffix = schema.Column(Unicode(3)) sex = schema.Column(Unicode(1), default=u'M') birthdate = schema.Column(Date()) martial_status = schema.Column(Unicode(1)) social_security_number = schema.Column(Unicode(12)) passport_number = schema.Column(Unicode(20)) passport_expiry_date = schema.Column(Date()) picture = schema.Column(camelot.types.Image(upload_to='person-pictures')) comment = schema.Column(camelot.types.RichText()) @property def note(self): for person in self.__class__.query.filter_by( first_name=self.first_name, last_name=self.last_name): if person != self: return _('A person with the same name already exists') @property def name(self): # we don't use full name in here, because for new objects, full name will be None, since # it needs to be fetched from the db first return ' '.join( [name for name in [self.first_name, self.last_name] if name]) def __unicode__(self): return self.name or ''
class Country(GeographicBoundary): """A subclass of GeographicBoundary used to store the name and the ISO code of a country""" using_options(tablename='geographic_boundary_country') geographicboundary_id = Field(camelot.types.PrimaryKey(), ForeignKey('geographic_boundary.id'), primary_key=True) __mapper_args__ = {'polymorphic_identity': 'country'} @classmethod def get_or_create(cls, code, name): country = Country.query.filter_by(code=code).first() if not country: country = Country(code=code, name=name) orm.object_session(country).flush() return country class Admin(EntityAdmin): form_size = (700, 150) verbose_name = _('Country') verbose_name_plural = _('Countries') list_display = ['name', 'code']
class Organization(Party): """An organization represents any internal or external organization. Organizations can include businesses and groups of individuals""" using_options(tablename='organization') party_id = Field(camelot.types.PrimaryKey(), ForeignKey('party.id'), primary_key=True) __mapper_args__ = {'polymorphic_identity': u'organization'} name = schema.Column(Unicode(50), nullable=False, index=True) logo = schema.Column(camelot.types.Image(upload_to='organization-logo')) tax_id = schema.Column(Unicode(20)) def __unicode__(self): return self.name or '' @property def note(self): session = orm.object_session(self) if session is not None: cls = self.__class__ if session.query(cls).filter( sql.and_(cls.name == self.name, cls.id != self.id)).count(): return _('An organization with the same name already exists')
class B( self.Entity ): name = Field(String(60)) a = ManyToOne('A')
class A( self.Entity ): name = Field(String(60)) b = OneToOne('B')
class Animal(self.Entity): name = Field(String(30)) owner_id = Field(Integer, colname='owner') owner = ManyToOne('Person', field=owner_id)
class Person(self.Entity): name = Field(String(30))
class A(self.Entity): name = Field(String(128), default="foo")