Пример #1
0
class Email(models.Model):
    headers = JSONField()
    email_to = ListCharField(base_field=EmailField())
    email_from = EmailField()
    bcc = ListCharField(base_field=EmailField())
    cc = ListCharField(base_field=EmailField())
    subject = CharField()
    raw_email = JSONField()wajyhggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg
Пример #2
0
class Migration(migrations.Migration):

    dependencies = [
        ('maps', '0029_delete_mapsnapshot'),
    ]

    operations = [
        migrations.CreateModel(
            name='MapData',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('blob', JSONField(default=dict)),
                ('resource',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='maps.Map')),
            ],
        ),
        migrations.AddField(
            model_name='map',
            name='data',
            field=models.OneToOneField(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name='data',
                to='maps.MapData'),
        ),
    ]
Пример #3
0
class Listing(QuicksellModel):
	"""Listing model."""

	class Status(IntegerChoices):
		"""Listing's poissble states."""

		draft = 0, 'Draft'
		active = 1, 'Active'
		sold = 2, 'Sold'
		closed = 3, 'Closed'
		deleted = 4, 'Deleted'

	uuid = UUIDField(default=uuid.uuid4, unique=True, editable=False)
	title = CharField(max_length=200)
	description = TextField(null=True, blank=True)
	price = PositiveIntegerField()
	category = ForeignKey('Category', on_delete=SET(uncategorized))
	status = PositiveSmallIntegerField(choices=Status.choices, default=0)
	quantity = PositiveIntegerField(default=1)
	sold = PositiveIntegerField(default=0)
	views = PositiveIntegerField(default=0)
	date_created = DateTimeField(default=datetime.now, editable=False)
	date_expires = DateTimeField(default=default_expiration_date)
	condition_new = BooleanField(default=False)
	properties = JSONField(null=True, blank=True)
	seller = ForeignKey('Profile', related_name='listings', on_delete=CASCADE)
	location = ForeignKey(**location_fk_kwargs)

	def __str__(self):
		return self.title
Пример #4
0
class Location(m.Model):
    """A location where a SunVox resource might be found"""
    def __str__(self):
        return self.url

    url = m.URLField(
        max_length=2048,
        help_text="URL where resource can be publicly accessed.",
        unique=True,
    )
    added_by = m.ForeignKey(
        User,
        on_delete=m.SET_NULL,
        related_name="locations_added",
        null=True,
        blank=True,
        help_text="User who added the resource.",
    )
    added_at = m.DateTimeField(
        auto_now_add=True,
        help_text="Timestamp of when the location was added.",
    )
    last_good_fetch = m.ForeignKey(
        "Fetch",
        on_delete=m.SET_NULL,
        related_name="locations",
        null=True,
        blank=True,
        help_text="Most recent fetch that succeeded.",
    )
    most_recent_file = m.ForeignKey(
        "File",
        on_delete=m.SET_NULL,
        related_name="locations",
        null=True,
        blank=True,
        help_text="Most recent file downloaded.",
    )
    metadata = JSONField(
        null=True,
        blank=True,
        help_text="Metadata provided by API client",
    )

    def save(self, *args, **kw) -> None:
        is_new = not self.id
        super().save(*args, **kw)
        if is_new and not (self.url.startswith("test://")
                           and "?noFetch=1" in self.url):
            self.fetches.create()
Пример #5
0
class Migration(migrations.Migration):

    dependencies = [
        ('monitoring', '0018_notification_check_def'),
    ]

    operations = [
        migrations.AddField(
            model_name='metricnotificationcheck',
            name='definition',
            field=models.OneToOneField(
                related_name='metric_check',
                on_delete=models.CASCADE,
                null=True,
                to='monitoring.NotificationMetricDefinition'),
        ),
        migrations.AlterField(
            model_name='notificationcheck',
            name='active',
            field=models.BooleanField(default=True, help_text='Is it active'),
        ),
        migrations.AlterField(
            model_name='notificationcheck',
            name='description',
            field=models.CharField(help_text='Description of the alert',
                                   max_length=255),
        ),
        migrations.AlterField(
            model_name='notificationcheck',
            name='severity',
            field=models.CharField(
                default='error',
                help_text='How severe would be error from this notification',
                max_length=32,
                choices=[('warning', 'Warning'), ('error', 'Error'),
                         ('fatal', 'Fatal')]),
        ),
        migrations.AlterField(
            model_name='notificationcheck',
            name='user_threshold',
            field=JSONField(
                default=dict,
                help_text='Expected min/max values for user configuration'),
        ),
    ]
Пример #6
0
class JSONObject(Func):
    function = 'JSON_OBJECT'
    output_field = JSONField()

    def __init__(self, **fields):
        expressions = []
        for key, value in fields.items():
            expressions.extend((Value(key), value))
        super().__init__(*expressions)

    def as_sql(self, compiler, connection, **extra_context):
        if not connection.features.has_json_object_function:
            raise NotSupportedError(
                'JSONObject() is not supported on this database backend.')
        return super().as_sql(compiler, connection, **extra_context)

    def as_postgresql(self, compiler, connection, **extra_context):
        return self.as_sql(
            compiler,
            connection,
            function='JSONB_BUILD_OBJECT',
            **extra_context,
        )

    def as_oracle(self, compiler, connection, **extra_context):
        class ArgJoiner:
            def join(self, args):
                args = [
                    ' VALUE '.join(arg) for arg in zip(args[::2], args[1::2])
                ]
                return ', '.join(args)

        return self.as_sql(
            compiler,
            connection,
            arg_joiner=ArgJoiner(),
            template='%(function)s(%(expressions)s RETURNING CLOB)',
            **extra_context,
        )
class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('monitoring', '0007_monitoring_exception_message'),
    ]

    operations = [
        migrations.CreateModel(
            name='MetricNotificationCheck',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('min_value',
                 models.DecimalField(default=None,
                                     null=True,
                                     max_digits=16,
                                     decimal_places=4,
                                     blank=True)),
                ('max_value',
                 models.DecimalField(default=None,
                                     null=True,
                                     max_digits=16,
                                     decimal_places=4,
                                     blank=True)),
                ('max_timeout',
                 models.DurationField(
                     help_text=
                     'Max timeout for given metric before error should be raised',
                     null=True,
                     blank=True)),
                ('active', models.BooleanField(default=True)),
                ('label',
                 models.ForeignKey(blank=True,
                                   to='monitoring.MetricLabel',
                                   on_delete=models.CASCADE,
                                   null=True)),
                ('metric',
                 models.ForeignKey(related_name='checks',
                                   to='monitoring.Metric',
                                   on_delete=models.CASCADE)),
            ],
        ),
        migrations.CreateModel(
            name='NotificationCheck',
            fields=[
                ('id',
                 models.AutoField(verbose_name='ID',
                                  serialize=False,
                                  auto_created=True,
                                  primary_key=True)),
                ('name', models.CharField(unique=True, max_length=255)),
                ('description', models.CharField(max_length=255)),
                ('user_threshold',
                 JSONField(default=dict, help_text='Threshold definition')),
            ],
        ),
        migrations.AddField(
            model_name='metricnotificationcheck',
            name='notification_check',
            field=models.ForeignKey(related_name='checks',
                                    to='monitoring.NotificationCheck',
                                    on_delete=models.CASCADE),
        ),
        migrations.AddField(
            model_name='metricnotificationcheck',
            name='ows_service',
            field=models.ForeignKey(blank=True,
                                    to='monitoring.OWSService',
                                    on_delete=models.CASCADE,
                                    null=True),
        ),
        migrations.AddField(
            model_name='metricnotificationcheck',
            name='resource',
            field=models.ForeignKey(blank=True,
                                    to='monitoring.MonitoredResource',
                                    on_delete=models.CASCADE,
                                    null=True),
        ),
        migrations.AddField(
            model_name='metricnotificationcheck',
            name='service',
            field=models.ForeignKey(related_name='checks',
                                    to='monitoring.Service',
                                    on_delete=models.CASCADE),
        ),
        migrations.AddField(
            model_name='metricnotificationcheck',
            name='user',
            field=models.ForeignKey(to=settings.AUTH_USER_MODEL,
                                    on_delete=models.CASCADE),
        ),
    ]
Пример #8
0
class Reservation(TimeableModel):
    house = models.ForeignKey('houses.House', on_delete=models.PROTECT, related_name='+', blank=True, null=True)
    connection = models.ForeignKey(
        'channels.Connection', on_delete=models.PROTECT, related_name='+', blank=True, null=True
    )
    source = models.CharField(max_length=25, choices=ReservationSources.choices())
    channel = models.CharField(max_length=25, choices=Channels.choices(), blank=True, null=True)
    channel_id = models.CharField(max_length=20)
    status = models.CharField(
        max_length=25, choices=ReservationStatuses.choices(), default=ReservationStatuses.NEW.name
    )
    close_reason = models.CharField(max_length=25, choices=RoomCloseReasons.choices(), blank=True, null=True)

    checkin = models.DateField()
    checkin_original = models.DateField()

    checkout = models.DateField()
    checkout_original = models.DateField()

    # original price from OTA
    price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0)
    # price accepted by Hotelier
    price_accepted = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0)

    # original price from OTA
    netto_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0)
    # price accepted by Hotelier
    netto_price_accepted = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0)

    room_count = models.PositiveSmallIntegerField(blank=True, default=1)
    currency = models.CharField(max_length=3, blank=True, null=True)
    tax = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0)
    fees = models.DecimalField(max_digits=10, decimal_places=2, blank=True, default=0)
    guest_name = models.CharField(max_length=100, blank=True, default='')
    guest_surname = models.CharField(max_length=100, blank=True, default='')
    guest_email = models.CharField(max_length=200, blank=True, default='')
    guest_phone = models.CharField(max_length=50, blank=True, default='')
    guest_country = models.CharField(max_length=2, blank=True, default='')
    guest_nationality = models.CharField(max_length=50, blank=True, default='')
    guest_city = models.CharField(max_length=100, blank=True, default='')
    guest_address = models.CharField(max_length=250, blank=True, default='')
    guest_post_code = models.CharField(max_length=10, blank=True, default='')
    guest_comments = models.TextField(blank=True, default='')
    promo = models.CharField(max_length=250, blank=True, default='')
    creditcard_info = JSONField(blank=True, default=dict)
    payment_info = models.CharField(max_length=250, blank=True, default='')
    booked_at = models.DateTimeField()

    is_verified = models.BooleanField(default=False)
    verified_at = models.DateTimeField(blank=True, null=True)

    # Odoo fields
    guest_contact_id = models.PositiveIntegerField(blank=True, null=True)
    guest_contact_ids = models.CharField(max_length=150, blank=True, default='')
    opportunity_id = models.PositiveIntegerField(blank=True, null=True)  # crm.lead
    quotation_id = models.PositiveIntegerField(blank=True, null=True)  # sale.order

    class Meta:
        app_label = 'board'
        indexes = [models.Index(fields=['channel_id'])]

    def __str__(self) -> str:
        return f"{self.source} CHANNEL ID={self.channel_id}"

    def save(self, **kwargs) -> None:
        for name in (
            'guest_name',
            'guest_surname',
            'guest_email',
            'guest_phone',
            'guest_country',
            'guest_nationality',
            'guest_city',
            'guest_address',
            'guest_post_code',
            'guest_comments',
            'guest_contact_ids',
            'promo',
            'payment_info',
        ):
            if getattr(self, name) is None:
                setattr(self, name, '')
        for name in ('price', 'price_accepted', 'tax', 'fees', 'netto_price', 'netto_price_accepted'):
            if getattr(self, name) is None:
                setattr(self, name, Decimal(0))

        if 'update_fields' in kwargs and kwargs['update_fields'] and 'updated_at' not in kwargs['update_fields']:
            kwargs['update_fields'].append('updated_at')
        super().save(**kwargs)
Пример #9
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='MapStoreAttribute',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=255)),
                ('label', models.CharField(blank=True, max_length=255, null=True)),
                ('type', models.CharField(choices=[('string', b'String'), ('number', b'Number'), ('integer', b'Integer'), ('boolean', b'Boolean'), ('binary', b'Binary')], max_length=80)),
                ('value', models.TextField(blank=True, db_column='value')),
            ],
        ),
        migrations.CreateModel(
            name='MapStoreData',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('blob', JSONField(default=dict)),
            ],
        ),
        migrations.CreateModel(
            name='MapStoreResource',
            fields=[
                ('id', models.BigIntegerField(blank=True, null=True, primary_key=True, serialize=False, unique=True)),
                ('name', models.CharField(max_length=255)),
                ('creation_date', models.DateTimeField(auto_now_add=True, null=True)),
                ('last_update', models.DateTimeField(auto_now=True, null=True)),
                ('attributes', models.ManyToManyField(blank=True, null=True, related_name='attributes',
                                                      to='mapstore2_adapter.MapStoreAttribute')),
                ('data', models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE,
                                              related_name='data', to='mapstore2_adapter.MapStoreData')),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.AddField(
            model_name='mapstoredata',
            name='resource',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                    to='mapstore2_adapter.MapStoreResource'),
        ),
        migrations.AddField(
            model_name='mapstoreattribute',
            name='resource',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                    to='mapstore2_adapter.MapStoreResource'),
        ),
        migrations.AddIndex(
            model_name='mapstoreresource',
            index=models.Index(fields=['id'], name='mapstore2_a_id_cd23a9_idx'),
        ),
        migrations.AddIndex(
            model_name='mapstoreresource',
            index=models.Index(fields=['name'], name='mapstore2_a_name_35c0a1_idx'),
        ),
    ]
Пример #10
0
class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='ExceptionEvent',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('created', models.DateTimeField(db_index=True)),
                ('received', models.DateTimeField(db_index=True)),
                ('error_type', models.CharField(max_length=255, db_index=True)),
                ('error_data', models.TextField(default='')),
            ],
        ),
        migrations.CreateModel(
            name='Host',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(unique=True, max_length=255)),
                ('ip', models.GenericIPAddressField()),
                ('active', models.BooleanField(default=True)),
            ],
        ),
        migrations.CreateModel(
            name='Metric',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=255, db_index=True)),
            ],
        ),
        migrations.CreateModel(
            name='MetricLabel',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.TextField(default='', blank=True)),
            ],
        ),
        migrations.CreateModel(
            name='MetricValue',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('valid_from', models.DateTimeField(db_index=True)),
                ('valid_to', models.DateTimeField(db_index=True)),
                ('value', models.CharField(max_length=255)),
                ('value_num', models.DecimalField(default=None, null=True, max_digits=16, decimal_places=4, blank=True)),
                ('value_raw', models.TextField(default=None, null=True, blank=True)),
                ('data', JSONField(default=dict)),
                ('label', models.ForeignKey(to='monitoring.MetricLabel', on_delete=models.CASCADE)),
            ],
        ),
        migrations.CreateModel(
            name='MonitoredResource',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(default='', max_length=255, blank=True)),
                ('type', models.CharField(default='', max_length=255, choices=[('','No resource'), ('layer','Layer'), ('map','Map'), ('document','Document'), ('style','Style'), ('admin','Admin'), ('other','Other')])),
            ],
        ),
        migrations.CreateModel(
            name='RequestEvent',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('created', models.DateTimeField(db_index=True)),
                ('received', models.DateTimeField(db_index=True)),
                ('ows_type', models.CharField(default='other', max_length=255, choices=[('TMS','TMS'), ('WMS-C','WMS-C'), ('WMTS','WMTS'), ('WCS','WCS'), ('WFS','WFS'), ('WMS','WMS'), ('WPS','WPS'), ('other','Other')])),
                ('host', models.CharField(default='', max_length=255, blank=True)),
                ('request_path', models.CharField(default='', max_length=255)),
                ('resources', models.TextField(default='', help_text='Resources name (style, layer, document, map)', blank=True)),
                ('request_method', models.CharField(max_length=16, choices=[('GET','GET'), ('POST','POST'), ('HEAD','HEAD'), ('OPTIONS','OPTIONS'), ('PUT','PUT'), ('DELETE','DELETE')])),
                ('response_status', models.PositiveIntegerField()),
                ('response_size', models.PositiveIntegerField(default=0)),
                ('response_time', models.PositiveIntegerField(default=0, help_text='Response processing time in ms')),
                ('response_type', models.CharField(default='', max_length=255, null=True, blank=True)),
                ('user_agent', models.CharField(default=None, max_length=255, null=True, blank=True)),
                ('user_agent_family', models.CharField(default=None, max_length=255, null=True, blank=True)),
                ('client_ip', models.GenericIPAddressField()),
                ('client_lat', models.DecimalField(default=None, null=True, max_digits=8, decimal_places=5, blank=True)),
                ('client_lon', models.DecimalField(default=None, null=True, max_digits=8, decimal_places=5, blank=True)),
                ('client_country', models.CharField(default=None, max_length=255, null=True, blank=True)),
                ('client_region', models.CharField(default=None, max_length=255, null=True, blank=True)),
                ('client_city', models.CharField(default=None, max_length=255, null=True, blank=True)),
                ('custom_id', models.CharField(default=None, max_length=255, null=True, db_index=True, blank=True)),
            ],
        ),
        migrations.CreateModel(
            name='Service',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(unique=True, max_length=255)),
                ('check_interval', models.DurationField(default=datetime.timedelta(0, 60))),
                ('last_check', models.DateTimeField(null=True, blank=True)),
                ('active', models.BooleanField(default=True)),
                ('notes', models.TextField(null=True, blank=True)),
                ('url', models.URLField(default='', null=True, blank=True)),
                ('host', models.ForeignKey(to='monitoring.Host', on_delete=models.CASCADE)),
            ],
        ),
        migrations.CreateModel(
            name='ServiceType',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(unique=True, max_length=255, choices=[('geonode','GeoNode'), ('geoserver','GeoServer'), ('hostgeoserver','Host (GeoServer)'), ('hostgeonode','Host (GeoNode)')])),
            ],
        ),
        migrations.CreateModel(
            name='ServiceTypeMetric',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('metric', models.ForeignKey(to='monitoring.Metric', on_delete=models.CASCADE)),
                ('service_type', models.ForeignKey(to='monitoring.ServiceType', on_delete=models.CASCADE)),
            ],
        ),
        migrations.AddField(
            model_name='service',
            name='service_type',
            field=models.ForeignKey(to='monitoring.ServiceType', on_delete=models.CASCADE),
        ),
        migrations.AddField(
            model_name='requestevent',
            name='service',
            field=models.ForeignKey(to='monitoring.Service', on_delete=models.CASCADE),
        ),
        migrations.AlterUniqueTogether(
            name='monitoredresource',
            unique_together={('name', 'type')},
        ),
        migrations.AddField(
            model_name='metricvalue',
            name='resource',
            field=models.ForeignKey(to='monitoring.MonitoredResource', on_delete=models.CASCADE),
        ),
        migrations.AddField(
            model_name='metricvalue',
            name='service',
            field=models.ForeignKey(to='monitoring.Service', on_delete=models.CASCADE),
        ),
        migrations.AddField(
            model_name='metricvalue',
            name='service_metric',
            field=models.ForeignKey(to='monitoring.ServiceTypeMetric', on_delete=models.CASCADE),
        ),
        migrations.AddField(
            model_name='exceptionevent',
            name='request',
            field=models.ForeignKey(to='monitoring.RequestEvent', on_delete=models.CASCADE),
        ),
        migrations.AddField(
            model_name='exceptionevent',
            name='service',
            field=models.ForeignKey(to='monitoring.Service', on_delete=models.CASCADE),
        ),
    ]
Пример #11
0
class ReservationRoom(TimeableModel):
    reservation = models.ForeignKey('board.Reservation',
                                    on_delete=models.CASCADE,
                                    related_name='rooms')
    channel_id = models.CharField(max_length=20)
    rate_id = models.PositiveIntegerField(blank=True, null=True)

    rate_plan_id = models.PositiveIntegerField(blank=True, null=True)
    rate_plan_id_original = models.PositiveIntegerField(blank=True, null=True)

    channel_rate_id = models.CharField(max_length=20)
    channel_rate_id_changed = models.CharField(max_length=20)

    checkin = models.DateField()
    checkin_original = models.DateField()

    checkout = models.DateField()
    checkout_original = models.DateField()

    # original price from OTA
    price = models.DecimalField(max_digits=10,
                                decimal_places=2,
                                blank=True,
                                default=0)
    # price accepted by Hotelier
    price_accepted = models.DecimalField(max_digits=10,
                                         decimal_places=2,
                                         blank=True,
                                         default=0)

    # original price from OTA
    netto_price = models.DecimalField(max_digits=10,
                                      decimal_places=2,
                                      blank=True,
                                      default=0)
    # price accepted by Hotelier
    netto_price_accepted = models.DecimalField(max_digits=10,
                                               decimal_places=2,
                                               blank=True,
                                               default=0)

    external_id = models.CharField(max_length=20, blank=True, null=True)
    external_name = models.CharField(max_length=250, blank=True, default='')
    guest_name = models.CharField(max_length=150, blank=True, default='')
    guest_count = models.PositiveSmallIntegerField(blank=True, default=1)
    adults = models.PositiveSmallIntegerField(blank=True, default=0)
    children = models.PositiveSmallIntegerField(blank=True, default=0)
    max_children = models.PositiveSmallIntegerField(blank=True, default=0)
    extra_bed = models.PositiveSmallIntegerField(blank=True, default=0)
    with_breakfast = models.BooleanField(default=False)
    currency = models.CharField(max_length=3, blank=True, null=True)
    tax = models.DecimalField(max_digits=10,
                              decimal_places=2,
                              blank=True,
                              default=0)
    fees = models.DecimalField(max_digits=10,
                               decimal_places=2,
                               blank=True,
                               default=0)
    notes_extra = models.TextField(blank=True, default='')
    notes_facilities = models.TextField(blank=True, default='')
    notes_info = models.TextField(blank=True, default='')
    notes_meal = models.TextField(blank=True, default='')

    policy = JSONField(blank=True, default=dict)
    policy_original = JSONField(blank=True, default=dict)

    is_deleted = models.BooleanField(default=False, db_index=True)
    deleted_at = models.DateTimeField(blank=True, null=True)

    objects = ReservationRoomQuerySet.as_manager()

    class Meta:
        app_label = 'board'

    def __str__(self) -> str:
        return f"CHANNEL ID={self.channel_id} RATE={self.channel_rate_id}"

    def save(self, **kwargs) -> None:
        self.guest_count = self.guest_count or 1
        for name in ('adults', 'children', 'max_children', 'extra_bed'):
            if getattr(self, name) is None:
                setattr(self, name, 0)
        for name in ('price', 'price_accepted', 'tax', 'fees', 'netto_price',
                     'netto_price_accepted'):
            if getattr(self, name) is None:
                setattr(self, name, Decimal(0))
        for name in ('external_name', 'guest_name', 'notes_extra',
                     'notes_facilities', 'notes_info', 'notes_meal'):
            if getattr(self, name) is None:
                setattr(self, name, '')

        if 'update_fields' in kwargs and kwargs['update_fields']:
            kwargs['update_fields'].append('updated_at')
        super().save(**kwargs)

    def delete(self, **kwargs) -> None:
        self.is_deleted = True
        self.deleted_at = timezone.now()
        self.save(update_fields=['is_deleted', 'deleted_at'])
Пример #12
0
class File(m.Model):
    """A file that has been retrieved and minimally processed."""
    class Meta:
        ordering = ["-cached_at"]

    class FileType(m.TextChoices):
        MODULE = "M", _("Module")
        PROJECT = "P", _("Project")

    hash = m.CharField(
        max_length=64,
        unique=True,
        help_text="SHA-256 hash of file",
    )
    file_type = m.CharField(
        max_length=1,
        choices=FileType.choices,
        null=True,
        blank=True,
        help_text="Type of file, if known.",
    )
    size = m.IntegerField(help_text="Size of file in bytes.", )
    cached_at = m.DateTimeField(help_text="When the file was cached.", )
    last_accessed_at = m.DateTimeField(
        null=True,
        blank=True,
        help_text="When the file was last accessed.",
    )
    metadata = JSONField(
        null=True,
        blank=True,
        help_text="Metadata provided by API client",
    )

    def file_ext(self) -> str:
        return {"M": "sunsynth", "P": "sunvox"}[self.file_type]

    def media_path(self) -> Path:
        dest_dir, dest_file = self.hash[:
                                        2], f"{self.hash[2:]}.{self.file_ext()}"
        return Path(settings.SVAUDIO_REPO_CACHE_PATH) / dest_dir / dest_file

    def alias_path_fragment(self) -> Optional[str]:
        if self.file_type == "M":
            name = self.module.name
        elif self.file_type == "P":
            name = self.project.name
        else:
            return
        hash = self.hash
        dest_dir_1, dest_dir_2 = hash[:2], hash[2:]
        basename = f"{slugify(name)}-{hash[:8]}" if name else hash
        filename = f"{basename}.{self.file_ext()}"
        return f"{dest_dir_1}/{dest_dir_2}/{filename}"

    def alias_path(self) -> Optional[Path]:
        fragment = self.alias_path_fragment()
        return (Path(settings.SVAUDIO_REPO_CACHE_PATH) /
                fragment) if fragment else None

    def media_url(self) -> Optional[str]:
        fragment = self.alias_path_fragment()
        return urljoin(settings.SVAUDIO_REPO_CACHE_URL,
                       fragment) if fragment else None

    def ensure_alias_symlink_exists(self):
        alias_path = self.alias_path()
        if not alias_path:
            return
        media_path = self.media_path()
        if not alias_path.is_symlink():
            alias_path.parent.mkdir(parents=True, exist_ok=True)
            alias_path.symlink_to(media_path)
Пример #13
0
class Migration(migrations.Migration):

    initial = True

    dependencies = [
        ('base', '0045_auto_20200507_0445'),
    ]

    operations = [
        migrations.CreateModel(
            name='GeoApp',
            fields=[
                ('resourcebase_ptr',
                 models.OneToOneField(
                     auto_created=True,
                     on_delete=django.db.models.deletion.CASCADE,
                     parent_link=True,
                     primary_key=True,
                     serialize=False,
                     to='base.ResourceBase')),
                ('name',
                 models.TextField(db_index=True,
                                  unique=True,
                                  verbose_name='Name')),
                ('zoom',
                 models.IntegerField(blank=True,
                                     null=True,
                                     verbose_name='zoom')),
                ('projection',
                 models.CharField(blank=True,
                                  max_length=32,
                                  null=True,
                                  verbose_name='projection')),
                ('center_x',
                 models.FloatField(blank=True,
                                   null=True,
                                   verbose_name='center X')),
                ('center_y',
                 models.FloatField(blank=True,
                                   null=True,
                                   verbose_name='center Y')),
                ('last_modified', models.DateTimeField(auto_now_add=True)),
                ('urlsuffix',
                 models.CharField(blank=True,
                                  max_length=255,
                                  null=True,
                                  verbose_name='Site URL')),
            ],
            options={
                'abstract': False,
                'base_manager_name': 'objects',
            },
            bases=('base.resourcebase', ),
        ),
        migrations.CreateModel(
            name='GeoAppData',
            fields=[
                ('id',
                 models.AutoField(auto_created=True,
                                  primary_key=True,
                                  serialize=False,
                                  verbose_name='ID')),
                ('blob', JSONField(default=dict)),
                ('resource',
                 models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                   to='geoapps.GeoApp')),
            ],
        ),
        migrations.AddField(
            model_name='geoapp',
            name='data',
            field=models.OneToOneField(
                blank=True,
                null=True,
                on_delete=django.db.models.deletion.CASCADE,
                related_name='data',
                to='geoapps.GeoAppData'),
        ),
    ]