class LACollision(Document): meta = {'collection': 'LACollision'} X = DecimalField() Y = DecimalField() OBJECTID = IntField() case_id = IntField() accident_year = IntField() proc_date = DateTimeField() juris = IntField() collision_date = DateTimeField() collision_time = IntField() officer_id = IntField() reporting_district = IntField() day_of_week = IntField() chp_shift = IntField() population = IntField() cnty_city_loc = IntField() special_cond = IntField() beat_type = IntField() chp_beat_type = IntField() city_division_lapd = StringField() chp_beat_class = IntField() beat_number = StringField() primary_rd = StringField() secondary_rd = StringField() distance = IntField()
class CarParts(Document): meta = {'collection': 'car_parts'} code = IntField(unique=True) product_name = StringField(min_length=1, max_length=200) category = StringField(min_length=1, max_length=200) buying_price = DecimalField(min_value=0, precision=2) client_price = DecimalField(min_value=0, precision=2) application = StringField(min_length=1, max_length=200) manufacturer = StringField(min_length=1, max_length=100)
class Price(EmbeddedDocument): valid_from = DateTimeField(required=True) valid_to = DateTimeField(required=True) currency = StringField(required=True) original_price = DecimalField(min_value=0, precision=2) discounted_price = DecimalField(min_value=0, precision=2) discount_rate = DecimalField(min_value=0, max_value=100, precision=4) # stock = IntField(min_value=0, required=True) # is_active = BooleanField(required=True) options = ListField(ReferenceField(Option))
class States(Document): meta = {'collection': 'states'} key = StringField() name = StringField() address = StringField() latitude = DecimalField() longitude = DecimalField() confirmed = IntField() deaths = IntField() recovered = IntField()
class Review(Document): meta = {"collection": "review"} date = DateTimeField(default=datetime.now) rating = DecimalField() organization = ReferenceField(Organization) user = ReferenceField(UserAccount)
class BusinessAccount(Document): meta = {"collection": "business"} company_name = StringField(unique=True, required=True) email = EmailField() fee = DecimalField() bank_account = StringField() password = StringField(required=True)
class Receipt(Document): meta = {"collection": "receipt"} date = DateTimeField(default=datetime.now) amount = DecimalField() recipient = StringField() sender = StringField() currency = StringField()
class PartModel(mongoengine.Document): meta = {'collection': 'part'} Id = StringField() name = StringField() company = ReferenceField(CompanyModel, reverse_delete_rule=mongoengine.DENY) material = StringField() color = StringField(required=False) weight = DecimalField()
class MouldModel(mongoengine.Document): meta = {'collection': 'mould'} Id = StringField() name = StringField() company = ReferenceField(CompanyModel, reverse_delete_rule=mongoengine.DENY) part = ReferenceField(PartModel, reverse_delete_rule=mongoengine.DENY) cavity = IntField() runnerWeight = DecimalField()
class Version(Document): meta = {'collection': 'version'} name = StringField() model = ReferenceField(Car) price = DecimalField() fuelType = StringField() fipeCode = StringField() year = IntField() version_id = IntField()
class Country(Document): CountryName = StringField(max_length=100, required=True) CountryCode = StringField(max_length=5) countryCurrency = StringField(default='dollar') monthlyAmount = DecimalField(precision=2) displayOrder = IntField(default=1) Language = StringField(max_length=5) status = IntField(default=1) date_created = DateTimeField(default=datetime.datetime.utcnow) date_modified = DateTimeField(default=datetime.datetime.utcnow)
class Donation(Document): meta = {"collection": "donation"} date = DateTimeField(default=datetime.now) currency = StringField() amount = DecimalField() payment_method = StringField() donor = ReferenceField(UserAccount) organization = ReferenceField(Organization) receipt = ReferenceField(Receipt)
class Statistics(Document): meta = {'collection': 'statistics'} country = StringField() code = StringField() flag = StringField() coordinates = ListField(DecimalField()) confirmed = IntField() deaths = IntField() recovered = IntField() states = ListField(ReferenceField(States))
class BasePriceOption(EmbeddedDocument, BaseMixin): """ A part of Products, keeps zone for hall of specified Event """ id = ObjectIdField(default=ObjectId) name = MLStringField(required=True) price = DecimalField(min_value=0, default=Decimal(0)) quantity = IntField(min_value=0, default=0) meta = { 'allow_inheritance': True }
class Subscription(Document): user = ReferenceField(User) membershipPlan = ReferenceField(Country) paymentGateway = StringField() paymentMethod = StringField() membershipAmount = DecimalField(precision=2) paymentAmount = DecimalField(precision=2) currency = StringField() voucher = ReferenceField(Voucher) paymentInfo = StringField() subscriptionId = StringField() subscriptionPlan = StringField() subscriptionInfo = StringField() subscriptionStatus = StringField(default='Initial') subscriptionCancelDate = DateTimeField() subscriptionNextBillingDate = DateTimeField() failedMessage = StringField() failedCode = StringField() date_created = DateTimeField(default=datetime.datetime.utcnow) date_modified = DateTimeField(default=datetime.datetime.utcnow)
class MachineModel(mongoengine.Document): meta = {'collection': 'machine'} Id = StringField() name = StringField() make = StringField() model = StringField() isEnabled = BooleanField() company = ReferenceField(CompanyModel, reverse_delete_rule=mongoengine.DENY) clampingCapacity = IntField() injectionVolume = DecimalField()
class Voucher(Document): name = StringField(max_length=100, required=True) description = StringField(max_length=200) code = StringField(max_length=50, required=True, unique=True) discount = DecimalField(default=0.00,precision=2,required=True,) uselimit = IntField(default=0) usedNum = IntField(default=0) membershipPlan = ListField(ReferenceField(Country)) expireDate = DateTimeField() status = IntField(default=1) date_created = DateTimeField(default=datetime.datetime.utcnow) date_modified = DateTimeField(default=datetime.datetime.utcnow)
class Transaction(Document): user = ReferenceField(User) subscription = ReferenceField(Subscription) paymentGateway = StringField() paymentMethod = StringField() amount = DecimalField(precision=2) currency = StringField() paymentInfo = StringField() subscriptionId = StringField() paymentStatus = StringField() failedMessage = StringField(default=1) failedCode = StringField(default=1) date_created = DateTimeField(default=datetime.datetime.utcnow) date_modified = DateTimeField(default=datetime.datetime.utcnow)
class Product(EmbeddedDocument): id = ObjectIdField(required=True, default=ObjectId, db_field='_id') name = StringField(required=True) value = DecimalField(required=True) @staticmethod def buildOne(product): return { 'id': str(product.id), 'name': product.name, 'value': product.value } @staticmethod def buildMany(products): return list(map(lambda product: Product.buildOne(product), products))
class User(Document): firstName = StringField(required=True) lastName = StringField(required=True, default='') email = EmailField(required=True) gender = StringField( required=True, default='Male') # choices=['Male', 'Female', 'Other']) password = BinaryField() resetPasswordToken = StringField() resetPasswordExpires = DateTimeField() role = StringField(default='User') # choices=['User', 'Admin']) dateOfBirth = StringField(required=True) # YYYY/MM/DD Format age = IntField(required=True, default=0) weight = IntField(required=True, default=0) weightUnit = StringField(required=True, default='kg') # choices=['kg', 'lb']) height = DecimalField(required=True, default=0, precision=1) heightUnit = StringField(required=True, default='cm') # choices=['cm', 'm', 'ft']) foodPreference = StringField( required=True, default='Vegetarian' ) # choices=['Vegan', 'Vegetarian', 'Non-Vegetarian']) timeZone = StringField(default='0') # Timezone Offset Value bmi = IntField(default=0) medicalCondition = StringField() targetWeight = IntField(default=0) targetDate = StringField(default='') # YYYY/MM/DD format targetCalories = IntField(default=0) accountCreationDate = DateTimeField(default=datetime.utcnow()) userPhoto = StringField(default='') messages = ListField(EmbeddedDocumentField(Messages)) mealAssigned = ListField(ReferenceField(Meal)) mealExpiry = DateTimeField() unreadCount = IntField(default=0) @staticmethod def pre_save_func(sender, document): document['password'] = bcrypt.generate_password_hash( document['password']) dob = parser.parse(document['dateOfBirth']) today = datetime.today() age = relativedelta.relativedelta(today, dob) document['age'] = age.years
class Recharge(Document): companyId = ObjectIdField(required=True) productId = ObjectIdField(required=True) createdAt = StringField(required=True) phoneNumber = StringField(required=True) value = DecimalField(required=True) @staticmethod def buildOne(recharge): return { 'id': str(recharge.id), 'createdAt': recharge.createdAt, 'companyId': str(recharge.companyId), 'productId': str(recharge.productId), 'phoneNumber': recharge.phoneNumber, 'value': recharge.value } @staticmethod def buildMany(recharges): return list( map(lambda recharge: Recharge.buildOne(recharge), recharges))
class Option(Document): meta = {'collection': 'options'} ID = StringField(required=True, primary_key=True) ticker = StringField(required=True) type = StringField(required=True, choices=['CALL', 'PUT']) implied_vol = DecimalField() implied_vol_rank = DecimalField() delta = DecimalField() theta = DecimalField() vega = DecimalField() current_value = DecimalField() # also track previous current_values from the same trading day? theoretical_value = DecimalField() # also track previous current_values from the same trading day? #underlying = ReferenceField(Stock, required=True) #strike = DecimalField(required=True) #expiry = DateTimeField(required=True) last_updated = DateTimeField(default=datetime.now)
class DataModelEvent(UniqueDocument): """ This class refers to any event in the FMX Data Model as described in the Cyber Analytics Repository (https://car.mitre.org/wiki/Data_Model). The event consists of an object type, an action performed by or on that object (often refers to a state change), and a set of fields. Objects can be causally related by connecting them with links, known as pivots. :var name: Name of the Data Model object (as in CAR) :var actions: list of the possible actions for the object :var fields: list of all acceptable fields for the object :var identifiers: list of the identifying fields for an event (given hostname, object, action and time) """ __metaclass__ = DataModelEventMeta meta = { 'allow_inheritance': True, 'abstract': False, 'indexes': [ dict(cls=False, fields=['time']), dict(cls=False, fields=['action']), dict(cls=False, fields=['object_type']), dict(cls=False, fields=['host']), # dict(cls=False, fields=['uuid'], unique=True), dict(cls=False, fields=['state.pid']), dict(cls=False, fields=['state.ppid']), dict(cls=False, fields=['state.hostname']) ] } # Specify a fallback/ for class properties, etc. # These will be updated via the metaclass, but documenting them here is helpful for autocompletion in IDEs # Mongo schema definition action = StringField(required=True) state = EmbeddedDocumentField(EventState) time = DateTimeField() discovered_time = DateTimeField(default=datetime.datetime.utcnow) sessions = ListField(ReferenceField('Session')) links = ListField(ReferenceField('self')) labeled_links = ListField(EmbeddedDocumentField(LabeledLink)) reverse_links = ListField(ReferenceField('self')) labeled_reverse_links = ListField(EmbeddedDocumentField(LabeledLink)) host = ReferenceField('Host') metadata = DictField() uuid = StringField(unique=True) object_type = StringField() confidence = DecimalField(default=0.0) # These should be implemented by the subclass object_name = str() actions = tuple() fields = tuple() identifiers = tuple() def __init__(self, action, **kwargs): if isinstance(kwargs.get('state'), dict): state = kwargs['state'] if 'fqdn' in state and 'hostname' not in state: state['hostname'] = state['fqdn'].split('.')[0] # Remove non-matching fields kwargs['state'] = { k: v for k, v in state.items() if k in self.fields } super(DataModelEvent, self).__init__(action=action, **kwargs) if self.uuid is None: self.uuid = self.get_uuid() def get_uuid_tuple(self): """ Generate an identifier string that is unique for this event. It depends on a set of fixed fields, such as the object name, action and host it occurred on. Additionally, it is generated from a set of class specific fields, described in the property 'identifiers'. :return: a string of a number that is unique for this DataModelEvent :rtype: str """ # Drop the microsecond granularity utc_time = datetime.datetime(*self.time.utctimetuple()[:-3]) loose_time = utc_time.isoformat() fixed_identifiers = (self.state.hostname, type(self).object_name, self.action, loose_time) identifiers = fixed_identifiers + tuple(self.state[_] for _ in self.identifiers) return identifiers @classmethod def search(cls, action=None, expression=EmptyQuery, **kwargs): """ Create a search query for this DataModel object. Given an expression as input (either a set of field requirements) or another search query. This function places query in the context of a DataModelEvent. :param kwargs: Field requirements (keys and values) :param action: Data model action for the specified object :type expression: QueryTerm :rtype: DataModelQuery """ if len(kwargs): for name, value in kwargs.items(): assert name in cls.fields if isinstance(value, CompareString): expression &= value.compare(name) else: expression &= (FieldQuery(name) == value) return DataModelQuery(cls, action, query=expression) def update_host(self): try: host = self.host except DoesNotExist: host = None hostname = self.state.hostname.upper() if not isinstance(host, Host): host = Host.update_existing(hostname=hostname) self.modify(host=host) if self.state.fqdn is not None and host.fqdn is None: host.update(fqdn=self.state.fqdn) elif host.fqdn is not None and self.state.fqdn is None: self.modify(state__fqdn=host.fqdn.upper()) if 'user' in self.fields and self and self.state.user: host.update(add_to_set__users=self.state.user) def save(self, *args, **kwargs): status = super(DataModelEvent, self).save(*args, **kwargs) self.update_host() return status @classmethod def update_existing(cls, action, **kwargs): # Create a new object to resolve the UUID to ObjectId kwargs.pop('host', None) return super(DataModelEvent, cls).update_existing(action=action, **kwargs) def __repr__(self): """ Display a representation of this DataModelEvent that can be reproduced with an eval statement. Currently, it just returns the class name (object), action, and the set of fields. """ return "{}(action={}, state={})".format( type(self).__name__, repr(self.action), self.state.to_json()) __str__ = __repr__
class Price(EmbeddedDocument): CurrencyID = StringField(max_length=6) Value = DecimalField()
class ServiceAttribute(EmbeddedDocument): code = StringField(required=True) variable = BooleanField(default=False) order = DecimalField(required=True) description = StringField(required=True)
class Person(Document): name = StringField() money = DecimalField(force_string=True) monies = ListField(DecimalField(force_string=True))
class Person(Document): name = StringField() money = DecimalField(precision=2, rounding=decimal.ROUND_HALF_UP) monies = ListField( DecimalField(precision=2, rounding=decimal.ROUND_HALF_UP))
class Outcome(EmbeddedDocument): outcome_electric_power = DecimalField(min_value=0, required=False, db_field="energia_electrica_egreso") outcome_water = DecimalField(min_value=0, required=False, db_field="agua_egreso") outcome_gas = DecimalField(min_value=0, required=False, db_field="gas_egreso") outcome_phone = DecimalField(min_value=0, required=False, db_field="telefono_egreso") outcome_food = DecimalField(min_value=0, required=False, db_field="alimentos_egreso") outcome_rent = DecimalField(min_value=0, required=False, db_field="renta_egreso") outcome_transportation = DecimalField(min_value=0, required=False, db_field="transporte_egreso") outcome_education = DecimalField(min_value=0, required=False, db_field="educacion_egreso") outcome_clothing = DecimalField(min_value=0, required=False, db_field="vestimenta_egreso") outcome_recreational = DecimalField(min_value=0, required=False, db_field="diversion_egreso") outcome_other = DecimalField(min_value=0, required=False, db_field="otros_egreso")
class Orders(Document): date = DateTimeField(required=True, default=datetime.utcnow) user = ReferenceField('Users') ordered_parts = StringField(min_length=1, max_length=200) total_costs = DecimalField(min_value=0, precision=2) profit = FloatField()