class Invoice(BaseModel): id = peewee.CharField(primary_key=True, max_length=28) serial_number = peewee.IntegerField() amount = peewee.IntegerField() status = peewee.CharField() payment_method = peewee.CharField() type = peewee.CharField() period_start_date = DateTimeTZField() period_end_date = DateTimeTZField() metadata = BinaryJSONField() class Meta: db_table = "Invoices" @classmethod def format_from_response(cls, data): return dict( id=data["id"], serial_number=data["serial_number"], amount=data["amount"], status=data["status"], payment_method=data["payment_method"], type=data["type"], period_start_date=time_utils.from_iso(data["period_start_date"]), period_end_date=time_utils.from_iso(data["period_end_date"]), metadata=data["metadata"])
class Payable(BaseModel): id = peewee.IntegerField(primary_key=True) status = peewee.CharField() amount = peewee.IntegerField() fee = peewee.IntegerField() anticipation_fee = peewee.IntegerField() fraud_coverage_fee = peewee.IntegerField() installment = peewee.IntegerField(null=True) payment_date = DateTimeTZField() original_payment_date = DateTimeTZField(null=True) type = peewee.CharField() payment_method = peewee.CharField() recipient_id = peewee.CharField(max_length=28) split_rule_id = peewee.CharField(max_length=28, null=True) created_at = DateTimeTZField() accrual_date = DateTimeTZField(null=True) transaction_id = peewee.IntegerField() bulk_anticipation_id = peewee.CharField(max_length=28, null=True) class Meta: db_table = "Payables" indexes = ((("status", ), False), (("payment_date", ), False), (("type", ), False), (("payment_method", ), False), (("recipient_id", ), False), (("split_rule_id", ), False), (("transaction_id", ), False), (("bulk_anticipation_id", ), False))
class FeeCollection(BaseModel): id = peewee.CharField(primary_key=True, max_length=28) status = peewee.CharField() type = peewee.CharField() description = peewee.CharField() payment_date = DateTimeTZField() amount = peewee.IntegerField() object_type = peewee.CharField(null=True) object_id = peewee.CharField(max_length=28, null=True) recipient_id = peewee.CharField(max_length=28) created_at = DateTimeTZField() class Meta: db_table = "FeeCollections" @classmethod def format_from_response(cls, data): return dict(id=data["id"], status=data["status"], type=data["type"], description=data["description"], payment_date=time_utils.from_iso(data["payment_date"]), amount=data["amount"], object_type=data["object_type"], object_id=data["object_id"], recipient_id=data["recipient_id"], created_at=time_utils.from_iso(data["date_created"]))
class Machine(Model): name = CharField(index=True, unique=True) metadata = BinaryJSONField() train_start_date = DateTimeTZField() train_end_date = DateTimeTZField() class Meta: database = db @classmethod def from_endpoint(cls, ep): """ Returns a Machine object constructed from a valid endpoint. Parameters ---------- ep: Dict Endpoint from watchman Returns ------- Machine """ return cls(**endpoint_to_machine_data(ep)) def __repr__(self): return f"Machine {self.__data__} "
class Card(BaseModel): id = peewee.CharField(primary_key=True, max_length=30) created_at = DateTimeTZField() updated_at = DateTimeTZField() brand = peewee.CharField(null=True) holder_name = peewee.CharField(null=True) first_digits = peewee.CharField(null=True, max_length=6) last_digits = peewee.CharField(null=True, max_length=4) country = peewee.CharField(null=True) fingerprint = peewee.CharField(null=True, max_length=40) valid = peewee.BooleanField(null=True) expiration_date = peewee.CharField(null=True, max_length=7) class Meta: db_table = "Cards" @classmethod def format_from_response(cls, data): created_at = time_utils.from_iso(data["date_created"]) updated_at = time_utils.from_iso(data["date_updated"]) return dict(id=data["id"], created_at=created_at, updated_at=updated_at, brand=data["brand"], holder_name=data["holder_name"], first_digits=data["first_digits"], last_digits=data["last_digits"], country=data["country"], fingerprint=data["fingerprint"], valid=data["valid"], expiration_date=data["expiration_date"])
class SplitRule(BaseModel): id = peewee.CharField(primary_key=True, max_length=28) amount = peewee.IntegerField(null=True) percentage = peewee.DoubleField(null=True) recipient_id = peewee.CharField(max_length=28) charge_processing_fee = peewee.BooleanField() charge_remainder = peewee.BooleanField(null=True) liable = peewee.BooleanField() created_at = DateTimeTZField() updated_at = DateTimeTZField() class Meta: db_table = "SplitRules" @classmethod def format_from_response(cls, data): created_at = time_utils.from_iso(data["date_created"]) updated_at = time_utils.from_iso(data["date_updated"]) return dict(id=data["id"], amount=data["amount"], percentage=data["percentage"], recipient_id=data["recipient_id"], charge_processing_fee=data["charge_processing_fee"], charge_remainder=data["charge_remainder"], liable=data["liable"], created_at=created_at, updated_at=updated_at)
class Recipient(BaseModel): id = peewee.CharField(primary_key=True, max_length=28) transfer_enabled = peewee.BooleanField() last_transfer = DateTimeTZField(null=True) transfer_interval = peewee.CharField(null=True) transfer_day = peewee.IntegerField(null=True) automatic_anticipation_enabled = peewee.BooleanField() automatic_anticipation_type = peewee.CharField() automatic_anticipation_days = peewee.CharField(null=True) automatic_anticipation_1025_delay = peewee.IntegerField() anticipatable_volume_percentage = peewee.IntegerField(null=True) created_at = DateTimeTZField() updated_at = DateTimeTZField() postback_url = peewee.CharField(null=True) status = peewee.CharField() status_reason = peewee.CharField(null=True) bank_account_id = peewee.IntegerField() ENDPOINT = "/recipients" class Meta: db_table = "Recipients" @classmethod def format_from_response(cls, data): bank_account = data["bank_account"] try: bank_account_id = bank_account["id"] except KeyError: bank_account_id = None anticipation_enabled = data["automatic_anticipation_enabled"] anticipation_type = data["automatic_anticipation_type"] anticipation_days = data["automatic_anticipation_days"] anticipation_1025_delay = data["automatic_anticipation_1025_delay"] volume_percentage = data["anticipatable_volume_percentage"] last_transfer = time_utils.from_iso(data["last_transfer"]) created_at = time_utils.from_iso(data["date_created"]) updated_at = time_utils.from_iso(data["date_updated"]) return dict( id=data["id"], transfer_enabled=data["transfer_enabled"], last_transfer=last_transfer, transfer_interval=data["transfer_interval"], transfer_day=data["transfer_day"], automatic_anticipation_enabled=anticipation_enabled, automatic_anticipation_type=anticipation_type, automatic_anticipation_days=anticipation_days, automatic_anticipation_1025_delay=anticipation_1025_delay, anticipatable_volume_percentage=volume_percentage, created_at=created_at, updated_at=updated_at, postback_url=data["postback_url"], status=data["status"], status_reason=data["status_reason"], bank_account_id=bank_account_id )
class ModelTimestampsMixin(BaseModel): updated_at = DateTimeTZField(default=datetime.datetime.now) created_at = DateTimeTZField(default=datetime.datetime.now) def pre_save(self, created): super(ModelTimestampsMixin, self).pre_save(created) self.updated_at = datetime.datetime.now()
class Users(BaseModel): email = CharField(255, unique=True) name = CharField(255, null=True) password_hash = CharField(255, null=True) email_validated = BooleanField(default=False) validation_token_hash = CharField(255, null=True) validation_token_expiry = DateTimeTZField(null=True) reset_token_hash = CharField(255, null=True) reset_token_expiry = DateTimeTZField(null=True) registration_source = CharField(255, null=True)
class BaseModel(Model): id = CharField(primary_key=True, default=lambda: shortuuid.uuid()) created_at = DateTimeTZField(default=lambda: dt.now(tz)) updated_at = DateTimeTZField(default=lambda: dt.now(tz)) def save(self, *args, **kwargs): self.updated_at = dt.now(tz) return super(BaseModel, self).save(*args, **kwargs) class Meta: database = db table_function = make_table_name
class Invoice(BaseModel): id = peewee.CharField(primary_key=True, max_length=28) serial_number = peewee.IntegerField() amount = peewee.IntegerField() status = peewee.CharField() payment_method = peewee.CharField() type = peewee.CharField() period_start_date = DateTimeTZField() period_end_date = DateTimeTZField() metadata = BinaryJSONField() class Meta: db_table = "Invoices"
class Transaction(BaseModel): id = peewee.IntegerField(primary_key=True) subscription_id = peewee.IntegerField(null=True) customer_id = peewee.IntegerField(null=True) address_id = peewee.IntegerField(null=True) phone_id = peewee.IntegerField(null=True) billing_id = peewee.IntegerField(null=True) card_id = peewee.CharField(max_length=30) status = peewee.CharField() status_reason = peewee.CharField() acquirer_response_code = peewee.CharField(null=True) acquirer_name = peewee.CharField(null=True) acquirer_id = peewee.CharField(null=True, max_length=24) authorization_code = peewee.CharField(null=True) soft_descriptor = peewee.CharField(null=True) tid = peewee.CharField(null=True) nsu = peewee.CharField(null=True) created_at = DateTimeTZField() updated_at = DateTimeTZField() amount = peewee.IntegerField() authorized_amount = peewee.IntegerField() paid_amount = peewee.IntegerField() refunded_amount = peewee.IntegerField() installments = peewee.IntegerField() cost = peewee.DoubleField() card_holder_name = peewee.CharField(null=True) card_last_digits = peewee.CharField(max_length=4) card_first_digits = peewee.CharField(max_length=6) card_brand = peewee.CharField(null=True) card_pin_mode = peewee.CharField(null=True) postback_url = peewee.CharField(null=True) payment_method = peewee.CharField() capture_method = peewee.CharField() antifraud_metadata = BinaryJSONField(null=True) antifraud_score = peewee.DoubleField(null=True) boleto_url = peewee.CharField(null=True) boleto_barcode = peewee.CharField(null=True) boleto_expiration_date = DateTimeTZField(null=True) referer = peewee.CharField(null=True) ip = peewee.CharField(null=True) reference_key = peewee.CharField(null=True) metadata = peewee.CharField(null=True) class Meta: db_table = "Transactions" indexes = ((("subscription_id", ), False), (("customer_id", ), False), (("address_id", ), False), (("phone_id", ), False), (("billing_id", ), False), (("card_id", ), False), (("capture_method", ), False), (("payment_method", ), False), (("status", ), False), (("tid", ), False))
class FeeCollection(BaseModel): id = peewee.CharField(primary_key=True, max_length=28) status = peewee.CharField() type = peewee.CharField() description = peewee.CharField() payment_date = DateTimeTZField() amount = peewee.IntegerField() object_type = peewee.CharField(null=True) object_id = peewee.CharField(max_length=28, null=True) recipient_id = peewee.CharField(max_length=28) created_at = DateTimeTZField() class Meta: db_table = "FeeCollections"
class SplitRule(BaseModel): id = peewee.CharField(primary_key=True, max_length=28) amount = peewee.IntegerField(null=True) percentage = peewee.DoubleField(null=True) recipient_id = peewee.CharField(max_length=28) charge_processing_fee = peewee.BooleanField() charge_remainder = peewee.BooleanField(null=True) liable = peewee.BooleanField() created_at = DateTimeTZField() updated_at = DateTimeTZField() class Meta: db_table = "SplitRules" indexes = ((("recipient_id", ), False), )
class Customer(BaseModel): id = peewee.IntegerField(primary_key=True) name = peewee.CharField(null=True) email = peewee.CharField(null=True) gender = peewee.CharField(null=True) document_type = peewee.CharField(null=True) document_number = peewee.CharField(null=True) born_at = DateTimeTZField(null=True) created_at = DateTimeTZField() class Meta: db_table = "Customers" indexes = ((("email", ), False), (("document_type", "document_number"), False))
class UrlNL(BaseModel): """ Tabel met unieke url's. Een URL kan nul of hooguit 1 kvk nummer hebben, omdat hooguit 1 bedrijf eigenaar van een url kan zijn. Dit is het verschil met de WebSite tabel, waarbij iedere url meerdere kvk's kan hebben omdat dat alleen de kvk zijn die op de site voorkomen, maar niet perse de eigenaars van de site. """ # maak url unique, maar gebruik geen primary key voor de url. Dat is minder efficient url = pw.CharField(null=True, unique=True, primary_key=True) bestaat = pw.BooleanField(null=True) nl_company = pw.BooleanField(null=True) post_code = pw.CharField(null=True) kvk_nummer = pw.IntegerField(null=True) btw_nummer = pw.CharField(null=True) datetime = DateTimeTZField(null=True) # the process time ssl = pw.BooleanField(null=True) ssl_valid = pw.BooleanField(null=True) subdomain = pw.CharField(null=True) domain = pw.CharField(null=True) suffix = pw.CharField(null=True) category = pw.IntegerField(null=True) ecommerce = pw.CharField(null=True, max_length=MAX_CHARFIELD_LENGTH) social_media = pw.CharField(null=True, max_length=MAX_CHARFIELD_LENGTH) referred_by = pw.CharField(null=True) all_psc = pw.CharField(null=True, max_length=MAX_CHARFIELD_LENGTH) all_kvk = pw.CharField(null=True, max_length=MAX_CHARFIELD_LENGTH) all_btw = pw.CharField(null=True, max_length=MAX_CHARFIELD_LENGTH)
class Event(BaseModel): org = peewee.ForeignKeyField(Organization, related_name="events") user = peewee.ForeignKeyField(User, related_name="events", null=True) action = peewee.CharField() object_type = peewee.CharField() object_id = peewee.CharField(null=True) additional_properties = peewee.TextField(null=True) created_at = DateTimeTZField(default=datetime.datetime.now) class Meta: db_table = 'events' def __unicode__(self): return u"%s,%s,%s,%s" % (self.user_id, self.action, self.object_type, self.object_id) @classmethod def record(cls, event): org = event.pop('org_id') user = event.pop('user_id', None) action = event.pop('action') object_type = event.pop('object_type') object_id = event.pop('object_id', None) created_at = datetime.datetime.utcfromtimestamp(event.pop('timestamp')) additional_properties = json.dumps(event) event = cls.create(org=org, user=user, action=action, object_type=object_type, object_id=object_id, additional_properties=additional_properties, created_at=created_at) return event
class ClanMember(BaseModel): clan = ForeignKeyField(Clan) member = ForeignKeyField(Member) platform_id = IntegerField() join_date = DateTimeTZField() is_active = BooleanField(default=True) last_active = DateTimeTZField(null=True) is_sherpa = BooleanField(default=False) member_type = IntegerField( null=True, constraints=[Check( f"member_type in ({constants.CLAN_MEMBER_NONE}, {constants.CLAN_MEMBER_BEGINNER}," f"{constants.CLAN_MEMBER_MEMBER}, {constants.CLAN_MEMBER_ADMIN}, " f"{constants.CLAN_MEMBER_ACTING_FOUNDER}, {constants.CLAN_MEMBER_FOUNDER})" )] )
class BankAccount(BaseModel): id = peewee.IntegerField(primary_key=True) bank_code = peewee.CharField(max_length=5) agencia = peewee.CharField(max_length=5) agencia_dv = peewee.CharField(null=True, max_length=20) conta = peewee.CharField(max_length=10) conta_dv = peewee.CharField(null=True, max_length=20) type = peewee.CharField() document_type = peewee.CharField() document_number = peewee.CharField(max_length=14) legal_name = peewee.CharField() charge_transfer_fees = peewee.BooleanField() created_at = DateTimeTZField() class Meta: db_table = "BankAccounts" @classmethod def format_from_response(cls, data): return dict(id=data["id"], bank_code=data["bank_code"], agencia=data["agencia"], agencia_dv=data["agencia_dv"], conta=data["conta"], conta_dv=data["conta_dv"], type=data["type"], document_type=data["document_type"], document_number=data["document_number"], legal_name=data["legal_name"], charge_transfer_fees=data["charge_transfer_fees"], created_at=time_utils.from_iso(data["date_created"]))
class BalanceOperation(BaseModel): id = peewee.IntegerField(primary_key=True) recipient_id = peewee.CharField(max_length=28, null=True) status = peewee.CharField() amount = peewee.IntegerField() fee = peewee.IntegerField() object_type = peewee.CharField() object_id = peewee.CharField(max_length=28) created_at = DateTimeTZField() ENDPOINT = "/balance/operations" class Meta: db_table = "BalanceOperations" @classmethod def format_from_response(cls, data): movement_object = data["movement_object"] if movement_object["object"] in ["payable", "fee_collection"]: recipient_id = movement_object["recipient_id"] elif movement_object["object"] == "transfer": recipient_id = movement_object["source_id"] return dict(id=data["id"], recipient_id=recipient_id, status=data["status"], amount=data["amount"], fee=data["fee"], object_type=data["type"], object_id=data["movement_object"]["id"], created_at=time_utils.from_iso(data["date_created"]))
class Asset(CommonModel): id = TextField(primary_key=True, unique=True, index=True) url = TextField() title = TextField() publication = ForeignKeyField(Publication, null=True) open_till = DateTimeTZField() moderation_policy = IntegerField(null=False, default=moderation_policies.default.value) @hybrid_property def pending_comments_count(self): return PendingComment.select().where( PendingComment.asset == self.id).count() @hybrid_property def comments_count(self): return Comment.select().where(Comment.asset == self.id).count() @hybrid_property def rejected_comments_count(self): return RejectedComment.select().where( RejectedComment.asset == self.id).count() @hybrid_property def commenting_closed(self): return self.open_till <= arrow.utcnow().datetime
class PostgresStorage(BaseModel, PrintStorage): """Storage container for Postgresql database.""" date = DateTimeTZField() url = TextField(null=True) scheme = TextField(null=True) host = TextField(null=True) path = TextField(null=True) method = CharField(null=True) referrer = TextField(null=True) remote_addr = TextField(null=True) real_ip = CharField(null=True) forwarded_proto = CharField(null=True) connecting_ip = CharField(null=True) ip_country = CharField(null=True) visitor = TextField(null=True) status = IntegerField(null=True) args = PickleField(null=True) user_agent = PickleField(null=True) access_route = ArrayField(CharField, null=True) headers = PickleField(null=True) cookies = PickleField(null=True) speed = FloatField(null=True) class Meta: table_name = 'tracking'
class Transfer(BaseModel): id = peewee.IntegerField(primary_key=True) status = peewee.CharField() amount = peewee.IntegerField() fee = peewee.IntegerField() type = peewee.CharField() transaction_id = peewee.IntegerField(null=True) recipient_id = peewee.CharField(max_length=28, null=True) created_at = DateTimeTZField() source_type = peewee.CharField() source_id = peewee.CharField(max_length=28) target_type = peewee.CharField() target_id = peewee.CharField(max_length=28) metadata = BinaryJSONField(null=True, default={}) class Meta: db_table = "Transfers" @classmethod def format_from_response(cls, data): return dict(id=data["id"], status=data["status"], amount=data["amount"], fee=data["fee"], type=data["type"], transaction_id=data["transaction_id"], recipient_id=data["source_id"], created_at=time_utils.from_iso(data["date_created"]), source_type=data["source_type"], source_id=data["source_id"], target_type=data["target_type"], target_id=data["target_id"], metadata=data["metadata"], bank_account=data["bank_account"])
class Group(BaseModel): DEFAULT_PERMISSIONS = [ 'create_dashboard', 'create_query', 'edit_dashboard', 'edit_query', 'view_query', 'view_source', 'execute_query' ] id = peewee.PrimaryKeyField() name = peewee.CharField(max_length=100) permissions = ArrayField(peewee.CharField, default=DEFAULT_PERMISSIONS) tables = ArrayField(peewee.CharField) created_at = DateTimeTZField(default=datetime.datetime.now) class Meta: db_table = 'groups' def to_dict(self): return { 'id': self.id, 'name': self.name, 'permissions': self.permissions, 'tables': self.tables, 'created_at': self.created_at } def __unicode__(self): return unicode(self.id)
class Alert(ModelTimestampsMixin, BaseModel): UNKNOWN_STATE = 'unknown' OK_STATE = 'ok' TRIGGERED_STATE = 'triggered' id = peewee.PrimaryKeyField() name = peewee.CharField() query = peewee.ForeignKeyField(Query, related_name='alerts') user = peewee.ForeignKeyField(User, related_name='alerts') options = JSONField() state = peewee.CharField(default=UNKNOWN_STATE) last_triggered_at = DateTimeTZField(null=True) class Meta: db_table = 'alerts' @classmethod def all(cls): return cls.select(Alert, User, Query).join(Query).switch(Alert).join(User) def to_dict(self, full=True): d = { 'id': self.id, 'name': self.name, 'options': self.options, 'state': self.state, 'last_triggered_at': self.last_triggered_at, 'updated_at': self.updated_at, 'created_at': self.created_at } if full: d['query'] = self.query.to_dict() d['user'] = self.user.to_dict() else: d['query_id'] = self._data['query'] d['user_id'] = self._data['user'] return d def evaluate(self): data = json.loads(self.query.latest_query_data.data) # todo: safe guard for empty value = data['rows'][0][self.options['column']] op = self.options['op'] if op == 'greater than' and value > self.options['value']: new_state = self.TRIGGERED_STATE elif op == 'less than' and value < self.options['value']: new_state = self.TRIGGERED_STATE elif op == 'equals' and value == self.options['value']: new_state = self.TRIGGERED_STATE else: new_state = self.OK_STATE return new_state def subscribers(self): return User.select().join(AlertSubscription).where(AlertSubscription.alert==self)
class Object(pw.Model): array_field = ArrayField() binary_json_field = BinaryJSONField() dattime_tz_field = DateTimeTZField() hstore_field = HStoreField() interval_field = IntervalField() json_field = JSONField() ts_vector_field = TSVectorField()
class Company(BaseModel): kvk_nummer = pw.IntegerField(primary_key=True) naam = pw.CharField(null=True) url = pw.CharField(null=True) ranking = pw.IntegerField(null=True) core_id = pw.IntegerField( null=True) # also give the process number. If -1, not done datetime = DateTimeTZField(null=True) # the process time
class TimestampsMixin(OutputModel): """ Fields for timestamping data. If 'created_at' and 'updated_at' are not defined, and a model using this mixing is created using 'bulk_create', then those timestamps will be set using the *pipeline's* time instead of the server database's time, because of limitations in the bulk_create method (see https://github.com/coleifer/peewee/issues/1931#issue-443944983). It's expected that the pipeline's clock and the server's clock will be sufficiently synchronized that this won't cause issues anytime soon. """ created_at = DateTimeTZField( constraints=[SQL("DEFAULT (now() at time zone 'utc')")], default=datetime.utcnow) updated_at = DateTimeTZField( constraints=[SQL("DEFAULT (now() at time zone 'utc')")], default=datetime.utcnow) " The client is responsible for updating this field whenever they update the model. "
class Repository(BaseModel): url = TextField(primary_key=True) # app_id = CharField() name = CharField(null=True) authors_num = IntegerField(null=True) commits_num = IntegerField(null=True) files_num = BigIntegerField(null=True) last_commit_date = DateTimeTZField(null=True) first_commit_date = DateTimeTZField(null=True) sloc = BigIntegerField(null=True) logging_loc = BigIntegerField(null=True) # analyzed_date = DateTimeTZField(null=True) def get_non_merge_commits(self): import model.commit return self.commits.where(model.commit.Commit.is_merge_commit is False)
class Game(BaseModel): mode_id = IntegerField() instance_id = BigIntegerField(unique=True) date = DateTimeTZField() reference_id = BigIntegerField(null=True) class Meta: indexes = ((('mode_id', 'reference_id'), False), )